@witbitz/sdk 0.0.0-stage → 4.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +20 -2
- package/a2aCore.js +200 -0
- package/a2aShared.js +27 -0
- package/accountErase.js +223 -0
- package/accountIndexDoc.js +122 -0
- package/accountOwner.js +59 -0
- package/accountRecord.js +90 -0
- package/accountScope.js +114 -0
- package/accountSeal.js +42 -0
- package/accountStores.js +173 -0
- package/acctV2App.js +619 -0
- package/acctV2Check.js +29 -0
- package/acctV2Client.js +382 -0
- package/acctV2Keys.js +43 -0
- package/acctV2Legacy.js +14 -0
- package/acctV2Switch.js +80 -0
- package/acctV2UiCore.js +857 -0
- package/acctV2WebAuthn.js +61 -0
- package/acctV2Wire.js +59 -0
- package/address.js +42 -0
- package/attestedBox.js +30 -0
- package/attestedRooms.js +78 -0
- package/awsKey.js +98 -0
- package/backupRecord.js +106 -0
- package/backupVault.js +97 -0
- package/blocks.js +115 -0
- package/blocksPush.js +64 -0
- package/browseSeal.js +103 -0
- package/cbor.js +225 -0
- package/changePush.js +75 -0
- package/chatLock.js +149 -0
- package/chatLockSw.js +13 -0
- package/cloudDeviceBuilds.js +11 -0
- package/cloudDevicePins.js +33 -0
- package/cloudDeviceSeal.js +53 -0
- package/codeBrowse.js +224 -0
- package/codeCloud.js +652 -0
- package/codeCloudKeys.js +112 -0
- package/codeCommands.js +167 -0
- package/codeComputers.js +388 -0
- package/codeEgress.js +123 -0
- package/codeFilesRoutes.js +17 -0
- package/codeMkdir.js +8 -0
- package/codeModes.js +57 -0
- package/codeOrphanKeys.js +42 -0
- package/codeOutputs.js +141 -0
- package/codeRelay.js +505 -0
- package/codeSentinel.js +86 -0
- package/codeTransport.js +295 -0
- package/codeUndo.js +48 -0
- package/compress.js +24 -0
- package/config.js +11 -0
- package/connCatalog.js +164 -0
- package/connDisp.js +76 -0
- package/connOtherWays.js +74 -0
- package/connPending.js +16 -0
- package/connWrap.js +53 -0
- package/connectionEntry.js +89 -0
- package/connections.js +562 -0
- package/credits.js +30 -0
- package/csAttest.js +112 -0
- package/decrypt.html +384 -0
- package/deviceAttest.js +521 -0
- package/deviceCall.js +54 -0
- package/deviceKeyCore.js +41 -0
- package/deviceSeal.js +59 -0
- package/e2ee.js +323 -0
- package/eat.js +103 -0
- package/emailFork.js +275 -0
- package/emailSignIn.js +81 -0
- package/emptySpaces.js +111 -0
- package/encSource.js +55 -0
- package/enclaveAccept.js +214 -0
- package/enclaveClaim.js +241 -0
- package/enclaveRoute.js +102 -0
- package/enclaveSnapshotMerge.js +44 -0
- package/entrySig.js +165 -0
- package/env.js +73 -0
- package/eraseFile.js +58 -0
- package/followImage.js +86 -0
- package/healNames.js +45 -0
- package/idb.js +97 -0
- package/idbSeal.js +119 -0
- package/indexGone.js +12 -0
- package/invite.js +51 -0
- package/inviteEnroll.js +67 -0
- package/inviteSend.js +68 -0
- package/jobAgents.js +87 -0
- package/keptMerge.js +84 -0
- package/l1-worker-src.js +2 -0
- package/l1-worker.js +831 -0
- package/laneConfig.js +57 -0
- package/laneLinkCore.js +177 -0
- package/ledgerView.js +64 -0
- package/manifest.json +220 -0
- package/mcpRecommended.js +25 -0
- package/memberChange.js +123 -0
- package/mkseal.js +101 -0
- package/nativePush.js +153 -0
- package/nitroVerify.js +220 -0
- package/noble-p256.js +27 -0
- package/notice.js +116 -0
- package/notifKey.js +58 -0
- package/offlineBundle.js +62 -0
- package/ohttp.js +177 -0
- package/opencodeWire.js +282 -0
- package/oprf.js +70 -0
- package/ownAgentLink.js +96 -0
- package/ownerPolicy.js +117 -0
- package/package.json +254 -4
- package/pollVerdict.js +33 -0
- package/prefetchPoll.js +60 -0
- package/protectedLocal.js +410 -0
- package/pushCore.js +42 -0
- package/recovery.js +107 -0
- package/regions.js +42 -0
- package/removedMessage.js +11 -0
- package/renameRefusal.js +9 -0
- package/replyQuote.js +34 -0
- package/reqEnvelope.js +126 -0
- package/roomDefaultPrefs.js +76 -0
- package/roomDelete.js +109 -0
- package/roomName.js +177 -0
- package/roomPass.js +256 -0
- package/roomRoster.js +289 -0
- package/roomSettings.js +61 -0
- package/roomState.js +58 -0
- package/roomStreamClient.js +115 -0
- package/rosterCount.js +49 -0
- package/rosterHash.js +13 -0
- package/rowSchema.js +113 -0
- package/safeMedia.js +116 -0
- package/safeMediaPins.js +17 -0
- package/schedulesDoc.js +78 -0
- package/sdkA2A.js +404 -0
- package/sdkAccount.js +470 -0
- package/sdkAccountDoc.js +81 -0
- package/sdkAccountSections.js +223 -0
- package/sdkAgui.js +141 -0
- package/sdkAttest.js +34 -0
- package/sdkBackup.js +480 -0
- package/sdkBackupV2.js +630 -0
- package/sdkBrowserPrivate.js +28 -0
- package/sdkBuilds.js +208 -0
- package/sdkCloudDevice.js +215 -0
- package/sdkComputers.js +480 -0
- package/sdkDictation.js +142 -0
- package/sdkErase.js +283 -0
- package/sdkExports.js +69 -0
- package/sdkInvitations.js +34 -0
- package/sdkKeptAgent.js +188 -0
- package/sdkLaneLink.js +205 -0
- package/sdkPlan.js +94 -0
- package/sdkProtect.js +228 -0
- package/sdkRedact.js +36 -0
- package/sdkRekey.js +307 -0
- package/sdkReport.js +68 -0
- package/sdkSafeMedia.js +255 -0
- package/sdkSchedules.js +39 -0
- package/sdkSpeech.js +54 -0
- package/sdkTurn.js +117 -0
- package/sdkVault.js +124 -0
- package/sealShare.js +18 -0
- package/sealedNames.js +64 -0
- package/sealedReceipt.js +17 -0
- package/sentinelRelease.js +154 -0
- package/shamir.js +85 -0
- package/sharedViews.js +38 -0
- package/sheetChrome.js +450 -0
- package/siri.js +171 -0
- package/spaceClient.js +1418 -0
- package/spaceConfig.js +81 -0
- package/spaceEmailGate.js +813 -0
- package/spaceExport.js +125 -0
- package/spaceFork.js +216 -0
- package/spaceLock.js +358 -0
- package/spacePasskey.js +180 -0
- package/speechOut.js +100 -0
- package/splitKeyClient.js +90 -0
- package/store.js +587 -0
- package/streamHint.js +36 -0
- package/sttCloud.js +220 -0
- package/sttWorklet.js +38 -0
- package/sw-notif-core.js +538 -0
- package/tempList.js +48 -0
- package/tinfoilVerifier.js +78 -0
- package/toolBooks.js +31 -0
- package/toolRules.js +52 -0
- package/turnCerts.js +254 -0
- package/turnFeed.js +58 -0
- package/turnVerdict.js +36 -0
- package/usageReceipts.js +176 -0
- package/usageSummary.js +90 -0
- package/util.js +181 -0
- package/vault-core.js +1958 -0
- package/vault-kit.mjs +354 -0
- package/vault-screens.js +263 -0
- package/vaultAtRest.js +177 -0
- package/vaultCoreLock.js +111 -0
- package/vaultCorePush.js +140 -0
- package/vaultDeviceKey.js +95 -0
- package/vaultEnclaveHandoff.js +114 -0
- package/vaultKeep.js +281 -0
- package/vaultSealedStore.js +77 -0
- package/vaultWorkerHost.js +98 -0
- package/vcWorker.js +34 -0
- package/voiceAttest.js +50 -0
- package/voiceCert.js +51 -0
- package/witbitz-admin.d.ts +135 -0
- package/witbitz-admin.js +529 -0
- package/witbitz-admin.mjs +1459 -0
- package/witbitz-sdk.d.ts +1106 -0
- package/witbitz-sdk.js +3835 -0
- package/workerClient.js +16 -0
- package/workerLiveness.js +21 -0
- package/x509.js +218 -0
package/l1-worker.js
ADDED
|
@@ -0,0 +1,831 @@
|
|
|
1
|
+
// spaces/public/l1-worker.js — A2a of the thin-L1 migration (docs/verified-client-l1-interface.md):
|
|
2
|
+
// the mk-CUSTODY KERNEL as a Web Worker. It hosts the sealed-ledger client, holds the room mk, and does
|
|
3
|
+
// all mk-crypto (keyFields) + entry signing (turn's identity JWK). The main thread posts SEMANTIC ops
|
|
4
|
+
// ({op, room, args}); mk NEVER posts back out — a main-thread (L3) compromise cannot read this realm's
|
|
5
|
+
// memory. spaceClient + its whole dep chain (e2ee/entrySig/mkseal/ownerPolicy/rosterHash/spaceConfig/
|
|
6
|
+
// invite) are localStorage/DOM-free, so they run here unmodified.
|
|
7
|
+
//
|
|
8
|
+
// FLAG-GATED: only used when the page is opened with ?l1worker=1 (l1.js). Default OFF → the A1 direct
|
|
9
|
+
// façade runs and this worker is never spawned. Ships safe; validate behind the flag before enabling.
|
|
10
|
+
//
|
|
11
|
+
// Auth stays on the main thread (localStorage-backed cachedEmailAuth): when the client needs auth for a
|
|
12
|
+
// room, `auth(room)` round-trips to the main thread via {authReq}. The enclave tier (mkPub/enclave) is
|
|
13
|
+
// read SYNCHRONOUSLY by keyFields, so we keep a pushed snapshot {enclaveKey, enclaveRooms} and read it
|
|
14
|
+
// locally rather than round-trip.
|
|
15
|
+
import { prefetchUsable, positionOf, prefetchAnswer, prefetchHashKey } from './prefetchPoll.js'
|
|
16
|
+
import { makeSpaceClient, setAttestProvider, setPushSelf, setPushAcct, pushAcctSecretOf, viewingTag } from './spaceClient.js'
|
|
17
|
+
import { idb } from './idb.js'
|
|
18
|
+
import { armIdbNaming, setIdbNaming } from './idbSeal.js' // §NAMES (docs/desktop-protection.md phase 2): this realm's store keeps opaque names on a protected device
|
|
19
|
+
import { _hasGzip, _jsonBytes, gunzipB64, gzipB64 } from './compress.js' // Atlas index docs: gzip/absorb/inject worker-side
|
|
20
|
+
import { combineShares, commit as commitMk } from './e2ee.js' // §9 split-key: reconstruct mk = userShare ⊕ appShare inside the worker (confinement mode)
|
|
21
|
+
import { deriveNotifKey } from './notifKey.js'
|
|
22
|
+
import { importRaw as importSealKey, sealIf, open as openSealed, isSealed } from './deviceSeal.js' // DEVICE STORAGE PROTECTION (docs/device-storage-protection.md): with the switch on, every key this worker persists is ciphertext under a key held only HERE, in memory
|
|
23
|
+
import { sealDoc, openDoc, isSealedDoc, rawSealKey } from './accountSeal.js' // acctSeal / acctOpen: room messages sealed under the account key (roomMail.js); rawSealKey: the temp index's own seal key
|
|
24
|
+
import { editTempList, addToTempList, removeFromTempList, keylessTempList, isTempRoomId } from './tempList.js' // the temporary-Spaces list, kept HERE for the hosted app (op tempList)
|
|
25
|
+
import { makeAccountStore } from './accountStores.js' // the account's sync docs SEALED on the device (docs/sdk-convergence.md § The account stores)
|
|
26
|
+
import { openRoomStream } from './roomStreamClient.js' // ROOM STREAMS: the socket lives HERE, beside the key it derives from (docs/change-inbox.md § Room streams)
|
|
27
|
+
import { roomRegion, DEFAULT_REGION } from './regions.js' // a room's region is in its id — its enclave's key seals it
|
|
28
|
+
import { opensEnvelopes, sealsIdentity } from './reqEnvelope.js' // does a live enclave open the sealed request envelope
|
|
29
|
+
import { gatedKey } from './enclaveAccept.js' // the user's accepted builds: the SAME seal gate as enclave.js, run here because mk is sealed HERE // §Phase-4: mirror NK=HKDF(mk,'notif') to idb HERE (the confined kernel) so vault-sw.js gets a preview key for SPLIT rooms — whose mk only ever materializes in this worker, never the main-thread loader (that's why split rooms showed the generic nudge)
|
|
30
|
+
import { signInOf, SIGNIN_RENEW_AUTH } from './roomPass.js' // the room pass: which sign-in a request carries (the page answers for it)
|
|
31
|
+
// One room's stream socket here (the key never leaves): events go up to the page; `tag` names this device as viewing it.
|
|
32
|
+
// A CARRIED ENTRY (roomStreamClient `tail`): kept here, beside the key, for the poll the event asks for — the page gets the event
|
|
33
|
+
// without the box. room → { count, box, at }; used once, for a poll from count-1, within FRAME_TAIL_MS.
|
|
34
|
+
const frameTails = new Map()
|
|
35
|
+
const FRAME_TAIL_MS = 30000
|
|
36
|
+
function openStreamHere (room, mk, grants, tag) {
|
|
37
|
+
return openRoomStream({ mk, grants: Array.isArray(grants) ? grants : null, tag, onEvent: (ev) => {
|
|
38
|
+
if (ev && ev.tail) { frameTails.set(room, { ...ev.tail, at: Date.now() }); const { tail, ...rest } = ev; ev = rest }
|
|
39
|
+
self.postMessage({ t: 'stream', room, ev })
|
|
40
|
+
}, onState: (up) => self.postMessage({ t: 'stream', room, up }) })
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
let client = null
|
|
44
|
+
let clientRealm = '' // the realm (endpoint · app · tenant) `client` was made for — 'open' keeps it within one (sweep 11-07 #6)
|
|
45
|
+
// ⛔ The account's sync docs (index, index2, pipes, …) carry every room key — sealed under acctKey before they leave
|
|
46
|
+
// (accountStores.js). acctKey comes from the page that owns this worker (regular app) or the vault hosting it (tenant).
|
|
47
|
+
let acctKey = null
|
|
48
|
+
let oldAcctKeys = [] // the account keys of PREVIOUS masters (accountStores.js oldKeys: documents sealed before a new master)
|
|
49
|
+
const unzipDoc = async (st) => (st && typeof st === 'object' && typeof st.z === 'string') ? await gunzipB64(st.z).catch(() => null) : st
|
|
50
|
+
const acct = makeAccountStore({ call: (...a) => client.state(...a), key: async () => acctKey, oldKeys: async () => oldAcctKeys })
|
|
51
|
+
// THE TEMPORARY-SPACES LIST (tempRooms.js; the owner, 2026-11-13: "Do 1+3+4"): in the hosted app the vault hands this worker the
|
|
52
|
+
// temp index's pointer (op tempHold — { room, sk }, its key into `mks`), and the frame reads and edits the list through op tempList,
|
|
53
|
+
// keyless. The list carries every temp room's key, sealed under the pointer's own random key `sk` (as the page seals it).
|
|
54
|
+
let tempPtr = null
|
|
55
|
+
const tempStore = makeAccountStore({ call: (...a) => client.state(...a), key: async () => (tempPtr && tempPtr.sk ? rawSealKey(tempPtr.sk) : null) })
|
|
56
|
+
const TEMP_SK = /^[A-Za-z0-9_-]{43}$/
|
|
57
|
+
// ROOM STREAMS: room → { s, holders }. The stream client needs mk, so it runs in this realm; only EVENTS go out — the
|
|
58
|
+
// reply text as it grows (the same plaintext a poll's partialText already carries out), "poll now", "the turn ended".
|
|
59
|
+
// Several frames can share this worker (the hoisted vault: the app + a lane panel), hence a holder count.
|
|
60
|
+
const streams = new Map()
|
|
61
|
+
const streamFeed = (room, result) => {
|
|
62
|
+
const h = streams.get(room)
|
|
63
|
+
if (!h || !result || result.status !== 200) return
|
|
64
|
+
if (Array.isArray(result.streamGrants)) { h.s.setGrants(result.streamGrants); h.grants = result.streamGrants }
|
|
65
|
+
h.s.sync(typeof result.partialText === 'string' ? result.partialText : '')
|
|
66
|
+
}
|
|
67
|
+
const mks = new Map() // room → mk — the worker's authoritative key store (A2b); mk never posts back out
|
|
68
|
+
// §9 SPLIT-KEY (confinement mode): a split room's key store is the user's userShare + the commit. resolveMk fetches the
|
|
69
|
+
// app half from the same-origin tenant backend, combines, verifies the commit, and CACHES the reconstructed mk in `mks`
|
|
70
|
+
// — so every mk-using op below works unchanged. The vault/worker never holds K_eco (that unwrap is the backend's job).
|
|
71
|
+
const splits = new Map() // room → { userShare, commit }
|
|
72
|
+
// §PERSIST (2026-09-01): mirror BOTH maps to this origin's idb and reload at boot. iOS reclaims workers under memory
|
|
73
|
+
// pressure; the heartbeat recreates one, but everything the old worker had ABSORBED (index-doc userShares, resolved mks)
|
|
74
|
+
// lived only in memory — so there was a window where opens failed ('key hasn't reached this device'). A recreated worker
|
|
75
|
+
// now self-restores instantly. The signout/reset path wipes this store (vault-loader _idbWipe) — the audit still holds.
|
|
76
|
+
// §PROTECT (docs/device-storage-protection.md). `sealKey` is the device's AES key, imported from raw bytes the page derived from
|
|
77
|
+
// its passkey (PRF/largeBlob) and sent over postMessage — non-extractable here, never written anywhere. While it is set, every
|
|
78
|
+
// persisted key is sealed; at boot, sealed entries are PARKED until the page unlocks and sends the key again; `relock` drops
|
|
79
|
+
// the maps and the key from memory. With the switch off (no key, no sealed entries) every store is byte-identical to before.
|
|
80
|
+
let sealKey = null
|
|
81
|
+
let storageEpoch = 0, storageWiped = false
|
|
82
|
+
let nkClear = false // §PREVIEWS (opt-in under protection): the push-preview keys (nk:) are written CLEAR so a locked device's tickle still shows sender + first line; everything else stays sealed
|
|
83
|
+
let protectedAtRest = false // sealed entries were seen at boot (or `seal` ran): the store is protected — NEVER write a clear key over it
|
|
84
|
+
const parked = new Map() // idb key ('mk:'/'us:'/'nk:' + room) → sealed blob awaiting the device key
|
|
85
|
+
// A key that reaches a protected-but-locked worker (the page re-sends a room key it still holds at open) stays in memory
|
|
86
|
+
// only; the `unseal` that follows persists everything held, sealed. Without protection: the clear write, as always.
|
|
87
|
+
// VOLATILE ROOMS (docs/emulated-attested-rooms.md; "attested rooms cannot be watched offline"): an attested room's key is held in
|
|
88
|
+
// this map only — never written, and anything an older build wrote is removed (op `volatile`). The page names them first.
|
|
89
|
+
const volatile = new Set()
|
|
90
|
+
const postAttNk = (room, nk) => { if (!room || !nk || String(room).startsWith('tmp-')) return; try { self.postMessage({ t: 'attNk', room, nk }) } catch { /* */ } }
|
|
91
|
+
const roomOfKey = (k) => String(k).slice(String(k).indexOf(':') + 1)
|
|
92
|
+
const persist = (k, v) => {
|
|
93
|
+
const epoch = storageEpoch
|
|
94
|
+
return storageWiped || volatile.has(roomOfKey(k)) ? Promise.resolve() : keysReady.then(() => ((!sealKey && protectedAtRest) ? undefined : sealIf(sealKey, v).then((stored) => epoch === storageEpoch && !storageWiped ? idb.set(k, stored) : undefined))).catch(() => {})
|
|
95
|
+
} // a wipe also cancels keys whose asynchronous sealing was still running
|
|
96
|
+
// AN ATTESTED ROOM'S PREVIEW KEY (the owner, 2026-11-24: "the notification preview for attested rooms doesn't work"): its room key stays
|
|
97
|
+
// in this worker's memory, so the vault — whose service worker and native shell show the notification — never learned its preview key.
|
|
98
|
+
// The vault gets the PREVIEW KEY alone (it opens a notification's preview, never the room): `attNk`. Nothing is written here.
|
|
99
|
+
const persistNk = (room, nk) => storageWiped ? Promise.resolve() : volatile.has(room) ? (postAttNk(room, nk), Promise.resolve()) : (nkClear ? keysReady.then(() => storageWiped ? undefined : idb.set('nk:' + room, nk)).catch(() => {}) : protectedAtRest ? keysReady.then(() => idb.delRaw('nk:' + room)).catch(() => {}) : persist('nk:' + room, nk))
|
|
100
|
+
// A ROOM'S KEY EPOCH (docs/key-rotation-design.md § (b)): a verified room re-keyed in place counts its keys. Kept per room
|
|
101
|
+
// (not secret: a count) so a key arriving from the account index can be refused when it is OLDER than the one held — a
|
|
102
|
+
// device that had not yet learned the new key, writing the index, must not put the old key back (never backwards).
|
|
103
|
+
const eps = new Map()
|
|
104
|
+
const noteEp = (room, ep) => { const n = Number(ep) || 0; if (room && n > (eps.get(room) || 0)) { eps.set(room, n); if (!volatile.has(room)) idb.set('ep:' + room, n).catch(() => {}) } }
|
|
105
|
+
// NEVER BACKWARDS: a key for a room this worker holds a NEWER key of (a higher epoch) is refused — the hosted vault re-seeds
|
|
106
|
+
// every key it holds at each launch with no epoch, an old link carries its old key, the index of a device that had not yet
|
|
107
|
+
// learned the change carries the old one. A room never re-keyed has epoch 0 everywhere: nothing is refused (as before).
|
|
108
|
+
const backwards = (room, held, incoming, ep) => held !== incoming && (Number(ep) || 0) < (eps.get(room) || 0) // nothing held is no exception: a dropped old key re-seeded without an epoch must not come back
|
|
109
|
+
// THE VAULT LEARNS A RE-KEYED ROOM'S KEY (`keyEpoch`): the hosted vault keeps its own copy of every key (its keyring, the
|
|
110
|
+
// account cache) and seeds a fresh worker from it — told here, it holds the new key and its epoch (vault-loader.js), and
|
|
111
|
+
// never hands the frame or the next worker the old one. Only a key with an epoch, only when it changed. The vault page is
|
|
112
|
+
// this worker's owner and already holds every key; the regular app's page ignores the message.
|
|
113
|
+
const tellEpoch = (room, ep, key) => { if (volatile.has(room) || String(room).startsWith('tmp-')) return; try { self.postMessage({ t: 'keyEpoch', room, ep, ...key }) } catch { /* */ } } // never a memory-only (attested) or temporary room's key: the vault would keep it in its account cache
|
|
114
|
+
const keep = (room, mk, ep) => { if (backwards(room, mks.get(room), mk, ep)) return false; if ((Number(ep) || 0) > 0 && (mks.get(room) !== mk || Number(ep) > (eps.get(room) || 0))) tellEpoch(room, Number(ep), { mk }); if (ep) noteEp(room, ep); mks.set(room, mk); persist('mk:' + room, mk); deriveNotifKey(mk).then((nk) => persistNk(room, nk)).catch(() => {}) } // + NK mirror: every mk the kernel holds (normal OR reconstructed-split) yields a push-preview key, so a background notification for THIS room shows sender+text (vault-sw.js notifPreview), not the generic nudge
|
|
115
|
+
// WHY a room has no key, per room — the worker's own verdict rides the no_key answer (the owner's trail said only "no key on
|
|
116
|
+
// this device" while the index held a share for every room, 2026-10-03).
|
|
117
|
+
const APPSHARE_URL = (() => { try { const o = self.location && self.location.origin; return (o && o !== 'null') ? o + '/api/appshare' : '/api/appshare' } catch (e) { return '/api/appshare' } })()
|
|
118
|
+
const noKeyWhy = new Map()
|
|
119
|
+
const noKeyReason = (room) => 'no key on this device' + (noKeyWhy.has(room) ? ' — ' + noKeyWhy.get(room) : '')
|
|
120
|
+
// Every DIFFERENT split share seen for a room, besides the held one. The index absorb replaces a held share on every read
|
|
121
|
+
// (seconds apart), so a share seeded from the room's own link was shadowed by the index's copy within a breath; resolveMk
|
|
122
|
+
// tries them all against the server's half and promotes the one whose commitment holds.
|
|
123
|
+
const splitAlts = new Map()
|
|
124
|
+
// A NEWER SHARE MAKES THE HELD KEY OLD (the owner, 2026-10-22: "the second device did not follow"): a split room's grant is the
|
|
125
|
+
// new user half; the full key this worker held is the room's OLD key, and resolveMk prefers a held key — so every read went
|
|
126
|
+
// out with it, came back stale_key, and the device fetched its grant for ever. It is dropped; the next read rebuilds the
|
|
127
|
+
// key from the new share and the app's half, checked against the room's commitment (resolveMk).
|
|
128
|
+
// A HELD KEY THAT IS NOT THE SHARE'S (the owner's second device, 2026-10-22): an older worker kept a re-keyed split room's OLD
|
|
129
|
+
// key beside its new share, on disk — and the held key wins in resolveMk. For a re-keyed split room (epoch > 0) the held key
|
|
130
|
+
// must be the one the share's commitment names; if not, it is dropped and the key rebuilt from the share and the app half.
|
|
131
|
+
// Checked once per key (a hash), never for a room that was not re-keyed.
|
|
132
|
+
const heldOk = new Map() // room → the held key that was checked against the share's commitment
|
|
133
|
+
async function heldMatchesShare (room, have) {
|
|
134
|
+
const sp = splits.get(room)
|
|
135
|
+
if (!sp || !sp.commit || !((eps.get(room) || 0) > 0) || heldOk.get(room) === have) return true
|
|
136
|
+
let ok = false
|
|
137
|
+
try { ok = (await commitMk(have)) === sp.commit } catch { ok = false }
|
|
138
|
+
if (ok) { heldOk.set(room, have); return true }
|
|
139
|
+
dropOldKey(room); return false
|
|
140
|
+
}
|
|
141
|
+
const dropOldKey = (room) => { if (!mks.has(room)) return; mks.delete(room); keysReady.then(() => idb.del('mk:' + room)).catch(() => {}) }
|
|
142
|
+
const keepSplit = (room, sp, ep) => { if (backwards(room, splits.get(room) && splits.get(room).userShare, sp.userShare, ep)) return false; if ((Number(ep) || 0) > 0 && ((splits.get(room) || {}).userShare !== sp.userShare || Number(ep) > (eps.get(room) || 0))) { tellEpoch(room, Number(ep), { split: { userShare: sp.userShare, commit: sp.commit || '' } }); if (Number(ep) > (eps.get(room) || 0) || (splits.get(room) || {}).userShare !== sp.userShare) dropOldKey(room) } if (ep) noteEp(room, ep); const held = splits.get(room); if (held && held.userShare !== sp.userShare) { const alts = splitAlts.get(room) || []; if (!alts.some((a) => a.userShare === held.userShare)) splitAlts.set(room, [held, ...alts].slice(0, 4)) } splits.set(room, sp); persist('us:' + room, sp) }
|
|
143
|
+
// The mirror of keep/keepSplit, and the thing that makes "delete this Space" mean anything: without it the app cleared
|
|
144
|
+
// localStorage while the WORKER kept the key — in memory AND in idb, from which a freshly-created worker reloads it at
|
|
145
|
+
// boot (the idb.entries('mk:') restore below). So a deleted room's key came BACK on the next page load. Clears every
|
|
146
|
+
// trace: the live maps, the persisted mk, the derived notification key, and the split half.
|
|
147
|
+
const forget = (room) => {
|
|
148
|
+
mks.delete(room); splits.delete(room); eps.delete(room)
|
|
149
|
+
for (const prefix of ['mk:', 'us:', 'nk:']) parked.delete(prefix + room)
|
|
150
|
+
lastPos.delete(room); heldOk.delete(room); splitAlts.delete(room)
|
|
151
|
+
return Promise.all([idb.del('mk:' + room), idb.del('nk:' + room), idb.del('us:' + room), idb.del('ep:' + room), idb.del('cnt:' + room)]).catch(() => {})
|
|
152
|
+
}
|
|
153
|
+
async function resolveMk(room) {
|
|
154
|
+
// ⚑ WAIT for the idb key map. EVERY page load starts a FRESH worker (plus browsers evict them), and the map loads
|
|
155
|
+
// asynchronously — so a room opened before that load finishes resolves against an EMPTY map and reports "no key". The
|
|
156
|
+
// user sees "This link is missing its key" while the key sits in idb the whole time (hasMk reads false too: presence
|
|
157
|
+
// hasn't published yet). Platform-independent — desktop and Android hit it as readily as iOS. keysReady settles once,
|
|
158
|
+
// so this costs nothing after boot. THE cold-start race behind the recurring missing-key report.
|
|
159
|
+
try { await keysReady } catch { /* load failed → fall through to the stores as they stand */ }
|
|
160
|
+
const have = mks.get(room); if (have && await heldMatchesShare(room, have)) return have
|
|
161
|
+
const sp = splits.get(room); if (!sp) { noKeyWhy.set(room, 'no split share held'); return undefined }
|
|
162
|
+
let r = null
|
|
163
|
+
try {
|
|
164
|
+
// ABSOLUTE, on this worker's own origin. The vault spawns this worker from a blob: URL, and a relative URL cannot be
|
|
165
|
+
// resolved against one — WebKit: "URL is not valid or contains user credentials." So the app half was NEVER fetched
|
|
166
|
+
// from the hoisted worker: every room that reached a device as a split share through the index read no_key (the owner's
|
|
167
|
+
// fresh install, 2026-10-03). A blob worker's origin is its creator's, so this lands on the vault's /api/appshare.
|
|
168
|
+
const x = await fetch(APPSHARE_URL, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ op: 'get', room }) }) // op 'get': the builder's template (spaces/templates/appshare) needs it; Witbitz's own function reads any non-create as a get
|
|
169
|
+
if (!x.ok) { noKeyWhy.set(room, 'app half: HTTP ' + x.status); return undefined }
|
|
170
|
+
r = await x.json()
|
|
171
|
+
} catch (e) { noKeyWhy.set(room, 'app half: ' + String((e && e.message) || e).slice(0, 60)); return undefined } // offline / tenant down → no key
|
|
172
|
+
if (!r || !r.appShare) { noKeyWhy.set(room, 'app half: no share in the answer'); return undefined }
|
|
173
|
+
const cands = [sp, ...(splitAlts.get(room) || [])]
|
|
174
|
+
for (const c of cands) { // §6.4 commit-check, over every share seen for the room (held first)
|
|
175
|
+
const mk = combineShares(c.userShare, r.appShare)
|
|
176
|
+
if (mk && (!c.commit || (await commitMk(mk)) === c.commit)) { if (c !== sp) keepSplit(room, c); keep(room, mk, c === sp ? eps.get(room) : 0); noKeyWhy.delete(room); return mk } // an alternate that holds becomes the held share
|
|
177
|
+
}
|
|
178
|
+
noKeyWhy.set(room, 'commitment mismatch: ' + cands.length + ' share(s) tried against the server half' + (r.commit ? ' (server commit ' + String(r.commit).slice(0, 8) + '…)' : ''))
|
|
179
|
+
return undefined
|
|
180
|
+
}
|
|
181
|
+
// §ID-CONFINE: the per-room SIGNING IDENTITY (the priv key that authors turns) lives HERE, not on the app main thread.
|
|
182
|
+
// Seeded by the vault (rememberId) from the account backup / at create+join; the turn op signs with it so the app never
|
|
183
|
+
// holds — or passes up — the private signing key. An invite/open room's id is {name, sign:{priv,pub?}, grant, gk}; an
|
|
184
|
+
// email room's is {email, sign:{priv,pub}, googleIdToken}. Never posts back out (same discipline as mk).
|
|
185
|
+
const ids = new Map() // room → identity (priv included)
|
|
186
|
+
let encKey = null // pushed enclave snapshot
|
|
187
|
+
let encKeys = {} // { region: { key, attested } } — each room seals to ITS region's enclave (docs/multi-region.md)
|
|
188
|
+
let encAttested = null // {pcrs, policyVersion, platform:{pcrs}} — the live attestation the room blocks are checked against
|
|
189
|
+
let encTrusted // the builds THIS USER accepted (trustedBuilds.js, pushed with the snapshot); undefined = not known yet → the gate refuses
|
|
190
|
+
const encRooms = new Set()
|
|
191
|
+
const authWaiters = new Map()
|
|
192
|
+
let aseq = 0
|
|
193
|
+
const attestWaiters = new Map()
|
|
194
|
+
// a create's DELETION COMMITMENT, asked of the vault that started this worker (vault-core.js) — never of a page
|
|
195
|
+
const delWaiters = new Map()
|
|
196
|
+
let dseq = 0, delAsking = 0
|
|
197
|
+
const askDel = (room) => new Promise((resolve) => {
|
|
198
|
+
const a = ++dseq
|
|
199
|
+
delWaiters.set(a, resolve)
|
|
200
|
+
self.postMessage({ delReq: a, room })
|
|
201
|
+
setTimeout(() => { if (delWaiters.delete(a)) resolve(null) }, 5000) // no answer: the room is made without one, as before
|
|
202
|
+
})
|
|
203
|
+
let atseq = 0
|
|
204
|
+
|
|
205
|
+
// Mirror WHICH rooms we hold a key for (room ids only — never the keys) so the main thread can answer
|
|
206
|
+
// hasMk(room) synchronously without holding mk (A2b presence mirror, feeds A2c value-eviction).
|
|
207
|
+
const publishPresence = () => self.postMessage({ t: 'presence', rooms: [...new Set([...mks.keys(), ...splits.keys()])], rk: 2, tl: 1 }) // tl: this worker keeps the temp-Spaces list (ops tempHold / tempList) — a hosted frame on a newer build than its vault checks it // rk: what this worker can re-key in place — 2 = split rooms (only the user's half) + never backwards + keyEpoch to its vault; a hosted frame on a newer build checks it (the vault's worker follows Official) // §9: a split room counts as "held" (userShare present; mk reconstructed on demand)
|
|
208
|
+
|
|
209
|
+
// Load the COMPLETE, persistent map from idb at boot (rememberMk mirrors every mk under 'mk:'+room).
|
|
210
|
+
// This makes hasMk correct across sessions without the main thread ever pushing keys.
|
|
211
|
+
// ⚑ keysReady: indexWrite MUST await this. The load is async, and indexWrite DROPS any room whose key this worker doesn't
|
|
212
|
+
// hold — so an index push that lands before the map is loaded (iOS evicts workers aggressively; a fresh one starts empty)
|
|
213
|
+
// would strip EVERY room's key from the shared index doc in a single write, account-wide and unrecoverable.
|
|
214
|
+
// §NAMES: a store already kept under opaque names (the flag, or any `p:` key) is protected: the names go on, LOCKED, before the
|
|
215
|
+
// scan — the scan then finds nothing until the unlock gives the key, and no clear key is ever written meanwhile.
|
|
216
|
+
const namesReady = Promise.all([idb.getRaw('protectedNames'), idb.keysRaw('p:')]).then(([f, ks]) => { if (f || (ks && ks.length)) { setIdbNaming({ on: true }); protectedAtRest = true } }).catch(() => {})
|
|
217
|
+
const keysReady = namesReady.then(() => Promise.all([
|
|
218
|
+
idb.entries('mk:').then((es) => { let n = 0; for (const [k, v] of es) if (isSealed(v)) { parked.set(k, v); protectedAtRest = true } else if (v) { mks.set(k.slice(3), v); n++ } if (n) publishPresence() }).catch(() => {}), // a sealed entry waits for the device key (§PROTECT)
|
|
219
|
+
idb.entries('ep:').then((es) => { for (const [k, v] of es) { const n = Number(v); if (n > 0) eps.set(k.slice(3), n) } }).catch(() => {}), // key epochs (noteEp)
|
|
220
|
+
idb.entries('us:').then((es) => { let n = 0; for (const [k, v] of es) if (isSealed(v)) { parked.set(k, v); protectedAtRest = true } else if (v && v.userShare) { splits.set(k.slice(3), v); n++ } if (n) publishPresence() }).catch(() => {}), // reload the split shares too — the reclaim-window fix
|
|
221
|
+
]))
|
|
222
|
+
|
|
223
|
+
// auth shim → main thread (which holds the localStorage-backed cachedEmailAuth)
|
|
224
|
+
const AUTH_WAIT_MS = 20_000 // longer than a silent renewal (the email session's /refresh), far shorter than for ever
|
|
225
|
+
const auth = (room) => {
|
|
226
|
+
// §ID-CONFINE: when we HOLD the room's email identity ({email, sign:{priv,pub}, googleIdToken}), resolve the gated-room
|
|
227
|
+
// READ auth ({idToken, spk}) HERE — so the token never has to travel to the app (no authReq round-trip). Rooms we don't
|
|
228
|
+
// hold (flag off / not yet seeded / invite rooms) fall back to the main-thread shim, unchanged. Inert until an email
|
|
229
|
+
// identity is seeded (nothing does so yet — the email slice wires the vault seed).
|
|
230
|
+
const id = ids.get(room)
|
|
231
|
+
if (id && id.googleIdToken && id.sign && id.sign.pub) return Promise.resolve({ idToken: id.googleIdToken, spk: id.sign.pub })
|
|
232
|
+
return new Promise((resolve) => {
|
|
233
|
+
const a = ++aseq
|
|
234
|
+
authWaiters.set(a, resolve)
|
|
235
|
+
self.postMessage({ authReq: a, room })
|
|
236
|
+
// A request nobody answers (the frame it went to is gone — liveFrames.js) must not hold the read for ever: after
|
|
237
|
+
// AUTH_WAIT_MS it goes out unsigned, exactly as when the page answers "no sign-in", and the room says so.
|
|
238
|
+
setTimeout(() => { const w = authWaiters.get(a); if (w) { authWaiters.delete(a); w({}) } }, AUTH_WAIT_MS)
|
|
239
|
+
})
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
// attestation shim → main thread (which reaches the L1 vault that mints client-release attestations). A verified room's
|
|
243
|
+
// material read runs HERE (mk stays worker-side), so the worker's spaceClient asks the main thread for the attestation.
|
|
244
|
+
const attestShim = (room, o) => new Promise((resolve) => {
|
|
245
|
+
const a = ++atseq
|
|
246
|
+
attestWaiters.set(a, resolve)
|
|
247
|
+
self.postMessage({ attestReq: a, room, ...(o && typeof o === 'object' ? { o: { read: o.read === true, challenge: typeof o.challenge === 'string' ? o.challenge : undefined } } : {}) }) // o: an attested READ (docs/emulated-attested-rooms.md step 2)
|
|
248
|
+
})
|
|
249
|
+
setAttestProvider(attestShim)
|
|
250
|
+
|
|
251
|
+
// The origin's small kv database, shared with the service worker (sw-notif-core.js uses the same name/store): the
|
|
252
|
+
// push handler leaves a PREFETCHED poll answer here and reads the room's position from here. Every call is bounded —
|
|
253
|
+
// a hung database must never hold a poll.
|
|
254
|
+
const IDB_WAIT = 2500
|
|
255
|
+
const idbOpen = () => new Promise((res) => { const t = setTimeout(() => res(null), IDB_WAIT); try { const r = indexedDB.open('spaces', 1); r.onupgradeneeded = () => { try { r.result.createObjectStore('kv') } catch { /* */ } }; r.onsuccess = () => { clearTimeout(t); res(r.result) }; r.onerror = () => { clearTimeout(t); res(null) } } catch { clearTimeout(t); res(null) } })
|
|
256
|
+
const idbGet = async (k) => { try { const db = await idbOpen(); if (!db) return null; return await new Promise((res) => { const t = setTimeout(() => res(null), IDB_WAIT); const q = db.transaction('kv', 'readonly').objectStore('kv').get(k); q.onsuccess = () => { clearTimeout(t); res(q.result || null) }; q.onerror = () => { clearTimeout(t); res(null) } }) } catch { return null } }
|
|
257
|
+
const idbSet = async (k, v) => { try { const db = await idbOpen(); if (!db) return false; return await new Promise((res) => { const t = setTimeout(() => res(false), IDB_WAIT); const q = db.transaction('kv', 'readwrite').objectStore('kv').put(v, k); q.onsuccess = () => { clearTimeout(t); res(true) }; q.onerror = () => { clearTimeout(t); res(false) } }) } catch { return false } }
|
|
258
|
+
const idbDel = async (k) => { try { const db = await idbOpen(); if (!db) return false; return await new Promise((res) => { const t = setTimeout(() => res(false), IDB_WAIT); const q = db.transaction('kv', 'readwrite').objectStore('kv').delete(k); q.onsuccess = () => { clearTimeout(t); res(true) }; q.onerror = () => { clearTimeout(t); res(false) } }) } catch { return false } }
|
|
259
|
+
const lastPos = new Map() // room → the position last written to cnt:<room> (write only on change)
|
|
260
|
+
const prefetchChecked = new Set() // rooms whose prefetch slot this worker has looked at
|
|
261
|
+
const prefetchFlag = new Set() // rooms the service worker announced a fresh prefetch for
|
|
262
|
+
let prefetchLookUntil = 0 // after a 'wakeup' (the page came to the foreground) every poll looks, for a few seconds: the first poll of a resumed page is already on its way before any tap message, and the push's announcement is lost while iOS holds the page suspended
|
|
263
|
+
try { const pfc = new BroadcastChannel('wb-prefetch'); pfc.onmessage = (e) => { const r = e && e.data && e.data.room; if (typeof r === 'string') prefetchFlag.add(r) } } catch { /* no BroadcastChannel: the first-poll check still runs */ }
|
|
264
|
+
|
|
265
|
+
self.onmessage = async (e) => {
|
|
266
|
+
const m = e.data || {}
|
|
267
|
+
switch (m.t) {
|
|
268
|
+
case 'delRes': {
|
|
269
|
+
const w = delWaiters.get(m.a)
|
|
270
|
+
if (w) { delWaiters.delete(m.a); w(typeof m.v === 'string' ? m.v : null) }
|
|
271
|
+
return
|
|
272
|
+
}
|
|
273
|
+
case 'authRes': {
|
|
274
|
+
const w = authWaiters.get(m.a)
|
|
275
|
+
if (w) { authWaiters.delete(m.a); w(m.v || {}) }
|
|
276
|
+
return
|
|
277
|
+
}
|
|
278
|
+
case 'attestRes': {
|
|
279
|
+
const w = attestWaiters.get(m.a)
|
|
280
|
+
if (w) { attestWaiters.delete(m.a); w(m.v || null) }
|
|
281
|
+
return
|
|
282
|
+
}
|
|
283
|
+
case 'enclave': { // main pushes {key, attested, acceptance, rooms} at open + on wake/re-attest
|
|
284
|
+
encKey = m.key || null
|
|
285
|
+
encAttested = m.attested || null
|
|
286
|
+
encKeys = (m.keys && typeof m.keys === 'object') ? m.keys : {}
|
|
287
|
+
const snap = (m.acceptance && typeof m.acceptance === 'object') ? m.acceptance : {}
|
|
288
|
+
encTrusted = Array.isArray(snap.trusted) ? snap.trusted : undefined
|
|
289
|
+
encRooms.clear()
|
|
290
|
+
for (const r of (m.rooms || [])) encRooms.add(r)
|
|
291
|
+
if (m.id != null) self.postMessage({ id: m.id, result: true })
|
|
292
|
+
return
|
|
293
|
+
}
|
|
294
|
+
// ── §PROTECT (docs/device-storage-protection.md): the device key arrives as 32 raw bytes, is imported non-extractable, and lives only here.
|
|
295
|
+
case 'seal': { // {id, key} → switch ON: hold the key, rewrite every persisted key sealed
|
|
296
|
+
try {
|
|
297
|
+
sealKey = await importSealKey(m.key); protectedAtRest = true; nkClear = !!m.previews
|
|
298
|
+
await keysReady
|
|
299
|
+
// Sealed entries parked at boot while protection was OFF are an earlier setup's leftovers: no lock names their key,
|
|
300
|
+
// so nothing can open them — and the next unlock would throw on the first one and stay locked. They go.
|
|
301
|
+
for (const k of parked.keys()) { try { await idb.delRaw(k) } catch { /* */ } }
|
|
302
|
+
parked.clear()
|
|
303
|
+
// …and a leftover sealed nk: — the boot scan parks only mk:/us:, so it stayed, and an unlock with no other sealed key
|
|
304
|
+
// re-reads the store and throws on it (the vault drops all three, vault-loader dropStaleKeys; sync sweep backlog P6)
|
|
305
|
+
for (const [k, v] of await idb.entries('nk:')) if (isSealed(v)) { try { await idb.delRaw(k) } catch { /* */ } }
|
|
306
|
+
await armIdbNaming(m.key)
|
|
307
|
+
let n = 0
|
|
308
|
+
for (const [room, mk] of mks) { await persist('mk:' + room, mk); n++; try { await persistNk(room, await deriveNotifKey(mk)) } catch { /* no nk → no sealed nk */ } }
|
|
309
|
+
for (const [room, sp] of splits) { await persist('us:' + room, sp); n++ }
|
|
310
|
+
self.postMessage({ id: m.id, result: { sealed: n } })
|
|
311
|
+
} catch (err) { sealKey = null; self.postMessage({ id: m.id, error: 'seal: ' + String((err && err.message) || err) }) }
|
|
312
|
+
return
|
|
313
|
+
}
|
|
314
|
+
case 'unseal': { // {id, key} → unlock: open every parked (or persisted) sealed entry into the maps
|
|
315
|
+
try {
|
|
316
|
+
const t0 = performance.now(), ms = {} // where the unlock's time goes (spaceAtRest.js prints it): the owner's iPhone, 96 ms here
|
|
317
|
+
const key = await importSealKey(m.key); nkClear = !!m.previews
|
|
318
|
+
await keysReady; ms.ready = performance.now() - t0; await armIdbNaming(m.key); ms.names = performance.now() - t0
|
|
319
|
+
if ((await idb.keysRaw('p:')).length && !(await idb.nameIndex()).length) { setIdbNaming({ on: true }); throw new Error('this key opens nothing here') } // §NAMES: a wrong key reads no name — refuse, and stay locked (never write under its names)
|
|
320
|
+
ms.check = performance.now() - t0
|
|
321
|
+
if (!parked.size) for (const pfx of ['mk:', 'us:', 'nk:']) for (const [k, v] of await idb.entries(pfx)) if (isSealed(v)) parked.set(k, v) // after a relock the maps are empty: re-read the sealed store
|
|
322
|
+
ms.read = performance.now() - t0; ms.n = parked.size
|
|
323
|
+
let n = 0
|
|
324
|
+
// ALL AT ONCE, then into the maps (2026-11-17: one by one, WebKit's WebCrypto costs a thread hop per key — ~450 rooms on the
|
|
325
|
+
// owner's iPhone): a wrong key THROWS → nothing opened, the page shows the lock again
|
|
326
|
+
const all = [...parked], vals = await Promise.all(all.map(([, blob]) => openSealed(key, blob)))
|
|
327
|
+
all.forEach(([k], i) => {
|
|
328
|
+
const v = vals[i]
|
|
329
|
+
if (k.startsWith('mk:')) { mks.set(k.slice(3), v); n++ } else if (k.startsWith('us:')) { if (v && v.userShare) { splits.set(k.slice(3), v); n++ } } // nk: is derived from mk at keep(); nothing to hold in memory
|
|
330
|
+
})
|
|
331
|
+
parked.clear(); sealKey = key; protectedAtRest = true
|
|
332
|
+
for (const [room, mk] of mks) { persist('mk:' + room, mk); deriveNotifKey(mk).then((nk) => persistNk(room, nk)).catch(() => {}) } // keys that reached the locked worker (the page re-sent them at open) are persisted sealed now
|
|
333
|
+
for (const [room, sp] of splits) persist('us:' + room, sp)
|
|
334
|
+
ms.open = performance.now() - t0
|
|
335
|
+
if (n) publishPresence()
|
|
336
|
+
self.postMessage({ id: m.id, result: { opened: n, ms } })
|
|
337
|
+
} catch (err) { self.postMessage({ id: m.id, error: 'unseal: ' + String((err && err.message) || err) }) }
|
|
338
|
+
return
|
|
339
|
+
}
|
|
340
|
+
case 'previews': { // {id, on} → §PREVIEWS toggled while unlocked: rewrite every nk: clear (on) or sealed (off)
|
|
341
|
+
nkClear = !!m.on
|
|
342
|
+
try { if (sealKey) for (const [room, mk] of mks) { try { await persistNk(room, await deriveNotifKey(mk)) } catch { /* */ } } } catch { /* */ }
|
|
343
|
+
if (m.id != null) self.postMessage({ id: m.id, result: { previews: nkClear } })
|
|
344
|
+
return
|
|
345
|
+
}
|
|
346
|
+
case 'memoryOnly': { // {id} → a room link on an unsecured computer: keys stay in memory, persist() writes nothing
|
|
347
|
+
protectedAtRest = true; sealKey = null; setIdbNaming({ on: true }) // names on, no key: every write is dropped
|
|
348
|
+
if (m.id != null) self.postMessage({ id: m.id, result: true })
|
|
349
|
+
return
|
|
350
|
+
}
|
|
351
|
+
case 'relock': { // {id} → the lock engaged: nothing usable stays in memory
|
|
352
|
+
if (sealKey) { mks.clear(); splits.clear(); parked.clear(); sealKey = null; setIdbNaming({ on: true }); publishPresence() } // unprotected devices keep their maps — a relock means nothing to them
|
|
353
|
+
if (m.id != null) self.postMessage({ id: m.id, result: true })
|
|
354
|
+
return
|
|
355
|
+
}
|
|
356
|
+
case 'unprotect': { // {id, key} → switch OFF: open everything and write it back in the clear
|
|
357
|
+
try {
|
|
358
|
+
const key = await importSealKey(m.key)
|
|
359
|
+
await keysReady; await armIdbNaming(m.key)
|
|
360
|
+
// §NAMES: take every key from under its opaque name (or its real name, if the page moved it back first), then names off
|
|
361
|
+
const held = []
|
|
362
|
+
for (const pfx of ['mk:', 'us:']) for (const [k, v] of await idb.entries(pfx)) { held.push([k, v]); await idb.del(k) }
|
|
363
|
+
setIdbNaming({ on: false })
|
|
364
|
+
for (const [k, v] of await idb.entries('nk:')) if (isSealed(v)) held.push([k, v])
|
|
365
|
+
for (const [k, v] of held) { const clear = isSealed(v) ? await openSealed(key, v) : v; await idb.set(k, clear); if (k.startsWith('mk:')) mks.set(k.slice(3), clear); else if (k.startsWith('us:') && clear && clear.userShare) splits.set(k.slice(3), clear) }
|
|
366
|
+
parked.clear(); sealKey = null; protectedAtRest = false; nkClear = false; publishPresence()
|
|
367
|
+
for (const [room, mk] of mks) deriveNotifKey(mk).then((nk) => persistNk(room, nk)).catch(() => {}) // the preview keys a protected device did not keep
|
|
368
|
+
self.postMessage({ id: m.id, result: true })
|
|
369
|
+
} catch (err) { self.postMessage({ id: m.id, error: 'unprotect: ' + String((err && err.message) || err) }) }
|
|
370
|
+
return
|
|
371
|
+
}
|
|
372
|
+
case 'presenceQuery': { // say which keys are held now, once the stored ones are in (a late frame asks: the tenant launch, 2026-10-16)
|
|
373
|
+
await keysReady; publishPresence()
|
|
374
|
+
if (m.id != null) self.postMessage({ id: m.id, result: true })
|
|
375
|
+
return
|
|
376
|
+
}
|
|
377
|
+
case 'wipeKeys': { // root-vault only: parked/opaque keys count even when no room list can name them
|
|
378
|
+
storageWiped = true; storageEpoch++
|
|
379
|
+
await keysReady
|
|
380
|
+
mks.clear(); splits.clear(); parked.clear(); splitAlts.clear(); eps.clear(); heldOk.clear(); lastPos.clear()
|
|
381
|
+
for (const k of await idb.keysRaw('')) await idb.delRaw(k)
|
|
382
|
+
publishPresence()
|
|
383
|
+
self.postMessage({ id: m.id, result: true })
|
|
384
|
+
return
|
|
385
|
+
}
|
|
386
|
+
case 'volatile': { // {rooms} → these rooms' keys are memory-only from now on: drop what is stored, write nothing
|
|
387
|
+
for (const r of (Array.isArray(m.rooms) ? m.rooms : [])) if (typeof r === 'string' && r && !volatile.has(r)) { volatile.add(r); keysReady.then(() => Promise.all([idb.del('mk:' + r), idb.del('us:' + r)])).catch(() => {}) } // its preview key stays (attNk): the room key never did
|
|
388
|
+
if (m.id != null) self.postMessage({ id: m.id, result: true })
|
|
389
|
+
return
|
|
390
|
+
}
|
|
391
|
+
case 'remember': { // {room, mk} → store a key in the map (the worker becomes the mk store)
|
|
392
|
+
// AFTER the boot scan: the stored key and its epoch are loaded first, so a launch's re-seed (no epoch) is judged against
|
|
393
|
+
// them — before, the scan put the new key back in memory and the re-seed's queued write put the old one on disk
|
|
394
|
+
keysReady.then(() => { if (m.room && m.mk) { keep(m.room, m.mk, m.ep); publishPresence() } if (m.id != null) self.postMessage({ id: m.id, result: true }) }) // m.ep: a re-keyed room's epoch (space.js adoptRoomKey)
|
|
395
|
+
return
|
|
396
|
+
}
|
|
397
|
+
case 'create': { // {id, cfg, base} → mint a Space HERE (vault-core.js, docs/sdk-vault-mode.md): its key is born in
|
|
398
|
+
// this worker and kept here; the reply carries the room and its share link (the vault keeps the link — it is the
|
|
399
|
+
// key — and hands its page only the room id). The client must be open (endpoint/app) first.
|
|
400
|
+
try {
|
|
401
|
+
if (!client) throw new Error('l1-worker: create before open')
|
|
402
|
+
// a SPLIT room is made through the builder's app-half function on this worker's own origin (the same one resolveMk asks)
|
|
403
|
+
const via = m.split ? async (body) => { const x = await fetch(APPSHARE_URL, { method: 'POST', credentials: 'same-origin', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) }); const j = await x.json().catch(() => ({})); return { ...(j && typeof j === 'object' ? j : {}), status: x.status } } : null
|
|
404
|
+
if (m.delAsk) delAsking++
|
|
405
|
+
let r
|
|
406
|
+
try { r = await client.create(m.cfg || {}, { base: m.base || undefined, ...(m.enclave ? { enclave: true } : {}), ...(via ? { split: true, via } : {}) }) } finally { if (m.delAsk) delAsking-- }
|
|
407
|
+
if (!r || !r.room || !r.mk) throw new Error('create: ' + String((r && (r.error || r.status)) || 'no room'))
|
|
408
|
+
if (m.split) { if (!r.userShare) throw new Error('create: the app-half function gave no share'); keepSplit(r.room, { userShare: r.userShare, commit: r.commit || '' }) }
|
|
409
|
+
keep(r.room, r.mk); publishPresence()
|
|
410
|
+
const link0 = (r.links && r.links[0]) || null
|
|
411
|
+
// a split room's link is the user's HALF (#us=…&spc=…), never the key; a confidential room's sealed config (ciphertext) rides back for the enclave's own copy
|
|
412
|
+
const link = m.split && link0 ? String(link0).split('#')[0] + '#us=' + encodeURIComponent(r.userShare) + (r.commit ? '&spc=' + encodeURIComponent(r.commit) : '') : link0
|
|
413
|
+
self.postMessage({ id: m.id, result: { room: r.room, link, ...(r.enclaveCreated === true ? { enclaveCreated: true } : {}), commit: r.commit || null, ...(r.configSealed ? { configSealed: r.configSealed } : {}), ...(m.returnMk ? { mk: r.mk } : {}) } }) // returnMk: the vault's own move needs the new key for its notice
|
|
414
|
+
} catch (err) { self.postMessage({ id: m.id, error: String((err && err.message) || err) }) }
|
|
415
|
+
return
|
|
416
|
+
}
|
|
417
|
+
case 'forget': { // {room} → DROP the key. AWAITS the idb deletes before replying: the caller holds
|
|
418
|
+
// navigation until it resolves, and a dedicated worker dies with its page — a fire-and-forget delete could be
|
|
419
|
+
// cut off mid-write, leaving the key in idb for the next worker to reload.
|
|
420
|
+
await keysReady
|
|
421
|
+
if (m.room) { await forget(m.room); publishPresence() }
|
|
422
|
+
if (m.id != null) self.postMessage({ id: m.id, result: true })
|
|
423
|
+
return
|
|
424
|
+
}
|
|
425
|
+
case 'setPushAcct': { // {room} = the account's INDEX room → derive the account push secret from ITS key, here,
|
|
426
|
+
// where the key lives (the page holds only the room id). Turns and subscriptions then carry the account tag, so the
|
|
427
|
+
// server skips the poster's OTHER devices too (spaceClient pushAcctField).
|
|
428
|
+
// {secret}: the secret itself (a one-way derivation, never a key), from a page that holds the index key on its own thread —
|
|
429
|
+
// the builders' vault (vault-core.js; sync sweep 11-16 #14). '' clears it (signed out).
|
|
430
|
+
try {
|
|
431
|
+
if (typeof m.secret === 'string') { if (m.secret === '' || /^[A-Za-z0-9_-]{43}$/.test(m.secret)) setPushAcct(m.secret) }
|
|
432
|
+
else { const mk = m.room ? (mks.get(m.room) || await resolveMk(m.room)) : ''; setPushAcct(await pushAcctSecretOf(mk || '')) }
|
|
433
|
+
} catch { /* */ }
|
|
434
|
+
if (m.id != null) self.postMessage({ id: m.id, result: true })
|
|
435
|
+
return
|
|
436
|
+
}
|
|
437
|
+
case 'prefetchIdentity': { // {token} → this worker's client fetches the sign-in's hints now (option B; sweep 11-06 #9)
|
|
438
|
+
try { if (client && typeof client.prefetchIdentity === 'function') await client.prefetchIdentity(String(m.token || '')) } catch { /* */ }
|
|
439
|
+
if (m.id != null) self.postMessage({ id: m.id, result: true })
|
|
440
|
+
return
|
|
441
|
+
}
|
|
442
|
+
case 'setPushSelf': { // {endpoint} → set THIS worker's spaceClient pushSelf. Turns are composed + POSTed
|
|
443
|
+
// HERE (the worker's own spaceClient instance), so the main-thread setPushSelf never reached the POST — the turn
|
|
444
|
+
// went out with no endpoint and the server fell back to the coarse author-NAME rule, skipping every device sharing
|
|
445
|
+
// the sender's name. With the endpoint, the server skips only THIS device (mode=endpoint) and tickles the others.
|
|
446
|
+
try { setPushSelf(m.endpoint || '') } catch { /* */ }
|
|
447
|
+
// A stream opened before the endpoint arrived carries no viewing tag: reopen it with one (the server then skips this
|
|
448
|
+
// device's tickle for the room on screen). Same room, same key; only the socket's name changes.
|
|
449
|
+
for (const [room, h] of streams) {
|
|
450
|
+
try { const tag = await viewingTag(room); if (tag && tag !== h.tag && h.mk) { h.s.stop(); h.s = openStreamHere(room, h.mk, h.grants || null, tag); h.tag = tag } } catch { /* the old socket stays */ }
|
|
451
|
+
}
|
|
452
|
+
if (m.id != null) self.postMessage({ id: m.id, result: true })
|
|
453
|
+
return
|
|
454
|
+
}
|
|
455
|
+
case 'serveKeyPort': { // {room} + a transferred MessagePort → send this room's mk DOWN the port so a SIBLING
|
|
456
|
+
// realm's worker (a same-origin docked lane panel) can adopt it WITHOUT the key ever crossing either main thread.
|
|
457
|
+
// Fire-and-forget: no RPC reply — the port carries the answer ({mk:null} if we don't hold it → the caller falls back).
|
|
458
|
+
const sp = e.ports && e.ports[0]
|
|
459
|
+
if (sp && m.room) { try { const mk = mks.get(m.room) || await resolveMk(m.room); sp.postMessage({ room: m.room, mk: mk || null }) } catch { try { sp.postMessage({ room: m.room, mk: null }) } catch { /* */ } } }
|
|
460
|
+
return
|
|
461
|
+
}
|
|
462
|
+
case 'adoptKeyPort': { // {id, room} + a transferred MessagePort → RECEIVE this room's mk over the port (sent by a
|
|
463
|
+
// sibling realm's worker) and store it in the key map. The main thread only relayed an opaque port; the key never
|
|
464
|
+
// touches L2. Reply {ok} on the RPC channel once stored (false on a null answer / timeout) so the caller can fall back.
|
|
465
|
+
const { id: aid, room: aroom } = m; const ap = e.ports && e.ports[0]
|
|
466
|
+
if (!ap || !aroom) { if (aid != null) self.postMessage({ id: aid, result: { ok: false } }); return }
|
|
467
|
+
let settled = false
|
|
468
|
+
const settle = (ok) => { if (settled) return; settled = true; try { ap.close() } catch { /* */ } if (aid != null) self.postMessage({ id: aid, result: { ok } }) }
|
|
469
|
+
ap.onmessage = (ev) => { const d = (ev && ev.data) || {}; if (d.mk && d.room === aroom) { keep(aroom, d.mk); publishPresence(); settle(true) } else settle(false) }
|
|
470
|
+
setTimeout(() => settle(false), m.timeoutMs > 0 ? m.timeoutMs : 8000) // the SERVING side may need a live appshare fetch to reconstruct a split mk (resolveMk) — 1.5s lost that race on cellular and read as 'parent:no'
|
|
471
|
+
return
|
|
472
|
+
}
|
|
473
|
+
case 'wakeup': { prefetchLookUntil = Date.now() + 8000; return } // the page came to the foreground (vault-loader.js / space.js onVisibility): look for a push-time prefetch on the polls that follow
|
|
474
|
+
case 'ping': { self.postMessage({ t: 'pong', n: m.n | 0 }); return } // liveness heartbeat — the vault detects a RECLAIMED worker (iOS memory pressure) and recreates it; without this a dead handle ate every message silently and rooms stopped opening
|
|
475
|
+
case 'rememberSplit': { // {room, userShare, commit} → hold the user's HALF here (the confined split store); mk reconstructs on demand via resolveMk. The main thread never keeps the userShare in a live variable.
|
|
476
|
+
keysReady.then(() => { if (m.room && m.userShare) { keepSplit(m.room, { userShare: m.userShare, commit: m.commit || '' }, m.ep); publishPresence() } if (m.id != null) self.postMessage({ id: m.id, result: true }) }) // after the boot scan, as `remember`
|
|
477
|
+
return
|
|
478
|
+
}
|
|
479
|
+
case 'rememberId': { // {room, identity} → hold the room's SIGNING IDENTITY here (the confined identity store). The turn op signs with it; the private signing key never crosses back to the app. Seeded by the vault at create/join and from the account backup. NB the identity travels as `identity` (not `id` — `id` is the RPC sequence field).
|
|
480
|
+
if (m.room && m.identity && m.identity.sign && m.identity.sign.priv) ids.set(m.room, m.identity)
|
|
481
|
+
if (m.id != null) self.postMessage({ id: m.id, result: true })
|
|
482
|
+
return
|
|
483
|
+
}
|
|
484
|
+
case 'ensureMk': { // {id, room} → reconstruct the room's mk HERE (fetch appShare ⊕ combine, commit-checked) + cache it; return only a BOOLEAN availability. mk never crosses back to the main thread — this is the split-room OPEN check without de-confining the key.
|
|
485
|
+
const { id, room } = m
|
|
486
|
+
try { const mk = await resolveMk(room); self.postMessage({ id, result: { ok: !!mk } }) }
|
|
487
|
+
catch (err) { self.postMessage({ id, error: 'ensureMk: ' + String((err && err.message) || err) }) }
|
|
488
|
+
return
|
|
489
|
+
}
|
|
490
|
+
case 'inviteLink': { // {id, room, base, suffix} → the invite link, with the split key fragment (#us=…&spc=…) INJECTED here from the confined store. Main thread supplies only the non-secret base/suffix; it never sees the userShare. null if we hold no split for the room.
|
|
491
|
+
const { id, room, base, suffix } = m
|
|
492
|
+
try {
|
|
493
|
+
const sp = splits.get(room)
|
|
494
|
+
const link = (sp && sp.userShare)
|
|
495
|
+
? (base + '#us=' + encodeURIComponent(sp.userShare) + (sp.commit ? '&spc=' + encodeURIComponent(sp.commit) : '') + (suffix || ''))
|
|
496
|
+
: null
|
|
497
|
+
self.postMessage({ id, result: { link } })
|
|
498
|
+
} catch (err) { self.postMessage({ id, error: 'inviteLink: ' + String((err && err.message) || err) }) }
|
|
499
|
+
return
|
|
500
|
+
}
|
|
501
|
+
case 'open': { // capture the room's mk here; (re)create the client bound to this realm
|
|
502
|
+
try {
|
|
503
|
+
if (m.room && m.mk) keep(m.room, m.mk)
|
|
504
|
+
// ONE CLIENT PER REALM (sync sweep 2026-11-07 #6): a room open in the SAME realm (endpoint · app · tenant) keeps the client
|
|
505
|
+
// it has — what it learned (option B's prefetched `idextras` hints, gated/verified rooms, older key chains) is the
|
|
506
|
+
// sign-in's and the rooms', not this open's. A new client on every open threw the hints away, so the first sealed request
|
|
507
|
+
// after each open fetched them inline — the timing option B rules out. Every other option reads this worker's state live.
|
|
508
|
+
const realm = JSON.stringify([m.endpoint || '/space', m.app || '', m.tenant || ''])
|
|
509
|
+
if (client && clientRealm === realm) { publishPresence(); self.postMessage({ id: m.id, result: true }); return }
|
|
510
|
+
clientRealm = '' // set again only once the new client is made
|
|
511
|
+
client = makeSpaceClient({
|
|
512
|
+
endpoint: m.endpoint || '/space',
|
|
513
|
+
app: m.app,
|
|
514
|
+
...(m.tenant ? { tenant: m.tenant } : {}), // a builder's vault (vault-core.js): the Spaces it creates are its tenant's
|
|
515
|
+
auth,
|
|
516
|
+
mkPub: (r) => (encRooms.has(r) ? (() => { const e = encKeys[roomRegion(r)] || (roomRegion(r) === DEFAULT_REGION ? { key: encKey, attested: encAttested } : {}); return gatedKey({ key: e.key || null, trusted: encTrusted, attested: e.attested || null, platform: e.attested && e.attested.platform, room: r }) })() : null), // r's OWN region's key; another region's is never borrowed // trusted undefined until the account's list is known → the gate refuses
|
|
517
|
+
enclave: (r) => encRooms.has(r),
|
|
518
|
+
envelope: (r) => { if (!encRooms.has(r)) return false; const e = encKeys[roomRegion(r)] || (roomRegion(r) === DEFAULT_REGION ? { attested: encAttested } : {}); return opensEnvelopes(e.attested) }, // the sealed request envelope (reqEnvelope.js): this room's live enclave opens it
|
|
519
|
+
identity: (r) => { if (!encRooms.has(r)) return false; const e = encKeys[roomRegion(r)] || (roomRegion(r) === DEFAULT_REGION ? { attested: encAttested } : {}); return sealsIdentity(e.attested) }, // option B: it takes the sign-in from inside
|
|
520
|
+
// A Spaces ACCOUNT's turn token (accountBilling.js) — asked of the page through the auth channel under a reserved
|
|
521
|
+
// name, only when an op can spend. No answer / no session ⇒ '' ⇒ the turn bills as before.
|
|
522
|
+
userToken: async () => { const v = await auth('#account-billing'); return (v && typeof v.userToken === 'string') ? v.userToken : '' },
|
|
523
|
+
// A builder's VAULT (vault-core.js) with an account backup: a create carries the deletion commitment, which only the
|
|
524
|
+
// vault can make (it holds the erase key — sdkErase.js). Asked only while a create that said `delAsk` runs.
|
|
525
|
+
delCommit: (r) => (delAsking > 0 ? askDel(r) : Promise.resolve(null)), // a promise either way: spaceClient .catch()es it
|
|
526
|
+
// THE ROOM PASS (docs/device-gate-design.md): the page holds it (roomPassWiring.js) — asked under the reserved name
|
|
527
|
+
// '#room-pass' with this request's op, room and sign-in (its email and key, never the token); {} = none (off)
|
|
528
|
+
roomPass: {
|
|
529
|
+
fieldsFor: async (body, o) => { const si = signInOf(body); if (!si) return {}; const v = await auth('#room-pass:' + JSON.stringify({ op: body.op, room: body.room, email: si.email, spk: si.spk, ...(o && Number.isFinite(o.ts) ? { ts: o.ts } : {}) })); return v && v.pass && v.psig ? { pass: v.pass, psig: v.psig } : {} }, // ts: this realm's sealNow — the server's clock as learned here
|
|
530
|
+
renew: async (body) => { const si = signInOf(body); if (si) return auth('#room-pass:' + JSON.stringify({ renew: true, email: si.email })) },
|
|
531
|
+
},
|
|
532
|
+
// A SIGN-IN THAT NAMES NO APP (docs/device-gate-design.md § 12.1, `pass: app_unnamed`): renewed by whoever holds it — the
|
|
533
|
+
// page, or the vault for an identity it seeded here — and, when it is one held here, kept here renewed too
|
|
534
|
+
renewSignIn: async (body) => {
|
|
535
|
+
const room = body && body.room
|
|
536
|
+
if (!room || !signInOf(body)) return null
|
|
537
|
+
const v = await auth(SIGNIN_RENEW_AUTH + ':' + room)
|
|
538
|
+
if (v?.retryable) return { retryable: true }
|
|
539
|
+
if (!v || typeof v.idToken !== 'string' || !v.spk) return null
|
|
540
|
+
const id = ids.get(room)
|
|
541
|
+
if (id && id.sign && JSON.stringify(id.sign.pub) === JSON.stringify(v.spk)) ids.set(room, { ...id, googleIdToken: v.idToken })
|
|
542
|
+
return { idToken: v.idToken, spk: v.spk }
|
|
543
|
+
},
|
|
544
|
+
})
|
|
545
|
+
clientRealm = realm
|
|
546
|
+
publishPresence()
|
|
547
|
+
self.postMessage({ id: m.id, result: true })
|
|
548
|
+
} catch (err) {
|
|
549
|
+
self.postMessage({ id: m.id, error: 'open: ' + String((err && err.message) || err) })
|
|
550
|
+
}
|
|
551
|
+
return
|
|
552
|
+
}
|
|
553
|
+
case 'acctSeal': // {obj} → a doc sealed under the ACCOUNT key (the server never holds it) · null without the key
|
|
554
|
+
case 'acctOpen': { // {doc} → its object · null when it will not open here
|
|
555
|
+
;(async () => {
|
|
556
|
+
try {
|
|
557
|
+
if (!acctKey) return self.postMessage({ id: m.id, result: null })
|
|
558
|
+
const result = m.t === 'acctSeal' ? await sealDoc(acctKey, m.obj) : (isSealedDoc(m.doc) ? await openDoc(acctKey, m.doc) : null)
|
|
559
|
+
self.postMessage({ id: m.id, result })
|
|
560
|
+
} catch { self.postMessage({ id: m.id, result: null }) }
|
|
561
|
+
})()
|
|
562
|
+
return
|
|
563
|
+
}
|
|
564
|
+
case 'acctKey': { // the account-store key (accountSeal.appStoreKey) — from the page's backup master, or the hosting vault's
|
|
565
|
+
acctKey = m.key || null
|
|
566
|
+
oldAcctKeys = Array.isArray(m.old) ? m.old.filter(Boolean) : []
|
|
567
|
+
if (m.id != null) self.postMessage({ id: m.id, result: { ok: !!acctKey } })
|
|
568
|
+
return
|
|
569
|
+
}
|
|
570
|
+
case 'indexRead': { // Atlas: read an index doc, ABSORB room→mk pointers into the key store, return KEYLESS
|
|
571
|
+
const { id, indexRoom, indexMk, name } = m
|
|
572
|
+
// ⛔ keyless: the caller does not own this worker — the hosted app frame, through its vault (§HOIST; the vault
|
|
573
|
+
// sets it on every relayed read of a frame that says so). It gets NO key back: no mkeys mirror, only which rooms are split
|
|
574
|
+
// (`splits`: room → its commit, which is not secret — roomState isSplitRoom reads it) (the owner, 2026-11-13; docs/sdk-convergence.md)
|
|
575
|
+
const keylessAsk = !!m.keyless
|
|
576
|
+
try {
|
|
577
|
+
if (!client) throw new Error('l1-worker: indexRead before open')
|
|
578
|
+
await keysReady // so hasMk/presence reflect the FULL map right after an absorb (a half-loaded map reads as "no key")
|
|
579
|
+
if (indexMk && !mks.get(indexRoom)) { keep(indexRoom, indexMk); publishPresence() } // the app passes the index ROOM's key so we can open the doc even when it was adopted from a backup
|
|
580
|
+
const r = await acct.get(indexRoom, mks.get(indexRoom) || indexMk, name, { plainOpen: unzipDoc }) // SEALED on the device (accountStores.js); the plain doc read through until it moves
|
|
581
|
+
if (!(r && r.status === 200 && r.state)) { self.postMessage({ id, result: { status: (r && r.status) || 0, state: null } }); return }
|
|
582
|
+
let st = r.state
|
|
583
|
+
const mirror = {} // → the main thread's localStorage cache (see below); `rooms` itself stays KEYLESS as before
|
|
584
|
+
const splitRooms = {} // room → commit: which listed rooms are split, with no share (what a keyless caller is told)
|
|
585
|
+
if (st && typeof st === 'object' && st.rooms && typeof st.rooms === 'object') {
|
|
586
|
+
const keyless = {}; let replaced = 0 // held split shares the doc's copy differs from (see keepSplit / splitAlts)
|
|
587
|
+
for (const rm of Object.keys(st.rooms)) { const e = st.rooms[rm] || {}; if (e.deleted) { const { mk: _dmk, ep: _dep, split: _ds, userShare: _du, commit: _dc, ...rest } = e; keyless[rm] = rest; continue } /* a DELETED Space's key is never taken back (2026-11-12: it returned on every sync and the delete ran again) */ if (e.split && e.userShare) { const held = splits.get(rm); if (keepSplit(rm, { userShare: e.userShare, commit: e.commit || '' }, e.ep) !== false) { if (held && held.userShare !== e.userShare) replaced++; mirror[rm] = { split: true, userShare: e.userShare, commit: e.commit || '' } } splitRooms[rm] = String(((splits.get(rm) || {}).commit) || e.commit || ''); const { split: _s, userShare: _u, commit: _c, ep: _sep, ...rest } = e; keyless[rm] = rest } else { if (e.mk && (mks.get(rm) === e.mk || (Number(e.ep) || 0) >= (eps.get(rm) || 0))) { keep(rm, e.mk, e.ep); mirror[rm] = { mk: e.mk } } const { mk, ep: _ep, ...rest } = e; keyless[rm] = rest } } // ABSORB — never a key OLDER than the one held (noteEp) → strip the key (mk, or a split room's userShare+commit)
|
|
588
|
+
publishPresence()
|
|
589
|
+
{ const all = Object.keys(st.rooms); const bare = all.filter((rm) => { const e = st.rooms[rm] || {}; return !e.deleted && !(e.split && e.userShare) && !e.mk && !mks.has(rm) && !splits.has(rm) }); self.postMessage({ t: 'note', line: 'index read: ' + all.length + ' rooms · ' + (all.length - bare.length) + ' with a key here · ' + (bare.length ? 'NO KEY for ' + bare.map((rm) => rm.slice(0, 10)).join(' ') : 'none keyless') + (replaced ? ' · ' + replaced + ' held share(s) differ from the index copy' : '') }) } // the trail says which listed rooms this device cannot open — a fresh device's rooms read 401/422 for a day and nothing said why (2026-10-03)
|
|
590
|
+
st = { ...st, rooms: keyless }
|
|
591
|
+
}
|
|
592
|
+
// ⚑ MIRROR the absorbed keys back to the main thread so it can cache them in localStorage, exactly as a room you
|
|
593
|
+
// CREATE or JOIN here already does (space.js rememberMk writes both stores). Without this, an index-synced room's
|
|
594
|
+
// key lived ONLY in the worker: the open path's synchronous first check missed it and every open had to round-trip
|
|
595
|
+
// the worker (~600ms) while every other room opened instantly — the same key, two storage paths, two speeds.
|
|
596
|
+
// This is a deliberate step AWAY from mk-confinement, chosen knowingly: the device already holds every
|
|
597
|
+
// create/join key in localStorage, so confining only index-synced keys bought no real protection while costing
|
|
598
|
+
// consistency. Real confinement means moving ALL keys into the worker (l1 `evictmk` / confineExistingLaneKeys),
|
|
599
|
+
// not leaving one arrival path out.
|
|
600
|
+
// ⛔ …but NEVER to a keyless caller (above): in the hosted app this answer crossed into the app frame and carried every
|
|
601
|
+
// room key and split share of the account on every index sync. It gets `splits` alone.
|
|
602
|
+
self.postMessage({ id, result: { status: 200, state: st, splits: splitRooms, ...(keylessAsk ? {} : { mkeys: mirror }), ...(Number.isInteger(r.v) ? { v: r.v } : {}) } }) // v: the version a write names (accountStores put ifV)
|
|
603
|
+
} catch (err) { self.postMessage({ id, error: 'indexRead: ' + String((err && err.message) || err) }) }
|
|
604
|
+
return
|
|
605
|
+
}
|
|
606
|
+
case 'indexWrite': { // Atlas: build the index doc INJECTING each room's mk from the key store; gzip if large
|
|
607
|
+
const { id, indexRoom, indexMk, name, patch, summary, by, ifV } = m
|
|
608
|
+
try {
|
|
609
|
+
if (!client) throw new Error('l1-worker: indexWrite before open')
|
|
610
|
+
await keysReady // NEVER write the index from a half-loaded key map — an empty `mks` would strip every room's key (below)
|
|
611
|
+
if (indexMk && !mks.get(indexRoom)) { keep(indexRoom, indexMk); publishPresence() } // index ROOM key passed by the app (adopted-from-backup case)
|
|
612
|
+
let p = { ...(patch || {}) }
|
|
613
|
+
if (p.rooms && typeof p.rooms === 'object') {
|
|
614
|
+
// PRESERVE keys we don't hold. The patch arrives KEYLESS (indexRead strips keys before handing it up), so a room
|
|
615
|
+
// whose key is missing from THIS worker used to be dropped outright — silently deleting that key from the shared
|
|
616
|
+
// doc for every device, with no way back. Read the CURRENT doc first and carry its key material over verbatim
|
|
617
|
+
// (and absorb it, self-healing this worker). Only a room whose key exists NOWHERE is dropped, as before.
|
|
618
|
+
let cur = {}
|
|
619
|
+
try {
|
|
620
|
+
let s = null; const rr = await acct.get(indexRoom, mks.get(indexRoom) || indexMk, name, { plainOpen: unzipDoc })
|
|
621
|
+
if (rr && rr.status === 200 && rr.state) s = rr.state
|
|
622
|
+
if (s && s.rooms && typeof s.rooms === 'object') cur = s.rooms
|
|
623
|
+
} catch { /* read failed → fall back to inject-what-we-hold (the pre-existing behaviour) */ }
|
|
624
|
+
const rooms = {}
|
|
625
|
+
for (const rm of Object.keys(p.rooms)) {
|
|
626
|
+
const e = p.rooms[rm] || {}
|
|
627
|
+
if (e.deleted) { const { mk: _dmk, ep: _dep, split: _ds, userShare: _du, commit: _dc, ...rest } = e; rooms[rm] = rest; continue } // a deleted Space's entry carries no key (2026-11-12): the doc stops handing it back
|
|
628
|
+
if (splits.has(rm)) { const sp = splits.get(rm); rooms[rm] = { ...e, split: true, userShare: sp.userShare, ...(sp.commit ? { commit: sp.commit } : {}), ...(eps.get(rm) ? { ep: eps.get(rm) } : {}) }; continue }
|
|
629
|
+
const mk = mks.get(rm)
|
|
630
|
+
if (mk) { rooms[rm] = { ...e, mk, ...(eps.get(rm) ? { ep: eps.get(rm) } : {}) }; continue } // + the key's epoch (noteEp)
|
|
631
|
+
const prev = cur[rm] // we hold no key — keep whatever the doc already carries, and absorb it
|
|
632
|
+
if (prev && prev.split && prev.userShare) { keepSplit(rm, { userShare: prev.userShare, commit: prev.commit || '' }, prev.ep); rooms[rm] = { ...e, split: true, userShare: prev.userShare, ...(prev.commit ? { commit: prev.commit } : {}), ...(prev.ep ? { ep: prev.ep } : {}) }; continue }
|
|
633
|
+
if (prev && prev.mk) { keep(rm, prev.mk, prev.ep); rooms[rm] = { ...e, mk: prev.mk, ...(prev.ep ? { ep: prev.ep } : {}) }; continue }
|
|
634
|
+
// no key here and none in the doc → drop (unchanged)
|
|
635
|
+
}
|
|
636
|
+
p.rooms = rooms
|
|
637
|
+
publishPresence()
|
|
638
|
+
}
|
|
639
|
+
// ⛔ SEALED on the device — the doc carries every room key (accountStores.js); without the account key nothing is written
|
|
640
|
+
const r = await acct.put(indexRoom, mks.get(indexRoom) || indexMk, name, p, summary, by, { ifV }) // ifV: only over the version the app merged
|
|
641
|
+
self.postMessage({ id, result: { status: (r && r.status) || 0, bytes: _jsonBytes(p), z: true, ...(r && r.error ? { error: r.error } : {}) } })
|
|
642
|
+
} catch (err) { self.postMessage({ id, error: 'indexWrite: ' + String((err && err.message) || err) }) }
|
|
643
|
+
return
|
|
644
|
+
}
|
|
645
|
+
case 'pipesRead': { // Atlas pipes: read the pipes doc, ABSORB each pipe's shared+lane room→mk into the store, return KEYLESS
|
|
646
|
+
const { id, pipesRoom, pipesMk, name } = m
|
|
647
|
+
try {
|
|
648
|
+
if (!client) throw new Error('l1-worker: pipesRead before open')
|
|
649
|
+
if (pipesMk && !mks.get(pipesRoom)) { keep(pipesRoom, pipesMk); publishPresence() }
|
|
650
|
+
const r = await acct.get(pipesRoom, mks.get(pipesRoom) || pipesMk, name) // SEALED on the device (accountStores.js)
|
|
651
|
+
if (!(r && r.status === 200 && r.state)) { self.postMessage({ id, result: { status: (r && r.status) || 0, state: null } }); return }
|
|
652
|
+
let st = r.state
|
|
653
|
+
if (st && typeof st === 'object' && st.pipes && typeof st.pipes === 'object') {
|
|
654
|
+
const keyless = {}
|
|
655
|
+
for (const s of Object.keys(st.pipes)) { const pp = st.pipes[s] || {}; const out = { ...pp }
|
|
656
|
+
if (pp.shared && pp.shared.room) { if (pp.shared.mk) keep(pp.shared.room, pp.shared.mk); const { mk, ...rest } = pp.shared; out.shared = rest }
|
|
657
|
+
if (pp.lane && pp.lane.room) { if (pp.lane.mk) keep(pp.lane.room, pp.lane.mk); const { mk, ...rest } = pp.lane; out.lane = rest }
|
|
658
|
+
// lane-to-lane rows (docs/spaces-linked-lanes.md): two lane endpoints, absorbed the same way
|
|
659
|
+
for (const k of ['laneA', 'laneB']) { const ep = pp[k]; if (ep && ep.room) { if (ep.mk) keep(ep.room, ep.mk); const { mk, ...rest } = ep; out[k] = rest } }
|
|
660
|
+
keyless[s] = out }
|
|
661
|
+
publishPresence(); st = { ...st, pipes: keyless }
|
|
662
|
+
}
|
|
663
|
+
self.postMessage({ id, result: { status: 200, state: st, ...(Number.isInteger(r.v) ? { v: r.v } : {}) } }) // v: the version a write names (accountStores put ifV)
|
|
664
|
+
} catch (err) { self.postMessage({ id, error: 'pipesRead: ' + String((err && err.message) || err) }) }
|
|
665
|
+
return
|
|
666
|
+
}
|
|
667
|
+
case 'pipesWrite': { // Atlas pipes: build the pipes doc INJECTING each pipe's shared+lane mk from the store
|
|
668
|
+
const { id, pipesRoom, pipesMk, name, patch, summary, by, ifV } = m
|
|
669
|
+
try {
|
|
670
|
+
if (!client) throw new Error('l1-worker: pipesWrite before open')
|
|
671
|
+
if (pipesMk && !mks.get(pipesRoom)) { keep(pipesRoom, pipesMk); publishPresence() }
|
|
672
|
+
let pp = { ...(patch || {}) }
|
|
673
|
+
if (pp.pipes && typeof pp.pipes === 'object') {
|
|
674
|
+
const pipes = {}
|
|
675
|
+
for (const s of Object.keys(pp.pipes)) { const e = pp.pipes[s] || {}; const out = { ...e }
|
|
676
|
+
if (e.shared && e.shared.room) { const mk = mks.get(e.shared.room); out.shared = mk ? { ...e.shared, mk } : e.shared }
|
|
677
|
+
if (e.lane && e.lane.room) { const mk = mks.get(e.lane.room); out.lane = mk ? { ...e.lane, mk } : e.lane }
|
|
678
|
+
for (const k of ['laneA', 'laneB']) { const ep = e[k]; if (ep && ep.room) { const mk = mks.get(ep.room); out[k] = mk ? { ...ep, mk } : ep } } // lane-to-lane rows: both lanes' keys injected
|
|
679
|
+
pipes[s] = out }
|
|
680
|
+
pp.pipes = pipes
|
|
681
|
+
}
|
|
682
|
+
const r = await acct.put(pipesRoom, mks.get(pipesRoom) || pipesMk, name, pp, summary, by, { ifV }) // ⛔ sealed — the doc carries lane + shared keys
|
|
683
|
+
self.postMessage({ id, result: { status: (r && r.status) || 0, ...(r && r.error ? { error: r.error } : {}) } })
|
|
684
|
+
} catch (err) { self.postMessage({ id, error: 'pipesWrite: ' + String((err && err.message) || err) }) }
|
|
685
|
+
return
|
|
686
|
+
}
|
|
687
|
+
case 'tempHold': { // {ptr: {room, mk, sk}} → hold the temp index (its key memory-only, beside the others) → {ok, room}
|
|
688
|
+
// From the hosted vault only in practice (its replay, its `index` answer, a frame's hand-over it relays after keeping the
|
|
689
|
+
// pointer itself — vault-loader.js). No sk → refused: a list sealed under a key nobody keeps would be lost.
|
|
690
|
+
const p = m.ptr || {}
|
|
691
|
+
const ok = isTempRoomId(p.room) && typeof p.mk === 'string' && !!p.mk && typeof p.sk === 'string' && TEMP_SK.test(p.sk)
|
|
692
|
+
keysReady.then(() => {
|
|
693
|
+
if (ok) { keep(p.room, p.mk); tempPtr = { room: p.room, sk: p.sk }; publishPresence() } // kept as an opened room's key is (the frame's copy lived in the vault's app store before); the vault re-hands the pointer to a new worker
|
|
694
|
+
if (m.id != null) self.postMessage({ id: m.id, result: { ok, room: ok ? p.room : null } })
|
|
695
|
+
})
|
|
696
|
+
return
|
|
697
|
+
}
|
|
698
|
+
case 'tempList': { // {do: 'read' | 'add' | 'remove', add?: {room, title, mk?, userShare?, commit?}, rooms?, by} → {status, room, rooms (KEYLESS)}
|
|
699
|
+
// Every listed room's key is ABSORBED here (as an open of the room puts it here — its preview key too); the caller gets the
|
|
700
|
+
// list without them (keylessTempList) and opens the rooms through this worker.
|
|
701
|
+
const { id } = m
|
|
702
|
+
const answer = (result) => self.postMessage({ id, result })
|
|
703
|
+
;(async () => {
|
|
704
|
+
try {
|
|
705
|
+
if (!client) throw new Error('l1-worker: tempList before open')
|
|
706
|
+
await keysReady
|
|
707
|
+
if (!tempPtr) return answer({ status: 0, error: 'no_pointer' })
|
|
708
|
+
const p = tempPtr, pmk = mks.get(p.room) || await resolveMk(p.room).catch(() => null)
|
|
709
|
+
if (!pmk) return answer({ status: 0, error: 'no_key', room: p.room })
|
|
710
|
+
const absorb = (list) => { for (const e of list) { if (!e || !isTempRoomId(e.room)) continue; if (e.mk) keep(e.room, e.mk); else if (e.userShare) keepSplit(e.room, { userShare: e.userShare, commit: e.commit || '' }) } publishPresence() }
|
|
711
|
+
let list = null
|
|
712
|
+
if (m.do === 'read') {
|
|
713
|
+
const r = await tempStore.get(p.room, pmk, 'rooms')
|
|
714
|
+
if (!(r && r.status === 200)) return answer({ status: (r && r.status) || 0, room: p.room })
|
|
715
|
+
list = r.state && Array.isArray(r.state.rooms) ? r.state.rooms : null // null: no list there — the caller keeps what it has
|
|
716
|
+
} else if (m.do === 'add') {
|
|
717
|
+
const a = m.add || {}, room = a.room
|
|
718
|
+
if (!isTempRoomId(room)) return answer({ status: 0, error: 'not_temp', room: p.room })
|
|
719
|
+
const sp = splits.get(room)
|
|
720
|
+
const fresh = a.mk ? { mk: a.mk } : a.userShare ? { userShare: a.userShare, commit: a.commit || '' } : (sp && sp.userShare) ? { userShare: sp.userShare, commit: sp.commit || '' } : mks.get(room) ? { mk: mks.get(room) } : null // the caller's material, else what this worker holds
|
|
721
|
+
list = await editTempList(tempStore, p.room, pmk, (all) => addToTempList(all, { room, title: typeof a.title === 'string' ? a.title.slice(0, 120) : '', fresh }), m.by)
|
|
722
|
+
if (!list) return answer({ status: 0, room: p.room })
|
|
723
|
+
} else if (m.do === 'remove') {
|
|
724
|
+
const rooms = (Array.isArray(m.rooms) ? m.rooms : []).filter(isTempRoomId)
|
|
725
|
+
list = await editTempList(tempStore, p.room, pmk, (all) => removeFromTempList(all, rooms), m.by)
|
|
726
|
+
if (!list) return answer({ status: 0, room: p.room })
|
|
727
|
+
} else throw new Error('tempList: unknown ' + String(m.do))
|
|
728
|
+
if (list) absorb(list)
|
|
729
|
+
answer({ status: 200, room: p.room, rooms: list ? keylessTempList(list) : null })
|
|
730
|
+
} catch (err) { self.postMessage({ id, error: 'tempList: ' + String((err && err.message) || err) }) }
|
|
731
|
+
})()
|
|
732
|
+
return
|
|
733
|
+
}
|
|
734
|
+
case 'streamOpen': { // {room, grants} → hold this room's stream (one socket however many frames ask)
|
|
735
|
+
const { room, grants } = m
|
|
736
|
+
const h = streams.get(room)
|
|
737
|
+
if (h) { h.holders++; if (Array.isArray(grants)) { h.s.setGrants(grants); h.grants = grants } return }
|
|
738
|
+
let mk = null
|
|
739
|
+
try { await keysReady } catch { /* */ }
|
|
740
|
+
try { mk = (typeof m.mk === 'string' && m.mk) || mks.get(room) || await resolveMk(room) } catch { mk = null } // m.mk: an account room's pointer key (index / pipes), as indexRead takes it
|
|
741
|
+
if (!mk || streams.has(room)) { if (streams.has(room)) streams.get(room).holders++; return } // no key here → no stream (the page keeps polling)
|
|
742
|
+
const tag = await viewingTag(room).catch(() => '') // THIS device is viewing the room (no tickle for it while the socket is open)
|
|
743
|
+
if (streams.has(room)) { streams.get(room).holders++; return } // another open won the race during the await
|
|
744
|
+
const s = openStreamHere(room, mk, grants, tag)
|
|
745
|
+
streams.set(room, { s, holders: 1, mk, tag, grants: Array.isArray(grants) ? grants : null })
|
|
746
|
+
return
|
|
747
|
+
}
|
|
748
|
+
case 'streamClose': { // {room} → one holder fewer; the last one closes the socket
|
|
749
|
+
const h = streams.get(m.room)
|
|
750
|
+
if (h && --h.holders <= 0) { h.s.stop(); streams.delete(m.room) }
|
|
751
|
+
return
|
|
752
|
+
}
|
|
753
|
+
case 'op': { // {id, op, room, args} → client[op](room, mks[room], …args) → {id, result}
|
|
754
|
+
const { id, op, room, args } = m
|
|
755
|
+
try {
|
|
756
|
+
if (!client) throw new Error('l1-worker: op before open')
|
|
757
|
+
try { await keysReady } catch { /* same cold-start race as resolveMk: never run an op against a half-loaded map */ }
|
|
758
|
+
if (typeof client[op] !== 'function') throw new Error('l1-worker: unknown op ' + op)
|
|
759
|
+
const aa = args || []
|
|
760
|
+
// §ID-CONFINE: turn signature is (room, message, identity, opts). When the app sends NO identity (idconfine on),
|
|
761
|
+
// sign with the identity CONFINED here (seeded by the vault) so the private signing key never leaves L1. A room we
|
|
762
|
+
// hold no identity for stays unsigned (open/legacy), unchanged. Only substitutes when the arg is absent — an app
|
|
763
|
+
// that still passes identity (flag off / email turn) is untouched.
|
|
764
|
+
if (op === 'turn' && (aa[1] == null) && ids.has(room)) aa[1] = ids.get(room)
|
|
765
|
+
for (const a of aa) { if (a && typeof a === 'object' && a.bridgeRoom && !a.bridgeMk) { const bmk = mks.get(a.bridgeRoom) || await resolveMk(a.bridgeRoom); if (bmk) a.bridgeMk = bmk } }
|
|
766
|
+
for (const a of aa) { if (a && typeof a === 'object' && Array.isArray(a.links)) for (const l of a.links) { if (l && typeof l === 'object' && l.room && !l.mk) { const lmk = mks.get(l.room) || await resolveMk(l.room).catch(() => null); if (lmk) l.mk = lmk } } } // a lane's linked rooms named by id (a vault's page holds no keys) // worker-resolve a lane bridge's key (?atlaspipes: laneBridge passes bridgeRoom only). resolveMk (not just the cache) so a split shared room whose mk isn't cached yet still gets its bridge injected. Inert when bridgeMk is already present.
|
|
767
|
+
const mkHere = await resolveMk(room) // §9: reconstruct a split room's mk (fetch appShare + combine) on demand
|
|
768
|
+
let result = null
|
|
769
|
+
let pfNote = '' // what the prefetch lookup found, for the page's tap timeline ('' = not looked up)
|
|
770
|
+
const afterTap = !!(aa[2] && typeof aa[2] === 'object' && aa[2].afterTap) // the page says this poll follows a notification tap
|
|
771
|
+
if ((op === 'poll' || op === 'pollSealed') && mkHere && typeof client.decodeSealed === 'function' && (afterTap || Date.now() < prefetchLookUntil || prefetchFlag.has(room) || !prefetchChecked.has(room))) {
|
|
772
|
+
// PREFETCHED AT PUSH TIME (prefetchPoll.js): the service worker fetched this room's new sealed entries when the
|
|
773
|
+
// notification arrived. The first poll asking from that same position is answered from them at once, and the
|
|
774
|
+
// network is still asked in the background — for freshness, and so the change inbox the first poll carries
|
|
775
|
+
// is still registered with the server. Looked up on a room's FIRST poll in this worker's life (a cold start
|
|
776
|
+
// after the tap) and whenever the service worker announced one (the worker was alive through the push).
|
|
777
|
+
prefetchChecked.add(room); prefetchFlag.delete(room)
|
|
778
|
+
let pfKey = 'prefetch:' + room, pf = await idbGet(pfKey)
|
|
779
|
+
if (!pf) { pfKey = await prefetchHashKey(room); pf = await idbGet(pfKey) } // a TAIL, kept under a hash of the room (no position was known)
|
|
780
|
+
if (!pf) pfNote = 'none stored'
|
|
781
|
+
else {
|
|
782
|
+
idbDel(pfKey) // once, whatever the verdict
|
|
783
|
+
const why = prefetchUsable(pf, aa[1] | 0)
|
|
784
|
+
if (why) pfNote = why + (why === 'position moved' ? ' (stored since ' + pf.sinceCount + ', asked since ' + (aa[1] | 0) + ')' : '')
|
|
785
|
+
else {
|
|
786
|
+
const pfAns = prefetchAnswer(pf, aa[1] | 0)
|
|
787
|
+
if (!pfAns) pfNote = 'the tail does not reach this position'
|
|
788
|
+
else try { const out = await client.decodeSealed(room, mkHere, aa[1] | 0, pfAns); if (out && out.status === 200) { result = { ...out, prefetched: true }; pfNote = pf.tail ? 'used (a tail from ' + pf.sinceCount + ')' : 'used'; client[op](room, mkHere, ...aa).catch(() => {}) } else pfNote = 'decoded to status ' + (out && out.status) } catch (e) { result = null; pfNote = 'decode failed: ' + String((e && e.message) || e).slice(0, 60) }
|
|
789
|
+
}
|
|
790
|
+
}
|
|
791
|
+
}
|
|
792
|
+
// THE ENTRY THE STREAM CARRIED (frameTails): a poll from exactly count-1 is answered from it at once — decoded with the
|
|
793
|
+
// key here, the decoder the network path uses — and the network is still asked behind it (as for a prefetch).
|
|
794
|
+
if (!result && (op === 'poll' || op === 'pollSealed') && mkHere && typeof client.decodeSealed === 'function' && frameTails.has(room)) {
|
|
795
|
+
const ft = frameTails.get(room); frameTails.delete(room)
|
|
796
|
+
if (ft && Date.now() - ft.at < FRAME_TAIL_MS && (aa[1] | 0) === ft.count - 1) {
|
|
797
|
+
try {
|
|
798
|
+
const out = await client.decodeSealed(room, mkHere, ft.count - 1, { status: 200, changed: true, count: ft.count, from: ft.count - 1, sealed: JSON.stringify({ v: 3, from: ft.count - 1, count: ft.count, boxes: [ft.box] }) })
|
|
799
|
+
if (out && out.status === 200) { result = { ...out, fromFrame: true }; client[op](room, mkHere, ...aa).catch(() => {}) }
|
|
800
|
+
} catch { /* the network answers below */ }
|
|
801
|
+
}
|
|
802
|
+
}
|
|
803
|
+
if (!result && op === 'poll' && !mkHere) result = { status: 401, error: 'no_key', reason: noKeyReason(room) } // a keyless plaintext read: the server refuses it with a BARE 401 ({} — no error field, measured 2026-10-03), which the page could not tell from anything. Say it here, and spare the round trip.
|
|
804
|
+
if (op === 'rekey' && splits.has(room)) aa[0] = { ...(aa[0] || {}), split: { userShare: splits.get(room).userShare } } // a SPLIT room rotates only the user's half (spaceClient.rekey)
|
|
805
|
+
if (!result) result = await client[op](room, mkHere, ...aa)
|
|
806
|
+
if (op === 'rekey' && result && result.status === 200 && result.newShare) { keepSplit(room, { userShare: result.newShare, commit: result.newCommit }, result.epoch); keep(room, result.newMk, result.epoch); publishPresence(); const { newMk: _nm, ...up } = result; result = { ...up, split: true } } // the full key stays HERE (the hosted rule: the frame never holds mk)
|
|
807
|
+
else if (op === 'rekey' && result && result.status === 200 && result.newMk) { keep(room, result.newMk, result.epoch); publishPresence() } // A ROOM RE-KEYED IN PLACE (docs/key-rotation-design.md § (b)): this realm made the new key; it holds it from now on
|
|
808
|
+
if (op === 'pollSealed' && !mkHere && result && result.status === 422) result = { ...result, error: 'no_key', reason: noKeyReason(room) } // the boxes came back and nothing here can open them: not a WRONG key — NO key (the owner's lock banner blamed the invite)
|
|
809
|
+
// A WRONG REMEMBERED KEY IS NOT THE ROOM'S KEY. resolveMk takes the remembered plain key before the split entry, and
|
|
810
|
+
// the remembered one is persisted here (idb mk:<room>) — so a wrong plain key, however it arrived, beat the correct,
|
|
811
|
+
// commit-checked split key on every launch: the owner's confidential room drawn blank for weeks (2026-10-03), its
|
|
812
|
+
// ten boxes opening fine with the key the split rebuilds. A read answering 422 'undecodable' from a room that HAS a
|
|
813
|
+
// split entry drops the remembered key, rebuilds from the split (appShare ⊕ userShare, commit-checked) and asks once more.
|
|
814
|
+
if ((op === 'poll' || op === 'pollSealed') && result && result.status === 422 && result.reason === 'undecodable' && splits.has(room) && mks.has(room)) {
|
|
815
|
+
const stale = mks.get(room); mks.delete(room); idb.del('mk:' + room).catch(() => {})
|
|
816
|
+
const fresh = await resolveMk(room).catch(() => undefined)
|
|
817
|
+
if (fresh && fresh !== stale) { const again = await client[op](room, fresh, ...aa); if (again && typeof again === 'object') result = { ...again, rekeyed: true } }
|
|
818
|
+
else if (stale) keep(room, stale) // nothing better — put it back rather than leave the room keyless
|
|
819
|
+
}
|
|
820
|
+
if (pfNote && result && typeof result === 'object') result = { ...result, prefetchNote: pfNote }
|
|
821
|
+
if (op === 'poll' || op === 'pollSealed') { const pos = positionOf(result); const last = lastPos.get(room); if (pos && (!last || last.etag !== pos.etag || last.count !== pos.count)) { lastPos.set(room, pos); if (!protectedAtRest) idbSet('cnt:' + room, pos) /* §NAMES: a protected device keeps no room-named position (the push prefetch is off there) */ } }
|
|
822
|
+
if (op === 'poll' || op === 'pollSealed') streamFeed(room, result) // a streaming room: the poll's reply text + fresh grants re-sync the stream
|
|
823
|
+
try { self.postMessage({ id, result }) } // structured-clone can throw on a non-cloneable result
|
|
824
|
+
catch (ce) { self.postMessage({ id, error: 'result-clone(' + op + '): ' + String((ce && ce.message) || ce) }) }
|
|
825
|
+
} catch (err) { // a tagged refusal (enclave_not_accepted) keeps its code + verdict so the app can show WHICH stage mismatched
|
|
826
|
+
self.postMessage({ id, error: op + ': ' + String((err && err.message) || err), ...(err && err.code ? { code: err.code, verdict: err.verdict || null, room: err.room || null } : {}) })
|
|
827
|
+
}
|
|
828
|
+
return
|
|
829
|
+
}
|
|
830
|
+
}
|
|
831
|
+
}
|