@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/sdkComputers.js
CHANGED
|
@@ -12,11 +12,11 @@
|
|
|
12
12
|
|
|
13
13
|
import { attachmentWarning, partsFor, parseModel, normRevert, ocPermissionRuleset, OC_ASK_PERMISSIONS } from './opencodeWire.js'
|
|
14
14
|
import { pageQuery, cursorBefore, mayHaveMore, mergeTail, PAGE } from './codeHistory.js'
|
|
15
|
-
import { undoTarget } from './codeUndo.js'
|
|
15
|
+
import { undoTarget, visibleMessages } from './codeUndo.js'
|
|
16
16
|
import { commandTurn, normCommands } from './codeCommands.js'
|
|
17
17
|
import { acceptEditsRules, acceptsEdits, unsuitableCodeModels, wildcardMatch } from './codeModes.js'
|
|
18
18
|
import { sentinelKeys, askGenuine, decideTag } from './codeSentinel.js'
|
|
19
|
-
import { cachedSessions, loadSession, saveSession, clearSession, saveList, loadList, slimSession, prune, forgetComputer } from './codeCache.js'
|
|
19
|
+
import { cachedSessions, loadSession, saveSession, clearSession, saveList, loadList, slimSession, prune, forgetComputer, removeCachedSession } from './codeCache.js'
|
|
20
20
|
import { idb } from './idb.js'
|
|
21
21
|
import { languageNudge, withLanguage } from './codeLanguage.js'
|
|
22
22
|
import { PendingCodeDrafts, providerRefusal, firstOutputStarted, promptLanded } from './codeSent.js'
|
|
@@ -397,6 +397,15 @@ export class Computer {
|
|
|
397
397
|
// create scoped). Each session's folder is learned once (create, list, or GET /session/<id>, which answers unscoped)
|
|
398
398
|
// and sent on every call about it.
|
|
399
399
|
this._dirs = new Map() // session id → its directory
|
|
400
|
+
// a listener whose folder lookups all failed waits here, and moves when any later read learns the folder (side sweep round 2)
|
|
401
|
+
this._dirWaiters = new Map() // session id → Set of (dir) => void
|
|
402
|
+
const setDir = this._dirs.set.bind(this._dirs)
|
|
403
|
+
this._dirs.set = (k, v) => {
|
|
404
|
+
setDir(k, v)
|
|
405
|
+
const w = this._dirWaiters.get(k)
|
|
406
|
+
if (w) { this._dirWaiters.delete(k); for (const f of w) { try { f(v) } catch { /* */ } } }
|
|
407
|
+
return this._dirs
|
|
408
|
+
}
|
|
400
409
|
this.id = computer.id
|
|
401
410
|
this.name = computer.name
|
|
402
411
|
const req = (m, p, b) => this._req(m, p, b)
|
|
@@ -406,7 +415,7 @@ export class Computer {
|
|
|
406
415
|
// app sends the open session's folder, opencodeApp.js api; unscoped, an approval in another folder was never seen after a
|
|
407
416
|
// reload and the agent waited). `{ dir }` or `{ session }` scopes one call; with neither, a list is asked in EVERY folder the
|
|
408
417
|
// computer's sessions live in (learned from the session list once) and joined by id.
|
|
409
|
-
const scopeOf = async ({ session = '', dir = '' } = {}) => (dir ? String(dir) : session ? this._dirOf(session) : null)
|
|
418
|
+
const scopeOf = async ({ session = '', dir = '' } = {}) => (dir ? String(dir) : session ? this._dirOf(session, { strict: true }) : null)
|
|
410
419
|
const allDirs = async () => {
|
|
411
420
|
const list = await req('GET', '/experimental/session?archived=true')
|
|
412
421
|
if (!Array.isArray(list)) throw fail('unreadable', 'the computer did not return its sessions')
|
|
@@ -521,6 +530,20 @@ export class Computer {
|
|
|
521
530
|
const write = snapshot.length ? saveSession(cache.cid, cacheSid, snapshot, { dir: this._dirs.get(sid) || '' }, cache.store) : clearSession(cache.cid, cacheSid, cache.store)
|
|
522
531
|
await write.then(() => prune(cache.cid, undefined, cache.store)).catch(() => {})
|
|
523
532
|
}
|
|
533
|
+
} else if (cache && messages.length) {
|
|
534
|
+
// AN OLDER PAGE joins the offline copy when it is the page just before what the copy holds (side sweep: sdk-offline-older-code-pages):
|
|
535
|
+
// it was returned and never kept, so the same page read again offline was missing. A copy that starts elsewhere is left alone.
|
|
536
|
+
cache.check()
|
|
537
|
+
const cacheSid = seg(sid, 'session')
|
|
538
|
+
const previous = await loadSession(cache.cid, cacheSid, cache.store).catch(() => null)
|
|
539
|
+
cache.check()
|
|
540
|
+
const held = Array.isArray(previous?.msgs) ? previous.msgs : []
|
|
541
|
+
// …or a page whose cursor falls INSIDE the copy (a tail refresh after a new message hands a cursor there): the page ends
|
|
542
|
+
// right before a held message, so it runs on from the copy without a gap (side sweep round 2)
|
|
543
|
+
if (held.length && held.some(m => cursorBefore(m) === cursor)) {
|
|
544
|
+
const ids = new Set(held.map(m => m?.info?.id).filter(Boolean))
|
|
545
|
+
await saveSession(cache.cid, cacheSid, [...messages.filter(m => !ids.has(m?.info?.id)), ...held], { ...(typeof previous.title === 'string' ? { title: previous.title } : {}), dir: this._dirs.get(sid) || previous.dir || '' }, cache.store).catch(() => {})
|
|
546
|
+
}
|
|
524
547
|
}
|
|
525
548
|
const next = mayHaveMore(messages, limit) && cursorBefore(messages[0])
|
|
526
549
|
return { messages, cursor: next && next !== cursor ? next : null }
|
|
@@ -796,7 +819,15 @@ export class Computer {
|
|
|
796
819
|
},
|
|
797
820
|
abort: async (sid) => req('POST', await inDir(sid, `/session/${seg(sid, 'session')}/abort`), {}),
|
|
798
821
|
rename: async (sid, title) => req('PATCH', await inDir(sid, `/session/${seg(sid, 'session')}`), { title: String(title || '').slice(0, 200) }),
|
|
799
|
-
remove: async (sid) => {
|
|
822
|
+
remove: async (sid) => {
|
|
823
|
+
const r = await req('DELETE', await inDir(sid, `/session/${seg(sid, 'session')}`))
|
|
824
|
+
this._dirs.delete(String(sid))
|
|
825
|
+
// …and its saved transcript on this device: cachedSession() still returned the deleted conversation (side sweep 2026-11-28).
|
|
826
|
+
// The cache is read through the account whether or not THIS handle opened it, so it is cleared the same way.
|
|
827
|
+
const saved = cache || await owner._cache(computer.id).catch(() => null)
|
|
828
|
+
if (saved) await removeCachedSession(saved.cid, seg(sid, 'session'), saved.store)
|
|
829
|
+
return r
|
|
830
|
+
},
|
|
800
831
|
todo: async (sid) => req('GET', await inDir(sid, `/session/${seg(sid, 'session')}/todo`)),
|
|
801
832
|
/** { <session id>: status } — `{ session }` or `{ dir }` for one folder; otherwise every folder's, joined. */
|
|
802
833
|
status: async (opts = {}) => {
|
|
@@ -937,9 +968,57 @@ export class Computer {
|
|
|
937
968
|
const sid = String(session || ''); seg(sid, 'session')
|
|
938
969
|
const info = await this._req('GET', `/session/${encodeURIComponent(sid)}`)
|
|
939
970
|
if (info && typeof info.directory === 'string' && info.directory) this._dirs.set(sid, info.directory)
|
|
940
|
-
|
|
941
|
-
|
|
942
|
-
|
|
971
|
+
const page = async (cursor) => (await this._req('GET', withDir(`/session/${encodeURIComponent(sid)}/message?${pageQuery({ limit: PAGE, cursor })}`, this._dirs.get(sid) || ''))) || []
|
|
972
|
+
let ms = Array.isArray(messages) ? messages : await page('')
|
|
973
|
+
// A LONG REPLY runs past one page: read back (a page at a time) until its prompt is in view or the session's start, so a file it
|
|
974
|
+
// wrote early is not left out (side sweep: sdk-code-outputs-truncate-long-reply; round 5: a bound of 25 pages cut a longer reply
|
|
975
|
+
// with no sign of it).
|
|
976
|
+
if (!Array.isArray(messages)) {
|
|
977
|
+
const rev = normRevert(info && info.revert)
|
|
978
|
+
for (let got = ms; mayHaveMore(got, PAGE) && !visibleMessages(ms, rev).some((m) => m && m.info && m.info.role === 'user');) {
|
|
979
|
+
const cursor = cursorBefore(ms[0]); if (!cursor) break
|
|
980
|
+
got = await page(cursor)
|
|
981
|
+
if (!Array.isArray(got) || !got.length) break
|
|
982
|
+
const have = new Set(ms.map((m) => m && m.info && m.info.id))
|
|
983
|
+
const older = got.filter((m) => m && m.info && !have.has(m.info.id))
|
|
984
|
+
if (!older.length) break // a page with nothing new (a server that ignored the cursor): never ask for it again
|
|
985
|
+
ms = [...older, ...ms]
|
|
986
|
+
}
|
|
987
|
+
}
|
|
988
|
+
let asked = 0 // when the prompt was sent, when known: a named file must have changed since (as the app's cards ask)
|
|
989
|
+
// the latest reply: after the last prompt STILL SHOWING — an undone turn (the session's revert point) is hidden first, as the app
|
|
990
|
+
// does before it draws output cards (side sweep: sdk-code-outputs-include-undone-reply)
|
|
991
|
+
// A revert point OLDER than the page read: every message read is undone — read back until it is found, with a prompt before it
|
|
992
|
+
// (side sweep round 2). Not found within the bound: no reply shows, and nothing is listed rather than an undone file.
|
|
993
|
+
const rv = !Array.isArray(messages) && normRevert(info && info.revert)
|
|
994
|
+
if (rv) {
|
|
995
|
+
const at = () => ms.findIndex((m) => m && m.info && m.info.id === rv.messageID)
|
|
996
|
+
const userBefore = () => ms.slice(0, at()).some((m) => m && m.info && m.info.role === 'user')
|
|
997
|
+
let more = mayHaveMore(ms, 20)
|
|
998
|
+
for (let n = 0; more && (at() < 0 || !userBefore()) && n < 10; n++) {
|
|
999
|
+
const page = (await this._req('GET', withDir(`/session/${encodeURIComponent(sid)}/message?${pageQuery({ limit: PAGE, cursor: cursorBefore(ms[0]) })}`, this._dirs.get(sid) || ''))) || []
|
|
1000
|
+
if (!Array.isArray(page) || !page.length) { more = false; break }
|
|
1001
|
+
const have = new Set(ms.map((m) => m && m.info && m.info.id))
|
|
1002
|
+
ms = [...page.filter((m) => m && m.info && !have.has(m.info.id)), ...ms]
|
|
1003
|
+
more = mayHaveMore(page, PAGE)
|
|
1004
|
+
}
|
|
1005
|
+
if (more && at() < 0) ms = [] // stopped at the bound with the revert point still further back (a point not in the history hides nothing)
|
|
1006
|
+
}
|
|
1007
|
+
if (!Array.isArray(messages)) { ms = visibleMessages(ms, rv); const k = ms.map((m) => m && m.info && m.info.role).lastIndexOf('user'); asked = k >= 0 ? Number(ms[k].info.time && ms[k].info.time.created) || 0 : 0; ms = k >= 0 ? ms.slice(k + 1) : ms } // the latest reply: after the last prompt
|
|
1008
|
+
const outs = replyOutputs(ms, { directory: (info && info.directory) || '', session: sid })
|
|
1009
|
+
// A path the answer only NAMES is an output only once the computer says the file is there — and, when the prompt's time is
|
|
1010
|
+
// known, that it changed since (codeOutputCards.js, the same rule; side sweep: sdk-code-outputs-list-unconfirmed-file-mentions).
|
|
1011
|
+
// A file the reply wrote, and a screenshot, come from its tools and are listed as before.
|
|
1012
|
+
const named = outs.filter((o) => o.source === 'named')
|
|
1013
|
+
if (!named.length) return outs
|
|
1014
|
+
const ok = new Set()
|
|
1015
|
+
await Promise.all(named.map(async (o) => {
|
|
1016
|
+
try {
|
|
1017
|
+
const r = await this._t.request('GET', `${OUTPUT_ROUTE}?session=${encodeURIComponent(sid)}&path=${encodeURIComponent(o.path)}&stat=1`)
|
|
1018
|
+
if (r && r.ok && r.json && (!asked || Number(r.json.mtime) >= asked - 2000)) ok.add(o)
|
|
1019
|
+
} catch { /* not confirmed: left out, as the app hides its card */ }
|
|
1020
|
+
}))
|
|
1021
|
+
return outs.filter((o) => o.source !== 'named' || ok.has(o))
|
|
943
1022
|
}
|
|
944
1023
|
|
|
945
1024
|
/** 'online' | 'connecting' | 'offline' */
|
|
@@ -955,13 +1034,21 @@ export class Computer {
|
|
|
955
1034
|
}
|
|
956
1035
|
|
|
957
1036
|
/** @private a session's directory — learned once, then kept ('' when the computer does not say) */
|
|
958
|
-
|
|
1037
|
+
// `strict`: a failed ask THROWS instead of answering '' (the default project) — a call scoped to one session must not run in
|
|
1038
|
+
// another folder (side sweep: sdk-code-file-list-default-after-folder-lookup-failure)
|
|
1039
|
+
async _dirOf (sid, { strict = false } = {}) {
|
|
1040
|
+
const r = await this._dirLookup(sid)
|
|
1041
|
+
if (!r.known && strict) throw fail('unreadable', 'could not find the session’s folder on the computer', { cause: r.err })
|
|
1042
|
+
return r.d
|
|
1043
|
+
}
|
|
1044
|
+
/** @private → { d, known, err }: `known` false = the ask failed (asked again next time) */
|
|
1045
|
+
async _dirLookup (sid) {
|
|
959
1046
|
const id = String(sid || '')
|
|
960
|
-
if (this._dirs.has(id)) return this._dirs.get(id)
|
|
961
|
-
let d = '', known = false
|
|
962
|
-
try { const info = await this._req('GET', `/session/${encodeURIComponent(seg(id, 'session') && id)}`); d = info && typeof info.directory === 'string' ? info.directory : ''; known = true } catch { d = '' }
|
|
1047
|
+
if (this._dirs.has(id)) return { d: this._dirs.get(id), known: true }
|
|
1048
|
+
let d = '', known = false, err = null
|
|
1049
|
+
try { const info = await this._req('GET', `/session/${encodeURIComponent(seg(id, 'session') && id)}`); d = info && typeof info.directory === 'string' ? info.directory : ''; known = true } catch (e) { d = ''; err = e }
|
|
963
1050
|
if (known) this._dirs.set(id, d) // an answer without a folder is kept too (asked once); a failed ask is asked again next time
|
|
964
|
-
return d
|
|
1051
|
+
return { d, known, err }
|
|
965
1052
|
}
|
|
966
1053
|
|
|
967
1054
|
/** Live events from the computer (OpenCode's, parsed): `on('message.part.updated', fn)`, or `on('*', fn)` for all. → off
|
|
@@ -969,7 +1056,7 @@ export class Computer {
|
|
|
969
1056
|
* server's default folder — without it, its events never arrive. */
|
|
970
1057
|
on (type, fn, { session = '', dir = '' } = {}) {
|
|
971
1058
|
if (typeof fn !== 'function') throw fail('invalid_argument', 'on(type, fn) needs a function')
|
|
972
|
-
let off = false, stream = null, streamDir = ''
|
|
1059
|
+
let off = false, stream = null, streamDir = '', waiter = null
|
|
973
1060
|
const attach = (d) => {
|
|
974
1061
|
if (off) return
|
|
975
1062
|
streamDir = d
|
|
@@ -985,10 +1072,7 @@ export class Computer {
|
|
|
985
1072
|
if (!stream.subs.has(type)) stream.subs.set(type, new Set())
|
|
986
1073
|
stream.subs.get(type).add(fn)
|
|
987
1074
|
}
|
|
988
|
-
|
|
989
|
-
else this._dirOf(session).then(attach, () => attach(''))
|
|
990
|
-
return () => {
|
|
991
|
-
off = true
|
|
1075
|
+
const detach = () => {
|
|
992
1076
|
const listeners = stream?.subs.get(type)
|
|
993
1077
|
if (!listeners || !listeners.delete(fn)) return
|
|
994
1078
|
if (!listeners.size) stream.subs.delete(type)
|
|
@@ -997,6 +1081,23 @@ export class Computer {
|
|
|
997
1081
|
stream.stop?.()
|
|
998
1082
|
}
|
|
999
1083
|
}
|
|
1084
|
+
if (dir || !session) attach(String(dir || ''))
|
|
1085
|
+
else {
|
|
1086
|
+
// A FAILED FOLDER LOOKUP is asked again (side sweep: sdk-code-event-listener-keeps-default-folder): the listener waits on the
|
|
1087
|
+
// default stream meanwhile, and MOVES to the session's folder once it is learned — it stayed on the default one for good.
|
|
1088
|
+
const lookup = (n) => this._dirLookup(session).then(({ d, known }) => {
|
|
1089
|
+
if (off) return
|
|
1090
|
+
if (known) { if (!stream) attach(d); else if (d !== streamDir) { detach(); stream = null; attach(d) } return }
|
|
1091
|
+
if (!stream) attach('')
|
|
1092
|
+
if (n < 5) { setTimeout(() => lookup(n + 1), (this._dirRetryMs ?? 2000) * 2 ** n); return }
|
|
1093
|
+
// the retries are spent: move when any later read (a session list, a message read) learns the folder
|
|
1094
|
+
waiter = (d) => { waiter = null; if (!off && d !== streamDir) { detach(); stream = null; attach(d) } }
|
|
1095
|
+
if (!this._dirWaiters.has(String(session))) this._dirWaiters.set(String(session), new Set())
|
|
1096
|
+
this._dirWaiters.get(String(session)).add(waiter)
|
|
1097
|
+
}, () => { if (!off && !stream) attach('') })
|
|
1098
|
+
lookup(0)
|
|
1099
|
+
}
|
|
1100
|
+
return () => { off = true; if (waiter) this._dirWaiters.get(String(session))?.delete(waiter); detach() }
|
|
1000
1101
|
}
|
|
1001
1102
|
|
|
1002
1103
|
_stop () { this._drafts.close(); for (const cancel of this._firstOutputWatches) cancel(); for (const st of this._streams.values()) { try { if (st.stop) st.stop() } catch { /* */ } } this._streams.clear(); try { this._t.close() } catch { /* */ } if (this._owner._open.get(this.id) === this) this._owner._open.delete(this.id) } // only itself: never a newer opening of the same computer
|
package/sdkDictation.js
CHANGED
|
@@ -203,7 +203,7 @@ export class Dictation {
|
|
|
203
203
|
|
|
204
204
|
/** Throw the press away. */
|
|
205
205
|
cancel() {
|
|
206
|
-
if (!this._live) return
|
|
206
|
+
if (!this._live) { this._interrupted = null; return } // an interrupted press's kept words go too — Stop must not return them (side sweep)
|
|
207
207
|
this._live = false
|
|
208
208
|
this._cloudRun = null
|
|
209
209
|
this._release()
|
package/sdkErase.js
CHANGED
|
@@ -188,7 +188,9 @@ export class Erasure {
|
|
|
188
188
|
read: d.read || (async (room) => {
|
|
189
189
|
const mk = await keyOf(room)
|
|
190
190
|
if (!mk) return null // a room this client cannot open is treated as shared: never deleted unchecked
|
|
191
|
-
|
|
191
|
+
let gone = false
|
|
192
|
+
const entries = await readAllEntries((since) => client.poll(room, mk, undefined, since), { onGone: () => { gone = true } }) // every page, not the first (sync sweep 2026-11-09)
|
|
193
|
+
if (gone) return { gone: true } // deleted already (410): not "unreadable ⇒ shared" (side sweep: account-erase-retry-treats-deleted-room-as-shared)
|
|
192
194
|
if (!entries) return null
|
|
193
195
|
let config = null; try { config = await client.getConfig(room, mk) } catch { config = null }
|
|
194
196
|
return { entries, config }
|
package/sdkExports.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { exportSpace, recreateSpace } from './spaceExport.js'
|
|
2
|
-
import { makeBundle, sealSpaceMeta, keysFileText } from './offlineBundle.js'
|
|
1
|
+
import { exportSpace, recreateSpace, missingAttachments, messageCount } from './spaceExport.js'
|
|
2
|
+
import { makeBundle, sealSpaceMeta, keysFileText, OFFLINE_ATTACHMENTS_MAX_BYTES, addAttachmentStats } from './offlineBundle.js'
|
|
3
3
|
|
|
4
4
|
// Downloads stay in the document doing the export. A vault never returns the
|
|
5
5
|
// contents or a recovery key to its embedding page.
|
|
@@ -24,8 +24,13 @@ export async function saveRoomExport(sp, tier, current = () => true, title = sp.
|
|
|
24
24
|
const bundle = await exportSpace(sp.room, reader, { title })
|
|
25
25
|
if (!current()) throw new Error('account_changed')
|
|
26
26
|
bundle.tier = tier
|
|
27
|
+
// A readable file carries no credential (a connection's callKey, the room's earlier keys): exportSpace leaves them out for
|
|
28
|
+
// every caller — spaceExport.js portableConfig (side sweep: portable-export-includes-room-credentials).
|
|
27
29
|
saveExport('witbitz-space-' + sp.room + '.json', JSON.stringify(bundle), 'application/json')
|
|
28
|
-
|
|
30
|
+
// the attachments the file still carries only as a pointer to this room (their read failed): said, as the app says it — a
|
|
31
|
+
// recreated room cannot open them (side sweep: portable-export-silent-attachment-read-failure)
|
|
32
|
+
const missing = missingAttachments(bundle)
|
|
33
|
+
return { count: messageCount(bundle.entries), ...(missing ? { attachmentsMissing: missing } : {}) } // the MESSAGE count: a photo's Safe media copy is not one (side sweep: room-export-counts-hidden-records-as-messages)
|
|
29
34
|
}
|
|
30
35
|
|
|
31
36
|
export async function recreateExport(wb, bundle, { tier = bundle?.tier || (bundle?.device?.confidential === false ? 'standard' : 'enclave') } = {}) {
|
|
@@ -49,16 +54,20 @@ export async function recreateExport(wb, bundle, { tier = bundle?.tier || (bundl
|
|
|
49
54
|
return { space, carried: result.carried, total: result.total, ...(titleWarning ? { titleWarning } : {}) }
|
|
50
55
|
}
|
|
51
56
|
|
|
57
|
+
// `resolveRoom(room, keysOnly, attachments)`: `attachments` = the exportSealed option that puts the room's stored attachments in
|
|
58
|
+
// its sealed ledger — ONE cap (OFFLINE_ATTACHMENTS_MAX_BYTES) for the whole file; the room's `attachments` answer comes back
|
|
59
|
+
// beside its ledger and the result says how many were left out (`attachments: { included, tooLarge, failed }`).
|
|
52
60
|
export async function saveAccountArchive(rooms, resolveRoom, recoveryKeys, current, destination = 'download') {
|
|
53
61
|
if (!['download', 'clipboard'].includes(destination) || (destination === 'clipboard' && !recoveryKeys)) throw Object.assign(new Error('Invalid archive destination'), { code: 'invalid_argument' })
|
|
54
62
|
const spaces = [], keys = [], unavailable = []
|
|
63
|
+
let att = null
|
|
55
64
|
for (const r of rooms) {
|
|
56
65
|
if (!current()) throw new Error('account_changed')
|
|
57
66
|
try {
|
|
58
|
-
const { key, ledger, count } = await resolveRoom(r, recoveryKeys)
|
|
67
|
+
const { key, ledger, count, attachments } = await resolveRoom(r, recoveryKeys, { budget: Math.max(1, OFFLINE_ATTACHMENTS_MAX_BYTES - ((att && att.bytes) || 0)) })
|
|
59
68
|
if (!key || (!recoveryKeys && !ledger)) throw new Error('room_unavailable')
|
|
60
69
|
if (recoveryKeys) keys.push({ room: r.room, title: r.label || r.title || '', key })
|
|
61
|
-
else spaces.push({ meta: await sealSpaceMeta(key, { room: r.room, title: r.label || r.title || '', count }), ledger })
|
|
70
|
+
else { spaces.push({ meta: await sealSpaceMeta(key, { room: r.room, title: r.label || r.title || '', count }), ledger }); att = addAttachmentStats(att, attachments) }
|
|
62
71
|
} catch { unavailable.push(r.room) }
|
|
63
72
|
}
|
|
64
73
|
if (!current()) throw new Error('account_changed')
|
|
@@ -67,5 +76,5 @@ export async function saveAccountArchive(rooms, resolveRoom, recoveryKeys, curre
|
|
|
67
76
|
if (destination === 'clipboard') await navigator.clipboard.writeText(keysFileText(keys))
|
|
68
77
|
else if (recoveryKeys) saveExport('witbitz-room-keys.txt', keysFileText(keys), 'text/plain')
|
|
69
78
|
else saveExport('witbitz-spaces.json', JSON.stringify(makeBundle(spaces)), 'application/json')
|
|
70
|
-
return { saved, unavailable }
|
|
79
|
+
return { saved, unavailable, ...(att && att.total ? { attachments: { included: att.included, tooLarge: att.tooLarge, failed: att.failed } } : {}) }
|
|
71
80
|
}
|
package/sdkInvitations.js
CHANGED
|
@@ -5,15 +5,17 @@ import { EMAIL } from './memberChange.js'
|
|
|
5
5
|
import { boxApp } from './attestedBox.js'
|
|
6
6
|
|
|
7
7
|
const fail = (code, text) => Object.assign(new Error('witbitz: ' + text), { code })
|
|
8
|
+
// the account backup's record of this room says it is a lane (kept as one, or detached from its Space)
|
|
9
|
+
const laneInBackup = (sp) => { try { const rooms = (sp._wb && sp._wb.backup && sp._wb.backup.rooms) || []; const r = rooms.find((x) => x && x.room === sp.room); return !!(r && (r.kind === 'lane' || r.detachedLane)) } catch { return false } }
|
|
8
10
|
export async function resendInvitation(sp, { email, username } = {}) {
|
|
9
|
-
if (sp._sharedRoom) throw fail('lane', 'a private lane cannot invite another member')
|
|
11
|
+
if (sp._sharedRoom || sp._detachedLane || laneInBackup(sp)) throw fail('lane', 'a private lane cannot invite another member') // a lane reopened as a plain Space, or detached, is still one member's room (side sweep: sdk-resend-forgets-private-lane-status)
|
|
10
12
|
if (!!email === !!username || (email && !EMAIL.test(email)) || (username && !validUsername(username))) throw fail('invalid_argument', 'name one recipient by email or username')
|
|
11
13
|
const wb = sp._wb, client = wb && wb._client
|
|
12
14
|
if (!client || !wb._session || !wb._session.idToken) throw fail('sign_in_required', 'sign in before sending an invitation')
|
|
13
15
|
// Never downgrade an attested invitation to a bearer link in a normal directory box.
|
|
14
16
|
let attested
|
|
15
17
|
try { attested = await client.attestedRoom(sp.room, sp._mk) } catch { throw fail('policy_unreadable', 'the device policy could not be read') }
|
|
16
|
-
const cfg = await sp._gateConfig()
|
|
18
|
+
const cfg = await sp._gateConfig({ fresh: true, plainMark: true }) // the CURRENT roles: isAdmin / isOwner below read this copy (side sweep 2026-11-28: a cached one kept a demoted admin, refused a promoted one)
|
|
17
19
|
if (cfg.admission === 'email') {
|
|
18
20
|
if (!(await sp.isAdmin(wb._session.email)) && !(await sp.isOwner(wb._session.email))) throw fail('not_admin', 'only an owner or admin may resend an invitation')
|
|
19
21
|
}
|
package/sdkKeptAgent.js
CHANGED
|
@@ -2,6 +2,7 @@ import { linkOwnAgent, unlinkOwnAgent } from './ownAgentLink.js'
|
|
|
2
2
|
import { enableLaneIn, addPeerIn, removePeerIn, peersOf, mcpUrlOf } from './a2aCore.js'
|
|
3
3
|
import { A2A_PEERS_DOC } from './a2aShared.js'
|
|
4
4
|
import { sealDoc } from './accountSeal.js'
|
|
5
|
+
import { keptDelivery, revokeKeptDrop } from './sdkKeptIntake.js' // its jobs to the cloud device (side sweep: sdk-kept-agent-missing-cloud-delivery)
|
|
5
6
|
|
|
6
7
|
const fail = (code, text) => Object.assign(new Error('witbitz: ' + text), { code })
|
|
7
8
|
const ID = /^[A-Za-z0-9_-]{1,128}$/
|
|
@@ -99,15 +100,29 @@ export function linkKeptAgent(lane, space, { spaceName = space && space.title, l
|
|
|
99
100
|
const cfg = await lane._gateConfig({ fresh: true }); guard()
|
|
100
101
|
if (!cfg || cfg.gated && !cfg.allow) throw fail('unreadable', 'the private assistant’s connections could not be read')
|
|
101
102
|
const connections = Array.isArray(cfg?.connections) ? cfg.connections : []
|
|
102
|
-
|
|
103
|
+
// both peers must still be listed: a peer removed since is no working link, so it is made again (side sweep 2026-11-28: it was reopened)
|
|
104
|
+
const hasPeer = (room, id) => peersOf(w.a2a._s, room).some((p) => p.id === id)
|
|
105
|
+
// a link made before its jobs reached the cloud device (an older SDK) gets its drop address now; one that has it is unchanged
|
|
106
|
+
if (connections.some((c) => c.id === existing.connId) && hasPeer(lane.room, existing.lPeer) && hasPeer(space.room, existing.sPeer)) return { ...publicLink(existing), ...await keptDelivery(w, { space: space.room, sPeer: existing.sPeer }, guard) }
|
|
103
107
|
}
|
|
104
108
|
if (existing) await unlinkKnown(w, lane, space, existing, guard)
|
|
105
109
|
const d = deps(w, lane, space, guard)
|
|
106
110
|
const result = await linkOwnAgent({ lane: lane.room, space: space.room, spaceName: String(spaceName || 'Kept assistant').slice(0, 80), laneName: String(laneName || 'Private assistant').slice(0, 80) }, d)
|
|
107
111
|
guard()
|
|
108
112
|
const link = { lane: lane.room, space: space.room, ...result }
|
|
109
|
-
|
|
110
|
-
|
|
113
|
+
// the completed record refused → the finished link is taken back (side sweep 2026-11-28: both peers, the report destination and
|
|
114
|
+
// the grant stayed installed); if that fails too, the pending record still names it and the next link removes it
|
|
115
|
+
try { await saveLink(w, link, guard) } catch (e) {
|
|
116
|
+
try {
|
|
117
|
+
await unlinkOwnAgent({ lane: lane.room, space: space.room, lPeer: link.lPeer, sPeer: link.sPeer, connId: link.connId }, d)
|
|
118
|
+
if (w._forgetAgentConnection) await w._forgetAgentConnection(link.connId)
|
|
119
|
+
if (w._keptAgentConnections) w._keptAgentConnections.delete(link.connId)
|
|
120
|
+
} catch { /* see above */ }
|
|
121
|
+
throw e
|
|
122
|
+
}
|
|
123
|
+
// ITS JOBS TO THE CLOUD DEVICE (side sweep: sdk-kept-agent-missing-cloud-delivery): the kept Space's peer gets a drop address in the
|
|
124
|
+
// account's message intake. Not done → the link still works as before ('client': its jobs wait at the Sentinel for a client).
|
|
125
|
+
return { ...link, ...await keptDelivery(w, { space: space.room, sPeer: link.sPeer }, guard) }
|
|
111
126
|
})
|
|
112
127
|
}
|
|
113
128
|
|
|
@@ -141,6 +156,7 @@ async function unlinkKnown(w, lane, space, link, guard) {
|
|
|
141
156
|
await unlinkOwnAgent({ lane: lane.room, space: space.room, lPeer: link.lPeer, sPeer: link.sPeer, connId: link.connId }, deps(w, lane, space, guard))
|
|
142
157
|
guard()
|
|
143
158
|
await saveLink(w, { ...publicLink(link), gone: true }, guard)
|
|
159
|
+
await revokeKeptDrop(w, { space: space.room, sPeer: link.sPeer }, guard)
|
|
144
160
|
if (w._forgetAgentConnection) await w._forgetAgentConnection(link.connId)
|
|
145
161
|
if (w._keptAgentConnections) w._keptAgentConnections.delete(link.connId)
|
|
146
162
|
}
|
package/sdkKeptIntake.js
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
// sdkKeptIntake.js — A KEPT ASSISTANT'S JOBS GO TO THE CLOUD DEVICE, AS IN THE APP (side sweep: sdk-kept-agent-missing-cloud-delivery).
|
|
2
|
+
// The cloud device reads an outside agent's message for one of its Spaces only from the account's MESSAGE INTAKE (docs/message-intake.md;
|
|
3
|
+
// cloud-device/worker.mjs collectDrops). The app gives each outside agent a drop address there (intakeProducers.js) and hands the device
|
|
4
|
+
// the message room (cloudDeviceSheet.js `msgroom`). The SDK had neither: its grant kept a drop address only for a peer the Sentinel
|
|
5
|
+
// already held, so the kept Space's peer that lane.linkKept made had none, and its jobs waited at the Sentinel for a client holding
|
|
6
|
+
// the lane's key — the always-on Space answered only while some client was awake.
|
|
7
|
+
//
|
|
8
|
+
// Now, for that ONE peer, the SDK does what the app does, with the app's own pieces:
|
|
9
|
+
// • the account's message room — the one the account index names (`msgsRoom`, accountIndexDoc.js, the pointer the app adopts),
|
|
10
|
+
// else one made like the app's (roomSync.js ensureMsgsRoom) and published there over the version read;
|
|
11
|
+
// • its drop address — roomIntake.js address(): derived from the intake key kept IN the message room, registered with kind 'a2a'
|
|
12
|
+
// and the kept Space as its only target, id 'a2a:<space>:<peer>' (= intakeProducers.js a2aProducerId — the device checks it);
|
|
13
|
+
// • the cloud device is handed the message room FIRST (door.mjs `msgroom`), then the record is pushed naming the intake. A step that
|
|
14
|
+
// fails stops there: nothing is dropped into an intake the device does not read.
|
|
15
|
+
// ONLY the kept Space's peer — and any peer the intake already lists (registered by the account's app devices) — gets an address: the SDK
|
|
16
|
+
// reads no message room, so a private lane's peer keeps the Sentinel's inbox, which its client collects (lane.a2a.collect()).
|
|
17
|
+
import { makeRoomIntake } from './roomIntake.js'
|
|
18
|
+
import { validPointer, indexDoc } from './accountIndexDoc.js'
|
|
19
|
+
import { APP_DOC } from './sdkAccountDoc.js'
|
|
20
|
+
import { sealDoc } from './accountSeal.js'
|
|
21
|
+
|
|
22
|
+
const fail = (code, text) => Object.assign(new Error('witbitz: ' + text), { code })
|
|
23
|
+
/** = intakeProducers.js a2aProducerId — and cloud-device/worker.mjs checks exactly this id. */
|
|
24
|
+
export const keptProducerId = (room, peerId) => `a2a:${room}:${peerId}`
|
|
25
|
+
const MSGS_ROOM = Object.freeze({ agentReplies: false, kind: 'msgs', retention: 'purgeable' }) // roomSync.js ensureMsgsRoom
|
|
26
|
+
|
|
27
|
+
/** The account's message room → { room, mk }: the index's, else made and published (a 409 re-reads and takes the winner's). With
|
|
28
|
+
* `create: false`, null when the index names none. */
|
|
29
|
+
export async function keptMessageRoom(w, guard, { create = true } = {}) {
|
|
30
|
+
const acc = w.account, c = acc._client()
|
|
31
|
+
let made = null
|
|
32
|
+
for (let i = 0; i < 5; i++) {
|
|
33
|
+
const loc = await acc._where(); guard()
|
|
34
|
+
const got = await acc._read(loc, APP_DOC, loc.app); guard()
|
|
35
|
+
if (!got.ok) throw fail('unreadable', 'the account index could not be read')
|
|
36
|
+
const have = validPointer(got.doc && got.doc.msgsRoom)
|
|
37
|
+
if (have) return { room: String(have.room), mk: String(have.mk) }
|
|
38
|
+
if (got.doc && got.doc.msgsRoom && got.doc.msgsRoom.room) throw fail('no_key', 'the account’s message room is named without its key') // never replaced by a second one
|
|
39
|
+
if (!create) return null
|
|
40
|
+
if (!made) { const s = await c.create({ ...MSGS_ROOM }, { base: acc._viewer || undefined }); guard(); made = { room: s.room, mk: s.mk } }
|
|
41
|
+
const doc = { ...(got.doc || indexDoc({ rooms: {}, devices: {}, signouts: {}, name: '' })), msgsRoom: made, at: Date.now() }
|
|
42
|
+
const r = await c.state(loc.room, loc.mk, APP_DOC, await sealDoc(loc.app, doc), 'account index', 'device', got.v); guard()
|
|
43
|
+
if (r && r.status === 409) continue
|
|
44
|
+
if (!r || r.status !== 200) throw fail('save_failed', 'the account’s message room could not be recorded')
|
|
45
|
+
return made
|
|
46
|
+
}
|
|
47
|
+
throw fail('version_conflict', 'the account index kept changing')
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** roomIntake.js over the message room, with this client. The SDK only gives addresses; the cloud device collects. */
|
|
51
|
+
export function keptIntakeOf(w, ptr) {
|
|
52
|
+
const c = w.account._client()
|
|
53
|
+
return makeRoomIntake({
|
|
54
|
+
room: async () => ptr.room, ensureRoom: async () => ptr.room,
|
|
55
|
+
state: (room, name, patch, ifV) => c.state(room, ptr.mk, name, patch, undefined, undefined, ifV),
|
|
56
|
+
intakeReg: (room, ops) => c.intakeReg(room, ptr.mk, ops),
|
|
57
|
+
})
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** Deliver the kept Space's peer `sPeer` to the cloud device. → 'device'; throws the reason (nothing named at the Sentinel then). */
|
|
61
|
+
export async function deliverKeptToDevice(w, { space, sPeer }, guard) {
|
|
62
|
+
if (typeof w.a2a?._pushIntake !== 'function' || typeof w.cloudDevice?._ask !== 'function' || typeof w.account?._client !== 'function') throw fail('not_available', 'this client cannot hand jobs to the cloud device')
|
|
63
|
+
const peer = (w.a2a._s.lanes[space]?.peers || []).find((p) => p.id === sPeer)
|
|
64
|
+
if (!peer) throw fail('not_in_record', 'the kept assistant’s peer is not in this account’s record')
|
|
65
|
+
const ptr = await keptMessageRoom(w, guard)
|
|
66
|
+
const intake = keptIntakeOf(w, ptr)
|
|
67
|
+
await intake.address({ id: keptProducerId(space, sPeer), label: peer.name, kind: 'a2a', target: space }); guard()
|
|
68
|
+
await w.cloudDevice._ask('msgroom', { room: ptr.room, mk: ptr.mk }); guard() // the device reads the room BEFORE anything is dropped there
|
|
69
|
+
await w.a2a._pushIntake(async (rec) => {
|
|
70
|
+
const listed = new Map((await intake.addresses()).map((a) => [a.id, a])) // one read: every address the intake lists (an unreadable one throws)
|
|
71
|
+
const drops = {}
|
|
72
|
+
let base = null
|
|
73
|
+
for (const [room, l] of Object.entries(rec.lanes || {})) for (const p of l.peers || []) {
|
|
74
|
+
const a = listed.get(keptProducerId(room, p.id))
|
|
75
|
+
if (a) { drops[room + '|' + p.id] = a.token; base = a }
|
|
76
|
+
}
|
|
77
|
+
if (!base || !drops[space + '|' + sPeer]) throw fail('not_in_record', 'the kept assistant’s peer left the record')
|
|
78
|
+
return { room: base.room, pub: base.pub, drops }
|
|
79
|
+
})
|
|
80
|
+
guard()
|
|
81
|
+
return 'device'
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** As deliverKeptToDevice, never throwing (an account change aside): → { delivery: 'device' } | { delivery: 'client', deliveryError }.
|
|
85
|
+
* 'client': the link works as before — its jobs wait at the Sentinel until a client collects them. */
|
|
86
|
+
export async function keptDelivery(w, args, guard) {
|
|
87
|
+
try { return { delivery: await deliverKeptToDevice(w, args, guard) } } catch (e) {
|
|
88
|
+
if (e && e.code === 'account_changed') throw e
|
|
89
|
+
return { delivery: 'client', deliveryError: String((e && e.code) || 'failed') }
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** The link is gone: its peer's drop address goes too (best effort — revoking the peer at the Sentinel already stopped it). */
|
|
94
|
+
export async function revokeKeptDrop(w, { space, sPeer }, guard) {
|
|
95
|
+
try {
|
|
96
|
+
if (typeof w.account?._client !== 'function' || !w.account.enabled) return
|
|
97
|
+
const ptr = await keptMessageRoom(w, guard, { create: false })
|
|
98
|
+
if (ptr) await keptIntakeOf(w, ptr).revokeAddress(keptProducerId(space, sPeer))
|
|
99
|
+
} catch { /* the Sentinel already refuses the removed peer's token; a leftover address only lets nothing in */ }
|
|
100
|
+
}
|
package/sdkLaneLink.js
CHANGED
|
@@ -13,7 +13,7 @@
|
|
|
13
13
|
// assistants asking each other stops at the cap. Default 3; `cap: 0` = no lane-to-lane traffic.
|
|
14
14
|
// ⚑ It runs while both lanes are OPEN on this device (the app's driver is "app-open only" too). `link.state` carries the
|
|
15
15
|
// cursors; pass it back as `resume` to pick up an exchange that was in flight when the page closed.
|
|
16
|
-
import { buildFramed, parseFramed, newCorr, askHopFrom, canForward, planForward, DEFAULT_LANE_LINK_CAP } from './laneLinkCore.js'
|
|
16
|
+
import { buildFramed, parseFramed, newCorr, askHopFrom, canForward, planForward, DEFAULT_LANE_LINK_CAP, uniqueLabel } from './laneLinkCore.js'
|
|
17
17
|
|
|
18
18
|
const GUIDANCE =
|
|
19
19
|
'You can ask the member\'s OTHER linked assistants a question with tell_lane. It is ASYNCHRONOUS: tell_lane posts ' +
|
|
@@ -35,14 +35,12 @@ const isAgent = (e) => !!(e && e.self === true)
|
|
|
35
35
|
* the tool's enum and its executor both read THIS list, so the name the model picks can never resolve to another lane
|
|
36
36
|
* (the app's linkedLaneChoices rule). */
|
|
37
37
|
export function peersOf(lane) {
|
|
38
|
-
const
|
|
38
|
+
const used = new Set(), out = []
|
|
39
39
|
for (const link of (lane._laneLinks || [])) {
|
|
40
40
|
if (link._dead) continue
|
|
41
41
|
const side = link._sideOf(lane)
|
|
42
42
|
const base = side.to || DEFAULT_LABEL
|
|
43
|
-
|
|
44
|
-
seen.set(base, n)
|
|
45
|
-
out.push({ label: n === 1 ? base : `${base} (${n})`, link, peer: side.other })
|
|
43
|
+
out.push({ label: uniqueLabel(used, base), link, peer: side.other }) // unique among ALL labels, generated ones too
|
|
46
44
|
}
|
|
47
45
|
return out
|
|
48
46
|
}
|
|
@@ -121,7 +119,7 @@ export class LaneLink {
|
|
|
121
119
|
clearTimeout(this._t)
|
|
122
120
|
for (const [l, sub] of [[this.a, this._subA], [this.b, this._subB]]) {
|
|
123
121
|
const subs = l._subs && l._subs.message
|
|
124
|
-
if (subs) { const i = subs.
|
|
122
|
+
if (subs) { const i = subs.findIndex((x) => x === sub || x._orig === sub); if (i >= 0) subs.splice(i, 1) } // on() keeps its own wrapper (_orig: sub)
|
|
125
123
|
l._laneLinks = (l._laneLinks || []).filter((x) => x !== this)
|
|
126
124
|
}
|
|
127
125
|
}
|
|
@@ -153,6 +151,7 @@ export class LaneLink {
|
|
|
153
151
|
// the corr out of `sent`, and another device with this link open keeps its own `sent` — both carried the same
|
|
154
152
|
// answer back again. The asking lane is the record: a framed reply with this corr in it is a forward done.
|
|
155
153
|
if ((side.other.messages || []).some((e) => { const p = parseFramed(e && e.text); return p && p.kind === 'reply' && p.corr === f.corr })) { this._sent[side.key].push(f.corr); continue }
|
|
154
|
+
if (this._dead) return { forwarded } // unlinked while the pass read or posted (side sweep 2026-11-28): nothing more crosses
|
|
156
155
|
const framed = buildFramed({ from: side.as, fromRoom: lane.room, corr: f.corr, hop: f.hop, cap: this.cap, kind: 'reply', body: f.text })
|
|
157
156
|
if (await postAndWake(side.other, framed, side.as)) { this._sent[side.key].push(f.corr); forwarded++ } else allOk = false
|
|
158
157
|
}
|
package/sdkRekey.js
CHANGED
|
@@ -10,6 +10,7 @@
|
|
|
10
10
|
// against the room's commitment, takes it → 'rekeyed'. No grant → 'removed'; on the list but nothing sealed → 'pending'.
|
|
11
11
|
// One scope per app: a member reached only in another app (or only in the Spaces app) gets 'pending' — "ask for a fresh link".
|
|
12
12
|
import { enroll, resolveHandle } from './inviteEnroll.js'
|
|
13
|
+
import { checkInbox } from './inviteReceive.js' // collect(): the same reading of the inbox as the Spaces app's
|
|
13
14
|
import { genRecipientKey, openBox, commit, combineShares } from './e2ee.js'
|
|
14
15
|
import { tokenApp, tokenClaims } from './accountScope.js'
|
|
15
16
|
import { GATE_DOMAIN } from './emailFork.js'
|
|
@@ -22,6 +23,16 @@ import { memberHash } from './rosterHash.js'
|
|
|
22
23
|
const sdkError = (message, code) => Object.assign(new Error(message), { code })
|
|
23
24
|
|
|
24
25
|
/** The directory scope a sign-in enrols under: 'app:<the app it speaks for>'; '' for a first-party sign-in (the Spaces app's own). */
|
|
26
|
+
|
|
27
|
+
/** collect(): a link a sender put in an invitation is used only when it is an https address of this room with its key (#mk= / #us=). */
|
|
28
|
+
export function inviteLinkFits (link, room) {
|
|
29
|
+
try {
|
|
30
|
+
const u = new URL(String(link))
|
|
31
|
+
if (u.protocol !== 'https:' || u.username || u.password) return false
|
|
32
|
+
if (u.searchParams.get('room') !== String(room)) return false
|
|
33
|
+
return /(^|[#&])(mk|us)=/.test(u.hash)
|
|
34
|
+
} catch { return false }
|
|
35
|
+
}
|
|
25
36
|
export function inviteScope (idToken) {
|
|
26
37
|
const app = tokenApp(tokenClaims(idToken))
|
|
27
38
|
return app == null ? '' : 'app:' + app
|
|
@@ -37,21 +48,52 @@ export class InviteAccount {
|
|
|
37
48
|
this._enrolling = null
|
|
38
49
|
this._waiting = new Set() // Spaces told 'pending' for want of this key (adoptGrant) — woken by restore()
|
|
39
50
|
this.status = this._state ? 'held' : 'none' // 'none' | 'held' | 'enrolled' | 'held_elsewhere' | 'failed'
|
|
40
|
-
|
|
51
|
+
this._leftFrom = null // the account that signed out of this client (_signedOut), until the next sign-in
|
|
52
|
+
hide(this, ['_wb', '_state', '_waiting', '_leftFrom'])
|
|
41
53
|
}
|
|
42
54
|
/** What to persist (it holds a private key — keep it as you keep the session), or null. */
|
|
43
55
|
get state () { const k = this._key(); return k ? { ...k } : null }
|
|
44
56
|
// the state handed in, else the account backup's (a restored device), else none
|
|
57
|
+
// ONLY THE SIGNED-IN ACCOUNT'S KEY (side sweep: sdk-invite-collection-keeps-previous-account): a key that names another account or
|
|
58
|
+
// app is not used — a reused client switched accounts and collect() opened the previous account's invitations.
|
|
45
59
|
_key () {
|
|
46
|
-
if (this._state) return this._state
|
|
60
|
+
if (this._fits(this._state)) return this._state
|
|
47
61
|
const b = this._wb && this._wb.backup && this._wb.backup.invite
|
|
48
|
-
if (validState(b)) { this._state = { ...b }; this.status = 'held' }
|
|
49
|
-
return
|
|
62
|
+
if (validState(b) && this._fits(b) && this._backupIsThisAccounts()) { this._state = { ...b }; this.status = 'held'; return this._state }
|
|
63
|
+
return null
|
|
64
|
+
}
|
|
65
|
+
// THE BACKUP A REUSED CLIENT KEPT IS THE PREVIOUS ACCOUNT'S (side sweep round 2): its key may name nobody, so the backup's owner decides —
|
|
66
|
+
// the account signed in when the client switched away from it (witbitz-sdk.js useSession), else the address its gate was made with
|
|
67
|
+
_backupIsThisAccounts () {
|
|
68
|
+
const wb = this._wb, s = wb && wb._session, st = wb && wb.backup && wb.backup._s
|
|
69
|
+
if (!s || !s.email || !st) return true
|
|
70
|
+
const owner = (wb._siriBackupOwners && wb._siriBackupOwners.get(st)) || st.email
|
|
71
|
+
return !owner || lc(owner) === lc(s.email)
|
|
72
|
+
}
|
|
73
|
+
_fits (k) {
|
|
74
|
+
if (!k) return false
|
|
75
|
+
const s = this._wb && this._wb._session
|
|
76
|
+
if (!s || !s.email) return true // nobody signed in: nothing to tell it apart from
|
|
77
|
+
return (k.email == null || lc(k.email) === lc(s.email)) && (k.scope == null || k.scope === inviteScope(s.idToken))
|
|
78
|
+
}
|
|
79
|
+
// the client's account changed (wb.useSession): a key that names nobody cannot be told apart, so it is not carried into the next one
|
|
80
|
+
_accountChanged () {
|
|
81
|
+
this._leftFrom = null
|
|
82
|
+
if (this._state && this._state.email == null) this._state = null
|
|
83
|
+
this.status = this._key() ? 'held' : 'none'
|
|
84
|
+
}
|
|
85
|
+
// A SWITCH THROUGH SIGN-OUT (side sweep round 5): signed out, nothing tells a key that names nobody apart, so the account that left is
|
|
86
|
+
// remembered and the next sign-in is compared with it — another account is a switch; the same one keeps its key. restore() clears it.
|
|
87
|
+
_signedOut (s) { this._leftFrom = s && s.email ? { email: lc(s.email), scope: inviteScope(s.idToken) } : null }
|
|
88
|
+
_signedIn (s) {
|
|
89
|
+
const was = this._leftFrom
|
|
90
|
+
this._leftFrom = null
|
|
91
|
+
if (was && s && (lc(s.email) !== was.email || inviteScope(s.idToken) !== was.scope)) this._accountChanged()
|
|
50
92
|
}
|
|
51
93
|
/** Hand back a persisted state (also `new Witbitz({ invite })`). */
|
|
52
94
|
restore (state) {
|
|
53
95
|
if (!validState(state)) throw sdkError('witbitz: invite.restore needs a state from wb.invite.state', 'invalid_argument')
|
|
54
|
-
this._state = { ...state }; this.status = 'held'
|
|
96
|
+
this._state = { ...state }; this.status = 'held'; this._leftFrom = null // handed back while signed out: the next account's own
|
|
55
97
|
for (const sp of [...this._waiting]) { this._waiting.delete(sp); try { sp._keyAt = 0; sp._keyMiss = null; sp._kick() } catch { /* */ } } // a Space waiting for a key it could not open tries at once — its grant backoff too (pass 6, K#5: the kicked poll's adoption was refused by it, up to 60 s)
|
|
56
98
|
try { if (typeof this._onRestore === 'function') this._onRestore() } catch { /* the vault's */ }
|
|
57
99
|
return this
|
|
@@ -64,6 +106,31 @@ export class InviteAccount {
|
|
|
64
106
|
this._enrolling = this._enroll().finally(() => { this._enrolling = null })
|
|
65
107
|
return this._enrolling
|
|
66
108
|
}
|
|
109
|
+
/** THE INVITATIONS DELIVERED TO THIS ACCOUNT, for this app (side sweep 2026-11-28: `resendInvite` and a member change's invite drop a
|
|
110
|
+
* sealed invitation in the recipient's inbox, and only the Spaces app read it). Opened with this device's invite key; the inbox
|
|
111
|
+
* keeps every invitation, so each call returns all of them — remember which rooms you already opened. An attested room's invite
|
|
112
|
+
* goes to its native app, never here. → [{ room, link, title, from, at }] (`link` for openSpace) */
|
|
113
|
+
async collect () {
|
|
114
|
+
const wb = this._wb, k = this._key()
|
|
115
|
+
if (wb && wb.vault) throw sdkError('witbitz: in vault mode the vault keeps the invite key', 'vault_unsupported')
|
|
116
|
+
if (!k) throw sdkError('witbitz: no invite key on this device — sign in (it publishes one) or invite.restore(state)', 'no_invite_key')
|
|
117
|
+
const client = wb && wb._client
|
|
118
|
+
if (!client || typeof client.inboxFetch !== 'function') throw sdkError('witbitz: this client cannot read an invite inbox', 'unsupported')
|
|
119
|
+
const out = []
|
|
120
|
+
// a fetch that rejects before any answer is `unreachable` too, as the types say (side sweep: sdk-invite-collection-network-error)
|
|
121
|
+
const n = await checkInbox({ client, inviteKey: k, onInvite: (inv) => {
|
|
122
|
+
if (inv.kind || !inv.room) return false // an attested room's: its native app takes it
|
|
123
|
+
const link = typeof inv.link === 'string' && inv.link ? inv.link : inv.mk ? `https://witbitz.chat/space?room=${encodeURIComponent(inv.room)}#mk=${encodeURIComponent(inv.mk)}${inv.gate ? '&gate=' + encodeURIComponent(inv.gate) : ''}` : ''
|
|
124
|
+
// ANYONE WHO FINDS THE INBOX CAN DROP A BOX (review 11-28): only an https link naming this room and carrying its key is returned,
|
|
125
|
+
// and an invitation cannot date itself into the future; `title` and `from` are the sender's words (untrusted, documented so)
|
|
126
|
+
if (!inviteLinkFits(link, inv.room)) return false
|
|
127
|
+
out.push({ room: String(inv.room), link, title: typeof inv.title === 'string' ? inv.title.slice(0, 200) : '', from: typeof inv.from === 'string' ? inv.from.slice(0, 320) : '', at: Math.min(Number(inv.at) || 0, Date.now()) })
|
|
128
|
+
return true
|
|
129
|
+
} }).catch(() => -1)
|
|
130
|
+
if (n < 0) throw sdkError('witbitz: the invite inbox could not be read', 'unreachable')
|
|
131
|
+
const seen = new Set()
|
|
132
|
+
return out.sort((a, b) => b.at - a.at).filter((x) => !seen.has(x.room) && seen.add(x.room)) // the newest invitation per room
|
|
133
|
+
}
|
|
67
134
|
async _enroll () {
|
|
68
135
|
const wb = this._wb, s = wb && wb._session
|
|
69
136
|
if (!s || !s.idToken || !s.email) return this.status
|