@witbitz/sdk 0.0.0-stage → 4.4.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 +221 -0
- package/a2aShared.js +27 -0
- package/accountErase.js +228 -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/agentDoorTools.js +28 -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 +165 -0
- package/chatLockSw.js +13 -0
- package/cloudDeviceBuilds.js +11 -0
- package/cloudDevicePins.js +33 -0
- package/cloudDeviceSeal.js +53 -0
- package/codeAttachments.js +100 -0
- package/codeBrowse.js +224 -0
- package/codeCache.js +149 -0
- package/codeCloud.js +650 -0
- package/codeCloudKeys.js +112 -0
- package/codeCommands.js +167 -0
- package/codeComputers.js +389 -0
- package/codeEgress.js +123 -0
- package/codeFilesRoutes.js +17 -0
- package/codeFolders.js +116 -0
- package/codeHistory.js +76 -0
- package/codeLanguage.js +54 -0
- package/codeMkdir.js +8 -0
- package/codeModes.js +59 -0
- package/codeOrphanKeys.js +42 -0
- package/codeOutputs.js +141 -0
- package/codeProgress.js +54 -0
- package/codeRelay.js +505 -0
- package/codeSent.js +68 -0
- package/codeSentinel.js +86 -0
- package/codeSubagents.js +107 -0
- package/codeTransport.js +317 -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 +561 -0
- package/credits.js +30 -0
- package/csAttest.js +112 -0
- package/decrypt.html +384 -0
- package/deviceAttest.js +527 -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 +113 -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 +91 -0
- package/l1-worker-src.js +2 -0
- package/l1-worker.js +894 -0
- package/laneAssociation.js +68 -0
- package/laneConfig.js +58 -0
- package/laneLinkCore.js +177 -0
- package/ledgerView.js +64 -0
- package/manifest.json +239 -0
- package/mcpRecommended.js +25 -0
- package/memberChange.js +125 -0
- package/mirrorBatch.js +47 -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/opRouting.js +10 -0
- package/opencodeWire.js +282 -0
- package/oprf.js +70 -0
- package/ownAgentLink.js +96 -0
- package/ownerPolicy.js +117 -0
- package/package.json +273 -4
- package/pdfOptions.js +13 -0
- package/pdfText.js +107 -0
- package/pdfjs.mjs +28 -0
- package/pdfjs.worker.mjs +28 -0
- package/pollVerdict.js +33 -0
- package/prefetchPoll.js +60 -0
- package/protectedLocal.js +426 -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/roomEmbed.js +111 -0
- package/roomName.js +177 -0
- package/roomPass.js +256 -0
- package/roomRoster.js +305 -0
- package/roomSettings.js +61 -0
- package/roomState.js +58 -0
- package/roomStreamClient.js +115 -0
- package/rosterCount.js +52 -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 +524 -0
- package/sdkAccount.js +483 -0
- package/sdkAccountDoc.js +89 -0
- package/sdkAccountSections.js +332 -0
- package/sdkAgui.js +141 -0
- package/sdkAttest.js +34 -0
- package/sdkBackup.js +507 -0
- package/sdkBackupV2.js +630 -0
- package/sdkBrowserPrivate.js +28 -0
- package/sdkBuilds.js +208 -0
- package/sdkCloudDevice.js +221 -0
- package/sdkComputers.js +1009 -0
- package/sdkDictation.js +232 -0
- package/sdkErase.js +288 -0
- package/sdkExports.js +71 -0
- package/sdkInvitations.js +34 -0
- package/sdkKeptAgent.js +188 -0
- package/sdkLaneLink.js +205 -0
- package/sdkPlan.js +96 -0
- package/sdkProtect.js +228 -0
- package/sdkRedact.js +36 -0
- package/sdkRekey.js +340 -0
- package/sdkReport.js +68 -0
- package/sdkSafeMedia.js +255 -0
- package/sdkSchedules.js +39 -0
- package/sdkSpeech.js +71 -0
- package/sdkTemporaryRooms.js +123 -0
- package/sdkTurn.js +117 -0
- package/sdkVault.js +180 -0
- package/sealShare.js +18 -0
- package/sealedNames.js +64 -0
- package/sealedReceipt.js +17 -0
- package/sentinelRelease.js +155 -0
- package/shamir.js +85 -0
- package/sharedViews.js +52 -0
- package/sheetChrome.js +450 -0
- package/siri.js +278 -0
- package/spaceClient.js +1429 -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/spaceTemplates.js +99 -0
- package/speechOut.js +102 -0
- package/splitKeyClient.js +90 -0
- package/store.js +656 -0
- package/streamHint.js +36 -0
- package/sttCloud.js +220 -0
- package/sttWorklet.js +38 -0
- package/sw-notif-core.js +540 -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 +37 -0
- package/usageReceipts.js +176 -0
- package/usageSummary.js +90 -0
- package/util.js +181 -0
- package/vault-core.js +2326 -0
- package/vault-kit.mjs +354 -0
- package/vault-screens.js +261 -0
- package/vaultAtRest.js +208 -0
- package/vaultCoreLock.js +111 -0
- package/vaultCorePush.js +140 -0
- package/vaultDeviceKey.js +95 -0
- package/vaultEnclaveHandoff.js +114 -0
- package/vaultKeep.js +287 -0
- package/vaultSealedStore.js +77 -0
- package/vaultWorkerHost.js +117 -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 +1460 -0
- package/witbitz-sdk.d.ts +1197 -0
- package/witbitz-sdk.js +4258 -0
- package/workerClient.js +16 -0
- package/workerLiveness.js +21 -0
- package/x509.js +218 -0
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
// accountIndexDoc.js — THE ACCOUNT INDEX'S RULES, pure (docs/sdk-account-format-plan.md, phase 1). The Spaces app keeps the
|
|
2
|
+
// account's room list in its index room (the sealed 'index' doc, `xindex`); these are the rules that build what a device writes
|
|
3
|
+
// there and fold what it reads back into its own list. They lived inside roomSync.js's push and sync, next to the page's storage;
|
|
4
|
+
// here they take state in and give state out — no storage, no DOM, no page state — so the SDK can run the same rules (phase 3).
|
|
5
|
+
// roomSync.js calls them; what the app writes and applies is unchanged (spaces/test/accountFormatGolden.test.mjs holds it).
|
|
6
|
+
|
|
7
|
+
const isTemp = (room) => String(room || '').startsWith('tmp-') // temp rooms never belong in the synced index (roomSync.js)
|
|
8
|
+
|
|
9
|
+
/** The entry this device writes for one of its rooms: `row` = its recents row, `prev` = the index's entry as read (or none),
|
|
10
|
+
* `key` = the key part ({ mk } / { split, userShare, commit? } / {} when the key worker injects it), `marks` = what this device
|
|
11
|
+
* knows of the room ({ help, gate, enclave }). Per-field last writer: a newer rename / archive / pin another device pushed is
|
|
12
|
+
* kept; the latest activity anywhere orders the list; a Help / verified / confidential mark is never taken off. */
|
|
13
|
+
export function indexRoomEntry (row, prev, key, { help = false, gate = '', enclave = false } = {}) {
|
|
14
|
+
const myTitle = (row.title && row.title !== 'Space' && row.title !== row.room) ? row.title : ''
|
|
15
|
+
const myAt = row.titleAt || 0
|
|
16
|
+
const keepRemote = prev && prev.title && (prev.titleAt || 0) > myAt // per-field LWW: don't clobber a newer rename another device pushed
|
|
17
|
+
const archNewer = !prev || (row.archivedAt || 0) >= (prev.archivedAt || 0) // newest archive/unarchive wins
|
|
18
|
+
const pinNewer = !prev || (row.pinnedAt || 0) >= (prev.pinnedAt || 0)
|
|
19
|
+
// KEPT ALWAYS ON by the account's cloud device (the owner, 2026-11-22: "We need to know in every device which rooms are always on"):
|
|
20
|
+
// a fact of the account, set by the device that handed the Space over or took it back — per field, newest wins, like a pin. Written
|
|
21
|
+
// only once it was ever set, so the doc of an account that never used it is byte-for-byte what it was (accountFormatGolden).
|
|
22
|
+
const aoAt = Math.max(row.alwaysOnAt || 0, (prev && prev.alwaysOnAt) || 0)
|
|
23
|
+
const aoOn = !prev || (row.alwaysOnAt || 0) >= (prev.alwaysOnAt || 0) ? !!row.alwaysOn : !!prev.alwaysOn
|
|
24
|
+
return {
|
|
25
|
+
...key,
|
|
26
|
+
title: keepRemote ? prev.title : myTitle, titleAt: keepRemote ? prev.titleAt : myAt, ...((keepRemote ? prev.manual : (myTitle && row.renamed)) ? { manual: true } : {}), // a name set by hand travels as such (roomTitle.js: never an impostor)
|
|
27
|
+
at: Math.max(row.at || 0, (prev && prev.at) || 0), // ordering: keep the LATEST activity across devices so the list order converges
|
|
28
|
+
archived: archNewer ? !!row.archived : !!prev.archived, archivedAt: Math.max(row.archivedAt || 0, (prev && prev.archivedAt) || 0),
|
|
29
|
+
pinned: pinNewer ? !!row.pinned : !!(prev && prev.pinned), pinnedAt: Math.max(row.pinnedAt || 0, (prev && prev.pinnedAt) || 0),
|
|
30
|
+
...(aoAt ? { alwaysOn: aoOn, alwaysOnAt: aoAt } : {}),
|
|
31
|
+
...((help || (prev && prev.help)) ? { help: 1 } : {}), // THE HELP SPACE: other devices open THIS one rather than make another
|
|
32
|
+
...((gate === 'email' || (prev && prev.gate === 'email')) ? { gate: 'email' } : {}), // a VERIFIED Space says so to the account's other devices — a gate never comes off
|
|
33
|
+
...(enclave || (prev && prev.enclave) ? { enclave: 1 } : {}), // the enclave tier flag (docs/enclave-room-acceptance.md §3.2) — a device that doesn't know it keeps another's
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** Every delete this device knows, as index entries — they win over any live entry. */
|
|
38
|
+
export function indexDeletes (tomb) {
|
|
39
|
+
const out = {}
|
|
40
|
+
for (const rm of Object.keys(tomb || {})) out[rm] = { deleted: true, at: tomb[rm] }
|
|
41
|
+
return out
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** The deletes the index carries, adopted into this device's tombstones (never undone): → { tomb (a new map), adopted (rooms
|
|
45
|
+
* newly tombstoned here, in the index's order), deleted (every room the index marks deleted, in its order) }. A delete with no
|
|
46
|
+
* time is stamped `now()`. */
|
|
47
|
+
export function adoptIndexDeletes (remoteRooms, tomb, now = Date.now) {
|
|
48
|
+
const next = { ...(tomb || {}) }, adopted = [], deleted = []
|
|
49
|
+
const rooms = remoteRooms && typeof remoteRooms === 'object' ? remoteRooms : {}
|
|
50
|
+
for (const rm of Object.keys(rooms)) {
|
|
51
|
+
const e = rooms[rm]
|
|
52
|
+
if (!(e && e.deleted)) continue
|
|
53
|
+
deleted.push(rm)
|
|
54
|
+
if (!next[rm]) { next[rm] = e.at || now(); adopted.push(rm) }
|
|
55
|
+
}
|
|
56
|
+
return { tomb: next, adopted, deleted }
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** Is the index's entry one this device takes into its list? Never a temp room, a deleted or tombstoned one, nor — when this
|
|
60
|
+
* device reads the index WITH keys (`keyless` false) — an entry that carries no key of either kind. Archived ones are taken. */
|
|
61
|
+
export const adoptableIndexEntry = (room, e, tomb, { keyless = false } = {}) => !(!e || isTemp(room) || (!keyless && !(e.mk || e.userShare)) || e.deleted || (tomb && tomb[room]))
|
|
62
|
+
|
|
63
|
+
/** A room another device listed, as this device's new recents row (its name, Help mark, archive, pin and order carried). */
|
|
64
|
+
export function recentFromIndexEntry (room, e) {
|
|
65
|
+
return { room, title: (e.title && e.title !== room) ? e.title : 'Space', at: e.at || 0, ...(e.help ? { help: true } : {}), ...(e.titleAt ? { titleAt: e.titleAt } : {}), ...(e.title && e.title !== room ? { titled: true } : {}), ...(e.manual && e.title && e.title !== room ? { renamed: true, llmTitled: true } : {}), ...(e.archived ? { archived: true, archivedAt: e.archivedAt || 0 } : {}), ...(e.pinned ? { pinned: true, pinnedAt: e.pinnedAt || 0 } : {}), ...(e.alwaysOnAt ? { alwaysOn: !!e.alwaysOn, alwaysOnAt: e.alwaysOnAt } : {}) }
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** The index's entry folded into this device's row for the same room: → { row (a new object; `row` itself when nothing moved),
|
|
69
|
+
* changed, renamed (a newer name arrived — the open room's header follows) }. Each field by its own clock. */
|
|
70
|
+
/** 11·R#2: the index sync merged the remote rows into `cur`, then WAITED (the lanes registry, ≤ 4 s) before saving. Another writer may have
|
|
71
|
+
* saved the list meanwhile (an attested restore, an invite) — saving `cur` dropped its rows. → the list to save: the list as it is NOW
|
|
72
|
+
* (`fresh`), with this pass's arrivals added and its merges re-applied. A room `fresh` lost meanwhile (deleted elsewhere) is not brought
|
|
73
|
+
* back unless this pass brought it. `fresh === cur` (nothing saved meanwhile) → `cur` as it is. */
|
|
74
|
+
export function rebaseIndexMerge (cur, fresh, arrived, remote) {
|
|
75
|
+
if (!Array.isArray(fresh) || fresh === cur) return cur
|
|
76
|
+
const out = fresh.slice(), by = new Map(out.map((x) => [x && x.room, x])), came = new Set(arrived || [])
|
|
77
|
+
for (const r of cur) {
|
|
78
|
+
if (!r || !r.room) continue
|
|
79
|
+
const f = by.get(r.room)
|
|
80
|
+
if (!f) { if (came.has(r.room)) { out.push(r); by.set(r.room, r) } continue }
|
|
81
|
+
if (f !== r && remote && remote[r.room]) { const m = mergeIndexEntry(f, remote[r.room], r.room); if (m && m.changed) Object.assign(f, m.row) }
|
|
82
|
+
}
|
|
83
|
+
return out
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
export function mergeIndexEntry (row, e, room) {
|
|
87
|
+
const li = { ...row }
|
|
88
|
+
let changed = false, renamed = false
|
|
89
|
+
if (e.help && !li.help) { li.help = true; changed = true } // the account's Help Space (docs/help-space.md)
|
|
90
|
+
if (e.manual && e.title && e.title === li.title && !li.renamed) { li.renamed = true; changed = true } // the same name, now known to be set by hand (another device named it): Invite must not ask again
|
|
91
|
+
if (e.title && e.title !== room && e.title !== li.title && (e.titleAt || 0) > (li.titleAt || 0)) { // a RENAME on another device (newer titleAt wins)
|
|
92
|
+
li.title = e.title; li.titleAt = e.titleAt; li.titled = true; li.renamed = !!e.manual; changed = true; renamed = true // a name from the index is a name: the first-message heuristic must not replace it (roomTitle.js pinRecentTitle)
|
|
93
|
+
}
|
|
94
|
+
if ((e.archivedAt || 0) > (li.archivedAt || 0) && !!e.archived !== !!li.archived) { li.archived = !!e.archived; li.archivedAt = e.archivedAt || 0; changed = true } // adopt a newer archive/unarchive
|
|
95
|
+
if ((e.pinnedAt || 0) > (li.pinnedAt || 0) && !!e.pinned !== !!li.pinned) { li.pinned = !!e.pinned; li.pinnedAt = e.pinnedAt || 0; changed = true } // adopt a newer pin/unpin
|
|
96
|
+
if ((e.alwaysOnAt || 0) > (li.alwaysOnAt || 0)) { li.alwaysOn = !!e.alwaysOn; li.alwaysOnAt = e.alwaysOnAt; changed = true } // adopt a newer always on / off (another device kept it, or stopped)
|
|
97
|
+
if ((e.at || 0) > (li.at || 0)) { li.at = e.at; changed = true } // converge ORDER to the latest activity anywhere
|
|
98
|
+
return { row: changed ? li : row, changed, renamed }
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** A hidden room's pointer ({ room, mk }) as the index carries it, or null. */
|
|
102
|
+
export const validPointer = (p) => (p && p.room && p.mk ? p : null)
|
|
103
|
+
|
|
104
|
+
/** The pointer this device publishes (the pipes room, the message room): the WINNER — the smaller room id — so a split heals in
|
|
105
|
+
* one round; this device's own when the index has none, and the index's when this device has none, so a device without one
|
|
106
|
+
* never deletes everyone's (op:'state' replaces the doc). `local` counts once it names a room; `remote` should be validPointer'd. */
|
|
107
|
+
export const pointerToPublish = (local, remote) => ((local && local.room && remote) ? (local.room <= remote.room ? local : remote) : (local && local.room ? local : remote))
|
|
108
|
+
|
|
109
|
+
/** Does the index's id win over this device's (the hidden rooms' pointers, the invite inbox)? When this device has none, or the
|
|
110
|
+
* index's is the smaller — every device independently picks the same winner, no flip-flop. */
|
|
111
|
+
export const adoptsRemote = (localId, remoteId) => (!localId || (remoteId !== localId && remoteId < localId))
|
|
112
|
+
|
|
113
|
+
/** THE `xindex` DOC (the sealed 'index'): the rooms map, the device registry and its sign-outs, the person's name, the read
|
|
114
|
+
* positions, and — only when this device has one — the invite inbox, the usage key (with the retired ones) and the pipes /
|
|
115
|
+
* message room pointers. Key order is the doc's: accountFormatGolden.test.mjs hashes it as written (phase 3: the SDK writes it too). */
|
|
116
|
+
export const indexDoc = ({ rooms, devices, signouts, name, seen, vseen, inviteKey, usageKey, usageKeysOld, pipesRoom, msgsRoom }) =>
|
|
117
|
+
({ v: 2, rooms, devices, signouts, name, seen, vseen, ...(inviteKey ? { inviteKey } : {}), ...(usageKey ? { usageKey, usageKeysOld } : {}), ...(pipesRoom ? { pipesRoom } : {}), ...(msgsRoom ? { msgsRoom } : {}) })
|
|
118
|
+
|
|
119
|
+
/** THE `xindex2` DOC (the sealed 'index2'): contacts, the personal calendar and to-dos, the Code settings, the connections'
|
|
120
|
+
* call keys with their removal marks (`connGone` only once someone detached), Siri and the A2A lanes. */
|
|
121
|
+
export const index2Doc = ({ contacts, events, todos, code, connections, connGone, siri, a2a }) =>
|
|
122
|
+
({ v: 2, contacts, events, todos, code, connections, ...(connGone ? { connGone } : {}), siri, a2a })
|
package/accountOwner.js
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
// WHOSE Spaces this device holds — so a second person signing in on it does not get the first one's rooms.
|
|
2
|
+
//
|
|
3
|
+
// Nothing used to tell accounts apart on one device: a sign-in only replaced the identity, the rooms and keys the device
|
|
4
|
+
// already held stayed, and the next sync PUSHED every one of them into the list (and the backup) of the account now
|
|
5
|
+
// signed in (the owner, 2026-10-09: Liat signed in on a computer that had been used with another account, and her list
|
|
6
|
+
// filled with rows called "Space" that are not hers). The device now remembers the email whose Spaces it holds — set by
|
|
7
|
+
// the first sync that runs signed in — and a different email gets NO push: the merge cannot happen, and the page offers
|
|
8
|
+
// "Switch account" (devices.js wipeDevice: this device's Spaces are cleared, the new person signs in on a clean device).
|
|
9
|
+
// Signed out (no email), nothing is decided. Log out / Switch account clears the record with everything else (space:*).
|
|
10
|
+
const KEY = 'space:acct-owner'
|
|
11
|
+
const norm = (e) => (typeof e === 'string' ? e.trim().toLowerCase() : '')
|
|
12
|
+
|
|
13
|
+
/** The signed-in email, read as spaceEmailGate.js reads its anchor (space:esession, unexpired) — no import of the sign-in
|
|
14
|
+
* module, so the sync code stays loadable on its own. */
|
|
15
|
+
export function signedInEmail() {
|
|
16
|
+
try { const a = JSON.parse(localStorage.getItem('space:esession') || 'null'); return a && (!a.exp || a.exp > Date.now()) ? norm(a.email) : '' } catch { return '' }
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export function deviceOwner() {
|
|
20
|
+
try { return norm(localStorage.getItem(KEY)) } catch { return '' }
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** May this device's Spaces be pushed into the account of `email`? The first signed-in sync claims the device for it. */
|
|
24
|
+
export function ownerAllows(email) {
|
|
25
|
+
const e = norm(email)
|
|
26
|
+
if (!e) return { ok: true }
|
|
27
|
+
const o = deviceOwner()
|
|
28
|
+
if (!o) {
|
|
29
|
+
try { localStorage.setItem(KEY, e) } catch { /* no storage: nothing to protect either */ }
|
|
30
|
+
return { ok: true }
|
|
31
|
+
}
|
|
32
|
+
return o === e ? { ok: true } : { ok: false, owner: o, email: e }
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
let told = false
|
|
36
|
+
/** Say it once per page: the page shows the switch (accountMismatch listener in space.js). */
|
|
37
|
+
export function noteMismatch(check) {
|
|
38
|
+
if (told || !check || check.ok) return
|
|
39
|
+
told = true
|
|
40
|
+
try { if (typeof dispatchEvent === 'function' && typeof CustomEvent === 'function') dispatchEvent(new CustomEvent('space:account-mismatch', { detail: { owner: check.owner, email: check.email } })) } catch { /* */ }
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
// ★ NOT A SILENT STOP (2026-11-07, the implicit-state-machine review): a refused push returned before the backup's error mark,
|
|
44
|
+
// so Back up & recovery kept saying all was well while nothing was saved, and the person was told once per page (a notice
|
|
45
|
+
// they could dismiss). The refusal is now kept (space:recovery:owner-mismatch) and shown as the backup's health until a push
|
|
46
|
+
// is allowed again (the right email signed in, or Switch account — which clears space:* with everything else).
|
|
47
|
+
const MISMATCH_KEY = 'space:recovery:owner-mismatch'
|
|
48
|
+
/** The refusal in force, if any: { owner, email, at } — for backupHealth. */
|
|
49
|
+
export function ownerMismatch() {
|
|
50
|
+
try { const m = JSON.parse(localStorage.getItem(MISMATCH_KEY) || 'null'); return m && m.owner && m.email ? m : null } catch { return null }
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** The guard both pushes call: false = do not push (and the page has been told). */
|
|
54
|
+
export function mayPushFor(email = signedInEmail()) {
|
|
55
|
+
const c = ownerAllows(email)
|
|
56
|
+
if (!c.ok) { noteMismatch(c); try { localStorage.setItem(MISMATCH_KEY, JSON.stringify({ owner: c.owner, email: c.email, at: Date.now() })) } catch { /* */ } }
|
|
57
|
+
else if (norm(email)) { try { localStorage.removeItem(MISMATCH_KEY) } catch { /* */ } } // a push for the owner again: the warning goes
|
|
58
|
+
return c.ok
|
|
59
|
+
}
|
package/accountRecord.js
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
// accountRecord.js — the account record a backup seals, one format for the Spaces app and the SDK (docs/sdk-convergence.md,
|
|
2
|
+
// phase 6; the owner, 2026-10-05: "Can we support both (legacy is the current sdk)").
|
|
3
|
+
//
|
|
4
|
+
// THE FORMAT is the Spaces app's: { v: 1, at, recents: [{ room, title, at, … }], keys: { room: { mk | userShare+commit, … } },
|
|
5
|
+
// … }. A builder app's record carries `app: 'sdk'` and, per room, what the SDK needs to reopen it (the link, lane or space,
|
|
6
|
+
// its shared room, archived) — extra fields the app's own reader ignores.
|
|
7
|
+
// LEGACY is the SDK's original record ({ kind: 'witbitz-sdk-rooms', rooms: [{ room, link, kind, … }] }): still read, and
|
|
8
|
+
// still written for a backup that has it, until the builder asks to upgrade (wb.backup.upgrade()).
|
|
9
|
+
//
|
|
10
|
+
// ⛔ ONE FORMAT, NOT ONE ACCOUNT. Each app keeps its own vault (its own master secret and recovery code). vaultOwner() says
|
|
11
|
+
// whose a record is, and each side opens only its own: a builder's page must never open a Witbitz account's backup (it
|
|
12
|
+
// would hold the key to every Space the person has), and the Spaces app never imports a builder app's rooms.
|
|
13
|
+
export const LEGACY_SDK_KIND = 'witbitz-sdk-rooms'
|
|
14
|
+
export const SDK_APP = 'sdk'
|
|
15
|
+
const APP_ADDRESS = /^https?:\/\/[^/\s]+$/ // an origin, as appIdentity.backupApp reads a backup's `app`
|
|
16
|
+
|
|
17
|
+
/** 'sdk' (a builder app's vault) · 'spaces' (the Witbitz account) · null (not an account record). */
|
|
18
|
+
export function vaultOwner (doc) {
|
|
19
|
+
if (!doc || typeof doc !== 'object') return null
|
|
20
|
+
if (doc.kind === LEGACY_SDK_KIND) return SDK_APP
|
|
21
|
+
if (doc.v === 1 && Array.isArray(doc.recents)) {
|
|
22
|
+
const app = typeof doc.app === 'string' ? doc.app : ''
|
|
23
|
+
// An ADDRESS is a Spaces app's own stamp (appIdentity.js stampFor, since 7c4b9b1d) — which Spaces app is
|
|
24
|
+
// backupMismatch's question, not this one. Read as the owner it refused every tagged restore (sweep, 2026-10-14).
|
|
25
|
+
if (!app || APP_ADDRESS.test(app)) return 'spaces'
|
|
26
|
+
return app // 'sdk', or an owner neither side knows: refused by both
|
|
27
|
+
}
|
|
28
|
+
return null
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** The whole key a room's link carries in its fragment (`#mk=…`, before a member's identity after the first `?` — as
|
|
32
|
+
* spaceConfig.parseConfiguredLink reads it), or '' — a SPLIT link (`#us=…`) carries half a key, so none. */
|
|
33
|
+
export function keyInLink (link) {
|
|
34
|
+
const s = String(link || ''); const h = s.indexOf('#')
|
|
35
|
+
if (h < 0) return ''
|
|
36
|
+
const raw = s.slice(h + 1); const q = raw.indexOf('?')
|
|
37
|
+
try { return new URLSearchParams(q >= 0 ? raw.slice(0, q) : raw).get('mk') || '' } catch { return '' }
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** The SDK's room list → the account record (the app's format, marked as the SDK's). */
|
|
41
|
+
// `inviteKey`: the account's invite key for this app (sdkRekey.js) — the Spaces app's own field, so a restored device follows a
|
|
42
|
+
// Space re-keyed in place.
|
|
43
|
+
// PHASE 2 (docs/sdk-account-format-plan.md, 2026-11-13), ADDED fields only — every older SDK reads `recents[].link` and ignores
|
|
44
|
+
// the rest: `keys[room].mk` for EVERY room (its link's key; a split room's ASSEMBLED key, as before — never the app's share +
|
|
45
|
+
// commit), `tombstones` ({ room: at }, the app's shape) for the SDK's forget marks of rooms the record does NOT hold (a room
|
|
46
|
+
// opened again after a forget is not deleted — the SDK's `tomb` stays its own, re-openable mark), and `indexRoom` ({ room, mk },
|
|
47
|
+
// the app's pointer) = the SDK's derived index room (sdkAccount.js indexRoomOf).
|
|
48
|
+
export function roomPin(r) {
|
|
49
|
+
const at = Number.isFinite(r.pinnedAt) && r.pinnedAt > 0 ? r.pinnedAt : 0
|
|
50
|
+
return r.pinned || at ? { pinned: !!r.pinned, pinnedAt: at } : {}
|
|
51
|
+
}
|
|
52
|
+
export function recordFromRooms ({ rooms = [], tomb, email, inviteKey, indexRoom, app = SDK_APP, at = Date.now() } = {}) {
|
|
53
|
+
const recents = []; const keys = {}
|
|
54
|
+
for (const r of rooms) {
|
|
55
|
+
if (!r || !r.room || !r.link) continue
|
|
56
|
+
recents.push({ room: r.room, title: r.label || '', ...(typeof r.renamed === 'boolean' ? { renamed: r.renamed } : {}), at: r.at || 0, ...roomPin(r), link: r.link, kind: r.kind === 'lane' ? 'lane' : 'space',
|
|
57
|
+
...(r.shared ? { shared: r.shared } : {}), ...(r.mintedFor ? { mintedFor: r.mintedFor } : {}), ...(r.laneOrigin === 'minted' && !r.detachedLane ? { laneOrigin: 'minted' } : {}), ...(Number(r.associationAt) > 0 ? { associationAt: Number(r.associationAt) } : {}), ...(r.detachedLane ? { detachedLane: true } : {}), ...(r.archived ? { archived: true } : {}) })
|
|
58
|
+
const mk = keyInLink(r.link) || r.mk // the link's own key first: a separate copy of a plain room's key may be stale
|
|
59
|
+
if (mk) keys[r.room] = { mk }
|
|
60
|
+
}
|
|
61
|
+
const held = new Set(recents.map((r) => r.room)); const tombstones = {}
|
|
62
|
+
for (const t of Array.isArray(tomb) ? tomb : []) if (t && typeof t.room === 'string' && t.room && !held.has(t.room) && Number.isFinite(t.at)) tombstones[t.room] = Math.max(tombstones[t.room] || 0, t.at)
|
|
63
|
+
return { v: 1, app, at, recents, keys, ...(Array.isArray(tomb) && tomb.length ? { tomb } : {}), ...(email ? { email } : {}), ...(inviteKey && inviteKey.boxPriv ? { inviteKey } : {}),
|
|
64
|
+
...(Object.keys(tombstones).length ? { tombstones } : {}), ...(indexRoom && typeof indexRoom.room === 'string' && indexRoom.room && typeof indexRoom.mk === 'string' && indexRoom.mk ? { indexRoom: { room: indexRoom.room, mk: indexRoom.mk } } : {}) }
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** Either format → the SDK's room list [{ room, link, kind, label?, shared?, archived?, mk?, at? }]. `mk` only where the link
|
|
68
|
+
* is not the key (a split room) — a record from phase 2 on carries every room's key, and the SDK's state keeps what it did. */
|
|
69
|
+
export function roomsOfRecord (doc) {
|
|
70
|
+
if (!doc || typeof doc !== 'object') return []
|
|
71
|
+
if (doc.kind === LEGACY_SDK_KIND) return Array.isArray(doc.rooms) ? doc.rooms : []
|
|
72
|
+
if (!Array.isArray(doc.recents)) return []
|
|
73
|
+
const keys = doc.keys && typeof doc.keys === 'object' ? doc.keys : {}
|
|
74
|
+
return doc.recents.filter((r) => r && r.room && r.link).map((r) => ({
|
|
75
|
+
room: r.room, ...roomPin(r), ...(r.mintedFor ? { mintedFor: r.mintedFor } : {}), ...(r.laneOrigin === 'minted' && !r.detachedLane ? { laneOrigin: 'minted' } : {}), ...(Number(r.associationAt) > 0 ? { associationAt: Number(r.associationAt) } : {}), ...(r.detachedLane ? { detachedLane: true } : {}), ...(r.at ? { at: r.at } : {}), ...(r.archived ? { archived: true } : {}), link: r.link,
|
|
76
|
+
kind: r.kind === 'lane' ? 'lane' : 'space', ...(r.title ? { label: r.title } : {}), ...(typeof r.renamed === 'boolean' ? { renamed: r.renamed } : {}), ...(r.shared ? { shared: r.shared } : {}),
|
|
77
|
+
...(keys[r.room] && keys[r.room].mk && !keyInLink(r.link) ? { mk: keys[r.room].mk } : {}),
|
|
78
|
+
}))
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** A record's forget marks as the SDK keeps them ([{ room, at }]): its `tomb`, and any room only in the app-shaped
|
|
82
|
+
* `tombstones` — the newer `at` of the two. A legacy record has `tomb` only. */
|
|
83
|
+
export function tombOfRecord (doc) {
|
|
84
|
+
if (!doc || typeof doc !== 'object') return []
|
|
85
|
+
const at = new Map()
|
|
86
|
+
for (const t of Array.isArray(doc.tomb) ? doc.tomb : []) if (t && typeof t.room === 'string' && t.room && Number.isFinite(t.at)) at.set(t.room, Math.max(at.get(t.room) || 0, t.at))
|
|
87
|
+
const ts = doc.tombstones && typeof doc.tombstones === 'object' && !Array.isArray(doc.tombstones) ? doc.tombstones : {}
|
|
88
|
+
for (const [room, t] of Object.entries(ts)) if (room && Number.isFinite(t)) at.set(room, Math.max(at.get(room) || 0, t))
|
|
89
|
+
return [...at].map(([room, t]) => ({ room, at: t }))
|
|
90
|
+
}
|
package/accountScope.js
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
// accountScope.js — which app a sign-in speaks for, and the ACCOUNT it may act on (2026-10-05 review, F1).
|
|
2
|
+
//
|
|
3
|
+
// THE HOLE. The SDK signs a builder's users in against Witbitz's own issuer from any website (CORS *), and every issuer
|
|
4
|
+
// minted the same audience — so a token a builder's page obtained was accepted as the user's FIRST-PARTY Witbitz account:
|
|
5
|
+
// erase it, mint billing tokens on it, revoke its connections, release its @username. A builder is supposed to be blind.
|
|
6
|
+
//
|
|
7
|
+
// THE RULE (one module, imported by the page and the Space Lambda, so both derive the same account):
|
|
8
|
+
// • a token is FIRST-PARTY when its issuer is one of Witbitz's own and it carries no `app` claim. The sign-in endpoints
|
|
9
|
+
// add `app: <origin>` when the request came from any other website (spaces/functions/api/email/_email.js appClaim).
|
|
10
|
+
// • anything else speaks for an APP: the `app` claim, or — a tenant's own issuer — the issuer itself.
|
|
11
|
+
// • an app's account is the user's email with a tag in the DOMAIN: dana@x.com → dana@x.com.app-<12 hex>. It still has
|
|
12
|
+
// the shape every account check expects (the Sentinel's ACCOUNT regex), and nobody can sign in AS it: no mail is
|
|
13
|
+
// delivered to a domain whose last label is not a real TLD. (A `+tag` in the local part would be a real, registrable
|
|
14
|
+
// mailbox on a domain without plus-addressing.)
|
|
15
|
+
// Room admission is untouched: a gate asks "is this email allowed", and both kinds of token prove the email.
|
|
16
|
+
|
|
17
|
+
export const FIRST_PARTY_ISSUERS = Object.freeze([
|
|
18
|
+
'https://witbitz-spaces.pages.dev', // the Spaces app's own email sign-in
|
|
19
|
+
'https://app.witbitz.chat', // the tenant app (auth broker)
|
|
20
|
+
'https://spaces.witbitz.chat', // its vault
|
|
21
|
+
'https://witbitz-vault-prod.pages.dev',
|
|
22
|
+
'https://witbitz-spaces-vaulted.pages.dev',
|
|
23
|
+
'https://accounts.google.com', // Google sign-in under Witbitz's own OAuth client
|
|
24
|
+
'accounts.google.com',
|
|
25
|
+
])
|
|
26
|
+
const FIRST = new Set(FIRST_PARTY_ISSUERS)
|
|
27
|
+
|
|
28
|
+
/** The payload of a JWT (no verification — call this on a token a verifier already accepted). null when malformed. */
|
|
29
|
+
export function tokenClaims(idToken) {
|
|
30
|
+
try {
|
|
31
|
+
const p = String(idToken || '').split('.')[1]
|
|
32
|
+
if (!p) return null
|
|
33
|
+
const b64 = p.replace(/-/g, '+').replace(/_/g, '/')
|
|
34
|
+
const json = typeof atob === 'function' ? new TextDecoder().decode(Uint8Array.from(atob(b64 + '==='.slice((b64.length + 3) % 4)), (c) => c.charCodeAt(0))) : Buffer.from(p, 'base64url').toString('utf8')
|
|
35
|
+
const o = JSON.parse(json)
|
|
36
|
+
return o && typeof o === 'object' ? o : null
|
|
37
|
+
} catch { return null }
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** null = the user's own Witbitz account; else the app (an origin, or a tenant issuer) the token speaks for. */
|
|
41
|
+
export function tokenApp(claims) {
|
|
42
|
+
if (!claims || typeof claims !== 'object') return 'unknown'
|
|
43
|
+
const iss = String(claims.iss || '').replace(/\/$/, '')
|
|
44
|
+
if (!FIRST.has(iss)) return iss || 'unknown'
|
|
45
|
+
if (claims.app !== undefined && claims.app !== null) return String(claims.app) || 'unknown'
|
|
46
|
+
return null
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
const hex = (buf) => Array.from(new Uint8Array(buf), (b) => b.toString(16).padStart(2, '0')).join('')
|
|
50
|
+
async function sha256Hex(s) {
|
|
51
|
+
const data = new TextEncoder().encode(s)
|
|
52
|
+
if (globalThis.crypto && globalThis.crypto.subtle) return hex(await globalThis.crypto.subtle.digest('SHA-256', data))
|
|
53
|
+
const { createHash } = await import('node:crypto')
|
|
54
|
+
return createHash('sha256').update(data).digest('hex')
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** The account a token may act on: the email itself for a first-party token, the app-tagged account otherwise. */
|
|
58
|
+
export async function scopedAccount(email, claims) {
|
|
59
|
+
const e = String(email || '').trim().toLowerCase()
|
|
60
|
+
const app = tokenApp(claims)
|
|
61
|
+
if (!app) return e
|
|
62
|
+
return `${e}.app-${(await sha256Hex('witbitz-app-scope\n' + app)).slice(0, 12)}`
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
// ── THE VAULTED APP IS ITS OWN APP AT THE SENTINEL (the owner, 2026-10-23: "All access to data of the same user to a different
|
|
66
|
+
// app should be gated by the server"; "Regular keeps all, vaulted starts empty"). Rooms were already split by tenant
|
|
67
|
+
// origin (10-18), but what the Sentinel keeps PER PERSON — connections, the Siri inbox, outside agents — was filed under the
|
|
68
|
+
// plain email by both first-party apps, so each saw and could revoke the other's: a connection made in the vaulted app
|
|
69
|
+
// showed in the regular app as "connected on another device". The vaulted app's requests now act on its own account (the
|
|
70
|
+
// same tag scheme as any app), the regular app keeps the plain email. Decided by the ORIGIN the request comes from — the
|
|
71
|
+
// browser sets it and a page cannot change it; the Lambda reads it from the request, the page from its own location — so
|
|
72
|
+
// both derive the same account (the Sentinel refuses a sealed record whose account is not the verified one).
|
|
73
|
+
// ONLY the Sentinel's per-person data: @usernames, the directory and room admission keep the plain email in both apps.
|
|
74
|
+
export const VAULTED_APP_ORIGINS = Object.freeze([
|
|
75
|
+
'https://app.witbitz.chat', // the vaulted app's frame
|
|
76
|
+
'https://spaces.witbitz.chat', // its vault
|
|
77
|
+
'https://witbitz-vault-prod.pages.dev',
|
|
78
|
+
'https://witbitz-spaces-vaulted.pages.dev',
|
|
79
|
+
])
|
|
80
|
+
export const VAULTED_APP = 'https://app.witbitz.chat' // one scope for the whole vaulted product
|
|
81
|
+
const VAULTED = new Set(VAULTED_APP_ORIGINS)
|
|
82
|
+
/** The account a request may act on at the Sentinel: an app's token → its app account (scopedAccount); a first-party token →
|
|
83
|
+
* the vaulted app's own account when the request comes from the vaulted app's origins, the plain email otherwise. */
|
|
84
|
+
export async function sentinelAccount(email, claims, { origin = '' } = {}) {
|
|
85
|
+
if (tokenApp(claims)) return scopedAccount(email, claims)
|
|
86
|
+
const e = String(email || '').trim().toLowerCase()
|
|
87
|
+
if (!VAULTED.has(String(origin || '').replace(/\/$/, ''))) return e
|
|
88
|
+
return `${e}.app-${(await sha256Hex('witbitz-app-scope\n' + VAULTED_APP)).slice(0, 12)}`
|
|
89
|
+
}
|
|
90
|
+
// ── WHICH FIRST-PARTY APP A TOKEN NAMES (docs/standing-sentinel.md § Related; the owner, 2026-11-07: "Do it"). The Origin rule
|
|
91
|
+
// above holds in a browser; a PROGRAM holding the person's token can send either origin and reach the other app's records.
|
|
92
|
+
// The token already says which app minted it: the vaulted app signs in on its own issuers (the vault's email code mints as its
|
|
93
|
+
// Pages project, the auth broker's Google handoff as the vault's origin — complete.js), the regular app on its own
|
|
94
|
+
// (witbitz-spaces.pages.dev) or with Google's own token. Stage 1 compares the two answers and counts the mismatches; the
|
|
95
|
+
// Lambda decides by the token only behind SENTINEL_APP_BY_TOKEN, and the Sentinel image follows.
|
|
96
|
+
const REGULAR_ISSUERS = new Set(['https://witbitz-spaces.pages.dev', 'https://accounts.google.com', 'accounts.google.com'])
|
|
97
|
+
/** A first-party token → 'vaulted' | 'regular' (the app that minted it); an app's token, or a first-party issuer that names
|
|
98
|
+
* neither, → null. */
|
|
99
|
+
export function firstPartyAppOf(claims) {
|
|
100
|
+
if (!claims || typeof claims !== 'object' || tokenApp(claims)) return null
|
|
101
|
+
const iss = String(claims.iss || '').replace(/\/$/, '')
|
|
102
|
+
if (VAULTED.has(iss)) return 'vaulted'
|
|
103
|
+
if (REGULAR_ISSUERS.has(iss)) return 'regular'
|
|
104
|
+
return null
|
|
105
|
+
}
|
|
106
|
+
/** The app a request's Origin names: 'vaulted' for the vaulted app's origins, 'regular' otherwise. */
|
|
107
|
+
export const originAppOf = (origin) => (VAULTED.has(String(origin || '').replace(/\/$/, '')) ? 'vaulted' : 'regular')
|
|
108
|
+
|
|
109
|
+
/** The page's side: this page's account at the Sentinel for a sign-in token ({ email, idToken }). */
|
|
110
|
+
export const myAccountFor = (tok) => sentinelAccount(tok && tok.email, tokenClaims(tok && tok.idToken), { origin: (typeof location !== 'undefined' && location.origin) || '' })
|
|
111
|
+
/** The person's email in an account at the Sentinel: an app account (`dana@x.com.app-<12 hex>`) without its app tag. For
|
|
112
|
+
* showing it, and for "is this person a member" (a Space's members are emails, never app accounts). */
|
|
113
|
+
export const accountEmail = (acct) => String(acct || '').replace(/\.app-[0-9a-f]{12}$/, '')
|
|
114
|
+
|
package/accountSeal.js
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
// accountSeal.js — sealing an account's sync documents ON THE DEVICE, one implementation for the SDK's account index
|
|
2
|
+
// (sdkAccount.js) and the Spaces app's account stores (accountStores.js). A sealed doc is { v: 1, z, s }: the JSON, gzipped
|
|
3
|
+
// where the platform can, AES-GCM under a key derived from the account's backup master secret — which the server never
|
|
4
|
+
// holds. So the server stores and serves what it cannot read: the room list and every room key in it, the invite and Siri
|
|
5
|
+
// and A2A private keys, contacts, the calendar (docs/sdk-convergence.md § The account stores).
|
|
6
|
+
const enc = new TextEncoder(), dec = new TextDecoder()
|
|
7
|
+
export 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 }
|
|
8
|
+
export const b64url = (u8) => { let s = ''; for (let i = 0; i < u8.length; i++) s += String.fromCharCode(u8[i]); return btoa(s).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '') }
|
|
9
|
+
export async function hkdf (secret, salt, info, len) {
|
|
10
|
+
const km = await crypto.subtle.importKey('raw', secret, 'HKDF', false, ['deriveBits'])
|
|
11
|
+
return new Uint8Array(await crypto.subtle.deriveBits({ name: 'HKDF', hash: 'SHA-256', salt: enc.encode(salt), info: enc.encode(info) }, km, len * 8))
|
|
12
|
+
}
|
|
13
|
+
const canZip = typeof CompressionStream === 'function' && typeof DecompressionStream === 'function'
|
|
14
|
+
async function pipeThrough (bytes, stream) { return new Uint8Array(await new Response(new Blob([bytes]).stream().pipeThrough(stream)).arrayBuffer()) }
|
|
15
|
+
export async function sealDoc (key, obj) {
|
|
16
|
+
let bytes = enc.encode(JSON.stringify(obj)), z = false
|
|
17
|
+
if (canZip) { bytes = await pipeThrough(bytes, new CompressionStream('gzip')); z = true }
|
|
18
|
+
const iv = crypto.getRandomValues(new Uint8Array(12))
|
|
19
|
+
const ct = new Uint8Array(await crypto.subtle.encrypt({ name: 'AES-GCM', iv }, key, bytes))
|
|
20
|
+
const buf = new Uint8Array(12 + ct.length); buf.set(iv); buf.set(ct, 12)
|
|
21
|
+
return { v: 1, z, s: b64url(buf) }
|
|
22
|
+
}
|
|
23
|
+
export async function openDoc (key, doc) {
|
|
24
|
+
const buf = ub64(doc.s)
|
|
25
|
+
let bytes = new Uint8Array(await crypto.subtle.decrypt({ name: 'AES-GCM', iv: buf.slice(0, 12) }, key, buf.slice(12)))
|
|
26
|
+
if (doc.z) bytes = await pipeThrough(bytes, new DecompressionStream('gzip'))
|
|
27
|
+
return JSON.parse(dec.decode(bytes))
|
|
28
|
+
}
|
|
29
|
+
export const isSealedDoc = (d) => !!(d && typeof d === 'object' && typeof d.s === 'string' && d.v === 1)
|
|
30
|
+
/** The Spaces app's account-store key, from the backup master secret (32 bytes). Non-extractable; it can be handed to a
|
|
31
|
+
* worker (structured clone) but never read back out. */
|
|
32
|
+
export async function appStoreKey (master) {
|
|
33
|
+
return crypto.subtle.importKey('raw', await hkdf(master, 'witbitz-account-stores-v1', 'seal', 32), { name: 'AES-GCM' }, false, ['encrypt', 'decrypt'])
|
|
34
|
+
}
|
|
35
|
+
/** A random device-held sealing key (the temp-room index: one device's list, so no account master is needed) as base64url,
|
|
36
|
+
* and its CryptoKey. It lives beside the pointer it seals for — never on the server. */
|
|
37
|
+
export const newRawKey = () => b64url(crypto.getRandomValues(new Uint8Array(32)))
|
|
38
|
+
const _rawKeys = new Map()
|
|
39
|
+
export function rawSealKey (b64) {
|
|
40
|
+
if (!_rawKeys.has(b64)) _rawKeys.set(b64, crypto.subtle.importKey('raw', ub64(b64), { name: 'AES-GCM' }, false, ['encrypt', 'decrypt']))
|
|
41
|
+
return _rawKeys.get(b64)
|
|
42
|
+
}
|
package/accountStores.js
ADDED
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
import { ROOM_DEFAULTS_DOC, mergeRoomDefaults } from './roomDefaultPrefs.js'
|
|
2
|
+
// accountStores.js — the Spaces app's account sync documents, SEALED on the device (docs/sdk-convergence.md § The account
|
|
3
|
+
// stores). ⛔ Found 2026-10-05: the index doc carried every room key — a confidential room's included — as JSON the
|
|
4
|
+
// standard tier read on every sync (spaces/test/indexCarriesKeys.test.mjs). Now each doc is written sealed (accountSeal.js)
|
|
5
|
+
// under its own name ('x' + name: an app that has not updated yet keeps writing the plain one and never overwrites this),
|
|
6
|
+
// and the plain one is emptied once this device has written the sealed copy.
|
|
7
|
+
//
|
|
8
|
+
// READ-THROUGH: read the sealed doc; with none yet, the plain one (a device's first sync after the update). A plain doc that
|
|
9
|
+
// an older app wrote AFTER the move still counts: its entries the sealed doc lacks are merged in (and sealed on the next
|
|
10
|
+
// write), so no room is lost to the overlap. A sealed doc that will not open is NOT a definitive read: status 0, so the
|
|
11
|
+
// caller writes nothing (the index-clobber rule).
|
|
12
|
+
// ⛔ NO KEY, NO WRITE: without the account key (no backup master on this device) nothing is written — never plaintext again.
|
|
13
|
+
//
|
|
14
|
+
// `call(room, mk, name, patch?, summary?, by?)` is the transport (spaceClient.state); `key()` answers the CryptoKey or null.
|
|
15
|
+
import { sealDoc, openDoc, isSealedDoc } from './accountSeal.js'
|
|
16
|
+
|
|
17
|
+
export const SEALED = (name) => 'x' + name
|
|
18
|
+
export const MOVED = 'sealed' // the plain doc's marker once its content lives in the sealed one
|
|
19
|
+
// the maps (or { room } lists) whose entries a late plain write can add (index: rooms; pipes: pipes; temp index: rooms)
|
|
20
|
+
const MAPS = ['rooms', 'pipes']
|
|
21
|
+
// The paired-computers list (codeComputers.js): the COMPUTER writes it too (tools/opencode-pair.mjs, witbitz_code/account.py)
|
|
22
|
+
// and it holds no account key, so it only ever reads and writes the PLAIN doc. That doc is never emptied here, every read
|
|
23
|
+
// folds its entries in, and both directions merge by the list's own rule — never "this write wins" (the owner, 2026-10-08:
|
|
24
|
+
// an uninstall found the plain doc emptied, removed nothing, and the sealed copy kept the computer listed;
|
|
25
|
+
// spaces/test/computersFromTheComputer.test.mjs).
|
|
26
|
+
const REGISTRIES = { computers: 'computers' } // doc name → its map
|
|
27
|
+
|
|
28
|
+
/** Two entry maps of the computers list → one: per entry the higher `mod` wins, a tie goes to the removal. Held equal to
|
|
29
|
+
* codeComputers.mergeRegistry by test (that module is not in the worker's bundle). */
|
|
30
|
+
export function mergeRegistryMap (a, b) {
|
|
31
|
+
const out = Object.create(null)
|
|
32
|
+
const mod = (e) => (e && typeof e === 'object' && typeof e.mod === 'number' && Number.isFinite(e.mod) && e.mod > 0 ? e.mod : 0)
|
|
33
|
+
for (const src of [a, b]) {
|
|
34
|
+
if (!src || typeof src !== 'object' || Array.isArray(src)) continue
|
|
35
|
+
for (const id of Object.keys(src)) {
|
|
36
|
+
const e = src[id], cur = out[id]
|
|
37
|
+
if (!mod(e)) continue
|
|
38
|
+
if (!cur || mod(e) > mod(cur) || (mod(e) === mod(cur) && e.removed && !cur.removed)) out[id] = e
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
return out
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
// What a write carries over from the doc it replaces: for each OBJECT map (rooms, pipes) the entries it lacks — removals
|
|
45
|
+
// there are tombstones ({ deleted } / { removed }), never omission, so an absent entry is one this device has not seen yet.
|
|
46
|
+
// This write wins on an entry both hold. Not carried: a temp room in the synced index (`tmp-…`, purged on purpose — they
|
|
47
|
+
// live in the temp index) and ARRAY lists (the temp index removes by omission; it gets the version check only).
|
|
48
|
+
export function carryMissing (mine, cur, name = '') {
|
|
49
|
+
if (!cur || typeof cur !== 'object' || !mine || typeof mine !== 'object') return mine
|
|
50
|
+
const out = { ...mine }
|
|
51
|
+
if (name === 'kept-agent-links') {
|
|
52
|
+
const links = { ...(cur.links || {}) }
|
|
53
|
+
for (const [id, link] of Object.entries(mine.links || {})) if (!links[id] || link.at > links[id].at || (link.at === links[id].at && link.gone)) links[id] = link
|
|
54
|
+
return { ...out, links }
|
|
55
|
+
}
|
|
56
|
+
if (name === ROOM_DEFAULTS_DOC) return mergeRoomDefaults(mine, cur) || mine
|
|
57
|
+
// Usage receipts are immutable, keyed by receipt id. A successful read-back lets a device advance its cursor;
|
|
58
|
+
// a later stale writer must therefore carry the other device's receipts too, including after a CAS retry.
|
|
59
|
+
if (/^usage-\d{4}-(0[1-9]|1[0-2])$/.test(name)) {
|
|
60
|
+
const rows = (r) => r && typeof r === 'object' && !Array.isArray(r) ? r : {}
|
|
61
|
+
return { ...out, r: { ...rows(cur.r), ...rows(mine.r) } }
|
|
62
|
+
}
|
|
63
|
+
const reg = REGISTRIES[name]
|
|
64
|
+
if (reg) { out[reg] = mergeRegistryMap(cur[reg], mine[reg]); return out } // the computers list: by its own rule, entry by entry
|
|
65
|
+
for (const m of MAPS) {
|
|
66
|
+
const c = cur[m]
|
|
67
|
+
if (!c || typeof c !== 'object' || Array.isArray(c) || Array.isArray(mine[m])) continue
|
|
68
|
+
const have = mine[m] && typeof mine[m] === 'object' ? mine[m] : {}
|
|
69
|
+
const add = {}
|
|
70
|
+
for (const id of Object.keys(c)) if (!(id in have) && !(m === 'rooms' && id.startsWith('tmp-'))) add[id] = c[id]
|
|
71
|
+
if (Object.keys(add).length) out[m] = { ...add, ...have }
|
|
72
|
+
}
|
|
73
|
+
return out
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export function makeAccountStore ({ call, key, oldKeys = async () => [] }) {
|
|
77
|
+
// A NEW ACCOUNT KEY (account recovery v2: starting on the new service and every new recovery code make a new master;
|
|
78
|
+
// the owner's iPhone, 2026-11-15): documents sealed under a PREVIOUS master open with `oldKeys` (the device that changed
|
|
79
|
+
// it keeps them: vault prevMasters, ≤ 3, 30 days) — a read writes the document back under the current key at once, so a
|
|
80
|
+
// device that holds only the new key (restored from the new backup) can read it; a write merges it as usual.
|
|
81
|
+
const openAny = async (k, sealed) => {
|
|
82
|
+
try { return { st: await openDoc(k, sealed), old: false } } catch { /* a previous key? */ }
|
|
83
|
+
let olds = []
|
|
84
|
+
try { olds = (await oldKeys()) || [] } catch { olds = [] }
|
|
85
|
+
for (const ok of olds) { try { return { st: await openDoc(ok, sealed), old: true } } catch { /* the next one */ } }
|
|
86
|
+
return null
|
|
87
|
+
}
|
|
88
|
+
const cleared = new Set() // room|name whose plain doc this page already emptied (or found emptied)
|
|
89
|
+
const read = async (room, mk, name) => { try { return await call(room, mk, name) } catch { return { status: 0 } } }
|
|
90
|
+
// A computer removed here leaves the plain doc too, so its relay secret is not kept there — only TOMBSTONES are written
|
|
91
|
+
// (nothing this device holds that the plain doc lacks), over the version just read; a miss waits for the next write.
|
|
92
|
+
const removalsToPlain = async (room, mk, name, reg, body) => {
|
|
93
|
+
try {
|
|
94
|
+
const pr = await read(room, mk, name)
|
|
95
|
+
const cur = pr && pr.status === 200 && pr.state && typeof pr.state === 'object' && !pr.state.z ? pr.state : null
|
|
96
|
+
const map = cur && cur[reg] && typeof cur[reg] === 'object' ? cur[reg] : null
|
|
97
|
+
if (!map) return
|
|
98
|
+
const gone = {}
|
|
99
|
+
for (const [id, e] of Object.entries((body && body[reg]) || {})) if (e && e.removed && map[id] && !map[id].removed && mergeRegistryMap({ [id]: map[id] }, { [id]: e })[id] === e) gone[id] = e
|
|
100
|
+
if (Object.keys(gone).length) await call(room, mk, name, { ...cur, [reg]: { ...map, ...gone } }, 'computer removed', '', Number.isInteger(pr.v) ? pr.v : 0)
|
|
101
|
+
} catch { /* the next write tries again */ }
|
|
102
|
+
}
|
|
103
|
+
return {
|
|
104
|
+
/** → { status, state, sealed: bool, v? } — status 200 only for a DEFINITIVE read. `v`: the sealed doc's version, for a
|
|
105
|
+
* write that must not land over a change it never merged (put's `ifV`). */
|
|
106
|
+
async get (room, mk, name, { plainOpen = (s) => s } = {}) {
|
|
107
|
+
const k = await key()
|
|
108
|
+
const plainR = await read(room, mk, name)
|
|
109
|
+
const plain = plainR && plainR.status === 200 && plainR.state && typeof plainR.state === 'object' ? await plainOpen(plainR.state) : null
|
|
110
|
+
if (plain && plain.moved === MOVED) cleared.add(room + '|' + name)
|
|
111
|
+
if (!k) return { status: plainR ? plainR.status : 0, state: plain && plain.moved !== MOVED ? plain : null, sealed: false }
|
|
112
|
+
const sr = await read(room, mk, SEALED(name))
|
|
113
|
+
if (!(sr && sr.status === 200)) return { status: (sr && sr.status) || 0, state: null, sealed: false }
|
|
114
|
+
if (!isSealedDoc(sr.state)) return { status: plainR ? plainR.status : 0, state: plain && plain.moved !== MOVED ? plain : null, sealed: false } // not moved yet → the plain doc
|
|
115
|
+
const opened = await openAny(k, sr.state)
|
|
116
|
+
if (!opened) return { status: 0, state: null, sealed: true, unopenable: true }
|
|
117
|
+
let st = opened.st
|
|
118
|
+
let v = Number.isInteger(sr.v) ? { v: sr.v } : {}
|
|
119
|
+
if (opened.old) { // under a previous key: write it back under this one (over the version just read; a race → the next read)
|
|
120
|
+
try { const w = await call(room, mk, SEALED(name), await sealDoc(k, st), 'sealed under the new account key', '', Number.isInteger(sr.v) ? sr.v : 0); if (w && w.status === 200) v = {} } catch { /* the next read heals it */ }
|
|
121
|
+
}
|
|
122
|
+
const reg = REGISTRIES[name]
|
|
123
|
+
if (reg) return { status: 200, state: plain && plain.moved !== MOVED ? { ...st, [reg]: mergeRegistryMap(st[reg], plain[reg]) } : st, sealed: true, ...v } // the computer's own writes
|
|
124
|
+
if (plain && plain.moved !== MOVED) { // an older app wrote the plain doc after the move: take what the sealed one lacks
|
|
125
|
+
st = { ...st }
|
|
126
|
+
for (const m of MAPS) {
|
|
127
|
+
if (Array.isArray(plain[m])) { // a list of { room } entries (the temp-room index): the sealed one's win, the plain one adds what it lacks
|
|
128
|
+
const have = new Set((Array.isArray(st[m]) ? st[m] : []).map((e) => e && e.room))
|
|
129
|
+
st[m] = [...(Array.isArray(st[m]) ? st[m] : []), ...plain[m].filter((e) => e && e.room && !have.has(e.room))]
|
|
130
|
+
} else if (plain[m] && typeof plain[m] === 'object') st[m] = { ...plain[m], ...(st[m] || {}) }
|
|
131
|
+
}
|
|
132
|
+
cleared.delete(room + '|' + name)
|
|
133
|
+
}
|
|
134
|
+
return { status: 200, state: st, sealed: true, ...v }
|
|
135
|
+
},
|
|
136
|
+
/** Write sealed; then empty the plain doc (once). → { status } — 0 + error 'no_account_key' without the key.
|
|
137
|
+
* ⛔ TWO DEVICES MUST NOT OVERWRITE EACH OTHER (a reviewer's finding, 2026-10-05): re-read the CURRENT sealed doc,
|
|
138
|
+
* carry over the map entries this write lacks (carryMissing — rooms/pipes are tombstoned, never dropped by
|
|
139
|
+
* omission), and write only if the doc has not moved since that read (ifV → 409 → again). A current doc that cannot
|
|
140
|
+
* be read or opened is NOT written over. spaces/test/accountStoresConcurrent.test.mjs.
|
|
141
|
+
* ⛔ `ifV` — THE VERSION THE CALLER MERGED (2026-11-07, the implicit-state-machine review): the re-read above carries over
|
|
142
|
+
* only the room/pipe maps; a list (contacts, events, to-dos), the device registry or the read positions written by
|
|
143
|
+
* another device between the CALLER's read and this one was replaced. With `ifV` the write lands only over that version:
|
|
144
|
+
* anything else answers 409 { error: 'moved' } and the caller reads and merges again. Without it: as before. */
|
|
145
|
+
async put (room, mk, name, obj, summary, by, { ifV } = {}) {
|
|
146
|
+
const pinned = Number.isInteger(ifV)
|
|
147
|
+
const k = await key()
|
|
148
|
+
if (!k) return { status: 0, error: 'no_account_key' }
|
|
149
|
+
for (let i = 0; i < 5; i++) {
|
|
150
|
+
const sr = await read(room, mk, SEALED(name))
|
|
151
|
+
if (!(sr && sr.status === 200)) return { status: (sr && sr.status) || 0, error: 'unread' } // unknown is not empty
|
|
152
|
+
if (pinned && isSealedDoc(sr.state) && sr.v !== ifV) return { status: 409, error: 'moved' } // written since the caller's read
|
|
153
|
+
let body = obj
|
|
154
|
+
if (isSealedDoc(sr.state)) {
|
|
155
|
+
const opened = await openAny(k, sr.state) // a previous key's document is merged and written under this one
|
|
156
|
+
if (!opened) return { status: 0, error: 'unopenable' }
|
|
157
|
+
body = carryMissing(obj, opened.st, name)
|
|
158
|
+
}
|
|
159
|
+
const r = await call(room, mk, SEALED(name), await sealDoc(k, body), summary, by, Number.isInteger(sr.v) ? sr.v : 0)
|
|
160
|
+
const status = (r && r.status) || 0
|
|
161
|
+
if (status === 409 && pinned) return { status: 409, error: 'moved' }
|
|
162
|
+
if (status === 409) { await new Promise((res) => setTimeout(res, 20 + Math.floor(Math.random() * 80) * (i + 1))); continue } // another device wrote first: re-read, re-merge
|
|
163
|
+
if (status === 200 && REGISTRIES[name]) await removalsToPlain(room, mk, name, REGISTRIES[name], body)
|
|
164
|
+
if (status === 200 && !REGISTRIES[name] && !cleared.has(room + '|' + name)) { // the computers list's plain doc is the computer's channel: never emptied
|
|
165
|
+
let w = null; try { w = await call(room, mk, name, { v: 2, moved: MOVED }, summary, by) } catch { /* emptied on a later write */ }
|
|
166
|
+
if (w && w.status === 200) cleared.add(room + '|' + name)
|
|
167
|
+
}
|
|
168
|
+
return { status }
|
|
169
|
+
}
|
|
170
|
+
return { status: 409, error: 'busy' }
|
|
171
|
+
},
|
|
172
|
+
}
|
|
173
|
+
}
|