@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/renameRefusal.js
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
// renameRefusal.js — WHY a rename was refused, in the room's own words: one table for the ⋯ menu, the drawer and the SDK
|
|
2
|
+
// (sync sweep, 2026-10-11 — every refusal said "admins", also to a signed-out, removed or unlisted member of a room with
|
|
3
|
+
// none). `refused` / `reason` are the title op's answer (roomName.sendRename: { refused: error, reason }).
|
|
4
|
+
export function renameRefusalText ({ refused, reason } = {}) {
|
|
5
|
+
if (refused === 'direct_chat') return 'A direct chat isn’t renamed — each side sees the other person’s name.'
|
|
6
|
+
if (refused === 'not_admin') return 'Only this Space’s admins can rename it.'
|
|
7
|
+
if (refused === 'not_authorized') return reason === 'not_on_list' ? 'Your sign-in isn’t on this Space’s list.' : 'Sign in to rename this Space.'
|
|
8
|
+
return 'Couldn’t rename this Space.'
|
|
9
|
+
}
|
package/replyQuote.js
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
// THE REPLY QUOTE — one rule for the app's reply strip (space.js onReply) and the SDK's `replyTo` (witbitz-sdk.js send).
|
|
2
|
+
// Two copies of it drifted apart once (sync sweep 10-12): what a quote is keyed by, who it names, and its line.
|
|
3
|
+
// key the quoted entry's key (ledgerView.entryKeyOf — how reactions and replies find it)
|
|
4
|
+
// name its sender, "Assistant" for the agent's own, else "someone" (each side says which name field it reads)
|
|
5
|
+
// excerpt the words, whitespace-collapsed, up to 120 characters; else what it carried ("📷 photo", "📎 file"); else ''
|
|
6
|
+
// The excerpt travels with the reply, so the quote still reads after the original scrolls out of the loaded window.
|
|
7
|
+
import { entryKeyOf } from './ledgerView.js'
|
|
8
|
+
|
|
9
|
+
// THE NAME A QUOTE SHOWS (the owner, 2026-10-22: a quote said "alice@example.com" under a header that says
|
|
10
|
+
// "@alice"). The name line puts a verified member's @username in place of their email (messageRender.js); a quote is
|
|
11
|
+
// the same person, so it does too — for a new reply (the entry carries `user`) and for one already sent (the email→username
|
|
12
|
+
// pairs learned from the messages drawn on this device).
|
|
13
|
+
const EMAIL = /^[^@\s]+@[^@\s]+\.[^@\s]+$/
|
|
14
|
+
const usernames = new Map() // email → username, server-attested (messageRender learns them)
|
|
15
|
+
export function learnUsername (email, user) { if (EMAIL.test(String(email || '').trim()) && user) usernames.set(String(email).trim().toLowerCase(), String(user)) }
|
|
16
|
+
/** The name to show for `name` (an email turns into the @username its owner is verified as, when known). */
|
|
17
|
+
export function quoteName (name, user) {
|
|
18
|
+
const n = String(name || '').trim()
|
|
19
|
+
if (!EMAIL.test(n)) return name
|
|
20
|
+
const u = user || usernames.get(n.toLowerCase())
|
|
21
|
+
return u ? '@' + u : name
|
|
22
|
+
}
|
|
23
|
+
export const replyExcerpt = (m) => {
|
|
24
|
+
const t = m && typeof m.text === 'string' ? m.text.replace(/\s+/g, ' ').trim().slice(0, 120) : ''
|
|
25
|
+
return t || (m && Array.isArray(m.images) && m.images.length ? '📷 photo' : (m && Array.isArray(m.files) && m.files.length ? '📎 file' : ''))
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** → { key, name, excerpt } | null (no entry). `name` overrides which field names the sender. */
|
|
29
|
+
export function replyQuote (m, { name } = {}) {
|
|
30
|
+
if (!m || typeof m !== 'object') return null
|
|
31
|
+
let who = name !== undefined ? name : (m.from || m.name)
|
|
32
|
+
if (m.verified === true && typeof m.user === 'string' && m.user) who = quoteName(who, m.user) // as the name line shows them
|
|
33
|
+
return { key: entryKeyOf(m), name: String(who || (m.self ? 'Assistant' : 'someone')).slice(0, 80), excerpt: replyExcerpt(m) }
|
|
34
|
+
}
|
package/reqEnvelope.js
ADDED
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
// spaces/public/reqEnvelope.js — the client's half of the SEALED REQUEST ENVELOPE (docs/confidential-path-sweep-2026-11-05.md,
|
|
2
|
+
// option A; the enclave's half is agent/reqEnvelope.mjs). A confidential room's request is sealed WHOLE to the enclave's
|
|
3
|
+
// attested recipient key, with a one-time ANSWER KEY inside; the enclave seals its answer under that key, so the Space
|
|
4
|
+
// Lambda and the enclave's parent host carry ciphertext both ways.
|
|
5
|
+
//
|
|
6
|
+
// Readable outside (option A — what the front needs to route, mark changes and attach its hints): op, room, the sign-in
|
|
7
|
+
// token, the device key id, a lane's shared room, a decision's yes/no, and that a state call WRITES. Nothing else.
|
|
8
|
+
// Option B (sealsIdentity): the sign-in token goes inside too (docs/confidential-identity-option-b.md).
|
|
9
|
+
// Used only when the LIVE enclave's measured policy says it opens envelopes (env SEALED_REQUESTS = '1').
|
|
10
|
+
import { sealMk, mkAad, newNonce, sealNow } from './mkseal.js'
|
|
11
|
+
|
|
12
|
+
/** Ops that carry no content (or that the Lambda itself answers): they stay as they are. Everything else is sealed. */
|
|
13
|
+
export const PLAIN_OPS = new Set(['create', 'pollsealed', 'blob', 'policy', 'touch', 'purge', 'drop', 'pushdrop', 'user',
|
|
14
|
+
'enclaveattest', 'wake', 'changes', 'changesub', 'changemark', 'attest-accept', 'deviceverify', 'receipts', 'receiptsack',
|
|
15
|
+
// the Lambda answers these itself (agent/enclaveRelay.mjs FRONT_OPS): sealed, it could not read them — device enrollment in an
|
|
16
|
+
// attested confidential room failed (sweep 11-06 #5). spaces/test/frontOpsPlain.test.mjs holds FRONT_OPS ⊆ PLAIN_OPS.
|
|
17
|
+
'attest-enroll', 'device-verify', 'device-verify-result',
|
|
18
|
+
// report: what a member CHOSE to show Witbitz (agent/reportOp.mjs — stored and mailed to reports@, never the enclave); the
|
|
19
|
+
// Lambda must read it, so sealed to the enclave it never arrived from a confidential room (CI 2026-11-07, frontOpsPlain)
|
|
20
|
+
'report'])
|
|
21
|
+
|
|
22
|
+
/** Does this live enclave open envelopes? `attested` is the room's attested facts (enclaveRoute.attestedFacts): the policy
|
|
23
|
+
* text measured to the live PCR17, so the front can neither fake nor strip the answer. */
|
|
24
|
+
/** → true (it opens them) · false (its verified policy says it does not: an older build) · null (UNKNOWN — not attested, or
|
|
25
|
+
* the policy text could not be fetched). UNKNOWN is never read as "no": whoever serves the policy file could otherwise
|
|
26
|
+
* switch the envelope off by failing that one fetch (security review, 2026-11-05). The client refuses a content op then. */
|
|
27
|
+
export const opensEnvelopes = (attested) => {
|
|
28
|
+
if (!attested || !attested.policy || typeof attested.policy !== 'object') return null
|
|
29
|
+
return !!(attested.policy.env && attested.policy.env.SEALED_REQUESTS === '1')
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** OPTION B (docs/confidential-identity-option-b.md): does this live enclave take WHO YOU ARE from inside the envelope (env
|
|
33
|
+
* SEALED_IDENTITY = '1')? Then the sign-in token rides inside, with the hints the device fetched from op `idextras`, and the
|
|
34
|
+
* reads that carry a token (a verified room's) go sealed too. Unknown → false: the token stays outside, as under option A
|
|
35
|
+
* (no content is exposed by that — only who; the content switch is opensEnvelopes, which never reads unknown as no). */
|
|
36
|
+
export const sealsIdentity = (attested) => !!(attested && attested.policy && attested.policy.env && attested.policy.env.SEALED_IDENTITY === '1')
|
|
37
|
+
|
|
38
|
+
/** The content-free ops that carry a sign-in on a verified room, and that the front relays without reading it — sealed under
|
|
39
|
+
* option B so the token is not readable. An open room's read carries no token and stays plain (the asleep read serves it). */
|
|
40
|
+
export const IDENTITY_PLAIN_OPS = new Set(['pollsealed', 'blob', 'policy', 'purge', 'attest-accept'])
|
|
41
|
+
/** What the front reads on a sealed read: the cursor (its first-read tier mark) and the change inbox (the drawer's follow). */
|
|
42
|
+
const READ_OUTSIDE = ['sinceEtag', 'sinceCount', 'changeInbox']
|
|
43
|
+
|
|
44
|
+
/** Does `body` carry a sign-in token (top level or in its message)? */
|
|
45
|
+
export const carriesIdentity = (body) => !!(body && (typeof body.idToken === 'string' || (body.message && typeof body.message === 'object' && typeof body.message.idToken === 'string')))
|
|
46
|
+
|
|
47
|
+
const b64 = (u) => { let s = ''; for (const x of u) s += String.fromCharCode(x); return btoa(s) }
|
|
48
|
+
const unb64 = (s) => Uint8Array.from(atob(String(s || '')), (c) => c.charCodeAt(0))
|
|
49
|
+
const answerAad = ({ room, op, nonce }) => new TextEncoder().encode(`witbitz-answer|v1|${room}|${op}|${nonce}`)
|
|
50
|
+
|
|
51
|
+
/** The readable outside of an envelope: only what the front reads. */
|
|
52
|
+
function outsideOf (body, identity) {
|
|
53
|
+
const o = { op: body.op, room: body.room, enclave: true }
|
|
54
|
+
if (!identity && typeof body.idToken === 'string') o.idToken = body.idToken
|
|
55
|
+
if (body.op === 'pollsealed' || body.op === 'blob') for (const k of READ_OUTSIDE) if (body[k] !== undefined) o[k] = body[k]
|
|
56
|
+
if (typeof body.bridgeRoom === 'string') o.bridgeRoom = body.bridgeRoom
|
|
57
|
+
if (body.op === 'decide' && typeof body.approve === 'boolean') o.approve = body.approve
|
|
58
|
+
if (body.op === 'state' && body.patch !== undefined) o.patch = null // a WRITE (agent/changeFeed.mjs changeIntent) — the patch itself is inside
|
|
59
|
+
// A READ'S device key id too (docs/confidential-attested-rooms.md step 1, 2026-11-08): the front adds that device's enrolment
|
|
60
|
+
// evidence, which the enclave needs to check the read's proof. The proof itself stays inside; the enclave takes nothing else from out here.
|
|
61
|
+
const ra = body.readAttestation && typeof body.readAttestation === 'object' ? body.readAttestation.attestation : null
|
|
62
|
+
// …and its PLATFORM (sync sweep 11-10 #2): a Windows key's record is under win.<keyId> — the front looks there only when told the
|
|
63
|
+
// platform, so a Windows device's sealed reads and turns reached the enclave with no evidence and were refused. Not a secret.
|
|
64
|
+
const plat = (x) => (typeof x.platform === 'string' && /^[a-z]{2,16}$/.test(x.platform) ? { platform: x.platform } : {})
|
|
65
|
+
if (ra && typeof ra === 'object' && typeof ra.keyId === 'string') o.readAttestation = { attestation: { keyId: ra.keyId, ...plat(ra) } }
|
|
66
|
+
const m = body.message
|
|
67
|
+
if (m && typeof m === 'object') {
|
|
68
|
+
const stub = {}
|
|
69
|
+
if (!identity && typeof m.idToken === 'string') stub.idToken = m.idToken
|
|
70
|
+
// the device key id stays outside even under option B: the front adds the enrolled device's evidence from its store, and
|
|
71
|
+
// that store is where a revoked device is struck off (only rooms that require an approved device send one)
|
|
72
|
+
if (m.attestation && typeof m.attestation === 'object' && typeof m.attestation.keyId === 'string') stub.attestation = { keyId: m.attestation.keyId, ...plat(m.attestation) }
|
|
73
|
+
if (Object.keys(stub).length || !identity) o.message = stub
|
|
74
|
+
}
|
|
75
|
+
return o
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** Seal `body` (the request as it would have been sent) into an envelope. → { outer, answer } — send `outer`; keep `answer`
|
|
79
|
+
* to open the reply. */
|
|
80
|
+
export async function sealRequest (body, publicJwk, { identity = false, extras = null } = {}) {
|
|
81
|
+
const key = crypto.getRandomValues(new Uint8Array(32))
|
|
82
|
+
const ts = sealNow(), nonce = newNonce() // the enclave's clock as far as known (mkseal.js, T#2)
|
|
83
|
+
const inner = { ...body, answerKey: b64(key) }
|
|
84
|
+
if (identity && extras && typeof extras === 'object') { // option B: the front's hints, which the device fetched (op idextras)
|
|
85
|
+
if (Array.isArray(extras.userHints) && extras.userHints.length) inner.userHints = extras.userHints
|
|
86
|
+
if (extras.issuerCfg && typeof extras.issuerCfg === 'object') inner.issuerCfg = extras.issuerCfg
|
|
87
|
+
if (Array.isArray(extras.boundHints) && extras.boundHints.length) inner.boundHints = extras.boundHints.slice(0, 4) // the room-pass cutoff's word (agent/reqEnvelope.mjs INSIDE_OK_FIELDS; sync sweep 2026-11-16 #6)
|
|
88
|
+
}
|
|
89
|
+
delete inner.op; delete inner.room; delete inner.enclave
|
|
90
|
+
const envSealed = await sealMk(JSON.stringify(inner), publicJwk, mkAad({ room: body.room, op: body.op + ':env', ts, nonce }))
|
|
91
|
+
return { outer: { ...outsideOf(body, identity), envSealed, envTs: ts, envNonce: nonce }, answer: { key, aad: answerAad({ room: body.room, op: body.op, nonce }) } }
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** Open a reply. A sealed answer → the enclave's response object; a reply with no sealed answer (the Lambda's own: warming,
|
|
95
|
+
* relay failure, a refusal before the enclave) → itself. A sealed answer that does not open → an error, never a guess. */
|
|
96
|
+
//
|
|
97
|
+
// ⛔ A SEALED REQUEST ACCEPTS ONLY A SEALED ANSWER (security review, 2026-11-05): the front holds no key, so an answer it made up
|
|
98
|
+
// must never pass for the enclave's. Without a sealed answer, only a bare REFUSAL is taken — a failure status, ok:false, a few
|
|
99
|
+
// short fields (the Lambda's own: enclave_warming, a relay failure, a front refusal, a transport error) — and nothing else
|
|
100
|
+
// from it. With a sealed answer, nothing from outside is merged in but the HTTP status.
|
|
101
|
+
const REFUSAL_FIELDS = ['error', 'reason', 'detail']
|
|
102
|
+
export async function openAnswer (reply, answer) {
|
|
103
|
+
const status = reply && Number.isInteger(reply.status) ? reply.status : 0
|
|
104
|
+
const sa = reply && reply.sealedAnswer
|
|
105
|
+
if (!sa || typeof sa !== 'object') {
|
|
106
|
+
if (status >= 200 && status < 300) return { status: 502, ok: false, error: 'answer_unsealed', reason: 'the answer to a sealed request came back unsealed — not from the enclave' } // never a 200: a success it is not (sweep 11-06 #1)
|
|
107
|
+
const out = { status, ok: false }
|
|
108
|
+
for (const k of REFUSAL_FIELDS) if (reply && typeof reply[k] === 'string') out[k] = reply[k].slice(0, 300)
|
|
109
|
+
if (reply && reply.warming === true) out.warming = true
|
|
110
|
+
if (reply && reply.confidential === true) out.confidential = true // the front's tier mark — it only ever ADDS the mark
|
|
111
|
+
if (reply && Number.isFinite(reply.now)) out.serverNow = reply.now // an envelope_* refusal carries the enclave's clock (T#2): post() may retry once with it
|
|
112
|
+
// ⛔ a bare 5xx with no code is a CUT-OFF (the API gateway's 30 s on a long confidential turn), not a refusal: the Lambda
|
|
113
|
+
// runs on and stores the reply. Marked 'refused', every long turn read "Not sent" (the owner, 2026-11-11) — left codeless,
|
|
114
|
+
// turnVerdict reads it 'pending' and the poll delivers it, as for a standard room
|
|
115
|
+
if (!out.error && !(status >= 500)) out.error = 'refused'
|
|
116
|
+
return out
|
|
117
|
+
}
|
|
118
|
+
try {
|
|
119
|
+
const k = await crypto.subtle.importKey('raw', answer.key, 'AES-GCM', false, ['decrypt'])
|
|
120
|
+
const pt = await crypto.subtle.decrypt({ name: 'AES-GCM', iv: unb64(sa.iv), additionalData: answer.aad }, k, unb64(sa.ct))
|
|
121
|
+
const inner = JSON.parse(new TextDecoder().decode(pt))
|
|
122
|
+
// as call() does: { status, ...data } — plus the front's `confidential` mark on a first read (enclaveRelay probeConfidential):
|
|
123
|
+
// it only ever ADDS the mark, and a forged one makes the page treat the room MORE carefully, never less
|
|
124
|
+
return { status, ...(inner && typeof inner === 'object' && !Array.isArray(inner) ? inner : {}), ...(reply.confidential === true ? { confidential: true } : {}) }
|
|
125
|
+
} catch { return { status, ok: false, error: 'answer_unopenable', reason: 'the enclave\'s answer could not be opened on this device' } }
|
|
126
|
+
}
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
// Account-scoped room defaults. Pure merge rule shared by live encrypted sync, backup and tenant restore.
|
|
2
|
+
export const ROOM_DEFAULTS_KEY = 'space:default-room'
|
|
3
|
+
export const ROOM_DEFAULTS_DOC = 'room-defaults'
|
|
4
|
+
const BOOLS = ['quick','enclave','verified','lanes','temporary']
|
|
5
|
+
const STRINGS = ['assistant','model']
|
|
6
|
+
const FIELDS = [...BOOLS,...STRINGS]
|
|
7
|
+
let memory = null, notify = () => {}
|
|
8
|
+
export const setRoomDefaultsSync = fn => { notify = typeof fn === 'function' ? fn : () => {} }
|
|
9
|
+
export function cleanRoomDefaults(value) {
|
|
10
|
+
if (!value || typeof value !== 'object' || value.v !== 1) return null
|
|
11
|
+
const out = { v:1, mods:{} }
|
|
12
|
+
for (const key of FIELDS) {
|
|
13
|
+
if (BOOLS.includes(key) ? typeof value[key] !== 'boolean' : typeof value[key] !== 'string' || value[key].length > 200) continue
|
|
14
|
+
out[key] = value[key]
|
|
15
|
+
const at = value.mods?.[key]
|
|
16
|
+
out.mods[key] = Number.isSafeInteger(at) && at >= 0 ? at : 0
|
|
17
|
+
}
|
|
18
|
+
return FIELDS.some(key => key in out) ? out : null
|
|
19
|
+
}
|
|
20
|
+
/** Per-option last-edit wins; equal clocks use a deterministic value order. An absent field never resets one. */
|
|
21
|
+
export function mergeRoomDefaults(a,b) {
|
|
22
|
+
a=cleanRoomDefaults(a);b=cleanRoomDefaults(b)
|
|
23
|
+
if(!a)return b;if(!b)return a
|
|
24
|
+
const out={v:1,mods:{}}
|
|
25
|
+
for(const key of FIELDS){
|
|
26
|
+
const winner=!(key in a)?b:!(key in b)?a:a.mods[key]>b.mods[key]?a:a.mods[key]<b.mods[key]?b:JSON.stringify(a[key])>=JSON.stringify(b[key])?a:b
|
|
27
|
+
if(key in winner){out[key]=winner[key];out.mods[key]=winner.mods[key]}
|
|
28
|
+
}
|
|
29
|
+
// Temporary rooms cannot create durable private assistants. The later of these two edits determines the combination.
|
|
30
|
+
if(out.temporary && out.lanes){if(out.mods.temporary>=out.mods.lanes)out.lanes=false;else out.temporary=false}
|
|
31
|
+
return out
|
|
32
|
+
}
|
|
33
|
+
export function readRoomDefaults(store=globalThis.localStorage) {
|
|
34
|
+
if(memory && store===globalThis.localStorage)return memory
|
|
35
|
+
try {
|
|
36
|
+
const value=cleanRoomDefaults(JSON.parse(store.getItem(ROOM_DEFAULTS_KEY)||'null'))
|
|
37
|
+
if(value)return value
|
|
38
|
+
if(store.getItem('space:simple-setup')==='1')return cleanRoomDefaults({v:1,quick:true,enclave:true,verified:true,lanes:true,temporary:false,assistant:'',model:''})
|
|
39
|
+
}catch{}
|
|
40
|
+
return null
|
|
41
|
+
}
|
|
42
|
+
function arrived(){if(typeof dispatchEvent==='function')dispatchEvent(new Event('wb-room-defaults'))}
|
|
43
|
+
export function writeRoomDefaults(patch,baseline={},store=globalThis.localStorage,now=Date.now()) {
|
|
44
|
+
const old=readRoomDefaults(store), next=cleanRoomDefaults({v:1,...baseline,...old,...patch})
|
|
45
|
+
if(!next)return null
|
|
46
|
+
next.mods={...(old?.mods||{})}
|
|
47
|
+
const at=Math.max(now,...Object.values(next.mods).map(n=>n+1))
|
|
48
|
+
for(const key of FIELDS)if(key in patch && key in next)next.mods[key]=at
|
|
49
|
+
if(patch.temporary===true){next.lanes=false;next.mods.lanes=at}
|
|
50
|
+
if(patch.lanes===true){next.temporary=false;next.mods.temporary=at}
|
|
51
|
+
const value=cleanRoomDefaults(next)
|
|
52
|
+
try{store.setItem(ROOM_DEFAULTS_KEY,JSON.stringify(value));store.removeItem('space:simple-setup');store.removeItem('space:simple-setup:previous-theme');memory=null}catch{if(store===globalThis.localStorage)memory=value}
|
|
53
|
+
if(store===globalThis.localStorage){arrived();notify()}
|
|
54
|
+
return value
|
|
55
|
+
}
|
|
56
|
+
export function adoptRoomDefaults(remote,store=globalThis.localStorage) {
|
|
57
|
+
const local=readRoomDefaults(store),merged=mergeRoomDefaults(local,remote)
|
|
58
|
+
if(!merged || JSON.stringify(local)===JSON.stringify(merged))return false
|
|
59
|
+
try{store.setItem(ROOM_DEFAULTS_KEY,JSON.stringify(merged));memory=null}catch{return false}
|
|
60
|
+
if(store===globalThis.localStorage)arrived()
|
|
61
|
+
return true
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** A dedicated sealed account doc; failed/unknown reads never authorize a replacement write. */
|
|
65
|
+
export async function syncRoomDefaultsDocument({read,write=null,store=globalThis.localStorage}) {
|
|
66
|
+
let response;try{response=await read()}catch{return {status:0}}
|
|
67
|
+
if(!response || ![200,404].includes(response.status))return {status:0}
|
|
68
|
+
const raw=response.state,remote=cleanRoomDefaults(raw)
|
|
69
|
+
const empty=raw==null || (typeof raw==='object' && !Array.isArray(raw) && !Object.keys(raw).length)
|
|
70
|
+
if(!remote && !empty)return {status:0}
|
|
71
|
+
const merged=mergeRoomDefaults(readRoomDefaults(store),remote)
|
|
72
|
+
if(!merged)return {status:200}
|
|
73
|
+
adoptRoomDefaults(merged,store)
|
|
74
|
+
if(write && JSON.stringify(merged)!==JSON.stringify(remote)){try{return await write(merged)}catch{return {status:0}}}
|
|
75
|
+
return {status:200}
|
|
76
|
+
}
|
package/roomDelete.js
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
// roomDelete.js — an ACCOUNT can delete the rooms it created (docs/user-erasure.md). At create, the page sends
|
|
2
|
+
// `delCommit = sha256(delete secret)`; the secret is HMAC(account secret, 'witbitz-room-delete:' + room) and only this
|
|
3
|
+
// account's devices can derive it, so a member who joined can never delete someone else's room. The account secret is the
|
|
4
|
+
// usage key's (usageReceipts.js) — it rides the account index, and a key that lost a convergence race is kept as retired,
|
|
5
|
+
// so a deletion tries every kept key.
|
|
6
|
+
import { loadUsageKey, loadOldUsageKeys, newUsageKey, saveUsageKey, dropFor } from './usageReceipts.js'
|
|
7
|
+
|
|
8
|
+
const enc = new TextEncoder()
|
|
9
|
+
const b64u = (u8) => { let x = ''; for (const b of u8) x += String.fromCharCode(b); return btoa(x).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '') }
|
|
10
|
+
const ub64u = (s) => Uint8Array.from(atob(String(s).replace(/-/g, '+').replace(/_/g, '/')), (c) => c.charCodeAt(0))
|
|
11
|
+
export const DELETE_URL = 'https://api.witbitz.chat/v1/spaces/rooms/delete'
|
|
12
|
+
|
|
13
|
+
export function deletionConfirmed(result) {
|
|
14
|
+
const body = result?.body
|
|
15
|
+
return !!result?.ok && (body?.tombstoned === true || (body?.deleted === true && !body.queued && !body.pending))
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export async function delSecretFor (key, room) {
|
|
19
|
+
const k = await crypto.subtle.importKey('raw', ub64u(key.secret), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign'])
|
|
20
|
+
return b64u(new Uint8Array(await crypto.subtle.sign('HMAC', k, enc.encode('witbitz-room-delete:' + room))))
|
|
21
|
+
}
|
|
22
|
+
export async function delCommitOf (secret) { return b64u(new Uint8Array(await crypto.subtle.digest('SHA-256', enc.encode(secret)))) }
|
|
23
|
+
|
|
24
|
+
/** The commitment a create carries — minting the account key on the spot if this device has none yet (a brand-new
|
|
25
|
+
* account creates its index room before any sync). Never throws: a create without a commitment still goes. */
|
|
26
|
+
export async function delCommitFor (room, { load = loadUsageKey, mint = async () => saveUsageKey(await newUsageKey()) } = {}) {
|
|
27
|
+
try { const key = load() || await mint(); return key ? await delCommitOf(await delSecretFor(key, room)) : null } catch { return null }
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** Delete a room this account created. Tries the current key, then retired ones. → { ok, status, body }
|
|
31
|
+
* A 200 may be `{ queued: true }` — the server answers on its one-row check and deletes in the background: NOT deleted yet.
|
|
32
|
+
* `check: true` asks only whether THIS account's tombstone is down (`{ deleted: true, tombstoned: true }`) and queues nothing —
|
|
33
|
+
* Delete my account confirms a queued room with it before it erases the account key (state machines pass 9, 9·S#1). */
|
|
34
|
+
export async function deleteOwnRoom (room, { keys = [loadUsageKey(), ...loadOldUsageKeys()].filter(Boolean), dropKeys = [], fetchImpl = (...a) => fetch(...a), check = false, reviewPolicy = false, reviewedPolicy, reviewedEtag, url = DELETE_URL } = {}) { // dropKeys: other keys this account leaves traces with (the SDK's usage key — sync sweep 11-08 #3)
|
|
35
|
+
let last = { ok: false, status: 0, body: { error: 'no_account_key' } }
|
|
36
|
+
// every drop this account holds in the room (current + retired keys): the server refuses only for OTHER accounts' traces
|
|
37
|
+
const drops = []; for (const k of [...keys, ...dropKeys]) { try { const d = await dropFor(k, room); if (!drops.includes(d)) drops.push(d) } catch { /* */ } }
|
|
38
|
+
for (const key of keys) {
|
|
39
|
+
const delSecret = await delSecretFor(key, room)
|
|
40
|
+
if (reviewedEtag !== undefined && !check) {
|
|
41
|
+
const probe = await deleteOwnRoom(room, { keys: [key], dropKeys: [...keys, ...dropKeys], fetchImpl, check: true, reviewedEtag, url })
|
|
42
|
+
if (probe.status === 404) { last = probe; continue }
|
|
43
|
+
if (probe.body?.deleted === true) return probe
|
|
44
|
+
if (probe.status !== 200 || !probe.body?.guardedCleanup || !reviewedPolicy || reviewedPolicy !== probe.body?.policyVersion) return { ok: false, status: probe.status === 200 ? 409 : probe.status, body: { error: 'cleanup_unconfirmed' } }
|
|
45
|
+
}
|
|
46
|
+
let r = null
|
|
47
|
+
try { r = await fetchImpl(url, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ room, confirm: room, delSecret, drops, ...(reviewedEtag !== undefined ? { reviewedEtag, reviewedPolicy } : {}), ...(reviewPolicy ? { reviewPolicy: true } : {}), ...(check ? { check: true } : {}) }) }) } catch { return { ok: false, status: 0, body: { error: 'unreachable' } } }
|
|
48
|
+
const body = await r.json().catch(() => ({}))
|
|
49
|
+
last = { ok: r.status === 200, status: r.status, body }
|
|
50
|
+
if (r.status !== 404) return last // 200 done · 207 partly (call again) · 409 shared (others used it: leave it) · anything else: stop and say so
|
|
51
|
+
}
|
|
52
|
+
return last
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** LEAVING A VERIFIED ROOM (agent/roomLeave.mjs): what this account hands over as it goes — its marks in the room (`drops`, every
|
|
56
|
+
* kept key's) and the room's delete secrets it can derive (`dels`; only the creator's matches the room's commitment). */
|
|
57
|
+
export async function leaveHandover (room, { keys = [loadUsageKey(), ...loadOldUsageKeys()].filter(Boolean), dropKeys = [] } = {}) {
|
|
58
|
+
const drops = [], dels = []
|
|
59
|
+
for (const k of [...keys, ...dropKeys]) { try { const d = await dropFor(k, room); if (!drops.includes(d)) drops.push(d) } catch { /* */ } }
|
|
60
|
+
for (const k of keys) { try { const s = await delSecretFor(k, room); if (!dels.includes(s)) dels.push(s) } catch { /* */ } }
|
|
61
|
+
return { drops: drops.slice(0, 16), dels: dels.slice(0, 8) }
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** The LAST ONE OUT deletes the room with what every leaver handed over (op `leave` answered `last`): each handed-over delete
|
|
65
|
+
* secret is tried with all the handed-over marks; the server's own checks still run (another account's mark → 409 shared). */
|
|
66
|
+
export async function deleteHandedOver (room, { drops = [], dels = [] } = {}, { fetchImpl = (...a) => fetch(...a), url = DELETE_URL, check = false } = {}) {
|
|
67
|
+
let last = { ok: false, status: 0, body: { error: 'no_delete_secret' } }
|
|
68
|
+
for (const delSecret of dels) {
|
|
69
|
+
let r = null
|
|
70
|
+
try { r = await fetchImpl(url, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ room, confirm: room, delSecret, drops, ...(check ? { check: true } : {}) }) }) } catch { return { ok: false, status: 0, body: { error: 'unreachable' } } }
|
|
71
|
+
const body = await r.json().catch(() => ({}))
|
|
72
|
+
last = { ok: r.status === 200, status: r.status, body }
|
|
73
|
+
if (r.status !== 404) return last
|
|
74
|
+
}
|
|
75
|
+
return last
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** Leave a room on the way out of an account: `post(handover)` sends op `leave`; a verified room whose last member this was is then
|
|
79
|
+
* deleted. → { left, deleted?, last? } — never throws (a room that is not verified, or a server without the op, just stays). */
|
|
80
|
+
// A CONFIDENTIAL Space's enclave may be asleep: `leave` wakes it (agent/enclaveRelay.mjs) and the answer is `enclave_warming` until
|
|
81
|
+
// it is up — asked again for up to LEAVE_WARM_TRIES × LEAVE_WARM_MS (an enclave wakes in 1–6 min; sweep 11-18 #1). Still asleep after
|
|
82
|
+
// that → `{ warming: true }`, which Delete my account reports as not finished (run it again), never as left.
|
|
83
|
+
export const LEAVE_WARM_TRIES = 40, LEAVE_WARM_MS = 10_000
|
|
84
|
+
const warmingAnswer = (r) => { const b = (r && (r.body || r)) || {}; return b.error === 'enclave_warming' || b.warming === true }
|
|
85
|
+
export async function leaveAndMaybeDelete (room, { post, handover = leaveHandover, del = deleteHandedOver, sleep = (ms) => new Promise((res) => setTimeout(res, ms)), tries = LEAVE_WARM_TRIES } = {}) {
|
|
86
|
+
let r = null
|
|
87
|
+
let h; try { h = await handover(room) } catch { return { left: false } }
|
|
88
|
+
for (let i = 0; ; i++) {
|
|
89
|
+
try { r = await post(h) } catch { return { left: false } }
|
|
90
|
+
if (!warmingAnswer(r)) break
|
|
91
|
+
if (i + 1 >= tries) return { left: false, warming: true }
|
|
92
|
+
await sleep(LEAVE_WARM_MS)
|
|
93
|
+
}
|
|
94
|
+
const b = (r && (r.body || r)) || {}
|
|
95
|
+
if (r?.status === 409 && b.error === 'not_verified_room') return { left: false, unverified: true }
|
|
96
|
+
if (r?.status !== 200 || b.left !== true) return { left: false }
|
|
97
|
+
if (b.last !== true) return { left: true }
|
|
98
|
+
if (b.lapses === true) return { left: true, last: true, lapses: true }
|
|
99
|
+
const handed = { drops: b.drops || [], dels: b.dels || [] }
|
|
100
|
+
let result = await Promise.resolve().then(() => del(room, handed)).catch(() => null)
|
|
101
|
+
if (result?.ok && result.body?.queued && !deletionConfirmed(result)) {
|
|
102
|
+
for (let i = 0; i < tries; i++) {
|
|
103
|
+
await sleep(LEAVE_WARM_MS)
|
|
104
|
+
result = await Promise.resolve().then(() => del(room, handed, { check: true })).catch(() => null)
|
|
105
|
+
if (deletionConfirmed(result) || (result && ![0, 200, 503].includes(result.status))) break
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
return { left: true, last: true, deleted: deletionConfirmed(result) }
|
|
109
|
+
}
|
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 || 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
|
+
|