@witbitz/sdk 0.0.0-stage → 4.4.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 (236) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +20 -2
  3. package/a2aCore.js +221 -0
  4. package/a2aShared.js +27 -0
  5. package/accountErase.js +228 -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/agentDoorTools.js +28 -0
  23. package/attestedBox.js +30 -0
  24. package/attestedRooms.js +78 -0
  25. package/awsKey.js +98 -0
  26. package/backupRecord.js +106 -0
  27. package/backupVault.js +97 -0
  28. package/blocks.js +115 -0
  29. package/blocksPush.js +64 -0
  30. package/browseSeal.js +103 -0
  31. package/cbor.js +225 -0
  32. package/changePush.js +75 -0
  33. package/chatLock.js +165 -0
  34. package/chatLockSw.js +13 -0
  35. package/cloudDeviceBuilds.js +11 -0
  36. package/cloudDevicePins.js +33 -0
  37. package/cloudDeviceSeal.js +53 -0
  38. package/codeAttachments.js +100 -0
  39. package/codeBrowse.js +224 -0
  40. package/codeCache.js +149 -0
  41. package/codeCloud.js +650 -0
  42. package/codeCloudKeys.js +112 -0
  43. package/codeCommands.js +167 -0
  44. package/codeComputers.js +389 -0
  45. package/codeEgress.js +123 -0
  46. package/codeFilesRoutes.js +17 -0
  47. package/codeFolders.js +116 -0
  48. package/codeHistory.js +76 -0
  49. package/codeLanguage.js +54 -0
  50. package/codeMkdir.js +8 -0
  51. package/codeModes.js +59 -0
  52. package/codeOrphanKeys.js +42 -0
  53. package/codeOutputs.js +141 -0
  54. package/codeProgress.js +54 -0
  55. package/codeRelay.js +505 -0
  56. package/codeSent.js +68 -0
  57. package/codeSentinel.js +86 -0
  58. package/codeSubagents.js +107 -0
  59. package/codeTransport.js +317 -0
  60. package/codeUndo.js +48 -0
  61. package/compress.js +24 -0
  62. package/config.js +11 -0
  63. package/connCatalog.js +164 -0
  64. package/connDisp.js +76 -0
  65. package/connOtherWays.js +74 -0
  66. package/connPending.js +16 -0
  67. package/connWrap.js +53 -0
  68. package/connectionEntry.js +89 -0
  69. package/connections.js +561 -0
  70. package/credits.js +30 -0
  71. package/csAttest.js +112 -0
  72. package/decrypt.html +384 -0
  73. package/deviceAttest.js +527 -0
  74. package/deviceCall.js +54 -0
  75. package/deviceKeyCore.js +41 -0
  76. package/deviceSeal.js +59 -0
  77. package/e2ee.js +323 -0
  78. package/eat.js +103 -0
  79. package/emailFork.js +275 -0
  80. package/emailSignIn.js +81 -0
  81. package/emptySpaces.js +111 -0
  82. package/encSource.js +55 -0
  83. package/enclaveAccept.js +214 -0
  84. package/enclaveClaim.js +241 -0
  85. package/enclaveRoute.js +102 -0
  86. package/enclaveSnapshotMerge.js +44 -0
  87. package/entrySig.js +165 -0
  88. package/env.js +73 -0
  89. package/eraseFile.js +58 -0
  90. package/followImage.js +86 -0
  91. package/healNames.js +45 -0
  92. package/idb.js +113 -0
  93. package/idbSeal.js +119 -0
  94. package/indexGone.js +12 -0
  95. package/invite.js +51 -0
  96. package/inviteEnroll.js +67 -0
  97. package/inviteSend.js +68 -0
  98. package/jobAgents.js +87 -0
  99. package/keptMerge.js +91 -0
  100. package/l1-worker-src.js +2 -0
  101. package/l1-worker.js +894 -0
  102. package/laneAssociation.js +68 -0
  103. package/laneConfig.js +58 -0
  104. package/laneLinkCore.js +177 -0
  105. package/ledgerView.js +64 -0
  106. package/manifest.json +239 -0
  107. package/mcpRecommended.js +25 -0
  108. package/memberChange.js +125 -0
  109. package/mirrorBatch.js +47 -0
  110. package/mkseal.js +101 -0
  111. package/nativePush.js +153 -0
  112. package/nitroVerify.js +220 -0
  113. package/noble-p256.js +27 -0
  114. package/notice.js +116 -0
  115. package/notifKey.js +58 -0
  116. package/offlineBundle.js +62 -0
  117. package/ohttp.js +177 -0
  118. package/opRouting.js +10 -0
  119. package/opencodeWire.js +282 -0
  120. package/oprf.js +70 -0
  121. package/ownAgentLink.js +96 -0
  122. package/ownerPolicy.js +117 -0
  123. package/package.json +273 -4
  124. package/pdfOptions.js +13 -0
  125. package/pdfText.js +107 -0
  126. package/pdfjs.mjs +28 -0
  127. package/pdfjs.worker.mjs +28 -0
  128. package/pollVerdict.js +33 -0
  129. package/prefetchPoll.js +60 -0
  130. package/protectedLocal.js +426 -0
  131. package/pushCore.js +42 -0
  132. package/recovery.js +107 -0
  133. package/regions.js +42 -0
  134. package/removedMessage.js +11 -0
  135. package/renameRefusal.js +9 -0
  136. package/replyQuote.js +34 -0
  137. package/reqEnvelope.js +126 -0
  138. package/roomDefaultPrefs.js +76 -0
  139. package/roomDelete.js +109 -0
  140. package/roomEmbed.js +111 -0
  141. package/roomName.js +177 -0
  142. package/roomPass.js +256 -0
  143. package/roomRoster.js +305 -0
  144. package/roomSettings.js +61 -0
  145. package/roomState.js +58 -0
  146. package/roomStreamClient.js +115 -0
  147. package/rosterCount.js +52 -0
  148. package/rosterHash.js +13 -0
  149. package/rowSchema.js +113 -0
  150. package/safeMedia.js +116 -0
  151. package/safeMediaPins.js +17 -0
  152. package/schedulesDoc.js +78 -0
  153. package/sdkA2A.js +524 -0
  154. package/sdkAccount.js +483 -0
  155. package/sdkAccountDoc.js +89 -0
  156. package/sdkAccountSections.js +332 -0
  157. package/sdkAgui.js +141 -0
  158. package/sdkAttest.js +34 -0
  159. package/sdkBackup.js +507 -0
  160. package/sdkBackupV2.js +630 -0
  161. package/sdkBrowserPrivate.js +28 -0
  162. package/sdkBuilds.js +208 -0
  163. package/sdkCloudDevice.js +221 -0
  164. package/sdkComputers.js +1009 -0
  165. package/sdkDictation.js +232 -0
  166. package/sdkErase.js +288 -0
  167. package/sdkExports.js +71 -0
  168. package/sdkInvitations.js +34 -0
  169. package/sdkKeptAgent.js +188 -0
  170. package/sdkLaneLink.js +205 -0
  171. package/sdkPlan.js +96 -0
  172. package/sdkProtect.js +228 -0
  173. package/sdkRedact.js +36 -0
  174. package/sdkRekey.js +340 -0
  175. package/sdkReport.js +68 -0
  176. package/sdkSafeMedia.js +255 -0
  177. package/sdkSchedules.js +39 -0
  178. package/sdkSpeech.js +71 -0
  179. package/sdkTemporaryRooms.js +123 -0
  180. package/sdkTurn.js +117 -0
  181. package/sdkVault.js +180 -0
  182. package/sealShare.js +18 -0
  183. package/sealedNames.js +64 -0
  184. package/sealedReceipt.js +17 -0
  185. package/sentinelRelease.js +155 -0
  186. package/shamir.js +85 -0
  187. package/sharedViews.js +52 -0
  188. package/sheetChrome.js +450 -0
  189. package/siri.js +278 -0
  190. package/spaceClient.js +1429 -0
  191. package/spaceConfig.js +81 -0
  192. package/spaceEmailGate.js +813 -0
  193. package/spaceExport.js +125 -0
  194. package/spaceFork.js +216 -0
  195. package/spaceLock.js +358 -0
  196. package/spacePasskey.js +180 -0
  197. package/spaceTemplates.js +99 -0
  198. package/speechOut.js +102 -0
  199. package/splitKeyClient.js +90 -0
  200. package/store.js +656 -0
  201. package/streamHint.js +36 -0
  202. package/sttCloud.js +220 -0
  203. package/sttWorklet.js +38 -0
  204. package/sw-notif-core.js +540 -0
  205. package/tempList.js +48 -0
  206. package/tinfoilVerifier.js +78 -0
  207. package/toolBooks.js +31 -0
  208. package/toolRules.js +52 -0
  209. package/turnCerts.js +254 -0
  210. package/turnFeed.js +58 -0
  211. package/turnVerdict.js +37 -0
  212. package/usageReceipts.js +176 -0
  213. package/usageSummary.js +90 -0
  214. package/util.js +181 -0
  215. package/vault-core.js +2326 -0
  216. package/vault-kit.mjs +354 -0
  217. package/vault-screens.js +261 -0
  218. package/vaultAtRest.js +208 -0
  219. package/vaultCoreLock.js +111 -0
  220. package/vaultCorePush.js +140 -0
  221. package/vaultDeviceKey.js +95 -0
  222. package/vaultEnclaveHandoff.js +114 -0
  223. package/vaultKeep.js +287 -0
  224. package/vaultSealedStore.js +77 -0
  225. package/vaultWorkerHost.js +117 -0
  226. package/vcWorker.js +34 -0
  227. package/voiceAttest.js +50 -0
  228. package/voiceCert.js +51 -0
  229. package/witbitz-admin.d.ts +135 -0
  230. package/witbitz-admin.js +529 -0
  231. package/witbitz-admin.mjs +1460 -0
  232. package/witbitz-sdk.d.ts +1197 -0
  233. package/witbitz-sdk.js +4258 -0
  234. package/workerClient.js +16 -0
  235. package/workerLiveness.js +21 -0
  236. package/x509.js +218 -0
