@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
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
// spaceTemplates.js — the M3 template layer (docs/configurable-space-m3.md).
|
|
2
|
+
//
|
|
3
|
+
// A Space is to a CONFIG what an agent is to a manifest. M3 proved the engine is fully config-driven: the SAME deployed
|
|
4
|
+
// /space Lambda runs any vertical with zero code changes — only the config differs (verified end-to-end on prod with a
|
|
5
|
+
// second vertical, `team-decision`, incl. the Shamir k-of-n key model, a distinct persona, and a propose-gated tool).
|
|
6
|
+
//
|
|
7
|
+
// This is the reusable library the roadmap calls "clinician-authored templates users personalize": pick a template,
|
|
8
|
+
// let the creator tweak the persona/knobs, then `makeSpaceClient().create(template)`. Each template is exactly the
|
|
9
|
+
// config the engine already reads — keyModel + persona/agentName + tools/immediateTools. Nothing here is a new engine
|
|
10
|
+
// axis: a Space's capabilities are just `declaredTools`; presence is the key model (2-of-2 = both present, not a
|
|
11
|
+
// separate flag); an effectful tool is propose-gated unless allow-listed in `immediateTools` (fail-closed).
|
|
12
|
+
|
|
13
|
+
export const SPACE_TEMPLATES = [
|
|
14
|
+
{
|
|
15
|
+
id: 'couples-comedian',
|
|
16
|
+
display: 'Couples — a comedian in the room',
|
|
17
|
+
blurb: 'A private, both-of-you room where a comedian helps you hash something out — funny at the situation, never at a person.',
|
|
18
|
+
keyModel: '2-of-2', // both partners' shares must combine to open it → presence IS the key model
|
|
19
|
+
agentName: 'The Comedian',
|
|
20
|
+
// The persona + safety floor are the VALIDATED, legally-load-bearing text — the canonical copy lives in
|
|
21
|
+
// tools/first-party-agents.json (comedian-therapist) and must not be forked here (it drifts). A Space using this
|
|
22
|
+
// template loads that text; the engine must inject `safetyFloor` as the LAST, un-removable block (exactly as
|
|
23
|
+
// agent.mjs does for the live call). `needsSafetyFloor` flags that a Space config field for it is required.
|
|
24
|
+
personaRef: 'first-party-agents.json#comedian-therapist',
|
|
25
|
+
tools: [],
|
|
26
|
+
immediateTools: [],
|
|
27
|
+
needsSafetyFloor: true,
|
|
28
|
+
},
|
|
29
|
+
|
|
30
|
+
{
|
|
31
|
+
id: 'team-decision',
|
|
32
|
+
display: 'Team — decide together',
|
|
33
|
+
blurb: 'A small team reaches a decision together; the facilitator records it only once you all approve.',
|
|
34
|
+
keyModel: { k: 2, n: 3 }, // any 2 of the team's members can open it (Shamir k-of-n) — the generalized key model
|
|
35
|
+
agentName: 'Facilitator',
|
|
36
|
+
persona:
|
|
37
|
+
'You are a calm, fair team facilitator helping a small group decide together. Note where they agree, surface the ' +
|
|
38
|
+
'one open question, and when the group clearly lands on a decision, record it. Neutral, brief, never take a side.',
|
|
39
|
+
tools: [
|
|
40
|
+
{ name: 'record_decision', description: 'Record a decision the team has agreed on', parameters: { type: 'object', properties: { decision: { type: 'string' }, rationale: { type: 'string' } }, required: ['decision'] } },
|
|
41
|
+
],
|
|
42
|
+
immediateTools: [], // record_decision is high-stakes → propose-gated (a human approves before it's recorded)
|
|
43
|
+
},
|
|
44
|
+
|
|
45
|
+
{
|
|
46
|
+
id: 'mediation',
|
|
47
|
+
display: 'Mediation — two parties + a neutral',
|
|
48
|
+
blurb: 'Two parties and a neutral mediator work toward a written agreement; each party approves what gets drafted.',
|
|
49
|
+
keyModel: '2-of-2', // both parties present to open (the money-attached vertical the roadmap flags)
|
|
50
|
+
agentName: 'Mediator',
|
|
51
|
+
persona:
|
|
52
|
+
'You are a neutral, patient mediator between two parties. Restate each side fairly, find the shared interest, and ' +
|
|
53
|
+
'when they converge, draft the agreement in plain language. Never advocate for either party; never give legal advice.',
|
|
54
|
+
tools: [
|
|
55
|
+
{ name: 'draft_agreement', description: 'Draft the terms both parties have agreed to', parameters: { type: 'object', properties: { terms: { type: 'string' } }, required: ['terms'] } },
|
|
56
|
+
],
|
|
57
|
+
immediateTools: [],
|
|
58
|
+
needsSafetyFloor: true, // an abuse/coercion floor applies here too (same discipline as couples)
|
|
59
|
+
},
|
|
60
|
+
|
|
61
|
+
{
|
|
62
|
+
// A confidential case room for a lawyer + client(s). The privilege/confidentiality guarantee is the SEALED room
|
|
63
|
+
// (E2EE, content-blind at rest) — exactly where verifiable trust is load-bearing (a third party who could read the
|
|
64
|
+
// communication can WAIVE privilege). No new engine axis: read_file (load case materials) and write_pdf (draft
|
|
65
|
+
// documents) are platform tools available in every Space; the private-lane panel gives each party their own agent +
|
|
66
|
+
// private room (attorney work-product stays out of the shared thread). This template only supplies the persona.
|
|
67
|
+
id: 'legal-case',
|
|
68
|
+
display: 'Legal — a confidential case room',
|
|
69
|
+
blurb: 'A sealed case room for a lawyer and client(s): load case materials, strategize together, and draft documents — readable only inside the room.',
|
|
70
|
+
agentName: 'Case Assistant',
|
|
71
|
+
persona:
|
|
72
|
+
'You are a meticulous legal case assistant inside a confidential lawyer–client room. Help the team work the case. ' +
|
|
73
|
+
'When a document is shared you will see a "[shared file: NAME]" marker — call read_file to read it, then lay out ' +
|
|
74
|
+
'the facts, the issues, key dates and deadlines, and the risks. Help the team respond and strategize: outline ' +
|
|
75
|
+
'options and their tradeoffs, and when asked, draft correspondence, memos, demand letters, and filings — use ' +
|
|
76
|
+
'write_pdf to produce a clean document. Ground everything in the materials you were given; NEVER invent facts, ' +
|
|
77
|
+
'quotes, citations, or case law, and say so plainly when something needs to be checked. You assist the ' +
|
|
78
|
+
'supervising attorney\'s judgment — you do not replace it, you do not give the client independent legal advice, ' +
|
|
79
|
+
'and you never promise an outcome. Be precise, organized, and concise.',
|
|
80
|
+
tools: [], // read_file + write_pdf are platform tools (auto-available every turn) — nothing to declare
|
|
81
|
+
immediateTools: [],
|
|
82
|
+
},
|
|
83
|
+
]
|
|
84
|
+
|
|
85
|
+
/** Look up a template by id. */
|
|
86
|
+
export const spaceTemplate = (id) => SPACE_TEMPLATES.find((t) => t.id === id) || null
|
|
87
|
+
|
|
88
|
+
const TRAVEL_PERSONA = 'A friendly, knowledgeable travel agent who helps plan trips together: destinations, day plans, restaurants, sights, hotels, getting around, and practical tradeoffs. Keep answers concise, concrete, and useful.'
|
|
89
|
+
// The GENERIC assistant — a general-purpose persona, not a specialized one. First in the list ⇒ it's the DEFAULT for a
|
|
90
|
+
// new Space (defaultCreateAgent falls back to builtinAgents()[0]) and the fallback persona in the create handler below.
|
|
91
|
+
export const GENERAL_PERSONA = 'A helpful, friendly assistant for anything that comes up — answering questions, writing and editing, planning, research, brainstorming, summarizing, and thinking through problems together. Be clear, concise, and practical, and ask a short clarifying question when it helps. Use shared docs, images, files, places/maps and flights when they are genuinely useful.'
|
|
92
|
+
export const CREATE_TEMPLATES = [
|
|
93
|
+
{ id: 'general', name: 'Assistant', sub: 'A helpful all-purpose assistant', agentName: 'Assistant', persona: GENERAL_PERSONA },
|
|
94
|
+
{ id: 'travel', name: 'Travel', sub: 'Plan trips, maps, places, itineraries', agentName: 'Travel Agent', persona: TRAVEL_PERSONA },
|
|
95
|
+
...SPACE_TEMPLATES.filter((t) => t.persona).map((t) => ({ id: t.id, name: t.display.replace(/\s+—\s+.*/, ''), sub: t.blurb, agentName: t.agentName, persona: t.persona })),
|
|
96
|
+
]
|
|
97
|
+
|
|
98
|
+
/** Independent copies of the built-in assistant choices. */
|
|
99
|
+
export function assistantTemplates() { return CREATE_TEMPLATES.map(template => ({ ...template })) }
|
package/speechOut.js
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
// speechOut.js — text read aloud (the Spaces app's "Play aloud" on a bubble, and the SDK's wb.speak()): the bubble's text read by Tinfoil's attested speech model, billed to the account's
|
|
2
|
+
// OWN capped key, exactly like press-to-talk the other way round (agent/sttKey.mjs § SPEECH OUTPUT; docs/stt-cloud.md §
|
|
3
|
+
// Speech output). The page POSTs the text STRAIGHT to the attested host and plays what comes back; our servers see
|
|
4
|
+
// neither the text nor the audio.
|
|
5
|
+
//
|
|
6
|
+
// Measured 2026-10-03: voxtral-tts bills $0.002 PER REQUEST whatever the length; a sentence answers in ~1.8 s, 1,500
|
|
7
|
+
// characters in ONE request take 15 s and arrive all at once. So a long message is cut into chunks at sentence ends — a
|
|
8
|
+
// SHORT first chunk for a quick first sound, larger ones after — and each chunk is fetched one ahead while the previous
|
|
9
|
+
// plays. A paragraph-long bubble is 2–4 requests, under a cent.
|
|
10
|
+
//
|
|
11
|
+
// ⚑ Neither speech model has Hebrew (their own transcriber hears a stuck syllable / mangled words back). Hebrew-dominant
|
|
12
|
+
// text is REFUSED with `no_hebrew` before any spend, so the person gets a sentence instead of gibberish and a charge.
|
|
13
|
+
//
|
|
14
|
+
// One module for both: the app's ttsPlay.js adds its surface stamp, the SDK's sdkSpeech.js its own key (sdk-assistant.md#speak).
|
|
15
|
+
|
|
16
|
+
// THE ENDPOINT IS PINNED HERE, as press-to-talk's (sttCloud.js STT_URL): the key comes from op:'tts', where the TEXT goes does
|
|
17
|
+
// not — the answer's `url` is ignored. And the page checks the key's evidence itself before any text goes (voiceAttest.js).
|
|
18
|
+
import { checkSpeechKey } from './voiceAttest.js'
|
|
19
|
+
export const TTS_URL = 'https://inference.tinfoil.sh/v1/audio/speech'
|
|
20
|
+
|
|
21
|
+
export const FIRST_CHUNK = 240 // characters: a quick first sound (~2 s)
|
|
22
|
+
export const CHUNK = 900 // characters: the later chunks (~8 s of generation each, fetched while the previous plays)
|
|
23
|
+
const KEY_SLACK_MS = 10 * 60_000 // ask for a new key this long before the old one expires (as sttCloud does)
|
|
24
|
+
|
|
25
|
+
// Split at sentence ends (., !, ?, Hebrew/Arabic full stops, newlines), the first piece short, the rest up to CHUNK; a
|
|
26
|
+
// sentence longer than a chunk is split at a space. Markdown is read as text: code fences and headings lose their marks.
|
|
27
|
+
export function chunkText (text, { first = FIRST_CHUNK, max = CHUNK } = {}) {
|
|
28
|
+
const t = String(text || '').replace(/```[\s\S]*?```/g, ' code block ').replace(/^#+\s*/gm, '').replace(/[*_`>]/g, '').replace(/\s+/g, ' ').trim()
|
|
29
|
+
if (!t) return []
|
|
30
|
+
const sentences = t.match(/[^.!?؟。\n]+[.!?؟。]*\s*/g) || [t]
|
|
31
|
+
const out = []; let cur = ''
|
|
32
|
+
const limit = () => (out.length === 0 ? first : max)
|
|
33
|
+
const push = () => { if (cur.trim()) out.push(cur.trim()); cur = '' }
|
|
34
|
+
for (let s of sentences) {
|
|
35
|
+
while (s.length > limit()) { // a run-on sentence: cut at the last space before the limit
|
|
36
|
+
const room = limit() - cur.length
|
|
37
|
+
if (room < 40) { push(); continue }
|
|
38
|
+
const cut = s.lastIndexOf(' ', room); const at = cut > 20 ? cut : room
|
|
39
|
+
cur += s.slice(0, at); push(); s = s.slice(at).trimStart()
|
|
40
|
+
}
|
|
41
|
+
if (cur && cur.length + s.length > limit()) push()
|
|
42
|
+
cur += s
|
|
43
|
+
}
|
|
44
|
+
push()
|
|
45
|
+
return out
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
// Hebrew-dominant? (letters only: a Hebrew message with Latin product names is still Hebrew; an English message quoting a
|
|
49
|
+
// Hebrew word is still English.)
|
|
50
|
+
export function isHebrew (text) {
|
|
51
|
+
const he = (String(text || '').match(/[-]/g) || []).length
|
|
52
|
+
const latin = (String(text || '').match(/[A-Za-z]/g) || []).length
|
|
53
|
+
return he > 0 && he >= latin
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** createTtsPlayer({ getKey, fetchImpl, AudioImpl, now, URLImpl }) → { play(text), stop(), playing }.
|
|
57
|
+
* getKey() → { key, model, voice, expiresAt, cert, bundleGz } from op:'tts' (its `url` is not used: TTS_URL). play() resolves when the whole text has played (or
|
|
58
|
+
* rejects: `no_hebrew`, `empty`, a fetch/HTTP failure); stop() ends playback and aborts fetches in flight. */
|
|
59
|
+
export function createTtsPlayer ({ getKey, checkKey = checkSpeechKey, fetchImpl = (...a) => globalThis.fetch(...a), AudioImpl = globalThis.Audio, now = () => Date.now(), URLImpl = globalThis.URL } = {}) {
|
|
60
|
+
let keyEpoch = 0, key = null, session = 0, audio = null, ctrl = null
|
|
61
|
+
const self = { playing: false }
|
|
62
|
+
const freshKey = async () => { if (!key || Date.parse(key.expiresAt) - now() < KEY_SLACK_MS) { const epoch = keyEpoch; const k = await getKey(); await checkKey(k); if (epoch !== keyEpoch) throw new Error('speech payer changed'); key = k } return key } // checkKey throws voice_unattested: no text is sent
|
|
63
|
+
const fetchChunk = async (text, k, signal) => {
|
|
64
|
+
const r = await fetchImpl(TTS_URL, { method: 'POST', headers: { authorization: 'Bearer ' + k.key, 'content-type': 'application/json' }, body: JSON.stringify({ model: k.model, input: text, ...(k.voice ? { voice: k.voice } : {}), response_format: 'mp3' }), signal })
|
|
65
|
+
if (!r.ok) { if (r.status === 401 || r.status === 402 || r.status === 403) key = null; throw Object.assign(new Error('speech ' + r.status), { code: 'http_' + r.status }) }
|
|
66
|
+
return r.blob()
|
|
67
|
+
}
|
|
68
|
+
const playBlob = (blob, signal) => new Promise((resolve, reject) => {
|
|
69
|
+
const url = URLImpl.createObjectURL(blob)
|
|
70
|
+
const a = new AudioImpl(url); audio = a
|
|
71
|
+
const done = (err) => { try { URLImpl.revokeObjectURL(url) } catch { /* */ } if (audio === a) audio = null; err ? reject(err) : resolve() }
|
|
72
|
+
a.onended = () => done(); a.onerror = () => done(Object.assign(new Error('audio failed'), { code: 'audio' }))
|
|
73
|
+
if (signal) signal.addEventListener('abort', () => { try { a.pause() } catch { /* */ } done(Object.assign(new Error('stopped'), { code: 'stopped' })) }, { once: true })
|
|
74
|
+
Promise.resolve(a.play()).catch((e) => done(Object.assign(e || new Error('play refused'), { code: 'play' })))
|
|
75
|
+
})
|
|
76
|
+
self.stop = () => { session++; self.playing = false; try { ctrl && ctrl.abort() } catch { /* */ } ctrl = null; try { audio && audio.pause() } catch { /* */ } audio = null }
|
|
77
|
+
self.resetKey = () => { keyEpoch++; key = null; self.stop() }
|
|
78
|
+
self.play = async (text) => {
|
|
79
|
+
self.stop()
|
|
80
|
+
if (isHebrew(text)) throw Object.assign(new Error('Hebrew is not supported by the speech model'), { code: 'no_hebrew' })
|
|
81
|
+
const chunks = chunkText(text)
|
|
82
|
+
if (!chunks.length) throw Object.assign(new Error('nothing to read'), { code: 'empty' })
|
|
83
|
+
const mine = ++session; ctrl = new AbortController(); const signal = ctrl.signal
|
|
84
|
+
self.playing = true
|
|
85
|
+
try {
|
|
86
|
+
const k = await freshKey()
|
|
87
|
+
if (session !== mine) return
|
|
88
|
+
let next = fetchChunk(chunks[0], k, signal)
|
|
89
|
+
for (let i = 0; i < chunks.length; i++) {
|
|
90
|
+
const blob = await next
|
|
91
|
+
if (session !== mine) return
|
|
92
|
+
next = i + 1 < chunks.length ? fetchChunk(chunks[i + 1], k, signal) : null // one ahead, while this one plays
|
|
93
|
+
if (next) next.catch(() => {}) // judged when awaited; never an unhandled rejection
|
|
94
|
+
await playBlob(blob, signal)
|
|
95
|
+
if (session !== mine) return
|
|
96
|
+
}
|
|
97
|
+
} catch (e) {
|
|
98
|
+
if (session === mine && e && e.code !== 'stopped') throw e
|
|
99
|
+
} finally { if (session === mine) { self.playing = false; ctrl = null } }
|
|
100
|
+
}
|
|
101
|
+
return self
|
|
102
|
+
}
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
// splitKeyClient.js — the CLIENT half of the tenant split-key model (docs/tenant-split-key-design.md).
|
|
2
|
+
//
|
|
3
|
+
// mk = userShare ⊕ appShare. The user's kernel keeps `userShare` (a normal keyring entry — custody/recovery unchanged,
|
|
4
|
+
// §5.1); an allowlisted ORIGIN serves `appShare` (unsealed from the platform's opaque blob with the ecosystem key
|
|
5
|
+
// K_eco); this module COMBINES the two and verifies commit(mk) before trusting it (§6.4 — refuse a crafted appShare).
|
|
6
|
+
//
|
|
7
|
+
// It holds NO secrets: the tenant-authed transport (`tenantPost`) and the origin's K_eco custody (`origin.privateJwk`)
|
|
8
|
+
// are INJECTED, so the same code runs in a Node test, a browser page, or a tenant backend. In production `tenantPost`
|
|
9
|
+
// reaches /tenant-space (the tenant key → the /v1 authorizer → the §4b gate); K_eco lives with the tenant/origin, never
|
|
10
|
+
// the platform. Pure composition over e2ee.js primitives — no new crypto.
|
|
11
|
+
import { newKey, splitKey, combineShares, commit, seal, open, sealTo, openBox } from './e2ee.js'
|
|
12
|
+
|
|
13
|
+
/** wrap(K_eco, origin.pub) for each allowed origin → the ecoWraps map (the CRYPTO allowlist). Each is an opaque box only
|
|
14
|
+
* that origin's private key opens; the platform stores them and can open none. `originPubs` = { originId: publicJwk }. */
|
|
15
|
+
export async function wrapKEco(K_eco, originPubs = {}) {
|
|
16
|
+
const wraps = {}
|
|
17
|
+
for (const id of Object.keys(originPubs)) wraps[id] = JSON.stringify(await sealTo(K_eco, originPubs[id]))
|
|
18
|
+
return wraps
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** CREATE a split-key room: mint mk → split → seal appShare under K_eco → tenant `create` (authed transport injected).
|
|
22
|
+
* Returns { room, mk, userShare, commit }. The caller persists `userShare` on the user keyring; the tenant keeps K_eco.
|
|
23
|
+
* `extra` folds in the normal create fields (configSealed, gk, …). `originPubs` seeds the per-origin K_eco wraps. */
|
|
24
|
+
export async function createSplitRoom({ room, mk, K_eco, originPubs = {}, extra = {}, tenantPost }) {
|
|
25
|
+
if (!K_eco) throw new Error('createSplitRoom needs K_eco')
|
|
26
|
+
if (typeof tenantPost !== 'function') throw new Error('createSplitRoom needs an authed tenantPost')
|
|
27
|
+
mk = mk || newKey()
|
|
28
|
+
const c = await commit(mk)
|
|
29
|
+
const { shareA: userShare, shareB: appShare } = splitKey(mk)
|
|
30
|
+
const appShareSealed = JSON.stringify(await seal(appShare, { eco: K_eco }))
|
|
31
|
+
const ecoWraps = await wrapKEco(K_eco, originPubs)
|
|
32
|
+
const r = await tenantPost('create', { room, commit: c, appShareSealed, ecoWraps, ...extra })
|
|
33
|
+
if (!r || r.status !== 200) throw new Error('createSplitRoom failed: ' + (r && (r.error || r.status)))
|
|
34
|
+
return { room, mk, userShare, commit: c }
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** CREATE a split-key room in the L1-vault model: the client mints mk + splits, keeps `userShare`, and hands the RAW
|
|
38
|
+
* `appShare` to the tenant BACKEND (which seals it under K_eco + creates the room — the client never holds K_eco).
|
|
39
|
+
* `tenantPost('create', {room, commit, appShare, configSealed?})` → `/api/appshare {op:'create'}`. Returns
|
|
40
|
+
* { room, mk, userShare, commit }; the caller persists `userShare` (space:us:) + `commit` (space:spc:), NEVER `mk`. */
|
|
41
|
+
export async function createSplitViaBackend({ room, mk, config, gk, roomKind, split = true, gated, tenantPost, delCommit, owner = null }) { // owner: { ownerPolicy, roomAuth, attestAccept? } — a room that requires an app (space.js createSplitLocal)
|
|
42
|
+
if (!room) throw new Error('createSplitViaBackend needs a room id')
|
|
43
|
+
if (typeof tenantPost !== 'function') throw new Error('createSplitViaBackend needs an authed tenantPost')
|
|
44
|
+
mk = mk || newKey()
|
|
45
|
+
const c = await commit(mk)
|
|
46
|
+
const extra = config ? { configSealed: JSON.stringify(await seal(JSON.stringify(config), { room: mk })) } : {}
|
|
47
|
+
// `roomKind` (clear) is stamped by the tenant for inventory; `split` chooses the key model — split-key rooms carry the
|
|
48
|
+
// appShare (cross-tenant-isolated, sealed under K_eco by the backend), a PLAIN tenant room omits it (attributed, not split).
|
|
49
|
+
// `gated` (clear) is the email-admission marker: the admission + allow-list ride SEALED in the config (the platform can't
|
|
50
|
+
// read who's allowed), but the server needs this cleartext flag to refuse the KEYLESS reads (pollsealed/blob) of a gated room.
|
|
51
|
+
const body = { room, commit: c, ...extra, ...(gk ? { gk } : {}), ...(roomKind ? { roomKind } : {}), ...(gated ? { gated: true } : {}), ...(delCommit ? { delCommit } : {}), ...(owner && owner.ownerPolicy && owner.roomAuth ? { ownerPolicy: owner.ownerPolicy, roomAuth: owner.roomAuth, ...(owner.attestAccept ? { attestAccept: owner.attestAccept } : {}) } : {}) } // gk: the room invite PUBLIC key, so per-member turns are attribution-verifiable (a membership fork mints a fresh gk)
|
|
52
|
+
let userShare
|
|
53
|
+
if (split) { const s = splitKey(mk); userShare = s.shareA; body.appShare = s.shareB }
|
|
54
|
+
const r = await tenantPost('create', body)
|
|
55
|
+
if (!r || r.status !== 200) throw new Error('createSplitViaBackend failed: ' + (r && (r.error || r.status)))
|
|
56
|
+
return { room, mk, commit: c, ...(split ? { userShare } : {}), ...(extra.configSealed ? { configSealed: extra.configSealed } : {}) } // configSealed surfaced so an ENCLAVE room can also seal it into the ENCLAVE's own record (the tenant copy isn't what the enclave turn reads)
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** RECONSTRUCT mk from the user's `userShare` (held by the L1 vault) + an ALREADY-UNWRAPPED `appShare` (served by the
|
|
60
|
+
* tenant/origin, which did the K_eco unwrap — the vault never holds K_eco, or it could reconstruct mk alone). Verifies
|
|
61
|
+
* commit(mk) (§6.4). Returns mk, or null (fail-closed). This is the vault-side half of the combine; the tenant-side half
|
|
62
|
+
* (fetch appShareSealed → unwrap with K_eco → appShare) lives in the tenant backend. */
|
|
63
|
+
export async function reconstructMk({ userShare, appShare, expectedCommit }) {
|
|
64
|
+
if (!userShare || !appShare) return null
|
|
65
|
+
const mk = combineShares(userShare, appShare)
|
|
66
|
+
if (!mk) return null
|
|
67
|
+
if (expectedCommit && (await commit(mk)) !== expectedCommit) return null // never trust an unverified combine
|
|
68
|
+
return mk
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** OPEN a split-key room. The `origin` (holding a K_eco wrap) unwraps K_eco → appShare; combine with the user's
|
|
72
|
+
* `userShare` → mk; verify commit(mk) against the room's registered commitment (§6.4). `origin` = { id, privateJwk }.
|
|
73
|
+
* Returns { room, mk } on success, or { room, mk:null, error } — a null mk is always fail-closed (never a wrong key). */
|
|
74
|
+
export async function openSplitRoom({ room, userShare, origin, tenantPost }) {
|
|
75
|
+
if (typeof tenantPost !== 'function') throw new Error('openSplitRoom needs an authed tenantPost')
|
|
76
|
+
const r = await tenantPost('appshare-get', { room })
|
|
77
|
+
if (!r || r.status !== 200) return { room, mk: null, error: (r && (r.error || r.status)) || 'appshare_get_failed' }
|
|
78
|
+
const wrap = r.ecoWraps && r.ecoWraps[origin && origin.id]
|
|
79
|
+
if (!wrap) return { room, mk: null, error: 'no_wrap_for_origin' }
|
|
80
|
+
let K_eco
|
|
81
|
+
try { K_eco = await openBox(JSON.parse(wrap), origin.privateJwk) } catch { K_eco = null }
|
|
82
|
+
if (!K_eco) return { room, mk: null, error: 'unwrap_failed' } // this origin's wrap is gone/invalid → dead (migration)
|
|
83
|
+
let appShare
|
|
84
|
+
try { appShare = await open(JSON.parse(r.appShareSealed), { mk: K_eco }) } catch { appShare = null }
|
|
85
|
+
if (!appShare) return { room, mk: null, error: 'appshare_undecodable' }
|
|
86
|
+
const mk = combineShares(userShare, appShare)
|
|
87
|
+
if (!mk) return { room, mk: null, error: 'combine_failed' }
|
|
88
|
+
if ((await commit(mk)) !== r.commit) return { room, mk: null, error: 'commit_mismatch' } // §6.4 — never trust an unverified combine
|
|
89
|
+
return { room, mk }
|
|
90
|
+
}
|