openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
322 lines (321 loc) • 11.8 kB
JavaScript
import { o as asDateTimestampMs } from "./number-coercion-D6u-4YD8.mjs";
import { h as runSqliteReadOperationSync } from "./sqlite-schema-facts-B1bVE8IB.mjs";
import { c as normalizeEd25519PublicKeyBase64Url } from "./ed25519-signature-CUaH7IDK.mjs";
import { o as roleScopesAllow } from "./operator-scope-compat-CpFHu-FC.mjs";
import { c as deviceBootstrapProfilesEqual, f as normalizeDeviceBootstrapHandoffProfile, m as resolveBootstrapProfileScopesForRole, p as normalizeDeviceBootstrapProfile, r as CONTROL_UI_OWNER_BOOTSTRAP_PROFILE } from "./device-bootstrap-profile-COYynVlw.mjs";
import { A as withDevicePairingStoreDatabase, C as persistDeviceBootstrapTokenRecords, E as readDevicePairSetupCompletionExpiryInDatabase, F as requestDevicePairingMutationAdmission, I as withDevicePairingMutationAdmission, L as DEVICE_BOOTSTRAP_TOKEN_TTL_MS, P as hasCloudWorkerSetupDeviceBinding, R as resolveDeviceBootstrapTokenExpiresAtMs, T as pruneExpiredDevicePairSetupCompletionsInDatabase, b as loadDeviceBootstrapTokenRecords, v as confirmDevicePairSetupCompletionDeliveryInTransaction, x as loadDevicePairSetupCompletionRecord, y as consumeDeviceBootstrapTokenWithSetupCompletionInTransaction } from "./device-pairing-identity-BqPJxbIo.mjs";
import "./device-identity-JBn8J50B.mjs";
import { n as verifyPairingToken, t as generatePairingToken } from "./pairing-token-alWAf5pN.mjs";
import { t as devicePairingMutation } from "./device-pairing-dispatch.worker-C1IQyPuR.mjs";
//#region src/infra/device-bootstrap.worker-kernel.ts
const DEVICE_PAIR_SETUP_COMPLETION_RETENTION_MS = 2 * DEVICE_BOOTSTRAP_TOKEN_TTL_MS;
function resolvePersistedPendingProfile(e) {
return e.pendingProfile ? normalizeDeviceBootstrapProfile(e.pendingProfile) : null;
}
function resolveRequestedBootstrapProfile(e) {
return normalizeDeviceBootstrapProfile({
roles: [e.role],
scopes: resolveBootstrapProfileScopesForRole(e.role, e.scopes, e.purpose),
purpose: e.purpose
});
}
function bootstrapProfileAllowsRequest(e) {
return e.allowedProfile.roles.includes(e.requestedRole) && roleScopesAllow({
role: e.requestedRole,
requestedScopes: e.requestedScopes,
allowedScopes: e.allowedProfile.scopes
});
}
function bootstrapProfileSatisfiesProfile(e) {
return e.requiredProfile.roles.every((t) => bootstrapProfileAllowsRequest({
allowedProfile: e.actualProfile,
requestedRole: t,
requestedScopes: resolveBootstrapProfileScopesForRole(t, e.requiredProfile.scopes, e.requiredProfile.purpose)
}));
}
function normalizeBootstrapPublicKey(e) {
const t = e.trim();
if (!t) return "";
if (t.includes("BEGIN") || /[+/=]/.test(t)) return normalizeEd25519PublicKeyBase64Url(t) ?? t;
return t;
}
function loadState(e) {
const t = loadDeviceBootstrapTokenRecords();
const n = asDateTimestampMs(e) ?? 0;
for (const [e, r] of Object.entries(t)) if (n > resolveDeviceBootstrapTokenExpiresAtMs(r)) delete t[e];
return t;
}
function findBootstrapToken(e, t) {
return Object.entries(e).find(([, e]) => verifyPairingToken(t, e.token));
}
function issueDeviceBootstrapTokenRecord(e, t = loadState(e.nowMs)) {
const n = generatePairingToken();
const r = asDateTimestampMs(e.nowMs);
const i = r === void 0 ? void 0 : asDateTimestampMs(resolveDeviceBootstrapTokenExpiresAtMs({
...e,
issuedAtMs: r
}));
if (r === void 0 || i === void 0) throw new Error("Device bootstrap token expiry could not be resolved.");
t[n] = {
token: n,
...e.setupId ? { setupId: e.setupId } : {},
ts: r,
profile: e.profile,
redeemedProfile: normalizeDeviceBootstrapProfile(void 0),
issuedAtMs: r
};
persistDeviceBootstrapTokenRecords(t);
return {
token: n,
expiresAtMs: i
};
}
/** Reuse one environment-owned setup credential across provider replay. */
function ensureDevicePairSetupBootstrapToken(e) {
const t = e.setupId.trim();
if (!t) throw new Error("Device setup id must be non-empty.");
const n = loadDevicePairSetupCompletionRecord(t, e.nowMs);
if (n) return {
status: "completed",
setupId: t,
deviceId: n.deviceId
};
const r = loadState(e.nowMs);
const i = Object.values(r).find((e) => e.setupId === t);
const a = normalizeDeviceBootstrapHandoffProfile(e.profile);
if (i) {
if (!deviceBootstrapProfilesEqual(i.profile, a)) throw new Error("Device setup profile changed during replay.");
return {
status: "pending",
token: i.token,
expiresAtMs: resolveDeviceBootstrapTokenExpiresAtMs(i),
setupId: t
};
}
return {
status: "pending",
...issueDeviceBootstrapTokenRecord({
profile: a,
setupId: t,
nowMs: e.nowMs
}, r),
setupId: t
};
}
/**
* Record that credential delivery is not yet known. Only cloud-worker setup
* keeps its device-bound bearer until delivery is confirmed, allowing the same
* worker to retry when its credential-bearing response never arrives.
*/
function consumeDeviceBootstrapTokenWithSetupCompletion(e, t) {
const n = e.nowMs;
return consumeDeviceBootstrapTokenWithSetupCompletionInTransaction({
token: e.token,
deviceId: e.deviceId,
completedAtMs: e.completedAtMs,
recordWorkerEnvironment: t,
nowMs: n,
retentionNowMs: n,
retainUntilMs: n + DEVICE_PAIR_SETUP_COMPLETION_RETENTION_MS,
pairedDeviceMatches: (e, t) => {
requestDevicePairingMutationAdmission({
kind: "bootstrap.consume",
pairedDevice: e,
expiresAtMs: resolveDeviceBootstrapTokenExpiresAtMs(t)
});
return true;
}
});
}
function clearDeviceBootstrapTokens(e) {
const t = loadState(e.nowMs);
const n = Object.keys(t).length;
persistDeviceBootstrapTokenRecords({});
return { removed: n };
}
/** Preserve already-bound cloud-worker credentials for delivery retry. */
function revokeDeviceBootstrapToken(e, t) {
const n = e.token.trim();
if (!n) return { removed: false };
const r = loadState(e.nowMs);
const i = findBootstrapToken(r, n);
if (!i) return { removed: false };
const [a, o] = i;
if (o.setupId && o.profile?.purpose === "cloud-worker" && o.deviceId && hasCloudWorkerSetupDeviceBinding({
db: t.db,
setupId: o.setupId,
deviceId: o.deviceId
})) return { removed: false };
delete r[a];
persistDeviceBootstrapTokenRecords(r);
return {
removed: true,
record: o
};
}
/** Revoke bootstrap credentials inside the rejected request's pairing transaction. */
function revokeDeviceBootstrapTokensForDeviceInDatabase(e, t) {
withDevicePairingStoreDatabase(e, () => {
const e = t.deviceId.trim();
const n = normalizeBootstrapPublicKey(t.publicKey);
if (!e || !n) return;
const r = loadState(t.nowMs);
let i = false;
for (const [t, a] of Object.entries(r)) {
const o = typeof a.publicKey === "string" ? normalizeBootstrapPublicKey(a.publicKey) : void 0;
if (a.deviceId?.trim() === e && o === n) {
delete r[t];
i = true;
}
}
if (i) persistDeviceBootstrapTokenRecords(r);
});
}
/** Restore an uncorrelated bootstrap bearer when its credential response was not delivered. */
function restoreGenericDeviceBootstrapToken(e) {
if (e.record.setupId) return false;
const t = loadState(e.nowMs);
t[e.record.token] = e.record;
persistDeviceBootstrapTokenRecords(t);
return true;
}
/** Record that one role/scope leg of a multi-role bootstrap handoff was redeemed. */
function redeemDeviceBootstrapTokenProfile(e) {
const t = e.token.trim();
if (!t) return {
recorded: false,
fullyRedeemed: false
};
const n = loadState(e.nowMs);
const r = findBootstrapToken(n, t);
if (!r) return {
recorded: false,
fullyRedeemed: false
};
const [i, a] = r;
const o = normalizeDeviceBootstrapProfile(a.profile);
requestDevicePairingMutationAdmission({
kind: "bootstrap.token",
expiresAtMs: resolveDeviceBootstrapTokenExpiresAtMs(a)
});
const s = resolvePersistedPendingProfile(a);
const c = normalizeDeviceBootstrapProfile(a.redeemedProfile);
const l = normalizeDeviceBootstrapProfile({
roles: [...c.roles, e.role],
scopes: [...c.scopes, ...resolveBootstrapProfileScopesForRole(e.role, e.scopes, o.purpose)],
purpose: o.purpose
});
const u = s && !bootstrapProfileSatisfiesProfile({
actualProfile: l,
requiredProfile: s
}) ? s : void 0;
const d = {
...a,
profile: o,
redeemedProfile: l
};
if (u) d.pendingProfile = u;
else delete d.pendingProfile;
n[i] = d;
persistDeviceBootstrapTokenRecords(n);
return {
recorded: true,
fullyRedeemed: bootstrapProfileSatisfiesProfile({
actualProfile: l,
requiredProfile: o
})
};
}
/** Verify a bootstrap token, bind it to the first device identity, and stage requested scopes. */
function verifyDeviceBootstrapToken(e) {
const t = loadState(e.nowMs);
const n = e.token.trim();
if (!n) return {
ok: false,
reason: "bootstrap_token_invalid"
};
const r = findBootstrapToken(t, n);
if (!r) return {
ok: false,
reason: "bootstrap_token_invalid"
};
const [i, a] = r;
const o = e.deviceId.trim();
const s = normalizeBootstrapPublicKey(e.publicKey);
const c = e.role.trim();
if (!o || !s || !c) return {
ok: false,
reason: "bootstrap_token_invalid"
};
const l = normalizeDeviceBootstrapProfile(a.profile);
const u = resolveRequestedBootstrapProfile({
role: c,
scopes: e.scopes,
purpose: l.purpose
});
if (l.roles.length === 0 || deviceBootstrapProfilesEqual(l, CONTROL_UI_OWNER_BOOTSTRAP_PROFILE) && !deviceBootstrapProfilesEqual(u, CONTROL_UI_OWNER_BOOTSTRAP_PROFILE) || !bootstrapProfileAllowsRequest({
allowedProfile: l,
requestedRole: c,
requestedScopes: e.scopes
})) return {
ok: false,
reason: "bootstrap_token_invalid"
};
requestDevicePairingMutationAdmission({
kind: "bootstrap.token",
expiresAtMs: resolveDeviceBootstrapTokenExpiresAtMs(a)
});
const d = a.deviceId?.trim();
const f = typeof a.publicKey === "string" ? normalizeBootstrapPublicKey(a.publicKey) : void 0;
let p = u;
if (d || f) {
if (d !== o || f !== s) return {
ok: false,
reason: "bootstrap_token_invalid"
};
const e = resolvePersistedPendingProfile(a);
if (e && !deviceBootstrapProfilesEqual(e, u)) return {
ok: false,
reason: "bootstrap_token_invalid"
};
p = e ?? u;
}
t[i] = {
...a,
profile: l,
pendingProfile: p,
deviceId: o,
publicKey: s,
lastUsedAtMs: e.nowMs
};
persistDeviceBootstrapTokenRecords(t);
return { ok: true };
}
const deviceBootstrapOperations = {
"bootstrap.issue": devicePairingMutation((e) => issueDeviceBootstrapTokenRecord(e)),
"bootstrap.ensure": devicePairingMutation(ensureDevicePairSetupBootstrapToken),
"bootstrap.consume": devicePairingMutation((e, { recordWorkerEnvironment: t }) => consumeDeviceBootstrapTokenWithSetupCompletion(e, t)),
"bootstrap.confirm": devicePairingMutation((e) => confirmDevicePairSetupCompletionDeliveryInTransaction(e)),
"bootstrap.readCompletion": devicePairingMutation((e) => loadDevicePairSetupCompletionRecord(e.setupId, e.nowMs)),
"bootstrap.prune": (e, { open: t, write: n }) => {
const r = t();
const readExpiry = () => runSqliteReadOperationSync(r.db, () => readDevicePairSetupCompletionExpiryInDatabase(r.db));
let i = readExpiry();
let a = 0;
if (i !== void 0 && i <= e.nowMs) {
a = n(({ db: t }) => withDevicePairingMutationAdmission(() => pruneExpiredDevicePairSetupCompletionsInDatabase(t, e.nowMs)));
i = readExpiry();
}
return {
removed: a,
nextExpiryAtMs: i ?? null
};
},
"bootstrap.clear": devicePairingMutation(clearDeviceBootstrapTokens),
"bootstrap.revoke": devicePairingMutation((e, { database: t }) => revokeDeviceBootstrapToken(e, t)),
"bootstrap.restore": devicePairingMutation(restoreGenericDeviceBootstrapToken),
"bootstrap.redeem": devicePairingMutation(redeemDeviceBootstrapTokenProfile),
"bootstrap.verify": devicePairingMutation(verifyDeviceBootstrapToken)
};
//#endregion
export { revokeDeviceBootstrapTokensForDeviceInDatabase as n, deviceBootstrapOperations as t };