@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/acctV2App.js
ADDED
|
@@ -0,0 +1,619 @@
|
|
|
1
|
+
// acctV2App.js — the app's side of account recovery v2 (docs/account-recovery-protocol.md): it joins the client library
|
|
2
|
+
// (acctV2Client.js) to what this device already holds — its non-extractable device key (devices.js), the backup's master and
|
|
3
|
+
// the escrowed recovery code (backup.js), the account key (store.js) — and gives the screens four actions: move this
|
|
4
|
+
// account from today's service (§ 12.2), the launch / foreground status check that removes a signed-out device's account
|
|
5
|
+
// (§ 8.5), sign out every other device (§ 8.3), and the state the screens read.
|
|
6
|
+
//
|
|
7
|
+
// OFF unless a v2 service address is set (`base`): v2 runs on staging only until its release gates. Dependencies are
|
|
8
|
+
// injected (makeAcctV2), so the whole flow is tested against the service code in-process (spaces/test/acctV2App.test.mjs).
|
|
9
|
+
import { accountClient } from './acctV2Client.js'
|
|
10
|
+
import { possessionKey, backupWriteKey, gateValues, webCryptoSigner, webCryptoSignerFromSpk } from './acctV2Keys.js'
|
|
11
|
+
import { rawToDer, b64u, hexOf } from './acctV2Wire.js'
|
|
12
|
+
import { transcriptForLegacy, transcriptForJoin, transcriptForSilent, transcriptForJoinAsk } from './acctV2Legacy.js'
|
|
13
|
+
|
|
14
|
+
export const STATE_KEY = 'space:acctv2' // { acct, base, at, address? } — an account id, the service's address and the account's email; no key
|
|
15
|
+
export const RESET_KEY = 'space:acctv2:reset' // § 11.5: the email move THIS device started — { reset, address, ready_at, expires, base }
|
|
16
|
+
export const ERASE_KEY = 'space:acctv2:erase' // 10·Q#3: "Delete my account"'s request while its answer is unknown — { acct, body, at }; sent again, never remade
|
|
17
|
+
export const MOVE_KEY = 'space:acctv2:move' // § 11.5, 3a: a move of THIS account's address under way, as the status answer said — { reset, ready_at, expires, objected, base }
|
|
18
|
+
|
|
19
|
+
/** deps: { base, fetch?, storage (getItem/setItem/removeItem), deviceKey() → { priv, pub } (WebCrypto pair), vault() →
|
|
20
|
+
* { master (base64), code? }, codeBytesOf(code) → Uint8Array, backupIdOf(master) → hex, wrapperIdOf(codeBytes) → hex,
|
|
21
|
+
* acctKey() → { priv (JWK), pub } | null, deviceKeys() → [spk of the account's other devices], wipe(),
|
|
22
|
+
* prepareRotation(headOf) → { newCode, newMaster, backupId, wrapperId, backupBlob, wrapperBlob } (sealed under the NEW
|
|
23
|
+
* secrets, merged with the current head), prepareSetup() → the same for an account's FIRST code (nothing to merge),
|
|
24
|
+
* adoptRotation(prep), openWrapper(codeBytes, sealed) → master | null, openBackup(master, sealed) → payload | null,
|
|
25
|
+
* applyRestored({ master, payload, code }) → rooms added (the restore's last step: apply, keep the master and code) — keep the new master and code, keys — the security-key
|
|
26
|
+
* adapter (acctV2WebAuthn.js browserKeys; a simulated key in tests) } */
|
|
27
|
+
const sha256Hex = async (s) => [...new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(String(s))))].map((b) => b.toString(16).padStart(2, '0')).join('')
|
|
28
|
+
|
|
29
|
+
export function makeAcctV2(deps) {
|
|
30
|
+
const client = deps.base ? accountClient({ base: deps.base, fetch: deps.fetch, headers: deps.headers }) : null // deps.headers: the vault's tenant (acctV2VaultWiring.js)
|
|
31
|
+
// ⛔ 10·Q#6 (pass 10): adoptLinked writes the state BEFORE the backup is read and applied; a page killed in between (iOS) left an
|
|
32
|
+
// account state with no master — Add a device then answered already_migrated, Restore did nothing, backups did nothing. That
|
|
33
|
+
// state carries `adopting` until the backup is applied; one found with no adoption running in THIS page is a half-made adopt:
|
|
34
|
+
// it is dropped, as the adopt's own failure path would have.
|
|
35
|
+
let adoptingNow = false
|
|
36
|
+
let erasingNow = false
|
|
37
|
+
const state = () => {
|
|
38
|
+
let s = null
|
|
39
|
+
try { s = JSON.parse(deps.storage.getItem(STATE_KEY) || 'null') } catch { return null }
|
|
40
|
+
if (s && s.adopting && !adoptingNow) { try { deps.storage.removeItem(STATE_KEY) } catch { /* */ } return null }
|
|
41
|
+
return s
|
|
42
|
+
}
|
|
43
|
+
const setState = (s) => { try { deps.storage.setItem(STATE_KEY, JSON.stringify(s)) } catch { /* private mode */ } }
|
|
44
|
+
// the stored public bytes (`spk`) when the device has them — what the app registers everywhere; else the public CryptoKey
|
|
45
|
+
const signer = async () => {
|
|
46
|
+
const k = await deps.deviceKey()
|
|
47
|
+
if (!k || !k.priv || !(k.spk || k.pub)) throw Object.assign(new Error('no_device_key'), { code: 'no_device_key' })
|
|
48
|
+
return k.spk ? webCryptoSignerFromSpk(k.priv, k.spk) : webCryptoSigner(k.priv, k.pub)
|
|
49
|
+
}
|
|
50
|
+
/** 1.10 (the owner's iPhone, 2026-11-15): before this device STARTS or RESTORES an account, its key must not be another
|
|
51
|
+
* account's — an account deleted in the app leaves the key registered on the service (the browser keeps it), and the
|
|
52
|
+
* service then refuses (`key_registered`). The service knows the key (any state but `unknown`) while this device keeps
|
|
53
|
+
* no account on the new service → a new device key (deps.newDeviceKey), then on. Offline / no answer: as before. */
|
|
54
|
+
const freshKeyIfTaken = async () => {
|
|
55
|
+
if (state() || !deps.newDeviceKey) return
|
|
56
|
+
let r = null
|
|
57
|
+
try { r = await client.deviceStatus(await signer()) } catch { return }
|
|
58
|
+
if (r && r.state && r.state !== 'unknown') await deps.newDeviceKey()
|
|
59
|
+
}
|
|
60
|
+
// this device's name on the service ("Chrome on Windows") — the app's own label (devices.js), else a neutral one
|
|
61
|
+
const myLabel = () => { try { return String((deps.label && deps.label()) || 'This device').slice(0, 64) } catch { return 'This device' } }
|
|
62
|
+
/** R2-03: show the new code, then keep it as pending with its session id, and refuse to go on (no activation is sent)
|
|
63
|
+
* unless it reads back from disk — `holdPending` answers whether it is durable. */
|
|
64
|
+
async function keepPending(prep, { rid } = {}, showCode) {
|
|
65
|
+
await showCode(prep.newCode)
|
|
66
|
+
const kept = deps.holdPending ? await deps.holdPending({ ...prep, rid }) : false
|
|
67
|
+
if (kept !== true) throw Object.assign(new Error('pending_not_kept'), { code: 'pending_not_kept' })
|
|
68
|
+
}
|
|
69
|
+
const need = () => { if (!client) throw Object.assign(new Error('v2_off'), { code: 'v2_off' }) }
|
|
70
|
+
/** Keep (or, for none, forget) the move a status answer named. → what is kept, or null */
|
|
71
|
+
const keepMove = (m) => {
|
|
72
|
+
const ok = m && typeof m.reset === 'string' && Number.isFinite(m.ready_at) && Number.isFinite(m.expires)
|
|
73
|
+
try {
|
|
74
|
+
if (!ok) { deps.storage.removeItem(MOVE_KEY); return null }
|
|
75
|
+
const rec = { reset: m.reset, ready_at: m.ready_at, expires: m.expires, objected: !!m.objected, base: deps.base }
|
|
76
|
+
deps.storage.setItem(MOVE_KEY, JSON.stringify(rec))
|
|
77
|
+
return rec
|
|
78
|
+
} catch { return ok ? { reset: m.reset, ready_at: m.ready_at, expires: m.expires, objected: !!m.objected } : null }
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
async function validateLegacy({ master, codeBytes, params, it, device }) {
|
|
82
|
+
if (deps.beforeLegacyCommit) {
|
|
83
|
+
try { await deps.beforeLegacyCommit({ master, codeBytes, params, read: (id) => client.req('GET', `/v2/account/legacy/${it.attempt}/blob`, { query: { id }, signer: device }) }) }
|
|
84
|
+
catch (e) {
|
|
85
|
+
try { const r = await client.req('POST', `/v2/account/legacy/${it.attempt}/abort`, { signer: device }); if (r.aborted && deps.legacyAborted) deps.legacyAborted() } catch { /* unknown: keep resumable state */ }
|
|
86
|
+
throw e
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
async function accountSigner() {
|
|
92
|
+
const a = deps.acctKey()
|
|
93
|
+
if (!a || !a.priv) return null
|
|
94
|
+
const key = await crypto.subtle.importKey('jwk', a.priv, { name: 'ECDSA', namedCurve: 'P-256' }, false, ['sign'])
|
|
95
|
+
return { sign: async (bytes) => rawToDer(new Uint8Array(await crypto.subtle.sign({ name: 'ECDSA', hash: 'SHA-256' }, key, bytes))) }
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** The silent join (legacySilent.mjs): the account key, the possession key from THIS device's code and the device key. */
|
|
99
|
+
async function joinMoved({ gid, codeBytes, device, acctSig, label }) {
|
|
100
|
+
const ts = Math.floor(Date.now() / 1000)
|
|
101
|
+
const ask = b64u(await acctSig.sign(transcriptForJoinAsk({ gid, deviceSpk: device.spk, ts })))
|
|
102
|
+
const it = await client.req('POST', '/v2/account/legacy/join', { body: { gid, ts, account_sig: ask }, signer: device })
|
|
103
|
+
const poss = await possessionKey(codeBytes)
|
|
104
|
+
const params = { device_spk: device.spk, label }
|
|
105
|
+
const T = transcriptForJoin(it, it.attempt, params)
|
|
106
|
+
const sigs = { account: b64u(await acctSig.sign(T)), possession: b64u(poss.sign(T)), device: b64u(await device.sign(T)) }
|
|
107
|
+
const r = await client.req('POST', `/v2/account/legacy/join/${it.attempt}/commit`, { body: { params, sigs }, signer: device })
|
|
108
|
+
setState({ acct: r.acct, base: deps.base, at: Date.now(), trust: r.legacy_trust, silent: 'joined' })
|
|
109
|
+
return { acct: r.acct, legacy_trust: r.legacy_trust, joined: true }
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
return {
|
|
113
|
+
enabled: () => !!client,
|
|
114
|
+
state,
|
|
115
|
+
|
|
116
|
+
/** § 12.2 — move this account. `typedCode` only when this device has no escrowed copy of the recovery code. */
|
|
117
|
+
async migrate({ address, getCode, typedCode = null, label = myLabel() }) {
|
|
118
|
+
need()
|
|
119
|
+
const v = deps.vault()
|
|
120
|
+
if (!v || !v.master) throw Object.assign(new Error('no_backup'), { code: 'no_backup' })
|
|
121
|
+
const code = typedCode || v.code
|
|
122
|
+
if (!code) throw Object.assign(new Error('need_code'), { code: 'need_code' })
|
|
123
|
+
const codeBytes = deps.codeBytesOf(code)
|
|
124
|
+
const master = Uint8Array.from(atob(v.master), (c) => c.charCodeAt(0))
|
|
125
|
+
const { gid, gk } = await gateValues(codeBytes)
|
|
126
|
+
const device = await signer()
|
|
127
|
+
const it = await client.req('POST', '/v2/account/legacy/intent', { body: { gid, resume: true }, signer: device })
|
|
128
|
+
// 10·Q#5: this device moved it already (the answer was lost): it is an active device of that account — take it, no second move
|
|
129
|
+
if (it && it.moved) { setState({ acct: it.acct, base: deps.base, at: Date.now(), trust: it.legacy_trust }); return { acct: it.acct, legacy_trust: it.legacy_trust, resumed: true } }
|
|
130
|
+
const { ticket } = await client.req('POST', '/v2/account/email/start', { body: { purpose: 'legacy', attempt: it.attempt, address, gk: hexOf(gk) } })
|
|
131
|
+
const v2 = await client.req('POST', '/v2/account/email/verify', { body: { ticket, code: await getCode() } })
|
|
132
|
+
if (!v2.verified) throw Object.assign(new Error('email_code_wrong'), { code: 'email_code_wrong' })
|
|
133
|
+
await client.req('POST', `/v2/account/legacy/${it.attempt}/authorize`, { body: { ticket }, signer: device })
|
|
134
|
+
const poss = await possessionKey(codeBytes), wk = await backupWriteKey(master)
|
|
135
|
+
const params = { backup_id: await deps.backupIdOf(master), wrapper_id: await deps.wrapperIdOf(codeBytes), possession_pub: poss.spk, write_pub: wk.spk,
|
|
136
|
+
device_spk: device.spk, label, devices: (deps.deviceKeys() || []).filter((k) => k && k !== device.spk) }
|
|
137
|
+
await validateLegacy({ master, codeBytes, params, it, device })
|
|
138
|
+
const T = transcriptForLegacy({ acct: it.acct, nonce: it.nonce, exp: it.exp }, it.attempt, params)
|
|
139
|
+
const acctSig = it.account_key ? await accountSigner() : null
|
|
140
|
+
if (it.account_key && !acctSig) throw Object.assign(new Error('no_account_key'), { code: 'no_account_key' })
|
|
141
|
+
const sigs = { possession: b64u(poss.sign(T)), device: b64u(await device.sign(T)), ...(acctSig ? { account: b64u(await acctSig.sign(T)) } : {}) }
|
|
142
|
+
const r = await client.req('POST', `/v2/account/legacy/${it.attempt}/commit`, { body: { params, sigs }, signer: device })
|
|
143
|
+
setState({ acct: r.acct, base: deps.base, at: Date.now(), trust: r.legacy_trust })
|
|
144
|
+
return r
|
|
145
|
+
},
|
|
146
|
+
|
|
147
|
+
/** THE SILENT MOVE (control-plane legacySilent.mjs; docs/account-recovery-silent-migration.md draft 2 — the owner, 2026-11-18:
|
|
148
|
+
* "Fully silent. No hold."): no question asked. This device's escrowed recovery code (gid, gk, the possession key) and its
|
|
149
|
+
* account key are the evidence, the address it signed in with must be the one the old backup was set up with. An account
|
|
150
|
+
* another device already moved this way: this device JOINS it. Throws with `.code` for everything that needs the person
|
|
151
|
+
* (need_code, no_account_key, email_needed, address_mismatch) or must stop (possession_mismatch, join_closed, …).
|
|
152
|
+
* → { acct, legacy_trust, moved: true } | { acct, legacy_trust, joined: true } */
|
|
153
|
+
async silentMove({ address, label = myLabel() }) {
|
|
154
|
+
need()
|
|
155
|
+
const fail = (code) => { throw Object.assign(new Error(code), { code }) }
|
|
156
|
+
const v = deps.vault()
|
|
157
|
+
if (!v || !v.master) fail('no_backup')
|
|
158
|
+
if (!v.code) fail('need_code') // a device that keeps no copy of the code: the Settings button (the person types it)
|
|
159
|
+
if (!address) fail('no_address')
|
|
160
|
+
const codeBytes = deps.codeBytesOf(v.code)
|
|
161
|
+
const master = Uint8Array.from(atob(v.master), (c) => c.charCodeAt(0))
|
|
162
|
+
const { gid, gk } = await gateValues(codeBytes)
|
|
163
|
+
const device = await signer()
|
|
164
|
+
// the service first: an old backup without an account key needs the email code whatever this device holds (such a device —
|
|
165
|
+
// from before account keys — usually holds none: asking for the key first stopped it as no_account_key, never offered the email)
|
|
166
|
+
let it
|
|
167
|
+
try { it = await client.req('POST', '/v2/account/legacy/intent', { body: { gid, resume: true }, signer: device }) } catch (e) {
|
|
168
|
+
if (e && e.code === 'already_migrated') { const acctSig = await accountSigner(); if (!acctSig) fail('no_account_key'); return joinMoved({ gid, codeBytes, device, acctSig, label }) }
|
|
169
|
+
throw e
|
|
170
|
+
}
|
|
171
|
+
if (it && it.moved) { setState({ acct: it.acct, base: deps.base, at: Date.now(), trust: it.legacy_trust, silent: 'moved' }); return { acct: it.acct, legacy_trust: it.legacy_trust, moved: true } } // 10·Q#5
|
|
172
|
+
if (!it.account_key) fail('email_needed') // an old backup without an account key moves only with the email code
|
|
173
|
+
const acctSig = await accountSigner()
|
|
174
|
+
if (!acctSig) fail('no_account_key')
|
|
175
|
+
const authz = b64u(await acctSig.sign(transcriptForSilent({ acct: it.acct, nonce: it.nonce, exp: it.exp }, it.attempt, device.spk)))
|
|
176
|
+
await client.req('POST', `/v2/account/legacy/${it.attempt}/silent`, { body: { address, gk: hexOf(gk), account_sig: authz }, signer: device })
|
|
177
|
+
const poss = await possessionKey(codeBytes), wk = await backupWriteKey(master)
|
|
178
|
+
const params = { backup_id: await deps.backupIdOf(master), wrapper_id: await deps.wrapperIdOf(codeBytes), possession_pub: poss.spk, write_pub: wk.spk,
|
|
179
|
+
device_spk: device.spk, label, devices: (deps.deviceKeys() || []).filter((k) => k && k !== device.spk) }
|
|
180
|
+
await validateLegacy({ master, codeBytes, params, it, device })
|
|
181
|
+
const T = transcriptForLegacy({ acct: it.acct, nonce: it.nonce, exp: it.exp }, it.attempt, params)
|
|
182
|
+
const sigs = { possession: b64u(poss.sign(T)), device: b64u(await device.sign(T)), account: b64u(await acctSig.sign(T)) }
|
|
183
|
+
const r = await client.req('POST', `/v2/account/legacy/${it.attempt}/commit`, { body: { params, sigs }, signer: device })
|
|
184
|
+
setState({ acct: r.acct, base: deps.base, at: Date.now(), trust: r.legacy_trust, silent: 'moved' })
|
|
185
|
+
return { acct: r.acct, legacy_trust: r.legacy_trust, moved: true }
|
|
186
|
+
},
|
|
187
|
+
|
|
188
|
+
/** § 12.4 + § 8.2a — start an account on the new service from this device: the address proved by an email code, then
|
|
189
|
+
* the first recovery code (shown until saved) and the first backup. The account is kept as soon as it exists, so a
|
|
190
|
+
* failure after that resumes at the code step (state.setup = 'pending') instead of making another account. */
|
|
191
|
+
async startFresh({ address, getCode, showCode, label = myLabel() }) {
|
|
192
|
+
need()
|
|
193
|
+
await freshKeyIfTaken()
|
|
194
|
+
const device = await signer()
|
|
195
|
+
let s = state()
|
|
196
|
+
if (s && s.setup !== 'pending') throw Object.assign(new Error('already_migrated'), { code: 'already_migrated' })
|
|
197
|
+
// ⛔ 10·Q#1: a first code may already be ACTIVE (its commit landed, its answer was lost) — adopt it before making another,
|
|
198
|
+
// which would overwrite the only copy of its master and be refused by the service
|
|
199
|
+
if (s && s.setup === 'pending') {
|
|
200
|
+
const was = await this.reconcilePending().catch(() => 'unknown')
|
|
201
|
+
if (was === 'adopted') return { acct: s.acct, resumed: true }
|
|
202
|
+
if (was === 'unknown' || was === 'waiting') throw Object.assign(new Error('service_busy'), { code: 'service_busy' })
|
|
203
|
+
}
|
|
204
|
+
if (!s) {
|
|
205
|
+
const r = await client.freshAccount({ device, address, getCode, label })
|
|
206
|
+
s = { acct: r.acct, base: deps.base, at: Date.now(), trust: null, setup: 'pending', address }
|
|
207
|
+
setState(s)
|
|
208
|
+
}
|
|
209
|
+
const prep = await deps.prepareSetup()
|
|
210
|
+
const r = await client.setupCode({ acct: s.acct, device, address, newCode: deps.codeBytesOf(prep.newCode), newMaster: prep.newMaster,
|
|
211
|
+
backupId: prep.backupId, wrapperId: prep.wrapperId, backupBlob: prep.backupBlob, wrapperBlob: prep.wrapperBlob,
|
|
212
|
+
confirmSaved: (at) => keepPending(prep, at, showCode) })
|
|
213
|
+
deps.adoptRotation(prep)
|
|
214
|
+
setState({ acct: s.acct, base: deps.base, at: Date.now(), trust: null, address })
|
|
215
|
+
return { acct: s.acct, ...r }
|
|
216
|
+
},
|
|
217
|
+
|
|
218
|
+
// ── § 11.5 THE EMAIL RESET, from this device (the claimant) ──────────────────────────────────────────────────────────
|
|
219
|
+
/** The move this device started, if any: { reset, address, ready_at, expires } (seconds), kept on this device only. */
|
|
220
|
+
pendingReset() { try { const r = JSON.parse(deps.storage.getItem(RESET_KEY) || 'null'); return r && r.reset && (!r.base || r.base === deps.base) ? r : null } catch { return null } }, // only a move started on THIS service
|
|
221
|
+
/** Start moving `address` to a new account: a claim code; the week begins. A device already in an account cannot. */
|
|
222
|
+
async resetBegin({ address, getCode }) {
|
|
223
|
+
need()
|
|
224
|
+
if (state()) throw Object.assign(new Error('already_migrated'), { code: 'already_migrated' })
|
|
225
|
+
await freshKeyIfTaken()
|
|
226
|
+
const r = await client.resetBegin({ device: await signer(), address, getCode })
|
|
227
|
+
const rec = { reset: r.reset, address, ready_at: r.ready_at, expires: r.expires, base: deps.base }
|
|
228
|
+
deps.storage.setItem(RESET_KEY, JSON.stringify(rec))
|
|
229
|
+
return rec
|
|
230
|
+
},
|
|
231
|
+
/** After the week: a new claim code → a FRESH account with this device in it, then its first recovery code (as startFresh). */
|
|
232
|
+
async resetFinish({ getCode, showCode, label = myLabel() }) {
|
|
233
|
+
need()
|
|
234
|
+
const p = this.pendingReset()
|
|
235
|
+
if (!p) throw Object.assign(new Error('no_reset'), { code: 'no_reset' })
|
|
236
|
+
const s0 = state()
|
|
237
|
+
// a device that meanwhile holds ANOTHER account cannot finish here (security review, 2026-11-15): the move stays, so it
|
|
238
|
+
// can still be cancelled; only the retry of THIS move's own setup (its account made, its first code not yet) goes on
|
|
239
|
+
if (s0 && !(s0.setup === 'pending' && s0.address === p.address)) throw Object.assign(new Error('already_migrated'), { code: 'already_migrated' })
|
|
240
|
+
if (!s0) {
|
|
241
|
+
const r = await client.resetFinish({ device: await signer(), reset: p.reset, address: p.address, getCode, label })
|
|
242
|
+
setState({ acct: r.acct, base: deps.base, at: Date.now(), trust: null, setup: 'pending', address: p.address })
|
|
243
|
+
}
|
|
244
|
+
deps.storage.removeItem(RESET_KEY)
|
|
245
|
+
return this.startFresh({ address: p.address, getCode, showCode, label }) // the account exists (setup pending): only its first code
|
|
246
|
+
},
|
|
247
|
+
/** Cancel the move (a claim code): the address stays with its account. */
|
|
248
|
+
async resetCancel({ getCode }) {
|
|
249
|
+
need()
|
|
250
|
+
const p = this.pendingReset()
|
|
251
|
+
if (!p) throw Object.assign(new Error('no_reset'), { code: 'no_reset' })
|
|
252
|
+
await client.resetCancel({ reset: p.reset, address: p.address, getCode })
|
|
253
|
+
deps.storage.removeItem(RESET_KEY)
|
|
254
|
+
return { cancelled: true }
|
|
255
|
+
},
|
|
256
|
+
/** A move that can no longer finish (cancelled, superseded, expired): forget it here. */
|
|
257
|
+
forgetReset() { deps.storage.removeItem(RESET_KEY) },
|
|
258
|
+
|
|
259
|
+
/** § 8.1 — bring an account on the new service to THIS device: the recovery code, an email code, and a security key when
|
|
260
|
+
* the account is Advanced. Both objects are opened here BEFORE the device is registered (a wrong code or a damaged copy
|
|
261
|
+
* registers nothing); then the restore finishes, and only then is the backup applied and the account kept. */
|
|
262
|
+
async restoreHere({ address, getCode, typedCode, label = myLabel() }) {
|
|
263
|
+
need()
|
|
264
|
+
if (state()) throw Object.assign(new Error('already_migrated'), { code: 'already_migrated' })
|
|
265
|
+
let codeBytes
|
|
266
|
+
try { codeBytes = deps.codeBytesOf(typedCode) } catch { throw Object.assign(new Error('bad_code'), { code: 'bad_code' }) }
|
|
267
|
+
await freshKeyIfTaken()
|
|
268
|
+
const device = await signer()
|
|
269
|
+
const r = await client.restore({ codeBytes, address, getCode, device, label, keys: deps.keys || null })
|
|
270
|
+
const dec = new TextDecoder()
|
|
271
|
+
const wrapper = r.blobs[await deps.wrapperIdOf(codeBytes)]
|
|
272
|
+
const master = wrapper ? await deps.openWrapper(codeBytes, dec.decode(wrapper)) : null
|
|
273
|
+
if (!master) throw Object.assign(new Error('wrapper_unopened'), { code: 'wrapper_unopened' })
|
|
274
|
+
const backupId = await deps.backupIdOf(master), backup = r.blobs[backupId]
|
|
275
|
+
const payload = backup ? await deps.openBackup(master, dec.decode(backup)) : null
|
|
276
|
+
if (!payload) throw Object.assign(new Error('backup_unopened'), { code: 'backup_unopened' })
|
|
277
|
+
if (deps.checkIncomingBackup) await deps.checkIncomingBackup(payload, backupId)
|
|
278
|
+
await r.finish()
|
|
279
|
+
setState({ acct: r.acct, base: deps.base, at: Date.now(), trust: null, address: r.address }) // the address asked (it may be a function)
|
|
280
|
+
const legacy = Array.isArray(r.versions) && r.versions.some((v) => v.id === backupId && v.ver === 'legacy')
|
|
281
|
+
const rooms = await deps.applyRestored({ master, payload, code: typedCode, legacy, ...(deps.checkIncomingBackup ? { appChecked: true } : {}) })
|
|
282
|
+
return { acct: r.acct, rooms, address: r.address }
|
|
283
|
+
},
|
|
284
|
+
|
|
285
|
+
/** § 8.6 Add a device, on the APPROVING device: register the new device's key with the service (this device + an email
|
|
286
|
+
* code; Advanced: + a security key). The account's keys may go to it only after this. → { acct, base, address } — what
|
|
287
|
+
* the new device needs to join (adoptLinked). */
|
|
288
|
+
async enrolDevice({ newSpk, label, address, getCode, onStep }) {
|
|
289
|
+
need()
|
|
290
|
+
const s = state()
|
|
291
|
+
if (!s) throw Object.assign(new Error('not_migrated'), { code: 'not_migrated' })
|
|
292
|
+
await client.enrolDevice({ acct: s.acct, device: await signer(), newSpk, label, address, getCode, keys: deps.keys || null, onStep })
|
|
293
|
+
return { acct: s.acct, base: deps.base, address: s.address || (typeof address === 'string' ? address : null) }
|
|
294
|
+
},
|
|
295
|
+
|
|
296
|
+
/** § 8.6 on the NEW device, once the approving device registered it and sent the account's keys over the link: this
|
|
297
|
+
* device is the account's now — its backup is read through the service with this device's own key (a device-signed
|
|
298
|
+
* read), then applied as a restore applies it. Nothing is kept if any step fails. → { acct, rooms } */
|
|
299
|
+
async adoptLinked({ acct, address, master: masterB64, code }) {
|
|
300
|
+
need()
|
|
301
|
+
if (state()) throw Object.assign(new Error('already_migrated'), { code: 'already_migrated' })
|
|
302
|
+
const master = Uint8Array.from(atob(masterB64), (ch) => ch.charCodeAt(0))
|
|
303
|
+
const st = { acct, base: deps.base, at: Date.now(), trust: null, address: address || null }
|
|
304
|
+
adoptingNow = true
|
|
305
|
+
setState({ ...st, adopting: true })
|
|
306
|
+
try {
|
|
307
|
+
const id = await deps.backupIdOf(master)
|
|
308
|
+
const r = await client.syncRead(await signer(), id)
|
|
309
|
+
const blob = r.blob && r.blob.length ? new TextDecoder().decode(r.blob) : null
|
|
310
|
+
const payload = blob ? await deps.openBackup(master, blob) : null
|
|
311
|
+
if (!payload) throw Object.assign(new Error('backup_unopened'), { code: 'backup_unopened' })
|
|
312
|
+
if (deps.checkIncomingBackup) await deps.checkIncomingBackup(payload, id)
|
|
313
|
+
const rooms = await deps.applyRestored({ master, payload, code, linked: true, ...(deps.checkIncomingBackup ? { appChecked: true } : {}) })
|
|
314
|
+
const now = state()
|
|
315
|
+
setState({ ...(now && now.acct === acct ? now : st), adopting: undefined }) // applied: the account is this device's for good
|
|
316
|
+
return { acct, rooms }
|
|
317
|
+
} catch (e) { deps.storage.removeItem(STATE_KEY); throw e } finally { adoptingNow = false }
|
|
318
|
+
},
|
|
319
|
+
|
|
320
|
+
/** F-01 / R2-03 / R3-01 (implementation review): a new code (rotation or the first one) is kept as `vault.pending`,
|
|
321
|
+
* with its session id, and read back from disk BEFORE its activation is sent; an activation can land with its answer
|
|
322
|
+
* lost. At launch and on foreground the SERVICE decides, never this device's clock:
|
|
323
|
+
* 1. the pending backup id is this account's current head → the activation committed → adopt (the code was shown);
|
|
324
|
+
* 2. else CLOSE the session (a write: it races any commit still on its way, and only one of them can win):
|
|
325
|
+
* still live by the service's clock → wait; the commit won → adopt once the head says so;
|
|
326
|
+
* 3. closed (now or earlier) or gone — no commit of it can ever land → read the head once more (a commit that
|
|
327
|
+
* landed before the close), and only if it is still not current → drop.
|
|
328
|
+
* A read of the session's time is never enough to drop (R3-01: a commit past its checks can land after it).
|
|
329
|
+
* Anything unknown (offline, an error, a revoked device, no session id) → change nothing.
|
|
330
|
+
* → 'none' | 'adopted' | 'dropped' | 'waiting' | 'unknown' */
|
|
331
|
+
async reconcilePending() {
|
|
332
|
+
// ⛔ 10·Q#1 (pass 10): the RAW record — a new account's first code is pending with no master yet, and vault() hid it: a first
|
|
333
|
+
// code whose commit answer was lost was never adopted, and the next try overwrote the only copy of the active master
|
|
334
|
+
const s = state(), v = (deps.vaultRecord && deps.vaultRecord()) || (deps.vault && deps.vault())
|
|
335
|
+
if (!client || !s || !v || !v.pending || !v.pending.master) return 'none'
|
|
336
|
+
const master = Uint8Array.from(atob(v.pending.master), (c) => c.charCodeAt(0))
|
|
337
|
+
let id, device
|
|
338
|
+
try { id = await deps.backupIdOf(master); device = await signer() } catch { return 'unknown' }
|
|
339
|
+
const current = async () => {
|
|
340
|
+
try { await client.syncRead(device, id); return true } catch (e) { return e && (e.code === 'not_a_member' || e.code === 'not_current') ? false : null }
|
|
341
|
+
}
|
|
342
|
+
const adopt = () => {
|
|
343
|
+
deps.adoptRotation({ newMaster: master, newCode: v.pending.code })
|
|
344
|
+
if (s.setup === 'pending') setState({ ...s, setup: undefined, at: Date.now() })
|
|
345
|
+
return 'adopted'
|
|
346
|
+
}
|
|
347
|
+
const c1 = await current()
|
|
348
|
+
if (c1 === true) return adopt()
|
|
349
|
+
if (c1 === null) return 'unknown'
|
|
350
|
+
if (!v.pending.rid) return 'waiting' // kept by an older build: no session to ask — keep it
|
|
351
|
+
let st
|
|
352
|
+
try { st = await client.rotationClose(device, v.pending.rid) } catch { return 'unknown' }
|
|
353
|
+
if (st.live) return 'waiting'
|
|
354
|
+
if (st.state !== 'closed' && st.state !== 'gone' && st.state !== 'committed') return 'unknown' // an answer this build does not know
|
|
355
|
+
const c2 = await current()
|
|
356
|
+
if (st.state === 'committed') return c2 === true ? adopt() : 'waiting' // the commit won: adopt through the head, never drop
|
|
357
|
+
if (c2 === true) return adopt()
|
|
358
|
+
if (c2 === null) return 'unknown'
|
|
359
|
+
deps.dropPending && deps.dropPending()
|
|
360
|
+
return 'dropped'
|
|
361
|
+
},
|
|
362
|
+
|
|
363
|
+
/** § 8.5 — at launch and on foreground. Removes this account ONLY on an authenticated answer naming this key and the
|
|
364
|
+
* nonce this request sent (the client checks the HTTP status; this checks the body); anything else changes nothing. */
|
|
365
|
+
async checkStatus() {
|
|
366
|
+
const s = state()
|
|
367
|
+
if (!client || !s) return { state: 'off' }
|
|
368
|
+
if (erasingNow) return { state: 'unknown' }
|
|
369
|
+
let r
|
|
370
|
+
try { r = await client.deviceStatus(await signer()) } catch { return { state: 'unknown' } } // offline, an error, a mismatch: nothing changes
|
|
371
|
+
if (erasingNow || JSON.stringify(state()) !== JSON.stringify(s)) return { state: 'unknown' }
|
|
372
|
+
if (typeof deps.canApplyStatus === 'function' && !deps.canApplyStatus()) return { state: 'unknown' } // an erase/account switch overtook this read
|
|
373
|
+
if (r.state === 'revoked') { await deps.wipe(); deps.storage.removeItem(STATE_KEY); deps.storage.removeItem(MOVE_KEY); return { state: 'revoked' } }
|
|
374
|
+
let pending = 'none'
|
|
375
|
+
if (r.state === 'active') { try { pending = await this.reconcilePending() } catch { pending = 'unknown' } }
|
|
376
|
+
// § 11.5, 3a: a move of this account's address — kept, so the warning shows at once at the next launch and the check
|
|
377
|
+
// runs at every launch until it ends; an active answer without one ends it (cancelled, finished, expired)
|
|
378
|
+
const move = r.state === 'active' ? keepMove(r.move) : this.knownMove()
|
|
379
|
+
return { state: r.state || 'unknown', pending, ...(move ? { move } : {}) }
|
|
380
|
+
},
|
|
381
|
+
|
|
382
|
+
/** The move of this account's email address under way, as the last status answer said (and not past its end) — or null. */
|
|
383
|
+
knownMove() {
|
|
384
|
+
try {
|
|
385
|
+
const m = JSON.parse(deps.storage.getItem(MOVE_KEY) || 'null')
|
|
386
|
+
if (!m || !m.reset || !state() || (m.base && m.base !== deps.base) || !(m.expires * 1000 > Date.now())) return null
|
|
387
|
+
return m
|
|
388
|
+
} catch { return null }
|
|
389
|
+
},
|
|
390
|
+
/** Ask for more time on that move (once): it then waits 30 days from its start. Never cancels. → the kept move */
|
|
391
|
+
async objectMove() {
|
|
392
|
+
need()
|
|
393
|
+
const m = this.knownMove()
|
|
394
|
+
if (!m) throw Object.assign(new Error('no_reset'), { code: 'no_reset' })
|
|
395
|
+
try {
|
|
396
|
+
const r = await client.resetObject({ device: await signer(), reset: m.reset })
|
|
397
|
+
return keepMove({ ...m, ready_at: r.ready_at, expires: r.expires, objected: true })
|
|
398
|
+
} catch (e) { if (e && (e.code === 'reset_ended' || e.code === 'no_reset')) deps.storage.removeItem(MOVE_KEY); throw e }
|
|
399
|
+
},
|
|
400
|
+
/** Cancel that move with a claim code sent to `address` (the mailbox decides — a device alone cannot). */
|
|
401
|
+
async cancelMove({ address, getCode }) {
|
|
402
|
+
need()
|
|
403
|
+
const m = this.knownMove()
|
|
404
|
+
if (!m) throw Object.assign(new Error('no_reset'), { code: 'no_reset' })
|
|
405
|
+
try { await client.resetCancel({ reset: m.reset, address, getCode }) } catch (e) { if (e && (e.code === 'reset_ended' || e.code === 'no_reset')) deps.storage.removeItem(MOVE_KEY); throw e }
|
|
406
|
+
deps.storage.removeItem(MOVE_KEY)
|
|
407
|
+
return { cancelled: true }
|
|
408
|
+
},
|
|
409
|
+
/** The mover: the dates of the move this device started, as the service has them now (a device of the old account may
|
|
410
|
+
* have asked for more time). → the kept move, or null when it ended (forgotten here). */
|
|
411
|
+
async refreshReset() {
|
|
412
|
+
need()
|
|
413
|
+
const p = this.pendingReset()
|
|
414
|
+
if (!p) return null
|
|
415
|
+
const r = await client.resetState({ device: await signer(), reset: p.reset })
|
|
416
|
+
if (r.state !== 'waiting') { if (r.state !== 'done') deps.storage.removeItem(RESET_KEY); return null }
|
|
417
|
+
const rec = { ...p, ready_at: r.ready_at, expires: r.expires }
|
|
418
|
+
deps.storage.setItem(RESET_KEY, JSON.stringify(rec))
|
|
419
|
+
return rec
|
|
420
|
+
},
|
|
421
|
+
|
|
422
|
+
/** § 8.4 — the committed head of this account's backup: { blob (the sealed string) | null, ver, rg, epoch }. */
|
|
423
|
+
async readBackup(id) {
|
|
424
|
+
need()
|
|
425
|
+
const r = await client.syncRead(await signer(), id)
|
|
426
|
+
return { blob: r.blob && r.blob.length ? new TextDecoder().decode(r.blob) : null, ver: r.ver, rg: r.rg, epoch: r.epoch }
|
|
427
|
+
},
|
|
428
|
+
|
|
429
|
+
/** § 8.4 — a new version over `head` (as readBackup returned it). → 'ok' | 'conflict' */
|
|
430
|
+
async writeBackup(id, sealed, head) {
|
|
431
|
+
need()
|
|
432
|
+
const s = state(), v = deps.vault()
|
|
433
|
+
const master = Uint8Array.from(atob(v.master), (c) => c.charCodeAt(0))
|
|
434
|
+
try {
|
|
435
|
+
await client.writeBackup({ device: await signer(), acct: s.acct, id, blob: new TextEncoder().encode(sealed), prev: head.ver, master, rg: head.rg, epoch: head.epoch })
|
|
436
|
+
return 'ok'
|
|
437
|
+
} catch (e) { if (e && e.code === 'conflict') return 'conflict'; throw e }
|
|
438
|
+
},
|
|
439
|
+
|
|
440
|
+
/** § 8.2 — a new recovery code: every new value made here, the new backup merged with the current head, the code shown
|
|
441
|
+
* (`showCode(code)` resolves once the person has saved it), then one activation. Every other device is signed out. */
|
|
442
|
+
async newRecoveryCode({ address, getCode, showCode }) {
|
|
443
|
+
need()
|
|
444
|
+
const s = state()
|
|
445
|
+
if (!s) throw Object.assign(new Error('not_migrated'), { code: 'not_migrated' })
|
|
446
|
+
const prep = await deps.prepareRotation((id) => this.readBackup(id))
|
|
447
|
+
const r = await client.rotate({
|
|
448
|
+
acct: s.acct, device: await signer(), address, getCode,
|
|
449
|
+
newCode: deps.codeBytesOf(prep.newCode), newMaster: prep.newMaster, backupId: prep.backupId, wrapperId: prep.wrapperId,
|
|
450
|
+
backupBlob: prep.backupBlob, wrapperBlob: prep.wrapperBlob, keys: deps.keys || null,
|
|
451
|
+
confirmSaved: (at) => keepPending(prep, at, showCode), // kept (and read back) before the activation is sent
|
|
452
|
+
})
|
|
453
|
+
deps.adoptRotation(prep)
|
|
454
|
+
return r
|
|
455
|
+
},
|
|
456
|
+
|
|
457
|
+
/** § 8.3 — sign out every other device of this account. */
|
|
458
|
+
/** Release checklist 1.11 — DELETE this account on the new service (the app's "Delete my account"): this device and an
|
|
459
|
+
* email code prove it, the service signs out every device, frees the address and deletes the backup. This device keeps
|
|
460
|
+
* no account afterwards (the app wipes the rest). */
|
|
461
|
+
async eraseAccount({ address, getCode }) {
|
|
462
|
+
need()
|
|
463
|
+
const s = state()
|
|
464
|
+
if (!s) throw Object.assign(new Error('not_migrated'), { code: 'not_migrated' })
|
|
465
|
+
if (erasingNow) throw Object.assign(new Error('account deletion is already running'), { code: 'busy' })
|
|
466
|
+
erasingNow = true
|
|
467
|
+
try {
|
|
468
|
+
const keep = {
|
|
469
|
+
get: (acct) => { try { const k = JSON.parse(deps.storage.getItem(ERASE_KEY) || 'null'); return k && k.acct === acct && Date.now() - (k.at || 0) < 29 * 86400_000 ? k.body : null } catch { return null } },
|
|
470
|
+
set: async (acct, body) => {
|
|
471
|
+
const text = JSON.stringify({ acct, body, at: Date.now() })
|
|
472
|
+
deps.storage.setItem(ERASE_KEY, text)
|
|
473
|
+
if (typeof deps.storage.flushed === 'function') await deps.storage.flushed()
|
|
474
|
+
if (typeof deps.flushed === 'function') await deps.flushed()
|
|
475
|
+
if (typeof deps.durableRead === 'function' && await deps.durableRead(ERASE_KEY) !== text) throw Object.assign(new Error('the deletion request could not be kept on this device'), { code: 'erase_not_kept' })
|
|
476
|
+
},
|
|
477
|
+
clear: () => { try { deps.storage.removeItem(ERASE_KEY) } catch { /* */ } },
|
|
478
|
+
}
|
|
479
|
+
const r = await client.eraseAccount({ acct: s.acct, device: await signer(), address, getCode, keys: deps.keys || null, keep })
|
|
480
|
+
try { deps.storage.removeItem(STATE_KEY) } catch { /* */ }
|
|
481
|
+
return r
|
|
482
|
+
} finally { erasingNow = false }
|
|
483
|
+
},
|
|
484
|
+
|
|
485
|
+
/** The email check for a guard on this device ("Show recovery code"): Google or the emailed code; nothing changes. */
|
|
486
|
+
async proveEmail({ address, getCode }) {
|
|
487
|
+
need()
|
|
488
|
+
const s = state()
|
|
489
|
+
if (!s) throw Object.assign(new Error('not_migrated'), { code: 'not_migrated' })
|
|
490
|
+
return client.proveEmail({ acct: s.acct, device: await signer(), address, getCode })
|
|
491
|
+
},
|
|
492
|
+
async signOutOthers({ address, getCode }) {
|
|
493
|
+
need()
|
|
494
|
+
const s = state()
|
|
495
|
+
if (!s) throw Object.assign(new Error('not_migrated'), { code: 'not_migrated' })
|
|
496
|
+
const r = await client.signoutOthers({ acct: s.acct, device: await signer(), address, getCode, keys: deps.keys || null })
|
|
497
|
+
this.prunePush().catch(() => {}) // § 8.8: their notifications leave every Space now (and again at each launch until done)
|
|
498
|
+
try { if (typeof deps.afterSignOut === 'function') deps.afterSignOut() } catch { /* best effort */ } // the room pass: renew at once (docs/device-gate-design.md)
|
|
499
|
+
return r
|
|
500
|
+
},
|
|
501
|
+
|
|
502
|
+
/** Sign out ONE other device of the account (Your devices: a computer paired for Code, …). Its notifications leave every
|
|
503
|
+
* Space as after any sign-out (§ 8.8). */
|
|
504
|
+
async signOutDevice({ spk, address, getCode }) {
|
|
505
|
+
need()
|
|
506
|
+
const s = state()
|
|
507
|
+
if (!s) throw Object.assign(new Error('not_migrated'), { code: 'not_migrated' })
|
|
508
|
+
const r = await client.signoutDevice({ acct: s.acct, device: await signer(), targetSpk: spk, address, getCode, keys: deps.keys || null })
|
|
509
|
+
this.prunePush().catch(() => {})
|
|
510
|
+
return r
|
|
511
|
+
},
|
|
512
|
+
/** The account's devices that count, as the service knows them → [{ spk, label, state, via, at, me }] (newest first), or
|
|
513
|
+
* null when this device has no account on the new service. Throws on anything else (offline, an error). */
|
|
514
|
+
async devices() {
|
|
515
|
+
if (!client || !state()) return null
|
|
516
|
+
const r = await client.listDevices(await signer())
|
|
517
|
+
return Array.isArray(r && r.devices) ? r.devices : []
|
|
518
|
+
},
|
|
519
|
+
|
|
520
|
+
/** § 8.8 (release checklist 1.6): this ACTIVE device's approval of ITS OWN AWS key (a handle on the person's budget)
|
|
521
|
+
* → { statement, sig } */
|
|
522
|
+
async awsStatement(signPub) {
|
|
523
|
+
need()
|
|
524
|
+
const r = await client.awsStatement(await signer(), signPub)
|
|
525
|
+
return { statement: r.statement, sig: r.sig }
|
|
526
|
+
},
|
|
527
|
+
|
|
528
|
+
/** docs/device-gate-design.md: this ACTIVE device's ten-minute room pass for its session key (roomPass.js) → { pass, sig, exp }.
|
|
529
|
+
* A signed-out device is refused (`revoked`), and the bridge's fetch runs the status check at once. */
|
|
530
|
+
async roomPass(email, sessionPub) {
|
|
531
|
+
need()
|
|
532
|
+
const r = await client.roomPass(await signer(), email, sessionPub)
|
|
533
|
+
return { pass: r.pass, sig: r.sig, exp: r.exp }
|
|
534
|
+
},
|
|
535
|
+
|
|
536
|
+
|
|
537
|
+
/** § 8.8: register THIS device's push address with the service — sealed under the account key (deps.sealPush), with its
|
|
538
|
+
* hash — when it changed (or none any more). → 'registered' | 'removed' | 'same' | 'off' */
|
|
539
|
+
async syncPush() {
|
|
540
|
+
if (!client || !state() || !deps.pushEndpoint || !deps.sealPush) return 'off'
|
|
541
|
+
const endpoint = await deps.pushEndpoint()
|
|
542
|
+
// NOT KNOWN YET is not "none" (Codex sweep 2026-11-16 #2: a builders' vault whose subscription was still loading sent an empty
|
|
543
|
+
// record, and another device could no longer find this one's address to revoke it) — nothing is sent; the change resyncs it
|
|
544
|
+
if (endpoint === undefined) return 'unknown'
|
|
545
|
+
const k = STATE_KEY + ':push', mark = endpoint ? await sha256Hex(endpoint) : 'none'
|
|
546
|
+
// the seal's key is part of the mark: after a new recovery code (a new master) the address is sealed again
|
|
547
|
+
const seal = deps.sealId ? await deps.sealId() : ''
|
|
548
|
+
let prev = null
|
|
549
|
+
try { prev = deps.storage.getItem(k) } catch { /* */ }
|
|
550
|
+
if (prev === state().acct + '|' + mark + '|' + seal) return 'same'
|
|
551
|
+
await client.devicePush(await signer(), endpoint ? { sealed: await deps.sealPush(endpoint), hash: mark } : {})
|
|
552
|
+
try { deps.storage.setItem(k, state().acct + '|' + mark + '|' + seal) } catch { /* */ }
|
|
553
|
+
return endpoint ? 'registered' : 'removed'
|
|
554
|
+
},
|
|
555
|
+
|
|
556
|
+
/** § 8.8: the signed-out devices' push addresses leave every Space this device holds (deps.withdrawPush), then each is
|
|
557
|
+
* marked done with its hash. A Space that could not be reached leaves it to the next run. → { pruned, left } */
|
|
558
|
+
async prunePush() {
|
|
559
|
+
if (!client || !state() || !deps.openPush || !deps.withdrawPush) return { pruned: 0, left: 0 }
|
|
560
|
+
const dev = await signer()
|
|
561
|
+
const { devices = [] } = await client.signedOutPush(dev)
|
|
562
|
+
let n = 0, left = devices.length
|
|
563
|
+
for (const d of devices) {
|
|
564
|
+
let endpoint = null
|
|
565
|
+
try { endpoint = await deps.openPush(d.sealed) } catch { /* sealed under another master (before a new code): nothing to do here */ }
|
|
566
|
+
if (!endpoint) continue
|
|
567
|
+
if (!(await deps.withdrawPush([endpoint]))) continue
|
|
568
|
+
await client.markPushPruned(dev, d.device, await sha256Hex(endpoint))
|
|
569
|
+
n++; left--
|
|
570
|
+
}
|
|
571
|
+
return { pruned: n, left }
|
|
572
|
+
},
|
|
573
|
+
|
|
574
|
+
/** The computers paired for Code (codeComputers.js pruneSignedOutComputers): which of the listed device keys are still this
|
|
575
|
+
* account's devices → { base, states } — `base` the service that answered (an entry registered on another is never judged by
|
|
576
|
+
* it) — or null when this device has no account on the new service. Throws on anything else (offline, an error): unknown. */
|
|
577
|
+
async deviceStates(spks) {
|
|
578
|
+
if (!client || !state()) return null
|
|
579
|
+
const r = await client.deviceStates(await signer(), spks)
|
|
580
|
+
return { base: deps.base, states: r && r.states && typeof r.states === 'object' ? r.states : {} }
|
|
581
|
+
},
|
|
582
|
+
|
|
583
|
+
/** § 10 — the account's mode and its active keys, for Settings. */
|
|
584
|
+
async security() {
|
|
585
|
+
need()
|
|
586
|
+
if (!state()) throw Object.assign(new Error('not_migrated'), { code: 'not_migrated' })
|
|
587
|
+
return client.security(await signer())
|
|
588
|
+
},
|
|
589
|
+
|
|
590
|
+
/** § 10.1 — turn Advanced Backup on: register and confirm every key the service asks for. */
|
|
591
|
+
async turnOnAdvanced({ address, getCode, onStep }) {
|
|
592
|
+
need()
|
|
593
|
+
const s = state()
|
|
594
|
+
if (!s) throw Object.assign(new Error('not_migrated'), { code: 'not_migrated' })
|
|
595
|
+
return client.enrolKeys({ acct: s.acct, device: await signer(), address, getCode, keys: deps.keys, purpose: 'advanced_on', onStep })
|
|
596
|
+
},
|
|
597
|
+
|
|
598
|
+
/** § 10.4 — add a key (an existing key confirms it). */
|
|
599
|
+
async addKey({ address, getCode, onStep }) {
|
|
600
|
+
need()
|
|
601
|
+
const s = state()
|
|
602
|
+
return client.enrolKeys({ acct: s.acct, device: await signer(), address, getCode, keys: deps.keys, purpose: 'key_add', onStep })
|
|
603
|
+
},
|
|
604
|
+
|
|
605
|
+
/** § 10.4 — remove a key; another key proves it. */
|
|
606
|
+
async removeKey({ address, getCode, credId }) {
|
|
607
|
+
need()
|
|
608
|
+
const s = state()
|
|
609
|
+
return client.removeKey({ acct: s.acct, device: await signer(), address, getCode, keys: deps.keys, credId })
|
|
610
|
+
},
|
|
611
|
+
|
|
612
|
+
/** Turn Advanced Backup off: every key retired. */
|
|
613
|
+
async turnOffAdvanced({ address, getCode }) {
|
|
614
|
+
need()
|
|
615
|
+
const s = state()
|
|
616
|
+
return client.advancedOff({ acct: s.acct, device: await signer(), address, getCode, keys: deps.keys })
|
|
617
|
+
},
|
|
618
|
+
}
|
|
619
|
+
}
|