@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/roomEmbed.js ADDED
@@ -0,0 +1,111 @@
1
+ const object = value => value !== null && typeof value === 'object' && !Array.isArray(value)
2
+ const types = new Set(['string', 'number', 'boolean', 'array', 'object'])
3
+ const validName = name => /^[a-zA-Z0-9_]{1,64}$/.test(name) && !Object.hasOwn(Object.prototype, name)
4
+ export function applySkills(config, skills) {
5
+ if (skills === undefined) return
6
+ if (!object(skills) || Object.keys(skills).length > 16 || !Object.entries(skills).every(([name, spec]) => validName(name) && object(spec) &&
7
+ [spec.in, ...(spec.out === undefined ? [] : [spec.out])].every(schema => object(schema) && Object.keys(schema).length <= 16 &&
8
+ Object.entries(schema).every(([key, type]) => validName(key) && types.has(type)))))
9
+ throw Object.assign(new Error('Each skill needs a name and a typed input schema.'), { code: 'invalid_argument' })
10
+ config.skills = Object.fromEntries(Object.entries(skills).map(([name, spec]) => [name, { in: { ...spec.in } }]))
11
+ const protocol = skillProtocol(skills)
12
+ if (protocol) config.persona = (config.persona || '') + '\n' + protocol
13
+ }
14
+
15
+ export function skillProtocol(skills) {
16
+ const names = Object.keys(skills || {})
17
+ if (!names.length) return ''
18
+ const rows = names.map((n) => ' • ' + n + '(' + JSON.stringify((skills[n] || {}).in || {}) + ')')
19
+ return [
20
+ '',
21
+ '--- YOUR MCP SKILLS (the app invokes these on you as TYPED tool calls over the bridge, NOT chat messages) ---',
22
+ ...rows,
23
+ 'When one is invoked you are told exactly which skill and with what arguments. Handle it FULLY — use your platform',
24
+ 'tools (read_url, web_search, the map/photo tools, …) whenever they make the answer better — then reply with the',
25
+ 'finished answer for the reader. Do not just echo the raw arguments back.',
26
+ ].join('\n')
27
+ }
28
+
29
+ export function embeddedInvite(template, link, origin) {
30
+ if (typeof template !== 'string' || template.length > 2000 || template.split('{link}').length !== 2 || !link)
31
+ throw Object.assign(new Error('An invite template needs a single {link} placeholder.'), { code: 'invalid_argument' })
32
+ const base = new URL(origin)
33
+ const url = new URL(template.replace('{link}', encodeURIComponent(link)), base.origin)
34
+ if (!['http:', 'https:'].includes(base.protocol) || url.origin !== base.origin || url.username || url.password)
35
+ throw Object.assign(new Error('The invite must open the embedding application.'), { code: 'invalid_argument' })
36
+ return url.href
37
+ }
38
+
39
+ export function setLiveDoc(docs, name, text) {
40
+ const key = String(name || 'document').slice(0, 80)
41
+ if (typeof text === 'string' && text) docs[key] = text.slice(0, 4000)
42
+ else delete docs[key]
43
+ }
44
+ export function formatLiveDocs(embedLiveDocs, meet = '') {
45
+ const names = Object.keys(embedLiveDocs).filter((n) => embedLiveDocs[n])
46
+ if (!names.length) return meet || undefined
47
+ let body = ''
48
+ for (const n of names) body += '[' + String(n).slice(0, 80) + ']\n' + String(embedLiveDocs[n]) + '\n\n'
49
+ return (meet + '=== LIVE CONTEXT (the CURRENT text of what the user has open right now — e.g. a draft, a call transcript. It updates live; reason over THIS and quote it exactly. It is not a saved file.) ===\n\n' + body + '=== end live context ===').slice(0, 4000) // matches the server's 4KB context cap; large sources get windowed/summarized later
50
+ }
51
+
52
+ export function roomEmbed(space, knownLane = () => false) {
53
+ const docs = Object.create(null), watches = new Set()
54
+ const owner = () => space._wb?.vault ? space._wb._memoryGeneration : space._wb?._archiveGeneration
55
+ const generation = space._memoryOwner ?? owner()
56
+ const active = () => !space._stopped && generation === owner()
57
+ function check() {
58
+ if (!active()) throw Object.assign(new Error('The Space closed or the account changed.'), { code: 'closed' })
59
+ }
60
+ async function state(patch) {
61
+ check()
62
+ const r = patch === undefined ? await space._client.state(space.room, space._mk, 'embed')
63
+ : await space._client.state(space.room, space._mk, 'embed', patch, '', 'embed')
64
+ check()
65
+ if (r?.status !== 200) throw Object.assign(new Error('The embedded state could not be synchronized.'), { code: r?.error || 'unavailable' })
66
+ return r
67
+ }
68
+ return {
69
+ context: () => active() ? formatLiveDocs(docs) : undefined,
70
+ close() { for (const stop of [...watches]) stop(); for (const name of Object.keys(docs)) delete docs[name] },
71
+ api: {
72
+ async invite(template) {
73
+ check()
74
+ if (space._sharedRoom || space._detachedLane || knownLane()) throw Object.assign(new Error('A private lane cannot be shared'), { code: 'private_lane' })
75
+ if (space._wb?.vault) return space._wb.vault.share(space, { hostInviteTemplate: template })
76
+ return embeddedInvite(template, space.shareLink, globalThis.location?.origin)
77
+ },
78
+ async read() { return (await state()).state ?? null },
79
+ async update(patch) {
80
+ if (!object(patch)) throw Object.assign(new Error('A state update needs an object.'), { code: 'invalid_argument' })
81
+ await state(patch)
82
+ },
83
+ watch(fn) {
84
+ check()
85
+ if (typeof fn !== 'function') throw new TypeError('A state listener is required.')
86
+ let timer, stopped = false, version = -1
87
+ const stop = () => { stopped = true; clearTimeout(timer); watches.delete(stop) }
88
+ async function poll() {
89
+ try {
90
+ const r = await state(), v = r.v || 0
91
+ if (!stopped && v > version) { version = v; fn(r.state ?? null) }
92
+ } catch { /* retry when the room becomes available */ }
93
+ if (!stopped && active()) timer = setTimeout(poll, 2500)
94
+ else stop()
95
+ }
96
+ watches.add(stop); void poll()
97
+ return stop
98
+ },
99
+ setLiveDocument(name, text) { check(); setLiveDoc(docs, name, text) },
100
+ },
101
+ }
102
+ }
103
+
104
+ export function roomInviteFlags(link) {
105
+ try {
106
+ const url = new URL(link, 'https://example.invalid/')
107
+ const fragment = new URLSearchParams(url.hash.slice(1))
108
+ const has = (key, value) => url.searchParams.getAll(key).includes(value) || fragment.getAll(key).includes(value)
109
+ return { gated: has('gate', 'email'), lanes: has('lanes', '1') }
110
+ } catch { return { gated: false, lanes: false } }
111
+ }
package/roomName.js ADDED
@@ -0,0 +1,177 @@
1
+ // spaces/public/roomName.js — A ROOM'S NAME, as every client reads it: the app (roomTitle.js, messageRender.js, unread.js)
2
+ // and the SDK (witbitz-sdk.js) import this one module, so a device and a builder's page can never disagree on a name.
3
+ //
4
+ // The name is an ENTRY in the room's log — { kind:'title', title, manual | auto, name, ts } — appended by op:'title' when a
5
+ // member renames the room (`set`) or a new name is generated (agent/spaceService.mjs). It reaches every device on every
6
+ // path a message takes. THE RULE: the room is called by the title entry with the LATEST ts (the server's clock), ties
7
+ // going to the one later in the log — so every device holding the same entries names the room the same, whatever order
8
+ // it read or rendered them in (an older page loaded later never wins). A title entry has no `text`: it is never chat.
9
+ export const TITLE_KIND = 'title'
10
+ export const TITLE_MAX = 80
11
+
12
+ /** A name as the server stores it: control characters and runs of whitespace folded, trimmed, ≤ TITLE_MAX. */
13
+ export function cleanTitle(s) {
14
+ return String(s == null ? '' : s).replace(/[\u0000-\u001f\u007f-\u009f]/g, ' ').replace(/\s+/g, ' ').trim().slice(0, TITLE_MAX)
15
+ }
16
+
17
+ export function isTitleEntry(e) {
18
+ return !!e && e.kind === TITLE_KIND && typeof e.title === 'string' && cleanTitle(e.title) !== ''
19
+ }
20
+
21
+ /** The room's name from its entries: { title, manual, by, ts, id } of the newest title entry, or null when there is none. */
22
+ export function latestTitle(entries) {
23
+ let best = null, bestTs = -Infinity
24
+ for (const e of Array.isArray(entries) ? entries : []) {
25
+ if (!isTitleEntry(e)) continue
26
+ const ts = Number(e.ts) || 0
27
+ if (ts >= bestTs) { best = e; bestTs = ts } // >= : a tie goes to the later entry
28
+ }
29
+ return best ? { title: cleanTitle(best.title), manual: !!best.manual, by: String(best.name || ''), ts: bestTs, id: best.id } : null
30
+ }
31
+
32
+ /** The line a rename shows in the conversation (a generated name shows nothing). */
33
+ export function renameLine(e) {
34
+ return `${String((e && e.name) || 'Someone').slice(0, 80)} renamed this Space to “${cleanTitle(e && e.title)}”`
35
+ }
36
+
37
+ /** The name a room's shared `title` doc gives — the fallback for a room with no title entry yet: { title, manual, at } | null. */
38
+ export function titleFromDoc(d) {
39
+ const title = d && d.state ? cleanTitle(d.state.title) : ''
40
+ return title ? { title, manual: !!d.state.manual, at: Number(d.state.at) || 0 } : null
41
+ }
42
+
43
+ /** Send a rename: `ops.title(name, by)` = op:'title' with `set` (the server appends it to the log and writes the doc).
44
+ * A server that does not take `set` yet answers without `set: true`; then `ops.writeDoc(state, summary)` writes the
45
+ * shared doc alone, as renames did before. → { took: true } when the room's log took it; { took: false, refused,
46
+ * reason } when the room refused it (only its admins may rename it); { took: false, unavailable } when nothing answered or
47
+ * the server failed (nothing stored — send it again); { took: false } after the doc-only fallback (an older server). */
48
+ export async function sendRename(ops, name, by) {
49
+ const title = cleanTitle(name); if (!title) return { took: false, refused: 'bad_request', reason: 'a name is 1–80 characters' }
50
+ let r = null
51
+ try { r = await ops.title(title, by || '') } catch { r = null }
52
+ if (r && r.status === 200 && r.set) return { took: true }
53
+ if (r && (r.status === 403 || r.status === 401 || r.error === 'stale_key')) return { took: false, refused: r.error || 'not_admin', reason: r.reason || '' }
54
+ // No answer, or the server/enclave failed (0, 5xx): NOT an older server — nothing was stored. Say so; the caller resends
55
+ // (the app keeps renamePending, the SDK throws `unavailable`). Writing the doc here would report a rename that never landed.
56
+ if (!r || !r.status || r.status >= 500) return { took: false, unavailable: true, reason: (r && r.error) || '' }
57
+ if (r.status !== 200 || r.error) return { took: false, unavailable: true, reason: r.error || '' }
58
+ try {
59
+ const saved = await ops.writeDoc({ title, manual: true, at: Date.now() }, title)
60
+ if (saved?.status === 200 && !saved.error) return { took: false, legacy: true }
61
+ if (saved?.status === 401 || saved?.status === 403) return { took: false, refused: saved.error || 'refused' }
62
+ } catch {}
63
+ return { took: false, unavailable: true }
64
+ }
65
+
66
+ /** May `email` rename a room whose sealed config is `cfg`? Where it has owners or admins, only they; otherwise anyone —
67
+ * the server's rule (op:'title' set), the same one a move follows (emailFork.js mayMove). */
68
+ export function mayRename(cfg, email) {
69
+ if (isDirect(cfg)) return false // nobody renames a direct chat: each side sees the other person's name
70
+ const lc = (v) => (Array.isArray(v) ? v : []).map((x) => String(x).trim().toLowerCase())
71
+ const owners = lc(cfg && cfg.owners && cfg.owners.emails), admins = lc(cfg && cfg.admins && cfg.admins.emails)
72
+ const me = String(email || '').trim().toLowerCase()
73
+ return !(owners.length || admins.length) || (!!me && (owners.includes(me) || admins.includes(me)))
74
+ }
75
+
76
+ // ── WHICH NAMES A ROOM GETS (the owner, 2026-10-08) ──────────────────────────────────────────────────────────────────────
77
+ // ALONE (you and the assistant, a private lane): the name follows the conversation — generated, revisited as the subject
78
+ // drifts — until you rename it; a name set by hand is never revisited. A GROUP (two or more people): named by hand at
79
+ // creation (a mandatory field), renamed by the room's admins where it has them and by anyone in a regular room; a
80
+ // rename is a line in the chat and a notification. No name is generated for a group: the one it had when it became a
81
+ // group stays until someone renames it. A DIRECT CHAT with one person (`direct: true` in its sealed config — a verified
82
+ // room of exactly two): each side sees the OTHER person's name; nobody renames it and no name is generated for it. One
83
+ // per pair (directChat.js).
84
+
85
+ /** A LANE COPY — a line mirrored from the linked shared room — and not this room's own. Its id is `sh:…`. An imported
86
+ * chat, a device-carried fork, a recreate-from-export and server-carried history also arrive through op 'mirror' with
87
+ * `source: 'shared'`, and they ARE this room's own history (sync sweep, 2026-10-10). The one rule for the app's render,
88
+ * the agent's label and every count of people. */
89
+ export const isLaneCopy = (e) => !!e && e.source === 'shared' && String(e.id == null ? '' : e.id).startsWith('sh:') && !(e.carried && typeof e.carried === 'object')
90
+
91
+ // One person, one key: their EMAIL where any of their entries shows it (a row carries it, a message does not), else
92
+ // the NAME they write under — so a post and a row are one person (sync sweep, 2026-10-10), and so are two names that one
93
+ // email wrote under. Never the signing key: each device has its own, and a phone and a laptop counted as two. Two people
94
+ // who share a name and show no email read as one here; in a verified room the ROSTER decides instead (`invited`).
95
+ function personKeyer(entries) {
96
+ const emailOf = new Map()
97
+ for (const e of entries) if (e && e.name && e.email) emailOf.set(String(e.name), String(e.email).toLowerCase())
98
+ return (e) => { const em = e.email ? String(e.email).toLowerCase() : (e.name ? emailOf.get(String(e.name)) : ''); return em ? 'e:' + em : (e.name ? 'n:' + String(e.name) : '') }
99
+ }
100
+
101
+ /** The people who have written in the room — never the assistant: each by their email where any entry shows it, else
102
+ * by the name they write under. Lane copies of the shared room's lines and generated names are not this room's people. */
103
+ export function peopleIn(entries) {
104
+ const who = new Set()
105
+ const list = Array.isArray(entries) ? entries : []
106
+ const personKey = personKeyer(list)
107
+ for (const e of list) {
108
+ if (!e || e.self || e.sys || e.kind === 'safe' || isLaneCopy(e) || e.kind === 'fork') continue
109
+ if (e.kind === TITLE_KIND && !e.manual) continue
110
+ const id = personKey(e)
111
+ if (id) who.add(id)
112
+ }
113
+ return who
114
+ }
115
+
116
+ /** May a name be GENERATED for this room? Only while one person is in it (`invited`: a verified room's roster size,
117
+ * which counts people who have not written yet) and nobody has named it by hand — in its log or in its doc. */
118
+ export function mayAutoName(entries, doc, { invited = null, direct = false } = {}) {
119
+ if (direct) return false // a direct chat is named by the other person, on each side
120
+ if (doc && doc.state && doc.state.manual) return false
121
+ const t = latestTitle(entries); if (t && t.manual) return false
122
+ // A verified room KNOWS who is in it (its roster): that number answers, whatever the log's names say (the owner's
123
+ // "roster first" rule, asyncTurn.mjs). The log is counted only where no roster number exists.
124
+ if (Number.isInteger(invited) && invited > 0) return invited <= 1
125
+ return peopleIn(entries).size <= 1
126
+ }
127
+
128
+ /** The push a rename sends: who did it, and what they did (renameLine, without the name in front). */
129
+ export function renamePreview(e) {
130
+ return { who: String((e && e.name) || 'Someone').slice(0, 80), preview: `renamed this Space to “${cleanTitle(e && e.title)}”` }
131
+ }
132
+
133
+ // ── DIRECT CHATS ─────────────────────────────────────────────────────────────────────────────────────────────────────────
134
+ /** Is the room whose sealed config is `cfg` a direct chat with one person? */
135
+ export const isDirect = (cfg) => !!(cfg && cfg.direct === true)
136
+ /** After a member change, is it still a chat between two? A third person, or a whole domain, makes it a group: its sealed
137
+ * `direct` goes, so it gets a name and no longer reads as one person (the sync sweep, 10-13 #10 — it stayed direct, titled
138
+ * by "the other person" when there were two). `allow` = the sealed list ({ emails, mh, domains }). */
139
+ export const staysDirect = (allow) => {
140
+ const a = allow || {}, n = (k) => (Array.isArray(a[k]) ? a[k].filter(Boolean).length : 0)
141
+ return !n('domains') && n('emails') + n('mh') + n('hidden') + n('users') <= 2 // users: a legacy room's @username entries are people (rosterCount counts them; agent/roomRekey.mjs holds the same rule)
142
+ }
143
+
144
+ /** The OTHER person of a direct chat, from its sealed allow-list (only these two can post — the gate checks it): an email,
145
+ * or { username, handle } for someone added by @username. `me` = this member's verified email. null when it is not a
146
+ * two-person room this member is in. */
147
+ export function directPeer(cfg, me) {
148
+ if (!isDirect(cfg)) return null
149
+ const mine = String(me || '').trim().toLowerCase()
150
+ const allow = (cfg && cfg.allow) || {}
151
+ const emails = (Array.isArray(allow.emails) ? allow.emails : []).map((e) => String(e).trim().toLowerCase()).filter(Boolean)
152
+ const users = (Array.isArray(allow.users) ? allow.users : []).filter((u) => u && u.username)
153
+ // ★ ADDED BY @USERNAME (sync sweep 10-13): that person is on the list only as a HASH of their handle (allow.hidden — the
154
+ // creator's device seals no username), so their own email is not in `emails` and the chat had no readable peer on their
155
+ // side. A device that read this sealed config passed the room's gate, so with exactly one hidden entry and one listed
156
+ // email, that email is the other person. (The creator's other devices still cannot read the hash — their recent names it.)
157
+ // stored as `allow.mh` (spaceClient create — sync sweep 11-08 #36: this read `allow.hidden`, which no config carries, so the
158
+ // @username member's side never had a peer); `hidden` is kept as a second name
159
+ const hidden = [...new Set([...(Array.isArray(allow.mh) ? allow.mh : []), ...(Array.isArray(allow.hidden) ? allow.hidden : [])].filter(Boolean))]
160
+ if (mine && !emails.includes(mine)) return (emails.length === 1 && hidden.length + users.length === 1) ? { email: emails[0] } : null
161
+ const others = emails.filter((e) => e !== mine)
162
+ if (others.length === 1 && !users.length) return { email: others[0] }
163
+ if (!others.length && users.length === 1) return { username: String(users[0].username).toLowerCase(), ...(users[0].handle ? { handle: String(users[0].handle) } : {}) }
164
+ return null
165
+ }
166
+
167
+ /** The key a person is filed under (contacts.js / address.js): the lowercased email, or "@" + the username. */
168
+ export const peerKey = (peer) => (peer && peer.email ? String(peer.email).toLowerCase() : (peer && peer.username ? '@' + String(peer.username).toLowerCase() : ''))
169
+
170
+ /** What a direct chat is called on this side: the name you saved for the person, else their @username, else their email. */
171
+ export function directTitle(peer, contactName = '') {
172
+ const n = cleanTitle(contactName)
173
+ if (n) return n
174
+ if (peer && peer.username) return '@' + peer.username
175
+ return peer && peer.email ? String(peer.email) : ''
176
+ }
177
+
package/roomPass.js ADDED
@@ -0,0 +1,256 @@
1
+ // roomPass.js — the APP'S HALF of the room pass (docs/device-gate-design.md § 4 A1–A2, revised in § 10). A device on the new
2
+ // account service holds a session key K (ECDSA P-256, NON-EXTRACTABLE, one a day), gets a ten-minute pass for it from the account
3
+ // service (POST /v2/account/room_pass, signed by the device key) and renews it in the background before it ends; every request
4
+ // to a verified Space that carries the sign-in also carries `pass` and `psig` — K's signature over { op, room, ts, nonce, the
5
+ // pass's hash, the sign-in key's nonce } (agent/roomPass.mjs verifies it). A refusal `revoked` means this device was signed out:
6
+ // `onRevoked` runs the status check, which removes the account (acctV2Check.js).
7
+ //
8
+ // Pure and injectable — each app wires it (roomPassWiring; the hosted vault's acctV2VaultWiring; a builder's vault-core) only behind
9
+ // its switch (ROOM_PASS_APP, below); nothing here runs unless asked.
10
+ // makeRoomPass({ ask(email, sessionPub) → { pass, sig, exp } (throws { code }), store?: { get(k), set(k, v) } (IndexedDB:
11
+ // a CryptoKey survives structured clone, its private half never leaves the browser), now?, onRevoked? })
12
+ export const PASS_PURPOSE = 'witbitz-room-pass'
13
+ export const REQ_PURPOSE = 'witbitz-room-req'
14
+ export const KEY_LIFE_MS = 86_400_000 // the owner, 2026-11-16: "one a day, across Spaces"
15
+ export const RENEW_BEFORE_S = 120 // a pass with less than this left is renewed before it is used
16
+ export const MAX_TS_SHIFT_MS = 86_400_000 // a caller's request time further than this from the clock here is not believed (= mkseal MAX_CLOCK_OFFSET_MS)
17
+ const STORE_KEY = 'roompass:k1'
18
+ const enc = new TextEncoder()
19
+ const b64u = (u8) => { let s = ''; for (const b of u8) s += String.fromCharCode(b); return btoa(s).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '') }
20
+ const unb64uText = (s) => { const b = atob(String(s).replace(/-/g, '+').replace(/_/g, '/')); return new TextDecoder().decode(Uint8Array.from(b, (c) => c.charCodeAt(0))) }
21
+ const subtle = () => globalThis.crypto.subtle
22
+ const canon = (o) => { if (o === null || typeof o !== 'object') return JSON.stringify(o); if (Array.isArray(o)) return '[' + o.map(canon).join(',') + ']'; return '{' + Object.keys(o).sort().map((k) => JSON.stringify(k) + ':' + canon(o[k])).join(',') + '}' }
23
+ /** = agent/spaceOidc.mjs spkNonce: base64url(SHA-256(canonical JWK)). */
24
+ export async function spkNonce (spk) { return b64u(new Uint8Array(await subtle().digest('SHA-256', enc.encode(canon(spk))))) }
25
+ const sha256hex = async (s) => [...new Uint8Array(await subtle().digest('SHA-256', enc.encode(String(s))))].map((b) => b.toString(16).padStart(2, '0')).join('')
26
+ const randNonce = () => b64u(globalThis.crypto.getRandomValues(new Uint8Array(12)))
27
+ /** = agent/roomPass.mjs psigBytes. */
28
+ export const psigBytes = ({ op, room, ts, nonce, ph, sk }) => enc.encode(REQ_PURPOSE + '\n' + JSON.stringify({ v: 1, op: String(op), room: String(room), ts, nonce: String(nonce), ph, sk }))
29
+ /** The pass's own fields (unverified here: the server is the judge) → { email, exp, sessionPub } | null. */
30
+ export const passFields = (pass) => { try { const p = JSON.parse(unb64uText(pass.p)); return p && typeof p === 'object' ? p : null } catch { return null } }
31
+
32
+ /** The sign-in a request body carries (top level, or the turn's message) → { email, spk } | null. */
33
+ export function signInOf (body) {
34
+ const m = body && body.message && typeof body.message === 'object' ? body.message : null
35
+ const tok = (body && typeof body.idToken === 'string' && body.idToken) || (m && typeof m.idToken === 'string' && m.idToken) || ''
36
+ const spk = (body && body.idToken && body.spk) || (m && m.idToken && m.spk) || null
37
+ if (!tok || !spk) return null
38
+ try { const p = JSON.parse(unb64uText(tok.split('.')[1])); const email = typeof p.email === 'string' ? p.email.trim().toLowerCase() : ''; return email.includes('@') ? { email, spk } : null } catch { return null }
39
+ }
40
+
41
+ export const REVOKED_RETRY_MS = 5 * 60_000 // after `revoked`, ask the account service again this much later (see makeRoomPass)
42
+ // WHY A REQUEST WENT WITHOUT A PASS (the owner, 2026-11-22: "yes" to fixing the bursts the Lambda's cutoff refuses — docs/TODO.md § "Lock a
43
+ // signed-out device out of rooms"). Our own apps sent requests without one in short bursts at launch (the hosted vault answered "none"
44
+ // without asking the service: its account was not there yet), and once for 10 minutes (Windows, 11-17: the service refused, and every
45
+ // refused request asked again — 365 asks in 13 minutes). So: after a refusal that says a pass is required, the renewal WAITS a little for
46
+ // this device's account (ACCOUNT_WAIT_MS); after the service refuses or does not answer, it is not asked again at once (backoff); and
47
+ // each "none" says why, once in a while, in the device's trail (`note`).
48
+ export const ACCOUNT_WAIT_MS = 8_000 // a Space said a pass is required: how long to wait for this device's account (the app may still be starting)
49
+ export const NO_ACCOUNT_QUIET_MS = 60_000 // …and not wait again for this long once a wait found none (a device with no account would wait on every request)
50
+ export const REFUSED_BACKOFF_MS = 60_000 // the account service refused a pass: asked again after this, not on every refused request
51
+ export const FAILED_BACKOFF_MS = 10_000 // the account service did not answer (the network, a 5xx): asked again after this
52
+ export const NOTE_EVERY_MS = 30_000 // the same trail line at most this often
53
+
54
+ /** `get` (sync or async) until it gives something, or `ms` has passed → it | null. Never throws. */
55
+ export async function waitFor (get, { ms = ACCOUNT_WAIT_MS, step = 200, now = () => Date.now(), sleep = (t) => new Promise((r) => setTimeout(r, t)) } = {}) {
56
+ const until = now() + ms
57
+ for (;;) {
58
+ let v = null
59
+ try { v = await get() } catch { v = null }
60
+ if (v) return v
61
+ if (now() >= until) return null
62
+ await sleep(step)
63
+ }
64
+ }
65
+ /** A trail writer that says the same line at most once per `ms`. `note` absent → says nothing. */
66
+ export function makeNoter (note, { ms = NOTE_EVERY_MS, now = () => Date.now() } = {}) {
67
+ const last = new Map()
68
+ return (line) => {
69
+ if (typeof note !== 'function') return
70
+ const t = now()
71
+ if (t - (last.get(line) || 0) < ms) return
72
+ last.set(line, t)
73
+ try { note(String(line)) } catch { /* a trail line is never worth an error */ }
74
+ }
75
+ }
76
+ const askWhy = (err) => String((err && (err.code || (err.status ? 'http_' + err.status : err.message))) || 'no answer').slice(0, 60)
77
+ const refusedByService = (err) => !!err && (err.code === 'no_pass' || (Number(err.status) >= 400 && Number(err.status) < 500 && ![408, 425, 429].includes(Number(err.status))))
78
+
79
+ export function makeRoomPass ({ ask, store = null, now = () => Date.now(), onRevoked = null, note = null } = {}) {
80
+ const say = makeNoter(note, { now })
81
+ let backoffUntil = 0, backoffWhy = '' // the service refused or did not answer: not asked again before this
82
+ let backoffRetryable = false
83
+ let keyP = null // → { priv, pub (JWK), at }
84
+ const passes = new Map() // email → { pass: { p, s }, exp } | { p: Promise }
85
+ let revokedAt = 0 // when the account service last said `revoked` (0: never)
86
+ // ★ NOT FOR THE SESSION (2026-11-16): a `revoked` answer stopped every later ask until a reload — and the account service once
87
+ // answered it to devices that were NOT signed out (a migrated account's provisional devices, fixed 43806abe5), so they stayed
88
+ // refused by the cutoff until relaunched. Now the ask goes again after REVOKED_RETRY_MS. A device really signed out is wiped
89
+ // by the status check onRevoked starts, so its maker is gone long before; one ask every few minutes is all it costs.
90
+ const revoked = () => revokedAt > 0 && now() - revokedAt < REVOKED_RETRY_MS
91
+
92
+ async function freshKey () {
93
+ const kp = await subtle().generateKey({ name: 'ECDSA', namedCurve: 'P-256' }, false, ['sign', 'verify']) // the private half: non-extractable
94
+ const j = await subtle().exportKey('jwk', kp.publicKey)
95
+ const k = { priv: kp.privateKey, pub: { kty: 'EC', crv: 'P-256', x: j.x, y: j.y }, at: now() }
96
+ if (store) { try { await store.set(STORE_KEY, k) } catch { /* memory only: a new key at the next start */ } }
97
+ return k // a pass names the key it was made for (kx): one made for an older key is never used with this one
98
+ }
99
+ async function sessionKey () {
100
+ if (keyP) { const k = await keyP.catch(() => null); if (k && now() - k.at < KEY_LIFE_MS) return k; keyP = null }
101
+ keyP = (async () => {
102
+ if (store) { try { const k = await store.get(STORE_KEY); if (k && typeof CryptoKey !== 'undefined' && k.priv instanceof CryptoKey && k.pub && now() - k.at < KEY_LIFE_MS) return k } catch { /* a new one */ } } // a CryptoKey a sealing store turned into {} is no key
103
+ return freshKey()
104
+ })()
105
+ return keyP
106
+ }
107
+ /** The pass for this address and the CURRENT session key → { p, s } (renewed when under RENEW_BEFORE_S left). Concurrent asks share
108
+ * one request (even the first one, while the key is being made). Throws { code } — `revoked` after onRevoked. */
109
+ async function passFor (email, { force = false } = {}) {
110
+ if (revoked()) throw Object.assign(new Error('revoked'), { code: 'revoked' })
111
+ const e = String(email || '').trim().toLowerCase()
112
+ const k = await sessionKey()
113
+ if (revoked()) throw Object.assign(new Error('revoked'), { code: 'revoked' })
114
+ const kx = k.pub.x
115
+ const hit = passes.get(e)
116
+ if (!force && hit && hit.pass && hit.kx === kx && hit.exp - RENEW_BEFORE_S > now() / 1000) return hit.pass
117
+ if (hit && hit.p && hit.pk === kx) return hit.p // already asked for this key
118
+ if (now() < backoffUntil) throw Object.assign(new Error('backoff'), { code: 'backoff', why: backoffWhy, retryable: backoffRetryable }) // the service refused or did not answer a moment ago
119
+ const p = (async () => {
120
+ let r
121
+ try {
122
+ r = await ask(e, k.pub)
123
+ if (!r || typeof r.pass !== 'string' || typeof r.sig !== 'string') throw Object.assign(new Error('no_pass'), { code: 'no_pass' })
124
+ } catch (err) {
125
+ if (err && err.code === 'revoked') { revokedAt = now(); passes.clear(); try { const x = onRevoked && onRevoked(); if (x && typeof x.catch === 'function') x.catch(() => {}) } catch { /* the status check runs at the next launch too */ } } // not awaited: the status check may wait on the very request asking (a vault's worker drops the account's rooms)
126
+ else {
127
+ const refused = refusedByService(err), wait = refused ? REFUSED_BACKOFF_MS : FAILED_BACKOFF_MS
128
+ backoffUntil = now() + wait; backoffWhy = askWhy(err); backoffRetryable = !refused
129
+ say(`room pass: the account service ${refused ? 'refused a pass' : 'did not answer'} (${backoffWhy}) — asked again in ${Math.round(wait / 1000)} s`)
130
+ }
131
+ throw err
132
+ }
133
+ backoffUntil = 0
134
+ const pass = { p: r.pass, s: r.sig }
135
+ passes.set(e, { pass, exp: Number(r.exp) || 0, kx })
136
+ return pass
137
+ })()
138
+ passes.set(e, { ...(hit && hit.pass ? { pass: hit.pass, exp: hit.exp, kx: hit.kx } : {}), p, pk: kx }) // a renewal keeps the pass it replaces until the new one is here
139
+ try { return await p } catch (err) { const h = passes.get(e); if (h && h.p === p) { if (h.pass && h.exp > now() / 1000) passes.set(e, { pass: h.pass, exp: h.exp, kx: h.kx }); else passes.delete(e) } throw err }
140
+ }
141
+ /** psig for one request. */
142
+ // `at`: the request's time as the CALLER knows it — spaceClient's sealNow(), this device's clock corrected by the server's (mkseal.js;
143
+ // sync sweep 2026-11-16 #8: a device whose clock was off by more than 2 minutes had every request that carried a pass refused).
144
+ // Asked from another realm (a key worker), so taken from the ask; more than a day from this clock = not believed, this clock signs.
145
+ async function sign ({ op, room, spk, pass, key = null, at }) {
146
+ const k = key || await sessionKey()
147
+ const t = Number(at)
148
+ const ts = Number.isFinite(t) && t > 0 && Math.abs(t - now()) <= MAX_TS_SHIFT_MS ? Math.round(t) : now(), nonce = randNonce()
149
+ const sig = new Uint8Array(await subtle().sign({ name: 'ECDSA', hash: 'SHA-256' }, k.priv, psigBytes({ op, room, ts, nonce, ph: await sha256hex(pass.p), sk: await spkNonce(spk) })))
150
+ return { ts, nonce, sig: b64u(sig) }
151
+ }
152
+ /** The fields to add to a request body that carries a sign-in → { pass, psig } | {} (no sign-in, or no pass to be had: the
153
+ * request goes as before and the server decides — with the cutoff on it refuses, and the next request asks again). */
154
+ async function fieldsFor (body, { ts } = {}) {
155
+ const si = signInOf(body)
156
+ if (!si || !body) return {}
157
+ return fieldsForSignIn({ op: body.op, room: body.room, email: si.email, spk: si.spk, ts })
158
+ }
159
+ /** The same, from its parts (the key worker asks the page with these: l1.js ROOM_PASS_AUTH). */
160
+ async function fieldsForSignIn ({ op, room, email, spk, ts }) {
161
+ if (typeof op !== 'string' || !op || typeof room !== 'string' || !room || !email || !spk) return {}
162
+ try {
163
+ const pass = await passFor(email)
164
+ const key = await sessionKey() // the key that pass was made for (passFor took it a moment ago)
165
+ if (!passFields(pass) || !passFields(pass).sessionPub || passFields(pass).sessionPub.x !== key.pub.x) { say('room pass: none this once (the day\'s session key changed)'); return {} } // the day's key changed in between: none this once
166
+ return { pass, psig: await sign({ op, room, spk, pass, key, at: ts }) }
167
+ } catch (err) { say(`room pass: none for this request (${err && err.code === 'backoff' ? 'waiting after: ' + err.why : askWhy(err)})`); return {} }
168
+ }
169
+ /** Renew in the background while in use (the app calls it from its timer) — and at once after a sign-out of the others. */
170
+ async function renew (email) {
171
+ try { await passFor(email, { force: true }); return {} }
172
+ catch (err) {
173
+ const retryable = err?.code === 'backoff' ? err.retryable : err?.code !== 'revoked' && !refusedByService(err)
174
+ return retryable ? { retryable: true } : {}
175
+ }
176
+ }
177
+ return { passFor, sign, fieldsFor, fieldsForSignIn, renew, sessionKey, revoked, forget: () => { passes.clear(); keyP = null } }
178
+ }
179
+
180
+ // ── THE SWITCH AND THE ASKS, shared by the three places a pass is made (2026-11-16, the owner: "Hosted + SDK passes, then roll out"):
181
+ // the regular app's page (roomPassWiring.js), the hosted app's VAULT (acctV2VaultWiring.js / vault-loader.js — the frame holds no
182
+ // device key, so the vault makes its passes) and a builder's vault (vault-core.js). One switch for all three.
183
+ export const ROOM_PASS_APP = true // ⚑ THE APPS' SWITCH — ON since 2026-11-16 (owner: "Rollout 1-7"; docs/device-gate-design.md § 11 step 5): every app (regular, the hosted vault, a builder's vault) sends room passes
184
+ export const ROOM_PASS_TEST_KEY = 'space:roompass' // '1' on one device = on there, for a test
185
+ export const ROOM_PASS_AUTH = '#room-pass' // not a room id (those never start with '#'): a key worker's ask, ROOM_PASS_AUTH + ':' + JSON
186
+ export const isRoomPassAsk = (name) => typeof name === 'string' && name.startsWith(ROOM_PASS_AUTH + ':')
187
+ // A key worker asks its page (or vault) to renew a room's sign-in so it names its app (a Space answered `pass: app_unnamed`):
188
+ // SIGNIN_RENEW_AUTH + ':' + the room → { idToken, spk } | {}.
189
+ export const SIGNIN_RENEW_AUTH = '#signin-renew'
190
+ export const isSigninRenewAsk = (name) => typeof name === 'string' && name.startsWith(SIGNIN_RENEW_AUTH + ':')
191
+ export const signinRenewRoom = (name) => (isSigninRenewAsk(name) ? String(name).slice(SIGNIN_RENEW_AUTH.length + 1) : '')
192
+ /** On: the apps' switch, or the test switch '1' in any of `stores` (each { getItem } — a store that throws is unread). '0' in any of
193
+ * them turns passes OFF on this device whatever the apps' switch says — for a test, or a device to step back by hand. */
194
+ export function roomPassSwitchOn (...stores) {
195
+ const vals = stores.map((s) => { try { return s && typeof s.getItem === 'function' ? s.getItem(ROOM_PASS_TEST_KEY) : null } catch { return null } })
196
+ if (vals.includes('0')) return false
197
+ return ROOM_PASS_APP || vals.includes('1')
198
+ }
199
+ /** A key worker's ask (ROOM_PASS_AUTH + ':' + JSON { op, room, email, spk } | { renew, email }), answered with `maker` (makeRoomPass, or
200
+ * null = off) → { pass, psig } | {}. Never throws. */
201
+ export async function answerRoomPassAsk (maker, name) {
202
+ try {
203
+ if (!maker || !isRoomPassAsk(name)) return {}
204
+ const q = JSON.parse(String(name).slice(ROOM_PASS_AUTH.length + 1))
205
+ if (!q || typeof q !== 'object') return {}
206
+ if (q.renew) return await maker.renew(String(q.email || '')) || {}
207
+ return await maker.fieldsForSignIn({ op: q.op, room: q.room, email: String(q.email || ''), spk: q.spk, ...(Number.isFinite(q.ts) ? { ts: q.ts } : {}) })
208
+ } catch { return {} }
209
+ }
210
+ /**
211
+ * One account's passes, made where its device key is: `on()` the switch; `account()` → { id (the account on the service), ask(email,
212
+ * sessionPub) → { pass, sig, exp }, onRevoked?() } | null (no account on the new service here). A new account (another id) gets a new
213
+ * session key and no pass of the one before; a signed-out one stops asking (makeRoomPass).
214
+ * → { maker() → makeRoomPass | null, client (spaceClient's `roomPass`), answer(name) (a key worker's ask), renewNow(email) }
215
+ */
216
+ export function makeRoomPassHolder ({ on, account, note = null, now = () => Date.now(), sleep } = {}) {
217
+ let cur = null // { id, m }
218
+ const say = makeNoter(note, { now })
219
+ const maker = () => {
220
+ try {
221
+ if (!on()) return null
222
+ const a = account()
223
+ if (!a || !a.id || typeof a.ask !== 'function') return null
224
+ if (!cur || cur.id !== a.id) cur = { id: a.id, m: makeRoomPass({ ask: a.ask, onRevoked: a.onRevoked || null, note, now }) }
225
+ return cur.m
226
+ } catch { return null }
227
+ }
228
+ const whenAccount = makeAccountWait(maker, { on, say, now, sleep })
229
+ const none = () => { try { if (on()) say('room pass: none — this device has no account on the new account service (yet)') } catch { /* */ } return {} }
230
+ return {
231
+ maker,
232
+ client: {
233
+ fieldsFor: async (body, o) => { if (!signInOf(body)) return {}; const m = maker(); return m ? m.fieldsFor(body, o) : none() }, // o: { ts } — the request's time (sign)
234
+ renew: async (body) => { const si = signInOf(body); const m = si ? await whenAccount() : null; if (m) return m.renew(si.email) }, // a Space said a pass is required: wait a little for the account
235
+ },
236
+ answer: async (name) => { if (isRenewAsk(name)) return answerRoomPassAsk(await whenAccount(), name); const m = maker(); return m ? answerRoomPassAsk(m, name) : (isRoomPassAsk(name) ? none() : {}) },
237
+ renewNow: async (email) => { try { const m = maker(); if (m && email) await m.renew(email) } catch { /* the next request asks */ } },
238
+ }
239
+ }
240
+ /** A key worker's ask that is a renewal ({ renew, email }) — the one sent after a Space answered that a pass is required. */
241
+ export const isRenewAsk = (name) => { try { return isRoomPassAsk(name) && !!JSON.parse(String(name).slice(ROOM_PASS_AUTH.length + 1)).renew } catch { return false } }
242
+ /** The account to renew with, waited for (ACCOUNT_WAIT_MS) when there is none yet — the app may still be starting — and not waited for
243
+ * again for NO_ACCOUNT_QUIET_MS once a wait found none. `maker` sync or async → it | null. */
244
+ export function makeAccountWait (maker, { on = () => true, say = () => {}, now = () => Date.now(), sleep, ms = ACCOUNT_WAIT_MS } = {}) {
245
+ let quietUntil = 0
246
+ return async () => {
247
+ let m = null
248
+ try { m = await maker() } catch { m = null }
249
+ if (m) return m
250
+ try { if (!on()) return null } catch { return null }
251
+ if (now() < quietUntil) return null
252
+ m = await waitFor(maker, { ms, now, ...(sleep ? { sleep } : {}) })
253
+ if (!m) { quietUntil = now() + NO_ACCOUNT_QUIET_MS; say(`room pass: a Space required a pass, and this device has no account on the new account service to ask with (waited ${Math.round(ms / 1000)} s)`) }
254
+ return m
255
+ }
256
+ }