From ea6234abd87e331160c335f021c4555efe18e4e1 Mon Sep 17 00:00:00 2001 From: Dr John O'Hare Date: Sat, 28 Nov 2026 20:09:23 +0000 Subject: [PATCH] Harden background IPC origin/sender checks, remove unused handler, and add toolbar lock badge --- src/background.js | 83 +++++++++++++++++++++++------------ src/nostr-provider.js | 4 +- test/consent-approval.test.js | 36 +++++++++++++-- test/set-session-key.test.js | 23 ++++++++++ 4 files changed, 112 insertions(+), 34 deletions(-) diff --git a/src/background.js b/src/background.js index 54a27df..de79eec 100644 --- a/src/background.js +++ b/src/background.js @@ -8,8 +8,7 @@ import { createSpends } from './sidestr/spends.js'; import { getConversationKey, encrypt as nip44Encrypt, - decrypt as nip44Decrypt, - bytesToHex as nip44BytesToHex + decrypt as nip44Decrypt } from './nip44.js'; import { storeKeypair, @@ -32,6 +31,32 @@ const DEBUG = false; if (DEBUG) console.log('[Podkey] Background service worker started'); +/** + * Keep the toolbar icon badge and tooltip in sync with lock state so the user + * can see at a glance whether Podkey is unlocked or locked. + */ +async function updateActionBadge () { + if (!chrome.action?.setBadgeText) return; + try { + if (await hasKeypair()) { + await chrome.action.setBadgeText({ text: '' }); + await chrome.action.setTitle?.({ title: 'Podkey — Unlocked' }); + return; + } + const { podkey_passkey: passkey } = await chrome.storage.local.get(['podkey_passkey']); + if ((await hasVault()) || passkey) { + await chrome.action.setBadgeBackgroundColor?.({ color: '#475569' }); + await chrome.action.setBadgeText({ text: 'LOCK' }); + await chrome.action.setTitle?.({ title: 'Podkey — Locked (click to unlock)' }); + return; + } + await chrome.action.setBadgeText({ text: '' }); + await chrome.action.setTitle?.({ title: 'Podkey — Set up your key' }); + } catch { + // Non-fatal: badge updates must never interrupt signing or key operations. + } +} + // Initialize extension chrome.runtime.onInstalled.addListener(async () => { console.log('[Podkey] Extension installed'); @@ -42,15 +67,26 @@ chrome.runtime.onInstalled.addListener(async () => { } else { console.log('[Podkey] Keypair already exists'); } + await updateActionBadge(); +}); + +chrome.runtime.onStartup?.addListener(() => { updateActionBadge(); }); +chrome.storage?.onChanged?.addListener((changes, area) => { + if ((area === 'session' && 'podkey_private_key' in changes) || + (area === 'local' && ('podkey_vault' in changes || 'podkey_passkey' in changes))) { + updateActionBadge(); + } }); +updateActionBadge(); // Pending signing approval promises: requestId -> resolve function const pendingApprovals = new Map(); // Handle messages from content scripts and popup chrome.runtime.onMessage.addListener((message, sender, sendResponse) => { - // Handle signing approval responses from the approve popup + // Handle signing approval responses from the approve popup (extension UI only) if (message.type === 'APPROVE_SIGNING') { + if (!isExtensionUiSender(sender)) return; const resolve = pendingApprovals.get(message.requestId); if (resolve) { pendingApprovals.delete(message.requestId); @@ -122,12 +158,14 @@ async function handleMessage (message, sender) { throw new Error(`${type} is not allowed from web content`); } + const requestOrigin = pageOrigin(sender, origin); + switch (type) { case 'GET_PUBLIC_KEY': - return await handleGetPublicKey(origin, sender); + return await handleGetPublicKey(requestOrigin, sender); case 'SIGN_EVENT': - return await handleSignEvent(message.event, origin, sender); + return await handleSignEvent(message.event, requestOrigin, sender); case 'GENERATE_KEYPAIR': return await handleGenerateKeypair(message.passphrase); @@ -148,16 +186,13 @@ async function handleMessage (message, sender) { return await handleSetSessionKey(message.privateKey); case 'NIP44_ENCRYPT': - return await handleNip44Encrypt(message.pubkey, message.plaintext, origin); + return await handleNip44Encrypt(message.pubkey, message.plaintext, requestOrigin); case 'NIP44_DECRYPT': - return await handleNip44Decrypt(message.pubkey, message.ciphertext, origin); - - case 'NIP44_GET_CONVERSATION_KEY': - return await handleNip44GetConversationKey(message.pubkey, origin); + return await handleNip44Decrypt(message.pubkey, message.ciphertext, requestOrigin); case 'SIDESTR_SIGN_TRANSACTION': - return await spends.request({ chain: message.chain, tx: message.tx }, pageOrigin(sender, origin)); + return await spends.request({ chain: message.chain, tx: message.tx }, requestOrigin); case 'SIDESTR_REQUEST': return spends.describe(message.id); @@ -309,6 +344,7 @@ function openUnlockPopup () { * Get public key with user permission */ async function handleGetPublicKey (origin, _sender) { + if (!origin) throw new Error('Missing origin'); // Require an unlocked key (locked vault -> opens unlock UI; no key -> setup). await ensureUnlocked(); @@ -339,6 +375,7 @@ async function handleGetPublicKey (origin, _sender) { * Sign event with user permission */ async function handleSignEvent (event, origin, _sender) { + if (!origin) throw new Error('Missing origin'); // Require an unlocked key (locked vault -> opens unlock UI; no key -> setup). await ensureUnlocked(); @@ -404,6 +441,7 @@ async function handleSignEvent (event, origin, _sender) { * @returns {Promise<{privateKey: string, publicKey: string}>} */ async function resolveKeypairForEncryption (origin, action) { + if (!origin) throw new Error('Missing origin'); // Require an unlocked key (locked vault -> opens unlock UI; no key -> setup). await ensureUnlocked(); @@ -457,24 +495,6 @@ async function handleNip44Decrypt (peerPubkey, ciphertext, origin) { return nip44Decrypt(ciphertext, conversationKey); } -/** - * NIP-44 (v2) conversation key derivation (hex). Some apps call this sub-API to - * cache the key client-side; we still derive it in the background so the raw - * private key stays here. - * @param {string} peerPubkey - 64-char hex peer public key - * @param {string} origin - requesting page origin - * @returns {Promise} 64-char hex conversation key - */ -async function handleNip44GetConversationKey (peerPubkey, origin) { - if (typeof peerPubkey !== 'string') { - throw new Error('nip44.getConversationKey requires a pubkey string'); - } - - const keypair = await resolveKeypairForEncryption(origin, 'derive a NIP-44 conversation key'); - const conversationKey = getConversationKey(keypair.privateKey, peerPubkey); - return nip44BytesToHex(conversationKey); -} - /** * Generate a new keypair, seal it under the passphrase, and unlock the session. */ @@ -483,6 +503,7 @@ async function handleGenerateKeypair (passphrase) { const keypair = await generateKeypair(); await createVault(keypair.privateKey, passphrase); // encrypted at rest await storeKeypair(keypair.privateKey, keypair.publicKey); // unlocked session + await updateActionBadge(); if (DEBUG) console.log('[Podkey] Keypair generated, sealed, and unlocked'); return { @@ -510,6 +531,7 @@ async function handleImportKeypair (privateKey, passphrase) { await createVault(hexKey, passphrase); // encrypted at rest (validates passphrase) await storeKeypair(hexKey, publicKey); // unlocked session + await updateActionBadge(); if (DEBUG) console.log('[Podkey] Keypair imported and sealed'); @@ -527,6 +549,7 @@ async function handleUnlockVault (passphrase) { const privateKey = await unlockVault(passphrase); // throws on wrong passphrase const publicKey = getPublicKey(privateKey); await storeKeypair(privateKey, publicKey); // populate session cache + await updateActionBadge(); if (DEBUG) console.log('[Podkey] Vault unlocked'); @@ -544,6 +567,7 @@ async function handleSetSessionKey (privateKey) { throw new Error('Passkey produced a different identity'); } await storeKeypair(hexKey, publicKey); + await updateActionBadge(); return { state: 'unlocked', exists: true, publicKey, did: `did:nostr:${publicKey}` }; } @@ -552,6 +576,7 @@ async function handleSetSessionKey (privateKey) { */ async function handleLockVault () { await clearSessionKey(); + await updateActionBadge(); if (DEBUG) console.log('[Podkey] Vault locked'); return { ok: true }; } diff --git a/src/nostr-provider.js b/src/nostr-provider.js index 4d87a45..a73c7a5 100644 --- a/src/nostr-provider.js +++ b/src/nostr-provider.js @@ -154,7 +154,9 @@ async function sendMessageToExtension (message, timeoutMs = 180000) { return new Promise((resolve, reject) => { // Create custom event to communicate with content script - const eventId = Math.random().toString(36).substring(7); + const eventId = typeof globalThis.crypto?.randomUUID === 'function' + ? globalThis.crypto.randomUUID() + : `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`; let timer = null; const handler = (event) => { diff --git a/test/consent-approval.test.js b/test/consent-approval.test.js index a931f02..8fc0e4b 100644 --- a/test/consent-approval.test.js +++ b/test/consent-approval.test.js @@ -43,9 +43,12 @@ function makeArea (store) { const stores = { local: {}, session: {} }; const windowsCreated = []; const captured = { onMessage: null }; +const EXT_ID = 'podkeyconsenttestid'; +const APPROVE_UI_SENDER = { id: EXT_ID, url: `chrome-extension://${EXT_ID}/popup/approve.html` }; global.chrome = { runtime: { + id: EXT_ID, onInstalled: { addListener: () => {} }, onMessage: { addListener: (fn) => { captured.onMessage = fn; } }, lastError: null @@ -76,8 +79,8 @@ const onMessage = captured.onMessage; const flush = () => new Promise((resolve) => setImmediate(resolve)); /** Send a message to the background and return a promise of sendResponse(). */ -function send (message) { - return new Promise((resolve) => { onMessage(message, {}, resolve); }); +function send (message, sender = {}) { + return new Promise((resolve) => { onMessage(message, sender, resolve); }); } /** Read the requestId out of the most recently opened approval popup URL. */ @@ -88,8 +91,8 @@ function lastRequestId () { } /** Resolve a pending prompt by sending the popup's APPROVE_SIGNING message. */ -function respond (requestId, approved) { - onMessage({ type: 'APPROVE_SIGNING', requestId, approved }, {}, () => {}); +function respond (requestId, approved, sender = APPROVE_UI_SENDER) { + onMessage({ type: 'APPROVE_SIGNING', requestId, approved }, sender, () => {}); } const SOLID_EVENT = { kind: 27235, created_at: 1700000000, tags: [['u', 'https://pod.test/']], content: '' }; @@ -243,4 +246,29 @@ describe('trusted-origin auto-path (general signer)', () => { assert.equal(windowsCreated.length, 1, 'origin became trusted; no second popup'); assert.equal(second.kind, 1); }); + + it('uses sender origin over spoofed message.origin for GET_PUBLIC_KEY and SIGN_EVENT', async () => { + await addTrustedOrigin('https://trusted.test'); + // Content script reports real host https://evil.test while claiming trusted.test + const evilSender = { id: EXT_ID, url: 'https://evil.test/page', origin: 'https://evil.test', tab: { id: 4 } }; + const pending = send({ type: 'GET_PUBLIC_KEY', origin: 'https://trusted.test' }, evilSender); + await flush(); + assert.equal(windowsCreated.length, 1, 'spoofed origin must not bypass consent prompt'); + const params = new URL('https://x/' + windowsCreated[0].url).searchParams; + assert.equal(params.get('origin'), 'https://evil.test'); + respond(params.get('id'), false); + assert.deepEqual(await pending, { error: 'User denied permission' }); + }); + + it('ignores APPROVE_SIGNING sent from a web content script', async () => { + const evilSender = { id: EXT_ID, url: 'https://evil.test/page', origin: 'https://evil.test', tab: { id: 4 } }; + const pending = send({ type: 'GET_PUBLIC_KEY', origin: 'https://evil.test' }, evilSender); + await flush(); + const id = lastRequestId(); + // Web content script attempts to self-approve — must be ignored + respond(id, true, evilSender); + // Still pending; legitimate extension UI denial settles it + respond(id, false, APPROVE_UI_SENDER); + assert.deepEqual(await pending, { error: 'User denied permission' }); + }); }); diff --git a/test/set-session-key.test.js b/test/set-session-key.test.js index 1d480c7..6feb79e 100644 --- a/test/set-session-key.test.js +++ b/test/set-session-key.test.js @@ -42,6 +42,7 @@ function makeArea (store) { const stores = { local: {}, session: {} }; const captured = { onMessage: null }; +const badgeState = { text: null, title: null }; const EXT_ID = 'podkeytestextensionid'; global.chrome = { @@ -51,6 +52,11 @@ global.chrome = { onMessage: { addListener: (fn) => { captured.onMessage = fn; } }, lastError: null }, + action: { + setBadgeText: async ({ text }) => { badgeState.text = text; }, + setBadgeBackgroundColor: async () => {}, + setTitle: async ({ title }) => { badgeState.title = title; } + }, windows: { create: () => Promise.resolve({ id: 1 }) }, @@ -153,4 +159,21 @@ describe('SET_SESSION_KEY contract', () => { assert.equal(response.publicKey, 'b'.repeat(64)); assert.equal(stores.local.podkey_public_key, 'b'.repeat(64)); }); + + it('rejects removed NIP44_GET_CONVERSATION_KEY handler as unknown', async () => { + const response = await send({ type: 'NIP44_GET_CONVERSATION_KEY', pubkey: 'a'.repeat(64) }); + assert.match(response.error, /Unknown message type/); + }); + + it('updates toolbar action badge on unlock and lock', async () => { + const { privateKey } = await generateKeypair(); + stores.local.podkey_vault = { v: 1, kdf: 'scrypt' }; + await send({ type: 'SET_SESSION_KEY', privateKey }); + assert.equal(badgeState.text, ''); + assert.match(badgeState.title, /Unlocked/); + + await send({ type: 'LOCK_VAULT' }); + assert.equal(badgeState.text, 'LOCK'); + assert.match(badgeState.title, /Locked/); + }); });