@witbitz/sdk 4.3.0 → 4.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (112) hide show
  1. package/README.md +2 -2
  2. package/a2aCore.js +41 -5
  3. package/accountErase.js +15 -4
  4. package/accountIndexDoc.js +24 -7
  5. package/accountRecord.js +6 -2
  6. package/accountStores.js +21 -5
  7. package/acctV2App.js +111 -12
  8. package/acctV2Client.js +11 -1
  9. package/acctV2UiCore.js +27 -7
  10. package/agentDoorTools.js +28 -0
  11. package/awsKey.js +3 -1
  12. package/backupRecord.js +3 -0
  13. package/chatLock.js +16 -0
  14. package/cloudDevicePins.js +2 -2
  15. package/codeAttachments.js +101 -0
  16. package/codeCache.js +173 -0
  17. package/codeCloud.js +2 -2
  18. package/codeComputers.js +9 -0
  19. package/codeFolders.js +116 -0
  20. package/codeHistory.js +76 -0
  21. package/codeLanguage.js +54 -0
  22. package/codeModes.js +2 -0
  23. package/codeProgress.js +54 -0
  24. package/codeSent.js +109 -0
  25. package/codeSubagents.js +107 -0
  26. package/codeTransport.js +46 -5
  27. package/connections.js +37 -20
  28. package/decrypt.html +69 -9
  29. package/deviceAttest.js +9 -3
  30. package/eraseFile.js +15 -0
  31. package/idb.js +19 -3
  32. package/idbSeal.js +5 -2
  33. package/inviteReceive.js +44 -0
  34. package/inviteSend.js +8 -2
  35. package/jobAgents.js +2 -2
  36. package/keptMerge.js +9 -2
  37. package/l1-worker-src.js +1 -1
  38. package/l1-worker.js +122 -43
  39. package/laneAssociation.js +78 -0
  40. package/laneConfig.js +4 -3
  41. package/laneLinkCore.js +9 -0
  42. package/ledgerView.js +30 -4
  43. package/manifest.json +112 -87
  44. package/memberChange.js +4 -2
  45. package/mirrorBatch.js +47 -0
  46. package/offlineBundle.js +21 -0
  47. package/opRouting.js +10 -0
  48. package/package.json +27 -2
  49. package/pdfOptions.js +13 -0
  50. package/pdfText.js +107 -0
  51. package/pdfjs.mjs +28 -0
  52. package/pdfjs.worker.mjs +28 -0
  53. package/protectedLocal.js +52 -13
  54. package/reactionHolders.js +86 -0
  55. package/removedMessage.js +1 -1
  56. package/roomEmbed.js +111 -0
  57. package/roomIntake.js +324 -0
  58. package/roomName.js +1 -1
  59. package/roomRoster.js +30 -7
  60. package/rosterCount.js +6 -3
  61. package/scheduleNext.js +60 -0
  62. package/sdkA2A.js +200 -42
  63. package/sdkAccount.js +88 -18
  64. package/sdkAccountDoc.js +13 -5
  65. package/sdkAccountSections.js +172 -23
  66. package/sdkAgui.js +33 -6
  67. package/sdkBackup.js +53 -11
  68. package/sdkBackupV2.js +15 -3
  69. package/sdkCloudDevice.js +20 -5
  70. package/sdkComputers.js +695 -65
  71. package/sdkDictation.js +115 -25
  72. package/sdkErase.js +12 -5
  73. package/sdkExports.js +19 -8
  74. package/sdkInvitations.js +4 -2
  75. package/sdkKeptAgent.js +19 -3
  76. package/sdkKeptIntake.js +100 -0
  77. package/sdkLaneLink.js +8 -9
  78. package/sdkPlan.js +4 -2
  79. package/sdkRekey.js +122 -22
  80. package/sdkReport.js +1 -1
  81. package/sdkSafeMedia.js +1 -1
  82. package/sdkSchedules.js +8 -1
  83. package/sdkSpeech.js +32 -2
  84. package/sdkTemporaryRooms.js +124 -0
  85. package/sdkTurn.js +12 -4
  86. package/sdkVault.js +66 -10
  87. package/sentinelRelease.js +1 -0
  88. package/sharedViews.js +34 -4
  89. package/siri.js +140 -9
  90. package/spaceClient.js +112 -17
  91. package/spaceEmailGate.js +2 -2
  92. package/spaceExport.js +50 -5
  93. package/spaceFork.js +15 -7
  94. package/spaceTemplates.js +99 -0
  95. package/speechOut.js +21 -5
  96. package/store.js +134 -27
  97. package/sw-notif-core.js +11 -8
  98. package/tapTrail.js +58 -0
  99. package/turnVerdict.js +1 -0
  100. package/usageReceipts.js +12 -5
  101. package/vault-core.js +568 -126
  102. package/vault-kit.mjs +3 -3
  103. package/vault-screens.js +30 -18
  104. package/vaultAtRest.js +38 -6
  105. package/vaultCoreLock.js +3 -1
  106. package/vaultCorePush.js +58 -7
  107. package/vaultKeep.js +9 -3
  108. package/vaultWorkerHost.js +32 -7
  109. package/witbitz-admin.d.ts +3 -0
  110. package/witbitz-admin.mjs +12 -11
  111. package/witbitz-sdk.d.ts +170 -43
  112. package/witbitz-sdk.js +833 -203
