@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/sdkLaneLink.js
ADDED
|
@@ -0,0 +1,205 @@
|
|
|
1
|
+
// spaces/public/sdkLaneLink.js — `lane.link(other)`: one member's two private assistants ask each other (2026-10-03,
|
|
2
|
+
// the owner: "Build the lane links"). The SDK twin of the app's linked lanes (https://witbitz.chat/docs/sdk-agents.md#lane-links; laneLink.js),
|
|
3
|
+
// on the SAME pure core (laneLinkCore.js: the frame, the hop counter, which answer goes back), so the two cannot drift.
|
|
4
|
+
//
|
|
5
|
+
// ENTIRELY ON THE DEVICE, as the design decided: the device holds both lanes' keys, so it is the only thing that can
|
|
6
|
+
// bridge them, and the server never joins two rooms. Two legs, one primitive (post into a lane + wake its assistant):
|
|
7
|
+
// • OUT — the asking assistant calls `tell_lane` (an `await` action: this device answers it within the turn). The
|
|
8
|
+
// device frames the question, posts it into the other lane and wakes that lane's assistant, then answers the tool
|
|
9
|
+
// AT ONCE: the exchange is asynchronous, never a blocking wait (Decision 2).
|
|
10
|
+
// • BACK — the device watches the lane that was asked; when its assistant answers, planForward() picks the answer and
|
|
11
|
+
// the device carries it back framed as a reply and wakes the asking assistant, which relays it to the member.
|
|
12
|
+
// The hop cap bounds BOTH legs (Decision 4): an ask continues the chain of the message that triggered it, so a loop of
|
|
13
|
+
// assistants asking each other stops at the cap. Default 3; `cap: 0` = no lane-to-lane traffic.
|
|
14
|
+
// ⚑ It runs while both lanes are OPEN on this device (the app's driver is "app-open only" too). `link.state` carries the
|
|
15
|
+
// cursors; pass it back as `resume` to pick up an exchange that was in flight when the page closed.
|
|
16
|
+
import { buildFramed, parseFramed, newCorr, askHopFrom, canForward, planForward, DEFAULT_LANE_LINK_CAP } from './laneLinkCore.js'
|
|
17
|
+
|
|
18
|
+
const GUIDANCE =
|
|
19
|
+
'You can ask the member\'s OTHER linked assistants a question with tell_lane. It is ASYNCHRONOUS: tell_lane posts ' +
|
|
20
|
+
'your question and returns immediately — the other assistant\'s answer arrives here later as a new message, and you ' +
|
|
21
|
+
'will be asked to relay it to the member then. So do NOT wait for the answer inside this turn and never invent one; ' +
|
|
22
|
+
'just send the question and tell the member you have asked. Keep the question self-contained — the other assistant ' +
|
|
23
|
+
'cannot see this conversation, only what you put in `message`.'
|
|
24
|
+
const DEFAULT_LABEL = 'linked assistant'
|
|
25
|
+
// How long a post into the other lane may take. A turn returns only AFTER its reply (the send IS the turn), so 10 s read
|
|
26
|
+
// every slower reply as "not delivered" — tell_lane told the model "busy" and a pass forwarded the same reply again (sync
|
|
27
|
+
// sweep, 2026-10-10). Now just past the server's turn budget (240 s), as the app waits for the turn's answer itself.
|
|
28
|
+
const WAKE_WAIT_MS = 280_000
|
|
29
|
+
const ASK_WAIT_MS = 6_000 // tell_lane: a refusal or a busy answer comes back at once; past this the question is in
|
|
30
|
+
|
|
31
|
+
const fail = (code, msg) => Object.assign(new Error('witbitz: ' + msg), { code })
|
|
32
|
+
const isAgent = (e) => !!(e && e.self === true)
|
|
33
|
+
|
|
34
|
+
/** The peers of `lane`, labelled the way its model sees them: [{ label, link, peer }]. Twins are suffixed ("… (2)"), and
|
|
35
|
+
* the tool's enum and its executor both read THIS list, so the name the model picks can never resolve to another lane
|
|
36
|
+
* (the app's linkedLaneChoices rule). */
|
|
37
|
+
export function peersOf(lane) {
|
|
38
|
+
const seen = new Map(), out = []
|
|
39
|
+
for (const link of (lane._laneLinks || [])) {
|
|
40
|
+
if (link._dead) continue
|
|
41
|
+
const side = link._sideOf(lane)
|
|
42
|
+
const base = side.to || DEFAULT_LABEL
|
|
43
|
+
const n = (seen.get(base) || 0) + 1
|
|
44
|
+
seen.set(base, n)
|
|
45
|
+
out.push({ label: n === 1 ? base : `${base} (${n})`, link, peer: side.other })
|
|
46
|
+
}
|
|
47
|
+
return out
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** The `tell_lane` def + guidance this lane's turns carry, or null when it has no live link. */
|
|
51
|
+
export function laneLinkTool(lane) {
|
|
52
|
+
const peers = peersOf(lane)
|
|
53
|
+
if (!peers.length) return null
|
|
54
|
+
return {
|
|
55
|
+
def: {
|
|
56
|
+
name: 'tell_lane',
|
|
57
|
+
mode: 'await',
|
|
58
|
+
description:
|
|
59
|
+
'Ask one of the member\'s OTHER linked assistants a question, on their behalf. `lane` is which assistant to ask; ' +
|
|
60
|
+
'`message` is the full question (the other assistant sees ONLY this — include everything it needs). ' +
|
|
61
|
+
'ASYNCHRONOUS: this returns immediately; the answer arrives later as a new message, and you relay it to the ' +
|
|
62
|
+
'member then. Never wait for it or make one up.',
|
|
63
|
+
inputSchema: { type: 'object', properties: { lane: { type: 'string', enum: peers.map((p) => p.label), description: 'Which linked assistant to ask.' }, message: { type: 'string', description: 'The complete question to ask it.' } }, required: ['lane', 'message'] },
|
|
64
|
+
},
|
|
65
|
+
guidance: GUIDANCE,
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
// Post a framed message into `lane` and wake its assistant ('always', whatever the lane's reply mode). True once the
|
|
70
|
+
// lane ACCEPTED it; a lane still busy past WAKE_WAIT_MS reads as not delivered, and the caller retries / reports it.
|
|
71
|
+
// `ask: true` = tell_lane's post, answered within the SERVER's device-call limit (25 s, spaceRoom.mjs): it waits ASK_WAIT_MS
|
|
72
|
+
// for a quick refusal, then counts the question as sent and lets the turn run on — the answer comes back through the
|
|
73
|
+
// link's pass, as the tool says (sync sweep, 2026-10-10: waiting for the whole reply ran past the limit).
|
|
74
|
+
async function postAndWake(lane, text, from, { ask = false } = {}) {
|
|
75
|
+
// Given up = given up (sync sweep, 2026-10-10): a pass's send still held for "busy" is not resent after the wait (the
|
|
76
|
+
// pass retries it, and a second copy would forward twice); and `from` is the LINK's label, never the member's name.
|
|
77
|
+
let timedOut = false
|
|
78
|
+
try {
|
|
79
|
+
const sent = lane.send(text, { from, mode: 'always', ...(ask ? { _noHold: true } : { _aborted: () => timedOut }), _linkPost: true })
|
|
80
|
+
const r = await Promise.race([sent, new Promise((res) => setTimeout(() => { timedOut = true; res(null) }, ask ? ASK_WAIT_MS : WAKE_WAIT_MS))])
|
|
81
|
+
if (r === null && ask) { sent.catch(() => {}); return true } // still running: the question is in, the turn is answering it
|
|
82
|
+
return !!(r && r.status === 200 && !r.busy && r.ok !== false)
|
|
83
|
+
} catch { return false }
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
export class LaneLink {
|
|
87
|
+
constructor(a, b, { to, as, cap, resume } = {}) {
|
|
88
|
+
this.a = a; this.b = b
|
|
89
|
+
// `to`: what A's assistant calls B; `as`: what B's assistant calls A.
|
|
90
|
+
this._labels = { a: String(to || DEFAULT_LABEL).slice(0, 60), b: String(as || DEFAULT_LABEL).slice(0, 60) }
|
|
91
|
+
this.cap = Number.isFinite(Number(cap)) && Number(cap) >= 0 ? Math.floor(Number(cap)) : DEFAULT_LANE_LINK_CAP
|
|
92
|
+
const r = resume && typeof resume === 'object' ? resume : {}
|
|
93
|
+
// Cursor per side: how many of that lane's messages the link has already judged. null = not seen yet → set to the
|
|
94
|
+
// lane's length at first sight, so linking never forwards history (the app's no-backfill rule).
|
|
95
|
+
this._cur = { a: Number.isFinite(r.cursorA) ? r.cursorA : null, b: Number.isFinite(r.cursorB) ? r.cursorB : null }
|
|
96
|
+
this._sent = { a: Array.isArray(r.sentA) ? r.sentA.slice(-200) : [], b: Array.isArray(r.sentB) ? r.sentB.slice(-200) : [] }
|
|
97
|
+
this._dead = false
|
|
98
|
+
this._busy = false
|
|
99
|
+
this._again = false
|
|
100
|
+
this._t = null
|
|
101
|
+
this._subA = () => this._schedule()
|
|
102
|
+
this._subB = () => this._schedule()
|
|
103
|
+
a.on('message', this._subA); b.on('message', this._subB)
|
|
104
|
+
for (const l of [a, b]) {
|
|
105
|
+
l._laneLinks = [...(l._laneLinks || []), this]
|
|
106
|
+
l._reads.tell_lane = (args) => tellLane(l, args)
|
|
107
|
+
}
|
|
108
|
+
Promise.all([a.ready, b.ready].map((p) => Promise.resolve(p).catch(() => {}))).then(() => this._schedule())
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/** The progress to persist (JSON-safe) — hand it back as `link(other, { resume })` after a reload. */
|
|
112
|
+
get state() { return { cursorA: this._cur.a, cursorB: this._cur.b, sentA: this._sent.a.slice(), sentB: this._sent.b.slice() } }
|
|
113
|
+
|
|
114
|
+
/** End the link: neither assistant is offered the other any more. */
|
|
115
|
+
unlink() { this._stop(); if (this._onUnlink) { try { this._onUnlink() } catch { /* the account record */ } } }
|
|
116
|
+
|
|
117
|
+
// Stop on THIS device without ending the link in the account (a lane closing).
|
|
118
|
+
_stop() {
|
|
119
|
+
if (this._dead) return
|
|
120
|
+
this._dead = true
|
|
121
|
+
clearTimeout(this._t)
|
|
122
|
+
for (const [l, sub] of [[this.a, this._subA], [this.b, this._subB]]) {
|
|
123
|
+
const subs = l._subs && l._subs.message
|
|
124
|
+
if (subs) { const i = subs.indexOf(sub); if (i >= 0) subs.splice(i, 1) }
|
|
125
|
+
l._laneLinks = (l._laneLinks || []).filter((x) => x !== this)
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/** Run one pass now (it also runs on its own whenever either lane gets a message). */
|
|
130
|
+
async run() { return this._pass() }
|
|
131
|
+
|
|
132
|
+
_sideOf(lane) { return lane === this.a ? { key: 'a', other: this.b, to: this._labels.a, as: this._labels.b } : { key: 'b', other: this.a, to: this._labels.b, as: this._labels.a } }
|
|
133
|
+
_schedule() { if (this._dead) return; clearTimeout(this._t); this._t = setTimeout(() => { this._pass().catch(() => {}) }, 120) }
|
|
134
|
+
|
|
135
|
+
// BACK LEG, both directions: for each lane, the answers its assistant gave to questions it was asked go to the asker.
|
|
136
|
+
async _pass() {
|
|
137
|
+
if (this._dead) return { forwarded: 0 }
|
|
138
|
+
if (this._busy) { this._again = true; return { forwarded: 0 } }
|
|
139
|
+
this._busy = true
|
|
140
|
+
let forwarded = 0
|
|
141
|
+
try {
|
|
142
|
+
for (const lane of [this.a, this.b]) {
|
|
143
|
+
const side = this._sideOf(lane)
|
|
144
|
+
if (lane._more || !(lane._historyRead || lane._hostDriven)) continue // the lane's 'message' events re-run the pass as its history arrives — no timer here (a history that never completes spun one every 120 ms; sync sweep, 2026-10-10) // not yet the WHOLE history (a page still to come, or one that failed — `_more` alone stops being true then; sync sweep, 2026-10-10) // still reading its pages: a cursor set (or a plan made) on part of the history would forward old asks again (sync sweep, 2026-10-10)
|
|
145
|
+
const entries = lane.messages || []
|
|
146
|
+
if (this._cur[side.key] == null) { this._cur[side.key] = entries.length; continue } // first sight: no backfill
|
|
147
|
+
const { forwards, cursor } = planForward(entries, this._cur[side.key], this._sent[side.key], this.cap, isAgent)
|
|
148
|
+
let allOk = true
|
|
149
|
+
for (const f of forwards) {
|
|
150
|
+
if (f.toRoom !== side.other.room) { this._sent[side.key].push(f.corr); continue } // asked by a lane this link does not hold
|
|
151
|
+
// The reply is labelled with how the ASKER knows this lane.
|
|
152
|
+
// Already there (state machines pass 7, L#8): a post that LANDED but whose answer was lost (a 5xx, a timeout) kept
|
|
153
|
+
// the corr out of `sent`, and another device with this link open keeps its own `sent` — both carried the same
|
|
154
|
+
// answer back again. The asking lane is the record: a framed reply with this corr in it is a forward done.
|
|
155
|
+
if ((side.other.messages || []).some((e) => { const p = parseFramed(e && e.text); return p && p.kind === 'reply' && p.corr === f.corr })) { this._sent[side.key].push(f.corr); continue }
|
|
156
|
+
const framed = buildFramed({ from: side.as, fromRoom: lane.room, corr: f.corr, hop: f.hop, cap: this.cap, kind: 'reply', body: f.text })
|
|
157
|
+
if (await postAndWake(side.other, framed, side.as)) { this._sent[side.key].push(f.corr); forwarded++ } else allOk = false
|
|
158
|
+
}
|
|
159
|
+
this._sent[side.key] = this._sent[side.key].slice(-200)
|
|
160
|
+
if (allOk) this._cur[side.key] = cursor // a failed forward holds the cursor, and `sent` keeps the rest from repeating
|
|
161
|
+
}
|
|
162
|
+
} finally {
|
|
163
|
+
this._busy = false
|
|
164
|
+
if (this._again && !this._dead) { this._again = false; this._schedule() }
|
|
165
|
+
}
|
|
166
|
+
return { forwarded }
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/** OUT LEG: the `tell_lane` handler on `lane` — the device answers the turn at once with what happened. */
|
|
171
|
+
async function tellLane(lane, args) {
|
|
172
|
+
const want = String((args && args.lane) || '').trim()
|
|
173
|
+
const hit = peersOf(lane).find((p) => p.label === want)
|
|
174
|
+
if (!hit) return { ok: false, error: 'No linked assistant by that name.' }
|
|
175
|
+
const { link, peer } = hit
|
|
176
|
+
const side = link._sideOf(lane)
|
|
177
|
+
// The ask continues the chain of the message that triggered this turn (a framed peer message → hop+1, else hop 1).
|
|
178
|
+
// the LAST message decides the hop: on part of the history it is a guess that could reset the cap — the app refuses too (sync sweep, 2026-10-11)
|
|
179
|
+
if (lane._more || !(lane._historyRead || lane._hostDriven)) return { ok: false, error: 'Couldn’t read this conversation just now — try again in a moment.' }
|
|
180
|
+
const hop = askHopFrom(lane.messages || [])
|
|
181
|
+
if (!canForward(hop, link.cap)) return { ok: false, error: `This request has crossed too many lanes already (limit ${link.cap}) — answering here instead of asking on.` }
|
|
182
|
+
const corr = newCorr()
|
|
183
|
+
const framed = buildFramed({ from: side.as, fromRoom: lane.room, corr, hop, cap: link.cap, kind: 'ask', body: String((args && args.message) || '') })
|
|
184
|
+
if (link._cur[link._sideOf(peer).key] == null) {
|
|
185
|
+
// the cursor pins at the end of the peer's WHOLE history — on part of it, the pass after the ask would forward older
|
|
186
|
+
// messages as if they answered it (the app reads every page first; sync sweep 10-12)
|
|
187
|
+
if (peer._more || !(peer._historyRead || peer._hostDriven)) return { ok: false, error: `Couldn’t read ${hit.label}’s conversation just now — try again in a moment.` }
|
|
188
|
+
link._cur[link._sideOf(peer).key] = (peer.messages || []).length // the question lands after this point
|
|
189
|
+
}
|
|
190
|
+
const ok = await postAndWake(peer, framed, side.as, { ask: true })
|
|
191
|
+
return ok
|
|
192
|
+
? { ok: true, corr, message: `Sent to ${hit.label}. Its answer will arrive here shortly.` }
|
|
193
|
+
: { ok: false, error: `${hit.label} is busy right now — try again in a moment.` }
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/** `a.link(b, opts)` — checks, then the link. Lanes of ANY kind (the owner, 2026-10-11): this client copies the words
|
|
197
|
+
* between them itself; no room's key is handed to the other's tier. */
|
|
198
|
+
export function linkLanes(a, b, opts = {}, { tierMismatch } = {}) {
|
|
199
|
+
if (!b || typeof b.send !== 'function' || !b.room) throw fail('not_a_lane', 'link takes another Lane (from privateLane or openLane)')
|
|
200
|
+
if (b === a || b.room === a.room) throw fail('self_link', 'a lane cannot be linked to itself')
|
|
201
|
+
if ((a._laneLinks || []).some((l) => !l._dead && (l.a === b || l.b === b))) throw fail('already_linked', 'these two lanes are already linked')
|
|
202
|
+
return new LaneLink(a, b, opts)
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
export { parseFramed }
|
package/sdkPlan.js
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
// sdkPlan.js — say what a change to a room requires BEFORE making it (https://witbitz.chat/docs/sdk-roadmap.md, "Later": space.plan).
|
|
2
|
+
//
|
|
3
|
+
// A Space's settings live in three places, and a builder could not tell which from the outside:
|
|
4
|
+
// · IN PLACE — the assistant's name, instructions and model, and the store's collections: `space.configure()`, for
|
|
5
|
+
// every member, the history untouched;
|
|
6
|
+
// · THE MEMBERS — a new member list (the email gate, admins, owners): since 2.3.0 IN PLACE too, `space.changeMembers()` — the
|
|
7
|
+
// same room and history, a new key for the members on the list (sdkRekey.js). Only an email-gated room, by an owner or
|
|
8
|
+
// admin; in a room with owners the owners must stay (emailFork.planGovernance). a Space no longer moves (`fork()` is retired);
|
|
9
|
+
// · CREATE-TIME — the tier, a split key, the tools the assistant may use and which run without approval: a new room
|
|
10
|
+
// (`wb.createSpace`), and the SDK carries no history into it.
|
|
11
|
+
// planChange() applies exactly those rules (the same functions configure() and fork() call) and changes nothing.
|
|
12
|
+
import { planGovernance, normAdmission, forkConfig, checkAdminCollections } from './emailFork.js'
|
|
13
|
+
|
|
14
|
+
const IN_PLACE_AGENT = ['name', 'instructions', 'model']
|
|
15
|
+
const CREATE_TIME = ['tier', 'key', 'tools', 'immediateTools']
|
|
16
|
+
const IN_PLACE_ROOM = ['platformTools', 'framing', 'dataWrites', 'safeMedia', 'lanes'] // safeMedia: Safe media on/off (sync sweep 2026-10-28) // configure()'s room settings — in place, admin-ruled (spaceService MUTABLE; sync sweep, 2026-10-10)
|
|
17
|
+
const RANK = { none: 0, in_place: 1, fork: 2, new_room: 3 }
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* @param change { agent?: { name?, instructions?, model? }, data?, platformTools?, framing?, dataWrites?, admission?, tier?, key?, tools?, immediateTools? }
|
|
21
|
+
* @param room { cfg (the room's sealed config, or null), me (the signed-in email, or ''), lane (bool), checkData?(data) }
|
|
22
|
+
* → { how: 'none'|'in_place'|'new_room'|'refused', history: 'kept'|'not_carried'|null, call, steps, reason? }
|
|
23
|
+
*/
|
|
24
|
+
export function planChange (change = {}, { cfg = null, me = '', lane = false, checkData = null, gatedUnread = false, signIn = 'wb.signIn' } = {}) { // signIn: the call that signs in here ('wb.vault.signIn' in a vault) // gatedUnread: a gated room answered only its stub (not signed in)
|
|
25
|
+
const steps = []
|
|
26
|
+
let members = false // the change includes a member list (in place: space.changeMembers)
|
|
27
|
+
let how = 'none', refusal = null
|
|
28
|
+
const need = (h) => { if (RANK[h] > RANK[how]) how = h }
|
|
29
|
+
const refuse = (code, reason) => { if (!refusal) refusal = { code, reason } }
|
|
30
|
+
// a private lane follows its Space's Safe media — refused as configure() refuses it (sync sweep 2026-11-02 #2), and FIRST, as
|
|
31
|
+
// configure() checks it first: after the admin/sign-in checks a lane read signed out planned sign_in_required (2026-11-03 #6)
|
|
32
|
+
if (lane && change.safeMedia !== undefined) refuse('lane_follows_space', 'a private lane follows its Space’s Safe media — set it on the Space')
|
|
33
|
+
|
|
34
|
+
const agent = change.agent && typeof change.agent === 'object' ? change.agent : {}
|
|
35
|
+
for (const k of Object.keys(agent)) {
|
|
36
|
+
if (IN_PLACE_AGENT.includes(k)) { need('in_place'); steps.push(`agent.${k}: changed in place for every member (a system line says so)`) }
|
|
37
|
+
else if (k === 'tools') { need('new_room'); steps.push('agent.tools: chosen at creation — a new room') }
|
|
38
|
+
else refuse('unknown_field', `agent.${k} is not a setting of the assistant`)
|
|
39
|
+
}
|
|
40
|
+
for (const k of IN_PLACE_ROOM) if (change[k] !== undefined) { need('in_place'); steps.push(`${k}: changed in place for every member`) }
|
|
41
|
+
if (change.data !== undefined) {
|
|
42
|
+
need('in_place'); steps.push('data: the store\'s collections are declared or changed in place')
|
|
43
|
+
if (typeof checkData === 'function') { try { checkData(change.data) } catch (e) { refuse(e.code || 'invalid_data', String(e.message || e)) } }
|
|
44
|
+
}
|
|
45
|
+
// THE SERVER'S IN-PLACE RULES (op 'config'; sync sweep, 2026-10-10 — the plan said "in place" for changes it refuses):
|
|
46
|
+
// an owner-governed room changes by fork; a room with admins or owners takes a change from them only; an admins-only
|
|
47
|
+
// collection needs admins or owners. Judged only when the room's config could be read.
|
|
48
|
+
// only the IN-PLACE keys: `agent.tools` alone is a new room, not a change the room's admins must make
|
|
49
|
+
if (Object.keys(agent).some((k) => IN_PLACE_AGENT.includes(k)) || change.data !== undefined || IN_PLACE_ROOM.some((k) => change[k] !== undefined)) {
|
|
50
|
+
if (gatedUnread && !cfg) refuse('sign_in_required', 'an email-gated room takes a change only from a signed-in member (' + signIn + ')')
|
|
51
|
+
else if (cfg && cfg.ownerPolicy && !(cfg.ownerPolicy.policy && cfg.ownerPolicy.policy.app === 'chat.witbitz')) refuse('governed_room', 'an owner-governed room changes by fork-and-replay') // the sealed field is ownerPolicy (it read cfg.policy, which no config carries — sync sweep 2026-11-09); a room under Witbitz's own rule changes in place, as the server allows (spaceService op config)
|
|
52
|
+
else if (cfg) {
|
|
53
|
+
const gov = [...lower(cfg.admins), ...lower(cfg.owners)], email = String(me || '').toLowerCase()
|
|
54
|
+
if (gov.length && !gov.includes(email)) refuse(email ? 'not_admin' : 'sign_in_required', email ? "only this room's admins can change the assistant" : 'a room with admins takes a change only from a signed-in admin (' + signIn + ')')
|
|
55
|
+
else if (change.data !== undefined) { try { checkAdminCollections(change.data, cfg) } catch (e) { refuse(e.code || 'admins_required', String(e.message || e).replace(/^witbitz: /, '')) } }
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
for (const k of CREATE_TIME) if (change[k] !== undefined) { need('new_room'); steps.push(`${k}: chosen at creation — a new room, and the history does not come along`) }
|
|
59
|
+
|
|
60
|
+
if (change.admission !== undefined) {
|
|
61
|
+
if (lane) refuse('lane', "a lane is one member's own room — change its Space's members instead")
|
|
62
|
+
else if (gatedUnread && !cfg) { need('in_place'); refuse('sign_in_required', 'a member change needs a signed-in member (' + signIn + ')') } // a gated room read signed out: it IS gated, its gate unread
|
|
63
|
+
else if (!cfg || cfg.admission !== 'email') { need('new_room'); steps.push("admission: an open room's link IS its membership — gate a new room (createSpace({ admission })); the history does not come along") }
|
|
64
|
+
else {
|
|
65
|
+
// A gate fork() would refuse is a refusal here, never a throw (sync sweep, 2026-10-12: normAdmission throws).
|
|
66
|
+
let gate = null, bad = null
|
|
67
|
+
try { gate = normAdmission(change.admission) } catch (e) { bad = e }
|
|
68
|
+
if (bad) refuse(bad.code || 'invalid_admission', String(bad.message || bad).replace(/^witbitz: /, ''))
|
|
69
|
+
else if (!gate) refuse('invalid_admission', 'admission needs at least one address or domain')
|
|
70
|
+
else {
|
|
71
|
+
// ONLY IN PLACE (2.3.0; the owner, 2026-10-23: "only in place"): the same room and history, a new key for the members on
|
|
72
|
+
// the list (sdkRekey.js, sdk-people.md#members). A Space no longer moves, so a change that names a `history` is refused by name.
|
|
73
|
+
if (change.history !== undefined) refuse('use_change_members', 'a Space no longer moves to a new room — its members change in place, history and all (space.changeMembers)')
|
|
74
|
+
need('in_place'); members = true; steps.push('admission: changed in place — the same room and history, a new key that only the members on the list receive (space.changeMembers)')
|
|
75
|
+
const admins = lower(cfg.admins), owners = lower(cfg.owners), email = String(me || '').toLowerCase()
|
|
76
|
+
if (!email) refuse('sign_in_required', 'a member change needs a signed-in member (' + signIn + ')')
|
|
77
|
+
else if (!admins.length && !owners.length) refuse('not_admin', 'this Space has no owners or admins — only the Spaces app can change it (its creator)')
|
|
78
|
+
else if ((admins.length || owners.length) && !admins.includes(email) && !owners.includes(email)) refuse('not_admin', "only this room's owners and admins change its members")
|
|
79
|
+
else {
|
|
80
|
+
// the same two checks space.fork() makes, in its order: governance, then an admins-only collection the
|
|
81
|
+
// new room would keep with no admin or owner (emailFork.checkAdminCollections; sync sweep, 2026-10-10)
|
|
82
|
+
try { planGovernance(cfg, gate, email, change.admission.admins !== undefined); const next = forkConfig(cfg, gate, ''); checkAdminCollections(next.dataSchema, next) } catch (e) { refuse(e.code || 'refused', String(e.message || e).replace(/^witbitz: /, '')) } }
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
if (refusal) return { how: 'refused', history: null, call: null, steps, reason: refusal.reason, code: refusal.code }
|
|
88
|
+
const history = how === 'new_room' ? 'not_carried' : how === 'in_place' ? 'kept' : null
|
|
89
|
+
const configures = steps.some((x) => !/^admission:/.test(x))
|
|
90
|
+
const call = how === 'in_place' ? (members ? (configures ? 'space.configure(…) and space.changeMembers(admission)' : 'space.changeMembers(admission)') : 'space.configure(…)') : how === 'new_room' ? 'wb.createSpace(…)' : null
|
|
91
|
+
return { how, history, call, steps }
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
const lower = (g) => (g && Array.isArray(g.emails) ? g.emails.map((x) => String(x).toLowerCase()) : [])
|
package/sdkProtect.js
ADDED
|
@@ -0,0 +1,228 @@
|
|
|
1
|
+
// sdkProtect.js — wb.protect: DEVICE STORAGE PROTECTION for what an app keeps on the device (https://witbitz.chat/docs/sdk-accounts.md#protect). The owner, 2026-10-06: "Build it and then use it in spaces".
|
|
2
|
+
//
|
|
3
|
+
// The SDK hands an app JSON to persist — the sign-in session, room snapshots (they carry room keys), the Siri / A2A /
|
|
4
|
+
// backup state (private keys) — and an infostealer copies localStorage along with the rest of the profile. With
|
|
5
|
+
// protection on, every value the app writes through `save()` / `seal()` is AES-GCM ciphertext under a key a PLATFORM
|
|
6
|
+
// passkey derives (Windows Hello → TPM, Touch ID → Secure Enclave, Android → StrongBox): PRF, or a secret stored in the
|
|
7
|
+
// credential's largeBlob. That key is nowhere on disk; this object holds it in memory while unlocked and drops it on lock.
|
|
8
|
+
//
|
|
9
|
+
// const p = wb.protect
|
|
10
|
+
// p.available() → can this browser hold such a passkey at all
|
|
11
|
+
// await p.enable({ label }) one passkey; everything already saved through save() is sealed in place
|
|
12
|
+
// await p.save(name, value) / load(name) / remove(name) a Storage (localStorage by default), sealed while on
|
|
13
|
+
// await p.seal(value) / open(stored) for a store of the app's own; both pass values through while protection is off
|
|
14
|
+
// p.lock() / await p.unlock() drop the key / a user-verified passkey assertion brings it back
|
|
15
|
+
// p.autoLock(minutes) lock when the page comes back after being hidden longer than this
|
|
16
|
+
// await p.disable() write what save() wrote back in the clear, forget the protection
|
|
17
|
+
// p.on('locked' | 'unlocked' | 'change', cb) → unsubscribe
|
|
18
|
+
//
|
|
19
|
+
// ⚑ A LOST PASSKEY LOSES THE SEALED STATE. `enable()` refuses unless the account backup is on (wb.backup) or the app says
|
|
20
|
+
// `withoutBackup: true` — the backup is what brings the rooms back on a new device.
|
|
21
|
+
// ⚑ The Spaces app takes its passkey → key step from here too (enrollProtectKey / unlockProtectKey): one derivation, and
|
|
22
|
+
// the protection passkey under its OWN user handle, so it never replaces the account's recovery passkey (spacePasskey.js).
|
|
23
|
+
import { deriveSealRaw, importRaw, seal as sealWith, open as openWith, isSealed } from './deviceSeal.js'
|
|
24
|
+
import { passkeyPossible, enrollPasskey, unlockPasskey, describePasskey } from './spacePasskey.js'
|
|
25
|
+
|
|
26
|
+
export const PROTECT_CFG = 'witbitz:protect'
|
|
27
|
+
/** The protection passkey's own user handle (spacePasskey.js keys one handle per purpose). A shared handle REPLACED the
|
|
28
|
+
* account's recovery passkey: an authenticator keeps one credential per (site, user handle). */
|
|
29
|
+
export const PROTECT_USER_KEY = 'space:pkuser:protect'
|
|
30
|
+
const CHECK = 'witbitz-protect-check-v1' // sealed into the config at enable: an unlock knows it has the right key before it opens anything
|
|
31
|
+
const fail = (code, msg) => Object.assign(new Error('witbitz: ' + msg), { code })
|
|
32
|
+
|
|
33
|
+
/** The browser's WebAuthn as a passkey for protection: { possible, enroll(label) → { credId, secret, mode },
|
|
34
|
+
* unlock(credId) → { credId, secret, mode, secrets } }. `rpId` / `rpName` default to this page's host. */
|
|
35
|
+
export function webauthnPasskey ({ rpId, rpName, userName = 'Device protection', userKey = PROTECT_USER_KEY } = {}) {
|
|
36
|
+
return {
|
|
37
|
+
// A SECURE CONTEXT, not only https: a builder developing on http://localhost has WebAuthn too (passkeyPossible() asks https).
|
|
38
|
+
possible: () => { try { return passkeyPossible() || !!(typeof window !== 'undefined' && window.isSecureContext && window.PublicKeyCredential && navigator.credentials && navigator.credentials.create) } catch { return false } },
|
|
39
|
+
enroll: (label) => enrollPasskey(label, rpId, { rpName: rpName || (typeof location !== 'undefined' ? location.hostname : ''), userName, userKey }),
|
|
40
|
+
unlock: (credId) => unlockPasskey(credId, rpId),
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** The secret an assertion answered for this mode — a credential can answer both (a PRF and a largeBlob), and only the one
|
|
45
|
+
* protection was enabled with opens what it sealed. */
|
|
46
|
+
const secretsOf = (r, mode) => {
|
|
47
|
+
const all = (r && Array.isArray(r.secrets) && r.secrets.length ? r.secrets : (r && r.secret ? [{ secret: r.secret, mode: r.mode }] : []))
|
|
48
|
+
return [...all.filter((s) => s.mode === mode), ...all.filter((s) => s.mode !== mode)]
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** THE SHARED STEP, for an app with stores of its own (the Spaces app): a new protection passkey → { credId, mode, raw },
|
|
52
|
+
* `raw` being the 32 device-key bytes (deviceSeal.importRaw makes the key). */
|
|
53
|
+
export async function enrollProtectKey (label, { rpId, passkey } = {}) {
|
|
54
|
+
const pk = passkey || webauthnPasskey({ rpId, rpName: 'Witbitz Spaces', userName: describePasskey('Spaces device protection') }) // purpose · device · date in the keychain
|
|
55
|
+
const r = await pk.enroll(label)
|
|
56
|
+
if (!r || !r.secret) throw fail('prf_unsupported', 'this passkey cannot hold a key')
|
|
57
|
+
return { credId: r.credId, mode: r.mode || 'prf', raw: await deriveSealRaw(r.secret) }
|
|
58
|
+
}
|
|
59
|
+
/** …and an unlock with it → { credId, mode, raw }. `mode` picks the secret protection was enabled with. */
|
|
60
|
+
export async function unlockProtectKey (credId, mode, { rpId, passkey } = {}) {
|
|
61
|
+
const pk = passkey || webauthnPasskey({ rpId })
|
|
62
|
+
const r = await pk.unlock(credId)
|
|
63
|
+
const [s] = secretsOf(r, mode)
|
|
64
|
+
if (!s) throw fail('wrong_passkey', 'the passkey answered no key')
|
|
65
|
+
return { credId: r.credId || credId, mode: s.mode || mode, raw: await deriveSealRaw(s.secret) }
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export class Protect {
|
|
69
|
+
/** @param {object} o { storage?, storeKey?, passkey?, backup?, rpId?, rpName?, doc?, now? } — `storage` is a Storage
|
|
70
|
+
* (localStorage by default), `backup` the account backup (wb.backup), `passkey` replaces WebAuthn (tests, a native shell). */
|
|
71
|
+
constructor ({ storage, storeKey = PROTECT_CFG, passkey, backup = null, rpId, rpName, doc, now } = {}) {
|
|
72
|
+
const hidden = (k, v) => Object.defineProperty(this, k, { value: v, writable: true, enumerable: false, configurable: true })
|
|
73
|
+
hidden('_storage', storage || (typeof localStorage !== 'undefined' ? localStorage : null))
|
|
74
|
+
hidden('_storeKey', storeKey)
|
|
75
|
+
hidden('_pk', passkey || webauthnPasskey({ rpId, rpName }))
|
|
76
|
+
hidden('_backup', backup)
|
|
77
|
+
hidden('_doc', doc || (typeof document !== 'undefined' ? document : null))
|
|
78
|
+
hidden('_now', typeof now === 'function' ? now : () => Date.now())
|
|
79
|
+
hidden('_key', null) // the AES-GCM key — in memory only, and only while unlocked
|
|
80
|
+
hidden('_ls', { locked: new Set(), unlocked: new Set(), change: new Set() })
|
|
81
|
+
hidden('_away', null)
|
|
82
|
+
if (this._cfg().auto) this._watch()
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
_cfg () { try { return JSON.parse((this._storage && this._storage.getItem(this._storeKey)) || 'null') || {} } catch { return {} } }
|
|
86
|
+
_setCfg (c) { if (!this._storage) return; if (c) this._storage.setItem(this._storeKey, JSON.stringify(c)); else this._storage.removeItem(this._storeKey) }
|
|
87
|
+
_emit (ev) { for (const f of [...this._ls[ev], ...(ev === 'change' ? [] : this._ls.change)]) { try { f(this.state) } catch { /* a listener must not break the lock */ } } }
|
|
88
|
+
|
|
89
|
+
/** { on, locked, mode, auto } — `locked` is true while protection is on and the key is not in memory. */
|
|
90
|
+
get state () { const c = this._cfg(); return { on: !!c.on, locked: !!c.on && !this._key, mode: c.on ? c.mode || null : null, auto: +c.auto || 0 } }
|
|
91
|
+
toJSON () { return { protect: this.state } }
|
|
92
|
+
|
|
93
|
+
/** Can this browser hold a protection passkey (WebAuthn on https)? PRF / largeBlob support is only known at enable. */
|
|
94
|
+
available () {
|
|
95
|
+
try {
|
|
96
|
+
const policy = globalThis.document?.permissionsPolicy || globalThis.document?.featurePolicy
|
|
97
|
+
if (globalThis.window && window.parent !== window && policy?.allowsFeature &&
|
|
98
|
+
(!policy.allowsFeature('publickey-credentials-create') || !policy.allowsFeature('publickey-credentials-get'))) return false
|
|
99
|
+
return !!this._pk.possible()
|
|
100
|
+
} catch { return false }
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
on (ev, cb) { const s = this._ls[ev]; if (!s || typeof cb !== 'function') throw fail('bad_event', 'protect events are locked, unlocked and change'); s.add(cb); return () => s.delete(cb) }
|
|
104
|
+
|
|
105
|
+
async enable ({ label = '', withoutBackup = false } = {}) {
|
|
106
|
+
if (this._cfg().on) throw fail('already_enabled', 'protection is already on for this app on this device')
|
|
107
|
+
if (!this.available()) throw fail('unavailable', 'this browser cannot hold a passkey for storage protection')
|
|
108
|
+
// No backup to check (a Protect made before its client, or alone) is no backup: never a silently skipped guard (code review).
|
|
109
|
+
if (!withoutBackup && !(this._backup && this._backup.enabled)) throw fail('backup_required', 'turn on the account backup (wb.backup) first: a lost passkey would lose everything sealed under it (or pass withoutBackup: true)')
|
|
110
|
+
const r = await this._pk.enroll(label || 'Device protection')
|
|
111
|
+
if (!r || !r.secret) throw fail('prf_unsupported', 'this passkey cannot hold a key')
|
|
112
|
+
const mode = r.mode || 'prf'
|
|
113
|
+
const key = await importRaw(await deriveSealRaw(r.secret))
|
|
114
|
+
// pass 7, F#7: the check is sealed BEFORE the config is read — a name save() added while it was awaited (the config read
|
|
115
|
+
// before it) was dropped from `keys` by the write below, and its value stayed clear for good
|
|
116
|
+
const check = await sealWith(key, CHECK)
|
|
117
|
+
const prev = this._cfg()
|
|
118
|
+
// RECORD THE SWITCH FIRST, the key held — then seal what was saved while off. A crash in between leaves clear values,
|
|
119
|
+
// which read as they are and are sealed at the next unlock (_sealPending). The other order (seal, then record) left
|
|
120
|
+
// sealed values behind an "off" config with no passkey recorded: unopenable for good (code review, 2026-10-06).
|
|
121
|
+
this._key = key
|
|
122
|
+
this._setCfg({ on: true, credId: r.credId, mode, at: this._now(), check, keys: Array.isArray(prev.keys) ? prev.keys : [], auto: +prev.auto || 0 })
|
|
123
|
+
await this._sealPending()
|
|
124
|
+
this._emit('unlocked')
|
|
125
|
+
return this.state
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
async unlock () {
|
|
129
|
+
const c = this._cfg()
|
|
130
|
+
if (!c.on) throw fail('not_enabled', 'protection is off')
|
|
131
|
+
if (this._key) return this.state
|
|
132
|
+
const r = await this._pk.unlock(c.credId)
|
|
133
|
+
for (const s of secretsOf(r, c.mode)) {
|
|
134
|
+
let key = null
|
|
135
|
+
try { key = await importRaw(await deriveSealRaw(s.secret)); if (await openWith(key, c.check) !== CHECK) key = null } catch { key = null }
|
|
136
|
+
if (key) { this._key = key; try { await this._sealPending() } catch { /* a full disk must not cost the unlock */ } this._emit('unlocked'); return this.state }
|
|
137
|
+
}
|
|
138
|
+
throw fail('wrong_passkey', 'that passkey does not open this device\'s protected storage')
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/** Seal every value save() wrote that is still clear — what an interrupted enable() left behind. */
|
|
142
|
+
async _sealPending () {
|
|
143
|
+
if (!this._key) return
|
|
144
|
+
for (const k of Array.isArray(this._cfg().keys) ? this._cfg().keys : []) { const v = this._read(k); if (v !== undefined && !isSealed(v)) this._write(k, await sealWith(this._key, v)) }
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
lock () { const was = !!this._key; this._key = null; if (was && this._cfg().on) this._emit('locked'); return this.state }
|
|
148
|
+
|
|
149
|
+
// ONE AT A TIME (state machines pass 7, F#8): disable() opens and rewrites every saved value across awaits, and a save() that
|
|
150
|
+
// finished in between left a sealed value behind the "off" it then wrote — load() deletes those. The two run in order.
|
|
151
|
+
_serial (fn) { const run = (this._chain || Promise.resolve()).then(fn, fn); this._chain = run.catch(() => {}); return run }
|
|
152
|
+
|
|
153
|
+
async disable () { return this._serial(() => this._disable()) }
|
|
154
|
+
async _disable () {
|
|
155
|
+
const c = this._cfg()
|
|
156
|
+
if (!c.on) return this.state
|
|
157
|
+
if (!this._key) await this.unlock() // the passkey confirms it, and its key writes the values back
|
|
158
|
+
const key = this._key
|
|
159
|
+
// a value sealed by an EARLIER setup (another passkey) never opens: dropped, not a throw that leaves protection half off (sync sweep backlog P3)
|
|
160
|
+
for (const k of Array.isArray(c.keys) ? c.keys : []) { const v = this._read(k); if (isSealed(v)) { let clear; try { clear = await openWith(key, v) } catch { this._storage.removeItem(k); continue } this._write(k, clear) } }
|
|
161
|
+
this._key = null
|
|
162
|
+
this._setCfg(c.auto || (c.keys && c.keys.length) ? { on: false, keys: c.keys || [], auto: +c.auto || 0 } : null)
|
|
163
|
+
this._emit('change')
|
|
164
|
+
return this.state
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/** Seal a value for a store of the app's own — the value itself while protection is off. Refuses while locked. */
|
|
168
|
+
async seal (value) {
|
|
169
|
+
if (!this._cfg().on) return value
|
|
170
|
+
if (!this._key) throw fail('locked', 'protected storage is locked — wb.protect.unlock() first')
|
|
171
|
+
return sealWith(this._key, value)
|
|
172
|
+
}
|
|
173
|
+
/** Open what seal() returned — a clear value passes through. Refuses a sealed one while locked. */
|
|
174
|
+
async open (stored) {
|
|
175
|
+
if (!isSealed(stored)) return stored
|
|
176
|
+
if (!this._key) throw fail('locked', 'protected storage is locked — wb.protect.unlock() first')
|
|
177
|
+
return openWith(this._key, stored)
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
_read (name) { const s = this._storage && this._storage.getItem(name); if (s == null) return undefined; try { return JSON.parse(s) } catch { return s } }
|
|
181
|
+
_write (name, v) { this._storage.setItem(name, JSON.stringify(v)) }
|
|
182
|
+
/** Persist `value` under `name` in the Storage — sealed while protection is on, and resealed / written back clear when it changes. */
|
|
183
|
+
async save (name, value) { return this._serial(() => this._save(name, value)) }
|
|
184
|
+
async _save (name, value) {
|
|
185
|
+
if (!this._storage) throw fail('no_storage', 'no Storage to save into (pass storage to wb.protect)')
|
|
186
|
+
const c = this._cfg()
|
|
187
|
+
if (c.on && !this._key) throw fail('locked', 'protected storage is locked — wb.protect.unlock() first')
|
|
188
|
+
const keys = Array.isArray(c.keys) ? c.keys : []
|
|
189
|
+
if (!keys.includes(name)) this._setCfg({ ...c, keys: [...keys, String(name)] })
|
|
190
|
+
if (!c.on) { this._write(name, value); return }
|
|
191
|
+
const sealed = await sealWith(this._key, value)
|
|
192
|
+
// pass 7, F#8: disable() ran while it was sealed — a sealed value behind an "off" config is what load() deletes; write it clear
|
|
193
|
+
this._write(name, this._cfg().on ? sealed : value)
|
|
194
|
+
}
|
|
195
|
+
/** The value saved under `name` (undefined if none). Refuses a sealed one while locked. */
|
|
196
|
+
async load (name) {
|
|
197
|
+
const v = this._read(name)
|
|
198
|
+
if (v === undefined) return undefined
|
|
199
|
+
if (!isSealed(v)) return v
|
|
200
|
+
// sealed while protection is OFF, or sealed under another key: an earlier setup's leftover, which nothing can open — it
|
|
201
|
+
// reads as absent and goes, never a throw (sync sweep backlog P3). Sealed under THIS key while locked still refuses.
|
|
202
|
+
if (!this._cfg().on) { this._storage.removeItem(name); return undefined }
|
|
203
|
+
if (!this._key) throw fail('locked', 'protected storage is locked — wb.protect.unlock() first')
|
|
204
|
+
try { return await openWith(this._key, v) } catch { this._storage.removeItem(name); return undefined }
|
|
205
|
+
}
|
|
206
|
+
remove (name) {
|
|
207
|
+
if (this._storage) this._storage.removeItem(name)
|
|
208
|
+
const c = this._cfg(); if (Array.isArray(c.keys) && c.keys.includes(name)) this._setCfg({ ...c, keys: c.keys.filter((k) => k !== name) })
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/** Lock when the page returns after being hidden longer than `minutes` (0 = only an explicit lock() or a new launch). */
|
|
212
|
+
autoLock (minutes) {
|
|
213
|
+
const m = Math.max(0, +minutes || 0)
|
|
214
|
+
const c = this._cfg(); this._setCfg({ ...c, auto: m, keys: c.keys || [] })
|
|
215
|
+
if (m) this._watch()
|
|
216
|
+
return this.state
|
|
217
|
+
}
|
|
218
|
+
_watch () {
|
|
219
|
+
if (this._away || !this._doc || !this._doc.addEventListener) return
|
|
220
|
+
this._away = { at: 0 }
|
|
221
|
+
this._doc.addEventListener('visibilitychange', () => {
|
|
222
|
+
const auto = +this._cfg().auto || 0
|
|
223
|
+
if (this._doc.hidden) { this._away.at = this._now(); return }
|
|
224
|
+
if (auto && this._away.at && this._now() - this._away.at > auto * 60000) this.lock()
|
|
225
|
+
this._away.at = 0
|
|
226
|
+
})
|
|
227
|
+
}
|
|
228
|
+
}
|
package/sdkRedact.js
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
// sdkRedact.js — keep a room's key out of a builder's logs (https://witbitz.chat/docs/sdk-roadmap.md, item 1, measured 2026-10-05).
|
|
2
|
+
//
|
|
3
|
+
// A Space's link and key ARE the admission: whoever holds them is a member. `console.log(space)` printed both (`_mk`,
|
|
4
|
+
// `shareLink` were plain enumerable properties), and an error reporter that walks objects (`Sentry.setContext('space',
|
|
5
|
+
// space)`) would have sent them to a third party. Two layers, so either habit is covered:
|
|
6
|
+
// 1. hide() — the credential-bearing properties become NON-ENUMERABLE: still readable and writable by name (the SDK's
|
|
7
|
+
// own code and `space.shareLink` / `space.key` are unchanged), invisible to Object.keys, for…in, spread, JSON and
|
|
8
|
+
// every walker that follows enumerable keys.
|
|
9
|
+
// 2. redacted() — `toJSON()` and Node's `inspect.custom` print a short summary with `[REDACTED]` in place of each secret.
|
|
10
|
+
// Browsers' consoles show non-enumerable properties greyed out when an object is EXPANDED by hand; that is the developer
|
|
11
|
+
// opening the object on their own screen, not a log leaving it.
|
|
12
|
+
|
|
13
|
+
export const REDACTED = '[REDACTED]'
|
|
14
|
+
export const INSPECT = Symbol.for('nodejs.util.inspect.custom')
|
|
15
|
+
|
|
16
|
+
/** Make `names` on `obj` non-enumerable, keeping their values and writability. Missing names are created undefined. */
|
|
17
|
+
export function hide(obj, names) {
|
|
18
|
+
for (const n of names) {
|
|
19
|
+
const d = Object.getOwnPropertyDescriptor(obj, n)
|
|
20
|
+
Object.defineProperty(obj, n, { value: d ? d.value : undefined, writable: true, configurable: true, enumerable: false })
|
|
21
|
+
}
|
|
22
|
+
return obj
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** Install toJSON + inspect.custom on a class prototype. `summary(self)` returns the plain object to show. */
|
|
26
|
+
export function redacted(proto, summary) {
|
|
27
|
+
Object.defineProperty(proto, 'toJSON', { value: function toJSON() { return summary(this) }, writable: true, configurable: true })
|
|
28
|
+
Object.defineProperty(proto, INSPECT, {
|
|
29
|
+
value: function inspect(depth, options, nodeInspect) {
|
|
30
|
+
const s = summary(this)
|
|
31
|
+
const name = (this && this.constructor && this.constructor.name) || 'Object'
|
|
32
|
+
return typeof nodeInspect === 'function' ? `${name} ${nodeInspect(s, options)}` : { [name]: s }
|
|
33
|
+
},
|
|
34
|
+
writable: true, configurable: true,
|
|
35
|
+
})
|
|
36
|
+
}
|