@witbitz/sdk 4.4.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 +15 -0
- package/accountErase.js +9 -3
- 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/awsKey.js +3 -1
- package/backupRecord.js +3 -0
- package/codeAttachments.js +1 -0
- package/codeCache.js +27 -3
- package/codeCloud.js +2 -0
- package/codeComputers.js +8 -0
- package/codeSent.js +43 -2
- package/codeTransport.js +24 -5
- package/connections.js +21 -3
- package/decrypt.html +69 -9
- package/eraseFile.js +15 -0
- package/idbSeal.js +5 -2
- package/inviteReceive.js +44 -0
- package/inviteSend.js +8 -2
- package/l1-worker-src.js +1 -1
- package/l1-worker.js +30 -14
- package/laneAssociation.js +11 -1
- package/laneLinkCore.js +9 -0
- package/ledgerView.js +30 -4
- package/manifest.json +78 -72
- package/offlineBundle.js +21 -0
- package/package.json +8 -2
- package/protectedLocal.js +34 -11
- package/reactionHolders.js +86 -0
- package/roomIntake.js +324 -0
- package/roomRoster.js +9 -2
- package/scheduleNext.js +60 -0
- package/sdkA2A.js +46 -8
- package/sdkAccount.js +71 -14
- package/sdkAccountDoc.js +3 -3
- package/sdkAccountSections.js +58 -18
- package/sdkAgui.js +33 -6
- package/sdkBackup.js +21 -6
- package/sdkBackupV2.js +15 -3
- package/sdkCloudDevice.js +12 -3
- package/sdkComputers.js +118 -17
- package/sdkDictation.js +1 -1
- package/sdkErase.js +3 -1
- package/sdkExports.js +15 -6
- package/sdkInvitations.js +4 -2
- package/sdkKeptAgent.js +19 -3
- package/sdkKeptIntake.js +100 -0
- package/sdkLaneLink.js +5 -6
- package/sdkRekey.js +72 -5
- package/sdkSchedules.js +8 -1
- package/sdkSpeech.js +14 -1
- package/sdkTemporaryRooms.js +2 -1
- package/sdkTurn.js +12 -4
- package/sharedViews.js +17 -1
- package/siri.js +29 -5
- package/spaceClient.js +96 -12
- package/spaceExport.js +50 -5
- package/spaceFork.js +15 -7
- package/spaceTemplates.js +2 -2
- package/speechOut.js +17 -3
- package/store.js +51 -13
- package/sw-notif-core.js +2 -1
- package/tapTrail.js +58 -0
- package/usageReceipts.js +12 -5
- package/vault-core.js +90 -16
- package/vault-kit.mjs +2 -2
- package/vault-screens.js +25 -11
- package/vaultAtRest.js +3 -2
- package/vaultCoreLock.js +3 -1
- package/vaultCorePush.js +58 -7
- package/vaultWorkerHost.js +9 -3
- package/witbitz-admin.d.ts +3 -0
- package/witbitz-admin.mjs +10 -10
- package/witbitz-sdk.d.ts +59 -23
- package/witbitz-sdk.js +271 -64
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@witbitz/sdk",
|
|
3
|
-
"version": "4.
|
|
4
|
-
"description": "The Witbitz SDK: Spaces — end-to-end encrypted rooms with an AI assistant — in your own app. The same bytes as https://witbitz.chat/sdk/4.
|
|
3
|
+
"version": "4.5.0",
|
|
4
|
+
"description": "The Witbitz SDK: Spaces — end-to-end encrypted rooms with an AI assistant — in your own app. The same bytes as https://witbitz.chat/sdk/4.5.0/",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./witbitz-sdk.js",
|
|
7
7
|
"types": "./witbitz-sdk.d.ts",
|
|
@@ -115,6 +115,7 @@
|
|
|
115
115
|
"indexGone.js",
|
|
116
116
|
"invite.js",
|
|
117
117
|
"inviteEnroll.js",
|
|
118
|
+
"inviteReceive.js",
|
|
118
119
|
"inviteSend.js",
|
|
119
120
|
"jobAgents.js",
|
|
120
121
|
"keptMerge.js",
|
|
@@ -149,6 +150,7 @@
|
|
|
149
150
|
"prefetchPoll.js",
|
|
150
151
|
"protectedLocal.js",
|
|
151
152
|
"pushCore.js",
|
|
153
|
+
"reactionHolders.js",
|
|
152
154
|
"recovery.js",
|
|
153
155
|
"regions.js",
|
|
154
156
|
"removedMessage.js",
|
|
@@ -158,6 +160,7 @@
|
|
|
158
160
|
"roomDefaultPrefs.js",
|
|
159
161
|
"roomDelete.js",
|
|
160
162
|
"roomEmbed.js",
|
|
163
|
+
"roomIntake.js",
|
|
161
164
|
"roomName.js",
|
|
162
165
|
"roomPass.js",
|
|
163
166
|
"roomRoster.js",
|
|
@@ -169,6 +172,7 @@
|
|
|
169
172
|
"rowSchema.js",
|
|
170
173
|
"safeMedia.js",
|
|
171
174
|
"safeMediaPins.js",
|
|
175
|
+
"scheduleNext.js",
|
|
172
176
|
"schedulesDoc.js",
|
|
173
177
|
"sdkA2A.js",
|
|
174
178
|
"sdkAccount.js",
|
|
@@ -187,6 +191,7 @@
|
|
|
187
191
|
"sdkExports.js",
|
|
188
192
|
"sdkInvitations.js",
|
|
189
193
|
"sdkKeptAgent.js",
|
|
194
|
+
"sdkKeptIntake.js",
|
|
190
195
|
"sdkLaneLink.js",
|
|
191
196
|
"sdkPlan.js",
|
|
192
197
|
"sdkProtect.js",
|
|
@@ -222,6 +227,7 @@
|
|
|
222
227
|
"sttCloud.js",
|
|
223
228
|
"sttWorklet.js",
|
|
224
229
|
"sw-notif-core.js",
|
|
230
|
+
"tapTrail.js",
|
|
225
231
|
"tempList.js",
|
|
226
232
|
"tinfoilVerifier.js",
|
|
227
233
|
"toolBooks.js",
|
package/protectedLocal.js
CHANGED
|
@@ -45,6 +45,7 @@ export const PROTECTED_PREFIXES = Object.freeze([
|
|
|
45
45
|
'space:share-in', 'space:share-last', // shareIn.js: words shared from another app (sessionStorage), the Space last shared into
|
|
46
46
|
'space:moved-unsent:', // space.js keepUnsentForMove: words you wrote that a moved room refused, carried to the new room's box (sessionStorage)
|
|
47
47
|
'space:away-unsent:', // space.js keepUnsentAway: words a Space refused after you had left it, kept for your return (sessionStorage; sync sweep 11-21 #7)
|
|
48
|
+
'space:update-draft', // drafts.js parkDraftForUpdate: the open room's draft across "Update now"'s one reload (sessionStorage)
|
|
48
49
|
'space:crossed:', // content: the lines you authored that crossed into a shared room
|
|
49
50
|
'space:inviteowed:', // rekeyMembers.js: the people a member change added whose invites are still to go (their emails)
|
|
50
51
|
// The 2026-10-10 audit (the owner: "Make sure that everything is encrypted when the lock is on") — every remaining store
|
|
@@ -85,14 +86,15 @@ export const cfgSaysProtected = (c) => !!(c && c.on && c.protect && c.protect.on
|
|
|
85
86
|
// this wrapper exists) — so on a protected device a wipe whose key clean-up failed was reported clean and never retried, and the
|
|
86
87
|
// previous account's keys could meet the next one. They name no room and no person ('1', 'reset', or the database names to drop).
|
|
87
88
|
export const STAYS_CLEAR = Object.freeze(['witbitz-builder-reset-pending', 'witbitz-spaces-signout-pending', 'witbitz-device-signout-pending', 'witbitz-device-reset-confirmed', 'space:lock', 'vault:lock', FRAMED_MARK,
|
|
88
|
-
'space:maplang', 'space:maplang.eff', 'space:mapsapp', 'space:settings:open', 'space:side', 'space:side-hidden', 'space:side-w', 'space:assistw',
|
|
89
|
+
'space:maplang', 'space:maplang.eff', 'space:mapsapp', 'space:mapsapp:chosen' /* its mark: '1' or 'probe:<time>' — read with it by the map widgets (side sweep 2026-11-28) */, 'space:settings:open', 'space:side', 'space:side-hidden', 'space:side-w', 'space:assistw',
|
|
89
90
|
'space:ohttp', 'space:caretdbg', 'space:rotlab', 'space:diag', 'space:notifPreview', 'space:boots', 'space:apps',
|
|
90
91
|
'space:channel', 'space:runAt', // Official / Beta / Pinned + the newest build time run (channelChoice.js): read before the unlock, or a locked device would fall back to Official
|
|
91
92
|
'space:strictfiles', // Strict file viewing (strictFiles.js): sealed, a locked device would read it as off and draw others' files behind the lock screen
|
|
92
93
|
'space:autoupdate', // "Update automatically" (updateState.js): sealed, a locked device read it as On and updated behind the lock screen (sync sweep, 10-16)
|
|
93
94
|
'space:atrest', // the regular app's storage is sealed by its DEVICE key (spaceAtRest.js SPACE_AT_REST_MARK): read at load, so its reads wait for the boot's unlock
|
|
94
95
|
'vault:atrest', // the hosted vault's storage is sealed by its DEVICE key (vaultDeviceKey.js AT_REST_MARK): read at load, so its reads wait for the boot's unlock
|
|
95
|
-
'vault:repairAt'
|
|
96
|
+
'vault:repairAt', // a time only: when the vault's boot guard last repaired (vault-boot-guard.js) — read before any unlock (sync sweep 10-21 #9)
|
|
97
|
+
'space:appearance', 'space:appearance:options', 'vault:appearance']) // the Appearance choice (a theme name, a mode, colours, a font — nothing private): read at load to paint the lock screen (side sweep: protected-cold-lock-misses-appearance)
|
|
96
98
|
// + the sign-in callbacks' hand-back: written by a page that holds no key (github-callback.html, mcp-callback.html) and
|
|
97
99
|
// removed once read (connections.js) — sealed, a protected device never finished that path (sync sweep 10-20 #8)
|
|
98
100
|
export const STAYS_CLEAR_PREFIXES = Object.freeze(['space:flag:', 'space:ghcb:', 'space:mcpcb:'])
|
|
@@ -143,7 +145,11 @@ const rawLength = () => (lengthDesc ? lengthDesc.get.call(localStorage) : localS
|
|
|
143
145
|
// Disk writes are async (WebCrypto) and must land in the order they were made: one chain.
|
|
144
146
|
let chain = Promise.resolve()
|
|
145
147
|
const onDisk = (fn) => { chain = chain.then(fn).catch(() => {}); return chain }
|
|
146
|
-
|
|
148
|
+
// A sealed write the store refused (full, private mode) leaves the CLEAR original where it was (side sweep:
|
|
149
|
+
// device-storage-migration-drops-unsaved-copy): removed only once its sealed copy is on disk — never a value on neither. `unsaved`
|
|
150
|
+
// names the entries whose last sealed write failed (a re-key keeps their old names).
|
|
151
|
+
const unsaved = new Set()
|
|
152
|
+
const writeSealed = (name, v) => { const k = key, nm = namer, g = sealGen; if (!k || !nm) return; onDisk(async () => { const o = await nm.opaque(name); const blob = await seal(k, v); if (sealGen !== g) return; try { raw.setItem.call(localStorage, o, JSON.stringify(blob)) } catch { unsaved.add(name); return } /* private mode / full */ unsaved.delete(name); try { raw.removeItem.call(localStorage, name) } catch { /* */ } }) }
|
|
147
153
|
const removeSealed = (name) => { const nm = namer; if (!nm) return; onDisk(async () => { try { raw.removeItem.call(localStorage, await nm.opaque(name)) } catch { /* */ } }) }
|
|
148
154
|
/** Resolves once every queued disk write has landed (tests, and the switch-off). */
|
|
149
155
|
export const protectedLocalFlushed = () => chain
|
|
@@ -266,21 +272,31 @@ export async function unlockProtectedLocal (rawKey, { switchOn = false, also = [
|
|
|
266
272
|
return { stale: true }
|
|
267
273
|
}
|
|
268
274
|
const blob = parseSealed(v); if (!blob) return { name, skip: true }
|
|
269
|
-
|
|
275
|
+
// side sweep (device-storage-unreadable-entry-clears-copy): one entry that will not open no longer throws out of the whole unlock
|
|
276
|
+
// (the at-rest boot read that as "the key opens nothing" and cleared every entry) — it is skipped and KEPT on disk
|
|
277
|
+
try { return { name, clear: String(await open(k, blob)) } } catch { return { name, unreadable: true } }
|
|
270
278
|
}
|
|
271
279
|
const blob = parseSealed(v)
|
|
272
280
|
if (blob && isProtectedKey(stored)) { // phase 1: sealed under its own name
|
|
273
|
-
try { return { clear: String(await open(k, blob)) } } catch (e) { if (!switchOn)
|
|
281
|
+
try { return { clear: String(await open(k, blob)), p1: true } } catch (e) { if (!switchOn) return { unreadable: true, p1: true }; return { stale: true } }
|
|
274
282
|
}
|
|
275
283
|
return { clear: v } // clear: never protected before, or written by an older build
|
|
276
284
|
}))
|
|
277
285
|
const logCopies = new Map() // an APPEND LOG's every copy, merged below — never one copy replacing another
|
|
278
286
|
const carried = [], carriedNames = new Set() // 10·V#1: entries another known key opened — re-sealed under this one, then their old names go
|
|
287
|
+
const unreadable = new Set() // names under this key whose entry would not open: kept on disk, never written over by a locked default
|
|
288
|
+
const toClear = [] // [opaque name, real name, value]: sealed by an older build under a name that stays clear now
|
|
289
|
+
let p1 = 0, p1Opened = 0
|
|
279
290
|
entries.forEach(([stored], i) => {
|
|
280
291
|
const r = opened[i]
|
|
292
|
+
if (r.p1) { p1++; if (!r.unreadable) p1Opened++ }
|
|
293
|
+
if (r.unreadable) { if (isOpaqueName(stored)) opaque++; unreadable.add(r.name || stored); return }
|
|
281
294
|
if (isOpaqueName(stored)) {
|
|
282
295
|
opaque++
|
|
283
296
|
if (r.stale) { stale.push(stored); return }
|
|
297
|
+
// A name that STAYS CLEAR now but an older build sealed (side sweep: map-widget-misses-protected-apple-choice): every read of
|
|
298
|
+
// it goes to the disk under its real name, so the sealed copy is written back there (unless a clear one exists) and goes.
|
|
299
|
+
if (staysClear(r.name)) { ours++; if (!r.skip) toClear.push([stored, r.name, r.clear]); return }
|
|
284
300
|
if (r.carried) { ours++; carried.push(stored); if (!next.has(r.name)) { next.set(r.name, r.clear); carriedNames.add(r.name) } return } // this key's own copy, where there is one, is the newer
|
|
285
301
|
ours++
|
|
286
302
|
if (!r.skip) { next.set(r.name, r.clear); if (APPEND_LOGS.includes(r.name)) logCopies.set(r.name, [r.clear, ...(logCopies.get(r.name) || [])]) } // the sealed copy is the older history: first
|
|
@@ -304,12 +320,16 @@ export async function unlockProtectedLocal (rawKey, { switchOn = false, also = [
|
|
|
304
320
|
while (lines.length > LOG_CAP) lines.shift()
|
|
305
321
|
next.set(n, JSON.stringify(lines)); lockedWrites.delete(n); logWritten.push(n)
|
|
306
322
|
}
|
|
307
|
-
|
|
323
|
+
// a wrong key: every name fails to open, change nothing. A phase-1 entry that OPENED proves the key too (a partly migrated device whose
|
|
324
|
+
// only opaque entry is damaged — side sweep: device-storage-unreadable-entry-clears-copy, round 3)
|
|
325
|
+
if (opaque && !ours && !p1Opened && !switchOn) throw new Error('this key opens nothing here')
|
|
326
|
+
if (p1 && !p1Opened && !ours && !switchOn) throw new Error('this key opens nothing here') // phase 1 only, and not one entry opens: a wrong key
|
|
308
327
|
if (switchOn) for (const n of stale) { try { raw.removeItem.call(localStorage, n) } catch { /* */ } }
|
|
328
|
+
for (const [o, n, v] of toClear) { try { if (raw.getItem.call(localStorage, n) == null) raw.setItem.call(localStorage, n, v); raw.removeItem.call(localStorage, o) } catch { /* the next unlock tries again */ } }
|
|
309
329
|
// A write made while locked is kept only where the disk has NOTHING under that name: a module that found a value "missing"
|
|
310
330
|
// at load (it was sealed) and wrote a default — a fresh device id, an empty list — must never replace the real one.
|
|
311
331
|
const written = []
|
|
312
|
-
for (const [n, v] of lockedWrites) if (v != null && !next.has(n)) { next.set(n, v); written.push(n) }
|
|
332
|
+
for (const [n, v] of lockedWrites) if (v != null && !next.has(n) && !unreadable.has(n)) { next.set(n, v); written.push(n) }
|
|
313
333
|
const removed = []
|
|
314
334
|
if (switchOn) sealGen++ // a new protection: writes made under another one are not this one's
|
|
315
335
|
key = k; namer = nm; active = true; memoryOnly = false; names = null
|
|
@@ -331,11 +351,11 @@ export async function rekeyProtectedLocal (newRaw) {
|
|
|
331
351
|
await chain
|
|
332
352
|
const oldNm = namer, k = await importRaw(newRaw), nm = await makeNamer(newRaw)
|
|
333
353
|
const old = []
|
|
334
|
-
for (const stored of rawKeys()) if (isOpaqueName(stored)
|
|
354
|
+
for (const stored of rawKeys()) { if (!isOpaqueName(stored)) continue; const n = await oldNm.real(stored); if (n != null) old.push([stored, n]) }
|
|
335
355
|
sealGen++; key = k; namer = nm; names = null
|
|
336
356
|
for (const [n, v] of overlay) writeSealed(n, v)
|
|
337
357
|
await chain
|
|
338
|
-
for (const o of old) { try { raw.removeItem.call(localStorage, o) } catch { /* */ } }
|
|
358
|
+
for (const [o, n] of old) { if (unsaved.has(n)) continue; try { raw.removeItem.call(localStorage, o) } catch { /* */ } } // a copy the new key could not write keeps its old one (unlockProtectedLocal's `also` carries it)
|
|
339
359
|
return { entries: overlay.size, moved: old.length }
|
|
340
360
|
}
|
|
341
361
|
/** Relock: nothing readable stays in memory; the sealed blobs stay on disk. */
|
|
@@ -377,8 +397,11 @@ try {
|
|
|
377
397
|
nm.real(e.key).then((name) => {
|
|
378
398
|
if (name == null || key !== k) return
|
|
379
399
|
names = null
|
|
380
|
-
|
|
381
|
-
|
|
400
|
+
// …and say WHICH setting changed, under its real name: a listener for the plain `storage` event saw only the opaque name (side
|
|
401
|
+
// sweep: protected-lane-misses-appearance-change — an open assistant kept the old Appearance)
|
|
402
|
+
const told = () => { try { dispatchEvent(new CustomEvent('wb-protected-storage', { detail: { key: name } })) } catch { /* no window */ } }
|
|
403
|
+
if (e.newValue == null) { overlay.delete(name); told(); return }
|
|
404
|
+
const blob = parseSealed(e.newValue); if (blob) open(k, blob).then((v) => { if (key === k) { overlay.set(name, String(v)); told() } }).catch(() => {})
|
|
382
405
|
}).catch(() => {})
|
|
383
406
|
})
|
|
384
407
|
} catch { /* no window */ }
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
// WHO HOLDS A REACTION — one rule for the server (agent/spaceService.mjs op 'react'), the app (messageActions.js) and the SDK
|
|
2
|
+
// (space.reactionsOf). Pure: no imports, no DOM (the server imports this file as it is).
|
|
3
|
+
//
|
|
4
|
+
// A message's reactions are stored as
|
|
5
|
+
// reactions { emoji: [names] } — what every client has always read; one entry PER REACTOR. In a verified
|
|
6
|
+
// room two members may share a display name, so a name can appear twice.
|
|
7
|
+
// reactBy { emoji: { keyId: name } } — verified rooms (side sweep: reaction-ownership-by-display-name, 2026-11-28):
|
|
8
|
+
// which verified key holds each reaction, under which name. One key holds an
|
|
9
|
+
// emoji once; a rename replaces its name.
|
|
10
|
+
// reactKeys { emoji: { name: keyId } } — the older verified-room record (2026-10-10), kept for older clients and an
|
|
11
|
+
// older server: each name with ONE key that holds it.
|
|
12
|
+
// `reactions` is what is present: a key whose name is no longer in the list holds nothing (an older server took the name
|
|
13
|
+
// out). A message written before `reactBy` existed is read through `reactKeys`; a key it shows under two names (a member
|
|
14
|
+
// who reacted, was renamed, and reacted again) counts once, under the later name.
|
|
15
|
+
// keyId = `${x}.${y}` of the member's signing key (agent/spaceService.mjs keyIdOfJwk).
|
|
16
|
+
|
|
17
|
+
const obj = (o) => (o && typeof o === 'object' && !Array.isArray(o) ? o : {})
|
|
18
|
+
const strs = (a) => (Array.isArray(a) ? a.filter((n) => typeof n === 'string') : [])
|
|
19
|
+
|
|
20
|
+
/** The keys holding `emoji` on `e` as [[keyId, name]] (insertion order), and the names a key no longer holds (legacy). */
|
|
21
|
+
function keyedOf(e, emoji) {
|
|
22
|
+
const by = Object.entries(obj(obj(e && e.reactBy)[emoji])).filter(([k, n]) => k && typeof n === 'string')
|
|
23
|
+
if (by.length) return { keyed: by, stale: [] }
|
|
24
|
+
const byKey = new Map(), stale = []
|
|
25
|
+
for (const [name, key] of Object.entries(obj(obj(e && e.reactKeys)[emoji]))) {
|
|
26
|
+
if (typeof key !== 'string' || !key) continue
|
|
27
|
+
if (byKey.has(key)) stale.push(byKey.get(key))
|
|
28
|
+
byKey.set(key, name)
|
|
29
|
+
}
|
|
30
|
+
return { keyed: [...byKey], stale }
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** One emoji's reactors on entry `e`, in the stored order: [{ name, key }] — `key` null for a name no verified key holds
|
|
34
|
+
* (an open room, or a reaction from before keys were recorded). */
|
|
35
|
+
export function reactorsOf(e, emoji) {
|
|
36
|
+
const names = strs(obj(e && e.reactions)[emoji])
|
|
37
|
+
const { keyed, stale } = keyedOf(e, emoji)
|
|
38
|
+
const queue = new Map() // name → the keys still to place on it
|
|
39
|
+
for (const [key, name] of keyed) { if (!queue.has(name)) queue.set(name, []); queue.get(name).push(key) }
|
|
40
|
+
const skip = new Map() // name → how many legacy duplicates of a renamed key to leave out
|
|
41
|
+
for (const n of stale) skip.set(n, (skip.get(n) || 0) + 1)
|
|
42
|
+
const out = []
|
|
43
|
+
for (const name of names) {
|
|
44
|
+
const q = queue.get(name)
|
|
45
|
+
if (q && q.length) { out.push({ name, key: q.shift() }); continue }
|
|
46
|
+
if (skip.get(name)) { skip.set(name, skip.get(name) - 1); continue }
|
|
47
|
+
out.push({ name, key: null })
|
|
48
|
+
}
|
|
49
|
+
return out
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** Every emoji's reactors: [[emoji, [{ name, key }]]], emoji nobody holds left out. */
|
|
53
|
+
export function allReactors(e) {
|
|
54
|
+
const out = []
|
|
55
|
+
for (const emoji of Object.keys(obj(e && e.reactions))) { const rows = reactorsOf(e, emoji); if (rows.length) out.push([emoji, rows]) }
|
|
56
|
+
return out
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** The three stored fields for one emoji's rows: { names, by, keys } — `by`/`keys` empty when no row has a key. */
|
|
60
|
+
export function storedOf(rows) {
|
|
61
|
+
const names = [], by = {}, keys = {}
|
|
62
|
+
for (const r of rows) {
|
|
63
|
+
names.push(r.name)
|
|
64
|
+
if (r.key) { by[r.key] = r.name; if (keys[r.name] === undefined) keys[r.name] = r.key }
|
|
65
|
+
}
|
|
66
|
+
return { names, by, keys }
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** This device's key in the stored keyId form: accepts the app's / SDK's `kty:crv:x:y` (agentIdentity.keyIdOf), a JWK, or
|
|
70
|
+
* `x.y` as is. '' when none. */
|
|
71
|
+
export function reactKeyOf(k) {
|
|
72
|
+
if (!k) return ''
|
|
73
|
+
if (typeof k === 'object') return k.x && k.y ? `${k.x}.${k.y}` : ''
|
|
74
|
+
const s = String(k)
|
|
75
|
+
const p = s.split(':')
|
|
76
|
+
if (p.length === 4 && p[2] && p[3]) return `${p[2]}.${p[3]}`
|
|
77
|
+
return /^[^:]+\.[^:]+$/.test(s) ? s : ''
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** Is this row mine? A row a verified key holds is mine only when that key is this device's (`myKey`, when it is known);
|
|
81
|
+
* a row with no key — every row of an open room — is mine by name, as it always was. */
|
|
82
|
+
export function rowIsMine(row, me, myKey) {
|
|
83
|
+
const mk = reactKeyOf(myKey)
|
|
84
|
+
if (row && row.key && mk) return row.key === mk
|
|
85
|
+
return !!(me && row && row.name === me)
|
|
86
|
+
}
|
package/roomIntake.js
ADDED
|
@@ -0,0 +1,324 @@
|
|
|
1
|
+
// roomIntake.js — THE MESSAGE INTAKE, the account's side (docs/message-intake.md). Producers that do not hold the
|
|
2
|
+
// message room's key (the Sentinel's Siri and A2A doors, a cloud bot, a webhook's result) WRITE to it and never read it:
|
|
3
|
+
// each holds a drop address (a random token minted here) and the intake's PUBLIC key, seals a box and drops it
|
|
4
|
+
// (op 'intakedrop', keyless). A device of the account reads the waiting boxes, opens them with the intake's private key,
|
|
5
|
+
// and turns each into an ordinary room message (roomMail) — so handlers, claims, retries and purge are roomMail's.
|
|
6
|
+
//
|
|
7
|
+
// THE INTAKE KEY is generated once and kept IN the message room, as its state doc `intakekey` — only holders of the
|
|
8
|
+
// room's key read it (the account's devices; in the hosted app, through the vault's worker). Nothing new travels with the
|
|
9
|
+
// account: the message room's pointer already does. (The design first said "derived from the room key"; a key pair kept
|
|
10
|
+
// in the room gives the same property and needs no curve arithmetic in the page.)
|
|
11
|
+
//
|
|
12
|
+
// THE REGISTRY: the server keeps only token HASHES (op 'intakereg'); the labels, kinds and allowed targets live in the
|
|
13
|
+
// message room's state doc `intake`, which the server checks nothing against and devices check everything against.
|
|
14
|
+
//
|
|
15
|
+
// A BOX BECOMES A MESSAGE ONCE: its row id is `in.<hash 10>.<n>`; one atomic write puts the message AND a mark
|
|
16
|
+
// (collection `inmark`, same id), both ifVersion null — a second device gets 409, and the mark outlives the message
|
|
17
|
+
// (handled and deleted) until the box has left the intake, so a stale read never converts it again. A small box is copied into the row and acknowledged at once; a big one (body over
|
|
18
|
+
// INLINE_MAX — a row holds 16 KB) rides BY REFERENCE ({ box: { drop, n } }; the handler calls body(msg)) and is
|
|
19
|
+
// acknowledged once its message has been handled and left the room. Box contents are UNTRUSTED data, never instructions.
|
|
20
|
+
import { genRecipientKey, openBox } from './e2ee.js'
|
|
21
|
+
|
|
22
|
+
export const INLINE_MAX = 12_000
|
|
23
|
+
export const INTAKE_PAGES_MAX = 8 // pages one collect reads past boxes that must stay (a 10 MB mail is ≤ 6 boxes)
|
|
24
|
+
const KEY_DOC = 'intakekey'
|
|
25
|
+
const REG_DOC = 'intake'
|
|
26
|
+
const KIND_RE = /^[a-z][a-z0-9:_-]{0,39}$/
|
|
27
|
+
// Kinds a producer's boxes may be besides its own (and `<kind>:…`): a mail address's attachment parts come as `mailfile`
|
|
28
|
+
// (infra/cloud-computer/sentinel/mail.mjs inbound, in the live Sentinel image) — refused before, so no attachment ever arrived
|
|
29
|
+
// (docs/state-machines.md I44, found with W#2).
|
|
30
|
+
const RELATED_KINDS = Object.freeze({ mail: Object.freeze(['mailfile']) })
|
|
31
|
+
const MSG = 'msg' // roomMail's collection
|
|
32
|
+
export const SEALED = 'sealed:' // roomMail's sealed-message kind prefix (held equal by spaces/test/roomMailSealed.test.mjs)
|
|
33
|
+
export const MARK = 'inmark' // one row per converted box, same id as its message
|
|
34
|
+
export const MARK_KEEP_MS = 60 * 60_000 // a mark outlives any device's stale read of the intake
|
|
35
|
+
const b64u = (u8) => btoa(String.fromCharCode(...u8)).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')
|
|
36
|
+
export async function dropHash(token) { return b64u(new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(String(token))))) }
|
|
37
|
+
const unb64u = (s) => Uint8Array.from(atob(String(s).replace(/-/g, '+').replace(/_/g, '/') + '='.repeat((4 - (String(s).length % 4)) % 4)), (c) => c.charCodeAt(0))
|
|
38
|
+
/** A producer's drop token, DERIVED from the intake's private key and the producer's id (HMAC-SHA256) — so any device of
|
|
39
|
+
* the account recomputes the same address for 'siri' or one A2A peer, and nothing new has to be stored or synced. */
|
|
40
|
+
export async function deriveDropToken(priv, id) {
|
|
41
|
+
const k = await crypto.subtle.importKey('raw', unb64u(priv.d), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign'])
|
|
42
|
+
return b64u(new Uint8Array(await crypto.subtle.sign('HMAC', k, new TextEncoder().encode('witbitz intake drop v1|' + String(id)))))
|
|
43
|
+
}
|
|
44
|
+
/** The producer a converted message came from, by its row id (`in.<hash 10>.<n>`) → the hash prefix, or ''. */
|
|
45
|
+
export const dropPrefixOf = (msg) => { const m = /^in\.([A-Za-z0-9_-]{10})\.\d+$/.exec(String((msg && msg.id) || '')); return m ? m[1] : '' }
|
|
46
|
+
export const LEAVE_FOR_MS = 5 * 60_000 // a box a cloud device should take (io.leaveFor) waits this long for it
|
|
47
|
+
export const intakeRowId = (hash, n) => `in.${String(hash).slice(0, 10).replace(/[^A-Za-z0-9_-]/g, '_')}.${n}`
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* @param io {{
|
|
51
|
+
* room: () => Promise<string|null>, ensureRoom: () => Promise<string>,
|
|
52
|
+
* state: (room, name, patch?, ifV?) => Promise<{ status, v, state }>, // the message room's state docs
|
|
53
|
+
* intakeReg: (room, ops) => Promise<object>, intake: (room, from?: { drop, n }) => Promise<{ status, boxes, more }>,
|
|
54
|
+
* intakeAck: (room, items) => Promise<object>,
|
|
55
|
+
* data: (room, ops) => Promise<{ status }>, // the room's data op (atomic; 409 = a condition failed)
|
|
56
|
+
* rowsOf: (collection) => Map<id, { row, v }>, // roomMail's fold (roomMail.rowsOf)
|
|
57
|
+
* broadcast?: (kind) => boolean, // a kind every device runs (no claim): see collect
|
|
58
|
+
* now?: () => number,
|
|
59
|
+
* onError?: (where, err) => void,
|
|
60
|
+
* }}
|
|
61
|
+
*/
|
|
62
|
+
export function makeRoomIntake(io) {
|
|
63
|
+
const say = (w, e) => { try { io.onError && io.onError(w, e) } catch { /* */ } }
|
|
64
|
+
const now = io.now || Date.now
|
|
65
|
+
let keyCache = null, regCache = null
|
|
66
|
+
let lastTo = null // the room the newest box this device opened was for — a tapped "New message for your assistant" opens it (space.js openIntakeTap)
|
|
67
|
+
let emptyUntil = 0 // no producer registered: the registry is read again only after this (a mint here resets it)
|
|
68
|
+
const EMPTY_RECHECK_MS = 5 * 60_000
|
|
69
|
+
|
|
70
|
+
// strict: a read that FAILED throws — "no intake" and "could not read it" are different answers (side sweep: an account erase
|
|
71
|
+
// took an unread key for no mail addresses and listed them as removed)
|
|
72
|
+
async function intakeKey({ create = false, strict = false } = {}) {
|
|
73
|
+
if (keyCache) return keyCache
|
|
74
|
+
const room = create ? await io.ensureRoom() : await io.room()
|
|
75
|
+
if (!room) return null
|
|
76
|
+
for (let i = 0; i < 4; i++) {
|
|
77
|
+
const r = await io.state(room, KEY_DOC)
|
|
78
|
+
if (strict && (!r || (r.status !== 200 && r.status !== 404))) throw new Error('intake: the key could not be read')
|
|
79
|
+
if (!r || r.status !== 200) return null
|
|
80
|
+
const st = r.state
|
|
81
|
+
if (st && st.pub && st.priv) { keyCache = { room, pub: st.pub, priv: st.priv }; return keyCache }
|
|
82
|
+
if (!create) return null
|
|
83
|
+
const k = await genRecipientKey()
|
|
84
|
+
const w = await io.state(room, KEY_DOC, { pub: k.publicJwk, priv: k.privateJwk }, Number(r.v) || 0) // another device made one first → 409, read theirs
|
|
85
|
+
if (w && w.status === 200) { keyCache = { room, pub: k.publicJwk, priv: k.privateJwk }; return keyCache }
|
|
86
|
+
}
|
|
87
|
+
return null
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
async function registry(room) {
|
|
91
|
+
const r = await io.state(room, REG_DOC)
|
|
92
|
+
if (!r || r.status !== 200) return null
|
|
93
|
+
regCache = { v: Number(r.v) || 0, drops: (r.state && r.state.drops) || {} }
|
|
94
|
+
return regCache
|
|
95
|
+
}
|
|
96
|
+
async function editRegistry(room, change) {
|
|
97
|
+
for (let i = 0; i < 6; i++) {
|
|
98
|
+
const cur = await registry(room); if (!cur) throw new Error('intake: the registry could not be read')
|
|
99
|
+
const drops = change({ ...cur.drops })
|
|
100
|
+
const w = await io.state(room, REG_DOC, { drops }, cur.v)
|
|
101
|
+
if (w && w.status === 200) { regCache = { v: cur.v + 1, drops }; return drops }
|
|
102
|
+
}
|
|
103
|
+
throw new Error('intake: the registry is busy')
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** A drop address for one producer. `kind` = what its boxes are (their messages' kind, or a prefix of it); `target` =
|
|
107
|
+
* the one room its boxes may address, or 'any'. → { token, hash, pub, room } — hand `token` + `pub` + `room` to the
|
|
108
|
+
* producer; nothing here can read back the token. */
|
|
109
|
+
async function mint({ label, kind, target = 'any' }) {
|
|
110
|
+
if (typeof kind !== 'string' || !KIND_RE.test(kind)) throw new Error('intake: a producer needs a kind')
|
|
111
|
+
const key = await intakeKey({ create: true }); if (!key) throw new Error('intake: no intake key')
|
|
112
|
+
const tok = new Uint8Array(32); crypto.getRandomValues(tok)
|
|
113
|
+
const token = b64u(tok), hash = await dropHash(token)
|
|
114
|
+
await editRegistry(key.room, (d) => ({ ...d, [hash]: { label: String(label || kind).slice(0, 80), kind, target: String(target || 'any').slice(0, 64), created: Date.now() } }))
|
|
115
|
+
const r = await io.intakeReg(key.room, [{ op: 'add', drop: hash }])
|
|
116
|
+
if (!r || r.status !== 200) throw new Error('intake: the drop address was not registered' + (r && r.error ? ` (${r.error})` : ''))
|
|
117
|
+
emptyUntil = 0
|
|
118
|
+
return { token, hash, pub: key.pub, room: key.room }
|
|
119
|
+
}
|
|
120
|
+
/** The drop address of a STABLE producer id ('siri', 'a2a:<lane>:<peer>'): derived from the intake key, registered once
|
|
121
|
+
* (with its kind and target in the sealed registry), the same on every device. → { token, hash, pub, room } */
|
|
122
|
+
async function address({ id, label, kind, target = 'any' }) {
|
|
123
|
+
if (typeof id !== 'string' || !id) throw new Error('intake: an address needs an id')
|
|
124
|
+
if (typeof kind !== 'string' || !KIND_RE.test(kind)) throw new Error('intake: a producer needs a kind')
|
|
125
|
+
const key = await intakeKey({ create: true }); if (!key) throw new Error('intake: no intake key')
|
|
126
|
+
const token = await deriveDropToken(key.priv, id), hash = await dropHash(token)
|
|
127
|
+
const want = { label: String(label || kind).slice(0, 80), kind, target: String(target || 'any').slice(0, 64), id }
|
|
128
|
+
const cur = await registry(key.room)
|
|
129
|
+
const have = cur && cur.drops[hash]
|
|
130
|
+
if (!(have && have.kind === want.kind && have.target === want.target && have.label === want.label && have.id === id)) {
|
|
131
|
+
await editRegistry(key.room, (d) => ({ ...d, [hash]: { ...want, created: (have && have.created) || Date.now() } }))
|
|
132
|
+
}
|
|
133
|
+
const r = await io.intakeReg(key.room, [{ op: 'add', drop: hash }]) // idempotent on the server
|
|
134
|
+
if (!r || r.status !== 200) throw new Error('intake: the drop address was not registered' + (r && r.error ? ` (${r.error})` : ''))
|
|
135
|
+
emptyUntil = 0
|
|
136
|
+
return { token, hash, pub: { x: key.pub.x, y: key.pub.y }, room: key.room }
|
|
137
|
+
}
|
|
138
|
+
/** The drop address a stable producer id ALREADY has — LOOKUP ONLY: no intake key is made, nothing is registered (a Space
|
|
139
|
+
* deleted without ever having had mail gets no address on its way out — I44 / W#3). → { token, hash, pub, room } | null */
|
|
140
|
+
async function lookup({ id }) {
|
|
141
|
+
if (typeof id !== 'string' || !id) return null
|
|
142
|
+
const key = await intakeKey(); if (!key) return null
|
|
143
|
+
const token = await deriveDropToken(key.priv, id), hash = await dropHash(token)
|
|
144
|
+
const cur = await registry(key.room)
|
|
145
|
+
if (!cur) throw new Error('intake: the registry could not be read')
|
|
146
|
+
return cur.drops[hash] ? { token, hash, pub: { x: key.pub.x, y: key.pub.y }, room: key.room } : null
|
|
147
|
+
}
|
|
148
|
+
/** Every stable producer registered in the CURRENT message room's intake, with its drop address → [{ id, kind, target,
|
|
149
|
+
* label, token, hash, pub, room }] (I44 / W#6: what a message-room switch must carry to the new intake). */
|
|
150
|
+
async function addresses() {
|
|
151
|
+
const key = await intakeKey({ strict: true }); if (!key) return []
|
|
152
|
+
const cur = await registry(key.room); if (!cur) throw new Error('intake: the registry could not be read')
|
|
153
|
+
const out = []
|
|
154
|
+
for (const [hash, e] of Object.entries(cur.drops)) {
|
|
155
|
+
if (!e || typeof e.id !== 'string' || !e.id) continue
|
|
156
|
+
const token = await deriveDropToken(key.priv, e.id)
|
|
157
|
+
if (await dropHash(token) !== hash) continue
|
|
158
|
+
out.push({ id: e.id, kind: e.kind, target: e.target, label: e.label, token, hash, pub: { x: key.pub.x, y: key.pub.y }, room: key.room })
|
|
159
|
+
}
|
|
160
|
+
return out
|
|
161
|
+
}
|
|
162
|
+
/** Cut a stable producer off by its id. */
|
|
163
|
+
async function revokeAddress(id) {
|
|
164
|
+
const key = await intakeKey(); if (!key) return false
|
|
165
|
+
return revoke(await dropHash(await deriveDropToken(key.priv, id)))
|
|
166
|
+
}
|
|
167
|
+
/** The registry entry of the producer a converted message came from (its label, kind, target, id) — or null. */
|
|
168
|
+
async function producerOf(msg) {
|
|
169
|
+
const pre = dropPrefixOf(msg); if (!pre) return null
|
|
170
|
+
const room = await io.room(); if (!room) return null
|
|
171
|
+
const find = (reg) => Object.entries(reg.drops).find(([h]) => h.slice(0, 10) === pre)
|
|
172
|
+
let hit = (regCache && regCache.drops) ? find(regCache) : null
|
|
173
|
+
if (!hit) { // not in the cached list (or none yet): read it now. Unreadable → THROW, so the message waits — null means a definite miss,
|
|
174
|
+
// and a handler drops on null (side sweep 2026-11-28: a fresh page's failed read dropped waiting mail)
|
|
175
|
+
const reg = await registry(room); if (!reg) throw new Error('intake: the registry could not be read')
|
|
176
|
+
hit = find(reg)
|
|
177
|
+
}
|
|
178
|
+
return hit ? { hash: hit[0], ...hit[1] } : null
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/** Cut a producer off: its address stops working and its waiting boxes go. */
|
|
182
|
+
async function revoke(hash) {
|
|
183
|
+
const room = await io.room(); if (!room) return false
|
|
184
|
+
const r = await io.intakeReg(room, [{ op: 'remove', drop: hash }])
|
|
185
|
+
await editRegistry(room, (d) => { delete d[hash]; return d })
|
|
186
|
+
return !!(r && r.status === 200)
|
|
187
|
+
}
|
|
188
|
+
async function producers() { const room = await io.room(); if (!room) return {}; const r = await registry(room); return r ? r.drops : {} }
|
|
189
|
+
|
|
190
|
+
const opened = new Map() // `drop:n` → the opened body of a big box this page read (body(msg) answers from here first)
|
|
191
|
+
async function openOne(key, b) {
|
|
192
|
+
let txt = null
|
|
193
|
+
try { txt = await openBox(b.box, key.priv) } catch { txt = null }
|
|
194
|
+
if (txt == null) return null
|
|
195
|
+
try { const o = JSON.parse(txt); return o && typeof o === 'object' ? o : null } catch { return null }
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
/** Read the waiting boxes and turn them into messages. Safe to run on several devices at once. → how many converted.
|
|
199
|
+
* Call it right after roomMail's pass, so the marks and messages it reads are fresh. */
|
|
200
|
+
// what happened to each waiting box (io.trace, optional) — said once per box and outcome, never its contents
|
|
201
|
+
const _traced = new Set()
|
|
202
|
+
const tr = (id, what) => { if (typeof io.trace !== 'function') return; const k = id + '|' + what; if (_traced.has(k)) return; _traced.add(k); try { io.trace('intake ' + String(id).slice(-14) + ': ' + what) } catch { /* */ } }
|
|
203
|
+
async function collect() {
|
|
204
|
+
const room = await io.room(); if (!room) return 0
|
|
205
|
+
if (now() < emptyUntil) return 0
|
|
206
|
+
const reg = await registry(room); if (!reg) return 0
|
|
207
|
+
if (!Object.keys(reg.drops).length) { emptyUntil = now() + EMPTY_RECHECK_MS; return 0 }
|
|
208
|
+
const key = await intakeKey(); if (!key) return 0
|
|
209
|
+
let r = await io.intake(room)
|
|
210
|
+
if (!r || r.status !== 200 || !Array.isArray(r.boxes)) return 0
|
|
211
|
+
const marks = io.rowsOf(MARK), msgs = io.rowsOf(MSG)
|
|
212
|
+
const t = now()
|
|
213
|
+
let converted = 0
|
|
214
|
+
const ackable = new Set() // `drop:n` that may go
|
|
215
|
+
// EVERY PAGE THAT A STAYING BOX HOLDS BACK (side sweep: mail-attachment-blocks-next-intake-page): a read carries ~5 M characters,
|
|
216
|
+
// a mail's attachment part ~3.6 M — and a converted part STAYS (its broadcast message lives 24 h, every device reads it by
|
|
217
|
+
// reference). The read always starts at the first box not acknowledged, so the next part was not read for 24 h, and its message
|
|
218
|
+
// was then born older than its lifetime: dropped, the mail waiting for ever. While the page holds a box that must stay, read on
|
|
219
|
+
// from after it (`from`, an older server ignores it and answers the same page: stop), up to INTAKE_PAGES_MAX pages.
|
|
220
|
+
const all = [], seenAt = new Set()
|
|
221
|
+
for (let page = 0; ; page++) {
|
|
222
|
+
const fresh = r.boxes.filter((b) => !seenAt.has(b.drop + ':' + b.n))
|
|
223
|
+
if (page && fresh.length !== r.boxes.length) break // `from` was not honoured: this page was read already
|
|
224
|
+
for (const b of fresh) { seenAt.add(b.drop + ':' + b.n); all.push(b) }
|
|
225
|
+
for (const b of fresh) {
|
|
226
|
+
const id = intakeRowId(b.drop, b.n), at = b.drop + ':' + b.n
|
|
227
|
+
if (marks.has(id)) { // converted already (here or on another device)
|
|
228
|
+
const mr = marks.get(id).row || {}
|
|
229
|
+
// ⛔ 10·D#1 (pass 10): THE CLOUD DEVICE'S CLAIM IS A LEASE. It marks a box before it delivers it; a worker killed in between
|
|
230
|
+
// (its 15-minute limit, an enclave restart) never delivers — and this device acked the box on the mark alone: the message
|
|
231
|
+
// was lost. A device mark with `until` and no `done` is a delivery in progress: the box stays; once the lease has passed
|
|
232
|
+
// the device is taken to have died and the mark goes, so a later pass delivers the box here (a rare repeat over a loss).
|
|
233
|
+
// A device mark with no `until` is an older device's: as before.
|
|
234
|
+
if (mr.by === 'cloud-device' && Number(mr.until) > 0 && !mr.done) {
|
|
235
|
+
if (t < Number(mr.until)) { tr(id, 'the cloud device is delivering it'); continue }
|
|
236
|
+
tr(id, 'the cloud device\'s claim ran out undelivered — taken back here')
|
|
237
|
+
try { await io.data(room, [{ op: 'del', collection: MARK, id }]) } catch (err) { say('intake:lease', err) }
|
|
238
|
+
continue
|
|
239
|
+
}
|
|
240
|
+
tr(id, 'converted already (mark there)')
|
|
241
|
+
const big = mr.big
|
|
242
|
+
if (!big || !msgs.has(id)) ackable.add(at) // small: copied into its message; big: its message was handled
|
|
243
|
+
continue
|
|
244
|
+
}
|
|
245
|
+
const prod = reg.drops[b.drop]
|
|
246
|
+
const o = prod ? await openOne(key, b) : null
|
|
247
|
+
const kindOk = o && typeof o.kind === 'string' && KIND_RE.test(o.kind) && (o.kind === prod.kind || o.kind.startsWith(prod.kind + ':') || (RELATED_KINDS[prod.kind] || []).includes(o.kind))
|
|
248
|
+
const to = o && typeof o.to === 'string' ? o.to.slice(0, 64) : ''
|
|
249
|
+
const targetOk = o && to && (prod.target === 'any' || prod.target === to)
|
|
250
|
+
if (!(o && kindOk && targetOk)) { tr(id, !prod ? 'no producer registered for its drop' : !o ? 'did not open with the intake key' : !kindOk ? 'kind ' + String(o.kind).slice(0, 20) + ' is not its producer\'s' : 'addressed to another room'); say('intake:refused', new Error(`a box from ${prod ? prod.label : 'an unknown producer'} was refused`)); ackable.add(at); continue }
|
|
251
|
+
// LEFT FOR THE CLOUD DEVICE (docs/always-on-agent-plan.md: an always-on Space answers its outside agents itself, no draft):
|
|
252
|
+
// io.leaveFor(kind, to) — a box for a Space the device keeps is left to it for LEAVE_FOR_MS (it is woken at once and takes it in
|
|
253
|
+
// seconds); after that the device is taken to be away, and this device delivers it as before.
|
|
254
|
+
let leave = false; try { leave = typeof io.leaveFor === 'function' && !!io.leaveFor(o.kind, to) && t - (Number(b.at) || Number(o.at) || t) < LEAVE_FOR_MS } catch { leave = false }
|
|
255
|
+
if (leave) { tr(id, 'left for the cloud device that keeps ' + to.slice(0, 12)); continue }
|
|
256
|
+
const body = o.body ?? null
|
|
257
|
+
const big = JSON.stringify(body).length > INLINE_MAX
|
|
258
|
+
const rowBody = big ? { box: { drop: b.drop, n: b.n } } : body
|
|
259
|
+
// ⛔ SEALED UNDER THE ACCOUNT KEY, like every room message (roomMail.js send): the message room is a standard room.
|
|
260
|
+
let sealedBody = null
|
|
261
|
+
if (typeof io.seal === 'function') { try { sealedBody = await io.seal(rowBody) } catch { sealedBody = null } }
|
|
262
|
+
// ⛔ NEVER READABLE FOR A CONFIDENTIAL ROOM (sync sweep 11-06 P1/P6, still open 11-09): a seal that failed (no account key here just
|
|
263
|
+
// now) wrote the body in the clear into the message room. As roomMail.send: a message for a CONFIDENTIAL room waits — the box
|
|
264
|
+
// stays in the intake, not acknowledged, and becomes a sealed message on a later pass once the key is here. An ordinary room's
|
|
265
|
+
// message goes as before (a device with no account key yet still delivers its Siri drops).
|
|
266
|
+
if (rowBody != null && !sealedBody && typeof io.confidential === 'function' && io.confidential(to)) { say('intake:waits', new Error(`a box from ${prod.label} for a confidential room waits — no account key here to seal it`)); continue }
|
|
267
|
+
lastTo = { to, kind: prod.kind, at: Date.now() } // opened and valid: whoever converts it, this is where it goes
|
|
268
|
+
// A BROADCAST kind (io.broadcast — a mail's attachment parts, I44 / W#2) is run by EVERY device that holds the target's key,
|
|
269
|
+
// not claimed by one: each keeps its copy, so whichever device later claims the mail has every part.
|
|
270
|
+
let fan = false; try { fan = typeof io.broadcast === 'function' && !!io.broadcast(o.kind) } catch { fan = false }
|
|
271
|
+
const row = { from: 'intake:' + prod.kind, to, kind: sealedBody ? SEALED + o.kind : o.kind, once: !fan, at: Number(o.at) || Number(b.at) || t, device: 'intake', via: { producer: prod.label }, ...(sealedBody ? { sbody: sealedBody } : { body: rowBody }) }
|
|
272
|
+
// ONE atomic write: the mark and the message, both "must not exist" — a box becomes a message once, even after its
|
|
273
|
+
// message was handled and deleted (the mark stays until the box has left the intake).
|
|
274
|
+
const w = await io.data(room, [
|
|
275
|
+
{ op: 'put', collection: MARK, id, row: { at: t, big }, ifVersion: null },
|
|
276
|
+
{ op: 'put', collection: MSG, id, row, ifVersion: null },
|
|
277
|
+
])
|
|
278
|
+
tr(id, (w && w.status === 200 ? 'converted into a ' + (sealedBody ? 'sealed ' : '') + 'message for ' : 'not converted (' + (w && w.status) + ') for ') + String(to).slice(0, 10) + ' · ' + o.kind)
|
|
279
|
+
if (w && w.status === 200) { converted++; if (big) opened.set(at, body); else ackable.add(at) }
|
|
280
|
+
// 409: another device converted it first — the next pass sees its mark
|
|
281
|
+
}
|
|
282
|
+
if (!r.more || page + 1 >= INTAKE_PAGES_MAX || !r.boxes.length || r.boxes.every((b) => ackable.has(b.drop + ':' + b.n))) break // nothing holds the head: the ack moves it
|
|
283
|
+
const last = r.boxes[r.boxes.length - 1]
|
|
284
|
+
const nx = await io.intake(room, { drop: last.drop, n: last.n + 1 })
|
|
285
|
+
if (!nx || nx.status !== 200 || !Array.isArray(nx.boxes)) break
|
|
286
|
+
r = nx
|
|
287
|
+
}
|
|
288
|
+
// acknowledge a CONTIGUOUS prefix per producer: positions are a count, so a box goes only with everything before it
|
|
289
|
+
const items = []
|
|
290
|
+
const byDrop = new Map(); for (const b of all) (byDrop.get(b.drop) || byDrop.set(b.drop, []).get(b.drop)).push(b.n)
|
|
291
|
+
for (const [drop, ns] of byDrop) {
|
|
292
|
+
let upTo = null
|
|
293
|
+
for (const n of ns.sort((a, c) => a - c)) { if (!ackable.has(drop + ':' + n)) break; upTo = n + 1 }
|
|
294
|
+
if (upTo != null) items.push({ drop, upTo })
|
|
295
|
+
}
|
|
296
|
+
if (items.length) { try { await io.intakeAck(room, items) } catch (err) { say('intake:ack', err) } }
|
|
297
|
+
// a mark goes once its box has left the intake for good: not in a COMPLETE read, and older than any stale read
|
|
298
|
+
if (!r.more) {
|
|
299
|
+
const waiting = new Set(all.map((b) => intakeRowId(b.drop, b.n)))
|
|
300
|
+
const done = [...marks].filter(([id, m]) => !waiting.has(id) && !msgs.has(id) && t - (Number(m.row && m.row.at) || 0) > MARK_KEEP_MS).map(([id]) => id).slice(0, 50)
|
|
301
|
+
if (done.length) { try { await io.data(room, done.map((id) => ({ op: 'del', collection: MARK, id }))) } catch (err) { say('intake:marks', err) } }
|
|
302
|
+
}
|
|
303
|
+
return converted
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
/** A message's body: inline, or — a big box carried by reference — read and opened from the intake. */
|
|
307
|
+
async function body(msg) {
|
|
308
|
+
const b = msg && msg.body
|
|
309
|
+
if (!(b && b.box && typeof b.box.drop === 'string' && Number.isInteger(b.box.n))) return b ?? null
|
|
310
|
+
const at = b.box.drop + ':' + b.box.n
|
|
311
|
+
if (opened.has(at)) return opened.get(at)
|
|
312
|
+
const room = await io.room(); const key = await intakeKey(); if (!room || !key) return null
|
|
313
|
+
const r = await io.intake(room, { drop: b.box.drop, n: b.box.n }) // read from THAT box: a later page is not behind the head (an older server: the head page, as before)
|
|
314
|
+
const hit = r && Array.isArray(r.boxes) ? r.boxes.find((x) => x.drop === b.box.drop && x.n === b.box.n) : null
|
|
315
|
+
const o = hit ? await openOne(key, hit) : null
|
|
316
|
+
const out = o ? (o.body ?? null) : null
|
|
317
|
+
if (o) opened.set(at, out)
|
|
318
|
+
return out
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
/** The message room moved (two devices made one): its intake key is another, so every address is too. */
|
|
322
|
+
const forget = () => { keyCache = null; regCache = null; emptyUntil = 0 }
|
|
323
|
+
return { mint, address, lookup, addresses, revoke, revokeAddress, producerOf, forget, producers, publicKey: async () => (await intakeKey({ create: true }) || {}).pub || null, collect, body, lastConverted: () => lastTo }
|
|
324
|
+
}
|