@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
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
// acctV2WebAuthn.js — the security-key ceremonies of account recovery v2 (docs/account-recovery-protocol.md § 10), as the
|
|
2
|
+
// small adapter the client takes (acctV2Client.js `keys`): create(options) → the registration, get({challenge, allow}) →
|
|
3
|
+
// an assertion, everything in base64url. This file is the BROWSER's adapter (navigator.credentials); the tests pass a
|
|
4
|
+
// simulated key with the same shape. The relying party is always witbitz.chat: one credential per key, for every app (§ 10.2).
|
|
5
|
+
import { b64u, unb64u } from './acctV2Wire.js'
|
|
6
|
+
|
|
7
|
+
export const RP_ID = 'witbitz.chat'
|
|
8
|
+
const err = (code) => Object.assign(new Error(code), { code })
|
|
9
|
+
const ab = (x) => b64u(new Uint8Array(x))
|
|
10
|
+
|
|
11
|
+
// The screen's gate before each prompt: `fn(kind, call)` shows what to touch and runs `call()` (the navigator call) INSIDE
|
|
12
|
+
// the person's tap, returning its promise — Safari opens a security-key prompt only in answer to a tap, and these flows
|
|
13
|
+
// reach the prompt after network calls and an email code. Without a gate (tests, or no screen) the call runs directly.
|
|
14
|
+
// A Standard account's flows never reach a prompt, so the gate never shows for them.
|
|
15
|
+
let _onPrompt = null
|
|
16
|
+
export const onKeyPrompt = (fn) => { _onPrompt = fn }
|
|
17
|
+
const ceremony = (kind, call) => (_onPrompt ? _onPrompt(kind, call) : call())
|
|
18
|
+
const rethrow = (e) => { throw (e && e.code === 'cancelled' ? e : why(e)) }
|
|
19
|
+
|
|
20
|
+
/** Why a prompt failed, in the client's words: the person closed it, this client cannot (no WebAuthn), or it refused. */
|
|
21
|
+
function why(e) {
|
|
22
|
+
if (e && e.name === 'NotAllowedError') return err('key_cancelled') // closed, timed out, or no matching key touched
|
|
23
|
+
if (e && e.name === 'InvalidStateError') return err('key_already_registered') // excludeCredentials matched
|
|
24
|
+
if (e && e.name === 'SecurityError') return err('key_wrong_site') // this origin may not use witbitz.chat (§ 10.2)
|
|
25
|
+
return err('key_failed')
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export function browserKeys({ rpId = RP_ID } = {}) {
|
|
29
|
+
const available = () => typeof window !== 'undefined' && !!window.PublicKeyCredential && !!navigator.credentials
|
|
30
|
+
return {
|
|
31
|
+
available,
|
|
32
|
+
/** § 10.1 step 2 → 3: the service's creation options in, the attestation out. */
|
|
33
|
+
async create(pk) {
|
|
34
|
+
if (!available()) throw err('webauthn_unavailable')
|
|
35
|
+
const publicKey = {
|
|
36
|
+
...pk,
|
|
37
|
+
challenge: unb64u(pk.challenge),
|
|
38
|
+
user: { ...pk.user, id: unb64u(pk.user.id) },
|
|
39
|
+
excludeCredentials: (pk.excludeCredentials || []).map((c) => ({ ...c, id: unb64u(c.id) })),
|
|
40
|
+
}
|
|
41
|
+
let cred
|
|
42
|
+
try { cred = await ceremony('create', () => navigator.credentials.create({ publicKey })) } catch (e) { rethrow(e) }
|
|
43
|
+
if (!cred) throw err('key_cancelled')
|
|
44
|
+
const r = cred.response
|
|
45
|
+
return { attestationObject: ab(r.attestationObject), clientDataJSON: ab(r.clientDataJSON), transports: (r.getTransports && r.getTransports()) || [] }
|
|
46
|
+
},
|
|
47
|
+
/** An assertion over `challenge` (bytes) by one of `allow` ([{ id, transports }]). */
|
|
48
|
+
async get({ challenge, allow }) {
|
|
49
|
+
if (!available()) throw err('webauthn_unavailable')
|
|
50
|
+
let a
|
|
51
|
+
const publicKey = {
|
|
52
|
+
rpId, challenge, userVerification: 'required', timeout: 120000,
|
|
53
|
+
allowCredentials: (allow || []).map((c) => ({ type: 'public-key', id: unb64u(c.id), transports: c.transports || [] })),
|
|
54
|
+
}
|
|
55
|
+
try { a = await ceremony('get', () => navigator.credentials.get({ publicKey })) } catch (e) { rethrow(e) }
|
|
56
|
+
if (!a) throw err('key_cancelled')
|
|
57
|
+
const r = a.response
|
|
58
|
+
return { credId: ab(a.rawId), clientDataJSON: ab(r.clientDataJSON), authenticatorData: ab(r.authenticatorData), signature: ab(r.signature) }
|
|
59
|
+
},
|
|
60
|
+
}
|
|
61
|
+
}
|
package/acctV2Wire.js
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
// acctV2Wire.js — the bytes of account recovery v2 on the CLIENT (docs/account-recovery-protocol.md § 5.2, § 5.4, § 8.4).
|
|
2
|
+
// The same formats the service verifies (control-plane/src/lib/acct/transcript.mjs); both sides are pinned to the protocol's
|
|
3
|
+
// § 13 vectors (spaces/test/acctV2Client.test.mjs), so a drift on either side fails a test. Browser and Node alike:
|
|
4
|
+
// WebCrypto only, no dependencies.
|
|
5
|
+
|
|
6
|
+
const enc = new TextEncoder()
|
|
7
|
+
|
|
8
|
+
/** RFC 8785 for the value types the protocol signs (strings, safe integers, booleans, null, arrays, plain objects). */
|
|
9
|
+
export function jcs(v) {
|
|
10
|
+
if (v === null) return 'null'
|
|
11
|
+
if (typeof v === 'boolean') return v ? 'true' : 'false'
|
|
12
|
+
if (typeof v === 'number') { if (!Number.isSafeInteger(v)) throw new Error('jcs: only safe integers are signed'); return String(v) }
|
|
13
|
+
if (typeof v === 'string') return JSON.stringify(v)
|
|
14
|
+
if (Array.isArray(v)) return '[' + v.map(jcs).join(',') + ']'
|
|
15
|
+
if (typeof v === 'object' && Object.getPrototypeOf(v) === Object.prototype) {
|
|
16
|
+
return '{' + Object.keys(v).sort().map((k) => { if (v[k] === undefined) throw new Error('jcs: undefined at ' + k); return JSON.stringify(k) + ':' + jcs(v[k]) }).join(',') + '}'
|
|
17
|
+
}
|
|
18
|
+
throw new Error('jcs: unsupported value')
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
const concat = (...parts) => { const n = parts.reduce((a, p) => a + p.length, 0); const o = new Uint8Array(n); let i = 0; for (const p of parts) { o.set(p, i); i += p.length } return o }
|
|
22
|
+
function framed(context, fields, obj) {
|
|
23
|
+
for (const f of fields) if (!(f in obj)) throw new Error(`${context}: missing ${f}`)
|
|
24
|
+
for (const k of Object.keys(obj)) if (!fields.includes(k)) throw new Error(`${context}: unexpected ${k}`)
|
|
25
|
+
return concat(enc.encode(context), new Uint8Array([0]), enc.encode(jcs(obj)))
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export const hexOf = (u8) => Array.from(u8, (b) => b.toString(16).padStart(2, '0')).join('')
|
|
29
|
+
export const b64u = (u8) => { let s = ''; for (const b of u8) s += String.fromCharCode(b); return btoa(s).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '') }
|
|
30
|
+
export const unb64u = (s) => { const b = atob(String(s).replace(/-/g, '+').replace(/_/g, '/') + '==='.slice((String(s).length + 3) % 4)); const u = new Uint8Array(b.length); for (let i = 0; i < b.length; i++) u[i] = b.charCodeAt(i); return u }
|
|
31
|
+
export const sha256 = async (u8) => new Uint8Array(await crypto.subtle.digest('SHA-256', u8))
|
|
32
|
+
|
|
33
|
+
/** § 5.2 — the operation transcript T. */
|
|
34
|
+
export const transcript = (o) => framed('witbitz-account-v1', ['op', 'acct', 'params', 'challenge', 'nonce', 'exp', 'pv', 'rg', 'ev', 'epoch'], o)
|
|
35
|
+
|
|
36
|
+
const enc3986 = (s) => encodeURIComponent(String(s)).replace(/[!'()*]/g, (c) => '%' + c.charCodeAt(0).toString(16).toUpperCase())
|
|
37
|
+
/** § 5.4 — the canonical query string. */
|
|
38
|
+
export function canonicalQuery(q) {
|
|
39
|
+
const pairs = []
|
|
40
|
+
for (const [k, v] of Object.entries(q || {})) for (const one of (Array.isArray(v) ? v : [v])) pairs.push([enc3986(k), enc3986(one)])
|
|
41
|
+
pairs.sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : a[1] < b[1] ? -1 : a[1] > b[1] ? 1 : 0))
|
|
42
|
+
return pairs.map(([k, v]) => k + '=' + v).join('&')
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** § 5.4 — the bytes a device signs for a request. */
|
|
46
|
+
export async function deviceRequestBytes({ method, path, query = '', body = new Uint8Array(0), ts, nonce }) {
|
|
47
|
+
return framed('witbitz-device-v1', ['method', 'path', 'query', 'body_sha256', 'ts', 'nonce'],
|
|
48
|
+
{ method: String(method).toUpperCase(), path, query, body_sha256: hexOf(await sha256(body)), ts, nonce })
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** § 8.4 — the bytes the backup write key signs. */
|
|
52
|
+
export const writeProofBytes = (o) => framed('witbitz-backup-write-v1', ['acct', 'id', 'ver', 'digest', 'prev', 'rg', 'epoch', 'nonce', 'ts'], o)
|
|
53
|
+
|
|
54
|
+
/** WebCrypto signs ECDSA as raw r‖s (64 bytes); the service verifies DER. */
|
|
55
|
+
export function rawToDer(raw) {
|
|
56
|
+
const int = (b) => { let i = 0; while (i < b.length - 1 && b[i] === 0) i++; let v = b.subarray(i); if (v[0] & 0x80) v = concat(new Uint8Array([0]), v); return concat(new Uint8Array([2, v.length]), v) }
|
|
57
|
+
const r = int(raw.subarray(0, 32)), s = int(raw.subarray(32, 64))
|
|
58
|
+
return concat(new Uint8Array([0x30, r.length + s.length]), r, s)
|
|
59
|
+
}
|
package/address.js
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
// address.js — the ADDRESS grammar a person can be reached by (docs/spaces-usernames.md §5): an email, or a public
|
|
2
|
+
// "@username". Pure; the browser twin of the server's agent/usernames.mjs grammar (kept identical by
|
|
3
|
+
// agent/usernamesParity.test.mjs — a name the picker accepts must be one the registry accepts, and vice versa).
|
|
4
|
+
//
|
|
5
|
+
// NO DOTS in a username: the allow-list already uses "@acme.com" to mean A DOMAIN, so with dots out "@x.y" is always a
|
|
6
|
+
// domain and "@x" is always a person, in every field, with no heuristic between them.
|
|
7
|
+
export const USERNAME_RE = /^[a-z0-9][a-z0-9_]{2,29}$/
|
|
8
|
+
export const EMAIL_RE = /^[^@\s]+@[^@\s]+\.[^@\s]+$/
|
|
9
|
+
export const RESERVED = new Set([
|
|
10
|
+
'admin', 'administrator', 'witbitz', 'witbitzchat', 'support', 'help', 'root', 'system', 'sys', 'assistant', 'agent',
|
|
11
|
+
'agents', 'bot', 'bots', 'official', 'staff', 'team', 'security', 'abuse', 'postmaster', 'noreply', 'null', 'undefined',
|
|
12
|
+
'anonymous', 'guest', 'everyone', 'all', 'here', 'me', 'you', 'space', 'spaces', 'room', 'rooms',
|
|
13
|
+
])
|
|
14
|
+
|
|
15
|
+
/** NFKC → trim → lowercase, and ONE leading "@" stripped. */
|
|
16
|
+
export function normUsername(s) {
|
|
17
|
+
const n = String(s == null ? '' : s).normalize('NFKC').trim().toLowerCase()
|
|
18
|
+
return n.startsWith('@') ? n.slice(1) : n
|
|
19
|
+
}
|
|
20
|
+
/** The canonical username, or null. */
|
|
21
|
+
export function validUsername(s) {
|
|
22
|
+
if (typeof s !== 'string') return null
|
|
23
|
+
const n = normUsername(s)
|
|
24
|
+
if (!USERNAME_RE.test(n) || RESERVED.has(n)) return null
|
|
25
|
+
return n
|
|
26
|
+
}
|
|
27
|
+
/** What was typed: `{ kind:'email', email }` (lowercased), `{ kind:'username', username }` (canonical, typed WITH a
|
|
28
|
+
* leading @), or null. A bare word is neither; "@x.y" is a domain, not a person, and is refused here. */
|
|
29
|
+
export function parseAddress(s) {
|
|
30
|
+
const t = String(s == null ? '' : s).trim()
|
|
31
|
+
if (!t) return null
|
|
32
|
+
if (t.startsWith('@')) { const u = validUsername(t); return u ? { kind: 'username', username: u } : null }
|
|
33
|
+
const e = t.toLowerCase()
|
|
34
|
+
return EMAIL_RE.test(e) ? { kind: 'email', email: e } : null
|
|
35
|
+
}
|
|
36
|
+
/** The one canonical string an address is keyed by everywhere (contacts, the picker's selection, the reach cache):
|
|
37
|
+
* the lowercased email, or "@" + the canonical username. null for anything else. */
|
|
38
|
+
export function addressKey(s) {
|
|
39
|
+
const a = parseAddress(s)
|
|
40
|
+
return a ? (a.kind === 'email' ? a.email : '@' + a.username) : null
|
|
41
|
+
}
|
|
42
|
+
export const isUsernameKey = (k) => typeof k === 'string' && k.startsWith('@')
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
// agentDoorTools.js — the two tools of a Witbitz member's door (agents.witbitz.chat/mcp/<handle>), as the Sentinel lists them
|
|
2
|
+
// (infra/cloud-computer/sentinel/mcpDoor.mjs TOOLS, held equal by spaces/test/agentDoorTools.test.mjs). A connection whose key only
|
|
3
|
+
// the vault holds cannot be listed by the Sentinel ("opens only with its key now"); its tools are these, known in advance.
|
|
4
|
+
export const AGENT_DOOR_HOST = 'agents.witbitz.chat'
|
|
5
|
+
export const AGENT_DOOR_TOOLS = Object.freeze([
|
|
6
|
+
{
|
|
7
|
+
name: 'message_member',
|
|
8
|
+
title: 'Message the member',
|
|
9
|
+
description: 'Send a message to the member who gave you this connection — a question, an update, or the result of a task they gave you. It lands in their private assistant, sealed so that only their own devices can read it. This call waits up to about 45 seconds for the answer and returns it when it comes in time — an assistant that answers on its own (one kept always on) usually does. Otherwise it returns a task_id and the state; then call get_reply with that task_id later (a person may take hours). To continue the same conversation, pass the task_id you got before.',
|
|
10
|
+
inputSchema: { type: 'object', properties: { text: { type: 'string', description: 'What to send (plain text, up to 8,000 characters).' }, task_id: { type: 'string', description: 'Optional: an earlier task_id, to continue that conversation.' } }, required: ['text'], additionalProperties: false },
|
|
11
|
+
annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: true },
|
|
12
|
+
},
|
|
13
|
+
{
|
|
14
|
+
name: 'get_reply',
|
|
15
|
+
title: 'Get the member’s reply',
|
|
16
|
+
description: 'The state of a message you sent with message_member, and the member’s reply once there is one. States: waiting (not read yet), read (the member has it), question (the member asked you something back — answer with message_member and the same task_id), answered, declined, expired.',
|
|
17
|
+
inputSchema: { type: 'object', properties: { task_id: { type: 'string' } }, required: ['task_id'], additionalProperties: false },
|
|
18
|
+
annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
|
|
19
|
+
},
|
|
20
|
+
])
|
|
21
|
+
|
|
22
|
+
/** The member's agent advertises these two tools even before the Sentinel can read a cached list. */
|
|
23
|
+
export async function listGrantTools(host, list) {
|
|
24
|
+
try { return await list() } catch (error) {
|
|
25
|
+
if (host !== AGENT_DOOR_HOST || !/opens only with its key/.test(String(error?.message || error))) throw error
|
|
26
|
+
return { tools: AGENT_DOOR_TOOLS.map(t => ({ ...t, readOnly: t.annotations?.readOnlyHint === true })) }
|
|
27
|
+
}
|
|
28
|
+
}
|
package/attestedBox.js
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
// attestedBox.js — THE ATTESTED BOX: how an attested room's key reaches a new member (docs/the-attested-client.md § The
|
|
2
|
+
// attested backup — "Invites go INTO the attested backup, never in a link"; docs/emulated-attested-rooms.md step 4). General
|
|
3
|
+
// over KINDS (attestedRooms.js): each kind has its own box — an ECDH key pair and an inbox — beside the account's ordinary
|
|
4
|
+
// invite box (inviteEnroll.js), published in the same directory row under its own APP slot (`spaces.<kind>`). Its PRIVATE half
|
|
5
|
+
// is kept on the device under its own name and travels only in that kind's attested backup — never in the regular backup or
|
|
6
|
+
// the room list (neither knows this key exists). An invite to an attested room is sealed to the invitee's box OF THAT KIND,
|
|
7
|
+
// carries no link, and is opened only by a device whose bridge serves the kind. A member with no such app gets nothing.
|
|
8
|
+
|
|
9
|
+
export const boxApp = (kind) => 'spaces.' + kind // the directory slot (agent/spaceHandler.mjs dirSlot: one row, one slot per app)
|
|
10
|
+
const KEY = (kind) => 'space:attestedBox:' + kind
|
|
11
|
+
const b64u = (bytes) => btoa(String.fromCharCode(...bytes)).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')
|
|
12
|
+
|
|
13
|
+
export function loadBox (kind) { try { const b = JSON.parse(localStorage.getItem(KEY(kind)) || 'null'); return b && b.boxPub && b.boxPriv && b.inbox ? b : null } catch { return null } }
|
|
14
|
+
export function saveBox (kind, box) { try { localStorage.setItem(KEY(kind), JSON.stringify({ boxPub: box.boxPub, boxPriv: box.boxPriv, inbox: box.inbox })) } catch { /* private mode */ } }
|
|
15
|
+
/** This device's box for `kind`: the one it has, else a new one (the caller pulls the kind's backup FIRST, so every device
|
|
16
|
+
* of the account adopts one box instead of each minting its own). */
|
|
17
|
+
export async function ensureBox (kind, { genRecipientKey }) {
|
|
18
|
+
const have = loadBox(kind); if (have) return have
|
|
19
|
+
const kp = await genRecipientKey()
|
|
20
|
+
const box = { boxPub: kp.publicJwk, boxPriv: kp.privateJwk, inbox: b64u(crypto.getRandomValues(new Uint8Array(18))) }
|
|
21
|
+
saveBox(kind, box)
|
|
22
|
+
return box
|
|
23
|
+
}
|
|
24
|
+
/** Publish the box in the account's directory row (the same proof as the ordinary slot: a sign-in whose blinded email IS the
|
|
25
|
+
* handle). → { ok } | { ok:false, reason }. */
|
|
26
|
+
export async function publishBox (kind, { box, handle, idToken, client, scope = '' }) {
|
|
27
|
+
if (!box || !handle || !idToken || !client) return { ok: false, reason: 'bad_args' }
|
|
28
|
+
const r = await client.dirPut(handle, { boxPub: box.boxPub, inbox: box.inbox }, idToken, scope, boxApp(kind))
|
|
29
|
+
return r && r.status === 200 ? { ok: true } : { ok: false, reason: 'dir_put_failed:' + (r ? r.status : 'net') }
|
|
30
|
+
}
|
package/attestedRooms.js
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
// attestedRooms.js — WHICH ROOMS REQUIRE AN ATTESTED APP, and so must never leave this device in the regular backup or the
|
|
2
|
+
// account's room list (docs/the-attested-client.md § The attested backup, step 1; the owner, 2026-10-12: "we should have an
|
|
3
|
+
// attested backup blob separate from the regular blob" → "Yes" to step 1).
|
|
4
|
+
//
|
|
5
|
+
// A room is attested when its owner-signed policy carries `requireAttestation` (agent/attestation.mjs) — learned here when
|
|
6
|
+
// the app verifies the room's governance (spaceClient.governance → ownerPolicy.verifyRoomGovernance). From then on its key
|
|
7
|
+
// is kept OUT of: the regular backup (backup.js gatherBackup, and the merged blob before a push), the account's room list
|
|
8
|
+
// (roomSync.js pushIndexRoom), so a browser restoring the account — even with the recovery code and the email — never gets
|
|
9
|
+
// it. Until the attested backup exists (step 2: released by the enclave / the Space Lambda after a fresh attestation) such a
|
|
10
|
+
// key lives on this device only. No attested room can exist yet (no owner may require it on the hosted service, and there
|
|
11
|
+
// is no attested app), so nothing is lost by that.
|
|
12
|
+
//
|
|
13
|
+
// The list holds room ids only (like space:enclaveRooms), and only ever grows: a room never stops being attested here.
|
|
14
|
+
|
|
15
|
+
// KINDS (the owner, 2026-10-18: "Do this code general so we can reuse it as is for the attested rooms"). One code path for every
|
|
16
|
+
// attested room; the KIND says which client proves it and which attested backup holds its key:
|
|
17
|
+
// attested — the Witbitz app on iPhone, Android or Mac: the attested backup, released to the device's fresh attestation;
|
|
18
|
+
// Every kind stays out of the regular backup and the account's room list (isAttestedRoom covers them all).
|
|
19
|
+
// windows — the Windows app (windows/attested-client; level `windows`): a key in a genuine TPM, never an app — ITS OWN backup
|
|
20
|
+
// (agent/attestedBackup.mjs KINDS.windows; the owner, 2026-11-09: "Its own Windows backup"), so a Windows proof never
|
|
21
|
+
// opens the phones' keys. Listed FIRST: a room made before the kind existed sits in 'attested' too, and is a Windows room.
|
|
22
|
+
export const KINDS = Object.freeze(['windows', 'attested'])
|
|
23
|
+
// RETIRED (the owner, 2026-11-22: "We dont need any emulation rooms"): the emulated kind — a browser vouching for itself. A room a
|
|
24
|
+
// device marked as one stays out of the regular backup and the room list (a room never stops being attested here), but nothing
|
|
25
|
+
// proves it any more: it has no kind, no bridge and no backup.
|
|
26
|
+
const KEYS = { windows: 'space:winAttestedRooms', attested: 'space:attestedRooms', retired: 'space:emuAttestedRooms' }
|
|
27
|
+
// Read from storage EVERY time — no module-level copy: three modules ask (space.js marks, backup.js and roomSync.js leave
|
|
28
|
+
// out), and a stale copy in one of them is a key in the backup.
|
|
29
|
+
const load = (kind) => { try { const a = JSON.parse(localStorage.getItem(KEYS[kind]) || '[]'); return new Set(Array.isArray(a) ? a.filter((r) => typeof r === 'string' && r) : []) } catch { return new Set() } }
|
|
30
|
+
|
|
31
|
+
/** The room's kind, or null for an ordinary room. */
|
|
32
|
+
export const attestedKindOf = (room) => (room ? KINDS.find((k) => load(k).has(room)) || null : null)
|
|
33
|
+
export const isAttestedRoom = (room) => !!attestedKindOf(room) || (!!room && load('retired').has(room)) // any kind, a retired one too: never in the regular backup or the room list
|
|
34
|
+
export const attestedRooms = (kind = 'attested') => (KEYS[kind] ? [...load(kind)].filter((r) => attestedKindOf(r) === kind) : []) // a room in two lists is the first kind's
|
|
35
|
+
/** Every room whose key the key worker keeps in memory only: each kind's, and the retired ones a device learned before
|
|
36
|
+
* (space.js l1.volatile — a retired room's key, if it ever comes back, must stay off the disk as before). */
|
|
37
|
+
export const volatileAttestedRooms = () => [...new Set([...KINDS.flatMap((k) => attestedRooms(k)), ...load('retired')])]
|
|
38
|
+
// THE OFFLINE COPY MAY INCLUDE AN ATTESTED ROOM — only when the person says so (owner, 2026-11-09: "Offer to include it"). Its key
|
|
39
|
+
// lives in the page's memory alone (space.js _attMk / _attSplit); space.js hands this module a reader so offlineExport.js can
|
|
40
|
+
// ask for it without importing space.js. → { mk } | { userShare, commit } | null.
|
|
41
|
+
let _attKeyOf = null
|
|
42
|
+
export const setAttestedKeyReader = (fn) => { _attKeyOf = typeof fn === 'function' ? fn : null }
|
|
43
|
+
export const attestedKeyOf = (room) => { try { return (_attKeyOf && room && isAttestedRoom(room) && _attKeyOf(room)) || null } catch { return null } }
|
|
44
|
+
export function markAttestedRoom(room, kind = 'attested') {
|
|
45
|
+
if (!room || typeof room !== 'string' || !KEYS[kind]) return false
|
|
46
|
+
const rooms = load(kind); if (rooms.has(room)) return false
|
|
47
|
+
rooms.add(room)
|
|
48
|
+
try { localStorage.setItem(KEYS[kind], JSON.stringify([...rooms])) } catch { /* private mode */ }
|
|
49
|
+
try { globalThis.dispatchEvent && globalThis.dispatchEvent(new CustomEvent('wb-attested-room', { detail: { room, kind } })) } catch { /* no events here */ } // SYNCHRONOUS: the app tells its key worker before any key of this room can reach it
|
|
50
|
+
return true
|
|
51
|
+
}
|
|
52
|
+
/** Does this VERIFIED owner policy require an attested app? (agent/attestation.mjs reads the same field.) */
|
|
53
|
+
export const policyRequiresAttestation = (policy) => !!(policy && policy.requireAttestation && typeof policy.requireAttestation === 'object')
|
|
54
|
+
/** Which kind a VERIFIED policy makes: ONLY windows → 'windows'; ONLY the retired emulation → 'retired' (kept out, never proved); any
|
|
55
|
+
* phone or Mac → 'attested'; none → null. */
|
|
56
|
+
export function policyAttestKind (policy) {
|
|
57
|
+
if (!policyRequiresAttestation(policy)) return null
|
|
58
|
+
const pl = Array.isArray(policy.requireAttestation.platforms) ? policy.requireAttestation.platforms : []
|
|
59
|
+
return pl.length > 0 && pl.every((p) => p === 'emulated') ? 'retired' : pl.length > 0 && pl.every((p) => p === 'windows') ? 'windows' : 'attested'
|
|
60
|
+
}
|
|
61
|
+
/** The bridge platform that answers for a kind: the Windows app for 'windows', the iPhone / Android / Mac app (any other) for 'attested'. */
|
|
62
|
+
export const bridgeServesKind = (platform, kind) => (kind === 'windows' ? platform === 'windows' : kind === 'attested' ? !!platform && platform !== 'emulated' && platform !== 'windows' : false)
|
|
63
|
+
|
|
64
|
+
/** THE SIGNED RULE FOR A CREATE THAT BUILDS ITS OWN REQUEST (space.js createSplitLocal — the hosted app's Spaces and lanes;
|
|
65
|
+
* spaceClient.create does the same for the regular app). `config.requireApp` = the level (Witbitz signs its own apps' rule; no
|
|
66
|
+
* app is named), `config.attestAccept` = the versions the room takes (optional). `ask(room, level, app)` → the server's op
|
|
67
|
+
* owner-policy. → { config, owner }: the rule sealed with the settings and the request flags gone; the rule + this room's
|
|
68
|
+
* signature (+ the versions) to send with the create. null when the config requires no app. No signed rule → throws
|
|
69
|
+
* `attested_not_set`: nothing may be created (the room would come out ordinary while this device marked it attested). */
|
|
70
|
+
export async function withSignedAppRule (config, room, ask) {
|
|
71
|
+
if (!config || !config.requireApp) return null
|
|
72
|
+
const level = String(config.requireApp)
|
|
73
|
+
let g
|
|
74
|
+
try { g = await ask(room, level) } catch (e) { g = { error: String((e && e.message) || e) } }
|
|
75
|
+
if (!g || g.status !== 200 || !g.ownerPolicy || !g.roomAuth) throw Object.assign(new Error('The app requirement could not be set (' + ((g && (g.error || g.status)) || 'no answer') + ') — nothing was created.'), { code: 'attested_not_set' })
|
|
76
|
+
const { requireApp: _r, requireAppId: _a, attestAccept: acc, ...rest } = config // requireAppId: dropped (retired 2026-11-22)
|
|
77
|
+
return { config: { ...rest, ownerPolicy: g.ownerPolicy }, owner: { ownerPolicy: g.ownerPolicy, roomAuth: g.roomAuth, ...(acc ? { attestAccept: acc } : {}) } }
|
|
78
|
+
}
|
package/awsKey.js
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
// awsKey.js — THE PERSON'S AWS KEY, on the device (docs/aws-keys.md; control-plane/src/lib/awsKeys.mjs). One minted, capped key per
|
|
2
|
+
// person per app for the AWS a Witbitz service spends for them — a cloud computer's hours and disk first. The device makes an
|
|
3
|
+
// Ed25519 pair; only the PUBLIC half goes to the server (POST /v1/spaces/aws-keys with the account's sign-in). The private half
|
|
4
|
+
// stays with the person: in the account's sealed document `awskey` (accountStores.js seals it under the account key, so every
|
|
5
|
+
// device of the account signs with the same key), or the vault's, in vault mode. A service is asked with a signed call.
|
|
6
|
+
//
|
|
7
|
+
// Pure: `fetchImpl` and the store ({ get(), put(rec) }) are given; no DOM, no localStorage.
|
|
8
|
+
|
|
9
|
+
import { creditsNumber, creditsOf, creditsText } from './credits.js' // what a person sees is credits (100 = $1)
|
|
10
|
+
|
|
11
|
+
export const AWS_KEYS_API = 'https://api.witbitz.chat/v1/spaces/aws-keys'
|
|
12
|
+
export const AWS_KEY_DOC = 'awskey' // the account document (sealed: 'xawskey')
|
|
13
|
+
|
|
14
|
+
const b64u = (u8) => { let s = ''; for (const b of u8) s += String.fromCharCode(b); return btoa(s).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '') }
|
|
15
|
+
/** The message the device signs = awsKeys.mjs signedMessage (v1, kept for reference) / signedMessageV2. */
|
|
16
|
+
export const signedMessage = (op, keyId, ts) => `wbaws-v1|${op}|${keyId}|${ts}`
|
|
17
|
+
// State machines pass 7: every signed call carries a fresh nonce the server accepts once — a captured call cannot be sent again.
|
|
18
|
+
export const signedMessageV2 = (op, keyId, ts, nonce) => `wbaws-v2|${op}|${keyId}|${ts}|${nonce}`
|
|
19
|
+
|
|
20
|
+
const coded = (code, message, extra = {}) => Object.assign(new Error(message || code), { code, ...extra })
|
|
21
|
+
const isRec = (r) => !!r && typeof r === 'object' && typeof r.keyId === 'string' && r.signPriv && typeof r.signPub === 'string'
|
|
22
|
+
|
|
23
|
+
/** A fresh pair: { signPub (raw, base64url), signPriv (JWK) }. Throws 'no_ed25519' where the browser lacks it. */
|
|
24
|
+
export async function newAwsKeyPair () {
|
|
25
|
+
let k
|
|
26
|
+
try { k = await crypto.subtle.generateKey({ name: 'Ed25519' }, true, ['sign', 'verify']) } catch { throw coded('no_ed25519', 'This browser cannot make the key (it lacks Ed25519) — update it, or use another device.') }
|
|
27
|
+
return { signPub: b64u(new Uint8Array(await crypto.subtle.exportKey('raw', k.publicKey))), signPriv: await crypto.subtle.exportKey('jwk', k.privateKey) }
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** { keyId, ts, nonce, sig } for one op, signed with the person's key. */
|
|
31
|
+
export async function signAws (rec, op, now = Date.now()) {
|
|
32
|
+
if (!isRec(rec)) throw coded('no_aws_key', 'this account has no AWS key yet')
|
|
33
|
+
const ts = Math.floor(now / 1000)
|
|
34
|
+
const nonce = b64u(crypto.getRandomValues(new Uint8Array(16)))
|
|
35
|
+
const k = await crypto.subtle.importKey('jwk', rec.signPriv, { name: 'Ed25519' }, false, ['sign'])
|
|
36
|
+
const sig = new Uint8Array(await crypto.subtle.sign({ name: 'Ed25519' }, k, new TextEncoder().encode(signedMessageV2(op, rec.keyId, ts, nonce))))
|
|
37
|
+
return { keyId: rec.keyId, ts, nonce, sig: b64u(sig) }
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
async function post (fetchImpl, url, body) {
|
|
41
|
+
const r = await fetchImpl(url, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) })
|
|
42
|
+
let j = null
|
|
43
|
+
try { j = await r.json() } catch { /* not JSON */ }
|
|
44
|
+
if (!r.ok) { const e = (j && j.error) || {}; throw coded(e.code || 'http_' + r.status, e.message || `the AWS key service answered ${r.status}`, { status: r.status }) }
|
|
45
|
+
return (j && j.data) || j
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* The account's AWS key, minted the first time. With one already in the sealed document, that one (no call). Two devices minting
|
|
50
|
+
* at once: the second is refused (aws_key_exists) and takes the first's from the document. A key the server has but no
|
|
51
|
+
* document holds (the record was lost) → 'aws_key_lost': replacing it is the person's choice (`replace: true`).
|
|
52
|
+
* opts: { token (sign-in), store: { get, put }, app?: 'regular' | 'vaulted', replace?, fetchImpl?, api? }
|
|
53
|
+
*/
|
|
54
|
+
// approve(signPub) → { statement, sig } (account recovery v2, § 8.8): an active device's approval of the new key — required
|
|
55
|
+
// by the mint once the account signed devices out; omitted otherwise.
|
|
56
|
+
export async function ensureAwsKey ({ token, store, app = '', replace = false, approve = null, fetchImpl = (...a) => fetch(...a), api = AWS_KEYS_API } = {}) {
|
|
57
|
+
const have = await store.get()
|
|
58
|
+
if (isRec(have) && !replace) return have
|
|
59
|
+
const pair = await newAwsKeyPair()
|
|
60
|
+
let out
|
|
61
|
+
try {
|
|
62
|
+
const v2 = approve ? await approve(pair.signPub) : null
|
|
63
|
+
out = await post(fetchImpl, api, { idToken: token, signPub: pair.signPub, ...(app ? { app } : {}), ...(replace ? { replace: true } : {}), ...(v2 ? { v2 } : {}) })
|
|
64
|
+
} catch (e) {
|
|
65
|
+
if (e.code !== 'aws_key_exists') throw e
|
|
66
|
+
const again = await store.get()
|
|
67
|
+
if (isRec(again)) return again
|
|
68
|
+
throw coded('aws_key_lost', 'This account has an AWS key, but no device record holds it. Replacing it keeps this month\'s spending.')
|
|
69
|
+
}
|
|
70
|
+
const rec = { v: 1, keyId: out.keyId, signPub: pair.signPub, signPriv: pair.signPriv, tier: out.tier, capUsd: out.capUsd, at: Date.now() }
|
|
71
|
+
await store.put(rec)
|
|
72
|
+
return rec
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** { live, tier, month: { usd, capUsd, byKind }, resetsAt } — or { live: false, why }. */
|
|
76
|
+
export async function awsKeyStatus (rec, { fetchImpl = (...a) => fetch(...a), api = AWS_KEYS_API, now = Date.now() } = {}) {
|
|
77
|
+
return post(fetchImpl, api + '/status', await signAws(rec, 'status', now))
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** The month as a row of Settings → Your usage (the owner, 2026-10-24: "It should be under usage"): { label, value, note } —
|
|
81
|
+
* "Cloud computers", "46 of 5,000 credits", "starts again on 1 November". The key is general (docs/aws-keys.md), but cloud computers
|
|
82
|
+
* are all that charge it today. null = no row. */
|
|
83
|
+
export function awsUsageRow (st) {
|
|
84
|
+
if (!st || typeof st !== 'object') return null
|
|
85
|
+
if (st.live === false) return st.why === 'paused' ? { label: 'Cloud computers', value: 'paused', note: '' } : null
|
|
86
|
+
const m = st.month || {}
|
|
87
|
+
const usd = Number(m.usd), cap = Number(m.capUsd)
|
|
88
|
+
if (!Number.isFinite(usd) || !(cap > 0)) return null
|
|
89
|
+
let when = ''
|
|
90
|
+
try { when = st.resetsAt ? 'starts again on ' + new Date(st.resetsAt).toLocaleDateString('en-GB', { day: 'numeric', month: 'long', timeZone: 'UTC' }) : '' } catch { when = '' }
|
|
91
|
+
const note = [st.tier === 'free' ? 'the free allowance' : '', usd >= cap ? 'used up' : '', when].filter(Boolean).join(' · ')
|
|
92
|
+
return { label: 'Cloud computers', value: `${creditsNumber(creditsOf(usd))} of ${creditsText(creditsOf(cap))}`, note } // credits (100 = $1); the key keeps dollars
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** Revoke with the device's signature (the sign-in route is the account's, for a device that lost the record). */
|
|
96
|
+
export async function revokeAwsKey (rec, { fetchImpl = (...a) => fetch(...a), api = AWS_KEYS_API, now = Date.now() } = {}) {
|
|
97
|
+
return post(fetchImpl, api + '/revoke', await signAws(rec, 'revoke', now))
|
|
98
|
+
}
|
package/backupRecord.js
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
// backupRecord.js — THE BACKUP RECORD'S RULES, pure (docs/sdk-account-format-plan.md, phase 1). The account's backup is one
|
|
2
|
+
// sealed record in the vault (accountRecord.js says whose it is); these are the rules that build what a device puts in it and
|
|
3
|
+
// what a restore takes back out. They lived inside backup.js's gatherBackup and applyBackup, next to the page's storage; here
|
|
4
|
+
// they take state in and give state out — no storage, no DOM, no page state — so the SDK restores through the same rules.
|
|
5
|
+
// backup.js reads the device, calls them and writes what they say; what the app writes and applies is unchanged
|
|
6
|
+
// (spaces/test/accountFormatGolden.test.mjs holds it).
|
|
7
|
+
import { vaultOwner } from './accountRecord.js'
|
|
8
|
+
import { mergeRoomDefaults } from './roomDefaultPrefs.js'
|
|
9
|
+
import { mergeChatLocks } from './chatLock.js'
|
|
10
|
+
|
|
11
|
+
const noAttested = () => false
|
|
12
|
+
|
|
13
|
+
/** A backup's tombstones, kept to the shape store.js writes ({ room: at }) — a blob is data from storage, not trusted shape. */
|
|
14
|
+
export function cleanTombstones (t) {
|
|
15
|
+
const out = {}
|
|
16
|
+
if (!t || typeof t !== 'object' || Array.isArray(t)) return out
|
|
17
|
+
for (const r of Object.keys(t)) if (typeof r === 'string' && r && r.length <= 200) out[r] = Number(t[r]) || 1
|
|
18
|
+
return out
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** THE ORPHAN RULE: every room whose key is on this device belongs in the backup, not just the ones on the list. The list is
|
|
22
|
+
* bounded, and a Space that fell off it used to be absent from every backup while it went on working here — gone for good
|
|
23
|
+
* with the device. `storageKeys` = the names this device's storage holds; a name under `prefixes.mk` (a normal room's key)
|
|
24
|
+
* or `prefixes.us` (a split room's share) whose room is not on `recents` gets a minimal row: the KEY is what matters. Never
|
|
25
|
+
* titled with the raw room id (it would show as "sp-…" in the drawer). */
|
|
26
|
+
export function orphanRows (recents, storageKeys, { mk, us }) {
|
|
27
|
+
const listed = new Set((recents || []).map((r) => r && r.room).filter(Boolean))
|
|
28
|
+
const orphans = []
|
|
29
|
+
for (const k of storageKeys || []) {
|
|
30
|
+
let rm = null
|
|
31
|
+
if (k && k.indexOf(mk) === 0) rm = k.slice(mk.length)
|
|
32
|
+
else if (k && k.indexOf(us) === 0) rm = k.slice(us.length)
|
|
33
|
+
if (rm && !listed.has(rm)) { orphans.push({ room: rm, title: '', at: 0 }); listed.add(rm) }
|
|
34
|
+
}
|
|
35
|
+
return orphans
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** The record a device backs up, from what it holds. `recents` + `orphans` are the rooms (an ATTESTED room — `isAttested` —
|
|
39
|
+
* stays on its device: neither its row nor its key); `keyOf(room)` is one room's key entry as this device holds it.
|
|
40
|
+
* An empty `name` never blanks a backed-up one (mergeBackups' {...remote,...local} would let '' win), so it is left out;
|
|
41
|
+
* `code` is the escrowed recovery code (security-neutral: whoever holds the master has the account already). `extra` is
|
|
42
|
+
* what ANOTHER store holds for the account (backup.js setAccountFieldSource: the hosted vault reads the framed app's copy) —
|
|
43
|
+
* a field this record already has wins; its contacts only where this device has none; its room defaults merged in. */
|
|
44
|
+
export function recordOf ({
|
|
45
|
+
at = Date.now(), recents = [], orphans = [], isAttested = noAttested, keyOf = () => ({}), tombstones = {}, name = '',
|
|
46
|
+
contacts = [], pipesRoom = null, msgsRoom = null, indexRoom = null, inviteKey = null, acctKey = null, code = '',
|
|
47
|
+
connectionKeys = {}, connGone = null, siri = null, a2a = null, defaultRoom = null, chatLocks = null, extra = {},
|
|
48
|
+
} = {}) {
|
|
49
|
+
const all = recents.concat(orphans).filter((r) => !(r && r.room && isAttested(r.room)))
|
|
50
|
+
const keys = {}
|
|
51
|
+
for (const r of all) {
|
|
52
|
+
if (!r || !r.room) continue
|
|
53
|
+
keys[r.room] = keyOf(r.room)
|
|
54
|
+
}
|
|
55
|
+
const out = { v: 1, at, ...(Object.keys(tombstones).length ? { tombstones } : {}), ...(name ? { name } : {}), recents: all, keys, contacts, ...(pipesRoom ? { pipesRoom } : {}), ...(msgsRoom && msgsRoom.room && msgsRoom.mk ? { msgsRoom } : {}), ...(indexRoom ? { indexRoom } : {}), ...(inviteKey ? { inviteKey } : {}), ...(acctKey ? { acctKey } : {}), ...(code ? { code } : {}), ...(Object.keys(connectionKeys).length ? { connectionKeys } : {}), ...(connGone && Object.keys(connGone).length ? { connGone } : {}), ...(siri ? { siri } : {}), ...(a2a ? { a2a } : {}) }
|
|
56
|
+
if (defaultRoom) out.defaultRoom = defaultRoom
|
|
57
|
+
if (chatLocks) out.chatLocks = chatLocks // THE CHAT LOCK (docs/chat-lock-plan.md): only an account that uses it carries the field — a restored device hides its locked chats before its first sync
|
|
58
|
+
for (const [f, v] of Object.entries(extra)) if (!(f in out)) out[f] = v
|
|
59
|
+
if (Array.isArray(extra.contacts) && extra.contacts.length && !(out.contacts || []).length) out.contacts = extra.contacts // the vault's page has no address book of its own (mergeBackups unions contacts, so an empty list never blanked one)
|
|
60
|
+
const mergedDefaults = mergeRoomDefaults(out.defaultRoom, extra.defaultRoom); if (mergedDefaults) out.defaultRoom = mergedDefaults
|
|
61
|
+
if (out.chatLocks || extra.chatLocks) { const ml = mergeChatLocks(out.chatLocks, extra.chatLocks); if (ml) out.chatLocks = ml }
|
|
62
|
+
return out
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** What a restore of record `p` writes on this device, as data — or null when `p` is not an account record of `app` (each
|
|
66
|
+
* app opens only its own vault's record: accountRecord.js vaultOwner, both directions). `local` = this device's state (or a
|
|
67
|
+
* function that reads it, called only for a record this app opens): { tombstones, recents, isAttested, myName, msgsRoom,
|
|
68
|
+
* pipesRoom, indexRoom, acctKey, inviteKey, code }.
|
|
69
|
+
* → { tombstones (the account's deletes, adopted), newTombstones (it grew: save it), add (rows restored), recents (the list
|
|
70
|
+
* to save, or null), fills ([{ room, slot: 'mk'|'us'|'spc'|'model'|'gate'|'id'|'sign', value }] — each written ONLY where
|
|
71
|
+
* this device holds none), name, msgsRoom, pipesRoom, indexRoom, acctKey, inviteKey, code (each null/'' = keep this
|
|
72
|
+
* device's), and defaultRoom, contacts, connectionKeys + connGone, siri, a2a (merged into this device's own) }. */
|
|
73
|
+
export function applyPlan (p, local = {}, { app = 'spaces' } = {}) {
|
|
74
|
+
if (!p || !Array.isArray(p.recents)) return null
|
|
75
|
+
if (vaultOwner(p) !== app) return null
|
|
76
|
+
const L = (typeof local === 'function' ? local() : local) || {}
|
|
77
|
+
const mine = L.tombstones || {}, cur = L.recents || [], isAttested = L.isAttested || noAttested
|
|
78
|
+
// ⚑ A DELETE MUST SURVIVE A RESTORE. The blob is a snapshot, so one taken BEFORE a delete still carries that room's key and
|
|
79
|
+
// its recents row — restoring it handed the key back to a Space the user destroyed. Checked for BOTH halves: the device's
|
|
80
|
+
// deletes and the account's (the record carries them), and a resurrected row is as wrong as a resurrected key.
|
|
81
|
+
const tomb = { ...cleanTombstones(p.tombstones), ...mine }
|
|
82
|
+
const have = new Set(cur.map((r) => r.room))
|
|
83
|
+
const add = p.recents.filter((r) => r && r.room && !have.has(r.room) && !tomb[r.room])
|
|
84
|
+
const fills = []
|
|
85
|
+
const fill = (room, slot, value) => { if (value != null) fills.push({ room, slot, value }) }
|
|
86
|
+
for (const rm of Object.keys(p.keys || {})) {
|
|
87
|
+
const e = p.keys[rm]; if (!e || tomb[rm]) continue
|
|
88
|
+
// SPLIT room → userShare + commit (NEVER an mk); normal room → mk. (tenant-split-key-dualstore.md)
|
|
89
|
+
if (isAttested(rm)) { /* an ATTESTED room's key is never written at rest (docs/emulated-attested-rooms.md): the caller keeps it in memory */ }
|
|
90
|
+
else if (e.split && e.userShare) { fill(rm, 'us', e.userShare); fill(rm, 'spc', e.commit) }
|
|
91
|
+
else { fill(rm, 'mk', e.mk) }
|
|
92
|
+
fill(rm, 'model', e.model); fill(rm, 'gate', e.gate); fill(rm, 'id', e.id); fill(rm, 'sign', e.sign)
|
|
93
|
+
}
|
|
94
|
+
const ptr = (x, held) => (x && x.room && x.mk && !held ? x : null) // a room minted on another device is adopted, never over this one's
|
|
95
|
+
return {
|
|
96
|
+
tombstones: tomb, newTombstones: Object.keys(tomb).length > Object.keys(mine).length,
|
|
97
|
+
add, recents: add.length || cur.some(r => tomb[r.room]) ? cur.filter(r => !tomb[r.room]).concat(add).sort((a, b) => (b.at || 0) - (a.at || 0)) : null,
|
|
98
|
+
fills,
|
|
99
|
+
name: p.name && !L.myName ? p.name : '', // a name typed here is never replaced; a waiting name prompt is answered
|
|
100
|
+
msgsRoom: ptr(p.msgsRoom, L.msgsRoom), pipesRoom: ptr(p.pipesRoom, L.pipesRoom), indexRoom: ptr(p.indexRoom, L.indexRoom),
|
|
101
|
+
acctKey: p.acctKey && p.acctKey.priv && !L.acctKey ? p.acctKey : null, // the account signing key: adopted, never clobbering a local one
|
|
102
|
+
inviteKey: p.inviteKey && p.inviteKey.boxPriv && !L.inviteKey ? p.inviteKey : null, // invites sealed to your boxPub open here too
|
|
103
|
+
code: typeof p.code === 'string' && p.code && !L.code ? p.code : '', // the escrowed recovery code → a passkey/link recovery can Show it
|
|
104
|
+
defaultRoom: p.defaultRoom, chatLocks: p.chatLocks || null, contacts: p.contacts, connectionKeys: p.connectionKeys, connGone: p.connGone, siri: p.siri, a2a: p.a2a,
|
|
105
|
+
}
|
|
106
|
+
}
|
package/backupVault.js
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
// spaces/public/backupVault.js
|
|
2
|
+
//
|
|
3
|
+
// Clean account-backup model:
|
|
4
|
+
// 1. A random 32-byte master secret identifies and encrypts the backup.
|
|
5
|
+
// 2. Each recovery method stores one wrapper: the master secret encrypted to that method's secret.
|
|
6
|
+
// 3. Restoring with any enrolled method opens its wrapper, gets the same master secret, then opens the one backup.
|
|
7
|
+
//
|
|
8
|
+
// The server remains content-blind. It stores opaque blobs by derived ids and never receives a recovery code, passkey
|
|
9
|
+
// secret, backup key, or plaintext.
|
|
10
|
+
import { deriveKeysFromSecret, seal, unseal } from './recovery.js'
|
|
11
|
+
|
|
12
|
+
const enc = new TextEncoder()
|
|
13
|
+
const WRAP_LABEL = enc.encode('witbitz:backup-wrapper:v2')
|
|
14
|
+
|
|
15
|
+
const b64 = (u8) => {
|
|
16
|
+
let s = ''
|
|
17
|
+
for (let i = 0; i < u8.length; i++) s += String.fromCharCode(u8[i])
|
|
18
|
+
return btoa(s)
|
|
19
|
+
}
|
|
20
|
+
const ub64 = (s) => {
|
|
21
|
+
const b = atob(s)
|
|
22
|
+
const u = new Uint8Array(b.length)
|
|
23
|
+
for (let i = 0; i < b.length; i++) u[i] = b.charCodeAt(i)
|
|
24
|
+
return u
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export function newMasterSecret() {
|
|
28
|
+
return crypto.getRandomValues(new Uint8Array(32))
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
async function wrapperSecret(credentialSecret) {
|
|
32
|
+
if (!credentialSecret || credentialSecret.length < 16) throw new Error('bad_secret')
|
|
33
|
+
const buf = new Uint8Array(credentialSecret.length + WRAP_LABEL.length)
|
|
34
|
+
buf.set(credentialSecret)
|
|
35
|
+
buf.set(WRAP_LABEL, credentialSecret.length)
|
|
36
|
+
return new Uint8Array(await crypto.subtle.digest('SHA-256', buf))
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export async function wrapperLocation(credentialSecret) {
|
|
40
|
+
return deriveKeysFromSecret(await wrapperSecret(credentialSecret))
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export async function backupLocation(masterSecret) {
|
|
44
|
+
if (!masterSecret || masterSecret.length !== 32) throw new Error('bad_master_secret')
|
|
45
|
+
return deriveKeysFromSecret(masterSecret)
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export async function sealWrapper(credentialSecret, masterSecret) {
|
|
49
|
+
const { key } = await wrapperLocation(credentialSecret)
|
|
50
|
+
return seal(key, { v: 2, master: b64(masterSecret) })
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export async function openWrapper(credentialSecret, blob) {
|
|
54
|
+
if (!blob) return null
|
|
55
|
+
try {
|
|
56
|
+
const { key } = await wrapperLocation(credentialSecret)
|
|
57
|
+
const data = await unseal(key, blob)
|
|
58
|
+
const master = data && typeof data.master === 'string' ? ub64(data.master) : null
|
|
59
|
+
return master && master.length === 32 ? master : null
|
|
60
|
+
} catch { return null }
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export async function enrollCredential(transport, credentialSecret, masterSecret) {
|
|
64
|
+
const { id, wt } = await wrapperLocation(credentialSecret)
|
|
65
|
+
return !!(await transport.put(id, await sealWrapper(credentialSecret, masterSecret), wt)) // wt binds the write to the credential secret (see backup.js write-auth)
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export async function unlockMaster(transport, credentialSecret) {
|
|
69
|
+
let loc
|
|
70
|
+
try { loc = await wrapperLocation(credentialSecret) } catch { return null }
|
|
71
|
+
const blob = await transport.get(loc.id)
|
|
72
|
+
return openWrapper(credentialSecret, blob)
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export async function createVault(transport, credentialSecrets) {
|
|
76
|
+
const secrets = (credentialSecrets || []).filter((s) => s && s.length >= 16)
|
|
77
|
+
if (!secrets.length) throw new Error('no_credentials')
|
|
78
|
+
const masterSecret = newMasterSecret()
|
|
79
|
+
const enrolled = []
|
|
80
|
+
for (const secret of secrets) {
|
|
81
|
+
if (await enrollCredential(transport, secret, masterSecret)) enrolled.push(secret)
|
|
82
|
+
}
|
|
83
|
+
if (!enrolled.length) throw new Error('enroll_failed')
|
|
84
|
+
return { masterSecret, enrolled, location: await backupLocation(masterSecret) }
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
export async function replaceCredential(transport, { masterSecret, oldWrapperId, newSecret }) {
|
|
88
|
+
if (!(await enrollCredential(transport, newSecret, masterSecret))) return false
|
|
89
|
+
if (oldWrapperId) {
|
|
90
|
+
try { await transport.put(oldWrapperId, null) } catch { /* stale old wrapper is acceptable */ }
|
|
91
|
+
}
|
|
92
|
+
return true
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
// (Retired 2026-09-03: the v3 "operator-resistant code wrapper" — code AND S=HMAC(GATE_ROOT_KEY,email) folded in — was
|
|
96
|
+
// the aTLS-P2 enclave-gated recovery. SUPERSEDED by passkey-PRF as the operator-resistant tier, docs/recovery-operator-
|
|
97
|
+
// resistance.md. It was additive + never wired into the live restore flow, so this removal is behaviour-neutral.)
|