@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
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
// vaultEnclaveHandoff.js — THE RULES FOR HANDING A VAULT'S ROOM-KEY WORKER THE CONFIDENTIAL TIER (docs/vault-core-convergence-review.md,
|
|
2
|
+
// option C, C2). Our hosted vault (vault-loader.js) and the builders' vault (vault-core.js) each told the same l1-worker which enclave
|
|
3
|
+
// key to seal to and which rooms are confidential, with their own code — and five bugs came out of the two copies:
|
|
4
|
+
// sync sweep 2026-11-06 #2 #3 (the core) — only the worker knew a room was confidential: the vault's own client sent a Space's
|
|
5
|
+
// key READABLE and a Stop to the standard tier → `enclaveReady`, `saysConfidential`.
|
|
6
|
+
// sync sweep 2026-11-09 #1 (ours) — a recreated worker's confidential list was EMPTY, so a room's key went out unsealed → the
|
|
7
|
+
// held `snapshot()` a replay sends (the core now sends it FIRST, before the open, as ours does before any key).
|
|
8
|
+
// sync sweep 2026-11-10 #1 (ours) — the worker got each frame's OWN list and replaces its list on every message: a panel's older
|
|
9
|
+
// list took a new confidential Space off → `offer()` returns the UNION, and that is what the worker is sent.
|
|
10
|
+
// state machines pass 8 R#1 (ours), pass 9 X#1 — a panel's older key over the main app's newer one; then the first key frozen →
|
|
11
|
+
// the NEWER attestation wins whoever sends it, equal/unknown times → the main app (enclaveSnapshotMerge.js).
|
|
12
|
+
// The worker REPLACES its enclave state with each `{ t:'enclave', key, attested, keys, acceptance, rooms }` (l1-worker.js), so a vault
|
|
13
|
+
// must only ever send it the whole held state. What stays each vault's own is WHO attests and whom it believes: ours, its trusted
|
|
14
|
+
// frames (the person's accepted builds); the core, itself (its page is untrusted) and exactly the builds Witbitz publishes.
|
|
15
|
+
//
|
|
16
|
+
// createEnclaveHandoff({ trust }) → h
|
|
17
|
+
// trust 'sender' (ours) the builds the worker trusts are the senders' accepted lists, unioned (the person's list, per frame)
|
|
18
|
+
// 'published' (the core) exactly the live builds of the held region keys that the claim each carries names
|
|
19
|
+
// (enclaveAccept.acceptsMeasurement — the SDK's 'published' rule); a sender's list never counts
|
|
20
|
+
// h.offer(snap, { fromMain }) merge a sender's snapshot into what is held → the message to send the worker (a copy)
|
|
21
|
+
// h.mark(rooms) add confidential rooms (the union only grows) → true when it grew
|
|
22
|
+
// h.has(room) · h.rooms() the union
|
|
23
|
+
// h.snapshot() the held message, a copy (no sender's id or extra fields) — what a replay sends
|
|
24
|
+
// h.known anything offered or marked yet
|
|
25
|
+
// enclaveReady({ confidential, hasKey, attest, mark }) → may this room be called on the enclave by a client the vault drives
|
|
26
|
+
// reattestOnce({ enc, run, reattest }) → one op: a missing/stale enclave key re-attests ONCE and runs the same sealed call again
|
|
27
|
+
import { mergeEnclaveSnapshot } from './enclaveSnapshotMerge.js'
|
|
28
|
+
import { acceptsMeasurement } from './enclaveAccept.js'
|
|
29
|
+
|
|
30
|
+
const obj = (o) => (o && typeof o === 'object' && !Array.isArray(o) ? o : {})
|
|
31
|
+
const list = (a) => (Array.isArray(a) ? a.filter((r) => typeof r === 'string' && r) : [])
|
|
32
|
+
|
|
33
|
+
/** The live builds of a snapshot's region keys that the published claim each key carries names (attested.platform). */
|
|
34
|
+
export function publishedBuilds (snap) {
|
|
35
|
+
const out = []
|
|
36
|
+
for (const e of Object.values(obj(snap && snap.keys))) {
|
|
37
|
+
const att = e && e.attested
|
|
38
|
+
if (!e || !e.key || !att) continue
|
|
39
|
+
const a = acceptsMeasurement(null, att, att.platform)
|
|
40
|
+
if (a.ok && a.live) out.push(a.live)
|
|
41
|
+
}
|
|
42
|
+
return out
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export function createEnclaveHandoff ({ trust = 'sender' } = {}) {
|
|
46
|
+
if (trust !== 'sender' && trust !== 'published') throw new Error('createEnclaveHandoff: trust is sender or published')
|
|
47
|
+
let held = null // the merged snapshot, without the room union
|
|
48
|
+
const rooms = new Set()
|
|
49
|
+
const copy = () => {
|
|
50
|
+
const h = held || {}
|
|
51
|
+
const keys = {}
|
|
52
|
+
for (const [region, e] of Object.entries(obj(h.keys))) keys[region] = e && typeof e === 'object' ? { ...e } : e
|
|
53
|
+
const acc = obj(h.acceptance)
|
|
54
|
+
return {
|
|
55
|
+
t: 'enclave',
|
|
56
|
+
key: h.key ?? null,
|
|
57
|
+
attested: h.attested ?? null,
|
|
58
|
+
keys,
|
|
59
|
+
acceptance: Array.isArray(acc.trusted) ? { ...acc, trusted: acc.trusted.slice() } : { ...acc },
|
|
60
|
+
rooms: [...rooms],
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
return {
|
|
64
|
+
get known () { return !!held || rooms.size > 0 },
|
|
65
|
+
offer (snap, { fromMain = true } = {}) {
|
|
66
|
+
const s = obj(snap)
|
|
67
|
+
for (const r of list(s.rooms)) rooms.add(r)
|
|
68
|
+
const m = mergeEnclaveSnapshot(held, { ...s, rooms: [] }, !!fromMain)
|
|
69
|
+
held = { key: m.key, attested: m.attested, keys: m.keys, acceptance: trust === 'published' ? { trusted: publishedBuilds(m) } : m.acceptance }
|
|
70
|
+
return copy()
|
|
71
|
+
},
|
|
72
|
+
mark (rs) { const n = rooms.size; for (const r of list(rs)) rooms.add(r); return rooms.size > n },
|
|
73
|
+
has: (room) => rooms.has(room),
|
|
74
|
+
rooms: () => [...rooms],
|
|
75
|
+
snapshot: copy,
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** The server says this room is confidential: the front's `confidential_room` refusal, or a (keyless) answer's `tier: 'enclave'`
|
|
80
|
+
* (agent/tierGuard.mjs; spaceClient's own tierRefusal answers the same). */
|
|
81
|
+
export const saysConfidential = (r) => !!(r && typeof r === 'object' && (r.error === 'confidential_room' || r.tier === 'enclave'))
|
|
82
|
+
/** The enclave was replaced (or restarted): what was sealed to its key no longer opens. */
|
|
83
|
+
export const staleEnclaveKey = (r) => !!(r && typeof r === 'object' && (r.status === 401 || r.status === 200) && r.error === 'bad_mkseal')
|
|
84
|
+
/** The worker refused to seal: no enclave key in hand for this room (spaceClient keyFields) — nothing was sent. */
|
|
85
|
+
export const noEnclaveKey = (err) => /enclave key unavailable/i.test(String(err && err.message))
|
|
86
|
+
|
|
87
|
+
/** A client the VAULT drives (not the worker) is marked confidential only once the enclave key is in hand: a marked room with no
|
|
88
|
+
* key would send its key readable (sweep 11-06 #2 #3). Attests when the key is missing; never marks a standard room. */
|
|
89
|
+
export async function enclaveReady ({ confidential, hasKey, attest, mark }) {
|
|
90
|
+
if (!confidential) return false
|
|
91
|
+
if (!hasKey()) { try { await attest() } catch { return false } }
|
|
92
|
+
if (!hasKey()) return false
|
|
93
|
+
mark()
|
|
94
|
+
return true
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** One op on a room: a confidential room whose enclave key is missing or stale re-attests ONCE and runs the SAME call again —
|
|
98
|
+
* through the same worker, so the room's key is sealed or not sent; there is no other path to fall back to. A standard room's
|
|
99
|
+
* answer and errors pass through untouched. */
|
|
100
|
+
export async function reattestOnce ({ enc, run, reattest }) {
|
|
101
|
+
let tried = false
|
|
102
|
+
const heal = async () => {
|
|
103
|
+
if (!enc || tried) return false
|
|
104
|
+
tried = true
|
|
105
|
+
try { return !!(await reattest()) } catch { return false }
|
|
106
|
+
}
|
|
107
|
+
let r
|
|
108
|
+
try { r = await run() } catch (err) {
|
|
109
|
+
if (!(noEnclaveKey(err) && await heal())) throw err
|
|
110
|
+
r = await run()
|
|
111
|
+
}
|
|
112
|
+
if (staleEnclaveKey(r) && await heal()) r = await run()
|
|
113
|
+
return r
|
|
114
|
+
}
|
package/vaultKeep.js
ADDED
|
@@ -0,0 +1,281 @@
|
|
|
1
|
+
// vaultKeep.js — WHAT AN SDK VAULT KEEPS FOR AN ACCOUNT, ON EVERY DEVICE OF IT (sync sweep 2026-11-11 P7; the owner: "8, yes").
|
|
2
|
+
// A builder's vault (vault-core.js) holds three things the page never sees: each connection's callKey, the Siri inbox's private
|
|
3
|
+
// keys and the outside agents' (A2A) lane keys. It kept them in its own storage only, so the same person's second device listed
|
|
4
|
+
// their connections (the server's list) but could not use one (`not_in_vault`), could not open Siri or an outside agent's message,
|
|
5
|
+
// and a lost device lost all three for good. The Witbitz app keeps the same things in the account's synced docs; this does that
|
|
6
|
+
// for the vault.
|
|
7
|
+
//
|
|
8
|
+
// WHERE: one doc (KEEP_DOC) in the account's INDEX ROOM (sdkAccount.js indexRoomOf — derived from the backup's master secret, so
|
|
9
|
+
// only the account's own devices can find or open it), sealed ON THE DEVICE under its own derived key: the room's key reaches the
|
|
10
|
+
// standard tier like any room's, but what this doc carries never does. A vault without the backup on has no index room: nothing
|
|
11
|
+
// syncs, as before.
|
|
12
|
+
// HOW DEVICES AGREE: per entry, last writer wins — a connection by its id, an A2A lane by its room, Siri as one entry — and a
|
|
13
|
+
// removed entry leaves a tombstone `{ at, gone: true }`, so a detach on one device is a detach everywhere. Merging is commutative.
|
|
14
|
+
// ★ THE CLOBBER RULE (as the index's): nothing is written unless the read before it was DEFINITIVE (a 200 that opened, or no doc
|
|
15
|
+
// yet), and the write is conditional on the version read (a 409 → read and merge again).
|
|
16
|
+
import { sealDoc, openDoc } from './accountSeal.js'
|
|
17
|
+
import { normA2A } from './a2aCore.js' // a lane's one normal form (what sdk.a2a.restore makes of it)
|
|
18
|
+
// THE MERGE RULES ARE THE APP'S TOO (vault-core convergence C3): Siri by Space, agents by id, removal marks, tombstones, "write
|
|
19
|
+
// only what was applied" — one copy, keptMerge.js; this file keeps only the keep's own format (stamps, entries, the doc).
|
|
20
|
+
import { canon, unionMarks, mergePeers, mergeSiriRooms, siriKeyOf, siriDefaultOf, newerEntry as newer, mergeEntries as mergeMap, settleOf, MAX_TOMBS } from './keptMerge.js'
|
|
21
|
+
import { index2Doc } from './accountIndexDoc.js' // the app's xindex2 builder (phase 4, below)
|
|
22
|
+
|
|
23
|
+
export const KEEP_DOC = 'xvaultkeep' // x…: sealed on the device (agent/spaceService.mjs ACCOUNT_DOCS)
|
|
24
|
+
export const APP_KEEP_DOC = 'xindex2' // the Spaces app's sealed 'index2' (accountStores.js SEALED) — phase 4, below
|
|
25
|
+
const enc = new TextEncoder()
|
|
26
|
+
const SALT = enc.encode('witbitz-sdk-account-v1') // = sdkAccount.js — one derivation tree per account
|
|
27
|
+
const num = (x) => (Number.isFinite(x) && x > 0 ? x : 0)
|
|
28
|
+
const ub64 = (s) => { const b = atob(String(s).replace(/-/g, '+').replace(/_/g, '/')); const u = new Uint8Array(b.length); for (let i = 0; i < b.length; i++) u[i] = b.charCodeAt(i); return u }
|
|
29
|
+
|
|
30
|
+
/** The doc's sealing key, from the account's backup master (base64). */
|
|
31
|
+
export async function keepKeyOf (masterB64) {
|
|
32
|
+
const km = await crypto.subtle.importKey('raw', ub64(masterB64), 'HKDF', false, ['deriveBits'])
|
|
33
|
+
const raw = new Uint8Array(await crypto.subtle.deriveBits({ name: 'HKDF', hash: 'SHA-256', salt: SALT, info: enc.encode('vault-keep-seal') }, km, 256))
|
|
34
|
+
return crypto.subtle.importKey('raw', raw, { name: 'AES-GCM' }, false, ['encrypt', 'decrypt'])
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export const emptyKeep = () => ({ v: 1, conns: {}, a2a: {}, siri: null })
|
|
38
|
+
const normKeep = (k) => ({ v: 1, conns: (k && k.conns && typeof k.conns === 'object') ? k.conns : {}, a2a: (k && k.a2a && typeof k.a2a === 'object') ? k.a2a : {}, siri: (k && k.siri && typeof k.siri === 'object') ? k.siri : null })
|
|
39
|
+
|
|
40
|
+
// ⛔ ONE NORMAL FORM BEFORE ANY COMPARISON (state machines pass 9, K#4): a lane was kept as enableLaneIn left it (the exported
|
|
41
|
+
// private JWK, `ext` and `key_ops` included) while every device that applied it held it as sdk.a2a.restore → normA2A makes it.
|
|
42
|
+
// The next pass read `prev` (raw) ≠ the store (normalised) as a change made HERE, stamped the lane "changed now" on every such
|
|
43
|
+
// device, and that stamp beat what the others had done to it since (an agent let in elsewhere dropped, a removed one back).
|
|
44
|
+
// A lane that is not a valid record (no normal form) is compared as it is.
|
|
45
|
+
const laneForm = (room, l) => { try { return normA2A({ lanes: { [room]: l } }).lanes[room] || l } catch { return l } }
|
|
46
|
+
|
|
47
|
+
/** What changed on this device since `prev` (the last merged view), stamped `now`. `cur` = { conns: [rec], siri: state, a2a: { lanes } }. */
|
|
48
|
+
export function stampKeep (prev, cur, now = Date.now()) {
|
|
49
|
+
const p = normKeep(prev), out = { v: 1, conns: { ...p.conns }, a2a: { ...p.a2a }, siri: p.siri }
|
|
50
|
+
const stampMap = (map, entries, field, form = (id, v) => v) => {
|
|
51
|
+
const seen = new Set()
|
|
52
|
+
for (const [id, val] of entries) {
|
|
53
|
+
seen.add(id)
|
|
54
|
+
const was = map[id]
|
|
55
|
+
if (!was || was.gone || canon(form(id, was[field])) !== canon(form(id, val))) map[id] = { at: now, [field]: val }
|
|
56
|
+
}
|
|
57
|
+
// a lane's tombstone names its inbox (K#8): an inbox switched off is never switched on again by a copy of THAT inbox
|
|
58
|
+
for (const [id, was] of Object.entries(map)) if (!seen.has(id) && !was.gone) map[id] = { at: now, gone: true, ...(field === 'lane' && was.lane && typeof was.lane.handle === 'string' ? { handle: was.lane.handle } : {}) }
|
|
59
|
+
}
|
|
60
|
+
stampMap(out.conns, ((cur && cur.conns) || []).filter((c) => c && c.id).map((c) => [String(c.id), c]), 'rec')
|
|
61
|
+
stampMap(out.a2a, Object.entries((cur && cur.a2a && cur.a2a.lanes) || {}), 'lane', laneForm)
|
|
62
|
+
// ⛔ an EMPTY Siri state on a device that never had one is "nothing yet", not a change: a fresh device would otherwise stamp its
|
|
63
|
+
// blank state newer than the account's and wipe Siri on every device. Once this device has held one, an empty one IS a change
|
|
64
|
+
// (Siri turned off everywhere — wb.siri.revoke()).
|
|
65
|
+
const siri = cur && cur.siri ? cur.siri : null
|
|
66
|
+
const blank = !siri || (!siri.token && !Object.keys(siri.rooms || {}).length)
|
|
67
|
+
if (siri && !(blank && !p.siri) && (!p.siri || canon(p.siri.state) !== canon(siri))) {
|
|
68
|
+
// WHAT WAS TAKEN OFF IS RECORDED (state machines pass 9, K#8): the entry merges Space by Space, so a Space this device had
|
|
69
|
+
// and no longer has is marked `gone`; a blank state (Delete Siri setup) marks every Space and bumps `rev` — the old key
|
|
70
|
+
// and its Spaces never come back from a copy made before the delete.
|
|
71
|
+
const was = (p.siri && p.siri.state && p.siri.state.rooms) || {}
|
|
72
|
+
const off = Object.fromEntries(Object.keys(was).filter((r) => !(siri.rooms || {})[r]).map((r) => [r, Math.max(now, num(Number(was[r] && was[r].at)) + 1)]))
|
|
73
|
+
const gone = unionMarks(p.siri && p.siri.gone, off), rev = num(Number(p.siri && p.siri.rev)) + (blank && p.siri ? 1 : 0)
|
|
74
|
+
out.siri = { at: now, state: siri, ...(Object.keys(gone).length ? { gone } : {}), ...(rev ? { rev } : {}) }
|
|
75
|
+
}
|
|
76
|
+
return out
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
// per entry: last writer wins, a tie goes to the tombstone, past 300 tombstones the oldest go (keptMerge.js newerEntry / mergeEntries)
|
|
80
|
+
// ⛔ A LANE AND SIRI MERGE BY THEIR PARTS (state machines pass 9, K#8): their unit was the WHOLE lane and the WHOLE Siri state,
|
|
81
|
+
// last writer wins — two devices that changed one lane inside one interval: the later stamp won, an agent removed on one came
|
|
82
|
+
// back from the other (and the next push granted it again), an agent let in on one was dropped (and revoked); Siri the same
|
|
83
|
+
// per Space. Now:
|
|
84
|
+
// · two copies of ONE inbox (same handle) are one lane — the newer's name and rules, the agents of both by id, and an agent
|
|
85
|
+
// either copy REMOVED (`removed`, a2aCore.js removePeerIn) never comes back: a2aCore.js mergeA2ARecords' rules;
|
|
86
|
+
// · a lane's tombstone names its inbox, and wins over any copy of that inbox whatever the clocks say (a handle is never
|
|
87
|
+
// reused — switching on again mints a new one);
|
|
88
|
+
// · Siri: the Spaces of both, less those a copy took off after they were made (`gone`); the copy with the higher `rev` (a
|
|
89
|
+
// Delete Siri setup) decides the key, and a copy made before that delete brings back none of its Spaces.
|
|
90
|
+
// (C3, the app's rule adopted: of the Spaces left, a Space whose newer copy is from before its `gone` mark is the other copy's
|
|
91
|
+
// when that one was made after the mark — a Space switched on again was lost; and a tie in `rev` keeps a key either copy has.)
|
|
92
|
+
function laneEntry (x, y) {
|
|
93
|
+
if (!x || !y) return x || y
|
|
94
|
+
if (!x.gone && !y.gone && x.lane && y.lane && x.lane.handle === y.lane.handle) {
|
|
95
|
+
const base = newer(x, y), other = base === x ? y : x
|
|
96
|
+
return { at: Math.max(num(x.at), num(y.at)), lane: mergePeers(base.lane, other.lane) }
|
|
97
|
+
}
|
|
98
|
+
const tomb = x.gone ? x : y.gone ? y : null, live = tomb === x ? y : x
|
|
99
|
+
if (tomb && !live.gone && tomb.handle && live.lane && live.lane.handle === tomb.handle) return tomb
|
|
100
|
+
return newer(x, y)
|
|
101
|
+
}
|
|
102
|
+
function siriEntry (x, y) {
|
|
103
|
+
if (!x || !y) return x || y || null
|
|
104
|
+
const base = newer(x, y), other = base === x ? y : x
|
|
105
|
+
const rev = Math.max(num(Number(x.rev)), num(Number(y.rev))), gone = unionMarks(x.gone, y.gone)
|
|
106
|
+
const atRev = [base, other].filter((e) => num(Number(e.rev)) === rev && e.state) // a copy from before a delete brings nothing back
|
|
107
|
+
const roomsOf = (e) => (atRev.includes(e) ? e.state.rooms || {} : {})
|
|
108
|
+
const rooms = mergeSiriRooms(roomsOf(base), roomsOf(other), gone) // the newer's copy of a Space while it outlives its mark
|
|
109
|
+
const lead = atRev[0] ? atRev[0].state : { token: '', defaultRoom: '' }
|
|
110
|
+
const keyOf = (e) => ({ token: e.state ? e.state.token : '', rev: e.rev })
|
|
111
|
+
const def = siriDefaultOf(rooms, ...atRev.map((e) => e.state.defaultRoom))
|
|
112
|
+
return { at: Math.max(num(x.at), num(y.at)), state: { ...lead, token: siriKeyOf(keyOf(base), keyOf(other)), defaultRoom: def, rooms }, ...(Object.keys(gone).length ? { gone } : {}), ...(rev ? { rev } : {}) }
|
|
113
|
+
}
|
|
114
|
+
/** The union of two views, the newer of each entry kept (a lane and Siri: merged by their parts). Pure — the whole agreement between devices is here. */
|
|
115
|
+
export function mergeKeep (a, b) {
|
|
116
|
+
const x = normKeep(a), y = normKeep(b)
|
|
117
|
+
return { v: 1, conns: mergeMap(x.conns, y.conns), a2a: mergeMap(x.a2a, y.a2a, laneEntry), siri: siriEntry(x.siri, y.siri) }
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/** What the vault holds from a merged view: { conns: [rec], siri: state | null, a2a: { lanes } }. */
|
|
121
|
+
export function viewOfKeep (k) {
|
|
122
|
+
const x = normKeep(k)
|
|
123
|
+
return {
|
|
124
|
+
conns: Object.values(x.conns).filter((e) => e && !e.gone && e.rec).map((e) => e.rec),
|
|
125
|
+
siri: x.siri && x.siri.state ? x.siri.state : null,
|
|
126
|
+
a2a: { lanes: Object.fromEntries(Object.entries(x.a2a).filter(([, e]) => e && !e.gone && e.lane).map(([room, e]) => [room, e.lane])) },
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
export const sameKeep = (a, b) => canon(normKeep(a)) === canon(normKeep(b))
|
|
130
|
+
|
|
131
|
+
// ── THE SAME KEEP IN THE SPACES APP'S FORMAT (docs/sdk-account-format-plan.md phase 4; the owner, 2026-11-13: "yes. Do 1-5") ──
|
|
132
|
+
// Beside KEEP_DOC the account's index room holds the app's `xindex2` (index2Doc: `connections` + `connGone`, `siri`, `a2a`),
|
|
133
|
+
// sealed under the app's account-store key (loc.app — sdkAccount.js _where, as phase 3's `xindex`). A pass READS BOTH and writes
|
|
134
|
+
// BOTH: KEEP_DOC stays for every kit built from an older SDK (they read only it). TRANSLATE, DO NOT DROP: a keep entry's stamp is
|
|
135
|
+
// the app record's `at` (a connection's, a lane's, Siri's — an added field the app's normal forms ignore), a tombstone is the
|
|
136
|
+
// app's removal mark (`connGone[id]`, `a2a.gone[handle]`), Siri's `gone`/`rev` are the app's own. The rules stay keptMerge.js's:
|
|
137
|
+
// the app's mark rule (an entry is off when a mark is as new) is the keep's tie-goes-to-the-tombstone.
|
|
138
|
+
const obj = (x) => (x && typeof x === 'object' && !Array.isArray(x) ? x : {})
|
|
139
|
+
/** The app's `xindex2` (as read; none → empty) → { keep, laneGone }: a keep view, and the inboxes the doc says were switched off
|
|
140
|
+
* (`a2a.gone` is by handle, not by lane — applied by dropGoneLanes). A stub (`held`, no callKey) is not a key: left out. */
|
|
141
|
+
export function appToKeep (doc) {
|
|
142
|
+
const d = obj(doc), conns = {}, a2a = {}
|
|
143
|
+
for (const [id, c] of Object.entries(obj(d.connections))) {
|
|
144
|
+
if (!c || typeof c.callKey !== 'string' || !c.callKey) continue
|
|
145
|
+
const { at, held: _h, ...rec } = c
|
|
146
|
+
conns[id] = { at: num(Number(at)), rec: { id, ...rec } }
|
|
147
|
+
}
|
|
148
|
+
for (const [id, at] of Object.entries(obj(d.connGone))) if (num(Number(at))) conns[id] = newer(conns[id], { at: Number(at), gone: true })
|
|
149
|
+
for (const [room, l] of Object.entries(obj(obj(d.a2a).lanes))) { if (!l || typeof l !== 'object') continue; const { at, ...lane } = l; a2a[room] = { at: num(Number(at)), lane } }
|
|
150
|
+
const s = obj(d.siri), { at: sAt, gone, rev, ...st } = s
|
|
151
|
+
const marks = unionMarks(gone, null), r = num(Number(rev))
|
|
152
|
+
const siri = (st.token || Object.keys(obj(st.rooms)).length || Object.keys(marks).length || r)
|
|
153
|
+
? { at: num(Number(sAt)), state: { token: typeof st.token === 'string' ? st.token : '', defaultRoom: typeof st.defaultRoom === 'string' ? st.defaultRoom : '', rooms: obj(st.rooms) }, ...(Object.keys(marks).length ? { gone: marks } : {}), ...(r ? { rev: r } : {}) }
|
|
154
|
+
: null
|
|
155
|
+
return { keep: { v: 1, conns, a2a, siri }, laneGone: unionMarks(obj(d.a2a).gone, null) }
|
|
156
|
+
}
|
|
157
|
+
/** A lane whose inbox a mark switched off becomes its tombstone (laneEntry's rule: it wins over any copy of that inbox). */
|
|
158
|
+
export function dropGoneLanes (keep, laneGone) {
|
|
159
|
+
const k = normKeep(keep), a2a = { ...k.a2a }
|
|
160
|
+
for (const [room, e] of Object.entries(a2a)) {
|
|
161
|
+
const h = e && !e.gone && e.lane && e.lane.handle
|
|
162
|
+
if (h && laneGone && laneGone[h]) a2a[room] = { at: Math.max(num(e.at), num(Number(laneGone[h]))), gone: true, handle: h }
|
|
163
|
+
}
|
|
164
|
+
return { ...k, a2a }
|
|
165
|
+
}
|
|
166
|
+
/** A merged keep → the app's `xindex2`. `prev` = the doc as read: its marks are kept (a mark only it had stays), and the sections
|
|
167
|
+
* a vault does not keep (contacts, events, todos, code) are carried as they were. */
|
|
168
|
+
export function keepToApp (keep, prev = null) {
|
|
169
|
+
const k = normKeep(keep), p = obj(prev), connections = {}, gone = {}, lanes = {}, laneGone = {}
|
|
170
|
+
for (const [id, e] of Object.entries(k.conns)) {
|
|
171
|
+
if (e && e.gone) gone[id] = num(e.at) || 1
|
|
172
|
+
else if (e && e.rec) { const { id: _id, ...rec } = e.rec; connections[id] = { ...rec, at: num(e.at) } }
|
|
173
|
+
}
|
|
174
|
+
for (const [room, e] of Object.entries(k.a2a)) {
|
|
175
|
+
if (e && e.gone) { if (typeof e.handle === 'string' && e.handle) laneGone[e.handle] = num(e.at) || 1 } else if (e && e.lane) lanes[room] = { ...e.lane, at: num(e.at) }
|
|
176
|
+
}
|
|
177
|
+
const connGone = unionMarks(obj(p.connGone), gone, MAX_TOMBS), aGone = unionMarks(obj(obj(p.a2a).gone), laneGone, MAX_TOMBS)
|
|
178
|
+
for (const [id, at] of Object.entries(connGone)) if (connections[id] && num(connections[id].at) <= at) delete connections[id] // the app's rule: a mark as new takes it off
|
|
179
|
+
const s = k.siri
|
|
180
|
+
const siri = s && s.state ? { ...s.state, ...(s.gone ? { gone: s.gone } : {}), ...(s.rev ? { rev: s.rev } : {}), at: num(s.at) } : { token: '', defaultRoom: '', rooms: {} }
|
|
181
|
+
const keepOr = (x, d) => (x === undefined ? d : x)
|
|
182
|
+
return index2Doc({ contacts: keepOr(p.contacts, []), events: keepOr(p.events, []), todos: keepOr(p.todos, []), code: keepOr(p.code, null), connections, connGone: Object.keys(connGone).length ? connGone : undefined, siri, a2a: { lanes, ...(Object.keys(aGone).length ? { gone: aGone } : {}) } })
|
|
183
|
+
}
|
|
184
|
+
/** The same doc, its write time aside. An unknown doc is never the same. */
|
|
185
|
+
const sameAppDoc = (a, b) => !!(a && b) && canon({ ...a, at: 0 }) === canon({ ...b, at: 0 })
|
|
186
|
+
|
|
187
|
+
/** One sync pass: stamp → read → merge → write if it moved (conditional) → the merged view.
|
|
188
|
+
* deps: { loc: { room, mk, master }, client (spaceClient: state(room, mk, name, patch?, summary?, by?, ifV?)), prev, cur, now? }
|
|
189
|
+
* → { ok: true, keep, own } | { ok: false, why, keep, own } (nothing written on a read that was not definitive).
|
|
190
|
+
* `keep` = the merged view as far as the pass got (it may hold the OTHER devices' entries, saved or not); `own` = this device's
|
|
191
|
+
* own view, stamped: `prev` + what changed here, never an entry `prev` and `cur` did not have. A caller that keeps a `prev`
|
|
192
|
+
* uses keepPass (below), which says which of the two it may record. */
|
|
193
|
+
export async function syncKeep ({ loc, client, prev, cur, now = Date.now }) {
|
|
194
|
+
const key = await keepKeyOf(loc.master)
|
|
195
|
+
const own = stampKeep(prev, cur, now())
|
|
196
|
+
let local = own
|
|
197
|
+
for (let i = 0; i < 4; i++) {
|
|
198
|
+
let r
|
|
199
|
+
try { r = await client.state(loc.room, loc.mk, KEEP_DOC) } catch (e) { return { ok: false, why: 'unreadable', keep: local, own } }
|
|
200
|
+
if (!r || r.status !== 200) return { ok: false, why: 'unreadable', status: r && r.status, keep: local, own }
|
|
201
|
+
const v = Number.isInteger(r.v) ? r.v : 0
|
|
202
|
+
let remote = null
|
|
203
|
+
const st = r.state
|
|
204
|
+
if (!(st == null || (typeof st === 'object' && !Object.keys(st).length))) { try { remote = normKeep(await openDoc(key, st)) } catch { return { ok: false, why: 'unopenable', keep: local, own } } }
|
|
205
|
+
// READ-THROUGH (phase 4): with the app's key (loc.app), the app's `xindex2` is read too — the same clobber rule: unknown is not empty
|
|
206
|
+
let x = null
|
|
207
|
+
if (loc.app) {
|
|
208
|
+
let rx
|
|
209
|
+
try { rx = await client.state(loc.room, loc.mk, APP_KEEP_DOC) } catch { return { ok: false, why: 'unreadable', keep: local, own } }
|
|
210
|
+
if (!rx || rx.status !== 200) return { ok: false, why: 'unreadable', status: rx && rx.status, keep: local, own }
|
|
211
|
+
const sx = rx.state
|
|
212
|
+
x = { doc: null, v: Number.isInteger(rx.v) ? rx.v : 0 }
|
|
213
|
+
if (!(sx == null || (typeof sx === 'object' && !Object.keys(sx).length))) { try { x.doc = await openDoc(loc.app, sx) } catch { return { ok: false, why: 'unopenable', keep: local, own } } }
|
|
214
|
+
}
|
|
215
|
+
const fromApp = x ? appToKeep(x.doc) : null
|
|
216
|
+
const merged = fromApp ? dropGoneLanes(mergeKeep(mergeKeep(local, remote), fromApp.keep), fromApp.laneGone) : mergeKeep(local, remote)
|
|
217
|
+
// DUAL WRITE: the keep's own doc for every older kit, then the app's; each only when it differs from what it holds, each over
|
|
218
|
+
// the version read. A 409 on either reads both and merges again; a failed save on either is a pass that did not save.
|
|
219
|
+
const appDoc = x ? keepToApp(merged, x.doc) : null
|
|
220
|
+
const writes = [[!(remote && sameKeep(merged, remote)), KEEP_DOC, key, merged, v, 'vault keep'], [!!x && !sameAppDoc(appDoc, x.doc), APP_KEEP_DOC, loc.app, appDoc && { ...appDoc, at: now() }, x && x.v, 'index2']]
|
|
221
|
+
let raced = false
|
|
222
|
+
for (const [differs, name, k, body, ver, sum] of writes) {
|
|
223
|
+
if (!differs) continue
|
|
224
|
+
const w = await client.state(loc.room, loc.mk, name, await sealDoc(k, body), sum, 'device', ver).catch(() => null)
|
|
225
|
+
if (w && w.status === 409) { raced = true; break } // another device wrote between: read and merge again
|
|
226
|
+
if (!w || w.status !== 200) return { ok: false, why: 'save_failed', status: w && w.status, keep: merged, own }
|
|
227
|
+
}
|
|
228
|
+
if (raced) { local = merged; continue }
|
|
229
|
+
return { ok: true, keep: merged, own }
|
|
230
|
+
}
|
|
231
|
+
return { ok: false, why: 'kept_changing', keep: local, own }
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
/** THE STORES ARE THE STORAGE'S, AND EVERY TAB OF A VAULT SHARES IT (state machines pass 9, K#1). A builder's app open in two
|
|
235
|
+
* tabs is two vault frames: each loaded connections, Siri and the lanes into memory ONCE, while `prev` is read from the
|
|
236
|
+
* shared storage at every pass. What tab A attached was in A's `prev`; tab B's pass compared it with ITS memory, read it as
|
|
237
|
+
* "removed here" and stamped it gone for every device — flapping each minute, and the callKey (or an inbox's private key)
|
|
238
|
+
* left the disk when B applied. A watch over the stores' keys: `moved()` → the keys ANOTHER writer changed since this tab
|
|
239
|
+
* last looked (each reported once); `wrote(key)` after this tab's own write. The vault re-reads a moved store before any
|
|
240
|
+
* look at it (vault-core.js adoptOtherTab), so a pass never mistakes another tab's change for this device's. */
|
|
241
|
+
export function tabStores (st, keys) {
|
|
242
|
+
const raw = (k) => { try { return st.getItem(k) } catch { return null } }
|
|
243
|
+
const seen = new Map(keys.map((k) => [k, raw(k)]))
|
|
244
|
+
return {
|
|
245
|
+
wrote (k) { seen.set(k, raw(k)) },
|
|
246
|
+
moved () { const out = []; for (const k of keys) { const now = raw(k); if (now !== seen.get(k)) { seen.set(k, now); out.push(k) } } return out },
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
// What a vault holds, in one comparable shape: the connections by id (their order is not a change), Siri, the lanes.
|
|
251
|
+
const heldOf = (c) => ({
|
|
252
|
+
conns: Object.fromEntries(((c && c.conns) || []).filter((x) => x && x.id).map((x) => [String(x.id), x])),
|
|
253
|
+
siri: (c && c.siri) || null,
|
|
254
|
+
a2a: (c && c.a2a && c.a2a.lanes) || {},
|
|
255
|
+
})
|
|
256
|
+
const sameHeld = (a, b) => canon(heldOf(a)) === canon(heldOf(b))
|
|
257
|
+
|
|
258
|
+
/** A VAULT'S WHOLE PASS: the sync, and what the vault may do with its answer. vault-core.js keepSync runs this.
|
|
259
|
+
* ⛔ `prev` MEANS "WHAT THIS DEVICE HOLDS": stampKeep reads an entry that `prev` has and the device lacks as REMOVED HERE, and
|
|
260
|
+
* stamps it gone for every device. So a merged view — it carries the other devices' entries — becomes `prev` only when it is
|
|
261
|
+
* also PUT INTO the vault. Two ways that was broken (sync sweep 2026-11-12):
|
|
262
|
+
* #1 a pass that did not save (save_failed, kept_changing, a read that failed after a lost race) was recorded but not applied:
|
|
263
|
+
* the next pass stamped every other device's connection, Siri and outside agent gone — deleted on EVERY device of the account;
|
|
264
|
+
* #2 the merged view is made from the state read BEFORE the round trip, and applying it replaces the vault's stores: a
|
|
265
|
+
* connection attached meanwhile was dropped (its callKey with it), a detach made meanwhile was undone.
|
|
266
|
+
* The rule: the merged view is recorded and applied only by a pass that SAVED and during which the vault did NOT change.
|
|
267
|
+
* Any other pass records this device's own stamped view (`own` — what changed here keeps the time it was first seen) and
|
|
268
|
+
* applies nothing; a vault that changed meanwhile is synced again (`again`).
|
|
269
|
+
* deps: syncKeep's, with `read()` → { conns, siri, a2a } (the vault's stores NOW) in place of `cur`, and `settle(answer)`:
|
|
270
|
+
* where the vault records and applies. It runs in the SAME synchronous step as the "did the vault change?" check, so nothing
|
|
271
|
+
* can be attached or detached between the check and the apply.
|
|
272
|
+
* → syncKeep's answer + { record: the view to keep as `prev`, apply: the merged view to put into the stores | null, again } */
|
|
273
|
+
export async function keepPass ({ loc, client, prev, read, now = Date.now, settle }) {
|
|
274
|
+
const cur = JSON.parse(JSON.stringify(read() || {})) // a copy: what the pass is given must not move under it
|
|
275
|
+
const r = await syncKeep({ loc, client, prev, cur, now })
|
|
276
|
+
// ── no await from here to the end of `settle` ──
|
|
277
|
+
const moved = !sameHeld(cur, read())
|
|
278
|
+
const out = { ...r, ...settleOf({ ok: r.ok, moved, keep: r.keep, own: r.own, prev, same: sameKeep }) }
|
|
279
|
+
if (typeof settle === 'function') settle(out)
|
|
280
|
+
return out
|
|
281
|
+
}
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
// vaultSealedStore.js — the BUILDERS' vault (vault-core.js) keeps its other secrets sealed on disk too, as our hosted vault does
|
|
2
|
+
// (protectedLocal.js, sealed by default since 2026-11-16). The owner, 2026-11-24: "Yes" to "bring the builders' vault to our rule".
|
|
3
|
+
//
|
|
4
|
+
// vaultAtRest.js seals the room list's keys and the backup state. The rest of `wbvault:*` was written clear: the sign-in session,
|
|
5
|
+
// the invite box's PRIVATE key, the Siri key, outside agents' tokens, the connections' call keys (and those still being granted),
|
|
6
|
+
// and the merged view that carries them across devices. A copy of this origin's localStorage alone handed them over.
|
|
7
|
+
//
|
|
8
|
+
// `sealedStorage(raw, names)` is a Storage with the same three calls the vault uses (getItem / setItem / removeItem). For a name
|
|
9
|
+
// in `names`, once `open(key)` ran: what is read comes from memory (opened at start), what is written is kept in memory at once and
|
|
10
|
+
// sealed to disk in the order written (`flushed()` resolves once it is there). Every other name passes through untouched.
|
|
11
|
+
// · Read-through, never destructive: a clear value an older vault wrote is read as it is and written back sealed; an entry no key
|
|
12
|
+
// here opens reads as absent and is KEPT on disk — moved aside to `<name>:unopened` before anything is written over it.
|
|
13
|
+
// · No key (no IndexedDB this launch): everything passes through as before — a secret is never lost for want of a seal. The
|
|
14
|
+
// vault refuses to start keyless over sealed data (vaultAtRest.holdsSealed, given these names).
|
|
15
|
+
// · Another tab's write: `refresh(name)` re-reads that name from disk (the vault's `storage` listener calls it first).
|
|
16
|
+
// Under the same key as the room list (deviceWrapKey: non-extractable, in this origin's IndexedDB) — so, like it, a copy of the whole
|
|
17
|
+
// browser profile still opens it; the person's passkey lock (vaultCoreLock.js) is the answer to that.
|
|
18
|
+
import { seal, open as openSealed, isSealed } from './deviceSeal.js'
|
|
19
|
+
|
|
20
|
+
const parse = (s) => { try { return JSON.parse(s) } catch { return undefined } }
|
|
21
|
+
|
|
22
|
+
export function sealedStorage (raw, names) {
|
|
23
|
+
const sealedNames = new Set(names)
|
|
24
|
+
const mem = new Map() // name → the clear string, as setItem got it
|
|
25
|
+
const unopened = new Set() // names whose disk value no key here opens (kept as it is)
|
|
26
|
+
let key = null
|
|
27
|
+
let chain = Promise.resolve()
|
|
28
|
+
const onDisk = (fn) => { const p = chain.then(fn); chain = p.catch(() => {}); return p }
|
|
29
|
+
const ours = (n) => key && sealedNames.has(String(n))
|
|
30
|
+
|
|
31
|
+
async function load (n) {
|
|
32
|
+
let v = null; try { v = raw.getItem(n) } catch { v = null }
|
|
33
|
+
mem.delete(n); unopened.delete(n)
|
|
34
|
+
if (v == null) return false
|
|
35
|
+
const blob = parse(v)
|
|
36
|
+
if (!isSealed(blob)) { mem.set(n, v); return true } // an older vault's clear value: read as it is (open() writes it back sealed)
|
|
37
|
+
try { const s = await openSealed(key, blob); if (typeof s === 'string') mem.set(n, s); else unopened.add(n) } catch { unopened.add(n) }
|
|
38
|
+
return false
|
|
39
|
+
}
|
|
40
|
+
function putSealed (n, s) {
|
|
41
|
+
return onDisk(async () => {
|
|
42
|
+
if (unopened.has(n)) { // another key's entry is never written over and lost
|
|
43
|
+
try { const was = raw.getItem(n); if (was != null) raw.setItem(n + ':unopened', was) } catch { /* */ }
|
|
44
|
+
unopened.delete(n)
|
|
45
|
+
}
|
|
46
|
+
if (s == null) { try { raw.removeItem(n) } catch { /* */ } return }
|
|
47
|
+
const blob = await seal(key, s)
|
|
48
|
+
if (mem.get(n) !== s) return // written again meanwhile: the later write is queued behind this one
|
|
49
|
+
try { raw.setItem(n, JSON.stringify(blob)) } catch { /* a full or blocked store: memory holds it this session */ }
|
|
50
|
+
})
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
return {
|
|
54
|
+
/** Start sealing under `k` (null: pass everything through, as before). Opens every sealed name; seals the clear ones. */
|
|
55
|
+
async open (k) {
|
|
56
|
+
key = k || null
|
|
57
|
+
if (!key) return
|
|
58
|
+
for (const n of sealedNames) if (await load(n)) putSealed(n, mem.get(n))
|
|
59
|
+
await chain
|
|
60
|
+
},
|
|
61
|
+
getItem (n) { if (!ours(n)) return raw.getItem(n); return mem.has(n) ? mem.get(n) : null },
|
|
62
|
+
setItem (n, v) { if (!ours(n)) return raw.setItem(n, v); const s = String(v); mem.set(n, s); putSealed(n, s) },
|
|
63
|
+
removeItem (n) { if (!ours(n)) return raw.removeItem(n); mem.delete(n); putSealed(n, null) },
|
|
64
|
+
/** Another tab wrote `n`: read it again from disk (after this tab's own writes). */
|
|
65
|
+
refresh (n) { return ours(n) ? onDisk(() => load(n)) : Promise.resolve() },
|
|
66
|
+
/** Resolves once every write made so far is on disk. */
|
|
67
|
+
flushed: () => chain,
|
|
68
|
+
async durableItem (n) {
|
|
69
|
+
await chain
|
|
70
|
+
const value = raw.getItem(n), blob = parse(value)
|
|
71
|
+
return ours(n) && isSealed(blob) ? openSealed(key, blob) : value
|
|
72
|
+
},
|
|
73
|
+
/** Whether any of `names` holds a sealed value on disk (a keyless start must not run over it). */
|
|
74
|
+
holdsSealed: () => [...sealedNames].some((n) => { try { return isSealed(parse(raw.getItem(n))) } catch { return false } }),
|
|
75
|
+
get raw () { return raw },
|
|
76
|
+
}
|
|
77
|
+
}
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
// vaultWorkerHost.js — ONE HOST FOR A VAULT'S ROOM-KEY WORKER (docs/vault-core-convergence-review.md, option C, C1).
|
|
2
|
+
// Our hosted vault (vault-loader.js) and the builders' vault (vault-core.js) each start the same l1-worker and each wrote
|
|
3
|
+
// its own liveness, restart and replay — and each had its own bug there: the core never pinged, so a worker iOS reclaimed
|
|
4
|
+
// hung every call (sync sweep 2026-10-18 #7); ours replayed too little, so attested rooms stayed dark until a relaunch
|
|
5
|
+
// (2026-11-08). Now both ask this module. It owns: making the worker (the CALLER's factory — ours pins the source,
|
|
6
|
+
// vcWorker.js), the heartbeat (workerLiveness.js, the same as the regular app's l1.js), the restart, and a REPLAY LIST
|
|
7
|
+
// each vault registers into: what a new worker must be told before anything else reaches it.
|
|
8
|
+
//
|
|
9
|
+
// It holds no key and decides nothing about trust: a replay step reads the caller's own state when it runs.
|
|
10
|
+
//
|
|
11
|
+
// createWorkerHost({ make, onMessage, onCurrent, onRestart, onRestarted, graceMs, beatMs, timers, doc }) → host
|
|
12
|
+
// make() → Worker; called synchronously (a network round trip in front of it races the heartbeat, vcWorker.js)
|
|
13
|
+
// onMessage(ev, w) the worker's messages, except the heartbeat's `pong` (the host takes those)
|
|
14
|
+
// onCurrent(w|null) the current worker changed (made, dropped) — the caller keeps its own handle in step
|
|
15
|
+
// onRestart() the heartbeat found the worker dead: fail what waits on it (before the new one exists)
|
|
16
|
+
// onRestarted(w) the new worker exists and its replay has been sent — tell whoever must hand back what only it held
|
|
17
|
+
// host.replay(name, step) register `step(w)` (order = registration order; the same name replaces in place). A step
|
|
18
|
+
// that returns a promise holds the steps after it (the core awaits its enclave and open).
|
|
19
|
+
// host.ensure() the worker; made and replayed when there is none. Synchronous.
|
|
20
|
+
// host.start() replace the worker with a new one (no onRestart) and resolve once its replay is done
|
|
21
|
+
// host.restart() what a missed pong does: onRestart, a new worker, its replay, onRestarted. No worker → nothing.
|
|
22
|
+
// host.drop() terminate and forget it (a sign-out); nothing restarts until ensure()/start()
|
|
23
|
+
// host.tick() send a ping now (the beat and the page's return to the foreground call it)
|
|
24
|
+
// host.worker the current worker or null; host.replays() the registered names, in order
|
|
25
|
+
import { createLiveness } from './workerLiveness.js'
|
|
26
|
+
|
|
27
|
+
export function createWorkerHost ({ make, onMessage = () => {}, onCurrent = () => {}, onRestart = () => {}, onRestarted = () => {}, graceMs = 5000, beatMs = 25000, timers = globalThis, doc = typeof document !== 'undefined' ? document : null } = {}) {
|
|
28
|
+
if (typeof make !== 'function') throw new Error('createWorkerHost: make() is required')
|
|
29
|
+
let worker = null
|
|
30
|
+
let started = Promise.resolve()
|
|
31
|
+
const steps = []
|
|
32
|
+
const set = (w) => { worker = w; try { onCurrent(w) } catch { /* the caller's mirror; never stops the host */ } }
|
|
33
|
+
function runReplay (w) {
|
|
34
|
+
let chain = null
|
|
35
|
+
for (const { step } of steps) {
|
|
36
|
+
if (chain) { chain = chain.then(() => (worker === w ? step(w) : undefined)); continue }
|
|
37
|
+
let r
|
|
38
|
+
try { r = step(w) } catch { r = undefined } // one step that throws never keeps the others from a new worker
|
|
39
|
+
if (r && typeof r.then === 'function') chain = Promise.resolve(r)
|
|
40
|
+
}
|
|
41
|
+
return chain || Promise.resolve()
|
|
42
|
+
}
|
|
43
|
+
function make1 () {
|
|
44
|
+
const w = make()
|
|
45
|
+
set(w)
|
|
46
|
+
w.onmessage = (ev) => {
|
|
47
|
+
const m = (ev && ev.data) || {}
|
|
48
|
+
if (m.t === 'pong') { live.pong(m.n); return } // the heartbeat's answer
|
|
49
|
+
onMessage(ev, w)
|
|
50
|
+
}
|
|
51
|
+
started = runReplay(w)
|
|
52
|
+
started.catch(() => { /* the caller awaits start(); a restart's replay that fails waits for the next beat */ })
|
|
53
|
+
return w
|
|
54
|
+
}
|
|
55
|
+
const terminate = () => { const w = worker; set(null); try { if (w) w.terminate() } catch { /* already gone */ } }
|
|
56
|
+
const live = createLiveness({
|
|
57
|
+
ping: (n) => { if (worker) worker.postMessage({ t: 'ping', n }) },
|
|
58
|
+
restart: () => host.restart(),
|
|
59
|
+
setTimeout: (f, ms) => timers.setTimeout(f, ms),
|
|
60
|
+
graceMs,
|
|
61
|
+
isHidden: () => !!(doc && doc.hidden),
|
|
62
|
+
})
|
|
63
|
+
const host = {
|
|
64
|
+
get worker () { return worker },
|
|
65
|
+
replays: () => steps.map((s) => s.name),
|
|
66
|
+
replay (name, step) {
|
|
67
|
+
const at = steps.findIndex((s) => s.name === name)
|
|
68
|
+
if (at >= 0) steps[at] = { name, step }; else steps.push({ name, step })
|
|
69
|
+
return host
|
|
70
|
+
},
|
|
71
|
+
ensure () { return worker || make1() },
|
|
72
|
+
async ready () {
|
|
73
|
+
const current = worker
|
|
74
|
+
await started
|
|
75
|
+
if (!current || worker !== current) throw Object.assign(new Error('the room worker was replaced'), { code: 'worker_restarted' })
|
|
76
|
+
return current
|
|
77
|
+
},
|
|
78
|
+
start () { terminate(); make1(); return started },
|
|
79
|
+
restart () {
|
|
80
|
+
if (!worker) return // dropped (signed out): nothing to bring back
|
|
81
|
+
try { onRestart() } catch { /* */ }
|
|
82
|
+
terminate()
|
|
83
|
+
let w
|
|
84
|
+
try { w = make1() } catch { return } // the next beat tries again
|
|
85
|
+
try { onRestarted(w) } catch { /* */ }
|
|
86
|
+
},
|
|
87
|
+
drop () { terminate() },
|
|
88
|
+
tick () { if (worker) live.tick() },
|
|
89
|
+
pong: (n) => live.pong(n),
|
|
90
|
+
}
|
|
91
|
+
try {
|
|
92
|
+
if (doc && beatMs > 0) {
|
|
93
|
+
timers.setInterval(() => host.tick(), beatMs)
|
|
94
|
+
doc.addEventListener('visibilitychange', () => { if (!doc.hidden) host.tick() })
|
|
95
|
+
}
|
|
96
|
+
} catch { /* no timers */ }
|
|
97
|
+
return host
|
|
98
|
+
}
|
package/vcWorker.js
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
// vcWorker.js — construct the key-holding Worker from source we already trust, with no runtime fetch.
|
|
2
|
+
//
|
|
3
|
+
// THE GAP. `new Worker(url)` accepts no `integrity`, and import maps are per-realm so the document's map never
|
|
4
|
+
// reaches a worker. `worker-src 'self'` is therefore the only workable policy — and `'self'` lets a compromised
|
|
5
|
+
// origin serve a swapped `l1-worker.js` straight into the realm that holds mk. Worse, a worker fetched by URL takes
|
|
6
|
+
// its CSP from its OWN response headers, so the document's connect-src does not restrain where it sends what it
|
|
7
|
+
// reads. Every other script on the page is pinned by hash; this one was not.
|
|
8
|
+
//
|
|
9
|
+
// THE FIX, AND WHY IT IS SHAPED LIKE THIS. The source arrives as a MODULE (`l1-worker-src.js`, generated at deploy
|
|
10
|
+
// by tools/build-verified-workers.mjs) that exports it as a string. So it is pinned exactly like every other
|
|
11
|
+
// module — an SRI entry, an import-map integrity key, and a hash in the enforced policy — and there is nothing to
|
|
12
|
+
// fetch, nothing to verify here, and no failure branch.
|
|
13
|
+
//
|
|
14
|
+
// ⚠ THE PREVIOUS ATTEMPT FETCHED AND HASHED THE BUNDLE AT RUNTIME, AND IT TOOK EVERY ROOM DOWN ON iOS. Worker
|
|
15
|
+
// creation sat behind a network round trip, inside a 5s liveness watchdog (vault-loader.js) that terminates and
|
|
16
|
+
// recreates a worker it believes is dead: on a slow link — or on iOS, where foregrounding fires that check
|
|
17
|
+
// mid-fetch — the watchdog killed a worker that did not exist yet, recreated it, and started another fetch. It
|
|
18
|
+
// never lived long enough to load keys. See design doc §14.5.
|
|
19
|
+
//
|
|
20
|
+
// So the property that matters here is not cryptographic, it is temporal: **this must stay SYNCHRONOUS.** Nothing
|
|
21
|
+
// in it may await. Keep it that way — a network round trip in front of worker creation is a change to somebody
|
|
22
|
+
// else's timeout, whether or not you were thinking about it.
|
|
23
|
+
// The deploy replaces the build placeholder everywhere in the tree, this file too — so the needle is built in two halves.
|
|
24
|
+
const UNSTAMPED = '__SPACES' + '_BUILD__'
|
|
25
|
+
export function makeVerifiedWorker (src, fallbackUrl, opts) {
|
|
26
|
+
// No source compiled in: ONLY an unbuilt tree (dev, the tests) may load the worker by URL. A DEPLOYED build always bundles it
|
|
27
|
+
// (deploy.sh / build-vault.sh run tools/build-verified-workers.mjs); one without it is broken or tampered with, and a URL worker
|
|
28
|
+
// there is exactly the unpinned load this file exists to close — refused, as the builders' vault refuses (sync sweep 2026-11-14 P8).
|
|
29
|
+
if (typeof src !== 'string' || src.length < 1000) {
|
|
30
|
+
if (!String(fallbackUrl || '').includes(UNSTAMPED)) throw new Error('the key worker\'s pinned source is missing from this build — refusing to load it by URL')
|
|
31
|
+
return new Worker(fallbackUrl, opts)
|
|
32
|
+
}
|
|
33
|
+
return new Worker(URL.createObjectURL(new Blob([src], { type: 'text/javascript' })), opts)
|
|
34
|
+
}
|