UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

799 lines (798 loc) • 34.4 kB
import { a as resolveGlobalSingleton } from "./global-singleton-D7yf05nR.mjs"; import { h as normalizeUniqueSingleOrTrimmedStringList } from "./string-normalization-DLmfYZXI.mjs"; import { j as readSqliteDatabaseWriteRevision } from "./sqlite-database-admission-DQIqro3d.mjs"; import { s as stageSqliteTransactionState } from "./sqlite-post-commit-BrUVQObC.mjs"; import { a as executeSqliteQueryTakeFirstSync, i as executeSqliteQuerySync, s as getNodeSqliteKysely } from "./kysely-sync-YJo2lmGV.mjs"; import { a as tableExists, o as tableHasColumn } from "./openclaw-state-db-schema-helpers-nImZNMq_.mjs"; import { o as runSqliteReadSnapshotSync } from "./sqlite-transaction-BHHu6P5-.mjs"; import { n as sha256Hex } from "./node-crypto-B6yuTjmm.mjs"; import { t as sha256Base64Url } from "./crypto-digest-B2m8wIBj.mjs"; import { f as requestSqliteWorkerOperationAdmission } from "./sqlite-worker-operation-admission-9E_X-oRy.mjs"; import { a as getSqliteWorkerStateContext } from "./sqlite-worker-state-context-CR8h__Vh.mjs"; import { l as runOpenClawStateWriteTransaction, r as openOpenClawStateDatabase } from "./openclaw-state-db-ARhwdPJg.mjs"; import { o as ensureDevicePairSetupBootstrapSchema, s as ensureDevicePairSetupCompletionSchema, y as ensureWorkerEnvironmentNodeEnrollmentSchema } from "./openclaw-state-db-schema-additive-BOxd1NE5.mjs"; import { o as roleScopesAllow } from "./operator-scope-compat-CpFHu-FC.mjs"; import { n as normalizeDeviceAuthScopes } from "./device-auth-Cu5vRDvP.mjs"; import { r as invalidateDevicePairingNodeSnapshot } from "./device-pairing-publication-PPGAGd4E.mjs"; import { v as resolvePairingSetupAccess } from "./device-bootstrap-profile-COYynVlw.mjs"; import { n as MAX_NODE_BOOTSTRAP_TIMEOUT_MS } from "./bootstrap-timeouts-H5rWuch_.mjs"; import { r as isNodeHostStats } from "./node-host-stats-vBi-GLvG.mjs"; import { i as pruneExpiredPending } from "./pairing-files-D32vzdZo.mjs"; import { AsyncLocalStorage } from "node:async_hooks"; //#region src/infra/device-bootstrap.worker-types.ts const DEVICE_BOOTSTRAP_TOKEN_TTL_MS = 6e5; function resolveDeviceBootstrapTokenExpiresAtMs(e) { const t = e.setupId && e.profile?.purpose === "cloud-worker" ? MAX_NODE_BOOTSTRAP_TIMEOUT_MS : DEVICE_BOOTSTRAP_TOKEN_TTL_MS; return e.issuedAtMs + t; } //#endregion //#region src/infra/device-pairing-mutation.worker.ts const admission = new AsyncLocalStorage(); /** Recheck live host custody while the authoritative SQLite rows remain locked. */ function requestDevicePairingMutationAdmission(e) { const t = admission.getStore(); if (!t) throw new Error("Pairing mutation requires its worker transaction"); const n = structuredClone(e); requestSqliteWorkerOperationAdmission({ stage: "transaction", facts: [n] }); t.push(n); } function withDevicePairingMutationAdmission(e) { return admission.run([], () => { requestSqliteWorkerOperationAdmission({ stage: "transaction", facts: [] }); const t = e(); requestSqliteWorkerOperationAdmission({ stage: "commit", facts: admission.getStore() }); return t; }); } //#endregion //#region src/infra/device-pairing-cloud-worker.ts function hasCloudWorkerSetupDeviceBinding(e) { const t = getNodeSqliteKysely(e.db); return executeSqliteQueryTakeFirstSync(e.db, t.selectFrom("worker_environments").select("node_device_id").where("node_setup_id", "=", e.setupId))?.node_device_id === e.deviceId; } /** Bind one environment-owned setup completion inside the pairing transaction. */ function bindCloudWorkerSetupCompletion(e) { ensureWorkerEnvironmentNodeEnrollmentSchema(e.db); const t = getNodeSqliteKysely(e.db); const n = executeSqliteQueryTakeFirstSync(e.db, t.selectFrom("worker_environments").select([ "environment_id", "state", "destroy_requested_at_ms", "node_device_id", "provision_operation_id", "owner_epoch", "updated_at_ms" ]).where("node_setup_id", "=", e.completion.setupId)); if (!n) throw new Error("Cloud worker setup completion has no owning environment"); const r = n.state === "provisioning" && n.node_device_id === null; const i = n.node_device_id === e.completion.deviceId && [ "provisioning", "bootstrapping", "ready", "idle", "attached" ].includes(n.state); if (n.destroy_requested_at_ms !== null || !r && !i) throw new Error("Cloud worker setup completion owner is no longer pending"); if (r) requestDevicePairingMutationAdmission({ kind: "bootstrap.cloudWorkerSetup", environmentId: n.environment_id, setupId: e.completion.setupId, credentialDigest: e.credentialDigest, provisionOperationId: n.provision_operation_id, ownerEpoch: n.owner_epoch }); executeSqliteQuerySync(e.db, t.updateTable("worker_environments").set({ node_device_id: e.completion.deviceId, updated_at_ms: Math.max(n.updated_at_ms, e.completion.completedAtMs) }).where("environment_id", "=", n.environment_id)); return { environmentId: n.environment_id, nodeDeviceId: e.completion.deviceId, updatedAtMs: Math.max(n.updated_at_ms, e.completion.completedAtMs) }; } //#endregion //#region src/infra/device-pairing-row-mapping.ts const APPROVAL_KINDS = new Set(Object.keys({ owner: true, silent: true, "trusted-cidr": true, "trusted-proxy": true, "remote-ingress": true, "ssh-verified": true, bootstrap: true })); function toJsonColumn(e) { return e === void 0 ? null : JSON.stringify(e); } function fromJsonColumn(e) { return e === null ? void 0 : JSON.parse(e); } function toBooleanColumn(e) { return e === void 0 ? null : e ? 1 : 0; } function optional(e, t) { return t === null ? {} : { [e]: t }; } function toPendingRow(e) { return { request_id: e.requestId, device_id: e.deviceId, public_key: e.publicKey, display_name: e.displayName ?? null, platform: e.platform ?? null, device_family: e.deviceFamily ?? null, client_id: e.clientId ?? null, client_mode: e.clientMode ?? null, browser_origin: e.browserOrigin ?? null, role: e.role ?? null, roles_json: toJsonColumn(e.roles), scopes_json: toJsonColumn(e.scopes), remote_ip: e.remoteIp ?? null, silent: toBooleanColumn(e.silent), is_repair: toBooleanColumn(e.isRepair), ts: e.ts, refreshed_at_ms: e.refreshedAtMs ?? null }; } function fromPendingRow(e) { return { requestId: e.request_id, deviceId: e.device_id, publicKey: e.public_key, ...optional("displayName", e.display_name), ...optional("platform", e.platform), ...optional("deviceFamily", e.device_family), ...optional("clientId", e.client_id), ...optional("clientMode", e.client_mode), ...optional("browserOrigin", e.browser_origin), ...optional("role", e.role), ...optional("roles", fromJsonColumn(e.roles_json) ?? null), ...optional("scopes", fromJsonColumn(e.scopes_json) ?? null), ...optional("remoteIp", e.remote_ip), ...optional("silent", e.silent === null ? null : e.silent !== 0), ...optional("isRepair", e.is_repair === null ? null : e.is_repair !== 0), ts: e.ts, ...optional("refreshedAtMs", e.refreshed_at_ms) }; } function toPairedRow(e) { return { device_id: e.deviceId, public_key: e.publicKey, display_name: e.displayName ?? null, operator_label: e.operatorLabel ?? null, platform: e.platform ?? null, device_family: e.deviceFamily ?? null, client_id: e.clientId ?? null, client_mode: e.clientMode ?? null, browser_origin: e.browserOrigin ?? null, role: e.role ?? null, roles_json: toJsonColumn(e.roles), scopes_json: toJsonColumn(e.scopes), approved_scopes_json: toJsonColumn(e.approvedScopes), remote_ip: e.remoteIp ?? null, tokens_json: toJsonColumn(e.tokens), approved_via: e.approvedVia ?? null, node_surface_json: toJsonColumn(e.nodeSurface), pending_node_surface_json: toJsonColumn(e.pendingNodeSurface), created_at_ms: e.createdAtMs, approved_at_ms: e.approvedAtMs, last_seen_at_ms: e.lastSeenAtMs ?? null, last_seen_reason: e.lastSeenReason ?? null }; } function fromApprovedViaColumn(e) { return e !== null && APPROVAL_KINDS.has(e) ? e : null; } const PAIRING_SETUP_ACCESS_VALUES = new Set(Object.keys({ full: true, limited: true, node: true })); function fromSetupCompletionAccessColumn(e) { return PAIRING_SETUP_ACCESS_VALUES.has(e) ? e : "limited"; } function fromSetupCompletionDeliveryStateColumn(e) { return e === "confirmed" ? "confirmed" : "uncertain"; } function fromSetupCompletionRow(e) { return { setupId: e.setup_id, deviceId: e.device_id, ...optional("deviceName", e.device_name), access: fromSetupCompletionAccessColumn(e.access), completedAtMs: e.completed_at_ms, deliveryState: fromSetupCompletionDeliveryStateColumn(e.delivery_state), retainUntilMs: e.retain_until_ms }; } function fromPairedRow(e) { const t = fromJsonColumn(e.node_surface_json); if (t?.lastHostStats !== void 0 && !isNodeHostStats(t.lastHostStats)) delete t.lastHostStats; return { deviceId: e.device_id, publicKey: e.public_key, ...optional("displayName", e.display_name), ...optional("operatorLabel", e.operator_label), ...optional("platform", e.platform), ...optional("deviceFamily", e.device_family), ...optional("clientId", e.client_id), ...optional("clientMode", e.client_mode), ...optional("browserOrigin", e.browser_origin), ...optional("role", e.role), ...optional("roles", fromJsonColumn(e.roles_json) ?? null), ...optional("scopes", fromJsonColumn(e.scopes_json) ?? null), ...optional("approvedScopes", fromJsonColumn(e.approved_scopes_json) ?? null), ...optional("remoteIp", e.remote_ip), ...optional("tokens", fromJsonColumn(e.tokens_json) ?? null), ...optional("approvedVia", fromApprovedViaColumn(e.approved_via)), ...optional("nodeSurface", t ?? null), ...optional("pendingNodeSurface", fromJsonColumn(e.pending_node_surface_json) ?? null), createdAtMs: e.created_at_ms, approvedAtMs: e.approved_at_ms, ...optional("lastSeenAtMs", e.last_seen_at_ms), ...optional("lastSeenReason", e.last_seen_reason) }; } function toBootstrapRow(e, t) { return { token_key: e, token: t.token, setup_id: t.setupId ?? null, ts: t.ts, device_id: t.deviceId ?? null, public_key: t.publicKey ?? null, profile_json: toJsonColumn(t.profile), redeemed_profile_json: toJsonColumn(t.redeemedProfile), pending_profile_json: toJsonColumn(t.pendingProfile), issued_at_ms: t.issuedAtMs, last_used_at_ms: t.lastUsedAtMs ?? null }; } function fromBootstrapRow(e) { return { token: e.token, ...optional("setupId", e.setup_id), ts: e.ts, ...optional("deviceId", e.device_id), ...optional("publicKey", e.public_key), ...optional("profile", fromJsonColumn(e.profile_json) ?? null), ...optional("redeemedProfile", fromJsonColumn(e.redeemed_profile_json) ?? null), ...optional("pendingProfile", fromJsonColumn(e.pending_profile_json) ?? null), issuedAtMs: e.issued_at_ms, ...optional("lastUsedAtMs", e.last_used_at_ms) }; } //#endregion //#region src/infra/device-pairing-store-cache.ts const cache = resolveGlobalSingleton(Symbol.for("openclaw.devicePairingStoreCache"), () => ({ value: void 0 })); function invalidateDevicePairingStoreCache(e) { if (cache.value?.connection === e.db && cache.value.path === e.path) cache.value = void 0; } /** Borrowed worker facts; projections must not mutate this revision's cached rows. */ function readCachedDevicePairingStoreSnapshot(e, t, n, r) { if (e.isTransaction) return n(); const i = readSqliteDatabaseWriteRevision(e); const a = cache.value; if (i !== void 0 && a?.connection === e && a.path === t && a.writeRevision === i && (a.deviceId === void 0 || a.deviceId === r)) return a; const o = r === void 0 ? runSqliteReadSnapshotSync(e, n, { operationLabel: "devicePairing.snapshot" }) : n(); if (i !== void 0) cache.value = { connection: e, path: t, ...o, writeRevision: i, deviceId: r }; return o; } //#endregion //#region src/infra/push-apns-store-transaction.ts /** Advances a registration/tombstone version without reusing an observed owner version. */ function nextApnsRegistrationVersion(e, t, n = Date.now()) { let r = -1; for (const n of t) { if (!Number.isSafeInteger(n) || n < 0) throw new Error(`invalid APNs registration version for node ${e}`); r = Math.max(r, n); } if (r === Number.MAX_SAFE_INTEGER) throw new Error(`APNs registration version exhausted for node ${e}`); return Math.max(n, r + 1); } /** Read both owner versions from the caller's transaction before advancing either one. */ function readApnsRegistrationVersions(e, t) { const n = getNodeSqliteKysely(e); const r = executeSqliteQueryTakeFirstSync(e, n.selectFrom("apns_registrations").select("updated_at_ms").where("node_id", "=", t)); const i = executeSqliteQueryTakeFirstSync(e, n.selectFrom("apns_registration_tombstones").select("deleted_at_ms").where("node_id", "=", t)); return [r?.updated_at_ms, i?.deleted_at_ms].filter((e) => e !== void 0); } /** Tombstones and deletes one APNs owner inside the caller's shared-state transaction. */ function clearApnsRegistrationFromDatabase(e, t, n = Date.now()) { const r = t.trim(); if (!r) return false; const i = getNodeSqliteKysely(e); const a = executeSqliteQueryTakeFirstSync(e, i.deleteFrom("apns_registrations").where("node_id", "=", r).returning("updated_at_ms")); const o = executeSqliteQueryTakeFirstSync(e, i.selectFrom("apns_registration_tombstones").select("deleted_at_ms").where("node_id", "=", r)); const s = nextApnsRegistrationVersion(r, [a?.updated_at_ms, o?.deleted_at_ms].filter((e) => e !== void 0), n); executeSqliteQuerySync(e, i.insertInto("apns_registration_tombstones").values({ node_id: r, deleted_at_ms: s }).onConflict((e) => e.column("node_id").doUpdateSet({ deleted_at_ms: s }))); return a !== void 0; } //#endregion //#region src/infra/device-pairing-store.ts const DEVICE_BOOTSTRAP_TOKEN_COLUMNS_WITHOUT_SETUP = [ "device_id", "issued_at_ms", "last_used_at_ms", "pending_profile_json", "profile_json", "public_key", "redeemed_profile_json", "token", "token_key", "ts" ]; const boundDatabase = new AsyncLocalStorage(); /** Keep nested domain kernels on the broker's admitted physical connection. */ function withDevicePairingStoreDatabase(e, t, n, r) { return boundDatabase.run({ database: e, paired: n, revision: r }, t); } function transactionPairedRecords(e) { const t = boundDatabase.getStore(); return t?.database.db === e ? t.paired : void 0; } /** Route an explicit pairing base dir (tests, alternate state roots) to that dir's DB. */ function resolveDevicePairingStateDbOptions(e) { const t = boundDatabase.getStore()?.database; if (t) return { database: t, path: t.path, env: getSqliteWorkerStateContext().environment }; return e ? { env: { ...process.env, OPENCLAW_STATE_DIR: e } } : {}; } function runDevicePairingStoreMutation(e, t) { const n = boundDatabase.getStore(); const apply = (e) => { const r = t(e); if (r.pairedChanged) { const t = bumpDevicePairingStoreRevision(e.db); if (n?.revision) n.revision.value = t; } if (r.mutated) stageSqliteTransactionState(e.db, { commit: () => { invalidateDevicePairingStoreCache(e); invalidateDevicePairingNodeSnapshot(e.path); } }); return r.value; }; if (n) return apply(n.database); const r = resolveDevicePairingStateDbOptions(e); const i = openOpenClawStateDatabase(r); return runOpenClawStateWriteTransaction(apply, { ...r, database: i }); } function readDevicePairingStoreStateFromDatabase(e) { return { pendingById: readDevicePairingPendingRecordsFromDatabase(e), pairedByDeviceId: readPairedDevicePairingRecordsFromDatabase(e) }; } function readDevicePairingPendingRecordsFromDatabase(e) { const t = getNodeSqliteKysely(e); const n = {}; for (const r of executeSqliteQuerySync(e, t.selectFrom("device_pairing_pending").selectAll()).rows) n[r.request_id] = fromPendingRow(r); return n; } const DEVICE_PAIRING_REVISION_KEY = "devicePairing.revision"; function devicePairingRevisionQuery(e) { return getNodeSqliteKysely(e).selectFrom("config_machine_state").select("value_json").where("state_key", "=", DEVICE_PAIRING_REVISION_KEY); } /** The pairing owner advances this row atomically with its paired-device writes. */ function bumpDevicePairingStoreRevision(e) { const t = getNodeSqliteKysely(e); return executeSqliteQuerySync(e, t.insertInto("config_machine_state").values({ state_key: DEVICE_PAIRING_REVISION_KEY, value_json: "1", updated_at_ms: Date.now() }).onConflict((e) => e.column("state_key").doUpdateSet((e) => ({ value_json: e.cast(e(e.cast("config_machine_state.value_json", "bigint"), "+", e.lit(1)), "text"), updated_at_ms: e.ref("excluded.updated_at_ms") }))).returning("value_json")).rows[0].value_json; } /** One statement keeps the selected rows and their revision in the same snapshot. */ function readPairedDevicePairingSnapshotFromDatabase(e, t) { const n = getNodeSqliteKysely(e); const r = n.selectNoFrom((t) => t.fn.coalesce(devicePairingRevisionQuery(e), t.val("0")).as("pairing_revision")).as("revision"); const i = n.selectFrom(r).leftJoin("device_pairing_paired as paired", (e) => t === void 0 ? e.onTrue() : e.on("paired.device_id", "=", t)).selectAll("paired").select("revision.pairing_revision"); const a = executeSqliteQuerySync(e, i).rows; const o = a.filter((e) => e.device_id !== null); return { pairedByDeviceId: Object.fromEntries(o.map((e) => [e.device_id, fromPairedRow(e)])), revision: a[0].pairing_revision }; } function readDevicePairingStoreSnapshotFromDatabase(e, t) { const { pairedByDeviceId: n, revision: r } = readPairedDevicePairingSnapshotFromDatabase(e, t); return { state: { pairedByDeviceId: n, pendingById: t === void 0 ? readDevicePairingPendingRecordsFromDatabase(e) : {} }, revision: r }; } function readPairedDevicePairingRecordsFromDatabase(e) { const t = transactionPairedRecords(e); if (t) return structuredClone(t); const n = getNodeSqliteKysely(e); return Object.fromEntries(executeSqliteQuerySync(e, n.selectFrom("device_pairing_paired").selectAll()).rows.map((e) => [e.device_id, fromPairedRow(e)])); } function loadDevicePairingStoreState(e) { const t = openOpenClawStateDatabase(resolveDevicePairingStateDbOptions(e)); return structuredClone(t.db.isTransaction ? readDevicePairingStoreStateFromDatabase(t.db) : readCachedDevicePairingStoreSnapshot(t.db, t.path, () => readDevicePairingStoreSnapshotFromDatabase(t.db)).state); } /** Load one paired-device row from an existing shared-state transaction. */ function loadPairedDevicePairingStoreRecordFromDatabase(e, t) { const n = t.trim(); if (!n) return null; const r = transactionPairedRecords(e); if (r) return Object.hasOwn(r, n) ? structuredClone(r[n]) : null; const i = getNodeSqliteKysely(e); const a = executeSqliteQueryTakeFirstSync(e, i.selectFrom("device_pairing_paired").selectAll().where("device_id", "=", n)); return a ? fromPairedRow(a) : null; } /** Read and patch one device under the worker's transaction and commit admission. */ function updatePairedDeviceInTransaction(e, t) { return runDevicePairingStoreMutation(void 0, ({ db: n }) => { const r = e.trim(); const i = loadPairedDevicePairingStoreRecordFromDatabase(n, r); const a = transactionPairedRecords(n); const o = a?.[r]; const s = t(i); const c = s.patch; if (!c || Object.keys(c).length === 0) return { mutated: false, value: s.value }; if (!i) throw new Error("cannot update a missing paired device"); const l = getNodeSqliteKysely(n); const u = { ..."displayName" in c ? { display_name: c.displayName ?? null } : {}, ..."operatorLabel" in c ? { operator_label: c.operatorLabel ?? null } : {}, ..."platform" in c ? { platform: c.platform ?? null } : {}, ..."clientId" in c ? { client_id: c.clientId ?? null } : {}, ..."clientMode" in c ? { client_mode: c.clientMode ?? null } : {}, ..."remoteIp" in c ? { remote_ip: c.remoteIp ?? null } : {}, ..."lastSeenAtMs" in c ? { last_seen_at_ms: c.lastSeenAtMs ?? null } : {}, ..."lastSeenReason" in c ? { last_seen_reason: c.lastSeenReason ?? null } : {}, ..."tokens" in c ? { tokens_json: toJsonColumn(c.tokens) } : {}, ..."nodeSurface" in c ? { node_surface_json: toJsonColumn(c.nodeSurface) } : {} }; executeSqliteQuerySync(n, l.updateTable("device_pairing_paired").set(u).where("device_id", "=", r)); if (a && o) a[r] = fromPairedRow({ ...toPairedRow(o), ...u }); return { mutated: true, pairedChanged: true, value: s.value }; }); } /** Replace the pending and/or paired table contents with the given snapshot. */ function persistDevicePairingStoreState(e, t, n, r) { runDevicePairingStoreMutation(t, ({ db: t }) => { const i = getNodeSqliteKysely(t); const a = n !== "pending" ? Object.values(e.pairedByDeviceId).map(toPairedRow) : void 0; if (n !== "paired") { executeSqliteQuerySync(t, i.deleteFrom("device_pairing_pending")); const n = Object.values(e.pendingById).map(toPendingRow); if (n.length > 0) executeSqliteQuerySync(t, i.insertInto("device_pairing_pending").values(n)); } if (a) { executeSqliteQuerySync(t, i.deleteFrom("device_pairing_paired")); if (a.length > 0) executeSqliteQuerySync(t, i.insertInto("device_pairing_paired").values(a)); } for (const e of new Set(r?.clearApnsNodeIds ?? [])) clearApnsRegistrationFromDatabase(t, e); const o = transactionPairedRecords(t); if (o && a) { for (const e of Object.keys(o)) delete o[e]; for (const e of a) Object.defineProperty(o, e.device_id, { value: fromPairedRow(e), configurable: true, enumerable: true, writable: true }); } return { mutated: true, pairedChanged: n !== "pending", value: void 0 }; }); } function loadDeviceBootstrapTokenRecords(e) { const { db: t } = openOpenClawStateDatabase(resolveDevicePairingStateDbOptions(e)); return readDeviceBootstrapTokenRecordsFromDatabase(t); } function readDeviceBootstrapTokenRecordsFromDatabase(e) { const t = getNodeSqliteKysely(e); const n = {}; const r = tableHasColumn(e, "device_bootstrap_tokens", "setup_id") ? executeSqliteQuerySync(e, t.selectFrom("device_bootstrap_tokens").selectAll()).rows : executeSqliteQuerySync(e, t.selectFrom("device_bootstrap_tokens").select(DEVICE_BOOTSTRAP_TOKEN_COLUMNS_WITHOUT_SETUP)).rows.map((e) => Object.assign(e, { setup_id: null })); for (const e of r) n[e.token_key] = fromBootstrapRow(e); return n; } /** Replace the bootstrap token table contents with the given snapshot. */ function persistDeviceBootstrapTokenRecords(e, t) { runOpenClawStateWriteTransaction(({ db: t }) => { const n = Object.entries(e).map(([e, t]) => toBootstrapRow(e, t)); if (n.some((e) => e.setup_id !== null)) ensureDevicePairSetupBootstrapSchema(t); const r = getNodeSqliteKysely(t); executeSqliteQuerySync(t, r.deleteFrom("device_bootstrap_tokens")); if (n.length > 0) { if (tableHasColumn(t, "device_bootstrap_tokens", "setup_id")) executeSqliteQuerySync(t, r.insertInto("device_bootstrap_tokens").values(n)); else { const e = n.map(({ setup_id: e, ...t }) => t); executeSqliteQuerySync(t, r.insertInto("device_bootstrap_tokens").values(e)); } } }, resolveDevicePairingStateDbOptions(t)); } /** Consume one bound bootstrap credential and record its setup outcome atomically. */ function consumeDeviceBootstrapTokenWithSetupCompletionInTransaction(e) { const t = e.token.trim(); const n = e.deviceId.trim(); if (!t || !n) return null; return runOpenClawStateWriteTransaction(({ db: r }) => { ensureDevicePairSetupBootstrapSchema(r); ensureDevicePairSetupCompletionSchema(r); const i = getNodeSqliteKysely(r); const a = executeSqliteQueryTakeFirstSync(r, i.selectFrom("device_bootstrap_tokens").selectAll().where("token_key", "=", t)); if (!a || a.token !== t || a.device_id?.trim() !== n) return null; const o = fromBootstrapRow(a); if (e.nowMs > resolveDeviceBootstrapTokenExpiresAtMs(o)) return null; const s = o.setupId || e.pairedDeviceMatches ? loadPairedDevicePairingStoreRecordFromDatabase(r, n) : null; if (e.pairedDeviceMatches && !e.pairedDeviceMatches(s, o)) return null; const c = s?.operatorLabel ?? s?.displayName; const l = o.setupId ? { setupId: o.setupId, deviceId: n, ...c ? { deviceName: c } : {}, access: resolvePairingSetupAccess(o.profile), completedAtMs: e.completedAtMs, deliveryState: "uncertain", retainUntilMs: e.retainUntilMs } : void 0; if (!l || o.profile?.purpose !== "cloud-worker") executeSqliteQuerySync(r, i.deleteFrom("device_bootstrap_tokens").where("token_key", "=", a.token_key)); if (l) { if (o.profile?.purpose === "cloud-worker") e.recordWorkerEnvironment(bindCloudWorkerSetupCompletion({ db: r, completion: l, credentialDigest: sha256Base64Url(a.token) })); executeSqliteQuerySync(r, i.deleteFrom("device_pair_setup_completions").where((t) => t.or([t("retain_until_ms", "<=", e.retentionNowMs), t("setup_id", "=", l.setupId)]))); executeSqliteQuerySync(r, i.insertInto("device_pair_setup_completions").values({ setup_id: l.setupId, device_id: l.deviceId, device_name: l.deviceName ?? null, access: l.access, completed_at_ms: l.completedAtMs, delivery_state: l.deliveryState, retain_until_ms: l.retainUntilMs })); } return { record: o, ...l ? { completion: l } : {} }; }, resolveDevicePairingStateDbOptions()); } /** Mark one consumed setup handoff as delivered without reviving an expired or replaced row. */ function confirmDevicePairSetupCompletionDeliveryInTransaction(e) { const t = e.setupId.trim(); const n = e.deviceId.trim(); if (!t || !n) return null; return runOpenClawStateWriteTransaction(({ db: r }) => { ensureDevicePairSetupCompletionSchema(r); const i = getNodeSqliteKysely(r); const a = executeSqliteQueryTakeFirstSync(r, i.updateTable("device_pair_setup_completions").set({ delivery_state: "confirmed" }).where("setup_id", "=", t).where("device_id", "=", n).where("retain_until_ms", ">", e.nowMs).returningAll()); if (!a) return null; executeSqliteQuerySync(r, i.deleteFrom("device_bootstrap_tokens").where("setup_id", "=", t).where("device_id", "=", n)); return fromSetupCompletionRow(a); }, resolveDevicePairingStateDbOptions()); } /** The host retains this deadline until a shared-state writer receipt changes. */ function readDevicePairSetupCompletionExpiryInDatabase(e) { if (!tableExists(e, "device_pair_setup_completions")) return; return executeSqliteQueryTakeFirstSync(e, getNodeSqliteKysely(e).selectFrom("device_pair_setup_completions").select("retain_until_ms").orderBy("retain_until_ms", "asc").limit(1))?.retain_until_ms; } /** The maintenance command owns the write transaction and its live admission. */ function pruneExpiredDevicePairSetupCompletionsInDatabase(e, t) { if (!tableExists(e, "device_pair_setup_completions")) return 0; const n = executeSqliteQuerySync(e, getNodeSqliteKysely(e).deleteFrom("device_pair_setup_completions").where("retain_until_ms", "<=", t)); return Number(n.numAffectedRows ?? 0); } /** Prune elapsed setup completions, then read one live record. */ function loadDevicePairSetupCompletionRecord(e, t, n) { const r = resolveDevicePairingStateDbOptions(n); const i = openOpenClawStateDatabase(r); ensureDevicePairSetupCompletionSchema(i.db); return runOpenClawStateWriteTransaction(({ db: n }) => { const r = getNodeSqliteKysely(n); executeSqliteQuerySync(n, r.deleteFrom("device_pair_setup_completions").where("retain_until_ms", "<=", t)); const i = executeSqliteQueryTakeFirstSync(n, r.selectFrom("device_pair_setup_completions").selectAll().where("setup_id", "=", e)); return i ? fromSetupCompletionRow(i) : null; }, { ...r, database: i }); } //#endregion //#region src/infra/device-pairing-state.kernel.ts const DEVICE_PAIRING_PENDING_TTL_MS = 3e5; /** Read authoritative rows inside the worker transaction or an admitted migration. */ function loadDevicePairingStateForMutation(e, t) { const n = loadDevicePairingStoreState(t); pruneExpiredPending(n.pendingById, e, DEVICE_PAIRING_PENDING_TTL_MS); return n; } function resolvePairingRequestExpiry(e) { return e + DEVICE_PAIRING_PENDING_TTL_MS; } function normalizeDevicePairingRole(e) { const t = e?.trim(); return t ? t : null; } /** Merge pairing roles while preserving first-seen order. */ function mergeDevicePairingRoles(...e) { const t = [...new Set(e.flatMap(normalizeUniqueSingleOrTrimmedStringList))]; return t.length > 0 ? t : void 0; } /** Merge pairing scopes while preserving first-seen order and explicit emptiness. */ function mergeDevicePairingScopes(...e) { const t = e.filter((e) => Array.isArray(e)); return t.length > 0 ? [...new Set(t.flatMap(normalizeUniqueSingleOrTrimmedStringList))] : void 0; } /** Preserve only approval scopes owned by one pairing role. */ function preserveDeviceRoleScopes(e, t) { return normalizeUniqueSingleOrTrimmedStringList(t).filter((t) => e === "operator" ? t.startsWith("operator.") : !t.startsWith("operator.")); } function sameDevicePairingStringSet(e, t) { if (e.length !== t.length) return false; const n = new Set(t); return e.every((e) => n.has(e)); } function resolveRequestedDeviceRoles(e) { return mergeDevicePairingRoles(e.roles, e.role) ?? []; } //#endregion //#region src/infra/device-pairing-identity.ts /** Use the same persisted approval ceiling for token verification and retained authority. */ function resolveApprovedDeviceScopeBaseline(e) { const t = e.approvedScopes ?? e.scopes; return Array.isArray(t) ? normalizeDeviceAuthScopes(t) : null; } /** Pin the credential actually accepted or issued, never a successor found on a later read. */ function resolveAuthenticatedDeviceTokenIdentity(e, t) { if (!e || e.publicKey !== t.publicKey || e.tokens?.[t.role]?.token !== t.token) return null; const n = resolvePairedDeviceTokenIdentity(e, t.role, t.scopes); return n ? Object.freeze(n) : null; } function listActiveTokenRoles(e) { if (!e) return; return mergeDevicePairingRoles(Object.values(e).filter((e) => !e.revokedAtMs).map((e) => e.role)); } /** List the durable roles an owner approved for a paired device record. */ function listApprovedPairedDeviceRoles(e) { return mergeDevicePairingRoles(e.roles, e.role) ?? []; } /** List active-token roles, bounded by the durable approved pairing roles. */ function listEffectivePairedDeviceRoles(e) { const t = listActiveTokenRoles(e.tokens); if (t && t.length > 0) { const n = new Set(listApprovedPairedDeviceRoles(e)); return t.filter((e) => n.has(e)); } return []; } /** Return whether a paired device currently has an active token for one role. */ function hasEffectivePairedDeviceRole(e, t) { const n = normalizeDevicePairingRole(t); if (!n) return false; return listEffectivePairedDeviceRoles(e).includes(n); } /** Resolve one exact active role-token generation without exposing its credential. */ function resolvePairedDeviceTokenIdentity(e, t, n) { const r = normalizeDevicePairingRole(t); if (!e || !r || !hasEffectivePairedDeviceRole(e, r)) return null; const i = e.tokens?.[r]; if (!i || i.role !== r || i.revokedAtMs) return null; if (n) { const t = resolveApprovedDeviceScopeBaseline(e); if (t === null || !roleScopesAllow({ role: r, requestedScopes: i.scopes, allowedScopes: t }) || !roleScopesAllow({ role: r, requestedScopes: n, allowedScopes: i.scopes })) return null; } const a = sha256Hex([ e.publicKey, e.createdAtMs, i.token, i.createdAtMs, i.rotatedAtMs ?? "", i.revokedAtMs ?? "" ].join("\0")); return { deviceId: e.deviceId, key: a }; } /** Re-admission retains the original token generation and current approved scope ceiling. */ function isPairedDeviceTokenIdentityCurrent(e, t, n, r) { const i = resolvePairedDeviceTokenIdentity(e, t, r); return i !== null && i.deviceId === n.deviceId && i.key === n.key; } /** Resolve the durable node-owned identity used to admit asynchronous work. */ function resolveNodePairingGeneration(e) { if (!e || !hasEffectivePairedDeviceRole(e, "node") || !e.nodeSurface) return null; const t = e.tokens?.node; const n = e.nodeSurface; const r = sha256Hex([ e.publicKey, e.createdAtMs, t?.token ?? "", t?.revokedAtMs ?? "", n.createdAtMs, n.approvedAtMs ].join("\0")); return { nodeId: e.deviceId, key: r }; } /** Clear node runtime facts when their owning pairing generation changes. */ function clearNodePairingGenerationState(e, t) { const n = resolveNodePairingGeneration(e); if (t?.key === n?.key || !e.nodeSurface) return; delete e.nodeSurface.bins; delete e.nodeSurface.sessionHost; } /** Resolve connection identity and optional approved surface generation from one row. */ function resolveNodePairingState(e) { const t = resolvePairedDeviceTokenIdentity(e, "node"); if (!t) return null; return { identity: { nodeId: t.deviceId, key: t.key }, generation: resolveNodePairingGeneration(e) }; } //#endregion export { withDevicePairingStoreDatabase as A, persistDeviceBootstrapTokenRecords as C, readDevicePairingStoreStateFromDatabase as D, readDevicePairSetupCompletionExpiryInDatabase as E, requestDevicePairingMutationAdmission as F, withDevicePairingMutationAdmission as I, DEVICE_BOOTSTRAP_TOKEN_TTL_MS as L, nextApnsRegistrationVersion as M, readApnsRegistrationVersions as N, readPairedDevicePairingSnapshotFromDatabase as O, hasCloudWorkerSetupDeviceBinding as P, resolveDeviceBootstrapTokenExpiresAtMs as R, loadPairedDevicePairingStoreRecordFromDatabase as S, pruneExpiredDevicePairSetupCompletionsInDatabase as T, sameDevicePairingStringSet as _, listEffectivePairedDeviceRoles as a, loadDeviceBootstrapTokenRecords as b, resolveNodePairingGeneration as c, mergeDevicePairingRoles as d, mergeDevicePairingScopes as f, resolveRequestedDeviceRoles as g, resolvePairingRequestExpiry as h, listApprovedPairedDeviceRoles as i, clearApnsRegistrationFromDatabase as j, updatePairedDeviceInTransaction as k, resolveNodePairingState as l, preserveDeviceRoleScopes as m, hasEffectivePairedDeviceRole as n, resolveApprovedDeviceScopeBaseline as o, normalizeDevicePairingRole as p, isPairedDeviceTokenIdentityCurrent as r, resolveAuthenticatedDeviceTokenIdentity as s, clearNodePairingGenerationState as t, loadDevicePairingStateForMutation as u, confirmDevicePairSetupCompletionDeliveryInTransaction as v, persistDevicePairingStoreState as w, loadDevicePairSetupCompletionRecord as x, consumeDeviceBootstrapTokenWithSetupCompletionInTransaction as y };