@witbitz/sdk 0.0.0-stage → 4.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +20 -2
- package/a2aCore.js +221 -0
- package/a2aShared.js +27 -0
- package/accountErase.js +228 -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/agentDoorTools.js +28 -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 +165 -0
- package/chatLockSw.js +13 -0
- package/cloudDeviceBuilds.js +11 -0
- package/cloudDevicePins.js +33 -0
- package/cloudDeviceSeal.js +53 -0
- package/codeAttachments.js +100 -0
- package/codeBrowse.js +224 -0
- package/codeCache.js +149 -0
- package/codeCloud.js +650 -0
- package/codeCloudKeys.js +112 -0
- package/codeCommands.js +167 -0
- package/codeComputers.js +389 -0
- package/codeEgress.js +123 -0
- package/codeFilesRoutes.js +17 -0
- package/codeFolders.js +116 -0
- package/codeHistory.js +76 -0
- package/codeLanguage.js +54 -0
- package/codeMkdir.js +8 -0
- package/codeModes.js +59 -0
- package/codeOrphanKeys.js +42 -0
- package/codeOutputs.js +141 -0
- package/codeProgress.js +54 -0
- package/codeRelay.js +505 -0
- package/codeSent.js +68 -0
- package/codeSentinel.js +86 -0
- package/codeSubagents.js +107 -0
- package/codeTransport.js +317 -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 +561 -0
- package/credits.js +30 -0
- package/csAttest.js +112 -0
- package/decrypt.html +384 -0
- package/deviceAttest.js +527 -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 +113 -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 +91 -0
- package/l1-worker-src.js +2 -0
- package/l1-worker.js +894 -0
- package/laneAssociation.js +68 -0
- package/laneConfig.js +58 -0
- package/laneLinkCore.js +177 -0
- package/ledgerView.js +64 -0
- package/manifest.json +239 -0
- package/mcpRecommended.js +25 -0
- package/memberChange.js +125 -0
- package/mirrorBatch.js +47 -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/opRouting.js +10 -0
- package/opencodeWire.js +282 -0
- package/oprf.js +70 -0
- package/ownAgentLink.js +96 -0
- package/ownerPolicy.js +117 -0
- package/package.json +273 -4
- package/pdfOptions.js +13 -0
- package/pdfText.js +107 -0
- package/pdfjs.mjs +28 -0
- package/pdfjs.worker.mjs +28 -0
- package/pollVerdict.js +33 -0
- package/prefetchPoll.js +60 -0
- package/protectedLocal.js +426 -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/roomEmbed.js +111 -0
- package/roomName.js +177 -0
- package/roomPass.js +256 -0
- package/roomRoster.js +305 -0
- package/roomSettings.js +61 -0
- package/roomState.js +58 -0
- package/roomStreamClient.js +115 -0
- package/rosterCount.js +52 -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 +524 -0
- package/sdkAccount.js +483 -0
- package/sdkAccountDoc.js +89 -0
- package/sdkAccountSections.js +332 -0
- package/sdkAgui.js +141 -0
- package/sdkAttest.js +34 -0
- package/sdkBackup.js +507 -0
- package/sdkBackupV2.js +630 -0
- package/sdkBrowserPrivate.js +28 -0
- package/sdkBuilds.js +208 -0
- package/sdkCloudDevice.js +221 -0
- package/sdkComputers.js +1009 -0
- package/sdkDictation.js +232 -0
- package/sdkErase.js +288 -0
- package/sdkExports.js +71 -0
- package/sdkInvitations.js +34 -0
- package/sdkKeptAgent.js +188 -0
- package/sdkLaneLink.js +205 -0
- package/sdkPlan.js +96 -0
- package/sdkProtect.js +228 -0
- package/sdkRedact.js +36 -0
- package/sdkRekey.js +340 -0
- package/sdkReport.js +68 -0
- package/sdkSafeMedia.js +255 -0
- package/sdkSchedules.js +39 -0
- package/sdkSpeech.js +71 -0
- package/sdkTemporaryRooms.js +123 -0
- package/sdkTurn.js +117 -0
- package/sdkVault.js +180 -0
- package/sealShare.js +18 -0
- package/sealedNames.js +64 -0
- package/sealedReceipt.js +17 -0
- package/sentinelRelease.js +155 -0
- package/shamir.js +85 -0
- package/sharedViews.js +52 -0
- package/sheetChrome.js +450 -0
- package/siri.js +278 -0
- package/spaceClient.js +1429 -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/spaceTemplates.js +99 -0
- package/speechOut.js +102 -0
- package/splitKeyClient.js +90 -0
- package/store.js +656 -0
- package/streamHint.js +36 -0
- package/sttCloud.js +220 -0
- package/sttWorklet.js +38 -0
- package/sw-notif-core.js +540 -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 +37 -0
- package/usageReceipts.js +176 -0
- package/usageSummary.js +90 -0
- package/util.js +181 -0
- package/vault-core.js +2326 -0
- package/vault-kit.mjs +354 -0
- package/vault-screens.js +261 -0
- package/vaultAtRest.js +208 -0
- package/vaultCoreLock.js +111 -0
- package/vaultCorePush.js +140 -0
- package/vaultDeviceKey.js +95 -0
- package/vaultEnclaveHandoff.js +114 -0
- package/vaultKeep.js +287 -0
- package/vaultSealedStore.js +77 -0
- package/vaultWorkerHost.js +117 -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 +1460 -0
- package/witbitz-sdk.d.ts +1197 -0
- package/witbitz-sdk.js +4258 -0
- package/workerClient.js +16 -0
- package/workerLiveness.js +21 -0
- package/x509.js +218 -0
package/spaceExport.js
ADDED
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
// Export / recreate a Space (this file is the description — there is no separate doc). EXPORT decrypts the FULL ledger + the agent config into a portable,
|
|
2
|
+
// human-readable JSON — for debugging, a plaintext backup, and recreating the room elsewhere. RECREATE mints a fresh
|
|
3
|
+
// room from such a bundle (its config) and replays the entries (mirror, server-deduped by id). Unlike the sealed offline
|
|
4
|
+
// backup (offlineBundle.js), this file is DECRYPTED cleartext — treat it exactly like the conversation it contains.
|
|
5
|
+
const EXPORT_KIND = 'witbitz-space-export'
|
|
6
|
+
|
|
7
|
+
// Build a decrypted snapshot of a room: { v, kind, room, title, exportedAt, count, config?, entries }.
|
|
8
|
+
// entries = the COMPLETE ledger (poll with sinceCount=0 returns all of it, decrypted). config is best-effort.
|
|
9
|
+
// READER, not (mk, client). The export is now assembled ENTIRELY IN L1: `reader` is the l1 façade, so the ledger is
|
|
10
|
+
// polled and the config read by the realm that HOLDS mk, and only plaintext comes back. The app never needs the key.
|
|
11
|
+
//
|
|
12
|
+
// That is what finally fixes this. The old signature forced the caller to produce mk in the app realm, which under
|
|
13
|
+
// mk-confinement it does not have — and the three attempts to find it there each failed differently: `recallMk` (the
|
|
14
|
+
// main thread has none), then `awaitVaultKey` (the vault answers from a page-level keyring that a worker-remembered
|
|
15
|
+
// key never reaches). Asking the holder to do the work removes the question instead of answering it.
|
|
16
|
+
//
|
|
17
|
+
// `reader` needs exactly two methods, both already l1 ops: poll(room, undefined, 0) and getConfig(room).
|
|
18
|
+
import { readAllPages } from './ledgerView.js'
|
|
19
|
+
export async function exportSpace(room, reader, meta = {}) {
|
|
20
|
+
if (!room || !reader || typeof reader.poll !== 'function') throw new Error('bad_args')
|
|
21
|
+
const p = await readAllPages((since) => reader.poll(room, undefined, since)) // the whole history, every page
|
|
22
|
+
// A page that failed would make a SHORT export look whole: refuse it, so the person tries again (sync sweep, 2026-10-10).
|
|
23
|
+
if (p && p.incomplete) throw Object.assign(new Error('export_incomplete'), { userMsg: 'Part of this Space’s history couldn’t be read — try the export again.' })
|
|
24
|
+
const raw = p && Array.isArray(p.entries) ? p.entries : []
|
|
25
|
+
// Collapse fork/relink mirror duplicates by canonical id (a fork changes the `sh:<sharedRoom>:` prefix), so an export
|
|
26
|
+
// matches what's shown in-app and a recreate doesn't carry doubles — even if the server ledger hasn't been collapsed yet.
|
|
27
|
+
const canon = (id) => { const s = String(id == null ? '' : id); const m = /^sh:sp-[^:]+:(.+)$/.exec(s); return m ? 'sh:' + m[1] : s }
|
|
28
|
+
const seenC = new Set()
|
|
29
|
+
const entries = raw.filter((e) => { if (!e || e.id == null) return true; const c = canon(e.id); if (seenC.has(c)) return false; seenC.add(c); return true })
|
|
30
|
+
let config = null
|
|
31
|
+
try { config = typeof reader.getConfig === 'function' ? await reader.getConfig(room) : null } catch { /* config is best-effort — a ledger-only export is still useful */ }
|
|
32
|
+
const withBytes = typeof reader.blob === 'function' ? await Promise.all(entries.map((e) => inlineAttachments(e, room, reader))) : entries
|
|
33
|
+
// DIAGNOSTICS (the owner, 2026-10-04, after a members sheet nobody could explain from the file: "add more info to the
|
|
34
|
+
// export"). The guest book and the server's sign-in records are what the members sheet is built from; the authors
|
|
35
|
+
// summary says which keys each name posted under; `device` is what the exporting device holds (public keys only).
|
|
36
|
+
let guestBook = null
|
|
37
|
+
try {
|
|
38
|
+
const g = typeof reader.state === 'function' ? await reader.state(room, 'roster') : null
|
|
39
|
+
if (g && (g.state || g.seen)) guestBook = { people: (g.state && Array.isArray(g.state.people)) ? g.state.people : [], ...(g.seen ? { seen: g.seen } : {}) }
|
|
40
|
+
} catch { /* best-effort, like the config */ }
|
|
41
|
+
return {
|
|
42
|
+
v: 1, kind: EXPORT_KIND, room, title: meta.title || '', exportedAt: meta.now || Date.now(), count: entries.length,
|
|
43
|
+
...(meta.device ? { device: meta.device } : {}),
|
|
44
|
+
...(config ? { config } : {}),
|
|
45
|
+
...(guestBook ? { guestBook } : {}),
|
|
46
|
+
authors: authorsOf(entries),
|
|
47
|
+
entries: withBytes,
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
const keyIdOf = (k) => (k && k.x && k.y ? k.x.slice(0, 8) + '…' : '')
|
|
52
|
+
/** Per author: how many entries, under which signing keys, verified or not, the attested @username, first/last time. */
|
|
53
|
+
export function authorsOf(entries = []) {
|
|
54
|
+
const by = new Map()
|
|
55
|
+
for (const e of entries) {
|
|
56
|
+
if (!e || e.self) continue
|
|
57
|
+
const name = String(e.name || e.from || (e.kind === 'agent' ? 'agent' : '?'))
|
|
58
|
+
const a = by.get(name) || { name, kinds: {}, entries: 0, verified: 0, keys: [], first: e.ts || 0, last: e.ts || 0 }
|
|
59
|
+
a.entries++; if (e.verified === true) a.verified++
|
|
60
|
+
a.kinds[e.kind || 'text'] = (a.kinds[e.kind || 'text'] || 0) + 1
|
|
61
|
+
if (e.user && !a.user) a.user = e.user
|
|
62
|
+
const k = keyIdOf(e.spk || e.vspk); if (k && !a.keys.includes(k)) a.keys.push(k)
|
|
63
|
+
if (e.ts) { a.first = Math.min(a.first || e.ts, e.ts); a.last = Math.max(a.last, e.ts) }
|
|
64
|
+
by.set(name, a)
|
|
65
|
+
}
|
|
66
|
+
return [...by.values()]
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
// An export is the WHOLE conversation, attachments included. A photo or document stored OUT OF LINE is a pointer in its
|
|
70
|
+
// entry (`ref` / `parts`) to a blob sealed to THIS room's key — useless in a file, and useless to a recreated room (a new
|
|
71
|
+
// key). So the export carries the bytes inline (reader.blob = the l1 op that opens a blob), and a recreate's mirror
|
|
72
|
+
// stores them out of line again under the new room. Best-effort per attachment: one that will not open keeps its pointer.
|
|
73
|
+
const isStored = (a) => !!a && !(typeof a.b64 === 'string' && a.b64) && ((typeof a.ref === 'string' && !!a.ref) || (Array.isArray(a.parts) && a.parts.length > 0))
|
|
74
|
+
async function inlineAttachments(e, room, reader) {
|
|
75
|
+
if (!e || typeof e !== 'object') return e
|
|
76
|
+
const out = { ...e }
|
|
77
|
+
for (const k of ['images', 'files']) {
|
|
78
|
+
if (!Array.isArray(e[k]) || !e[k].some(isStored)) continue
|
|
79
|
+
out[k] = await Promise.all(e[k].map(async (a) => {
|
|
80
|
+
if (!isStored(a)) return a
|
|
81
|
+
try {
|
|
82
|
+
const refs = Array.isArray(a.parts) && a.parts.length ? a.parts : [a.ref] // empty parts → `ref`, media.js's rule (sync sweep, 2026-10-10)
|
|
83
|
+
if (!refs[0]) return a
|
|
84
|
+
const parts = await Promise.all(refs.map((ref) => reader.blob(room, ref)))
|
|
85
|
+
if (parts.some((p) => !p || p.status !== 200 || typeof p.b64 !== 'string' || !p.b64)) return a
|
|
86
|
+
const { ref, parts: _p, size, ...rest } = a
|
|
87
|
+
return { ...rest, b64: parts.map((p) => p.b64).join(''), mime: a.mime || parts[0].mime || 'application/octet-stream' }
|
|
88
|
+
} catch { return a }
|
|
89
|
+
}))
|
|
90
|
+
}
|
|
91
|
+
return out
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
export function isExport(bundle) { return !!bundle && bundle.kind === EXPORT_KIND && Array.isArray(bundle.entries) }
|
|
95
|
+
|
|
96
|
+
// Recreate a room from an export: mint a NEW room carrying the exported agent config, then replay the entries. Injected
|
|
97
|
+
// `createSpace(config) → { room, mk }` and `mirror(room, mk, entries)` keep this decoupled from the app's create wiring
|
|
98
|
+
// (and testable). The new room gets a fresh key — the export's room id/key are NOT reused (a clone, not the same room).
|
|
99
|
+
// A whole history goes to op 'mirror' in SLICES, as the lane mirror (mirrorLoop.js) and the SDK do: one request with every
|
|
100
|
+
// entry — attachment bytes included — went over the request limit on a long room (sync sweep, 2026-10-10). A slice the
|
|
101
|
+
// server refuses STOPS the copy (later slices would leave a hole in the middle) and the count says how far it got; it
|
|
102
|
+
// never throws, so a fork that already minted its room still finishes.
|
|
103
|
+
export const MIRROR_BATCH = 25
|
|
104
|
+
export async function mirrorInBatches(mirror, room, mk, entries) {
|
|
105
|
+
let sent = 0
|
|
106
|
+
for (let i = 0; i < entries.length; i += MIRROR_BATCH) {
|
|
107
|
+
const slice = entries.slice(i, i + MIRROR_BATCH)
|
|
108
|
+
let r; try { r = await mirror(room, mk, slice) } catch { break }
|
|
109
|
+
if (r && typeof r.status === 'number' && r.status !== 200) break
|
|
110
|
+
sent += slice.length
|
|
111
|
+
}
|
|
112
|
+
return sent
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
export async function recreateSpace(bundle, { createSpace, mirror }) {
|
|
116
|
+
if (!isExport(bundle)) throw new Error('bad_export')
|
|
117
|
+
const made = await createSpace(bundle.config || {})
|
|
118
|
+
if (!made || !made.room || (!made.mk && made.keyless !== true)) throw new Error('create_failed')
|
|
119
|
+
// A "room moved" notice (kind 'fork') is a forwarding address of the OLD room's history — every other copy path drops
|
|
120
|
+
// it, or the new room's poll follows a stale move (spaceFork.js; sync sweep, 2026-10-10).
|
|
121
|
+
// Rows ride as DATA (`carry: 'fork'`, as spaceFork.js marks them), so the new room's store holds the same rows.
|
|
122
|
+
const entries = bundle.entries.filter((e) => e && e.kind !== 'fork').map((e) => (e.kind === 'data' && Array.isArray(e.ops) ? { ...e, carry: 'fork' } : e))
|
|
123
|
+
const carried = entries.length ? await mirrorInBatches(mirror, made.room, made.mk, entries) : 0
|
|
124
|
+
return { ...made, carried, total: entries.length }
|
|
125
|
+
}
|
package/spaceFork.js
ADDED
|
@@ -0,0 +1,216 @@
|
|
|
1
|
+
// spaces/public/spaceFork.js — MEMBERSHIP CHANGE = ROOM FORK (docs/spaces-membership-fork.md).
|
|
2
|
+
//
|
|
3
|
+
// Adding or removing a member is ONE epoch operation (the MLS "commit advances an epoch, re-keys the group" shape):
|
|
4
|
+
// create a NEW room with the desired roster and a fresh key, carry the history you choose, and hand each keeper a
|
|
5
|
+
// forward pointer sealed so a removed party can't read it. Exclusion is STRUCTURAL — the removed member simply isn't in
|
|
6
|
+
// the new roster and never receives the new key; nothing has to *reach* them for them to be out (the one property a
|
|
7
|
+
// pushed `revoke` can't guarantee against a content-blind server).
|
|
8
|
+
//
|
|
9
|
+
// It reuses primitives we already have — `create` (new roster + fresh gk), `mirror` (ledger transfer), `sealTo` (the
|
|
10
|
+
// pointer) — so there is NO new trust machinery. Each keeper already holds an ECDSA P-256 SIGNING key whose public
|
|
11
|
+
// point is on the SAME curve as sealTo's ECDH, so the pointer is sealed to that existing key (spk-reuse). The room
|
|
12
|
+
// ROSTER (name→spk) is read from the ledger, where P0 stamps each verified member's spk. All crypto lives in
|
|
13
|
+
// entrySig.js / e2ee.js; this module is orchestration over the client transport.
|
|
14
|
+
//
|
|
15
|
+
// The FORK INITIATOR enters the new room by the SAME path as every other keeper (their own sealed pointer / the grant
|
|
16
|
+
// returned here) — so there is no privileged "owner identity", just N keepers who each reuse their signing key.
|
|
17
|
+
import { genKeypair, mintGrant, signEntry, attribute } from './entrySig.js'
|
|
18
|
+
import { sealTo, openBox } from './e2ee.js'
|
|
19
|
+
import { mirrorInBatches } from './spaceExport.js' // the whole history in slices of 25, as the lane mirror
|
|
20
|
+
import { roomRegion } from './regions.js' // a room's home region is in its id (docs/multi-region.md)
|
|
21
|
+
import { readAllPages } from './ledgerView.js'
|
|
22
|
+
|
|
23
|
+
async function readForkHistory(client, room, mk) {
|
|
24
|
+
const poll = await readAllPages((since) => client.pollSealed(room, mk, undefined, since))
|
|
25
|
+
if (poll.incomplete) throw Object.assign(new Error('history_incomplete'), { code: 'history_incomplete' })
|
|
26
|
+
return poll
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
const GRANT_TTL_S = 400 * 24 * 3600 // long-lived member grant, matching createSoloIdentity
|
|
30
|
+
const enc = new TextEncoder()
|
|
31
|
+
const b64u = (buf) => btoa(String.fromCharCode(...new Uint8Array(buf))).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')
|
|
32
|
+
// A stable hash over the sealed boxes → carried in the fork notice's signed `text`, so the signature BINDS the exact
|
|
33
|
+
// box set (a relay can't add/swap/drop a box without breaking attribution). Only the fields the box needs to open.
|
|
34
|
+
export const boxesHash = async (boxes) => b64u(await crypto.subtle.digest('SHA-256', enc.encode(JSON.stringify((boxes || []).map((b) => ({ x: b.epk.x, y: b.epk.y, iv: b.iv, ct: b.ct }))))))
|
|
35
|
+
// A bare EC JWK (kty/crv/x/y[/d], no key_ops) — REQUIRED for spk-reuse: WebCrypto refuses to import an ECDSA key
|
|
36
|
+
// (key_ops ['sign']/['verify']) for ECDH deriveBits, so strip the op hints before sealTo/openBox.
|
|
37
|
+
export const bareEC = (jwk) => (jwk && jwk.x && jwk.y) ? { kty: 'EC', crv: 'P-256', x: jwk.x, y: jwk.y, ...(jwk.d ? { d: jwk.d } : {}) } : null
|
|
38
|
+
// Identity of an EC public key (its curve point) — for de-dup, removal matching, and agent exclusion.
|
|
39
|
+
export const jkey = (jwk) => (jwk && jwk.x && jwk.y) ? `${jwk.x}.${jwk.y}` : ''
|
|
40
|
+
|
|
41
|
+
/** Derive the room ROSTER from decrypted ledger entries: the distinct HUMAN members who posted a VERIFIED turn, each
|
|
42
|
+
* with their signing pubkey (spk, stamped by P0). The agent's own replies (self:true) carry no spk and are excluded;
|
|
43
|
+
* the agent re-attaches in the fork via the carried agentKeys, not a sealed pointer. Last spk wins per name (key
|
|
44
|
+
* rotation). `agentKeys` (optional) drops any 3rd-party agent that posted by key — it too re-attaches via agentKeys. */
|
|
45
|
+
export function deriveRoster(entries = [], agentKeys = []) {
|
|
46
|
+
const agentSet = new Set((Array.isArray(agentKeys) ? agentKeys : []).map((e) => jkey(e && e.key)).filter(Boolean))
|
|
47
|
+
const byName = new Map()
|
|
48
|
+
for (const e of entries) {
|
|
49
|
+
if (!e || e.self || e.verified !== true || !e.spk || !e.name) continue
|
|
50
|
+
if (agentSet.has(jkey(e.spk))) continue // a 3rd-party agent, not a human keeper
|
|
51
|
+
const prev = byName.get(e.name)
|
|
52
|
+
// `attestedClient`: the server's stamp that a turn came from an attested app (docs/the-attested-client.md, step 5) — a
|
|
53
|
+
// member keeps the mark once any of their turns carried it (the members sheet shows it; nothing else reads it)
|
|
54
|
+
const attestedClient = (typeof e.attestedClient === 'string' && e.attestedClient) || (prev && prev.attestedClient) || undefined
|
|
55
|
+
const attestedVersion = (typeof e.attestedClient === 'string' && Number.isInteger(e.attestedVersion) ? e.attestedVersion : undefined) ?? (prev && prev.attestedVersion)
|
|
56
|
+
byName.set(e.name, { name: e.name, spk: e.spk, ...(attestedClient ? { attestedClient } : {}), ...(attestedClient && attestedVersion ? { attestedVersion } : {}) })
|
|
57
|
+
}
|
|
58
|
+
return [...byName.values()]
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** Fork a room to change its membership. `client` exposes { pollSealed, getConfig, create, mirror }.
|
|
62
|
+
* opts:
|
|
63
|
+
* self {name, spk} — the INITIATOR; always kept (so they can enter the fork even if they never posted). Required.
|
|
64
|
+
* remove [name | {spk}]— members to drop (matched by name OR by spk). Their turns' history still rides along as
|
|
65
|
+
* history unless `history:'forward'` (dropping past turns is REDACTION — a separate feature).
|
|
66
|
+
* add [{name, spk}] — new members (each supplies a signing pubkey; the host provisions or they generate one).
|
|
67
|
+
* history 'full'|'forward' — carry the whole ledger (newcomers see everything) or nothing (forward-only). Default 'full'.
|
|
68
|
+
* base — optional endpoint base for create.
|
|
69
|
+
* Returns { room, mk, gk, selfGrant, keepers, pointers:[{name, spk, box}], links, carried }.
|
|
70
|
+
* gk PRIVATE is generated, used to mint every grant, then DISCARDED here (never returned or persisted) — like a
|
|
71
|
+
* room-invite key at create. `selfGrant` lets the initiator enter immediately without opening their own pointer. */
|
|
72
|
+
// `configPatch` (P2 fork-to-accept, docs/enclave-room-acceptance.md §3.3): fields merged over the carried config — accepting
|
|
73
|
+
// a new enclave build is a fork with NO member change and a widened `enclave` block. `enclave:true` mints the new epoch
|
|
74
|
+
// in the enclave tier; `onMinted(room)` fires BEFORE history is mirrored so the caller can mark the room (routing + the
|
|
75
|
+
// seal gate) and the mirror seals to the enclave under the NEW block.
|
|
76
|
+
export async function forkRoom(client, oldRoom, oldMk, { self, remove = [], add = [], history = 'full', epochKeys = {}, base, splitMint, configPatch = null, enclave = false, onMinted = null, attest = null } = {}) {
|
|
77
|
+
if (!self || !self.name || !self.spk) throw new Error('forkRoom needs { self: { name, spk } } (the initiator)')
|
|
78
|
+
// 1) roster + the old agent config (to carry the agent's behavior into the fork). A forked room carries its epoch's
|
|
79
|
+
// admitted roster in the config (authoritative, since membership only changes via a fork); an ORIGINAL room has
|
|
80
|
+
// none, so bootstrap it from the ledger (P0 spks). Reading the config roster avoids re-admitting a removed member
|
|
81
|
+
// whose carried history still holds their spk.
|
|
82
|
+
const poll = await readForkHistory(client, oldRoom, oldMk)
|
|
83
|
+
const old = (await client.getConfig(oldRoom, oldMk)) || {}
|
|
84
|
+
const roster = (Array.isArray(old.roster) && old.roster.length)
|
|
85
|
+
? old.roster.filter((m) => m && m.name && m.spk)
|
|
86
|
+
: deriveRoster(poll.entries || [], old.agentKeys)
|
|
87
|
+
// 2) keepers = roster − removed (+ added), and ALWAYS the initiator (unless explicitly removed)
|
|
88
|
+
const rmNames = new Set(remove.map((r) => (typeof r === 'string' ? r : r && r.name)).filter(Boolean))
|
|
89
|
+
const rmKeys = new Set(remove.map((r) => (r && r.spk ? jkey(r.spk) : '')).filter(Boolean))
|
|
90
|
+
const removed = (m) => rmNames.has(m.name) || rmKeys.has(jkey(m.spk))
|
|
91
|
+
const keepers = roster.filter((m) => !removed(m))
|
|
92
|
+
if (!removed(self) && !keepers.some((k) => jkey(k.spk) === jkey(self.spk))) keepers.push({ name: self.name, spk: self.spk })
|
|
93
|
+
for (const a of add) if (a && a.name && a.spk && !keepers.some((k) => jkey(k.spk) === jkey(a.spk))) keepers.push({ name: a.name, spk: a.spk })
|
|
94
|
+
// 3) fork: a fresh room with the carried config forced to the INVITE gate + a fresh gk (every grant chains to gk₂ →
|
|
95
|
+
// uniform peer-verification). keyModel is not in the sealed config, so create defaults to a solo (single-mk) room.
|
|
96
|
+
const gk = await genKeypair()
|
|
97
|
+
// stamp the resolved roster (name+spk per keeper) so the NEXT fork reads it authoritatively instead of re-deriving
|
|
98
|
+
// from the ledger (whose carried history would otherwise re-admit a removed member); carry the fork AUTHORITY forward
|
|
99
|
+
// (the old room's, or the initiator when none) so the same authority keeps forking and keepers can verify follows.
|
|
100
|
+
// In LINK mode (P4, epoch-keyed) the fork records a `parent` pointer to the old room instead of re-sealing its ledger:
|
|
101
|
+
// history is read BY REFERENCE up the chain, so a fork is O(1) regardless of ledger size. Full-history keepers receive
|
|
102
|
+
// the ancestor epoch keys in their sealed pointer; a newly-ADDED member (not in the old roster) gets none → they read
|
|
103
|
+
// only from this epoch forward (forward-only), for free.
|
|
104
|
+
const linked = history === 'link'
|
|
105
|
+
const cfg = { ...old, admission: 'invite', revoked: undefined, roster: keepers.map((k) => ({ name: k.name, spk: k.spk })), forkAuthority: old.forkAuthority || self.spk, ...(linked ? { parent: { room: oldRoom } } : { parent: undefined }) , ...(configPatch && typeof configPatch === 'object' ? configPatch : {}) }
|
|
106
|
+
// SPLIT fork: mint the new room as a SPLIT-KEY room (each keeper holds the userShare; the app-half is sealed under K_eco)
|
|
107
|
+
// so the fork PRESERVES the split-key property. splitMint(cfg, gkPub) → { room, mk, userShare, commit, links }.
|
|
108
|
+
cfg.region = roomRegion(oldRoom) // the new room stays in the old one's region (regions.js)
|
|
109
|
+
// AN ATTESTED ROOM MOVES AS ONE (docs/emulated-attested-rooms.md step 5; "rotate on removal"): `attest` = { room, level,
|
|
110
|
+
// accept } from the caller, who marked `room` before anything exists. The new room gets its OWN signed rule (a rule names one
|
|
111
|
+
// room — the old one's is dropped) and the old room's accepted versions; the key goes only to the keepers' sealed pointers.
|
|
112
|
+
if (attest) { delete cfg.ownerPolicy; cfg.room = attest.room; cfg.requireApp = attest.level; if (attest.accept) cfg.attestAccept = attest.accept }
|
|
113
|
+
const minted = splitMint ? await splitMint(cfg, gk.pub) : await client.create(cfg, { ...(base ? { base } : {}), gk: gk.pub, ...(enclave ? { enclave: true } : {}) })
|
|
114
|
+
const room = minted.room, mk = minted.mk, links = minted.links || null
|
|
115
|
+
if (typeof onMinted === 'function') await onMinted(room, cfg)
|
|
116
|
+
const forkUserShare = splitMint ? (minted.userShare || null) : null, forkCommit = splitMint ? (minted.commit || null) : null
|
|
117
|
+
// the ancestor keys a full-history keeper needs to read the whole chain from this room down to the root: the old
|
|
118
|
+
// room's key + whatever ancestors the forker already holds (accumulated across prior forks).
|
|
119
|
+
const chainKeys = linked ? { ...(epochKeys || {}), [oldRoom]: oldMk } : null
|
|
120
|
+
const oldSpks = new Set(roster.map((m) => jkey(m.spk))) // who was already a member → entitled to full history
|
|
121
|
+
// 4) mint a grant per keeper under gk₂, seal a forward pointer to each keeper's EXISTING spk (spk-reuse), then let
|
|
122
|
+
// gk.priv fall out of scope (never persisted). The initiator's grant is returned for immediate navigation.
|
|
123
|
+
const exp = Math.floor(Date.now() / 1000) + GRANT_TTL_S
|
|
124
|
+
let selfGrant = null
|
|
125
|
+
const pointers = []
|
|
126
|
+
for (const k of keepers) {
|
|
127
|
+
const grant = await mintGrant(gk.priv, { name: String(k.name).slice(0, 24), room, exp, spk: k.spk })
|
|
128
|
+
if (jkey(k.spk) === jkey(self.spk)) selfGrant = grant
|
|
129
|
+
const ek = (linked && oldSpks.has(jkey(k.spk))) ? chainKeys : undefined // existing keeper → full history via chain; added member → forward-only
|
|
130
|
+
const keyF = forkUserShare ? { split: true, userShare: forkUserShare, commit: forkCommit } : { mk } // SPLIT: the pointer carries the userShare (not mk) → the keeper joins split, reconstructing via the tenant app-half
|
|
131
|
+
const plain = JSON.stringify({ v: 1, kind: 'space-fork', from: oldRoom, room, ...keyF, gk: gk.pub, name: k.name, grant, ...(ek ? { epochKeys: ek } : {}) })
|
|
132
|
+
pointers.push({ name: k.name, spk: k.spk, box: await sealTo(plain, bareEC(k.spk)) })
|
|
133
|
+
}
|
|
134
|
+
// 5) carry history: full → the whole decrypted ledger, re-sealed under mk₂ (deduped by id server-side); link → by
|
|
135
|
+
// reference (parent chain, no re-seal); forward → nothing. Drop prior 'fork' control entries either way — they're
|
|
136
|
+
// forwarding notices for OTHER epochs, not history, and carrying them would make the poll loop follow a stale fork.
|
|
137
|
+
let carried = 0
|
|
138
|
+
// Data entries ride as DATA (`carry: 'fork'`), so the new room's store holds the same rows (agent/spaceService.mjs
|
|
139
|
+
// sanitizeMirrorEntry); without the marker the server keeps every mirrored entry as a text line.
|
|
140
|
+
const entries = (poll.entries || []).filter((e) => e && e.kind !== 'fork').map((e) => (e.kind === 'data' && Array.isArray(e.ops) ? { ...e, carry: 'fork' } : e))
|
|
141
|
+
if (history === 'full' && entries.length) carried = await mirrorInBatches((r, m, es) => client.mirror(r, m, es), room, mk, entries)
|
|
142
|
+
return { room, mk, gk: gk.pub, selfGrant, keepers, pointers, links, carried, historyTotal: history === 'full' ? entries.length : 0, ...(forkUserShare ? { split: true, userShare: forkUserShare, commit: forkCommit } : {}), ...(linked ? { parent: oldRoom, selfEpochKeys: chainKeys } : {}) }
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/** Read a room's FULL history across the epoch chain (P4). Reads this room's native ledger, then — if it records a
|
|
146
|
+
* `parent` and the caller holds that epoch's key — recurses into the parent, oldest-first. A reader missing an ancestor
|
|
147
|
+
* key simply stops there (forward-only from that epoch). Past epochs are immutable sealed history, so this is a one-shot
|
|
148
|
+
* read on entry; the live poll loop still handles only the current epoch. `epochKeys` maps room → mk for each ancestor. */
|
|
149
|
+
export async function readEpochChain(client, room, mk, epochKeys = {}, depth = 0) {
|
|
150
|
+
const poll = await readForkHistory(client, room, mk)
|
|
151
|
+
const here = ((poll && poll.entries) || []).filter((e) => e && e.kind !== 'fork')
|
|
152
|
+
if (depth >= 64) return here // cycle / runaway guard
|
|
153
|
+
const cfg = await client.getConfig(room, mk).catch(() => null)
|
|
154
|
+
const parent = cfg && cfg.parent && cfg.parent.room
|
|
155
|
+
if (parent && epochKeys && epochKeys[parent]) {
|
|
156
|
+
const older = await readEpochChain(client, parent, epochKeys[parent], epochKeys, depth + 1)
|
|
157
|
+
return [...older, ...here]
|
|
158
|
+
}
|
|
159
|
+
return here
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/** A keeper opens a sealed fork pointer with their SIGNING private key (spk-reuse: re-imported for ECDH via bareEC).
|
|
163
|
+
* Returns the payload { room, mk, gk, grant, name, from } addressed to this key, or null (not for this key / tamper). */
|
|
164
|
+
export async function openForkPointer(box, signPrivJwk) {
|
|
165
|
+
try {
|
|
166
|
+
const pt = await openBox(box, bareEC(signPrivJwk))
|
|
167
|
+
if (!pt) return null
|
|
168
|
+
const o = JSON.parse(pt)
|
|
169
|
+
return (o && o.kind === 'space-fork' && o.room && (o.mk || (o.split && o.userShare)) && o.grant) ? o : null // accept a SPLIT pointer (userShare instead of mk)
|
|
170
|
+
} catch { return null }
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/** Publish the sealed forward pointers into the OLD room as a `fork` control entry, so keepers (incl. those offline at
|
|
174
|
+
* fork time) discover them on their next poll. `identity` = the INITIATOR's { name, sign:{priv}, grant } — the notice
|
|
175
|
+
* is SIGNED over `text: 'fork:<boxes-hash>'` (binding the exact box set) and carries the grant, so a keeper can verify
|
|
176
|
+
* it came from the room's fork authority (followFork) rather than an mk-holder forging a fork to a room they control.
|
|
177
|
+
* The boxes are opaque to non-keepers (a removed member sees a list of unopenable boxes). Reuses the mirror transport. */
|
|
178
|
+
export async function postForkPointers(client, oldRoom, oldMk, pointers, identity) {
|
|
179
|
+
if (!identity || !identity.sign || !identity.sign.priv || !identity.grant) throw new Error('postForkPointers needs the initiator identity { name, sign:{priv}, grant }')
|
|
180
|
+
const boxes = (pointers || []).map((p) => p.box).filter(Boolean)
|
|
181
|
+
if (!boxes.length) return { status: 200, added: 0 }
|
|
182
|
+
const ts = Date.now()
|
|
183
|
+
const id = `fork:${ts}`
|
|
184
|
+
const name = String(identity.name || 'someone').slice(0, 24)
|
|
185
|
+
const text = 'fork:' + (await boxesHash(boxes)) // in the SIGNED entry-core → the signature binds the box set
|
|
186
|
+
const { sig } = await signEntry(identity.sign.priv, { room: oldRoom, author: name, ts, kind: 'fork', id, text })
|
|
187
|
+
const entry = { kind: 'fork', id, ts, author: name, from: name, name, text, sig, grant: identity.grant, boxes }
|
|
188
|
+
const r = await client.mirror(oldRoom, oldMk, [entry])
|
|
189
|
+
return { ...r, id } // `id` lets the initiator suppress auto-following their OWN notice
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/** Decide whether to AUTO-FOLLOW a `fork` control entry, and if so return the pointer addressed to THIS device.
|
|
193
|
+
* Defenses, in order: (1) the boxes must match the signed hash (integrity); (2) the notice must attribute to a genuine
|
|
194
|
+
* old-room member via `oldGk` (authenticity); (3) that member's spk must equal the room's `forkAuthority` when one is
|
|
195
|
+
* set (the hijack gate — only the authority may move the room). Then open the box addressed to `signPrivJwk`. Returns
|
|
196
|
+
* the pointer { room, mk, gk, grant, name } or null (not a valid/authorized fork, or not addressed to this key).
|
|
197
|
+
* `now` is epoch SECONDS. A legacy room without a forkAuthority still requires a genuine-member signature when oldGk
|
|
198
|
+
* is known; an open room (no gk) has an empty roster, so no meaningful fork is produced or followed. */
|
|
199
|
+
export async function followFork(entry, signPrivJwk, { oldGk, room, forkAuthority, now = Math.floor(Date.now() / 1000) } = {}) {
|
|
200
|
+
if (!entry || entry.kind !== 'fork' || !Array.isArray(entry.boxes) || !entry.boxes.length) return null
|
|
201
|
+
if (String(entry.text || '') !== 'fork:' + (await boxesHash(entry.boxes))) return null // (1) integrity
|
|
202
|
+
if (oldGk) { // (2) authenticity + (3) authority
|
|
203
|
+
if (!entry.grant || !entry.sig) return null
|
|
204
|
+
const core = { room, author: entry.name, ts: entry.ts, kind: 'fork', id: entry.id, text: entry.text, sig: entry.sig }
|
|
205
|
+
const a = await attribute(core, entry.grant, oldGk, { room, now })
|
|
206
|
+
if (!a.ok) return null
|
|
207
|
+
if (forkAuthority && jkey(a.spk) !== jkey(forkAuthority)) return null
|
|
208
|
+
} else if (forkAuthority) {
|
|
209
|
+
return null // an authority is required but the notice can't be attributed (no gk) → refuse
|
|
210
|
+
}
|
|
211
|
+
for (const box of entry.boxes) {
|
|
212
|
+
const p = await openForkPointer(box, signPrivJwk)
|
|
213
|
+
if (p) return p
|
|
214
|
+
}
|
|
215
|
+
return null
|
|
216
|
+
}
|