@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/acctV2Check.js
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
// acctV2Check.js — WHEN a device asks the account service for its status (acctV2Wiring.js startAcctV2StatusChecks).
|
|
2
|
+
// Every status call is signed by the device key, so each one tells the service "this device is in use now". It was every
|
|
3
|
+
// launch and every return to the foreground; now at most once a day (owner, 2026-11-15), remembered across launches.
|
|
4
|
+
// Nothing protected depends on it: the service refuses a signed-out device on every operation itself — the check only lets
|
|
5
|
+
// a signed-out device notice sooner and remove the account. So it still runs at once when it matters:
|
|
6
|
+
// - an unfinished new recovery code (vault().pending): the F-01 reconcile must run at the next launch;
|
|
7
|
+
// - the service refused this device as signed out on another call (403 `revoked`): remove the account now;
|
|
8
|
+
// - the person opened Settings → Your devices (owner, 2026-11-15: a signed-out device showed nothing for a day) — they
|
|
9
|
+
// asked, so the check is theirs, not a per-launch record; at most once per OPEN_FLOOR however often the panel opens;
|
|
10
|
+
// - a move of this account's email address is under way (`moving` — the last answer said so: protocol § 11.5, 3a): every
|
|
11
|
+
// launch and foreground until it ends, so the warning is current and goes away when the move is cancelled or over.
|
|
12
|
+
export const CHECK_EVERY = 24 * 3600 * 1000
|
|
13
|
+
export const CHECKED_KEY = 'space:acctv2:checked' // when this device last had an answer — a time, kept on this device only
|
|
14
|
+
|
|
15
|
+
/** Is a status check due? `last` = the stored time of the last answer (ms), anything else = never. */
|
|
16
|
+
export function statusDue({ now, last, pending = false, force = false, moving = false }) {
|
|
17
|
+
if (force || pending || moving) return true
|
|
18
|
+
const t = Number(last)
|
|
19
|
+
if (!Number.isFinite(t) || !t || t > now) return true // never checked, garbage, or a clock moved back: check
|
|
20
|
+
return now - t >= CHECK_EVERY
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export const OPEN_FLOOR = 10 * 1000
|
|
24
|
+
|
|
25
|
+
/** Opening Your devices: check now, unless the panel was opened (and checked) less than OPEN_FLOOR ago. */
|
|
26
|
+
export const openCheckDue = ({ now, lastOpen }) => !(Number(lastOpen) > 0 && now - Number(lastOpen) < OPEN_FLOOR && now >= Number(lastOpen))
|
|
27
|
+
|
|
28
|
+
/** A v2 answer that says this device is signed out (any route but the status check, which answers 200 { state }). */
|
|
29
|
+
export const refusedAsRevoked = (status, body) => status === 403 && !!body && body.reason === 'revoked'
|
package/acctV2Client.js
ADDED
|
@@ -0,0 +1,382 @@
|
|
|
1
|
+
// acctV2Client.js — the client of account recovery v2 (/v2/account/*; docs/account-recovery-protocol.md). Requests are
|
|
2
|
+
// signed with the device's key where the protocol says so (§ 5.4); every proof is computed over the server's challenge
|
|
3
|
+
// (§ 5.2). The flows take the person's email code through a callback — the UI asks for it — and never hold it longer.
|
|
4
|
+
// Pure over an injected fetch: the same code runs in the app and in the tests, against the real service code in-process.
|
|
5
|
+
import { transcript, canonicalQuery, deviceRequestBytes, writeProofBytes, b64u, unb64u, hexOf, sha256 } from './acctV2Wire.js'
|
|
6
|
+
import { possessionKey, backupWriteKey, gateValues } from './acctV2Keys.js'
|
|
7
|
+
|
|
8
|
+
const enc = new TextEncoder()
|
|
9
|
+
const rand = (n) => crypto.getRandomValues(new Uint8Array(n))
|
|
10
|
+
|
|
11
|
+
/** § 11.1 — trim; split at the last '@'; domain lower-cased and IDNA to ASCII; local part lower-cased. */
|
|
12
|
+
// The same checks as the service's (control-plane/src/lib/acct/email.mjs): a disagreement would commit a recovery code to a
|
|
13
|
+
// form the service never computes, and email restore would fail later. The domain may not carry a port, path or other
|
|
14
|
+
// URL syntax (URL() would quietly drop them); it needs a dot; the local part no whitespace; at most 254 characters.
|
|
15
|
+
export function canonicalAddress(raw) {
|
|
16
|
+
const s = String(raw || '').trim(), at = s.lastIndexOf('@')
|
|
17
|
+
if (at < 1 || at === s.length - 1 || s.length > 254) return null
|
|
18
|
+
const local = s.slice(0, at).toLowerCase(), rawDomain = s.slice(at + 1).toLowerCase()
|
|
19
|
+
if (/\s/.test(local) || /[\s:/\\?#@[\]]/.test(rawDomain)) return null
|
|
20
|
+
let domain
|
|
21
|
+
try { domain = new URL('http://' + rawDomain).hostname } catch { return null }
|
|
22
|
+
if (!domain || !domain.includes('.')) return null
|
|
23
|
+
return local + '@' + domain
|
|
24
|
+
}
|
|
25
|
+
export async function emailCommit(gk, canonical) {
|
|
26
|
+
const k = await crypto.subtle.importKey('raw', gk, { name: 'HMAC', hash: 'SHA-256' }, false, ['sign'])
|
|
27
|
+
return hexOf(new Uint8Array(await crypto.subtle.sign('HMAC', k, enc.encode(canonical))))
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
// headers: extra headers on every request — the hosted app's vault names its tenant (`x-acct-tenant`), so its accounts are its
|
|
31
|
+
// own (control-plane/src/lib/acct/appScope.mjs). They never replace the content type or a device signature's headers.
|
|
32
|
+
export function accountClient({ base, fetch: f = globalThis.fetch, now = () => Math.floor(Date.now() / 1000), timeoutMs = 20000, headers: extra = null }) {
|
|
33
|
+
// ⛔ 10·A#2 / A#3 / Q#4 (pass 10): a commit whose ANSWER was lost (no HTTP status: the network, a timeout) is sent again — the
|
|
34
|
+
// same request; the service answers its claimant with what it already did (reset.mjs). Not repeated: the device gave up its
|
|
35
|
+
// key and the address stayed bound to an empty account (fresh / reset finish), or locked for two weeks (reset start).
|
|
36
|
+
const again = async (call) => {
|
|
37
|
+
for (let i = 0; ; i++) {
|
|
38
|
+
try { return await call() } catch (e) { if ((e && e.status) || i >= 2) throw e; await new Promise((r) => setTimeout(r, 800 * (i + 1))) }
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
async function req(method, path, { body, query = {}, signer } = {}) {
|
|
42
|
+
const raw = body ? enc.encode(JSON.stringify(body)) : new Uint8Array(0)
|
|
43
|
+
const headers = { ...(extra || {}), 'content-type': 'application/json' }
|
|
44
|
+
const qs = canonicalQuery(query)
|
|
45
|
+
if (signer) {
|
|
46
|
+
const ts = now(), nonce = b64u(rand(9))
|
|
47
|
+
const sig = await signer.sign(await deviceRequestBytes({ method, path, query: qs, body: raw, ts, nonce }))
|
|
48
|
+
Object.assign(headers, { 'x-dev-spk': signer.spk, 'x-dev-ts': String(ts), 'x-dev-nonce': nonce, 'x-dev-sig': b64u(sig) })
|
|
49
|
+
}
|
|
50
|
+
const r = await f(base + path + (qs ? '?' + qs : ''), { method, headers, signal: AbortSignal.timeout(timeoutMs), ...(method === 'GET' ? {} : { body: raw }) })
|
|
51
|
+
const j = await r.json().catch(() => null)
|
|
52
|
+
if (!r.ok || !j || !j.ok) throw Object.assign(new Error((j && j.reason) || 'http_' + r.status), { code: j && j.reason, status: r.status })
|
|
53
|
+
return j
|
|
54
|
+
}
|
|
55
|
+
const T = (c, op, params) => transcript({ op, acct: c.acct, params, challenge: c.challenge, nonce: c.nonce, exp: c.exp, pv: c.pv, rg: c.rg, ev: c.ev, epoch: c.epoch })
|
|
56
|
+
const sigOf = async (signer, bytes) => b64u(await signer.sign(bytes))
|
|
57
|
+
// getCode({ action }) answers the code — or { google: idToken }, a Google sign-in for THIS action (its nonce, acct/googleProof.mjs)
|
|
58
|
+
// in place of the code, which the service turns into the same verified ticket
|
|
59
|
+
// FIRST A CHOICE (the owner, 2026-11-16: "It should first ask for a choice between sending the code and Google login. Currently
|
|
60
|
+
// it automatically sends the code"): a getCode with `choose` asks before anything is mailed — { google: idToken } goes straight
|
|
61
|
+
// to the Google route and no code is sent; anything else (the person chose the email) mails the code, then asks for it.
|
|
62
|
+
const chooseFirst = async (getCode, action) => (typeof getCode.choose === 'function' ? getCode.choose({ action }) : null)
|
|
63
|
+
async function emailProof(c, address, getCode, gk) {
|
|
64
|
+
const pick = await chooseFirst(getCode, c.challenge)
|
|
65
|
+
if (pick && pick.google) return (await req('POST', '/v2/account/email/google', { body: { purpose: 'authz', challenge: c.challenge, idToken: pick.google, ...(gk ? { gk: hexOf(gk) } : {}) } })).ticket
|
|
66
|
+
// THE APP'S OWN SIGN-IN (the owner, 2026-11-23: a restore signed in twice): the sign-in this device just made, bound to this
|
|
67
|
+
// challenge by its key (control-plane acct/signInProof.mjs) — the email proved once, and the device keeps the session
|
|
68
|
+
// a service from before the route (404 not_found / 501) gets the emailed code instead — the device stays signed in either way
|
|
69
|
+
if (pick && pick.signIn) {
|
|
70
|
+
try { return (await req('POST', '/v2/account/email/signin', { body: { purpose: 'authz', challenge: c.challenge, idToken: pick.signIn.idToken, spk: pick.signIn.spk, sig: pick.signIn.sig, ...(gk ? { gk: hexOf(gk) } : {}) } })).ticket } catch (e) { if (!(e && (e.status === 404 || e.status === 501))) throw e }
|
|
71
|
+
}
|
|
72
|
+
const { ticket } = await req('POST', '/v2/account/email/start', { body: { purpose: 'authz', challenge: c.challenge, address, ...(gk ? { gk: hexOf(gk) } : {}) } })
|
|
73
|
+
const code = await getCode({ action: c.challenge, chose: !!pick })
|
|
74
|
+
if (code && typeof code === 'object' && code.google) return (await req('POST', '/v2/account/email/google', { body: { purpose: 'authz', challenge: c.challenge, idToken: code.google, ...(gk ? { gk: hexOf(gk) } : {}) } })).ticket
|
|
75
|
+
const v = await req('POST', '/v2/account/email/verify', { body: { ticket, code } })
|
|
76
|
+
if (!v.verified) throw Object.assign(new Error('email_code_wrong'), { code: 'email_code_wrong' })
|
|
77
|
+
return ticket
|
|
78
|
+
}
|
|
79
|
+
/** § 10.3 — when the challenge needs a security key: an assertion over SHA-256(T) by one of the account's active keys
|
|
80
|
+
* (the challenge lists them), never by `except` (key_remove must be proved by ANOTHER key). */
|
|
81
|
+
async function keyProof(c, Tb, keys, except = null) {
|
|
82
|
+
if (!c.needs.includes('hwkey')) return {}
|
|
83
|
+
if (!keys) throw Object.assign(new Error('need_security_key'), { code: 'need_security_key' })
|
|
84
|
+
const allow = (c.keys || []).filter((k) => k.id !== except)
|
|
85
|
+
if (!allow.length) throw Object.assign(new Error('no_other_key'), { code: 'no_other_key' })
|
|
86
|
+
return { hwkey: await keys.get({ challenge: await sha256(Tb), allow }) }
|
|
87
|
+
}
|
|
88
|
+
const fail = (code) => { throw Object.assign(new Error(code), { code }) }
|
|
89
|
+
/** A new code's parameters (§ 8.2): every value derived HERE from the new code and master, before anything is sent. */
|
|
90
|
+
async function codeParams({ device, address, newCode, newMaster, backupId, wrapperId }) {
|
|
91
|
+
const { gid: new_gid, gk } = await gateValues(newCode)
|
|
92
|
+
const canonical = canonicalAddress(address)
|
|
93
|
+
if (!canonical) fail('bad_address')
|
|
94
|
+
return {
|
|
95
|
+
new_gid, new_possession_pub: (await possessionKey(newCode)).spk, new_commit_email: await emailCommit(gk, canonical),
|
|
96
|
+
new_members: [backupId, wrapperId], new_write_pub: (await backupWriteKey(newMaster)).spk, initiator_spk: device.spk,
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
/** Stage both objects, read each back and check it, show the code (`confirmSaved`), then the one activation. */
|
|
100
|
+
async function stageAndActivate({ rid, device, backupId, wrapperId, backupBlob, wrapperBlob, confirmSaved }) {
|
|
101
|
+
const staged = {}
|
|
102
|
+
for (const [name, id, blob] of [['backup', backupId, backupBlob], ['wrapper', wrapperId, wrapperBlob]]) {
|
|
103
|
+
const st = await req('POST', `/v2/account/rotation/${rid}/stage`, { body: { id, blob: b64u(blob) }, signer: device })
|
|
104
|
+
const back = unb64u((await req('GET', `/v2/account/rotation/${rid}/staged`, { query: { ver: st.ver }, signer: device })).blob)
|
|
105
|
+
if (hexOf(await sha256(back)) !== st.digest || hexOf(await sha256(blob)) !== st.digest) fail('staged_mismatch')
|
|
106
|
+
staged[name] = { ver: st.ver, digest: st.digest }
|
|
107
|
+
}
|
|
108
|
+
await confirmSaved({ rid }) // the caller keeps the new code with this session id BEFORE the activation below is sent
|
|
109
|
+
return req('POST', `/v2/account/rotation/${rid}/commit`, { body: { backup: staged.backup, wrapper: staged.wrapper, idem: b64u(rand(16)) }, signer: device })
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
return {
|
|
113
|
+
req,
|
|
114
|
+
/** § 8.5 — this device's status; an answer that does not name this key AND echo this request's nonce is refused. */
|
|
115
|
+
async deviceStatus(device) {
|
|
116
|
+
const nonce = b64u(rand(9))
|
|
117
|
+
const r = await req('GET', '/v2/account/device', { query: { nonce }, signer: device })
|
|
118
|
+
if (r.spk !== device.spk || r.nonce !== nonce) throw Object.assign(new Error('status_mismatch'), { code: 'status_mismatch' })
|
|
119
|
+
return r
|
|
120
|
+
},
|
|
121
|
+
|
|
122
|
+
/** § 8.1 — restore onto `device` (a new key) with the recovery code and an email code. → { sid, blobs: { [id]: bytes } } */
|
|
123
|
+
async restore({ codeBytes, address, getCode, device, label = 'New device', keys = null }) {
|
|
124
|
+
const { gid, gk } = await gateValues(codeBytes)
|
|
125
|
+
const poss = await possessionKey(codeBytes)
|
|
126
|
+
const params = { gid, restore_spk: device.spk, label }
|
|
127
|
+
const c = await req('POST', '/v2/account/challenge', { body: { op: 'restore_authorize', gid, params } })
|
|
128
|
+
// `address` may be asked only now (a function): the challenge has just shown the code IS an account here — a code the
|
|
129
|
+
// service does not know answers 404 no_account above, before anyone is asked for an email (the normal Restore tries
|
|
130
|
+
// this service first; an old account's restore must not cost an email prompt)
|
|
131
|
+
const addr = typeof address === 'function' ? await address({ action: c.challenge }) : address
|
|
132
|
+
const ticket = await emailProof(c, addr, getCode, gk)
|
|
133
|
+
const Tb = T(c, 'restore_authorize', params)
|
|
134
|
+
const proofs = { possession: await sigOf(poss, Tb), email_authz: ticket, ...(await keyProof(c, Tb, keys)) }
|
|
135
|
+
const { sid } = await req('POST', '/v2/account/restore_authorize', { body: { challenge: c.challenge, params, proofs, idem: b64u(rand(16)) }, signer: device })
|
|
136
|
+
const { versions } = await req('GET', `/v2/account/restore/${sid}/versions`, { signer: device })
|
|
137
|
+
const blobs = {}
|
|
138
|
+
for (const id of [...new Set(versions.map((v) => v.id))]) {
|
|
139
|
+
const got = await req('GET', `/v2/account/restore/${sid}/blob`, { query: { id }, signer: device })
|
|
140
|
+
const bytes = unb64u(got.blob)
|
|
141
|
+
if (hexOf(await sha256(bytes)) !== got.digest) throw Object.assign(new Error('blob_corrupt'), { code: 'blob_corrupt' }) // the bytes are the version committed
|
|
142
|
+
blobs[id] = bytes
|
|
143
|
+
}
|
|
144
|
+
// R5-01: `try_again` = the account record changed between the service's read and its write (the session still
|
|
145
|
+
// holds) — finishing again is safe and idempotent; a few attempts, then the error stands
|
|
146
|
+
const finish = async () => {
|
|
147
|
+
for (let i = 0; ; i++) {
|
|
148
|
+
try { return await req('POST', `/v2/account/restore/${sid}/finish`, { signer: device }) } catch (e) { if (!(e && e.code === 'try_again') || i >= 2) throw e }
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
return { sid, acct: c.acct, blobs, versions, finish, address: addr }
|
|
152
|
+
},
|
|
153
|
+
|
|
154
|
+
/** PROVE THE EMAIL, CHANGE NOTHING (the owner, 2026-11-22: "Show recovery code" had no check on an account on this service):
|
|
155
|
+
* the email check — the emailed code or Google — run against a fresh challenge, and nothing committed. A verified ticket is
|
|
156
|
+
* the proof; it expires unused. The challenge is a sign-out's (the one op every registered device may ask), never sent on.
|
|
157
|
+
* For a guard on THIS device only (the code it shows is already stored here) — never an authorisation at the service. */
|
|
158
|
+
async proveEmail({ acct, device, address, getCode }) {
|
|
159
|
+
const c = await req('POST', '/v2/account/challenge', { body: { op: 'signout_others', acct, params: { initiator_spk: device.spk } } })
|
|
160
|
+
await emailProof(c, address, getCode)
|
|
161
|
+
return true
|
|
162
|
+
},
|
|
163
|
+
/** § 8.3 — sign out every other device. */
|
|
164
|
+
async signoutOthers({ acct, device, address, getCode, keys = null }) {
|
|
165
|
+
const params = { initiator_spk: device.spk }
|
|
166
|
+
const c = await req('POST', '/v2/account/challenge', { body: { op: 'signout_others', acct, params } })
|
|
167
|
+
const ticket = await emailProof(c, address, getCode)
|
|
168
|
+
const Tb = T(c, 'signout_others', params)
|
|
169
|
+
const proofs = { device: { spk: device.spk, sig: await sigOf(device, Tb) }, email_authz: ticket, ...(await keyProof(c, Tb, keys)) }
|
|
170
|
+
return req('POST', '/v2/account/signout_others', { body: { challenge: c.challenge, params, proofs, idem: b64u(rand(16)) }, signer: device })
|
|
171
|
+
},
|
|
172
|
+
/** Sign out ONE other device (its key `targetSpk`) — proved as signing out all of them: this device + an email code (+ a
|
|
173
|
+
* security key in Advanced). Every other device stays signed in. → { signed_out: true } */
|
|
174
|
+
async signoutDevice({ acct, device, targetSpk, address, getCode, keys = null }) {
|
|
175
|
+
const params = { initiator_spk: device.spk, device_spk: String(targetSpk || '') }
|
|
176
|
+
const c = await req('POST', '/v2/account/challenge', { body: { op: 'signout_device', acct, params } })
|
|
177
|
+
const ticket = await emailProof(c, address, getCode)
|
|
178
|
+
const Tb = T(c, 'signout_device', params)
|
|
179
|
+
const proofs = { device: { spk: device.spk, sig: await sigOf(device, Tb) }, email_authz: ticket, ...(await keyProof(c, Tb, keys)) }
|
|
180
|
+
return req('POST', '/v2/account/signout_device', { body: { challenge: c.challenge, params, proofs, idem: b64u(rand(16)) }, signer: device })
|
|
181
|
+
},
|
|
182
|
+
/** § 8.6 Add a device — THIS active device registers the new one's key. Standard: + an email code; Advanced: + a
|
|
183
|
+
* security key (no email; the challenge says which). */
|
|
184
|
+
async enrolDevice({ acct, device, newSpk, label = '', address, getCode, keys = null }) {
|
|
185
|
+
const params = { new_spk: newSpk, label: String(label || '').slice(0, 64), approver_spk: device.spk }
|
|
186
|
+
const c = await req('POST', '/v2/account/challenge', { body: { op: 'enrol_device', acct, params } })
|
|
187
|
+
const Tb = T(c, 'enrol_device', params)
|
|
188
|
+
const ticket = (c.needs || []).includes('email_authz') ? await emailProof(c, typeof address === 'function' ? await address() : address, getCode) : null
|
|
189
|
+
const proofs = { device: { spk: device.spk, sig: await sigOf(device, Tb) }, ...(ticket ? { email_authz: ticket } : {}), ...(await keyProof(c, Tb, keys)) }
|
|
190
|
+
return req('POST', '/v2/account/enrol_device', { body: { challenge: c.challenge, params, proofs, idem: b64u(rand(16)) }, signer: device })
|
|
191
|
+
},
|
|
192
|
+
/** Release checklist 1.11 — delete this account on the service (as a sign-out is proved: this device + an email code). */
|
|
193
|
+
async eraseAccount({ acct, device, address, getCode, keys = null, keep = null }) {
|
|
194
|
+
// ⛔ 10·Q#3 (pass 10): a request whose answer was lost past these retries (offline, the page killed) is KEPT (`keep`) and a
|
|
195
|
+
// later run sends that same request again — the service answers with what it did. A new one is refused: the erase itself
|
|
196
|
+
// signed this device out; the deletion could never be finished, and the device was soon wiped with the Spaces still there.
|
|
197
|
+
let body = keep && keep.get ? keep.get(acct) : null
|
|
198
|
+
const resumed = !!body
|
|
199
|
+
if (!body) {
|
|
200
|
+
const params = { initiator_spk: device.spk }
|
|
201
|
+
const c = await req('POST', '/v2/account/challenge', { body: { op: 'account_erase', acct, params } })
|
|
202
|
+
const ticket = await emailProof(c, address, getCode)
|
|
203
|
+
const Tb = T(c, 'account_erase', params)
|
|
204
|
+
const proofs = { device: { spk: device.spk, sig: await sigOf(device, Tb) }, email_authz: ticket, ...(await keyProof(c, Tb, keys)) }
|
|
205
|
+
body = { challenge: c.challenge, params, proofs, idem: b64u(rand(16)) }
|
|
206
|
+
if (keep && keep.set) await keep.set(acct, body) // durably kept before it is sent
|
|
207
|
+
}
|
|
208
|
+
// a LOST answer (no HTTP status: the network) is asked again with the SAME request and idempotency key — the service
|
|
209
|
+
// answers with what it did (idemLookup); a new challenge would be refused, the device being signed out by the erase
|
|
210
|
+
// itself (review, 2026-11-15: the app then looked as if nothing was deleted)
|
|
211
|
+
for (let i = 0; ; i++) {
|
|
212
|
+
try { const r = await req('POST', '/v2/account/erase', { body, signer: device }); if (keep && keep.clear) keep.clear(); return r } catch (e) {
|
|
213
|
+
if (e && e.status) { if (resumed && keep && keep.clear) keep.clear(); throw e } // refused: a kept request is not sent again
|
|
214
|
+
if (i >= 2) throw e
|
|
215
|
+
await new Promise((r) => setTimeout(r, 1000 * (i + 1)))
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
},
|
|
219
|
+
|
|
220
|
+
/** § 8.4 — the committed head, for merging. */
|
|
221
|
+
syncRead: async (device, id) => { const r = await req('GET', `/v2/account/backup/${id}/head`, { signer: device }); return { ...r, blob: unb64u(r.blob) } },
|
|
222
|
+
|
|
223
|
+
/** § 8.4 — upload and commit a new version over `prev`. `master` makes the write key; rg/epoch from the device's view. */
|
|
224
|
+
async writeBackup({ device, acct, id, blob, prev, master, rg, epoch }) {
|
|
225
|
+
const wk = await backupWriteKey(master)
|
|
226
|
+
const up = await req('POST', `/v2/account/backup/${id}/upload`, { body: { blob: b64u(blob) }, signer: device })
|
|
227
|
+
const nonce = b64u(rand(9)), ts = now()
|
|
228
|
+
const write_sig = b64u(wk.sign(writeProofBytes({ acct, id, ver: up.ver, digest: up.digest, prev, rg, epoch, nonce, ts })))
|
|
229
|
+
return req('POST', `/v2/account/backup/${id}/commit`, { body: { ver: up.ver, prev, nonce, ts, write_sig }, signer: device })
|
|
230
|
+
},
|
|
231
|
+
|
|
232
|
+
/** § 8.2 — a new recovery code. The caller has made the new code and master and sealed both blobs under them
|
|
233
|
+
* (`backupBlob` under the new master, `wrapperBlob` under the new code); `confirmSaved` shows the code and resolves
|
|
234
|
+
* once the person has saved it. Every new value is derived HERE, before authorising. */
|
|
235
|
+
async rotate({ acct, device, address, getCode, newCode, newMaster, backupId, wrapperId, backupBlob, wrapperBlob, confirmSaved, keys = null }) {
|
|
236
|
+
const params = await codeParams({ device, address, newCode, newMaster, backupId, wrapperId })
|
|
237
|
+
const c = await req('POST', '/v2/account/challenge', { body: { op: 'rotation_authorize', acct, params } })
|
|
238
|
+
const ticket = await emailProof(c, address, getCode)
|
|
239
|
+
const Tr = T(c, 'rotation_authorize', params)
|
|
240
|
+
const proofs = { device: { spk: device.spk, sig: await sigOf(device, Tr) }, email_authz: ticket, ...(await keyProof(c, Tr, keys)) }
|
|
241
|
+
const { rid } = await req('POST', '/v2/account/rotation_authorize', { body: { challenge: c.challenge, params, proofs, idem: b64u(rand(16)) }, signer: device })
|
|
242
|
+
return stageAndActivate({ rid, device, backupId, wrapperId, backupBlob, wrapperBlob, confirmSaved })
|
|
243
|
+
},
|
|
244
|
+
|
|
245
|
+
// § 11.5 — THE EMAIL RESET: an address whose account's recovery code (and devices) are lost moves to a NEW account after a
|
|
246
|
+
// week, announced to the old account. Proved by `claim` email codes only — never Google, never a device or key of the old
|
|
247
|
+
// account. The CLAIMANT is this device: its key signs the start and the finish.
|
|
248
|
+
async claimTicket({ reset, address, getCode }) {
|
|
249
|
+
const { ticket } = await req('POST', '/v2/account/email/start', { body: { purpose: 'claim', reset, address } })
|
|
250
|
+
const v = await req('POST', '/v2/account/email/verify', { body: { ticket, code: await getCode() } }) // no { action }: no Google here
|
|
251
|
+
if (!v.verified) throw Object.assign(new Error('email_code_wrong'), { code: 'email_code_wrong' })
|
|
252
|
+
return ticket
|
|
253
|
+
},
|
|
254
|
+
/** Start: the intent, a claim code, the start — the week begins. → { reset, ready_at, expires } */
|
|
255
|
+
async resetBegin({ device, address, getCode }) {
|
|
256
|
+
const { reset } = await req('POST', '/v2/account/reset/intent', { body: { address, dest: 'new' }, signer: device })
|
|
257
|
+
const ticket = await this.claimTicket({ reset, address, getCode })
|
|
258
|
+
const r = await again(() => req('POST', `/v2/account/reset/${reset}/start`, { body: { ticket }, signer: device }))
|
|
259
|
+
return { reset, ready_at: r.ready_at, expires: r.expires }
|
|
260
|
+
},
|
|
261
|
+
/** Finish, once the week is over: a NEW claim code, the claimant's signature → { acct } (a fresh account, this device in it). */
|
|
262
|
+
async resetFinish({ device, reset, address, getCode, label = 'This device' }) {
|
|
263
|
+
const ticket = await this.claimTicket({ reset, address, getCode })
|
|
264
|
+
return again(() => req('POST', `/v2/account/reset/${reset}/finish`, { body: { ticket, label }, signer: device }))
|
|
265
|
+
},
|
|
266
|
+
/** Cancel: a claim code bound to this reset — from any device; nothing else cancels. */
|
|
267
|
+
async resetCancel({ reset, address, getCode }) {
|
|
268
|
+
const ticket = await this.claimTicket({ reset, address, getCode })
|
|
269
|
+
return req('POST', `/v2/account/reset/${reset}/cancel`, { body: { ticket } })
|
|
270
|
+
},
|
|
271
|
+
|
|
272
|
+
/** § 11.5, 3a — a device of the account whose address is being moved asks for more time, once (the wait becomes 30 days
|
|
273
|
+
* from the move's start; it never cancels). → { ready_at, expires } */
|
|
274
|
+
resetObject({ device, reset }) { return req('POST', `/v2/account/reset/${reset}/object`, { signer: device }) },
|
|
275
|
+
/** § 11.5, 3a — the mover's own view of its move (claimant-signed). → { state, ready_at?, expires? } */
|
|
276
|
+
resetState({ device, reset }) { return req('GET', `/v2/account/reset/${reset}`, { signer: device }) },
|
|
277
|
+
|
|
278
|
+
/** § 12.4 — a new account on this device for an address that has none (an email code proves it). → { acct } */
|
|
279
|
+
async freshAccount({ device, address, getCode, label = 'This device' }) {
|
|
280
|
+
const { attempt } = await req('POST', '/v2/account/fresh/intent', { signer: device })
|
|
281
|
+
const pick = await chooseFirst(getCode, attempt) // Google or the emailed code, asked before anything is mailed
|
|
282
|
+
if (pick && pick.google) {
|
|
283
|
+
const { ticket } = await req('POST', '/v2/account/email/google', { body: { purpose: 'new_identity', attempt, idToken: pick.google, address } })
|
|
284
|
+
return again(() => req('POST', `/v2/account/fresh/${attempt}/commit`, { body: { ticket, label }, signer: device }))
|
|
285
|
+
}
|
|
286
|
+
const { ticket: sent } = await req('POST', '/v2/account/email/start', { body: { purpose: 'new_identity', attempt, address } })
|
|
287
|
+
const code = await getCode({ action: attempt, chose: !!pick })
|
|
288
|
+
let ticket = sent
|
|
289
|
+
if (code && typeof code === 'object' && code.google) ticket = (await req('POST', '/v2/account/email/google', { body: { purpose: 'new_identity', attempt, idToken: code.google, address } })).ticket // Google in place of the code
|
|
290
|
+
else {
|
|
291
|
+
const v = await req('POST', '/v2/account/email/verify', { body: { ticket, code } })
|
|
292
|
+
if (!v.verified) throw Object.assign(new Error('email_code_wrong'), { code: 'email_code_wrong' })
|
|
293
|
+
}
|
|
294
|
+
return again(() => req('POST', `/v2/account/fresh/${attempt}/commit`, { body: { ticket, label }, signer: device }))
|
|
295
|
+
},
|
|
296
|
+
|
|
297
|
+
/** § 8.2a — the FIRST recovery code of an account that has none: the device alone authorises it. */
|
|
298
|
+
async setupCode({ acct, device, address, newCode, newMaster, backupId, wrapperId, backupBlob, wrapperBlob, confirmSaved }) {
|
|
299
|
+
const params = await codeParams({ device, address, newCode, newMaster, backupId, wrapperId })
|
|
300
|
+
const c = await req('POST', '/v2/account/challenge', { body: { op: 'setup_code', acct, params } })
|
|
301
|
+
const proofs = { device: { spk: device.spk, sig: await sigOf(device, T(c, 'setup_code', params)) } }
|
|
302
|
+
const { rid } = await req('POST', '/v2/account/setup_code', { body: { challenge: c.challenge, params, proofs, idem: b64u(rand(16)) }, signer: device })
|
|
303
|
+
return stageAndActivate({ rid, device, backupId, wrapperId, backupBlob, wrapperBlob, confirmSaved })
|
|
304
|
+
},
|
|
305
|
+
|
|
306
|
+
/** R2-03 — this device's rotation session, by the service's clock: { state, live }. */
|
|
307
|
+
/** R3-01: close this device's code-change session if it can no longer commit (a write that races the commit). */
|
|
308
|
+
rotationClose: (device, rid) => req('POST', `/v2/account/rotation/${rid}/close`, { body: {}, signer: device }),
|
|
309
|
+
/** § 8.8 (release checklist 1.6): this device's sealed push address ({} = none); the signed-out devices' to remove; one done. */
|
|
310
|
+
devicePush: (device, body) => req('POST', '/v2/account/device/push', { body, signer: device }),
|
|
311
|
+
signedOutPush: (device) => req('GET', '/v2/account/devices/signed_out', { signer: device }),
|
|
312
|
+
markPushPruned: (device, target, hash) => req('POST', '/v2/account/devices/push_pruned', { body: { device: target, hash }, signer: device }),
|
|
313
|
+
/** Which of `spks` are still this account's devices → { states: { <spk>: 'active' | 'provisional' | 'revoked' | 'not_ours' } }
|
|
314
|
+
* (a computer paired for Code, in the account's computers list: codeComputers.js signedOutIds). */
|
|
315
|
+
listDevices: (device) => req('GET', '/v2/account/devices', { signer: device }), // the account's devices that count (Your devices)
|
|
316
|
+
deviceStates: (device, spks) => req('POST', '/v2/account/devices/state', { body: { spks }, signer: device }),
|
|
317
|
+
/** § 8.8: an active device's approval of the person's next AWS key (the mint requires it once a sign-out gated it). */
|
|
318
|
+
awsStatement: (device, signPub) => req('POST', '/v2/account/aws_statement', { body: { signPub }, signer: device }),
|
|
319
|
+
/** docs/device-gate-design.md: an active device's ten-minute room pass for its session key → { pass, sig, exp }. */
|
|
320
|
+
roomPass: (device, email, sessionPub) => req('POST', '/v2/account/room_pass', { body: { email, sessionPub }, signer: device }),
|
|
321
|
+
|
|
322
|
+
/** The account's mode and active keys (an active device only). */
|
|
323
|
+
security: (device) => req('GET', '/v2/account/security', { signer: device }),
|
|
324
|
+
|
|
325
|
+
/** § 10.1 / § 10.4 — turn Advanced on (`advanced_on`: every slot the service asks for, two keys) or add a key
|
|
326
|
+
* (`key_add`: one slot, and an existing key proves it at authorise AND at finish). `onStep({ step, slot, of })` tells
|
|
327
|
+
* the screen which key to touch: 'register' a new key, 'confirm' a new key (it proves it works), 'existing' an old one.
|
|
328
|
+
* The finishing transcript is built HERE from what this device knows — never signed as the server hands it. */
|
|
329
|
+
async enrolKeys({ acct, device, address, getCode, keys, purpose = 'advanced_on', onStep = () => {} }) {
|
|
330
|
+
if (!keys) fail('need_security_key')
|
|
331
|
+
const params = { purpose, initiator_spk: device.spk }
|
|
332
|
+
const c = await req('POST', '/v2/account/challenge', { body: { op: 'enrol_authorize', acct, params, ctx: { purpose } } })
|
|
333
|
+
const ticket = await emailProof(c, address, getCode)
|
|
334
|
+
const Ta = T(c, 'enrol_authorize', params)
|
|
335
|
+
const proofs = { device: { spk: device.spk, sig: await sigOf(device, Ta) }, email_authz: ticket, ...(await keyProof(c, Ta, keys)) }
|
|
336
|
+
const { eid, slots } = await req('POST', '/v2/account/enrol_authorize', { body: { challenge: c.challenge, params, proofs, idem: b64u(rand(16)) }, signer: device })
|
|
337
|
+
const made = []
|
|
338
|
+
for (const [i, slot] of slots.entries()) {
|
|
339
|
+
onStep({ step: 'register', slot, index: i, of: slots.length })
|
|
340
|
+
const o = await req('POST', `/v2/account/enrol/${eid}/options`, { body: { slot }, signer: device })
|
|
341
|
+
const att = await keys.create(o.publicKey)
|
|
342
|
+
const r = await req('POST', `/v2/account/enrol/${eid}/register`, { body: { slot, attestation: att }, signer: device })
|
|
343
|
+
made.push({ id: r.credId, transports: att.transports || [] })
|
|
344
|
+
}
|
|
345
|
+
const f = await req('POST', `/v2/account/enrol/${eid}/finish_challenge`, { signer: device })
|
|
346
|
+
const creds = made.map((m) => m.id).sort()
|
|
347
|
+
if (JSON.stringify(f.creds) !== JSON.stringify(creds)) fail('keys_mismatch') // the service must name exactly the keys this device registered
|
|
348
|
+
const Tf = transcript({ op: purpose, acct: c.acct, params: { session: eid, creds }, challenge: eid, nonce: f.nonce, exp: f.exp, pv: c.pv, rg: c.rg, ev: c.ev, epoch: c.epoch })
|
|
349
|
+
const ch = await sha256(Tf)
|
|
350
|
+
const assertions = []
|
|
351
|
+
for (const [i, m] of made.entries()) {
|
|
352
|
+
onStep({ step: 'confirm', index: i, of: made.length })
|
|
353
|
+
assertions.push(await keys.get({ challenge: ch, allow: [m] }))
|
|
354
|
+
}
|
|
355
|
+
if (purpose === 'key_add') {
|
|
356
|
+
onStep({ step: 'existing' })
|
|
357
|
+
assertions.push(await keys.get({ challenge: ch, allow: (f.active || []).filter((k) => !creds.includes(k.id)) }))
|
|
358
|
+
}
|
|
359
|
+
return req('POST', `/v2/account/enrol/${eid}/finish`, { body: { device_sig: await sigOf(device, Tf), assertions, idem: b64u(rand(16)) }, signer: device })
|
|
360
|
+
},
|
|
361
|
+
|
|
362
|
+
/** § 10.4 — remove a key, proved by another one. */
|
|
363
|
+
async removeKey({ acct, device, address, getCode, keys, credId }) {
|
|
364
|
+
const params = { cred_id: credId }
|
|
365
|
+
const c = await req('POST', '/v2/account/challenge', { body: { op: 'key_remove', acct, params } })
|
|
366
|
+
const ticket = await emailProof(c, address, getCode)
|
|
367
|
+
const Tb = T(c, 'key_remove', params)
|
|
368
|
+
const proofs = { device: { spk: device.spk, sig: await sigOf(device, Tb) }, email_authz: ticket, ...(await keyProof(c, Tb, keys, credId)) }
|
|
369
|
+
return req('POST', '/v2/account/key_remove', { body: { challenge: c.challenge, params, proofs, idem: b64u(rand(16)) }, signer: device })
|
|
370
|
+
},
|
|
371
|
+
|
|
372
|
+
/** Turn Advanced off (every key retired). */
|
|
373
|
+
async advancedOff({ acct, device, address, getCode, keys }) {
|
|
374
|
+
const params = {}
|
|
375
|
+
const c = await req('POST', '/v2/account/challenge', { body: { op: 'advanced_off', acct, params } })
|
|
376
|
+
const ticket = await emailProof(c, address, getCode)
|
|
377
|
+
const Tb = T(c, 'advanced_off', params)
|
|
378
|
+
const proofs = { device: { spk: device.spk, sig: await sigOf(device, Tb) }, email_authz: ticket, ...(await keyProof(c, Tb, keys)) }
|
|
379
|
+
return req('POST', '/v2/account/advanced_off', { body: { challenge: c.challenge, params, proofs, idem: b64u(rand(16)) }, signer: device })
|
|
380
|
+
},
|
|
381
|
+
}
|
|
382
|
+
}
|
package/acctV2Keys.js
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
// acctV2Keys.js — the CLIENT's keys for account recovery v2 (docs/account-recovery-protocol.md § 3):
|
|
2
|
+
// the possession key from the recovery code, the backup write key from the master (P-256 from a 48-byte seed, § 3.1 —
|
|
3
|
+
// WebCrypto cannot import a bare private scalar, so the vendored noble P-256 computes the point and signs), and a signer
|
|
4
|
+
// over THIS device's existing non-extractable WebCrypto key (devices.js) — whose raw r‖s signatures become DER here.
|
|
5
|
+
import { p256, sha256 as nobleSha256 } from './noble-p256.js'
|
|
6
|
+
import { rawToDer, b64u, unb64u } from './acctV2Wire.js'
|
|
7
|
+
|
|
8
|
+
const N = 0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551n
|
|
9
|
+
const enc = new TextEncoder()
|
|
10
|
+
const SALT = enc.encode('witbitz-spaces-backup-v1')
|
|
11
|
+
|
|
12
|
+
export async function hkdf(ikm, info, n) {
|
|
13
|
+
const k = await crypto.subtle.importKey('raw', ikm, 'HKDF', false, ['deriveBits'])
|
|
14
|
+
return new Uint8Array(await crypto.subtle.deriveBits({ name: 'HKDF', hash: 'SHA-256', salt: SALT, info: enc.encode(info) }, k, n * 8))
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** § 3.1 — a P-256 key from a 48-byte seed: { d (bigint), pub (65 bytes), sign(bytes) → DER } */
|
|
18
|
+
export function p256FromSeed(seed) {
|
|
19
|
+
if (!seed || seed.length !== 48) throw new Error('p256FromSeed: the seed must be 48 bytes')
|
|
20
|
+
let x = 0n
|
|
21
|
+
for (const b of seed) x = (x << 8n) | BigInt(b)
|
|
22
|
+
const d = (x % (N - 1n)) + 1n
|
|
23
|
+
const dBytes = new Uint8Array(32)
|
|
24
|
+
for (let i = 31, t = d; i >= 0; i--, t >>= 8n) dBytes[i] = Number(t & 0xffn)
|
|
25
|
+
const pub = p256.getPublicKey(dBytes, false)
|
|
26
|
+
// no private scalar on the returned object: a key that is logged or serialised must not carry it
|
|
27
|
+
return { pub, spk: b64u(pub), sign: (bytes) => p256.sign(nobleSha256(bytes), dBytes).toDERRawBytes() }
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export const possessionKey = async (codeBytes) => p256FromSeed(await hkdf(codeBytes, 'possession-key-v1', 48))
|
|
31
|
+
export const backupWriteKey = async (master) => p256FromSeed(await hkdf(master, 'backup-write-key-v1', 48))
|
|
32
|
+
export const gateValues = async (codeBytes) => ({ gid: Array.from(await hkdf(codeBytes, 'gate-id', 16), (b) => b.toString(16).padStart(2, '0')).join(''), gk: await hkdf(codeBytes, 'gate-commit', 32) })
|
|
33
|
+
|
|
34
|
+
/** A signer over a WebCrypto ECDSA P-256 key pair (the device key: devices.js keeps it non-extractable in IndexedDB). */
|
|
35
|
+
/** The device key as the app stores it (devices.js: a non-extractable private key + `spk`, the public point in base64url):
|
|
36
|
+
* older records carry no usable public CryptoKey, so the signer is built from the stored bytes. */
|
|
37
|
+
export function webCryptoSignerFromSpk(privateKey, spk) {
|
|
38
|
+
return { pub: unb64u(spk), spk, sign: async (bytes) => rawToDer(new Uint8Array(await crypto.subtle.sign({ name: 'ECDSA', hash: 'SHA-256' }, privateKey, bytes))) }
|
|
39
|
+
}
|
|
40
|
+
export async function webCryptoSigner(privateKey, publicKey) {
|
|
41
|
+
const pub = new Uint8Array(await crypto.subtle.exportKey('raw', publicKey))
|
|
42
|
+
return { pub, spk: b64u(pub), sign: async (bytes) => rawToDer(new Uint8Array(await crypto.subtle.sign({ name: 'ECDSA', hash: 'SHA-256' }, privateKey, bytes))) }
|
|
43
|
+
}
|
package/acctV2Legacy.js
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
// acctV2Legacy.js — the transcript a move from today's service signs (docs/account-recovery-protocol.md § 12.2): the attempt
|
|
2
|
+
// is the challenge, and the new account's counters are all 0. The same bytes as the service's legacyTranscript
|
|
3
|
+
// (control-plane/src/lib/acct/legacy.mjs); spaces/test/acctV2App.test.mjs holds them equal.
|
|
4
|
+
import { transcript } from './acctV2Wire.js'
|
|
5
|
+
|
|
6
|
+
export const transcriptForLegacy = (m, attempt, params) => transcript({ op: 'legacy_commit', acct: m.acct, params, challenge: attempt, nonce: m.nonce, exp: m.exp, pv: 0, rg: 0, ev: 0, epoch: 0 })
|
|
7
|
+
|
|
8
|
+
/** The silent JOIN's transcript (legacySilent.mjs joinTranscript): the join is the challenge, the account's counters as its
|
|
9
|
+
* intent answered them. spaces/test/acctV2App.test.mjs holds the bytes equal to the service's. */
|
|
10
|
+
export const transcriptForJoin = (j, attempt, params) => transcript({ op: 'legacy_join', acct: j.acct, params, challenge: attempt, nonce: j.nonce, exp: j.exp, pv: j.pv, rg: j.rg, ev: j.ev, epoch: j.epoch })
|
|
11
|
+
/** The account key's authorisation of a silent move, before anything is locked (legacySilent.mjs silentTranscript). */
|
|
12
|
+
export const transcriptForSilent = (m, attempt, deviceSpk) => transcript({ op: 'legacy_silent', acct: m.acct, params: { device_spk: deviceSpk }, challenge: attempt, nonce: m.nonce, exp: m.exp, pv: 0, rg: 0, ev: 0, epoch: 0 })
|
|
13
|
+
/** The account key's ask for a join (legacySilent.mjs joinAskTranscript): only a holder of the account key gets a challenge. */
|
|
14
|
+
export const transcriptForJoinAsk = ({ gid, deviceSpk, ts }) => transcript({ op: 'legacy_join_ask', acct: '', params: { gid, device_spk: deviceSpk, ts }, challenge: gid, nonce: '', exp: ts, pv: 0, rg: 0, ev: 0, epoch: 0 })
|
package/acctV2Switch.js
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
// acctV2Switch.js — the device switch for account recovery v2 (acctV2Wiring.js): `space:acctv2:base` names the v2 service;
|
|
2
|
+
// unset, everything v2 is off. It can only point at one of the TWO services below — never at an address a link names — and
|
|
3
|
+
// each only on its own app:
|
|
4
|
+
// - the STAGING app (preview.witbitz-spaces.pages.dev, which talks to the staging servers): ON by default; ?acctv2=off
|
|
5
|
+
// switches it off for this device, ?acctv2=staging back on.
|
|
6
|
+
// - the PRODUCTION regular app (witbitz-spaces.pages.dev): OFF unless a device is switched on with ?acctv2=prod — the
|
|
7
|
+
// owner-only preview for release checklist 1.10 (real devices against production), never on by default; ?acctv2=off
|
|
8
|
+
// switches it off again. In the hosted app the client runs in its VAULT (below), never in app.witbitz.chat's page.
|
|
9
|
+
// (The release switch below has since made new accounts start on the service by default.)
|
|
10
|
+
export const BASE_KEY = 'space:acctv2:base'
|
|
11
|
+
export const STAGING_APP = 'preview.witbitz-spaces.pages.dev'
|
|
12
|
+
export const STAGING_SERVICE = 'https://wvevotytx5.execute-api.eu-central-1.amazonaws.com'
|
|
13
|
+
export const PROD_APP = 'witbitz-spaces.pages.dev'
|
|
14
|
+
// the API domain the production app's CSP already allows (api.witbitz.chat/v1 → the production /v1 API; the gateway strips
|
|
15
|
+
// the /v1, so the service sees, and the device signs, the bare /v2/account/... path)
|
|
16
|
+
export const PROD_SERVICE = 'https://api.witbitz.chat/v1'
|
|
17
|
+
// THE HOSTED APP'S VAULTS (docs/hosted-account-v2-plan.md; owner, 2026-11-15: "before deploy do the vault app with the new
|
|
18
|
+
// backup"): in the hosted app the VAULT holds the master, so the client runs there — never in the app page it frames
|
|
19
|
+
// (app.witbitz.chat stays off: no entry here). The production vault talks to the production service at the same API domain
|
|
20
|
+
// its CSP already allows; the staging vault (it frames the staging app) to the staging service.
|
|
21
|
+
export const PROD_VAULT = 'spaces.witbitz.chat'
|
|
22
|
+
export const STAGING_VAULT = 'vault.witbitz-spaces.pages.dev'
|
|
23
|
+
const SERVICE_OF = { [STAGING_APP]: STAGING_SERVICE, [PROD_APP]: PROD_SERVICE, [STAGING_VAULT]: STAGING_SERVICE, [PROD_VAULT]: PROD_SERVICE }
|
|
24
|
+
|
|
25
|
+
export function stagingSwitch(loc = globalThis.location, storage = globalThis.localStorage) {
|
|
26
|
+
try {
|
|
27
|
+
if (!loc || (loc.hostname !== STAGING_APP && loc.hostname !== STAGING_VAULT)) return
|
|
28
|
+
const v = new URLSearchParams(loc.search).get('acctv2')
|
|
29
|
+
if (v === 'staging') storage.setItem(BASE_KEY, STAGING_SERVICE)
|
|
30
|
+
else if (v === 'off') storage.setItem(BASE_KEY, 'off') // remembered: the default below does not turn it back on
|
|
31
|
+
// ON BY DEFAULT on the staging app: an installed iPhone app keeps storage apart from Safari, so a link cannot switch it
|
|
32
|
+
else if (storage.getItem(BASE_KEY) == null) storage.setItem(BASE_KEY, STAGING_SERVICE)
|
|
33
|
+
} catch { /* no storage */ }
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** The production preview: only `?acctv2=prod` switches a device on, `?acctv2=off` off; nothing else, no default. */
|
|
37
|
+
export function prodSwitch(loc = globalThis.location, storage = globalThis.localStorage) {
|
|
38
|
+
try {
|
|
39
|
+
if (!loc || loc.hostname !== PROD_APP) return
|
|
40
|
+
const v = new URLSearchParams(loc.search).get('acctv2')
|
|
41
|
+
if (v === 'prod') storage.setItem(BASE_KEY, PROD_SERVICE)
|
|
42
|
+
else if (v === 'off') storage.setItem(BASE_KEY, 'off')
|
|
43
|
+
} catch { /* no storage */ }
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
// THE RELEASE SWITCH FOR NEW ACCOUNTS (account recovery v2, Release 1): ON since Official v247 (owner, 2026-11-15: "Now").
|
|
47
|
+
// A NEW account made on the production regular app starts on the new service — the normal "Turn on backup"
|
|
48
|
+
// (recoverySheet.js turnOnBackup), same screens — and the normal Restore asks the new service first (acctV2Ui.restoreFromCode).
|
|
49
|
+
// Accounts on the old service stay there (migration is Release 3). Off again = a release with false here; accounts already
|
|
50
|
+
// made on the new service stay on it.
|
|
51
|
+
export const NEW_ACCOUNTS_ON_V2 = true
|
|
52
|
+
/** Where a NEW account made here starts: the new service's address, or '' (the old service, as before). The production
|
|
53
|
+
* regular app and the production vault (the hosted app's v2 client runs there — acctV2VaultWiring.js); the staging app keeps
|
|
54
|
+
* its preview card as the way in. A device switched off (?acctv2=off) stays off. */
|
|
55
|
+
export function newAccountService({ host, stored, releaseOn = NEW_ACCOUNTS_ON_V2 }) {
|
|
56
|
+
if (host === PROD_VAULT && stored !== 'off') return releaseOn ? PROD_SERVICE : '' // the hosted app: its vault
|
|
57
|
+
if (host !== PROD_APP || stored === 'off') return ''
|
|
58
|
+
if (stored === PROD_SERVICE) return PROD_SERVICE
|
|
59
|
+
return releaseOn ? PROD_SERVICE : ''
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
// RELEASE 3 — AN OLD ACCOUNT MOVES (protocol § 12.2; owner, 2026-11-15: "Let's just add a button in settings that lets you
|
|
63
|
+
// migrate if you are on the old backup"): Settings → "Move to the new account service" (acctV2UiCore.js). It is offered only
|
|
64
|
+
// where the SERVICE accepts moves — its own switch (ACCT_FEATURES `migration`; off = `501 feature_unavailable`), which the
|
|
65
|
+
// button asks first (acctV2UiCore.moveOpen) — so no release of the app is needed to open or close it. Never automatic.
|
|
66
|
+
/** The service an account still on the old service would move to from this app, or '': the production regular app and the
|
|
67
|
+
* production vault (the staging apps have no old service). A device switched off (?acctv2=off) stays off. */
|
|
68
|
+
export function moveService({ host, stored }) {
|
|
69
|
+
if (stored === 'off') return ''
|
|
70
|
+
return host === PROD_APP || host === PROD_VAULT ? PROD_SERVICE : ''
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** The service address the switch holds, or '' (off). With `host`, only that app's own service counts. */
|
|
74
|
+
export const baseOf = (v, host) => {
|
|
75
|
+
if (!v || v === 'off') return ''
|
|
76
|
+
// the local test harness (spaces/test/acctV2Ui.test.mjs): a page on a loopback host may use a service on that same host
|
|
77
|
+
if (host === '127.0.0.1' || host === 'localhost') { try { return new URL(v).hostname === host ? v : '' } catch { return '' } }
|
|
78
|
+
if (host !== undefined) return SERVICE_OF[host] === v ? v : ''
|
|
79
|
+
return v === STAGING_SERVICE || v === PROD_SERVICE ? v : ''
|
|
80
|
+
}
|