Skip to content
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
83 changes: 54 additions & 29 deletions src/background.js
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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');
Expand All @@ -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);
Expand Down Expand Up @@ -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);
Expand All @@ -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);
Expand Down Expand Up @@ -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();

Expand Down Expand Up @@ -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();

Expand Down Expand Up @@ -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();

Expand Down Expand Up @@ -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<string>} 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.
*/
Expand All @@ -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 {
Expand Down Expand Up @@ -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');

Expand All @@ -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');

Expand All @@ -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}` };
}

Expand All @@ -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 };
}
Expand Down
4 changes: 3 additions & 1 deletion src/nostr-provider.js
Original file line number Diff line number Diff line change
Expand Up @@ -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) => {
Expand Down
36 changes: 32 additions & 4 deletions test/consent-approval.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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. */
Expand All @@ -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: '' };
Expand Down Expand Up @@ -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' });
});
});
23 changes: 23 additions & 0 deletions test/set-session-key.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 = {
Expand All @@ -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 })
},
Expand Down Expand Up @@ -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/);
});
});
Loading