UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

276 lines (275 loc) • 9.56 kB
import { t as createSubsystemLogger } from "./subsystem-BHJiy01V.mjs"; import { x as registerOpenClawStateDatabaseLifecycleListener } from "./openclaw-state-db-cache-CkwtTqzF.mjs"; import { r as captureOpenClawStateWorkerContext } from "./openclaw-state-worker-context-DAKL_dnZ.mjs"; import { n as createAsyncLock } from "./json-files-Cb1h8pYs.mjs"; import { n as executeDevicePairingMutation, r as onDevicePairSetupChange, t as DevicePairingAuthorityRefusedError } from "./device-pairing-worker-SqWhlBR1.mjs"; import { n as loadBoundDeviceBootstrapContextReadOnly } from "./device-pairing-store-readonly-CIEEZowO.mjs"; import { f as normalizeDeviceBootstrapHandoffProfile, o as PAIRING_SETUP_BOOTSTRAP_PROFILE, p as normalizeDeviceBootstrapProfile } from "./device-bootstrap-profile-COYynVlw.mjs"; import "./pairing-files-D32vzdZo.mjs"; import { randomUUID } from "node:crypto"; //#region src/infra/device-bootstrap.ts const withLock = createAsyncLock(); const log = createSubsystemLogger("device-bootstrap"); function assertBootstrapTokenCurrent(e) { if (e.expiresAtMs < Date.now()) throw new DevicePairingAuthorityRefusedError(); } function warnIfIssuedBootstrapScopesWereStripped(e) { if (!e.input) return; const t = normalizeDeviceBootstrapProfile(e.input); const n = t.scopes; if (n.length === 0) return; const r = new Set(e.profile.scopes); const i = n.filter((e) => !r.has(e)); if (i.length === 0) return; log.warn("bootstrap_token_scopes_stripped", { roles: t.roles, requestedScopes: n, retainedScopes: e.profile.scopes, strippedScopes: i, consoleMessage: "bootstrap token scopes stripped to bootstrap handoff allowlist" }); } async function issueDeviceBootstrapTokenRecord(e) { const t = e.assertCurrent; return await withLock(async () => { const n = e.profile || (e.roles || e.scopes ? { roles: e.roles, scopes: e.scopes } : void 0); const r = n ? normalizeDeviceBootstrapHandoffProfile(n) : PAIRING_SETUP_BOOTSTRAP_PROFILE; warnIfIssuedBootstrapScopesWereStripped({ input: n, profile: r }); return await executeDevicePairingMutation({ type: "bootstrap.issue", input: { profile: r, setupId: e.setupId, nowMs: Date.now() } }, { baseDir: e.baseDir, assertCurrent: t }); }); } /** Issue a short-lived generic bootstrap token with a bounded role/scope handoff profile. */ async function issueDeviceBootstrapToken(e = {}) { return await issueDeviceBootstrapTokenRecord(e); } /** * Issue a setup bootstrap token plus an opaque correlation id. `setupId` is * minted here, beside the credential, so the presenting client can follow one * exact credential without ever handling the bearer token. Generic bootstrap * handoffs stay uncorrelated: only setup codes have a presenting client. */ async function issueDevicePairSetupBootstrapToken(e) { const t = randomUUID(); return { ...await issueDeviceBootstrapTokenRecord({ ...e, setupId: t }), setupId: t }; } function runBootstrapMutation(e, t, n) { return withLock(() => executeDevicePairingMutation({ type: e, input: t(Date.now()) }, n)); } /** Reuse one environment-owned setup credential across provider replay. */ async function ensureDevicePairSetupBootstrapToken(e) { const { baseDir: t, ...n } = e; return await runBootstrapMutation("bootstrap.ensure", (e) => ({ ...n, nowMs: e }), { baseDir: t }); } /** Consume only while the bound device and its live handoff authority remain current. */ async function consumeDeviceBootstrapTokenWithSetupCompletion(e) { const { baseDir: t, pairedDeviceMatches: n, admitsCloudWorkerSetup: r, ...i } = e; return await runBootstrapMutation("bootstrap.consume", (e) => ({ ...i, nowMs: e }), { baseDir: t, onAuthorityRefused: () => null, admit: (e) => { if (e.kind === "bootstrap.consume") { assertBootstrapTokenCurrent(e); if (n && !n(e.pairedDevice)) throw new DevicePairingAuthorityRefusedError(); } if (e.kind === "bootstrap.cloudWorkerSetup" && r?.(e) !== true) throw new DevicePairingAuthorityRefusedError(); } }); } /** Confirm that the pairing client received the credential-bearing handoff response. */ async function confirmDevicePairSetupCompletionDelivery(e) { const { baseDir: t, ...n } = e; return await runBootstrapMutation("bootstrap.confirm", (e) => ({ ...n, nowMs: e }), { baseDir: t }); } /** Read the terminal outcome and prune expired completions under the settlement lock. */ async function readDevicePairSetupCompletion(e) { const { baseDir: t, ...n } = e; return await runBootstrapMutation("bootstrap.readCompletion", (e) => ({ ...n, nowMs: e }), { baseDir: t }); } async function clearDeviceBootstrapTokens(e = {}) { const { baseDir: t, assertCurrent: n, ...r } = e; return await runBootstrapMutation("bootstrap.clear", (e) => ({ ...r, nowMs: e }), { baseDir: t, assertCurrent: n }); } /** Revoke a bootstrap token unless its cloud-worker environment is already bound to the token's device. */ async function revokeDeviceBootstrapToken(e) { const { baseDir: t, ...n } = e; return await runBootstrapMutation("bootstrap.revoke", (e) => ({ ...n, nowMs: e }), { baseDir: t }); } /** Restore an uncorrelated bootstrap bearer after an undelivered credential response. */ async function restoreGenericDeviceBootstrapToken(e) { return await runBootstrapMutation("bootstrap.restore", (t) => ({ ...e, nowMs: t }), {}); } /** Record one role/scope leg of a multi-role bootstrap handoff. */ async function redeemDeviceBootstrapTokenProfile(e) { const { baseDir: t, ...n } = e; return await runBootstrapMutation("bootstrap.redeem", (e) => ({ ...n, nowMs: e }), { baseDir: t, onAuthorityRefused: () => ({ recorded: false, fullyRedeemed: false }), admit: (e) => { if (e.kind === "bootstrap.token") assertBootstrapTokenCurrent(e); } }); } /** Verify a bootstrap token, bind its first device identity, and stage requested scopes. */ async function verifyDeviceBootstrapToken(e) { const { baseDir: t, ...n } = e; return await runBootstrapMutation("bootstrap.verify", (e) => ({ ...n, nowMs: e }), { baseDir: t, onAuthorityRefused: () => ({ ok: false, reason: "bootstrap_token_invalid" }), admit: (e) => { if (e.kind === "bootstrap.token") assertBootstrapTokenCurrent(e); } }); } let setupExpiryObservation; registerOpenClawStateDatabaseLifecycleListener((e) => { if (e.kind !== "opened") setupExpiryObservation = void 0; }); onDevicePairSetupChange((e) => { if (setupExpiryObservation?.path === e) setupExpiryObservation.dirty = true; }); /** Remove retained setup outcomes independently of status requests or later pairings. */ async function pruneExpiredDevicePairSetupCompletions(e = {}) { return await withLock(async () => { const t = e.nowMs ?? Date.now(); const n = captureOpenClawStateWorkerContext(e.baseDir ? { env: { ...process.env, OPENCLAW_STATE_DIR: e.baseDir } } : {}); const r = n.admission.databasePath; const i = setupExpiryObservation?.path === r ? setupExpiryObservation : void 0; if (i && !i.dirty && (i.result.nextExpiryAtMs === null || t < i.result.nextExpiryAtMs)) return 0; const a = { path: r, dirty: false, result: { removed: 0, nextExpiryAtMs: null } }; setupExpiryObservation = a; try { const e = await executeDevicePairingMutation({ type: "bootstrap.prune", input: { nowMs: t } }, { context: n }); a.result = e; return e.removed; } catch (e) { a.dirty = true; throw e; } }); } /** Rebuild retained deadlines at startup, then wake only for setup writes or expiry. */ function startDevicePairSetupMaintenance(e) { const { scheduler: t } = e; if (t.signal.aborted) return; setupExpiryObservation = void 0; let n = false; const schedule = (e) => { if (!t.signal.aborted) t.schedule({ id: "maintenance:device-pair-setup", atMs: e, mode: "earliest", run }); }; const run = async () => { if (n) return; n = true; try { await pruneExpiredDevicePairSetupCompletions({ nowMs: t.now() }); const e = setupExpiryObservation; if (!e || e.dirty) schedule(t.now()); else if (e.result.nextExpiryAtMs !== null) schedule(e.result.nextExpiryAtMs); } catch (n) { e.onError(n); schedule(t.now() + 6e4); } finally { n = false; } }; const r = onDevicePairSetupChange(() => schedule(t.now())); const i = registerOpenClawStateDatabaseLifecycleListener((e) => { if (e.kind !== "opened") schedule(t.now()); }); t.signal.addEventListener("abort", () => { r(); i(); }, { once: true }); schedule(t.now()); } /** Read already-bound context only after verifying the same credential and identity. */ async function getBoundDeviceBootstrapContext(e) { const { baseDir: t, ...n } = e; return await withLock(() => loadBoundDeviceBootstrapContextReadOnly({ ...n, nowMs: Date.now() }, t)); } async function getBoundDeviceBootstrapProfile(e) { return (await getBoundDeviceBootstrapContext(e))?.profile ?? null; } //#endregion export { getBoundDeviceBootstrapContext as a, issueDevicePairSetupBootstrapToken as c, restoreGenericDeviceBootstrapToken as d, revokeDeviceBootstrapToken as f, ensureDevicePairSetupBootstrapToken as i, readDevicePairSetupCompletion as l, verifyDeviceBootstrapToken as m, confirmDevicePairSetupCompletionDelivery as n, getBoundDeviceBootstrapProfile as o, startDevicePairSetupMaintenance as p, consumeDeviceBootstrapTokenWithSetupCompletion as r, issueDeviceBootstrapToken as s, clearDeviceBootstrapTokens as t, redeemDeviceBootstrapTokenProfile as u };