@witbitz/sdk 0.0.0-stage → 4.3.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 (217) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +20 -2
  3. package/a2aCore.js +200 -0
  4. package/a2aShared.js +27 -0
  5. package/accountErase.js +223 -0
  6. package/accountIndexDoc.js +122 -0
  7. package/accountOwner.js +59 -0
  8. package/accountRecord.js +90 -0
  9. package/accountScope.js +114 -0
  10. package/accountSeal.js +42 -0
  11. package/accountStores.js +173 -0
  12. package/acctV2App.js +619 -0
  13. package/acctV2Check.js +29 -0
  14. package/acctV2Client.js +382 -0
  15. package/acctV2Keys.js +43 -0
  16. package/acctV2Legacy.js +14 -0
  17. package/acctV2Switch.js +80 -0
  18. package/acctV2UiCore.js +857 -0
  19. package/acctV2WebAuthn.js +61 -0
  20. package/acctV2Wire.js +59 -0
  21. package/address.js +42 -0
  22. package/attestedBox.js +30 -0
  23. package/attestedRooms.js +78 -0
  24. package/awsKey.js +98 -0
  25. package/backupRecord.js +106 -0
  26. package/backupVault.js +97 -0
  27. package/blocks.js +115 -0
  28. package/blocksPush.js +64 -0
  29. package/browseSeal.js +103 -0
  30. package/cbor.js +225 -0
  31. package/changePush.js +75 -0
  32. package/chatLock.js +149 -0
  33. package/chatLockSw.js +13 -0
  34. package/cloudDeviceBuilds.js +11 -0
  35. package/cloudDevicePins.js +33 -0
  36. package/cloudDeviceSeal.js +53 -0
  37. package/codeBrowse.js +224 -0
  38. package/codeCloud.js +652 -0
  39. package/codeCloudKeys.js +112 -0
  40. package/codeCommands.js +167 -0
  41. package/codeComputers.js +388 -0
  42. package/codeEgress.js +123 -0
  43. package/codeFilesRoutes.js +17 -0
  44. package/codeMkdir.js +8 -0
  45. package/codeModes.js +57 -0
  46. package/codeOrphanKeys.js +42 -0
  47. package/codeOutputs.js +141 -0
  48. package/codeRelay.js +505 -0
  49. package/codeSentinel.js +86 -0
  50. package/codeTransport.js +295 -0
  51. package/codeUndo.js +48 -0
  52. package/compress.js +24 -0
  53. package/config.js +11 -0
  54. package/connCatalog.js +164 -0
  55. package/connDisp.js +76 -0
  56. package/connOtherWays.js +74 -0
  57. package/connPending.js +16 -0
  58. package/connWrap.js +53 -0
  59. package/connectionEntry.js +89 -0
  60. package/connections.js +562 -0
  61. package/credits.js +30 -0
  62. package/csAttest.js +112 -0
  63. package/decrypt.html +384 -0
  64. package/deviceAttest.js +521 -0
  65. package/deviceCall.js +54 -0
  66. package/deviceKeyCore.js +41 -0
  67. package/deviceSeal.js +59 -0
  68. package/e2ee.js +323 -0
  69. package/eat.js +103 -0
  70. package/emailFork.js +275 -0
  71. package/emailSignIn.js +81 -0
  72. package/emptySpaces.js +111 -0
  73. package/encSource.js +55 -0
  74. package/enclaveAccept.js +214 -0
  75. package/enclaveClaim.js +241 -0
  76. package/enclaveRoute.js +102 -0
  77. package/enclaveSnapshotMerge.js +44 -0
  78. package/entrySig.js +165 -0
  79. package/env.js +73 -0
  80. package/eraseFile.js +58 -0
  81. package/followImage.js +86 -0
  82. package/healNames.js +45 -0
  83. package/idb.js +97 -0
  84. package/idbSeal.js +119 -0
  85. package/indexGone.js +12 -0
  86. package/invite.js +51 -0
  87. package/inviteEnroll.js +67 -0
  88. package/inviteSend.js +68 -0
  89. package/jobAgents.js +87 -0
  90. package/keptMerge.js +84 -0
  91. package/l1-worker-src.js +2 -0
  92. package/l1-worker.js +831 -0
  93. package/laneConfig.js +57 -0
  94. package/laneLinkCore.js +177 -0
  95. package/ledgerView.js +64 -0
  96. package/manifest.json +220 -0
  97. package/mcpRecommended.js +25 -0
  98. package/memberChange.js +123 -0
  99. package/mkseal.js +101 -0
  100. package/nativePush.js +153 -0
  101. package/nitroVerify.js +220 -0
  102. package/noble-p256.js +27 -0
  103. package/notice.js +116 -0
  104. package/notifKey.js +58 -0
  105. package/offlineBundle.js +62 -0
  106. package/ohttp.js +177 -0
  107. package/opencodeWire.js +282 -0
  108. package/oprf.js +70 -0
  109. package/ownAgentLink.js +96 -0
  110. package/ownerPolicy.js +117 -0
  111. package/package.json +254 -4
  112. package/pollVerdict.js +33 -0
  113. package/prefetchPoll.js +60 -0
  114. package/protectedLocal.js +410 -0
  115. package/pushCore.js +42 -0
  116. package/recovery.js +107 -0
  117. package/regions.js +42 -0
  118. package/removedMessage.js +11 -0
  119. package/renameRefusal.js +9 -0
  120. package/replyQuote.js +34 -0
  121. package/reqEnvelope.js +126 -0
  122. package/roomDefaultPrefs.js +76 -0
  123. package/roomDelete.js +109 -0
  124. package/roomName.js +177 -0
  125. package/roomPass.js +256 -0
  126. package/roomRoster.js +289 -0
  127. package/roomSettings.js +61 -0
  128. package/roomState.js +58 -0
  129. package/roomStreamClient.js +115 -0
  130. package/rosterCount.js +49 -0
  131. package/rosterHash.js +13 -0
  132. package/rowSchema.js +113 -0
  133. package/safeMedia.js +116 -0
  134. package/safeMediaPins.js +17 -0
  135. package/schedulesDoc.js +78 -0
  136. package/sdkA2A.js +404 -0
  137. package/sdkAccount.js +470 -0
  138. package/sdkAccountDoc.js +81 -0
  139. package/sdkAccountSections.js +223 -0
  140. package/sdkAgui.js +141 -0
  141. package/sdkAttest.js +34 -0
  142. package/sdkBackup.js +480 -0
  143. package/sdkBackupV2.js +630 -0
  144. package/sdkBrowserPrivate.js +28 -0
  145. package/sdkBuilds.js +208 -0
  146. package/sdkCloudDevice.js +215 -0
  147. package/sdkComputers.js +480 -0
  148. package/sdkDictation.js +142 -0
  149. package/sdkErase.js +283 -0
  150. package/sdkExports.js +69 -0
  151. package/sdkInvitations.js +34 -0
  152. package/sdkKeptAgent.js +188 -0
  153. package/sdkLaneLink.js +205 -0
  154. package/sdkPlan.js +94 -0
  155. package/sdkProtect.js +228 -0
  156. package/sdkRedact.js +36 -0
  157. package/sdkRekey.js +307 -0
  158. package/sdkReport.js +68 -0
  159. package/sdkSafeMedia.js +255 -0
  160. package/sdkSchedules.js +39 -0
  161. package/sdkSpeech.js +54 -0
  162. package/sdkTurn.js +117 -0
  163. package/sdkVault.js +124 -0
  164. package/sealShare.js +18 -0
  165. package/sealedNames.js +64 -0
  166. package/sealedReceipt.js +17 -0
  167. package/sentinelRelease.js +154 -0
  168. package/shamir.js +85 -0
  169. package/sharedViews.js +38 -0
  170. package/sheetChrome.js +450 -0
  171. package/siri.js +171 -0
  172. package/spaceClient.js +1418 -0
  173. package/spaceConfig.js +81 -0
  174. package/spaceEmailGate.js +813 -0
  175. package/spaceExport.js +125 -0
  176. package/spaceFork.js +216 -0
  177. package/spaceLock.js +358 -0
  178. package/spacePasskey.js +180 -0
  179. package/speechOut.js +100 -0
  180. package/splitKeyClient.js +90 -0
  181. package/store.js +587 -0
  182. package/streamHint.js +36 -0
  183. package/sttCloud.js +220 -0
  184. package/sttWorklet.js +38 -0
  185. package/sw-notif-core.js +538 -0
  186. package/tempList.js +48 -0
  187. package/tinfoilVerifier.js +78 -0
  188. package/toolBooks.js +31 -0
  189. package/toolRules.js +52 -0
  190. package/turnCerts.js +254 -0
  191. package/turnFeed.js +58 -0
  192. package/turnVerdict.js +36 -0
  193. package/usageReceipts.js +176 -0
  194. package/usageSummary.js +90 -0
  195. package/util.js +181 -0
  196. package/vault-core.js +1958 -0
  197. package/vault-kit.mjs +354 -0
  198. package/vault-screens.js +263 -0
  199. package/vaultAtRest.js +177 -0
  200. package/vaultCoreLock.js +111 -0
  201. package/vaultCorePush.js +140 -0
  202. package/vaultDeviceKey.js +95 -0
  203. package/vaultEnclaveHandoff.js +114 -0
  204. package/vaultKeep.js +281 -0
  205. package/vaultSealedStore.js +77 -0
  206. package/vaultWorkerHost.js +98 -0
  207. package/vcWorker.js +34 -0
  208. package/voiceAttest.js +50 -0
  209. package/voiceCert.js +51 -0
  210. package/witbitz-admin.d.ts +135 -0
  211. package/witbitz-admin.js +529 -0
  212. package/witbitz-admin.mjs +1459 -0
  213. package/witbitz-sdk.d.ts +1106 -0
  214. package/witbitz-sdk.js +3835 -0
  215. package/workerClient.js +16 -0
  216. package/workerLiveness.js +21 -0
  217. package/x509.js +218 -0
