openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
744 lines (743 loc) • 26.3 kB
JavaScript
import { t as deferSqlitePostCommitPublication } from "./sqlite-post-commit-BrUVQObC.mjs";
import { a as executeSqliteQueryTakeFirstSync, i as executeSqliteQuerySync, s as getNodeSqliteKysely } from "./kysely-sync-YJo2lmGV.mjs";
import { c as ensureDevicePairingJoinCodeSchema } from "./openclaw-state-db-schema-additive-BOxd1NE5.mjs";
import { a as resolveScopeOutsideRequestedRoles, i as resolveMissingRequestedScope, o as roleScopesAllow } from "./operator-scope-compat-CpFHu-FC.mjs";
import { n as normalizeDeviceAuthScopes } from "./device-auth-Cu5vRDvP.mjs";
import { _ as resolveDeviceProfileScopes, g as resolveDeviceProfileRoleScopes } from "./device-bootstrap-profile-COYynVlw.mjs";
import { F as requestDevicePairingMutationAdmission, _ as sameDevicePairingStringSet, c as resolveNodePairingGeneration, d as mergeDevicePairingRoles, f as mergeDevicePairingScopes, g as resolveRequestedDeviceRoles, h as resolvePairingRequestExpiry, i as listApprovedPairedDeviceRoles, k as updatePairedDeviceInTransaction, m as preserveDeviceRoleScopes, o as resolveApprovedDeviceScopeBaseline, p as normalizeDevicePairingRole, t as clearNodePairingGenerationState, u as loadDevicePairingStateForMutation, w as persistDevicePairingStoreState } from "./device-pairing-identity-BqPJxbIo.mjs";
import { n as scopesWithinApprovedDeviceBaseline, r as verifyPairedDeviceToken, t as reusablePairedDeviceToken } from "./device-pairing-token-policy-BQS0XwDZ.mjs";
import { n as resolveRoleTokenScopes, t as createDeviceAuthToken } from "./device-pairing-token-utils-fd1VQ1i6.mjs";
import { t as devicePairingMutation } from "./device-pairing-dispatch.worker-C1IQyPuR.mjs";
import { n as revokeDeviceBootstrapTokensForDeviceInDatabase } from "./device-bootstrap.worker-kernel-B1165il8.mjs";
import { randomUUID } from "node:crypto";
//#region src/infra/device-pairing-approval.kernel.ts
const OPERATOR_ROLE = "operator";
const OPERATOR_SCOPE_PREFIX = "operator.";
function mergeApprovalKind(e, t) {
if (t === "owner" || !e) return t;
if (e.approvedVia === void 0) return t === "bootstrap" ? "bootstrap" : void 0;
if (e.approvedVia === "owner" || e.approvedVia === "bootstrap") return e.approvedVia;
return t;
}
function mergeApprovalRoles(e, t) {
return mergeDevicePairingRoles(e?.roles, e?.role, t.roles, t.role);
}
function buildApprovedPairedDevice(e) {
return {
deviceId: e.pending.deviceId,
publicKey: e.pending.publicKey,
displayName: e.accessMetadata?.displayName ?? e.pending.displayName,
platform: e.pending.platform,
deviceFamily: e.pending.deviceFamily,
clientId: e.pending.clientId,
clientMode: e.pending.clientMode,
browserOrigin: e.pending.browserOrigin,
role: e.pending.role,
roles: e.roles,
scopes: e.approvedScopes,
approvedScopes: e.approvedScopes,
remoteIp: e.accessMetadata?.remoteIp ?? e.pending.remoteIp,
tokens: e.tokens,
approvedVia: mergeApprovalKind(e.existing, e.approvedVia),
...e.existing?.nodeSurface ? { nodeSurface: e.existing.nodeSurface } : {},
...e.existing?.pendingNodeSurface ? { pendingNodeSurface: e.existing.pendingNodeSurface } : {},
...e.existing?.operatorLabel ? { operatorLabel: e.existing.operatorLabel } : {},
createdAtMs: e.existing?.createdAtMs ?? e.now,
approvedAtMs: e.now,
lastSeenAtMs: e.accessMetadata?.lastSeenAtMs ?? e.existing?.lastSeenAtMs,
lastSeenReason: e.accessMetadata?.lastSeenReason ?? e.existing?.lastSeenReason
};
}
function commitApprovedDevicePairing(e) {
const { state: t, requestId: n, device: r } = e;
const i = t.pairedByDeviceId[r.deviceId];
const a = resolveNodePairingGeneration(i ?? null);
const o = resolveNodePairingGeneration(r);
const s = Boolean(a && a.key !== o?.key);
clearNodePairingGenerationState(r, a);
const c = Boolean(i && i.publicKey !== r.publicKey);
delete t.pendingById[n];
t.pairedByDeviceId[r.deviceId] = r;
persistDevicePairingStoreState(t, void 0, "both", c ? { clearApnsNodeIds: [r.deviceId] } : void 0);
return {
status: "approved",
requestId: n,
device: r,
...s ? { nodePairingGenerationChanged: true } : {}
};
}
function resolveApprovedTokenScopes(e) {
const t = resolveRoleTokenScopes(e.role, e.pending.scopes);
if (t.length > 0) {
const n = e.existingToken?.revokedAtMs ? void 0 : e.existingToken;
const r = resolveRoleTokenScopes(e.role, e.existing?.approvedScopes ?? e.existing?.scopes);
const i = n && r.length > 0 ? t.filter((e) => !r.includes(e)) : t;
if (i.length === 0 && n) return resolveRoleTokenScopes(e.role, n.scopes);
return resolveRoleTokenScopes(e.role, mergeDevicePairingScopes(n?.scopes, i));
}
return resolveRoleTokenScopes(e.role, e.existingToken?.scopes ?? e.approvedScopes ?? e.existing?.approvedScopes ?? e.existing?.scopes);
}
function withPendingDevicePairingApproval(e, t, n) {
const r = loadDevicePairingStateForMutation(t);
const i = r.pendingById[e];
if (!i) return null;
const a = r.pairedByDeviceId[i.deviceId];
requestDevicePairingMutationAdmission({
kind: "pairing-approval",
pending: i,
existing: a
});
return n(r, i, a);
}
/** Approve an authoritative pending row inside the admitted pairing transaction. */
function approveDevicePairingInWorker(e, t, n) {
return withPendingDevicePairingApproval(e, n, (r, i, a) => {
const o = t?.autoApproveNewDeviceScopes;
const s = resolveRequestedDeviceRoles(i);
const c = (t?.approvedVia === "trusted-proxy" || t?.approvedVia === "remote-ingress") && a !== void 0 && a.publicKey === i.publicKey;
if (o && ((i.isRepair || a) && !c || !sameDevicePairingStringSet(s, [OPERATOR_ROLE]))) return null;
const l = o ? {
...i,
scopes: [...o]
} : i;
const u = normalizeDeviceAuthScopes(l.scopes);
const d = resolveScopeOutsideRequestedRoles({
requestedRoles: s,
requestedScopes: u
});
if (d) return {
status: "forbidden",
reason: "scope-outside-requested-roles",
scope: d
};
const f = n;
const p = mergeApprovalRoles(a, l);
const m = mergeDevicePairingScopes(a?.approvedScopes ?? a?.scopes, l.scopes);
const h = a?.tokens ? { ...a.tokens } : {};
const g = /* @__PURE__ */ new Map();
for (const e of s) {
const n = h[e];
const r = resolveApprovedTokenScopes({
role: e,
pending: l,
existingToken: n,
approvedScopes: m,
existing: a
});
g.set(e, r);
if (e === OPERATOR_ROLE && r.length > 0) {
const n = mergeDevicePairingScopes(resolveRoleTokenScopes(e, l.scopes), r) ?? r;
if (!t?.callerScopes) return {
status: "forbidden",
reason: "caller-scopes-required",
scope: n[0]
};
const i = resolveMissingRequestedScope({
role: OPERATOR_ROLE,
requestedScopes: n,
allowedScopes: t.callerScopes
});
if (i) return {
status: "forbidden",
reason: "caller-missing-scope",
scope: i
};
}
}
for (const [e, t] of g) {
const r = h[e];
const i = n;
h[e] = createDeviceAuthToken({
role: e,
scopes: t,
existing: r,
preserveExistingIssuer: true,
now: i,
rotatedAtMs: r ? i : void 0
});
}
return commitApprovedDevicePairing({
state: r,
requestId: e,
device: buildApprovedPairedDevice({
pending: l,
existing: a,
roles: p,
approvedScopes: m,
tokens: h,
now: f,
approvedVia: t?.approvedVia ?? "owner",
accessMetadata: t?.accessMetadata
})
});
});
}
/** Approve one bounded bootstrap grant inside the admitted pairing transaction. */
function approveBootstrapDevicePairingInWorker(e, t, n, r) {
let i = [];
const a = mergeDevicePairingRoles(t.roles) ?? [];
const o = resolveDeviceProfileScopes(t, a);
return {
result: withPendingDevicePairingApproval(e, r, (s, c, l) => {
const u = resolveRequestedDeviceRoles(c);
const d = u.find((e) => !a.includes(e));
if (d) return {
status: "forbidden",
reason: "bootstrap-role-not-allowed",
role: d
};
const f = normalizeDeviceAuthScopes(c.scopes).filter((e) => e.startsWith(OPERATOR_SCOPE_PREFIX));
const p = resolveMissingRequestedScope({
role: OPERATOR_ROLE,
requestedScopes: f,
allowedScopes: o
});
if (p) return {
status: "forbidden",
reason: "bootstrap-scope-not-allowed",
scope: p
};
const m = r;
const h = u;
const g = resolveDeviceProfileScopes(t, h, c.scopes ?? []);
const _ = new Set(h);
const v = (mergeDevicePairingRoles(l?.roles, l?.role) ?? []).flatMap((e) => _.has(e) ? [] : preserveDeviceRoleScopes(e, l?.approvedScopes ?? l?.scopes));
const y = mergeApprovalRoles(l, c);
const b = mergeDevicePairingScopes(v, g);
const x = l?.tokens ? { ...l.tokens } : {};
for (const e of h) {
const n = x[e];
const r = e === OPERATOR_ROLE ? resolveDeviceProfileRoleScopes(t, e, g) : [];
x[e] = createDeviceAuthToken({
role: e,
scopes: r,
existing: n,
now: m,
...n ? { rotatedAtMs: m } : {}
});
}
const S = commitApprovedDevicePairing({
state: s,
requestId: e,
device: buildApprovedPairedDevice({
pending: c,
existing: l,
roles: y,
approvedScopes: b,
tokens: x,
now: m,
approvedVia: "bootstrap",
accessMetadata: n?.accessMetadata
})
});
i = h.filter((e) => l?.tokens?.[e]);
return S;
}),
replacedRoles: i
};
}
//#endregion
//#region src/infra/device-pairing-core.kernel.ts
function canRefreshPendingDevicePairingRequest(e, t) {
if (e.publicKey !== t.publicKey) return false;
if (e.browserOrigin !== t.browserOrigin) return false;
if (normalizeDevicePairingRole(e.role) !== normalizeDevicePairingRole(t.role)) return false;
const n = resolveRequestedDeviceRoles(t);
const r = resolveRequestedDeviceRoles(e);
const i = normalizeDeviceAuthScopes(t.scopes);
const a = normalizeDeviceAuthScopes(e.scopes);
if (sameDevicePairingStringSet(r, n) && sameDevicePairingStringSet(a, i)) return true;
const o = new Set(r);
if (!n.every((e) => o.has(e))) return false;
return i.every((e) => n.some((t) => roleScopesAllow({
role: t,
requestedScopes: [e],
allowedScopes: a
})));
}
function refreshPendingDevicePairingRequest(e, t, n, r) {
return {
...e,
publicKey: t.publicKey,
displayName: t.displayName ?? e.displayName,
platform: t.platform ?? e.platform,
deviceFamily: t.deviceFamily ?? e.deviceFamily,
clientId: t.clientId ?? e.clientId,
clientMode: t.clientMode ?? e.clientMode,
browserOrigin: e.browserOrigin,
remoteIp: t.remoteIp ?? e.remoteIp,
silent: Boolean(e.silent && t.silent),
isRepair: e.isRepair || n,
ts: e.ts,
refreshedAtMs: r
};
}
function toPublicPendingDevicePairingRequest(e) {
const { refreshedAtMs: t, ...n } = e;
return n;
}
/** Create or refresh a pending device pairing request for owner approval. */
function requestDevicePairingInWorker(e, t) {
const n = loadDevicePairingStateForMutation(t);
const r = e.deviceId.trim();
if (!r) throw new Error("deviceId required");
const i = Boolean(n.pairedByDeviceId[r]);
const a = Object.values(n.pendingById).filter((e) => e.deviceId === r).toSorted((e, t) => t.ts - e.ts);
const o = a[0];
let s;
let c = false;
if (a.length === 1 && o && canRefreshPendingDevicePairingRequest(o, e)) s = refreshPendingDevicePairingRequest(o, e, i, t);
else {
for (const e of a) delete n.pendingById[e.requestId];
const l = normalizeDevicePairingRole(e.role) ?? normalizeDevicePairingRole(o?.role) ?? void 0;
s = {
requestId: randomUUID(),
deviceId: r,
publicKey: e.publicKey,
displayName: e.displayName,
platform: e.platform,
deviceFamily: e.deviceFamily,
clientId: e.clientId,
clientMode: e.clientMode,
browserOrigin: e.browserOrigin,
role: l,
roles: mergeDevicePairingRoles(...a.flatMap((e) => [e.roles, e.role]), e.roles, e.role, l),
scopes: mergeDevicePairingScopes(...a.map((e) => e.scopes), e.scopes),
remoteIp: e.remoteIp,
silent: Boolean(e.silent && a.every((e) => e.silent === true)),
isRepair: i,
ts: t
};
c = true;
}
n.pendingById[s.requestId] = s;
persistDevicePairingStoreState(n, void 0, "pending");
const l = c ? a.filter((e) => e.requestId !== s.requestId).map((e) => ({
requestId: e.requestId,
deviceId: e.deviceId
})) : [];
return {
status: "pending",
request: toPublicPendingDevicePairingRequest(s),
created: c,
expiresAtMs: resolvePairingRequestExpiry(s.refreshedAtMs ?? s.ts),
...l.length > 0 ? { superseded: l } : {}
};
}
/** Reject a pending request and revoke matching bootstrap tokens for that device. */
function rejectDevicePairingInWorker(e, t, n) {
const r = loadDevicePairingStateForMutation(n);
const i = r.pendingById[t];
if (!i) return null;
delete r.pendingById[t];
persistDevicePairingStoreState(r, void 0, "pending");
revokeDeviceBootstrapTokensForDeviceInDatabase(e, {
deviceId: i.deviceId,
publicKey: i.publicKey,
nowMs: n
});
return {
requestId: t,
deviceId: i.deviceId
};
}
/** Remove a paired device and any pending repair requests for the same device id. */
function removePairedDeviceRecord(e, t) {
delete e.pairedByDeviceId[t];
for (const [n, r] of Object.entries(e.pendingById)) if (r.deviceId === t) delete e.pendingById[n];
}
function removePairedDeviceInWorker(e, t) {
const n = loadDevicePairingStateForMutation(t);
const r = e.trim();
if (!r || !n.pairedByDeviceId[r]) return null;
removePairedDeviceRecord(n, r);
persistDevicePairingStoreState(n, void 0, "both", { clearApnsNodeIds: [r] });
return { deviceId: r };
}
function silentPairingClusterKey(e) {
const t = e.clientId?.trim().toLowerCase() ?? "";
const n = e.clientMode?.trim().toLowerCase() ?? "";
const r = e.displayName?.trim().toLowerCase() ?? "";
if (!t && !n && !r) return null;
return `${t}\0${n}\0${r}`;
}
const PRUNE_RECENT_APPROVAL_GRACE_MS = 6e4;
/**
* Remove silent-approved sibling records superseded by a newly approved silent
* pairing of the same client cluster. Only records whose latest approval was
* same-host local ("silent") are eligible, as anchor and as victim: local
* clients re-pair silently by construction and share the gateway host, so the
* metadata cluster key cannot match a different machine. Currently connected
* devices are skipped so concurrent sessions with distinct state dirs keep
* their tokens while live.
*/
function pruneSupersededSilentPairedDevicesInWorker(e) {
const t = loadDevicePairingStateForMutation(e.nowMs);
const n = t.pairedByDeviceId[e.deviceId.trim()];
if (!n || n.approvedVia !== "silent") return [];
const r = silentPairingClusterKey(n);
if (!r) return [];
const i = e.nowMs;
const a = new Set(e.protectedDeviceIds);
const o = [];
for (const e of Object.values(t.pairedByDeviceId)) {
if (e.deviceId === n.deviceId) continue;
if (e.approvedVia !== "silent") continue;
if (silentPairingClusterKey(e) !== r) continue;
if (i - e.approvedAtMs < PRUNE_RECENT_APPROVAL_GRACE_MS) continue;
if (a.has(e.deviceId)) continue;
removePairedDeviceRecord(t, e.deviceId);
o.push({
deviceId: e.deviceId,
roles: listApprovedPairedDeviceRoles(e)
});
}
if (o.length === 0) return [];
requestDevicePairingMutationAdmission({
kind: "pairing-prune",
deviceIds: o.map((e) => e.deviceId)
});
persistDevicePairingStoreState(t, void 0, "both", { clearApnsNodeIds: o.map((e) => e.deviceId) });
return o;
}
/** Remove one approved paired-device role while preserving unrelated role tokens. */
function removePairedDeviceRoleInWorker(e) {
const t = loadDevicePairingStateForMutation(e.nowMs);
const n = e.deviceId.trim();
const r = normalizeDevicePairingRole(e.role);
const i = t.pairedByDeviceId[n];
if (!i || !r || !listApprovedPairedDeviceRoles(i).includes(r)) return null;
const a = { ...i.tokens };
delete a[r];
const o = listApprovedPairedDeviceRoles(i).filter((e) => e !== r);
if (o.length === 0) {
removePairedDeviceRecord(t, n);
persistDevicePairingStoreState(t, void 0, "both", { clearApnsNodeIds: [n] });
return {
deviceId: n,
role: r,
removedDevice: true
};
}
for (const [e, i] of Object.entries(t.pendingById)) {
if (i.deviceId !== n) continue;
const a = resolveRequestedDeviceRoles(i);
if (!a.includes(r)) continue;
const o = a.filter((e) => e !== r);
if (o.length === 0) {
delete t.pendingById[e];
continue;
}
const s = Array.isArray(i.scopes) ? mergeDevicePairingScopes(...o.map((e) => preserveDeviceRoleScopes(e, i.scopes))) : void 0;
t.pendingById[e] = {
...i,
role: o[0],
roles: o,
scopes: s
};
}
const s = i.approvedScopes ?? i.scopes;
const c = Array.isArray(s) ? mergeDevicePairingScopes(...o.map((e) => preserveDeviceRoleScopes(e, s))) : void 0;
const l = {
...i,
role: o[0],
roles: o,
...c !== void 0 ? {
scopes: c,
approvedScopes: c
} : {},
tokens: Object.keys(a).length > 0 ? a : void 0
};
if (r === "node") {
delete l.nodeSurface;
delete l.pendingNodeSurface;
}
t.pairedByDeviceId[n] = l;
persistDevicePairingStoreState(t, void 0, "both");
return {
deviceId: n,
role: r,
removedDevice: false
};
}
/** Update non-auth metadata for a paired device presence/status refresh. */
function updatePairedDeviceMetadataInWorker(e, t, n) {
return updatePairedDeviceInTransaction(e, (e) => {
if (!e || n && (e.publicKey !== n.publicKey || e.approvedAtMs !== n.approvedAtMs)) return { value: false };
const r = {};
for (const e of [
"displayName",
"operatorLabel",
"platform",
"clientId",
"clientMode",
"remoteIp",
"lastSeenAtMs",
"lastSeenReason"
]) if (e in t) Object.assign(r, { [e]: t[e] });
return {
value: true,
patch: r
};
});
}
/** Update paired-device presence only while the authenticated node generation still owns it. */
function updatePairedDevicePresenceInWorker(e, t, n) {
return updatePairedDeviceInTransaction(e, (e) => {
const r = resolveNodePairingGeneration(e);
if (!e || n.nodeId !== e.deviceId || r?.key !== n.key) return { value: false };
return {
value: true,
patch: {
lastSeenAtMs: t.lastSeenAtMs,
lastSeenReason: t.lastSeenReason
}
};
});
}
//#endregion
//#region src/infra/device-pairing-join-code.worker.ts
const initializedDatabases = /* @__PURE__ */ new WeakSet();
function joinCodeDatabase(e) {
if (!initializedDatabases.has(e)) {
ensureDevicePairingJoinCodeSchema(e);
deferSqlitePostCommitPublication(e, () => initializedDatabases.add(e));
}
return getNodeSqliteKysely(e);
}
function registerDevicePairingJoinCodeInWorker(e, t) {
const n = joinCodeDatabase(e);
executeSqliteQuerySync(e, n.deleteFrom("device_pairing_join_codes").where("expires_at_ms", "<=", t.createdAtMs));
executeSqliteQuerySync(e, n.insertInto("device_pairing_join_codes").values({
shortcode: t.shortcode,
payload_json: t.payloadJson,
created_at_ms: t.createdAtMs,
expires_at_ms: t.expiresAtMs
}));
}
function redeemDevicePairingJoinCodeInWorker(e, t) {
const n = Date.now();
const r = joinCodeDatabase(e);
executeSqliteQuerySync(e, r.deleteFrom("device_pairing_join_codes").where("expires_at_ms", "<=", n));
const i = executeSqliteQueryTakeFirstSync(e, r.deleteFrom("device_pairing_join_codes").where("shortcode", "=", t.shortcode).returning(["payload_json", "expires_at_ms"]));
if (!i || typeof i.payload_json !== "string" || typeof i.expires_at_ms !== "number") return;
return {
payload_json: i.payload_json,
expires_at_ms: i.expires_at_ms
};
}
//#endregion
//#region src/infra/device-pairing-tokens.kernel.ts
/** Record use only if the current token still authorizes the request. */
function verifyDeviceTokenInWorker(e) {
return updatePairedDeviceInTransaction(e.deviceId, (t) => {
const n = verifyPairedDeviceToken(t, e);
if (!n.ok || !t) return { value: n };
const r = e.role.trim();
const i = t.tokens[r];
return {
value: n,
patch: {
tokens: {
...t.tokens,
[r]: {
...i,
lastUsedAtMs: e.nowMs
}
},
lastSeenAtMs: e.nowMs,
lastSeenReason: "device-token-auth"
}
};
});
}
/** Return a reusable token for a role or issue one within the approved scope baseline. */
function ensureDeviceTokenInWorker(e) {
return updatePairedDeviceInTransaction(e.deviceId, (t) => {
requestDevicePairingMutationAdmission({ kind: "pairing-token-issuance" });
const n = normalizeDeviceAuthScopes(e.scopes);
const r = resolveDeviceTokenUpdateContext({
device: t,
role: e.role
});
if (!r) return { value: null };
const { device: i, role: a, tokens: o, existing: s } = r;
const c = resolveNodePairingGeneration(i);
const l = resolveApprovedDeviceScopeBaseline(i);
if (!scopesWithinApprovedDeviceBaseline({
role: a,
scopes: n,
approvedScopes: l
})) return { value: null };
const u = reusablePairedDeviceToken(i, e);
if (u) return { value: u };
const d = e.nowMs;
const f = createDeviceAuthToken({
role: a,
scopes: n,
issuer: e.issuer,
existing: s,
now: d,
rotatedAtMs: s ? d : void 0
});
o[a] = f;
i.tokens = o;
clearNodePairingGenerationState(i, c);
return {
value: f,
patch: {
tokens: o,
nodeSurface: i.nodeSurface
}
};
});
}
function resolveDeviceTokenUpdateContext(e) {
const t = e.device;
if (!t) return null;
const n = normalizeDevicePairingRole(e.role);
if (!n) return null;
if (!listApprovedPairedDeviceRoles(t).includes(n)) return null;
const r = { ...t.tokens };
return {
device: t,
role: n,
tokens: r,
existing: r[n]
};
}
/** Rotate a role token inside the device's approved scope baseline. */
function rotateDeviceTokenInWorker(e, t) {
const n = loadDevicePairingStateForMutation(e.nowMs);
const r = resolveDeviceTokenUpdateContext({
device: n.pairedByDeviceId[e.deviceId.trim()] ?? null,
role: e.role
});
if (!r) return {
ok: false,
reason: "unknown-device-or-role"
};
const { device: i, role: a, tokens: o, existing: s } = r;
const c = resolveNodePairingGeneration(i);
const l = normalizeDeviceAuthScopes(e.scopes ?? s?.scopes ?? i.scopes);
const u = resolveApprovedDeviceScopeBaseline(i);
if (!u) return {
ok: false,
reason: "missing-approved-scope-baseline"
};
if (!scopesWithinApprovedDeviceBaseline({
role: a,
scopes: l,
approvedScopes: u
})) return {
ok: false,
reason: "scope-outside-approved-baseline"
};
if (e.callerScopes) {
const t = resolveMissingRequestedScope({
role: a,
requestedScopes: l,
allowedScopes: e.callerScopes
});
if (t) return {
ok: false,
reason: "caller-missing-scope",
scope: t
};
}
const d = e.nowMs;
const f = createDeviceAuthToken({
role: a,
scopes: l,
existing: s,
preserveExistingIssuer: true,
now: d,
rotatedAtMs: d
});
o[a] = f;
i.tokens = o;
clearNodePairingGenerationState(i, c);
n.pairedByDeviceId[i.deviceId] = i;
const p = a === "node" && e.scopes !== void 0 && l.length === 0 && s && !scopesWithinApprovedDeviceBaseline({
role: a,
scopes: s.scopes,
approvedScopes: u
}) ? {
deviceId: i.deviceId,
expectedToken: s.token
} : void 0;
persistDevicePairingStoreState(n, void 0, "paired");
if (p) t?.(p);
return {
ok: true,
entry: f
};
}
/** Revoke one active role token after optional caller-scope authorization. */
function revokeDeviceTokenInWorker(e) {
const t = loadDevicePairingStateForMutation(e.nowMs);
const n = resolveDeviceTokenUpdateContext({
device: t.pairedByDeviceId[e.deviceId.trim()] ?? null,
role: e.role
});
if (!n || !n.existing) return {
ok: false,
reason: "unknown-device-or-role"
};
const { device: r, role: i, tokens: a, existing: o } = n;
const s = resolveNodePairingGeneration(r);
const c = normalizeDeviceAuthScopes(Array.isArray(o.scopes) ? o.scopes : r.scopes);
if (e.callerScopes) {
const t = resolveMissingRequestedScope({
role: i,
requestedScopes: c,
allowedScopes: e.callerScopes
});
if (t) return {
ok: false,
reason: "caller-missing-scope",
scope: t
};
}
const l = {
...o,
revokedAtMs: e.nowMs
};
a[i] = l;
r.tokens = a;
clearNodePairingGenerationState(r, s);
t.pairedByDeviceId[r.deviceId] = r;
persistDevicePairingStoreState(t, void 0, "paired");
return {
ok: true,
entry: l
};
}
//#endregion
//#region src/infra/device-pairing-core.worker.ts
const devicePairingOperations = {
"devicePairing.registerJoinCode": devicePairingMutation((e, { database: t }) => registerDevicePairingJoinCodeInWorker(t.db, e), { publishPairing: false }),
"devicePairing.redeemJoinCode": devicePairingMutation((e, { database: t }) => redeemDevicePairingJoinCodeInWorker(t.db, e), { publishPairing: false }),
"devicePairing.request": devicePairingMutation((e) => requestDevicePairingInWorker(e.request, e.nowMs)),
"devicePairing.reject": devicePairingMutation((e, { database: t }) => rejectDevicePairingInWorker(t, e.requestId, e.nowMs)),
"devicePairing.remove": devicePairingMutation((e) => removePairedDeviceInWorker(e.deviceId, e.nowMs)),
"devicePairing.pruneSilent": devicePairingMutation(pruneSupersededSilentPairedDevicesInWorker),
"devicePairing.removeRole": devicePairingMutation(removePairedDeviceRoleInWorker),
"devicePairing.updateMetadata": devicePairingMutation((e) => updatePairedDeviceMetadataInWorker(e.deviceId, e.patch, e.accessIdentity), { pairedDeviceId: (e) => e.deviceId }),
"devicePairing.updatePresence": devicePairingMutation((e) => updatePairedDevicePresenceInWorker(e.deviceId, e.patch, e.expectedPairingGeneration), { pairedDeviceId: (e) => e.deviceId }),
"devicePairing.approve": devicePairingMutation((e) => approveDevicePairingInWorker(e.requestId, e.options, e.nowMs)),
"devicePairing.approveBootstrap": devicePairingMutation((e, { recordTokenReplacement: t }) => {
const n = approveBootstrapDevicePairingInWorker(e.requestId, e.bootstrapProfile, { accessMetadata: e.accessMetadata }, e.nowMs);
if (n.result?.status === "approved" && n.replacedRoles.length > 0) t({
deviceId: n.result.device.deviceId,
roles: n.replacedRoles
});
return n;
}),
"devicePairing.verifyToken": devicePairingMutation(verifyDeviceTokenInWorker, { pairedDeviceId: (e) => e.deviceId }),
"devicePairing.ensureToken": devicePairingMutation(ensureDeviceTokenInWorker, { pairedDeviceId: (e) => e.deviceId }),
"devicePairing.rotateToken": devicePairingMutation((e, { recordRetiredNodeToken: t }) => rotateDeviceTokenInWorker(e, t)),
"devicePairing.revokeToken": devicePairingMutation(revokeDeviceTokenInWorker)
};
//#endregion
export { devicePairingOperations };