@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,410 @@
|
|
|
1
|
+
// protectedLocal.js — DEVICE STORAGE PROTECTION for the PAGE's own secrets (docs/device-storage-protection.md, slice 2).
|
|
2
|
+
// The key worker seals ITS store (l1-worker.js §PROTECT); this seals what the main thread keeps in localStorage: the
|
|
3
|
+
// backup master, the room signing identities, split shares and commitments, sign-in tokens, the account/invite keys, the
|
|
4
|
+
// Connections / Siri / outside-agent keys, the Code pairing, contacts and the recents list (room titles).
|
|
5
|
+
//
|
|
6
|
+
// HOW, without touching the dozen modules that read them: every protected entry stays IN localStorage UNDER ITS OWN KEY,
|
|
7
|
+
// but as a sealed blob ({ v: 1, s }) — so the code that enumerates localStorage (`key(i)` / `length`) still sees it — and
|
|
8
|
+
// `Storage.prototype.getItem/setItem/removeItem` are wrapped so a protected key reads from an in-memory OVERLAY (filled at
|
|
9
|
+
// unlock, cleared at relock) and writes to the overlay + a fresh sealed blob. Readers are synchronous, WebCrypto is not:
|
|
10
|
+
// the overlay is what makes a synchronous read possible, and `ready()` is what boot awaits so no reader runs before it.
|
|
11
|
+
//
|
|
12
|
+
// INACTIVE (the switch off, or a framed app that does not own the lock): the wrappers pass straight through — every
|
|
13
|
+
// store byte-identical to today. Turning the switch on migrates the existing clear entries in place; turning it off
|
|
14
|
+
// writes them back in the clear.
|
|
15
|
+
//
|
|
16
|
+
// Limit, stated: while LOCKED the overlay is empty, so a protected key reads as absent (the app looks signed out under
|
|
17
|
+
// the lock screen) and a write made while locked lives only in the overlay until the next unlock persists it — a tab
|
|
18
|
+
// closed while locked loses that write. Boot waits for the unlock, so in practice nothing reads or writes before it.
|
|
19
|
+
import { importRaw, seal, open, isSealed } from './deviceSeal.js'
|
|
20
|
+
import { makeNamer, isOpaqueName } from './sealedNames.js'
|
|
21
|
+
|
|
22
|
+
export const PROTECTED_PREFIXES = Object.freeze([
|
|
23
|
+
'space:vault', // the backup master
|
|
24
|
+
'space:id:', // room signing identities (private keys)
|
|
25
|
+
'space:sign:', // room signing keypairs carried for the backup
|
|
26
|
+
'space:myphoto', 'space:myphoto:safe', 'space:mykey:', // your profile picture and its safe copy (profilePhoto.js)
|
|
27
|
+
'space:faces', // pictures of people seen in verified Spaces, by email (profilePhoto.js)
|
|
28
|
+
'space:us:', 'space:spc:', // split-key shares + commitments
|
|
29
|
+
'space:mk:', // room keys (the worker is the store when protected; any leftover is sealed too)
|
|
30
|
+
'space:installHelp', // the retired built-in install help's room + its key — an older device may still hold one (docs/install-help.md)
|
|
31
|
+
'space:compsec', // each paired computer's security check: its weak spots (codeSecurity.js)
|
|
32
|
+
'space:tok:', 'space:esession', 'space:google-pending', // sign-in tokens, the email-session anchor, a browser sign-in waiting across a restart (its key)
|
|
33
|
+
'space:acctv2', // account recovery v2's state (acctV2App.js): the account id and its email (exact — `space:acctv2:base` stays clear)
|
|
34
|
+
'space:acctv2:reset', // an email move this device started (acctV2App.js RESET_KEY, § 11.5): its id and the address
|
|
35
|
+
'space:acctv2:erase', // "Delete my account"'s request while its answer is unknown (acctV2App.js ERASE_KEY, 10·Q#3): a device signature and a used email ticket
|
|
36
|
+
'space:awshandle', // THIS device's own AWS key (a handle on the person's AWS budget — acctV2Wiring.js awsHandleStore): its PRIVATE half
|
|
37
|
+
'space:invitekey', 'space:acctkey', // the invite key, the account-store key
|
|
38
|
+
'space:attestedBox:', // an attested kind's invite box — its PRIVATE half (attestedBox.js), like the invite key above
|
|
39
|
+
'space:connectionKeys', 'space:siri', 'space:a2a', 'space:code', 'space:clouddevice', // Connections call keys, the Siri inbox key, outside-agent keys, the Code pairing
|
|
40
|
+
'space:connPending', 'space:androidConsent', // pending grants and the short-lived key for an Android connector return
|
|
41
|
+
'space:contacts', 'space:agentlinks', 'space:recents', // content: people, agent links, the room list with its titles
|
|
42
|
+
'space:blocks', // the people you blocked (blocks.js) — names and @usernames
|
|
43
|
+
'space:chat-locks', // THE CHAT LOCK (chatLockStore.js): which chats are locked, and the wrong-PIN count
|
|
44
|
+
'space:blocks:keys', // the keys seen writing for a blocked email (blocksPush.js) — emails
|
|
45
|
+
'space:share-in', 'space:share-last', // shareIn.js: words shared from another app (sessionStorage), the Space last shared into
|
|
46
|
+
'space:moved-unsent:', // space.js keepUnsentForMove: words you wrote that a moved room refused, carried to the new room's box (sessionStorage)
|
|
47
|
+
'space:away-unsent:', // space.js keepUnsentAway: words a Space refused after you had left it, kept for your return (sessionStorage; sync sweep 11-21 #7)
|
|
48
|
+
'space:crossed:', // content: the lines you authored that crossed into a shared room
|
|
49
|
+
'space:inviteowed:', // rekeyMembers.js: the people a member change added whose invites are still to go (their emails)
|
|
50
|
+
// The 2026-10-10 audit (the owner: "Make sure that everything is encrypted when the lock is on") — every remaining store
|
|
51
|
+
// that holds a key or content: computers' pairing secrets + cloud computers' provider keys, the account index / pipes /
|
|
52
|
+
// temp-index pointers (each carries a room key), lane links (shared + lane keys), forked rooms' ancestor keys, the usage-
|
|
53
|
+
// receipt keys, the agenda, outside-agent tasks, your name / @username / email, contacts' reach, pinned file names, view
|
|
54
|
+
// labels — and the Code frame's own copies (it installs this module too: the computers, the direct-server password, the
|
|
55
|
+
// session list). Left clear: room ids, flags, settings, diagnostics, public keys.
|
|
56
|
+
'space:computers', 'space:cloud-computers', 'space:index-room', 'space:pipes-room', 'space:msgs-room', 'space:mail-handled', 'space:pipes', 'space:tempidx',
|
|
57
|
+
'space:epoch:', 'space:usagekey', 'space:usagekey:old', 'space:todos', 'space:events', 'space:a2a-pending',
|
|
58
|
+
'space:myname', 'space:username', 'space:myusers', 'space:acct-owner', 'space:recovery:owner-mismatch', 'space:reach', 'pinnedfiles:', 'viewmeta:',
|
|
59
|
+
'oc.computers', 'oc.pass', 'oc.list',
|
|
60
|
+
'space:negotiations', 'space:vaultprofile:', // legacy lane links (with their keys, migrated away) and the retired vault page's free-text profile
|
|
61
|
+
// THE VAULT's own stores (slice 4 — the hosted app's top-level origin, vault-loader.js): the derived keyring with the
|
|
62
|
+
// index/pipes pointers, the per-room email signing keypairs, the framed app's durable keys/tokens mirrored up, and the
|
|
63
|
+
// mirrored content (contacts, the room list with titles, the temp-room pointers, your name). `space:vault` above is the
|
|
64
|
+
// master there too. Left clear on purpose: `vault:lock` (the config), `vault:place`, the flags and the boot/tap trails.
|
|
65
|
+
'vault:acct', 'vault:esign:', 'vault:appkv', 'vault:contacts', 'vault:roomlist', 'vault:tempidx', 'vault:myname', 'vault:pending-cloud-signout' /* an email while the cloud device's sign-out is unconfirmed */,
|
|
66
|
+
'vault:acctsecrets', // the Siri / A2A inbox private keys and the Siri Shortcut key the vault holds for the app (vaultAcctSecrets.js)
|
|
67
|
+
])
|
|
68
|
+
export const isProtectedKey = (k) => { const s = String(k); return PROTECTED_PREFIXES.some((p) => (p.endsWith(':') ? s.startsWith(p) : s === p)) }
|
|
69
|
+
/** A FRAMED app's marker (clear, non-secret): "my framer protects this device" — set when our vault first hands the key over,
|
|
70
|
+
* cleared when protection is switched off. The framed app has no lock config of its own to read. */
|
|
71
|
+
export const FRAMED_MARK = 'space:protected'
|
|
72
|
+
/** Does a lock config (space:lock / vault:lock) say the device is protected? */
|
|
73
|
+
export const cfgSaysProtected = (c) => !!(c && c.on && c.protect && c.protect.on)
|
|
74
|
+
|
|
75
|
+
// PHASE 2 (docs/desktop-protection.md § Names; the owner, 2026-10-11: "Some metadata stays readable — why?"): on a protected
|
|
76
|
+
// device EVERY entry is sealed, not only the secrets above — room ids in `space:last`, the confidential-room list, the
|
|
77
|
+
// places trail, the flags — and stored under an OPAQUE name (sealedNames.js: `p:` + the encrypted real name), so a disk
|
|
78
|
+
// copy learns neither what is kept nor about which rooms. Only these stay readable: what the lock screen needs before the
|
|
79
|
+
// passkey (the lock configs) and the framed app's marker.
|
|
80
|
+
// And a reviewed handful of SETTINGS that name no room, no person and no activity, which modules read ONCE at load — before
|
|
81
|
+
// the unlock — so sealing them would reset them on every launch: feature flags, the side panel's width, the map language,
|
|
82
|
+
// the diagnostics switches, the boot counter and the PUBLIC app catalog. Anything naming a room or a person is sealed.
|
|
83
|
+
export const STAYS_CLEAR = Object.freeze(['witbitz-builder-reset-pending', 'space:lock', 'vault:lock', FRAMED_MARK,
|
|
84
|
+
'space:maplang', 'space:maplang.eff', 'space:mapsapp', 'space:settings:open', 'space:side', 'space:side-hidden', 'space:side-w', 'space:assistw',
|
|
85
|
+
'space:ohttp', 'space:caretdbg', 'space:rotlab', 'space:diag', 'space:notifPreview', 'space:boots', 'space:apps',
|
|
86
|
+
'space:channel', 'space:runAt', // Official / Beta / Pinned + the newest build time run (channelChoice.js): read before the unlock, or a locked device would fall back to Official
|
|
87
|
+
'space:strictfiles', // Strict file viewing (strictFiles.js): sealed, a locked device would read it as off and draw others' files behind the lock screen
|
|
88
|
+
'space:autoupdate', // "Update automatically" (updateState.js): sealed, a locked device read it as On and updated behind the lock screen (sync sweep, 10-16)
|
|
89
|
+
'space:atrest', // the regular app's storage is sealed by its DEVICE key (spaceAtRest.js SPACE_AT_REST_MARK): read at load, so its reads wait for the boot's unlock
|
|
90
|
+
'vault:atrest', // the hosted vault's storage is sealed by its DEVICE key (vaultDeviceKey.js AT_REST_MARK): read at load, so its reads wait for the boot's unlock
|
|
91
|
+
'vault:repairAt']) // a time only: when the vault's boot guard last repaired (vault-boot-guard.js) — read before any unlock (sync sweep 10-21 #9)
|
|
92
|
+
// + the sign-in callbacks' hand-back: written by a page that holds no key (github-callback.html, mcp-callback.html) and
|
|
93
|
+
// removed once read (connections.js) — sealed, a protected device never finished that path (sync sweep 10-20 #8)
|
|
94
|
+
export const STAYS_CLEAR_PREFIXES = Object.freeze(['space:flag:', 'space:ghcb:', 'space:mcpcb:'])
|
|
95
|
+
// Logs every writer APPENDS to (a JSON array of lines, capped like the writers cap it): unlocking joins their copies.
|
|
96
|
+
const APPEND_LOGS = Object.freeze(['space:bootlog', 'vault:bootlog']), LOG_CAP = 1000
|
|
97
|
+
const staysClear = (k) => { const s = String(k); return STAYS_CLEAR.includes(s) || STAYS_CLEAR_PREFIXES.some((p) => s.startsWith(p)) }
|
|
98
|
+
const sealsHere = (k) => !staysClear(k) && !isOpaqueName(String(k)) // on a protected device: everything else
|
|
99
|
+
|
|
100
|
+
const overlay = new Map() // real name → clear string, while unlocked (or memory-only)
|
|
101
|
+
const lockedWrites = new Map() // real name → value | null (a removal): written while LOCKED, applied over the disk at unlock
|
|
102
|
+
let active = false // the switch is on for THIS surface
|
|
103
|
+
let key = null // the device's AES key (values) while unlocked
|
|
104
|
+
// ⛔ A RELOCK IS NOT A NEW KEY (2026-11-08, docs/state-machines.md I16 / A#11): a sealed write still on its way when the lock engaged
|
|
105
|
+
// was dropped (`key !== k`) — the value was gone at the next unlock. Made under that key, it is still that key's: only a change of
|
|
106
|
+
// the protection itself (switched on or off, released, memory-only) retires writes in flight. `sealGen` counts those.
|
|
107
|
+
let sealGen = 0
|
|
108
|
+
let namer = null // the device's name keys (sealedNames.makeNamer) while unlocked
|
|
109
|
+
let raw = null // the original Storage.prototype methods
|
|
110
|
+
let names = null // the enumeration cache: the real names key(i)/length answer while active
|
|
111
|
+
let readyResolve = null, readyPromise = Promise.resolve()
|
|
112
|
+
// A pending promise is KEPT: a relock while someone already waits (the vault's boot awaits this, and the launch lock's onLock
|
|
113
|
+
// relocks after it started waiting) must not orphan them — the unlock settles the promise they hold (2026-10-13: the hosted
|
|
114
|
+
// app unlocked into an empty window on every protected launch).
|
|
115
|
+
const armReady = () => { if (readyResolve) return; readyPromise = new Promise((r) => { readyResolve = r }) }
|
|
116
|
+
const settleReady = () => { if (readyResolve) { readyResolve(); readyResolve = null } }
|
|
117
|
+
|
|
118
|
+
/** True while a protected key must be answered from the overlay. */
|
|
119
|
+
export const protectedLocalActive = () => active
|
|
120
|
+
/** Boot awaits this: resolved at once when inactive; after the unlock has filled the overlay when active. */
|
|
121
|
+
export const protectedLocalReady = () => readyPromise
|
|
122
|
+
/** A protected key can be read AND written truly now (inactive, unlocked, or memory-only) — while locked a read answers absent
|
|
123
|
+
* and a write would replace the sealed value at the unlock (vaultConnKeys.js asks before it merges). */
|
|
124
|
+
export const protectedLocalOpen = () => !active || !!key || memoryOnly
|
|
125
|
+
/** The stored bytes under a key, unwrapped by nothing — what a disk copy would see. */
|
|
126
|
+
export const rawGet = (k) => (raw ? raw.getItem.call(localStorage, k) : localStorage.getItem(k))
|
|
127
|
+
/** Every key as stored on disk (opaque names included) — what a disk copy would list. */
|
|
128
|
+
export const rawKeys = () => { const out = []; const n = raw ? rawLength() : localStorage.length; for (let i = 0; i < n; i++) { const k = raw ? raw.key.call(localStorage, i) : localStorage.key(i); if (k != null) out.push(k) } return out }
|
|
129
|
+
// On a fresh reset boot the overlay is still locked. Remove the actual stored names, including opaque ones.
|
|
130
|
+
export function clearLocalForBuilderReset(marker) {
|
|
131
|
+
for (const name of rawKeys()) if (name !== marker) {
|
|
132
|
+
if (raw) raw.removeItem.call(localStorage, name)
|
|
133
|
+
else localStorage.removeItem(name)
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
let lengthDesc = null
|
|
137
|
+
const rawLength = () => (lengthDesc ? lengthDesc.get.call(localStorage) : localStorage.length)
|
|
138
|
+
|
|
139
|
+
// Disk writes are async (WebCrypto) and must land in the order they were made: one chain.
|
|
140
|
+
let chain = Promise.resolve()
|
|
141
|
+
const onDisk = (fn) => { chain = chain.then(fn).catch(() => {}); return chain }
|
|
142
|
+
const writeSealed = (name, v) => { const k = key, nm = namer, g = sealGen; if (!k || !nm) return; onDisk(async () => { const o = await nm.opaque(name); const blob = await seal(k, v); if (sealGen !== g) return; try { raw.setItem.call(localStorage, o, JSON.stringify(blob)) } catch { /* private mode / full */ } try { raw.removeItem.call(localStorage, name) } catch { /* */ } }) }
|
|
143
|
+
const removeSealed = (name) => { const nm = namer; if (!nm) return; onDisk(async () => { try { raw.removeItem.call(localStorage, await nm.opaque(name)) } catch { /* */ } }) }
|
|
144
|
+
/** Resolves once every queued disk write has landed (tests, and the switch-off). */
|
|
145
|
+
export const protectedLocalFlushed = () => chain
|
|
146
|
+
/** What is ON DISK for `name` once the queued writes have landed — opened as a protected read would open it; null when
|
|
147
|
+
* nothing is there or it cannot be kept (locked, memory-only). Writes swallow their errors (a full or private store), so a
|
|
148
|
+
* caller that must know a value is durable reads it back here (account recovery v2: a new recovery code is kept BEFORE
|
|
149
|
+
* its activation is sent — implementation review R2-03). */
|
|
150
|
+
export async function durableRead (name) {
|
|
151
|
+
await chain
|
|
152
|
+
if (!active || !raw) return rawGet(name)
|
|
153
|
+
if (memoryOnly || !key || !namer) return null
|
|
154
|
+
try {
|
|
155
|
+
const v = raw.getItem.call(localStorage, await namer.opaque(name))
|
|
156
|
+
const blob = v && parseSealed(v)
|
|
157
|
+
return blob ? String(await open(key, blob)) : null
|
|
158
|
+
} catch { return null }
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
// LOCKED or MEMORY-ONLY, an entry still CLEAR on disk (never migrated: an unsecured computer, or a flag an older build wrote)
|
|
162
|
+
// reads through — unless it is a secret: those are only ever answered by the overlay.
|
|
163
|
+
const readThrough = (n) => { if (isProtectedKey(n)) return null; const v = raw.getItem.call(localStorage, n); return v != null && !parseSealed(v) ? v : null }
|
|
164
|
+
const enumerate = () => {
|
|
165
|
+
if (names) return names
|
|
166
|
+
const set = new Set(overlay.keys())
|
|
167
|
+
for (const [n, v] of lockedWrites) if (v != null) set.add(n)
|
|
168
|
+
for (const k of rawKeys()) if (!isOpaqueName(k) && (staysClear(k) || (!key && readThrough(k) != null))) set.add(k)
|
|
169
|
+
names = [...set]; return names
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/** Wrap Storage.prototype once (idempotent). `proto` is injectable for tests. */
|
|
173
|
+
export function installProtectedLocal (proto = (typeof Storage !== 'undefined' ? Storage.prototype : null), { on = false } = {}) {
|
|
174
|
+
if (!proto || raw) { if (on && !active) { active = true; names = null; armReady() } return }
|
|
175
|
+
raw = { getItem: proto.getItem, setItem: proto.setItem, removeItem: proto.removeItem, clear: proto.clear, key: proto.key }
|
|
176
|
+
lengthDesc = Object.getOwnPropertyDescriptor(proto, 'length') || null
|
|
177
|
+
const mine = (t) => active && t === localStorage
|
|
178
|
+
proto.getItem = function (k) {
|
|
179
|
+
if (!mine(this) || !sealsHere(k)) return raw.getItem.call(this, k)
|
|
180
|
+
const n = String(k); if (overlay.has(n)) return overlay.get(n)
|
|
181
|
+
if (lockedWrites.has(n)) return lockedWrites.get(n)
|
|
182
|
+
if (!key && !memoryOnly && lockedReads.size < 200) lockedReads.add(n) // a read made before the unlock answers absent: kept so it can be seen (protectedLocalLockedReads)
|
|
183
|
+
return key ? null : readThrough(n)
|
|
184
|
+
}
|
|
185
|
+
proto.setItem = function (k, v) {
|
|
186
|
+
if (!mine(this) || !sealsHere(k)) return raw.setItem.call(this, k, v)
|
|
187
|
+
const n = String(k), s = String(v); names = null
|
|
188
|
+
if (key) { overlay.set(n, s); writeSealed(n, s) } else if (memoryOnly) overlay.set(n, s); else lockedWrites.set(n, s)
|
|
189
|
+
}
|
|
190
|
+
proto.removeItem = function (k) {
|
|
191
|
+
if (!mine(this) || !sealsHere(k)) return raw.removeItem.call(this, k)
|
|
192
|
+
const n = String(k); names = null; overlay.delete(n)
|
|
193
|
+
if (key) { removeSealed(n); try { raw.removeItem.call(this, n) } catch { /* */ } } else if (!memoryOnly) lockedWrites.set(n, null)
|
|
194
|
+
}
|
|
195
|
+
proto.clear = function () { if (this === localStorage) { overlay.clear(); lockedWrites.clear(); names = null; if (memoryOnly) return } return raw.clear.call(this) } // memory-only: the disk (an account, sealed entries) is never touched
|
|
196
|
+
proto.key = function (i) { if (!mine(this)) return raw.key.call(this, i); const a = enumerate(); return i >= 0 && i < a.length ? a[i] : null }
|
|
197
|
+
if (lengthDesc && lengthDesc.get) Object.defineProperty(proto, 'length', { configurable: true, enumerable: lengthDesc.enumerable, get () { return mine(this) ? enumerate().length : lengthDesc.get.call(this) } })
|
|
198
|
+
if (on) { active = true; armReady() }
|
|
199
|
+
}
|
|
200
|
+
let memoryOnly = false
|
|
201
|
+
const lockedReads = new Set()
|
|
202
|
+
/** The names read while LOCKED (answered absent) — a module that read a setting at load, before the unlock, shows up here. */
|
|
203
|
+
export const protectedLocalLockedReads = () => [...lockedReads]
|
|
204
|
+
|
|
205
|
+
const parseSealed = (s) => { try { const o = JSON.parse(s); return isSealed(o) ? o : null } catch { return null } }
|
|
206
|
+
|
|
207
|
+
/** Switch ON / unlock: import the device key, fill the overlay from disk — opaque entries opened; phase-1 entries (sealed
|
|
208
|
+
* under their own names) and clear entries MOVED under opaque names — apply what was written while locked, then answer
|
|
209
|
+
* `ready()`. A wrong key throws on the first sealed entry and changes nothing. */
|
|
210
|
+
//
|
|
211
|
+
// `switchOn`: protection is being TURNED ON with a new passkey (spaceLock.enableProtection). Protection was off, so no lock
|
|
212
|
+
// names a passkey for whatever sealed entries are still here — an earlier setup's leftovers (a reset, site data cleared in
|
|
213
|
+
// part): nothing can ever open them. They are dropped rather than refused — refusing failed every "Secure this computer"
|
|
214
|
+
// for good, each retry a new passkey that opened none of them (the owner's second desktop, 2026-10-29: protect_failed).
|
|
215
|
+
// A GUEST'S VISIT STAYS MEMORY-ONLY (sync sweep 11-04 #1, #5): an unlock would turn memory-only off and write the visit into the
|
|
216
|
+
// account's storage; a "forget" would delete this device's sealed entries. During the demo's temporary room neither happens.
|
|
217
|
+
const guestVisit = () => { try { return memoryOnly && typeof location !== 'undefined' && isGuestTempRoom(location) } catch { return false } }
|
|
218
|
+
export async function unlockProtectedLocal (rawKey, { switchOn = false, also = [] } = {}) {
|
|
219
|
+
if (guestVisit()) return
|
|
220
|
+
if (!raw) installProtectedLocal()
|
|
221
|
+
await chain // a second unlock (the frame takes the key at its store's hand-over, then again from framedProtect): writes still on their way land first, or the disk read below would put an older value back
|
|
222
|
+
const k = await importRaw(rawKey), nm = await makeNamer(rawKey)
|
|
223
|
+
// ⛔ 10·V#1 (pass 10): THE OTHER KEY THIS DEVICE KNOWS (`also` — the device storage key, while a passkey protects it). A switch between
|
|
224
|
+
// them killed half-way left entries under BOTH keys' names: a resumed switch-on removed every name the passkey could not read (the
|
|
225
|
+
// entries not yet re-keyed — the account master among them), and a switch-off that finished its re-key before the lock's config
|
|
226
|
+
// said so left a passkey that "opens nothing here" for good. A name another known key opens is CARRIED: re-sealed under this key,
|
|
227
|
+
// then its old name goes. Nothing a known key can open is ever removed.
|
|
228
|
+
const others = []
|
|
229
|
+
for (const r of (Array.isArray(also) ? also : [also])) { if (!r) continue; try { others.push({ k: await importRaw(r), nm: await makeNamer(r) }) } catch { /* not a key */ } }
|
|
230
|
+
const next = new Map(), move = [], stale = []
|
|
231
|
+
let opaque = 0, ours = 0
|
|
232
|
+
// ALL AT ONCE (2026-11-17, the owner's iPhone: "storage opened with the device key in 223 ms"): WebKit answers each WebCrypto call
|
|
233
|
+
// on another thread, so ~1200 entries × 3 calls awaited one by one cost 127 ms in WebKit here, issued together 4 ms (Chromium: 11 / 9).
|
|
234
|
+
// Every entry is opened first, then taken in the disk's order below — the same outcome, the same throws.
|
|
235
|
+
const entries = []
|
|
236
|
+
for (const stored of rawKeys()) {
|
|
237
|
+
if (staysClear(stored)) continue
|
|
238
|
+
const v = raw.getItem.call(localStorage, stored); if (v == null) continue
|
|
239
|
+
entries.push([stored, v])
|
|
240
|
+
}
|
|
241
|
+
const opened = await Promise.all(entries.map(async ([stored, v]) => {
|
|
242
|
+
if (isOpaqueName(stored)) {
|
|
243
|
+
const name = await nm.real(stored)
|
|
244
|
+
if (name == null) { // not this key's name: another key this device knows (10·V#1), else another key's leftover
|
|
245
|
+
for (const o of others) {
|
|
246
|
+
const n2 = await o.nm.real(stored); if (n2 == null) continue
|
|
247
|
+
const blob = parseSealed(v); if (!blob) return { stale: true }
|
|
248
|
+
try { return { name: n2, clear: String(await open(o.k, blob)), carried: true } } catch { return { stale: true } }
|
|
249
|
+
}
|
|
250
|
+
return { stale: true }
|
|
251
|
+
}
|
|
252
|
+
const blob = parseSealed(v); if (!blob) return { name, skip: true }
|
|
253
|
+
return { name, clear: String(await open(k, blob)) }
|
|
254
|
+
}
|
|
255
|
+
const blob = parseSealed(v)
|
|
256
|
+
if (blob && isProtectedKey(stored)) { // phase 1: sealed under its own name
|
|
257
|
+
try { return { clear: String(await open(k, blob)) } } catch (e) { if (!switchOn) throw e; return { stale: true } }
|
|
258
|
+
}
|
|
259
|
+
return { clear: v } // clear: never protected before, or written by an older build
|
|
260
|
+
}))
|
|
261
|
+
const logCopies = new Map() // an APPEND LOG's every copy, merged below — never one copy replacing another
|
|
262
|
+
const carried = [], carriedNames = new Set() // 10·V#1: entries another known key opened — re-sealed under this one, then their old names go
|
|
263
|
+
entries.forEach(([stored], i) => {
|
|
264
|
+
const r = opened[i]
|
|
265
|
+
if (isOpaqueName(stored)) {
|
|
266
|
+
opaque++
|
|
267
|
+
if (r.stale) { stale.push(stored); return }
|
|
268
|
+
if (r.carried) { ours++; carried.push(stored); if (!next.has(r.name)) { next.set(r.name, r.clear); carriedNames.add(r.name) } return } // this key's own copy, where there is one, is the newer
|
|
269
|
+
ours++
|
|
270
|
+
if (!r.skip) { next.set(r.name, r.clear); if (APPEND_LOGS.includes(r.name)) logCopies.set(r.name, [r.clear, ...(logCopies.get(r.name) || [])]) } // the sealed copy is the older history: first
|
|
271
|
+
} else {
|
|
272
|
+
if (r.stale) { stale.push(stored); return }
|
|
273
|
+
next.set(stored, r.clear)
|
|
274
|
+
if (APPEND_LOGS.includes(stored)) logCopies.set(stored, [...(logCopies.get(stored) || []), r.clear])
|
|
275
|
+
move.push(stored)
|
|
276
|
+
}
|
|
277
|
+
})
|
|
278
|
+
// THE BOOT LOG KEEPS EVERY LINE (2026-11-17, the owner's iPhone sealed by the device key: each Diagnostics showed ONE launch, and one
|
|
279
|
+
// lost every line after the unlock). The loader writes its lines to a CLEAR `space:bootlog` before this module runs, the sealed copy
|
|
280
|
+
// holds the history, and a line written while locked waits in lockedWrites — whichever the disk listed last replaced the others,
|
|
281
|
+
// and a locked write was dropped because the disk had the name. Now the copies are joined (history first, each line once, the cap kept).
|
|
282
|
+
const logWritten = []
|
|
283
|
+
for (const n of APPEND_LOGS) {
|
|
284
|
+
const parts = [...(logCopies.get(n) || []), lockedWrites.get(n)].filter((v) => v != null)
|
|
285
|
+
if (parts.length < 2) continue
|
|
286
|
+
const seen = new Set(), lines = []
|
|
287
|
+
for (const v of parts) { let a = null; try { a = JSON.parse(v) } catch { a = null } if (!Array.isArray(a)) continue; for (const l of a) { const t = String(l); if (!seen.has(t)) { seen.add(t); lines.push(t) } } }
|
|
288
|
+
while (lines.length > LOG_CAP) lines.shift()
|
|
289
|
+
next.set(n, JSON.stringify(lines)); lockedWrites.delete(n); logWritten.push(n)
|
|
290
|
+
}
|
|
291
|
+
if (opaque && !ours && !switchOn) throw new Error('this key opens nothing here') // a wrong key: every name fails to open, change nothing
|
|
292
|
+
if (switchOn) for (const n of stale) { try { raw.removeItem.call(localStorage, n) } catch { /* */ } }
|
|
293
|
+
// A write made while locked is kept only where the disk has NOTHING under that name: a module that found a value "missing"
|
|
294
|
+
// at load (it was sealed) and wrote a default — a fresh device id, an empty list — must never replace the real one.
|
|
295
|
+
const written = []
|
|
296
|
+
for (const [n, v] of lockedWrites) if (v != null && !next.has(n)) { next.set(n, v); written.push(n) }
|
|
297
|
+
const removed = []
|
|
298
|
+
if (switchOn) sealGen++ // a new protection: writes made under another one are not this one's
|
|
299
|
+
key = k; namer = nm; active = true; memoryOnly = false; names = null
|
|
300
|
+
overlay.clear(); for (const [n, v] of next) overlay.set(n, v)
|
|
301
|
+
lockedWrites.clear()
|
|
302
|
+
for (const n of new Set([...move, ...written, ...logWritten, ...carriedNames])) if (overlay.has(n)) writeSealed(n, overlay.get(n))
|
|
303
|
+
if (carried.length) { await chain; for (const o of carried) { try { raw.removeItem.call(localStorage, o) } catch { /* */ } } } // written under this key first (10·V#1)
|
|
304
|
+
settleReady()
|
|
305
|
+
// Modules that cached a value at load (read while locked → absent) re-read it now: enclave.js (the confidential rooms),
|
|
306
|
+
// trustedBuilds.js, unread.js. An event, not an import — the SDK shares those modules and must not install this one.
|
|
307
|
+
try { if (typeof dispatchEvent === 'function' && typeof Event === 'function') dispatchEvent(new Event('wb-protected-unlocked')) } catch { /* */ }
|
|
308
|
+
return { entries: next.size, migrated: move.length }
|
|
309
|
+
}
|
|
310
|
+
/** RE-KEY (docs/vault-at-rest-and-invites-plan.md § 1): the storage, sealed and open under one key, is written again under another —
|
|
311
|
+
* the hosted vault's device key ↔ a passkey's. Every entry in the overlay is sealed under the new key's opaque name FIRST, then the
|
|
312
|
+
* old key's opaque names go: never a clear moment on disk. Unlocked only; throws when locked (nothing would be carried). */
|
|
313
|
+
export async function rekeyProtectedLocal (newRaw) {
|
|
314
|
+
if (!raw || !active || !key || !namer) throw new Error('rekey: not unlocked')
|
|
315
|
+
await chain
|
|
316
|
+
const oldNm = namer, k = await importRaw(newRaw), nm = await makeNamer(newRaw)
|
|
317
|
+
const old = []
|
|
318
|
+
for (const stored of rawKeys()) if (isOpaqueName(stored) && (await oldNm.real(stored)) != null) old.push(stored)
|
|
319
|
+
sealGen++; key = k; namer = nm; names = null
|
|
320
|
+
for (const [n, v] of overlay) writeSealed(n, v)
|
|
321
|
+
await chain
|
|
322
|
+
for (const o of old) { try { raw.removeItem.call(localStorage, o) } catch { /* */ } }
|
|
323
|
+
return { entries: overlay.size, moved: old.length }
|
|
324
|
+
}
|
|
325
|
+
/** Relock: nothing readable stays in memory; the sealed blobs stay on disk. */
|
|
326
|
+
export function relockProtectedLocal () { overlay.clear(); lockedWrites.clear(); key = null; namer = null; names = null; memoryOnly = false; if (active) armReady() }
|
|
327
|
+
/** MEMORY ONLY (docs/desktop-protection.md, a room link on an unsecured computer): every entry but the lock config is
|
|
328
|
+
* answered from and written to the overlay alone — nothing reaches the disk — and boot is not held. */
|
|
329
|
+
export function memoryOnlyProtectedLocal () { sealGen++; if (!raw) installProtectedLocal(); overlay.clear(); lockedWrites.clear(); key = null; namer = null; names = null; memoryOnly = true; active = true; settleReady() }
|
|
330
|
+
/** Switch OFF: every entry back in the clear under its real name; the opaque entries go; the wrappers pass through again. */
|
|
331
|
+
export async function unprotectProtectedLocal (rawKey) {
|
|
332
|
+
if (!raw) installProtectedLocal()
|
|
333
|
+
await chain
|
|
334
|
+
const k = await importRaw(rawKey), nm = await makeNamer(rawKey)
|
|
335
|
+
for (const stored of rawKeys()) {
|
|
336
|
+
const v = raw.getItem.call(localStorage, stored); if (v == null) continue
|
|
337
|
+
if (isOpaqueName(stored)) {
|
|
338
|
+
const name = await nm.real(stored); const blob = parseSealed(v)
|
|
339
|
+
if (name != null && blob) raw.setItem.call(localStorage, name, String(await open(k, blob)))
|
|
340
|
+
if (name != null) raw.removeItem.call(localStorage, stored)
|
|
341
|
+
} else if (isProtectedKey(stored)) { const blob = parseSealed(v); if (blob) raw.setItem.call(localStorage, stored, String(await open(k, blob))) } // phase 1
|
|
342
|
+
}
|
|
343
|
+
sealGen++; overlay.clear(); lockedWrites.clear(); key = null; namer = null; names = null; memoryOnly = false; active = false; settleReady()
|
|
344
|
+
}
|
|
345
|
+
/** A FRAMED app whose framer no longer protects the device (the marker is stale, or the vault never answered): the sealed
|
|
346
|
+
* entries cannot be opened without a key that is gone — drop them (they are mirrors the vault seeds back) and pass through. */
|
|
347
|
+
export function forgetProtectedLocal () { if (guestVisit()) return;
|
|
348
|
+
if (!raw) installProtectedLocal()
|
|
349
|
+
for (const stored of rawKeys()) { const v = raw.getItem.call(localStorage, stored); if (isOpaqueName(stored) || (v != null && parseSealed(v))) { try { raw.removeItem.call(localStorage, stored) } catch { /* */ } } }
|
|
350
|
+
try { raw.removeItem.call(localStorage, FRAMED_MARK) } catch { /* */ }
|
|
351
|
+
sealGen++; overlay.clear(); lockedWrites.clear(); key = null; namer = null; names = null; memoryOnly = false; active = false; settleReady()
|
|
352
|
+
}
|
|
353
|
+
/** A FRAME whose parent switched protection off: the parent wrote every entry back in the clear — just pass through. */
|
|
354
|
+
export function releaseProtectedLocal () { sealGen++; overlay.clear(); lockedWrites.clear(); key = null; namer = null; names = null; memoryOnly = false; active = false; settleReady() }
|
|
355
|
+
// ANOTHER DOCUMENT of this origin wrote an entry (the app and its Code frame share localStorage, each with its own overlay):
|
|
356
|
+
// take the new value into this overlay, so neither reads a stale copy until it reloads.
|
|
357
|
+
try {
|
|
358
|
+
if (typeof window !== 'undefined') addEventListener('storage', (e) => {
|
|
359
|
+
if (!active || !key || !namer || !e.key || e.storageArea !== localStorage || !isOpaqueName(e.key)) return
|
|
360
|
+
const k = key, nm = namer
|
|
361
|
+
nm.real(e.key).then((name) => {
|
|
362
|
+
if (name == null || key !== k) return
|
|
363
|
+
names = null
|
|
364
|
+
if (e.newValue == null) { overlay.delete(name); return }
|
|
365
|
+
const blob = parseSealed(e.newValue); if (blob) open(k, blob).then((v) => { if (key === k) overlay.set(name, String(v)) }).catch(() => {})
|
|
366
|
+
}).catch(() => {})
|
|
367
|
+
})
|
|
368
|
+
} catch { /* no window */ }
|
|
369
|
+
// SELF-INSTALL at import. This module is the FIRST import of space.js (and of vault-loader.js), so it evaluates before any
|
|
370
|
+
// module that reads a protected key; it wraps the prototype once and switches on when the device is protected (active ⇒
|
|
371
|
+
// reads answer null until the unlock fills the overlay). A TOP-LEVEL page owns a lock: the standalone app's `space:lock`
|
|
372
|
+
// or the vault's `vault:lock`. A FRAMED app owns none — its framer (our vault, slice 4) hands it the key, and the marker it
|
|
373
|
+
// leaves says to start sealed; framed by anyone else, or unmarked, nothing happens.
|
|
374
|
+
try {
|
|
375
|
+
if (typeof window !== 'undefined' && typeof Storage !== 'undefined') {
|
|
376
|
+
const rawGet0 = (k) => { try { return Storage.prototype.getItem.call(localStorage, k) } catch { return null } }
|
|
377
|
+
const cfgOn = (k) => { try { return cfgSaysProtected(JSON.parse(rawGet0(k) || 'null')) } catch { return false } }
|
|
378
|
+
// a SAME-ORIGIN frame of the app (the Code section, codeView.js) shares its localStorage: it reads the app's own lock
|
|
379
|
+
// config, and the app hands it the key ({ch:'codeProtect'}), exactly as idbSeal.js does for the idb
|
|
380
|
+
let sameOriginFramed = false; try { sameOriginFramed = window.top !== window && window.parent.location.origin === location.origin } catch { sameOriginFramed = false }
|
|
381
|
+
// A same-origin frame shares only the APP's lock (space:lock — the Code frame inside the app). The vault's vault:lock is
|
|
382
|
+
// the vault's own: an app the vault frames on its origin (dev, a test fixture) waits for the vault's hand-off marker,
|
|
383
|
+
// never reads that config as its own and sits sealed waiting for a key (2026-10-13, vaultProtect).
|
|
384
|
+
const on = window.top === window ? (cfgOn('space:lock') || cfgOn('vault:lock') || rawGet0(FRAMED_MARK) === '1' || rawGet0('vault:atrest') === '1' || rawGet0('space:atrest') === '1')
|
|
385
|
+
: sameOriginFramed ? (cfgOn('space:lock') || rawGet0(FRAMED_MARK) === '1' || rawGet0('space:atrest') === '1') : rawGet0(FRAMED_MARK) === '1' // space:atrest: the app's device key (spaceAtRest.js) — a same-origin frame (Code, the lane panel) waits for its parent's hand-off
|
|
386
|
+
installProtectedLocal(Storage.prototype, { on })
|
|
387
|
+
// A GUEST'S TEMPORARY ROOM (the HN demo's link: ?room=tmp-…, #…guest=1 — the app's address, regular or framed by the vault):
|
|
388
|
+
// the visitor came to look, so NOTHING of the visit reaches the disk — memory-only from this module's first line, before
|
|
389
|
+
// any module writes a device id, a boot log or the room's settings (the owner, 2026-11-04: "Fix Secure this computer"; the
|
|
390
|
+
// hosted frame kept space:model:<room>, space:tempidx, space:usagekey … in its own storage). On a PROTECTED device too: the
|
|
391
|
+
// visit reads nothing sealed and writes nothing, so it needs no unlock (the owner's computer: the demo met "Spaces is locked").
|
|
392
|
+
if (isGuestTempRoom(location)) memoryOnlyProtectedLocal()
|
|
393
|
+
}
|
|
394
|
+
} catch { /* no storage (a worker, a sandbox): nothing to protect here */ }
|
|
395
|
+
|
|
396
|
+
/** The demo's guest link for a temporary room: ?room=tmp-… with guest=1 — after the # (the app's address, the frame's) or in
|
|
397
|
+
* the query (the vault's own link, hnPage.js vaultLinkOf). THE one test: nameGate.js, encHint.js and space.js ask it too — a
|
|
398
|
+
* guest=1 on any other room changes nothing (sync sweep 11-04 #7, #12). */
|
|
399
|
+
export function isGuestTempRoom (loc) {
|
|
400
|
+
try {
|
|
401
|
+
const q = new URLSearchParams(loc.search || '')
|
|
402
|
+
return (/[#&]guest=1(?:&|$)/.test(String(loc.hash || '')) || q.get('guest') === '1') && String(q.get('room') || '').startsWith('tmp-')
|
|
403
|
+
} catch { return false }
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
/** For tests: forget the wrapping (restores the prototype). */
|
|
407
|
+
export function _uninstallProtectedLocal (proto = (typeof Storage !== 'undefined' ? Storage.prototype : null)) {
|
|
408
|
+
if (!raw || !proto) return
|
|
409
|
+
Object.assign(proto, raw); if (lengthDesc) Object.defineProperty(proto, 'length', lengthDesc); raw = null; lengthDesc = null; overlay.clear(); lockedWrites.clear(); key = null; namer = null; names = null; memoryOnly = false; active = false; readyPromise = Promise.resolve(); readyResolve = null
|
|
410
|
+
}
|
package/pushCore.js
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
// pushCore.js — THE PUSH SUBSCRIPTION, ONE IMPLEMENTATION FOR BOTH APPS (docs/convergence-review-2026-10-17.md, step 2). The
|
|
2
|
+
// regular app (notifications.js) and the tenant vault (vault-loader.js — it owns push for the framed app) each had their
|
|
3
|
+
// own; the vault's subscribe had none of the iOS lessons the regular one learned. Leaf module: no DOM beyond what is passed.
|
|
4
|
+
import { nativeRegistration } from './nativePush.js' // the Android / Windows app's registration (no service worker needed)
|
|
5
|
+
|
|
6
|
+
/** A base64URL VAPID public key → the bytes pushManager.subscribe wants. */
|
|
7
|
+
export function vapidBytes (s) {
|
|
8
|
+
const t = (String(s) + '='.repeat((4 - (String(s).length % 4)) % 4)).replace(/-/g, '+').replace(/_/g, '/')
|
|
9
|
+
const b = atob(t); const u = new Uint8Array(b.length)
|
|
10
|
+
for (let i = 0; i < b.length; i++) u[i] = b.charCodeAt(i)
|
|
11
|
+
return u
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/** The page's service-worker registration, ACTIVE — bounded. `navigator.serviceWorker.ready` waits for ever when the
|
|
15
|
+
* registration is gone (the update fail-safe unregisters it), and every push path then hangs with no error: re-register a
|
|
16
|
+
* missing one, and give up with a readable error after `ms`. */
|
|
17
|
+
export async function swRegBounded ({ ms = 8000, sw = (typeof navigator !== 'undefined' ? navigator.serviceWorker : null), path = '/sw.js', sleep = (r) => setTimeout(r, 250), native = nativeRegistration } = {}) {
|
|
18
|
+
if (!sw) { const nr = native(); if (nr) return nr; throw new Error('no service worker support') }
|
|
19
|
+
let reg = null
|
|
20
|
+
try { reg = await sw.getRegistration() } catch { /* */ }
|
|
21
|
+
// inside the Windows app no service worker may register (bridge.go): its push runs through the app's bridge (nativePush.js)
|
|
22
|
+
if (!reg) { const nr = native(); if (nr) return nr }
|
|
23
|
+
if (!reg) { try { reg = await sw.register(path) } catch (e) { throw new Error('service worker gone and re-register failed (' + ((e && e.message) || e) + ') — close and reopen the app') } }
|
|
24
|
+
const t0 = Date.now()
|
|
25
|
+
while (!reg.active) { if (Date.now() - t0 > ms) throw new Error('service worker not active after ' + (ms / 1000) + 's — close and reopen the app'); await new Promise(sleep) }
|
|
26
|
+
return reg
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** This registration's push subscription, made if there is none — the iOS lessons (2026-09): subscribe() can STALL for ever
|
|
30
|
+
* when the push service does not answer (raced against `timeoutMs`), and THROWS for a wedged registration or one minted
|
|
31
|
+
* under an older VAPID key (drop the stale subscription, try once more). Permission is the caller's: this assumes it is
|
|
32
|
+
* granted. → { sub, err } — never throws, never hangs. */
|
|
33
|
+
export async function subscribeRobust (reg, vapidKey, { timeoutMs = 10000 } = {}) {
|
|
34
|
+
let sub = null
|
|
35
|
+
try { sub = await reg.pushManager.getSubscription() } catch { /* treat as none */ }
|
|
36
|
+
if (sub) return { sub, err: '' }
|
|
37
|
+
const withTimeout = (pr) => Promise.race([pr, new Promise((_, rej) => setTimeout(() => rej(new Error('timed out after ' + (timeoutMs / 1000) + 's — push service unreachable')), timeoutMs))])
|
|
38
|
+
const mk = () => withTimeout(reg.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey: vapidBytes(vapidKey) }))
|
|
39
|
+
try { return { sub: await mk(), err: '' } } catch { /* a stale or wedged subscription: drop it and try once more */ }
|
|
40
|
+
try { const old = await reg.pushManager.getSubscription(); if (old) await old.unsubscribe() } catch { /* */ }
|
|
41
|
+
try { return { sub: await mk(), err: '' } } catch (e) { return { sub: null, err: e && e.name ? e.name + ': ' + e.message : String(e) } }
|
|
42
|
+
}
|
package/recovery.js
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
// spaces/public/recovery.js — CONTENT-BLIND backup of your Spaces (the list + each room's key). A device-generated
|
|
2
|
+
// RECOVERY CODE is the only secret. From it we derive, by two SEPARATE HKDF labels: an `id` (which ciphertext on the
|
|
3
|
+
// server is yours) and an AES-GCM `key` (that opens it) — so the id can never reveal the key. The server stores ONLY the
|
|
4
|
+
// ciphertext under the id and can't read it. The code NEVER reaches the server. Lose the code → the backup is
|
|
5
|
+
// unrecoverable (that's the guarantee). Zero deps: pure Web Crypto.
|
|
6
|
+
|
|
7
|
+
const B32 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567' // RFC 4648 base32 (no padding), for a human-savable code
|
|
8
|
+
function b32encode(u8) {
|
|
9
|
+
let bits = 0, val = 0, out = ''
|
|
10
|
+
for (const b of u8) { val = (val << 8) | b; bits += 8; while (bits >= 5) { out += B32[(val >>> (bits - 5)) & 31]; bits -= 5 } }
|
|
11
|
+
if (bits > 0) out += B32[(val << (5 - bits)) & 31]
|
|
12
|
+
return out
|
|
13
|
+
}
|
|
14
|
+
function b32decode(s) {
|
|
15
|
+
const clean = String(s).toUpperCase().replace(/[^A-Z2-7]/g, '') // tolerate spaces/hyphens/case on input
|
|
16
|
+
let bits = 0, val = 0; const out = []
|
|
17
|
+
for (const c of clean) { val = (val << 5) | B32.indexOf(c); bits += 5; if (bits >= 8) { out.push((val >>> (bits - 8)) & 255); bits -= 8 } }
|
|
18
|
+
return new Uint8Array(out)
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
const enc = new TextEncoder(), dec = new TextDecoder()
|
|
22
|
+
const SALT = enc.encode('witbitz-spaces-backup-v1')
|
|
23
|
+
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(/=+$/, '') }
|
|
24
|
+
const fromB64url = (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 }
|
|
25
|
+
|
|
26
|
+
/** A fresh 128-bit recovery code as grouped base32, e.g. "ABCD-EFGH-JKLM-NPQR-STUV-WX". */
|
|
27
|
+
export function newRecoveryCode() {
|
|
28
|
+
return b32encode(crypto.getRandomValues(new Uint8Array(16))).match(/.{1,4}/g).join('-')
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
async function hkdf(codeBytes, info, len) {
|
|
32
|
+
const km = await crypto.subtle.importKey('raw', codeBytes, 'HKDF', false, ['deriveBits'])
|
|
33
|
+
return new Uint8Array(await crypto.subtle.deriveBits({ name: 'HKDF', hash: 'SHA-256', salt: SALT, info: enc.encode(info) }, km, len * 8))
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** Derive { id (hex storage key), key (AES-GCM) } from raw secret bytes. Two HKDF labels → id can't reveal key. The
|
|
37
|
+
* secret can be a typed recovery code (below) OR a passkey's PRF output (spacePasskey.js) — same 32B secret, same backup. */
|
|
38
|
+
export async function deriveKeysFromSecret(secretBytes) {
|
|
39
|
+
if (!secretBytes || secretBytes.length < 16) throw new Error('bad_secret')
|
|
40
|
+
const idBytes = await hkdf(secretBytes, 'id', 16)
|
|
41
|
+
const id = Array.from(idBytes, (b) => b.toString(16).padStart(2, '0')).join('')
|
|
42
|
+
const key = await crypto.subtle.importKey('raw', await hkdf(secretBytes, 'enc', 32), { name: 'AES-GCM' }, false, ['encrypt', 'decrypt'])
|
|
43
|
+
// WRITE-AUTHENTICATOR: a third, DISTINCT HKDF label. The server stores only SHA-256(wt) (write-once) and checks it on
|
|
44
|
+
// every overwrite, so an attacker who captured just the `id` (which can't yield wt — different label) can't clobber the
|
|
45
|
+
// backup. wt reveals neither the id nor the AES key nor the code, and it can't decrypt — it only proves "the writer holds
|
|
46
|
+
// the recovery code". Sent to the server per write (functions/api/backup.js) ⇒ gates OUTSIDERS, not a malicious server.
|
|
47
|
+
const wt = Array.from(await hkdf(secretBytes, 'bak-write', 32), (b) => b.toString(16).padStart(2, '0')).join('')
|
|
48
|
+
return { id, key, wt }
|
|
49
|
+
}
|
|
50
|
+
/** The raw 16-byte secret behind a typed recovery code. The backup vault wraps the master secret to this value. */
|
|
51
|
+
export function codeSecret(code) {
|
|
52
|
+
const b = b32decode(code)
|
|
53
|
+
if (b.length < 16) throw new Error('bad_code')
|
|
54
|
+
return b
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** Encrypt an object → base64url(iv‖ciphertext). */
|
|
58
|
+
export async function seal(key, obj) {
|
|
59
|
+
const iv = crypto.getRandomValues(new Uint8Array(12))
|
|
60
|
+
const ct = new Uint8Array(await crypto.subtle.encrypt({ name: 'AES-GCM', iv }, key, enc.encode(JSON.stringify(obj))))
|
|
61
|
+
const buf = new Uint8Array(iv.length + ct.length); buf.set(iv); buf.set(ct, iv.length)
|
|
62
|
+
return b64url(buf)
|
|
63
|
+
}
|
|
64
|
+
/** Decrypt base64url(iv‖ciphertext) → object. Throws on a wrong code or any tamper (AES-GCM auth). */
|
|
65
|
+
export async function unseal(key, blob) {
|
|
66
|
+
const buf = fromB64url(blob)
|
|
67
|
+
const pt = await crypto.subtle.decrypt({ name: 'AES-GCM', iv: buf.slice(0, 12) }, key, buf.slice(12))
|
|
68
|
+
return JSON.parse(dec.decode(pt))
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
// ── 2-of-2 RECOVERY GATE (design A) ──────────────────────────────────────────────────────────────────────────────────
|
|
72
|
+
// Recovery today is BEARER: the code alone opens the backup. Design A adds a server-enforced second factor — "(code) AND
|
|
73
|
+
// (email OR passkey)" — WITHOUT a server-side email↔backup graph. From the SAME secret, two more HKDF labels give a `gid`
|
|
74
|
+
// (where the server's gate record lives — separate from the ciphertext id) and a `gk` (HMAC key). The email commitment
|
|
75
|
+
// HMAC(gk, email) is KEYED by the 128-bit code, so a server that holds only the commitment can neither read nor
|
|
76
|
+
// brute-force the email; at recovery it checks a presented HMAC before mailing a code (stops a leaked code from spraying
|
|
77
|
+
// mail to arbitrary addresses). The code still decrypts — this is a gate IN FRONT of the unchanged bearer secret.
|
|
78
|
+
|
|
79
|
+
const normEmail = (e) => String(e || '').trim().toLowerCase()
|
|
80
|
+
|
|
81
|
+
/** { gid (hex, where the gate record lives), gk (HMAC key bytes) } from the recovery secret. Distinct HKDF labels from
|
|
82
|
+
* deriveKeysFromSecret, so the gate id can't reveal the ciphertext id or key, and vice versa. */
|
|
83
|
+
export async function gateParams(secretBytes) {
|
|
84
|
+
if (!secretBytes || secretBytes.length < 16) throw new Error('bad_secret')
|
|
85
|
+
const gidBytes = await hkdf(secretBytes, 'gate-id', 16)
|
|
86
|
+
const gid = Array.from(gidBytes, (b) => b.toString(16).padStart(2, '0')).join('')
|
|
87
|
+
const gk = await hkdf(secretBytes, 'gate-commit', 32)
|
|
88
|
+
return { gid, gk }
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** A locator (hex) for the gate id, derived from a PASSKEY secret P — so a passkey-only restore (which has no recovery
|
|
92
|
+
* code, hence can't derive the gid) can still find its gate to pass the passkey factor. Distinct HKDF label; a P-holder
|
|
93
|
+
* is already the legitimate passkey user, so this reveals nothing extra. */
|
|
94
|
+
export async function gatePtr(secretBytes) {
|
|
95
|
+
if (!secretBytes || secretBytes.length < 16) throw new Error('bad_secret')
|
|
96
|
+
const b = await hkdf(secretBytes, 'gate-ptr', 16)
|
|
97
|
+
return Array.from(b, (x) => x.toString(16).padStart(2, '0')).join('')
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** Bind an email to this code: HMAC-SHA256(gk, normalized email) → hex. Stored server-side as the gate's `commit_email`;
|
|
101
|
+
* reveals nothing about the email without the code. Normalizes case + surrounding space so the same address always
|
|
102
|
+
* matches. */
|
|
103
|
+
export async function emailCommit(gk, email) {
|
|
104
|
+
const key = await crypto.subtle.importKey('raw', gk, { name: 'HMAC', hash: 'SHA-256' }, false, ['sign'])
|
|
105
|
+
const mac = new Uint8Array(await crypto.subtle.sign('HMAC', key, enc.encode(normEmail(email))))
|
|
106
|
+
return Array.from(mac, (b) => b.toString(16).padStart(2, '0')).join('')
|
|
107
|
+
}
|
package/regions.js
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
// regions.js — a room's home region is IN ITS ID (docs/multi-region.md). One parser for the page, the SDK and the Lambda
|
|
2
|
+
// (agent/spaceHandler.mjs imports this file, as it does roomName.js).
|
|
3
|
+
//
|
|
4
|
+
// sp-k3j9x0a1b2c3 no marker: the default region — every room made before regions existed
|
|
5
|
+
// sp-us-k3j9x0a1b2c3 homed in "us" (tmp-us-… for a temporary room)
|
|
6
|
+
//
|
|
7
|
+
// Only codes in REGIONS count: sp-ci- (CI rooms), sp-rc- (/rc rooms) and the other two-letter prefixes this repo already
|
|
8
|
+
// uses are NOT regions, and spaces/test/regions.test.mjs refuses a table code that collides with one of them.
|
|
9
|
+
// Nothing is looked up — a room's region is known from its id alone, wherever the id is.
|
|
10
|
+
|
|
11
|
+
export const DEFAULT_REGION = 'eu'
|
|
12
|
+
|
|
13
|
+
/** The regions a room can be homed in. `aws` is where its storage and turns run. A code is two lower-case letters. */
|
|
14
|
+
export const REGIONS = Object.freeze({
|
|
15
|
+
eu: Object.freeze({ aws: 'eu-central-1' }),
|
|
16
|
+
us: Object.freeze({ aws: 'us-east-1' }),
|
|
17
|
+
})
|
|
18
|
+
|
|
19
|
+
const MARKED = /^(?:sp|tmp)-([a-z]{2})-[0-9a-z]+$/
|
|
20
|
+
|
|
21
|
+
/** The region a room is homed in: its marker when it names a region in the table, else the default. */
|
|
22
|
+
export function roomRegion(room) {
|
|
23
|
+
const m = MARKED.exec(typeof room === 'string' ? room : '')
|
|
24
|
+
return m && Object.prototype.hasOwnProperty.call(REGIONS, m[1]) ? m[1] : DEFAULT_REGION
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** A deployment's own region, from its /space-config (or the Lambda's env): an exact code in the table, else the default. */
|
|
28
|
+
export function regionCode(cfg) {
|
|
29
|
+
const r = cfg && typeof cfg.region === 'string' ? cfg.region : ''
|
|
30
|
+
return Object.prototype.hasOwnProperty.call(REGIONS, r) ? r : DEFAULT_REGION
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** True when `room` is homed somewhere other than `here`. */
|
|
34
|
+
export const isRemoteRoom = (room, here = DEFAULT_REGION) => roomRegion(room) !== here
|
|
35
|
+
|
|
36
|
+
/** A new room id homed in `region`. In the default region (or an unknown one) it has the old shape exactly, so a
|
|
37
|
+
* single-region deployment makes the same ids it always made. `rand` is for tests. */
|
|
38
|
+
export function newRoomId(region, { prefix = 'sp', rand = () => crypto.getRandomValues(new Uint8Array(8)) } = {}) {
|
|
39
|
+
const tail = Array.from(rand()).map((x) => x.toString(36)).join('').slice(0, 12)
|
|
40
|
+
const marked = region && region !== DEFAULT_REGION && Object.prototype.hasOwnProperty.call(REGIONS, region)
|
|
41
|
+
return `${prefix}-${marked ? region + '-' : ''}${tail}`
|
|
42
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
export const REMOVED_TEXT = 'Removed by Witbitz for breaking the Terms'
|
|
2
|
+
export const SHARED_REMOVED_TEXT = 'Removed in the shared Space'
|
|
3
|
+
/** Replacement, never a merge: no body, media, tool output or attachment references survive. */
|
|
4
|
+
export function removedCopy(e) {
|
|
5
|
+
const { id, ts, name, from, self, verified, user, spk, vspk, sid } = e || {}
|
|
6
|
+
return { id, ts, name, from, self, verified, user, spk, vspk, sid, kind: 'text', text: REMOVED_TEXT, removedByWitbitz: true }
|
|
7
|
+
}
|
|
8
|
+
export function sharedRemovedCopy(e) {
|
|
9
|
+
const { id, ts, name, from, self } = e || {}
|
|
10
|
+
return { id, ts, name, from, self, kind: 'text', source: 'shared', text: SHARED_REMOVED_TEXT, sourceRemoved: true }
|
|
11
|
+
}
|