@witbitz/sdk 0.0.0-stage → 4.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +20 -2
- package/a2aCore.js +200 -0
- package/a2aShared.js +27 -0
- package/accountErase.js +223 -0
- package/accountIndexDoc.js +122 -0
- package/accountOwner.js +59 -0
- package/accountRecord.js +90 -0
- package/accountScope.js +114 -0
- package/accountSeal.js +42 -0
- package/accountStores.js +173 -0
- package/acctV2App.js +619 -0
- package/acctV2Check.js +29 -0
- package/acctV2Client.js +382 -0
- package/acctV2Keys.js +43 -0
- package/acctV2Legacy.js +14 -0
- package/acctV2Switch.js +80 -0
- package/acctV2UiCore.js +857 -0
- package/acctV2WebAuthn.js +61 -0
- package/acctV2Wire.js +59 -0
- package/address.js +42 -0
- package/attestedBox.js +30 -0
- package/attestedRooms.js +78 -0
- package/awsKey.js +98 -0
- package/backupRecord.js +106 -0
- package/backupVault.js +97 -0
- package/blocks.js +115 -0
- package/blocksPush.js +64 -0
- package/browseSeal.js +103 -0
- package/cbor.js +225 -0
- package/changePush.js +75 -0
- package/chatLock.js +149 -0
- package/chatLockSw.js +13 -0
- package/cloudDeviceBuilds.js +11 -0
- package/cloudDevicePins.js +33 -0
- package/cloudDeviceSeal.js +53 -0
- package/codeBrowse.js +224 -0
- package/codeCloud.js +652 -0
- package/codeCloudKeys.js +112 -0
- package/codeCommands.js +167 -0
- package/codeComputers.js +388 -0
- package/codeEgress.js +123 -0
- package/codeFilesRoutes.js +17 -0
- package/codeMkdir.js +8 -0
- package/codeModes.js +57 -0
- package/codeOrphanKeys.js +42 -0
- package/codeOutputs.js +141 -0
- package/codeRelay.js +505 -0
- package/codeSentinel.js +86 -0
- package/codeTransport.js +295 -0
- package/codeUndo.js +48 -0
- package/compress.js +24 -0
- package/config.js +11 -0
- package/connCatalog.js +164 -0
- package/connDisp.js +76 -0
- package/connOtherWays.js +74 -0
- package/connPending.js +16 -0
- package/connWrap.js +53 -0
- package/connectionEntry.js +89 -0
- package/connections.js +562 -0
- package/credits.js +30 -0
- package/csAttest.js +112 -0
- package/decrypt.html +384 -0
- package/deviceAttest.js +521 -0
- package/deviceCall.js +54 -0
- package/deviceKeyCore.js +41 -0
- package/deviceSeal.js +59 -0
- package/e2ee.js +323 -0
- package/eat.js +103 -0
- package/emailFork.js +275 -0
- package/emailSignIn.js +81 -0
- package/emptySpaces.js +111 -0
- package/encSource.js +55 -0
- package/enclaveAccept.js +214 -0
- package/enclaveClaim.js +241 -0
- package/enclaveRoute.js +102 -0
- package/enclaveSnapshotMerge.js +44 -0
- package/entrySig.js +165 -0
- package/env.js +73 -0
- package/eraseFile.js +58 -0
- package/followImage.js +86 -0
- package/healNames.js +45 -0
- package/idb.js +97 -0
- package/idbSeal.js +119 -0
- package/indexGone.js +12 -0
- package/invite.js +51 -0
- package/inviteEnroll.js +67 -0
- package/inviteSend.js +68 -0
- package/jobAgents.js +87 -0
- package/keptMerge.js +84 -0
- package/l1-worker-src.js +2 -0
- package/l1-worker.js +831 -0
- package/laneConfig.js +57 -0
- package/laneLinkCore.js +177 -0
- package/ledgerView.js +64 -0
- package/manifest.json +220 -0
- package/mcpRecommended.js +25 -0
- package/memberChange.js +123 -0
- package/mkseal.js +101 -0
- package/nativePush.js +153 -0
- package/nitroVerify.js +220 -0
- package/noble-p256.js +27 -0
- package/notice.js +116 -0
- package/notifKey.js +58 -0
- package/offlineBundle.js +62 -0
- package/ohttp.js +177 -0
- package/opencodeWire.js +282 -0
- package/oprf.js +70 -0
- package/ownAgentLink.js +96 -0
- package/ownerPolicy.js +117 -0
- package/package.json +254 -4
- package/pollVerdict.js +33 -0
- package/prefetchPoll.js +60 -0
- package/protectedLocal.js +410 -0
- package/pushCore.js +42 -0
- package/recovery.js +107 -0
- package/regions.js +42 -0
- package/removedMessage.js +11 -0
- package/renameRefusal.js +9 -0
- package/replyQuote.js +34 -0
- package/reqEnvelope.js +126 -0
- package/roomDefaultPrefs.js +76 -0
- package/roomDelete.js +109 -0
- package/roomName.js +177 -0
- package/roomPass.js +256 -0
- package/roomRoster.js +289 -0
- package/roomSettings.js +61 -0
- package/roomState.js +58 -0
- package/roomStreamClient.js +115 -0
- package/rosterCount.js +49 -0
- package/rosterHash.js +13 -0
- package/rowSchema.js +113 -0
- package/safeMedia.js +116 -0
- package/safeMediaPins.js +17 -0
- package/schedulesDoc.js +78 -0
- package/sdkA2A.js +404 -0
- package/sdkAccount.js +470 -0
- package/sdkAccountDoc.js +81 -0
- package/sdkAccountSections.js +223 -0
- package/sdkAgui.js +141 -0
- package/sdkAttest.js +34 -0
- package/sdkBackup.js +480 -0
- package/sdkBackupV2.js +630 -0
- package/sdkBrowserPrivate.js +28 -0
- package/sdkBuilds.js +208 -0
- package/sdkCloudDevice.js +215 -0
- package/sdkComputers.js +480 -0
- package/sdkDictation.js +142 -0
- package/sdkErase.js +283 -0
- package/sdkExports.js +69 -0
- package/sdkInvitations.js +34 -0
- package/sdkKeptAgent.js +188 -0
- package/sdkLaneLink.js +205 -0
- package/sdkPlan.js +94 -0
- package/sdkProtect.js +228 -0
- package/sdkRedact.js +36 -0
- package/sdkRekey.js +307 -0
- package/sdkReport.js +68 -0
- package/sdkSafeMedia.js +255 -0
- package/sdkSchedules.js +39 -0
- package/sdkSpeech.js +54 -0
- package/sdkTurn.js +117 -0
- package/sdkVault.js +124 -0
- package/sealShare.js +18 -0
- package/sealedNames.js +64 -0
- package/sealedReceipt.js +17 -0
- package/sentinelRelease.js +154 -0
- package/shamir.js +85 -0
- package/sharedViews.js +38 -0
- package/sheetChrome.js +450 -0
- package/siri.js +171 -0
- package/spaceClient.js +1418 -0
- package/spaceConfig.js +81 -0
- package/spaceEmailGate.js +813 -0
- package/spaceExport.js +125 -0
- package/spaceFork.js +216 -0
- package/spaceLock.js +358 -0
- package/spacePasskey.js +180 -0
- package/speechOut.js +100 -0
- package/splitKeyClient.js +90 -0
- package/store.js +587 -0
- package/streamHint.js +36 -0
- package/sttCloud.js +220 -0
- package/sttWorklet.js +38 -0
- package/sw-notif-core.js +538 -0
- package/tempList.js +48 -0
- package/tinfoilVerifier.js +78 -0
- package/toolBooks.js +31 -0
- package/toolRules.js +52 -0
- package/turnCerts.js +254 -0
- package/turnFeed.js +58 -0
- package/turnVerdict.js +36 -0
- package/usageReceipts.js +176 -0
- package/usageSummary.js +90 -0
- package/util.js +181 -0
- package/vault-core.js +1958 -0
- package/vault-kit.mjs +354 -0
- package/vault-screens.js +263 -0
- package/vaultAtRest.js +177 -0
- package/vaultCoreLock.js +111 -0
- package/vaultCorePush.js +140 -0
- package/vaultDeviceKey.js +95 -0
- package/vaultEnclaveHandoff.js +114 -0
- package/vaultKeep.js +281 -0
- package/vaultSealedStore.js +77 -0
- package/vaultWorkerHost.js +98 -0
- package/vcWorker.js +34 -0
- package/voiceAttest.js +50 -0
- package/voiceCert.js +51 -0
- package/witbitz-admin.d.ts +135 -0
- package/witbitz-admin.js +529 -0
- package/witbitz-admin.mjs +1459 -0
- package/witbitz-sdk.d.ts +1106 -0
- package/witbitz-sdk.js +3835 -0
- package/workerClient.js +16 -0
- package/workerLiveness.js +21 -0
- package/x509.js +218 -0
package/vaultAtRest.js
ADDED
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
// vaultAtRest.js — what the BUILDERS' vault (vault-core.js) keeps on disk carries no room key in the clear
|
|
2
|
+
// (docs/sdk-vault-mode.md § At rest; the owner, 2026-11-13, decision 5 of docs/vault-core-convergence-review.md).
|
|
3
|
+
//
|
|
4
|
+
// The vault keeps, in its own origin's localStorage: the room list (`wbvault:rooms`, one invite link per Space — the link IS
|
|
5
|
+
// the key: `#mk=` or a split room's half `#us=`), and the account backup's state per account (`wbvault:backup` — its master
|
|
6
|
+
// opens every key, its rooms carry links and keys). Both were plain JSON. Here:
|
|
7
|
+
// · a room entry keeps its link WITHOUT the key (`href`, the `mk=` / `us=` values emptied in place, every other mark kept) and
|
|
8
|
+
// the key SEALED beside it (`ks`); the link is rebuilt, byte for byte, when it is loaded into the vault's memory;
|
|
9
|
+
// · a backup state is sealed whole, per account; another account's entry is carried over as it is (another tab's write).
|
|
10
|
+
// Sealed under `key`, an AES-GCM CryptoKey (deviceSeal.js does the sealing): by default a NON-EXTRACTABLE key this vault makes
|
|
11
|
+
// once and keeps in its origin's IndexedDB (`deviceWrapKey`). That is the at-rest level the key worker's own IndexedDB has
|
|
12
|
+
// on an unprotected device — a copy of the localStorage alone, a sync of it, a search of it for `#mk=`, finds no key; a copy
|
|
13
|
+
// of the whole browser profile still does. Against that, the person's passkey lock (vaultProtect.js) is the answer.
|
|
14
|
+
//
|
|
15
|
+
// Read-through, never a destructive switch: an entry an older vault wrote (`link`, clear) is read as it is and written back
|
|
16
|
+
// sealed; an entry no key here opens is KEPT, keyless (the backup refills its link); with no key at all (no IndexedDB: an
|
|
17
|
+
// iPhone in Lockdown Mode, a private window that refuses it) the list is written as before — a key is never lost for want
|
|
18
|
+
// of a seal.
|
|
19
|
+
import { seal, open, isSealed } from './deviceSeal.js'
|
|
20
|
+
|
|
21
|
+
const SECRET = /([#&])(mk|us)=([^&]*)/g // the fragment params that ARE a key (or a split room's half of one)
|
|
22
|
+
|
|
23
|
+
/** `…#mk=K&gate=email` → { href: '…#mk=&gate=email', secret: { mk: 'K' } }; null when the link carries no key. */
|
|
24
|
+
export function splitLink (link) {
|
|
25
|
+
if (typeof link !== 'string' || !link.includes('#')) return null
|
|
26
|
+
const i = link.indexOf('#'), head = link.slice(0, i), frag = link.slice(i)
|
|
27
|
+
const secret = {}
|
|
28
|
+
const keyless = frag.replace(SECRET, (_, sep, name, v) => { if (v) secret[name] = v; return sep + name + '=' })
|
|
29
|
+
return Object.keys(secret).length ? { href: head + keyless, secret } : null
|
|
30
|
+
}
|
|
31
|
+
/** The inverse of splitLink: each emptied key param gets its value back, in place. */
|
|
32
|
+
export function joinLink (href, secret) {
|
|
33
|
+
return String(href).replace(/([#&])(mk|us)=(?=&|$)/g, (m, sep, name) => (secret && typeof secret[name] === 'string' ? sep + name + '=' + secret[name] : m))
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** The vault's own sealing key: a non-extractable AES-GCM key kept in this origin's IndexedDB, made once (the first of two
|
|
37
|
+
* tabs to make it wins: `add`, then read back). null when there is no IndexedDB to keep it in.
|
|
38
|
+
* ⛔ A READ THAT FAILED IS NOT "NO KEY" (sync sweep 2026-11-15 #3; our vault's 12a425b16, the owner's iPhone 11-14): iOS fails an
|
|
39
|
+
* IndexedDB open now and then. Every error answered null, the vault ran with no key, the sealed backup state read as "off", and
|
|
40
|
+
* turning backup on made a new master and code. Now a failed read is tried again, and one that keeps failing THROWS
|
|
41
|
+
* (code `device_key_unreadable`) — the caller asks the person, it never runs keyless over sealed data. */
|
|
42
|
+
const WRAP_RETRY_MS = [150, 400, 900]
|
|
43
|
+
export async function deviceWrapKey ({ idb = (typeof indexedDB !== 'undefined' ? indexedDB : null), name = 'wbvault-at-rest', wait = (ms) => new Promise((r) => setTimeout(r, ms)) } = {}) {
|
|
44
|
+
if (!idb || !(globalThis.crypto && crypto.subtle)) return null
|
|
45
|
+
let last = null
|
|
46
|
+
for (let i = 0; i <= WRAP_RETRY_MS.length; i++) {
|
|
47
|
+
if (i) await wait(WRAP_RETRY_MS[i - 1])
|
|
48
|
+
try { return await wrapKeyOnce(idb, name) } catch (e) { last = e }
|
|
49
|
+
}
|
|
50
|
+
throw Object.assign(new Error('this vault\'s saved data could not be opened (' + String((last && (last.name || last.message)) || last || 'IndexedDB') .slice(0, 120) + ')'), { code: 'device_key_unreadable' })
|
|
51
|
+
}
|
|
52
|
+
async function wrapKeyOnce (idb, name) {
|
|
53
|
+
let db = null
|
|
54
|
+
try {
|
|
55
|
+
db = await new Promise((res, rej) => { const r = idb.open(name, 1); r.onupgradeneeded = () => r.result.createObjectStore('k'); r.onsuccess = () => res(r.result); r.onerror = () => rej(r.error) })
|
|
56
|
+
const get = () => new Promise((res, rej) => { const q = db.transaction('k', 'readonly').objectStore('k').get('wrap'); q.onsuccess = () => res(q.result || null); q.onerror = () => rej(q.error) })
|
|
57
|
+
let k = await get()
|
|
58
|
+
if (!k) {
|
|
59
|
+
const made = await crypto.subtle.generateKey({ name: 'AES-GCM', length: 256 }, false, ['encrypt', 'decrypt'])
|
|
60
|
+
await new Promise((res) => { const t = db.transaction('k', 'readwrite'); t.objectStore('k').add(made, 'wrap'); t.oncomplete = res; t.onabort = res; t.onerror = (e) => { try { e.preventDefault() } catch { /* */ } } })
|
|
61
|
+
k = await get()
|
|
62
|
+
}
|
|
63
|
+
if (k && k.type === 'secret') return k
|
|
64
|
+
throw Object.assign(new Error('no usable key in IndexedDB'), { name: 'NoKey' })
|
|
65
|
+
} finally { try { db && db.close() } catch { /* */ } }
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
const read = (st, k) => { try { const v = st.getItem(k); return v ? JSON.parse(v) : null } catch { return null } }
|
|
69
|
+
const write = (st, k, v) => { try { if (v == null) st.removeItem(k); else st.setItem(k, JSON.stringify(v)) } catch { /* a full or blocked store: the vault still works this session */ } }
|
|
70
|
+
const isState = (x) => !!(x && typeof x === 'object' && !Array.isArray(x) && typeof x.master === 'string')
|
|
71
|
+
|
|
72
|
+
/** @param {{ storage: Storage, key: CryptoKey|null }} o */
|
|
73
|
+
/** Does this storage hold anything sealed — a room's key, an account's backup state? A vault with NO key (no IndexedDB this launch)
|
|
74
|
+
* must not run over it: it would read the backup as off (sync sweep 11-18; our vault asks there too). */
|
|
75
|
+
export function holdsSealed (storage, { rooms, backup } = {}) {
|
|
76
|
+
const list = rooms ? read(storage, rooms) : null
|
|
77
|
+
if (Array.isArray(list) && list.some((e) => e && isSealed(e.ks))) return true
|
|
78
|
+
const b = backup ? read(storage, backup) : null
|
|
79
|
+
return !!(b && typeof b === 'object' && !Array.isArray(b) && Object.values(b).some((v) => isSealed(v)))
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
export function createAtRest ({ storage, key }) {
|
|
83
|
+
let chain = Promise.resolve()
|
|
84
|
+
const onDisk = (fn) => { const p = chain.then(fn); chain = p.catch(() => {}); return p }
|
|
85
|
+
const sealedOf = new Map() // room → { secret (JSON), ks } — an unchanged key is not sealed again on every save
|
|
86
|
+
// ⛔ AN ENTRY THIS KEY CANNOT OPEN (another key's, or no key at all: IndexedDB failed at start) is carried over AS IT IS on every
|
|
87
|
+
// save — read as keyless and written as `rest`, the next save erased its sealed key for good (review, 2026-11-13).
|
|
88
|
+
const unopened = new Map() // room → { href, ks }
|
|
89
|
+
|
|
90
|
+
async function entryOut (r) {
|
|
91
|
+
const { link, mk, ...rest } = r
|
|
92
|
+
if (link === undefined && unopened.has(r.room)) { const u = unopened.get(r.room); return { ...rest, href: u.href, ks: u.ks } }
|
|
93
|
+
const s = key ? splitLink(link) : null
|
|
94
|
+
if (!s) return link === undefined ? rest : { ...rest, link } // no key here (or a keyless link): as before
|
|
95
|
+
if (mk && s.secret.us) s.secret.whole = mk
|
|
96
|
+
const sj = JSON.stringify(s.secret), had = sealedOf.get(r.room)
|
|
97
|
+
const ks = had && had.secret === sj ? had.ks : await seal(key, s.secret)
|
|
98
|
+
sealedOf.set(r.room, { secret: sj, ks })
|
|
99
|
+
return { ...rest, href: s.href, ks }
|
|
100
|
+
}
|
|
101
|
+
async function entryIn (e) {
|
|
102
|
+
if (!e || typeof e !== 'object' || typeof e.room !== 'string') return null
|
|
103
|
+
const { href, ks, ...rest } = e
|
|
104
|
+
if (!isSealed(ks)) return { ...rest } // an older vault's entry (`link` in it), or a keyless one
|
|
105
|
+
let secret = null
|
|
106
|
+
try { secret = key ? await open(key, ks) : null } catch { secret = null }
|
|
107
|
+
if (!secret || typeof secret !== 'object') { unopened.set(e.room, { href, ks }); return { ...rest } } // sealed under a key this vault does not have: keyless in memory, kept as it is on disk
|
|
108
|
+
unopened.delete(e.room)
|
|
109
|
+
sealedOf.set(e.room, { secret: JSON.stringify(secret), ks })
|
|
110
|
+
return { ...rest, link: joinLink(href, secret), ...(secret.us && secret.whole ? { mk: secret.whole } : {}) }
|
|
111
|
+
}
|
|
112
|
+
return {
|
|
113
|
+
/** The room list, links whole (in memory only). An older clear list is written back sealed at once. */
|
|
114
|
+
async loadRooms (k) {
|
|
115
|
+
const raw = read(storage, k)
|
|
116
|
+
const list = Array.isArray(raw) ? raw : []
|
|
117
|
+
const out = (await Promise.all(list.map(entryIn))).filter(Boolean)
|
|
118
|
+
if (key && list.some((e) => e && typeof e.link === 'string' && splitLink(e.link))) this.saveRooms(k, out)
|
|
119
|
+
return out
|
|
120
|
+
},
|
|
121
|
+
/** Write the list — the links' keys sealed. In the order called; resolves once this one is on disk. */
|
|
122
|
+
saveRooms (k, rooms) {
|
|
123
|
+
const snap = (Array.isArray(rooms) ? rooms : []).map((r) => ({ ...r }))
|
|
124
|
+
return onDisk(async () => { write(storage, k, await Promise.all(snap.map(entryOut))) })
|
|
125
|
+
},
|
|
126
|
+
/** Every account's backup state (the vault's `wbvault:backup` = { email: state }), opened. */
|
|
127
|
+
async loadBackups (k) {
|
|
128
|
+
const raw = read(storage, k)
|
|
129
|
+
if (!raw || typeof raw !== 'object' || Array.isArray(raw) || 'master' in raw) return {}
|
|
130
|
+
const out = {}
|
|
131
|
+
let clear = false
|
|
132
|
+
for (const [email, v] of Object.entries(raw)) {
|
|
133
|
+
if (isState(v)) { out[email] = v; clear = true; continue } // an older vault's: read through
|
|
134
|
+
if (!isSealed(v) || !key) continue
|
|
135
|
+
try { const s = await open(key, v); if (isState(s)) out[email] = s } catch { /* another key's: left on disk, not ours to read */ }
|
|
136
|
+
}
|
|
137
|
+
if (clear && key) for (const [email, s] of Object.entries(out)) if (isState(raw[email])) this.putBackup(k, email, s)
|
|
138
|
+
return out
|
|
139
|
+
},
|
|
140
|
+
/** Move a matching signed-out email request to the signed-in account in one storage write. */
|
|
141
|
+
claimEmailMove(k, email) {
|
|
142
|
+
const owner = String(email || '').trim().toLowerCase()
|
|
143
|
+
return onDisk(async () => {
|
|
144
|
+
const before = read(storage, k), slot = before?.['']
|
|
145
|
+
if (!owner || !slot || before[owner]) return false
|
|
146
|
+
let draft = slot
|
|
147
|
+
if (isSealed(slot) && key) { try { draft = await open(key, slot) } catch { return false } }
|
|
148
|
+
if (!isState(draft) || !draft.v2?.resetDraft || String(draft.email || '').toLowerCase() !== owner) return false
|
|
149
|
+
const all = read(storage, k)
|
|
150
|
+
if (!all || all[owner] || JSON.stringify(all['']) !== JSON.stringify(slot)) return false
|
|
151
|
+
delete all['']
|
|
152
|
+
all[owner] = slot
|
|
153
|
+
storage.setItem(k, JSON.stringify(all))
|
|
154
|
+
return true
|
|
155
|
+
})
|
|
156
|
+
},
|
|
157
|
+
/** One account's state (null removes it); the other accounts' entries are carried over as they are on disk. */
|
|
158
|
+
putBackup (k, email, state) {
|
|
159
|
+
return onDisk(async () => {
|
|
160
|
+
const v = state == null ? null : key ? await seal(key, state) : state
|
|
161
|
+
const now = read(storage, k)
|
|
162
|
+
const all = now && typeof now === 'object' && !Array.isArray(now) && !('master' in now) ? now : {}
|
|
163
|
+
// ⛔ a sealed state THIS key cannot open (its master opens every room key in the account's backup) is never written over
|
|
164
|
+
// and lost: it is kept aside first, under `<k>:unopened` (review, 2026-11-13)
|
|
165
|
+
const was = all[email]
|
|
166
|
+
if (isSealed(was)) {
|
|
167
|
+
let ours = false; try { ours = !!(key && isState(await open(key, was))) } catch { ours = false }
|
|
168
|
+
if (!ours) { const aside = read(storage, k + ':unopened'); write(storage, k + ':unopened', { ...(aside && typeof aside === 'object' && !Array.isArray(aside) ? aside : {}), [email]: was }) }
|
|
169
|
+
}
|
|
170
|
+
if (v == null) delete all[email]; else all[email] = v
|
|
171
|
+
write(storage, k, all)
|
|
172
|
+
})
|
|
173
|
+
},
|
|
174
|
+
/** Resolves once every write made so far is on disk. */
|
|
175
|
+
flushed: () => chain,
|
|
176
|
+
}
|
|
177
|
+
}
|
package/vaultCoreLock.js
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
// vaultCoreLock.js — THE LOCK AND DEVICE STORAGE PROTECTION of a builders' vault (vault-core.js; docs/sdk-vault-mode.md § The lock;
|
|
2
|
+
// the owner, 2026-11-13: "Do all including #5"). Loaded ONLY for a vault started with `lock: true` — a vault without it never
|
|
3
|
+
// fetches this file, nor anything it imports — and on only once the PERSON turns it on, in the vault's own sheet
|
|
4
|
+
// (wb.vault.showLock()): first the lock (a passkey covers the page at every launch), then "Also protect this device's storage".
|
|
5
|
+
//
|
|
6
|
+
// Nothing here is new machinery: it is our own vault's (vault-loader.js vaultProtectHooks), wired for this one:
|
|
7
|
+
// spaceLock.js the lock, its sheet, the passkey ceremonies, the write-ahead switch-on, Start over
|
|
8
|
+
// sdkProtect.js the protection passkey → the 32 device-key bytes (its own user handle; the SDK's wb.protect derives the same way)
|
|
9
|
+
// protectedLocal.js this origin's localStorage sealed under that key, under OPAQUE names — every `wbvault:*` entry included;
|
|
10
|
+
// only the lock config (`vault:lock`) stays readable, since the lock screen reads it before any passkey
|
|
11
|
+
// l1-worker.js the key worker seals its own store (seal / unseal / relock / unprotect), as it does in our vaults
|
|
12
|
+
// What this vault adds: it waits for the unlock BEFORE it reads anything or frames the page (`boot`), and a lock that engages
|
|
13
|
+
// while it runs (away too long) RELOADS it — the vault's memory holds every link, so the only lock that drops them is a new
|
|
14
|
+
// launch behind the lock screen.
|
|
15
|
+
import { makeLock } from './spaceLock.js'
|
|
16
|
+
import { enrollProtectKey, unlockProtectKey, webauthnPasskey } from './sdkProtect.js'
|
|
17
|
+
import { clearLocalForBuilderReset, installProtectedLocal, protectedLocalActive, protectedLocalReady, unlockProtectedLocal, relockProtectedLocal, unprotectProtectedLocal } from './protectedLocal.js'
|
|
18
|
+
import { BLOCKS_SW_KEY } from './blocksPush.js'
|
|
19
|
+
import { idb } from './idb.js'
|
|
20
|
+
import { migrateIdbProtection, armIdbProtection, moveToOpaqueNames, unprotectIdb, setIdbProtection } from './idbSeal.js' // the worker's IndexedDB: what it does not seal itself (a room's read position, cnt:) moves under opaque names too
|
|
21
|
+
|
|
22
|
+
export const resetMarker = 'witbitz-builder-reset-pending'
|
|
23
|
+
export async function finishBuilderReset () {
|
|
24
|
+
clearLocalForBuilderReset(resetMarker)
|
|
25
|
+
sessionStorage.clear()
|
|
26
|
+
if (typeof indexedDB === 'undefined') return false
|
|
27
|
+
const results = await Promise.all(['spaces', 'wbvault-at-rest', 'wbvault-acct'].map(name => new Promise(resolve => {
|
|
28
|
+
const q = indexedDB.deleteDatabase(name)
|
|
29
|
+
q.onsuccess = () => resolve(true)
|
|
30
|
+
q.onerror = q.onblocked = () => resolve(false)
|
|
31
|
+
})))
|
|
32
|
+
if (!results.every(Boolean)) return false
|
|
33
|
+
localStorage.removeItem(resetMarker)
|
|
34
|
+
return true
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export const LOCK_KEY = 'vault:lock' // a name protectedLocal keeps clear (STAYS_CLEAR): read before any passkey
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* @param {object} o
|
|
41
|
+
* @param {string} o.brand the vault's name, in the sheet and on the passkeys
|
|
42
|
+
* @param {() => void} o.mountUi puts #lockscreen / #lockset in the page (screens.lockUi)
|
|
43
|
+
* @param {(why?: string) => void} o.hide hide the builder's page (the lock covers it)
|
|
44
|
+
* @param {() => void} o.show
|
|
45
|
+
* @param {(view: object) => void} [o.onState] the lock's state changed (→ the page, `ev:'lock'`)
|
|
46
|
+
* @param {(q: object) => Promise<boolean>} o.confirm the vault's confirm screen (Start over)
|
|
47
|
+
*/
|
|
48
|
+
export function createVaultLock ({ brand = 'this app', mountUi, hide, show, onState, confirm, onUnprotected, beforeProtect, reload = () => location.reload() }) {
|
|
49
|
+
installProtectedLocal() // idempotent: its own import already switched it on, on a protected device
|
|
50
|
+
let raw = null, previews = false, workerCall = null, released = null, onReleased = null, running = false
|
|
51
|
+
const passkey = webauthnPasskey({ rpName: brand, userName: brand + ' — device protection' }) // never "Witbitz Spaces" in a builder's users' keychain
|
|
52
|
+
const lock = makeLock({
|
|
53
|
+
storeKey: LOCK_KEY,
|
|
54
|
+
appName: brand,
|
|
55
|
+
// a lock that ENGAGES while the vault runs (away too long — `why` is set; the sheet's own call passes none) restarts it behind the
|
|
56
|
+
// lock screen, protected or not: the vault's memory holds every link, and the page behind a mere cover kept calling (review)
|
|
57
|
+
cover: { onEngage: (why) => { hide(why); if (running && why) reload() }, onRelease: () => { show(); if (onReleased) { const f = onReleased; onReleased = null; f() } } },
|
|
58
|
+
onState: () => { try { onState && onState(view()) } catch { /* the page is gone */ } },
|
|
59
|
+
protect: {
|
|
60
|
+
enroll: async (label) => { const k = await enrollProtectKey(label, { passkey }); return { credId: k.credId, mode: k.mode, secret: k.raw } },
|
|
61
|
+
unlock: async (credId) => { const c = lock.cfg(); const k = await unlockProtectKey(credId, c.protect && c.protect.mode, { passkey }); return { credId: k.credId, secret: k.raw } },
|
|
62
|
+
// ON, in our vault's order: this origin's localStorage (protectedLocal moves every entry under an opaque name), the worker
|
|
63
|
+
// (a key arriving meanwhile is written sealed), then the rest of the worker's IndexedDB under opaque names
|
|
64
|
+
onProtect: async (secret, o) => { if (beforeProtect) await beforeProtect(); raw = secret; previews = !!(o && o.previews); if (!previews) await idb.del(BLOCKS_SW_KEY); await unlockProtectedLocal(secret, { switchOn: true }); if (workerCall) await workerCall({ t: 'seal', key: secret, previews }); await migrateIdbProtection(idb, secret) },
|
|
65
|
+
onUnlock: async (secret, o) => { raw = secret; previews = !!(o && o.previews); await unlockProtectedLocal(secret); await armIdbProtection(secret); moveToOpaqueNames(idb).catch(() => {}); if (workerCall) await workerCall({ t: 'unseal', key: secret, previews }) },
|
|
66
|
+
onPreviews: async (on) => { previews = !!on; if (!on) await idb.del(BLOCKS_SW_KEY); if (workerCall) await workerCall({ t: 'previews', on: previews }) },
|
|
67
|
+
// a lock that engages while the vault RUNS: start again behind the lock screen (the vault's memory holds the links). At a
|
|
68
|
+
// launch nothing was unlocked yet: nothing to drop, no reload.
|
|
69
|
+
onLock: () => { raw = null; relockProtectedLocal(); setIdbProtection({ active: true, key: null }); if (workerCall) workerCall({ t: 'relock' }).catch(() => {}) }, // the reload follows from the cover (onEngage), at a launch none
|
|
70
|
+
onUnprotect: async (secret) => { await unprotectProtectedLocal(secret); await unprotectIdb(idb, secret); if (workerCall) await workerCall({ t: 'unprotect', key: secret }); raw = null; try { if (onUnprotected) await onUnprotected() } catch { /* */ } },
|
|
71
|
+
// A PROTECTED device whose passkey is gone can never open its sealed copy: this origin starts over (the Spaces live in the
|
|
72
|
+
// account backup and the other devices)
|
|
73
|
+
startOver: async () => {
|
|
74
|
+
if (!(await confirm({ title: 'Start over on this device?', text: 'This copy can’t be unlocked anymore, so it will be cleared. Your Spaces stay in your account — restore them with your recovery code.', ok: 'Start over', cancel: 'Cancel' }).catch(() => false))) return
|
|
75
|
+
localStorage.setItem(resetMarker, '1')
|
|
76
|
+
reload()
|
|
77
|
+
},
|
|
78
|
+
},
|
|
79
|
+
})
|
|
80
|
+
const view = () => { const c = lock.cfg(); return { available: true, on: !!c.on, protect: !!(c.on && c.protect && c.protect.on) } }
|
|
81
|
+
return {
|
|
82
|
+
/** Before the vault reads anything: the lock screen at every launch while the lock is on; resolves once it is unlocked
|
|
83
|
+
* (on a protected device, once the passkey has opened this origin's storage). */
|
|
84
|
+
async boot () {
|
|
85
|
+
mountUi()
|
|
86
|
+
lock.wireVisibility()
|
|
87
|
+
if (!lock.cfg().on) { running = true; return } // turned on later in the sheet, it then engages while running
|
|
88
|
+
released = new Promise((res) => { onReleased = res })
|
|
89
|
+
lock.engage('launch')
|
|
90
|
+
if (lock.isLocked()) await released
|
|
91
|
+
if (protectedLocalActive()) await protectedLocalReady()
|
|
92
|
+
running = true
|
|
93
|
+
},
|
|
94
|
+
/** The worker exists: from now on the hooks reach it. */
|
|
95
|
+
setWorker (fn) { workerCall = fn },
|
|
96
|
+
/** What a NEW worker must hear before anything else (replayed at every start / restart): the device key, on a protected device. */
|
|
97
|
+
workerUnseal: () => (raw ? { t: 'unseal', key: raw, previews } : null),
|
|
98
|
+
previewsAllowed: () => !view().protect || previews,
|
|
99
|
+
/** The lock sheet — resolves with the lock's state when the person closes it. */
|
|
100
|
+
showSheet () {
|
|
101
|
+
return new Promise((resolve) => {
|
|
102
|
+
lock.showSheet(); show() // the sheet is a card over the page: only a real lock hides it
|
|
103
|
+
const cl = document.getElementById('lockClose')
|
|
104
|
+
const done = () => { if (cl) cl.removeEventListener('click', done); resolve(view()) }
|
|
105
|
+
if (cl) cl.addEventListener('click', done); else resolve(view())
|
|
106
|
+
})
|
|
107
|
+
},
|
|
108
|
+
view,
|
|
109
|
+
locked: () => lock.isLocked(),
|
|
110
|
+
}
|
|
111
|
+
}
|
package/vaultCorePush.js
ADDED
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
// vaultCorePush.js — NOTIFICATIONS FROM A BUILDERS' VAULT (vault-core.js; docs/sdk-vault-mode.md § Notifications; the owner,
|
|
2
|
+
// 2026-11-13: "Do all including #5"). Loaded ONLY for a vault started with `push: true` — a vault without it never fetches this
|
|
3
|
+
// file — and on only once the PERSON says yes, in the vault's own card (wb.vault.showNotifications()).
|
|
4
|
+
//
|
|
5
|
+
// What it does is what our hosted vault does, with the same pieces: the browser's subscription with Witbitz's PUBLIC push key
|
|
6
|
+
// (config.js — the server signs every tickle with its private half), made the robust way (pushCore.js: the iOS lessons), then
|
|
7
|
+
// registered on each Space the vault holds through the vault's OWN key worker (`subscribe` / `unsubscribe` — never page ops).
|
|
8
|
+
// Witbitz's server already tickles every device a room lists, so nothing new runs there. The service worker is the kit's
|
|
9
|
+
// push-sw.js over the shared sw-notif-core.js: it opens the sealed preview with the room's notification key the key worker
|
|
10
|
+
// keeps in this origin's IndexedDB (generic text when the device's storage is protected), and routes a tap.
|
|
11
|
+
//
|
|
12
|
+
// The page learns { available, on } and, when a notification is tapped, which Space (`notifOpen`) — only one this vault holds.
|
|
13
|
+
import { swRegBounded, subscribeRobust } from './pushCore.js'
|
|
14
|
+
import { VAPID_PUBLIC_KEY } from './config.js'
|
|
15
|
+
|
|
16
|
+
export const PUSH_KEY = 'wbvault:push' // { on, endpoint, rooms: [the Spaces this device is listed on] } — this device's setting
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* @param {object} o
|
|
20
|
+
* @param {Storage} o.storage
|
|
21
|
+
* @param {(room: string, sub: object, quiet: boolean) => Promise<object>} o.subscribe through the vault's key worker
|
|
22
|
+
* @param {(room: string, sub: object) => Promise<object>} o.unsubscribe
|
|
23
|
+
* @param {(endpoint: string) => void} o.setSelf the key worker's turns skip this device (its own posts do not tickle it)
|
|
24
|
+
* @param {(room: string) => boolean} o.held
|
|
25
|
+
* @param {(room: string) => void} o.onOpen a tapped notification's Space (warm)
|
|
26
|
+
* @param {string} [o.worker] the service worker's path (default /push-sw.js, the kit's)
|
|
27
|
+
*/
|
|
28
|
+
export function createVaultPush ({ storage, subscribe, unsubscribe, setSelf, held, onOpen, onChange = null, worker = '/push-sw.js', nav = (typeof navigator !== 'undefined' ? navigator : null), N = (typeof Notification !== 'undefined' ? Notification : null) }) {
|
|
29
|
+
const read = () => { try { const v = JSON.parse(storage.getItem(PUSH_KEY) || 'null'); return v && typeof v === 'object' ? v : { on: false } } catch { return { on: false } } }
|
|
30
|
+
const save = (v) => { try { storage.setItem(PUSH_KEY, JSON.stringify(v)) } catch { /* a full store: on for this session */ } }
|
|
31
|
+
let sub = null, chain = Promise.resolve()
|
|
32
|
+
// KNOWN: start() has finished (a subscription loaded, or found off / unsupported). Until then this device's endpoint is NOT KNOWN —
|
|
33
|
+
// the account service must not be told "none" (Codex sweep 2026-11-16 #2). `changed` runs after every change of it.
|
|
34
|
+
let readyOk = null
|
|
35
|
+
const ready = new Promise((r) => { readyOk = r })
|
|
36
|
+
const changed = () => { readyOk(); try { if (typeof onChange === 'function') onChange() } catch { /* */ } }
|
|
37
|
+
const serial = (fn) => { const p = chain.then(fn); chain = p.catch(() => {}); return p } // one change of the list at a time
|
|
38
|
+
const supported = () => !!(nav && nav.serviceWorker && N && typeof globalThis.PushManager !== 'undefined')
|
|
39
|
+
const view = () => ({ available: true, on: !!read().on })
|
|
40
|
+
const json = (s) => (s && typeof s.toJSON === 'function' ? s.toJSON() : s)
|
|
41
|
+
// what an unsubscribe names: the live subscription, else the endpoint this device was listed under (the server drops by endpoint) —
|
|
42
|
+
// a revoked permission or a missing worker must not leave every Space tickling a device that turned notifications off (review)
|
|
43
|
+
const named = (st) => (sub ? json(sub) : st && st.endpoint ? { endpoint: st.endpoint } : null)
|
|
44
|
+
// ⛔ A SPACE IS TAKEN OFF ITS LIST ONLY WHEN THE SERVER SAYS SO (review, 2026-11-13): a failed unsubscribe (offline) is kept in
|
|
45
|
+
// `off` and tried again at the next start — three starts, then it is let go (a Space whose key is gone can never be asked).
|
|
46
|
+
// → whether it is settled (taken off, or refused for good by the server).
|
|
47
|
+
const takeOff = async (room, s) => { const a = s ? await unsubscribe(room, s).catch(() => null) : null; return !!(a && a.status >= 200 && a.status < 500) }
|
|
48
|
+
const stillOff = (st, room) => { const off = (Array.isArray(st.off) ? st.off : []).filter((o) => o && o.room !== room); return [...off, { room, n: 0 }].slice(-200) }
|
|
49
|
+
|
|
50
|
+
// THE LIST, kept in step: every Space held is listed, a Space dropped is taken off — the vault calls it after each change
|
|
51
|
+
// `loud`: the first Space listed asks the server for its "Notifications are on" push — the person's proof it works, now
|
|
52
|
+
function sync (rooms, { loud = false } = {}) {
|
|
53
|
+
return serial(async () => {
|
|
54
|
+
let st = read(); if (!st.on || !sub) return
|
|
55
|
+
const want = new Set(rooms), had = new Set(Array.isArray(st.rooms) ? st.rooms : [])
|
|
56
|
+
for (const r of want) if (!had.has(r)) { const a = await subscribe(r, json(sub), !loud).catch(() => null); if (a && a.status === 200) { had.add(r); loud = false } }
|
|
57
|
+
for (const r of [...had]) if (!want.has(r)) { had.delete(r); if (!(await takeOff(r, json(sub)))) st = { ...st, off: stillOff(st, r) } }
|
|
58
|
+
save({ ...read(), rooms: [...had], ...(st.off ? { off: st.off } : {}) })
|
|
59
|
+
})
|
|
60
|
+
}
|
|
61
|
+
try { // a TAP on a warm vault: sw-notif-core focuses this window and posts the room
|
|
62
|
+
nav && nav.serviceWorker && nav.serviceWorker.addEventListener('message', (e) => {
|
|
63
|
+
const d = e && e.data
|
|
64
|
+
if (d && d.ch === 'notif-open' && typeof d.room === 'string' && d.room && held(d.room)) onOpen(d.room)
|
|
65
|
+
})
|
|
66
|
+
} catch { /* no service workers here */ }
|
|
67
|
+
return {
|
|
68
|
+
view,
|
|
69
|
+
sync,
|
|
70
|
+
endpoint: () => (sub ? sub.endpoint : ''),
|
|
71
|
+
/** Resolves once start() knows this device's endpoint (or that there is none). */
|
|
72
|
+
ready,
|
|
73
|
+
/** A Space about to be forgotten: off its list NOW, while the key worker still holds its key (after, the request has none). */
|
|
74
|
+
drop (room) {
|
|
75
|
+
return serial(async () => {
|
|
76
|
+
const st = read(), rs = Array.isArray(st.rooms) ? st.rooms : []
|
|
77
|
+
if (!rs.includes(room)) return
|
|
78
|
+
const done = await takeOff(room, named(st))
|
|
79
|
+
save({ ...read(), rooms: rs.filter((r) => r !== room), ...(done ? {} : { off: stillOff(read(), room) }) })
|
|
80
|
+
})
|
|
81
|
+
},
|
|
82
|
+
/** At start: a device that turned notifications on keeps its subscription (and the worker, its current bytes). */
|
|
83
|
+
async start (rooms) {
|
|
84
|
+
try { return await this._start(rooms) } finally { changed() } // known now, whatever the outcome
|
|
85
|
+
},
|
|
86
|
+
/** @private */
|
|
87
|
+
async _start (rooms) {
|
|
88
|
+
if (!read().on) return this._retryOff() // turned off with a list it could not reach: try those once more
|
|
89
|
+
if (!supported()) return
|
|
90
|
+
if (N.permission !== 'granted') { await this.disable(); return } // revoked in the browser's settings: off, and off every list (review)
|
|
91
|
+
await serial(async () => { // what an earlier unsubscribe could not reach, once more
|
|
92
|
+
const st = read(), s = named(st), off = []
|
|
93
|
+
for (const o of Array.isArray(st.off) ? st.off : []) if (o && !(await takeOff(o.room, s)) && o.n < 2) off.push({ room: o.room, n: o.n + 1 })
|
|
94
|
+
save({ ...read(), off })
|
|
95
|
+
})
|
|
96
|
+
try { await nav.serviceWorker.register(worker); const r = await subscribeRobust(await swRegBounded({ path: worker, sw: nav.serviceWorker }), VAPID_PUBLIC_KEY); sub = r.sub } catch { sub = null }
|
|
97
|
+
if (!sub) return
|
|
98
|
+
setSelf(sub.endpoint)
|
|
99
|
+
if (sub.endpoint !== read().endpoint) save({ ...read(), endpoint: sub.endpoint, rooms: [] }) // a new subscription: every Space lists it again
|
|
100
|
+
return sync(rooms)
|
|
101
|
+
},
|
|
102
|
+
/** On — call it right after the person's click (the permission prompt needs that gesture). */
|
|
103
|
+
async enable (rooms) {
|
|
104
|
+
if (!supported()) throw Object.assign(new Error('vault: this browser cannot receive notifications here'), { code: 'push_unavailable' })
|
|
105
|
+
const perm = N.permission === 'granted' ? 'granted' : await N.requestPermission()
|
|
106
|
+
if (perm !== 'granted') throw Object.assign(new Error('vault: notifications were not allowed'), { code: 'push_denied' })
|
|
107
|
+
await nav.serviceWorker.register(worker)
|
|
108
|
+
const reg = await swRegBounded({ path: worker, sw: nav.serviceWorker })
|
|
109
|
+
const r = await subscribeRobust(reg, VAPID_PUBLIC_KEY)
|
|
110
|
+
if (!r.sub) throw Object.assign(new Error('vault: the push service did not answer — ' + r.err), { code: 'push_unavailable' })
|
|
111
|
+
sub = r.sub; setSelf(sub.endpoint)
|
|
112
|
+
save({ on: true, endpoint: sub.endpoint, rooms: [] })
|
|
113
|
+
await sync(rooms, { loud: true })
|
|
114
|
+
changed()
|
|
115
|
+
return view()
|
|
116
|
+
},
|
|
117
|
+
/** Off: every Space takes this device off its list, then the subscription goes. */
|
|
118
|
+
async disable () {
|
|
119
|
+
await serial(async () => {
|
|
120
|
+
const st = read(), s = named(st), off = []
|
|
121
|
+
for (const r of [...(Array.isArray(st.rooms) ? st.rooms : []), ...(Array.isArray(st.off) ? st.off.map((o) => o && o.room) : [])].filter(Boolean)) if (!(await takeOff(r, s))) off.push({ room: r, n: 0 })
|
|
122
|
+
try { if (sub) await sub.unsubscribe() } catch { /* the push service forgets it on its own */ }
|
|
123
|
+
sub = null; setSelf('')
|
|
124
|
+
save(off.length && st.endpoint ? { on: false, endpoint: st.endpoint, off } : { on: false }) // what could not be reached is tried again at the next start
|
|
125
|
+
})
|
|
126
|
+
changed()
|
|
127
|
+
return view()
|
|
128
|
+
},
|
|
129
|
+
/** @private an OFF device's leftovers — the Spaces an earlier "off" could not reach (start() runs it while off) */
|
|
130
|
+
async _retryOff () {
|
|
131
|
+
await serial(async () => {
|
|
132
|
+
const st = read(); if (st.on || !Array.isArray(st.off) || !st.off.length) return
|
|
133
|
+
const off = []
|
|
134
|
+
for (const o of st.off) if (o && !(await takeOff(o.room, named(st))) && o.n < 2) off.push({ room: o.room, n: o.n + 1 })
|
|
135
|
+
save(off.length ? { ...st, off } : { on: false })
|
|
136
|
+
})
|
|
137
|
+
return view()
|
|
138
|
+
},
|
|
139
|
+
}
|
|
140
|
+
}
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
// THE HOSTED VAULT'S DEVICE STORAGE KEY (docs/vault-at-rest-and-invites-plan.md § 1, phase 1). 32 random bytes made once per vault
|
|
2
|
+
// origin and kept WRAPPED (AES-GCM) under a NON-extractable key in this origin's IndexedDB — the builders' vault's pattern
|
|
3
|
+
// (vaultAtRest.deviceWrapKey). At every launch the vault unwraps it with no prompt and hands the bytes to the same three sealers
|
|
4
|
+
// passkey protection uses (protectedLocal, the key worker, idbSeal): a copy, sync or search of the saved data alone finds no room
|
|
5
|
+
// key. It does NOT stand against malware that copies the whole browser profile (the wrapping key is in it) — the passkey does.
|
|
6
|
+
//
|
|
7
|
+
// null when there is no IndexedDB (Lockdown Mode, some private windows): the vault stays as it is, clear — never a key lost for want
|
|
8
|
+
// of a seal (the builders' vault's rule). A wrapped key the wrapping key cannot open (IndexedDB half cleared) also answers null and
|
|
9
|
+
// `lost: true`: the sealed entries cannot be opened, and the caller treats the device as new.
|
|
10
|
+
const DB = 'wbvault-device-key'
|
|
11
|
+
const reqP = (r) => new Promise((res, rej) => { r.onsuccess = () => res(r.result); r.onerror = () => rej(r.error) })
|
|
12
|
+
|
|
13
|
+
/** The sealing switch's clear marker (protectedLocal.js STAYS_CLEAR): set once this vault's storage was sealed by the device key, so
|
|
14
|
+
* the next launch's protectedLocal starts sealed (reads wait for the unlock) instead of passing through. */
|
|
15
|
+
export const AT_REST_MARK = 'vault:atrest'
|
|
16
|
+
|
|
17
|
+
// ⛔ A READ THAT FAILED IS NOT A KEY THAT IS GONE (the owner's iPhone, 2026-11-14 12:43:56Z: "My account was reset"). Any error here
|
|
18
|
+
// answered null — the same answer as "this browser has no IndexedDB" — and the vault, finding its storage sealed, took it for a lost
|
|
19
|
+
// key and dropped every sealed entry, the account record among them. iOS fails IndexedDB opens now and then (a page woken from the
|
|
20
|
+
// background: "Connection to Indexed Database server lost"). So: a failed read is tried again (`tries`), and one that keeps failing
|
|
21
|
+
// answers `{ raw: null, error }` — the caller deletes nothing on it. `made` is true only when THIS call wrote the key: an `add` that
|
|
22
|
+
// lost to an existing one (a read that came back empty for a moment) is not a new key.
|
|
23
|
+
const RETRY_MS = [150, 400, 900]
|
|
24
|
+
|
|
25
|
+
// THE OS KEY STORE MAY WAIT FOR THE PERSON (the owner's WSL, 2026-11-22): a keyring never set up asks for a password in a window of its own
|
|
26
|
+
// (GNOME Keyring's prompt — on WSL it can open behind the app), and the read waits for that answer. It used to wait in silence under the
|
|
27
|
+
// loading screen until the boot watch said "didn't finish loading" and offered a Repair that cannot help. Now: the wait is marked
|
|
28
|
+
// `data-unlocking` (the boot watch holds its verdict, vault-boot-guard.js), the loading screen says what it waits for, and a key store
|
|
29
|
+
// that never answers ends in an error (the caller's "Couldn't open your saved data" — Try again), never a hang.
|
|
30
|
+
export const KEY_WAIT_MS = 180000
|
|
31
|
+
const KEY_WAIT_SAY_MS = 3000
|
|
32
|
+
export async function waitForKeyStore (call, ms = KEY_WAIT_MS) {
|
|
33
|
+
const doc = typeof document !== 'undefined' ? document : null
|
|
34
|
+
const root = doc && doc.documentElement
|
|
35
|
+
let said = null, sayT = 0, endT = 0
|
|
36
|
+
try { if (root) root.setAttribute('data-unlocking', 'keyring') } catch { /* */ }
|
|
37
|
+
sayT = setTimeout(() => {
|
|
38
|
+
try {
|
|
39
|
+
const t = doc && doc.querySelector('#bootLoad .bl-txt')
|
|
40
|
+
if (t) { said = t.textContent; t.textContent = 'Waiting for your keyring… If a window asks for a keyring password, answer it — it may be behind this one.' }
|
|
41
|
+
} catch { /* */ }
|
|
42
|
+
}, KEY_WAIT_SAY_MS)
|
|
43
|
+
try {
|
|
44
|
+
return await Promise.race([typeof call === 'function' ? call() : call, new Promise((resolve) => { endT = setTimeout(() => resolve({ error: 'the keyring did not answer in ' + Math.round(ms / 1000) + ' s' }), ms) })])
|
|
45
|
+
} finally {
|
|
46
|
+
clearTimeout(sayT); clearTimeout(endT)
|
|
47
|
+
try { if (root && root.getAttribute('data-unlocking') === 'keyring') root.removeAttribute('data-unlocking') } catch { /* */ }
|
|
48
|
+
try { const t = said != null && doc.querySelector('#bootLoad .bl-txt'); if (t) t.textContent = said } catch { /* */ }
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
/** @returns {Promise<{ raw: Uint8Array, made: boolean, os?: true } | { raw: null, lost: true } | { raw: null, error: string } | null>} */
|
|
52
|
+
export async function deviceStorageKey ({ desktop = globalThis.WitbitzDesktop, idb = (typeof indexedDB !== 'undefined' ? indexedDB : null), subtle = (globalThis.crypto && crypto.subtle), tries = RETRY_MS.length + 1, wait = (ms) => new Promise((r) => setTimeout(r, ms)), keyWaitMs = KEY_WAIT_MS } = {}) {
|
|
53
|
+
// THE DESKTOP APP (desktop/keyStore.mjs, Linux and the Mac): the key is kept by the operating system's key store (the Keychain, the
|
|
54
|
+
// Secret Service), not beside the files it seals — a copy of the app's files opens nothing. Its `error` is this function's (the caller
|
|
55
|
+
// deletes nothing); a desktop app with no usable key store (Linux without a keyring) falls back to this origin's own key below.
|
|
56
|
+
if (desktop && typeof desktop.storageKey === 'function') {
|
|
57
|
+
let r = null
|
|
58
|
+
try { r = await waitForKeyStore(() => desktop.storageKey(), keyWaitMs) } catch (e) { r = { error: String((e && e.message) || e).slice(0, 200) } }
|
|
59
|
+
if (r && typeof r.raw === 'string' && r.raw) {
|
|
60
|
+
const raw = Uint8Array.from(atob(r.raw.replace(/-/g, '+').replace(/_/g, '/')), (c) => c.charCodeAt(0))
|
|
61
|
+
if (raw.length === 32) return { raw, made: !!r.made, os: true }
|
|
62
|
+
return { raw: null, error: 'desktop key: bad length' }
|
|
63
|
+
}
|
|
64
|
+
// `refused`: the key store answered and would not open the key saved here (made under a keyring since replaced) — not "no keyring"
|
|
65
|
+
if (!(r && /^no_(keystore|keyring)$/.test(String(r.error)))) return { raw: null, error: 'desktop key: ' + String((r && r.error) || 'no answer').slice(0, 160), ...(/^(keystore_refused|bad_key)/.test(String(r && r.error)) ? { refused: true } : {}) }
|
|
66
|
+
}
|
|
67
|
+
if (!idb || !subtle) return null
|
|
68
|
+
let last = null
|
|
69
|
+
for (let i = 0; i < tries; i++) {
|
|
70
|
+
if (i) await wait(RETRY_MS[Math.min(i - 1, RETRY_MS.length - 1)])
|
|
71
|
+
try { return await readOnce(idb, subtle) } catch (e) { last = e }
|
|
72
|
+
}
|
|
73
|
+
return { raw: null, error: String((last && (last.name ? last.name + ': ' : '') + (last.message || '')) || last || 'unknown').slice(0, 200) }
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
async function readOnce (idb, subtle) {
|
|
77
|
+
let db = null
|
|
78
|
+
try {
|
|
79
|
+
db = await new Promise((res, rej) => { const r = idb.open(DB, 1); r.onupgradeneeded = () => r.result.createObjectStore('k'); r.onsuccess = () => res(r.result); r.onerror = () => rej(r.error) })
|
|
80
|
+
const get = (k) => reqP(db.transaction('k', 'readonly').objectStore('k').get(k)).then((v) => v || null)
|
|
81
|
+
// `add`, never `put`: two tabs making it at once — the first wins, both read back the same one
|
|
82
|
+
const add = (k, v) => new Promise((res) => { const t = db.transaction('k', 'readwrite'); t.objectStore('k').add(v, k); t.oncomplete = () => res(true); t.onabort = () => res(false); t.onerror = (e) => { try { e.preventDefault() } catch { /* */ } } }) // true: this call wrote it
|
|
83
|
+
let wrap = await get('wrap')
|
|
84
|
+
if (!wrap) { await add('wrap', await subtle.generateKey({ name: 'AES-GCM', length: 256 }, false, ['encrypt', 'decrypt'])); wrap = await get('wrap') }
|
|
85
|
+
if (!wrap || wrap.type !== 'secret') return null
|
|
86
|
+
let made = false, sealed = await get('sealed')
|
|
87
|
+
if (!sealed) {
|
|
88
|
+
const raw = crypto.getRandomValues(new Uint8Array(32)), iv = crypto.getRandomValues(new Uint8Array(12))
|
|
89
|
+
made = await add('sealed', { iv, ct: new Uint8Array(await subtle.encrypt({ name: 'AES-GCM', iv }, wrap, raw)) })
|
|
90
|
+
sealed = await get('sealed')
|
|
91
|
+
if (!sealed) throw new Error('the device key could not be read back')
|
|
92
|
+
}
|
|
93
|
+
try { return { raw: new Uint8Array(await subtle.decrypt({ name: 'AES-GCM', iv: sealed.iv }, wrap, sealed.ct)), made } } catch { return { raw: null, lost: true } }
|
|
94
|
+
} finally { try { db && db.close() } catch { /* */ } }
|
|
95
|
+
}
|