Repository navigation
Expand file tree
/
Copy pathsw.js
More file actions
766 lines (661 loc) · 27.5 KB
/
Copy pathsw.js
File metadata and controls
766 lines (661 loc) · 27.5 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
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
// sw.js - Service Worker for Push Notifications with Client Verification
// ================================================
// This file MUST be at the root of the site
// to have scope over all pages.
// ================================================
const SW_VERSION = '2.6.0';
// ================================================
// INDEXEDDB CONFIGURATION
// ================================================
const DB_NAME = 'pombo-sw';
const DB_VERSION = 3;
const STORES = {
CHANNELS: 'channels',
LAST_SEEN: 'lastSeen',
CONFIG: 'config',
DM_PEERS: 'dmPeers'
};
let db = null;
const PROVIDERS_REFRESH_MS = 10 * 60 * 1000;
const GRAPH_TIMEOUT_MS = 8000;
const API_PATH = '/streams/{streamId}/data/partitions/{partition}/last?count=1';
// A page has to sign for us, so it must answer while the push event is alive.
const SIGNATURE_TIMEOUT_MS = 3000;
// ================================================
// INDEXEDDB FUNCTIONS
// ================================================
async function openDatabase() {
if (db) return db;
return new Promise((resolve, reject) => {
const request = indexedDB.open(DB_NAME, DB_VERSION);
request.onerror = () => {
console.error('[SW] IndexedDB error:', request.error);
reject(request.error);
};
request.onsuccess = () => {
db = request.result;
console.log('[SW] IndexedDB opened');
resolve(db);
};
request.onupgradeneeded = (event) => {
const database = event.target.result;
// The tag index must NOT be unique: a tag is one byte, so two of
// this user's own channels can hold the same one.
if (!database.objectStoreNames.contains(STORES.CHANNELS)) {
const channelsStore = database.createObjectStore(STORES.CHANNELS, { keyPath: 'streamId' });
channelsStore.createIndex('tag', 'tag', { unique: false });
console.log('[SW] Created channels store with tag index');
} else {
const channelsStore = event.target.transaction.objectStore(STORES.CHANNELS);
if (channelsStore.indexNames.contains('tag')) {
channelsStore.deleteIndex('tag');
}
channelsStore.createIndex('tag', 'tag', { unique: false });
console.log('[SW] Tag index rebuilt as non-unique');
}
// LastSeen store
if (!database.objectStoreNames.contains(STORES.LAST_SEEN)) {
database.createObjectStore(STORES.LAST_SEEN, { keyPath: 'streamId' });
console.log('[SW] Created lastSeen store');
}
// Config store
if (!database.objectStoreNames.contains(STORES.CONFIG)) {
database.createObjectStore(STORES.CONFIG, { keyPath: 'key' });
console.log('[SW] Created config store');
}
// DM Peers store (address -> name mapping)
if (!database.objectStoreNames.contains(STORES.DM_PEERS)) {
database.createObjectStore(STORES.DM_PEERS, { keyPath: 'address' });
console.log('[SW] Created dmPeers store');
}
};
});
}
/**
* Every channel registered under a tag, with the watermark already notified
* about. ALL of them: one byte of tag collides across this user's own
* channels by design, so a single answer is never the whole answer.
*/
async function getChannelsByTag(tag) {
if (!db) await openDatabase();
return new Promise((resolve, reject) => {
const tx = db.transaction([STORES.CHANNELS, STORES.LAST_SEEN], 'readonly');
const channelsStore = tx.objectStore(STORES.CHANNELS);
const lastSeenStore = tx.objectStore(STORES.LAST_SEEN);
const request = channelsStore.index('tag').getAll(tag);
request.onsuccess = () => {
const channels = request.result || [];
if (channels.length === 0) {
resolve([]);
return;
}
let pending = channels.length;
const out = [];
for (const channel of channels) {
const lastSeenReq = lastSeenStore.get(channel.streamId);
const done = (timestamp) => {
out.push({ ...channel, lastTimestamp: timestamp });
if (--pending === 0) resolve(out);
};
lastSeenReq.onsuccess = () => done(lastSeenReq.result?.timestamp || 0);
lastSeenReq.onerror = () => done(0);
}
};
request.onerror = () => reject(request.error);
});
}
async function updateLastSeen(streamId, timestamp) {
if (!db) await openDatabase();
return new Promise((resolve, reject) => {
const tx = db.transaction(STORES.LAST_SEEN, 'readwrite');
const store = tx.objectStore(STORES.LAST_SEEN);
store.put({
streamId,
timestamp,
updatedAt: Date.now()
});
tx.oncomplete = () => resolve();
tx.onerror = () => reject(tx.error);
});
}
async function syncChannelsToIndexedDB(channels) {
if (!db) await openDatabase();
return new Promise((resolve, reject) => {
const tx = db.transaction(STORES.CHANNELS, 'readwrite');
const store = tx.objectStore(STORES.CHANNELS);
// Clear old channels
const clearReq = store.clear();
clearReq.onsuccess = () => {
// Add new channels
for (const channel of channels) {
store.put({
streamId: channel.streamId,
type: channel.type,
name: channel.name || 'Channel',
tag: channel.tag,
storageEndpoints: channel.storageEndpoints || [],
// Whether the node serves this stream only to a signed
// read. The page decides it: it knows the channel's real
// type, which the labels here do not carry.
needsSignature: !!channel.needsSignature,
lastChecked: Date.now()
});
}
};
tx.oncomplete = () => {
console.log('[SW] Synced', channels.length, 'channels to IndexedDB');
resolve();
};
tx.onerror = () => reject(tx.error);
});
}
async function getConfig(key) {
if (!db) await openDatabase();
return new Promise((resolve) => {
const request = db.transaction(STORES.CONFIG, 'readonly').objectStore(STORES.CONFIG).get(key);
request.onsuccess = () => resolve(request.result?.value ?? null);
request.onerror = () => resolve(null);
});
}
async function setConfig(key, value) {
if (!db) await openDatabase();
return new Promise((resolve, reject) => {
const tx = db.transaction(STORES.CONFIG, 'readwrite');
tx.objectStore(STORES.CONFIG).put({ key, value });
tx.oncomplete = () => resolve();
tx.onerror = () => reject(tx.error);
});
}
async function rememberProviders(streamId, endpoints) {
if (!db) await openDatabase();
return new Promise((resolve, reject) => {
const tx = db.transaction(STORES.CHANNELS, 'readwrite');
const store = tx.objectStore(STORES.CHANNELS);
const request = store.get(streamId);
request.onsuccess = () => {
if (!request.result) return;
store.put({
...request.result,
...(endpoints.length > 0 ? { storageEndpoints: endpoints } : {}),
providersCheckedAt: Date.now()
});
};
tx.oncomplete = () => resolve();
tx.onerror = () => reject(tx.error);
});
}
// DM peer name sync/lookup removed: sealed sender makes the SW unable to
// identify a DM's sender, so there was nothing left to look a name up for.
// The empty DM_PEERS object store is left in place on existing installs
// (harmless) rather than forcing an IndexedDB migration.
// ================================================
// HTTP VERIFICATION FUNCTIONS
// ================================================
function buildUrl(endpoint, streamId, partition = 0) {
const encoded = encodeURIComponent(streamId);
return endpoint + API_PATH
.replace('{streamId}', encoded)
.replace('{partition}', partition);
}
async function fetchWithTimeout(url, timeout = 5000, extraHeaders = null) {
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), timeout);
try {
const response = await fetch(url, {
method: 'GET',
headers: { 'Accept': 'application/json', ...(extraHeaders || {}) },
signal: controller.signal
});
clearTimeout(timeoutId);
if (!response.ok) {
return { success: false, status: response.status, error: `HTTP ${response.status}` };
}
const data = await response.json();
if (!data || data.length === 0) {
return { success: true, timestamp: 0 };
}
const msg = data[0];
return {
success: true,
timestamp: msg.timestamp,
content: msg.content,
publisherId: msg.publisherId
};
} catch (error) {
clearTimeout(timeoutId);
throw error;
}
}
/**
* Asks an open page to sign a storage read. The key lives in the page, behind
* the user's unlock, and must never be held here, so a wake that arrives with
* every window closed cannot verify a private stream and stays silent.
* @returns {Promise<Object|null>} the x-pombo-* headers, or null
*/
async function requestSignature(url) {
const windows = await self.clients.matchAll({ type: 'window', includeUncontrolled: true });
for (const client of windows) {
const headers = await askClientToSign(client, url);
if (headers) return headers;
}
return null;
}
function askClientToSign(client, url) {
return new Promise((resolve) => {
let settled = false;
const finish = (value) => {
if (settled) return;
settled = true;
clearTimeout(timer);
resolve(value);
};
const timer = setTimeout(() => finish(null), SIGNATURE_TIMEOUT_MS);
try {
const channel = new MessageChannel();
channel.port1.onmessage = (event) => finish(event.data?.headers || null);
client.postMessage({ type: 'SIGN_STORAGE_READ', url }, [channel.port2]);
} catch (error) {
finish(null);
}
});
}
// A provider taken off a stream still serves its old rows: its "nothing new" proves nothing.
async function verifyChannel(channel) {
const stored = channel.storageEndpoints || [];
const result = stored.length > 0
? await verifyAt(channel, stored)
: { hasNew: false, error: 'No providers' };
if (result.hasNew || result.error === 'No signer') return result;
if (Date.now() - (channel.providersCheckedAt || 0) < PROVIDERS_REFRESH_MS) return result;
const current = await resolveProviders(channel.streamId);
await rememberProviders(channel.streamId, current)
.catch((error) => console.warn('[SW] Could not record providers:', error?.message));
if (current.length === 0 || sameEndpoints(current, stored)) return result;
console.log('[SW] Providers of', channel.streamId, 'changed; asking the current ones');
return verifyAt(channel, current);
}
function sameEndpoints(a, b) {
return a.length === b.length && a.every((url) => b.includes(url));
}
/** Mirrors the page's isWebSafeStorageNodeUrl: https, a name, never an IP literal. */
function isWebSafeUrl(value) {
try {
const url = new URL(value);
const host = url.hostname.toLowerCase();
if (url.protocol !== 'https:') return false;
if (!host || host === 'localhost' || host.endsWith('.localhost')) return false;
if (/^\d{1,3}(?:\.\d{1,3}){3}$/.test(host) || host.includes(':')) return false;
return true;
} catch {
return false;
}
}
async function resolveProviders(streamId) {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), GRAPH_TIMEOUT_MS);
try {
const graphUrl = await getConfig('graphUrl');
if (!graphUrl) return [];
const response = await fetch(graphUrl, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
query: `{ stream(id: ${JSON.stringify(streamId)}) { storageNodes { metadata } } }`
}),
signal: controller.signal
});
if (!response.ok) return [];
const body = await response.json();
const urls = [];
for (const node of body?.data?.stream?.storageNodes || []) {
let metadata;
try { metadata = JSON.parse(node?.metadata || '{}'); } catch { continue; }
for (const raw of Array.isArray(metadata?.urls) ? metadata.urls : []) {
const url = typeof raw === 'string' ? raw.trim().replace(/\/+$/, '') : '';
if (isWebSafeUrl(url) && !urls.includes(url)) urls.push(url);
}
}
return urls;
} catch (error) {
console.warn('[SW] Could not ask The Graph about', streamId, error?.message);
return [];
} finally {
clearTimeout(timer);
}
}
async function verifyAt(channel, endpoints) {
const { streamId, lastTimestamp, needsSignature } = channel;
for (const endpoint of endpoints) {
try {
const url = buildUrl(endpoint, streamId, 0);
let headers = null;
if (needsSignature) {
headers = await requestSignature(url);
if (!headers) {
// No page to sign: every endpoint would refuse the same way.
console.log('[SW] No open window to sign for', streamId);
return { hasNew: false, error: 'No signer' };
}
}
const result = await fetchWithTimeout(url, 5000, headers);
if (result.success) {
const hasNew = result.timestamp > lastTimestamp;
return {
hasNew,
timestamp: result.timestamp,
content: hasNew ? result.content : null,
publisherId: hasNew ? result.publisherId : null
};
}
// A 4xx is the node answering ABOUT the request (unsigned, no
// access, stream gone); the next node answers the same. Only a
// node that failed as a node is worth asking again.
if (result.status >= 400 && result.status < 500) {
console.warn(`[SW] ${result.error} for ${streamId}`);
return { hasNew: false, error: result.error };
}
console.warn(`[SW] Endpoint ${endpoint}: ${result.error}`);
} catch (error) {
console.warn(`[SW] Endpoint ${endpoint} failed:`, error.message);
}
}
console.warn('[SW] All storage endpoints failed for', streamId);
return { hasNew: false, error: 'All endpoints failed' };
}
// ================================================
// MESSAGE PREVIEW FOR NOTIFICATIONS
// ================================================
function getMessagePreview(channel) {
const { type, content } = channel;
// Nothing here holds the key to a channel's own encryption, and a direct
// message arrives sealed to a key that lives in the page: all this can say
// is that something arrived.
if (type === 'dm') {
return 'You have a new message';
}
// 'native' is what an install registered before this version called a
// gated channel, and 'private' can still come from a channel saved long
// ago: both mean "encrypted", so neither may fall through to the branch
// that prints what was said.
if (type === 'gated' || type === 'native' || type === 'private') {
return 'New message';
}
// Public channels - show content
if (!content) {
return 'New message';
}
switch (content.type) {
case 'text':
const text = content.text || '';
return text.length > 100 ? text.substring(0, 100) + '...' : text;
case 'image':
return '📷 Image';
case 'file':
return `📎 ${content.fileName || 'File'}`;
case 'audio':
return '🎵 Audio message';
case 'video':
return '🎬 Video';
case 'gif':
return '🎞️ GIF';
case 'reaction':
return `Reacted with ${content.emoji || '👍'}`;
default:
return 'New message';
}
}
// ================================================
// INSTALLATION
// ================================================
self.addEventListener('install', (event) => {
console.log('[SW] Installed v' + SW_VERSION);
self.skipWaiting();
});
self.addEventListener('activate', (event) => {
console.log('[SW] Activated');
event.waitUntil(
(async () => {
await openDatabase();
await self.clients.claim();
console.log('[SW] Ready for push verification');
})()
);
});
// ================================================
// PUSH NOTIFICATION WITH VERIFICATION
// ================================================
self.addEventListener('push', (event) => {
console.log('[SW] Push received');
let data = {};
try {
if (event.data) {
data = event.data.json();
}
} catch (e) {
console.warn('[SW] Push data is not JSON:', e);
}
event.waitUntil(handlePushWithVerification(data));
});
async function handlePushWithVerification(pushData) {
try {
if (!db) {
await openDatabase();
}
const { tag } = pushData;
// If no tag, can't verify - ignore (K-anonymity noise)
if (!tag) {
console.log('[SW] Push without tag - ignoring (K-anonymity noise)');
return;
}
// Key-request wake: silent by contract. The key responder runs in an
// open tab (its own sweep loop) — the SW neither sweeps nor notifies.
if (pushData.channelType === 'keys') {
console.log('[SW] Keys wake - silent (key responder handles it in-tab)');
return;
}
// Every channel under this tag, since one byte collides by design.
const channels = await getChannelsByTag(tag);
if (channels.length === 0) {
console.log('[SW] Channel not found for tag - ignoring (not subscribed)');
return;
}
for (const channel of channels) {
console.log('[SW] Verifying channel:', channel.name || channel.streamId);
const result = await verifyChannel(channel);
if (!result.hasNew) {
console.log('[SW] No new messages - false positive');
continue;
}
await updateLastSeen(channel.streamId, result.timestamp);
await showVerifiedNotification({
...channel,
newTimestamp: result.timestamp,
content: result.content,
publisherId: result.publisherId
});
}
} catch (error) {
console.error('[SW] Verification error:', error);
// Fallback: show generic notification
await showFallbackNotification(pushData);
}
}
async function showVerifiedNotification(channelWithNews) {
// Title. DMs are deliberately MINIMAL and never name the sender.
//
// Under sealed sender the row's publisherId is a throwaway key and the
// real sender lives inside the ECDH ciphertext — unreadable without the
// wallet private key, which the service worker does not have and must
// never hold (it lives behind the page's unlock-derived AES key, in page
// memory only). Attributing from the throwaway publisherId would be
// wrong, so we don't try: a DM notification says only that one arrived.
// Per-peer mute is unavailable here for the same reason — the sender
// cannot be known — so a muted peer may still produce this generic
// notification when no tab is open; the app-layer honours the mute
// whenever a tab is alive. See the port brief.
let title;
if (channelWithNews.type === 'dm' || channelWithNews.type === 'dm-inbox') {
title = 'Pombo';
} else if (channelWithNews.type === 'gated' || channelWithNews.type === 'native' || channelWithNews.type === 'private') {
title = channelWithNews.name || 'Pombo';
} else {
// Public channel: content is public by design, so the channel name
// and a preview are not a disclosure.
title = channelWithNews.name || 'Pombo';
}
const body = getMessagePreview(channelWithNews);
const options = {
body: body,
icon: '/favicon/web-app-manifest-192x192.png',
badge: '/favicon/favicon-96x96.png',
tag: 'pombo-' + Date.now(),
renotify: true,
requireInteraction: false,
silent: false,
vibrate: [200, 100, 200],
data: {
url: '/',
channelStreamId: channelWithNews.streamId,
timestamp: channelWithNews.newTimestamp
},
actions: [
{ action: 'open', title: 'Open' },
{ action: 'dismiss', title: 'Dismiss' }
]
};
// Check if app is focused
const clients = await self.clients.matchAll({
type: 'window',
includeUncontrolled: true
});
const focusedClient = clients.find(c => c.focused);
if (focusedClient) {
console.log('[SW] App already focused - notifying via postMessage');
focusedClient.postMessage({
type: 'NEW_MESSAGE',
streamId: channelWithNews.streamId,
timestamp: channelWithNews.newTimestamp,
content: channelWithNews.content
});
return;
}
return self.registration.showNotification(title, options);
}
async function showFallbackNotification(pushData) {
const options = {
body: pushData.channelType === 'private'
? 'New message in private channel'
: 'You may have new messages',
icon: '/favicon/web-app-manifest-192x192.png',
badge: '/favicon/favicon-96x96.png',
tag: 'pombo-fallback-' + Date.now(),
renotify: true,
vibrate: [200, 100, 200],
data: {
url: '/'
}
};
return self.registration.showNotification('Pombo', options);
}
// ================================================
// NOTIFICATION CLICK
// ================================================
self.addEventListener('notificationclick', (event) => {
console.log('[SW] Notification clicked:', event.action);
event.notification.close();
if (event.action === 'dismiss') {
return;
}
// Open or focus the app
event.waitUntil(
self.clients.matchAll({ type: 'window', includeUncontrolled: true })
.then((clients) => {
// If we already have a window, focus it
if (clients.length > 0) {
const client = clients[0];
client.focus();
// Notify that it was clicked
client.postMessage({
type: 'NOTIFICATION_CLICKED'
});
return;
}
// Otherwise, open new window
return self.clients.openWindow(event.notification.data?.url || '/');
})
);
});
// ================================================
// NOTIFICATION CLOSE
// ================================================
self.addEventListener('notificationclose', (event) => {
console.log('[SW] Notification closed');
});
// ================================================
// WEB SHARE TARGET
// Receives images shared from any Android app (Tenor, Gallery,
// Samsung Keyboard long-press → Share, etc.) when Pombo is installed
// as a PWA. Files are stashed in a Cache and the page is redirected
// to /?share=1 so the SPA can pick them up on boot.
// ================================================
const SHARE_CACHE = 'pombo-share-v1';
const SHARE_ALLOWED_MIME = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
self.addEventListener('fetch', (event) => {
const url = new URL(event.request.url);
if (event.request.method !== 'POST' || url.pathname !== '/share') return;
event.respondWith(handleShareTarget(event.request));
});
async function handleShareTarget(request) {
try {
const formData = await request.formData();
const files = formData.getAll('shared').filter(f =>
f instanceof File && SHARE_ALLOWED_MIME.includes(f.type)
);
const cache = await caches.open(SHARE_CACHE);
// Wipe previous shares so we never replay stale files.
const old = await cache.keys();
await Promise.all(old.map(req => cache.delete(req)));
for (let i = 0; i < files.length; i++) {
const file = files[i];
await cache.put(
`/__shared/${i}`,
new Response(file, {
headers: {
'Content-Type': file.type,
'X-Pombo-Filename': encodeURIComponent(file.name || `shared-${i}`)
}
})
);
}
} catch (err) {
console.warn('[SW] Share target handling failed:', err?.message);
}
return Response.redirect('/?share=1', 303);
}
// ================================================
// CLIENT MESSAGES
// ================================================
self.addEventListener('message', async (event) => {
const { type } = event.data || {};
// Sync channels from app
if (type === 'SYNC_CHANNELS') {
console.log('[SW] Syncing channels:', event.data.channels?.length || 0);
await syncChannelsToIndexedDB(event.data.channels || []);
if (event.data.graphUrl) await setConfig('graphUrl', event.data.graphUrl);
// DM peer names are no longer synced: under sealed sender the SW cannot
// know a DM's sender (see showVerifiedNotification), so a peer
// address→name map here would be unused identity data — dropped.
return;
}
// Update last seen timestamp
if (type === 'UPDATE_LAST_SEEN') {
await updateLastSeen(event.data.streamId, event.data.timestamp);
return;
}
// Force update
if (type === 'SKIP_WAITING') {
self.skipWaiting();
return;
}
console.log('[SW] Unknown message type:', type);
});