package/sdkRekey.js ADDED
@@ -0,0 +1,307 @@
1
+ // sdkRekey.js — A VERIFIED ROOM CHANGES ITS MEMBERS IN PLACE, in a builder's app (https://witbitz.chat/docs/sdk-people.md#members;
2
+ // docs/key-rotation-design.md § (b)). The Spaces app's rule (rekeyMembers.js), with the key held by the Space itself:
3
+ // • wb.invite — the account's INVITE KEY for this app: an ECDH box whose public half is in the directory under the app's own
4
+ // scope ('app:<origin>', the sign-in's app — the server refuses any other app writing it). A member change seals the room's
5
+ // new key to it. The builder keeps `wb.invite.state` as it keeps `wb.a2a.state` (it holds a private key) and hands it back
6
+ // as `new Witbitz({ invite })`; a second device without it never takes over the slot (it would cut the first one off).
7
+ // • space.changeMembers({ emails, … }) / space.rotateKey() — a new key, the config with the old key in its chain, one grant
8
+ // per remaining member (spaceClient.rekey); the same room, link, history and lanes.
9
+ // • a device holding the old key meets `stale_key` → fetches its grant (op 'grant'), opens it with the invite key, checks it
10
+ // against the room's commitment, takes it → 'rekeyed'. No grant → 'removed'; on the list but nothing sealed → 'pending'.
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
+ import { enroll, resolveHandle } from './inviteEnroll.js'
13
+ import { genRecipientKey, openBox, commit, combineShares } from './e2ee.js'
14
+ import { tokenApp, tokenClaims } from './accountScope.js'
15
+ import { lc, recipientsFor, membersAfter, unseenHidden, stillOnList, dropsForUsers } from './memberChange.js'
16
+ import { ROSTER_DOC } from './roomRoster.js'
17
+ import { hide } from './sdkRedact.js'
18
+ import { assertNotKept } from './sdkCloudDevice.js'
19
+ import { memberHash } from './rosterHash.js'
20
+
21
+ const sdkError = (message, code) => Object.assign(new Error(message), { code })
22
+
23
+ /** 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). */
24
+ export function inviteScope (idToken) {
25
+ const app = tokenApp(tokenClaims(idToken))
26
+ return app == null ? '' : 'app:' + app
27
+ }
28
+
29
+ const validState = (s) => !!(s && typeof s === 'object' && s.boxPub && s.boxPriv && typeof s.inbox === 'string' && s.inbox)
30
+
31
+ /** wb.invite — this account's invite key for this app (see the header). */
32
+ export class InviteAccount {
33
+ constructor (wb, { state = null } = {}) {
34
+ this._wb = wb
35
+ this._state = validState(state) ? { ...state } : null
36
+ this._enrolling = null
37
+ this._waiting = new Set() // Spaces told 'pending' for want of this key (adoptGrant) — woken by restore()
38
+ this.status = this._state ? 'held' : 'none' // 'none' | 'held' | 'enrolled' | 'held_elsewhere' | 'failed'
39
+ hide(this, ['_wb', '_state', '_waiting'])
40
+ }
41
+ /** What to persist (it holds a private key — keep it as you keep the session), or null. */
42
+ get state () { const k = this._key(); return k ? { ...k } : null }
43
+ // the state handed in, else the account backup's (a restored device), else none
44
+ _key () {
45
+ if (this._state) return this._state
46
+ 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
49
+ }
50
+ /** Hand back a persisted state (also `new Witbitz({ invite })`). */
51
+ restore (state) {
52
+ if (!validState(state)) throw sdkError('witbitz: invite.restore needs a state from wb.invite.state', 'invalid_argument')
53
+ this._state = { ...state }; this.status = 'held'
54
+ 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
+ try { if (typeof this._onRestore === 'function') this._onRestore() } catch { /* the vault's */ }
56
+ return this
57
+ }
58
+ /** Publish this account's invite key for this app (after signIn / refreshSession — the SDK runs it). Idempotent. A slot that
59
+ * already holds ANOTHER key (another device of this account, without this state) is left as it is: status 'held_elsewhere'
60
+ * — restore that device's state here, or from the account backup. → the status. */
61
+ async enroll () {
62
+ if (this._enrolling) return this._enrolling
63
+ this._enrolling = this._enroll().finally(() => { this._enrolling = null })
64
+ return this._enrolling
65
+ }
66
+ async _enroll () {
67
+ const wb = this._wb, s = wb && wb._session
68
+ if (!s || !s.idToken || !s.email) return this.status
69
+ const client = wb._client
70
+ if (!client || typeof client.dirPut !== 'function' || typeof client.oprf !== 'function') return this.status
71
+ const scope = inviteScope(s.idToken)
72
+ const email = lc(s.email)
73
+ try {
74
+ // NEVER TAKE OVER ANOTHER DEVICE'S SLOT: the box published under this account's handle wins. This device publishes only when
75
+ // the slot is empty or already holds the key this device holds (read AFTER the lookup: a restore may land meanwhile)
76
+ const handle = await resolveHandle(email, client, scope)
77
+ const g = handle ? await client.dirGet(handle, { idToken: s.idToken, ...(scope ? { scope } : {}) }) : null // as its owner: a slot hidden from lookups still answers
78
+ const mine = this._key()
79
+ const usable = mine && (mine.scope == null || mine.scope === scope) && (mine.email == null || lc(mine.email) === email)
80
+ const published = g && g.status === 200 && g.entry && g.entry.boxPub
81
+ const held = usable && published && JSON.stringify(g.entry.boxPub) === JSON.stringify(mine.boxPub)
82
+ if (published && !held) { this.status = 'held_elsewhere'; return this.status }
83
+ if (!g || (g.status !== 200 && g.status !== 404)) throw new Error('directory_unavailable: ' + ((g && (g.error || g.status)) || 'no answer')) // unknown is not empty: never mint over a slot that may exist
84
+ const next = await enroll({ email, idToken: s.idToken, client, genRecipientKey, scope, load: () => (usable ? mine : null), save: () => {} })
85
+ if (next) { this._state = { boxPub: next.boxPub, boxPriv: next.boxPriv, inbox: next.inbox, handle: next.handle, scope, email }; this.status = 'enrolled' }
86
+ try { if (wb.backup && this._state) wb.backup.setInvite(this._state) } catch { /* the backup is best-effort */ }
87
+ } catch (e) { this._error = String((e && e.message) || e); this.status = this._state ? 'held' : 'failed' }
88
+ return this.status
89
+ }
90
+ }
91
+
92
+ // THE LINK FOLLOWS THE KEY: `#mk=` (or a split room's `#us=…&spc=…`) is replaced; every other mark (gate, tier) stays.
93
+ export function relink (link, { mk = null, userShare = null, commit: spc = null } = {}) {
94
+ const s = String(link || '')
95
+ const i = s.indexOf('#')
96
+ if (i < 0) return s
97
+ const keep = s.slice(i + 1).split('&').filter((p) => p && !/^(mk|s|us|spc)=/.test(p))
98
+ const key = userShare ? ['us=' + encodeURIComponent(userShare), ...(spc ? ['spc=' + encodeURIComponent(spc)] : [])] : mk ? ['mk=' + mk] : []
99
+ return s.slice(0, i) + '#' + [...key, ...keep].join('&')
100
+ }
101
+ const fragParam = (link, k) => { const m = new RegExp('[#&]' + k + '=([^&]*)').exec(String(link)); return m ? decodeURIComponent(m[1]) : '' }
102
+
103
+ // ON THE LIST, BUT NO KEY THIS DEVICE CAN TAKE: 'pending' once per reason (the poll slows meanwhile) — send this member the link again
104
+ function waiting (space, reason) {
105
+ const was = space._keyWait
106
+ space._keyWait = reason
107
+ try { if (space._wb && space._wb.invite) space._wb.invite._waiting.add(space) } catch { /* */ }
108
+ if (was !== reason) space._emit('pending', { room: space.room, reason })
109
+ return null
110
+ }
111
+
112
+ /** The answer to op 'grant', opened with this account's invite key and checked against the room's commitment — one reading for a
113
+ * Space (below) and a vault (vault-core.js, whose worker holds the key). → { mk, epoch } | { userShare, commit, epoch } (a split
114
+ * room's new user half) | { removed:true } | { wait: reason } */
115
+ export async function openGrant (r, room, invite, { gated: markGated = true } = {}) {
116
+ const gated = (r && r.gated === true) || markGated // the server says so (spaceRoom op grant, only ever true); else the link's mark
117
+ // A LINK SPACE (not email-gated) changed in place seals its key to its members' SIGNING keys, which only the Spaces app holds
118
+ // (rekeyMembers linkProof) — an account has no grant there, so "no grant" is not "removed": ask for the link again
119
+ // (sweep 10-23 #17: the SDK and the vault said 'removed', or waited for ever)
120
+ if (!gated && (!r || r.status === 404 || r.status === 401)) return { wait: 'link_changed' }
121
+ // a VERIFIED room answering 401: the sign-in lapsed — say so (the app asks for one, rekeyMembers.js signInNeeded); it was a silent
122
+ // 'grant_unavailable' (sync sweep 2026-11-14 #6)
123
+ if (gated && r && r.status === 401) return { wait: 'sign_in_required' }
124
+ if (!r || r.status !== 200 || !r.grant) return r && r.status === 404 ? { removed: true } : { wait: 'grant_unavailable' }
125
+ if (r.grant === 'pending') return { wait: 'pending' }
126
+ if (!invite || !invite.boxPriv) return { wait: 'no_invite_key' }
127
+ let g = null
128
+ try { g = JSON.parse(await openBox(JSON.parse(r.grant), invite.boxPriv)) } catch { g = null }
129
+ if (!g || g.room !== room) return { wait: 'grant_unopenable' }
130
+ const epoch = Number(r.epoch) || Number(g.epoch) || 0
131
+ if (g.kind === 'room-split-key' && typeof g.userShare === 'string' && g.userShare && g.commit === r.commit) return { userShare: g.userShare, commit: g.commit, epoch }
132
+ if (g.kind !== 'room-key' || typeof g.mk !== 'string' || (await commit(g.mk)) !== r.commit) return { wait: 'grant_not_current' }
133
+ return { mk: g.mk, epoch }
134
+ }
135
+
136
+ /** This Space met its room's new key: fetch the grant sealed to this account, open it, take it. → { mk } | null (and 'removed' /
137
+ * 'pending' is emitted). */
138
+ export async function adoptGrant (space) {
139
+ const wb = space._wb
140
+ const r = await space._client.grant(space.room).catch(() => null)
141
+ const o = await openGrant(r, space.room, wb && wb.invite && wb.invite._key(), { gated: !!space._gated })
142
+ if (o.removed) { if (space._keyWait !== 'removed') { space._keyWait = 'removed'; space._emit('removed', { room: space.room }) } return null }
143
+ if (o.wait) return o.wait === 'grant_unavailable' ? null : waiting(space, o.wait)
144
+ if (o.userShare) {
145
+ // a split room: the grant is the new USER half; the app's half did not change — mk ⊕ old user half
146
+ const oldShare = fragParam(space.shareLink, 'us')
147
+ const app = oldShare && space._mk ? combineShares(space._mk, oldShare) : null
148
+ const mk = app ? combineShares(o.userShare, app) : null
149
+ if (!mk || (await commit(mk)) !== o.commit) return waiting(space, 'split_unpaired')
150
+ space._setKey(mk, o.epoch, { userShare: o.userShare, commit: o.commit })
151
+ return { mk }
152
+ }
153
+ space._setKey(o.mk, o.epoch)
154
+ return { mk: o.mk }
155
+ }
156
+
157
+ // Who the room has now: the advertised addresses, and the members whose email the guest book shows (a hidden address is only
158
+ // its hash in the config — the book is where a removed hidden member can still be named)
159
+ async function currentMembers (space, cfg) {
160
+ const al = (cfg && cfg.allow) || {}
161
+ // ⛔ A FAILED READ IS NOT AN EMPTY BOOK (state machines pass 7, F#6; the app's V#6): read as "nobody has joined", a member the
162
+ // book alone names (a hidden address, a domain, an @username) fell out of the list — a change removed them with no word, and
163
+ // rotateKey left them out of the new key while it reported success. The read failing fails the call; nothing changes.
164
+ const book = await space._client.state(space.room, space._mk, ROSTER_DOC).catch(() => null)
165
+ if (!book || (book.status !== undefined && book.status !== 200)) throw sdkError('witbitz: who has joined this Space could not be read — nothing has changed; try again', 'book_unavailable')
166
+ const seen0 = Object.values(book.seen || {}).filter((x) => x && !x.left).map((x) => x.email).filter((e) => typeof e === 'string' && e)
167
+ // a room changed in place keeps its guest book — those already removed are still in it; only the people on the list count
168
+ // (the app's rule, memberChange.stillOnList; sweep 10-23 #5: the SDK gave them the new key back)
169
+ 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
+ const seen = onList ? seen0.filter((e) => onList(e, '')) : seen0
171
+ 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) }
173
+ }
174
+
175
+ 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 }) {
177
+ const me = lc(space._wb && space._wb._session && space._wb._session.email)
178
+ const wb = space._wb
179
+ const scope = inviteScope(wb._session.idToken)
180
+ 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
+ const people = Object.values(book.seen || {})
184
+ 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
187
+ 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
+ const split = space._split ? { userShare: fragParam(space.shareLink, 'us') } : null
189
+ 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
191
+ 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)
192
+ const code = r && r.error === 'stale_epoch' ? 'changed_meanwhile' : (r && r.error) || 'rekey_failed'
193
+ 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
+ }
195
+ space._setKey(r.newMk || null, r.epoch, r.newShare ? { userShare: r.newShare, commit: r.newCommit } : null)
196
+ return { epoch: r.epoch, unreachable: unreachable.filter((e) => e !== me) }
197
+ }
198
+
199
+ /** May this session change this Space (`what`: 'changeMembers' | 'rotateKey')? Throws the refusal; → { cfg, me }. Exported so a
200
+ * vault checks BEFORE it asks the person (sweep 10-23 #21). */
201
+ export async function changeable (space, what) {
202
+ const wb = space._wb
203
+ if (!wb || !wb._session || !wb._session.email) throw sdkError(`witbitz: ${what} needs a signed-in session (wb.signIn)`, 'sign_in_required')
204
+ if (typeof space._client.rekey !== 'function' || typeof space._client.grant !== 'function') throw sdkError(`witbitz: ${what} is not available on this client`, 'not_supported')
205
+ const read = () => space._client.getConfig(space.room, space._mk).catch(() => null)
206
+ let cfg = await read()
207
+ // A SLEEPING CONFIDENTIAL SPACE (sweep 10-24 #3): a config read does not wake its enclave, so it fails — wake it, read again
208
+ if (!cfg && wb._enc && wb._enc.rooms && wb._enc.rooms.has(space.room) && typeof wb._encWake === 'function') {
209
+ try { await wb._encWake(space.room, { tries: 8 }) } catch { /* the read below says it */ }
210
+ cfg = await read()
211
+ }
212
+ if (!cfg) throw sdkError(`witbitz: couldn’t read this Space’s members — try ${what} again shortly`, 'config_unavailable')
213
+ if (cfg.admission !== 'email') throw sdkError(`witbitz: only an email-gated Space changes ${what === 'rotateKey' ? 'its key' : 'its members'}`, 'invalid_argument')
214
+ const me = lc(wb._session.email)
215
+ const owners = ((cfg.owners && cfg.owners.emails) || []).map(lc), admins = ((cfg.admins && cfg.admins.emails) || []).map(lc)
216
+ if (!owners.length && !admins.length) throw sdkError('witbitz: this Space has no owners or admins — only the Spaces app can change it (its creator)', 'not_admin')
217
+ if (!owners.includes(me) && !admins.includes(me)) throw sdkError('witbitz: only an owner or an admin changes this Space', 'not_admin')
218
+ return { cfg, me }
219
+ }
220
+
221
+ // the same people on the list (emails, hashes, domains, advertised usernames) — whatever the order
222
+ const sameList = (a, b) => { const k = (x) => JSON.stringify(['emails', 'mh', 'domains'].map((f) => [...((x && Array.isArray(x[f])) ? x[f] : [])].map(String).sort()).concat([((x && Array.isArray(x.users)) ? x.users : []).map((u) => String(u && u.handle)).sort()])); return k(a) === k(b) }
223
+ /** THE LIST A CHANGE ENDS WITH, in the config's own shape (the app's rule, rekeyMembers + memberChange; sweep 10-23 #6):
224
+ * membersAfter's list; someone removed who is also on it by @username loses exactly those entries — the ones the server
225
+ * recorded at their sign-in (roster_seen `entries`) and their tag; every other hashed entry stays (replacing `mh` with the
226
+ * stated emails' hashes dropped every member added by @username); a NEW hidden member (stated, not shown) is admitted by
227
+ * its hash. `book()` → the guest book read ({ seen }); `tagOf(username)` → its tag for this room. */
228
+ export async function listAfter (cfg, room, want, { book, tagOf } = {}) {
229
+ // A tag-only member's email is visible in the guest book, but is not part of the SDK's email-list contract.
230
+ // Keep them unless the caller can actually name their admission entry; do not silently drop their tag.
231
+ const al = cfg.allow || {}, hashes = new Set(al.mh || [])
232
+ const known = []
233
+ for (const e of want.known || []) {
234
+ if ((al.emails || []).map(lc).includes(lc(e)) || hashes.has(await memberHash(lc(e), room))) known.push(e)
235
+ }
236
+ want = { ...want, known }
237
+ let m = await membersAfter(cfg, want, room)
238
+ if (m.removed.length) {
239
+ const b = typeof book === 'function' ? await book() : null
240
+ const gone = new Set(m.removed.map(lc)), recs = Object.values((b && b.seen) || {}).filter((x) => x && gone.has(lc(x.email)))
241
+ const drop = await dropsForUsers(room, recs.map((x) => x.user).filter(Boolean), { tagOf })
242
+ for (const x of recs) for (const k of (Array.isArray(x.entries) ? x.entries : [])) if (typeof k === 'string' && k.startsWith('mh:')) drop.mh.push(k.slice(3))
243
+ m = await membersAfter(cfg, { ...want, drop }, room)
244
+ }
245
+ const shownSet = new Set((m.allow.emails || []).map(lc))
246
+ const newHidden = await Promise.all([...new Set([...(want.emails || []), ...(want.owners || []), ...(want.admins || [])].map(lc))].filter((e) => !shownSet.has(e)).map((e) => memberHash(e, room)))
247
+ const mh = [...new Set([...(Array.isArray(m.allow.mh) ? m.allow.mh : []), ...newHidden])]
248
+ if (mh.length) m.allow.mh = mh; else delete m.allow.mh
249
+ return m
250
+ }
251
+
252
+ /** WHAT changeMembers(admission) WILL DO, before it does it: the list after (listAfter — hidden members counted) and `roles`, true
253
+ * 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
+ * (sync sweep 10-26 #3: the vault compared only the shown addresses). `cfg`: the config changeable() read, else it is read. */
255
+ export async function planMembers (space, admission = {}, cfg = null) {
256
+ if (!cfg) cfg = (await changeable(space, 'changeMembers')).cfg
257
+ const emails = [...new Set((Array.isArray(admission.emails) ? admission.emails : []).map(lc).filter(Boolean))]
258
+ if (!emails.length) throw sdkError('witbitz: changeMembers needs admission.emails (the whole list)', 'invalid_argument')
259
+ // 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')
262
+ const cur = await currentMembers(space, cfg)
263
+ const want = {
264
+ emails,
265
+ ...(Array.isArray(admission.domains) ? { domains: admission.domains } : {}),
266
+ owners: Array.isArray(admission.owners) ? admission.owners.map(lc) : cur.owners,
267
+ 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)),
269
+ }
270
+ const c = (space._wb && space._wb._client) || space._client
271
+ 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) }
274
+ }
275
+
276
+ /** space.changeMembers(admission) — `admission`: { emails, domains?, admins?, owners?, advertise? }, the list stated in FULL,
277
+ * as fork() takes it. → { inPlace:true, epoch, link, removed, added, unreachable } */
278
+ export async function changeMembers (space, admission = {}) {
279
+ await assertNotKept(space)
280
+ const { cfg, me } = await changeable(space, 'changeMembers')
281
+ const { emails, cur, want, m, roles } = await planMembers(space, admission, cfg)
282
+ // 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
+ // room keeps its key and the config changes in place (op 'config'). A server that does not take it yet answers
284
+ // config_immutable / not_enabled: then the change is made as before, by a re-key.
285
+ if (roles && typeof space._client.setConfig === 'function') {
286
+ 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
+ if (r && r.status === 200) return { inPlace: true, roles: true, epoch: space.epoch, link: space.shareLink, removed: [], added: [], unreachable: [] }
288
+ 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
+ }
290
+ 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) })
292
+ // added = on neither list before: not an address the room showed or its book knew, and not a hidden address's hash
293
+ const hidden = new Set(Array.isArray(cfg.allow && cfg.allow.mh) ? cfg.allow.mh : [])
294
+ const before = new Set(cur.emails)
295
+ const added = []
296
+ for (const e of emails) if (!before.has(e) && !hidden.has(await memberHash(e, space.room))) added.push(e)
297
+ return { inPlace: true, epoch, link: space.shareLink, removed: m.removed, added, unreachable }
298
+ }
299
+
300
+ /** space.rotateKey() — the same members, a new key (a lost phone, a link sent to the wrong place). → { inPlace:true, rotated:true, epoch, link, unreachable } */
301
+ export async function rotateKey (space) {
302
+ const { cfg, me } = await changeable(space, 'rotateKey')
303
+ const cur = await currentMembers(space, cfg)
304
+ 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) })
306
+ return { inPlace: true, rotated: true, epoch, link: space.shareLink, unreachable }
307
+ }
package/sdkReport.js ADDED
@@ -0,0 +1,68 @@
1
+ // sdkReport.js — `space.report(message, { reason, note, context })`: REPORT from a builder's page (App Store rule 1.2;
2
+ // docs/report-and-block.md §3; sync sweep 2026-11-13 "not in the SDK, not decided"). The same report the Spaces app files
3
+ // (reportActions.js, whose body is built from the drawn rows — this one from the SDK's messages): what the member chose to show
4
+ // Witbitz — the message, and only if asked the 5 before it — sent in the clear to the front (op `report`, agent/reportOp.mjs),
5
+ // which stores it and mails the reports address. Signed in (who reported), and a MEMBER: a token only the room's current key gets
6
+ // (op membertoken) is fetched first, as the app does.
7
+
8
+ /** The reasons the server takes (agent/reportOp.mjs REASONS — sdkAppParityMore.test holds them equal). */
9
+ export const REPORT_REASONS = Object.freeze(['harassment', 'threats', 'sexual', 'hate', 'spam', 'other'])
10
+ const CONTEXT = 5
11
+ const fail = (code, message) => Object.assign(new Error('witbitz: ' + message), { code })
12
+ const isPerson = (m) => m && typeof m === 'object' && !m.sys && m.kind !== 'data' && m.kind !== 'fork' && m.kind !== 'title'
13
+
14
+ /** One message as the report names it: what it said, and who the room says wrote it (`who`: the Block identity — the verified
15
+ * email / @username and the key that signed it; none for the assistant or an outside agent's relayed line). */
16
+ export function reportEntry (m, who, { proof = false } = {}) {
17
+ const files = [...(Array.isArray(m.images) ? m.images : []), ...(Array.isArray(m.files) ? m.files : [])].map((a) => String((a && a.name) || '')).filter(Boolean).slice(0, 10)
18
+ return {
19
+ name: String(m.from || m.name || '').slice(0, 80), text: String(m.text || '').slice(0, 8000), ...(files.length ? { files } : {}), agent: m.self === true,
20
+ ...(who && who.email ? { email: who.email } : {}), ...(who && who.user ? { user: who.user, verified: true } : {}), ...(who && who.sid ? { kid: who.sid } : {}),
21
+ ...(m.ts != null ? { ts: m.ts } : {}), ...(m.id != null ? { id: String(m.id) } : {}),
22
+ // FRANKING (docs/report-and-block.md §2; sync sweep 11-16 #5): the reported message's sealed record and the RAW text it was made
23
+ // over — with them Witbitz can prove the report and act on it, as from the app (reportActions.js). The context carries none.
24
+ ...(proof && typeof m.fr === 'string' ? { fr: m.fr, raw: String(m.text || '') } : {}),
25
+ ...(proof && (m.source === 'shared' || (m.carried && typeof m.carried === 'object')) ? { copied: true } : {}), // #10: a copy from another Space
26
+ }
27
+ }
28
+
29
+ /** The report's body → { room, reason, note, entry, context, confidential? }; throws invalid_argument. */
30
+ /** A mirrored copy in a lane → { room, id, fr } of the Space's original; anything else → null (reportActions.js laneOriginal's rule). */
31
+ export function laneOriginal (m) {
32
+ if (!m || typeof m.fr !== 'string' || typeof m.frRoom !== 'string' || !m.frRoom) return null
33
+ const id = String(m.id == null ? '' : m.id)
34
+ return id.startsWith('sh:') && id.length > 3 ? { room: m.frRoom, id: id.slice(3), fr: m.fr } : null
35
+ }
36
+
37
+ export function reportBody (space, message, { reason, note = '', context = false } = {}) {
38
+ if (!message || typeof message !== 'object' || message.id == null) throw fail('invalid_argument', 'report(message, { reason }) takes a Message (from "message" or space.messages)')
39
+ if (!REPORT_REASONS.includes(reason)) throw fail('invalid_argument', 'reason is one of ' + REPORT_REASONS.join(', '))
40
+ const who = (m) => (m.self === true ? null : space.blockIdentity(m))
41
+ const before = []
42
+ if (context === true) {
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])))
45
+ }
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
+ }
48
+
49
+ /** The whole report: sign-in, member token, the report → { ok: true, id } | { ok: false, error, detail? } (refusals are answers). */
50
+ export async function fileReport (space, message, opts = {}) {
51
+ // A LANE COPY of its Space's message (the app's reportActions.js laneOriginal; sync sweep 11-19 P1): the record is the Space's, so
52
+ // the report names the Space and the original's id, and the member token is the Space's — not the lane's
53
+ const orig = laneOriginal(message)
54
+ if (orig && space && space._sharedSpace && space._sharedSpace.room === orig.room) { const { source: _s, carried: _c, frRoom: _r, ...m } = message; return fileReport(space._sharedSpace, { ...m, id: orig.id, fr: orig.fr }, opts) } // the original, not a copy (no `copied`)
55
+ const c = space._client
56
+ if (c && c.vault) throw fail('vault_unsupported', 'a report from a vault is not available yet — the vault holds the sign-in and the room key')
57
+ const body = reportBody(space, message, opts)
58
+ const wb = space._wb
59
+ if (!wb || typeof wb._auth !== 'function') throw fail('sign_in_required', 'sign in first — a report names who sent it')
60
+ const { idToken } = wb._auth('a report belongs')
61
+ if (!c || typeof c.memberToken !== 'function' || typeof c.report !== 'function') throw fail('unavailable', 'this Space cannot file a report here')
62
+ const mt = await Promise.resolve().then(() => c.memberToken(space.room, space._mk)).catch(() => null)
63
+ if (!mt || mt.status !== 200 || !mt.token) return { ok: false, error: 'not_member', detail: 'only a member of this Space can report from it — or email reports@witbitz.chat' }
64
+ let r
65
+ try { r = await c.report(idToken, body, mt.token) } catch (e) { return { ok: false, error: String((e && e.code) || 'unavailable'), detail: 'the report was not sent — try again, or email reports@witbitz.chat' } }
66
+ if (r && r.ok === true) return { ok: true, id: String(r.id || ''), proven: r.proven === true } // proven: Witbitz's record matched (#5)
67
+ return { ok: false, error: String((r && r.error) || 'failed'), ...(r && r.reason ? { detail: String(r.reason) } : {}) }
68
+ }