package/sdkRekey.js CHANGED
@@ -10,9 +10,11 @@
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
- import { lc, recipientsFor, membersAfter, unseenHidden, stillOnList, dropsForUsers } from './memberChange.js'
16
+ import { GATE_DOMAIN } from './emailFork.js'
17
+ import { EMAIL, normalizeDomains, lc, recipientsFor, membersAfter, unseenHidden, stillOnList, dropsForUsers } from './memberChange.js'
16
18
  import { ROSTER_DOC } from './roomRoster.js'
17
19
  import { hide } from './sdkRedact.js'
18
20
  import { assertNotKept } from './sdkCloudDevice.js'
@@ -21,6 +23,16 @@ import { memberHash } from './rosterHash.js'
21
23
  const sdkError = (message, code) => Object.assign(new Error(message), { code })
22
24
 
23
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
+ }
24
36
  export function inviteScope (idToken) {
25
37
  const app = tokenApp(tokenClaims(idToken))
26
38
  return app == null ? '' : 'app:' + app
@@ -36,21 +48,52 @@ export class InviteAccount {
36
48
  this._enrolling = null
37
49
  this._waiting = new Set() // Spaces told 'pending' for want of this key (adoptGrant) — woken by restore()
38
50
  this.status = this._state ? 'held' : 'none' // 'none' | 'held' | 'enrolled' | 'held_elsewhere' | 'failed'
39
- hide(this, ['_wb', '_state', '_waiting'])
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'])
40
53
  }
41
54
  /** What to persist (it holds a private key — keep it as you keep the session), or null. */
42
55
  get state () { const k = this._key(); return k ? { ...k } : null }
43
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.
44
59
  _key () {
45
- if (this._state) return this._state
60
+ if (this._fits(this._state)) return this._state
46
61
  const b = this._wb && this._wb.backup && this._wb.backup.invite
47
- if (validState(b)) { this._state = { ...b }; this.status = 'held' }
48
- return this._state
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()
49
92
  }
50
93
  /** Hand back a persisted state (also `new Witbitz({ invite })`). */
51
94
  restore (state) {
52
95
  if (!validState(state)) throw sdkError('witbitz: invite.restore needs a state from wb.invite.state', 'invalid_argument')
53
- 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
54
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)
55
98
  try { if (typeof this._onRestore === 'function') this._onRestore() } catch { /* the vault's */ }
56
99
  return this
@@ -63,6 +106,31 @@ export class InviteAccount {
63
106
  this._enrolling = this._enroll().finally(() => { this._enrolling = null })
64
107
  return this._enrolling
65
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
+ }
66
134
  async _enroll () {
67
135
  const wb = this._wb, s = wb && wb._session
68
136
  if (!s || !s.idToken || !s.email) return this.status
@@ -169,26 +237,27 @@ async function currentMembers (space, cfg) {
169
237
  const onList = await stillOnList(cfg, space.room, Object.values(book.seen || {}).filter((x) => x && x.email && !x.left)).catch(() => null) // the records: a person in by @username is on by the entry they came in by (sync sweep 11-23 #2)
170
238
  const seen = onList ? seen0.filter((e) => onList(e, '')) : seen0
171
239
  const emails = [...new Set([...(Array.isArray(al.emails) ? al.emails : []), ...seen].map(lc))]
172
- return { emails, owners: ((cfg.owners && cfg.owners.emails) || []).map(lc), admins: ((cfg.admins && cfg.admins.emails) || []).map(lc) }
240
+ return { book, emails, owners: ((cfg.owners && cfg.owners.emails) || []).map(lc), admins: ((cfg.admins && cfg.admins.emails) || []).map(lc) }
173
241
  }
174
242
 
175
243
  const epochOf = (cfg) => (Array.isArray(cfg && cfg.keyChain) ? cfg.keyChain.length : 0) // the epoch a config was read at (= the app's rekeyToWant)
176
- async function rekeyNow (space, { members, stay, allowAfter, expectEpoch = null }) {
244
+ async function rekeyNow (space, { members, stay, allowAfter, expectEpoch = null, book }) {
177
245
  const me = lc(space._wb && space._wb._session && space._wb._session.email)
178
246
  const wb = space._wb
179
247
  const scope = inviteScope(wb._session.idToken)
180
248
  if (!wb.invite._key()) await wb.invite.enroll()
181
- const book = await space._client.state(space.room, space._mk, ROSTER_DOC).catch(() => null)
182
- if (!book || (book.status !== undefined && book.status !== 200)) throw sdkError('witbitz: the member list could not be read — nothing changed', 'book_unavailable')
183
249
  const people = Object.values(book.seen || {})
184
250
  const retained = await stillOnList({ keyChain: [{ epoch: expectEpoch }], allow: allowAfter }, space.room, people)
185
- const legacy = people.filter((p) => p && !p.left && p.email && p.entries?.some((e) => typeof e === 'string' && e.startsWith('u:')) && retained(p.email)).map((p) => lc(p.email))
186
- const { recipients, unreachable, pending } = await recipientsFor(space.room, [...stay, ...legacy], wb._client || space._client, { scope, allow: allowAfter, people }) // include observed retained legacy handles, never arbitrary roster emails
251
+ const domains = new Set(normalizeDomains(allowAfter?.domains))
252
+ const joined = people.filter(p => p && !p.left && p.email && retained(p.email) &&
253
+ (domains.has(lc(p.email).split('@')[1]) || p.entries?.some(e => typeof e === 'string' && e.startsWith('u:')))).map(p => lc(p.email))
254
+ const { recipients, unreachable, pending } = await recipientsFor(space.room, [...stay, ...joined], wb._client || space._client, { scope, allow: allowAfter, people }) // include observed retained legacy handles, never arbitrary roster emails
187
255
  if (!recipients.some((x) => x.email === me)) throw sdkError('witbitz: this account has no invite key for this app yet (wb.invite.status: ' + wb.invite.status + ') — restore wb.invite.state from the device that has it', 'no_invite_key')
188
256
  const split = space._split ? { userShare: fragParam(space.shareLink, 'us') } : null
189
257
  if (space._split && !split.userShare) throw sdkError('witbitz: this split Space was not opened from its link — its user half is unknown here', 'invalid_argument')
190
- const r = await space._client.rekey(space.room, space._mk, { ...(members ? { members } : {}), recipients: recipients.map(({ mh, boxPub }) => ({ mh, boxPub })), pending: [...pending, ...unseenHidden(allowAfter, recipients, pending)], by: me, ...(split ? { split } : {}), ...(Number.isInteger(expectEpoch) ? { expectEpoch } : {}) }) // ONE SNAPSHOT (docs/state-machines.md V#5, the SDK's twin K#1): the change was planned at this epoch — a key adopted on the way (the healing client's retry) must not apply it to another
258
+ const r = await space._client.rekey(space.room, space._mk, { ...(members ? { members } : {}), recipients: recipients.map(({ mh, boxPub }) => ({ mh, boxPub })), pending: [...pending, ...unseenHidden(allowAfter, recipients, pending)], by: me, ...(split ? { split } : {}), ...(Number.isInteger(expectEpoch) ? { expectEpoch } : {}) }).catch(() => null) // ONE SNAPSHOT (docs/state-machines.md V#5, the SDK's twin K#1): the change was planned at this epoch — a key adopted on the way (the healing client's retry) must not apply it to another
191
259
  if (!r || r.status !== 200 || !(r.newMk || r.newShare)) { // a split room in a vault: the worker keeps the key and answers only the new share (sweep 10-23 #3; the app's rekeyMembers takes it too)
260
+ if (!r || !r.status || r.status >= 500 || r.status === 200) throw sdkError('The service did not confirm the new key. Refresh this Space to check its current membership before trying again.', 'rekey_unknown')
192
261
  const code = r && r.error === 'stale_epoch' ? 'changed_meanwhile' : (r && r.error) || 'rekey_failed'
193
262
  throw Object.assign(new Error('witbitz: the key was not changed — nothing has changed' + (r && r.reason ? ` (${r.reason})` : '')), { code, status: r && r.status })
194
263
  }
@@ -253,42 +322,73 @@ export async function listAfter (cfg, room, want, { book, tagOf } = {}) {
253
322
  * when nobody's access changes (only who manages it; the key stays). One rule for the SDK's change and the vault's question
254
323
  * (sync sweep 10-26 #3: the vault compared only the shown addresses). `cfg`: the config changeable() read, else it is read. */
255
324
  export async function planMembers (space, admission = {}, cfg = null) {
325
+ if (admission.domains !== undefined && (!Array.isArray(admission.domains) || admission.domains.some(d => typeof d !== 'string' || !GATE_DOMAIN.test(lc(d).replace(/^@/, ''))))) throw sdkError('witbitz: invalid admission domain', 'invalid_argument')
256
326
  if (!cfg) cfg = (await changeable(space, 'changeMembers')).cfg
257
327
  const emails = [...new Set((Array.isArray(admission.emails) ? admission.emails : []).map(lc).filter(Boolean))]
258
328
  if (!emails.length) throw sdkError('witbitz: changeMembers needs admission.emails (the whole list)', 'invalid_argument')
259
329
  // An @username is not an email: the SDK cannot add one (intended.md) — say so instead of reporting it unreachable (sync sweep 2026-11-23)
260
- const handle = emails.find((e) => e.startsWith('@') || !e.includes('@'))
261
- if (handle) throw sdkError(`witbitz: changeMembers takes email addresses only (${handle})`, 'invalid_argument')
330
+ const handle = [...emails, ...(Array.isArray(admission.owners) ? admission.owners : []), ...(Array.isArray(admission.admins) ? admission.admins : [])].find(e => !EMAIL.test(lc(e)))
331
+ if (handle !== undefined) throw sdkError(`witbitz: changeMembers takes email addresses only (${handle})`, 'invalid_argument')
262
332
  const cur = await currentMembers(space, cfg)
263
333
  const want = {
264
334
  emails,
265
335
  ...(Array.isArray(admission.domains) ? { domains: admission.domains } : {}),
266
336
  owners: Array.isArray(admission.owners) ? admission.owners.map(lc) : cur.owners,
267
337
  admins: Array.isArray(admission.admins) ? admission.admins.map(lc) : cur.admins,
268
- shown: admission.advertise === true ? emails : Array.isArray(admission.advertise) ? admission.advertise : ((cfg.allow && cfg.allow.emails) || []).map(lc).filter((e) => emails.includes(e)),
338
+ shown: admission.advertise === true ? emails : admission.advertise === false ? [] : Array.isArray(admission.advertise) ? admission.advertise : ((cfg.allow && cfg.allow.emails) || []).map(lc).filter((e) => emails.includes(e)),
269
339
  }
270
340
  const c = (space._wb && space._wb._client) || space._client
271
341
  const tagOf = async (u) => { const t = typeof c.userTag === 'function' ? await c.userTag(u, space.room).catch(() => null) : null; return t && t.status === 200 ? t.tag : '' }
272
- const m = await listAfter(cfg, space.room, { ...want, known: cur.emails }, { book: () => space._client.state(space.room, space._mk, ROSTER_DOC).catch(() => null), tagOf })
273
- return { emails, cur, want, m, roles: !m.removed.length && sameList(cfg.allow, m.allow) }
342
+ const domains = normalizeDomains(want.domains ?? cfg.allow?.domains)
343
+ const admitted = address => emails.includes(address) || domains.includes(address.split('@')[1])
344
+ for (const role of ['owners', 'admins']) {
345
+ if (Array.isArray(admission[role])) {
346
+ const outside = want[role].find(address => !admitted(address))
347
+ if (outside) throw sdkError('A manager must already be admitted by email or domain: ' + outside, 'invalid_argument')
348
+ } else {
349
+ const retained = []
350
+ for (const address of want[role]) {
351
+ if (admitted(address) || (!cur.emails.includes(address) && cfg.allow?.mh?.includes(await memberHash(address, space.room)))) retained.push(address)
352
+ }
353
+ want[role] = retained
354
+ }
355
+ }
356
+ const m = await listAfter(cfg, space.room, { ...want, known: cur.emails }, { book: () => cur.book, tagOf })
357
+ // ⛔ NOT YOURSELF, SILENTLY (second review, 2026-11-27): a manager the new list does not admit is dropped (545f3a97f, so a role cannot
358
+ // admit anyone) — a manager who leaves THEIR OWN address off the whole list would lose the Space with no word. Refused by name
359
+ // instead: they add it, or leave the Space. Asked of the change itself (`m.removed`), so a manager who stays by a domain, a
360
+ // hidden-member hash or an @username tag is not refused.
361
+ const actor = lc(space._wb?._session?.email)
362
+ if (actor && (cur.owners.includes(actor) || cur.admins.includes(actor)) && (m.removed || []).map(lc).includes(actor)) {
363
+ throw sdkError('witbitz: your own address is not on the new list — add it, or leave the Space instead', 'invalid_argument')
364
+ }
365
+ return { emails, cur, want, m, epoch: epochOf(cfg), actor: lc(space._wb?._session?.email), roles: !m.removed.length && sameList(cfg.allow, m.allow) }
274
366
  }
275
367
 
276
368
  /** space.changeMembers(admission) — `admission`: { emails, domains?, admins?, owners?, advertise? }, the list stated in FULL,
277
369
  * as fork() takes it. → { inPlace:true, epoch, link, removed, added, unreachable } */
278
- export async function changeMembers (space, admission = {}) {
370
+ export async function changeMembers (space, admission = {}, approved = null) {
279
371
  await assertNotKept(space)
280
372
  const { cfg, me } = await changeable(space, 'changeMembers')
281
- const { emails, cur, want, m, roles } = await planMembers(space, admission, cfg)
373
+ const plan = await planMembers(space, admission, cfg)
374
+ const approvalFields = p => {
375
+ const { book, ...cur } = p.cur
376
+ const admissions = Object.values(book?.seen || {}).filter(x => x && !x.left).map(x => JSON.stringify([lc(x.email), x.user || '', [...(x.entries || [])].sort()])).sort()
377
+ return JSON.stringify({ ...p, cur, admissions })
378
+ }
379
+ if (approved && approvalFields(plan) !== approvalFields(approved)) throw sdkError('Space membership changed during confirmation. Review it again.', 'config_changed')
380
+ const { emails, cur, want, m, roles } = plan
282
381
  // A ROLE CHANGE NEEDS NO NEW KEY (the app's decision 4, verifiedMove.js; sweep 10-23 #16): nobody's access changes, so the
283
382
  // room keeps its key and the config changes in place (op 'config'). A server that does not take it yet answers
284
383
  // config_immutable / not_enabled: then the change is made as before, by a re-key.
285
384
  if (roles && typeof space._client.setConfig === 'function') {
286
385
  const r = await space._client.setConfig(space.room, space._mk, { admins: m.admins, owners: m.owners }, space._who ? space._who() : 'An admin').catch(() => null)
287
386
  if (r && r.status === 200) return { inPlace: true, roles: true, epoch: space.epoch, link: space.shareLink, removed: [], added: [], unreachable: [] }
387
+ if (!r || !r.status || r.status >= 500) throw sdkError('The service did not confirm the role change. Refresh the membership list before trying again.', 'config_unknown')
288
388
  if (!(r && (r.error === 'config_immutable' || r.error === 'not_enabled'))) throw Object.assign(new Error('witbitz: the roles were not changed — nothing has changed' + (r && r.reason ? ` (${r.reason})` : '')), { code: (r && r.error) || 'config_failed', status: r && r.status })
289
389
  }
290
390
  const stay = [...new Set([...want.emails, ...want.owners, ...want.admins, me])]
291
- const { epoch, unreachable } = await rekeyNow(space, { members: { allow: m.allow, owners: m.owners, admins: m.admins }, stay, allowAfter: m.allow, expectEpoch: epochOf(cfg) })
391
+ const { epoch, unreachable } = await rekeyNow(space, { members: { allow: m.allow, owners: m.owners, admins: m.admins }, stay, allowAfter: m.allow, expectEpoch: epochOf(cfg), book: cur.book })
292
392
  // added = on neither list before: not an address the room showed or its book knew, and not a hidden address's hash
293
393
  const hidden = new Set(Array.isArray(cfg.allow && cfg.allow.mh) ? cfg.allow.mh : [])
294
394
  const before = new Set(cur.emails)
@@ -302,6 +402,6 @@ export async function rotateKey (space) {
302
402
  const { cfg, me } = await changeable(space, 'rotateKey')
303
403
  const cur = await currentMembers(space, cfg)
304
404
  const stay = [...new Set([...cur.emails, ...cur.owners, ...cur.admins, me])]
305
- const { epoch, unreachable } = await rekeyNow(space, { members: null, stay, allowAfter: cfg.allow || {}, expectEpoch: epochOf(cfg) })
405
+ const { epoch, unreachable } = await rekeyNow(space, { members: null, stay, allowAfter: cfg.allow || {}, expectEpoch: epochOf(cfg), book: cur.book })
306
406
  return { inPlace: true, rotated: true, epoch, link: space.shareLink, unreachable }
307
407
  }
package/sdkReport.js CHANGED
@@ -41,7 +41,7 @@ export function reportBody (space, message, { reason, note = '', context = false
41
41
  const before = []
42
42
  if (context === true) {
43
43
  const list = space.messages || [], at = list.findIndex((m) => m && m.id === message.id)
44
- for (let i = (at < 0 ? list.length : at) - 1; i >= 0 && before.length < CONTEXT; i--) if (isPerson(list[i])) before.unshift(reportEntry(list[i], who(list[i])))
44
+ for (let i = at - 1; i >= 0 && before.length < CONTEXT; i--) if (isPerson(list[i])) before.unshift(reportEntry(list[i], who(list[i])))
45
45
  }
46
46
  return { room: space.room, reason, note: String(note || '').slice(0, 500), entry: reportEntry(message, who(message), { proof: true }), context: before, ...(space._isEnclave() ? { confidential: true } : {}) }
47
47
  }
package/sdkSafeMedia.js CHANGED
@@ -80,7 +80,7 @@ export class SpaceSafeMedia {
80
80
  // a SLEEPING confidential Space reads nothing: wake it and read once more, as the vault does (sweep P2: a lane's refresh,
81
81
  // which reads its Space's, failed until something else woke it)
82
82
  const wb = this._s._wb
83
- if (!cfg && wb && typeof wb._encWake === 'function' && typeof this._s._isEnclave === 'function' && this._s._isEnclave()) {
83
+ if (!cfg && !c.keyless && !c.vault && wb && typeof wb._encWake === 'function' && typeof this._s._isEnclave === 'function' && this._s._isEnclave()) {
84
84
  try { await wb._encWake(this._s.room, { tries: 8 }); cfg = await c.getConfig(this._s.room, this._s._mk) } catch { /* said below */ }
85
85
  }
86
86
  // "sign in" only where it is the reason — a gated room's settings before sign-in; a sleeping enclave or a failed read is not
package/sdkSchedules.js CHANGED
@@ -1,5 +1,7 @@
1
1
  import { SCHEDULES_DOC, ALWAYSON_DOC, alwaysOnNow, jobsOf, withJob, withoutJob, withPaused, summaryOf } from './schedulesDoc.js'
2
+ import { withNextRuns } from './scheduleNext.js'
2
3
 
4
+ const deviceZone = () => { try { return Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC' } catch { return 'UTC' } }
3
5
  const fail = (code, message, status) => Object.assign(new Error('witbitz: ' + message), { code, ...(status ? { status } : {}) })
4
6
 
5
7
  /** The same sealed schedule document edited by the app and executed by the cloud device. */
@@ -10,7 +12,9 @@ export class SpaceSchedules {
10
12
  if (!r || r.status !== 200 || !Number.isInteger(r.v)) throw fail((r && r.error) || 'unreadable', 'the schedule document could not be read', r && r.status)
11
13
  return r
12
14
  }
13
- async list() { const s = this._sp; if (s._wb?.vault) return s._wb.vault._c.roomAccount(s.room, 'schedules', 'list'); return jobsOf(await this._read(SCHEDULES_DOC)) }
15
+ /** Each active daily job carries `next`: when it runs next (ms), by this device's time zone rules — on the night the clocks skip
16
+ * its time, the moment they jump (side sweep daily-schedule-display-omits-spring-gap-run-time). */
17
+ async list() { const s = this._sp; if (s._wb?.vault) return withNextRuns(await s._wb.vault._c.roomAccount(s.room, 'schedules', 'list')); return withNextRuns(jobsOf(await this._read(SCHEDULES_DOC))) }
14
18
  async _edit(fn, needsDevice = false) {
15
19
  const s = this._sp
16
20
  if (needsDevice && !alwaysOnNow(await this._read(ALWAYSON_DOC))) throw fail('not_always_on', 'this Space needs an active cloud device for schedules')
@@ -26,6 +30,9 @@ export class SpaceSchedules {
26
30
  throw fail('version_conflict', 'the schedules kept changing; try again', 409)
27
31
  }
28
32
  async add({ when, text } = {}) {
33
+ // a daily time with no zone is THIS device's zone, as the app saves it (cloudDeviceSheet.js) — UTC would move it an hour on
34
+ // the local clock at the next clock change (side sweep: sdk-daily-schedule-omitted-zone-defaults-to-utc)
35
+ if (when && typeof when.at === 'string' && !when.tz) when = { ...when, tz: deviceZone() }
29
36
  const s = this._sp; if (s._wb?.vault) return s._wb.vault._c.roomAccount(s.room, 'schedules', 'add', { when, text })
30
37
  let id
31
38
  const jobs = await this._edit((jobs) => { const next = withJob(jobs, { when, text, by: this._sp._who() }); id = next.at(-1).id; return next }, true)
package/sdkSpeech.js CHANGED
@@ -14,6 +14,18 @@
14
14
  import { createTtsPlayer } from './speechOut.js'
15
15
 
16
16
  const err = (code, message) => Object.assign(new Error('witbitz: ' + message), { code })
17
+ // WHO PAYS, not which token: a refreshed user token (a later exp) for the same tenant user is the same payer, so its key is
18
+ // kept — each new key spends one of the account's hourly issuances (side sweep). The token is base64url(JSON{v,t,u,exp}) +
19
+ // '.' + signature (control-plane tenantUsers.mjs issueTurnToken); anything else is compared whole, as before.
20
+ export function tokenPayer (token) {
21
+ if (!token) return ''
22
+ try {
23
+ const b = String(token).split('.')[0].replace(/-/g, '+').replace(/_/g, '/')
24
+ const j = JSON.parse(atob(b + '='.repeat((4 - (b.length % 4)) % 4)))
25
+ if (j && typeof j.t === 'string' && typeof j.u === 'string' && j.t && j.u) return 'tu:' + j.t + '|' + j.u
26
+ } catch { /* not that format */ }
27
+ return token
28
+ }
17
29
 
18
30
  export class Speech {
19
31
  constructor (wb, { fetchImpl, AudioImpl, URLImpl, checkKey } = {}) { // checkKey: a test seam — the page's own evidence check (voiceAttest.js) by default
@@ -25,12 +37,17 @@ export class Speech {
25
37
  get playing () { return this._player.playing }
26
38
 
27
39
  /** @private the page's key (op:'tts'): a signed-in session first (the person), else the tenant's user token. */
28
- async _key () {
40
+ async _who () {
29
41
  const wb = this._wb, sess = wb._session
30
42
  const idToken = sess && sess.idToken && !(sess.exp && sess.exp <= Date.now()) ? sess.idToken : ''
31
43
  let userToken = ''
32
44
  try { const t = typeof wb._userToken === 'function' ? await wb._userToken() : wb._userToken; userToken = typeof t === 'string' ? t : '' } catch { userToken = '' }
33
45
  if (!idToken && !userToken && !wb.vault) throw err('sign_in_required', 'speak needs a signed-in user (wb.signIn) or a user token (wb.useUserToken)') // in a vault, the vault's sign-in mints the key
46
+ return { idToken, userToken, payer: tokenPayer(userToken) || sess?.email || '' }
47
+ }
48
+ async _key () {
49
+ const { idToken, userToken } = this._playAuth || await this._who()
50
+ const wb = this._wb
34
51
  const r = await wb._client.tts(idToken, userToken)
35
52
  if (!r || r.status !== 200 || !r.key) {
36
53
  const code = (r && r.error === 'signin_required') ? 'sign_in_required' : (r && r.status === 429) ? 'tts_rate_limited' : 'tts_unavailable'
@@ -42,7 +59,20 @@ export class Speech {
42
59
  /** Read `text` aloud → resolves when it has played. Rejects with `code`: `no_hebrew`, `empty`, `sign_in_required`,
43
60
  * `tts_rate_limited`, `tts_unavailable`, `http_<status>`, `audio` / `play` (the browser would not play it). A new call
44
61
  * stops the one playing. */
62
+ _resetPayer () {
63
+ this._epoch = (this._epoch || 0) + 1
64
+ this._playAuth = null
65
+ this._player.resetKey()
66
+ }
45
67
  async play (text) {
68
+ const seq = this._sequence = (this._sequence || 0) + 1
69
+ const epoch = this._epoch
70
+ this._player.stop() // the reading in progress stops NOW, not after this call's token arrives (side sweep)
71
+ const auth = await this._who()
72
+ if (seq !== this._sequence) return
73
+ if (epoch !== this._epoch) throw err('account_changed', 'the voice payer changed')
74
+ if (this._playAuth && this._playAuth.payer !== auth.payer) this._player.resetKey()
75
+ this._playAuth = auth
46
76
  try { await this._player.play(String(text == null ? '' : text)) } catch (e) {
47
77
  if (e && e.code && !String(e.message || '').startsWith('witbitz:')) e.message = 'witbitz: ' + e.message
48
78
  throw e
@@ -50,5 +80,5 @@ export class Speech {
50
80
  }
51
81
 
52
82
  /** Stop what is playing (its promise resolves). */
53
- stop () { this._player.stop() }
83
+ stop () { this._sequence = (this._sequence || 0) + 1; this._player.stop() }
54
84
  }
@@ -0,0 +1,124 @@
1
+ import { deviceWrapKey } from './vaultAtRest.js'
2
+ import { seal, open } from './deviceSeal.js'
3
+
4
+ const fail = (code, message) => Object.assign(new Error('witbitz: ' + message), { code })
5
+ const pendingScope = wb => JSON.stringify([wb._endpoint, wb._tenant, wb._clientOpts.app || '', wb._session?.email || ''])
6
+ const storagePrefix = scope => 'wb-sdk:temporary:' + encodeURIComponent(scope) + ':'
7
+
8
+ export class TemporaryRooms {
9
+ constructor(wb, persist) {
10
+ this._wb = wb
11
+ this._persist = persist === true
12
+ this._memory = new Map()
13
+ this._generation = 0
14
+ }
15
+
16
+ _scope() {
17
+ if (this._wb.vault) throw fail('vault_unsupported', 'temporary rooms are unavailable in vault mode')
18
+ return pendingScope(this._wb)
19
+ }
20
+
21
+ async _remember(sp, scope, { days, title, onlyIfListed = false } = {}) {
22
+ if (scope !== this._scope()) return
23
+ const generation = this._generation, name = storagePrefix(scope) + sp.room
24
+ const previous = this._memory.get(name) || (await this._records(scope, sp.room)).get(name)
25
+ if (scope !== this._scope() || generation !== this._generation) return
26
+ if (onlyIfListed && !previous) return // a closed handle's new key: never puts back a room the list no longer has
27
+ const record = { ...previous, room: sp.room, link: sp.shareLink, at: previous?.at || Date.now() }
28
+ if (days) record.days = days
29
+ const label = sp.title || title
30
+ if (label) record.title = String(label).slice(0, 200)
31
+ sp._temporaryScope = scope
32
+ this._memory.set(name, record)
33
+ if (!this._persist) return
34
+ try {
35
+ const key = await deviceWrapKey({ name: 'witbitz-sdk-temporary' })
36
+ if (!key) return
37
+ const blob = await seal(key, { scope, ...record })
38
+ if (pendingScope(this._wb) === scope && this._generation === generation && this._memory.get(name) === record) globalThis.localStorage.setItem(name, JSON.stringify(blob))
39
+ } catch { /* still available in this SDK instance */ }
40
+ }
41
+
42
+ async _records(scope, onlyRoom) {
43
+ const prefix = storagePrefix(scope)
44
+ const wanted = onlyRoom ? prefix + onlyRoom : null
45
+ const rows = new Map([...this._memory].filter(([k]) => wanted ? k === wanted : k.startsWith(prefix)))
46
+ if (!this._persist) return rows
47
+ let key, storage
48
+ try {
49
+ storage = globalThis.localStorage
50
+ if (!storage) return rows
51
+ key = await deviceWrapKey({ name: 'witbitz-sdk-temporary' })
52
+ } catch { return rows }
53
+ if (!key) return rows
54
+ const names = wanted ? [wanted] : Array.from({ length: storage.length }, (_, i) => storage.key(i))
55
+ for (const name of names) {
56
+ if (!name?.startsWith(prefix) || rows.has(name)) continue
57
+ try {
58
+ const blob = storage.getItem(name)
59
+ if (!blob) continue
60
+ const row = await open(key, JSON.parse(blob))
61
+ if (row?.scope === scope && row.room?.startsWith('tmp-') && name === prefix + row.room) rows.set(name, row)
62
+ } catch { /* leave unreadable records in place and continue with the others */ }
63
+ }
64
+ return rows
65
+ }
66
+
67
+ async _status(row) {
68
+ if (Date.now() - row.at < (row.days ? row.days * 86_400_000 : 30 * 60_000)) return 'recent'
69
+ try {
70
+ const k = await this._wb._openLink(row.link)
71
+ if (k.room !== row.room) return 'unknown'
72
+ const r = await this._wb._client.pollSealed(k.room, k.mk, '', 0)
73
+ if (r?.status === 410) return 'expired'
74
+ if (r?.status === 200 && !r.changed && !r.entries?.length) return 'unknown'
75
+ return r?.status === 200 ? 'live' : 'unknown'
76
+ } catch { return 'unknown' }
77
+ }
78
+
79
+ _drop(name) {
80
+ this._memory.delete(name)
81
+ if (this._persist) globalThis.localStorage?.removeItem(name)
82
+ }
83
+
84
+ _title(sp) {
85
+ if (sp._temporaryScope !== this._scope()) return
86
+ const row = this._memory.get(storagePrefix(sp._temporaryScope) + sp.room)
87
+ if (row && row.title !== sp.title) this._remember(sp, sp._temporaryScope).catch(() => {})
88
+ }
89
+
90
+ _erase(scope) {
91
+ this._generation++
92
+ const prefix = storagePrefix(scope)
93
+ for (const name of this._memory.keys()) if (name.startsWith(prefix)) this._memory.delete(name)
94
+ let storage
95
+ try { storage = globalThis.localStorage } catch { return }
96
+ if (!storage) return
97
+ for (let i = storage.length - 1; i >= 0; i--) {
98
+ const name = storage.key(i)
99
+ if (name?.startsWith(prefix)) storage.removeItem(name)
100
+ }
101
+ }
102
+
103
+ async list() {
104
+ const scope = this._scope(), rows = await this._records(scope), result = []
105
+ for (const [name, row] of rows) {
106
+ const status = await this._status(row)
107
+ if (scope !== this._scope()) throw fail('account_changed', 'the account changed')
108
+ if (status === 'expired') this._drop(name)
109
+ else result.push({ room: row.room, at: row.at, title: row.title || '', status })
110
+ }
111
+ if (scope !== this._scope()) throw fail('account_changed', 'the account changed')
112
+ return result.sort((a, b) => b.at - a.at)
113
+ }
114
+
115
+ async open(room, options) {
116
+ const scope = this._scope(), name = storagePrefix(scope) + room
117
+ const row = (await this._records(scope, room)).get(name)
118
+ if (!row) throw fail('not_found', 'this device has no such temporary room')
119
+ const status = await this._status(row)
120
+ if (scope !== this._scope()) throw fail('account_changed', 'the account changed')
121
+ if (status === 'expired') { this._drop(name); throw fail('expired', 'this temporary room has expired') }
122
+ return this._wb.openSpace(row.link, options)
123
+ }
124
+ }
package/sdkTurn.js CHANGED
@@ -51,6 +51,8 @@ export class Turn {
51
51
  this._stopKey = randStopKey()
52
52
  this._mark = null // messages.length when the attempt that RAN was posted
53
53
  this._replyText = null // the server's word on the reply, when it gave one
54
+ this._promptId = null // the ledger id of this turn's own message, when the server names it
55
+ this._sent = String(text == null ? '' : text) // this turn's own message, as it lands in the room
54
56
  /** 'running' until it settles; then 'done' | 'silent' | 'failed' | 'aborted' | 'timeout'. */
55
57
  this.status = 'running'
56
58
  /** The reply as it has streamed so far ('' before the first token). */
@@ -84,7 +86,7 @@ export class Turn {
84
86
  this.result = r
85
87
  const v = turnVerdict(r)
86
88
  if (v.kind === 'silent') return this._settle('silent')
87
- if (v.kind === 'ok') { this._replyText = typeof r.reply === 'string' ? r.reply : null; if (this._replyText === '') return this._settle('silent'); return this._look() }
89
+ if (v.kind === 'ok') { this._replyText = typeof r.reply === 'string' ? r.reply : null; this._promptId = typeof r.promptId === 'string' && r.promptId ? r.promptId : null; if (this._replyText === '') return this._settle('silent'); return this._look() }
88
90
  if (r && r.pending) return this._look() // cut at the front door; the reply still comes on the poll
89
91
  // NO ANSWER at all (status 0) settles as failed with its code — it MAY have posted (sdk.md): read the room before resending
90
92
  this._settle('failed', { error: (r && r.error) || v.code || v.kind, reason: (r && r.reason) || v.reason }) // the server's sentence too (sweep 11-04 P3: TurnResult had no reason)
@@ -94,9 +96,15 @@ export class Turn {
94
96
  _look() {
95
97
  if (this.status !== 'running' || this._mark === null) return
96
98
  if (this.result === null) return // the request is still out: a reply that lands now may be a previous turn's
97
- const list = this._space.messages
98
- const after = list.slice(this._mark).filter(isReply)
99
- const m = (this._replyText ? after.find((x) => String(x.text || '') === this._replyText) : null) || after[0]
99
+ const slice = this._space.messages.slice(this._mark)
100
+ const after = slice.filter(isReply)
101
+ // Not the server's exact words → the first reply AFTER this turn's own message: a delayed poll can bring an EARLIER answer in
102
+ // past the mark, and it was taken for this turn's (side sweep 2026-11-28). With the server's words in hand, nothing else is
103
+ // guessed while its own message has not landed; without them (a turn cut at the front door) the first reply, as before.
104
+ // …and its own message by the ledger id the server named (side sweep round 2: an EARLIER message with the same text, brought in
105
+ // by a late poll, was taken for it, and that message's answer for the reply); a server that names none: the first same text
106
+ const own = this._promptId ? slice.findIndex((x) => x && x.id === this._promptId) : slice.findIndex((x) => !isReply(x) && String(x.text || '') === this._sent)
107
+ const m = (this._replyText ? after.find((x) => String(x.text || '') === this._replyText) : null) || (own >= 0 ? slice.slice(own + 1).find(isReply) : this._replyText ? null : after[0])
100
108
  if (m) this._settle(m.stopped ? 'aborted' : 'done', { reply: m })
101
109
  }
102
110