@witbitz/sdk 0.0.0-stage → 4.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +20 -2
- package/a2aCore.js +221 -0
- package/a2aShared.js +27 -0
- package/accountErase.js +228 -0
- package/accountIndexDoc.js +122 -0
- package/accountOwner.js +59 -0
- package/accountRecord.js +90 -0
- package/accountScope.js +114 -0
- package/accountSeal.js +42 -0
- package/accountStores.js +173 -0
- package/acctV2App.js +619 -0
- package/acctV2Check.js +29 -0
- package/acctV2Client.js +382 -0
- package/acctV2Keys.js +43 -0
- package/acctV2Legacy.js +14 -0
- package/acctV2Switch.js +80 -0
- package/acctV2UiCore.js +857 -0
- package/acctV2WebAuthn.js +61 -0
- package/acctV2Wire.js +59 -0
- package/address.js +42 -0
- package/agentDoorTools.js +28 -0
- package/attestedBox.js +30 -0
- package/attestedRooms.js +78 -0
- package/awsKey.js +98 -0
- package/backupRecord.js +106 -0
- package/backupVault.js +97 -0
- package/blocks.js +115 -0
- package/blocksPush.js +64 -0
- package/browseSeal.js +103 -0
- package/cbor.js +225 -0
- package/changePush.js +75 -0
- package/chatLock.js +165 -0
- package/chatLockSw.js +13 -0
- package/cloudDeviceBuilds.js +11 -0
- package/cloudDevicePins.js +33 -0
- package/cloudDeviceSeal.js +53 -0
- package/codeAttachments.js +100 -0
- package/codeBrowse.js +224 -0
- package/codeCache.js +149 -0
- package/codeCloud.js +650 -0
- package/codeCloudKeys.js +112 -0
- package/codeCommands.js +167 -0
- package/codeComputers.js +389 -0
- package/codeEgress.js +123 -0
- package/codeFilesRoutes.js +17 -0
- package/codeFolders.js +116 -0
- package/codeHistory.js +76 -0
- package/codeLanguage.js +54 -0
- package/codeMkdir.js +8 -0
- package/codeModes.js +59 -0
- package/codeOrphanKeys.js +42 -0
- package/codeOutputs.js +141 -0
- package/codeProgress.js +54 -0
- package/codeRelay.js +505 -0
- package/codeSent.js +68 -0
- package/codeSentinel.js +86 -0
- package/codeSubagents.js +107 -0
- package/codeTransport.js +317 -0
- package/codeUndo.js +48 -0
- package/compress.js +24 -0
- package/config.js +11 -0
- package/connCatalog.js +164 -0
- package/connDisp.js +76 -0
- package/connOtherWays.js +74 -0
- package/connPending.js +16 -0
- package/connWrap.js +53 -0
- package/connectionEntry.js +89 -0
- package/connections.js +561 -0
- package/credits.js +30 -0
- package/csAttest.js +112 -0
- package/decrypt.html +384 -0
- package/deviceAttest.js +527 -0
- package/deviceCall.js +54 -0
- package/deviceKeyCore.js +41 -0
- package/deviceSeal.js +59 -0
- package/e2ee.js +323 -0
- package/eat.js +103 -0
- package/emailFork.js +275 -0
- package/emailSignIn.js +81 -0
- package/emptySpaces.js +111 -0
- package/encSource.js +55 -0
- package/enclaveAccept.js +214 -0
- package/enclaveClaim.js +241 -0
- package/enclaveRoute.js +102 -0
- package/enclaveSnapshotMerge.js +44 -0
- package/entrySig.js +165 -0
- package/env.js +73 -0
- package/eraseFile.js +58 -0
- package/followImage.js +86 -0
- package/healNames.js +45 -0
- package/idb.js +113 -0
- package/idbSeal.js +119 -0
- package/indexGone.js +12 -0
- package/invite.js +51 -0
- package/inviteEnroll.js +67 -0
- package/inviteSend.js +68 -0
- package/jobAgents.js +87 -0
- package/keptMerge.js +91 -0
- package/l1-worker-src.js +2 -0
- package/l1-worker.js +894 -0
- package/laneAssociation.js +68 -0
- package/laneConfig.js +58 -0
- package/laneLinkCore.js +177 -0
- package/ledgerView.js +64 -0
- package/manifest.json +239 -0
- package/mcpRecommended.js +25 -0
- package/memberChange.js +125 -0
- package/mirrorBatch.js +47 -0
- package/mkseal.js +101 -0
- package/nativePush.js +153 -0
- package/nitroVerify.js +220 -0
- package/noble-p256.js +27 -0
- package/notice.js +116 -0
- package/notifKey.js +58 -0
- package/offlineBundle.js +62 -0
- package/ohttp.js +177 -0
- package/opRouting.js +10 -0
- package/opencodeWire.js +282 -0
- package/oprf.js +70 -0
- package/ownAgentLink.js +96 -0
- package/ownerPolicy.js +117 -0
- package/package.json +273 -4
- package/pdfOptions.js +13 -0
- package/pdfText.js +107 -0
- package/pdfjs.mjs +28 -0
- package/pdfjs.worker.mjs +28 -0
- package/pollVerdict.js +33 -0
- package/prefetchPoll.js +60 -0
- package/protectedLocal.js +426 -0
- package/pushCore.js +42 -0
- package/recovery.js +107 -0
- package/regions.js +42 -0
- package/removedMessage.js +11 -0
- package/renameRefusal.js +9 -0
- package/replyQuote.js +34 -0
- package/reqEnvelope.js +126 -0
- package/roomDefaultPrefs.js +76 -0
- package/roomDelete.js +109 -0
- package/roomEmbed.js +111 -0
- package/roomName.js +177 -0
- package/roomPass.js +256 -0
- package/roomRoster.js +305 -0
- package/roomSettings.js +61 -0
- package/roomState.js +58 -0
- package/roomStreamClient.js +115 -0
- package/rosterCount.js +52 -0
- package/rosterHash.js +13 -0
- package/rowSchema.js +113 -0
- package/safeMedia.js +116 -0
- package/safeMediaPins.js +17 -0
- package/schedulesDoc.js +78 -0
- package/sdkA2A.js +524 -0
- package/sdkAccount.js +483 -0
- package/sdkAccountDoc.js +89 -0
- package/sdkAccountSections.js +332 -0
- package/sdkAgui.js +141 -0
- package/sdkAttest.js +34 -0
- package/sdkBackup.js +507 -0
- package/sdkBackupV2.js +630 -0
- package/sdkBrowserPrivate.js +28 -0
- package/sdkBuilds.js +208 -0
- package/sdkCloudDevice.js +221 -0
- package/sdkComputers.js +1009 -0
- package/sdkDictation.js +232 -0
- package/sdkErase.js +288 -0
- package/sdkExports.js +71 -0
- package/sdkInvitations.js +34 -0
- package/sdkKeptAgent.js +188 -0
- package/sdkLaneLink.js +205 -0
- package/sdkPlan.js +96 -0
- package/sdkProtect.js +228 -0
- package/sdkRedact.js +36 -0
- package/sdkRekey.js +340 -0
- package/sdkReport.js +68 -0
- package/sdkSafeMedia.js +255 -0
- package/sdkSchedules.js +39 -0
- package/sdkSpeech.js +71 -0
- package/sdkTemporaryRooms.js +123 -0
- package/sdkTurn.js +117 -0
- package/sdkVault.js +180 -0
- package/sealShare.js +18 -0
- package/sealedNames.js +64 -0
- package/sealedReceipt.js +17 -0
- package/sentinelRelease.js +155 -0
- package/shamir.js +85 -0
- package/sharedViews.js +52 -0
- package/sheetChrome.js +450 -0
- package/siri.js +278 -0
- package/spaceClient.js +1429 -0
- package/spaceConfig.js +81 -0
- package/spaceEmailGate.js +813 -0
- package/spaceExport.js +125 -0
- package/spaceFork.js +216 -0
- package/spaceLock.js +358 -0
- package/spacePasskey.js +180 -0
- package/spaceTemplates.js +99 -0
- package/speechOut.js +102 -0
- package/splitKeyClient.js +90 -0
- package/store.js +656 -0
- package/streamHint.js +36 -0
- package/sttCloud.js +220 -0
- package/sttWorklet.js +38 -0
- package/sw-notif-core.js +540 -0
- package/tempList.js +48 -0
- package/tinfoilVerifier.js +78 -0
- package/toolBooks.js +31 -0
- package/toolRules.js +52 -0
- package/turnCerts.js +254 -0
- package/turnFeed.js +58 -0
- package/turnVerdict.js +37 -0
- package/usageReceipts.js +176 -0
- package/usageSummary.js +90 -0
- package/util.js +181 -0
- package/vault-core.js +2326 -0
- package/vault-kit.mjs +354 -0
- package/vault-screens.js +261 -0
- package/vaultAtRest.js +208 -0
- package/vaultCoreLock.js +111 -0
- package/vaultCorePush.js +140 -0
- package/vaultDeviceKey.js +95 -0
- package/vaultEnclaveHandoff.js +114 -0
- package/vaultKeep.js +287 -0
- package/vaultSealedStore.js +77 -0
- package/vaultWorkerHost.js +117 -0
- package/vcWorker.js +34 -0
- package/voiceAttest.js +50 -0
- package/voiceCert.js +51 -0
- package/witbitz-admin.d.ts +135 -0
- package/witbitz-admin.js +529 -0
- package/witbitz-admin.mjs +1460 -0
- package/witbitz-sdk.d.ts +1197 -0
- package/witbitz-sdk.js +4258 -0
- package/workerClient.js +16 -0
- package/workerLiveness.js +21 -0
- package/x509.js +218 -0
package/sdkBackupV2.js
ADDED
|
@@ -0,0 +1,630 @@
|
|
|
1
|
+
// sdkBackupV2.js — A BUILDER'S ACCOUNT ON THE NEW ACCOUNT SERVICE (account recovery v2, docs/account-recovery-protocol.md), run
|
|
2
|
+
// in the builder's VAULT (vault-core.js), where the master never leaves. The owner, 2026-11-16: "Yes. Do the sdk." — the SDK
|
|
3
|
+
// follows our own two apps (2026-11-15): a NEW account made in a vault that names its tenant starts on the new service; an
|
|
4
|
+
// account already on the old backup store stays there; a restore asks the new service first, then the old store.
|
|
5
|
+
//
|
|
6
|
+
// What it reuses: the reviewed flows of acctV2App.js (makeAcctV2: the first code shown and kept before its activation, the
|
|
7
|
+
// pending-code reconcile, restore, the status check, sign out the other devices, a new code, delete) over acctV2Client.js. What
|
|
8
|
+
// is the SDK's: where the state lives (the backup state's `v2`, persisted by the vault and sealed on its disk), the device key
|
|
9
|
+
// (the vault origin's IndexedDB, one per account — `v2.dk`), and the record it backs up (the SDK's account record).
|
|
10
|
+
//
|
|
11
|
+
// TWO MASTERS. `state.master` stays the account's IDENTITY — its index room, usage and erase keys derive from it (sdkAccount.js,
|
|
12
|
+
// sdkErase.js) — and a new recovery code does not change it. `state.v2.bm` is the BACKUP master the service's two objects are
|
|
13
|
+
// sealed under (backupVault.js), replaced by every new code. The backup carries the identity (`sdkMaster`), so a restore brings
|
|
14
|
+
// both back.
|
|
15
|
+
//
|
|
16
|
+
// THE TENANT names the app on every request (`x-acct-tenant`): the builder's accounts are its own on the service, and the service
|
|
17
|
+
// believes it only from one of the tenant's declared AND proven origins (control-plane/src/lib/acct/appScope.mjs) — so the
|
|
18
|
+
// VAULT's origin must be one. A vault whose origin the service refuses (403 tenant_origin) before anything is made goes on with the
|
|
19
|
+
// old store, as before this release.
|
|
20
|
+
// Security keys use the shared account-service ceremonies. To add a second device, restore with the
|
|
21
|
+
// recovery code. Legacy migration and email-move flows reuse the reviewed account-service protocol below.
|
|
22
|
+
import { makeAcctV2, STATE_KEY, ERASE_KEY, MOVE_KEY, RESET_KEY } from './acctV2App.js'
|
|
23
|
+
import { canonicalAddress } from './acctV2Client.js'
|
|
24
|
+
import { refusedAsRevoked, statusDue } from './acctV2Check.js'
|
|
25
|
+
import { codeSecret, newRecoveryCode, seal, unseal } from './recovery.js'
|
|
26
|
+
import { backupLocation, wrapperLocation, newMasterSecret, sealWrapper, openWrapper } from './backupVault.js'
|
|
27
|
+
import { ensureKeyRecord, newKeyRecord } from './deviceKeyCore.js'
|
|
28
|
+
import { recordFromRooms, roomsOfRecord, tombOfRecord, vaultOwner, SDK_APP } from './accountRecord.js'
|
|
29
|
+
import { applyPlan } from './backupRecord.js'
|
|
30
|
+
import { indexRoomOf, mergeIndex } from './sdkAccount.js'
|
|
31
|
+
import { appStoreKey, sealDoc, openDoc } from './accountSeal.js' // a push address sealed under the backup master (as acctV2VaultWiring.js)
|
|
32
|
+
import { v2Of, halfMade, keptPrevMasters } from './sdkBackup.js'
|
|
33
|
+
import { unb64u } from './acctV2Wire.js'
|
|
34
|
+
import { browserKeys } from './acctV2WebAuthn.js'
|
|
35
|
+
import { tokenClaims, tokenApp } from './accountScope.js'
|
|
36
|
+
import { GOOGLE_CLIENT_ID } from './config.js'
|
|
37
|
+
import { signRestoreChallenge, spkNonce } from './entrySig.js'
|
|
38
|
+
|
|
39
|
+
export const TENANT_ID = /^t_[0-9a-f]{32}$/
|
|
40
|
+
/** The account service's address — the same API domain the default Space endpoint uses (acctV2Switch.js PROD_SERVICE). */
|
|
41
|
+
export const ACCOUNT_SERVICE = 'https://api.witbitz.chat/v1'
|
|
42
|
+
|
|
43
|
+
/** A compatible, fresh vault sign-in can prove the address without a second email code. */
|
|
44
|
+
export async function restoreSignInProof(session, { action, email, origin, base = ACCOUNT_SERVICE }) {
|
|
45
|
+
if (base !== ACCOUNT_SERVICE || !action || !session?.sign?.priv || !session.sign.pub || !email) return null
|
|
46
|
+
const claims = tokenClaims(session.idToken), address = canonicalAddress(email)
|
|
47
|
+
if (!address || address !== canonicalAddress(session.email) || address !== canonicalAddress(claims?.email) || tokenApp(claims) !== null) return null
|
|
48
|
+
const now = Date.now() / 1000
|
|
49
|
+
if (!(claims.exp > now && claims.iat > now - 295 && claims.iat <= now + 60)) return null
|
|
50
|
+
if (claims.iss === 'accounts.google.com' || claims.iss === 'https://accounts.google.com') {
|
|
51
|
+
const domain = address.split('@')[1]
|
|
52
|
+
if (claims.aud !== GOOGLE_CLIENT_ID || claims.email_verified !== true) return null
|
|
53
|
+
if (!['gmail.com', 'googlemail.com'].includes(domain) && claims.hd !== domain) return null
|
|
54
|
+
} else if (claims.iss !== origin && !(origin === 'https://spaces.witbitz.chat' && claims.iss === 'https://witbitz-vault-prod.pages.dev')) return null
|
|
55
|
+
if (claims.nonce !== await spkNonce(session.sign.pub)) return null
|
|
56
|
+
return { signIn: { idToken: session.idToken, spk: session.sign.pub, sig: await signRestoreChallenge(session.sign.priv, action) } }
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
const b64 = (u8) => { let s = ''; for (let i = 0; i < u8.length; i++) s += String.fromCharCode(u8[i]); return btoa(s) }
|
|
60
|
+
const unb64 = (s) => Uint8Array.from(atob(s), (c) => c.charCodeAt(0))
|
|
61
|
+
const utf8 = (s) => new TextEncoder().encode(s)
|
|
62
|
+
const fail = (code, msg, extra = {}) => Object.assign(new Error('witbitz: ' + msg), { code, ...extra })
|
|
63
|
+
const rand = (n) => b64(crypto.getRandomValues(new Uint8Array(n))).replace(/[^A-Za-z0-9]/g, '').slice(0, n)
|
|
64
|
+
const is32 = (s) => { try { return typeof s === 'string' && unb64(s).length === 32 } catch { return false } }
|
|
65
|
+
|
|
66
|
+
/** This browser's name on the service ("Chrome on iPhone") — the words of our vault's (acctV2VaultWiring.js vaultDeviceLabel). */
|
|
67
|
+
export function deviceLabel(ua = (typeof navigator !== 'undefined' && navigator.userAgent) || '') {
|
|
68
|
+
const os = /iPhone/.test(ua) ? 'iPhone' : /iPad/.test(ua) ? 'iPad' : /Android/.test(ua) ? 'Android' : /(Mac OS X|Macintosh)/.test(ua) ? 'Mac' : /Windows/.test(ua) ? 'Windows' : /Linux/.test(ua) ? 'Linux' : 'device'
|
|
69
|
+
const br = /Edg\//.test(ua) ? 'Edge' : /(OPR\/|Opera)/.test(ua) ? 'Opera' : /Firefox\//.test(ua) ? 'Firefox' : /Chrome\//.test(ua) ? 'Chrome' : /Safari\//.test(ua) ? 'Safari' : 'browser'
|
|
70
|
+
return br + ' on ' + os
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** Where a vault keeps its device keys: raw values (a non-extractable CryptoKey is kept AS a key, never as bytes) in this origin's
|
|
74
|
+
* IndexedDB `name`. A failed read throws — the caller never mistakes it for "no key" (a new key would be another device). */
|
|
75
|
+
export function idbKeyStore(name = 'wbvault-acct', idb = (typeof indexedDB !== 'undefined' ? indexedDB : null)) {
|
|
76
|
+
const open = () => new Promise((res, rej) => { if (!idb) return rej(new Error('no IndexedDB')); const r = idb.open(name, 1); r.onupgradeneeded = () => r.result.createObjectStore('k'); r.onsuccess = () => res(r.result); r.onerror = () => rej(r.error) })
|
|
77
|
+
const run = async (mode, fn) => {
|
|
78
|
+
const db = await open()
|
|
79
|
+
try { return await new Promise((res, rej) => { const t = db.transaction('k', mode); const q = fn(t.objectStore('k')); t.oncomplete = () => res(q.result); t.onerror = () => rej(t.error); t.onabort = () => rej(t.error) }) } finally { try { db.close() } catch { /* */ } }
|
|
80
|
+
}
|
|
81
|
+
return {
|
|
82
|
+
get: async (k) => (await run('readonly', (s) => s.get(k))) ?? null,
|
|
83
|
+
set: async (k, v) => { await run('readwrite', (s) => s.put(v, k)) },
|
|
84
|
+
del: async (k) => { await run('readwrite', (s) => s.delete(k)) },
|
|
85
|
+
clear: async () => { await run('readwrite', (s) => s.clear()) },
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** THE RESTORE SCREEN, unchanged for the new service (vault-screens.js restore): it calls `restore({ code, email? })` and, on
|
|
90
|
+
* `email_code_required` with a `ticket`, asks the person for the mailed code and calls again with `{ code, ticket, emailCode }`.
|
|
91
|
+
* The new service asks for the mailed code in the MIDDLE of its flow (acctV2Client.restore) — so the flow is held there: the
|
|
92
|
+
* first call answers `email_code_required` (a `v2-` ticket) as soon as the code is mailed, and the second call hands the code in
|
|
93
|
+
* and waits for the flow's end. `run(q, getCode)` → the restore. A builder's own restore screen works as it did. */
|
|
94
|
+
export function restoreBridge(run, { waitMs = 15 * 60_000 } = {}) {
|
|
95
|
+
let held = null // { ticket, give(code), outcome: Promise }
|
|
96
|
+
return async (q = {}) => {
|
|
97
|
+
if (held && q.ticket && q.ticket === held.ticket && q.emailCode) {
|
|
98
|
+
const h = held; held = null
|
|
99
|
+
h.give(String(q.emailCode).trim())
|
|
100
|
+
const x = await h.outcome
|
|
101
|
+
if (x.e) throw x.e
|
|
102
|
+
return x.r
|
|
103
|
+
}
|
|
104
|
+
held = null
|
|
105
|
+
let asked, give, timer
|
|
106
|
+
const askedP = new Promise((res) => { asked = res })
|
|
107
|
+
const getCode = () => new Promise((res, rej) => { give = res; timer = setTimeout(() => rej(fail('cancelled', 'no code was entered')), waitMs); if (timer && timer.unref) timer.unref(); asked() })
|
|
108
|
+
const outcome = Promise.resolve().then(() => run({ ...q, ...(q.ticket && /^v2-/.test(q.ticket) ? { ticket: undefined, emailCode: undefined } : {}) }, getCode)).then((r) => ({ r }), (e) => ({ e }))
|
|
109
|
+
const first = await Promise.race([outcome.then((x) => ({ x })), askedP.then(() => null)])
|
|
110
|
+
if (first) { clearTimeout(timer); if (first.x.e) throw first.x.e; return first.x.r }
|
|
111
|
+
const ticket = 'v2-' + rand(12)
|
|
112
|
+
held = { ticket, give: (c) => { clearTimeout(timer); give(c) }, outcome }
|
|
113
|
+
throw Object.assign(fail('email_code_required', 'we emailed a code — call again with { code, ticket, emailCode }'), { ticket })
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* The new account service for a builder's vault → the object sdkBackup.js consults (`backup._v2`), or null when the vault names
|
|
119
|
+
* no tenant (no header would make its accounts the regular Witbitz app's — never).
|
|
120
|
+
* @param {object} o { tenant, base?, fetch, keyStore: { get(k), set(k, v) } (raw IndexedDB values), label?() → this device's name,
|
|
121
|
+
* persistNow(state) → Promise<boolean> (the state is on disk, read back — a new code is kept BEFORE its activation),
|
|
122
|
+
* onRevoked() (a request was refused as signed out: run the status check now), afterSignOut?(address) (the other devices were just
|
|
123
|
+
* signed out: the room pass renews at once — vault-core.js) }
|
|
124
|
+
*/
|
|
125
|
+
export function accountService({ tenant, base = ACCOUNT_SERVICE, fetch: f = (...a) => globalThis.fetch(...a), keyStore, label = () => deviceLabel(), persistNow, legacyRecovery, onRevoked = () => {}, afterSignOut = null, pushEndpoint = null, withdrawPush = null } = {}) {
|
|
126
|
+
if (!TENANT_ID.test(String(tenant || '')) || !base || !keyStore) return null
|
|
127
|
+
const headers = { 'x-acct-tenant': tenant }
|
|
128
|
+
const fetchWatched = async (...args) => {
|
|
129
|
+
const r = await f(...args)
|
|
130
|
+
if (r && r.status === 403 && typeof r.clone === 'function') r.clone().json().then((j) => { if (refusedAsRevoked(r.status, j)) onRevoked() }).catch(() => {})
|
|
131
|
+
return r
|
|
132
|
+
}
|
|
133
|
+
// one device key PER ACCOUNT in this vault (a vault keeps one backup per signed-in person): `devkey:v1|<dk>`
|
|
134
|
+
let keyEpoch = 0
|
|
135
|
+
const keysOf = (dk) => {
|
|
136
|
+
const epoch = keyEpoch
|
|
137
|
+
return { get: (k) => keyStore.get(k + '|' + dk), set: async (k, v) => {
|
|
138
|
+
if (epoch !== keyEpoch) throw fail('account_changed', 'this device was signed out while its key was being made')
|
|
139
|
+
await keyStore.set(k + '|' + dk, v)
|
|
140
|
+
if (epoch !== keyEpoch && typeof keyStore.del === 'function') await keyStore.del(k + '|' + dk)
|
|
141
|
+
} }
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/** The SDK's account record for state `s` (rooms, tombstones, email, invite key, index pointer) + the identity master. */
|
|
145
|
+
async function recordOf(s, rooms = s.rooms) {
|
|
146
|
+
return { ...recordFromRooms({ rooms, tomb: s.tomb, email: s.email, inviteKey: s.invite, indexRoom: await indexRoomOf(s.master) }), sdkMaster: s.master }
|
|
147
|
+
}
|
|
148
|
+
/** The rooms another device wrote into the head, kept beside this device's (never one this device forgot). */
|
|
149
|
+
async function recordOverHead(s, key, head) {
|
|
150
|
+
const remote = head?.blob ? await openRecord(key, head.blob) : null
|
|
151
|
+
if (!remote) throw fail('unopenable', 'the current backup could not be opened')
|
|
152
|
+
const { rooms, tomb } = mergeIndex(s, { rooms: roomsOfRecord(remote), tomb: tombOfRecord(remote) })
|
|
153
|
+
return recordOf({ ...s, tomb }, rooms)
|
|
154
|
+
}
|
|
155
|
+
const openRecord = async (key, sealed) => { try { const d = await unseal(key, sealed); return vaultOwner(d) === 'sdk' ? d : null } catch { return null } }
|
|
156
|
+
|
|
157
|
+
/** makeAcctV2 over backup state `s` (its `v2` holds what the flows keep). `hooks`: { applyRestored?, wipe?, changed?, current? }
|
|
158
|
+
* — `current()` false: the vault moved to another account (or state) meanwhile, and a new code is NOT kept (no activation is sent). */
|
|
159
|
+
const memOf = new WeakMap()
|
|
160
|
+
function client(s, hooks = {}) {
|
|
161
|
+
if (!s.v2) s.v2 = {}
|
|
162
|
+
if (!s.v2.dk) s.v2.dk = rand(16)
|
|
163
|
+
// per ACCOUNT STATE for the session, not per call: syncPush's "already sent" mark lives here — a map made fresh each call resent
|
|
164
|
+
// the device's push record on every status check (and on every change, Codex 11-16 #2)
|
|
165
|
+
const mem = memOf.get(s) || new Map(); memOf.set(s, mem)
|
|
166
|
+
const fields = new Map([[STATE_KEY, 'svc'], [ERASE_KEY, 'erase'], [MOVE_KEY, 'emailMove'], [RESET_KEY, 'reset']])
|
|
167
|
+
const storage = {
|
|
168
|
+
getItem(k) {
|
|
169
|
+
if (!fields.has(k)) return mem.get(k) ?? null
|
|
170
|
+
const value = s.v2[fields.get(k)]
|
|
171
|
+
return value == null ? null : k === STATE_KEY ? JSON.stringify(value) : value
|
|
172
|
+
},
|
|
173
|
+
setItem(k, v) {
|
|
174
|
+
if (!fields.has(k)) { mem.set(k, String(v)); return }
|
|
175
|
+
s.v2[fields.get(k)] = k === STATE_KEY ? v2Of({ svc: JSON.parse(v) })?.svc : String(v)
|
|
176
|
+
hooks.changed?.()
|
|
177
|
+
},
|
|
178
|
+
removeItem(k) {
|
|
179
|
+
if (!fields.has(k)) { mem.delete(k); return }
|
|
180
|
+
// Keep this device's request until its new account and first code are both durable.
|
|
181
|
+
if (k === RESET_KEY && hooks.finishingReset) return
|
|
182
|
+
delete s.v2[fields.get(k)]
|
|
183
|
+
hooks.changed?.()
|
|
184
|
+
},
|
|
185
|
+
flushed: async () => { if (typeof persistNow === 'function' && !(await persistNow(s))) throw fail('save_failed', 'the deletion request could not be kept on this device') },
|
|
186
|
+
}
|
|
187
|
+
const ks = keysOf(s.v2.dk)
|
|
188
|
+
let rec = null
|
|
189
|
+
const deviceKey = async () => { rec = rec || await ensureKeyRecord(ks); return rec && rec.priv && rec.spk ? { priv: rec.priv, pub: rec.pub, spk: rec.spk } : null }
|
|
190
|
+
async function sealed(payload, newCode, newMaster) {
|
|
191
|
+
const cs = codeSecret(newCode), loc = await backupLocation(newMaster)
|
|
192
|
+
return { newCode, newMaster, backupId: loc.id, wrapperId: (await wrapperLocation(cs)).id, backupBlob: utf8(await seal(loc.key, payload)), wrapperBlob: utf8(await sealWrapper(cs, newMaster)) }
|
|
193
|
+
}
|
|
194
|
+
return makeAcctV2({
|
|
195
|
+
base, fetch: fetchWatched, headers, storage,
|
|
196
|
+
canApplyStatus: hooks.canApplyStatus,
|
|
197
|
+
deviceKey,
|
|
198
|
+
newDeviceKey: async () => { rec = await newKeyRecord(ks); return rec },
|
|
199
|
+
vault: () => (s.v2.bm || s.v2.pending ? { ...(s.v2.bm ? { master: s.v2.bm, ...(hooks.legacy ? { code: hooks.legacy.code } : {}) } : {}), ...(s.v2.pending ? { pending: { ...s.v2.pending } } : {}) } : null),
|
|
200
|
+
codeBytesOf: codeSecret,
|
|
201
|
+
beforeLegacyCommit: hooks.beforeLegacyCommit,
|
|
202
|
+
legacyAborted: hooks.legacyAborted,
|
|
203
|
+
backupIdOf: async (m) => (await backupLocation(m)).id,
|
|
204
|
+
wrapperIdOf: async (c) => (await wrapperLocation(c)).id,
|
|
205
|
+
acctKey: () => hooks.legacy?.acctKey || null,
|
|
206
|
+
deviceKeys: () => [],
|
|
207
|
+
wipe: async () => { if (hooks.wipe) await hooks.wipe() },
|
|
208
|
+
label: () => { try { return String(label() || 'This device').slice(0, 64) } catch { return 'This device' } },
|
|
209
|
+
keys: browserKeys(),
|
|
210
|
+
prepareSetup: async () => sealed(await recordOf(s), newRecoveryCode(), newMasterSecret()),
|
|
211
|
+
// § 8.2: merged with the current head (another device's rooms kept), sealed under the NEW master
|
|
212
|
+
prepareRotation: async (readHead) => {
|
|
213
|
+
const oldLoc = await backupLocation(unb64(s.v2.bm))
|
|
214
|
+
const head = await readHead(oldLoc.id)
|
|
215
|
+
return sealed(await recordOverHead(s, oldLoc.key, head), newRecoveryCode(), newMasterSecret())
|
|
216
|
+
},
|
|
217
|
+
openWrapper: (codeBytes, blob) => openWrapper(codeBytes, blob),
|
|
218
|
+
openBackup: async (m, blob) => openRecord((await backupLocation(m)).key, blob),
|
|
219
|
+
applyRestored: (r) => hooks.applyRestored(r),
|
|
220
|
+
// R2-03: the new code's master is ON DISK (read back) before its activation is sent — the code itself is never kept
|
|
221
|
+
holdPending: async (prep) => {
|
|
222
|
+
if (hooks.current && !hooks.current()) return false // review 2026-11-16: never written under another account's entry
|
|
223
|
+
s.v2.pending = { master: b64(prep.newMaster), rid: prep.rid || null, at: Date.now() }
|
|
224
|
+
let kept = false
|
|
225
|
+
try { kept = persistNow ? (await persistNow(JSON.parse(JSON.stringify(s)))) === true : false } catch { kept = false }
|
|
226
|
+
if (!kept) delete s.v2.pending // not kept → no activation is sent (acctV2App keepPending): nothing is on its way
|
|
227
|
+
return kept
|
|
228
|
+
},
|
|
229
|
+
dropPending: () => { delete s.v2.pending; if (hooks.changed) hooks.changed() },
|
|
230
|
+
adoptRotation: (prep) => {
|
|
231
|
+
// the master this replaces is KEPT a while (Codex sweep 2026-11-16 #1): the devices this new code signs out registered their
|
|
232
|
+
// push addresses under it, and prunePush must still open them to take them off every Space (as our vault's prevMasters)
|
|
233
|
+
if (s.v2.bm) s.v2.pb = keptPrevMasters([{ m: s.v2.bm, at: Date.now() }, ...(s.v2.pb || [])])
|
|
234
|
+
s.v2.bm = b64(prep.newMaster instanceof Uint8Array ? prep.newMaster : unb64(prep.newMaster))
|
|
235
|
+
delete s.v2.pending
|
|
236
|
+
if (hooks.changed) hooks.changed()
|
|
237
|
+
},
|
|
238
|
+
...pushDeps(s),
|
|
239
|
+
})
|
|
240
|
+
}
|
|
241
|
+
// § 8.8 — ONLY in a vault that sends notifications (vault-core.js `push: true`; sync sweep 11-16 #14, as our vault's
|
|
242
|
+
// acctV2VaultWiring.js): this device's push address registered with the service, sealed under the BACKUP master, so a device
|
|
243
|
+
// still signed in can take a signed-out one's address off every Space (withdrawPush) — a vault without push passes none of these.
|
|
244
|
+
const pushKey = async (s) => { if (!s.v2 || !s.v2.bm) throw fail('no_master', 'no backup master'); return appStoreKey(unb64(s.v2.bm)) }
|
|
245
|
+
const pushDeps = (s) => (typeof pushEndpoint !== 'function' || typeof withdrawPush !== 'function' ? {} : {
|
|
246
|
+
sealId: async () => (s.v2 && s.v2.bm ? [...new Uint8Array(await crypto.subtle.digest('SHA-256', utf8('push-seal|' + s.v2.bm)))].slice(0, 8).map((x) => x.toString(16).padStart(2, '0')).join('') : ''),
|
|
247
|
+
// undefined = NOT KNOWN YET (the subscription is still loading — Codex sweep 2026-11-16 #2): syncPush then sends nothing
|
|
248
|
+
pushEndpoint: async () => { try { const e = await pushEndpoint(); return e === undefined ? undefined : (e || null) } catch { return undefined } },
|
|
249
|
+
sealPush: async (endpoint) => { const d = await sealDoc(await pushKey(s), { e: endpoint }); return (d.z ? '1.' : '0.') + d.s },
|
|
250
|
+
openPush: async (sealed) => { // the current master, then the kept previous ones (#1)
|
|
251
|
+
const [z, x] = String(sealed).split('.')
|
|
252
|
+
for (const m of [s.v2 && s.v2.bm, ...keptPrevMasters(s.v2 && s.v2.pb).map((p) => p.m)].filter(Boolean)) { try { return (await openDoc(await appStoreKey(unb64(m)), { v: 1, z: z === '1', s: x })).e || null } catch { /* another master */ } }
|
|
253
|
+
return null
|
|
254
|
+
},
|
|
255
|
+
withdrawPush: async (endpoints) => !!(await withdrawPush(endpoints)),
|
|
256
|
+
})
|
|
257
|
+
|
|
258
|
+
// a flow that may hold a new code (a first one, a new one) is running: the status check waits — its reconcile would close the
|
|
259
|
+
// session whose activation is on its way (review 2026-11-16)
|
|
260
|
+
let busy = 0
|
|
261
|
+
const busyWhile = async (fn) => { busy++; try { return await fn() } finally { busy-- } }
|
|
262
|
+
|
|
263
|
+
// ── what sdkBackup.js asks ─────────────────────────────────────────────────────────────────────────────────────────
|
|
264
|
+
const moveDates = p => p ? { ready_at: p.ready_at, expires: p.expires } : null
|
|
265
|
+
const resetState = b => {
|
|
266
|
+
if (!b._s?.v2?.resetDraft) throw fail('no_reset', 'this device has no pending email move')
|
|
267
|
+
return b._s
|
|
268
|
+
}
|
|
269
|
+
async function withReset(b, state, fn) {
|
|
270
|
+
if (busy || b._isEnabling()) throw fail('busy', 'an account operation is already in progress')
|
|
271
|
+
const current = () => {
|
|
272
|
+
if (b._s !== state) throw fail('account_changed', 'the account changed during the email move')
|
|
273
|
+
}
|
|
274
|
+
const save = async () => {
|
|
275
|
+
current()
|
|
276
|
+
if (typeof persistNow !== 'function' || !(await persistNow(structuredClone(state)))) {
|
|
277
|
+
throw fail('save_failed', 'this device could not keep the pending move')
|
|
278
|
+
}
|
|
279
|
+
current()
|
|
280
|
+
}
|
|
281
|
+
const screen = ask => async (...args) => {
|
|
282
|
+
current()
|
|
283
|
+
if (typeof ask !== 'function') throw fail('no_screen', 'the email move needs a vault screen')
|
|
284
|
+
const answer = await ask(...args)
|
|
285
|
+
current()
|
|
286
|
+
return answer
|
|
287
|
+
}
|
|
288
|
+
return busyWhile(() => fn({ current, save, screen, changed: () => { current(); b._changed() } }))
|
|
289
|
+
}
|
|
290
|
+
const svc = {
|
|
291
|
+
async beginEmailMove(b, { email, getCode } = {}) {
|
|
292
|
+
const address = canonicalAddress(email || b._email())
|
|
293
|
+
if (!address) throw fail('email_required', 'enter the email address to move')
|
|
294
|
+
if (b._s && (!b._s.v2?.resetDraft || b._s.email !== address)) throw fail('already_enabled', 'this device already holds an account or another email move')
|
|
295
|
+
if (busy || b._isEnabling()) throw fail('busy', 'an account operation is already in progress')
|
|
296
|
+
const s = b._s || { v: 1, format: 'account', master: b64(newMasterSecret()), email: address, rooms: [], v2: { resetDraft: true } }
|
|
297
|
+
b._s = s
|
|
298
|
+
return withReset(b, s, async ({ save, screen, changed }) => {
|
|
299
|
+
const a = client(s, { changed })
|
|
300
|
+
await save()
|
|
301
|
+
const existing = a.pendingReset()
|
|
302
|
+
if (existing) return moveDates(existing)
|
|
303
|
+
try {
|
|
304
|
+
const pending = await a.resetBegin({ address, getCode: screen(getCode) })
|
|
305
|
+
await save()
|
|
306
|
+
return moveDates(pending)
|
|
307
|
+
} catch (error) {
|
|
308
|
+
if (!a.pendingReset() && ['feature_unavailable', 'tenant_origin', 'bad_tenant', 'cancelled', 'no_screen', 'email_code_wrong'].includes(error.code)) {
|
|
309
|
+
if (b._s === s) b._drop()
|
|
310
|
+
}
|
|
311
|
+
throw error
|
|
312
|
+
}
|
|
313
|
+
})
|
|
314
|
+
},
|
|
315
|
+
async pendingEmailMove(b) {
|
|
316
|
+
if (!b._s?.v2?.resetDraft) return null
|
|
317
|
+
const s = b._s
|
|
318
|
+
return withReset(b, s, async ({ current, changed }) => {
|
|
319
|
+
const a = client(s, { changed })
|
|
320
|
+
if (s.v2.svc) return moveDates(a.pendingReset())
|
|
321
|
+
if (!a.pendingReset()) return null
|
|
322
|
+
const p = await a.refreshReset()
|
|
323
|
+
current()
|
|
324
|
+
if (!p && !a.pendingReset()) b._drop()
|
|
325
|
+
return moveDates(p || a.pendingReset())
|
|
326
|
+
})
|
|
327
|
+
},
|
|
328
|
+
async finishEmailMove(b, { getCode, showCode } = {}) {
|
|
329
|
+
const s = resetState(b)
|
|
330
|
+
if (typeof showCode !== 'function') throw fail('no_screen', 'the new recovery code needs a vault screen')
|
|
331
|
+
return withReset(b, s, async ({ current, save, screen, changed }) => {
|
|
332
|
+
const a = client(s, { current: () => b._s === s, changed, finishingReset: true })
|
|
333
|
+
if (!s.v2.bm || s.v2.svc?.setup === 'pending') {
|
|
334
|
+
await a.resetFinish({ getCode: screen(getCode), showCode: screen(showCode) })
|
|
335
|
+
}
|
|
336
|
+
await save()
|
|
337
|
+
current()
|
|
338
|
+
const reset = s.v2.reset
|
|
339
|
+
delete s.v2.resetDraft
|
|
340
|
+
delete s.v2.reset
|
|
341
|
+
try { await save() } catch (error) {
|
|
342
|
+
s.v2.resetDraft = true
|
|
343
|
+
s.v2.reset = reset
|
|
344
|
+
throw error
|
|
345
|
+
}
|
|
346
|
+
b._changed(); b._started()
|
|
347
|
+
return { enabled: true }
|
|
348
|
+
})
|
|
349
|
+
},
|
|
350
|
+
async cancelPendingEmailMove(b, { getCode } = {}) {
|
|
351
|
+
const s = resetState(b)
|
|
352
|
+
if (s.v2.svc) throw fail('already_migrated', 'finish the first recovery code for the new account')
|
|
353
|
+
return withReset(b, s, async ({ current, changed, screen }) => {
|
|
354
|
+
const a = client(s, { changed })
|
|
355
|
+
if (a.pendingReset()) {
|
|
356
|
+
try { await a.resetCancel({ getCode: screen(getCode) }) }
|
|
357
|
+
catch (e) { if (!['reset_ended', 'no_reset'].includes(e.code)) throw e }
|
|
358
|
+
}
|
|
359
|
+
current(); b._drop()
|
|
360
|
+
return { cancelled: true }
|
|
361
|
+
})
|
|
362
|
+
},
|
|
363
|
+
get busy() { return busy > 0 },
|
|
364
|
+
tenant, base,
|
|
365
|
+
async migrate(b, { code, getCode, silent = false } = {}) {
|
|
366
|
+
const s = b._s
|
|
367
|
+
if (!s || !b.enabled) throw fail('not_enabled', 'restore this legacy account before moving it')
|
|
368
|
+
if (s.v2 && s.v2.svc && !s.v2.moving) throw fail('already_migrated', 'this account already uses the account service')
|
|
369
|
+
if (b._migrating || busy) throw fail('busy', 'another account operation is running')
|
|
370
|
+
if (b.format !== 'account') throw fail('legacy_format', 'upgrade this backup to the account format before moving it')
|
|
371
|
+
if (typeof persistNow !== 'function' || typeof b._afterMigration !== 'function') throw fail('migration_unavailable', 'migration needs durable storage and the account index')
|
|
372
|
+
if (s.v2?.moving) silent = s.v2.moveMode === 'signed' || s.v2.svc?.silent === 'moved'
|
|
373
|
+
const current = () => { if (b._s !== s) throw fail('account_changed', 'the account changed during migration') }
|
|
374
|
+
b._migrating = true
|
|
375
|
+
clearTimeout(b._timer); b._timer = null
|
|
376
|
+
return busyWhile(async () => {
|
|
377
|
+
try {
|
|
378
|
+
if (!(s.v2 && s.v2.svc)) {
|
|
379
|
+
let legacy
|
|
380
|
+
if (silent) {
|
|
381
|
+
if (!legacyRecovery || !s.email || canonicalAddress(b._email()) !== canonicalAddress(s.email)) throw fail('silent_unavailable', 'a signed-in eligible legacy account is required')
|
|
382
|
+
legacy = await legacyRecovery(s.email)
|
|
383
|
+
current()
|
|
384
|
+
if (!legacy?.code || !legacy.acctKey?.priv) throw fail('silent_unavailable', 'this vault has no registered legacy signing key or recovery code')
|
|
385
|
+
code = legacy.code
|
|
386
|
+
}
|
|
387
|
+
try { codeSecret(code) } catch { throw fail('code_required', 'enter this account’s recovery code to move it') }
|
|
388
|
+
if (!silent && typeof getCode !== 'function') throw fail('no_screen', 'migration needs an emailed code')
|
|
389
|
+
const address = canonicalAddress(s.email || b._email())
|
|
390
|
+
if (!address) throw fail('email_required', 'this legacy account needs its recovery email')
|
|
391
|
+
const a = client(s, { legacy, changed: () => { current(); b._changed() }, legacyAborted: () => {
|
|
392
|
+
current(); delete s.v2; b._changed()
|
|
393
|
+
}, beforeLegacyCommit: async ({ codeBytes, params, read }) => {
|
|
394
|
+
current()
|
|
395
|
+
const wrapper = await read(params.wrapper_id), backup = await read(params.backup_id)
|
|
396
|
+
current()
|
|
397
|
+
const master = await openWrapper(codeBytes, new TextDecoder().decode(unb64u(wrapper.blob)))
|
|
398
|
+
if (!master || b64(master) !== s.master) throw fail('wrong_account', 'that code does not open this account')
|
|
399
|
+
const payload = await openRecord((await backupLocation(master)).key, new TextDecoder().decode(unb64u(backup.blob)))
|
|
400
|
+
if (!payload) throw fail('unopenable', 'the legacy backup cannot be opened as an SDK account')
|
|
401
|
+
current()
|
|
402
|
+
} })
|
|
403
|
+
// This device key and backup master must survive a lost commit reply. The recovery code is never stored.
|
|
404
|
+
s.v2.bm = s.master; s.v2.moving = true; if (silent) s.v2.moveMode = 'signed'
|
|
405
|
+
if (!(await svc.deviceSpk(b))) throw fail('no_device_key', 'the migration device key could not be kept')
|
|
406
|
+
if (!(await persistNow(s))) throw fail('save_failed', 'the migration state could not be kept on this device')
|
|
407
|
+
current()
|
|
408
|
+
if (silent) await a.silentMove({ address })
|
|
409
|
+
else await a.migrate({ address, typedCode: code, getCode: async () => { current(); const c = await getCode(); current(); return c } })
|
|
410
|
+
current(); b._changed()
|
|
411
|
+
if (!(await persistNow(s))) throw fail('save_failed', 'the migrated account state could not be kept')
|
|
412
|
+
}
|
|
413
|
+
current()
|
|
414
|
+
await b._afterMigration({ signed: silent })
|
|
415
|
+
current()
|
|
416
|
+
await svc.write(b, s)
|
|
417
|
+
current()
|
|
418
|
+
delete s.v2.moving
|
|
419
|
+
if (!(await persistNow(s))) { s.v2.moving = true; throw fail('save_failed', 'migration completion could not be kept; retry the move') }
|
|
420
|
+
b._changed()
|
|
421
|
+
return { migrated: true, trust: s.v2.svc.trust }
|
|
422
|
+
} finally { b._migrating = false }
|
|
423
|
+
})
|
|
424
|
+
},
|
|
425
|
+
async emailMove(b) {
|
|
426
|
+
onService(b)
|
|
427
|
+
const r = await svc.status(b, { force: true })
|
|
428
|
+
if (!r || r.state !== 'active') throw fail('status_unavailable', 'the account service could not confirm this account is active')
|
|
429
|
+
return r.move || null
|
|
430
|
+
},
|
|
431
|
+
async requestMoveTime(b) {
|
|
432
|
+
if (!(await svc.emailMove(b))) throw fail('no_reset', 'no email move is pending')
|
|
433
|
+
const s = onService(b)
|
|
434
|
+
return busyWhile(() => client(s).objectMove())
|
|
435
|
+
},
|
|
436
|
+
async cancelEmailMove(b, { getCode } = {}) {
|
|
437
|
+
if (typeof getCode !== 'function') throw fail('no_screen', 'cancelling an email move needs an emailed code')
|
|
438
|
+
if (!(await svc.emailMove(b))) throw fail('no_reset', 'no email move is pending')
|
|
439
|
+
const s = onService(b)
|
|
440
|
+
return busyWhile(() => client(s).cancelMove({ address: addressOf(b, s), getCode }))
|
|
441
|
+
},
|
|
442
|
+
/** A new account here: the address proved by an email code, the first recovery code shown (`showCode`) and kept before its
|
|
443
|
+
* activation, then the first backup. A failure after the account exists KEEPS it (half-made), so the next enable() finishes
|
|
444
|
+
* it instead of making another (an address with an account and no code could not start again). → { code } | null (the
|
|
445
|
+
* service refused this vault's tenant before anything was made: the old store, as before) */
|
|
446
|
+
async enable(b, { email, getCode, showCode, rooms = [] } = {}) {
|
|
447
|
+
if (typeof getCode !== 'function' || typeof showCode !== 'function') throw fail('no_screen', 'the new account service needs the vault\'s screens (an emailed code, the recovery code)')
|
|
448
|
+
const resume = b._s && halfMade(b._s) ? b._s : null
|
|
449
|
+
const address = canonicalAddress((resume && resume.v2.svc && resume.v2.svc.address) || email || b._email())
|
|
450
|
+
if (!address) throw fail('email_required', 'the account needs an email address — sign in first, or pass `email`')
|
|
451
|
+
// A FIRST CODE ALREADY ON ITS WAY (its activation sent, the answer lost): the service decides first — adopted, the account is
|
|
452
|
+
// whole; still open, nothing new is made over it (a second code's master would replace the first's; review 2026-11-16)
|
|
453
|
+
if (resume && resume.v2.pending) {
|
|
454
|
+
await busyWhile(() => client(resume, { changed: () => { if (b._s === resume) b._changed() }, wipe: async () => { if (b._s === resume) b._drop() } }).checkStatus())
|
|
455
|
+
if (b._s !== resume) throw fail('cancelled', 'this account is no longer on this device')
|
|
456
|
+
if (!halfMade(resume)) { b._changed(); b._started(); return { code: '' } } // the first code (already shown) is active
|
|
457
|
+
if (resume.v2.pending) throw fail('try_again', 'the first recovery code is still being activated — try again in a minute')
|
|
458
|
+
}
|
|
459
|
+
const s = resume || { v: 1, format: 'account', master: b64(newMasterSecret()), rooms, email: address, v2: {} }
|
|
460
|
+
b._s = s; b._enabling = s; b._enablingDirty = false
|
|
461
|
+
let code = ''
|
|
462
|
+
try {
|
|
463
|
+
await busyWhile(() => client(s, { current: () => b._s === s }).startFresh({ address, getCode, showCode: async (c) => { code = c; await showCode(c) } }))
|
|
464
|
+
} catch (e) {
|
|
465
|
+
if (b._enabling === s) b._enabling = null
|
|
466
|
+
const made = !!(s.v2 && s.v2.svc && s.v2.svc.acct)
|
|
467
|
+
if (b._s === s) { if (!made) b._s = null; b._changed() } // made: kept, not enabled (halfMade) — the app persists it
|
|
468
|
+
if (!made && !resume && e && (e.code === 'tenant_origin' || e.code === 'bad_tenant')) return null
|
|
469
|
+
throw e
|
|
470
|
+
}
|
|
471
|
+
const queued = b._enablingDirty
|
|
472
|
+
b._enabling = null; b._enablingDirty = false
|
|
473
|
+
if (b._s !== s) throw fail('cancelled', 'the backup was replaced while it was being set up')
|
|
474
|
+
b._changed(); b._started()
|
|
475
|
+
if (queued) b._schedule()
|
|
476
|
+
return { code }
|
|
477
|
+
},
|
|
478
|
+
|
|
479
|
+
/** § 8.1 — the recovery code on the new service. → { rooms } | null (not an account there, or the service could not say before it
|
|
480
|
+
* knew the code: the old store is asked). `getCode` is the emailed code's question; `askAddress()` the email when none is known. */
|
|
481
|
+
async restore(b, { code, email, getCode, askAddress } = {}) {
|
|
482
|
+
let typed
|
|
483
|
+
try { codeSecret(code); typed = code } catch { throw fail('bad_code', 'that is not a recovery code') }
|
|
484
|
+
if (typeof getCode !== 'function') return null // no screen for the emailed code (a page outside a vault): the old store only
|
|
485
|
+
const s1 = { v: 1, format: 'account', master: '', rooms: [], v2: {} }
|
|
486
|
+
let found = false, done = null
|
|
487
|
+
const address = async () => {
|
|
488
|
+
found = true // the service knows this code
|
|
489
|
+
const x = canonicalAddress(email || b._email() || (askAddress ? await askAddress() : ''))
|
|
490
|
+
if (!x) throw fail('email_required', 'this account also needs its email address')
|
|
491
|
+
return x
|
|
492
|
+
}
|
|
493
|
+
const a = client(s1, {
|
|
494
|
+
applyRestored: async ({ master: bm, payload, legacy }) => {
|
|
495
|
+
const identity = is32(payload.sdkMaster) ? payload.sdkMaster : legacy && payload.sdkMaster === undefined ? b64(bm) : null
|
|
496
|
+
if (vaultOwner(payload) !== 'sdk' || !identity) throw fail('not_sdk_backup', 'that code opens a backup made by a different app')
|
|
497
|
+
const plan = applyPlan(payload, {}, { app: SDK_APP })
|
|
498
|
+
done = { master: identity, rooms: roomsOfRecord(plan ? { ...payload, recents: plan.add } : payload), tomb: tombOfRecord(payload),
|
|
499
|
+
...(payload.email ? { email: payload.email } : {}), ...((plan ? plan.inviteKey : payload.inviteKey) ? { invite: plan ? plan.inviteKey : payload.inviteKey } : {}),
|
|
500
|
+
format: 'account', v2: { ...s1.v2, bm: b64(bm) } }
|
|
501
|
+
return done.rooms.length
|
|
502
|
+
},
|
|
503
|
+
})
|
|
504
|
+
try {
|
|
505
|
+
await a.restoreHere({ address, getCode, typedCode: typed })
|
|
506
|
+
} catch (e) {
|
|
507
|
+
if (e && e.code === 'no_account') return null
|
|
508
|
+
if (!found && e && (e.code === 'tenant_origin' || e.code === 'bad_tenant' || !(e.status && e.status < 500))) return null // the service could not say: the old store
|
|
509
|
+
throw e
|
|
510
|
+
}
|
|
511
|
+
if (!done) throw fail('unopenable', 'the backup could not be opened')
|
|
512
|
+
return done
|
|
513
|
+
},
|
|
514
|
+
|
|
515
|
+
/** The routine write (sdkBackup.js _write): read the head, keep another device's rooms, seal, commit over the version read. */
|
|
516
|
+
async write(b, s0) {
|
|
517
|
+
if (halfMade(s0)) return // its first code is not active yet: nothing to write over
|
|
518
|
+
const a = client(s0, { changed: () => { if (b._s === s0) b._changed() } })
|
|
519
|
+
const loc = await backupLocation(unb64(s0.v2.bm))
|
|
520
|
+
for (let attempt = 0; attempt < 4; attempt++) {
|
|
521
|
+
let head
|
|
522
|
+
try { head = await a.readBackup(loc.id) } catch (e) { throw fail('save_failed', 'the backup could not be read', { status: e && e.status, reason: e && e.code }) }
|
|
523
|
+
if (b._s !== s0) return
|
|
524
|
+
const blob = await seal(loc.key, await recordOverHead(s0, loc.key, head))
|
|
525
|
+
if (b._s !== s0) return
|
|
526
|
+
let r
|
|
527
|
+
try { r = await a.writeBackup(loc.id, blob, head) } catch (e) { throw fail('save_failed', 'the backup could not be saved', { status: e && e.status, reason: e && e.code }) }
|
|
528
|
+
if (r === 'conflict') { await new Promise((res) => setTimeout(res, 100 + Math.floor(Math.random() * 300))); continue }
|
|
529
|
+
b.lastError = null
|
|
530
|
+
return
|
|
531
|
+
}
|
|
532
|
+
throw fail('save_failed', 'the backup kept changing under this save (another device writing) — the next change tries again', { status: 409 })
|
|
533
|
+
},
|
|
534
|
+
|
|
535
|
+
// ── the account's own calls (the vault's screens ask the person) ──────────────────────────────────────────────────
|
|
536
|
+
/** § 8.3 — every other device of the account is signed out; each one notices at its next status check and forgets it. */
|
|
537
|
+
/** ONE other device of the account, signed out AT THE SERVICE (the regular app's revokeAtService; sync sweep 11-19 P8): `spk` = that
|
|
538
|
+
* device's key as its index entry names it. The email code proves it is the account's owner. */
|
|
539
|
+
async listDevices(b) { return client(onService(b)).devices() },
|
|
540
|
+
async signOutDevice(b, { spk, getCode }) {
|
|
541
|
+
const s = onService(b)
|
|
542
|
+
return client(s).signOutDevice({ spk, address: addressOf(b, s), getCode })
|
|
543
|
+
},
|
|
544
|
+
/** This device's key on the service (its spk) — what its index entry carries so another device can sign it out there. null: none. */
|
|
545
|
+
async deviceSpk(b) {
|
|
546
|
+
const s = b && b._s; if (!s || !s.v2 || !s.v2.dk) return null
|
|
547
|
+
try { const rec = await ensureKeyRecord(keysOf(s.v2.dk)); return (rec && rec.spk) || null } catch { return null }
|
|
548
|
+
},
|
|
549
|
+
async forgetDevice(b) {
|
|
550
|
+
keyEpoch++
|
|
551
|
+
// A vault wipe forgets every locally held account, even when erase/status already dropped the active backup state.
|
|
552
|
+
if (typeof keyStore.clear === 'function') { await keyStore.clear(); return }
|
|
553
|
+
const dk = b && b._s && b._s.v2 && b._s.v2.dk
|
|
554
|
+
if (dk && typeof keyStore.del === 'function') await keyStore.del('devkey:v1|' + dk)
|
|
555
|
+
},
|
|
556
|
+
securityKeyActions(b) {
|
|
557
|
+
const state = onService(b), service = client(state)
|
|
558
|
+
const action = (method) => (...args) => {
|
|
559
|
+
if (b._s !== state) throw fail('account_changed', 'the account changed during security-key management')
|
|
560
|
+
return service[method](...args)
|
|
561
|
+
}
|
|
562
|
+
return Object.fromEntries(['security', 'turnOnAdvanced', 'turnOffAdvanced', 'addKey', 'removeKey'].map((method) => [method, action(method)]))
|
|
563
|
+
},
|
|
564
|
+
async signOutOthers(b, { getCode }) {
|
|
565
|
+
const s = onService(b)
|
|
566
|
+
const r = await client(s).signOutOthers({ address: addressOf(b, s), getCode })
|
|
567
|
+
try { if (typeof afterSignOut === 'function') afterSignOut(addressOf(b, s)) } catch { /* best effort: the next request renews */ }
|
|
568
|
+
return r
|
|
569
|
+
},
|
|
570
|
+
/** docs/device-gate-design.md: this ACTIVE device's ten-minute room pass for its session key (roomPass.js) → { pass, sig, exp } —
|
|
571
|
+
* in this vault's tenant's scope (x-acct-tenant). A signed-out device is refused (`revoked`), and onRevoked runs the status check. */
|
|
572
|
+
async roomPass(b, email, sessionPub) {
|
|
573
|
+
const s = onService(b)
|
|
574
|
+
return client(s).roomPass(email, sessionPub)
|
|
575
|
+
},
|
|
576
|
+
async enrolCloudDevice(b, { spk, getCode } = {}) {
|
|
577
|
+
const s = onService(b)
|
|
578
|
+
if (typeof getCode !== 'function') throw fail('no_screen', 'registering the cloud device needs an emailed code')
|
|
579
|
+
const current = () => { if (b._s !== s) throw fail('account_changed', 'the account changed during device registration') }
|
|
580
|
+
await busyWhile(() => client(s).enrolDevice({ newSpk: spk, label: 'Cloud device', address: addressOf(b, s), getCode: async () => { current(); const code = await getCode(); current(); return code } }))
|
|
581
|
+
current()
|
|
582
|
+
return { base }
|
|
583
|
+
},
|
|
584
|
+
/** § 8.2 — a new recovery code (shown by `showCode` before it is activated); the old code stops working and every other
|
|
585
|
+
* device is signed out. The account's identity (its rooms, index, usage) is unchanged. */
|
|
586
|
+
async newRecoveryCode(b, { getCode, showCode }) {
|
|
587
|
+
const s = onService(b)
|
|
588
|
+
await busyWhile(() => client(s, { changed: () => { if (b._s === s) b._changed() }, current: () => b._s === s }).newRecoveryCode({ address: addressOf(b, s), getCode, showCode }))
|
|
589
|
+
if (b._s === s) b._changed()
|
|
590
|
+
return { ok: true }
|
|
591
|
+
},
|
|
592
|
+
/** Release checklist 1.11 — the account is deleted on the service (every device signed out, the address freed, the backup
|
|
593
|
+
* gone); this client then holds no account. */
|
|
594
|
+
async deleteAccount(b, { getCode, keep = false }) {
|
|
595
|
+
const s = onService(b)
|
|
596
|
+
await busyWhile(() => client(s, { changed: () => { if (b._s === s) b._changed() } }).eraseAccount({ address: addressOf(b, s), getCode }))
|
|
597
|
+
// keep: the full erase (sdkErase.js) still needs the backup's master for the rooms after this step — it marks the state
|
|
598
|
+
// erased (no write re-creates it) and drops it at its end; anyone else drops it now
|
|
599
|
+
if (b._s === s) { clearTimeout(b._timer); b._timer = null; if (keep) { s.erased = true; b._changed() } else b._drop() }
|
|
600
|
+
return { deleted: true }
|
|
601
|
+
},
|
|
602
|
+
/** § 8.8 — this device's push address changed (on, off, a subscription loaded or renewed): registered with the service again
|
|
603
|
+
* now, not at the next daily check (Codex sweep 2026-11-16 #2). → 'registered' | 'removed' | 'same' | 'unknown' | 'off' */
|
|
604
|
+
async syncPush(b) {
|
|
605
|
+
const s = b._s
|
|
606
|
+
if (!s || !s.v2 || !s.v2.svc || halfMade(s) || busy || b._isEnabling()) return 'off'
|
|
607
|
+
return client(s).syncPush()
|
|
608
|
+
},
|
|
609
|
+
/** § 8.5 — at launch, on return to the foreground (at most daily), at once for an unfinished new code or a refusal as signed
|
|
610
|
+
* out. A device signed out elsewhere: `onSignedOut()` (the vault forgets the account here). → the service's state, or null */
|
|
611
|
+
async status(b, { force = false, onSignedOut } = {}) {
|
|
612
|
+
const s = b._s
|
|
613
|
+
if (!s || !s.v2 || !s.v2.svc || s.v2.resetDraft || busy || b._isEnabling()) return null
|
|
614
|
+
if (!statusDue({ now: Date.now(), last: s.v2.checked, pending: !!s.v2.pending || halfMade(s), moving: !!s.v2.emailMove, force })) return null
|
|
615
|
+
let wiped = false
|
|
616
|
+
const a = client(s, { canApplyStatus: () => b._s === s && !busy && !s.erased, changed: () => { if (b._s === s) b._changed() }, wipe: async () => { wiped = true } })
|
|
617
|
+
const r = await a.checkStatus()
|
|
618
|
+
if (b._s !== s) return r
|
|
619
|
+
if (wiped || (r && r.state === 'revoked')) { clearTimeout(b._timer); b._timer = null; b._drop(); if (onSignedOut) await onSignedOut(s); return r }
|
|
620
|
+
if (r && r.state !== 'unknown') { s.v2.checked = Date.now(); b._changed() }
|
|
621
|
+
// § 8.8, as our vault's status check: this device's push address registered, the signed-out devices' taken off every Space
|
|
622
|
+
// (each a no-op without push — pushDeps; sync sweep 11-16 #14)
|
|
623
|
+
if (r && r.state === 'active') { a.syncPush().catch(() => {}); a.prunePush().catch(() => {}) }
|
|
624
|
+
return r
|
|
625
|
+
},
|
|
626
|
+
}
|
|
627
|
+
const onService = (b) => { const s = b._s; if (!s || !s.v2 || !s.v2.svc || halfMade(s)) throw fail('not_on_service', 'this account is not on the account service (an account on the old backup store has no such call)'); return s }
|
|
628
|
+
const addressOf = (b, s) => (s.v2.svc && s.v2.svc.address) || s.email || b._email()
|
|
629
|
+
return svc
|
|
630
|
+
}
|