@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/sdkReport.js
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
// sdkReport.js — `space.report(message, { reason, note, context })`: REPORT from a builder's page (App Store rule 1.2;
|
|
2
|
+
// docs/report-and-block.md §3; sync sweep 2026-11-13 "not in the SDK, not decided"). The same report the Spaces app files
|
|
3
|
+
// (reportActions.js, whose body is built from the drawn rows — this one from the SDK's messages): what the member chose to show
|
|
4
|
+
// Witbitz — the message, and only if asked the 5 before it — sent in the clear to the front (op `report`, agent/reportOp.mjs),
|
|
5
|
+
// which stores it and mails the reports address. Signed in (who reported), and a MEMBER: a token only the room's current key gets
|
|
6
|
+
// (op membertoken) is fetched first, as the app does.
|
|
7
|
+
|
|
8
|
+
/** The reasons the server takes (agent/reportOp.mjs REASONS — sdkAppParityMore.test holds them equal). */
|
|
9
|
+
export const REPORT_REASONS = Object.freeze(['harassment', 'threats', 'sexual', 'hate', 'spam', 'other'])
|
|
10
|
+
const CONTEXT = 5
|
|
11
|
+
const fail = (code, message) => Object.assign(new Error('witbitz: ' + message), { code })
|
|
12
|
+
const isPerson = (m) => m && typeof m === 'object' && !m.sys && m.kind !== 'data' && m.kind !== 'fork' && m.kind !== 'title'
|
|
13
|
+
|
|
14
|
+
/** One message as the report names it: what it said, and who the room says wrote it (`who`: the Block identity — the verified
|
|
15
|
+
* email / @username and the key that signed it; none for the assistant or an outside agent's relayed line). */
|
|
16
|
+
export function reportEntry (m, who, { proof = false } = {}) {
|
|
17
|
+
const files = [...(Array.isArray(m.images) ? m.images : []), ...(Array.isArray(m.files) ? m.files : [])].map((a) => String((a && a.name) || '')).filter(Boolean).slice(0, 10)
|
|
18
|
+
return {
|
|
19
|
+
name: String(m.from || m.name || '').slice(0, 80), text: String(m.text || '').slice(0, 8000), ...(files.length ? { files } : {}), agent: m.self === true,
|
|
20
|
+
...(who && who.email ? { email: who.email } : {}), ...(who && who.user ? { user: who.user, verified: true } : {}), ...(who && who.sid ? { kid: who.sid } : {}),
|
|
21
|
+
...(m.ts != null ? { ts: m.ts } : {}), ...(m.id != null ? { id: String(m.id) } : {}),
|
|
22
|
+
// FRANKING (docs/report-and-block.md §2; sync sweep 11-16 #5): the reported message's sealed record and the RAW text it was made
|
|
23
|
+
// over — with them Witbitz can prove the report and act on it, as from the app (reportActions.js). The context carries none.
|
|
24
|
+
...(proof && typeof m.fr === 'string' ? { fr: m.fr, raw: String(m.text || '') } : {}),
|
|
25
|
+
...(proof && (m.source === 'shared' || (m.carried && typeof m.carried === 'object')) ? { copied: true } : {}), // #10: a copy from another Space
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** The report's body → { room, reason, note, entry, context, confidential? }; throws invalid_argument. */
|
|
30
|
+
/** A mirrored copy in a lane → { room, id, fr } of the Space's original; anything else → null (reportActions.js laneOriginal's rule). */
|
|
31
|
+
export function laneOriginal (m) {
|
|
32
|
+
if (!m || typeof m.fr !== 'string' || typeof m.frRoom !== 'string' || !m.frRoom) return null
|
|
33
|
+
const id = String(m.id == null ? '' : m.id)
|
|
34
|
+
return id.startsWith('sh:') && id.length > 3 ? { room: m.frRoom, id: id.slice(3), fr: m.fr } : null
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export function reportBody (space, message, { reason, note = '', context = false } = {}) {
|
|
38
|
+
if (!message || typeof message !== 'object' || message.id == null) throw fail('invalid_argument', 'report(message, { reason }) takes a Message (from "message" or space.messages)')
|
|
39
|
+
if (!REPORT_REASONS.includes(reason)) throw fail('invalid_argument', 'reason is one of ' + REPORT_REASONS.join(', '))
|
|
40
|
+
const who = (m) => (m.self === true ? null : space.blockIdentity(m))
|
|
41
|
+
const before = []
|
|
42
|
+
if (context === true) {
|
|
43
|
+
const list = space.messages || [], at = list.findIndex((m) => m && m.id === message.id)
|
|
44
|
+
for (let i = at - 1; i >= 0 && before.length < CONTEXT; i--) if (isPerson(list[i])) before.unshift(reportEntry(list[i], who(list[i])))
|
|
45
|
+
}
|
|
46
|
+
return { room: space.room, reason, note: String(note || '').slice(0, 500), entry: reportEntry(message, who(message), { proof: true }), context: before, ...(space._isEnclave() ? { confidential: true } : {}) }
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** The whole report: sign-in, member token, the report → { ok: true, id } | { ok: false, error, detail? } (refusals are answers). */
|
|
50
|
+
export async function fileReport (space, message, opts = {}) {
|
|
51
|
+
// A LANE COPY of its Space's message (the app's reportActions.js laneOriginal; sync sweep 11-19 P1): the record is the Space's, so
|
|
52
|
+
// the report names the Space and the original's id, and the member token is the Space's — not the lane's
|
|
53
|
+
const orig = laneOriginal(message)
|
|
54
|
+
if (orig && space && space._sharedSpace && space._sharedSpace.room === orig.room) { const { source: _s, carried: _c, frRoom: _r, ...m } = message; return fileReport(space._sharedSpace, { ...m, id: orig.id, fr: orig.fr }, opts) } // the original, not a copy (no `copied`)
|
|
55
|
+
const c = space._client
|
|
56
|
+
if (c && c.vault) throw fail('vault_unsupported', 'a report from a vault is not available yet — the vault holds the sign-in and the room key')
|
|
57
|
+
const body = reportBody(space, message, opts)
|
|
58
|
+
const wb = space._wb
|
|
59
|
+
if (!wb || typeof wb._auth !== 'function') throw fail('sign_in_required', 'sign in first — a report names who sent it')
|
|
60
|
+
const { idToken } = wb._auth('a report belongs')
|
|
61
|
+
if (!c || typeof c.memberToken !== 'function' || typeof c.report !== 'function') throw fail('unavailable', 'this Space cannot file a report here')
|
|
62
|
+
const mt = await Promise.resolve().then(() => c.memberToken(space.room, space._mk)).catch(() => null)
|
|
63
|
+
if (!mt || mt.status !== 200 || !mt.token) return { ok: false, error: 'not_member', detail: 'only a member of this Space can report from it — or email reports@witbitz.chat' }
|
|
64
|
+
let r
|
|
65
|
+
try { r = await c.report(idToken, body, mt.token) } catch (e) { return { ok: false, error: String((e && e.code) || 'unavailable'), detail: 'the report was not sent — try again, or email reports@witbitz.chat' } }
|
|
66
|
+
if (r && r.ok === true) return { ok: true, id: String(r.id || ''), proven: r.proven === true } // proven: Witbitz's record matched (#5)
|
|
67
|
+
return { ok: false, error: String((r && r.error) || 'failed'), ...(r && r.reason ? { detail: String(r.reason) } : {}) }
|
|
68
|
+
}
|
package/sdkSafeMedia.js
ADDED
|
@@ -0,0 +1,255 @@
|
|
|
1
|
+
// sdkSafeMedia.js — `space.safeMedia`: SAFE MEDIA from a builder's page (docs/safe-media.md; the owner, 2026-10-27: "Do 1+2").
|
|
2
|
+
// The same engine as the Spaces app (safeMedia.js makeSafe / verifySafe, safeMediaRoom.js): in a room with `safeMedia: true`,
|
|
3
|
+
// a photo or a PDF is made safe ONCE — sent, sealed to the tools enclave's ATTESTED key, through the Space server (which sees
|
|
4
|
+
// ciphertext only), and given back as JPEGs our enclave encoded from pixels a keyless one-shot parser produced, with the
|
|
5
|
+
// hardware's attestation over exactly those bytes. The copies are stored beside the original (op 'safe', a hidden entry
|
|
6
|
+
// `{ kind: 'safe', safeFor: { id, at, i }, safe }`), and a reader draws one only after checking that attestation itself.
|
|
7
|
+
//
|
|
8
|
+
// space.safeMedia.on → true | false | null (not known yet: call refresh())
|
|
9
|
+
// await space.safeMedia.refresh() → boolean, from the room's sealed settings
|
|
10
|
+
// await space.safeMedia.set(on, { from }) → { changed } — the admins' where the room names some, any member's otherwise
|
|
11
|
+
// await space.safeMedia.copy(message, ref) → { ok, versions: [{ w, h, b64 }], statement, att } | { ok: false, why } — VERIFIED here, or ok:false
|
|
12
|
+
// await space.safeMedia.make(message, ref) → { ok, error? } — make the copy for everyone (needs a signed-in session)
|
|
13
|
+
// await space.safeMedia.isOriginal(copy, b64) → boolean — the original is the file the copy was made from
|
|
14
|
+
// events on the Space: 'safeMedia' { on, from, ts } (the setting moved) · 'safeCopy' { for: { id, at, i } } (a copy arrived)
|
|
15
|
+
//
|
|
16
|
+
// `ref` = { at: 'images' | 'files', i } — which attachment of the message (default: its first image, else its first file).
|
|
17
|
+
// While the setting is on, send() makes the copies of what it sends by itself, as the app does (best effort: signed out,
|
|
18
|
+
// offline or too large, the message goes anyway and anyone may make() it later).
|
|
19
|
+
|
|
20
|
+
import { makeSafe, verifySafe, isTheOriginal, firstVerifiedCopy, safeMediaReady, SAFE_MAX_INPUT } from './safeMedia.js'
|
|
21
|
+
|
|
22
|
+
const fail = (code, message) => Object.assign(new Error('witbitz: ' + message), { code })
|
|
23
|
+
const stdB64 = (b) => { let s = ''; for (let i = 0; i < b.length; i += 0x8000) s += String.fromCharCode(...b.subarray(i, i + 0x8000)); return btoa(s) }
|
|
24
|
+
const fromB64 = (s) => Uint8Array.from(atob(String(s || '').replace(/^data:[^,]*,/, '')), (c) => c.charCodeAt(0))
|
|
25
|
+
const isPdf = (a) => !!a && (a.mime === 'application/pdf' || /\.pdf$/i.test(a.name || ''))
|
|
26
|
+
export const isImg = (a) => !!a && (a.kind === 'image' || /^image\//i.test(String(a.mime || ''))) // = media.js isImageAtt, COPIED: media.js loads the app's idb and key worker, which the SDK must not (isImgCopy.test holds them equal) — a photo sent as a file is a photo
|
|
27
|
+
const slotKey = (f) => `${f.id}|${f.at}|${f.i}`
|
|
28
|
+
// the assistant's photos (_autoAgent): the app's numbers, COPIED — messageRender.js and safeMediaRoom.js load the app's shell
|
|
29
|
+
// (sdkAppParityMore.test holds them equal)
|
|
30
|
+
export const AUTO_SAFE_MS = 30 * 60_000 // a photo younger than this gets its copy made by the first device that draws it
|
|
31
|
+
export const AUTO_SAFE_WAIT_MS = 2500 // …after this wait, for a copy another device may be making
|
|
32
|
+
/** What send() matches its own stored message by — the app's echo signature (space.js echoSig). */
|
|
33
|
+
export const sigOf = (m) => `${String((m && m.text) || '').trim()}|${((m && m.images) || []).length}|${((m && m.files) || []).length}`
|
|
34
|
+
|
|
35
|
+
export class SpaceSafeMedia {
|
|
36
|
+
/** @param {object} space the Space; @param {object} [deps] injectable engine (tests): { makeSafe, verifySafe, pins, root, now } */
|
|
37
|
+
constructor (space, deps = {}) {
|
|
38
|
+
this._s = space
|
|
39
|
+
this._d = { makeSafe, verifySafe, pins: undefined, root: undefined, ...deps }
|
|
40
|
+
this._on = null; this._at = -1 // what is known, as of `_at` (a settings read: now; a line: its ts) — an older word never wins
|
|
41
|
+
this._copies = new Map() // slotKey → [copy entries], oldest first
|
|
42
|
+
this._sent = [] // { sig, made: [{ at, i, p }] } — copies being made for messages this handle sent, waiting for their ids
|
|
43
|
+
this._autoTried = new Set() // the assistant's photos this handle has made (or tried to make) a copy of — once each
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** The setting as this handle knows it: true / false, or null before the room's settings or a line said. A private lane
|
|
47
|
+
* follows its Space's (sync sweep 2026-10-27 #1: the mirror copies the Space's photos into the lane, and there they were
|
|
48
|
+
* read as plain attachments) — draw a lane's photos through copy() as the Space's. */
|
|
49
|
+
get on () {
|
|
50
|
+
// a lane's OWN value is ignored: before 2026-10-30 a lane could be turned on alone, and nothing can turn that off now — it
|
|
51
|
+
// stayed on after its Space turned it off (sync sweep 2026-10-31 #3)
|
|
52
|
+
if (this._isLane()) { const sh = this._lane(); return sh && sh.safeMedia ? sh.safeMedia.on : null } // without its Space's handle: not known here
|
|
53
|
+
return this._on
|
|
54
|
+
}
|
|
55
|
+
/** @private the Space this handle's lane follows, or null for a Space (or a lane opened without its Space's handle) */
|
|
56
|
+
_lane () { const sh = this._s && this._s._sharedSpace; return sh && sh !== this._s ? sh : null }
|
|
57
|
+
/** @private IS this handle a private lane? ONE check (sync sweep P7: `configure` asked `_sharedRoom`, this file `_sharedSpace`, and
|
|
58
|
+
* a Lane built without its Space's handle — the app's and the vault's — read as a Space here: its own value, `set` allowed). */
|
|
59
|
+
_isLane () { return !!(this._s && this._s._sharedRoom) }
|
|
60
|
+
/** Is there an accepted safe-media build in this release at all? (safeMediaPins.js) — false: nothing verifies yet. */
|
|
61
|
+
get available () { return safeMediaReady(this._d.pins) }
|
|
62
|
+
|
|
63
|
+
/** @private learn the setting as of `at`; tells listeners when it moved. */
|
|
64
|
+
_learn (on, at, from = '') {
|
|
65
|
+
if (at < this._at) return
|
|
66
|
+
const was = this._on
|
|
67
|
+
this._on = !!on; this._at = at
|
|
68
|
+
// a LANE's own value is kept but never said: the lane follows its Space, and relays the Space's moves (sweep 11-07 #12)
|
|
69
|
+
if (was !== this._on && was !== null && !this._isLane()) this._s._emit('safeMedia', { on: this._on, from, ts: at })
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** Read the room's sealed settings → boolean. */
|
|
73
|
+
async refresh () {
|
|
74
|
+
const sh = this._lane()
|
|
75
|
+
if (sh && sh.safeMedia) return sh.safeMedia.refresh() // a lane follows its Space: read the Space's
|
|
76
|
+
if (this._isLane()) throw fail('lane_follows_space', 'a private lane follows its Space’s Safe media — read it on the Space (open the lane with its Space)')
|
|
77
|
+
const c = this._s._client
|
|
78
|
+
if (!c || typeof c.getConfig !== 'function') throw fail('unavailable', 'this Space cannot read its settings here')
|
|
79
|
+
let cfg = await c.getConfig(this._s.room, this._s._mk)
|
|
80
|
+
// a SLEEPING confidential Space reads nothing: wake it and read once more, as the vault does (sweep P2: a lane's refresh,
|
|
81
|
+
// which reads its Space's, failed until something else woke it)
|
|
82
|
+
const wb = this._s._wb
|
|
83
|
+
if (!cfg && !c.keyless && !c.vault && wb && typeof wb._encWake === 'function' && typeof this._s._isEnclave === 'function' && this._s._isEnclave()) {
|
|
84
|
+
try { await wb._encWake(this._s.room, { tries: 8 }); cfg = await c.getConfig(this._s.room, this._s._mk) } catch { /* said below */ }
|
|
85
|
+
}
|
|
86
|
+
// "sign in" only where it is the reason — a gated room's settings before sign-in; a sleeping enclave or a failed read is not
|
|
87
|
+
// (sweep 11-07 #8: a vault, signed in, was told to sign in)
|
|
88
|
+
if (!cfg || typeof cfg !== 'object') throw fail('config_unavailable', 'the room’s settings could not be read just now — try again')
|
|
89
|
+
if (cfg.gated === true && !cfg.allow) throw fail('config_unavailable', 'the room’s settings could not be read (sign in to a verified Space first)')
|
|
90
|
+
this._learn(cfg.safeMedia === true, Date.now())
|
|
91
|
+
return this.on === true // a private lane follows its Space (sync sweep 2026-10-29 #7: refresh() answered false while `on` was true)
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** Turn Safe media on or off for everyone — a line every member sees says who did. */
|
|
95
|
+
async set (on, { from } = {}) {
|
|
96
|
+
if (typeof on !== 'boolean') throw fail('invalid_argument', 'safeMedia.set takes true or false')
|
|
97
|
+
// A private lane follows its Space: its own setting could turn it on for the lane alone and never off (sync sweep
|
|
98
|
+
// 2026-10-30 #4) — the Space's admins set it, for everyone, on the Space.
|
|
99
|
+
if (this._isLane()) throw fail('lane_follows_space', 'a private lane follows its Space’s Safe media — set it on the Space')
|
|
100
|
+
if (on && !this.available) throw fail('safe_media_unavailable', 'no safe-media enclave is accepted in this release yet')
|
|
101
|
+
return this._s.configure({ safeMedia: on, ...(from ? { from } : {}) })
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/** @private one ledger entry, from the poll: a copy (kept, never a message) or the line that moved the setting. → true if consumed. */
|
|
105
|
+
_note (e) {
|
|
106
|
+
if (!e || typeof e !== 'object') return false
|
|
107
|
+
if (e.kind === 'safe') {
|
|
108
|
+
if (!e.safeFor || !e.safe) return true
|
|
109
|
+
const k = slotKey(e.safeFor), list = this._copies.get(k) || []
|
|
110
|
+
if (!list.some((x) => x.id === e.id)) { this._copies.set(k, [...list, e]); this._s._emit('safeCopy', { for: { id: e.safeFor.id, at: e.safeFor.at, i: e.safeFor.i } }) }
|
|
111
|
+
return true
|
|
112
|
+
}
|
|
113
|
+
if (e.sys && e.safeMedia && typeof e.safeMedia === 'object') this._learn(e.safeMedia.on === true, Number(e.ts) || 0, e.name || e.from || '')
|
|
114
|
+
return false
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** @private which attachment of a message → { at, i, att, kind } */
|
|
118
|
+
_slot (message, ref) {
|
|
119
|
+
if (!message || typeof message !== 'object' || message.id == null) throw fail('invalid_argument', 'safeMedia takes a stored message (from "message" or space.messages)')
|
|
120
|
+
let at = ref && ref.at, i = ref && Number.isInteger(ref.i) ? ref.i : 0
|
|
121
|
+
if (!at) at = Array.isArray(message.images) && message.images.length ? 'images' : 'files'
|
|
122
|
+
if (at !== 'images' && at !== 'files') throw fail('invalid_argument', "ref.at is 'images' or 'files'")
|
|
123
|
+
const att = Array.isArray(message[at]) ? message[at][i] : null
|
|
124
|
+
if (!att) throw fail('invalid_argument', `the message has no ${at}[${i}]`)
|
|
125
|
+
if (at === 'files' && !isPdf(att) && !isImg(att)) throw fail('invalid_argument', 'only photos and PDFs have safe copies')
|
|
126
|
+
return { at, i, att, kind: at === 'images' || isImg(att) ? 'image' : 'pdf' }
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/** The first copy of that attachment that VERIFIES on this device, every version checked → { ok, versions, statement, att } | { ok: false, why }. */
|
|
130
|
+
async copy (message, ref) {
|
|
131
|
+
const s = this._slot(message, ref)
|
|
132
|
+
const list = (this._copies.get(slotKey({ id: message.id, at: s.at, i: s.i })) || []).map((c) => ({ c, via: this._s }))
|
|
133
|
+
// a private lane's MIRRORED entry (`sh:<the Space's id>`) is drawn from its Space's copies — the same bytes; the original
|
|
134
|
+
// check below still holds (sync sweep: the Space's verified copies were never seen in the lane). Its COPIES are the Space's
|
|
135
|
+
// stored blobs, read through the SPACE's handle — the lane's room has none (sync sweep 11-08 #13); its ORIGINAL is the
|
|
136
|
+
// lane's own: the mirror stored the photo's bytes again in the lane, so the entry's ref is under the lane's key (sync
|
|
137
|
+
// sweep 11-09: read through the Space, it was a 404)
|
|
138
|
+
const m = /^sh:(.+)$/.exec(String(message.id || '')), sh = this._lane()
|
|
139
|
+
const shared = !!(m && sh && sh.safeMedia)
|
|
140
|
+
if (shared) list.push(...(sh.safeMedia._copies.get(slotKey({ id: m[1], at: s.at, i: s.i })) || []).map((c) => ({ c, via: sh.safeMedia._s })))
|
|
141
|
+
if (!list.length) return { ok: false, why: 'no safe copy yet' }
|
|
142
|
+
const origVia = this._s // the entry's own room holds its original — the lane's, for a mirrored one
|
|
143
|
+
// every version fetched and checked; the loop, the verify and the "made from THIS file" check are safeMedia.js firstVerifiedCopy,
|
|
144
|
+
// the app's too (sync sweep 2026-10-29 #1: a copy must be OF this file)
|
|
145
|
+
const r = await firstVerifiedCopy(list, {
|
|
146
|
+
fetch: async ({ via }, vs) => ({ bytes: await Promise.all(vs.map(async (v) => fromB64((await via.attachment({ ...v, mime: 'image/jpeg' })).b64))) }),
|
|
147
|
+
verify: (safe, bytes) => this._d.verifySafe(safe, bytes, { pins: this._d.pins, root: this._d.root }),
|
|
148
|
+
original: async () => fromB64((await origVia.attachment(s.att)).b64),
|
|
149
|
+
})
|
|
150
|
+
if (!r.ok) return r
|
|
151
|
+
const c = r.cand.c, vs = c.safe.versions
|
|
152
|
+
return { ok: true, versions: vs.map((x, k) => ({ w: x.w, h: x.h, b64: stdB64(r.bytes[k]) })), statement: c.safe.statement, att: c.safe.att }
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/** Does `b64` (the original's bytes, from space.attachment) hash to what `copy` was made from? Check before opening it. */
|
|
156
|
+
async isOriginal (copy, b64) {
|
|
157
|
+
let st; try { st = JSON.parse(copy && copy.statement) } catch { return false }
|
|
158
|
+
return isTheOriginal(st, fromB64(b64))
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/** @private the sign-in a make needs, or a clear error */
|
|
162
|
+
_idToken () {
|
|
163
|
+
const wb = this._s._wb
|
|
164
|
+
if (!wb || typeof wb._auth !== 'function') throw fail('sign_in_required', 'sign in first — making a file safe is counted to an account')
|
|
165
|
+
return wb._auth('making a file safe is counted').idToken
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/** @private bytes → the enclave → a verified result (throws with a reason) */
|
|
169
|
+
async _made (bytes, kind, mime, idToken) {
|
|
170
|
+
if (!bytes.length || bytes.length > SAFE_MAX_INPUT) throw fail('too_large', 'this file is too large to make safe')
|
|
171
|
+
return this._d.makeSafe({ bytes, kind, mime }, { client: this._s._client, idToken, pins: this._d.pins, root: this._d.root, ...(this._d.now ? { now: this._d.now } : {}) })
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/** @private post one made copy beside its original */
|
|
175
|
+
async _post (ref, made, from) {
|
|
176
|
+
const safe = { for: { id: ref.id, at: ref.at, i: ref.i }, statement: made.statement, att: made.att, versions: made.versions.map((v) => ({ w: v.w, h: v.h, b64: stdB64(v.bytes) })) }
|
|
177
|
+
// A sleeping confidential Space answers 'warming' (a copy wakes nothing), and one whose enclave key is not known yet throws
|
|
178
|
+
// before sending: wake it, then post once more — as the app does (sync sweep 2026-10-29 #6).
|
|
179
|
+
const post = () => Promise.resolve().then(() => this._s._client.safeCopy(this._s.room, this._s._mk, safe, from || this._s._who()))
|
|
180
|
+
.catch((e) => (/enclave key unavailable/.test(String((e && e.message) || e)) ? { status: 503, error: 'enclave_warming' } : Promise.reject(e)))
|
|
181
|
+
let r = await post()
|
|
182
|
+
const wb = this._s._wb
|
|
183
|
+
if (r && (r.status === 503 || r.error === 'enclave_warming') && wb && typeof wb._encWake === 'function' && typeof this._s._isEnclave === 'function' && this._s._isEnclave()) {
|
|
184
|
+
try { await wb._encWake(this._s.room, { tries: 8 }); r = await post() } catch { /* the enclave did not come up: say the first answer */ }
|
|
185
|
+
}
|
|
186
|
+
if (!r || r.status !== 200) return { ok: false, error: String((r && (r.reason || r.error)) || 'the room did not take it') }
|
|
187
|
+
this._s._kick()
|
|
188
|
+
return { ok: true }
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/** Make the safe copy of an attachment already in the room, for everyone. Never throws for a refusal: { ok, error? }. */
|
|
192
|
+
async make (message, ref, { from } = {}) {
|
|
193
|
+
this._s._needKey('safe media')
|
|
194
|
+
const s = this._slot(message, ref)
|
|
195
|
+
if (!this.available) return { ok: false, error: 'safe_media_unavailable' }
|
|
196
|
+
const idToken = this._idToken()
|
|
197
|
+
try {
|
|
198
|
+
const got = await this._s.attachment(s.att)
|
|
199
|
+
const made = await this._made(fromB64(got.b64), s.kind, s.att.mime || got.mime || '', idToken)
|
|
200
|
+
return await this._post({ id: message.id, at: s.at, i: s.i }, made, from)
|
|
201
|
+
} catch (e) { return { ok: false, error: String((e && (e.code === 'too_large' ? 'too_large' : e.message)) || e) } }
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/** @private at send: start making the copies of a message's photos and PDFs (only while the setting is on, signed in). */
|
|
205
|
+
async _prepare (msg) {
|
|
206
|
+
if (!(msg.images || []).length && !(msg.files || []).some((a) => isPdf(a) || isImg(a))) return
|
|
207
|
+
if (this.on === false || !this.available) return // `on`, not `_on`: a lane follows its Space (sync sweep 2026-10-29 #7)
|
|
208
|
+
const c = this._s._client
|
|
209
|
+
if (!c || c.keyless || typeof c.safeCopy !== 'function') return
|
|
210
|
+
if (this.on === null) { try { await this.refresh() } catch { return } } // once per handle: the first photo sent asks the room
|
|
211
|
+
if (this.on !== true) return
|
|
212
|
+
let idToken; try { idToken = this._idToken() } catch { return } // signed out: the message goes, anyone may make() later
|
|
213
|
+
const made = []
|
|
214
|
+
const start = (at, i, a, kind) => {
|
|
215
|
+
if (!a || typeof a.b64 !== 'string') return
|
|
216
|
+
let bytes; try { bytes = fromB64(a.b64) } catch { return }
|
|
217
|
+
made.push({ at, i, p: this._made(bytes, kind, a.mime || '', idToken).catch(() => null) })
|
|
218
|
+
}
|
|
219
|
+
;(msg.images || []).forEach((a, i) => start('images', i, a, 'image'))
|
|
220
|
+
;(msg.files || []).forEach((a, i) => { if (isPdf(a)) start('files', i, a, 'pdf'); else if (isImg(a)) start('files', i, a, 'image') })
|
|
221
|
+
if (made.length) this._sent.push({ sig: sigOf(msg), made, at: Date.now() })
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
/** @private THE ASSISTANT'S PHOTOS TOO (the app's messageRender.js autoSafe + safeMediaRoom.js `auto`; docs/safe-media.md § 11;
|
|
225
|
+
* sync sweep 2026-11-13): show_photo and fetch_url put pictures from web pages into its replies, and no device sent them, so
|
|
226
|
+
* nobody made their copy at send. A RECENT one with no copy after a short wait (another member's device may be making it) is
|
|
227
|
+
* made here — the bytes go to the tools enclave, nothing is decoded on this device. Once per photo per handle; signed out, a
|
|
228
|
+
* keyless client (a vault) or a failure: it waits for make(), as before. Its PDFs are left alone (write_pdf's are our own). */
|
|
229
|
+
_autoAgent (m) {
|
|
230
|
+
if (this.on !== true || !this.available || /^sh:/.test(String(m.id))) return // a lane's copy of its Space's line: the Space's handle makes it
|
|
231
|
+
const c = this._s._client
|
|
232
|
+
if (!c || c.keyless || typeof c.safeCopy !== 'function' || !(Number(m.ts) > Date.now() - AUTO_SAFE_MS)) return
|
|
233
|
+
const todo = (Array.isArray(m.images) ? m.images : []).map((_a, i) => i).filter((i) => !this._autoTried.has(slotKey({ id: m.id, at: 'images', i })))
|
|
234
|
+
if (!todo.length) return
|
|
235
|
+
for (const i of todo) this._autoTried.add(slotKey({ id: m.id, at: 'images', i }))
|
|
236
|
+
const t = setTimeout(async () => {
|
|
237
|
+
for (const i of todo) {
|
|
238
|
+
if ((this._copies.get(slotKey({ id: m.id, at: 'images', i })) || []).length || this._s._stopped) continue // a copy came meanwhile
|
|
239
|
+
try { await this.make(m, { at: 'images', i }) } catch { /* signed out: Make safe stays the way */ }
|
|
240
|
+
}
|
|
241
|
+
}, this._d.autoWaitMs ?? AUTO_SAFE_WAIT_MS)
|
|
242
|
+
try { t.unref?.() } catch { /* a browser timer */ }
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
/** @private a stored message arrived: if this handle sent it, its copies go beside it; the assistant's recent photos get theirs. */
|
|
246
|
+
_arrived (m) {
|
|
247
|
+
if (m && m.self && !m.sys && m.id != null) { this._autoAgent(m); return }
|
|
248
|
+
if (!this._sent.length || !m || m.self || m.sys || m.id == null) return
|
|
249
|
+
this._sent = this._sent.filter((x) => Date.now() - x.at < 10 * 60_000) // a message the room never gave back is let go
|
|
250
|
+
const k = this._sent.findIndex((x) => x.sig === sigOf(m))
|
|
251
|
+
if (k < 0) return
|
|
252
|
+
const [x] = this._sent.splice(k, 1)
|
|
253
|
+
;(async () => { for (const y of x.made) { const made = await y.p; if (made) await this._post({ id: m.id, at: y.at, i: y.i }, made).catch(() => null) } })()
|
|
254
|
+
}
|
|
255
|
+
}
|
package/sdkSchedules.js
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { SCHEDULES_DOC, ALWAYSON_DOC, alwaysOnNow, jobsOf, withJob, withoutJob, withPaused, summaryOf } from './schedulesDoc.js'
|
|
2
|
+
|
|
3
|
+
const fail = (code, message, status) => Object.assign(new Error('witbitz: ' + message), { code, ...(status ? { status } : {}) })
|
|
4
|
+
|
|
5
|
+
/** The same sealed schedule document edited by the app and executed by the cloud device. */
|
|
6
|
+
export class SpaceSchedules {
|
|
7
|
+
constructor(space) { this._sp = space }
|
|
8
|
+
async _read(name) {
|
|
9
|
+
const s = this._sp, r = await s._client.state(s.room, s._mk, name)
|
|
10
|
+
if (!r || r.status !== 200 || !Number.isInteger(r.v)) throw fail((r && r.error) || 'unreadable', 'the schedule document could not be read', r && r.status)
|
|
11
|
+
return r
|
|
12
|
+
}
|
|
13
|
+
async list() { const s = this._sp; if (s._wb?.vault) return s._wb.vault._c.roomAccount(s.room, 'schedules', 'list'); return jobsOf(await this._read(SCHEDULES_DOC)) }
|
|
14
|
+
async _edit(fn, needsDevice = false) {
|
|
15
|
+
const s = this._sp
|
|
16
|
+
if (needsDevice && !alwaysOnNow(await this._read(ALWAYSON_DOC))) throw fail('not_always_on', 'this Space needs an active cloud device for schedules')
|
|
17
|
+
for (let i = 0; i < 5; i++) {
|
|
18
|
+
const cur = await this._read(SCHEDULES_DOC), jobs = fn(jobsOf(cur))
|
|
19
|
+
const r = await s._client.state(s.room, s._mk, SCHEDULES_DOC, { jobs }, summaryOf(jobs), s._who(), cur.v)
|
|
20
|
+
if (r && r.status === 409) continue
|
|
21
|
+
if (!r || r.status !== 200) throw fail((r && r.error) || 'save_failed', 'the schedules could not be saved', r && r.status)
|
|
22
|
+
s._kick()
|
|
23
|
+
if (s._wb && s._wb.cloudDevice) s._wb.cloudDevice._ask('sched', { room: s.room }).catch(() => {})
|
|
24
|
+
return jobs
|
|
25
|
+
}
|
|
26
|
+
throw fail('version_conflict', 'the schedules kept changing; try again', 409)
|
|
27
|
+
}
|
|
28
|
+
async add({ when, text } = {}) {
|
|
29
|
+
const s = this._sp; if (s._wb?.vault) return s._wb.vault._c.roomAccount(s.room, 'schedules', 'add', { when, text })
|
|
30
|
+
let id
|
|
31
|
+
const jobs = await this._edit((jobs) => { const next = withJob(jobs, { when, text, by: this._sp._who() }); id = next.at(-1).id; return next }, true)
|
|
32
|
+
return jobs.find((j) => j.id === id)
|
|
33
|
+
}
|
|
34
|
+
async remove(id) { const s = this._sp; if (s._wb?.vault) return s._wb.vault._c.roomAccount(s.room, 'schedules', 'remove', id); return this._edit((jobs) => withoutJob(jobs, id)) }
|
|
35
|
+
async pause(id, paused = true) {
|
|
36
|
+
const s = this._sp; if (s._wb?.vault) return s._wb.vault._c.roomAccount(s.room, 'schedules', 'pause', id, !!paused)
|
|
37
|
+
return this._edit((jobs) => { if (!jobs.some((j) => j.id === id)) throw fail('not_found', 'that schedule does not exist'); return withPaused(jobs, id, !!paused) }, !paused)
|
|
38
|
+
}
|
|
39
|
+
}
|
package/sdkSpeech.js
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
// sdkSpeech.js — wb.speak(text): text read aloud on a builder's page, the same player the Spaces app's "Play aloud" uses
|
|
2
|
+
// (speechOut.js).
|
|
3
|
+
//
|
|
4
|
+
// await wb.speak('Your table is booked for 8.') // resolves when it has finished playing
|
|
5
|
+
// wb.speech.stop() // stop what is playing
|
|
6
|
+
// wb.speech.playing // true while it plays
|
|
7
|
+
//
|
|
8
|
+
// The text goes STRAIGHT from the page to Tinfoil's attested speech model — never through Witbitz. Witbitz only mints the
|
|
9
|
+
// page a short-lived, capped key (op:'tts', agent/sttKey.mjs), and only for a signed-in person (wb.signIn) or a user the
|
|
10
|
+
// tenant's backend vouched for (wb.useUserToken), as dictation does. A long text is cut at sentence ends; each request is
|
|
11
|
+
// $0.002 whatever its length. https://witbitz.chat/docs/sdk-assistant.md#speak.
|
|
12
|
+
// ⚑ No Hebrew: Hebrew-dominant text is refused (`no_hebrew`) before anything is spent. ⚑ The page's own CSP must allow
|
|
13
|
+
// `connect-src https://inference.tinfoil.sh` and `media-src blob:`; playback needs a user gesture on most browsers.
|
|
14
|
+
import { createTtsPlayer } from './speechOut.js'
|
|
15
|
+
|
|
16
|
+
const err = (code, message) => Object.assign(new Error('witbitz: ' + message), { code })
|
|
17
|
+
|
|
18
|
+
export class Speech {
|
|
19
|
+
constructor (wb, { fetchImpl, AudioImpl, URLImpl, checkKey } = {}) { // checkKey: a test seam — the page's own evidence check (voiceAttest.js) by default
|
|
20
|
+
this._wb = wb
|
|
21
|
+
this._player = createTtsPlayer({ getKey: () => this._key(), ...(checkKey ? { checkKey } : {}), ...(fetchImpl ? { fetchImpl } : {}), ...(AudioImpl ? { AudioImpl } : {}), ...(URLImpl ? { URLImpl } : {}) })
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** true while something is playing. */
|
|
25
|
+
get playing () { return this._player.playing }
|
|
26
|
+
|
|
27
|
+
/** @private the page's key (op:'tts'): a signed-in session first (the person), else the tenant's user token. */
|
|
28
|
+
async _who () {
|
|
29
|
+
const wb = this._wb, sess = wb._session
|
|
30
|
+
const idToken = sess && sess.idToken && !(sess.exp && sess.exp <= Date.now()) ? sess.idToken : ''
|
|
31
|
+
let userToken = ''
|
|
32
|
+
try { const t = typeof wb._userToken === 'function' ? await wb._userToken() : wb._userToken; userToken = typeof t === 'string' ? t : '' } catch { userToken = '' }
|
|
33
|
+
if (!idToken && !userToken && !wb.vault) throw err('sign_in_required', 'speak needs a signed-in user (wb.signIn) or a user token (wb.useUserToken)') // in a vault, the vault's sign-in mints the key
|
|
34
|
+
return { idToken, userToken, payer: userToken || sess?.email || '' }
|
|
35
|
+
}
|
|
36
|
+
async _key () {
|
|
37
|
+
const { idToken, userToken } = this._playAuth || await this._who()
|
|
38
|
+
const wb = this._wb
|
|
39
|
+
const r = await wb._client.tts(idToken, userToken)
|
|
40
|
+
if (!r || r.status !== 200 || !r.key) {
|
|
41
|
+
const code = (r && r.error === 'signin_required') ? 'sign_in_required' : (r && r.status === 429) ? 'tts_rate_limited' : 'tts_unavailable'
|
|
42
|
+
throw Object.assign(err(code, 'reading aloud is unavailable: ' + String((r && (r.reason || r.error)) || 'HTTP ' + (r && r.status))), { status: r && r.status })
|
|
43
|
+
}
|
|
44
|
+
return r
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** Read `text` aloud → resolves when it has played. Rejects with `code`: `no_hebrew`, `empty`, `sign_in_required`,
|
|
48
|
+
* `tts_rate_limited`, `tts_unavailable`, `http_<status>`, `audio` / `play` (the browser would not play it). A new call
|
|
49
|
+
* stops the one playing. */
|
|
50
|
+
_resetPayer () {
|
|
51
|
+
this._epoch = (this._epoch || 0) + 1
|
|
52
|
+
this._playAuth = null
|
|
53
|
+
this._player.resetKey()
|
|
54
|
+
}
|
|
55
|
+
async play (text) {
|
|
56
|
+
const seq = this._sequence = (this._sequence || 0) + 1
|
|
57
|
+
const epoch = this._epoch
|
|
58
|
+
const auth = await this._who()
|
|
59
|
+
if (seq !== this._sequence) return
|
|
60
|
+
if (epoch !== this._epoch) throw err('account_changed', 'the voice payer changed')
|
|
61
|
+
if (this._playAuth && this._playAuth.payer !== auth.payer) this._player.resetKey()
|
|
62
|
+
this._playAuth = auth
|
|
63
|
+
try { await this._player.play(String(text == null ? '' : text)) } catch (e) {
|
|
64
|
+
if (e && e.code && !String(e.message || '').startsWith('witbitz:')) e.message = 'witbitz: ' + e.message
|
|
65
|
+
throw e
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** Stop what is playing (its promise resolves). */
|
|
70
|
+
stop () { this._sequence = (this._sequence || 0) + 1; this._player.stop() }
|
|
71
|
+
}
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
import { deviceWrapKey } from './vaultAtRest.js'
|
|
2
|
+
import { seal, open } from './deviceSeal.js'
|
|
3
|
+
|
|
4
|
+
const fail = (code, message) => Object.assign(new Error('witbitz: ' + message), { code })
|
|
5
|
+
const pendingScope = wb => JSON.stringify([wb._endpoint, wb._tenant, wb._clientOpts.app || '', wb._session?.email || ''])
|
|
6
|
+
const storagePrefix = scope => 'wb-sdk:temporary:' + encodeURIComponent(scope) + ':'
|
|
7
|
+
|
|
8
|
+
export class TemporaryRooms {
|
|
9
|
+
constructor(wb, persist) {
|
|
10
|
+
this._wb = wb
|
|
11
|
+
this._persist = persist === true
|
|
12
|
+
this._memory = new Map()
|
|
13
|
+
this._generation = 0
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
_scope() {
|
|
17
|
+
if (this._wb.vault) throw fail('vault_unsupported', 'temporary rooms are unavailable in vault mode')
|
|
18
|
+
return pendingScope(this._wb)
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
async _remember(sp, scope, { days, title } = {}) {
|
|
22
|
+
if (scope !== this._scope()) return
|
|
23
|
+
const generation = this._generation, name = storagePrefix(scope) + sp.room
|
|
24
|
+
const previous = this._memory.get(name) || (await this._records(scope, sp.room)).get(name)
|
|
25
|
+
if (scope !== this._scope() || generation !== this._generation) return
|
|
26
|
+
const record = { ...previous, room: sp.room, link: sp.shareLink, at: previous?.at || Date.now() }
|
|
27
|
+
if (days) record.days = days
|
|
28
|
+
const label = sp.title || title
|
|
29
|
+
if (label) record.title = String(label).slice(0, 200)
|
|
30
|
+
sp._temporaryScope = scope
|
|
31
|
+
this._memory.set(name, record)
|
|
32
|
+
if (!this._persist) return
|
|
33
|
+
try {
|
|
34
|
+
const key = await deviceWrapKey({ name: 'witbitz-sdk-temporary' })
|
|
35
|
+
if (!key) return
|
|
36
|
+
const blob = await seal(key, { scope, ...record })
|
|
37
|
+
if (pendingScope(this._wb) === scope && this._generation === generation && this._memory.get(name) === record) globalThis.localStorage.setItem(name, JSON.stringify(blob))
|
|
38
|
+
} catch { /* still available in this SDK instance */ }
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
async _records(scope, onlyRoom) {
|
|
42
|
+
const prefix = storagePrefix(scope)
|
|
43
|
+
const wanted = onlyRoom ? prefix + onlyRoom : null
|
|
44
|
+
const rows = new Map([...this._memory].filter(([k]) => wanted ? k === wanted : k.startsWith(prefix)))
|
|
45
|
+
if (!this._persist) return rows
|
|
46
|
+
let key, storage
|
|
47
|
+
try {
|
|
48
|
+
storage = globalThis.localStorage
|
|
49
|
+
if (!storage) return rows
|
|
50
|
+
key = await deviceWrapKey({ name: 'witbitz-sdk-temporary' })
|
|
51
|
+
} catch { return rows }
|
|
52
|
+
if (!key) return rows
|
|
53
|
+
const names = wanted ? [wanted] : Array.from({ length: storage.length }, (_, i) => storage.key(i))
|
|
54
|
+
for (const name of names) {
|
|
55
|
+
if (!name?.startsWith(prefix) || rows.has(name)) continue
|
|
56
|
+
try {
|
|
57
|
+
const blob = storage.getItem(name)
|
|
58
|
+
if (!blob) continue
|
|
59
|
+
const row = await open(key, JSON.parse(blob))
|
|
60
|
+
if (row?.scope === scope && row.room?.startsWith('tmp-') && name === prefix + row.room) rows.set(name, row)
|
|
61
|
+
} catch { /* leave unreadable records in place and continue with the others */ }
|
|
62
|
+
}
|
|
63
|
+
return rows
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
async _status(row) {
|
|
67
|
+
if (Date.now() - row.at < (row.days ? row.days * 86_400_000 : 30 * 60_000)) return 'recent'
|
|
68
|
+
try {
|
|
69
|
+
const k = await this._wb._openLink(row.link)
|
|
70
|
+
if (k.room !== row.room) return 'unknown'
|
|
71
|
+
const r = await this._wb._client.pollSealed(k.room, k.mk, '', 0)
|
|
72
|
+
if (r?.status === 410) return 'expired'
|
|
73
|
+
if (r?.status === 200 && !r.changed && !r.entries?.length) return 'unknown'
|
|
74
|
+
return r?.status === 200 ? 'live' : 'unknown'
|
|
75
|
+
} catch { return 'unknown' }
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
_drop(name) {
|
|
79
|
+
this._memory.delete(name)
|
|
80
|
+
if (this._persist) globalThis.localStorage?.removeItem(name)
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
_title(sp) {
|
|
84
|
+
if (sp._temporaryScope !== this._scope()) return
|
|
85
|
+
const row = this._memory.get(storagePrefix(sp._temporaryScope) + sp.room)
|
|
86
|
+
if (row && row.title !== sp.title) this._remember(sp, sp._temporaryScope).catch(() => {})
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
_erase(scope) {
|
|
90
|
+
this._generation++
|
|
91
|
+
const prefix = storagePrefix(scope)
|
|
92
|
+
for (const name of this._memory.keys()) if (name.startsWith(prefix)) this._memory.delete(name)
|
|
93
|
+
let storage
|
|
94
|
+
try { storage = globalThis.localStorage } catch { return }
|
|
95
|
+
if (!storage) return
|
|
96
|
+
for (let i = storage.length - 1; i >= 0; i--) {
|
|
97
|
+
const name = storage.key(i)
|
|
98
|
+
if (name?.startsWith(prefix)) storage.removeItem(name)
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
async list() {
|
|
103
|
+
const scope = this._scope(), rows = await this._records(scope), result = []
|
|
104
|
+
for (const [name, row] of rows) {
|
|
105
|
+
const status = await this._status(row)
|
|
106
|
+
if (scope !== this._scope()) throw fail('account_changed', 'the account changed')
|
|
107
|
+
if (status === 'expired') this._drop(name)
|
|
108
|
+
else result.push({ room: row.room, at: row.at, title: row.title || '', status })
|
|
109
|
+
}
|
|
110
|
+
if (scope !== this._scope()) throw fail('account_changed', 'the account changed')
|
|
111
|
+
return result.sort((a, b) => b.at - a.at)
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
async open(room, options) {
|
|
115
|
+
const scope = this._scope(), name = storagePrefix(scope) + room
|
|
116
|
+
const row = (await this._records(scope, room)).get(name)
|
|
117
|
+
if (!row) throw fail('not_found', 'this device has no such temporary room')
|
|
118
|
+
const status = await this._status(row)
|
|
119
|
+
if (scope !== this._scope()) throw fail('account_changed', 'the account changed')
|
|
120
|
+
if (status === 'expired') { this._drop(name); throw fail('expired', 'this temporary room has expired') }
|
|
121
|
+
return this._wb.openSpace(row.link, options)
|
|
122
|
+
}
|
|
123
|
+
}
|