@witbitz/sdk 0.0.0-stage → 4.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +20 -2
- package/a2aCore.js +200 -0
- package/a2aShared.js +27 -0
- package/accountErase.js +223 -0
- package/accountIndexDoc.js +122 -0
- package/accountOwner.js +59 -0
- package/accountRecord.js +90 -0
- package/accountScope.js +114 -0
- package/accountSeal.js +42 -0
- package/accountStores.js +173 -0
- package/acctV2App.js +619 -0
- package/acctV2Check.js +29 -0
- package/acctV2Client.js +382 -0
- package/acctV2Keys.js +43 -0
- package/acctV2Legacy.js +14 -0
- package/acctV2Switch.js +80 -0
- package/acctV2UiCore.js +857 -0
- package/acctV2WebAuthn.js +61 -0
- package/acctV2Wire.js +59 -0
- package/address.js +42 -0
- package/attestedBox.js +30 -0
- package/attestedRooms.js +78 -0
- package/awsKey.js +98 -0
- package/backupRecord.js +106 -0
- package/backupVault.js +97 -0
- package/blocks.js +115 -0
- package/blocksPush.js +64 -0
- package/browseSeal.js +103 -0
- package/cbor.js +225 -0
- package/changePush.js +75 -0
- package/chatLock.js +149 -0
- package/chatLockSw.js +13 -0
- package/cloudDeviceBuilds.js +11 -0
- package/cloudDevicePins.js +33 -0
- package/cloudDeviceSeal.js +53 -0
- package/codeBrowse.js +224 -0
- package/codeCloud.js +652 -0
- package/codeCloudKeys.js +112 -0
- package/codeCommands.js +167 -0
- package/codeComputers.js +388 -0
- package/codeEgress.js +123 -0
- package/codeFilesRoutes.js +17 -0
- package/codeMkdir.js +8 -0
- package/codeModes.js +57 -0
- package/codeOrphanKeys.js +42 -0
- package/codeOutputs.js +141 -0
- package/codeRelay.js +505 -0
- package/codeSentinel.js +86 -0
- package/codeTransport.js +295 -0
- package/codeUndo.js +48 -0
- package/compress.js +24 -0
- package/config.js +11 -0
- package/connCatalog.js +164 -0
- package/connDisp.js +76 -0
- package/connOtherWays.js +74 -0
- package/connPending.js +16 -0
- package/connWrap.js +53 -0
- package/connectionEntry.js +89 -0
- package/connections.js +562 -0
- package/credits.js +30 -0
- package/csAttest.js +112 -0
- package/decrypt.html +384 -0
- package/deviceAttest.js +521 -0
- package/deviceCall.js +54 -0
- package/deviceKeyCore.js +41 -0
- package/deviceSeal.js +59 -0
- package/e2ee.js +323 -0
- package/eat.js +103 -0
- package/emailFork.js +275 -0
- package/emailSignIn.js +81 -0
- package/emptySpaces.js +111 -0
- package/encSource.js +55 -0
- package/enclaveAccept.js +214 -0
- package/enclaveClaim.js +241 -0
- package/enclaveRoute.js +102 -0
- package/enclaveSnapshotMerge.js +44 -0
- package/entrySig.js +165 -0
- package/env.js +73 -0
- package/eraseFile.js +58 -0
- package/followImage.js +86 -0
- package/healNames.js +45 -0
- package/idb.js +97 -0
- package/idbSeal.js +119 -0
- package/indexGone.js +12 -0
- package/invite.js +51 -0
- package/inviteEnroll.js +67 -0
- package/inviteSend.js +68 -0
- package/jobAgents.js +87 -0
- package/keptMerge.js +84 -0
- package/l1-worker-src.js +2 -0
- package/l1-worker.js +831 -0
- package/laneConfig.js +57 -0
- package/laneLinkCore.js +177 -0
- package/ledgerView.js +64 -0
- package/manifest.json +220 -0
- package/mcpRecommended.js +25 -0
- package/memberChange.js +123 -0
- package/mkseal.js +101 -0
- package/nativePush.js +153 -0
- package/nitroVerify.js +220 -0
- package/noble-p256.js +27 -0
- package/notice.js +116 -0
- package/notifKey.js +58 -0
- package/offlineBundle.js +62 -0
- package/ohttp.js +177 -0
- package/opencodeWire.js +282 -0
- package/oprf.js +70 -0
- package/ownAgentLink.js +96 -0
- package/ownerPolicy.js +117 -0
- package/package.json +254 -4
- package/pollVerdict.js +33 -0
- package/prefetchPoll.js +60 -0
- package/protectedLocal.js +410 -0
- package/pushCore.js +42 -0
- package/recovery.js +107 -0
- package/regions.js +42 -0
- package/removedMessage.js +11 -0
- package/renameRefusal.js +9 -0
- package/replyQuote.js +34 -0
- package/reqEnvelope.js +126 -0
- package/roomDefaultPrefs.js +76 -0
- package/roomDelete.js +109 -0
- package/roomName.js +177 -0
- package/roomPass.js +256 -0
- package/roomRoster.js +289 -0
- package/roomSettings.js +61 -0
- package/roomState.js +58 -0
- package/roomStreamClient.js +115 -0
- package/rosterCount.js +49 -0
- package/rosterHash.js +13 -0
- package/rowSchema.js +113 -0
- package/safeMedia.js +116 -0
- package/safeMediaPins.js +17 -0
- package/schedulesDoc.js +78 -0
- package/sdkA2A.js +404 -0
- package/sdkAccount.js +470 -0
- package/sdkAccountDoc.js +81 -0
- package/sdkAccountSections.js +223 -0
- package/sdkAgui.js +141 -0
- package/sdkAttest.js +34 -0
- package/sdkBackup.js +480 -0
- package/sdkBackupV2.js +630 -0
- package/sdkBrowserPrivate.js +28 -0
- package/sdkBuilds.js +208 -0
- package/sdkCloudDevice.js +215 -0
- package/sdkComputers.js +480 -0
- package/sdkDictation.js +142 -0
- package/sdkErase.js +283 -0
- package/sdkExports.js +69 -0
- package/sdkInvitations.js +34 -0
- package/sdkKeptAgent.js +188 -0
- package/sdkLaneLink.js +205 -0
- package/sdkPlan.js +94 -0
- package/sdkProtect.js +228 -0
- package/sdkRedact.js +36 -0
- package/sdkRekey.js +307 -0
- package/sdkReport.js +68 -0
- package/sdkSafeMedia.js +255 -0
- package/sdkSchedules.js +39 -0
- package/sdkSpeech.js +54 -0
- package/sdkTurn.js +117 -0
- package/sdkVault.js +124 -0
- package/sealShare.js +18 -0
- package/sealedNames.js +64 -0
- package/sealedReceipt.js +17 -0
- package/sentinelRelease.js +154 -0
- package/shamir.js +85 -0
- package/sharedViews.js +38 -0
- package/sheetChrome.js +450 -0
- package/siri.js +171 -0
- package/spaceClient.js +1418 -0
- package/spaceConfig.js +81 -0
- package/spaceEmailGate.js +813 -0
- package/spaceExport.js +125 -0
- package/spaceFork.js +216 -0
- package/spaceLock.js +358 -0
- package/spacePasskey.js +180 -0
- package/speechOut.js +100 -0
- package/splitKeyClient.js +90 -0
- package/store.js +587 -0
- package/streamHint.js +36 -0
- package/sttCloud.js +220 -0
- package/sttWorklet.js +38 -0
- package/sw-notif-core.js +538 -0
- package/tempList.js +48 -0
- package/tinfoilVerifier.js +78 -0
- package/toolBooks.js +31 -0
- package/toolRules.js +52 -0
- package/turnCerts.js +254 -0
- package/turnFeed.js +58 -0
- package/turnVerdict.js +36 -0
- package/usageReceipts.js +176 -0
- package/usageSummary.js +90 -0
- package/util.js +181 -0
- package/vault-core.js +1958 -0
- package/vault-kit.mjs +354 -0
- package/vault-screens.js +263 -0
- package/vaultAtRest.js +177 -0
- package/vaultCoreLock.js +111 -0
- package/vaultCorePush.js +140 -0
- package/vaultDeviceKey.js +95 -0
- package/vaultEnclaveHandoff.js +114 -0
- package/vaultKeep.js +281 -0
- package/vaultSealedStore.js +77 -0
- package/vaultWorkerHost.js +98 -0
- package/vcWorker.js +34 -0
- package/voiceAttest.js +50 -0
- package/voiceCert.js +51 -0
- package/witbitz-admin.d.ts +135 -0
- package/witbitz-admin.js +529 -0
- package/witbitz-admin.mjs +1459 -0
- package/witbitz-sdk.d.ts +1106 -0
- package/witbitz-sdk.js +3835 -0
- package/workerClient.js +16 -0
- package/workerLiveness.js +21 -0
- package/x509.js +218 -0
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
|
+
}
|
package/roomRoster.js
ADDED
|
@@ -0,0 +1,289 @@
|
|
|
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 verifiedPosters(entries, seen) {
|
|
5
|
+
const posters = []
|
|
6
|
+
for (const e of entries || []) {
|
|
7
|
+
const point = e?.spk || e?.vspk
|
|
8
|
+
if (e?.verified !== true || e.self || e.kind === 'agent' || !point?.x || !point?.y) continue
|
|
9
|
+
const id = point.x + '.' + point.y
|
|
10
|
+
const person = Object.prototype.hasOwnProperty.call(seen, id) ? seen[id] : null
|
|
11
|
+
if (person?.left) continue
|
|
12
|
+
const owner = person?.swapped ? null : person
|
|
13
|
+
const email = owner?.email || (e.emailNameVerified === true ? String(e.name || '').trim().toLowerCase() : '')
|
|
14
|
+
const user = owner?.user || e.user || ''
|
|
15
|
+
if (email || user) posters.push({ email, user })
|
|
16
|
+
}
|
|
17
|
+
return posters
|
|
18
|
+
}
|
|
19
|
+
// roomRoster.js — the room's guest book: everyone who ANNOUNCED themselves, in join order.
|
|
20
|
+
//
|
|
21
|
+
// A public room's only credential is the link, so reading it is an unauthenticated poll (`spaceService.mjs` op
|
|
22
|
+
// 'poll' — no gate) and nothing can make a visitor announce. ★ THIS LIST THEREFORE MEANS "PEOPLE WHO ANNOUNCED
|
|
23
|
+
// THEMSELVES", NEVER "EVERYONE WHO OPENED THIS ROOM", and the UI must say so. A lurker with the link is invisible by
|
|
24
|
+
// construction, not by oversight; a design that implied otherwise would be handing someone a number that looks like
|
|
25
|
+
// attendance and is really politeness. If you need the stronger claim, that is an email/invite-gated room, where
|
|
26
|
+
// every READ carries an identity before the server serves a byte — not this.
|
|
27
|
+
//
|
|
28
|
+
// Two rules do the real work here, and neither may bend:
|
|
29
|
+
// 1. A GUEST IS NEVER SHOWN A NAME THEY CHOSE. Anyone with the link can type "Alon". Guests get an ordinal, and
|
|
30
|
+
// only an entry the SERVER attested (grant-bound `from`, see spaceService.mjs) may carry a name.
|
|
31
|
+
// 2. A LABEL MEANS THE SAME THING TO EVERY VIEWER. Labels are DERIVED from join order, never stored, so two
|
|
32
|
+
// devices reading the same doc agree without coordinating and without asking the server.
|
|
33
|
+
//
|
|
34
|
+
// Storage is one mk-sealed `state` doc (l1.state(room, ROSTER_DOC)) — the transport liveLocation already uses: a
|
|
35
|
+
// turn-less write that never wakes the agent, and opaque to the server. ⚑ `state` is last-writer-wins on the WHOLE
|
|
36
|
+
// doc, so two people joining at once can clobber each other. There is no lock; instead every client re-asserts
|
|
37
|
+
// itself on every open and `mergeRoster` restores what was lost — see the self-healing tests.
|
|
38
|
+
// ⚑ And never put any of this in the op's `by` field: that one is cleartext to the server.
|
|
39
|
+
|
|
40
|
+
export const ROSTER_DOC = 'roster'
|
|
41
|
+
export const MAX_ENTRIES = 200 // every byte is written by someone holding the link; bound the griefer, keep the early
|
|
42
|
+
|
|
43
|
+
// An id is either a GUEST's local marker (`meId()` — 'm-' + 8 chars) or a MEMBER's signing key as `jkey(spk)`,
|
|
44
|
+
// which is `${jwk.x}.${jwk.y}` — 43 + 1 + 43 = 87 characters for P-256. ★ This cap was 64, so every signed-in member
|
|
45
|
+
// failed `isId`, `ensureSelf` returned `changed: false`, and NO WRITE WAS EVER ATTEMPTED — a silent no-op that reads
|
|
46
|
+
// exactly like "nobody has announced yet". It excluded precisely the people the guest book exists to attest: the
|
|
47
|
+
// `verified` row, with a real name instead of an ordinal, is reachable ONLY with a jkey id. Found 2026-09-21 on a
|
|
48
|
+
// live room whose doc was still v0 while guests demonstrably wrote fine. The id must stay the jkey verbatim —
|
|
49
|
+
// openWho matches it against `deriveRoster(entries).map(jkey)` — so the CAP is what was wrong, not the id. Still
|
|
50
|
+
// bounded (this is a griefer bound, and MAX_ENTRIES × 128 B is a small doc). spaces/test/roomRoster.test.mjs.
|
|
51
|
+
const MAX_ID = 128
|
|
52
|
+
const isId = (v) => typeof v === 'string' && !!v && v.length <= MAX_ID
|
|
53
|
+
// A name from the doc is UNTRUSTED INPUT — written by anyone holding the link. Bounded and trimmed here; rendered
|
|
54
|
+
// with textContent, never as markup; and it gains no standing from being stored.
|
|
55
|
+
const cleanName = (v) => (typeof v === 'string' && v.trim() ? v.trim().replace(/\s+/g, ' ').slice(0, 40) : undefined)
|
|
56
|
+
/** One stored row, sanitized. A name is kept whether or not it was attested — `verified` is what separates them. */
|
|
57
|
+
function clean (e) {
|
|
58
|
+
if (!e || typeof e !== 'object') return null
|
|
59
|
+
if (!isId(e.id) || !Number.isFinite(e.at)) return null
|
|
60
|
+
const out = { id: e.id, at: e.at }
|
|
61
|
+
const nm = cleanName(e.name)
|
|
62
|
+
if (nm) out.name = nm
|
|
63
|
+
if (e.verified === true) out.verified = true
|
|
64
|
+
return out
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
const rows = (roster) => (Array.isArray(roster) ? roster : Array.isArray(roster?.people) ? roster.people : []).map(clean).filter(Boolean)
|
|
68
|
+
// Join order, with the id as a tiebreak: two devices can stamp the same millisecond, and without this two viewers
|
|
69
|
+
// could number them oppositely — which would quietly break the one promise a label makes.
|
|
70
|
+
const byJoin = (a, b) => (a.at - b.at) || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0)
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Add this device to the roster if it is not already there. Idempotent ON PURPOSE: re-opening a room must not
|
|
74
|
+
* rewrite the doc, because every write is a chance to clobber someone who joined at the same moment.
|
|
75
|
+
* @returns {{roster: object[], changed: boolean}} — write only when `changed`.
|
|
76
|
+
*/
|
|
77
|
+
/** The key of a JWK, the way spaceFork.jkey names it — the id an attested row is matched to the ledger by. */
|
|
78
|
+
export const keyOf = (jwk) => (jwk && jwk.x && jwk.y) ? `${jwk.x}.${jwk.y}` : ''
|
|
79
|
+
|
|
80
|
+
/** WHAT A DEVICE ANNOUNCES ITSELF AS. Under a signing key the READER can attest against the ledger (a server-verified
|
|
81
|
+
* entry signed by that key), or as a bare device id shown as an ordinal. Two keys count, in this order:
|
|
82
|
+
* grantSpk — the invite-grant identity (an invited member)
|
|
83
|
+
* signPub — the EMAIL-gate signing key (identity.js recallSign): what a member of a verified room actually posts
|
|
84
|
+
* with. ★ This one was missing (2026-09-26, "so why is Tomer unverified?"): announceSelf read only the
|
|
85
|
+
* grant, so in an email-gated room every member announced a bare id no ledger key could ever match, and
|
|
86
|
+
* the sheet called them "unverified" however much they had posted.
|
|
87
|
+
* The `verified` on the row is a CLAIM the reader re-checks (listRoster's `attested`); the name is what the person
|
|
88
|
+
* goes by here. */
|
|
89
|
+
// ★ In a VERIFIED room the sign-in key wins (2026-10-04, sp-294n…): the server records each gate sign-in under the key
|
|
90
|
+
// the request was SIGNED with (spaceService `roster_seen`, keyed by req.spk = signPub), so a creator or invited device
|
|
91
|
+
// that announced under its grant key wrote a row the server's record never matched.
|
|
92
|
+
export function selfRow ({ grantSpk = null, signPub = null, deviceId = '', name = '', gated = false } = {}) {
|
|
93
|
+
const key = gated ? (keyOf(signPub) || keyOf(grantSpk)) : (keyOf(grantSpk) || keyOf(signPub))
|
|
94
|
+
return key ? { id: key, name: name || '', verified: true } : { id: deviceId, name: name || '' }
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** THE MEMBERS VIEW OF A VERIFIED ROOM (owner, 2026-09-26: "for verified rooms it should be Members, and in there it can
|
|
98
|
+
* show the status"). A room with an email gate has a LIST of who may post (advertised emails / @usernames in the clear,
|
|
99
|
+
* hidden ones as room-salted hashes, whole domains), and the server vouches for whoever passed the gate (`seen`). So the
|
|
100
|
+
* sheet is not "who's been here" but "who is a member, and where each of them stands":
|
|
101
|
+
* signed in — the gate verified them here (seen), or a server-badged ledger entry carries their key (named)
|
|
102
|
+
* not yet opened — on the list, no sighting yet
|
|
103
|
+
* allowed — a whole domain
|
|
104
|
+
* unverified — a typed name the server never vouched for (a guest row in a gated room)
|
|
105
|
+
* Hidden entries cannot be named, only counted. `rows` = listRoster(...) output; `seenIdentity(id)` → "@user" | email | "". */
|
|
106
|
+
// `onList(email, user)` (verifiedMove.stillOnList): a room re-keyed in place keeps its guest book and its history, so a REMOVED
|
|
107
|
+
// member still has rows and posts — they are not members. Absent (a room never re-keyed): every sighting is a member, as before.
|
|
108
|
+
export function membersView ({ allow = {}, rows = [], seenIdentity = () => '', seenPerson = null, posters = [], myEmail = '', mineId = '', myName = '', hiddenUnseen = null, seenHandles = new Set(), onList = null } = {}) {
|
|
109
|
+
const norm = (s) => String(s || '').trim().toLowerCase()
|
|
110
|
+
const me = norm(myEmail)
|
|
111
|
+
// ONE ROW PER PERSON (2026-10-04, sp-294n…: four "@alice" rows for one person on four keys, and both listed emails
|
|
112
|
+
// "not yet opened" — the owner's own and an account with five verified posts). A row is a signing KEY, and every
|
|
113
|
+
// device, app and reinstall makes its own; the person is the verified EMAIL the server recorded beside the key.
|
|
114
|
+
// `seenPerson(id)` → { email, user } (the older `seenIdentity(id)` → "@user" | email still works, with less to match).
|
|
115
|
+
const personOf = (id) => {
|
|
116
|
+
if (seenPerson) { const p = seenPerson(id); return p && (p.email || p.user) ? { email: norm(p.email), user: String(p.user || '').replace(/^@/, '') } : null }
|
|
117
|
+
const s = String(seenIdentity(id) || ''); if (!s) return null
|
|
118
|
+
return s.startsWith('@') ? { email: '', user: s.slice(1) } : { email: norm(s), user: '' }
|
|
119
|
+
}
|
|
120
|
+
const people = new Map() // key → { email, user, label, me, id }
|
|
121
|
+
const add = (key, p) => {
|
|
122
|
+
const had = people.get(key)
|
|
123
|
+
if (had) { had.email ||= p.email; had.user ||= p.user; had.me ||= p.me; return }
|
|
124
|
+
people.set(key, { ...p })
|
|
125
|
+
}
|
|
126
|
+
for (const r of rows) {
|
|
127
|
+
const p = personOf(r.id)
|
|
128
|
+
const isMe = r.id === mineId || (!!me && !!p && p.email === me)
|
|
129
|
+
// A verified room lists MEMBERS: a row nobody vouched for (a typed name — a reader with the link, or a device that
|
|
130
|
+
// announced before it had its key) is not a member and is not shown. The owner read "Tomer · unverified" beside a
|
|
131
|
+
// list that admits Tomer as "Tomer is not verified"; the row said only that the device had not re-announced yet.
|
|
132
|
+
if (!isMe && !p && !r.named) continue
|
|
133
|
+
if (!isMe && onList && !onList(p ? p.email : '', p ? p.user : '')) continue // removed since (a re-keyed room's guest book)
|
|
134
|
+
const email = (p && p.email) || (isMe ? me : '')
|
|
135
|
+
const user = (p && p.user) || ''
|
|
136
|
+
add(email || (user ? '@' + norm(user) : 'id:' + r.id), { email, user, me: isMe, id: r.id, label: r.label })
|
|
137
|
+
}
|
|
138
|
+
// A verified post is the strongest sighting there is: its author opened the room, announced or not.
|
|
139
|
+
for (const a of Array.isArray(posters) ? posters : []) {
|
|
140
|
+
const email = norm(a && a.email), user = String((a && a.user) || '').replace(/^@/, '')
|
|
141
|
+
if (!email && !user) continue
|
|
142
|
+
if (onList && !(me && email === me) && !onList(email, user)) continue // a removed member's old posts do not make them a member
|
|
143
|
+
const key = email || '@' + norm(user)
|
|
144
|
+
const byUser = !email && [...people.values()].find((x) => user && norm(x.user) === norm(user))
|
|
145
|
+
if (byUser) continue
|
|
146
|
+
add(key, { email, user, me: !!me && email === me, label: '' })
|
|
147
|
+
}
|
|
148
|
+
// You are a member the moment you are reading as your verified self, whether or not this device has announced.
|
|
149
|
+
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: '' }) }
|
|
150
|
+
const items = []
|
|
151
|
+
const covered = new Set()
|
|
152
|
+
const ordered = [...people.values()].sort((x, y) => (y.me ? 1 : 0) - (x.me ? 1 : 0))
|
|
153
|
+
for (const x of ordered) {
|
|
154
|
+
if (x.email) covered.add(x.email)
|
|
155
|
+
if (x.user) covered.add(norm('@' + x.user))
|
|
156
|
+
const label = x.user ? '@' + x.user : (x.email || (x.me ? (myName || x.label) : x.label))
|
|
157
|
+
const address = x.email || (x.user ? '@' + x.user : '')
|
|
158
|
+
items.push({ label, tag: x.me ? 'you' : 'signed in', ...(x.id ? { id: x.id } : {}), ...(address ? { address } : {}), ...(x.user ? { user: x.user } : {}) })
|
|
159
|
+
}
|
|
160
|
+
const emails = Array.isArray(allow.emails) ? allow.emails.filter(Boolean) : []
|
|
161
|
+
// an older room's @username entry: { handle, username } — the username it had THEN. A signed-in member whose handle it is
|
|
162
|
+
// (seenHandles: the caller resolved the signed-in usernames) is that member under their new name, not a second person.
|
|
163
|
+
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) : []
|
|
164
|
+
for (const e of emails) if (!covered.has(norm(e))) items.push({ label: e, tag: 'not yet opened', address: e })
|
|
165
|
+
for (const u of users) if (!covered.has(norm('@' + u))) items.push({ label: '@' + u, tag: 'not yet opened', address: '@' + u, user: u })
|
|
166
|
+
const domains = Array.isArray(allow.domains) ? allow.domains.filter(Boolean) : []
|
|
167
|
+
for (const d of domains) items.push({ label: 'anyone at @' + d, tag: 'allowed' })
|
|
168
|
+
// Hidden (hashed) entries: the caller matches them against the people the room verified (rosterHash.memberHash of
|
|
169
|
+
// each seen email) and passes how many are still UNSEEN — those are invites nobody has opened, not "more people".
|
|
170
|
+
// Without that count, every hidden entry is reported, which double-counts a member who is already listed above.
|
|
171
|
+
const hiddenAll = Array.isArray(allow.mh) ? allow.mh.length : 0
|
|
172
|
+
const hidden = Number.isInteger(hiddenUnseen) ? Math.max(0, Math.min(hiddenUnseen, hiddenAll)) : hiddenAll
|
|
173
|
+
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.'
|
|
174
|
+
+ (hidden ? ` ${hidden} private ${hidden === 1 ? 'invite hasn’t' : 'invites haven’t'} been opened yet.` : '')
|
|
175
|
+
return { title: 'Members', note, items, hidden }
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/** 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
|
|
179
|
+
* verified): announce again even with nothing changed — a lost write (two members announcing at once) would otherwise leave the
|
|
180
|
+
* member nameless for ever, and a member change in place cannot reach a hidden member it cannot name. */
|
|
181
|
+
export const unseenIn = (seen, id) => !!id && !(seen && typeof seen === 'object' && seen[id] && seen[id].email)
|
|
182
|
+
/** Seen, but before the record kept WHICH list entries this person is (2026-10-23, rosterCount samePeople): announced ONCE more
|
|
183
|
+
* 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
|
|
184
|
+
* @username counts once. */
|
|
185
|
+
const _entriesAsked = new Set()
|
|
186
|
+
export const entriesMissing = (seen, id, room = '') => {
|
|
187
|
+
if (!id || unseenIn(seen, id) || Array.isArray(seen[id].entries)) return false
|
|
188
|
+
const k = room + '\n' + id; if (_entriesAsked.has(k)) return false // once per room and key on this page
|
|
189
|
+
_entriesAsked.add(k); return true
|
|
190
|
+
}
|
|
191
|
+
/** This page announced `id` in `room` (for any reason): the server had its chance to record the entries — no extra announce. */
|
|
192
|
+
export const announcedIn = (room, id) => { if (id) _entriesAsked.add(room + '\n' + id) }
|
|
193
|
+
|
|
194
|
+
export function ensureSelf (roster, self, now = Date.now(), { retire = '' } = {}) {
|
|
195
|
+
let list = rows(roster)
|
|
196
|
+
// A device that now announces under a KEY retires the bare-id row it wrote before it had one (same device, same
|
|
197
|
+
// person) — otherwise the sheet shows the person twice, once attested and once "unverified".
|
|
198
|
+
// `retire` may be a list: in a verified room the device also retires the row it wrote under its grant key (selfRow).
|
|
199
|
+
const gone = [].concat(retire || []).filter((x) => x && self && self.id !== x && list.some((e) => e.id === x))
|
|
200
|
+
if (gone.length) { list = list.filter((e) => !gone.includes(e.id)); return { ...ensureSelf(list, self, now), changed: true } }
|
|
201
|
+
if (!self || !isId(self.id)) return { roster: list, changed: false }
|
|
202
|
+
const had = list.find((e) => e.id === self.id)
|
|
203
|
+
if (had) {
|
|
204
|
+
// Already listed. Only a CHANGED name is worth a write — every write is a chance to clobber a concurrent joiner.
|
|
205
|
+
const nm = cleanName(self.name)
|
|
206
|
+
if (nm === had.name) return { roster: list, changed: false }
|
|
207
|
+
return { roster: list.map((e) => (e.id === self.id ? clean({ ...e, name: nm }) : e)).sort(byJoin), changed: true } // the ORIGINAL join time is kept
|
|
208
|
+
}
|
|
209
|
+
const mine = clean({ id: self.id, at: Number.isFinite(now) ? now : Date.now(), name: self.name, verified: self.verified })
|
|
210
|
+
const next = [...list, mine].sort(byJoin)
|
|
211
|
+
// Cap by dropping the LATEST, never the earliest: a flood must not push the room's actual people out of their own
|
|
212
|
+
// list. (It can still stop new joins being recorded — that is the honest failure, and it is visible.)
|
|
213
|
+
return { roster: next.slice(0, MAX_ENTRIES), changed: true }
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/** Union two copies of the doc. Commutative and idempotent, earliest join wins, attestation is sticky. */
|
|
217
|
+
export function mergeRoster (a, b) {
|
|
218
|
+
const by = new Map()
|
|
219
|
+
for (const e of [...rows(a), ...rows(b)]) {
|
|
220
|
+
const prev = by.get(e.id)
|
|
221
|
+
if (!prev) { by.set(e.id, e); continue }
|
|
222
|
+
const at = Math.min(prev.at, e.at) // a rejoin never jumps the queue
|
|
223
|
+
const vr = prev.verified === true ? prev : (e.verified === true ? e : null)
|
|
224
|
+
const nm = vr ? vr.name : (prev.name || e.name) // an ATTESTED name wins over a claimed one
|
|
225
|
+
by.set(e.id, { id: e.id, at, ...(nm ? { name: nm } : {}), ...(vr ? { verified: true } : {}) })
|
|
226
|
+
}
|
|
227
|
+
return [...by.values()].sort(byJoin).slice(0, MAX_ENTRIES)
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
/**
|
|
231
|
+
* The list to render: join order, labelled. Guests are numbered among GUESTS, so a named member joining does not
|
|
232
|
+
* shift everyone's ordinal.
|
|
233
|
+
* @param {(entry) => boolean} [opts.attested] — re-check an entry's claim to be verified. The doc is written by
|
|
234
|
+
* whoever holds the link, so `verified` in the stored bytes is a CLAIM; the caller passes what it can actually
|
|
235
|
+
* attest (e.g. an spk seen on a server-stamped ledger entry). Default: trust the row, for tests and for callers
|
|
236
|
+
* that have already sanitized it.
|
|
237
|
+
*/
|
|
238
|
+
export function listRoster (roster, { attested = null } = {}) {
|
|
239
|
+
const list = rows(roster).sort(byJoin)
|
|
240
|
+
const ok = list.map((e) => e.verified === true && (attested ? !!attested(e) : true))
|
|
241
|
+
// How many rows carry each name, attested or claimed. A name held by exactly one row can stand alone; a name two
|
|
242
|
+
// rows claim is disambiguated, so copying someone's name can never merge two people into one row. That is the one
|
|
243
|
+
// thing this list does that the chat cannot: it counts PEOPLE, not strings.
|
|
244
|
+
const held = new Map()
|
|
245
|
+
for (const e of list) if (e.name) held.set(e.name, (held.get(e.name) || 0) + 1)
|
|
246
|
+
// An ordinal is only spent where one is SHOWN — an attested member with a name consumes none, so the guests are
|
|
247
|
+
// user1, user2… in join order however many named members share the room.
|
|
248
|
+
const standalone = list.map((e, i) => !!e.name && (ok[i] || (held.get(e.name) || 0) === 1))
|
|
249
|
+
let n = 0
|
|
250
|
+
return list.map((e, i) => {
|
|
251
|
+
const verified = ok[i]
|
|
252
|
+
const ordinal = standalone[i] ? '' : 'user' + (++n)
|
|
253
|
+
return {
|
|
254
|
+
id: e.id,
|
|
255
|
+
at: e.at,
|
|
256
|
+
verified,
|
|
257
|
+
named: verified && !!e.name, // a name someone ATTESTED — the only kind that may be shown plain
|
|
258
|
+
claimed: !verified && !!e.name, // a name its owner typed — shown, and the UI must mark it
|
|
259
|
+
label: standalone[i] ? e.name : (e.name ? `${e.name} (${ordinal})` : ordinal),
|
|
260
|
+
}
|
|
261
|
+
})
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
export async function privateInvitationMatches(cfg, room, seen, { resolveUsers, userTag, within = promise => promise }) {
|
|
265
|
+
// hidden (hashed) list entries: subtract the ones a verified person matches, so a member is not counted twice
|
|
266
|
+
let hiddenUnseen = null
|
|
267
|
+
// THE HANDLES OF THE SIGNED-IN @USERNAMES (sync sweep 10-12): an older room lists an @username by its stable handle and
|
|
268
|
+
// the name it had THEN; a member who renamed is signed in under the new name — matched by handle, the old name is not
|
|
269
|
+
// listed again as "not yet opened". Resolved once, for this and for the hidden entries below.
|
|
270
|
+
const seenHandles = new Set()
|
|
271
|
+
const seenUsers = [...new Set(Object.values(seen).map((p) => p && p.user).filter(Boolean))]
|
|
272
|
+
const legacyUsers = Array.isArray(cfg.allow && cfg.allow.users) ? cfg.allow.users.filter((u) => u && typeof u === 'object' && u.handle) : []
|
|
273
|
+
let resolvedSeen = null
|
|
274
|
+
const resolveSeen = async () => { if (resolvedSeen) return resolvedSeen; try { resolvedSeen = ((await within(resolveUsers(seenUsers))) || { resolved: [] }).resolved || [] } catch { resolvedSeen = [] } return resolvedSeen }
|
|
275
|
+
if (seenUsers.length && legacyUsers.length) for (const r of await resolveSeen()) if (r && r.handle) seenHandles.add(String(r.handle))
|
|
276
|
+
try {
|
|
277
|
+
const mh = Array.isArray(cfg.allow && cfg.allow.mh) ? cfg.allow.mh : []
|
|
278
|
+
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) } }
|
|
279
|
+
// THE ENTRIES THE GATE RECORDED AT EACH SIGN-IN (roster_seen `entries`, server-written — what member removal reads,
|
|
280
|
+
// sdkRekey listAfter): an older room hashed an @username from its HANDLE, which resolve no longer hands out for a member
|
|
281
|
+
// whose email door is closed (f8eb472a) — matched by what admitted them instead (sync sweep 11-08 #37)
|
|
282
|
+
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))
|
|
283
|
+
// A hidden @username entry is hashed from its HANDLE (createBtn pushes r.handle), so a seen member is matched by
|
|
284
|
+
// their username's handle too — or a member invited by @username who opened the room still counted as an
|
|
285
|
+
// unopened private invite (sync sweep, 2026-10-10).
|
|
286
|
+
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 }
|
|
287
|
+
} catch { /* unknown → the view reports every hidden entry */ }
|
|
288
|
+
return { hiddenUnseen, seenHandles }
|
|
289
|
+
}
|
package/roomSettings.js
ADDED
|
@@ -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
|
+
}
|