@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/recovery.js
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
// spaces/public/recovery.js — CONTENT-BLIND backup of your Spaces (the list + each room's key). A device-generated
|
|
2
|
+
// RECOVERY CODE is the only secret. From it we derive, by two SEPARATE HKDF labels: an `id` (which ciphertext on the
|
|
3
|
+
// server is yours) and an AES-GCM `key` (that opens it) — so the id can never reveal the key. The server stores ONLY the
|
|
4
|
+
// ciphertext under the id and can't read it. The code NEVER reaches the server. Lose the code → the backup is
|
|
5
|
+
// unrecoverable (that's the guarantee). Zero deps: pure Web Crypto.
|
|
6
|
+
|
|
7
|
+
const B32 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567' // RFC 4648 base32 (no padding), for a human-savable code
|
|
8
|
+
function b32encode(u8) {
|
|
9
|
+
let bits = 0, val = 0, out = ''
|
|
10
|
+
for (const b of u8) { val = (val << 8) | b; bits += 8; while (bits >= 5) { out += B32[(val >>> (bits - 5)) & 31]; bits -= 5 } }
|
|
11
|
+
if (bits > 0) out += B32[(val << (5 - bits)) & 31]
|
|
12
|
+
return out
|
|
13
|
+
}
|
|
14
|
+
function b32decode(s) {
|
|
15
|
+
const clean = String(s).toUpperCase().replace(/[^A-Z2-7]/g, '') // tolerate spaces/hyphens/case on input
|
|
16
|
+
let bits = 0, val = 0; const out = []
|
|
17
|
+
for (const c of clean) { val = (val << 5) | B32.indexOf(c); bits += 5; if (bits >= 8) { out.push((val >>> (bits - 8)) & 255); bits -= 8 } }
|
|
18
|
+
return new Uint8Array(out)
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
const enc = new TextEncoder(), dec = new TextDecoder()
|
|
22
|
+
const SALT = enc.encode('witbitz-spaces-backup-v1')
|
|
23
|
+
const b64url = (u8) => { let s = ''; for (let i = 0; i < u8.length; i++) s += String.fromCharCode(u8[i]); return btoa(s).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '') }
|
|
24
|
+
const fromB64url = (s) => { const b = atob(String(s).replace(/-/g, '+').replace(/_/g, '/')); const u = new Uint8Array(b.length); for (let i = 0; i < b.length; i++) u[i] = b.charCodeAt(i); return u }
|
|
25
|
+
|
|
26
|
+
/** A fresh 128-bit recovery code as grouped base32, e.g. "ABCD-EFGH-JKLM-NPQR-STUV-WX". */
|
|
27
|
+
export function newRecoveryCode() {
|
|
28
|
+
return b32encode(crypto.getRandomValues(new Uint8Array(16))).match(/.{1,4}/g).join('-')
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
async function hkdf(codeBytes, info, len) {
|
|
32
|
+
const km = await crypto.subtle.importKey('raw', codeBytes, 'HKDF', false, ['deriveBits'])
|
|
33
|
+
return new Uint8Array(await crypto.subtle.deriveBits({ name: 'HKDF', hash: 'SHA-256', salt: SALT, info: enc.encode(info) }, km, len * 8))
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** Derive { id (hex storage key), key (AES-GCM) } from raw secret bytes. Two HKDF labels → id can't reveal key. The
|
|
37
|
+
* secret can be a typed recovery code (below) OR a passkey's PRF output (spacePasskey.js) — same 32B secret, same backup. */
|
|
38
|
+
export async function deriveKeysFromSecret(secretBytes) {
|
|
39
|
+
if (!secretBytes || secretBytes.length < 16) throw new Error('bad_secret')
|
|
40
|
+
const idBytes = await hkdf(secretBytes, 'id', 16)
|
|
41
|
+
const id = Array.from(idBytes, (b) => b.toString(16).padStart(2, '0')).join('')
|
|
42
|
+
const key = await crypto.subtle.importKey('raw', await hkdf(secretBytes, 'enc', 32), { name: 'AES-GCM' }, false, ['encrypt', 'decrypt'])
|
|
43
|
+
// WRITE-AUTHENTICATOR: a third, DISTINCT HKDF label. The server stores only SHA-256(wt) (write-once) and checks it on
|
|
44
|
+
// every overwrite, so an attacker who captured just the `id` (which can't yield wt — different label) can't clobber the
|
|
45
|
+
// backup. wt reveals neither the id nor the AES key nor the code, and it can't decrypt — it only proves "the writer holds
|
|
46
|
+
// the recovery code". Sent to the server per write (functions/api/backup.js) ⇒ gates OUTSIDERS, not a malicious server.
|
|
47
|
+
const wt = Array.from(await hkdf(secretBytes, 'bak-write', 32), (b) => b.toString(16).padStart(2, '0')).join('')
|
|
48
|
+
return { id, key, wt }
|
|
49
|
+
}
|
|
50
|
+
/** The raw 16-byte secret behind a typed recovery code. The backup vault wraps the master secret to this value. */
|
|
51
|
+
export function codeSecret(code) {
|
|
52
|
+
const b = b32decode(code)
|
|
53
|
+
if (b.length < 16) throw new Error('bad_code')
|
|
54
|
+
return b
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** Encrypt an object → base64url(iv‖ciphertext). */
|
|
58
|
+
export async function seal(key, obj) {
|
|
59
|
+
const iv = crypto.getRandomValues(new Uint8Array(12))
|
|
60
|
+
const ct = new Uint8Array(await crypto.subtle.encrypt({ name: 'AES-GCM', iv }, key, enc.encode(JSON.stringify(obj))))
|
|
61
|
+
const buf = new Uint8Array(iv.length + ct.length); buf.set(iv); buf.set(ct, iv.length)
|
|
62
|
+
return b64url(buf)
|
|
63
|
+
}
|
|
64
|
+
/** Decrypt base64url(iv‖ciphertext) → object. Throws on a wrong code or any tamper (AES-GCM auth). */
|
|
65
|
+
export async function unseal(key, blob) {
|
|
66
|
+
const buf = fromB64url(blob)
|
|
67
|
+
const pt = await crypto.subtle.decrypt({ name: 'AES-GCM', iv: buf.slice(0, 12) }, key, buf.slice(12))
|
|
68
|
+
return JSON.parse(dec.decode(pt))
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
// ── 2-of-2 RECOVERY GATE (design A) ──────────────────────────────────────────────────────────────────────────────────
|
|
72
|
+
// Recovery today is BEARER: the code alone opens the backup. Design A adds a server-enforced second factor — "(code) AND
|
|
73
|
+
// (email OR passkey)" — WITHOUT a server-side email↔backup graph. From the SAME secret, two more HKDF labels give a `gid`
|
|
74
|
+
// (where the server's gate record lives — separate from the ciphertext id) and a `gk` (HMAC key). The email commitment
|
|
75
|
+
// HMAC(gk, email) is KEYED by the 128-bit code, so a server that holds only the commitment can neither read nor
|
|
76
|
+
// brute-force the email; at recovery it checks a presented HMAC before mailing a code (stops a leaked code from spraying
|
|
77
|
+
// mail to arbitrary addresses). The code still decrypts — this is a gate IN FRONT of the unchanged bearer secret.
|
|
78
|
+
|
|
79
|
+
const normEmail = (e) => String(e || '').trim().toLowerCase()
|
|
80
|
+
|
|
81
|
+
/** { gid (hex, where the gate record lives), gk (HMAC key bytes) } from the recovery secret. Distinct HKDF labels from
|
|
82
|
+
* deriveKeysFromSecret, so the gate id can't reveal the ciphertext id or key, and vice versa. */
|
|
83
|
+
export async function gateParams(secretBytes) {
|
|
84
|
+
if (!secretBytes || secretBytes.length < 16) throw new Error('bad_secret')
|
|
85
|
+
const gidBytes = await hkdf(secretBytes, 'gate-id', 16)
|
|
86
|
+
const gid = Array.from(gidBytes, (b) => b.toString(16).padStart(2, '0')).join('')
|
|
87
|
+
const gk = await hkdf(secretBytes, 'gate-commit', 32)
|
|
88
|
+
return { gid, gk }
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** A locator (hex) for the gate id, derived from a PASSKEY secret P — so a passkey-only restore (which has no recovery
|
|
92
|
+
* code, hence can't derive the gid) can still find its gate to pass the passkey factor. Distinct HKDF label; a P-holder
|
|
93
|
+
* is already the legitimate passkey user, so this reveals nothing extra. */
|
|
94
|
+
export async function gatePtr(secretBytes) {
|
|
95
|
+
if (!secretBytes || secretBytes.length < 16) throw new Error('bad_secret')
|
|
96
|
+
const b = await hkdf(secretBytes, 'gate-ptr', 16)
|
|
97
|
+
return Array.from(b, (x) => x.toString(16).padStart(2, '0')).join('')
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** Bind an email to this code: HMAC-SHA256(gk, normalized email) → hex. Stored server-side as the gate's `commit_email`;
|
|
101
|
+
* reveals nothing about the email without the code. Normalizes case + surrounding space so the same address always
|
|
102
|
+
* matches. */
|
|
103
|
+
export async function emailCommit(gk, email) {
|
|
104
|
+
const key = await crypto.subtle.importKey('raw', gk, { name: 'HMAC', hash: 'SHA-256' }, false, ['sign'])
|
|
105
|
+
const mac = new Uint8Array(await crypto.subtle.sign('HMAC', key, enc.encode(normEmail(email))))
|
|
106
|
+
return Array.from(mac, (b) => b.toString(16).padStart(2, '0')).join('')
|
|
107
|
+
}
|
package/regions.js
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
// regions.js — a room's home region is IN ITS ID (docs/multi-region.md). One parser for the page, the SDK and the Lambda
|
|
2
|
+
// (agent/spaceHandler.mjs imports this file, as it does roomName.js).
|
|
3
|
+
//
|
|
4
|
+
// sp-k3j9x0a1b2c3 no marker: the default region — every room made before regions existed
|
|
5
|
+
// sp-us-k3j9x0a1b2c3 homed in "us" (tmp-us-… for a temporary room)
|
|
6
|
+
//
|
|
7
|
+
// Only codes in REGIONS count: sp-ci- (CI rooms), sp-rc- (/rc rooms) and the other two-letter prefixes this repo already
|
|
8
|
+
// uses are NOT regions, and spaces/test/regions.test.mjs refuses a table code that collides with one of them.
|
|
9
|
+
// Nothing is looked up — a room's region is known from its id alone, wherever the id is.
|
|
10
|
+
|
|
11
|
+
export const DEFAULT_REGION = 'eu'
|
|
12
|
+
|
|
13
|
+
/** The regions a room can be homed in. `aws` is where its storage and turns run. A code is two lower-case letters. */
|
|
14
|
+
export const REGIONS = Object.freeze({
|
|
15
|
+
eu: Object.freeze({ aws: 'eu-central-1' }),
|
|
16
|
+
us: Object.freeze({ aws: 'us-east-1' }),
|
|
17
|
+
})
|
|
18
|
+
|
|
19
|
+
const MARKED = /^(?:sp|tmp)-([a-z]{2})-[0-9a-z]+$/
|
|
20
|
+
|
|
21
|
+
/** The region a room is homed in: its marker when it names a region in the table, else the default. */
|
|
22
|
+
export function roomRegion(room) {
|
|
23
|
+
const m = MARKED.exec(typeof room === 'string' ? room : '')
|
|
24
|
+
return m && Object.prototype.hasOwnProperty.call(REGIONS, m[1]) ? m[1] : DEFAULT_REGION
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** A deployment's own region, from its /space-config (or the Lambda's env): an exact code in the table, else the default. */
|
|
28
|
+
export function regionCode(cfg) {
|
|
29
|
+
const r = cfg && typeof cfg.region === 'string' ? cfg.region : ''
|
|
30
|
+
return Object.prototype.hasOwnProperty.call(REGIONS, r) ? r : DEFAULT_REGION
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** True when `room` is homed somewhere other than `here`. */
|
|
34
|
+
export const isRemoteRoom = (room, here = DEFAULT_REGION) => roomRegion(room) !== here
|
|
35
|
+
|
|
36
|
+
/** A new room id homed in `region`. In the default region (or an unknown one) it has the old shape exactly, so a
|
|
37
|
+
* single-region deployment makes the same ids it always made. `rand` is for tests. */
|
|
38
|
+
export function newRoomId(region, { prefix = 'sp', rand = () => crypto.getRandomValues(new Uint8Array(8)) } = {}) {
|
|
39
|
+
const tail = Array.from(rand()).map((x) => x.toString(36)).join('').slice(0, 12)
|
|
40
|
+
const marked = region && region !== DEFAULT_REGION && Object.prototype.hasOwnProperty.call(REGIONS, region)
|
|
41
|
+
return `${prefix}-${marked ? region + '-' : ''}${tail}`
|
|
42
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
export const REMOVED_TEXT = 'Removed by Witbitz for breaking the Terms'
|
|
2
|
+
export const SHARED_REMOVED_TEXT = 'Removed in the shared Space'
|
|
3
|
+
/** Replacement, never a merge: no body, media, tool output or attachment references survive. */
|
|
4
|
+
export function removedCopy(e) {
|
|
5
|
+
const { id, ts, name, from, self, verified, user, spk, vspk, sid } = e || {}
|
|
6
|
+
return { id, ts, name, from, self, verified, user, spk, vspk, sid, ...(e?.keyOnly ? { keyOnly: true } : {}), kind: 'text', text: REMOVED_TEXT, removedByWitbitz: true }
|
|
7
|
+
}
|
|
8
|
+
export function sharedRemovedCopy(e) {
|
|
9
|
+
const { id, ts, name, from, self } = e || {}
|
|
10
|
+
return { id, ts, name, from, self, kind: 'text', source: 'shared', text: SHARED_REMOVED_TEXT, sourceRemoved: true }
|
|
11
|
+
}
|
package/renameRefusal.js
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
// renameRefusal.js — WHY a rename was refused, in the room's own words: one table for the ⋯ menu, the drawer and the SDK
|
|
2
|
+
// (sync sweep, 2026-10-11 — every refusal said "admins", also to a signed-out, removed or unlisted member of a room with
|
|
3
|
+
// none). `refused` / `reason` are the title op's answer (roomName.sendRename: { refused: error, reason }).
|
|
4
|
+
export function renameRefusalText ({ refused, reason } = {}) {
|
|
5
|
+
if (refused === 'direct_chat') return 'A direct chat isn’t renamed — each side sees the other person’s name.'
|
|
6
|
+
if (refused === 'not_admin') return 'Only this Space’s admins can rename it.'
|
|
7
|
+
if (refused === 'not_authorized') return reason === 'not_on_list' ? 'Your sign-in isn’t on this Space’s list.' : 'Sign in to rename this Space.'
|
|
8
|
+
return 'Couldn’t rename this Space.'
|
|
9
|
+
}
|
package/replyQuote.js
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
// THE REPLY QUOTE — one rule for the app's reply strip (space.js onReply) and the SDK's `replyTo` (witbitz-sdk.js send).
|
|
2
|
+
// Two copies of it drifted apart once (sync sweep 10-12): what a quote is keyed by, who it names, and its line.
|
|
3
|
+
// key the quoted entry's key (ledgerView.entryKeyOf — how reactions and replies find it)
|
|
4
|
+
// name its sender, "Assistant" for the agent's own, else "someone" (each side says which name field it reads)
|
|
5
|
+
// excerpt the words, whitespace-collapsed, up to 120 characters; else what it carried ("📷 photo", "📎 file"); else ''
|
|
6
|
+
// The excerpt travels with the reply, so the quote still reads after the original scrolls out of the loaded window.
|
|
7
|
+
import { entryKeyOf } from './ledgerView.js'
|
|
8
|
+
|
|
9
|
+
// THE NAME A QUOTE SHOWS (the owner, 2026-10-22: a quote said "alice@example.com" under a header that says
|
|
10
|
+
// "@alice"). The name line puts a verified member's @username in place of their email (messageRender.js); a quote is
|
|
11
|
+
// the same person, so it does too — for a new reply (the entry carries `user`) and for one already sent (the email→username
|
|
12
|
+
// pairs learned from the messages drawn on this device).
|
|
13
|
+
const EMAIL = /^[^@\s]+@[^@\s]+\.[^@\s]+$/
|
|
14
|
+
const usernames = new Map() // email → username, server-attested (messageRender learns them)
|
|
15
|
+
export function learnUsername (email, user) { if (EMAIL.test(String(email || '').trim()) && user) usernames.set(String(email).trim().toLowerCase(), String(user)) }
|
|
16
|
+
/** The name to show for `name` (an email turns into the @username its owner is verified as, when known). */
|
|
17
|
+
export function quoteName (name, user) {
|
|
18
|
+
const n = String(name || '').trim()
|
|
19
|
+
if (!EMAIL.test(n)) return name
|
|
20
|
+
const u = user || usernames.get(n.toLowerCase())
|
|
21
|
+
return u ? '@' + u : name
|
|
22
|
+
}
|
|
23
|
+
export const replyExcerpt = (m) => {
|
|
24
|
+
const t = m && typeof m.text === 'string' ? m.text.replace(/\s+/g, ' ').trim().slice(0, 120) : ''
|
|
25
|
+
return t || (m && Array.isArray(m.images) && m.images.length ? '📷 photo' : (m && Array.isArray(m.files) && m.files.length ? '📎 file' : ''))
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** → { key, name, excerpt } | null (no entry). `name` overrides which field names the sender. */
|
|
29
|
+
export function replyQuote (m, { name } = {}) {
|
|
30
|
+
if (!m || typeof m !== 'object') return null
|
|
31
|
+
let who = name !== undefined ? name : (m.from || m.name)
|
|
32
|
+
if (m.verified === true && typeof m.user === 'string' && m.user) who = quoteName(who, m.user) // as the name line shows them
|
|
33
|
+
return { key: entryKeyOf(m), name: String(who || (m.self ? 'Assistant' : 'someone')).slice(0, 80), excerpt: replyExcerpt(m) }
|
|
34
|
+
}
|
package/reqEnvelope.js
ADDED
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
// spaces/public/reqEnvelope.js — the client's half of the SEALED REQUEST ENVELOPE (docs/confidential-path-sweep-2026-11-05.md,
|
|
2
|
+
// option A; the enclave's half is agent/reqEnvelope.mjs). A confidential room's request is sealed WHOLE to the enclave's
|
|
3
|
+
// attested recipient key, with a one-time ANSWER KEY inside; the enclave seals its answer under that key, so the Space
|
|
4
|
+
// Lambda and the enclave's parent host carry ciphertext both ways.
|
|
5
|
+
//
|
|
6
|
+
// Readable outside (option A — what the front needs to route, mark changes and attach its hints): op, room, the sign-in
|
|
7
|
+
// token, the device key id, a lane's shared room, a decision's yes/no, and that a state call WRITES. Nothing else.
|
|
8
|
+
// Option B (sealsIdentity): the sign-in token goes inside too (docs/confidential-identity-option-b.md).
|
|
9
|
+
// Used only when the LIVE enclave's measured policy says it opens envelopes (env SEALED_REQUESTS = '1').
|
|
10
|
+
import { sealMk, mkAad, newNonce, sealNow } from './mkseal.js'
|
|
11
|
+
|
|
12
|
+
/** Ops that carry no content (or that the Lambda itself answers): they stay as they are. Everything else is sealed. */
|
|
13
|
+
export const PLAIN_OPS = new Set(['create', 'pollsealed', 'blob', 'policy', 'touch', 'purge', 'drop', 'pushdrop', 'user',
|
|
14
|
+
'enclaveattest', 'wake', 'changes', 'changesub', 'changemark', 'attest-accept', 'deviceverify', 'receipts', 'receiptsack',
|
|
15
|
+
// the Lambda answers these itself (agent/enclaveRelay.mjs FRONT_OPS): sealed, it could not read them — device enrollment in an
|
|
16
|
+
// attested confidential room failed (sweep 11-06 #5). spaces/test/frontOpsPlain.test.mjs holds FRONT_OPS ⊆ PLAIN_OPS.
|
|
17
|
+
'attest-enroll', 'device-verify', 'device-verify-result',
|
|
18
|
+
// report: what a member CHOSE to show Witbitz (agent/reportOp.mjs — stored and mailed to reports@, never the enclave); the
|
|
19
|
+
// Lambda must read it, so sealed to the enclave it never arrived from a confidential room (CI 2026-11-07, frontOpsPlain)
|
|
20
|
+
'report'])
|
|
21
|
+
|
|
22
|
+
/** Does this live enclave open envelopes? `attested` is the room's attested facts (enclaveRoute.attestedFacts): the policy
|
|
23
|
+
* text measured to the live PCR17, so the front can neither fake nor strip the answer. */
|
|
24
|
+
/** → true (it opens them) · false (its verified policy says it does not: an older build) · null (UNKNOWN — not attested, or
|
|
25
|
+
* the policy text could not be fetched). UNKNOWN is never read as "no": whoever serves the policy file could otherwise
|
|
26
|
+
* switch the envelope off by failing that one fetch (security review, 2026-11-05). The client refuses a content op then. */
|
|
27
|
+
export const opensEnvelopes = (attested) => {
|
|
28
|
+
if (!attested || !attested.policy || typeof attested.policy !== 'object') return null
|
|
29
|
+
return !!(attested.policy.env && attested.policy.env.SEALED_REQUESTS === '1')
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** OPTION B (docs/confidential-identity-option-b.md): does this live enclave take WHO YOU ARE from inside the envelope (env
|
|
33
|
+
* SEALED_IDENTITY = '1')? Then the sign-in token rides inside, with the hints the device fetched from op `idextras`, and the
|
|
34
|
+
* reads that carry a token (a verified room's) go sealed too. Unknown → false: the token stays outside, as under option A
|
|
35
|
+
* (no content is exposed by that — only who; the content switch is opensEnvelopes, which never reads unknown as no). */
|
|
36
|
+
export const sealsIdentity = (attested) => !!(attested && attested.policy && attested.policy.env && attested.policy.env.SEALED_IDENTITY === '1')
|
|
37
|
+
|
|
38
|
+
/** The content-free ops that carry a sign-in on a verified room, and that the front relays without reading it — sealed under
|
|
39
|
+
* option B so the token is not readable. An open room's read carries no token and stays plain (the asleep read serves it). */
|
|
40
|
+
export const IDENTITY_PLAIN_OPS = new Set(['pollsealed', 'blob', 'policy', 'purge', 'attest-accept'])
|
|
41
|
+
/** What the front reads on a sealed read: the cursor (its first-read tier mark) and the change inbox (the drawer's follow). */
|
|
42
|
+
const READ_OUTSIDE = ['sinceEtag', 'sinceCount', 'changeInbox']
|
|
43
|
+
|
|
44
|
+
/** Does `body` carry a sign-in token (top level or in its message)? */
|
|
45
|
+
export const carriesIdentity = (body) => !!(body && (typeof body.idToken === 'string' || (body.message && typeof body.message === 'object' && typeof body.message.idToken === 'string')))
|
|
46
|
+
|
|
47
|
+
const b64 = (u) => { let s = ''; for (const x of u) s += String.fromCharCode(x); return btoa(s) }
|
|
48
|
+
const unb64 = (s) => Uint8Array.from(atob(String(s || '')), (c) => c.charCodeAt(0))
|
|
49
|
+
const answerAad = ({ room, op, nonce }) => new TextEncoder().encode(`witbitz-answer|v1|${room}|${op}|${nonce}`)
|
|
50
|
+
|
|
51
|
+
/** The readable outside of an envelope: only what the front reads. */
|
|
52
|
+
function outsideOf (body, identity) {
|
|
53
|
+
const o = { op: body.op, room: body.room, enclave: true }
|
|
54
|
+
if (!identity && typeof body.idToken === 'string') o.idToken = body.idToken
|
|
55
|
+
if (body.op === 'pollsealed' || body.op === 'blob') for (const k of READ_OUTSIDE) if (body[k] !== undefined) o[k] = body[k]
|
|
56
|
+
if (typeof body.bridgeRoom === 'string') o.bridgeRoom = body.bridgeRoom
|
|
57
|
+
if (body.op === 'decide' && typeof body.approve === 'boolean') o.approve = body.approve
|
|
58
|
+
if (body.op === 'state' && body.patch !== undefined) o.patch = null // a WRITE (agent/changeFeed.mjs changeIntent) — the patch itself is inside
|
|
59
|
+
// A READ'S device key id too (docs/confidential-attested-rooms.md step 1, 2026-11-08): the front adds that device's enrolment
|
|
60
|
+
// evidence, which the enclave needs to check the read's proof. The proof itself stays inside; the enclave takes nothing else from out here.
|
|
61
|
+
const ra = body.readAttestation && typeof body.readAttestation === 'object' ? body.readAttestation.attestation : null
|
|
62
|
+
// …and its PLATFORM (sync sweep 11-10 #2): a Windows key's record is under win.<keyId> — the front looks there only when told the
|
|
63
|
+
// platform, so a Windows device's sealed reads and turns reached the enclave with no evidence and were refused. Not a secret.
|
|
64
|
+
const plat = (x) => (typeof x.platform === 'string' && /^[a-z]{2,16}$/.test(x.platform) ? { platform: x.platform } : {})
|
|
65
|
+
if (ra && typeof ra === 'object' && typeof ra.keyId === 'string') o.readAttestation = { attestation: { keyId: ra.keyId, ...plat(ra) } }
|
|
66
|
+
const m = body.message
|
|
67
|
+
if (m && typeof m === 'object') {
|
|
68
|
+
const stub = {}
|
|
69
|
+
if (!identity && typeof m.idToken === 'string') stub.idToken = m.idToken
|
|
70
|
+
// the device key id stays outside even under option B: the front adds the enrolled device's evidence from its store, and
|
|
71
|
+
// that store is where a revoked device is struck off (only rooms that require an approved device send one)
|
|
72
|
+
if (m.attestation && typeof m.attestation === 'object' && typeof m.attestation.keyId === 'string') stub.attestation = { keyId: m.attestation.keyId, ...plat(m.attestation) }
|
|
73
|
+
if (Object.keys(stub).length || !identity) o.message = stub
|
|
74
|
+
}
|
|
75
|
+
return o
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** Seal `body` (the request as it would have been sent) into an envelope. → { outer, answer } — send `outer`; keep `answer`
|
|
79
|
+
* to open the reply. */
|
|
80
|
+
export async function sealRequest (body, publicJwk, { identity = false, extras = null } = {}) {
|
|
81
|
+
const key = crypto.getRandomValues(new Uint8Array(32))
|
|
82
|
+
const ts = sealNow(), nonce = newNonce() // the enclave's clock as far as known (mkseal.js, T#2)
|
|
83
|
+
const inner = { ...body, answerKey: b64(key) }
|
|
84
|
+
if (identity && extras && typeof extras === 'object') { // option B: the front's hints, which the device fetched (op idextras)
|
|
85
|
+
if (Array.isArray(extras.userHints) && extras.userHints.length) inner.userHints = extras.userHints
|
|
86
|
+
if (extras.issuerCfg && typeof extras.issuerCfg === 'object') inner.issuerCfg = extras.issuerCfg
|
|
87
|
+
if (Array.isArray(extras.boundHints) && extras.boundHints.length) inner.boundHints = extras.boundHints.slice(0, 4) // the room-pass cutoff's word (agent/reqEnvelope.mjs INSIDE_OK_FIELDS; sync sweep 2026-11-16 #6)
|
|
88
|
+
}
|
|
89
|
+
delete inner.op; delete inner.room; delete inner.enclave
|
|
90
|
+
const envSealed = await sealMk(JSON.stringify(inner), publicJwk, mkAad({ room: body.room, op: body.op + ':env', ts, nonce }))
|
|
91
|
+
return { outer: { ...outsideOf(body, identity), envSealed, envTs: ts, envNonce: nonce }, answer: { key, aad: answerAad({ room: body.room, op: body.op, nonce }) } }
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** Open a reply. A sealed answer → the enclave's response object; a reply with no sealed answer (the Lambda's own: warming,
|
|
95
|
+
* relay failure, a refusal before the enclave) → itself. A sealed answer that does not open → an error, never a guess. */
|
|
96
|
+
//
|
|
97
|
+
// ⛔ A SEALED REQUEST ACCEPTS ONLY A SEALED ANSWER (security review, 2026-11-05): the front holds no key, so an answer it made up
|
|
98
|
+
// must never pass for the enclave's. Without a sealed answer, only a bare REFUSAL is taken — a failure status, ok:false, a few
|
|
99
|
+
// short fields (the Lambda's own: enclave_warming, a relay failure, a front refusal, a transport error) — and nothing else
|
|
100
|
+
// from it. With a sealed answer, nothing from outside is merged in but the HTTP status.
|
|
101
|
+
const REFUSAL_FIELDS = ['error', 'reason', 'detail']
|
|
102
|
+
export async function openAnswer (reply, answer) {
|
|
103
|
+
const status = reply && Number.isInteger(reply.status) ? reply.status : 0
|
|
104
|
+
const sa = reply && reply.sealedAnswer
|
|
105
|
+
if (!sa || typeof sa !== 'object') {
|
|
106
|
+
if (status >= 200 && status < 300) return { status: 502, ok: false, error: 'answer_unsealed', reason: 'the answer to a sealed request came back unsealed — not from the enclave' } // never a 200: a success it is not (sweep 11-06 #1)
|
|
107
|
+
const out = { status, ok: false }
|
|
108
|
+
for (const k of REFUSAL_FIELDS) if (reply && typeof reply[k] === 'string') out[k] = reply[k].slice(0, 300)
|
|
109
|
+
if (reply && reply.warming === true) out.warming = true
|
|
110
|
+
if (reply && reply.confidential === true) out.confidential = true // the front's tier mark — it only ever ADDS the mark
|
|
111
|
+
if (reply && Number.isFinite(reply.now)) out.serverNow = reply.now // an envelope_* refusal carries the enclave's clock (T#2): post() may retry once with it
|
|
112
|
+
// ⛔ a bare 5xx with no code is a CUT-OFF (the API gateway's 30 s on a long confidential turn), not a refusal: the Lambda
|
|
113
|
+
// runs on and stores the reply. Marked 'refused', every long turn read "Not sent" (the owner, 2026-11-11) — left codeless,
|
|
114
|
+
// turnVerdict reads it 'pending' and the poll delivers it, as for a standard room
|
|
115
|
+
if (!out.error && !(status >= 500)) out.error = 'refused'
|
|
116
|
+
return out
|
|
117
|
+
}
|
|
118
|
+
try {
|
|
119
|
+
const k = await crypto.subtle.importKey('raw', answer.key, 'AES-GCM', false, ['decrypt'])
|
|
120
|
+
const pt = await crypto.subtle.decrypt({ name: 'AES-GCM', iv: unb64(sa.iv), additionalData: answer.aad }, k, unb64(sa.ct))
|
|
121
|
+
const inner = JSON.parse(new TextDecoder().decode(pt))
|
|
122
|
+
// as call() does: { status, ...data } — plus the front's `confidential` mark on a first read (enclaveRelay probeConfidential):
|
|
123
|
+
// it only ever ADDS the mark, and a forged one makes the page treat the room MORE carefully, never less
|
|
124
|
+
return { status, ...(inner && typeof inner === 'object' && !Array.isArray(inner) ? inner : {}), ...(reply.confidential === true ? { confidential: true } : {}) }
|
|
125
|
+
} catch { return { status, ok: false, error: 'answer_unopenable', reason: 'the enclave\'s answer could not be opened on this device' } }
|
|
126
|
+
}
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
// Account-scoped room defaults. Pure merge rule shared by live encrypted sync, backup and tenant restore.
|
|
2
|
+
export const ROOM_DEFAULTS_KEY = 'space:default-room'
|
|
3
|
+
export const ROOM_DEFAULTS_DOC = 'room-defaults'
|
|
4
|
+
const BOOLS = ['quick','enclave','verified','lanes','temporary']
|
|
5
|
+
const STRINGS = ['assistant','model']
|
|
6
|
+
const FIELDS = [...BOOLS,...STRINGS]
|
|
7
|
+
let memory = null, notify = () => {}
|
|
8
|
+
export const setRoomDefaultsSync = fn => { notify = typeof fn === 'function' ? fn : () => {} }
|
|
9
|
+
export function cleanRoomDefaults(value) {
|
|
10
|
+
if (!value || typeof value !== 'object' || value.v !== 1) return null
|
|
11
|
+
const out = { v:1, mods:{} }
|
|
12
|
+
for (const key of FIELDS) {
|
|
13
|
+
if (BOOLS.includes(key) ? typeof value[key] !== 'boolean' : typeof value[key] !== 'string' || value[key].length > 200) continue
|
|
14
|
+
out[key] = value[key]
|
|
15
|
+
const at = value.mods?.[key]
|
|
16
|
+
out.mods[key] = Number.isSafeInteger(at) && at >= 0 ? at : 0
|
|
17
|
+
}
|
|
18
|
+
return FIELDS.some(key => key in out) ? out : null
|
|
19
|
+
}
|
|
20
|
+
/** Per-option last-edit wins; equal clocks use a deterministic value order. An absent field never resets one. */
|
|
21
|
+
export function mergeRoomDefaults(a,b) {
|
|
22
|
+
a=cleanRoomDefaults(a);b=cleanRoomDefaults(b)
|
|
23
|
+
if(!a)return b;if(!b)return a
|
|
24
|
+
const out={v:1,mods:{}}
|
|
25
|
+
for(const key of FIELDS){
|
|
26
|
+
const winner=!(key in a)?b:!(key in b)?a:a.mods[key]>b.mods[key]?a:a.mods[key]<b.mods[key]?b:JSON.stringify(a[key])>=JSON.stringify(b[key])?a:b
|
|
27
|
+
if(key in winner){out[key]=winner[key];out.mods[key]=winner.mods[key]}
|
|
28
|
+
}
|
|
29
|
+
// Temporary rooms cannot create durable private assistants. The later of these two edits determines the combination.
|
|
30
|
+
if(out.temporary && out.lanes){if(out.mods.temporary>=out.mods.lanes)out.lanes=false;else out.temporary=false}
|
|
31
|
+
return out
|
|
32
|
+
}
|
|
33
|
+
export function readRoomDefaults(store=globalThis.localStorage) {
|
|
34
|
+
if(memory && store===globalThis.localStorage)return memory
|
|
35
|
+
try {
|
|
36
|
+
const value=cleanRoomDefaults(JSON.parse(store.getItem(ROOM_DEFAULTS_KEY)||'null'))
|
|
37
|
+
if(value)return value
|
|
38
|
+
if(store.getItem('space:simple-setup')==='1')return cleanRoomDefaults({v:1,quick:true,enclave:true,verified:true,lanes:true,temporary:false,assistant:'',model:''})
|
|
39
|
+
}catch{}
|
|
40
|
+
return null
|
|
41
|
+
}
|
|
42
|
+
function arrived(){if(typeof dispatchEvent==='function')dispatchEvent(new Event('wb-room-defaults'))}
|
|
43
|
+
export function writeRoomDefaults(patch,baseline={},store=globalThis.localStorage,now=Date.now()) {
|
|
44
|
+
const old=readRoomDefaults(store), next=cleanRoomDefaults({v:1,...baseline,...old,...patch})
|
|
45
|
+
if(!next)return null
|
|
46
|
+
next.mods={...(old?.mods||{})}
|
|
47
|
+
const at=Math.max(now,...Object.values(next.mods).map(n=>n+1))
|
|
48
|
+
for(const key of FIELDS)if(key in patch && key in next)next.mods[key]=at
|
|
49
|
+
if(patch.temporary===true){next.lanes=false;next.mods.lanes=at}
|
|
50
|
+
if(patch.lanes===true){next.temporary=false;next.mods.temporary=at}
|
|
51
|
+
const value=cleanRoomDefaults(next)
|
|
52
|
+
try{store.setItem(ROOM_DEFAULTS_KEY,JSON.stringify(value));store.removeItem('space:simple-setup');store.removeItem('space:simple-setup:previous-theme');memory=null}catch{if(store===globalThis.localStorage)memory=value}
|
|
53
|
+
if(store===globalThis.localStorage){arrived();notify()}
|
|
54
|
+
return value
|
|
55
|
+
}
|
|
56
|
+
export function adoptRoomDefaults(remote,store=globalThis.localStorage) {
|
|
57
|
+
const local=readRoomDefaults(store),merged=mergeRoomDefaults(local,remote)
|
|
58
|
+
if(!merged || JSON.stringify(local)===JSON.stringify(merged))return false
|
|
59
|
+
try{store.setItem(ROOM_DEFAULTS_KEY,JSON.stringify(merged));memory=null}catch{return false}
|
|
60
|
+
if(store===globalThis.localStorage)arrived()
|
|
61
|
+
return true
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** A dedicated sealed account doc; failed/unknown reads never authorize a replacement write. */
|
|
65
|
+
export async function syncRoomDefaultsDocument({read,write=null,store=globalThis.localStorage}) {
|
|
66
|
+
let response;try{response=await read()}catch{return {status:0}}
|
|
67
|
+
if(!response || ![200,404].includes(response.status))return {status:0}
|
|
68
|
+
const raw=response.state,remote=cleanRoomDefaults(raw)
|
|
69
|
+
const empty=raw==null || (typeof raw==='object' && !Array.isArray(raw) && !Object.keys(raw).length)
|
|
70
|
+
if(!remote && !empty)return {status:0}
|
|
71
|
+
const merged=mergeRoomDefaults(readRoomDefaults(store),remote)
|
|
72
|
+
if(!merged)return {status:200}
|
|
73
|
+
adoptRoomDefaults(merged,store)
|
|
74
|
+
if(write && JSON.stringify(merged)!==JSON.stringify(remote)){try{return await write(merged)}catch{return {status:0}}}
|
|
75
|
+
return {status:200}
|
|
76
|
+
}
|
package/roomDelete.js
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
// roomDelete.js — an ACCOUNT can delete the rooms it created (docs/user-erasure.md). At create, the page sends
|
|
2
|
+
// `delCommit = sha256(delete secret)`; the secret is HMAC(account secret, 'witbitz-room-delete:' + room) and only this
|
|
3
|
+
// account's devices can derive it, so a member who joined can never delete someone else's room. The account secret is the
|
|
4
|
+
// usage key's (usageReceipts.js) — it rides the account index, and a key that lost a convergence race is kept as retired,
|
|
5
|
+
// so a deletion tries every kept key.
|
|
6
|
+
import { loadUsageKey, loadOldUsageKeys, newUsageKey, saveUsageKey, dropFor } from './usageReceipts.js'
|
|
7
|
+
|
|
8
|
+
const enc = new TextEncoder()
|
|
9
|
+
const b64u = (u8) => { let x = ''; for (const b of u8) x += String.fromCharCode(b); return btoa(x).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '') }
|
|
10
|
+
const ub64u = (s) => Uint8Array.from(atob(String(s).replace(/-/g, '+').replace(/_/g, '/')), (c) => c.charCodeAt(0))
|
|
11
|
+
export const DELETE_URL = 'https://api.witbitz.chat/v1/spaces/rooms/delete'
|
|
12
|
+
|
|
13
|
+
export function deletionConfirmed(result) {
|
|
14
|
+
const body = result?.body
|
|
15
|
+
return !!result?.ok && (body?.tombstoned === true || (body?.deleted === true && !body.queued && !body.pending))
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export async function delSecretFor (key, room) {
|
|
19
|
+
const k = await crypto.subtle.importKey('raw', ub64u(key.secret), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign'])
|
|
20
|
+
return b64u(new Uint8Array(await crypto.subtle.sign('HMAC', k, enc.encode('witbitz-room-delete:' + room))))
|
|
21
|
+
}
|
|
22
|
+
export async function delCommitOf (secret) { return b64u(new Uint8Array(await crypto.subtle.digest('SHA-256', enc.encode(secret)))) }
|
|
23
|
+
|
|
24
|
+
/** The commitment a create carries — minting the account key on the spot if this device has none yet (a brand-new
|
|
25
|
+
* account creates its index room before any sync). Never throws: a create without a commitment still goes. */
|
|
26
|
+
export async function delCommitFor (room, { load = loadUsageKey, mint = async () => saveUsageKey(await newUsageKey()) } = {}) {
|
|
27
|
+
try { const key = load() || await mint(); return key ? await delCommitOf(await delSecretFor(key, room)) : null } catch { return null }
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** Delete a room this account created. Tries the current key, then retired ones. → { ok, status, body }
|
|
31
|
+
* A 200 may be `{ queued: true }` — the server answers on its one-row check and deletes in the background: NOT deleted yet.
|
|
32
|
+
* `check: true` asks only whether THIS account's tombstone is down (`{ deleted: true, tombstoned: true }`) and queues nothing —
|
|
33
|
+
* Delete my account confirms a queued room with it before it erases the account key (state machines pass 9, 9·S#1). */
|
|
34
|
+
export async function deleteOwnRoom (room, { keys = [loadUsageKey(), ...loadOldUsageKeys()].filter(Boolean), dropKeys = [], fetchImpl = (...a) => fetch(...a), check = false, reviewPolicy = false, reviewedPolicy, reviewedEtag, url = DELETE_URL } = {}) { // dropKeys: other keys this account leaves traces with (the SDK's usage key — sync sweep 11-08 #3)
|
|
35
|
+
let last = { ok: false, status: 0, body: { error: 'no_account_key' } }
|
|
36
|
+
// every drop this account holds in the room (current + retired keys): the server refuses only for OTHER accounts' traces
|
|
37
|
+
const drops = []; for (const k of [...keys, ...dropKeys]) { try { const d = await dropFor(k, room); if (!drops.includes(d)) drops.push(d) } catch { /* */ } }
|
|
38
|
+
for (const key of keys) {
|
|
39
|
+
const delSecret = await delSecretFor(key, room)
|
|
40
|
+
if (reviewedEtag !== undefined && !check) {
|
|
41
|
+
const probe = await deleteOwnRoom(room, { keys: [key], dropKeys: [...keys, ...dropKeys], fetchImpl, check: true, reviewedEtag, url })
|
|
42
|
+
if (probe.status === 404) { last = probe; continue }
|
|
43
|
+
if (probe.body?.deleted === true) return probe
|
|
44
|
+
if (probe.status !== 200 || !probe.body?.guardedCleanup || !reviewedPolicy || reviewedPolicy !== probe.body?.policyVersion) return { ok: false, status: probe.status === 200 ? 409 : probe.status, body: { error: 'cleanup_unconfirmed' } }
|
|
45
|
+
}
|
|
46
|
+
let r = null
|
|
47
|
+
try { r = await fetchImpl(url, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ room, confirm: room, delSecret, drops, ...(reviewedEtag !== undefined ? { reviewedEtag, reviewedPolicy } : {}), ...(reviewPolicy ? { reviewPolicy: true } : {}), ...(check ? { check: true } : {}) }) }) } catch { return { ok: false, status: 0, body: { error: 'unreachable' } } }
|
|
48
|
+
const body = await r.json().catch(() => ({}))
|
|
49
|
+
last = { ok: r.status === 200, status: r.status, body }
|
|
50
|
+
if (r.status !== 404) return last // 200 done · 207 partly (call again) · 409 shared (others used it: leave it) · anything else: stop and say so
|
|
51
|
+
}
|
|
52
|
+
return last
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** LEAVING A VERIFIED ROOM (agent/roomLeave.mjs): what this account hands over as it goes — its marks in the room (`drops`, every
|
|
56
|
+
* kept key's) and the room's delete secrets it can derive (`dels`; only the creator's matches the room's commitment). */
|
|
57
|
+
export async function leaveHandover (room, { keys = [loadUsageKey(), ...loadOldUsageKeys()].filter(Boolean), dropKeys = [] } = {}) {
|
|
58
|
+
const drops = [], dels = []
|
|
59
|
+
for (const k of [...keys, ...dropKeys]) { try { const d = await dropFor(k, room); if (!drops.includes(d)) drops.push(d) } catch { /* */ } }
|
|
60
|
+
for (const k of keys) { try { const s = await delSecretFor(k, room); if (!dels.includes(s)) dels.push(s) } catch { /* */ } }
|
|
61
|
+
return { drops: drops.slice(0, 16), dels: dels.slice(0, 8) }
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** The LAST ONE OUT deletes the room with what every leaver handed over (op `leave` answered `last`): each handed-over delete
|
|
65
|
+
* secret is tried with all the handed-over marks; the server's own checks still run (another account's mark → 409 shared). */
|
|
66
|
+
export async function deleteHandedOver (room, { drops = [], dels = [] } = {}, { fetchImpl = (...a) => fetch(...a), url = DELETE_URL, check = false } = {}) {
|
|
67
|
+
let last = { ok: false, status: 0, body: { error: 'no_delete_secret' } }
|
|
68
|
+
for (const delSecret of dels) {
|
|
69
|
+
let r = null
|
|
70
|
+
try { r = await fetchImpl(url, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ room, confirm: room, delSecret, drops, ...(check ? { check: true } : {}) }) }) } catch { return { ok: false, status: 0, body: { error: 'unreachable' } } }
|
|
71
|
+
const body = await r.json().catch(() => ({}))
|
|
72
|
+
last = { ok: r.status === 200, status: r.status, body }
|
|
73
|
+
if (r.status !== 404) return last
|
|
74
|
+
}
|
|
75
|
+
return last
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** Leave a room on the way out of an account: `post(handover)` sends op `leave`; a verified room whose last member this was is then
|
|
79
|
+
* deleted. → { left, deleted?, last? } — never throws (a room that is not verified, or a server without the op, just stays). */
|
|
80
|
+
// A CONFIDENTIAL Space's enclave may be asleep: `leave` wakes it (agent/enclaveRelay.mjs) and the answer is `enclave_warming` until
|
|
81
|
+
// it is up — asked again for up to LEAVE_WARM_TRIES × LEAVE_WARM_MS (an enclave wakes in 1–6 min; sweep 11-18 #1). Still asleep after
|
|
82
|
+
// that → `{ warming: true }`, which Delete my account reports as not finished (run it again), never as left.
|
|
83
|
+
export const LEAVE_WARM_TRIES = 40, LEAVE_WARM_MS = 10_000
|
|
84
|
+
const warmingAnswer = (r) => { const b = (r && (r.body || r)) || {}; return b.error === 'enclave_warming' || b.warming === true }
|
|
85
|
+
export async function leaveAndMaybeDelete (room, { post, handover = leaveHandover, del = deleteHandedOver, sleep = (ms) => new Promise((res) => setTimeout(res, ms)), tries = LEAVE_WARM_TRIES } = {}) {
|
|
86
|
+
let r = null
|
|
87
|
+
let h; try { h = await handover(room) } catch { return { left: false } }
|
|
88
|
+
for (let i = 0; ; i++) {
|
|
89
|
+
try { r = await post(h) } catch { return { left: false } }
|
|
90
|
+
if (!warmingAnswer(r)) break
|
|
91
|
+
if (i + 1 >= tries) return { left: false, warming: true }
|
|
92
|
+
await sleep(LEAVE_WARM_MS)
|
|
93
|
+
}
|
|
94
|
+
const b = (r && (r.body || r)) || {}
|
|
95
|
+
if (r?.status === 409 && b.error === 'not_verified_room') return { left: false, unverified: true }
|
|
96
|
+
if (r?.status !== 200 || b.left !== true) return { left: false }
|
|
97
|
+
if (b.last !== true) return { left: true }
|
|
98
|
+
if (b.lapses === true) return { left: true, last: true, lapses: true }
|
|
99
|
+
const handed = { drops: b.drops || [], dels: b.dels || [] }
|
|
100
|
+
let result = await Promise.resolve().then(() => del(room, handed)).catch(() => null)
|
|
101
|
+
if (result?.ok && result.body?.queued && !deletionConfirmed(result)) {
|
|
102
|
+
for (let i = 0; i < tries; i++) {
|
|
103
|
+
await sleep(LEAVE_WARM_MS)
|
|
104
|
+
result = await Promise.resolve().then(() => del(room, handed, { check: true })).catch(() => null)
|
|
105
|
+
if (deletionConfirmed(result) || (result && ![0, 200, 503].includes(result.status))) break
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
return { left: true, last: true, deleted: deletionConfirmed(result) }
|
|
109
|
+
}
|