@witbitz/sdk 4.3.0 → 4.5.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/README.md +2 -2
- package/a2aCore.js +41 -5
- package/accountErase.js +15 -4
- package/accountIndexDoc.js +24 -7
- package/accountRecord.js +6 -2
- package/accountStores.js +21 -5
- package/acctV2App.js +111 -12
- package/acctV2Client.js +11 -1
- package/acctV2UiCore.js +27 -7
- package/agentDoorTools.js +28 -0
- package/awsKey.js +3 -1
- package/backupRecord.js +3 -0
- package/chatLock.js +16 -0
- package/cloudDevicePins.js +2 -2
- package/codeAttachments.js +101 -0
- package/codeCache.js +173 -0
- package/codeCloud.js +2 -2
- package/codeComputers.js +9 -0
- package/codeFolders.js +116 -0
- package/codeHistory.js +76 -0
- package/codeLanguage.js +54 -0
- package/codeModes.js +2 -0
- package/codeProgress.js +54 -0
- package/codeSent.js +109 -0
- package/codeSubagents.js +107 -0
- package/codeTransport.js +46 -5
- package/connections.js +37 -20
- package/decrypt.html +69 -9
- package/deviceAttest.js +9 -3
- package/eraseFile.js +15 -0
- package/idb.js +19 -3
- package/idbSeal.js +5 -2
- package/inviteReceive.js +44 -0
- package/inviteSend.js +8 -2
- package/jobAgents.js +2 -2
- package/keptMerge.js +9 -2
- package/l1-worker-src.js +1 -1
- package/l1-worker.js +122 -43
- package/laneAssociation.js +78 -0
- package/laneConfig.js +4 -3
- package/laneLinkCore.js +9 -0
- package/ledgerView.js +30 -4
- package/manifest.json +112 -87
- package/memberChange.js +4 -2
- package/mirrorBatch.js +47 -0
- package/offlineBundle.js +21 -0
- package/opRouting.js +10 -0
- package/package.json +27 -2
- package/pdfOptions.js +13 -0
- package/pdfText.js +107 -0
- package/pdfjs.mjs +28 -0
- package/pdfjs.worker.mjs +28 -0
- package/protectedLocal.js +52 -13
- package/reactionHolders.js +86 -0
- package/removedMessage.js +1 -1
- package/roomEmbed.js +111 -0
- package/roomIntake.js +324 -0
- package/roomName.js +1 -1
- package/roomRoster.js +30 -7
- package/rosterCount.js +6 -3
- package/scheduleNext.js +60 -0
- package/sdkA2A.js +200 -42
- package/sdkAccount.js +88 -18
- package/sdkAccountDoc.js +13 -5
- package/sdkAccountSections.js +172 -23
- package/sdkAgui.js +33 -6
- package/sdkBackup.js +53 -11
- package/sdkBackupV2.js +15 -3
- package/sdkCloudDevice.js +20 -5
- package/sdkComputers.js +695 -65
- package/sdkDictation.js +115 -25
- package/sdkErase.js +12 -5
- package/sdkExports.js +19 -8
- package/sdkInvitations.js +4 -2
- package/sdkKeptAgent.js +19 -3
- package/sdkKeptIntake.js +100 -0
- package/sdkLaneLink.js +8 -9
- package/sdkPlan.js +4 -2
- package/sdkRekey.js +122 -22
- package/sdkReport.js +1 -1
- package/sdkSafeMedia.js +1 -1
- package/sdkSchedules.js +8 -1
- package/sdkSpeech.js +32 -2
- package/sdkTemporaryRooms.js +124 -0
- package/sdkTurn.js +12 -4
- package/sdkVault.js +66 -10
- package/sentinelRelease.js +1 -0
- package/sharedViews.js +34 -4
- package/siri.js +140 -9
- package/spaceClient.js +112 -17
- package/spaceEmailGate.js +2 -2
- package/spaceExport.js +50 -5
- package/spaceFork.js +15 -7
- package/spaceTemplates.js +99 -0
- package/speechOut.js +21 -5
- package/store.js +134 -27
- package/sw-notif-core.js +11 -8
- package/tapTrail.js +58 -0
- package/turnVerdict.js +1 -0
- package/usageReceipts.js +12 -5
- package/vault-core.js +568 -126
- package/vault-kit.mjs +3 -3
- package/vault-screens.js +30 -18
- package/vaultAtRest.js +38 -6
- package/vaultCoreLock.js +3 -1
- package/vaultCorePush.js +58 -7
- package/vaultKeep.js +9 -3
- package/vaultWorkerHost.js +32 -7
- package/witbitz-admin.d.ts +3 -0
- package/witbitz-admin.mjs +12 -11
- package/witbitz-sdk.d.ts +170 -43
- package/witbitz-sdk.js +833 -203
package/connections.js
CHANGED
|
@@ -22,7 +22,7 @@ import { sealDisp, withDisplay } from './connDisp.js' // step 2: a connection's
|
|
|
22
22
|
/** The standing Sentinel's image, a rollover set of PCR0s (docs/standing-sentinel.md; infra/enclave/sentinel-host/README.md
|
|
23
23
|
* for the repin). Empty would mean attach REFUSES: the page will not seal an API key to an enclave it cannot name.
|
|
24
24
|
* Pin it here and in the Lambda's SENTINEL_HOP_PCRS together. */
|
|
25
|
-
export const STANDING_SENTINEL_PCR0 = ['1903ce28fc5a75efe2e57a451d667f1ce8b4b6e11872fb2b81d9e62d8cd994ed80fcfa99807f289af5f281aa4e4cc010'
|
|
25
|
+
export const STANDING_SENTINEL_PCR0 = ['1903ce28fc5a75efe2e57a451d667f1ce8b4b6e11872fb2b81d9e62d8cd994ed80fcfa99807f289af5f281aa4e4cc010'] // st56
|
|
26
26
|
|
|
27
27
|
const b64 = (u8) => btoa(String.fromCharCode(...new Uint8Array(u8)))
|
|
28
28
|
const unb64 = (s) => Uint8Array.from(atob(s), (c) => c.charCodeAt(0))
|
|
@@ -106,13 +106,25 @@ export async function attestStandingSentinel({ post, auth = {}, pins = STANDING_
|
|
|
106
106
|
/** The entry a ROOM keeps (its sealed config): enough to name and spend the connection, never the secret. */
|
|
107
107
|
export const roomEntry = (c) => ({ account: c.account, id: c.id, callKey: c.callKey, label: c.label || '', host: c.host, ...(c.mcp ? { mcp: c.mcp } : {}), ...(c.webhook ? { webhook: c.webhook } : {}), ...(c.webhook && c.job ? { job: c.job } : {}), ...(c.reads === 'auto' && !c.mcp ? { reads: 'auto' } : {}) }) // reads: a GET through it runs without asking (connectionEntry.js keeps it; agent/connectionTools.mjs readsRunAlone)
|
|
108
108
|
|
|
109
|
+
/** A SETUP FORM'S CONNECTION, ATTACHED ONCE (side sweep 2026-11-28): the Grok Bot and job-agent forms saved a new account connection
|
|
110
|
+
* and then asked the room to take it; when the room refused, Connect was enabled again and a retry made a SECOND connection for the
|
|
111
|
+
* same trigger, the first left in the account. `get(key, attach)` hands back the connection already made for the same pasted values;
|
|
112
|
+
* `done()` once the room took it. → { get, done } */
|
|
113
|
+
export function attachOnce () {
|
|
114
|
+
let held = null
|
|
115
|
+
return {
|
|
116
|
+
async get (key, attach) { if (held && held.key === key) return held.conn; const conn = await attach(); held = { key, conn }; return conn },
|
|
117
|
+
done () { held = null },
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
|
|
109
121
|
/**
|
|
110
122
|
* Attach: seal to the Sentinel, grant, then record in this room through `record(patch, by)` — the shell passes
|
|
111
123
|
* `(patch, by) => l1.setConfig(room, patch, by)`; the patch is DECLARATIVE ({ add: entry }) because it crosses the L1
|
|
112
124
|
* façade by structured clone, and spaceClient.setConfig applies it to the room's current list under its own key.
|
|
113
125
|
* @returns {{ id: string, label: string, host: string, callKey: string }}
|
|
114
126
|
*/
|
|
115
|
-
export async function attachConnection({ post, auth = {}, record, by, account, label, host, secret, rules, limits, pins, verify, follow, tenant, bearerWebhook, dispKey } = {}) { // dispKey: connDisp.js — the name also goes sealed to the person's devices (step 2)
|
|
127
|
+
export async function attachConnection({ post, pendingStore, auth = {}, record, by, account, label, host, secret, rules, limits, pins, verify, follow, tenant, bearerWebhook, dispKey } = {}) { // dispKey: connDisp.js — the name also goes sealed to the person's devices (step 2)
|
|
116
128
|
const acct = String(account || '').trim().toLowerCase()
|
|
117
129
|
if (!/^[^\s@]{1,200}@[^\s@]{1,63}$/.test(acct)) throw new ConnectionError('sign in with your email first — a connection belongs to an account', 'account')
|
|
118
130
|
const s = String(secret || '')
|
|
@@ -141,7 +153,7 @@ export async function attachConnection({ post, auth = {}, record, by, account, l
|
|
|
141
153
|
? { id, account: acct, provider: 'bearer', host: h, secret: s.trim(), label: lbl, ...(disp ? { disp } : {}), sign: /^whsec_/.test(s.trim()) ? 'standard-webhooks' : 'bearer', rules: { paths: [path] }, own: true, ...(limits ? { limits } : {}) } // a SIGNED WEBHOOK is the member's own, never under a tenant: the tenant vouches for API hosts, and a webhook's host is wherever the member's routine lives (the app's rule, now here for every caller — the SDK filed it under its tenant and the Sentinel refused the host; sync sweep, 2026-10-10)
|
|
142
154
|
: { id, account: acct, provider: 'bearer', host: h, secret: s.trim(), label: lbl, ...(disp ? { disp } : {}), ...(tenant ? { tenant: String(tenant) } : {}), ...(rules ? { rules } : {}), ...(limits ? { limits } : {}) }
|
|
143
155
|
const sk = await sealWithCallKey(att, grant, id, { label: lbl, host: h, account: acct })
|
|
144
|
-
const g = await postGrant(post, { op: 'sentinel', sentinel: { mode: 'credgrant', sealed: sk.sealed }, ...auth }, id, { label: lbl, host: h, account: acct, at: Date.now() }, sk)
|
|
156
|
+
const g = await postGrant(post, { op: 'sentinel', sentinel: { mode: 'credgrant', sealed: sk.sealed }, ...auth }, id, { label: lbl, host: h, account: acct, at: Date.now() }, sk, undefined, undefined, pendingStore)
|
|
145
157
|
if (!g || g.error || !g.ok) throw new ConnectionError(`the Sentinel refused the connection (${(g && g.error) || 'no answer'})`, (g && g.error) || 'refused')
|
|
146
158
|
// ⛔ THE CONNECTION IS RETURNED EVEN WHEN THE SPACE COULD NOT RECORD IT (2026-11-08, docs/state-machines.md I16 / C#11): this threw
|
|
147
159
|
// after the Sentinel had taken the grant — the callKey was dropped with the error, the Sentinel kept a connection no device
|
|
@@ -162,11 +174,14 @@ export async function attachConnection({ post, auth = {}, record, by, account, l
|
|
|
162
174
|
// dropped on a definite answer (the caller keeps a granted one), and adopted when the account's list shows it.
|
|
163
175
|
let _pendingStore = { keep () {}, drop () {} }
|
|
164
176
|
export const setPendingKeyStore = (s) => { _pendingStore = { keep () {}, drop () {}, ...(s || {}) } }
|
|
165
|
-
|
|
166
|
-
|
|
177
|
+
// NOT A DEFINITE ANSWER: the relay timed out or could not read the Sentinel's reply, or the gateway failed — the grant may have
|
|
178
|
+
// been filed. The key stays pending (adopted when the account lists it), as for no answer (side sweep 2026-11-28: a timeout dropped it).
|
|
179
|
+
const UNSURE = new Set(['sentinel_timeout', 'sentinel_bad_answer', 'sentinel_error'])
|
|
180
|
+
export const unsureAnswer = (r) => !!r && (UNSURE.has(r.error) || (typeof r.status === 'number' && (r.status === 0 || r.status >= 500)))
|
|
181
|
+
export async function postWithPendingKey (post, body, id, rec, store = _pendingStore) {
|
|
167
182
|
try { await store.keep(id, rec) } catch (e) { if (store.durable) throw e }
|
|
168
183
|
const r = await post(body) // a throw (no answer) leaves it pending
|
|
169
|
-
if (r && (r.error || (r.ok && !store.durable))) { try { await store.drop(id) } catch { /* */ } }
|
|
184
|
+
if (r && !unsureAnswer(r) && (r.error || (r.ok && !store.durable))) { try { await store.drop(id, rec?.callKey) } catch { /* */ } }
|
|
170
185
|
return r
|
|
171
186
|
}
|
|
172
187
|
export { adoptPendingKeys } // connPending.js — the rule, shared with the hosted app's vault (vaultConnKeys.js)
|
|
@@ -181,9 +196,9 @@ export { adoptPendingKeys } // connPending.js — the rule, shared with the host
|
|
|
181
196
|
let _minter = null
|
|
182
197
|
export const setCallKeyMinter = (m) => { _minter = m && typeof m.seal === 'function' ? m : null }
|
|
183
198
|
/** `payload` + a fresh callKey, sealed to the attested Sentinel → { sealed, callKey ('' when the vault holds it), held, settle } */
|
|
184
|
-
async function sealWithCallKey (att, payload, id, rec) {
|
|
185
|
-
if (
|
|
186
|
-
let v = null; try { v = await
|
|
199
|
+
async function sealWithCallKey (att, payload, id, rec, minter = _minter) {
|
|
200
|
+
if (minter && att.spki) {
|
|
201
|
+
let v = null; try { v = await minter.seal({ spki: att.spki, nonce: att.nonce, payload, id, rec }) } catch (e) { if (e?.code === 'connection_limit') throw e; v = null }
|
|
187
202
|
if (v && v.sealed) return { sealed: v.sealed, callKey: '', held: true, settle: v.settle }
|
|
188
203
|
}
|
|
189
204
|
const callKey = b64(crypto.getRandomValues(new Uint8Array(32)))
|
|
@@ -191,10 +206,10 @@ async function sealWithCallKey (att, payload, id, rec) {
|
|
|
191
206
|
}
|
|
192
207
|
/** Post a grant; while its answer is out the key is PENDING — in this page's store (rec = null: none), or the vault's, which a
|
|
193
208
|
* definite answer settles: `filed` = it was filed (r.ok), `final(r)` = what the Sentinel filed it as ({ id, label, account }). */
|
|
194
|
-
async function postGrant (post, body, id, rec, sk, filed = (r) => !!(r && r.ok && !r.error), final = () => ({})) {
|
|
195
|
-
if (!sk.held) return rec ? postWithPendingKey(post, body, id, { ...rec, callKey: sk.callKey }) : post(body)
|
|
209
|
+
async function postGrant (post, body, id, rec, sk, filed = (r) => !!(r && r.ok && !r.error), final = () => ({}), pendingStore) {
|
|
210
|
+
if (!sk.held) return rec ? postWithPendingKey(post, body, id, { ...rec, callKey: sk.callKey }, pendingStore) : post(body)
|
|
196
211
|
const r = await post(body) // a throw (no answer): the vault keeps it pending, adopted when the account lists it
|
|
197
|
-
if (r && (r.ok || r.error)) { let ok = false; try { ok = !!(await sk.settle(filed(r), filed(r) ? final(r) : {})) } catch { ok = false } if (filed(r) && !ok) throw new ConnectionError('the connection was made, but your vault did not keep its key — open Connections again to finish', 'vault') }
|
|
212
|
+
if (r && !unsureAnswer(r) && (r.ok || r.error)) { let ok = false; try { ok = !!(await sk.settle(filed(r), filed(r) ? final(r) : {})) } catch { ok = false } if (filed(r) && !ok) throw new ConnectionError('the connection was made, but your vault did not keep its key — open Connections again to finish', 'vault') }
|
|
198
213
|
return r
|
|
199
214
|
}
|
|
200
215
|
|
|
@@ -208,7 +223,9 @@ export async function listConnections({ post, auth = {}, dispKey }) { // dispKey
|
|
|
208
223
|
/** Detach everywhere (the Sentinel forgets it; every room's callKey for it is dead), and drop it from this room. */
|
|
209
224
|
export async function detachConnection({ post, auth = {}, record, by, id }) {
|
|
210
225
|
const r = await post({ op: 'sentinel', sentinel: { mode: 'credrevoke', id }, ...auth })
|
|
211
|
-
|
|
226
|
+
// only the Sentinel's own "done" counts (side sweep 2026-11-28: a failed request answered with a status alone read as revoked, 0) —
|
|
227
|
+
// an already-removed connection answers { ok: true, revoked: 0 }
|
|
228
|
+
if (!r || r.error || r.ok !== true) throw new ConnectionError(`could not detach (${(r && (r.error || r.status)) || 'no answer'})`, (r && r.error) || 'unreachable')
|
|
212
229
|
if (typeof record === 'function') await record({ connections: { remove: id } }, by)
|
|
213
230
|
return { revoked: Number(r.revoked) || 0 }
|
|
214
231
|
}
|
|
@@ -263,7 +280,7 @@ export function connectionName (c) {
|
|
|
263
280
|
* reachable while this connection lives, and a tenant's declared hosts vouch only for plain keys. (The SDK passed its tenant
|
|
264
281
|
* here, and the Sentinel refused every MCP host the builder had not declared — DeepWiki included; docs sync, 2026-11-22.)
|
|
265
282
|
* "Your own server" on a room's card is another mark: a server not in the catalog (connectionEntry.js, isCurated). */
|
|
266
|
-
export async function attachMcp({ post, auth = {}, account, label, url, token = '', pins, verify, follow, dispKey, sealGrant = sealWithCallKey } = {}) {
|
|
283
|
+
export async function attachMcp({ post, pendingStore, auth = {}, account, label, url, token = '', pins, verify, follow, dispKey, sealGrant = sealWithCallKey } = {}) {
|
|
267
284
|
const acct = String(account || '').trim().toLowerCase()
|
|
268
285
|
if (!/^[^\s@]{1,200}@[^\s@]{1,63}$/.test(acct)) throw new ConnectionError('sign in with your email first — a connection belongs to an account', 'account')
|
|
269
286
|
const { host, path } = parseMcpUrl(url)
|
|
@@ -275,7 +292,7 @@ export async function attachMcp({ post, auth = {}, account, label, url, token =
|
|
|
275
292
|
const disp = dispKey ? await sealDisp(dispKey, id, { label: lbl }).catch(() => '') : ''
|
|
276
293
|
const grant = { id, account: acct, provider: 'bearer', host, secret: t, label: lbl, ...(disp ? { disp } : {}), mcp: { path }, own: true }
|
|
277
294
|
const sk = await sealGrant(att, grant, id, { label: lbl, host, account: acct })
|
|
278
|
-
const g = await postGrant(post, { op: 'sentinel', sentinel: { mode: 'credgrant', sealed: sk.sealed }, ...auth }, id, { label: lbl, host, account: acct, at: Date.now() }, sk)
|
|
295
|
+
const g = await postGrant(post, { op: 'sentinel', sentinel: { mode: 'credgrant', sealed: sk.sealed }, ...auth }, id, { label: lbl, host, account: acct, at: Date.now() }, sk, undefined, undefined, pendingStore)
|
|
279
296
|
if (!g || g.error || !g.ok) throw new ConnectionError(`the Sentinel refused the connection (${(g && g.error) || 'no answer'})`, (g && g.error) || 'refused')
|
|
280
297
|
return { id, label: lbl, host, callKey: sk.callKey, ...(sk.held ? { held: 1 } : {}) }
|
|
281
298
|
}
|
|
@@ -464,7 +481,7 @@ export async function connectorConsent (state, { trip, authUrl, win, broker, sig
|
|
|
464
481
|
}
|
|
465
482
|
|
|
466
483
|
/** Finish: seal { state, code, callKey, id, label } to the Sentinel, which exchanges the code and files the connection. */
|
|
467
|
-
export async function finishMcpSignIn({ post, auth = {}, state, code, label, host, pins, verify, follow, dispKey }) {
|
|
484
|
+
export async function finishMcpSignIn({ post, pendingStore, auth = {}, state, code, label, host, pins, verify, follow, dispKey }) {
|
|
468
485
|
const att = await attestStandingSentinel({ post, auth, pins, verify, follow })
|
|
469
486
|
const id = 'conn_' + b64u(crypto.getRandomValues(new Uint8Array(12)))
|
|
470
487
|
const lbl = String(label || '').trim().slice(0, 80) || connectionName({ host }) // empty → the server's known name (GitHub), else the host
|
|
@@ -472,7 +489,7 @@ export async function finishMcpSignIn({ post, auth = {}, state, code, label, hos
|
|
|
472
489
|
// clear label only) keeps it as it does a grant's; until then this record shows the Sentinel's label
|
|
473
490
|
const disp = dispKey ? await sealDisp(dispKey, id, { label: lbl }).catch(() => '') : ''
|
|
474
491
|
const sk = await sealWithCallKey(att, { state, code, id, label: lbl, ...(disp ? { disp } : {}) }, id, { label: lbl, host })
|
|
475
|
-
const r = await postGrant(post, { op: 'sentinel', sentinel: { mode: 'mcpoauthfinish', sealed: sk.sealed }, ...auth }, id, { label: lbl, host, at: Date.now() }, sk)
|
|
492
|
+
const r = await postGrant(post, { op: 'sentinel', sentinel: { mode: 'mcpoauthfinish', sealed: sk.sealed }, ...auth }, id, { label: lbl, host, at: Date.now() }, sk, undefined, undefined, pendingStore)
|
|
476
493
|
if (!r || r.error || !r.ok) throw new ConnectionError(`${host}: ${(r && r.error) || 'the sign-in did not finish'}`, 'signin')
|
|
477
494
|
return { id, label: lbl, host, callKey: sk.callKey, ...(sk.held ? { held: 1 } : {}) }
|
|
478
495
|
}
|
|
@@ -534,13 +551,13 @@ export function awaitGitHubInstall(state, { timeoutMs = 15 * 60_000, drop = null
|
|
|
534
551
|
})
|
|
535
552
|
}
|
|
536
553
|
/** Finish: seal { code, installationId, callKey, id } to the Sentinel, which checks the install is this person's and files it. */
|
|
537
|
-
export async function finishGitHubInstall({ post, auth = {}, code, installationId, pins, verify, follow }) {
|
|
554
|
+
export async function finishGitHubInstall({ post, auth = {}, pendingStore, minter, code, installationId, pins, verify, follow }) {
|
|
538
555
|
const att = await attestStandingSentinel({ post, auth, pins, verify, follow })
|
|
539
556
|
const id = 'conn_' + b64u(crypto.getRandomValues(new Uint8Array(12)))
|
|
540
|
-
const sk = await sealWithCallKey(att, { code: String(code || ''), installationId: Number(installationId), id }, id, { label: 'GitHub', host: 'api.github.com' })
|
|
557
|
+
const sk = await sealWithCallKey(att, { code: String(code || ''), installationId: Number(installationId), id }, id, { label: 'GitHub', host: 'api.github.com' }, minter)
|
|
541
558
|
// no pending key in the page here (as before: the Sentinel may file it under its own id); a vault's is settled under the filed one
|
|
542
559
|
const body = { op: 'sentinel', sentinel: { mode: 'ghappfinish', sealed: sk.sealed }, ...auth }
|
|
543
|
-
const r =
|
|
560
|
+
const r = await postGrant(post, body, id, { label: 'GitHub', host: 'api.github.com', at: Date.now() }, sk, undefined, (x) => ({ id: String(x.id || id), label: `GitHub · ${x.login || 'app'}`, account: String(x.account || '') }), pendingStore)
|
|
544
561
|
if (!r || r.error || !r.ok) throw new ConnectionError(`GitHub: ${(r && r.error) || 'the install could not be connected'}`, 'ghapp')
|
|
545
562
|
return { id: String(r.id || id), callKey: sk.callKey, ...(sk.held ? { held: 1 } : {}), account: String(r.account || ''), login: String(r.login || ''), installationId: Number(r.installationId || installationId), label: `GitHub · ${r.login || 'app'}` }
|
|
546
563
|
}
|
package/decrypt.html
CHANGED
|
@@ -149,6 +149,10 @@
|
|
|
149
149
|
<script>
|
|
150
150
|
(function () {
|
|
151
151
|
'use strict'
|
|
152
|
+
// THE READER AS IT LOADED — before anything below touches the page. "Save this decryptor" saves this, never the live page: after a
|
|
153
|
+
// conversation was read the live page holds its messages and photos in the clear (side sweep 11-28). (This script is the body's
|
|
154
|
+
// last element, so the whole document is parsed here; typed values are never serialised.)
|
|
155
|
+
const PRISTINE = '<!doctype html>\n' + document.documentElement.outerHTML
|
|
152
156
|
const enc = new TextEncoder(), dec = new TextDecoder()
|
|
153
157
|
const $ = (id) => document.getElementById(id)
|
|
154
158
|
const subtle = window.crypto && window.crypto.subtle
|
|
@@ -222,18 +226,64 @@
|
|
|
222
226
|
} else for (const key of usable) { s = await openEnv(env, key); if (s != null) break }
|
|
223
227
|
if (s == null) continue; opened++; try { entries.push(JSON.parse(s)) } catch (e) {}
|
|
224
228
|
}
|
|
225
|
-
return { entries, opened, total: ledger.boxes.length, v3: true, needsRoom: bound > 0 && !room && !cands.length }
|
|
229
|
+
return { entries, opened, total: ledger.boxes.length, v3: true, needsRoom: bound > 0 && !room && !cands.length, keys: usable }
|
|
226
230
|
}
|
|
227
231
|
const s = await openEnv(ledger, wk); if (s == null) return { entries: null, v3: false }
|
|
228
232
|
let p; try { p = JSON.parse(s) } catch (e) { return { entries: null, v3: false } }
|
|
229
|
-
return { entries: Array.isArray(p) ? p : (p && Array.isArray(p.entries) ? p.entries : null), v3: false }
|
|
233
|
+
return { entries: Array.isArray(p) ? p : (p && Array.isArray(p.entries) ? p.entries : null), v3: false, keys: [wk] }
|
|
230
234
|
}
|
|
231
235
|
|
|
236
|
+
// THE STORED ATTACHMENTS. A photo or document a member shared is stored apart from its message (the message keeps `ref`, or
|
|
237
|
+
// `parts` for a large file). An offline copy made since 2026-11-28 carries their bytes, still SEALED exactly as the Space
|
|
238
|
+
// stored them, under `blobs` = { ref: envelope } (spaceClient.js archiveAttachments); each opens with the keys that opened the
|
|
239
|
+
// messages. One that is not in the file — an older copy, past the copy's size cap, or a read that failed — is marked so the
|
|
240
|
+
// transcript says "not in this copy". Returns NEW entries; the opened ones carry their bytes as an inline attachment does.
|
|
241
|
+
const NOT_IN_COPY = '__wbNotInCopy'
|
|
242
|
+
const storedRefs = (a) => (a && !(typeof a.b64 === 'string' && a.b64)) ? (Array.isArray(a.parts) && a.parts.length ? a.parts : (typeof a.ref === 'string' && a.ref ? [a.ref] : [])) : []
|
|
243
|
+
async function openAttachments(entries, blobs, keys) {
|
|
244
|
+
const have = blobs && typeof blobs === 'object' && !Array.isArray(blobs) ? blobs : {}
|
|
245
|
+
const cache = new Map()
|
|
246
|
+
const openBlob = async (ref) => {
|
|
247
|
+
if (cache.has(ref)) return cache.get(ref)
|
|
248
|
+
let env = Object.prototype.hasOwnProperty.call(have, ref) ? have[ref] : null, out = null
|
|
249
|
+
if (typeof env === 'string') { try { env = JSON.parse(env) } catch (e) { env = null } }
|
|
250
|
+
if (env) for (const k of (keys || [])) { const s = await openEnv(env, k); if (s == null) continue; try { const o = JSON.parse(s); if (o && typeof o.b64 === 'string') out = o } catch (e) { /* not an attachment */ } break }
|
|
251
|
+
cache.set(ref, out); return out
|
|
252
|
+
}
|
|
253
|
+
const one = async (a) => {
|
|
254
|
+
const refs = storedRefs(a); if (!refs.length || refs.some((r) => typeof r !== 'string' || !r)) return a
|
|
255
|
+
const parts = []
|
|
256
|
+
for (const r of refs) { const o = await openBlob(r); if (!o) return { ...a, [NOT_IN_COPY]: true }; parts.push(o) }
|
|
257
|
+
return { ...a, b64: parts.map((p) => p.b64).join(''), mime: a.mime || parts[0].mime || 'application/octet-stream' } // parts' base64 concatenates exactly (agent/attachmentBlobs.mjs PARTS)
|
|
258
|
+
}
|
|
259
|
+
const out = []
|
|
260
|
+
for (const e of entries) {
|
|
261
|
+
if (!e || typeof e !== 'object') { out.push(e); continue }
|
|
262
|
+
const next = { ...e }
|
|
263
|
+
for (const kind of ['images', 'files']) if (Array.isArray(e[kind])) { const list = []; for (const a of e[kind]) list.push(await one(a)); next[kind] = list }
|
|
264
|
+
out.push(next)
|
|
265
|
+
}
|
|
266
|
+
return out
|
|
267
|
+
}
|
|
268
|
+
const notInCopyCount = (entries) => entries.reduce((n, e) => n + (e && typeof e === 'object' ? [].concat(Array.isArray(e.images) ? e.images : [], Array.isArray(e.files) ? e.files : []).filter((a) => a && a[NOT_IN_COPY]).length : 0), 0)
|
|
269
|
+
const notInCopyNote = (entries) => { const n = notInCopyCount(entries || []); return n ? ` ${n} attachment${n === 1 ? ' is' : 's are'} not in this copy.` : '' }
|
|
270
|
+
|
|
232
271
|
// ── render ──
|
|
233
272
|
const esc = (s) => String(s == null ? '' : s).replace(/[&<>"]/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c]))
|
|
234
273
|
const fmtTs = (ts) => { const n = Number(ts); if (!Number.isFinite(n) || n <= 0) return ''; try { return new Date(n).toLocaleString() } catch (e) { return '' } }
|
|
235
274
|
let lastEntries = null, lastTitle = 'Conversation'
|
|
236
275
|
const looksLikeAgent = (e) => { const n = String((e && e.name) || '').toLowerCase(); return e && (e.agent === true || n === 'assistant' || n === 'agent') }
|
|
276
|
+
// SENDERS AS THE LIVE TRANSCRIPT NAMES THEM (side sweep: offline-reader-omits-message-attribution; messageRender.js addSharedLine and
|
|
277
|
+
// the verified-name line): a private lane's copy of a shared-room message says so, and an email gives way to the @username the Space
|
|
278
|
+
// verified (`by.user` on a lane copy, `user` on a verified entry); a name the person chose stays, with the @username beside it.
|
|
279
|
+
const EMAIL_RE = /^[^@\s]+@[^@\s]+\.[^@\s]+$/
|
|
280
|
+
const isLaneCopy = (e) => e.source === 'shared' && String(e.id == null ? '' : e.id).startsWith('sh:') && !(e.carried && typeof e.carried === 'object') // = laneLinkCore.js
|
|
281
|
+
function whoOf(e) {
|
|
282
|
+
const base = String(e.name || e.from || 'Unknown')
|
|
283
|
+
if (isLaneCopy(e)) { const u = e.by && typeof e.by === 'object' && typeof e.by.user === 'string' ? e.by.user : ''; return { lane: true, name: u && EMAIL_RE.test(base.trim()) ? '@' + u : base, user: '' } }
|
|
284
|
+
if (!looksLikeAgent(e) && e.verified === true && typeof e.user === 'string' && e.user) return EMAIL_RE.test(base.trim()) ? { name: '@' + e.user, user: '' } : { name: base, user: e.user }
|
|
285
|
+
return { name: base, user: '' }
|
|
286
|
+
}
|
|
237
287
|
|
|
238
288
|
function render(entries, title) {
|
|
239
289
|
lastEntries = entries; lastTitle = title || 'Conversation'
|
|
@@ -245,11 +295,20 @@
|
|
|
245
295
|
for (const e of entries) {
|
|
246
296
|
if (!e || typeof e !== 'object') continue
|
|
247
297
|
const row = document.createElement('div'); row.className = 'msg' + (looksLikeAgent(e) ? ' agent' : '')
|
|
248
|
-
|
|
298
|
+
const w = whoOf(e)
|
|
299
|
+
let html = `<div>${w.lane ? '<span class="ts">↩ from the shared room · </span>' : ''}<span class="who">${esc(w.name)}</span>${w.user ? `<span class="ts">@${esc(w.user)}</span>` : ''}<span class="ts">${esc(fmtTs(e.ts))}</span></div>`
|
|
249
300
|
if (e.text) html += `<div class="body">${esc(e.text)}</div>`
|
|
250
301
|
row.innerHTML = html
|
|
251
|
-
for (const im of (Array.isArray(e.images) ? e.images : [])) {
|
|
252
|
-
|
|
302
|
+
for (const im of (Array.isArray(e.images) ? e.images : [])) {
|
|
303
|
+
if (im && im.b64 && im.mime) { const img = document.createElement('img'); img.src = `data:${im.mime};base64,${im.b64}`; img.alt = im.name || 'image'; row.appendChild(img) }
|
|
304
|
+
else if (im && im[NOT_IN_COPY]) { const c = document.createElement('span'); c.className = 'chip'; c.textContent = '🖼 ' + (im.name || im.alt || 'photo') + ' — not in this copy'; row.appendChild(c) }
|
|
305
|
+
}
|
|
306
|
+
for (const f of (Array.isArray(e.files) ? e.files : [])) {
|
|
307
|
+
const name = (f && f.name) || 'file'
|
|
308
|
+
if (f && typeof f.b64 === 'string' && f.b64) { // a document with its bytes: a download link under its own name
|
|
309
|
+
const a = document.createElement('a'); a.className = 'chip'; a.download = name; a.href = `data:${f.mime || 'application/octet-stream'};base64,${f.b64}`; a.textContent = '📎 ' + name; row.appendChild(a)
|
|
310
|
+
} else { const c = document.createElement('span'); c.className = 'chip'; c.textContent = '📎 ' + name + (f && f[NOT_IN_COPY] ? ' — not in this copy' : ''); row.appendChild(c) }
|
|
311
|
+
}
|
|
253
312
|
for (const w of (Array.isArray(e.widgets) ? e.widgets : [])) { const c = document.createElement('span'); c.className = 'chip'; c.textContent = '▦ ' + ((w && (w.title || w.kind)) || 'widget'); row.appendChild(c) }
|
|
254
313
|
t.appendChild(row)
|
|
255
314
|
}
|
|
@@ -347,13 +406,14 @@
|
|
|
347
406
|
for (const key of keys) {
|
|
348
407
|
try {
|
|
349
408
|
const rooms = [...(idx >= 0 && bundleRooms[idx] ? [bundleRooms[idx]] : []), ...roomsForKey(key)]
|
|
350
|
-
const { entries, opened, total, v3, needsRoom: nr } = await decryptLedger(target, key, rooms, keys.filter(k => roomsForKey(k).some(r => rooms.includes(r)) || !roomsForKey(k).length))
|
|
409
|
+
const { entries: sealedEntries, opened, total, v3, needsRoom: nr, keys: opener } = await decryptLedger(target, key, rooms, keys.filter(k => roomsForKey(k).some(r => rooms.includes(r)) || !roomsForKey(k).length))
|
|
351
410
|
if (nr) needsRoom = true
|
|
352
|
-
|
|
411
|
+
const entries = sealedEntries ? await openAttachments(sealedEntries, target.blobs, opener) : sealedEntries
|
|
412
|
+
if (entries != null && (!v3 || opened === total)) { render(entries, title); return status(`Read ${entries.length} message${entries.length === 1 ? '' : 's'}.` + notInCopyNote(entries)) }
|
|
353
413
|
if (opened && (!best || opened > best.opened)) best = { entries, opened, total }
|
|
354
414
|
} catch (e) { /* try the next key */ }
|
|
355
415
|
}
|
|
356
|
-
if (best) { render(best.entries, title); return status(`Read ${best.opened} of ${best.total} messages (${best.total - best.opened} could not be opened).`) }
|
|
416
|
+
if (best) { render(best.entries, title); return status(`Read ${best.opened} of ${best.total} messages (${best.total - best.opened} could not be opened).` + notInCopyNote(best.entries)) }
|
|
357
417
|
if (needsRoom) return status('This conversation is tied to its Space. Load the keys file from the same backup, or paste the Space’s link beside the key, then try again.', true)
|
|
358
418
|
status(keys.length > 1 ? 'Couldn’t decrypt — none of the keys provided match this conversation.' : 'Couldn’t decrypt — the key doesn’t match this conversation (or it isn’t a Witbitz ledger).', true)
|
|
359
419
|
})
|
|
@@ -377,7 +437,7 @@
|
|
|
377
437
|
const body = $('transcript').innerHTML
|
|
378
438
|
download(safeName(lastTitle) + '.html', `<!doctype html><meta charset=utf-8><title>${esc(lastTitle)}</title><style>body{font:15px/1.5 -apple-system,system-ui,sans-serif;max-width:760px;margin:24px auto;padding:0 16px}.msg{padding:10px 0;border-top:1px solid #eee}.who{font-weight:650}.ts{color:#888;font-size:11.5px;margin-left:8px}.body{white-space:pre-wrap;margin-top:3px}img{max-width:100%;border-radius:10px;margin-top:8px;display:block}.chip{display:inline-block;margin:6px 6px 0 0;padding:3px 9px;border-radius:7px;background:#f0f0ec;color:#666;font-size:12px}</style><h2>${esc(lastTitle)}</h2>${body}`, 'text/html;charset=utf-8')
|
|
379
439
|
})
|
|
380
|
-
$('saveSelf').addEventListener('click', () => download('witbitz-offline-decryptor.html',
|
|
440
|
+
$('saveSelf').addEventListener('click', () => download('witbitz-offline-decryptor.html', PRISTINE, 'text/html;charset=utf-8'))
|
|
381
441
|
})();
|
|
382
442
|
</script>
|
|
383
443
|
</body>
|
package/deviceAttest.js
CHANGED
|
@@ -510,10 +510,16 @@ export function makeDeviceAttest ({ bridge: bridgeOpt = deviceBridge(), client,
|
|
|
510
510
|
// THE PHONE SIGNS WITH ANOTHER KEY than the one this page names (the owner's iPhone, 2026-11-24: the key enrolled at 09:20 never
|
|
511
511
|
// signed once; every attested backup "ios: bad assertion signature"): forgotten, so the next proof enrols the key the phone holds —
|
|
512
512
|
// at most once an hour, so a verifier that refuses every key cannot make a new hardware key per request
|
|
513
|
-
|
|
513
|
+
const expiredEnrollment = (['ios', 'macos'].includes(platform()) && /(?:^|: )enroll again: certificate expired\/not-yet-valid$/.test(reason)) ||
|
|
514
|
+
(platform() === 'android' && /(?:^|: )enroll again: a chain certificate is expired\/not-yet-valid$/.test(reason))
|
|
515
|
+
if (expiredEnrollment || /\b(ios|macos): bad assertion signature/.test(reason)) {
|
|
514
516
|
const m = readMemo()
|
|
515
|
-
if (sentKeyId && m.keyId && sentKeyId !== m.keyId)
|
|
516
|
-
|
|
517
|
+
if (sentKeyId && m.keyId && sentKeyId !== m.keyId) return true // another page already renewed it
|
|
518
|
+
if (!m.keyId) return !!sentKeyId
|
|
519
|
+
if (m.badSigAt && now() - m.badSigAt < 60 * 60_000) return false
|
|
520
|
+
writeMemo({ platform: m.platform, badSigAt: now() })
|
|
521
|
+
log(expiredEnrollment ? 'attest: the enrollment certificate is outside its validity period — will enroll again' : 'attest: the server could not verify this key’s signature — will enroll again')
|
|
522
|
+
return true
|
|
517
523
|
}
|
|
518
524
|
if (/windows_needs_activation/.test(reason)) { const m = readMemo(); const { act: _a, ...rest } = m; writeMemo(rest); log('attest: an enclave does not know this key\'s activation — will activate again') }
|
|
519
525
|
},
|
package/eraseFile.js
CHANGED
|
@@ -56,3 +56,18 @@ export async function fileEraseList ({ tenant, account, rooms, post, auth = {},
|
|
|
56
56
|
try { ls.setItem(FILED, JSON.stringify({ fp, at: now })) } catch { /* */ }
|
|
57
57
|
return { filed: true, rooms: rec.items.length }
|
|
58
58
|
}
|
|
59
|
+
|
|
60
|
+
/** One filing at a time (side sweep: tenant-erase-withdrawal-joins-ordinary-filing). `run(opts)` files; the returned function
|
|
61
|
+
* answers an ORDINARY call (no `items`) with the filing already in flight, but a call that brings its OWN list (Delete my
|
|
62
|
+
* account's withdrawal: `items: []`) waits for that one to end and then files its own — it never takes another filing's
|
|
63
|
+
* `filed: true` as its own, and its list is the one the Sentinel keeps. */
|
|
64
|
+
export function serialFiler (run) {
|
|
65
|
+
let current = null
|
|
66
|
+
return function file (opts = {}) {
|
|
67
|
+
if (current && !opts.items) return current
|
|
68
|
+
const prior = current
|
|
69
|
+
const p = (async () => { if (prior) await prior.catch(() => {}); return run(opts) })().finally(() => { if (current === p) current = null })
|
|
70
|
+
current = p
|
|
71
|
+
return p
|
|
72
|
+
}
|
|
73
|
+
}
|
package/idb.js
CHANGED
|
@@ -27,10 +27,10 @@ export const idb = (() => {
|
|
|
27
27
|
if (typeof indexedDB === 'undefined' || !indexedDB) { rej(Object.assign(new Error('no IndexedDB'), { noIdb: true })); return }
|
|
28
28
|
let r
|
|
29
29
|
try { r = indexedDB.open('spaces', 1) } catch (e) { rej(Object.assign(e instanceof Error ? e : new Error(String(e)), { noIdb: true })); return }
|
|
30
|
-
r.onupgradeneeded = () => r.result.createObjectStore('kv'); r.onsuccess = () =>
|
|
30
|
+
r.onupgradeneeded = () => r.result.createObjectStore('kv'); r.onsuccess = () => { const db = r.result; db.onversionchange = () => { db.close(); dbp = null }; res(db) }; r.onerror = () => rej(Object.assign(r.error || new Error('open failed'), { noIdb: true }))
|
|
31
31
|
}))
|
|
32
32
|
// `fn` on IndexedDB, or `onMem(map)` when there is none (it never opened — a failed TRANSACTION stays a failure, as before)
|
|
33
|
-
const tx = (mode, fn, onMem) => open().then((db) => new Promise((res, rej) => { const t = db.transaction('kv', mode), rq = fn(t.objectStore('kv')); t.oncomplete = () => res(rq && rq.result); t.onerror = () => rej(t.error) }),
|
|
33
|
+
const tx = (mode, fn, onMem) => open().then((db) => new Promise((res, rej) => { const t = db.transaction('kv', mode), rq = fn(t.objectStore('kv')); t.oncomplete = () => res(rq && rq.result); t.onerror = t.onabort = () => rej(t.error || new Error('IndexedDB transaction aborted')) }),
|
|
34
34
|
(e) => { if (e && e.noIdb && onMem) return onMem(memory()); throw e })
|
|
35
35
|
const inRange = (k, pfx) => !pfx || String(k).startsWith(pfx)
|
|
36
36
|
// §APP STORE (appStore.js; docs/hosted-app-design.md §6): in the hosted app every raw call below is the VAULT's — its store
|
|
@@ -54,7 +54,16 @@ export const idb = (() => {
|
|
|
54
54
|
// Keys only — a scan over a prefix that never loads the values (the protection migration walks the content ONE entry at a
|
|
55
55
|
// time with it: a getAll() of the values holds every cached room in memory at once, and that killed the page on an iPhone).
|
|
56
56
|
const keysRaw = (pfx) => (vault() ? vault()('keys', pfx || '') : tx('readonly', (s) => s.getAllKeys(range(pfx)), (m) => [...m.keys()])).then((ks) => (ks || []).map(String).filter((k) => k.startsWith(pfx))).catch(() => [])
|
|
57
|
-
const
|
|
57
|
+
const delRawStrict = (k) => vault() ? vault()('del', k) : tx('readwrite', (s) => s.delete(k), (m) => { m.delete(k) })
|
|
58
|
+
const delRaw = (k) => delRawStrict(k).catch(() => {})
|
|
59
|
+
const delStrict = async (k) => {
|
|
60
|
+
if (isNamed(k)) {
|
|
61
|
+
const namer = idbNamingState().namer
|
|
62
|
+
if (!namer) throw new Error('cannot delete a protected key before unlocking')
|
|
63
|
+
await delRawStrict(await namer.opaque(k))
|
|
64
|
+
}
|
|
65
|
+
await delRawStrict(k)
|
|
66
|
+
}
|
|
58
67
|
const delPrefixRaw = (pfx) => (vault() ? vault()('delPrefix', pfx || '') : tx('readwrite', (s) => { const rq = s.getAllKeys(range(pfx)); rq.onsuccess = () => { for (const k of (rq.result || [])) if (String(k).startsWith(pfx)) s.delete(k) } },
|
|
59
68
|
(m) => { for (const k of [...m.keys()]) if (String(k).startsWith(pfx)) m.delete(k) })).catch(() => {})
|
|
60
69
|
// §NAMES: the real names behind every opaque key (keys only — no value is read), [opaque, real] pairs.
|
|
@@ -71,6 +80,13 @@ export const idb = (() => {
|
|
|
71
80
|
set: (k, v) => (!isNamed(k) ? wrapForStore(k, v).then((stored) => (stored === undefined ? undefined : setRaw(k, stored)))
|
|
72
81
|
: !idbNamingState().namer ? Promise.resolve(undefined) // locked or memory-only: dropped, never a write under a real name
|
|
73
82
|
: (async () => { const nm = idbNamingState().namer, key = idbNamingState().key; const o = await nm.opaque(k); const stored = await seal(key, v); await setRaw(o, stored); await delRaw(k) })()).catch(() => {}),
|
|
83
|
+
async clearStrict() {
|
|
84
|
+
if (vault()) return vault()('delPrefix', '')
|
|
85
|
+
if (typeof indexedDB === 'undefined' || !indexedDB) { memory().clear(); return }
|
|
86
|
+
await tx('readwrite', store => store.clear())
|
|
87
|
+
if (mem) mem.clear()
|
|
88
|
+
},
|
|
89
|
+
delStrict,
|
|
74
90
|
del: (k) => (!isNamed(k) || !idbNamingState().namer ? delRaw(k) : idbNamingState().namer.opaque(k).then((o) => Promise.all([delRaw(o), delRaw(k)]))).catch(() => {}),
|
|
75
91
|
delPrefix: (pfx) => (!idbNamingState().on || !idbNamingState().namer ? delPrefixRaw(pfx)
|
|
76
92
|
: nameIndex().then((ix) => Promise.all([...ix.filter(([, n]) => n.startsWith(pfx)).map(([o]) => delRaw(o)), delPrefixRaw(pfx)]))).catch(() => {}),
|
package/idbSeal.js
CHANGED
|
@@ -31,7 +31,7 @@ export const idbNamingState = () => naming
|
|
|
31
31
|
/** Key worker: the device key's raw bytes → this realm's naming (null = locked; off = unprotected). */
|
|
32
32
|
export async function armIdbNaming (rawKey) { setIdbNaming({ on: true, key: await importRaw(rawKey), namer: await makeNamer(rawKey) }) }
|
|
33
33
|
|
|
34
|
-
export const IDB_PROTECTED_PREFIXES = Object.freeze(['chat:', 'wstate:', 'blob:', 'code:', 'vchat:', 'vblob:', 'vblobidx', 'hidx:', 'zoom:', 'mailpend:']) // vchat: = the vault's durable seed of the framed app's chat (slice 4); hidx: = Help search's full-history copy (helpIndex.js); mailpend: = a mail's attachment parts waiting for their mail (mailShare.js)
|
|
34
|
+
export const IDB_PROTECTED_PREFIXES = Object.freeze(['chat:', 'wstate:', 'blob:', 'code:', 'vchat:', 'vblob:', 'vblobidx', 'hidx:', 'zoom:', 'outbox:', 'mailpend:']) // outbox: = a message held for a busy room, with its photos (roomOutbox.js); vchat: = the vault's durable seed of the framed app's chat (slice 4); hidx: = Help search's full-history copy (helpIndex.js); mailpend: = a mail's attachment parts waiting for their mail (mailShare.js)
|
|
35
35
|
export const isProtectedIdbKey = (k) => { const s = String(k); return IDB_PROTECTED_PREFIXES.some((p) => s.startsWith(p)) }
|
|
36
36
|
|
|
37
37
|
const st = { active: false, key: null }
|
|
@@ -74,6 +74,9 @@ export async function moveToOpaqueNames (idb) {
|
|
|
74
74
|
if (isProtectedIdbKey(k) && isSealed(v)) { try { v = await openIf(st.key || key, v) } catch { continue } }
|
|
75
75
|
const o = await namer.opaque(k)
|
|
76
76
|
if ((await idb.getRaw(o)) == null) await idb.setRaw(o, await seal(key, v))
|
|
77
|
+
// the store may refuse the write and say nothing (a swallowed error, a `false`): the original goes only once its sealed copy
|
|
78
|
+
// is really there — else a later pass moves it (side sweep: device-storage-migration-drops-unsaved-copy)
|
|
79
|
+
if ((await idb.getRaw(o)) == null) continue
|
|
77
80
|
await idb.delRaw(k); n++
|
|
78
81
|
}
|
|
79
82
|
return n
|
|
@@ -87,7 +90,7 @@ export async function migrateIdbProtection (idb, rawKey) {
|
|
|
87
90
|
/** Switch off: open every sealed protected entry and write it back in the clear, one at a time; then pass-through. */
|
|
88
91
|
export async function unprotectIdb (idb, rawKey) {
|
|
89
92
|
const key = await importRaw(rawKey), namer = await makeNamer(rawKey)
|
|
90
|
-
for (const o of await idb.keysRaw('p:')) { const name = await namer.real(o); const v = await idb.getRaw(o); if (name != null && v != null) { try {
|
|
93
|
+
for (const o of await idb.keysRaw('p:')) { const name = await namer.real(o); const v = await idb.getRaw(o); if (name != null && v != null) { let back; try { back = await open(key, v) } catch { back = undefined /* junk: dropped */ } if (back !== undefined) { await idb.setRaw(name, back); if ((await idb.getRaw(name)) == null) continue /* not written: the sealed copy stays (side sweep) */ } } await idb.delRaw(o) } // back under real names (the key worker opens its own keys after)
|
|
91
94
|
for (const k of await protectedKeys(idb)) { const v = await idb.getRaw(k); if (isSealed(v)) { try { await idb.setRaw(k, await openIf(key, v)) } catch { await idb.delRaw(k) } } } // an entry the key cannot open is junk: drop it
|
|
92
95
|
try { await idb.delRaw('protectedNames') } catch { /* */ }
|
|
93
96
|
setIdbProtection({ active: false, key: null })
|
package/inviteReceive.js
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
// Tier-2 email invite — RECEIVE (docs/spaces-email-invite.md). Poll YOUR inbox, open each sealed box with your boxPriv,
|
|
2
|
+
// and hand the recovered { room, mk, title, from } to onInvite (which adds it to your Space list when it's new). The
|
|
3
|
+
// inbox is append-only, so this re-reads every box each poll — onInvite MUST be idempotent (no-op a room you already
|
|
4
|
+
// have or have deleted; recents + tombstones are the dedup). onInvite returns truthy when it actually added a room.
|
|
5
|
+
import { openBox } from './e2ee.js'
|
|
6
|
+
|
|
7
|
+
export async function checkInbox({ client, inviteKey, onInvite }) {
|
|
8
|
+
if (!client || !inviteKey || !inviteKey.inbox || !inviteKey.boxPriv || typeof onInvite !== 'function') return 0
|
|
9
|
+
const r = await client.inboxFetch(inviteKey.inbox, 0)
|
|
10
|
+
if (!r || r.status !== 200 || !Array.isArray(r.boxes)) return -1 // NOT READ (offline, refused): -1, so a caller can tell it from "nothing new" (emailInvites.js pollInbox's first pass)
|
|
11
|
+
let added = 0
|
|
12
|
+
for (const box of r.boxes) {
|
|
13
|
+
let plain = null
|
|
14
|
+
try { plain = await openBox(box, inviteKey.boxPriv) } catch { continue } // not sealed to us / corrupt → skip
|
|
15
|
+
if (!plain) continue
|
|
16
|
+
let inv = null
|
|
17
|
+
try { inv = JSON.parse(plain) } catch { continue }
|
|
18
|
+
if (!inv || !inv.room || (!inv.mk && !inv.link && !inv.us)) continue // a SPLIT invite carries the key in `link` (#us=), not `mk` — onInvite reverse-parses it; an ATTESTED split invite carries `us` itself (2026-11-24: skipped here, never reached onInvite)
|
|
19
|
+
try { if (await onInvite(inv)) added++ } catch { /* one bad invite must not stop the rest */ }
|
|
20
|
+
}
|
|
21
|
+
return added
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
// ⛔ STATE MACHINES PASS 8, A#1: the identity a device gives up when it adopts the account's (roomSync.js convergence) stays
|
|
25
|
+
// RETIRED for a week, inside the invite key itself (sealed, backed up, synced), and its inbox is read beside the current one —
|
|
26
|
+
// until the directory names the new inbox, invites still arrive at the old one.
|
|
27
|
+
export const RETIRED_MS = 7 * 24 * 3600 * 1000
|
|
28
|
+
const RETIRED_MAX = 3
|
|
29
|
+
/** The invite identities still to be read besides the current one. */
|
|
30
|
+
export const liveRetired = (id, now = Date.now()) => (Array.isArray(id && id.retired) ? id.retired : [])
|
|
31
|
+
.filter((r) => r && typeof r.inbox === 'string' && r.boxPriv && Number(r.until) > now && r.inbox !== (id && id.inbox))
|
|
32
|
+
/** `next` (the account's identity), with `local` (this device's, being replaced) and what it had retired kept as retired. */
|
|
33
|
+
export function retireInto (local, next, now = Date.now()) {
|
|
34
|
+
const was = local && local.inbox && local.boxPriv && local.inbox !== next.inbox ? [{ inbox: local.inbox, boxPriv: local.boxPriv, boxPub: local.boxPub, until: now + RETIRED_MS }] : []
|
|
35
|
+
const seen = new Set([next.inbox])
|
|
36
|
+
const retired = [...was, ...liveRetired(local, now), ...liveRetired(next, now)].filter((r) => !seen.has(r.inbox) && seen.add(r.inbox)).slice(0, RETIRED_MAX)
|
|
37
|
+
const { retired: _drop, ...rest } = next
|
|
38
|
+
return retired.length ? { ...rest, retired } : rest
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** Sent within the last day — only such an invite is announced ("X invited you to …"); an older one, or one with no time (an
|
|
42
|
+
* old sender), is added to the menu quietly (emailInvites.onSpaceInvite; the owner, 2026-11-10: "It is an old invite"). */
|
|
43
|
+
export const ANNOUNCE_MS = 24 * 3600 * 1000
|
|
44
|
+
export const inviteIsFresh = (at, now = Date.now()) => { const t = Number(at) || 0; return t > 0 && now - t >= -60_000 && now - t < ANNOUNCE_MS }
|
package/inviteSend.js
CHANGED
|
@@ -7,6 +7,9 @@ import { resolveHandle, usernameSlotApp } from './inviteEnroll.js' // ⛔ THIS a
|
|
|
7
7
|
import { validUsername } from './address.js'
|
|
8
8
|
import { sealTo } from './e2ee.js'
|
|
9
9
|
|
|
10
|
+
// ≡ agent/spaceHandlerCommon.mjs appTag: the names a directory slot can have
|
|
11
|
+
const slotName = (v) => { const t = typeof v === 'string' ? v.trim().toLowerCase() : ''; return !!t && t.length <= 64 && /^[a-z0-9][a-z0-9_.-]*$/.test(t) }
|
|
12
|
+
|
|
10
13
|
/** The invitee's directory handle for `{ email } | { username }`. Returns `{ handle }` or `{ reason }`:
|
|
11
14
|
* `no_user` = no such username (distinct from an enrolled-or-not email — a name is either claimed or it is not).
|
|
12
15
|
* Throws only if the OPRF/DLEQ round-trip fails. */
|
|
@@ -17,6 +20,9 @@ export async function resolveInvitee({ email, username, app, scope }, client) {
|
|
|
17
20
|
// the slot of THIS app: an attested kind's box, else — in a scoped app (the hosted app) — its own slot under the global
|
|
18
21
|
// handle (inviteEnroll.js enrollUsernameSlot), never the regular app's default one
|
|
19
22
|
const slot = app || (scope === undefined ? usernameSlotApp() : scope) || undefined
|
|
23
|
+
// A SLOT NAME THE SERVER CANNOT HOLD (side sweep 2026-11-28): a builder SDK's scope is 'app:<origin>', which no username slot is
|
|
24
|
+
// named after (agent/spaceHandlerCommon.mjs appTag) — every lookup answered "not enrolled" for a person who is. Said plainly.
|
|
25
|
+
if (slot && !slotName(slot)) return { reason: 'username_unsupported' }
|
|
20
26
|
const r = await client.userResolve(u, slot)
|
|
21
27
|
if (!r || r.status === 404) return { reason: 'no_user' }
|
|
22
28
|
if (r.status !== 200) return { reason: 'resolve_failed:' + (r ? r.status : 'net') }
|
|
@@ -47,7 +53,7 @@ export async function findInvitee({ email, username, app, scope }, client) {
|
|
|
47
53
|
|
|
48
54
|
// Returns { ok:true } or { ok:false, reason }. `not_enrolled` = the recipient has never opened Spaces, so there is no
|
|
49
55
|
// slot to seal to (the UI should say "ask them to open Spaces once"); `no_user` = that username does not exist.
|
|
50
|
-
export async function sendInvite({ email, username, room, mk, title, from, gate, link, client, direct, app, scope, kind, us = null, spc = '' }) { // app/kind: an ATTESTED room's invite goes to the invitee's box for that kind (attestedBox.js), never with a link
|
|
56
|
+
export async function sendInvite({ email, username, room, mk, title, from, gate, link, client, direct, app, scope, kind, enc = false, us = null, spc = '' }) { // app/kind: an ATTESTED room's invite goes to the invitee's box for that kind (attestedBox.js), never with a link
|
|
51
57
|
// A SPLIT room has NO mk to deliver — the self-contained `link` carries the userShare (#us=) instead, so accept when
|
|
52
58
|
// EITHER an mk or a link is present. (`mk` is still delivered for a plain room, and as a v1 fallback field below.)
|
|
53
59
|
// AN ATTESTED SPLIT ROOM (the hosted app's — 2026-11-24, every attested invite there failed bad_args): no mk and no link, the user
|
|
@@ -60,7 +66,7 @@ export async function sendInvite({ email, username, room, mk, title, from, gate,
|
|
|
60
66
|
// Seal the self-contained LINK (room+mk+gate+lanes in ONE grammar) as the source of truth the recipient reverse-parses,
|
|
61
67
|
// so no field is ever hand-dropped again (that was the "synced, can't open" bug — the gate marker went missing). room/mk
|
|
62
68
|
// /gate are ALSO carried for now so a not-yet-updated recipient (a v1 reader) still works during rollout.
|
|
63
|
-
const box = await sealTo(JSON.stringify({ v: 2, ...(link ? { link } : {}), room, ...(mk ? { mk } : {}), ...(us ? { us: String(us), ...(spc ? { spc: String(spc) } : {}) } : {}), ...(gate ? { gate } : {}), title: title || '', from: from || '', ...(kind ? { kind } : {}), ...(direct ? { direct: String(direct).slice(0, 254) } : {}), at: Date.now() }), g.entry.boxPub)
|
|
69
|
+
const box = await sealTo(JSON.stringify({ v: 2, ...(link ? { link } : {}), room, ...(mk ? { mk } : {}), ...(us ? { us: String(us), ...(spc ? { spc: String(spc) } : {}) } : {}), ...(gate ? { gate } : {}), title: title || '', from: from || '', ...(kind ? { kind, ...(enc === true ? { enc: true } : {}) } : {}), ...(direct ? { direct: String(direct).slice(0, 254) } : {}), at: Date.now() }), g.entry.boxPub)
|
|
64
70
|
const r = await client.drop(g.entry.inbox, box)
|
|
65
71
|
if (r && r.status === 200) return { ok: true }
|
|
66
72
|
if (r && r.status === 507) return { ok: false, reason: 'inbox_full' }
|
package/jobAgents.js
CHANGED
|
@@ -53,9 +53,9 @@ export function jobAgentOf(c) {
|
|
|
53
53
|
export const isJobAgentConn = (c) => !!jobAgentOf(c)
|
|
54
54
|
|
|
55
55
|
/** The names one Space's agent goes by: its connector on the agent's side ("Witbitz · Kyoto") and its peer here. */
|
|
56
|
-
export function jobNames(agent, spaceName) {
|
|
56
|
+
export function jobNames(agent, spaceName, lane) {
|
|
57
57
|
const s = clean(spaceName, 40) || 'my Space'
|
|
58
|
-
return { connector: 'Witbitz · ' + s, peer: agent.name + ' · ' + s }
|
|
58
|
+
return { connector: 'Witbitz · ' + s, peer: agent.name + ' · ' + (lane || s) }
|
|
59
59
|
}
|
|
60
60
|
|
|
61
61
|
/** The saved prompt for the agent's task: act on the job it is sent, and always report back through this Space's connector. */
|
package/keptMerge.js
CHANGED
|
@@ -27,8 +27,15 @@ export function unionMarks (a, b, max = MAX_MARKS) {
|
|
|
27
27
|
export function mergePeers (pref, other, max = MAX_MARKS) {
|
|
28
28
|
const removed = unionMarks(pref && pref.removed, other && other.removed, max)
|
|
29
29
|
const mine = Array.isArray(pref && pref.peers) ? pref.peers : [], theirs = Array.isArray(other && other.peers) ? other.peers : []
|
|
30
|
-
const
|
|
31
|
-
const peers =
|
|
30
|
+
const others = new Map(theirs.map(p => [p?.id, p]))
|
|
31
|
+
const peers = mine.map(peer => {
|
|
32
|
+
const remote = others.get(peer?.id)
|
|
33
|
+
others.delete(peer?.id)
|
|
34
|
+
if (!remote || !peer) return peer
|
|
35
|
+
const a = Number(peer.replyAt) || 0, b = Number(remote.replyAt) || 0
|
|
36
|
+
if (b > a || (b && b === a && remote.reply === 'ask')) return { ...peer, reply: remote.reply, replyAt: b }
|
|
37
|
+
return peer
|
|
38
|
+
}).concat([...others.values()]).filter(p => p && !removed[p.id])
|
|
32
39
|
return { ...pref, peers, ...(Object.keys(removed).length ? { removed } : {}) }
|
|
33
40
|
}
|
|
34
41
|
|