@witbitz/sdk 0.0.0-stage → 4.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +20 -2
- package/a2aCore.js +221 -0
- package/a2aShared.js +27 -0
- package/accountErase.js +228 -0
- package/accountIndexDoc.js +122 -0
- package/accountOwner.js +59 -0
- package/accountRecord.js +90 -0
- package/accountScope.js +114 -0
- package/accountSeal.js +42 -0
- package/accountStores.js +173 -0
- package/acctV2App.js +619 -0
- package/acctV2Check.js +29 -0
- package/acctV2Client.js +382 -0
- package/acctV2Keys.js +43 -0
- package/acctV2Legacy.js +14 -0
- package/acctV2Switch.js +80 -0
- package/acctV2UiCore.js +857 -0
- package/acctV2WebAuthn.js +61 -0
- package/acctV2Wire.js +59 -0
- package/address.js +42 -0
- package/agentDoorTools.js +28 -0
- package/attestedBox.js +30 -0
- package/attestedRooms.js +78 -0
- package/awsKey.js +98 -0
- package/backupRecord.js +106 -0
- package/backupVault.js +97 -0
- package/blocks.js +115 -0
- package/blocksPush.js +64 -0
- package/browseSeal.js +103 -0
- package/cbor.js +225 -0
- package/changePush.js +75 -0
- package/chatLock.js +165 -0
- package/chatLockSw.js +13 -0
- package/cloudDeviceBuilds.js +11 -0
- package/cloudDevicePins.js +33 -0
- package/cloudDeviceSeal.js +53 -0
- package/codeAttachments.js +100 -0
- package/codeBrowse.js +224 -0
- package/codeCache.js +149 -0
- package/codeCloud.js +650 -0
- package/codeCloudKeys.js +112 -0
- package/codeCommands.js +167 -0
- package/codeComputers.js +389 -0
- package/codeEgress.js +123 -0
- package/codeFilesRoutes.js +17 -0
- package/codeFolders.js +116 -0
- package/codeHistory.js +76 -0
- package/codeLanguage.js +54 -0
- package/codeMkdir.js +8 -0
- package/codeModes.js +59 -0
- package/codeOrphanKeys.js +42 -0
- package/codeOutputs.js +141 -0
- package/codeProgress.js +54 -0
- package/codeRelay.js +505 -0
- package/codeSent.js +68 -0
- package/codeSentinel.js +86 -0
- package/codeSubagents.js +107 -0
- package/codeTransport.js +317 -0
- package/codeUndo.js +48 -0
- package/compress.js +24 -0
- package/config.js +11 -0
- package/connCatalog.js +164 -0
- package/connDisp.js +76 -0
- package/connOtherWays.js +74 -0
- package/connPending.js +16 -0
- package/connWrap.js +53 -0
- package/connectionEntry.js +89 -0
- package/connections.js +561 -0
- package/credits.js +30 -0
- package/csAttest.js +112 -0
- package/decrypt.html +384 -0
- package/deviceAttest.js +527 -0
- package/deviceCall.js +54 -0
- package/deviceKeyCore.js +41 -0
- package/deviceSeal.js +59 -0
- package/e2ee.js +323 -0
- package/eat.js +103 -0
- package/emailFork.js +275 -0
- package/emailSignIn.js +81 -0
- package/emptySpaces.js +111 -0
- package/encSource.js +55 -0
- package/enclaveAccept.js +214 -0
- package/enclaveClaim.js +241 -0
- package/enclaveRoute.js +102 -0
- package/enclaveSnapshotMerge.js +44 -0
- package/entrySig.js +165 -0
- package/env.js +73 -0
- package/eraseFile.js +58 -0
- package/followImage.js +86 -0
- package/healNames.js +45 -0
- package/idb.js +113 -0
- package/idbSeal.js +119 -0
- package/indexGone.js +12 -0
- package/invite.js +51 -0
- package/inviteEnroll.js +67 -0
- package/inviteSend.js +68 -0
- package/jobAgents.js +87 -0
- package/keptMerge.js +91 -0
- package/l1-worker-src.js +2 -0
- package/l1-worker.js +894 -0
- package/laneAssociation.js +68 -0
- package/laneConfig.js +58 -0
- package/laneLinkCore.js +177 -0
- package/ledgerView.js +64 -0
- package/manifest.json +239 -0
- package/mcpRecommended.js +25 -0
- package/memberChange.js +125 -0
- package/mirrorBatch.js +47 -0
- package/mkseal.js +101 -0
- package/nativePush.js +153 -0
- package/nitroVerify.js +220 -0
- package/noble-p256.js +27 -0
- package/notice.js +116 -0
- package/notifKey.js +58 -0
- package/offlineBundle.js +62 -0
- package/ohttp.js +177 -0
- package/opRouting.js +10 -0
- package/opencodeWire.js +282 -0
- package/oprf.js +70 -0
- package/ownAgentLink.js +96 -0
- package/ownerPolicy.js +117 -0
- package/package.json +273 -4
- package/pdfOptions.js +13 -0
- package/pdfText.js +107 -0
- package/pdfjs.mjs +28 -0
- package/pdfjs.worker.mjs +28 -0
- package/pollVerdict.js +33 -0
- package/prefetchPoll.js +60 -0
- package/protectedLocal.js +426 -0
- package/pushCore.js +42 -0
- package/recovery.js +107 -0
- package/regions.js +42 -0
- package/removedMessage.js +11 -0
- package/renameRefusal.js +9 -0
- package/replyQuote.js +34 -0
- package/reqEnvelope.js +126 -0
- package/roomDefaultPrefs.js +76 -0
- package/roomDelete.js +109 -0
- package/roomEmbed.js +111 -0
- package/roomName.js +177 -0
- package/roomPass.js +256 -0
- package/roomRoster.js +305 -0
- package/roomSettings.js +61 -0
- package/roomState.js +58 -0
- package/roomStreamClient.js +115 -0
- package/rosterCount.js +52 -0
- package/rosterHash.js +13 -0
- package/rowSchema.js +113 -0
- package/safeMedia.js +116 -0
- package/safeMediaPins.js +17 -0
- package/schedulesDoc.js +78 -0
- package/sdkA2A.js +524 -0
- package/sdkAccount.js +483 -0
- package/sdkAccountDoc.js +89 -0
- package/sdkAccountSections.js +332 -0
- package/sdkAgui.js +141 -0
- package/sdkAttest.js +34 -0
- package/sdkBackup.js +507 -0
- package/sdkBackupV2.js +630 -0
- package/sdkBrowserPrivate.js +28 -0
- package/sdkBuilds.js +208 -0
- package/sdkCloudDevice.js +221 -0
- package/sdkComputers.js +1009 -0
- package/sdkDictation.js +232 -0
- package/sdkErase.js +288 -0
- package/sdkExports.js +71 -0
- package/sdkInvitations.js +34 -0
- package/sdkKeptAgent.js +188 -0
- package/sdkLaneLink.js +205 -0
- package/sdkPlan.js +96 -0
- package/sdkProtect.js +228 -0
- package/sdkRedact.js +36 -0
- package/sdkRekey.js +340 -0
- package/sdkReport.js +68 -0
- package/sdkSafeMedia.js +255 -0
- package/sdkSchedules.js +39 -0
- package/sdkSpeech.js +71 -0
- package/sdkTemporaryRooms.js +123 -0
- package/sdkTurn.js +117 -0
- package/sdkVault.js +180 -0
- package/sealShare.js +18 -0
- package/sealedNames.js +64 -0
- package/sealedReceipt.js +17 -0
- package/sentinelRelease.js +155 -0
- package/shamir.js +85 -0
- package/sharedViews.js +52 -0
- package/sheetChrome.js +450 -0
- package/siri.js +278 -0
- package/spaceClient.js +1429 -0
- package/spaceConfig.js +81 -0
- package/spaceEmailGate.js +813 -0
- package/spaceExport.js +125 -0
- package/spaceFork.js +216 -0
- package/spaceLock.js +358 -0
- package/spacePasskey.js +180 -0
- package/spaceTemplates.js +99 -0
- package/speechOut.js +102 -0
- package/splitKeyClient.js +90 -0
- package/store.js +656 -0
- package/streamHint.js +36 -0
- package/sttCloud.js +220 -0
- package/sttWorklet.js +38 -0
- package/sw-notif-core.js +540 -0
- package/tempList.js +48 -0
- package/tinfoilVerifier.js +78 -0
- package/toolBooks.js +31 -0
- package/toolRules.js +52 -0
- package/turnCerts.js +254 -0
- package/turnFeed.js +58 -0
- package/turnVerdict.js +37 -0
- package/usageReceipts.js +176 -0
- package/usageSummary.js +90 -0
- package/util.js +181 -0
- package/vault-core.js +2326 -0
- package/vault-kit.mjs +354 -0
- package/vault-screens.js +261 -0
- package/vaultAtRest.js +208 -0
- package/vaultCoreLock.js +111 -0
- package/vaultCorePush.js +140 -0
- package/vaultDeviceKey.js +95 -0
- package/vaultEnclaveHandoff.js +114 -0
- package/vaultKeep.js +287 -0
- package/vaultSealedStore.js +77 -0
- package/vaultWorkerHost.js +117 -0
- package/vcWorker.js +34 -0
- package/voiceAttest.js +50 -0
- package/voiceCert.js +51 -0
- package/witbitz-admin.d.ts +135 -0
- package/witbitz-admin.js +529 -0
- package/witbitz-admin.mjs +1460 -0
- package/witbitz-sdk.d.ts +1197 -0
- package/witbitz-sdk.js +4258 -0
- package/workerClient.js +16 -0
- package/workerLiveness.js +21 -0
- package/x509.js +218 -0
package/sdkBackup.js
ADDED
|
@@ -0,0 +1,507 @@
|
|
|
1
|
+
import { associationTime } from './laneAssociation.js'
|
|
2
|
+
// spaces/public/sdkBackup.js — `wb.backup`: the ACCOUNT BACKUP for a builder's app, on the SAME vault our own app uses
|
|
3
|
+
// (2026-10-02, a builder: "a short recovery code instead of the restore link"; the owner: "why not use our account
|
|
4
|
+
// structure?"). Nothing new is invented here — it is the existing vault, reached from the SDK:
|
|
5
|
+
//
|
|
6
|
+
// • backupVault.js: a random 32-byte MASTER SECRET seals the backup; each recovery method stores a WRAPPER of it.
|
|
7
|
+
// Here the method is a RECOVERY CODE (recovery.js: 16 random bytes, typed as 44YW-572I-…).
|
|
8
|
+
// • the store is `/v1/vault/*` (api.witbitz.chat) — content-blind: ids derived from the secrets, ciphertext only.
|
|
9
|
+
// • a SPLIT room (https://witbitz.chat/docs/sdk-keys.md#split-key) is recorded with its assembled key as well as its half-key link (§3.4).
|
|
10
|
+
// • the 2-of-2 recovery gate (design A): with an email, the gate record commits to it (an HMAC keyed by the code, so
|
|
11
|
+
// the server can neither read nor guess the address). When the server enforces the gate, a restore needs the code
|
|
12
|
+
// AND an emailed code (ENFORCE_GATE is on in every home since 2026-10-06); where it is off, the code alone restores. restore() handles both.
|
|
13
|
+
//
|
|
14
|
+
// SEPARATE PER APP, for free: each enable() mints its own master secret and code, so a builder's users get their own
|
|
15
|
+
// vault — it never mixes with the Witbitz app's, and one app's restore never touches another's. The writing origin is
|
|
16
|
+
// recorded beside the blob by the server (attribution, never permission).
|
|
17
|
+
//
|
|
18
|
+
// What the backup HOLDS: the rooms this client created or opened — each one's link (which carries its key), label, and
|
|
19
|
+
// for a lane, the Space it belongs to — enough for restore() to hand them back to openSpace / openLane.
|
|
20
|
+
// ⚑ The STATE (`wb.backup.state`) holds the master secret: persist it like the room links it protects, never send it.
|
|
21
|
+
import { newRecoveryCode, codeSecret, gateParams, emailCommit, seal, unseal } from './recovery.js'
|
|
22
|
+
import { recordFromRooms, roomsOfRecord, roomPin, tombOfRecord, keyInLink, vaultOwner, LEGACY_SDK_KIND, SDK_APP } from './accountRecord.js' // one account record for the app and the SDK; this module's original is LEGACY
|
|
23
|
+
import { applyPlan } from './backupRecord.js' // the Spaces app's restore rules, pure (docs/sdk-account-format-plan.md phase 1)
|
|
24
|
+
import { normUsageKey } from './usageReceipts.js'
|
|
25
|
+
import { indexRoomOf, mergeIndex } from './sdkAccount.js' // the account's derived index room — published in the record as the app's `indexRoom` pointer
|
|
26
|
+
import { newMasterSecret, backupLocation, wrapperLocation, enrollCredential, openWrapper } from './backupVault.js'
|
|
27
|
+
|
|
28
|
+
export const DEFAULT_VAULT_API = 'https://api.witbitz.chat/v1/vault'
|
|
29
|
+
const KIND = LEGACY_SDK_KIND
|
|
30
|
+
const MAX_ROOMS = 500
|
|
31
|
+
|
|
32
|
+
const b64 = (u8) => { let s = ''; for (let i = 0; i < u8.length; i++) s += String.fromCharCode(u8[i]); return btoa(s) }
|
|
33
|
+
const ub64 = (s) => { const b = atob(s); const u = new Uint8Array(b.length); for (let i = 0; i < b.length; i++) u[i] = b.charCodeAt(i); return u }
|
|
34
|
+
const fail = (code, msg, extra = {}) => Object.assign(new Error('witbitz: ' + msg), { code, ...extra })
|
|
35
|
+
const is32 = (s) => { try { return typeof s === 'string' && ub64(s).length === 32 } catch { return false } }
|
|
36
|
+
|
|
37
|
+
// ── THE NEW ACCOUNT SERVICE (sdkBackupV2.js; the owner, 2026-11-16: "Yes. Do the sdk."): a builder's VAULT that names its tenant
|
|
38
|
+
// installs it (`backup._v2`) and NEW accounts start there; a state with `v2` is an account there. Its parts, as they may be kept:
|
|
39
|
+
// `svc` the service's record (acctV2App.js STATE_KEY: the account id, the service, the address), `bm` the BACKUP master (the
|
|
40
|
+
// service's objects are sealed under it; a new recovery code replaces it — `master` stays the account's identity), `pending` a
|
|
41
|
+
// new code's master kept before its activation, `dk` which of the vault's device keys is this account's, `checked` the last
|
|
42
|
+
// status answer, `pb` the PREVIOUS backup masters (≤ 3, ≤ 30 days: a signed-out device's push address was sealed under the
|
|
43
|
+
// master of its day — Codex sweep 2026-11-16 #1, as our vault's prevMasters). Anything else is dropped.
|
|
44
|
+
export function v2Of(x) {
|
|
45
|
+
if (!x || typeof x !== 'object' || Array.isArray(x)) return null
|
|
46
|
+
const o = {}
|
|
47
|
+
const sv = x.svc
|
|
48
|
+
if (sv && typeof sv === 'object' && typeof sv.acct === 'string' && sv.acct && sv.acct.length <= 200) {
|
|
49
|
+
o.svc = { acct: sv.acct, base: String(sv.base || '').slice(0, 300), at: Number(sv.at) || 0, trust: sv.trust == null ? null : String(sv.trust).slice(0, 40),
|
|
50
|
+
...(sv.setup === 'pending' ? { setup: 'pending' } : {}), ...(typeof sv.address === 'string' && sv.address ? { address: sv.address.slice(0, 254) } : {}) }
|
|
51
|
+
}
|
|
52
|
+
if (is32(x.bm)) o.bm = x.bm
|
|
53
|
+
if (x.pending && is32(x.pending.master)) o.pending = { master: x.pending.master, rid: typeof x.pending.rid === 'string' ? x.pending.rid.slice(0, 200) : null, at: Number(x.pending.at) || 0 }
|
|
54
|
+
if (typeof x.dk === 'string' && /^[A-Za-z0-9]{8,32}$/.test(x.dk)) o.dk = x.dk
|
|
55
|
+
if (Number.isFinite(x.checked) && x.checked > 0) o.checked = x.checked
|
|
56
|
+
if (typeof x.erase === 'string' && x.erase.length <= 32768) o.erase = x.erase
|
|
57
|
+
if (x.moving === true) { o.moving = true; if (x.moveMode === 'signed') o.moveMode = 'signed' }
|
|
58
|
+
if (x.resetDraft === true) o.resetDraft = true
|
|
59
|
+
if (typeof x.reset === 'string' && x.reset.length <= 4096) o.reset = x.reset
|
|
60
|
+
if (typeof x.emailMove === 'string' && x.emailMove.length <= 4096) o.emailMove = x.emailMove
|
|
61
|
+
const pb = keptPrevMasters(x.pb)
|
|
62
|
+
if (pb.length) o.pb = pb
|
|
63
|
+
return o
|
|
64
|
+
}
|
|
65
|
+
/** The previous backup masters still worth trying: ≤ 3, newest first, ≤ 30 days old (acctV2VaultWiring.js keptMasters). */
|
|
66
|
+
export const keptPrevMasters = (list, now = Date.now()) => (Array.isArray(list) ? list : []).filter((x) => x && is32(x.m) && Number(x.at) > 0 && now - Number(x.at) < 30 * 86400000).slice(0, 3).map((x) => ({ m: x.m, at: Number(x.at) }))
|
|
67
|
+
/** An account made on the service whose first recovery code is not active (or not adopted) here yet: kept, never "enabled" — the
|
|
68
|
+
* next enable() finishes it (an address with an account and no code could not start again). */
|
|
69
|
+
export const halfMade = (s) => !!(s && s.v2 && (s.v2.resetDraft || !s.v2.bm || (s.v2.svc && s.v2.svc.setup === 'pending')))
|
|
70
|
+
const notOnService = () => fail('not_on_service', 'this call is for an account on the Witbitz account service, in a vault that names its tenant (wb.backup.service === \'account\')')
|
|
71
|
+
|
|
72
|
+
/** One room as the backup records it. `link` carries the room key (the fragment), so the whole list is sealed. */
|
|
73
|
+
const roomOf = (r) => (r && typeof r === 'object' && typeof r.room === 'string' && r.room && typeof r.link === 'string' && r.link
|
|
74
|
+
? { room: r.room.slice(0, 120), ...roomPin(r), ...(typeof r.mintedFor === 'string' && r.mintedFor ? { mintedFor: r.mintedFor } : r.laneOrigin === 'minted' && r.shared ? { mintedFor: r.shared } : {}), ...(r.laneOrigin === 'minted' && !r.detachedLane ? { laneOrigin: 'minted' } : {}), ...(Number(r.associationAt) > 0 ? { associationAt: Number(r.associationAt) } : {}), ...(typeof r.renamed === 'boolean' ? { renamed: r.renamed } : {}), ...(Number.isFinite(r.at) && r.at > 0 ? { at: r.at } : {}), ...(r.archived ? { archived: true } : {}), ...(r.detachedLane ? { detachedLane: true } : {}), link: r.link.slice(0, 4000), kind: !r.detachedLane && r.kind === 'lane' ? 'lane' : 'space', ...(r.label ? { label: String(r.label).slice(0, 120) } : {}), ...(!r.detachedLane && r.kind === 'lane' && r.shared ? { shared: String(r.shared).slice(0, 120) } : {}), ...(typeof r.mk === 'string' && r.mk && r.mk.length <= 200 ? { mk: r.mk } : {}) }
|
|
75
|
+
: null)
|
|
76
|
+
|
|
77
|
+
function stateOf(x) {
|
|
78
|
+
const o = x && typeof x === 'object' ? x : null
|
|
79
|
+
if (!o || typeof o.master !== 'string') return null
|
|
80
|
+
try { if (ub64(o.master).length !== 32) return null } catch { return null }
|
|
81
|
+
// `tomb` + `device` belong to the LIVE index (sdkAccount.js): a forgotten room's tombstone, and this device's id in the account.
|
|
82
|
+
const tomb = (Array.isArray(o.tomb) ? o.tomb : []).filter((t) => t && typeof t.room === 'string' && Number.isFinite(t.at)).map((t) => ({ room: t.room.slice(0, 120), at: t.at })).slice(-500)
|
|
83
|
+
const device = o.device && typeof o.device.id === 'string' ? { id: o.device.id.slice(0, 40), name: String(o.device.name || '').slice(0, 80), ...(o.device.made ? { made: true } : {}) } : null
|
|
84
|
+
const links = (Array.isArray(o.links) ? o.links : []).filter((l) => l && typeof l.a === 'string' && typeof l.b === 'string' && Number.isFinite(l.at)).map((l) => ({ a: l.a.slice(0, 120), b: l.b.slice(0, 120), at: l.at, ...(Number.isFinite(l.cap) ? { cap: l.cap } : {}), ...(l.removed ? { removed: true } : {}) })).slice(-200)
|
|
85
|
+
// `outs`: sign-outs of OTHER devices this device made, kept until the index carries them (sdkAccount.js signOut; pass 6, K#7)
|
|
86
|
+
const outs = o.outs && typeof o.outs === 'object' ? Object.fromEntries(Object.entries(o.outs).filter(([id, at]) => typeof id === 'string' && id.length <= 40 && Number.isFinite(at)).slice(-50)) : {}
|
|
87
|
+
return { v: 1, ...(Number.isSafeInteger(o.chatLockMarkPending) && o.chatLockMarkPending > 0 ? { chatLockMarkPending: o.chatLockMarkPending } : {}), ...(o.format === 'account' ? { format: 'account' } : {}), ...(Object.keys(outs).length ? { outs } : {}), master: o.master, ...(typeof o.savedVersion === 'string' && o.savedVersion.length <= 200 ? { savedVersion: o.savedVersion } : {}), rooms: (Array.isArray(o.rooms) ? o.rooms : []).map(roomOf).filter(Boolean).slice(0, MAX_ROOMS), ...(tomb.length ? { tomb } : {}), ...(links.length ? { links } : {}), ...(device ? { device } : {}), ...(o.email ? { email: String(o.email) } : {}), ...(inviteOf(o.invite) ? { invite: inviteOf(o.invite) } : {}), ...(normUsageKey(o.usage) ? { usage: normUsageKey(o.usage) } : {}), ...(usageOldOf(o.usageOld).length ? { usageOld: usageOldOf(o.usageOld) } : {}), ...(o.erased ? { erased: true } : {}), ...(v2Of(o.v2) ? { v2: v2Of(o.v2) } : {}) }
|
|
88
|
+
}
|
|
89
|
+
// the account's USAGE key (usageReceipts.js; the owner, 2026-10-23: a builder's app records the account's usage too) and the
|
|
90
|
+
// ones it replaced — kept in step between the devices by the live index (sdkAccount.js)
|
|
91
|
+
const usageOldOf = (a) => (Array.isArray(a) ? a.map(normUsageKey).filter(Boolean).slice(-5) : [])
|
|
92
|
+
// the account's invite key for this app (sdkRekey.js): kept as it was given, bounded
|
|
93
|
+
const inviteOf = (x) => (x && typeof x === 'object' && x.boxPub && x.boxPriv && typeof x.inbox === 'string' && JSON.stringify(x).length < 4000 ? JSON.parse(JSON.stringify(x)) : null)
|
|
94
|
+
|
|
95
|
+
export class AccountBackup {
|
|
96
|
+
/** @param {object} o { fetch, base?, state?, email?: () => string } — `email` answers the signed-in address, if any. */
|
|
97
|
+
constructor({ fetch: fetchImpl, base = DEFAULT_VAULT_API, state = null, email = () => '', tenant = '' } = {}) {
|
|
98
|
+
this._fetch = fetchImpl
|
|
99
|
+
this._base = String(base || DEFAULT_VAULT_API).replace(/\/+$/, '')
|
|
100
|
+
this._s = stateOf(state)
|
|
101
|
+
this._email = email
|
|
102
|
+
this._tenant = tenant
|
|
103
|
+
/** Called with the new state whenever it changes (a room added, a restore) — persist it there. */
|
|
104
|
+
this.onState = null
|
|
105
|
+
this._timer = null
|
|
106
|
+
this._v2 = null // the new account service (sdkBackupV2.js accountService), installed by a builder's vault
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** JSON-safe state to persist (it holds the master secret), or null while no backup is set up. */
|
|
110
|
+
get state() { return this._s && !this._isEnabling() ? JSON.parse(JSON.stringify(this._s)) : null }
|
|
111
|
+
get enabled() { return !!this._s && !this._isEnabling() && !halfMade(this._s) }
|
|
112
|
+
/** Where this account is kept: 'account' (the Witbitz account service — new accounts in a vault that names its tenant),
|
|
113
|
+
* 'legacy' (the backup store every account used before), or null (no backup on this client). */
|
|
114
|
+
get service() { return this._s && !this._isEnabling() ? (this._s.v2 && !(this._s.v2.moving && !this._s.v2.svc) ? 'account' : 'legacy') : null }
|
|
115
|
+
/** @private ENABLING (pass 6, K#4): enable() is between its first await and its answer. The state exists (a Space opened
|
|
116
|
+
* meanwhile is queued in it) but is handed to nobody — not the app (onState), not the live index — until the vault copy,
|
|
117
|
+
* the recovery code and the gate are all saved. A failed enable then leaves nothing behind that reads "enabled". */
|
|
118
|
+
_isEnabling() { return !!this._enabling && this._enabling === this._s }
|
|
119
|
+
/** The rooms the backup holds: [{ room, link, kind: 'space'|'lane', label?, shared?, archived? }]. */
|
|
120
|
+
get rooms() { return this._s ? this._s.rooms.map(({ at, ...r }) => r) : [] } // `at` is the live index's bookkeeping
|
|
121
|
+
|
|
122
|
+
/** Set up the backup → `{ code }`. Show the code ONCE: it is the only way back if this device is lost. With an email
|
|
123
|
+
* (default: the signed-in session's), the recovery gate is enrolled too, so a restore can also be made to need it. */
|
|
124
|
+
async enable({ email, address, getCode, showCode, initialRooms = [] } = {}) {
|
|
125
|
+
if (this._s?.v2?.resetDraft) throw fail('email_move_pending', 'finish or cancel this device’s email move first')
|
|
126
|
+
// one set-up at a time (review 2026-11-16: a second enable() during the first one's screens ran a second flow over the same state)
|
|
127
|
+
if (this._isEnabling()) throw fail('already_enabling', 'the backup is being set up already')
|
|
128
|
+
// an account the new service made whose first code did not go through: finished now, never a second one
|
|
129
|
+
if (this._s && !(this._v2 && halfMade(this._s))) throw fail('already_enabled', 'the backup is already set up on this client (its state is wb.backup.state)')
|
|
130
|
+
// IN A VAULT THAT NAMES ITS TENANT: the new account service (sdkBackupV2.js) — the vault's screens ask for the emailed code
|
|
131
|
+
// (`getCode`) and show the recovery code (`showCode`) before it is activated. null = the service refused this vault's tenant
|
|
132
|
+
// before anything was made: the old store, as before. `address`: one the person TYPED for the service (no sign-in) — never enrolled
|
|
133
|
+
// as the old store's email gate on the way back (a typo would lock the backup behind a code mailed elsewhere; review 2026-11-16)
|
|
134
|
+
const rooms = initialRooms.map(roomOf).filter(r => r && !r.room.startsWith('tmp-'))
|
|
135
|
+
if (this._v2) { const r = await this._v2.enable(this, { email: address || email, getCode, showCode, rooms }); if (r) return r }
|
|
136
|
+
const code = newRecoveryCode(), cs = codeSecret(code), master = newMasterSecret()
|
|
137
|
+
const s = { v: 1, format: 'account', master: b64(master), rooms } // a new backup is written in the account format (accountRecord.js)
|
|
138
|
+
this._s = s; this._enabling = s; this._enablingDirty = false
|
|
139
|
+
// another account's state put in place meanwhile (_adopt / _drop / restore) ends this enable: it must not finish on that one
|
|
140
|
+
const mine = () => { if (this._s !== s) throw fail('cancelled', 'the backup was replaced while it was being set up') }
|
|
141
|
+
try {
|
|
142
|
+
await this._write() // the backup itself first: a code that opens nothing is worse than no code
|
|
143
|
+
mine()
|
|
144
|
+
if (!(await enrollCredential(this._transport(), cs, master))) throw fail('enroll_failed', 'the recovery code could not be saved')
|
|
145
|
+
mine()
|
|
146
|
+
const addr = String(email || this._email() || '').trim().toLowerCase()
|
|
147
|
+
if (addr) {
|
|
148
|
+
const { gid, gk } = await gateParams(cs)
|
|
149
|
+
const gate = { methods: ['email'], members: [(await backupLocation(master)).id, (await wrapperLocation(cs)).id], commit_email: await emailCommit(gk, addr) }
|
|
150
|
+
const r = await this._post('/gate', { gid, gate })
|
|
151
|
+
if (!(r.json && (r.json.ok || r.json.reason === 'exists'))) throw fail('gate_failed', 'the recovery email could not be recorded', { status: r.status })
|
|
152
|
+
mine()
|
|
153
|
+
s.email = addr
|
|
154
|
+
}
|
|
155
|
+
} catch (e) {
|
|
156
|
+
const ours = this._s === s
|
|
157
|
+
if (this._enabling === s) this._enabling = null
|
|
158
|
+
if (ours) { this._s = null; this._changed() } // nothing was handed out, but say so: the app persists "no backup"
|
|
159
|
+
throw e
|
|
160
|
+
}
|
|
161
|
+
const queued = this._enablingDirty
|
|
162
|
+
this._enabling = null; this._enablingDirty = false
|
|
163
|
+
this._onEnabled?.(s.master); this._changed(); this._started()
|
|
164
|
+
if (queued) this._schedule() // a Space recorded while it was being set up: the vault copy and the index get it now
|
|
165
|
+
return { code }
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/** Record a Space or Lane (done for you as rooms are created and opened). `label` names it in a restore. */
|
|
169
|
+
add(spaceOrLane, { label } = {}) {
|
|
170
|
+
if (!this._s || !spaceOrLane || !spaceOrLane.room || !spaceOrLane.shareLink) return this
|
|
171
|
+
if (String(spaceOrLane.room).startsWith('tmp-')) return this // a TEMPORARY room is never backed up (it is wiped) — whichever way it was opened (sync sweep 2026-10-27 #4)
|
|
172
|
+
const lane = !!spaceOrLane._sharedRoom
|
|
173
|
+
// A SPLIT room's link is half a key, so the backup also keeps the assembled key — a restore never depends on the
|
|
174
|
+
// app half (https://witbitz.chat/docs/sdk-keys.md#split-key). A plain room's link already is the key.
|
|
175
|
+
// a lane opened as a plain Space (wb.openSpace(laneLink)) knows nothing of its Space: the record it already has as a LANE
|
|
176
|
+
// stays one — a restore must not bring it back as a Space (sync sweep 2026-11-02 #5)
|
|
177
|
+
const had = this._s.rooms.find((x) => x.room === spaceOrLane.room)
|
|
178
|
+
if (lane && (had?.detachedLane || (had?.shared && had.shared !== spaceOrLane._sharedRoom))) return this
|
|
179
|
+
const wasLane = !lane && !spaceOrLane._detachedLane && had && had.kind === 'lane' && had.shared
|
|
180
|
+
const r = roomOf({ room: spaceOrLane.room, link: spaceOrLane.shareLink, mintedFor: had?.mintedFor || spaceOrLane._mintedFor, laneOrigin: spaceOrLane._laneOrigin || had?.laneOrigin, associationAt: spaceOrLane._associationAt || had?.associationAt, kind: lane || wasLane ? 'lane' : 'space', detachedLane: spaceOrLane._detachedLane || had?.detachedLane, label, shared: lane ? spaceOrLane._sharedRoom : wasLane ? had.shared : undefined, mk: spaceOrLane._split ? spaceOrLane._mk : undefined })
|
|
181
|
+
if (!r) return this
|
|
182
|
+
const i = this._s.rooms.findIndex((x) => x.room === r.room)
|
|
183
|
+
const prev = i >= 0 ? this._s.rooms[i] : null
|
|
184
|
+
if (prev && prev.link === r.link && prev.kind === r.kind && prev.shared === r.shared && prev.laneOrigin === r.laneOrigin && prev.associationAt === r.associationAt && !!prev.detachedLane === !!r.detachedLane && prev.mk === r.mk && (!label || prev.label === r.label)) return this
|
|
185
|
+
const next = { ...(prev ? { ...prev, ...r, ...(label ? {} : prev.label ? { label: prev.label } : {}), ...(prev.archived ? { archived: true } : {}) } : r), at: Date.now() } // `at`: the live index keeps the newer of each entry
|
|
186
|
+
if (next.detachedLane) { delete next.shared; delete next.laneOrigin }
|
|
187
|
+
if (i >= 0) this._s.rooms[i] = next; else { if (this._s.rooms.length >= MAX_ROOMS) return this; this._s.rooms.push(next) }
|
|
188
|
+
this._schedule()
|
|
189
|
+
return this
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
_attachLane(room, parent) {
|
|
193
|
+
const entry = this._s?.rooms.find(r => r.room === room)
|
|
194
|
+
if (!entry) throw Object.assign(new Error('Add the private room to the account first.'), { code: 'not_in_account' })
|
|
195
|
+
if (entry.shared && entry.shared !== parent) throw Object.assign(new Error('Unlink this room from its current Space first.'), { code: 'already_linked' })
|
|
196
|
+
if (entry.laneOrigin === 'minted' && entry.shared) entry.mintedFor ||= entry.shared
|
|
197
|
+
if (entry.mintedFor === parent) entry.laneOrigin = 'minted'
|
|
198
|
+
else delete entry.laneOrigin
|
|
199
|
+
entry.kind = 'lane'
|
|
200
|
+
entry.shared = parent
|
|
201
|
+
delete entry.detachedLane
|
|
202
|
+
entry.at = entry.associationAt = associationTime(entry)
|
|
203
|
+
this._schedule()
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
_detachLane(room, shared) {
|
|
207
|
+
const entry = this._s?.rooms.find((r) => r.room === room && r.kind === 'lane' && r.shared === shared)
|
|
208
|
+
if (!entry) return
|
|
209
|
+
if (entry.laneOrigin === 'minted') entry.mintedFor ||= entry.shared
|
|
210
|
+
delete entry.laneOrigin
|
|
211
|
+
delete entry.shared
|
|
212
|
+
entry.kind = 'space'
|
|
213
|
+
entry.detachedLane = true
|
|
214
|
+
entry.at = entry.associationAt = associationTime(entry)
|
|
215
|
+
this._schedule()
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
/** The account's invite key for this app, kept with the rooms (wb.invite hands it over; a restore gives it back). */
|
|
219
|
+
get invite() { return this._s && this._s.invite ? { ...this._s.invite } : null }
|
|
220
|
+
setInvite(state) {
|
|
221
|
+
const v = inviteOf(state)
|
|
222
|
+
if (!this._s || !v || JSON.stringify(this._s.invite || null) === JSON.stringify(v)) return this
|
|
223
|
+
this._s.invite = v; this._schedule()
|
|
224
|
+
return this
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
/** The whole key the backup holds for a SPLIT room, or null — so a restored device opens it without the app half. */
|
|
228
|
+
// A room whose link IS its key answers null: a separate copy of it (an older SDK that restored a record carrying every room's
|
|
229
|
+
// key spreads one through the index) may be stale after a change in place — the link is the one kept current.
|
|
230
|
+
keyFor(room) { const r = this._s && this._s.rooms.find((x) => x.room === room); return (r && r.mk && !keyInLink(r.link) && r.mk) || null }
|
|
231
|
+
|
|
232
|
+
/** Stop backing up one room (e.g. the user left it). It leaves a tombstone, so the account's other devices drop it too
|
|
233
|
+
* (wb.account) — opening the room again later brings it back. */
|
|
234
|
+
remove(room) {
|
|
235
|
+
if (!this._s) return this
|
|
236
|
+
const n = this._s.rooms.length
|
|
237
|
+
this._s.rooms = this._s.rooms.filter((x) => x.room !== room)
|
|
238
|
+
if (this._s.rooms.length !== n) { this._s.tomb = [...(this._s.tomb || []).filter((t) => t.room !== room), { room, at: Date.now() }].slice(-500); this._schedule() }
|
|
239
|
+
return this
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
/** The backup's record format: 'account' (the one the Spaces app uses) or 'legacy' (this SDK's original). */
|
|
243
|
+
get format() { return this._s ? (this._s.format === 'account' ? 'account' : 'legacy') : null }
|
|
244
|
+
/** Rewrite a LEGACY backup in the account format (the one the Spaces app uses). Same vault, code and rooms; a client
|
|
245
|
+
* on an older SDK can no longer restore it. Nothing does this for you. */
|
|
246
|
+
async upgrade() {
|
|
247
|
+
if (!this._s) throw fail('not_enabled', 'no backup is set up — call wb.backup.enable() first')
|
|
248
|
+
if (this._s.format === 'account') return { format: 'account' }
|
|
249
|
+
const was = this._s.format
|
|
250
|
+
this._s.format = 'account'
|
|
251
|
+
try { await this._write() } catch (e) { this._s.format = was; throw e }
|
|
252
|
+
this._changed()
|
|
253
|
+
return { format: 'account' }
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
/** Write the backup now (it is also written shortly after every change). */
|
|
257
|
+
async save(verification) { clearTimeout(this._timer); this._timer = null; if (!this.enabled) throw fail('not_enabled', 'no backup is set up — call wb.backup.enable() first'); await this._write(verification); return { rooms: this._s.rooms.length } }
|
|
258
|
+
/** True when enable() recorded an email gate: deleting (or restoring) this backup then needs the emailed code as well. */
|
|
259
|
+
get gated() { return !!(this._s && this._s.email) }
|
|
260
|
+
/** Enroll the currently signed-in address for an existing legacy backup. */
|
|
261
|
+
async protectRecoveryEmail({ code } = {}) {
|
|
262
|
+
const state = this._s, email = String(this._email() || '').trim().toLowerCase()
|
|
263
|
+
if (!state?.master || state.v2?.svc) throw fail('legacy_required', 'open a legacy backup first')
|
|
264
|
+
if (!email) throw fail('sign_in_required', 'sign in with your recovery email first')
|
|
265
|
+
const cs = codeSecret(code || ''), wrapper = await wrapperLocation(cs)
|
|
266
|
+
const stored = await this._get('/backup', '?id=' + wrapper.id)
|
|
267
|
+
if (stored.status === 403 && stored.json?.reason === 'gated') throw fail('already_protected', 'the recovery code already has a recovery factor')
|
|
268
|
+
const master = stored.json?.ok && await openWrapper(cs, stored.json.blob)
|
|
269
|
+
if (!master || b64(master) !== state.master) throw fail('bad_code', 'use the recovery code for this backup')
|
|
270
|
+
const { gid, gk } = await gateParams(cs)
|
|
271
|
+
const gate = { methods: ['email'], members: [(await backupLocation(master)).id, wrapper.id], commit_email: await emailCommit(gk, email) }
|
|
272
|
+
const guard = () => { if (this._s !== state || String(this._email() || '').trim().toLowerCase() !== email) throw fail('account_changed', 'the account changed during enrollment') }
|
|
273
|
+
guard()
|
|
274
|
+
const r = await this._post('/gate', { gid, gate })
|
|
275
|
+
if (!r.json?.ok || r.json.reason === 'exists') throw fail(r.json?.reason === 'exists' ? 'already_protected' : 'gate_failed', 'the new recovery email could not be confirmed')
|
|
276
|
+
guard()
|
|
277
|
+
state.email = email
|
|
278
|
+
this._changed()
|
|
279
|
+
await this.save()
|
|
280
|
+
return { enrolled: true }
|
|
281
|
+
}
|
|
282
|
+
/** @private A RELEASE TOKEN for this backup's email gate — what the server asks before it deletes a gated backup, as a
|
|
283
|
+
* gated restore (vaultBackupApi backupDelete). The first call (with the recovery `code`) mails a code and throws
|
|
284
|
+
* `email_code_required` with a `ticket`; the second (with `ticket` + `emailCode`) returns the token. */
|
|
285
|
+
async _release({ code, email, ticket, emailCode } = {}) {
|
|
286
|
+
if (ticket && emailCode) return this._emailVerify(ticket, emailCode)
|
|
287
|
+
let cs
|
|
288
|
+
try { cs = codeSecret(code) } catch { throw fail('code_required', 'this backup is protected by its email: pass its recovery code ({ code }) — a code is then emailed to it') }
|
|
289
|
+
return this._emailStart(cs, String(email || (this._s && this._s.email) || this._email() || '').trim().toLowerCase())
|
|
290
|
+
}
|
|
291
|
+
/** @private the gate's emailed code → its release token */
|
|
292
|
+
async _emailVerify(ticket, emailCode) {
|
|
293
|
+
const v = await this._post('/email/verify', { ticket, code: String(emailCode).trim() })
|
|
294
|
+
const token = v.json && v.json.ok ? v.json.token : null
|
|
295
|
+
if (!token) throw fail('email_code_wrong', 'that email code did not verify', { status: v.status })
|
|
296
|
+
return token
|
|
297
|
+
}
|
|
298
|
+
/** @private mail the gate's code to `addr`; always throws (email_code_required with a ticket, or why it could not) */
|
|
299
|
+
async _emailStart(cs, addr) {
|
|
300
|
+
if (!addr) throw fail('email_required', 'this backup needs its email as well as the code — pass `email`')
|
|
301
|
+
const { gid, gk } = await gateParams(cs)
|
|
302
|
+
const s = await this._post('/email/start', { gid, commit: await emailCommit(gk, addr), email: addr, gk: Array.from(gk, (b) => b.toString(16).padStart(2, '0')).join('') })
|
|
303
|
+
// the server's own reason is the code when it gives one (update_required: an SDK too old for the gate's check) — a builder
|
|
304
|
+
// could not tell "update the SDK" from "wrong address" (sync sweep, 10-17 #10)
|
|
305
|
+
if (!(s.json && s.json.ok && s.json.ticket)) { const why = s.json && typeof s.json.reason === 'string' && /^[a-z_]{3,40}$/.test(s.json.reason) ? s.json.reason : 'email_refused'; throw fail(why, why === 'update_required' ? 'this backup\'s protection needs a newer SDK — load the latest release' : 'a code could not be sent to that address (it must be the one this backup was set up with)', { status: s.status }) }
|
|
306
|
+
throw fail('email_code_required', `we emailed a code to ${addr} — call again with { code, ticket, emailCode }`, { ticket: s.json.ticket })
|
|
307
|
+
}
|
|
308
|
+
/** @private DELETE MY ACCOUNT (wb.erasure.deleteAccount): delete the vault copy (POST /v1/vault/backup/delete — the one
|
|
309
|
+
* route; 404 = already gone), with the gate's release token when the backup has one (sync sweep 11-08 #1: it posted to a
|
|
310
|
+
* path that does not exist and read the 404 as done). Leaves the local state — the erase drops it last. → { ok, status?, reason? } */
|
|
311
|
+
async _deleteRemote(token = null) {
|
|
312
|
+
if (!this._s) return { ok: true }
|
|
313
|
+
if (this._s.v2) return { ok: false, status: 0, reason: 'this account is on the account service — wb.backup.deleteAccount() deletes it' }
|
|
314
|
+
const loc = await backupLocation(ub64(this._s.master))
|
|
315
|
+
const r = await this._post('/backup/delete', { id: loc.id, ...(token ? { token } : {}) })
|
|
316
|
+
if ((r.status === 200 && r.json?.deleted === true) || r.status === 404) return { ok: true }
|
|
317
|
+
return { ok: false, status: r.status, reason: (r.json && (r.json.error || (r.json.reason === 'incomplete' ? 'some old copies could not be deleted yet — run it again' : r.json.reason))) || ('backup ' + (r.status || 'unreachable')) }
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
/** Restore on a new device from the recovery code → `{ rooms }`, and this client now holds the backup.
|
|
321
|
+
* If the vault's gate requires the email, the first call mails a code and throws `code: 'email_code_required'` with
|
|
322
|
+
* a `ticket`; call again with `{ code, ticket, emailCode }`. `email` defaults to the signed-in address. */
|
|
323
|
+
async restore({ code, email, ticket, emailCode, getCode, askAddress } = {}) {
|
|
324
|
+
const epoch = this._restoreEpoch = (this._restoreEpoch || 0) + 1
|
|
325
|
+
const owner = this._restoreIdentity?.() ?? this._email(), original = this._s
|
|
326
|
+
const check = () => {
|
|
327
|
+
if (epoch !== this._restoreEpoch || original !== this._s || owner !== (this._restoreIdentity?.() ?? this._email())) throw fail('account_changed', 'The account changed during recovery.')
|
|
328
|
+
}
|
|
329
|
+
if (this._s?.v2?.resetDraft) throw fail('email_move_pending', 'finish or cancel this device’s email move first')
|
|
330
|
+
let cs
|
|
331
|
+
try { cs = codeSecret(code) } catch { throw fail('bad_code', 'that is not a recovery code') }
|
|
332
|
+
// THE NEW ACCOUNT SERVICE FIRST (a vault that names its tenant; `getCode` asks for its emailed code): a code that is no account
|
|
333
|
+
// there (or a service that could not say) goes on to the old store below. A ticket of the old store's gate goes straight there.
|
|
334
|
+
if (this._v2 && !(ticket && emailCode)) {
|
|
335
|
+
const d = await this._v2.restore(this, { code, email, getCode, askAddress })
|
|
336
|
+
check()
|
|
337
|
+
if (d) { clearTimeout(this._timer); this._timer = null; this._s = stateOf(d); this._changed(); this._started(); return { rooms: this.rooms } }
|
|
338
|
+
}
|
|
339
|
+
const w = await wrapperLocation(cs)
|
|
340
|
+
let token = null
|
|
341
|
+
if (ticket && emailCode) token = await this._emailVerify(ticket, emailCode)
|
|
342
|
+
const read = async (id) => {
|
|
343
|
+
const r = token ? await this._post('/release', { token, id, builderRestore: true })
|
|
344
|
+
: await this._get('/backup', '?id=' + id + '&builderRestore=1')
|
|
345
|
+
if (r.json?.reason === 'other_app') throw fail('other_app', 'Open the app that created this backup to restore it.')
|
|
346
|
+
if (r.json?.reason === 'backup_app_unknown' || (r.json?.ok && r.json.appVerified !== true)) {
|
|
347
|
+
throw fail('backup_app_unknown', 'The backup service cannot verify which app created this recovery code.')
|
|
348
|
+
}
|
|
349
|
+
return r
|
|
350
|
+
}
|
|
351
|
+
let r = await read(w.id)
|
|
352
|
+
if (r.status === 403 && r.json && r.json.reason === 'gated') await this._emailStart(cs, String(email || this._email() || '').trim().toLowerCase()) // throws: email_code_required (with a ticket) or why not
|
|
353
|
+
if (r.status === 404) throw fail('not_found', 'no backup was found for that recovery code')
|
|
354
|
+
const master = r.json && r.json.ok ? await openWrapper(cs, r.json.blob) : null
|
|
355
|
+
if (!master) throw fail('unopenable', 'the backup for that code could not be opened', { status: r.status })
|
|
356
|
+
const loc = await backupLocation(master)
|
|
357
|
+
const b = await read(loc.id)
|
|
358
|
+
if (!(b.json && b.json.ok)) throw fail(b.status === 404 ? 'not_found' : 'unreadable', 'the backup could not be read', { status: b.status })
|
|
359
|
+
let doc
|
|
360
|
+
try { doc = await unseal(loc.key, b.json.blob) } catch { throw fail('unopenable', 'the backup could not be opened') }
|
|
361
|
+
// ⛔ This app's vault only — never a Witbitz account's (it would hold the key to every Space the person has).
|
|
362
|
+
if (vaultOwner(doc) !== 'sdk') throw fail('not_sdk_backup', 'that code opens a backup made by a different app')
|
|
363
|
+
// THROUGH THE SPACES APP'S RESTORE (backupRecord.js applyPlan) where its rule is the SDK's too: which rows come back — never
|
|
364
|
+
// one the record itself marks deleted in `tombstones` (the SDK writes there only rooms it no longer holds, so a record from
|
|
365
|
+
// any SDK loses nothing) — and the invite key (whole, or none). The SDK's own forget (`tomb`) is NOT applied: it is
|
|
366
|
+
// re-openable, a room opened again after one comes back. A fresh state: nothing on this client to keep. A LEGACY record
|
|
367
|
+
// is not in the account format: no plan, read as before.
|
|
368
|
+
const plan = applyPlan(doc, {}, { app: SDK_APP })
|
|
369
|
+
const invite = plan ? plan.inviteKey : doc.inviteKey
|
|
370
|
+
check()
|
|
371
|
+
this._s = stateOf({ master: b64(master), savedVersion: b.json.ver, rooms: roomsOfRecord(plan ? { ...doc, recents: plan.add } : doc), tomb: tombOfRecord(doc), ...(doc.email ? { email: doc.email } : {}), ...(invite ? { invite } : {}), ...(doc.kind === KIND ? {} : { format: 'account' }) })
|
|
372
|
+
this._changed(); this._started()
|
|
373
|
+
return { rooms: this.rooms }
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
// ── THE ACCOUNT SERVICE'S OWN CALLS (an account with service === 'account'; a builder's vault runs them, its screens asking
|
|
377
|
+
// the person for the emailed code — `getCode` — and showing a new code — `showCode`).
|
|
378
|
+
/** Sign out every OTHER device of this account: each one forgets the account at its next status check. */
|
|
379
|
+
async signOutOthers({ getCode } = {}) { if (!this._v2) throw notOnService(); return this._v2.signOutOthers(this, { getCode }) }
|
|
380
|
+
/** A new recovery code (shown before it is activated): the old code stops working and every other device is signed out. */
|
|
381
|
+
async newRecoveryCode({ getCode, showCode } = {}) { if (!this._v2) throw notOnService(); return this._v2.newRecoveryCode(this, { getCode, showCode }) }
|
|
382
|
+
/** Delete this account on the account service (every device signed out, the address freed, the backup gone); this client then
|
|
383
|
+
* holds no account. The Spaces themselves are not deleted by this call. */
|
|
384
|
+
async deleteAccount({ getCode } = {}) { if (!this._v2) throw notOnService(); return this._v2.deleteAccount(this, { getCode }) }
|
|
385
|
+
async manageSecurityKeys() { throw fail('vault_required', 'manage account security keys in the account’s vault') }
|
|
386
|
+
async migrate({ code, getCode, silent = false } = {}) { if (!this._v2) throw notOnService(); return this._v2.migrate(this, { code, getCode, silent }) }
|
|
387
|
+
async beginEmailMove(opts = {}) { if (!this._v2) throw notOnService(); return this._v2.beginEmailMove(this, opts) }
|
|
388
|
+
async pendingEmailMove() { if (!this._v2) throw notOnService(); return this._v2.pendingEmailMove(this) }
|
|
389
|
+
async finishEmailMove(opts = {}) { if (!this._v2) throw notOnService(); return this._v2.finishEmailMove(this, opts) }
|
|
390
|
+
async cancelPendingEmailMove(opts = {}) { if (!this._v2) throw notOnService(); return this._v2.cancelPendingEmailMove(this, opts) }
|
|
391
|
+
async emailMove() { if (!this._v2) throw notOnService(); return this._v2.emailMove(this) }
|
|
392
|
+
async requestMoveTime() { if (!this._v2) throw notOnService(); return this._v2.requestMoveTime(this) }
|
|
393
|
+
async cancelEmailMove({ getCode } = {}) { if (!this._v2) throw notOnService(); return this._v2.cancelEmailMove(this, { getCode }) }
|
|
394
|
+
|
|
395
|
+
// ── internals ──────────────────────────────────────────────────────────────────────────────────────────────────
|
|
396
|
+
_schedule() { if (this._isEnabling()) { this._enablingDirty = true; return } this._persist(); if (typeof this._onLocal === 'function') { try { this._onLocal() } catch { /* the live index */ } } }
|
|
397
|
+
/** Write the vault copy soon and hand the app the new state — without telling the live index (it is the caller). */
|
|
398
|
+
_persist() { if (this._isEnabling()) { this._enablingDirty = true; return } if (this._s && this._s.erased) { this._changed(); return } clearTimeout(this._timer); this._timer = setTimeout(() => { this._timer = null; if (this._s) this._write().catch((e) => { this.lastError = e }) }, 400); this._changed() }
|
|
399
|
+
/** This device was signed out of the account (wb.account): forget it here, and tell the app to persist that. */
|
|
400
|
+
_drop() { this._restoreEpoch = (this._restoreEpoch || 0) + 1; clearTimeout(this._timer); this._timer = null; this._s = null; this._changed() }
|
|
401
|
+
/** @private take another persisted state in place (a vault switching accounts keeps one backup per account) */
|
|
402
|
+
_adopt(state) { this._restoreEpoch = (this._restoreEpoch || 0) + 1; clearTimeout(this._timer); this._timer = null; this._s = stateOf(state); this._changed() }
|
|
403
|
+
_started() { if (typeof this._onStart === 'function') { try { this._onStart() } catch { /* the live index */ } } }
|
|
404
|
+
_changed() { if (this._isEnabling()) return; if (typeof this.onState === 'function') { try { this.onState(this.state) } catch { /* the app's callback must not break the backup */ } } }
|
|
405
|
+
async _write(verification) {
|
|
406
|
+
if (this._migrating) return // the move pins the old head; its completion writes all rooms to the new service
|
|
407
|
+
if (this._s && this._s.v2 && this._s.v2.moving && !this._s.v2.svc) throw fail('migration_pending', 'retry migration to learn whether the service committed; no backup was overwritten')
|
|
408
|
+
// ★ THE STATE IT BEGAN WITH (pass 6, K#2): `master` and the location were this account's, but the rooms, email and invite key
|
|
409
|
+
// were read again after the awaits — an account switch meanwhile sealed the next account's rooms into this one's backup.
|
|
410
|
+
const s0 = this._s
|
|
411
|
+
if (!s0) return
|
|
412
|
+
if (s0.erased) throw fail('deleted', 'this backup was deleted with its account')
|
|
413
|
+
// an account on the NEW SERVICE is written there, and only there — never to the old store
|
|
414
|
+
if (s0.v2) { if (!this._v2) throw fail('service_unavailable', 'this account is on the Witbitz account service — only its vault can write it'); return this._v2.write(this, s0) }
|
|
415
|
+
const master = ub64(s0.master)
|
|
416
|
+
const loc = await backupLocation(master)
|
|
417
|
+
// ★ ONLY OVER THE VERSION WE READ (sync sweep 2026-11-09, 11-08 #32; the app's backup.js pushBackup since the 10-05 review):
|
|
418
|
+
// two devices of one backup each wrote their own list whole, so the room one added vanished at the other's next save. Each
|
|
419
|
+
// write reads the backup first, keeps the rooms another device added (never one this device forgot — its tombstone), and
|
|
420
|
+
// A gated read supplies only a version. Reuse our complete local copy
|
|
421
|
+
// only when the service identifies it as the last version we saved.
|
|
422
|
+
let releaseToken
|
|
423
|
+
for (let attempt = 0; attempt < 4; attempt++) {
|
|
424
|
+
let cur = await this._get('/backup', '?id=' + loc.id)
|
|
425
|
+
if (this._s !== s0) return // another account's state is in place now: its own write follows
|
|
426
|
+
if (cur.status === 404 && cur.json && cur.json.deleted === true) { s0.erased = true; this.lastError = null; this._changed(); return } // pass 7, F#2/F#10: deleted with its account
|
|
427
|
+
if (cur.status === 403 && cur.json?.reason === 'gated' && (!s0.savedVersion || s0.savedVersion !== cur.json.ver)) {
|
|
428
|
+
if (!verification) throw fail('backup_verification_required', 'Verify the recovery email to merge the latest backup before saving')
|
|
429
|
+
releaseToken ||= await this._release(verification)
|
|
430
|
+
if (this._s !== s0) return
|
|
431
|
+
cur = await this._post('/release', { token: releaseToken, id: loc.id })
|
|
432
|
+
if (this._s !== s0) return
|
|
433
|
+
if (cur.status !== 200) throw fail('backup_unreadable', 'The verified backup could not be read before saving')
|
|
434
|
+
}
|
|
435
|
+
const ver = cur.json && typeof cur.json.ver === 'string' && cur.json.ver ? cur.json.ver : undefined
|
|
436
|
+
let remote = { rooms: [], tomb: [] }
|
|
437
|
+
const absent = cur.status === 404 && cur.json?.reason === 'not_found'
|
|
438
|
+
const ownGatedVersion = cur.status === 403 && cur.json?.reason === 'gated' && ver && ver === s0.savedVersion
|
|
439
|
+
if (!absent && !ownGatedVersion) {
|
|
440
|
+
if (cur.status !== 200 || !cur.json?.ok || typeof cur.json.blob !== 'string' || !ver) throw fail('backup_unreadable', 'Could not read the current backup before saving')
|
|
441
|
+
const doc = await unseal(loc.key, cur.json.blob)
|
|
442
|
+
if (vaultOwner(doc) !== 'sdk') throw fail('backup_unreadable', 'The existing backup could not be opened as this account')
|
|
443
|
+
remote = { rooms: roomsOfRecord(doc).map(roomOf).filter(Boolean), tomb: tombOfRecord(doc) }
|
|
444
|
+
}
|
|
445
|
+
const { rooms, tomb } = mergeIndex({ rooms: s0.rooms, tomb: s0.tomb }, remote, MAX_ROOMS)
|
|
446
|
+
// The format this backup already has: the account record (accountRecord.js), or the LEGACY one it was made with —
|
|
447
|
+
// never changed under the builder's feet (upgrade() does it on request).
|
|
448
|
+
// The account record also names the account's index room (phase 2: the app's `indexRoom` pointer, derived from the master
|
|
449
|
+
// — the same room sdkAccount.js syncs; a legacy record stays as it was written).
|
|
450
|
+
const doc = s0.format === 'account'
|
|
451
|
+
? recordFromRooms({ rooms, tomb, email: s0.email, inviteKey: s0.invite, indexRoom: await indexRoomOf(s0.master) })
|
|
452
|
+
: { kind: KIND, v: 1, at: Date.now(), rooms, ...(tomb.length ? { tomb } : {}), ...(s0.email ? { email: s0.email } : {}), ...(s0.invite ? { inviteKey: s0.invite } : {}) }
|
|
453
|
+
const blob = await seal(loc.key, doc)
|
|
454
|
+
if (this._s !== s0) return
|
|
455
|
+
const bindBuilder = this._enabling === s0
|
|
456
|
+
const r = await this._post('/backup', { id: loc.id, blob, ifVer: ver ?? null, returnVersion: true, ...(bindBuilder ? { bindBuilder: true } : {}) })
|
|
457
|
+
if (bindBuilder && r.json?.ok && r.json.appVerified !== true) throw fail('app_binding_unavailable', 'The backup service must support app-specific recovery before a new code can be created.')
|
|
458
|
+
if (r.status === 409) { await new Promise((res) => setTimeout(res, 100 + Math.floor(Math.random() * 300))); continue } // another device wrote since our read
|
|
459
|
+
// ⛔ DELETED WITH ITS ACCOUNT (state machines pass 7, F#2): an erase that stopped half way (or ran on another device) left
|
|
460
|
+
// this client writing it; the server refuses to bring it back (410). Final: the state says so (the app persists it) and
|
|
461
|
+
// no later change schedules a write — quietly, the backup is gone on purpose.
|
|
462
|
+
if (r.status === 410) { if (this._s === s0) { s0.erased = true; this.lastError = null; this._changed() } return }
|
|
463
|
+
if (!(r.json && r.json.ok)) throw fail('save_failed', 'the backup could not be saved', { status: r.status, reason: r.json && r.json.reason })
|
|
464
|
+
if (this._s !== s0) return
|
|
465
|
+
const adopted = mergeIndex({ rooms: s0.rooms, tomb: s0.tomb }, { rooms, tomb }, MAX_ROOMS)
|
|
466
|
+
s0.rooms = adopted.rooms
|
|
467
|
+
s0.tomb = adopted.tomb
|
|
468
|
+
s0.savedVersion = r.json.ver || undefined
|
|
469
|
+
this._changed()
|
|
470
|
+
this.lastError = null
|
|
471
|
+
return
|
|
472
|
+
}
|
|
473
|
+
throw fail('save_failed', 'the backup kept changing under this save (another device writing) — the next change tries again', { status: 409 })
|
|
474
|
+
}
|
|
475
|
+
/** @private Was this backup deleted with its account — by an erase on another device (state machines pass 7, F#10)? The server
|
|
476
|
+
* says so on a read (404 `deleted`); the state then says so too (the app persists it), and nothing writes it again. */
|
|
477
|
+
async _checkErased() {
|
|
478
|
+
const s0 = this._s
|
|
479
|
+
if (!s0) return false
|
|
480
|
+
if (s0.erased) return true
|
|
481
|
+
if (s0.v2) return false // the account service signs a deleted account's devices out: the vault's status check
|
|
482
|
+
const loc = await backupLocation(ub64(s0.master))
|
|
483
|
+
const r = await this._get('/backup', '?id=' + loc.id)
|
|
484
|
+
if (!(r.status === 404 && r.json && r.json.deleted === true) || this._s !== s0) return false
|
|
485
|
+
s0.erased = true; clearTimeout(this._timer); this._timer = null; this._changed()
|
|
486
|
+
return true
|
|
487
|
+
}
|
|
488
|
+
_transport() {
|
|
489
|
+
return {
|
|
490
|
+
put: async (id, blob) => { const r = await this._post('/backup', { id, blob, bindBuilder: true }); return !!(r.json?.ok && r.json.appVerified === true) },
|
|
491
|
+
get: async (id) => { const r = await this._get('/backup', '?id=' + id); return r.json && r.json.ok ? r.json.blob : null },
|
|
492
|
+
}
|
|
493
|
+
}
|
|
494
|
+
async _get(path, qs = '') { return this._req('GET', path + qs) }
|
|
495
|
+
async _post(path, body) { return this._req('POST', path, body) }
|
|
496
|
+
async _req(method, path, body) {
|
|
497
|
+
try {
|
|
498
|
+
if (this._tenant) {
|
|
499
|
+
if (body) body = { ...body, builderTenant: this._tenant }
|
|
500
|
+
else path += (path.includes('?') ? '&' : '?') + 'builderTenant=' + encodeURIComponent(this._tenant)
|
|
501
|
+
}
|
|
502
|
+
const res = await this._fetch(this._base + path, { method, headers: body ? { 'content-type': 'application/json' } : {}, ...(body ? { body: JSON.stringify(body) } : {}) })
|
|
503
|
+
let json = null; try { json = await res.json() } catch { json = null }
|
|
504
|
+
return { status: res.status, json }
|
|
505
|
+
} catch { return { status: 0, json: null } }
|
|
506
|
+
}
|
|
507
|
+
}
|