Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support configurable logger namespaces #712

Merged
merged 1 commit into from
Apr 17, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions add-on/_locales/en/messages.json
Original file line number Diff line number Diff line change
Expand Up @@ -399,6 +399,14 @@
"message": "Enables automatic preload of uploaded assets via asynchronous HTTP HEAD request to a Public Gateway",
"description": "An option description on the Preferences screen (option_preloadAtPublicGateway_description)"
},
"option_logNamespaces_title": {
"message": "Log Namespaces",
"description": "An option title for tweaking log level (option_logNamespaces_title)"
},
"option_logNamespaces_description": {
"message": "Customize which namespaces are logged to Browser Console. Changing this value will trigger extension restart.",
"description": "An option description for the log level (option_logNamespaces_description)"
},
"option_resetAllOptions_title": {
"message": "Reset Everything",
"description": "An option title and button label on the Preferences screen (option_resetAllOptions_title)"
Expand Down
11 changes: 5 additions & 6 deletions add-on/src/background/background.js
Original file line number Diff line number Diff line change
@@ -1,19 +1,18 @@
'use strict'
/* eslint-env browser, webextensions */

// Enable some debug output from js-ipfs
// (borrowed from https://github.com/ipfs-shipyard/ipfs-companion/pull/557)
// to include everything (mplex, libp2p, mss): localStorage.debug = '*'
localStorage.debug = 'jsipfs*,ipfs*,-*:mfs*,-*:ipns*,-ipfs:preload*'

const browser = require('webextension-polyfill')
const createIpfsCompanion = require('../lib/ipfs-companion')
const { onInstalled } = require('../lib/on-installed')
const { optionDefaults } = require('../lib/options')

// register onInstalled hook early, otherwise we miss first install event
browser.runtime.onInstalled.addListener(onInstalled)

// init add-on after all libs are loaded
document.addEventListener('DOMContentLoaded', async () => {
// setting debug level early
localStorage.debug = (await browser.storage.local.get({ logNamespaces: optionDefaults.logNamespaces })).logNamespaces
// init inlined to read updated localStorage.debug
const createIpfsCompanion = require('../lib/ipfs-companion')
window.ipfsCompanion = await createIpfsCompanion()
})
1 change: 0 additions & 1 deletion add-on/src/landing-pages/welcome/store.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ function createWelcomePageStore (i18n, runtime) {
emitter.emit('render')
port = runtime.connect({ name: 'browser-action-port' })
port.onMessage.addListener(async (message) => {
console.log('port.onMessage', message)
if (message.statusUpdate) {
const peerCount = message.statusUpdate.peerCount
const isIpfsOnline = peerCount > -1
Expand Down
10 changes: 7 additions & 3 deletions add-on/src/lib/context-menus.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@

const browser = require('webextension-polyfill')

const debug = require('debug')
const log = debug('ipfs-companion:context-menus')
log.error = debug('ipfs-companion:context-menus:error')

// mapping between context name and field with data for it
// https://developer.mozilla.org/en-US/Add-ons/WebExtensions/API/menus/ContextType
const contextSources = {
Expand Down Expand Up @@ -142,12 +146,12 @@ function createContextMenus (getState, runtime, ipfsPathValidator, { onAddFromCo
} catch (err) {
// documentUrlPatterns is not supported in Muon-Brave
if (err.message.indexOf('createProperties.documentUrlPatterns of contextMenus.create is not supported yet') > -1) {
console.warn('[ipfs-companion] Context menus disabled - createProperties.documentUrlPatterns of contextMenus.create is not supported yet')
log('context menus disabled - createProperties.documentUrlPatterns of contextMenus.create is not supported yet')
return { update: () => Promise.resolve() }
}
// contextMenus are not supported in Firefox for Android
if (err.message === 'browser.contextMenus is undefined' || typeof browser.contextMenus === 'undefined') {
console.warn('[ipfs-companion] Context menus disabled - browser.contextMenus is undefined')
log('context menus disabled - browser.contextMenus is undefined')
return { update: () => Promise.resolve() }
}
throw err
Expand Down Expand Up @@ -179,7 +183,7 @@ function createContextMenus (getState, runtime, ipfsPathValidator, { onAddFromCo
await browser.contextMenus.update(item, { enabled: (ifApi && ipfsContext) })
}
} catch (err) {
console.log('[ipfs-companion] Error updating context menus', err)
log.error('Error updating context menus', err)
}
}

Expand Down
12 changes: 8 additions & 4 deletions add-on/src/lib/dnslink.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
'use strict'
/* eslint-env browser */

const debug = require('debug')
const log = debug('ipfs-companion:dnslink')
log.error = debug('ipfs-companion:dnslink:error')

const IsIpfs = require('is-ipfs')
const LRU = require('lru-cache')
const PQueue = require('p-queue')
Expand Down Expand Up @@ -64,18 +68,18 @@ module.exports = function createDnslinkResolver (getState) {
let dnslink = dnslinkResolver.cachedDnslink(fqdn)
if (typeof dnslink === 'undefined') {
try {
console.info(`[ipfs-companion] dnslink cache miss for '${fqdn}', running DNS TXT lookup`)
log(`dnslink cache miss for '${fqdn}', running DNS TXT lookup`)
dnslink = dnslinkResolver.readDnslinkFromTxtRecord(fqdn)
if (dnslink) {
// TODO: set TTL as maxAge: setDnslink(fqdn, dnslink, maxAge)
dnslinkResolver.setDnslink(fqdn, dnslink)
console.info(`[ipfs-companion] found dnslink: '${fqdn}' -> '${dnslink}'`)
log(`found dnslink: '${fqdn}' -> '${dnslink}'`)
} else {
dnslinkResolver.setDnslink(fqdn, false)
console.info(`[ipfs-companion] found NO dnslink for '${fqdn}'`)
log(`found NO dnslink for '${fqdn}'`)
}
} catch (error) {
console.error(`[ipfs-companion] Error in readAndCacheDnslink for '${fqdn}'`)
log.error(`error in readAndCacheDnslink for '${fqdn}'`, error)
console.error(error)
}
} else {
Expand Down
6 changes: 3 additions & 3 deletions add-on/src/lib/ipfs-client/embedded-chromesockets.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
'use strict'
/* eslint-env browser, webextensions */
const browser = require('webextension-polyfill')

const debug = require('debug')
const log = debug('ipfs-companion:client:embedded')
log.error = debug('ipfs-companion:client:embedded:error')

// Polyfills required by embedded HTTP server
const uptimeStart = Date.now()
Expand All @@ -24,9 +27,6 @@ let nodeHttpApi = null
// let httpServer = null
// let hapiServer = null

const log = debug('ipfs-companion:client:embedded')
log.error = debug('ipfs-companion:client:embedded:error')

exports.init = function init (opts) {
/*
// TEST RAW require('http') SERVER
Expand Down
12 changes: 8 additions & 4 deletions add-on/src/lib/ipfs-client/embedded.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,17 @@
'use strict'

const debug = require('debug')
const log = debug('ipfs-companion:client:embedded')
log.error = debug('ipfs-companion:client:embedded:error')

const mergeOptions = require('merge-options')
const Ipfs = require('ipfs')
const { optionDefaults } = require('../options')

let node = null

exports.init = function init (opts) {
console.log('[ipfs-companion] Embedded ipfs init')
log('init')

const defaultOpts = JSON.parse(optionDefaults.ipfsNodeConfig)
const userOpts = JSON.parse(opts.ipfsNodeConfig)
Expand All @@ -17,15 +21,15 @@ exports.init = function init (opts) {

return new Promise((resolve, reject) => {
node.once('error', (error) => {
console.error('[ipfs-companion] Something went terribly wrong during startup of js-ipfs!', error)
log.error('something went terribly wrong during startup of js-ipfs!', error)
reject(error)
})
node.once('ready', async () => {
node.once('start', () => {
resolve(node)
})
node.on('error', error => {
console.error('[ipfs-companion] Something went terribly wrong in embedded js-ipfs!', error)
log.error('something went terribly wrong in embedded js-ipfs!', error)
})
try {
await node.start()
Expand All @@ -37,7 +41,7 @@ exports.init = function init (opts) {
}

exports.destroy = async function () {
console.log('[ipfs-companion] Embedded ipfs destroy')
log('destroy')
if (!node) return

await node.stop()
Expand Down
8 changes: 6 additions & 2 deletions add-on/src/lib/ipfs-client/external.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,14 @@
'use strict'
/* eslint-env browser */

const debug = require('debug')
const log = debug('ipfs-companion:client:external')
log.error = debug('ipfs-companion:client:external:error')

const IpfsApi = require('ipfs-http-client')

exports.init = async function (opts) {
console.log('[ipfs-companion] External ipfs init', opts.apiURLString)
log(`init with API: ${opts.apiURLString}`)

const url = opts.apiURL
const protocol = url.protocol.substr(0, url.protocol.length - 1) // http: -> http
Expand All @@ -14,7 +18,7 @@ exports.init = async function (opts) {
}

exports.destroy = async function () {
console.log('[ipfs-companion] External ipfs destroy')
log('destroy')
}

// TODO: Upgrade to a caching proxy for ipfs-http-client
18 changes: 14 additions & 4 deletions add-on/src/lib/ipfs-companion.js
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ module.exports = async function init () {

function getIpfs () {
if (state.active && ipfs) return ipfs
console.error('[ipfs-companion] Refused access to IPFS API client, check if extension is enabled')
log.error('refused access to IPFS API client, check if extension is enabled')
throw new Error('IPFS Companion: API client is disabled')
}

Expand All @@ -116,10 +116,10 @@ module.exports = async function init () {
browser.runtime.onConnect.addListener(onRuntimeConnect)

if (runtime.hasNativeProtocolHandler) {
console.log('[ipfs-companion] registerStringProtocol available. Adding ipfs:// handler')
log('registerStringProtocol available. Adding ipfs:// handler')
browser.protocol.registerStringProtocol('ipfs', createIpfsUrlProtocolHandler(() => ipfs))
} else {
console.log('[ipfs-companion] browser.protocol.registerStringProtocol not available, native protocol will not be registered')
log('no browser.protocol API, native protocol will not be registered')
}
}

Expand Down Expand Up @@ -598,6 +598,7 @@ module.exports = async function init () {
}

async function onStorageChange (changes, area) {
let shouldReloadExtension = false
let shouldRestartIpfsClient = false
let shouldStopIpfsClient = false

Expand All @@ -606,7 +607,7 @@ module.exports = async function init () {
if (change.oldValue === change.newValue) continue

// debug info
// console.info(`Storage key "${key}" in namespace "${area}" changed. Old value was "${change.oldValue}", new value is "${change.newValue}".`)
log(`storage key "${key}" changed: "${change.oldValue}""${change.newValue}"`)
switch (key) {
case 'active':
state[key] = change.newValue
Expand Down Expand Up @@ -649,6 +650,10 @@ module.exports = async function init () {
await browser.storage.local.set({ detectIpfsPathHeader: true })
}
break
case 'logNamespaces':
shouldReloadExtension = true
state[key] = localStorage.debug = change.newValue
break
case 'linkify':
case 'catchUnhandledProtocols':
case 'displayNotifications':
Expand Down Expand Up @@ -687,6 +692,11 @@ module.exports = async function init () {

apiStatusUpdate()
}
if (shouldReloadExtension) {
log('reloading extension due to config change')
browser.tabs.reload() // async reload of options page to keep it alive
await browser.runtime.reload()
}
// Post update to Browser Action (if exists) -- this gives UX a snappy feel
await sendStatusUpdateToBrowserAction()
}
Expand Down
6 changes: 5 additions & 1 deletion add-on/src/lib/ipfs-proxy/enable-command.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
const debug = require('debug')
const log = debug('ipfs-companion:proxy')
log.error = debug('ipfs-companion:proxy:error')

const { inCommandWhitelist, createCommandWhitelistError } = require('./pre-command')
const { createProxyAclError } = require('./pre-acl')

Expand All @@ -6,7 +10,7 @@ const { createProxyAclError } = require('./pre-acl')
function createEnableCommand (getIpfs, getState, getScope, accessControl, requestAccess) {
return async (opts) => {
const scope = await getScope()
console.log(`[ipfs-companion] received window.ipfs.enable request from ${scope}`, opts)
log(`received window.ipfs.enable request from ${scope}`, opts)

// Check if all access to the IPFS node is disabled
if (!getState().ipfsProxy) throw new Error('User disabled access to API proxy in IPFS Companion')
Expand Down
22 changes: 13 additions & 9 deletions add-on/src/lib/ipfs-request.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
'use strict'
/* eslint-env browser, webextensions */

const debug = require('debug')
const log = debug('ipfs-companion:request')
log.error = debug('ipfs-companion:request:error')

const LRU = require('lru-cache')
const IsIpfs = require('is-ipfs')
const { pathAtHttpGateway } = require('./ipfs-path')
Expand Down Expand Up @@ -225,7 +229,7 @@ function createRequestModifier (getState, dnslinkResolver, ipfsPathValidator, ru
if (request.url.includes('/api/v0/add') && request.url.includes('stream-channels=true')) {
let addExpectHeader = true
const expectHeader = { name: 'Expect', value: '100-continue' }
const warningMsg = '[ipfs-companion] Executing "Expect: 100-continue" workaround for ipfs.add due to https://github.com/ipfs/go-ipfs/issues/5168'
const warningMsg = 'Executing "Expect: 100-continue" workaround for ipfs.add due to https://github.com/ipfs/go-ipfs/issues/5168'
for (let header of request.requestHeaders) {
// Workaround A: https://github.com/ipfs/go-ipfs/issues/5168#issuecomment-401417420
// (works in Firefox, but Chromium does not expose Connection header)
Expand All @@ -242,14 +246,14 @@ function createRequestModifier (getState, dnslinkResolver, ipfsPathValidator, ru
if (header.name === expectHeader.name) {
addExpectHeader = false
if (header.value !== expectHeader.value) {
console.log(warningMsg)
log(warningMsg)
header.value = expectHeader.value
}
break
}
}
if (addExpectHeader) {
console.log(warningMsg)
log(warningMsg)
request.requestHeaders.push(expectHeader)
}
}
Expand Down Expand Up @@ -335,7 +339,7 @@ function createRequestModifier (getState, dnslinkResolver, ipfsPathValidator, ru
if (header.name.toLowerCase() === 'x-ipfs-path' && isSafeToRedirect(request, runtime)) {
// console.log('onHeadersReceived.request.responseHeaders', request.responseHeaders.length)
const xIpfsPath = header.value
console.log(`[ipfs-companion] detected x-ipfs-path for ${request.url}: ${xIpfsPath}`)
log(`detected x-ipfs-path for ${request.url}: ${xIpfsPath}`)
// First: Check if dnslink heuristic yields any results
// Note: this depends on which dnslink lookup policy is selecten in Preferences
if (state.dnslinkPolicy && dnslinkResolver.canLookupURL(request.url)) {
Expand All @@ -346,15 +350,15 @@ function createRequestModifier (getState, dnslinkResolver, ipfsPathValidator, ru
const cachedDnslink = dnslinkResolver.readAndCacheDnslink(new URL(request.url).hostname)
const dnslinkRedirect = dnslinkResolver.dnslinkRedirect(request.url, cachedDnslink)
if (dnslinkRedirect) {
console.log(`[ipfs-companion] onHeadersReceived: dnslinkRedirect from ${request.url} to ${dnslinkRedirect.redirectUrl}`)
log(`onHeadersReceived: dnslinkRedirect from ${request.url} to ${dnslinkRedirect.redirectUrl}`)
return dnslinkRedirect
}
}
// Additional validation of X-Ipfs-Path
if (IsIpfs.ipnsPath(xIpfsPath)) {
// Ignore unhandled IPNS path by this point
// (means DNSLink is disabled so we don't want to make a redirect that works like DNSLink)
console.log(`[ipfs-companion] onHeadersReceived: ignoring x-ipfs-path=${xIpfsPath} (dnslinkPolicy=false or missing DNS TXT record)`)
log(`onHeadersReceived: ignoring x-ipfs-path=${xIpfsPath} (dnslinkPolicy=false or missing DNS TXT record)`)
} else if (IsIpfs.ipfsPath(xIpfsPath)) {
// It is possible that someone exposed /ipfs/<cid>/ under /
// and our path-based onBeforeRequest heuristics were unable
Expand All @@ -367,7 +371,7 @@ function createRequestModifier (getState, dnslinkResolver, ipfsPathValidator, ru
const newUrl = pathAtHttpGateway(pathWithArgs, state.pubGwURLString)
// redirect only if anything changed
if (newUrl !== request.url) {
console.log(`[ipfs-companion] onHeadersReceived: normalized ${request.url} to ${newUrl}`)
log(`onHeadersReceived: normalized ${request.url} to ${newUrl}`)
return redirectToGateway(newUrl, state, ipfsPathValidator)
}
}
Expand Down Expand Up @@ -403,7 +407,7 @@ function createRequestModifier (getState, dnslinkResolver, ipfsPathValidator, ru
// recover by opening IPNS version in a new tab
// TODO: add tests and demo
if (dnslinkRedirect) {
console.log(`[ipfs-companion] onErrorOccurred: recovering using dnslink for ${request.url}`, dnslinkRedirect)
log(`onErrorOccurred: recovering using dnslink for ${request.url}`, dnslinkRedirect)
const currentTabId = await browser.tabs.query({ active: true, currentWindow: true }).then(tabs => tabs[0].id)
await browser.tabs.create({
active: true,
Expand Down Expand Up @@ -454,7 +458,7 @@ function isSafeToRedirect (request, runtime) {
const sourceOrigin = new URL(request.originUrl).origin
const targetOrigin = new URL(request.url).origin
if (sourceOrigin !== targetOrigin) {
console.warn('[ipfs-companion] Delaying redirect of CORS XHR until onHeadersReceived due to https://github.com/ipfs-shipyard/ipfs-companion/issues/436 :', request.url)
log('Delaying redirect of CORS XHR until onHeadersReceived due to https://github.com/ipfs-shipyard/ipfs-companion/issues/436 :', request.url)
onHeadersReceivedRedirect.add(request.requestId)
return false
}
Expand Down
1 change: 0 additions & 1 deletion add-on/src/lib/on-installed.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
const browser = require('webextension-polyfill')

exports.onInstalled = async (details) => {
console.log('[ipfs-companion] onInstalled event', details)
// details.temporary === run via `npm run firefox`
if (details.reason === 'install' || details.temporary) {
await browser.storage.local.set({ showLandingPage: 'onInstallWelcome' })
Expand Down
Loading