package/roomRoster.js ADDED
@@ -0,0 +1,305 @@
1
+ import { memberHash } from './rosterHash.js'
2
+
3
+ /** Resolve a verified post against the server's signing-key directory. A chosen name alone proves no address. */
4
+ export function verifiedSigningIds(entries) {
5
+ const ids = new Set()
6
+ for (const e of entries || []) {
7
+ const key = e?.spk || e?.vspk
8
+ if (e?.verified === true && !e.keyOnly && !e.self && e.kind !== 'agent' && key?.x && key?.y) ids.add(key.x + '.' + key.y)
9
+ }
10
+ return ids
11
+ }
12
+
13
+ export function verifiedPosters(entries, seen, { withId = false } = {}) {
14
+ const posters = []
15
+ for (const e of entries || []) {
16
+ const point = e?.spk || e?.vspk
17
+ if (e?.verified !== true || e.self || e.kind === 'agent' || !point?.x || !point?.y) continue
18
+ const id = point.x + '.' + point.y
19
+ const person = Object.prototype.hasOwnProperty.call(seen, id) ? seen[id] : null
20
+ if (person?.left) continue
21
+ const owner = person?.swapped ? null : person
22
+ const stampedEmail = (e.kind === 'data' || e.kind === 'title') && typeof e.email === 'string' ? e.email.trim().toLowerCase() : ''
23
+ const email = owner?.email || stampedEmail || (e.emailNameVerified === true ? String(e.name || '').trim().toLowerCase() : '')
24
+ const user = owner?.user || e.user || ''
25
+ if (email || user) posters.push({ email, user, ...(withId && !person?.swapped ? { id } : {}) })
26
+ }
27
+ return posters
28
+ }
29
+ // roomRoster.js — the room's guest book: everyone who ANNOUNCED themselves, in join order.
30
+ //
31
+ // A public room's only credential is the link, so reading it is an unauthenticated poll (`spaceService.mjs` op
32
+ // 'poll' — no gate) and nothing can make a visitor announce. ★ THIS LIST THEREFORE MEANS "PEOPLE WHO ANNOUNCED
33
+ // THEMSELVES", NEVER "EVERYONE WHO OPENED THIS ROOM", and the UI must say so. A lurker with the link is invisible by
34
+ // construction, not by oversight; a design that implied otherwise would be handing someone a number that looks like
35
+ // attendance and is really politeness. If you need the stronger claim, that is an email/invite-gated room, where
36
+ // every READ carries an identity before the server serves a byte — not this.
37
+ //
38
+ // Two rules do the real work here, and neither may bend:
39
+ // 1. A GUEST IS NEVER SHOWN A NAME THEY CHOSE. Anyone with the link can type "Alon". Guests get an ordinal, and
40
+ // only an entry the SERVER attested (grant-bound `from`, see spaceService.mjs) may carry a name.
41
+ // 2. A LABEL MEANS THE SAME THING TO EVERY VIEWER. Labels are DERIVED from join order, never stored, so two
42
+ // devices reading the same doc agree without coordinating and without asking the server.
43
+ //
44
+ // Storage is one mk-sealed `state` doc (l1.state(room, ROSTER_DOC)) — the transport liveLocation already uses: a
45
+ // turn-less write that never wakes the agent, and opaque to the server. ⚑ `state` is last-writer-wins on the WHOLE
46
+ // doc, so two people joining at once can clobber each other. There is no lock; instead every client re-asserts
47
+ // itself on every open and `mergeRoster` restores what was lost — see the self-healing tests.
48
+ // ⚑ And never put any of this in the op's `by` field: that one is cleartext to the server.
49
+
50
+ export const ROSTER_DOC = 'roster'
51
+ export const MAX_ENTRIES = 200 // every byte is written by someone holding the link; bound the griefer, keep the early
52
+
53
+ // An id is either a GUEST's local marker (`meId()` — 'm-' + 8 chars) or a MEMBER's signing key as `jkey(spk)`,
54
+ // which is `${jwk.x}.${jwk.y}` — 43 + 1 + 43 = 87 characters for P-256. ★ This cap was 64, so every signed-in member
55
+ // failed `isId`, `ensureSelf` returned `changed: false`, and NO WRITE WAS EVER ATTEMPTED — a silent no-op that reads
56
+ // exactly like "nobody has announced yet". It excluded precisely the people the guest book exists to attest: the
57
+ // `verified` row, with a real name instead of an ordinal, is reachable ONLY with a jkey id. Found 2026-09-21 on a
58
+ // live room whose doc was still v0 while guests demonstrably wrote fine. The id must stay the jkey verbatim —
59
+ // openWho matches it against `deriveRoster(entries).map(jkey)` — so the CAP is what was wrong, not the id. Still
60
+ // bounded (this is a griefer bound, and MAX_ENTRIES × 128 B is a small doc). spaces/test/roomRoster.test.mjs.
61
+ const MAX_ID = 128
62
+ const isId = (v) => typeof v === 'string' && !!v && v.length <= MAX_ID
63
+ // A name from the doc is UNTRUSTED INPUT — written by anyone holding the link. Bounded and trimmed here; rendered
64
+ // with textContent, never as markup; and it gains no standing from being stored.
65
+ const cleanName = (v) => (typeof v === 'string' && v.trim() ? v.trim().replace(/\s+/g, ' ').slice(0, 40) : undefined)
66
+ /** One stored row, sanitized. A name is kept whether or not it was attested — `verified` is what separates them. */
67
+ function clean (e) {
68
+ if (!e || typeof e !== 'object') return null
69
+ if (!isId(e.id) || !Number.isFinite(e.at)) return null
70
+ const out = { id: e.id, at: e.at }
71
+ const nm = cleanName(e.name)
72
+ if (nm) out.name = nm
73
+ if (e.verified === true) out.verified = true
74
+ return out
75
+ }
76
+
77
+ export const hasVerifiedClaim = roster => rows(roster).some(e => e.verified === true)
78
+ const rows = (roster) => (Array.isArray(roster) ? roster : Array.isArray(roster?.people) ? roster.people : []).map(clean).filter(Boolean)
79
+ // Join order, with the id as a tiebreak: two devices can stamp the same millisecond, and without this two viewers
80
+ // could number them oppositely — which would quietly break the one promise a label makes.
81
+ const byJoin = (a, b) => (a.at - b.at) || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0)
82
+
83
+ /**
84
+ * Add this device to the roster if it is not already there. Idempotent ON PURPOSE: re-opening a room must not
85
+ * rewrite the doc, because every write is a chance to clobber someone who joined at the same moment.
86
+ * @returns {{roster: object[], changed: boolean}} — write only when `changed`.
87
+ */
88
+ /** The key of a JWK, the way spaceFork.jkey names it — the id an attested row is matched to the ledger by. */
89
+ export const keyOf = (jwk) => (jwk && jwk.x && jwk.y) ? `${jwk.x}.${jwk.y}` : ''
90
+
91
+ /** WHAT A DEVICE ANNOUNCES ITSELF AS. Under a signing key the READER can attest against the ledger (a server-verified
92
+ * entry signed by that key), or as a bare device id shown as an ordinal. Two keys count, in this order:
93
+ * grantSpk — the invite-grant identity (an invited member)
94
+ * signPub — the EMAIL-gate signing key (identity.js recallSign): what a member of a verified room actually posts
95
+ * with. ★ This one was missing (2026-09-26, "so why is Tomer unverified?"): announceSelf read only the
96
+ * grant, so in an email-gated room every member announced a bare id no ledger key could ever match, and
97
+ * the sheet called them "unverified" however much they had posted.
98
+ * The `verified` on the row is a CLAIM the reader re-checks (listRoster's `attested`); the name is what the person
99
+ * goes by here. */
100
+ // ★ In a VERIFIED room the sign-in key wins (2026-10-04, sp-294n…): the server records each gate sign-in under the key
101
+ // the request was SIGNED with (spaceService `roster_seen`, keyed by req.spk = signPub), so a creator or invited device
102
+ // that announced under its grant key wrote a row the server's record never matched.
103
+ export function selfRow ({ grantSpk = null, signPub = null, deviceId = '', name = '', gated = false } = {}) {
104
+ const key = gated ? (keyOf(signPub) || keyOf(grantSpk)) : (keyOf(grantSpk) || keyOf(signPub))
105
+ return key ? { id: key, name: name || '', verified: true } : { id: deviceId, name: name || '' }
106
+ }
107
+
108
+ /** THE MEMBERS VIEW OF A VERIFIED ROOM (owner, 2026-09-26: "for verified rooms it should be Members, and in there it can
109
+ * show the status"). A room with an email gate has a LIST of who may post (advertised emails / @usernames in the clear,
110
+ * hidden ones as room-salted hashes, whole domains), and the server vouches for whoever passed the gate (`seen`). So the
111
+ * sheet is not "who's been here" but "who is a member, and where each of them stands":
112
+ * signed in — the gate verified them here (seen), or a server-badged ledger entry carries their key (named)
113
+ * not yet opened — on the list, no sighting yet
114
+ * allowed — a whole domain
115
+ * unverified — a typed name the server never vouched for (a guest row in a gated room)
116
+ * Hidden entries cannot be named, only counted. `rows` = listRoster(...) output; `seenIdentity(id)` → "@user" | email | "". */
117
+ // `onList(email, user)` (verifiedMove.stillOnList): a room re-keyed in place keeps its guest book and its history, so a REMOVED
118
+ // member still has rows and posts — they are not members. Absent (a room never re-keyed): every sighting is a member, as before.
119
+ export function membersView ({ allow = {}, rows = [], seenIdentity = () => '', seenPerson = null, posters = [], myEmail = '', mineId = '', myName = '', hiddenUnseen = null, seenHandles = new Set(), onList = null } = {}) {
120
+ const norm = (s) => String(s || '').trim().toLowerCase()
121
+ const me = norm(myEmail)
122
+ // ONE ROW PER PERSON (2026-10-04, sp-294n…: four "@alice" rows for one person on four keys, and both listed emails
123
+ // "not yet opened" — the owner's own and an account with five verified posts). A row is a signing KEY, and every
124
+ // device, app and reinstall makes its own; the person is the verified EMAIL the server recorded beside the key.
125
+ // `seenPerson(id)` → { email, user } (the older `seenIdentity(id)` → "@user" | email still works, with less to match).
126
+ const personOf = (id) => {
127
+ if (seenPerson) { const p = seenPerson(id); return p && (p.email || p.user) ? { email: norm(p.email), user: String(p.user || '').replace(/^@/, '') } : null }
128
+ const s = String(seenIdentity(id) || ''); if (!s) return null
129
+ return s.startsWith('@') ? { email: '', user: s.slice(1) } : { email: norm(s), user: '' }
130
+ }
131
+ const people = new Map() // key → { email, user, label, me, id }
132
+ const add = (key, p) => {
133
+ const had = people.get(key)
134
+ if (had) { had.email ||= p.email; had.user ||= p.user; had.me ||= p.me; return }
135
+ people.set(key, { ...p })
136
+ }
137
+ const postedById = new Map((posters || []).filter(p => p?.id && (p.email || p.user)).map(p => [p.id, p]))
138
+ for (const r of rows) {
139
+ const p = personOf(r.id) || postedById.get(r.id)
140
+ const isMe = r.id === mineId || (!!me && !!p && p.email === me)
141
+ // A verified room lists MEMBERS: a row nobody vouched for (a typed name — a reader with the link, or a device that
142
+ // announced before it had its key) is not a member and is not shown. The owner read "Tomer · unverified" beside a
143
+ // list that admits Tomer as "Tomer is not verified"; the row said only that the device had not re-announced yet.
144
+ if (!isMe && !p && !r.named) continue
145
+ if (!isMe && onList && !onList(p ? p.email : '', p ? p.user : '')) continue // removed since (a re-keyed room's guest book)
146
+ const email = (p && p.email) || (isMe ? me : '')
147
+ const user = (p && p.user) || ''
148
+ add(email || (user ? '@' + norm(user) : 'id:' + r.id), { email, user, me: isMe, id: r.id, label: r.label })
149
+ }
150
+ // A verified post is the strongest sighting there is: its author opened the room, announced or not.
151
+ for (const a of Array.isArray(posters) ? posters : []) {
152
+ const email = norm(a && a.email), user = String((a && a.user) || '').replace(/^@/, '')
153
+ if (!email && !user) continue
154
+ if (onList && !(me && email === me) && !onList(email, user)) continue // a removed member's old posts do not make them a member
155
+ const key = email || '@' + norm(user)
156
+ const byUser = !email && [...people.values()].find((x) => user && norm(x.user) === norm(user))
157
+ if (byUser) continue
158
+ add(key, { email, user, me: !!me && email === me, label: '' })
159
+ }
160
+ // You are a member the moment you are reading as your verified self, whether or not this device has announced.
161
+ if (me && ![...people.values()].some((x) => x.me)) { if (people.has(me)) people.get(me).me = true; else add(me, { email: me, user: '', me: true, label: '' }) }
162
+ const items = []
163
+ const covered = new Set()
164
+ const ordered = [...people.values()].sort((x, y) => (y.me ? 1 : 0) - (x.me ? 1 : 0))
165
+ for (const x of ordered) {
166
+ if (x.email) covered.add(x.email)
167
+ if (x.user) covered.add(norm('@' + x.user))
168
+ const label = x.user ? '@' + x.user : (x.email || (x.me ? (myName || x.label) : x.label))
169
+ const address = x.email || (x.user ? '@' + x.user : '')
170
+ items.push({ label, tag: x.me ? 'you' : 'signed in', ...(x.id ? { id: x.id } : {}), ...(address ? { address } : {}), ...(x.user ? { user: x.user } : {}) })
171
+ }
172
+ const emails = Array.isArray(allow.emails) ? allow.emails.filter(Boolean) : []
173
+ // an older room's @username entry: { handle, username } — the username it had THEN. A signed-in member whose handle it is
174
+ // (seenHandles: the caller resolved the signed-in usernames) is that member under their new name, not a second person.
175
+ const users = Array.isArray(allow.users) ? allow.users.filter((u) => !(u && typeof u === 'object' && u.handle && seenHandles.has(String(u.handle)))).map((u) => (u && typeof u === 'object' ? u.username : u)).filter(Boolean) : []
176
+ for (const e of emails) if (!covered.has(norm(e))) items.push({ label: e, tag: 'not yet opened', address: e })
177
+ for (const u of users) if (!covered.has(norm('@' + u))) items.push({ label: '@' + u, tag: 'not yet opened', address: '@' + u, user: u })
178
+ const domains = Array.isArray(allow.domains) ? allow.domains.filter(Boolean) : []
179
+ for (const d of domains) items.push({ label: 'anyone at @' + d, tag: 'allowed' })
180
+ // Hidden (hashed) entries: the caller matches them against the people the room verified (rosterHash.memberHash of
181
+ // each seen email) and passes how many are still UNSEEN — those are invites nobody has opened, not "more people".
182
+ // Without that count, every hidden entry is reported, which double-counts a member who is already listed above.
183
+ const hiddenAll = Array.isArray(allow.mh) ? allow.mh.length : 0
184
+ const hidden = Number.isInteger(hiddenUnseen) ? Math.max(0, Math.min(hiddenUnseen, hiddenAll)) : hiddenAll
185
+ const note = 'Everyone this room lets post. Signed in: verified on their own device. Not yet opened: invited, but hasn’t opened the room yet.'
186
+ + (hidden ? ` ${hidden} private ${hidden === 1 ? 'invite hasn’t' : 'invites haven’t'} been opened yet.` : '')
187
+ return { title: 'Members', note, items, hidden }
188
+ }
189
+
190
+ /** A verified room's guest book does not yet SHOW this row as signed in (`seen`, the server's record of who the email gate
191
+ * verified): announce again even with nothing changed — a lost write (two members announcing at once) would otherwise leave the
192
+ * member nameless for ever, and a member change in place cannot reach a hidden member it cannot name. */
193
+ // ⚑ A RECORD MARKED `left` IS NOT A SIGHTING (the owner, 2026-11-27: removed from a Space and added back, he opened it and the owner's
194
+ // list said "Not yet opened" for good). A removal — or leaving — marks the member's record `left` (roomLeave.markLeft) and every
195
+ // reader skips such a record; it still holds the email, so this said "seen", the device never announced again, and the mark never
196
+ // cleared. The server writes a fresh record over a `left` one (spaceService roster_seen `mine`).
197
+ export const unseenIn = (seen, id) => !!id && !(seen && typeof seen === 'object' && seen[id] && seen[id].email && !seen[id].left)
198
+ /** Seen, but before the record kept WHICH list entries this person is (2026-10-23, rosterCount samePeople): announced ONCE more
199
+ * per room and key on this page (never retried — a server that does not keep them yet answers the same) so one person on the list by email and by
200
+ * @username counts once. */
201
+ const _entriesAsked = new Set()
202
+ export const entriesMissing = (seen, id, room = '') => {
203
+ if (!id || unseenIn(seen, id) || Array.isArray(seen[id].entries)) return false
204
+ const k = room + '\n' + id; if (_entriesAsked.has(k)) return false // once per room and key on this page
205
+ _entriesAsked.add(k); return true
206
+ }
207
+ /** This page announced `id` in `room` (for any reason): the server had its chance to record the entries — no extra announce. */
208
+ export const announcedIn = (room, id) => { if (id) _entriesAsked.add(room + '\n' + id) }
209
+
210
+ export function ensureSelf (roster, self, now = Date.now(), { retire = '' } = {}) {
211
+ let list = rows(roster)
212
+ // A device that now announces under a KEY retires the bare-id row it wrote before it had one (same device, same
213
+ // person) — otherwise the sheet shows the person twice, once attested and once "unverified".
214
+ // `retire` may be a list: in a verified room the device also retires the row it wrote under its grant key (selfRow).
215
+ const gone = [].concat(retire || []).filter((x) => x && self && self.id !== x && list.some((e) => e.id === x))
216
+ if (gone.length) { list = list.filter((e) => !gone.includes(e.id)); return { ...ensureSelf(list, self, now), changed: true } }
217
+ if (!self || !isId(self.id)) return { roster: list, changed: false }
218
+ const had = list.find((e) => e.id === self.id)
219
+ if (had) {
220
+ // Already listed. Only a CHANGED name is worth a write — every write is a chance to clobber a concurrent joiner.
221
+ const nm = cleanName(self.name)
222
+ if (nm === had.name) return { roster: list, changed: false }
223
+ return { roster: list.map((e) => (e.id === self.id ? clean({ ...e, name: nm }) : e)).sort(byJoin), changed: true } // the ORIGINAL join time is kept
224
+ }
225
+ const mine = clean({ id: self.id, at: Number.isFinite(now) ? now : Date.now(), name: self.name, verified: self.verified })
226
+ const next = [...list, mine].sort(byJoin)
227
+ // Cap by dropping the LATEST, never the earliest: a flood must not push the room's actual people out of their own
228
+ // list. (It can still stop new joins being recorded — that is the honest failure, and it is visible.)
229
+ return { roster: next.slice(0, MAX_ENTRIES), changed: true }
230
+ }
231
+
232
+ /** Union two copies of the doc. Commutative and idempotent, earliest join wins, attestation is sticky. */
233
+ export function mergeRoster (a, b) {
234
+ const by = new Map()
235
+ for (const e of [...rows(a), ...rows(b)]) {
236
+ const prev = by.get(e.id)
237
+ if (!prev) { by.set(e.id, e); continue }
238
+ const at = Math.min(prev.at, e.at) // a rejoin never jumps the queue
239
+ const vr = prev.verified === true ? prev : (e.verified === true ? e : null)
240
+ const nm = vr ? vr.name : (prev.name || e.name) // an ATTESTED name wins over a claimed one
241
+ by.set(e.id, { id: e.id, at, ...(nm ? { name: nm } : {}), ...(vr ? { verified: true } : {}) })
242
+ }
243
+ return [...by.values()].sort(byJoin).slice(0, MAX_ENTRIES)
244
+ }
245
+
246
+ /**
247
+ * The list to render: join order, labelled. Guests are numbered among GUESTS, so a named member joining does not
248
+ * shift everyone's ordinal.
249
+ * @param {(entry) => boolean} [opts.attested] — re-check an entry's claim to be verified. The doc is written by
250
+ * whoever holds the link, so `verified` in the stored bytes is a CLAIM; the caller passes what it can actually
251
+ * attest (e.g. an spk seen on a server-stamped ledger entry). Default: trust the row, for tests and for callers
252
+ * that have already sanitized it.
253
+ */
254
+ export function listRoster (roster, { attested = null } = {}) {
255
+ const list = rows(roster).sort(byJoin)
256
+ const ok = list.map((e) => e.verified === true && (attested ? !!attested(e) : true))
257
+ // How many rows carry each name, attested or claimed. A name held by exactly one row can stand alone; a name two
258
+ // rows claim is disambiguated, so copying someone's name can never merge two people into one row. That is the one
259
+ // thing this list does that the chat cannot: it counts PEOPLE, not strings.
260
+ const held = new Map()
261
+ for (const e of list) if (e.name) held.set(e.name, (held.get(e.name) || 0) + 1)
262
+ // An ordinal is only spent where one is SHOWN — an attested member with a name consumes none, so the guests are
263
+ // user1, user2… in join order however many named members share the room.
264
+ const standalone = list.map((e, i) => !!e.name && (ok[i] || (held.get(e.name) || 0) === 1))
265
+ let n = 0
266
+ return list.map((e, i) => {
267
+ const verified = ok[i]
268
+ const ordinal = standalone[i] ? '' : 'user' + (++n)
269
+ return {
270
+ id: e.id,
271
+ at: e.at,
272
+ verified,
273
+ named: verified && !!e.name, // a name someone ATTESTED — the only kind that may be shown plain
274
+ claimed: !verified && !!e.name, // a name its owner typed — shown, and the UI must mark it
275
+ label: standalone[i] ? e.name : (e.name ? `${e.name} (${ordinal})` : ordinal),
276
+ }
277
+ })
278
+ }
279
+
280
+ export async function privateInvitationMatches(cfg, room, seen, { resolveUsers, userTag, within = promise => promise }) {
281
+ // hidden (hashed) list entries: subtract the ones a verified person matches, so a member is not counted twice
282
+ let hiddenUnseen = null
283
+ // THE HANDLES OF THE SIGNED-IN @USERNAMES (sync sweep 10-12): an older room lists an @username by its stable handle and
284
+ // the name it had THEN; a member who renamed is signed in under the new name — matched by handle, the old name is not
285
+ // listed again as "not yet opened". Resolved once, for this and for the hidden entries below.
286
+ const seenHandles = new Set()
287
+ const seenUsers = [...new Set(Object.values(seen).map((p) => p && p.user).filter(Boolean))]
288
+ const legacyUsers = Array.isArray(cfg.allow && cfg.allow.users) ? cfg.allow.users.filter((u) => u && typeof u === 'object' && u.handle) : []
289
+ let resolvedSeen = null
290
+ const resolveSeen = async () => { if (resolvedSeen) return resolvedSeen; try { resolvedSeen = ((await within(resolveUsers(seenUsers))) || { resolved: [] }).resolved || [] } catch { resolvedSeen = [] } return resolvedSeen }
291
+ if (seenUsers.length && legacyUsers.length) for (const r of await resolveSeen()) if (r && r.handle) seenHandles.add(String(r.handle))
292
+ try {
293
+ const mh = Array.isArray(cfg.allow && cfg.allow.mh) ? cfg.allow.mh : []
294
+ if (mh.length) { const got = new Set(); for (const p of Object.values(seen)) { if (p && p.email) { const h = await memberHash(p.email, room); if (h) got.add(h) } }
295
+ // THE ENTRIES THE GATE RECORDED AT EACH SIGN-IN (roster_seen `entries`, server-written — what member removal reads,
296
+ // sdkRekey listAfter): an older room hashed an @username from its HANDLE, which resolve no longer hands out for a member
297
+ // whose email door is closed (f8eb472a) — matched by what admitted them instead (sync sweep 11-08 #37)
298
+ for (const p of Object.values(seen)) for (const k of (p && Array.isArray(p.entries) ? p.entries : [])) if (typeof k === 'string' && k.startsWith('mh:')) got.add(k.slice(3))
299
+ // A hidden @username entry is hashed from its HANDLE (createBtn pushes r.handle), so a seen member is matched by
300
+ // their username's handle too — or a member invited by @username who opened the room still counted as an
301
+ // unopened private invite (sync sweep, 2026-10-10).
302
+ if (seenUsers.length) { try { for (const r of await resolveSeen()) { if (r.handle) { const h = await memberHash(r.handle, room); if (h) got.add(h) } const t = await within(userTag(r.username, room)).catch(() => null); if (t && t.status === 200 && t.tag) got.add(t.tag) } } catch { /* unresolved → counted as before — §12: a TAG (new rooms) or the handle's hash (older) */ } } hiddenUnseen = mh.filter((h) => !got.has(h)).length }
303
+ } catch { /* unknown → the view reports every hidden entry */ }
304
+ return { hiddenUnseen, seenHandles }
305
+ }
@@ -0,0 +1,61 @@
1
+ // roomSettings.js — a room's two PER-SPACE assistant settings, read the same way by the Spaces app and the SDK
2
+ // (sync sweep, 2026-10-10; spaces/test/roomSettings.test.mjs). Both are sealed, content-blind, last-writer-wins docs any
3
+ // member may write: `agentmode` (how the assistant replies) and `model` (which model answers, and its effort). Each turn
4
+ // carries them, so whichever client sends a message, the room answers the same way. The app's chips (agentMode.js,
5
+ // modelChip.js) and the SDK (witbitz-sdk.js) used to each keep their own copy — the SDK never read `model` at all, and
6
+ // read `agentmode` once — so one room answered with different models depending on who sent the message.
7
+
8
+ export const REPLY_MODES = ['auto', 'always', 'ondemand']
9
+ export const REPLY_MODE_LABEL = { auto: 'Auto', always: 'Always', ondemand: 'On demand' }
10
+
11
+ /** THE APP OFFERS TWO (the owner, 2026-11-12: "hide the auto mode … It is not working well. Let's stay with always and on demand").
12
+ * `auto` stays in REPLY_MODES for the SDK and builders' apps; the app's chip lists these. */
13
+ export const APP_REPLY_MODES = ['always', 'ondemand']
14
+ /** A Space's mode when nobody picked one: a verified Space with several people → On demand; one person, or
15
+ * a Space that is not verified → Always (the owner's rule). `members` null = not counted yet: a verified Space counts as a group,
16
+ * so a group is never answered on every message by mistake. */
17
+ export function defaultReplyMode ({ verified = false, members = null } = {}) {
18
+ if (!verified) return 'always'
19
+ return members === null || members > 1 ? 'ondemand' : 'always'
20
+ }
21
+ /** THE ONE DEFAULT, from a room's settings — the app (agentMode.js) and the server (agent/spaceService.mjs) both ask this (sync
22
+ * sweep 2026-11-13 #1, #4; the owner: "A room with no stored mode uses the app's default for everyone — SDK, Siri and outside
23
+ * agents included"). `cfg`: the room's config (verified = admission 'email'); `participants`: what rosterParticipants counts,
24
+ * WITH the room's sign-in record (`seen`) — null when the rule cannot count (a domain), which a verified Space reads as a group. */
25
+ export const roomDefaultReplyMode = (cfg, participants = null) => defaultReplyMode({
26
+ verified: !!cfg && cfg.admission === 'email',
27
+ members: typeof participants === 'number' && Number.isFinite(participants) ? participants : null,
28
+ })
29
+ /** The mode the app shows and each turn carries: the room's stored mode — Auto included (the owner, 2026-11-13: "A stored 'auto'
30
+ * stays Auto (an SDK builder chose it) and the app's chip shows it as Auto"; the chip OFFERS only APP_REPLY_MODES) — else the default. */
31
+ export const appReplyMode = (stored, dflt) => (REPLY_MODES.includes(stored) ? stored : dflt)
32
+ /** The mode a turn runs in on the server: the room's stored mode (Auto included), else a valid mode the turn sent, else the
33
+ * room's default (roomDefaultReplyMode) — never a silent Auto. */
34
+ export const turnReplyMode = (stored, sent, dflt) => (REPLY_MODES.includes(stored) ? stored : REPLY_MODES.includes(sent) ? sent : dflt)
35
+
36
+ /** The `agentmode` doc (as `state(room, 'agentmode')` returns it) → a reply mode, or null (no doc / unknown). */
37
+ export function modeFromDoc(d) {
38
+ const m = d && d.state && d.state.mode
39
+ return REPLY_MODES.includes(m) ? m : null
40
+ }
41
+
42
+ /** The `model` doc → `undefined` (no doc: nobody picked), `null` (picked "the room's own model"), or the pick
43
+ * `{ catalog, wire, label, effort? }`. */
44
+ export function modelPickFromDoc(d) {
45
+ const s = d && d.state
46
+ if (!s || typeof s !== 'object' || !('catalog' in s)) return undefined
47
+ return s.catalog ? { catalog: String(s.catalog), wire: String(s.wire || ''), label: String(s.label || ''), ...(s.effort ? { effort: String(s.effort) } : {}) } : null
48
+ }
49
+
50
+ /** What a turn carries for a pick (agent/modelCatalog.mjs turnModelPick). `efforts`: the catalog's measured list for that
51
+ * model when known — an effort outside it is dropped; unknown (null) → sent, and the server fits it. */
52
+ export function turnModelOf(pick, efforts = null) {
53
+ if (!pick || !pick.catalog) return undefined
54
+ const effort = pick.effort && (!Array.isArray(efforts) || efforts.map(String).includes(pick.effort)) ? pick.effort : ''
55
+ return { catalog: pick.catalog, ...(pick.wire ? { wire: pick.wire } : {}), ...(effort ? { params: { reasoning_effort: effort } } : {}) }
56
+ }
57
+
58
+ /** The `model` doc's state for a pick (null = back to the room's own model). */
59
+ export function modelDocOf(pick) {
60
+ return { catalog: pick ? pick.catalog : '', wire: pick ? (pick.wire || '') : '', label: pick ? (pick.label || '') : '', effort: pick ? (pick.effort || '') : '', at: Date.now() }
61
+ }
package/roomState.js ADDED
@@ -0,0 +1,58 @@
1
+ import { isAttestedRoom } from './attestedRooms.js'
2
+ // roomState.js — the per-room key/persistence custody layer (Verified-Client Phase 1, L1).
3
+ // Pure, self-contained localStorage helpers keyed by room id: the room key (mk) read, the per-member
4
+ // signing identity, the email-gate flag, and the key model. Extracted from space.js as the first TCB
5
+ // module. NOTE: rememberMk stays in space.js for now — it also mirrors mk into IndexedDB for the SW
6
+ // and enqueues a recovery backup, so it moves when those layers modularize. Everything here is dep-free.
7
+
8
+ export const mkKey = (r) => 'space:mk:' + r
9
+ export const recallMk = (r) => { try { return localStorage.getItem(mkKey(r)) } catch { return null } }
10
+ // The CURRENT room's key from state (worker-held mk lives there, not in localStorage); any other room's from the store.
11
+ export const curMk = (r = state.room) => (r === state.room ? (state.mk || recallMk(r)) : recallMk(r))
12
+ // TENANT SPLIT-KEY (docs/tenant-split-key-dualstore.md): a split room stores the user's MEMBERSHIP half (userShare) +
13
+ // the room's commit instead of `mk`. Never both — a room is normal (space:mk:) XOR split (space:us:+space:spc:).
14
+ export const usKey = (r) => 'space:us:' + r
15
+ export const spcKey = (r) => 'space:spc:' + r
16
+ export const recallUserShare = (r) => { try { return localStorage.getItem(usKey(r)) } catch { return null } }
17
+ // Room TYPE (is it split?) reads the NON-SECRET commit marker (space:spc:), not the secret userShare (space:us:). The
18
+ // commit is a public hash of mk, written alongside the userShare at every split site; keying room-type off it means the
19
+ // main thread never needs the secret to know a room is split — a prerequisite for confining the userShare to the kernel.
20
+ // (Kept `|| usKey` for the rare split entry that predates a commit; either marker means split.)
21
+ export const isSplitRoom = (r) => { try { return !!localStorage.getItem(spcKey(r)) || !!localStorage.getItem(usKey(r)) } catch { return false } }
22
+ export const modelKey = (r) => 'space:model:' + r
23
+ export const setModel = (r, m) => { try { localStorage.setItem(modelKey(r), m) } catch { /* private mode */ } }
24
+ export const getModel = (r) => { try { return localStorage.getItem(modelKey(r)) } catch { return null } }
25
+ export const idKey = (r) => 'space:id:' + r
26
+ export const rememberId = (r, id) => { try { localStorage.setItem(idKey(r), JSON.stringify(id)) } catch { /* private mode */ } }
27
+ export const recallId = (r) => { try { const s = localStorage.getItem(idKey(r)); return s ? JSON.parse(s) : null } catch { return null } }
28
+ export const gateKey = (r) => 'space:gate:' + r
29
+ export const setGate = (r, g) => { try { localStorage.setItem(gateKey(r), g) } catch { /* private mode */ } }
30
+ export const gateOf = (r) => { try { return localStorage.getItem(gateKey(r)) || '' } catch { return '' } }
31
+ // Verified-client marker (docs/verified-client-design.md): this room requires the Verified Client — its share link is a
32
+ // `?vc=` capability and it opens only in the extension. Local hint (mirrors setGate) so the share UI picks the right link.
33
+ export const vcKey = (r) => 'space:vc:' + r
34
+ export const setVerifiedClient = (r) => { try { localStorage.setItem(vcKey(r), '1') } catch { /* private mode */ } }
35
+ export const isVerifiedClient = (r) => { try { return localStorage.getItem(vcKey(r)) === '1' } catch { return false } }
36
+ export const signKey = (r) => 'space:sign:' + r
37
+ // EVERYTHING THIS DEVICE KEEPS UNDER A ROOM'S NAME (2026-10-26, the owner: "Check that there are no problems when we delete a
38
+ // space"). A delete removed the key, the model and the split shares, and left the rest — the room's private signing identity
39
+ // and keypair among them — for good, through every relaunch. space.js forgetSpace removes each of these; roomKeysOnDelete.test
40
+ // fails when a new `'space:<x>:' + room` key appears in the app without being here (or named as kept on purpose).
41
+ export const ROOM_KEY_PREFIXES = ['space:mk:', 'space:model:', 'space:us:', 'space:spc:', 'space:id:', 'space:sign:', 'space:gate:', 'space:vc:',
42
+ 'space:ak:', 'space:lanes:', 'space:nolane:', 'space:lanechk:', 'space:lanechk2:', 'space:laneup:', 'space:crossed:', 'space:epoch:', 'space:mykey:', 'space:notif:',
43
+ 'space:moved-unsent:', 'space:away-unsent:', 'space:safemedia:', 'space:inviteowed:', 'space:removed:']
44
+ export const recallSign = (r) => { try { const s = localStorage.getItem(signKey(r)); return s ? JSON.parse(s) : null } catch { return null } }
45
+ export const rememberSign = (r, kp) => { try { localStorage.setItem(signKey(r), JSON.stringify(kp)) } catch { /* private mode */ } }
46
+
47
+ // The LIVE session singleton — a mutable object so extracted TCB modules can READ and WRITE the same
48
+ // session state across module boundaries (ES imports are read-only bindings, but an object's properties
49
+ // are not). `client` is assigned at runtime in space.js (its init needs the page's auth/enclave glue).
50
+ export const state = { room: null, mk: null, etag: null, count: 0, client: null, myName: '', enclaveKey: null, enclaveClaim: null, enclaveAttested: null, apiEndpoint: '', enclaveAsleep: false, wakingEnclave: false, sessionRelease: null, lastBackupRead: null }
51
+
52
+ // A TEMPORARY room (docs: spaces-temporary-rooms) is named by its id — `tmp-` — and lives in the shreddable temp index,
53
+ // never in durable recents/backups. One definition, read by the shell and the modules alike.
54
+ export const isTempRoom = (r) => String(r || '').startsWith('tmp-')
55
+ // NOTHING OF THIS ROOM IS KEPT ON THE DEVICE: a temporary room (session-only) and an ATTESTED room of any kind (docs/emulated-
56
+ // attested-rooms.md; the owner, 2026-10-18: "attested rooms cannot be watched offline") — its key only in memory, released
57
+ // after a fresh attestation; no chat, state or image cache at rest. One rule for every cache.
58
+ export const noDeviceCopy = (r) => isTempRoom(r) || isAttestedRoom(r)
@@ -0,0 +1,115 @@
1
+ // roomStreamClient.js — the READING end of a room stream (docs/change-inbox.md § Room streams; the writer is
2
+ // agent/roomStream.mjs). While a room is on screen, the realm that holds its key keeps a socket on the room's channel on
3
+ // the relay and turns sealed frames into events: the reply as it grows (so the bubble is fed directly instead of by a
4
+ // poll every 350 ms), "poll now" when the ledger grew, and "the turn ended". It runs wherever the key is — the l1 worker
5
+ // by default (mk never leaves it), the page itself on the direct path — so it takes mk and never hands it on.
6
+ //
7
+ // The channel and the frame key derive from the room key (and, in a gated room, from the current epoch's GRANT, handed
8
+ // out only by a poll that passed the room's gate) — identical to agent/roomStream.mjs, held equal by
9
+ // spaces/test/roomStreamClient.test.mjs. Nothing here is the record: any doubt (a gap, a rewrite, a frame too big to
10
+ // send) becomes one "poll now", and a socket that cannot open leaves the page polling exactly as before.
11
+ import { open } from './e2ee.js'
12
+ import { RELAY_URL, RELAY_PING, RELAY_PONG, HEARTBEAT_MS, PONG_WAIT_MS } from './changePush.js'
13
+
14
+ export const STREAM_EPOCH_MS = 10 * 60 * 1000 // == agent/roomStream.mjs
15
+ const te = new TextEncoder()
16
+ const b64u = (u) => { let s = ''; for (const b of u) s += String.fromCharCode(b); return btoa(s).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '') }
17
+ const sha = async (s) => new Uint8Array(await crypto.subtle.digest('SHA-256', te.encode(s)))
18
+ export const streamChannel = async (mk, grant = '') => b64u(await sha('witbitz-room-stream|' + mk + (grant ? '|' + grant : '')))
19
+ export const streamKey = async (mk, grant = '') => (grant ? b64u(await sha('witbitz-room-stream-key|' + mk + '|' + grant)) : mk)
20
+ /** The grant for the epoch `now` falls in, from a poll's grants; null when none is current (poll again for fresh ones). */
21
+ export function currentGrant (grants, now = Date.now()) {
22
+ const e = Math.floor(now / STREAM_EPOCH_MS)
23
+ const g = (Array.isArray(grants) ? grants : []).find((x) => x && x.e === e && typeof x.g === 'string')
24
+ return g ? g.g : null
25
+ }
26
+
27
+ /** Pure reassembly: frames in → events out. {k:'partial', text, pseq, step} · {k:'poll', why} · {k:'end'}.
28
+ * sync(text): the page just POLLED and holds `text` as the reply so far — later deltas continue from it. */
29
+ export function frameReader () {
30
+ let text = '', valid = true, lastSeq = 0, owedPoll = false, turn = null
31
+ const poll = (why) => { if (owedPoll) return null; owedPoll = true; return { k: 'poll', why } } // one poll per doubt, not one per frame
32
+ return {
33
+ // A poll's text REPAIRS a reader that lost its place; it never overrides one that has not. The writer stores each
34
+ // step and THEN posts its frame, so a poll can be ahead of the frames or behind them — the frames are the authority
35
+ // while they are whole (the page's renderPartial orders the two by sequence number).
36
+ sync (t) { if (valid) return; text = String(t || ''); valid = true; owedPoll = false },
37
+ apply (f) {
38
+ if (!f || typeof f !== 'object') return null
39
+ // A write announced OUTSIDE any turn (agent/spaceService.mjs announceWrite): poll now, and leave the turn's sequence
40
+ // and the reply in progress exactly as they are — it carries no seq on purpose.
41
+ // An ARTIFACT changed (spaceService noteViewWrite): the page reads the room's one version list — not the ledger.
42
+ // A frame may CARRY the newest entry, sealed with the room key (agent/asyncTurn.mjs frameTail; 2026-10-20): { count, box }
43
+ // rides the poll event as `tail` — the key worker answers that poll from it (l1-worker.js frameTails), no network.
44
+ const tail = Number.isInteger(f.count) && f.count > 0 && typeof f.box === 'string' ? { tail: { count: f.count, box: f.box } } : {}
45
+ if (f.oob) return f.k === 'entries' ? { k: 'poll', why: 'changed', ...tail, ...(typeof f.doc === 'string' && /^[A-Za-z0-9]{1,24}$/.test(f.doc) ? { doc: f.doc } : {}) } : f.k === 'views' ? { k: 'views' } : null
46
+ if (f.seq === 1) { lastSeq = 0; text = ''; valid = true; owedPoll = false; turn = typeof f.tid === 'string' ? f.tid : null } // a new turn
47
+ // ANOTHER TURN'S FRAME (state machines pass 7, L#12): two turns on one channel each count from 1, so the other's next
48
+ // seq could look like ours and its text was spliced onto this reply. A frame naming another publisher is a doubt.
49
+ else if (turn && typeof f.tid === 'string' && f.tid !== turn) { valid = false; return poll('other turn') }
50
+ const gap = lastSeq && f.seq !== lastSeq + 1
51
+ lastSeq = Number(f.seq) || lastSeq
52
+ if (gap) { valid = false; return poll('gap') }
53
+ if (f.k === 'entries') { if (tail.tail) { owedPoll = true; return { k: 'poll', why: 'entries', ...tail } } return poll('entries') } // a carried entry is never deduped away
54
+ if (f.k === 'resync') { valid = false; return poll('resync') }
55
+ if (f.k === 'end') { owedPoll = false; return { k: 'end' } }
56
+ if (f.k !== 'partial') return null
57
+ const add = typeof f.add === 'string' ? f.add : ''
58
+ // A reply only grows, so a frame that starts INSIDE what we hold continues it from there; one that starts beyond it
59
+ // means frames were lost.
60
+ if (f.from === 0) { text = add; valid = true; owedPoll = false } else if (valid && f.from <= text.length) text = text.slice(0, f.from) + add
61
+ else { valid = false; return poll('gap') }
62
+ return { k: 'partial', text, pseq: f.pseq, step: f.step || null }
63
+ },
64
+ }
65
+ }
66
+
67
+ /** Hold the room's stream. onEvent(ev) per event above; onState(up). → { up(), sync(text), setGrants(grants), stop() }.
68
+ * `grants` null → an open room (the key alone); an array → a gated room (no current grant → no socket until fresh ones). */
69
+ export function openRoomStream ({ mk, grants = null, tag = '', onEvent = () => {}, onState = () => {}, relay = RELAY_URL, path = 'c', WebSocketImpl = globalThis.WebSocket, now = () => Date.now(), heartbeatMs = HEARTBEAT_MS, pongWaitMs = PONG_WAIT_MS } = {}) {
70
+ if (!mk || typeof WebSocketImpl !== 'function') return { up: () => false, sync () {}, setGrants () {}, stop () {} }
71
+ const reader = frameReader()
72
+ let ws = null, up = false, stopped = false, backoff = 1000, retry = null, beat = null, pongTimer = null, epochTimer = null, key = null, gs = grants
73
+ const setUp = (v) => { if (v !== up) { up = v; try { onState(v) } catch { /* */ } } }
74
+ const drop = () => { clearInterval(beat); clearTimeout(pongTimer); clearTimeout(epochTimer); beat = pongTimer = epochTimer = null; setUp(false); if (ws) { try { ws.onclose = ws.onerror = ws.onmessage = null; ws.close() } catch { /* */ } } ws = null }
75
+ const schedule = () => { if (stopped || retry) return; retry = setTimeout(() => { retry = null; connect() }, backoff); backoff = Math.min(backoff * 2, 30_000) }
76
+ async function connect () {
77
+ if (stopped || ws) return
78
+ const grant = gs ? currentGrant(gs, now()) : ''
79
+ if (gs && !grant) return // a gated room with no current grant: wait for the next poll's
80
+ key = await streamKey(mk, grant)
81
+ let s
82
+ // path 's': a page on ANY origin (the SDK) — the relay's /s/ namespace (relay/relay.mjs); the app keeps 'c'
83
+ try { s = new WebSocketImpl(String(relay).replace(/\/+$/, '') + '/' + path + '/' + await streamChannel(mk, grant) + (tag ? '?v=' + encodeURIComponent(tag) : '')) } catch { schedule(); return } // tag: THIS device is viewing (spaceClient viewingTag)
84
+ if (stopped) { try { s.close() } catch { /* */ } return }
85
+ ws = s
86
+ s.onopen = () => {
87
+ backoff = 1000; setUp(true)
88
+ beat = setInterval(() => { if (!ws || pongTimer) return; try { ws.send(RELAY_PING) } catch { drop(); schedule(); return } pongTimer = setTimeout(() => { pongTimer = null; drop(); schedule() }, pongWaitMs) }, heartbeatMs)
89
+ if (gs) { const t = now(); epochTimer = setTimeout(() => { drop(); connect() }, (Math.floor(t / STREAM_EPOCH_MS) + 1) * STREAM_EPOCH_MS - t + 50) } // a gated room moves to the next epoch's channel
90
+ }
91
+ s.onmessage = async (ev) => {
92
+ const text = typeof ev.data === 'string' ? ev.data : ''
93
+ if (text === RELAY_PONG) { clearTimeout(pongTimer); pongTimer = null; return }
94
+ if (!text || text.startsWith('{"t":')) return
95
+ let f = null
96
+ try { f = JSON.parse((await open(JSON.parse(text), { mk: key })) || 'null') } catch { f = null }
97
+ const e = f && reader.apply(f)
98
+ if (e) { try { onEvent(e) } catch { /* */ } }
99
+ }
100
+ s.onclose = s.onerror = () => { if (ws === s) { drop(); schedule() } }
101
+ }
102
+ connect()
103
+ return {
104
+ up: () => up,
105
+ sync: (t) => reader.sync(t),
106
+ /** Fresh grants from a poll (a gated room): reconnect only if the current epoch's grant changed (a rotation). */
107
+ setGrants (next) {
108
+ if (!Array.isArray(next)) return
109
+ const changed = currentGrant(next, now()) !== currentGrant(gs, now())
110
+ gs = next
111
+ if (changed || !ws) { drop(); clearTimeout(retry); retry = null; connect() }
112
+ },
113
+ stop () { stopped = true; clearTimeout(retry); drop() },
114
+ }
115
+ }
package/rosterCount.js ADDED
@@ -0,0 +1,52 @@
1
+ // rosterCount.js — how many people an email-gated room admits, counted from its sealed config: the PAGE's copy of the
2
+ // server's rule (agent/rosterCount.mjs rosterParticipants), held equal by spaces/test/fundingCounts.test.mjs.
3
+ // ⋯ → Fund this room uses it (sync sweep, 2026-10-10): the member count sets the grant's ceiling, and the sheet summed
4
+ // every list as is — a person listed both plain and hashed counted twice, a domain
5
+ // room given a number nobody can know.
6
+ // null = "this room's shape cannot know" (not email-gated, a domain wildcard, nothing enumerable); 0 is an answer.
7
+ import { memberHash } from './rosterHash.js'
8
+
9
+ const norm = (s) => String(s == null ? '' : s).toLowerCase().trim()
10
+ const list = (v) => (Array.isArray(v) ? v.map(norm).filter(Boolean) : [])
11
+
12
+ /** Exactly one admitted identity, and it is the signed-in person; no usernames or domains. */
13
+ export async function isSoloVerified(cfg, room, me, { hash = memberHash } = {}) {
14
+ const email = norm(me), allow = cfg?.allow
15
+ if (!email || cfg?.admission !== 'email' || !allow || allow.users?.length || allow.domains?.length || allow.tags?.length) return false
16
+ const shown = Array.isArray(allow.emails) ? allow.emails.map(norm) : []
17
+ const hidden = Array.isArray(allow.mh) ? allow.mh : []
18
+ if (!shown.length && !hidden.length) return false
19
+ if (shown.some(address => address !== email)) return false
20
+ if (!hidden.length) return true
21
+ const expected = await hash(email, room)
22
+ return hidden.every(h => h === expected)
23
+ }
24
+
25
+ export async function rosterParticipants (space, roomSalt, { seen = null } = {}) {
26
+ if (!space || space.admission !== 'email') return null
27
+ const allow = space.allow && typeof space.allow === 'object' ? space.allow : {}
28
+ if (list(allow.domains).length) return null
29
+ const emails = new Set(list(allow.emails))
30
+ const mh = new Set(Array.isArray(allow.mh) ? allow.mh.filter((h) => typeof h === 'string' && h) : [])
31
+ const users = new Set((Array.isArray(allow.users) ? allow.users : []).map((u) => u && typeof u === 'object' ? norm(u.handle) : '').filter(Boolean))
32
+ if (!emails.size && !mh.size && !users.size) return null
33
+ const plainOnly = new Set()
34
+ for (const e of emails) if (!(mh.size && mh.has(await memberHash(e, roomSalt)))) plainOnly.add(e)
35
+ return mh.size + plainOnly.size + users.size - await samePeople(seen, { mh, plainOnly, users })
36
+ }
37
+ // ONE PERSON, ONE COUNT (the owner, 2026-10-23: added by email AND by @username is "One person"). The list cannot tell —
38
+ // an @username's tag is unlinkable to an email by design — but the server can when that person signs in: roster_seen keeps,
39
+ // per signed-in member, the list entries their verified email matched (spaceOidc allowEntriesFor). Entries one person
40
+ // matched count once. → how many entries to take off.
41
+ export async function samePeople(seen, { mh, plainOnly, users }) {
42
+ if (!seen || typeof seen !== 'object') return 0
43
+ const counted = new Set([...[...mh].map((h) => 'mh:' + h), ...[...plainOnly].map((e) => 'e:' + e), ...[...users].map((u) => 'u:' + u)])
44
+ const parent = new Map(), find = (k) => { while (parent.get(k) !== k) k = parent.get(k); return k }
45
+ let merged = 0
46
+ for (const p of Object.values(seen)) {
47
+ const ks = (p && Array.isArray(p.entries) ? p.entries : []).filter((k) => counted.has(k))
48
+ for (const k of ks) if (!parent.has(k)) parent.set(k, k)
49
+ for (let i = 1; i < ks.length; i++) { const a = find(ks[0]), b = find(ks[i]); if (a !== b) { parent.set(b, a); merged++ } }
50
+ }
51
+ return merged
52
+ }
package/rosterHash.js ADDED
@@ -0,0 +1,13 @@
1
+ // Client twin of agent/rosterHash.mjs — a room-bound salted hash of a roster identity (an email), ported from
2
+ // kibitz/src/core/rosterHash.ts. Used at CREATE time to hash the email allow-list before it's sealed into the config,
3
+ // so co-members can't read each other's addresses; the server-side gate hashes the verified email the same way and
4
+ // checks membership. Output MUST be byte-identical to the server twin (same NFKC→trim→lowercase, SHA-256, base64url).
5
+ const enc = new TextEncoder()
6
+ const b64url = (buf) => btoa(String.fromCharCode(...new Uint8Array(buf))).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')
7
+ const norm = (s) => String(s == null ? '' : s).normalize('NFKC').trim().toLowerCase()
8
+
9
+ /** base64url(SHA-256(`norm(identity)|roomSalt`)); roomSalt (the room id) appended raw — matches kibitz + the server. */
10
+ export async function memberHash(identity, roomSalt) {
11
+ const digest = await crypto.subtle.digest('SHA-256', enc.encode(`${norm(identity)}|${roomSalt}`))
12
+ return b64url(digest)
13
+ }