-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathbackground.ts
More file actions
279 lines (244 loc) · 11.8 KB
/
Copy pathbackground.ts
File metadata and controls
279 lines (244 loc) · 11.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
import browser from './lib/browser.ts';
import * as vault from './lib/vault.ts';
import * as signer from './lib/signer.ts';
import * as signerPermissions from './lib/permissions.ts';
import { openPopupForActiveTab } from './lib/openPopupForActiveTab.ts';
import { randomHex } from './lib/crypto/utils.ts';
// ── State & handler modules ──
import {
config,
NIP07_SIGNING_METHODS,
npubToHex,
buildPrivilegedMethods, setPrivilegedMethods,
PRIVILEGED_METHODS,
type HandlerFn,
} from './lib/bg/state.ts';
import { handlers as miscHandlers, logActivity } from './lib/bg/misc-handlers.ts';
import {
handlers as domainHandlers,
isDomainAllowed, isDomainDismissed,
waitForDomainAllowed,
isActiveAccountReadOnly,
} from './lib/bg/domain-handlers.ts';
import { handlers as vaultHandlers } from './lib/bg/vault-handlers.ts';
import { handlers as walletHandlers } from './lib/bg/wallet-handlers.ts';
import { handlers as nip07Handlers, validateNip07Params } from './lib/bg/nip07-handlers.ts';
import { handlers as onboardingHandlers } from './lib/bg/onboarding-handlers.ts';
// ── Assemble handler map ──
const allHandlers = new Map<string, HandlerFn>();
const handlerGroups = [miscHandlers, domainHandlers, vaultHandlers, walletHandlers, nip07Handlers, onboardingHandlers];
for (const group of handlerGroups) {
for (const [method, fn] of group) {
if (allHandlers.has(method)) {
console.error(`[BG] Duplicate handler registration: "${method}" — later registration overwrites earlier one`);
}
allHandlers.set(method, fn);
}
}
// configUpdated stays here because it calls loadConfig which is local
allHandlers.set('configUpdated', async () => {
await loadConfig();
return { ok: true };
});
// Auto-derive PRIVILEGED_METHODS from all handler maps (no manual allowlist needed)
const privilegedHandlerGroups = [miscHandlers, domainHandlers, vaultHandlers, walletHandlers, nip07Handlers, onboardingHandlers];
setPrivilegedMethods(buildPrivilegedMethods(...privilegedHandlerGroups));
// Also add configUpdated and other locally-defined handlers
PRIVILEGED_METHODS.add('configUpdated');
// ── Config loading ──
async function loadConfig(): Promise<void> {
const data = await browser.storage.sync.get([
'myPubkey', 'relays'
]) as Record<string, unknown>;
config.myPubkey = (data.myPubkey as string) || null;
// Parse relays from comma-separated string
if (data.relays) {
config.relays = (data.relays as string).split(',').map(r => r.trim()).filter(Boolean);
}
// Ensure an active account exists in local storage.
const localData = await browser.storage.local.get(['accounts', 'activeAccountId']) as Record<string, unknown>;
let activeAccountId = localData.activeAccountId as string | undefined;
// Migration: if no accounts in local storage but myPubkey exists, create one
if (!activeAccountId && data.myPubkey) {
let accts = (localData.accounts as Array<{ id: string; name: string; pubkey: string; type: string; readOnly: boolean }>) || [];
if (accts.length === 0) {
const id = Date.now().toString(36) + randomHex(6);
accts = [{ id, name: 'Default', pubkey: data.myPubkey as string, type: 'npub', readOnly: true }];
activeAccountId = id;
await browser.storage.local.set({ accounts: accts, activeAccountId: id });
} else {
activeAccountId = accts[0].id;
await browser.storage.local.set({ activeAccountId });
}
}
}
// ── Request dispatch ──
async function handleRequest({ method, params }: { method: string; params: Record<string, unknown> }): Promise<unknown> {
// NIP-07: validate params and gate behind domain allowlist
if (method.startsWith('nip07_')) {
validateNip07Params(method, params);
const origin = params?.origin as string;
if (!origin) {
logActivity({ domain: 'unknown', method: method.replace('nip07_', ''), decision: 'blocked' });
throw new Error('Site not connected');
}
if (!(await isDomainAllowed(origin))) {
// Dismissed domains are silently rejected (user previously denied)
if (await isDomainDismissed(origin)) {
logActivity({ domain: origin, method: method.replace('nip07_', ''), decision: 'blocked' });
throw new Error('Site not connected');
}
// First visit: open the popup so the user sees the "Connect this site"
// card — but only when the request comes from the tab they're actually
// looking at. A background/inactive tab making nostr requests (or one
// polling) must not pop the popup open.
await openPopupForActiveTab(origin);
// Wait for the user to click Connect (domain added to allowedDomains)
const connected = await waitForDomainAllowed(origin);
if (!connected) {
logActivity({ domain: origin, method: method.replace('nip07_', ''), decision: 'blocked' });
throw new Error('Site not connected');
}
}
}
// Gate WebLN methods (except enable) behind the same domain allowlist
if (method.startsWith('webln_') && method !== 'webln_enable') {
const origin = params?.origin as string;
if (!origin || !(await isDomainAllowed(origin))) {
logActivity({ domain: origin || 'unknown', method: method.replace('webln_', ''), decision: 'blocked' });
throw new Error('Site not connected');
}
}
// Read-only account guard
if (NIP07_SIGNING_METHODS.has(method) && await isActiveAccountReadOnly()) {
logActivity({ domain: params?.origin as string, method: method.replace('nip07_', ''), decision: 'blocked' });
throw new Error('Signing not available for read-only accounts');
}
// Normalize pubkey params from npub to hex (used by relay-list and profile handlers)
if (params?.pubkey) params.pubkey = npubToHex(params.pubkey as string) || params.pubkey;
if (Array.isArray(params?.pubkeys)) {
params.pubkeys = (params.pubkeys as string[]).map(t => npubToHex(t) || t);
}
const handler = allHandlers.get(method);
if (!handler) {
throw new Error(`Unknown method: ${method}`);
}
return await handler(params);
}
// ── Message listeners ──
browser.runtime.onMessage.addListener((request: Record<string, unknown>, sender: chrome.runtime.MessageSender, sendResponse: (response: unknown) => void) => {
const method = request?.method as string | undefined;
// Gate privileged methods to internal extension pages only
if (method && PRIVILEGED_METHODS.has(method)) {
const senderUrl = sender.url || sender.tab?.url || '';
const isInternal = sender.id === browser.runtime.id &&
(!sender.tab || senderUrl.startsWith(browser.runtime.getURL('')));
if (!isInternal) {
sendResponse({ error: 'Permission denied' });
return true;
}
}
// Defense-in-depth: derive NIP-07 origin from browser-verified sender info
if (method?.startsWith('nip07_')) {
const originUrl = sender.frameId === 0
? sender.tab?.url
: (sender.url || sender.tab?.url);
if (!originUrl) {
sendResponse({ error: 'Cannot determine request origin' });
return true;
}
(request.params as Record<string, unknown>).origin = new URL(originUrl).hostname;
}
handleRequest(request as { method: string; params: Record<string, unknown> })
.then(result => {
sendResponse({ result });
})
.catch(error => {
sendResponse({ error: (error as Error).message || (error as { name?: string }).name || 'Unknown error' });
});
return true;
});
// Port-based handler for NIP-07 and WebLN requests from content scripts
browser.runtime.onConnect.addListener((port: chrome.runtime.Port) => {
if (port.name !== 'nip07' && port.name !== 'webln') return;
port.onMessage.addListener(async (request: Record<string, unknown>) => {
const method = request.method as string;
// Defense-in-depth: derive origin from browser-verified sender info
if (method?.startsWith('nip07_') || method?.startsWith('webln_')) {
const originUrl = port.sender?.frameId === 0
? port.sender?.tab?.url
: (port.sender?.url || port.sender?.tab?.url);
if (!originUrl) {
try { port.postMessage({ error: 'Cannot determine request origin' }); } catch {}
return;
}
(request.params as Record<string, unknown>).origin = new URL(originUrl).hostname;
}
try {
const result = await handleRequest(request as { method: string; params: Record<string, unknown> });
try { port.postMessage({ result }); } catch {}
} catch (error) {
console.error('[PORT]', port.name, 'error:', method, (error as Error).message);
try { port.postMessage({ error: (error as Error).message || 'Unknown error' }); } catch {}
}
});
});
// Keep-alive alarm: while the vault is unlocked in timed-lock mode, lib/vault.ts
// arms a periodic 'vault-keepalive' alarm. Each tick does a trivial async
// storage read, which resets the Chrome MV3 service-worker idle timer and keeps
// the in-memory decrypted key alive until the configured auto-lock fires —
// instead of the SW being torn down early (e.g. on page refresh, bug #10).
// Guarded for environments without browser.alarms (Safari persistent background
// page, tests).
if (browser.alarms?.onAlarm) {
browser.alarms.onAlarm.addListener((alarm: chrome.alarms.Alarm) => {
if (alarm.name === 'vault-keepalive') {
// Trivial read just to reset the SW idle timer; result is unused.
browser.storage.local.get('autoLockMs').catch(() => {});
}
});
}
// ── Startup (runs AFTER listeners are registered, so messages during async
// init don't race against listener registration) ──
loadConfig();
signer.cleanupStale();
// Permission migrations
(async () => {
try {
const data = await browser.storage.local.get('_permMigrationVersion');
if ((data as Record<string, unknown>)._permMigrationVersion !== 4) {
await signerPermissions.migrateToPerKind();
await signerPermissions.migrateToPerAccount();
await signerPermissions.migrateForwardToAsk();
await signerPermissions.migrateDmKindsToSendMessages();
await browser.storage.local.set({ _permMigrationVersion: 4 });
}
} catch (e: unknown) {
console.warn('[PERMISSIONS] Migration failed:', (e as Error).message);
}
})();
// Auto-unlock vault when auto-lock is "Never"
(async () => {
try {
// Restore the configured auto-lock interval on cold start. _autoLockMs is
// module-level in-memory state that otherwise reverts to the 15-min default
// every time the service worker restarts (bug #10).
await vault.restoreAutoLockSetting();
const data = await browser.storage.local.get(['autoLockMs', 'activeAccountId']);
if (((data as Record<string, unknown>).autoLockMs ?? 900000) === 0 && await vault.exists()) {
const ok = await vault.unlock('');
if (ok) {
if ((data as Record<string, unknown>).activeAccountId) {
try {
await vault.setActiveAccount((data as Record<string, unknown>).activeAccountId as string);
} catch {
vault.clearActiveAccount();
}
}
await signer.onVaultUnlocked();
}
}
} catch (e: unknown) {
console.warn('[VAULT] Auto-unlock failed:', (e as Error).message);
}
})();