UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

7 lines • 15.9 kB
import{l as isRecord}from"./record-coerce-BTbqdJ3-.mjs";import{r as truncateUtf16Safe}from"./utf16-slice-DA3Mllbx.mjs";import{c as redactSensitiveText}from"./redact-BT59pdZ_.mjs";import{t as createSubsystemLogger}from"./subsystem-DLCDFvCH.mjs";import{randomUUID}from"node:crypto";import{isProxy}from"node:util/types";import{Value}from"typebox/value";import{Type}from"typebox"; //!src/audit/execution-identity-ordering.ts function sortUniqueExecutionIdentityEntries(e,t){return[...new Map(e.map(e=>[t(e),e])).values()].toSorted((e,n)=>{const r=t(e);const i=t(n);return r<i?-1:r>i?1:0})} //!src/audit/execution-identity-spawn-admission.ts const EXECUTION_IDENTITY_SPAWN_ADMISSION_FACTS=Symbol(`executionIdentitySpawnAdmissionFacts`);function ownDataDescriptor(e,t){const n=Object.getOwnPropertyDescriptor(e,t);if(!n)return;if(!n.enumerable||!(`value`in n))throw new Error(`execution identity spawn admission carrier is invalid`);return n}function copyBaseFacts(e){const t=Object.getPrototypeOf(e);if(t!==Object.prototype&&t!==null)throw new Error(`execution identity spawn admission carrier is invalid`);const n=Object.getOwnPropertyDescriptors(e);for(const e of Reflect.ownKeys(n)){const t=n[e];if(!t||!t.enumerable||!(`value`in t)||typeof e!==`string`&&(e!==EXECUTION_IDENTITY_SPAWN_ADMISSION_FACTS||typeof t.value!==`string`))throw new Error(`execution identity spawn admission carrier is invalid`);if(typeof e!==`string`)delete n[e]}return Object.create(null,n)}function validRef(e,t){return typeof e===`string`&&e.length>=1&&e.length<=t}function validateEnvelopeExtension(e,t){if(!Array.isArray(t)||t.length>16||!t.every(e=>validRef(e,256)))throw new Error(`execution identity spawn missing-evidence facts are invalid`);if(e===void 0||e===null)return{missingEvidence:t};if(!isRecord(e)||e.parentContextId!==void 0&&!validRef(e.parentContextId,256)||e.parentExecutionId!==void 0&&!validRef(e.parentExecutionId,256)||e.parentRunId!==void 0&&!validRef(e.parentRunId,256)||!validRef(e.parentAgentId,256)||e.relation!==`sessions_spawn`||!validRef(e.rawRequesterRef,4096)||!validRef(e.rawControllerRef,4096)||!Number.isSafeInteger(e.depth)||typeof e.depth!==`number`||e.depth<1||e.depth>64||!Array.isArray(e.localPolicyRefs)||e.localPolicyRefs.length>16||!e.localPolicyRefs.every(e=>validRef(e,4096))||!Array.isArray(e.targetPolicyRefs)||e.targetPolicyRefs.length>16||!e.targetPolicyRefs.every(e=>validRef(e,4096)))throw new Error(`execution identity spawn lineage facts are invalid`);return{lineage:{...e.parentContextId!==void 0?{parentContextId:e.parentContextId}:{},...e.parentExecutionId!==void 0?{parentExecutionId:e.parentExecutionId}:{},...e.parentRunId!==void 0?{parentRunId:e.parentRunId}:{},parentAgentId:e.parentAgentId,relation:e.relation,rawRequesterRef:e.rawRequesterRef,rawControllerRef:e.rawControllerRef,depth:e.depth,localPolicyRefs:e.localPolicyRefs,targetPolicyRefs:e.targetPolicyRefs},missingEvidence:t}}function uniqueSorted(e){return[...new Set(e)].toSorted()}function executionIdentitySpawnAdmission(e){const{operation:t,value:n}=e;if(t===`serialize`){const t=validateEnvelopeExtension(n,e.extra);return JSON.stringify([t.lineage??null,t.missingEvidence])}if(t===`parse`){if(typeof n!==`string`)throw new Error(`execution identity spawn admission facts are invalid`);const e=JSON.parse(n);if(!Array.isArray(e)||e.length!==2)throw new Error(`execution identity spawn admission facts are invalid`);const t=validateEnvelopeExtension(e[0],e[1]);return[t.lineage,t.missingEvidence]}if(!isRecord(n))throw new Error(`execution identity spawn admission carrier is invalid`);if(t===`attach`){if(typeof e.extra!==`string`)return n;const t=Object.create(Object.getPrototypeOf(n),Object.getOwnPropertyDescriptors(n));Object.defineProperty(t,EXECUTION_IDENTITY_SPAWN_ADMISSION_FACTS,{configurable:true,enumerable:true,value:e.extra,writable:true});return t}if(t===`base-facts`)return copyBaseFacts(n);if(t===`extend-envelope`){const[t,r]=executionIdentitySpawnAdmission({operation:`parse`,value:typeof e.extra===`string`?e.extra:JSON.stringify([null,[]])});const i=t?{...t,localPolicyRefs:uniqueSorted(t.localPolicyRefs),targetPolicyRefs:uniqueSorted(t.targetPolicyRefs)}:void 0;return{...n,...i?{lineage:i}:{},missingEvidence:uniqueSorted(r)}}if(t===`base-envelope`){const e=copyBaseFacts(n);const{lineage:t,missingEvidence:r}=e;validateEnvelopeExtension(t,r);delete e.lineage;delete e.missingEvidence;return e}const r=ownDataDescriptor(n,EXECUTION_IDENTITY_SPAWN_ADMISSION_FACTS)?.value;if(r!==void 0){if(typeof r!==`string`)throw new Error(`execution identity spawn admission carrier is invalid`);return r}const i=ownDataDescriptor(n,`missingEvidence`)?.value;if(!Array.isArray(i))return;const a=ownDataDescriptor(n,`lineage`)?.value;const o=validateEnvelopeExtension(a,i);return JSON.stringify([o.lineage??null,o.missingEvidence])} //!src/audit/execution-identity-admission.ts const EXECUTION_IDENTITY_ADMISSION_MAX_BYTES=16384;const EXECUTION_IDENTITY_ADMISSION_MAX_ITEMS=16;const RAW_REF_MAX_LENGTH=4096;const PROCESS_RUNTIME_INSTANCE_ID=randomUUID();const log=createSubsystemLogger(`audit/events`);const boundedRef=()=>Type.String({minLength:1,maxLength:256});const rawRef=()=>Type.String({minLength:1,maxLength:RAW_REF_MAX_LENGTH});const evidenceState=()=>Type.Union([Type.Literal(`present`),Type.Literal(`absent`),Type.Literal(`unknown`),Type.Literal(`unsupported`)]);const closedObject=e=>Type.Object(e,{additionalProperties:false});const ingressKind=()=>Type.Union([Type.Literal(`local-cli`),Type.Literal(`gateway-client`),Type.Literal(`channel`),Type.Literal(`api`),Type.Literal(`schedule`),Type.Literal(`webhook`),Type.Literal(`task`),Type.Literal(`subagent`),Type.Literal(`acp`),Type.Literal(`worker`),Type.Literal(`plugin`),Type.Literal(`recovery`),Type.Literal(`system`)]);const runtimeKind=()=>Type.Union([Type.Literal(`gateway`),Type.Literal(`embedded`),Type.Literal(`worker`),Type.Literal(`plugin-harness`),Type.Literal(`acp`)]);const admissionGrant=()=>closedObject({rawGrantRef:rawRef(),state:evidenceState()});const admissionGrants=()=>Type.Array(admissionGrant(),{maxItems:EXECUTION_IDENTITY_ADMISSION_MAX_ITEMS});const admissionAssurance=()=>Type.Array(closedObject({kind:Type.Union([Type.Literal(`durable-profile`),Type.Literal(`trusted-proxy`),Type.Literal(`tailscale-whois`),Type.Literal(`device-proof`),Type.Literal(`channel-admission`),Type.Literal(`local-process`),Type.Literal(`spawn-lineage`),Type.Literal(`worker-admission`),Type.Literal(`runtime-binding`),Type.Literal(`other`)]),rawEvidenceRef:rawRef(),strength:Type.Union([Type.Literal(`self-asserted`),Type.Literal(`boundary-verified`),Type.Literal(`cryptographic`)])}),{maxItems:EXECUTION_IDENTITY_ADMISSION_MAX_ITEMS});const ExecutionIdentityAdmissionInvokerSchema=Type.Union([closedObject({state:Type.Literal(`present`),kind:Type.Union([Type.Literal(`person`),Type.Literal(`agent`),Type.Literal(`service`),Type.Literal(`schedule`),Type.Literal(`webhook`),Type.Literal(`system`),Type.Literal(`local-account`),Type.Literal(`runtime`)]),rawPrincipalRef:rawRef(),displayLabel:Type.Optional(Type.String({maxLength:128}))}),closedObject({state:Type.Literal(`unknown`)})]);const ExecutionIdentityRepresentedSubjectSchema=closedObject({state:Type.Literal(`present`),kind:Type.Literal(`person`),rawPrincipalRef:rawRef()});const ExecutionIdentityAdmissionEnvelopeSchema=closedObject({envelopeVersion:Type.Literal(1),contextId:boundedRef(),executionId:boundedRef(),runId:boundedRef(),createdAt:Type.Integer({minimum:0}),runtimeInstanceId:rawRef(),agentId:boundedRef(),ingress:closedObject({kind:ingressKind(),boundary:boundedRef(),state:evidenceState(),rawSourceRef:Type.Optional(rawRef())}),runtime:closedObject({kind:runtimeKind()}),invoker:Type.Optional(ExecutionIdentityAdmissionInvokerSchema),representedSubject:Type.Optional(ExecutionIdentityRepresentedSubjectSchema),applicableGrants:admissionGrants(),assurance:admissionAssurance()});const ExecutionIdentityAdmissionFactsSchema=closedObject({runId:boundedRef(),agentId:boundedRef(),ingress:closedObject({kind:ingressKind(),boundary:boundedRef(),state:Type.Optional(evidenceState()),rawSourceRef:Type.Optional(rawRef())}),runtime:closedObject({kind:runtimeKind()}),invoker:Type.Optional(ExecutionIdentityAdmissionInvokerSchema),representedSubject:Type.Optional(ExecutionIdentityRepresentedSubjectSchema),applicableGrants:Type.Optional(admissionGrants()),assurance:Type.Optional(admissionAssurance())});const ExecutionIdentityAdmissionTokenSchema=closedObject({tokenVersion:Type.Literal(1),contextId:boundedRef(),executionId:boundedRef(),runId:boundedRef(),createdAt:Type.Integer({minimum:0})});let admissionSink;let admissionFailureWarned=false;function freezeEnvelope(e,t=/* @__PURE__ */ new WeakSet){if(!e||typeof e!==`object`||t.has(e))return e;t.add(e);for(const n of Object.values(e))freezeEnvelope(n,t);return Object.freeze(e)}function copyOwnedData(e,t=/* @__PURE__ */ new WeakSet){if(e===null||[`string`,`number`,`boolean`].includes(typeof e))return e;if(typeof e!==`object`||isProxy(e))throw new Error(`execution identity admission data must be clone-safe plain data`);if(t.has(e))throw new Error(`execution identity admission data must be clone-safe plain data`);t.add(e);try{const n=Object.getPrototypeOf(e);const r=Reflect.ownKeys(e);const i=Array.isArray(e);if(Array.isArray(e)){const t=Object.getOwnPropertyDescriptor(e,`length`);if(n!==Array.prototype||!t||!(`value`in t)||typeof t.value!==`number`||r.length!==t.value+1||r.at(-1)!==`length`)throw new Error(`execution identity admission data must be clone-safe plain data`)}else if(n!==Object.prototype&&n!==null)throw new Error(`execution identity admission data must be clone-safe plain data`);const a=i?[]:Object.create(null);for(const[n,o]of r.entries()){if(o===`length`&&i)continue;if(typeof o!==`string`||i&&o!==String(n))throw new Error(`execution identity admission data must be clone-safe plain data`);const r=Object.getOwnPropertyDescriptor(e,o);if(!r?.enumerable||!(`value`in r))throw new Error(`execution identity admission data must be clone-safe plain data`);Object.defineProperty(a,o,{configurable:true,enumerable:true,value:copyOwnedData(r.value,t),writable:true})}return a}finally{t.delete(e)}}function validateEnvelope(e){const t=copyOwnedData(e);const n=executionIdentitySpawnAdmission({operation:`base-envelope`,value:t});if(!Value.Check(ExecutionIdentityAdmissionEnvelopeSchema,n)||typeof n.createdAt!==`number`||!Number.isSafeInteger(n.createdAt))throw new Error(`execution identity admission envelope violates its bounded contract`);if(!t||typeof t!==`object`||Array.isArray(t))throw new Error(`execution identity admission envelope violates its bounded contract`);const r=JSON.stringify(t);if(Buffer.byteLength(r,`utf8`)>EXECUTION_IDENTITY_ADMISSION_MAX_BYTES)throw new Error(`execution identity admission envelope exceeds 16 KiB`);return t}function validateFacts(e){const t=copyOwnedData(executionIdentitySpawnAdmission({operation:`base-facts`,value:e}));if(!Value.Check(ExecutionIdentityAdmissionFactsSchema,t))throw new Error(`execution identity admission facts violate their bounded contract`);const n=executionIdentitySpawnAdmission({operation:`read`,value:e});return executionIdentitySpawnAdmission({operation:`attach`,value:t,extra:n})}function validateToken(e){const t=copyOwnedData(e);if(!Value.Check(ExecutionIdentityAdmissionTokenSchema,t)||!Number.isSafeInteger(t.createdAt))throw new Error(`execution identity admission token violates its bounded contract`);return t}function createExecutionIdentityAdmissionToken(e,t={}){return freezeEnvelope(validateToken({tokenVersion:1,contextId:t.contextId??randomUUID(),executionId:t.executionId??randomUUID(),runId:e,createdAt:t.now??Date.now()}))}function parseExecutionIdentityAdmissionToken(e){return freezeEnvelope(validateToken(e))}function redactDisplayLabel(e){return truncateUtf16Safe(redactSensitiveText(redactSensitiveText(e,{mode:`tools`}),{mode:`tools`}),128)}function captureExecutionIdentityAdmissionEnvelope(e,t){const n=validateToken(t.token);if(n.runId!==e.runId)throw new Error(`execution identity admission token disagrees with the admitted run`);const r=t.runtimeInstanceId??PROCESS_RUNTIME_INSTANCE_ID;const i=e.assurance??[{kind:`runtime-binding`,rawEvidenceRef:r,strength:`boundary-verified`}];const a=executionIdentitySpawnAdmission({operation:`read`,value:e});const o={envelopeVersion:1,contextId:n.contextId,executionId:n.executionId,runId:n.runId,createdAt:n.createdAt,runtimeInstanceId:r,agentId:e.agentId,ingress:{...e.ingress,state:e.ingress.state??`present`},runtime:{...e.runtime},...e.invoker?.state===`present`?{invoker:{state:`present`,kind:e.invoker.kind,rawPrincipalRef:e.invoker.rawPrincipalRef,...e.invoker.displayLabel!==void 0?{displayLabel:redactDisplayLabel(e.invoker.displayLabel)}:{}}}:e.invoker?.state===`unknown`?{invoker:{state:`unknown`}}:{},...e.representedSubject?{representedSubject:{...e.representedSubject}}:{},applicableGrants:sortUniqueExecutionIdentityEntries(e.applicableGrants??[],e=>`${e.rawGrantRef}\0${e.state}`).map(e=>({rawGrantRef:e.rawGrantRef,state:e.state})),assurance:sortUniqueExecutionIdentityEntries(i,e=>`${e.kind}\0${e.rawEvidenceRef}\0${e.strength}`).map(e=>({kind:e.kind,rawEvidenceRef:e.rawEvidenceRef,strength:e.strength}))};return freezeEnvelope(validateEnvelope(executionIdentitySpawnAdmission({operation:`extend-envelope`,value:o,extra:a})))}function parseExecutionIdentityAdmissionEnvelope(e){const t=validateEnvelope(e);const n=executionIdentitySpawnAdmission({operation:`read`,value:t});if(!n)throw new Error(`execution identity admission envelope is missing spawn evidence state`);const r=captureExecutionIdentityAdmissionEnvelope(executionIdentitySpawnAdmission({operation:`attach`,value:t,extra:n}),{token:createExecutionIdentityAdmissionToken(t.runId,{contextId:t.contextId,executionId:t.executionId,now:t.createdAt}),runtimeInstanceId:t.runtimeInstanceId});if(JSON.stringify(r)!==JSON.stringify(t))throw new Error(`execution identity admission envelope is not canonical`);return r}function parseExecutionIdentityAdmissionWork(e){const t=copyOwnedData(e);if(!t||typeof t!==`object`)throw new Error(`execution identity admission work violates its bounded contract`);const n=t;if(n.kind===`capture`)return freezeEnvelope({kind:`capture`,envelope:parseExecutionIdentityAdmissionEnvelope(n.envelope)});if(n.kind===`retry-reference`)return freezeEnvelope({kind:`retry-reference`,token:parseExecutionIdentityAdmissionToken(n.token)});throw new Error(`execution identity admission work violates its bounded contract`)}function configureExecutionIdentityAdmissionSink(e){admissionSink=e;return()=>{if(admissionSink===e)admissionSink=void 0}}function hasExecutionIdentityAdmissionSink(){return admissionSink!==void 0}function enqueueExecutionIdentityContextAtAdmission(e,t){if(!t.enabled)return;try{const n=validateFacts(e);const r=validateToken(t.token??createExecutionIdentityAdmissionToken(n.runId,{contextId:t.contextId,executionId:t.executionId,now:t.now}));const i=t.retryOnly?{kind:`retry-reference`,token:r}:{kind:`capture`,envelope:captureExecutionIdentityAdmissionEnvelope(n,{token:r,runtimeInstanceId:t.runtimeInstanceId})};if(!admissionSink)throw new Error(`audit writer unavailable`);return{candidateContextId:r.contextId,candidateExecutionId:r.executionId,accepted:admissionSink(i)}}catch{if(!admissionFailureWarned){admissionFailureWarned=true;log.warn(`audit execution identity admission evidence was not queued; continuing without it`)}return}}export{parseExecutionIdentityAdmissionToken as a,sortUniqueExecutionIdentityEntries as c,hasExecutionIdentityAdmissionSink as i,createExecutionIdentityAdmissionToken as n,parseExecutionIdentityAdmissionWork as o,enqueueExecutionIdentityContextAtAdmission as r,executionIdentitySpawnAdmission as s,configureExecutionIdentityAdmissionSink as t};