@tenuo/core 0.3.0-beta.0 → 0.3.1-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/api.d.ts CHANGED
@@ -378,6 +378,8 @@ export type ExplainedField = {
378
378
  /** Absent when the argument was not supplied. */
379
379
  readonly value?: unknown;
380
380
  readonly satisfied: boolean;
381
+ /** Stable machine-readable diagnostic, when the core can identify one. */
382
+ readonly reasonCode?: string;
381
383
  readonly reason?: string;
382
384
  };
383
385
  /** What a session would decide for `tool(args)`, field by field. No proof-of-possession involved. */
package/dist/api.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"api.js","sourceRoot":"","sources":["../src/api.ts"],"names":[],"mappings":"AAAA;;;;;GAKG","sourcesContent":["/**\n * Frozen public contract for `@tenuo/core`.\n *\n * Names and shapes here are the review surface — do not grow this file with\n * protocol vocabulary (`Warrant`, `mint`, `guard`) as the lead API.\n */\n\n/** Canonical kebab-case codes from Rust `ErrorCode::name()` / `Denial::code()`. */\nexport type ProtocolDenialCode =\n | \"signature-invalid\"\n | \"untrusted-root\"\n | \"chain-broken\"\n | \"depth-exceeded\"\n | \"warrant-expired\"\n | \"tool-not-authorized\"\n | \"constraint-violation\"\n | \"pop-signature-invalid\"\n | \"approval-required\"\n | \"insufficient-approvals\"\n | \"warrant-revoked\";\n\n/** Legacy SCREAMING_SNAKE aliases accepted by existing TypeScript callers. */\nexport type LegacyTenuoErrorCode =\n | \"TENUO_NOT_READY\"\n | \"TENUO_CONFIGURATION\"\n | \"TENUO_CONSTRAINT_VIOLATION\"\n | \"TENUO_TOOL_NOT_AUTHORIZED\"\n | \"TENUO_WARRANT_EXPIRED\"\n | \"TENUO_UNTRUSTED_ROOT\"\n | \"TENUO_INVALID_POP\"\n | \"TENUO_SIGNATURE_INVALID\"\n | \"TENUO_CHAIN_INVALID\"\n | \"TENUO_DEPTH_EXCEEDED\"\n | \"TENUO_REVOKED\"\n | \"TENUO_APPROVAL_REQUIRED\"\n | \"TENUO_INSUFFICIENT_APPROVALS\"\n | \"TENUO_CANONICALIZATION\"\n | \"TENUO_NOT_IMPLEMENTED\";\n\nexport type TenuoErrorCode = ProtocolDenialCode | LegacyTenuoErrorCode;\n\n// ---------------------------------------------------------------------------\n// Constraints. Every kind is evaluated in the Rust core; TypeScript only\n// builds the marker object. The set matches the core `Constraint` enum.\n// ---------------------------------------------------------------------------\n\n/** Path-traversal-safe prefix. Core evaluates this; TypeScript does not. */\nexport type UnderConstraint = {\n readonly kind: \"under\";\n readonly root: string;\n /** Default true. */\n readonly caseSensitive?: boolean;\n /** Whether the root itself is allowed. Default true. */\n readonly allowEqual?: boolean;\n};\n\nexport type EmailConstraint = {\n readonly kind: \"email\";\n readonly domain: string;\n};\n\nexport type MaxConstraint = {\n readonly kind: \"max\";\n readonly value: number;\n};\n\nexport type MinConstraint = {\n readonly kind: \"min\";\n readonly value: number;\n};\n\nexport type RangeConstraint = {\n readonly kind: \"range\";\n readonly min?: number;\n readonly max?: number;\n readonly minExclusive?: boolean;\n readonly maxExclusive?: boolean;\n};\n\nexport type OneOfConstraint = {\n readonly kind: \"oneOf\";\n readonly values: readonly string[];\n};\n\nexport type NotOneOfConstraint = {\n readonly kind: \"notOneOf\";\n readonly values: readonly string[];\n};\n\nexport type PatternConstraint = {\n readonly kind: \"pattern\";\n readonly pattern: string;\n};\n\nexport type RegexConstraint = {\n readonly kind: \"regex\";\n readonly source: string;\n};\n\nexport type ExactConstraint = {\n readonly kind: \"exact\";\n readonly value: string | number | boolean;\n};\n\nexport type WildcardConstraint = {\n readonly kind: \"wildcard\";\n};\n\nexport type CidrConstraint = {\n readonly kind: \"cidr\";\n readonly network: string;\n};\n\nexport type UrlPatternConstraint = {\n readonly kind: \"urlPattern\";\n readonly pattern: string;\n};\n\nexport type UrlSafeConstraint = {\n readonly kind: \"urlSafe\";\n readonly schemes?: readonly string[];\n readonly allowDomains?: readonly string[];\n readonly denyDomains?: readonly string[];\n};\n\nexport type ShlexConstraint = {\n readonly kind: \"shlex\";\n readonly allow: readonly string[];\n};\n\nexport type ContainsConstraint = {\n readonly kind: \"contains\";\n readonly values: readonly (string | number | boolean)[];\n};\n\nexport type SubsetConstraint = {\n readonly kind: \"subset\";\n readonly values: readonly (string | number | boolean)[];\n};\n\nexport type AnyOfConstraint = {\n readonly kind: \"anyOf\";\n readonly constraints: readonly ConstraintExpr[];\n};\n\nexport type AllConstraint = {\n readonly kind: \"all\";\n readonly constraints: readonly ConstraintExpr[];\n};\n\nexport type NotConstraint = {\n readonly kind: \"not\";\n readonly constraint: ConstraintExpr;\n};\n\nexport type CelConstraint = {\n readonly kind: \"cel\";\n readonly expression: string;\n};\n\nexport type ConstraintExpr =\n | UnderConstraint\n | EmailConstraint\n | MaxConstraint\n | MinConstraint\n | RangeConstraint\n | OneOfConstraint\n | NotOneOfConstraint\n | PatternConstraint\n | RegexConstraint\n | ExactConstraint\n | WildcardConstraint\n | CidrConstraint\n | UrlPatternConstraint\n | UrlSafeConstraint\n | ShlexConstraint\n | ContainsConstraint\n | SubsetConstraint\n | AnyOfConstraint\n | AllConstraint\n | NotConstraint\n | CelConstraint;\n\n/** Per-argument allow policy. Not a Zod schema. */\nexport type AllowPolicy = {\n readonly [field: string]: ConstraintExpr;\n};\n\n/**\n * Framework tool shape we wrap. No dependency on `ai` / Mastra.\n * `parameters` is host-schema (usually Zod) and is never treated as authority.\n */\nexport type ToolLike<\n TArgs extends Record<string, unknown> = Record<string, unknown>,\n TResult = unknown,\n> = {\n readonly description?: string;\n readonly parameters?: unknown;\n execute: (args: TArgs, options?: unknown) => TResult | Promise<TResult>;\n};\n\ntype KeysOfUnion<T> = T extends unknown ? keyof T : never;\n\nexport type ToolPolicy<TArgs = undefined> = {\n /**\n * Host ceiling. AND'd with the session in Rust.\n * Non-empty maps are zero-trust: every call argument must be named here.\n * `{}` means no extra ceiling (session/warrant only).\n */\n readonly allow: [NonNullable<TArgs>] extends [object]\n ? [KeysOfUnion<NonNullable<TArgs>>] extends [never]\n ? AllowPolicy\n : string extends KeysOfUnion<NonNullable<TArgs>>\n ? AllowPolicy\n : number extends KeysOfUnion<NonNullable<TArgs>>\n ? AllowPolicy\n : symbol extends KeysOfUnion<NonNullable<TArgs>>\n ? AllowPolicy\n : { readonly [Field in KeysOfUnion<NonNullable<TArgs>>]?: ConstraintExpr }\n : AllowPolicy;\n readonly capability?: string;\n};\n\n/** Compile-time brand only — never assigned at runtime. Do not `in`/`has` this key. */\ndeclare const protectedBrand: unique symbol;\n\nexport type ExecuteOptions = {\n readonly session?: Session;\n /** Already-signed approval envelopes (hex, standard base64, or CBOR bytes). */\n readonly approvals?: readonly (string | Uint8Array)[];\n /**\n * Signed evidence of the decision. Not a security hook.\n * Exceptions (sync or rejected Promise) are isolated and never deny or\n * fail the tool.\n */\n readonly onReceipt?: (receipt: string) => void | Promise<void>;\n /**\n * Correlation handle written to the receipt. Use whatever id the host\n * already has — a JSON-RPC id, a trace or span id — so a receipt can be\n * matched against your own logs. Not an identity: nothing enforces\n * uniqueness, and distinguishing repeated calls is the receipt chain's job.\n */\n readonly requestId?: string;\n};\n\ntype ExtraExecuteOptions<T extends { execute: (args: never) => unknown }> =\n T[\"execute\"] extends (args: never, options?: infer O) => unknown\n ? unknown extends O\n ? object\n : Omit<NonNullable<O>, keyof ExecuteOptions>\n : object;\n\n/** Wrapped tool. `execute` still authorizes; optional `{ session }` overrides ALS. */\nexport type ProtectedTool<T extends { execute: (args: never) => unknown }> = Omit<T, \"execute\"> & {\n execute: (\n args: Parameters<T[\"execute\"]>[0],\n options?: ExecuteOptions & ExtraExecuteOptions<T>,\n ) => Promise<Awaited<ReturnType<T[\"execute\"]>>>;\n readonly [protectedBrand]: true;\n};\n\n// ---------------------------------------------------------------------------\n// Approvals\n// ---------------------------------------------------------------------------\n\n/** Per-argument trigger for an approval gate. */\nexport type ArgApprovalGate =\n /** Every value of this argument fires the gate. */\n | \"all\"\n /** Only values satisfying the constraint fire the gate. */\n | { readonly when: ConstraintExpr }\n /** Every value except those satisfying the constraint fires the gate. Narrowable across delegation. */\n | { readonly exempt: ConstraintExpr };\n\n/** Gate on one tool: a message for the approver and optional per-argument triggers. */\nexport type ToolApprovalGate = {\n readonly message?: string;\n /** Absent: the whole tool is gated. */\n readonly args?: { readonly [field: string]: ArgApprovalGate };\n};\n\n/** Approval requirement. Host collects SignedApproval envelopes; Rust decides. */\nexport type RequireApproval = {\n readonly approvers: readonly PublicKeyHandle[];\n readonly min: number;\n /** Whole-tool gates. Defaults to every tool in the session when `gates` is absent too. */\n readonly tools?: readonly string[];\n /** Per-tool gates with messages and per-argument triggers. */\n readonly gates?: { readonly [tool: string]: ToolApprovalGate };\n};\n\n/** What an approval service needs to present a call to a human. Not a signed artifact. */\nexport type ApprovalRequest = {\n readonly requestId: string;\n readonly warrantId: string;\n readonly tool: string;\n readonly args: Readonly<Record<string, unknown>>;\n /** Hex SHA-256 committing to warrant id, tool, canonical args, and holder. */\n readonly requestHash: string;\n readonly holderPublicKey: string;\n readonly requiredApprovers: readonly string[];\n readonly minApprovals: number;\n /** Unix seconds. An approval cannot outlive the warrant. */\n readonly warrantExpiresAt: number;\n readonly createdAt: number;\n readonly message: string;\n};\n\n/** Holder-signed statement that it is the one asking. Carried in a control-plane request. */\nexport type ApprovalContextAttestation = {\n readonly version: number;\n readonly canonicalization: string;\n readonly warrantId: string;\n readonly tool: string;\n readonly requestHash: string;\n readonly holderKeyHex: string;\n readonly argsCanonicalCborB64: string;\n readonly signerKeyHex: string;\n readonly signatureB64: string;\n};\n\n/** Wire body for a control-plane approval API. Field names are the wire names. */\nexport type ControlPlaneApprovalRequestV1 = {\n readonly schema_version: 1;\n readonly request_id_hex: string;\n readonly warrant_id: string;\n readonly tool: string;\n readonly arguments: Readonly<Record<string, unknown>>;\n readonly request_hash_hex: string;\n readonly holder_public_key_hex: string;\n readonly required_approver_keys_hex: readonly string[];\n readonly min_approvals: number;\n readonly warrant_expires_at_unix: number;\n readonly created_at_unix: number;\n readonly attestation?: Readonly<Record<string, unknown>>;\n readonly temporal?: Readonly<Record<string, string>>;\n readonly message?: string;\n};\n\nexport type ControlPlaneApprovalResponseV1 = {\n readonly status: string;\n readonly signed_approvals_b64?: readonly string[];\n readonly error?: string;\n readonly server_request_id?: string;\n};\n\nexport type SignApprovalOptions = {\n /** Who approved, in the approver system's own terms. Required. */\n readonly externalId: string;\n /** Approval lifetime. Default one hour, always clamped to the warrant's expiry when given. */\n readonly ttlSeconds?: number;\n readonly warrantExpiresAt?: number;\n};\n\n/** Decoded approval envelope. Not authorization. */\nexport type ApprovalInfo = {\n readonly approverPublicKey: string;\n readonly requestHash: string;\n readonly externalId: string;\n readonly approvedAt: number;\n readonly expiresAt: number;\n readonly expired: boolean;\n readonly signatureValid: boolean;\n readonly error?: string;\n};\n\n// ---------------------------------------------------------------------------\n// Sessions\n// ---------------------------------------------------------------------------\n\nexport type SessionAllow = {\n readonly [capability: string]: AllowPolicy;\n};\n\n/** Named level or a number 0-255. Delegation can only lower it. */\nexport type Clearance =\n | number\n | \"untrusted\"\n | \"external\"\n | \"partner\"\n | \"internal\"\n | \"privileged\"\n | \"system\";\n\nexport type SessionInput = {\n /** Capability map. Optional when `tools` is set. Issuer sessions may omit it. */\n readonly allow?: SessionAllow;\n /** Wrapped tools from `tenuo.tool()`. Their `allow` is minted into the session. */\n readonly tools?: readonly object[];\n readonly ttlSeconds?: number;\n readonly requireApproval?: RequireApproval;\n /**\n * Issue to another agent's key instead of a fresh local holder. The\n * returned session cannot authorize here (it has no holder secret); send\n * `toWire()` to that agent, which imports it with `sessionFromWire()`.\n */\n readonly holder?: PublicKeyHandle;\n /**\n * How many times this authority may be delegated below the root.\n * `0` makes the session terminal. Omit for the protocol maximum.\n * Delegation can lower this ceiling and never raise it.\n */\n readonly maxDepth?: number;\n /**\n * `\"execution\"` (default) can call tools. `\"issuer\"` cannot call tools; its\n * holder can mint execution sessions with `tenuo.issue()` for the tools in\n * `issuableTools`, within `constraintBounds`, without the root key.\n */\n readonly kind?: \"execution\" | \"issuer\";\n readonly clearance?: Clearance;\n /** Free-form task correlation id. Inherited unchanged through delegation. */\n readonly sessionId?: string;\n /** Free-form agent label. Delegation may change it. */\n readonly agentId?: string;\n /** Issuer sessions only. */\n readonly issuableTools?: readonly string[];\n /** Issuer sessions only: ceiling on the constraints of anything issued, by field. */\n readonly constraintBounds?: AllowPolicy;\n /** Issuer sessions only: how deep issued sessions may themselves delegate. */\n readonly maxIssueDepth?: number;\n};\n\n/** Options for `tenuo.narrow()`. All optional; the default keeps the holder. */\nexport type NarrowOptions = {\n /**\n * Bind the child to another agent's key. This is delegation: the current\n * holder signs, the child belongs to `holder`, and the returned session\n * cannot authorize here. Hand `toWire()` to that agent.\n */\n readonly holder?: PublicKeyHandle;\n /** Child lifetime. Clamped to what the parent has left. */\n readonly ttlSeconds?: number;\n /** The child's holder cannot delegate further. */\n readonly terminal?: boolean;\n /** Lower the delegation ceiling. Cannot exceed the parent's. */\n readonly maxDepth?: number;\n /** Lower the clearance. Cannot exceed the parent's. */\n readonly clearance?: Clearance;\n readonly agentId?: string;\n /** Approvers can only be added. */\n readonly addApprovers?: readonly PublicKeyHandle[];\n /** The threshold can only go up. */\n readonly minApprovals?: number;\n};\n\n/** Options for `tenuo.issue()`: an execution session minted from an issuer session. */\nexport type IssueInput = {\n readonly allow: SessionAllow;\n /** The distinct agent that will use it. Issuer/holder separation is enforced. */\n readonly holder: PublicKeyHandle;\n readonly ttlSeconds?: number;\n readonly maxDepth?: number;\n readonly clearance?: Clearance;\n readonly sessionId?: string;\n readonly agentId?: string;\n /** Approval policy for the issued execution session. Defaults to gating every issued tool. */\n readonly requireApproval?: RequireApproval;\n};\n\n/** Public view of a session's leaf. Never includes the holder secret. */\nexport type SessionInfo = {\n readonly kind: \"execution\" | \"issuer\";\n /** Hex public key the leaf is bound to. */\n readonly holderPublicKey: string;\n /** Hex public key that signed the root of the chain. */\n readonly rootPublicKey: string;\n /** 0 for a root session, +1 per delegation. */\n readonly depth: number;\n /** Delegation ceiling in force for this leaf. */\n readonly maxDepth: number;\n /** True when `depth >= maxDepth`: cannot be narrowed further. */\n readonly terminal: boolean;\n /** Unix seconds. */\n readonly expiresAt: number;\n readonly tools: readonly string[];\n /** Warrant ids, root first. */\n readonly warrantIds: readonly string[];\n /**\n * True when this process holds the leaf's holder secret. False for a\n * session issued or delegated to another agent: `toWire()` works,\n * `execute` and `narrow` do not.\n */\n readonly canAuthorize: boolean;\n readonly clearance?: number;\n readonly sessionId?: string;\n readonly agentId?: string;\n readonly issuableTools?: readonly string[];\n readonly maxIssueDepth?: number;\n readonly requiredApprovers?: readonly string[];\n readonly minApprovals?: number;\n readonly approvalGatedTools: readonly string[];\n};\n\n/** One constrained argument in an `explain()` result. */\nexport type ExplainedField = {\n readonly field: string;\n /** Core constraint type name, e.g. `\"Subpath\"`, `\"Range\"`. */\n readonly kind: string;\n /** The constraint as core serializes it. */\n readonly constraint: unknown;\n /** Absent when the argument was not supplied. */\n readonly value?: unknown;\n readonly satisfied: boolean;\n readonly reason?: string;\n};\n\n/** What a session would decide for `tool(args)`, field by field. No proof-of-possession involved. */\nexport type Explanation = {\n readonly tool: string;\n readonly kind: \"execution\" | \"issuer\";\n readonly outcome: \"allow\" | \"deny\";\n readonly code?: TenuoErrorCode;\n readonly field?: string;\n readonly message?: string;\n readonly toolGranted: boolean;\n readonly fields: readonly ExplainedField[];\n /** Arguments the session does not name. Zero-trust policies reject these. */\n readonly unknownFields: readonly string[];\n /** Constrained arguments the call did not supply. */\n readonly missingFields: readonly string[];\n readonly expired: boolean;\n readonly expiresAt: number;\n readonly chainValid: boolean;\n readonly chainError?: TenuoErrorCode;\n};\n\nexport type DevRoot = {\n readonly kind: \"dev-root\";\n /**\n * Required when `NODE_ENV` is unset or is not `development` / `test`.\n * Unset `NODE_ENV` is not treated as development.\n */\n readonly allowInProduction?: boolean;\n};\n\n/** A stable issuer secret: this process is a control plane. */\nexport type IssuerKey = {\n readonly kind: \"issuer-key\";\n readonly secret: Uint8Array;\n};\n\nexport type PublicKeyHandle = {\n readonly kind: \"public-key\";\n readonly source: \"env\" | \"hex\" | \"bytes\";\n readonly hex: string;\n};\n\nexport type WarrantPart = {\n readonly payload_hex: string;\n readonly signature_hex: string;\n};\n\nexport type SessionFromWireInput = {\n readonly warrant: string | readonly string[] | readonly WarrantPart[];\n readonly holderKey: Uint8Array;\n};\n\n/** Field-level (`{ path: under(\"/data\") }`) or per-capability (`{ read_file: { path: ... } }`). */\nexport type NarrowInput = AllowPolicy | SessionAllow;\n\nexport type CreateTenuoOptions = {\n readonly trustedRoots?: readonly PublicKeyHandle[];\n /**\n * `devRoot()` for development; an `issuerKey*` for a control plane that\n * mints with a stable key; a public key for a verifier. An issuer key\n * trusts itself plus `trustedRoots`.\n */\n readonly root?: DevRoot | IssuerKey | PublicKeyHandle;\n /** Published SignedRevocationList (hex or standard base64). Verified against a trusted root. */\n readonly revocationList?: string | Uint8Array;\n /** 32-byte holder seed used to sign verifier receipts. Runtime supplies this. */\n readonly receiptSigner?: Uint8Array;\n};\n\nexport type ApprovalRequestSummary = {\n readonly tool: string;\n readonly required: number;\n readonly received: number;\n};\n\nexport type Decision =\n | { readonly outcome: \"allow\"; readonly args: Readonly<Record<string, unknown>> }\n | { readonly outcome: \"deny\"; readonly code: TenuoErrorCode; readonly field?: string }\n | { readonly outcome: \"approval_required\"; readonly request: ApprovalRequestSummary };\n\n// ---------------------------------------------------------------------------\n// Revocation and receipts\n// ---------------------------------------------------------------------------\n\nexport type RevocationListInput = {\n readonly revoke: readonly string[];\n /** Monotonic; verifiers refuse an older version. Default 1. */\n readonly version?: number;\n};\n\nexport type RevocationListInfo = {\n readonly version: number;\n readonly issuedAt: number;\n readonly issuerPublicKey: string;\n readonly revokedIds: readonly string[];\n readonly signatureValid: boolean;\n};\n\n/** Signature authenticity of a receipt. Not authorization. */\nexport type ReceiptInfo = {\n readonly authentic: true;\n /** Hex key the receipt is signed under — resolve against your own authorizer set. */\n readonly signerKey: string;\n readonly outcome: \"allow\" | \"deny\";\n readonly action: string;\n readonly decisionCode?: string;\n readonly requestId: string;\n readonly srlVersion?: number;\n readonly srlHash?: string;\n readonly requestHash?: string;\n readonly policyDefinitionHash?: string;\n readonly prevReceiptHash?: string;\n readonly trustedRootsHash?: string;\n};\n\n/** Root-anchored receipt check: the embedded chain against trusted roots at decision time. */\nexport type ReceiptChainInfo = {\n readonly signerKey: string;\n readonly outcome: \"allow\" | \"deny\";\n readonly decisionCode?: string;\n readonly timestamp: number;\n readonly chainValid: boolean;\n readonly chainError?: string;\n readonly corroboratesDenial?: boolean;\n readonly rootIssuer?: string;\n readonly leafHolder?: string;\n};\n\n// ---------------------------------------------------------------------------\n// Presenting authority across any boundary\n// ---------------------------------------------------------------------------\n\n/** Warrant chain plus proof-of-possession for one call. Transport-agnostic. */\nexport type PresentedCall = {\n readonly warrant: string;\n readonly signature: string;\n readonly approvals?: readonly string[];\n};\n\nexport interface Session {\n readonly [Symbol.toStringTag]: \"TenuoSession\";\n /** Warrant tokens, root first. Does not include the holder secret. */\n toWire(): readonly string[];\n /** SHA-256 of `(warrant_id, tool, canonical args)`. App-level idempotency, not PoP. */\n dedupKey(tool: string, args: Readonly<Record<string, unknown>>): string;\n /** Holder public key, depth, ceiling, lifetime, tools. Never the secret. */\n inspect(): SessionInfo;\n /**\n * Receipt helpers below are required for `createTenuo.runtime({ receipts:\n * \"collect\" })`. Implementers that are not runtime sessions can return\n * empty snapshots and `0` from acknowledge.\n */\n /**\n * Receipts collected for this session and not yet drained. Empty when the\n * session was not created by a Runtime with `receipts: \"collect\"`.\n */\n peekReceipts(): readonly string[];\n /**\n * Snapshot of collected receipts. Same as `peekReceipts`; nothing is removed\n * until `acknowledgeReceipts`.\n */\n drainReceipts(): readonly string[];\n /** Remove the first `count` pending receipts. */\n acknowledgeReceipts(count: number): number;\n}\n\nexport interface Tenuo {\n /**\n * Wrap any `{ execute }` tool (Vercel AI SDK, Mastra, plain object).\n * `parameters` / Zod stay on the inner tool and are never treated as authority.\n */\n tool<T extends { execute: (args: never) => unknown }>(\n inner: T,\n policy: ToolPolicy<Parameters<T[\"execute\"]>[0]>,\n ): ProtectedTool<T>;\n session(input: SessionInput): Session;\n /** Import a warrant minted elsewhere (Rust / Python / another process). */\n sessionFromWire(input: SessionFromWireInput): Session;\n withSession<R>(session: Session, fn: () => R): R;\n /**\n * Child session with less authority. Without options the same holder keeps\n * it; with `options.holder` it is delegated to another agent's key. Core\n * rejects any child that is not within its parent before a token exists.\n */\n narrow(session: Session, allow: NarrowInput, options?: NarrowOptions): Session;\n /**\n * Mint an execution session from an issuer session, signed by the issuer\n * session's holder. Core checks tools against `issuableTools`, constraints\n * against `constraintBounds`, clearance, and issue depth. No root key.\n */\n issue(issuer: Session, input: IssueInput): Session;\n /**\n * Public key of the local issuer (dev root or issuer key). Other processes\n * put it in `trustedRoots` to accept warrants this context mints.\n */\n issuerPublicKey(): PublicKeyHandle;\n /** What the session would decide for `tool(args)`, field by field. Never runs the tool. */\n explain(session: Session, tool: string, args: Readonly<Record<string, unknown>>): Explanation;\n /** Everything an approval service needs to present `tool(args)` to a human. */\n approvalRequest(session: Session, tool: string, args: Readonly<Record<string, unknown>>): ApprovalRequest;\n /** Holder-signed proof that this session is the one asking for `tool(args)`. */\n attestApprovalRequest(\n session: Session,\n tool: string,\n args: Readonly<Record<string, unknown>>,\n ): ApprovalContextAttestation;\n /** Authorize locally, then produce warrant + proof-of-possession for another boundary to verify. */\n present(\n session: Session,\n tool: string,\n args: Readonly<Record<string, unknown>>,\n options?: McpAttachOptions,\n ): PresentedCall;\n /** Verify a presented call at any boundary. Resolves with the authorized arguments; the tool must not run otherwise. */\n verify(\n presented: PresentedCall,\n tool: string,\n args: Readonly<Record<string, unknown>>,\n options?: McpVerifyOptions,\n ): Promise<Readonly<Record<string, unknown>>>;\n /** Sign a revocation list with this context's issuer key. Load it with `revoke()` where this issuer is trusted. */\n revocationList(input: RevocationListInput): string;\n /** Load a published SignedRevocationList. Rust verifies the issuer against trusted roots. */\n revoke(list: string | Uint8Array): void;\n /** MCP `_meta.tenuo` attach / verify. No MCP SDK dependency. */\n readonly mcp: TenuoMcp;\n ready(): void;\n}\n\n/** Wire envelope Python and TypeScript both read from `params._meta`. */\nexport type TenuoMcpMeta = {\n readonly tenuo: PresentedCall;\n};\n\nexport type McpAttachOptions = {\n readonly approvals?: readonly (string | Uint8Array)[];\n readonly onReceipt?: (receipt: string) => void | Promise<void>;\n /**\n * Correlation handle written to the receipt. Use whatever id the host\n * already has — a JSON-RPC id, a trace or span id — so a receipt can be\n * matched against your own logs. Not an identity: nothing enforces\n * uniqueness, and distinguishing repeated calls is the receipt chain's job.\n */\n readonly requestId?: string;\n};\n\n/** Host ceiling and optional receipt hook on `mcp.handler()`. */\nexport type McpHandlerPolicy = {\n readonly allow?: AllowPolicy;\n readonly onReceipt?: (receipt: string) => void | Promise<void>;\n readonly nonceStore?: NonceStore;\n /**\n * Isolated. Called when `nonceStore.checkAndRecord` throws or rejects.\n * The client only ever sees \"Replay store unavailable\".\n */\n readonly onNonceStoreError?: (error: unknown) => void | Promise<void>;\n};\n\nexport type McpVerifyOptions = {\n readonly allow?: AllowPolicy;\n readonly onReceipt?: (receipt: string) => void | Promise<void>;\n /**\n * Opt-in exact-PoP replay check. `checkAndRecord` may return a Promise\n * (Redis). A rejected Promise fails closed. In-memory stores do not work\n * across processes. PoP v1 is otherwise replayable in-window, including\n * envelopes that already carry approvals.\n */\n readonly nonceStore?: NonceStore;\n /**\n * Isolated. Called when `nonceStore.checkAndRecord` throws or rejects.\n * The client only ever sees \"Replay store unavailable\".\n */\n readonly onNonceStoreError?: (error: unknown) => void | Promise<void>;\n /**\n * Correlation handle written to the receipt. Use whatever id the host\n * already has — a JSON-RPC id, a trace or span id — so a receipt can be\n * matched against your own logs. Not an identity: nothing enforces\n * uniqueness, and distinguishing repeated calls is the receipt chain's job.\n */\n readonly requestId?: string;\n};\n\n/**\n * Returns true if the PoP is fresh and recorded; false if this exact token\n * was already consumed. Async stores (Redis) return `Promise<boolean>`.\n * `verify()` / handlers await the result. Never return a Promise from a\n * store that is only consulted synchronously — that used to fail open.\n */\nexport type NonceStore = {\n checkAndRecord(popSignature: string): boolean | Promise<boolean>;\n};\n\nexport type McpCallParams = {\n readonly name: string;\n readonly arguments: Readonly<Record<string, unknown>>;\n readonly _meta: TenuoMcpMeta;\n};\n\nexport type McpJsonRpcError = {\n readonly code: -32602 | -32001 | -32002;\n readonly message: string;\n readonly data?: { readonly tenuo?: { readonly code: TenuoErrorCode } };\n};\n\nexport interface TenuoMcp {\n /** Local authorize, then put warrant + PoP on `_meta.tenuo`. */\n attach(\n session: Session,\n name: string,\n args: Readonly<Record<string, unknown>>,\n options?: McpAttachOptions,\n ): McpCallParams;\n /**\n * Server path. Verifies a presented warrant + PoP. Tool handler must not\n * run unless this returns.\n */\n verify(\n name: string,\n args: Readonly<Record<string, unknown>>,\n meta: unknown,\n options?: McpVerifyOptions,\n ): Promise<Readonly<Record<string, unknown>>>;\n /** Wrap a handler: verify from `extra._meta` / `extra.meta`, then execute. */\n handler<TArgs extends Record<string, unknown>, TResult>(\n name: string,\n execute: (args: TArgs) => TResult | Promise<TResult>,\n ): (\n args: TArgs,\n extra?: { readonly _meta?: unknown; readonly meta?: unknown },\n ) => Promise<TResult>;\n handler<TArgs extends Record<string, unknown>, TResult>(\n name: string,\n policy: McpHandlerPolicy,\n execute: (args: TArgs) => TResult | Promise<TResult>,\n ): (\n args: TArgs,\n extra?: { readonly _meta?: unknown; readonly meta?: unknown },\n ) => Promise<TResult>;\n jsonRpcError(error: unknown): McpJsonRpcError;\n}\n"]}
1
+ {"version":3,"file":"api.js","sourceRoot":"","sources":["../src/api.ts"],"names":[],"mappings":"AAAA;;;;;GAKG","sourcesContent":["/**\n * Frozen public contract for `@tenuo/core`.\n *\n * Names and shapes here are the review surface — do not grow this file with\n * protocol vocabulary (`Warrant`, `mint`, `guard`) as the lead API.\n */\n\n/** Canonical kebab-case codes from Rust `ErrorCode::name()` / `Denial::code()`. */\nexport type ProtocolDenialCode =\n | \"signature-invalid\"\n | \"untrusted-root\"\n | \"chain-broken\"\n | \"depth-exceeded\"\n | \"warrant-expired\"\n | \"tool-not-authorized\"\n | \"constraint-violation\"\n | \"pop-signature-invalid\"\n | \"approval-required\"\n | \"insufficient-approvals\"\n | \"warrant-revoked\";\n\n/** Legacy SCREAMING_SNAKE aliases accepted by existing TypeScript callers. */\nexport type LegacyTenuoErrorCode =\n | \"TENUO_NOT_READY\"\n | \"TENUO_CONFIGURATION\"\n | \"TENUO_CONSTRAINT_VIOLATION\"\n | \"TENUO_TOOL_NOT_AUTHORIZED\"\n | \"TENUO_WARRANT_EXPIRED\"\n | \"TENUO_UNTRUSTED_ROOT\"\n | \"TENUO_INVALID_POP\"\n | \"TENUO_SIGNATURE_INVALID\"\n | \"TENUO_CHAIN_INVALID\"\n | \"TENUO_DEPTH_EXCEEDED\"\n | \"TENUO_REVOKED\"\n | \"TENUO_APPROVAL_REQUIRED\"\n | \"TENUO_INSUFFICIENT_APPROVALS\"\n | \"TENUO_CANONICALIZATION\"\n | \"TENUO_NOT_IMPLEMENTED\";\n\nexport type TenuoErrorCode = ProtocolDenialCode | LegacyTenuoErrorCode;\n\n// ---------------------------------------------------------------------------\n// Constraints. Every kind is evaluated in the Rust core; TypeScript only\n// builds the marker object. The set matches the core `Constraint` enum.\n// ---------------------------------------------------------------------------\n\n/** Path-traversal-safe prefix. Core evaluates this; TypeScript does not. */\nexport type UnderConstraint = {\n readonly kind: \"under\";\n readonly root: string;\n /** Default true. */\n readonly caseSensitive?: boolean;\n /** Whether the root itself is allowed. Default true. */\n readonly allowEqual?: boolean;\n};\n\nexport type EmailConstraint = {\n readonly kind: \"email\";\n readonly domain: string;\n};\n\nexport type MaxConstraint = {\n readonly kind: \"max\";\n readonly value: number;\n};\n\nexport type MinConstraint = {\n readonly kind: \"min\";\n readonly value: number;\n};\n\nexport type RangeConstraint = {\n readonly kind: \"range\";\n readonly min?: number;\n readonly max?: number;\n readonly minExclusive?: boolean;\n readonly maxExclusive?: boolean;\n};\n\nexport type OneOfConstraint = {\n readonly kind: \"oneOf\";\n readonly values: readonly string[];\n};\n\nexport type NotOneOfConstraint = {\n readonly kind: \"notOneOf\";\n readonly values: readonly string[];\n};\n\nexport type PatternConstraint = {\n readonly kind: \"pattern\";\n readonly pattern: string;\n};\n\nexport type RegexConstraint = {\n readonly kind: \"regex\";\n readonly source: string;\n};\n\nexport type ExactConstraint = {\n readonly kind: \"exact\";\n readonly value: string | number | boolean;\n};\n\nexport type WildcardConstraint = {\n readonly kind: \"wildcard\";\n};\n\nexport type CidrConstraint = {\n readonly kind: \"cidr\";\n readonly network: string;\n};\n\nexport type UrlPatternConstraint = {\n readonly kind: \"urlPattern\";\n readonly pattern: string;\n};\n\nexport type UrlSafeConstraint = {\n readonly kind: \"urlSafe\";\n readonly schemes?: readonly string[];\n readonly allowDomains?: readonly string[];\n readonly denyDomains?: readonly string[];\n};\n\nexport type ShlexConstraint = {\n readonly kind: \"shlex\";\n readonly allow: readonly string[];\n};\n\nexport type ContainsConstraint = {\n readonly kind: \"contains\";\n readonly values: readonly (string | number | boolean)[];\n};\n\nexport type SubsetConstraint = {\n readonly kind: \"subset\";\n readonly values: readonly (string | number | boolean)[];\n};\n\nexport type AnyOfConstraint = {\n readonly kind: \"anyOf\";\n readonly constraints: readonly ConstraintExpr[];\n};\n\nexport type AllConstraint = {\n readonly kind: \"all\";\n readonly constraints: readonly ConstraintExpr[];\n};\n\nexport type NotConstraint = {\n readonly kind: \"not\";\n readonly constraint: ConstraintExpr;\n};\n\nexport type CelConstraint = {\n readonly kind: \"cel\";\n readonly expression: string;\n};\n\nexport type ConstraintExpr =\n | UnderConstraint\n | EmailConstraint\n | MaxConstraint\n | MinConstraint\n | RangeConstraint\n | OneOfConstraint\n | NotOneOfConstraint\n | PatternConstraint\n | RegexConstraint\n | ExactConstraint\n | WildcardConstraint\n | CidrConstraint\n | UrlPatternConstraint\n | UrlSafeConstraint\n | ShlexConstraint\n | ContainsConstraint\n | SubsetConstraint\n | AnyOfConstraint\n | AllConstraint\n | NotConstraint\n | CelConstraint;\n\n/** Per-argument allow policy. Not a Zod schema. */\nexport type AllowPolicy = {\n readonly [field: string]: ConstraintExpr;\n};\n\n/**\n * Framework tool shape we wrap. No dependency on `ai` / Mastra.\n * `parameters` is host-schema (usually Zod) and is never treated as authority.\n */\nexport type ToolLike<\n TArgs extends Record<string, unknown> = Record<string, unknown>,\n TResult = unknown,\n> = {\n readonly description?: string;\n readonly parameters?: unknown;\n execute: (args: TArgs, options?: unknown) => TResult | Promise<TResult>;\n};\n\ntype KeysOfUnion<T> = T extends unknown ? keyof T : never;\n\nexport type ToolPolicy<TArgs = undefined> = {\n /**\n * Host ceiling. AND'd with the session in Rust.\n * Non-empty maps are zero-trust: every call argument must be named here.\n * `{}` means no extra ceiling (session/warrant only).\n */\n readonly allow: [NonNullable<TArgs>] extends [object]\n ? [KeysOfUnion<NonNullable<TArgs>>] extends [never]\n ? AllowPolicy\n : string extends KeysOfUnion<NonNullable<TArgs>>\n ? AllowPolicy\n : number extends KeysOfUnion<NonNullable<TArgs>>\n ? AllowPolicy\n : symbol extends KeysOfUnion<NonNullable<TArgs>>\n ? AllowPolicy\n : { readonly [Field in KeysOfUnion<NonNullable<TArgs>>]?: ConstraintExpr }\n : AllowPolicy;\n readonly capability?: string;\n};\n\n/** Compile-time brand only — never assigned at runtime. Do not `in`/`has` this key. */\ndeclare const protectedBrand: unique symbol;\n\nexport type ExecuteOptions = {\n readonly session?: Session;\n /** Already-signed approval envelopes (hex, standard base64, or CBOR bytes). */\n readonly approvals?: readonly (string | Uint8Array)[];\n /**\n * Signed evidence of the decision. Not a security hook.\n * Exceptions (sync or rejected Promise) are isolated and never deny or\n * fail the tool.\n */\n readonly onReceipt?: (receipt: string) => void | Promise<void>;\n /**\n * Correlation handle written to the receipt. Use whatever id the host\n * already has — a JSON-RPC id, a trace or span id — so a receipt can be\n * matched against your own logs. Not an identity: nothing enforces\n * uniqueness, and distinguishing repeated calls is the receipt chain's job.\n */\n readonly requestId?: string;\n};\n\ntype ExtraExecuteOptions<T extends { execute: (args: never) => unknown }> =\n T[\"execute\"] extends (args: never, options?: infer O) => unknown\n ? unknown extends O\n ? object\n : Omit<NonNullable<O>, keyof ExecuteOptions>\n : object;\n\n/** Wrapped tool. `execute` still authorizes; optional `{ session }` overrides ALS. */\nexport type ProtectedTool<T extends { execute: (args: never) => unknown }> = Omit<T, \"execute\"> & {\n execute: (\n args: Parameters<T[\"execute\"]>[0],\n options?: ExecuteOptions & ExtraExecuteOptions<T>,\n ) => Promise<Awaited<ReturnType<T[\"execute\"]>>>;\n readonly [protectedBrand]: true;\n};\n\n// ---------------------------------------------------------------------------\n// Approvals\n// ---------------------------------------------------------------------------\n\n/** Per-argument trigger for an approval gate. */\nexport type ArgApprovalGate =\n /** Every value of this argument fires the gate. */\n | \"all\"\n /** Only values satisfying the constraint fire the gate. */\n | { readonly when: ConstraintExpr }\n /** Every value except those satisfying the constraint fires the gate. Narrowable across delegation. */\n | { readonly exempt: ConstraintExpr };\n\n/** Gate on one tool: a message for the approver and optional per-argument triggers. */\nexport type ToolApprovalGate = {\n readonly message?: string;\n /** Absent: the whole tool is gated. */\n readonly args?: { readonly [field: string]: ArgApprovalGate };\n};\n\n/** Approval requirement. Host collects SignedApproval envelopes; Rust decides. */\nexport type RequireApproval = {\n readonly approvers: readonly PublicKeyHandle[];\n readonly min: number;\n /** Whole-tool gates. Defaults to every tool in the session when `gates` is absent too. */\n readonly tools?: readonly string[];\n /** Per-tool gates with messages and per-argument triggers. */\n readonly gates?: { readonly [tool: string]: ToolApprovalGate };\n};\n\n/** What an approval service needs to present a call to a human. Not a signed artifact. */\nexport type ApprovalRequest = {\n readonly requestId: string;\n readonly warrantId: string;\n readonly tool: string;\n readonly args: Readonly<Record<string, unknown>>;\n /** Hex SHA-256 committing to warrant id, tool, canonical args, and holder. */\n readonly requestHash: string;\n readonly holderPublicKey: string;\n readonly requiredApprovers: readonly string[];\n readonly minApprovals: number;\n /** Unix seconds. An approval cannot outlive the warrant. */\n readonly warrantExpiresAt: number;\n readonly createdAt: number;\n readonly message: string;\n};\n\n/** Holder-signed statement that it is the one asking. Carried in a control-plane request. */\nexport type ApprovalContextAttestation = {\n readonly version: number;\n readonly canonicalization: string;\n readonly warrantId: string;\n readonly tool: string;\n readonly requestHash: string;\n readonly holderKeyHex: string;\n readonly argsCanonicalCborB64: string;\n readonly signerKeyHex: string;\n readonly signatureB64: string;\n};\n\n/** Wire body for a control-plane approval API. Field names are the wire names. */\nexport type ControlPlaneApprovalRequestV1 = {\n readonly schema_version: 1;\n readonly request_id_hex: string;\n readonly warrant_id: string;\n readonly tool: string;\n readonly arguments: Readonly<Record<string, unknown>>;\n readonly request_hash_hex: string;\n readonly holder_public_key_hex: string;\n readonly required_approver_keys_hex: readonly string[];\n readonly min_approvals: number;\n readonly warrant_expires_at_unix: number;\n readonly created_at_unix: number;\n readonly attestation?: Readonly<Record<string, unknown>>;\n readonly temporal?: Readonly<Record<string, string>>;\n readonly message?: string;\n};\n\nexport type ControlPlaneApprovalResponseV1 = {\n readonly status: string;\n readonly signed_approvals_b64?: readonly string[];\n readonly error?: string;\n readonly server_request_id?: string;\n};\n\nexport type SignApprovalOptions = {\n /** Who approved, in the approver system's own terms. Required. */\n readonly externalId: string;\n /** Approval lifetime. Default one hour, always clamped to the warrant's expiry when given. */\n readonly ttlSeconds?: number;\n readonly warrantExpiresAt?: number;\n};\n\n/** Decoded approval envelope. Not authorization. */\nexport type ApprovalInfo = {\n readonly approverPublicKey: string;\n readonly requestHash: string;\n readonly externalId: string;\n readonly approvedAt: number;\n readonly expiresAt: number;\n readonly expired: boolean;\n readonly signatureValid: boolean;\n readonly error?: string;\n};\n\n// ---------------------------------------------------------------------------\n// Sessions\n// ---------------------------------------------------------------------------\n\nexport type SessionAllow = {\n readonly [capability: string]: AllowPolicy;\n};\n\n/** Named level or a number 0-255. Delegation can only lower it. */\nexport type Clearance =\n | number\n | \"untrusted\"\n | \"external\"\n | \"partner\"\n | \"internal\"\n | \"privileged\"\n | \"system\";\n\nexport type SessionInput = {\n /** Capability map. Optional when `tools` is set. Issuer sessions may omit it. */\n readonly allow?: SessionAllow;\n /** Wrapped tools from `tenuo.tool()`. Their `allow` is minted into the session. */\n readonly tools?: readonly object[];\n readonly ttlSeconds?: number;\n readonly requireApproval?: RequireApproval;\n /**\n * Issue to another agent's key instead of a fresh local holder. The\n * returned session cannot authorize here (it has no holder secret); send\n * `toWire()` to that agent, which imports it with `sessionFromWire()`.\n */\n readonly holder?: PublicKeyHandle;\n /**\n * How many times this authority may be delegated below the root.\n * `0` makes the session terminal. Omit for the protocol maximum.\n * Delegation can lower this ceiling and never raise it.\n */\n readonly maxDepth?: number;\n /**\n * `\"execution\"` (default) can call tools. `\"issuer\"` cannot call tools; its\n * holder can mint execution sessions with `tenuo.issue()` for the tools in\n * `issuableTools`, within `constraintBounds`, without the root key.\n */\n readonly kind?: \"execution\" | \"issuer\";\n readonly clearance?: Clearance;\n /** Free-form task correlation id. Inherited unchanged through delegation. */\n readonly sessionId?: string;\n /** Free-form agent label. Delegation may change it. */\n readonly agentId?: string;\n /** Issuer sessions only. */\n readonly issuableTools?: readonly string[];\n /** Issuer sessions only: ceiling on the constraints of anything issued, by field. */\n readonly constraintBounds?: AllowPolicy;\n /** Issuer sessions only: how deep issued sessions may themselves delegate. */\n readonly maxIssueDepth?: number;\n};\n\n/** Options for `tenuo.narrow()`. All optional; the default keeps the holder. */\nexport type NarrowOptions = {\n /**\n * Bind the child to another agent's key. This is delegation: the current\n * holder signs, the child belongs to `holder`, and the returned session\n * cannot authorize here. Hand `toWire()` to that agent.\n */\n readonly holder?: PublicKeyHandle;\n /** Child lifetime. Clamped to what the parent has left. */\n readonly ttlSeconds?: number;\n /** The child's holder cannot delegate further. */\n readonly terminal?: boolean;\n /** Lower the delegation ceiling. Cannot exceed the parent's. */\n readonly maxDepth?: number;\n /** Lower the clearance. Cannot exceed the parent's. */\n readonly clearance?: Clearance;\n readonly agentId?: string;\n /** Approvers can only be added. */\n readonly addApprovers?: readonly PublicKeyHandle[];\n /** The threshold can only go up. */\n readonly minApprovals?: number;\n};\n\n/** Options for `tenuo.issue()`: an execution session minted from an issuer session. */\nexport type IssueInput = {\n readonly allow: SessionAllow;\n /** The distinct agent that will use it. Issuer/holder separation is enforced. */\n readonly holder: PublicKeyHandle;\n readonly ttlSeconds?: number;\n readonly maxDepth?: number;\n readonly clearance?: Clearance;\n readonly sessionId?: string;\n readonly agentId?: string;\n /** Approval policy for the issued execution session. Defaults to gating every issued tool. */\n readonly requireApproval?: RequireApproval;\n};\n\n/** Public view of a session's leaf. Never includes the holder secret. */\nexport type SessionInfo = {\n readonly kind: \"execution\" | \"issuer\";\n /** Hex public key the leaf is bound to. */\n readonly holderPublicKey: string;\n /** Hex public key that signed the root of the chain. */\n readonly rootPublicKey: string;\n /** 0 for a root session, +1 per delegation. */\n readonly depth: number;\n /** Delegation ceiling in force for this leaf. */\n readonly maxDepth: number;\n /** True when `depth >= maxDepth`: cannot be narrowed further. */\n readonly terminal: boolean;\n /** Unix seconds. */\n readonly expiresAt: number;\n readonly tools: readonly string[];\n /** Warrant ids, root first. */\n readonly warrantIds: readonly string[];\n /**\n * True when this process holds the leaf's holder secret. False for a\n * session issued or delegated to another agent: `toWire()` works,\n * `execute` and `narrow` do not.\n */\n readonly canAuthorize: boolean;\n readonly clearance?: number;\n readonly sessionId?: string;\n readonly agentId?: string;\n readonly issuableTools?: readonly string[];\n readonly maxIssueDepth?: number;\n readonly requiredApprovers?: readonly string[];\n readonly minApprovals?: number;\n readonly approvalGatedTools: readonly string[];\n};\n\n/** One constrained argument in an `explain()` result. */\nexport type ExplainedField = {\n readonly field: string;\n /** Core constraint type name, e.g. `\"Subpath\"`, `\"Range\"`. */\n readonly kind: string;\n /** The constraint as core serializes it. */\n readonly constraint: unknown;\n /** Absent when the argument was not supplied. */\n readonly value?: unknown;\n readonly satisfied: boolean;\n /** Stable machine-readable diagnostic, when the core can identify one. */\n readonly reasonCode?: string;\n readonly reason?: string;\n};\n\n/** What a session would decide for `tool(args)`, field by field. No proof-of-possession involved. */\nexport type Explanation = {\n readonly tool: string;\n readonly kind: \"execution\" | \"issuer\";\n readonly outcome: \"allow\" | \"deny\";\n readonly code?: TenuoErrorCode;\n readonly field?: string;\n readonly message?: string;\n readonly toolGranted: boolean;\n readonly fields: readonly ExplainedField[];\n /** Arguments the session does not name. Zero-trust policies reject these. */\n readonly unknownFields: readonly string[];\n /** Constrained arguments the call did not supply. */\n readonly missingFields: readonly string[];\n readonly expired: boolean;\n readonly expiresAt: number;\n readonly chainValid: boolean;\n readonly chainError?: TenuoErrorCode;\n};\n\nexport type DevRoot = {\n readonly kind: \"dev-root\";\n /**\n * Required when `NODE_ENV` is unset or is not `development` / `test`.\n * Unset `NODE_ENV` is not treated as development.\n */\n readonly allowInProduction?: boolean;\n};\n\n/** A stable issuer secret: this process is a control plane. */\nexport type IssuerKey = {\n readonly kind: \"issuer-key\";\n readonly secret: Uint8Array;\n};\n\nexport type PublicKeyHandle = {\n readonly kind: \"public-key\";\n readonly source: \"env\" | \"hex\" | \"bytes\";\n readonly hex: string;\n};\n\nexport type WarrantPart = {\n readonly payload_hex: string;\n readonly signature_hex: string;\n};\n\nexport type SessionFromWireInput = {\n readonly warrant: string | readonly string[] | readonly WarrantPart[];\n readonly holderKey: Uint8Array;\n};\n\n/** Field-level (`{ path: under(\"/data\") }`) or per-capability (`{ read_file: { path: ... } }`). */\nexport type NarrowInput = AllowPolicy | SessionAllow;\n\nexport type CreateTenuoOptions = {\n readonly trustedRoots?: readonly PublicKeyHandle[];\n /**\n * `devRoot()` for development; an `issuerKey*` for a control plane that\n * mints with a stable key; a public key for a verifier. An issuer key\n * trusts itself plus `trustedRoots`.\n */\n readonly root?: DevRoot | IssuerKey | PublicKeyHandle;\n /** Published SignedRevocationList (hex or standard base64). Verified against a trusted root. */\n readonly revocationList?: string | Uint8Array;\n /** 32-byte holder seed used to sign verifier receipts. Runtime supplies this. */\n readonly receiptSigner?: Uint8Array;\n};\n\nexport type ApprovalRequestSummary = {\n readonly tool: string;\n readonly required: number;\n readonly received: number;\n};\n\nexport type Decision =\n | { readonly outcome: \"allow\"; readonly args: Readonly<Record<string, unknown>> }\n | { readonly outcome: \"deny\"; readonly code: TenuoErrorCode; readonly field?: string }\n | { readonly outcome: \"approval_required\"; readonly request: ApprovalRequestSummary };\n\n// ---------------------------------------------------------------------------\n// Revocation and receipts\n// ---------------------------------------------------------------------------\n\nexport type RevocationListInput = {\n readonly revoke: readonly string[];\n /** Monotonic; verifiers refuse an older version. Default 1. */\n readonly version?: number;\n};\n\nexport type RevocationListInfo = {\n readonly version: number;\n readonly issuedAt: number;\n readonly issuerPublicKey: string;\n readonly revokedIds: readonly string[];\n readonly signatureValid: boolean;\n};\n\n/** Signature authenticity of a receipt. Not authorization. */\nexport type ReceiptInfo = {\n readonly authentic: true;\n /** Hex key the receipt is signed under — resolve against your own authorizer set. */\n readonly signerKey: string;\n readonly outcome: \"allow\" | \"deny\";\n readonly action: string;\n readonly decisionCode?: string;\n readonly requestId: string;\n readonly srlVersion?: number;\n readonly srlHash?: string;\n readonly requestHash?: string;\n readonly policyDefinitionHash?: string;\n readonly prevReceiptHash?: string;\n readonly trustedRootsHash?: string;\n};\n\n/** Root-anchored receipt check: the embedded chain against trusted roots at decision time. */\nexport type ReceiptChainInfo = {\n readonly signerKey: string;\n readonly outcome: \"allow\" | \"deny\";\n readonly decisionCode?: string;\n readonly timestamp: number;\n readonly chainValid: boolean;\n readonly chainError?: string;\n readonly corroboratesDenial?: boolean;\n readonly rootIssuer?: string;\n readonly leafHolder?: string;\n};\n\n// ---------------------------------------------------------------------------\n// Presenting authority across any boundary\n// ---------------------------------------------------------------------------\n\n/** Warrant chain plus proof-of-possession for one call. Transport-agnostic. */\nexport type PresentedCall = {\n readonly warrant: string;\n readonly signature: string;\n readonly approvals?: readonly string[];\n};\n\nexport interface Session {\n readonly [Symbol.toStringTag]: \"TenuoSession\";\n /** Warrant tokens, root first. Does not include the holder secret. */\n toWire(): readonly string[];\n /** SHA-256 of `(warrant_id, tool, canonical args)`. App-level idempotency, not PoP. */\n dedupKey(tool: string, args: Readonly<Record<string, unknown>>): string;\n /** Holder public key, depth, ceiling, lifetime, tools. Never the secret. */\n inspect(): SessionInfo;\n /**\n * Receipt helpers below are required for `createTenuo.runtime({ receipts:\n * \"collect\" })`. Implementers that are not runtime sessions can return\n * empty snapshots and `0` from acknowledge.\n */\n /**\n * Receipts collected for this session and not yet drained. Empty when the\n * session was not created by a Runtime with `receipts: \"collect\"`.\n */\n peekReceipts(): readonly string[];\n /**\n * Snapshot of collected receipts. Same as `peekReceipts`; nothing is removed\n * until `acknowledgeReceipts`.\n */\n drainReceipts(): readonly string[];\n /** Remove the first `count` pending receipts. */\n acknowledgeReceipts(count: number): number;\n}\n\nexport interface Tenuo {\n /**\n * Wrap any `{ execute }` tool (Vercel AI SDK, Mastra, plain object).\n * `parameters` / Zod stay on the inner tool and are never treated as authority.\n */\n tool<T extends { execute: (args: never) => unknown }>(\n inner: T,\n policy: ToolPolicy<Parameters<T[\"execute\"]>[0]>,\n ): ProtectedTool<T>;\n session(input: SessionInput): Session;\n /** Import a warrant minted elsewhere (Rust / Python / another process). */\n sessionFromWire(input: SessionFromWireInput): Session;\n withSession<R>(session: Session, fn: () => R): R;\n /**\n * Child session with less authority. Without options the same holder keeps\n * it; with `options.holder` it is delegated to another agent's key. Core\n * rejects any child that is not within its parent before a token exists.\n */\n narrow(session: Session, allow: NarrowInput, options?: NarrowOptions): Session;\n /**\n * Mint an execution session from an issuer session, signed by the issuer\n * session's holder. Core checks tools against `issuableTools`, constraints\n * against `constraintBounds`, clearance, and issue depth. No root key.\n */\n issue(issuer: Session, input: IssueInput): Session;\n /**\n * Public key of the local issuer (dev root or issuer key). Other processes\n * put it in `trustedRoots` to accept warrants this context mints.\n */\n issuerPublicKey(): PublicKeyHandle;\n /** What the session would decide for `tool(args)`, field by field. Never runs the tool. */\n explain(session: Session, tool: string, args: Readonly<Record<string, unknown>>): Explanation;\n /** Everything an approval service needs to present `tool(args)` to a human. */\n approvalRequest(session: Session, tool: string, args: Readonly<Record<string, unknown>>): ApprovalRequest;\n /** Holder-signed proof that this session is the one asking for `tool(args)`. */\n attestApprovalRequest(\n session: Session,\n tool: string,\n args: Readonly<Record<string, unknown>>,\n ): ApprovalContextAttestation;\n /** Authorize locally, then produce warrant + proof-of-possession for another boundary to verify. */\n present(\n session: Session,\n tool: string,\n args: Readonly<Record<string, unknown>>,\n options?: McpAttachOptions,\n ): PresentedCall;\n /** Verify a presented call at any boundary. Resolves with the authorized arguments; the tool must not run otherwise. */\n verify(\n presented: PresentedCall,\n tool: string,\n args: Readonly<Record<string, unknown>>,\n options?: McpVerifyOptions,\n ): Promise<Readonly<Record<string, unknown>>>;\n /** Sign a revocation list with this context's issuer key. Load it with `revoke()` where this issuer is trusted. */\n revocationList(input: RevocationListInput): string;\n /** Load a published SignedRevocationList. Rust verifies the issuer against trusted roots. */\n revoke(list: string | Uint8Array): void;\n /** MCP `_meta.tenuo` attach / verify. No MCP SDK dependency. */\n readonly mcp: TenuoMcp;\n ready(): void;\n}\n\n/** Wire envelope Python and TypeScript both read from `params._meta`. */\nexport type TenuoMcpMeta = {\n readonly tenuo: PresentedCall;\n};\n\nexport type McpAttachOptions = {\n readonly approvals?: readonly (string | Uint8Array)[];\n readonly onReceipt?: (receipt: string) => void | Promise<void>;\n /**\n * Correlation handle written to the receipt. Use whatever id the host\n * already has — a JSON-RPC id, a trace or span id — so a receipt can be\n * matched against your own logs. Not an identity: nothing enforces\n * uniqueness, and distinguishing repeated calls is the receipt chain's job.\n */\n readonly requestId?: string;\n};\n\n/** Host ceiling and optional receipt hook on `mcp.handler()`. */\nexport type McpHandlerPolicy = {\n readonly allow?: AllowPolicy;\n readonly onReceipt?: (receipt: string) => void | Promise<void>;\n readonly nonceStore?: NonceStore;\n /**\n * Isolated. Called when `nonceStore.checkAndRecord` throws or rejects.\n * The client only ever sees \"Replay store unavailable\".\n */\n readonly onNonceStoreError?: (error: unknown) => void | Promise<void>;\n};\n\nexport type McpVerifyOptions = {\n readonly allow?: AllowPolicy;\n readonly onReceipt?: (receipt: string) => void | Promise<void>;\n /**\n * Opt-in exact-PoP replay check. `checkAndRecord` may return a Promise\n * (Redis). A rejected Promise fails closed. In-memory stores do not work\n * across processes. PoP v1 is otherwise replayable in-window, including\n * envelopes that already carry approvals.\n */\n readonly nonceStore?: NonceStore;\n /**\n * Isolated. Called when `nonceStore.checkAndRecord` throws or rejects.\n * The client only ever sees \"Replay store unavailable\".\n */\n readonly onNonceStoreError?: (error: unknown) => void | Promise<void>;\n /**\n * Correlation handle written to the receipt. Use whatever id the host\n * already has — a JSON-RPC id, a trace or span id — so a receipt can be\n * matched against your own logs. Not an identity: nothing enforces\n * uniqueness, and distinguishing repeated calls is the receipt chain's job.\n */\n readonly requestId?: string;\n};\n\n/**\n * Returns true if the PoP is fresh and recorded; false if this exact token\n * was already consumed. Async stores (Redis) return `Promise<boolean>`.\n * `verify()` / handlers await the result. Never return a Promise from a\n * store that is only consulted synchronously — that used to fail open.\n */\nexport type NonceStore = {\n checkAndRecord(popSignature: string): boolean | Promise<boolean>;\n};\n\nexport type McpCallParams = {\n readonly name: string;\n readonly arguments: Readonly<Record<string, unknown>>;\n readonly _meta: TenuoMcpMeta;\n};\n\nexport type McpJsonRpcError = {\n readonly code: -32602 | -32001 | -32002;\n readonly message: string;\n readonly data?: { readonly tenuo?: { readonly code: TenuoErrorCode } };\n};\n\nexport interface TenuoMcp {\n /** Local authorize, then put warrant + PoP on `_meta.tenuo`. */\n attach(\n session: Session,\n name: string,\n args: Readonly<Record<string, unknown>>,\n options?: McpAttachOptions,\n ): McpCallParams;\n /**\n * Server path. Verifies a presented warrant + PoP. Tool handler must not\n * run unless this returns.\n */\n verify(\n name: string,\n args: Readonly<Record<string, unknown>>,\n meta: unknown,\n options?: McpVerifyOptions,\n ): Promise<Readonly<Record<string, unknown>>>;\n /** Wrap a handler: verify from `extra._meta` / `extra.meta`, then execute. */\n handler<TArgs extends Record<string, unknown>, TResult>(\n name: string,\n execute: (args: TArgs) => TResult | Promise<TResult>,\n ): (\n args: TArgs,\n extra?: { readonly _meta?: unknown; readonly meta?: unknown },\n ) => Promise<TResult>;\n handler<TArgs extends Record<string, unknown>, TResult>(\n name: string,\n policy: McpHandlerPolicy,\n execute: (args: TArgs) => TResult | Promise<TResult>,\n ): (\n args: TArgs,\n extra?: { readonly _meta?: unknown; readonly meta?: unknown },\n ) => Promise<TResult>;\n jsonRpcError(error: unknown): McpJsonRpcError;\n}\n"]}
@@ -0,0 +1,8 @@
1
+ {
2
+ "package": "@tenuo/core",
3
+ "version": "0.3.1-beta.0",
4
+ "sourceCommit": "beacaf0b92abb238f1df39ee97479a988f63a339",
5
+ "sourceClean": false,
6
+ "wasmSha256": "02b056ba107079a1e9ee648d03cf28b6e1d04baf62f0ac3688347c307c25c7b0",
7
+ "wasmMatchesCommit": false
8
+ }
package/dist/client.js CHANGED
@@ -439,6 +439,9 @@ class TenuoClient {
439
439
  if (f.reason !== undefined) {
440
440
  field.reason = f.reason;
441
441
  }
442
+ if (f.reason_code !== undefined) {
443
+ field.reasonCode = f.reason_code;
444
+ }
442
445
  return field;
443
446
  }),
444
447
  unknownFields: [...raw.unknown_fields],
@@ -676,11 +679,14 @@ function approvalRequestFromWasm(raw) {
676
679
  };
677
680
  }
678
681
  function explainDeny(message, field) {
679
- if (!message.includes("unknown field not allowed")) {
680
- return message;
682
+ if (message.includes("unknown field not allowed")) {
683
+ const named = field !== undefined && field.length > 0 ? `'${field}'` : "this argument";
684
+ return `${message}. Zero-trust: name ${named} in allow with the tightest constraint that admits the real values (wildcard() only when the value does not change what the tool does), or remove ${named} from the call if the tool does not act on it; constrained policies reject omitted fields.`;
685
+ }
686
+ if (message.includes("value does not match constraint")) {
687
+ return `${message}. Use tenuo.explain(session, tool, args) locally for field-level diagnostics.`;
681
688
  }
682
- const named = field !== undefined && field.length > 0 ? `'${field}'` : "this argument";
683
- return `${message}. Zero-trust: name ${named} in allow (for example ${named}: pattern("*")), or remove it from the call; constrained policies reject omitted fields.`;
689
+ return message;
684
690
  }
685
691
  function forwardExecuteOptions(callOptions) {
686
692
  if (callOptions === null || typeof callOptions !== "object") {
@@ -1 +1 @@
1
- {"version":3,"file":"client.js","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AACrD,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAkC1C,OAAO,EAAE,iBAAiB,EAAE,MAAM,cAAc,CAAC;AACjD,OAAO,EAAE,gBAAgB,EAAE,eAAe,EAAE,MAAM,eAAe,CAAC;AAClE,OAAO,EAAE,SAAS,EAAE,WAAW,EAAE,eAAe,EAAe,MAAM,UAAU,CAAC;AAChF,OAAO,EAAE,cAAc,EAAE,mBAAmB,EAAE,uBAAuB,EAAE,MAAM,eAAe,CAAC;AAC7F,OAAO,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAC7C,OAAO,EAAE,wBAAwB,EAAE,qBAAqB,EAAE,uBAAuB,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACnH,OAAO,EAAE,OAAO,EAAE,SAAS,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AACjE,OAAO,EACL,gBAAgB,EAChB,mBAAmB,EACnB,qBAAqB,EACrB,sBAAsB,EACtB,qBAAqB,EACrB,QAAQ,EACR,cAAc,EACd,yBAAyB,GAS1B,MAAM,WAAW,CAAC;AAEnB,MAAM,cAAc,GAAG,IAAI,iBAAiB,EAAW,CAAC;AACxD,MAAM,YAAY,GAAG,IAAI,OAAO,EAAsD,CAAC;AACvF,MAAM,aAAa,GAAG,IAAI,OAAO,EAAU,CAAC;AAE5C,MAAM,eAAe,GAAG,IAAI,GAAG,CAAC,CAAC,WA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,CAAC;IAC7D,CAAC;IACD,QAAQ,EAAE,CAAC;IACX,OAAO,IAAI,WAAW,CAAC,OAAO,CAAC,CAAC;AAClC,CAAC;AAED,MAAM,CAAC,MAAM,WAAW,GAyBpB,MAAM,CAAC,MAAM,CAAC,eAAe,EAAE;IACjC,OAAO;IACP,gBAAgB;IAChB,gBAAgB;IAChB,kBAAkB;IAClB,gBAAgB;IAChB,gBAAgB;IAChB,iBAAiB;IACjB,iBAAiB;IACjB,sBAAsB;IACtB,gBAAgB;IAChB,gBAAgB;IAChB,kBAAkB;IAClB,YAAY;IACZ,eAAe;IACf,kBAAkB;IAClB,qBAAqB;IACrB,aAAa;IACb,kBAAkB;IAClB,6BAA6B;IAC7B,6BAA6B;IAC7B,iBAAiB;IACjB,QAAQ,EAAE,eAAe;IACzB,gBAAgB;IAChB,OAAO,EAAE,CAAC,OAA4C,EAAE,EAAE,CAAC,aAAa,CAAC,eAAe,EAAE,OAAO,CAAC;CACnG,CAAC,CAAC","sourcesContent":["import { AsyncLocalStorage } from \"node:async_hooks\";\nimport { randomBytes } from \"node:crypto\";\nimport type {\n AllowPolicy,\n ApprovalContextAttestation,\n ApprovalInfo,\n ApprovalRequest,\n Clearance,\n ControlPlaneApprovalRequestV1,\n ControlPlaneApprovalResponseV1,\n CreateTenuoOptions,\n DevRoot,\n Explanation,\n IssueInput,\n IssuerKey,\n McpAttachOptions,\n McpVerifyOptions,\n NarrowInput,\n NarrowOptions,\n PresentedCall,\n ProtectedTool,\n PublicKeyHandle,\n ReceiptChainInfo,\n ReceiptInfo,\n RequireApproval,\n RevocationListInfo,\n RevocationListInput,\n SessionFromWireInput,\n SessionInput,\n SignApprovalOptions,\n Tenuo,\n TenuoErrorCode,\n TenuoMcp,\n ToolPolicy,\n} from \"./api.ts\";\nimport { parseConnectToken } from \"./connect.ts\";\nimport { generateIdentity, identityFromKey } from \"./identity.ts\";\nimport { createMcp, presentCall, verifyPresented, type Decide } from \"./mcp.ts\";\nimport { collectReceipt, emitIsolatedReceipt, inheritSessionCollector } from \"./receipts.ts\";\nimport { createRuntime } from \"./runtime.ts\";\nimport { AuthorizationDeniedError, ApprovalRequiredError, TenuoConfigurationError, TenuoError } from \"./errors.ts\";\nimport { Session, isSession, nativeSession } from \"./session.ts\";\nimport {\n createDevContext,\n createIssuerContext,\n createVerifierContext,\n importSessionFromChain,\n importSessionFromWire,\n loadWasm,\n protocolLimits,\n publicKeyHexFromHolderKey,\n type WasmApprovalRequest,\n type WasmAttestation,\n type WasmContext,\n type WasmExplain,\n type WasmIssueOptions,\n type WasmMintOptions,\n type WasmNarrowOptions,\n type WasmRequireApproval,\n} from \"./wasm.ts\";\n\nconst currentSession = new AsyncLocalStorage<Session>();\nconst toolPolicies = new WeakMap<object, { capability: string; allow: AllowPolicy }>();\nconst wrappedInners = new WeakSet<object>();\n\nconst CLEARANCE_NAMES = new Set([\"untrusted\", \"external\", \"partner\", \"internal\", \"privileged\", \"system\"]);\n\nfunction nodeEnv(): string | undefined {\n if (typeof process === \"undefined\") {\n return undefined;\n }\n return process.env.NODE_ENV;\n}\n\nfunction allowDev(): boolean {\n if (typeof process === \"undefined\") {\n return false;\n }\n return process.env.TENUO_ALLOW_DEV === \"1\";\n}\n\nexport function devRoot(options?: { readonly allowInProduction?: boolean }): DevRoot {\n const root: DevRoot = {\n kind: \"dev-root\",\n ...(options?.allowInProduction === true ? { allowInProduction: true } : {}),\n };\n if (!devRootAllowed(root)) {\n throw new TenuoConfigurationError(devRootBlockedMessage());\n }\n return root;\n}\n\nfunction devRootAllowed(root: DevRoot): boolean {\n if (root.allowInProduction === true || allowDev()) {\n return true;\n }\n const env = nodeEnv();\n return env === \"development\" || env === \"test\";\n}\n\nfunction devRootBlockedMessage(): string {\n return \"createTenuo.devRoot() is for development. Set NODE_ENV=development or test, pass devRoot({ allowInProduction: true }), or TENUO_ALLOW_DEV=1. Unset NODE_ENV is not treated as development.\";\n}\n\nfunction normalizeHex(value: string): string {\n const hex = value.trim().toLowerCase().replace(/^0x/, \"\");\n if (!/^[0-9a-f]{64}$/.test(hex)) {\n throw new TenuoConfigurationError(\n \"Trusted root must be a 32-byte hex public key (64 hex characters)\",\n );\n }\n return hex;\n}\n\nfunction envValue(name: string, what: string): string {\n if (name.length === 0) {\n throw new TenuoConfigurationError(`${what} requires an environment variable name`);\n }\n if (typeof process === \"undefined\") {\n throw new TenuoConfigurationError(\n `Environment variable ${name} is not available. Tenuo fails closed without a ${what}.`,\n );\n }\n const value = process.env[name];\n if (value === undefined || value.length === 0) {\n throw new TenuoConfigurationError(\n `Environment variable ${name} is not set or empty. Tenuo fails closed without a ${what}.`,\n );\n }\n return value;\n}\n\nexport function publicKeyFromEnv(name: string): PublicKeyHandle {\n return { kind: \"public-key\", source: \"env\", hex: normalizeHex(envValue(name, \"trusted root\")) };\n}\n\nexport function publicKeyFromHex(hex: string): PublicKeyHandle {\n return { kind: \"public-key\", source: \"hex\", hex: normalizeHex(hex) };\n}\n\nexport function publicKeyFromBytes(bytes: Uint8Array): PublicKeyHandle {\n if (bytes.length !== 32) {\n throw new TenuoConfigurationError(\"publicKeyFromBytes() requires a 32-byte public key\");\n }\n return { kind: \"public-key\", source: \"bytes\", hex: bytesToHex(bytes) };\n}\n\nfunction normalizeSecretHex(value: string, what: string): string {\n const hex = value.trim().toLowerCase().replace(/^0x/, \"\");\n if (!/^[0-9a-f]{64}$/.test(hex)) {\n throw new TenuoConfigurationError(`${what} must be a 32-byte hex secret (64 hex characters)`);\n }\n return hex;\n}\n\nfunction hexToBytes(hex: string): Uint8Array {\n const bytes = new Uint8Array(hex.length / 2);\n for (let i = 0; i < bytes.length; i += 1) {\n bytes[i] = Number.parseInt(hex.slice(i * 2, i * 2 + 2), 16);\n }\n return bytes;\n}\n\nfunction bytesToHex(bytes: Uint8Array): string {\n return Array.from(bytes, (b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\nexport function holderKeyFromEnv(name: string): Uint8Array {\n return hexToBytes(normalizeSecretHex(envValue(name, \"holder key\"), \"Holder key\"));\n}\n\nexport function holderKeyFromHex(hex: string): Uint8Array {\n return hexToBytes(normalizeSecretHex(hex, \"Holder key\"));\n}\n\n/**\n * A fresh 32-byte Ed25519 secret. One per agent, kept in that agent's\n * process; only its public key (see `publicKeyFromHolderKey`) travels.\n */\nexport function generateHolderKey(): Uint8Array {\n return new Uint8Array(randomBytes(32));\n}\n\n/** Same shape as a holder key. Named separately so a control plane's key reads as one. */\nexport function generateIssuerKey(): Uint8Array {\n return generateHolderKey();\n}\n\n/** The public half of a holder or issuer secret. */\nexport function publicKeyFromHolderKey(holderKey: Uint8Array): PublicKeyHandle {\n if (!(holderKey instanceof Uint8Array) || holderKey.length !== 32) {\n throw new TenuoConfigurationError(\"publicKeyFromHolderKey() requires a 32-byte holder key\");\n }\n loadWasm();\n return { kind: \"public-key\", source: \"bytes\", hex: publicKeyHexFromHolderKey(holderKey) };\n}\n\nconst MAX_WASM_U32 = 0xffff_ffff;\n\nfunction requireUint32(value: number, name: string, minimum = 0): number {\n if (!Number.isInteger(value) || value < minimum || value > MAX_WASM_U32) {\n throw new TenuoConfigurationError(\n `${name} must be an integer between ${minimum} and ${MAX_WASM_U32}`,\n );\n }\n return value;\n}\n\n/** Stable control-plane key from the environment. This process becomes an issuer. */\nexport function issuerKeyFromEnv(name: string): IssuerKey {\n return { kind: \"issuer-key\", secret: hexToBytes(normalizeSecretHex(envValue(name, \"issuer key\"), \"Issuer key\")) };\n}\n\nexport function issuerKeyFromHex(hex: string): IssuerKey {\n return { kind: \"issuer-key\", secret: hexToBytes(normalizeSecretHex(hex, \"Issuer key\")) };\n}\n\nexport function issuerKeyFromBytes(secret: Uint8Array): IssuerKey {\n if (!(secret instanceof Uint8Array) || secret.length !== 32) {\n throw new TenuoConfigurationError(\"issuerKeyFromBytes() requires a 32-byte secret\");\n }\n return { kind: \"issuer-key\", secret: new Uint8Array(secret) };\n}\n\nfunction requireDepth(value: number, name: string): number {\n requireUint32(value, name);\n const maximum = protocolLimits().max_delegation_depth;\n if (value > maximum) {\n throw new TenuoConfigurationError(\n `${name} ${value} exceeds the protocol maximum of ${maximum}`,\n );\n }\n return value;\n}\n\nfunction requireTtl(value: number, name: string, minimum = 0): number {\n requireUint32(value, name, minimum);\n const maximum = protocolLimits().max_warrant_ttl_seconds;\n if (value > maximum) {\n throw new TenuoConfigurationError(\n `${name} ${value} exceeds the protocol maximum of ${maximum}`,\n );\n }\n return value;\n}\n\nfunction requirePublicKey(value: unknown, name: string): PublicKeyHandle {\n if (\n value === null ||\n typeof value !== \"object\" ||\n (value as { kind?: unknown }).kind !== \"public-key\" ||\n typeof (value as { hex?: unknown }).hex !== \"string\"\n ) {\n throw new TenuoConfigurationError(\n `${name} must be a public key handle (createTenuo.publicKeyFromHolderKey / publicKeyFromHex / publicKeyFromEnv)`,\n );\n }\n return value as PublicKeyHandle;\n}\n\nfunction clearanceJson(value: Clearance, name: string): number | string {\n if (typeof value === \"number\") {\n if (!Number.isInteger(value) || value < 0 || value > 255) {\n throw new TenuoConfigurationError(`${name} must be an integer 0-255 or a level name`);\n }\n return value;\n }\n if (typeof value === \"string\" && CLEARANCE_NAMES.has(value)) {\n return value;\n }\n throw new TenuoConfigurationError(\n `${name} must be one of ${[...CLEARANCE_NAMES].join(\", \")} or an integer 0-255`,\n );\n}\n\nfunction rootHexes(options: CreateTenuoOptions): string[] {\n const handles: PublicKeyHandle[] = [];\n if (options.root !== undefined && options.root.kind === \"public-key\") {\n handles.push(options.root);\n }\n for (const root of options.trustedRoots ?? []) {\n handles.push(root);\n }\n return handles.map((h) => h.hex);\n}\n\nfunction hasTrustAnchor(options: CreateTenuoOptions): boolean {\n if (options.root !== undefined) {\n return true;\n }\n return (options.trustedRoots?.length ?? 0) > 0;\n}\n\nfunction capabilityName(inner: object, policy: Pick<ToolPolicy, \"capability\">): string {\n if (policy.capability !== undefined && policy.capability.length > 0) {\n return policy.capability;\n }\n const named = inner as { name?: unknown; id?: unknown };\n if (typeof named.name === \"string\" && named.name.length > 0) {\n return named.name;\n }\n if (typeof named.id === \"string\" && named.id.length > 0) {\n return named.id;\n }\n throw new TenuoConfigurationError(\n \"tenuo.tool() needs a capability name (policy.capability, or tool.name / tool.id)\",\n );\n}\n\nclass TenuoClient implements Tenuo {\n private readonly context: WasmContext;\n private readonly canMint: boolean;\n readonly mcp: TenuoMcp;\n private readonly decide: Decide;\n\n constructor(options: CreateTenuoOptions) {\n if (options.root?.kind === \"dev-root\") {\n this.context = createDevContext(options.receiptSigner);\n this.canMint = true;\n } else if (options.root?.kind === \"issuer-key\") {\n if (!(options.root.secret instanceof Uint8Array) || options.root.secret.length !== 32) {\n throw new TenuoConfigurationError(\"root: issuer key must be a 32-byte secret\");\n }\n this.context = createIssuerContext(\n options.root.secret,\n rootHexes(options),\n options.receiptSigner,\n );\n this.canMint = true;\n } else {\n this.context = createVerifierContext(\n rootHexes(options),\n undefined,\n options.receiptSigner,\n );\n this.canMint = false;\n }\n if (options.revocationList !== undefined) {\n this.context.loadRevocationList(normalizeWireBytes(options.revocationList));\n }\n this.decide = (decision, tool, native, args) => {\n this.applyDecision(decision, tool, native, args);\n };\n this.mcp = createMcp(this.context, this.decide, this);\n }\n\n private applyDecision(\n decision: { outcome: string; code?: string; field?: string; message?: string; tool?: string; required?: number; received?: number },\n tool: string,\n native?: object,\n args?: Record<string, unknown>,\n ): void {\n if (decision.outcome === \"allow\") {\n return;\n }\n if (decision.outcome === \"approval_required\") {\n let request: ApprovalRequest | undefined;\n if (native !== undefined && args !== undefined) {\n try {\n request = approvalRequestFromWasm(this.context.approvalRequest(native, tool, args));\n } catch {\n request = undefined;\n }\n }\n throw new ApprovalRequiredError(\n decision.tool ?? tool,\n decision.required ?? 1,\n decision.received ?? 0,\n decision.message,\n request,\n );\n }\n throw new AuthorizationDeniedError(\n (decision.code as TenuoErrorCode | undefined) ?? \"TENUO_TOOL_NOT_AUTHORIZED\",\n explainDeny(decision.message ?? \"Authorization denied\", decision.field),\n decision.field,\n );\n }\n\n tool<T extends { execute: (args: never) => unknown }>(\n inner: T,\n policy: ToolPolicy<Parameters<T[\"execute\"]>[0]>,\n ): ProtectedTool<T> {\n if (toolPolicies.has(inner) || wrappedInners.has(inner)) {\n throw new TenuoConfigurationError(\"tenuo.tool() already wrapped this tool\");\n }\n const capability = capabilityName(inner, policy);\n const original = inner.execute as (\n args: Record<string, unknown>,\n options?: unknown,\n ) => unknown;\n const execute = async (args: never, callOptions?: unknown) => {\n const session = resolveSession(callOptions);\n const native = nativeSession(session);\n const decision = this.context.authorize(\n native,\n capability,\n args,\n approvalsFrom(callOptions),\n policy.allow,\n requestIdFrom(callOptions),\n );\n emitReceipt(callOptions, decision.receipt, session, this);\n if (decision.outcome === \"allow\") {\n return original(plainArgs(decision.args), forwardExecuteOptions(callOptions));\n }\n this.applyDecision(decision, capability, native, plainArgs(args));\n throw new TenuoConfigurationError(\"unreachable: decision was neither allow nor deny\");\n };\n\n const wrapped = Object.assign(Object.create(Object.getPrototypeOf(inner)), inner, {\n execute,\n }) as ProtectedTool<T>;\n wrappedInners.add(inner);\n toolPolicies.set(wrapped, { capability, allow: { ...policy.allow } as AllowPolicy });\n return wrapped;\n }\n\n session(input: SessionInput): Session {\n const allow = collectSessionAllow(input);\n const kind = input.kind ?? \"execution\";\n if (kind !== \"execution\" && kind !== \"issuer\") {\n throw new TenuoConfigurationError('session().kind must be \"execution\" or \"issuer\"');\n }\n if (Object.keys(allow).length === 0 && kind === \"execution\") {\n throw new TenuoConfigurationError(\n \"tenuo.session() requires tools from tenuo.tool() or at least one capability in allow\",\n );\n }\n if (!this.canMint) {\n throw new TenuoConfigurationError(\n \"session() mints a warrant and needs a local issuer. Use createTenuo({ root: createTenuo.devRoot() }) or an issuer key.\",\n );\n }\n const options: WasmMintOptions = { kind, allow };\n if (input.ttlSeconds !== undefined) {\n options.ttlSeconds = requireTtl(input.ttlSeconds, \"session().ttlSeconds\");\n }\n if (input.holder !== undefined) {\n options.holder = requirePublicKey(input.holder, \"session().holder\").hex;\n }\n if (input.maxDepth !== undefined) {\n options.maxDepth = requireDepth(input.maxDepth, \"session().maxDepth\");\n }\n if (input.clearance !== undefined) {\n options.clearance = clearanceJson(input.clearance, \"session().clearance\");\n }\n if (input.sessionId !== undefined) {\n options.sessionId = requireLabel(input.sessionId, \"session().sessionId\");\n }\n if (input.agentId !== undefined) {\n options.agentId = requireLabel(input.agentId, \"session().agentId\");\n }\n if (input.requireApproval !== undefined) {\n options.requireApproval = requireApprovalJson(input.requireApproval);\n }\n if (input.issuableTools !== undefined) {\n options.issuableTools = [...input.issuableTools];\n }\n if (input.constraintBounds !== undefined) {\n options.constraintBounds = input.constraintBounds;\n }\n if (input.maxIssueDepth !== undefined) {\n options.maxIssueDepth = requireDepth(input.maxIssueDepth, \"session().maxIssueDepth\");\n }\n try {\n return new Session(this.context.mintExtended(options));\n } catch (error) {\n throw new TenuoConfigurationError(errorMessage(error));\n }\n }\n\n issue(issuer: Session, input: IssueInput): Session {\n if (!isSession(issuer)) {\n throw new TenuoConfigurationError(\"issue() requires a Tenuo Session, not a plain object\");\n }\n if (input === null || typeof input !== \"object\" || input.allow === undefined || Object.keys(input.allow).length === 0) {\n throw new TenuoConfigurationError(\"issue() requires at least one capability in allow\");\n }\n const options: WasmIssueOptions = {\n allow: input.allow,\n holder: requirePublicKey(input.holder, \"issue().holder\").hex,\n };\n if (input.ttlSeconds !== undefined) {\n options.ttlSeconds = requireTtl(input.ttlSeconds, \"issue().ttlSeconds\", 1);\n }\n if (input.maxDepth !== undefined) {\n options.maxDepth = requireDepth(input.maxDepth, \"issue().maxDepth\");\n }\n if (input.clearance !== undefined) {\n options.clearance = clearanceJson(input.clearance, \"issue().clearance\");\n }\n if (input.sessionId !== undefined) {\n options.sessionId = requireLabel(input.sessionId, \"issue().sessionId\");\n }\n if (input.agentId !== undefined) {\n options.agentId = requireLabel(input.agentId, \"issue().agentId\");\n }\n if (input.requireApproval !== undefined) {\n options.requireApproval = requireApprovalJson(input.requireApproval);\n }\n try {\n return new Session(this.context.issue(nativeSession(issuer), options));\n } catch (error) {\n throw chainError(error);\n }\n }\n\n issuerPublicKey(): PublicKeyHandle {\n if (!this.canMint) {\n throw new TenuoConfigurationError(\n \"issuerPublicKey() needs a local issuer. This context verifies against trustedRoots and does not mint.\",\n );\n }\n return { kind: \"public-key\", source: \"bytes\", hex: this.context.issuerPublicKey() };\n }\n\n sessionFromWire(input: SessionFromWireInput): Session {\n if (!(input.holderKey instanceof Uint8Array) || input.holderKey.length !== 32) {\n throw new TenuoConfigurationError(\"sessionFromWire() requires a 32-byte holderKey\");\n }\n if (typeof input.warrant === \"string\" && input.warrant.trim().length === 0) {\n throw new TenuoConfigurationError(\"sessionFromWire() requires a warrant\");\n }\n try {\n if (typeof input.warrant === \"string\") {\n return new Session(importSessionFromWire(input.warrant, input.holderKey));\n }\n if (input.warrant.length === 0) {\n throw new TenuoConfigurationError(\"sessionFromWire() requires a warrant\");\n }\n return new Session(importSessionFromChain([...input.warrant], input.holderKey));\n } catch (error) {\n throw importWireError(error);\n }\n }\n\n withSession<R>(session: Session, fn: () => R): R {\n if (!isSession(session)) {\n throw new TenuoConfigurationError(\"withSession() requires a Tenuo Session, not a plain object\");\n }\n return currentSession.run(session, fn);\n }\n\n narrow(session: Session, allow: NarrowInput, options?: NarrowOptions): Session {\n if (Object.keys(allow).length === 0) {\n throw new TenuoConfigurationError(\"tenuo.narrow() requires a non-empty allow policy\");\n }\n if (!isSession(session)) {\n throw new TenuoConfigurationError(\"narrow() requires a Tenuo Session, not a plain object\");\n }\n const native = options === undefined ? undefined : narrowOptionsJson(options);\n try {\n const child = new Session(this.context.narrow(nativeSession(session), allow, native));\n inheritSessionCollector(session, child);\n return child;\n } catch (error) {\n throw chainError(error);\n }\n }\n\n explain(session: Session, tool: string, args: Readonly<Record<string, unknown>>): Explanation {\n if (!isSession(session)) {\n throw new TenuoConfigurationError(\"explain() requires a Tenuo Session, not a plain object\");\n }\n let raw: WasmExplain;\n try {\n raw = this.context.explain(nativeSession(session), tool, args);\n } catch (error) {\n throw new TenuoConfigurationError(errorMessage(error));\n }\n const out: { -readonly [K in keyof Explanation]: Explanation[K] } = {\n tool: raw.tool,\n kind: raw.kind,\n outcome: raw.outcome,\n toolGranted: raw.tool_granted,\n fields: raw.fields.map((f) => {\n const field: { -readonly [K in keyof Explanation[\"fields\"][number]]: Explanation[\"fields\"][number][K] } = {\n field: f.field,\n kind: f.kind,\n constraint: f.constraint,\n satisfied: f.satisfied,\n };\n if (f.value !== undefined) {\n field.value = f.value;\n }\n if (f.reason !== undefined) {\n field.reason = f.reason;\n }\n return field;\n }),\n unknownFields: [...raw.unknown_fields],\n missingFields: [...raw.missing_fields],\n expired: raw.expired,\n expiresAt: raw.expires_at,\n chainValid: raw.chain_valid,\n };\n if (raw.code !== undefined) {\n out.code = raw.code;\n }\n if (raw.field !== undefined) {\n out.field = raw.field;\n }\n if (raw.message !== undefined) {\n out.message = raw.message;\n }\n if (raw.chain_error !== undefined) {\n out.chainError = raw.chain_error;\n }\n return out;\n }\n\n approvalRequest(session: Session, tool: string, args: Readonly<Record<string, unknown>>): ApprovalRequest {\n if (!isSession(session)) {\n throw new TenuoConfigurationError(\"approvalRequest() requires a Tenuo Session, not a plain object\");\n }\n try {\n return approvalRequestFromWasm(this.context.approvalRequest(nativeSession(session), tool, args));\n } catch (error) {\n throw new TenuoConfigurationError(errorMessage(error));\n }\n }\n\n attestApprovalRequest(\n session: Session,\n tool: string,\n args: Readonly<Record<string, unknown>>,\n ): ApprovalContextAttestation {\n if (!isSession(session)) {\n throw new TenuoConfigurationError(\"attestApprovalRequest() requires a Tenuo Session, not a plain object\");\n }\n let raw: WasmAttestation;\n try {\n raw = this.context.approvalContextAttestation(nativeSession(session), tool, args);\n } catch (error) {\n throw new TenuoConfigurationError(errorMessage(error));\n }\n return {\n version: raw.version,\n canonicalization: raw.canonicalization,\n warrantId: raw.warrant_id,\n tool: raw.tool,\n requestHash: raw.request_hash,\n holderKeyHex: raw.holder_key_hex,\n argsCanonicalCborB64: raw.args_canonical_cbor_b64,\n signerKeyHex: raw.signer_key_hex,\n signatureB64: raw.signature_b64,\n };\n }\n\n present(\n session: Session,\n tool: string,\n args: Readonly<Record<string, unknown>>,\n options?: McpAttachOptions,\n ): PresentedCall {\n if (!isSession(session)) {\n throw new TenuoConfigurationError(\"present() requires a Tenuo Session, not a plain object\");\n }\n return presentCall(this.context, this.decide, session, tool, args, options, \"present()\", this)\n .presented;\n }\n\n verify(\n presented: PresentedCall,\n tool: string,\n args: Readonly<Record<string, unknown>>,\n options?: McpVerifyOptions,\n ): Promise<Readonly<Record<string, unknown>>> {\n return verifyPresented(\n this.context,\n this.decide,\n presented,\n tool,\n args,\n options,\n \"verify()\",\n this,\n );\n }\n\n revocationList(input: RevocationListInput): string {\n if (!this.canMint) {\n throw new TenuoConfigurationError(\n \"revocationList() needs a local issuer key. Use createTenuo.signRevocationList() with an explicit secret, or an issuer-key root.\",\n );\n }\n const { ids, version } = revocationInput(input);\n try {\n return this.context.signRevocationListVersioned(ids, version);\n } catch (error) {\n throw new TenuoConfigurationError(errorMessage(error));\n }\n }\n\n revoke(list: string | Uint8Array): void {\n this.context.loadRevocationList(normalizeWireBytes(list));\n }\n\n ready(): void {\n loadWasm();\n }\n}\n\nfunction requireLabel(value: string, name: string): string {\n if (typeof value !== \"string\" || value.trim().length === 0) {\n throw new TenuoConfigurationError(`${name} must be a non-empty string`);\n }\n return value;\n}\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\n/** Map a prefixed core message from narrow()/issue() to the matching error class. */\nfunction chainError(error: unknown): TenuoError {\n if (error instanceof TenuoError) {\n return error;\n }\n const message = explainChainFailure(errorMessage(error));\n for (const code of [\"TENUO_CHAIN_INVALID\", \"TENUO_DEPTH_EXCEEDED\", \"TENUO_WARRANT_EXPIRED\"] as const) {\n if (message.startsWith(code)) {\n return new AuthorizationDeniedError(code, message);\n }\n }\n return new TenuoConfigurationError(message);\n}\n\nfunction explainChainFailure(message: string): string {\n const tool = /tool '([^']+)' not in parent's tools/.exec(message)?.[1];\n if (tool !== undefined) {\n return `${message}. narrow() cannot add '${tool}': remove it or delegate from a parent that grants it.`;\n }\n if (\n message.includes(\"parent's allowed set\") ||\n message.includes(\"range expanded\") ||\n message.includes(\"would expand permissions\") ||\n message.includes(\"clearance cannot increase\")\n ) {\n return `${message}. narrow() only accepts a child policy that is equal to or stricter than its parent.`;\n }\n return message;\n}\n\nfunction revocationInput(input: RevocationListInput): { ids: string[]; version: number | undefined } {\n if (input === null || typeof input !== \"object\" || !Array.isArray(input.revoke)) {\n throw new TenuoConfigurationError(\"revocation list input must be { revoke: string[], version? }\");\n }\n const ids = input.revoke.filter((id): id is string => typeof id === \"string\" && id.length > 0);\n if (ids.length === 0 || ids.length !== input.revoke.length) {\n throw new TenuoConfigurationError(\"revoke must be a non-empty array of warrant ids\");\n }\n if (input.version !== undefined && (!Number.isInteger(input.version) || input.version < 1)) {\n throw new TenuoConfigurationError(\"revocation list version must be a positive integer\");\n }\n return { ids, version: input.version };\n}\n\nfunction plainArgs(value: unknown): Record<string, unknown> {\n if (value instanceof Map) {\n return Object.fromEntries(value);\n }\n if (value !== null && typeof value === \"object\" && !Array.isArray(value)) {\n return { ...(value as Record<string, unknown>) };\n }\n return {};\n}\n\nfunction requireApprovalJson(require: RequireApproval): WasmRequireApproval {\n if (require === null || typeof require !== \"object\") {\n throw new TenuoConfigurationError(\"requireApproval must be an object\");\n }\n if (!Array.isArray(require.approvers) || require.approvers.length === 0) {\n throw new TenuoConfigurationError(\"requireApproval.approvers must not be empty\");\n }\n if (!Number.isInteger(require.min) || require.min < 1) {\n throw new TenuoConfigurationError(\"requireApproval.min must be at least 1\");\n }\n const payload: WasmRequireApproval = {\n approvers: require.approvers.map((approver, i) => requirePublicKey(approver, `requireApproval.approvers[${i}]`).hex),\n min: require.min,\n };\n if (require.tools !== undefined) {\n payload.tools = [...require.tools];\n }\n if (require.gates !== undefined) {\n const gates: NonNullable<WasmRequireApproval[\"gates\"]> = {};\n for (const [tool, gate] of Object.entries(require.gates)) {\n const out: { message?: string; args?: Record<string, unknown> } = {};\n if (gate.message !== undefined) {\n out.message = gate.message;\n }\n if (gate.args !== undefined) {\n out.args = { ...gate.args };\n }\n gates[tool] = out;\n }\n payload.gates = gates;\n }\n return payload;\n}\n\nfunction narrowOptionsJson(options: NarrowOptions): WasmNarrowOptions {\n if (options === null || typeof options !== \"object\") {\n throw new TenuoConfigurationError(\"narrow() options must be an object\");\n }\n const known = [\"holder\", \"ttlSeconds\", \"terminal\", \"maxDepth\", \"clearance\", \"agentId\", \"addApprovers\", \"minApprovals\"];\n for (const key of Object.keys(options)) {\n if (!known.includes(key)) {\n throw new TenuoConfigurationError(\n `narrow() options: unknown key '${key}' (expected ${known.join(\", \")})`,\n );\n }\n }\n const out: WasmNarrowOptions = {};\n if (options.holder !== undefined) {\n out.holder = requirePublicKey(options.holder, \"narrow().holder\").hex;\n }\n if (options.ttlSeconds !== undefined) {\n out.ttlSeconds = requireTtl(options.ttlSeconds, \"narrow().ttlSeconds\", 1);\n }\n if (options.terminal !== undefined) {\n if (typeof options.terminal !== \"boolean\") {\n throw new TenuoConfigurationError(\"narrow().terminal must be a boolean\");\n }\n out.terminal = options.terminal;\n }\n if (options.maxDepth !== undefined) {\n out.maxDepth = requireDepth(options.maxDepth, \"narrow().maxDepth\");\n }\n if (out.terminal === true && out.maxDepth !== undefined) {\n throw new TenuoConfigurationError(\"narrow() options: pass terminal or maxDepth, not both\");\n }\n if (options.clearance !== undefined) {\n out.clearance = clearanceJson(options.clearance, \"narrow().clearance\");\n }\n if (options.agentId !== undefined) {\n out.agentId = requireLabel(options.agentId, \"narrow().agentId\");\n }\n if (options.addApprovers !== undefined) {\n out.addApprovers = options.addApprovers.map((a, i) => requirePublicKey(a, `narrow().addApprovers[${i}]`).hex);\n }\n if (options.minApprovals !== undefined) {\n if (!Number.isInteger(options.minApprovals) || options.minApprovals < 1) {\n throw new TenuoConfigurationError(\"narrow().minApprovals must be at least 1\");\n }\n out.minApprovals = options.minApprovals;\n }\n return out;\n}\n\nfunction approvalRequestFromWasm(raw: WasmApprovalRequest): ApprovalRequest {\n return {\n requestId: raw.request_id,\n warrantId: raw.warrant_id,\n tool: raw.tool,\n args: { ...raw.args },\n requestHash: raw.request_hash,\n holderPublicKey: raw.holder_public_key,\n requiredApprovers: [...raw.required_approvers],\n minApprovals: raw.min_approvals,\n warrantExpiresAt: raw.warrant_expires_at,\n createdAt: raw.created_at,\n message: raw.message,\n };\n}\n\nfunction explainDeny(message: string, field?: string): string {\n if (!message.includes(\"unknown field not allowed\")) {\n return message;\n }\n const named = field !== undefined && field.length > 0 ? `'${field}'` : \"this argument\";\n return `${message}. Zero-trust: name ${named} in allow (for example ${named}: pattern(\"*\")), or remove it from the call; constrained policies reject omitted fields.`;\n}\n\nfunction forwardExecuteOptions(callOptions: unknown): unknown {\n if (callOptions === null || typeof callOptions !== \"object\") {\n return callOptions;\n }\n const rest: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(callOptions as Record<string, unknown>)) {\n if (\n key === \"session\" ||\n key === \"approvals\" ||\n key === \"onReceipt\" ||\n key === \"requestId\"\n ) {\n continue;\n }\n rest[key] = value;\n }\n return Object.keys(rest).length === 0 ? undefined : rest;\n}\n\nfunction importWireError(error: unknown): TenuoError {\n const message = errorMessage(error);\n if (message.startsWith(\"TENUO_CHAIN_INVALID\") || message.includes(\"invalid warrant\")) {\n return new TenuoError(\"TENUO_CHAIN_INVALID\", message);\n }\n if (message.startsWith(\"TENUO_SIGNATURE_INVALID\")) {\n return new TenuoError(\"TENUO_SIGNATURE_INVALID\", message);\n }\n if (message.startsWith(\"TENUO_UNTRUSTED_ROOT\")) {\n return new TenuoError(\"TENUO_UNTRUSTED_ROOT\", message);\n }\n if (message.startsWith(\"TENUO_INVALID_POP\")) {\n // The warrant is fine; the key is not the one it was issued to.\n const separator = /[.!?]$/.test(message.trim()) ? \"\" : \".\";\n return new AuthorizationDeniedError(\n \"TENUO_INVALID_POP\",\n `${message}${separator} If this followed narrow(), set { holder: receiverPublicKey } for the agent that imports the child.`,\n );\n }\n return new TenuoConfigurationError(message);\n}\n\nfunction normalizeWireBytes(value: string | Uint8Array): string {\n if (typeof value === \"string\") {\n return value;\n }\n return bytesToHex(value);\n}\n\nfunction emitReceipt(\n callOptions: unknown,\n receipt: string | undefined,\n session: Session,\n host: object,\n): void {\n collectReceipt(receipt, session, host);\n if (receipt === undefined || callOptions === null || typeof callOptions !== \"object\") {\n return;\n }\n if (!(\"onReceipt\" in callOptions)) {\n return;\n }\n const onReceipt = (callOptions as { onReceipt?: unknown }).onReceipt;\n if (typeof onReceipt !== \"function\") {\n return;\n }\n emitIsolatedReceipt(onReceipt as (receipt: string) => void | Promise<void>, receipt);\n}\n\nfunction requestIdFrom(callOptions: unknown): string | undefined {\n if (callOptions !== null && typeof callOptions === \"object\" && \"requestId\" in callOptions) {\n const value = (callOptions as { requestId?: unknown }).requestId;\n if (typeof value === \"string\" && value.length > 0) {\n return value;\n }\n }\n return undefined;\n}\n\nfunction approvalsFrom(callOptions: unknown): unknown {\n if (callOptions !== null && typeof callOptions === \"object\" && \"approvals\" in callOptions) {\n return (callOptions as { approvals?: unknown }).approvals;\n }\n return undefined;\n}\n\nfunction resolveSession(callOptions: unknown): Session {\n if (callOptions !== null && typeof callOptions === \"object\" && \"session\" in callOptions) {\n const explicit = (callOptions as { session: unknown }).session;\n if (!isSession(explicit)) {\n throw new TenuoConfigurationError(\"options.session must be a Tenuo Session\");\n }\n return explicit;\n }\n const ambient = currentSession.getStore();\n if (ambient === undefined) {\n throw new TenuoConfigurationError(\n \"No session. Wrap the call in tenuo.withSession(session, ...) or pass { session }.\",\n );\n }\n return ambient;\n}\n\nfunction collectSessionAllow(input: SessionInput): { [capability: string]: AllowPolicy } {\n const allow: { [capability: string]: AllowPolicy } = { ...(input.allow ?? {}) };\n for (const tool of input.tools ?? []) {\n if (tool === null || typeof tool !== \"object\") {\n throw new TenuoConfigurationError(\"session({ tools }) requires tools from tenuo.tool()\");\n }\n const policy = toolPolicies.get(tool);\n if (policy === undefined) {\n throw new TenuoConfigurationError(\"session({ tools }) requires tools from tenuo.tool()\");\n }\n const existing = allow[policy.capability];\n if (existing !== undefined && !sameAllow(existing, policy.allow)) {\n throw new TenuoConfigurationError(\n `session() allow and tools disagree on ${policy.capability}`,\n );\n }\n allow[policy.capability] = policy.allow;\n }\n return allow;\n}\n\nfunction sameAllow(left: AllowPolicy, right: AllowPolicy): boolean {\n return JSON.stringify(sortedAllow(left)) === JSON.stringify(sortedAllow(right));\n}\n\nfunction sortedAllow(allow: AllowPolicy): AllowPolicy {\n const keys = Object.keys(allow).sort();\n const out: { [field: string]: AllowPolicy[string] } = {};\n for (const key of keys) {\n const value = allow[key];\n if (value !== undefined) {\n out[key] = value;\n }\n }\n return out;\n}\n\n// ---------------------------------------------------------------------------\n// Static helpers: approvals, revocation, receipts, control-plane wire shapes\n// ---------------------------------------------------------------------------\n\nfunction requestHashOf(request: ApprovalRequest | string): string {\n const hash = typeof request === \"string\" ? request : request.requestHash;\n const hex = hash.trim().toLowerCase();\n if (!/^[0-9a-f]{64}$/.test(hex)) {\n throw new TenuoConfigurationError(\"signApproval() needs an ApprovalRequest or a 64-hex request hash\");\n }\n return hex;\n}\n\n/** Sign an approval as an approver. The approver never needs the warrant or the holder key. */\nexport function signApproval(\n request: ApprovalRequest | string,\n approverSecret: Uint8Array,\n options: SignApprovalOptions,\n): string {\n if (!(approverSecret instanceof Uint8Array) || approverSecret.length !== 32) {\n throw new TenuoConfigurationError(\"signApproval() requires a 32-byte approver secret\");\n }\n if (options === null || typeof options !== \"object\" || typeof options.externalId !== \"string\" || options.externalId.trim().length === 0) {\n throw new TenuoConfigurationError(\"signApproval() requires options.externalId: who approved\");\n }\n if (options.ttlSeconds !== undefined && (!Number.isInteger(options.ttlSeconds) || options.ttlSeconds < 1)) {\n throw new TenuoConfigurationError(\"signApproval().ttlSeconds must be a positive integer\");\n }\n const warrantExpiresAt =\n options.warrantExpiresAt ?? (typeof request === \"object\" ? request.warrantExpiresAt : undefined);\n try {\n return loadWasm().sdkSignApprovalForRequest(\n requestHashOf(request),\n approverSecret,\n options.externalId,\n options.ttlSeconds,\n warrantExpiresAt,\n );\n } catch (error) {\n throw new TenuoConfigurationError(errorMessage(error));\n }\n}\n\n/** Decode an approval envelope. Not authorization: the call path still decides. */\nexport function inspectApproval(envelope: string | Uint8Array): ApprovalInfo {\n const text = typeof envelope === \"string\" ? envelope : Buffer.from(envelope).toString(\"base64\");\n let raw;\n try {\n raw = loadWasm().sdkInspectApproval(text);\n } catch (error) {\n throw new TenuoConfigurationError(errorMessage(error));\n }\n const out: { -readonly [K in keyof ApprovalInfo]: ApprovalInfo[K] } = {\n approverPublicKey: raw.approver_public_key,\n requestHash: raw.request_hash,\n externalId: raw.external_id,\n approvedAt: raw.approved_at,\n expiresAt: raw.expires_at,\n expired: raw.expired,\n signatureValid: raw.signature_valid,\n };\n if (raw.error !== undefined) {\n out.error = raw.error;\n }\n return out;\n}\n\n/** Sign a revocation list with an explicit issuer secret. */\nexport function signRevocationList(input: RevocationListInput, issuerSecret: Uint8Array): string {\n if (!(issuerSecret instanceof Uint8Array) || issuerSecret.length !== 32) {\n throw new TenuoConfigurationError(\"signRevocationList() requires a 32-byte issuer secret\");\n }\n const { ids, version } = revocationInput(input);\n try {\n return loadWasm().sdkSignRevocationListVersioned(ids, version, issuerSecret);\n } catch (error) {\n throw new TenuoConfigurationError(errorMessage(error));\n }\n}\n\nexport function inspectRevocationList(wire: string | Uint8Array): RevocationListInfo {\n let raw;\n try {\n raw = loadWasm().sdkInspectRevocationList(normalizeWireBytes(wire));\n } catch (error) {\n throw new TenuoConfigurationError(errorMessage(error));\n }\n return {\n version: raw.version,\n issuedAt: raw.issued_at,\n issuerPublicKey: raw.issuer_public_key,\n revokedIds: [...raw.revoked_ids],\n signatureValid: raw.signature_valid,\n };\n}\n\n/** Signature authenticity of a receipt. Not authorization. */\nexport function verifyReceipt(wire: string | Uint8Array): ReceiptInfo {\n let raw;\n try {\n raw = loadWasm().sdkVerifyReceipt(normalizeWireBytes(wire));\n } catch (error) {\n throw new TenuoConfigurationError(errorMessage(error));\n }\n const out: { -readonly [K in keyof ReceiptInfo]: ReceiptInfo[K] } = {\n authentic: true,\n signerKey: raw.signer_key,\n outcome: raw.outcome,\n action: raw.action,\n requestId: raw.request_id,\n };\n if (raw.decision_code !== undefined) out.decisionCode = raw.decision_code;\n if (raw.srl_version !== undefined) out.srlVersion = raw.srl_version;\n if (raw.srl_hash !== undefined) out.srlHash = raw.srl_hash;\n if (raw.request_hash !== undefined) out.requestHash = raw.request_hash;\n if (raw.policy_definition_hash !== undefined) out.policyDefinitionHash = raw.policy_definition_hash;\n if (raw.prev_receipt_hash !== undefined) out.prevReceiptHash = raw.prev_receipt_hash;\n if (raw.trusted_roots_hash !== undefined) out.trustedRootsHash = raw.trusted_roots_hash;\n return out;\n}\n\n/**\n * Root-anchored receipt check: the embedded warrant chain against `roots`\n * at the receipt's own decision instant. Needs no trust in the signer.\n */\nexport function verifyReceiptChain(wire: string | Uint8Array, roots: readonly PublicKeyHandle[]): ReceiptChainInfo {\n if (!Array.isArray(roots) || roots.length === 0) {\n throw new TenuoConfigurationError(\"verifyReceiptChain() requires at least one trusted root\");\n }\n let raw;\n try {\n raw = loadWasm().sdkVerifyReceiptChain(\n normalizeWireBytes(wire),\n roots.map((r, i) => requirePublicKey(r, `roots[${i}]`).hex),\n );\n } catch (error) {\n throw new TenuoConfigurationError(errorMessage(error));\n }\n const out: { -readonly [K in keyof ReceiptChainInfo]: ReceiptChainInfo[K] } = {\n signerKey: raw.signer_key,\n outcome: raw.outcome,\n timestamp: raw.timestamp,\n chainValid: raw.chain_valid,\n };\n if (raw.decision_code !== undefined) out.decisionCode = raw.decision_code;\n if (raw.chain_error !== undefined) out.chainError = raw.chain_error;\n if (raw.corroborates_denial !== undefined) out.corroboratesDenial = raw.corroborates_denial;\n if (raw.root_issuer !== undefined) out.rootIssuer = raw.root_issuer;\n if (raw.leaf_holder !== undefined) out.leafHolder = raw.leaf_holder;\n return out;\n}\n\n/**\n * The v1 JSON body a control plane's approval API accepts. Same shape the\n * Python SDK produces, so one approval service serves both.\n */\nexport function controlPlaneApprovalRequestV1(\n request: ApprovalRequest,\n options?: {\n readonly attestation?: ApprovalContextAttestation;\n readonly temporal?: Readonly<Record<string, string>>;\n },\n): ControlPlaneApprovalRequestV1 {\n if (request === null || typeof request !== \"object\" || typeof request.requestHash !== \"string\") {\n throw new TenuoConfigurationError(\"controlPlaneApprovalRequestV1() needs an ApprovalRequest from tenuo.approvalRequest()\");\n }\n const body: { -readonly [K in keyof ControlPlaneApprovalRequestV1]: ControlPlaneApprovalRequestV1[K] } = {\n schema_version: 1,\n request_id_hex: request.requestId,\n warrant_id: request.warrantId,\n tool: request.tool,\n arguments: { ...request.args },\n request_hash_hex: request.requestHash,\n holder_public_key_hex: request.holderPublicKey,\n required_approver_keys_hex: [...request.requiredApprovers],\n min_approvals: Math.max(1, request.minApprovals),\n warrant_expires_at_unix: request.warrantExpiresAt,\n created_at_unix: request.createdAt,\n };\n if (options?.attestation !== undefined) {\n const a = options.attestation;\n body.attestation = {\n version: a.version,\n canonicalization: a.canonicalization,\n warrant_id: a.warrantId,\n tool: a.tool,\n request_hash: a.requestHash,\n holder_key_hex: a.holderKeyHex,\n args_canonical_cbor_b64: a.argsCanonicalCborB64,\n signer_key_hex: a.signerKeyHex,\n signature_b64: a.signatureB64,\n // Python readers look for these two names.\n signer_key: a.signerKeyHex,\n signature: a.signatureB64,\n };\n }\n if (options?.temporal !== undefined && Object.keys(options.temporal).length > 0) {\n body.temporal = { ...options.temporal };\n }\n if (request.message.length > 0) {\n body.message = request.message;\n }\n return body;\n}\n\n/** Approval envelopes from a v1 response, ready for `{ approvals }` on the call. Empty unless status is a success. */\nexport function signedApprovalsFromResponseV1(response: ControlPlaneApprovalResponseV1): string[] {\n if (response === null || typeof response !== \"object\" || typeof response.status !== \"string\") {\n throw new TenuoConfigurationError(\"approval response must be an object with a status\");\n }\n if (response.status !== \"approved\") {\n return [];\n }\n const list = response.signed_approvals_b64;\n if (list === undefined || list === null) {\n return [];\n }\n if (!Array.isArray(list) || list.some((item) => typeof item !== \"string\" || item.length === 0)) {\n throw new TenuoConfigurationError(\"signed_approvals_b64 must be an array of base64 strings\");\n }\n return [...list];\n}\n\nfunction createTenuoImpl(options: CreateTenuoOptions = {}): Tenuo {\n if (!hasTrustAnchor(options)) {\n throw new TenuoConfigurationError(\n \"createTenuo() requires trustedRoots or root: createTenuo.devRoot(). An empty trust set is not a configuration.\",\n );\n }\n if (options.root?.kind === \"dev-root\" && !devRootAllowed(options.root)) {\n throw new TenuoConfigurationError(devRootBlockedMessage());\n }\n loadWasm();\n return new TenuoClient(options);\n}\n\nexport const createTenuo: ((options?: CreateTenuoOptions) => Tenuo) & {\n devRoot: typeof devRoot;\n publicKeyFromEnv: typeof publicKeyFromEnv;\n publicKeyFromHex: typeof publicKeyFromHex;\n publicKeyFromBytes: typeof publicKeyFromBytes;\n holderKeyFromEnv: typeof holderKeyFromEnv;\n holderKeyFromHex: typeof holderKeyFromHex;\n generateHolderKey: typeof generateHolderKey;\n generateIssuerKey: typeof generateIssuerKey;\n publicKeyFromHolderKey: typeof publicKeyFromHolderKey;\n issuerKeyFromEnv: typeof issuerKeyFromEnv;\n issuerKeyFromHex: typeof issuerKeyFromHex;\n issuerKeyFromBytes: typeof issuerKeyFromBytes;\n signApproval: typeof signApproval;\n inspectApproval: typeof inspectApproval;\n signRevocationList: typeof signRevocationList;\n inspectRevocationList: typeof inspectRevocationList;\n verifyReceipt: typeof verifyReceipt;\n verifyReceiptChain: typeof verifyReceiptChain;\n controlPlaneApprovalRequestV1: typeof controlPlaneApprovalRequestV1;\n signedApprovalsFromResponseV1: typeof signedApprovalsFromResponseV1;\n parseConnectToken: typeof parseConnectToken;\n identity: typeof identityFromKey;\n generateIdentity: typeof generateIdentity;\n runtime: (options: Parameters<typeof createRuntime>[1]) => ReturnType<typeof createRuntime>;\n} = Object.assign(createTenuoImpl, {\n devRoot,\n publicKeyFromEnv,\n publicKeyFromHex,\n publicKeyFromBytes,\n holderKeyFromEnv,\n holderKeyFromHex,\n generateHolderKey,\n generateIssuerKey,\n publicKeyFromHolderKey,\n issuerKeyFromEnv,\n issuerKeyFromHex,\n issuerKeyFromBytes,\n signApproval,\n inspectApproval,\n signRevocationList,\n inspectRevocationList,\n verifyReceipt,\n verifyReceiptChain,\n controlPlaneApprovalRequestV1,\n signedApprovalsFromResponseV1,\n parseConnectToken,\n identity: identityFromKey,\n generateIdentity,\n runtime: (options: Parameters<typeof createRuntime>[1]) => createRuntime(createTenuoImpl, options),\n});\n"]}
1
+ {"version":3,"file":"client.js","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AACrD,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAkC1C,OAAO,EAAE,iBAAiB,EAAE,MAAM,cAAc,CAAC;AACjD,OAAO,EAAE,gBAAgB,EAAE,eAAe,EAAE,MAAM,eAAe,CAAC;AAClE,OAAO,EAAE,SAAS,EAAE,WAAW,EAAE,eAAe,EAAe,MAAM,UAAU,CAAC;AAChF,OAAO,EAAE,cAAc,EAAE,mBAAmB,EAAE,uBAAuB,EAAE,MAAM,eAAe,CAAC;AAC7F,OAAO,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAC7C,OAAO,EAAE,wBAAwB,EAAE,qBAAqB,EAAE,uBAAuB,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACnH,OAAO,EAAE,OAAO,EAAE,SAAS,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AACjE,OAAO,EACL,gBAAgB,EAChB,mBAAmB,EACnB,qBAAqB,EACrB,sBAAsB,EACtB,qBAAqB,EACrB,QAAQ,EACR,cAAc,EACd,yBAAyB,GAS1B,MAAM,WAAW,CAAC;AA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IAAI,uBAAuB,CAAC,yDAAyD,CAAC,CAAC;IAC/F,CAAC;IACD,OAAO,CAAC,GAAG,IAAI,CAAC,CAAC;AACnB,CAAC;AAED,SAAS,eAAe,CAAC,UAA8B,EAAE;IACvD,IAAI,CAAC,cAAc,CAAC,OAAO,CAAC,EAAE,CAAC;QAC7B,MAAM,IAAI,uBAAuB,CAC/B,gHAAgH,CACjH,CAAC;IACJ,CAAC;IACD,IAAI,OAAO,CAAC,IAAI,EAAE,IAAI,KAAK,UAAU,IAAI,CAAC,cAAc,CAAC,OAAO,CAAC,IAAI,CAAC,EAAE,CAAC;QACvE,MAAM,IAAI,uBAAuB,CAAC,qBAAqB,EAAE,CAAC,CAAC;IAC7D,CAAC;IACD,QAAQ,EAAE,CAAC;IACX,OAAO,IAAI,WAAW,CAAC,OAAO,CAAC,CAAC;AAClC,CAAC;AAED,MAAM,CAAC,MAAM,WAAW,GAyBpB,MAAM,CAAC,MAAM,CAAC,eAAe,EAAE;IACjC,OAAO;IACP,gBAAgB;IAChB,gBAAgB;IAChB,kBAAkB;IAClB,gBAAgB;IAChB,gBAAgB;IAChB,iBAAiB;IACjB,iBAAiB;IACjB,sBAAsB;IACtB,gBAAgB;IAChB,gBAAgB;IAChB,kBAAkB;IAClB,YAAY;IACZ,eAAe;IACf,kBAAkB;IAClB,qBAAqB;IACrB,aAAa;IACb,kBAAkB;IAClB,6BAA6B;IAC7B,6BAA6B;IAC7B,iBAAiB;IACjB,QAAQ,EAAE,eAAe;IACzB,gBAAgB;IAChB,OAAO,EAAE,CAAC,OAA4C,EAAE,EAAE,CAAC,aAAa,CAAC,eAAe,EAAE,OAAO,CAAC;CACnG,CAAC,CAAC","sourcesContent":["import { AsyncLocalStorage } from \"node:async_hooks\";\nimport { randomBytes } from \"node:crypto\";\nimport type {\n AllowPolicy,\n ApprovalContextAttestation,\n ApprovalInfo,\n ApprovalRequest,\n Clearance,\n ControlPlaneApprovalRequestV1,\n ControlPlaneApprovalResponseV1,\n CreateTenuoOptions,\n DevRoot,\n Explanation,\n IssueInput,\n IssuerKey,\n McpAttachOptions,\n McpVerifyOptions,\n NarrowInput,\n NarrowOptions,\n PresentedCall,\n ProtectedTool,\n PublicKeyHandle,\n ReceiptChainInfo,\n ReceiptInfo,\n RequireApproval,\n RevocationListInfo,\n RevocationListInput,\n SessionFromWireInput,\n SessionInput,\n SignApprovalOptions,\n Tenuo,\n TenuoErrorCode,\n TenuoMcp,\n ToolPolicy,\n} from \"./api.ts\";\nimport { parseConnectToken } from \"./connect.ts\";\nimport { generateIdentity, identityFromKey } from \"./identity.ts\";\nimport { createMcp, presentCall, verifyPresented, type Decide } from \"./mcp.ts\";\nimport { collectReceipt, emitIsolatedReceipt, inheritSessionCollector } from \"./receipts.ts\";\nimport { createRuntime } from \"./runtime.ts\";\nimport { AuthorizationDeniedError, ApprovalRequiredError, TenuoConfigurationError, TenuoError } from \"./errors.ts\";\nimport { Session, isSession, nativeSession } from \"./session.ts\";\nimport {\n createDevContext,\n createIssuerContext,\n createVerifierContext,\n importSessionFromChain,\n importSessionFromWire,\n loadWasm,\n protocolLimits,\n publicKeyHexFromHolderKey,\n type WasmApprovalRequest,\n type WasmAttestation,\n type WasmContext,\n type WasmExplain,\n type WasmIssueOptions,\n type WasmMintOptions,\n type WasmNarrowOptions,\n type WasmRequireApproval,\n} from \"./wasm.ts\";\n\nconst currentSession = new AsyncLocalStorage<Session>();\nconst toolPolicies = new WeakMap<object, { capability: string; allow: AllowPolicy }>();\nconst wrappedInners = new WeakSet<object>();\n\nconst CLEARANCE_NAMES = new Set([\"untrusted\", \"external\", \"partner\", \"internal\", \"privileged\", \"system\"]);\n\nfunction nodeEnv(): string | undefined {\n if (typeof process === \"undefined\") {\n return undefined;\n }\n return process.env.NODE_ENV;\n}\n\nfunction allowDev(): boolean {\n if (typeof process === \"undefined\") {\n return false;\n }\n return process.env.TENUO_ALLOW_DEV === \"1\";\n}\n\nexport function devRoot(options?: { readonly allowInProduction?: boolean }): DevRoot {\n const root: DevRoot = {\n kind: \"dev-root\",\n ...(options?.allowInProduction === true ? { allowInProduction: true } : {}),\n };\n if (!devRootAllowed(root)) {\n throw new TenuoConfigurationError(devRootBlockedMessage());\n }\n return root;\n}\n\nfunction devRootAllowed(root: DevRoot): boolean {\n if (root.allowInProduction === true || allowDev()) {\n return true;\n }\n const env = nodeEnv();\n return env === \"development\" || env === \"test\";\n}\n\nfunction devRootBlockedMessage(): string {\n return \"createTenuo.devRoot() is for development. Set NODE_ENV=development or test, pass devRoot({ allowInProduction: true }), or TENUO_ALLOW_DEV=1. Unset NODE_ENV is not treated as development.\";\n}\n\nfunction normalizeHex(value: string): string {\n const hex = value.trim().toLowerCase().replace(/^0x/, \"\");\n if (!/^[0-9a-f]{64}$/.test(hex)) {\n throw new TenuoConfigurationError(\n \"Trusted root must be a 32-byte hex public key (64 hex characters)\",\n );\n }\n return hex;\n}\n\nfunction envValue(name: string, what: string): string {\n if (name.length === 0) {\n throw new TenuoConfigurationError(`${what} requires an environment variable name`);\n }\n if (typeof process === \"undefined\") {\n throw new TenuoConfigurationError(\n `Environment variable ${name} is not available. Tenuo fails closed without a ${what}.`,\n );\n }\n const value = process.env[name];\n if (value === undefined || value.length === 0) {\n throw new TenuoConfigurationError(\n `Environment variable ${name} is not set or empty. Tenuo fails closed without a ${what}.`,\n );\n }\n return value;\n}\n\nexport function publicKeyFromEnv(name: string): PublicKeyHandle {\n return { kind: \"public-key\", source: \"env\", hex: normalizeHex(envValue(name, \"trusted root\")) };\n}\n\nexport function publicKeyFromHex(hex: string): PublicKeyHandle {\n return { kind: \"public-key\", source: \"hex\", hex: normalizeHex(hex) };\n}\n\nexport function publicKeyFromBytes(bytes: Uint8Array): PublicKeyHandle {\n if (bytes.length !== 32) {\n throw new TenuoConfigurationError(\"publicKeyFromBytes() requires a 32-byte public key\");\n }\n return { kind: \"public-key\", source: \"bytes\", hex: bytesToHex(bytes) };\n}\n\nfunction normalizeSecretHex(value: string, what: string): string {\n const hex = value.trim().toLowerCase().replace(/^0x/, \"\");\n if (!/^[0-9a-f]{64}$/.test(hex)) {\n throw new TenuoConfigurationError(`${what} must be a 32-byte hex secret (64 hex characters)`);\n }\n return hex;\n}\n\nfunction hexToBytes(hex: string): Uint8Array {\n const bytes = new Uint8Array(hex.length / 2);\n for (let i = 0; i < bytes.length; i += 1) {\n bytes[i] = Number.parseInt(hex.slice(i * 2, i * 2 + 2), 16);\n }\n return bytes;\n}\n\nfunction bytesToHex(bytes: Uint8Array): string {\n return Array.from(bytes, (b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\nexport function holderKeyFromEnv(name: string): Uint8Array {\n return hexToBytes(normalizeSecretHex(envValue(name, \"holder key\"), \"Holder key\"));\n}\n\nexport function holderKeyFromHex(hex: string): Uint8Array {\n return hexToBytes(normalizeSecretHex(hex, \"Holder key\"));\n}\n\n/**\n * A fresh 32-byte Ed25519 secret. One per agent, kept in that agent's\n * process; only its public key (see `publicKeyFromHolderKey`) travels.\n */\nexport function generateHolderKey(): Uint8Array {\n return new Uint8Array(randomBytes(32));\n}\n\n/** Same shape as a holder key. Named separately so a control plane's key reads as one. */\nexport function generateIssuerKey(): Uint8Array {\n return generateHolderKey();\n}\n\n/** The public half of a holder or issuer secret. */\nexport function publicKeyFromHolderKey(holderKey: Uint8Array): PublicKeyHandle {\n if (!(holderKey instanceof Uint8Array) || holderKey.length !== 32) {\n throw new TenuoConfigurationError(\"publicKeyFromHolderKey() requires a 32-byte holder key\");\n }\n loadWasm();\n return { kind: \"public-key\", source: \"bytes\", hex: publicKeyHexFromHolderKey(holderKey) };\n}\n\nconst MAX_WASM_U32 = 0xffff_ffff;\n\nfunction requireUint32(value: number, name: string, minimum = 0): number {\n if (!Number.isInteger(value) || value < minimum || value > MAX_WASM_U32) {\n throw new TenuoConfigurationError(\n `${name} must be an integer between ${minimum} and ${MAX_WASM_U32}`,\n );\n }\n return value;\n}\n\n/** Stable control-plane key from the environment. This process becomes an issuer. */\nexport function issuerKeyFromEnv(name: string): IssuerKey {\n return { kind: \"issuer-key\", secret: hexToBytes(normalizeSecretHex(envValue(name, \"issuer key\"), \"Issuer key\")) };\n}\n\nexport function issuerKeyFromHex(hex: string): IssuerKey {\n return { kind: \"issuer-key\", secret: hexToBytes(normalizeSecretHex(hex, \"Issuer key\")) };\n}\n\nexport function issuerKeyFromBytes(secret: Uint8Array): IssuerKey {\n if (!(secret instanceof Uint8Array) || secret.length !== 32) {\n throw new TenuoConfigurationError(\"issuerKeyFromBytes() requires a 32-byte secret\");\n }\n return { kind: \"issuer-key\", secret: new Uint8Array(secret) };\n}\n\nfunction requireDepth(value: number, name: string): number {\n requireUint32(value, name);\n const maximum = protocolLimits().max_delegation_depth;\n if (value > maximum) {\n throw new TenuoConfigurationError(\n `${name} ${value} exceeds the protocol maximum of ${maximum}`,\n );\n }\n return value;\n}\n\nfunction requireTtl(value: number, name: string, minimum = 0): number {\n requireUint32(value, name, minimum);\n const maximum = protocolLimits().max_warrant_ttl_seconds;\n if (value > maximum) {\n throw new TenuoConfigurationError(\n `${name} ${value} exceeds the protocol maximum of ${maximum}`,\n );\n }\n return value;\n}\n\nfunction requirePublicKey(value: unknown, name: string): PublicKeyHandle {\n if (\n value === null ||\n typeof value !== \"object\" ||\n (value as { kind?: unknown }).kind !== \"public-key\" ||\n typeof (value as { hex?: unknown }).hex !== \"string\"\n ) {\n throw new TenuoConfigurationError(\n `${name} must be a public key handle (createTenuo.publicKeyFromHolderKey / publicKeyFromHex / publicKeyFromEnv)`,\n );\n }\n return value as PublicKeyHandle;\n}\n\nfunction clearanceJson(value: Clearance, name: string): number | string {\n if (typeof value === \"number\") {\n if (!Number.isInteger(value) || value < 0 || value > 255) {\n throw new TenuoConfigurationError(`${name} must be an integer 0-255 or a level name`);\n }\n return value;\n }\n if (typeof value === \"string\" && CLEARANCE_NAMES.has(value)) {\n return value;\n }\n throw new TenuoConfigurationError(\n `${name} must be one of ${[...CLEARANCE_NAMES].join(\", \")} or an integer 0-255`,\n );\n}\n\nfunction rootHexes(options: CreateTenuoOptions): string[] {\n const handles: PublicKeyHandle[] = [];\n if (options.root !== undefined && options.root.kind === \"public-key\") {\n handles.push(options.root);\n }\n for (const root of options.trustedRoots ?? []) {\n handles.push(root);\n }\n return handles.map((h) => h.hex);\n}\n\nfunction hasTrustAnchor(options: CreateTenuoOptions): boolean {\n if (options.root !== undefined) {\n return true;\n }\n return (options.trustedRoots?.length ?? 0) > 0;\n}\n\nfunction capabilityName(inner: object, policy: Pick<ToolPolicy, \"capability\">): string {\n if (policy.capability !== undefined && policy.capability.length > 0) {\n return policy.capability;\n }\n const named = inner as { name?: unknown; id?: unknown };\n if (typeof named.name === \"string\" && named.name.length > 0) {\n return named.name;\n }\n if (typeof named.id === \"string\" && named.id.length > 0) {\n return named.id;\n }\n throw new TenuoConfigurationError(\n \"tenuo.tool() needs a capability name (policy.capability, or tool.name / tool.id)\",\n );\n}\n\nclass TenuoClient implements Tenuo {\n private readonly context: WasmContext;\n private readonly canMint: boolean;\n readonly mcp: TenuoMcp;\n private readonly decide: Decide;\n\n constructor(options: CreateTenuoOptions) {\n if (options.root?.kind === \"dev-root\") {\n this.context = createDevContext(options.receiptSigner);\n this.canMint = true;\n } else if (options.root?.kind === \"issuer-key\") {\n if (!(options.root.secret instanceof Uint8Array) || options.root.secret.length !== 32) {\n throw new TenuoConfigurationError(\"root: issuer key must be a 32-byte secret\");\n }\n this.context = createIssuerContext(\n options.root.secret,\n rootHexes(options),\n options.receiptSigner,\n );\n this.canMint = true;\n } else {\n this.context = createVerifierContext(\n rootHexes(options),\n undefined,\n options.receiptSigner,\n );\n this.canMint = false;\n }\n if (options.revocationList !== undefined) {\n this.context.loadRevocationList(normalizeWireBytes(options.revocationList));\n }\n this.decide = (decision, tool, native, args) => {\n this.applyDecision(decision, tool, native, args);\n };\n this.mcp = createMcp(this.context, this.decide, this);\n }\n\n private applyDecision(\n decision: { outcome: string; code?: string; field?: string; message?: string; tool?: string; required?: number; received?: number },\n tool: string,\n native?: object,\n args?: Record<string, unknown>,\n ): void {\n if (decision.outcome === \"allow\") {\n return;\n }\n if (decision.outcome === \"approval_required\") {\n let request: ApprovalRequest | undefined;\n if (native !== undefined && args !== undefined) {\n try {\n request = approvalRequestFromWasm(this.context.approvalRequest(native, tool, args));\n } catch {\n request = undefined;\n }\n }\n throw new ApprovalRequiredError(\n decision.tool ?? tool,\n decision.required ?? 1,\n decision.received ?? 0,\n decision.message,\n request,\n );\n }\n throw new AuthorizationDeniedError(\n (decision.code as TenuoErrorCode | undefined) ?? \"TENUO_TOOL_NOT_AUTHORIZED\",\n explainDeny(decision.message ?? \"Authorization denied\", decision.field),\n decision.field,\n );\n }\n\n tool<T extends { execute: (args: never) => unknown }>(\n inner: T,\n policy: ToolPolicy<Parameters<T[\"execute\"]>[0]>,\n ): ProtectedTool<T> {\n if (toolPolicies.has(inner) || wrappedInners.has(inner)) {\n throw new TenuoConfigurationError(\"tenuo.tool() already wrapped this tool\");\n }\n const capability = capabilityName(inner, policy);\n const original = inner.execute as (\n args: Record<string, unknown>,\n options?: unknown,\n ) => unknown;\n const execute = async (args: never, callOptions?: unknown) => {\n const session = resolveSession(callOptions);\n const native = nativeSession(session);\n const decision = this.context.authorize(\n native,\n capability,\n args,\n approvalsFrom(callOptions),\n policy.allow,\n requestIdFrom(callOptions),\n );\n emitReceipt(callOptions, decision.receipt, session, this);\n if (decision.outcome === \"allow\") {\n return original(plainArgs(decision.args), forwardExecuteOptions(callOptions));\n }\n this.applyDecision(decision, capability, native, plainArgs(args));\n throw new TenuoConfigurationError(\"unreachable: decision was neither allow nor deny\");\n };\n\n const wrapped = Object.assign(Object.create(Object.getPrototypeOf(inner)), inner, {\n execute,\n }) as ProtectedTool<T>;\n wrappedInners.add(inner);\n toolPolicies.set(wrapped, { capability, allow: { ...policy.allow } as AllowPolicy });\n return wrapped;\n }\n\n session(input: SessionInput): Session {\n const allow = collectSessionAllow(input);\n const kind = input.kind ?? \"execution\";\n if (kind !== \"execution\" && kind !== \"issuer\") {\n throw new TenuoConfigurationError('session().kind must be \"execution\" or \"issuer\"');\n }\n if (Object.keys(allow).length === 0 && kind === \"execution\") {\n throw new TenuoConfigurationError(\n \"tenuo.session() requires tools from tenuo.tool() or at least one capability in allow\",\n );\n }\n if (!this.canMint) {\n throw new TenuoConfigurationError(\n \"session() mints a warrant and needs a local issuer. Use createTenuo({ root: createTenuo.devRoot() }) or an issuer key.\",\n );\n }\n const options: WasmMintOptions = { kind, allow };\n if (input.ttlSeconds !== undefined) {\n options.ttlSeconds = requireTtl(input.ttlSeconds, \"session().ttlSeconds\");\n }\n if (input.holder !== undefined) {\n options.holder = requirePublicKey(input.holder, \"session().holder\").hex;\n }\n if (input.maxDepth !== undefined) {\n options.maxDepth = requireDepth(input.maxDepth, \"session().maxDepth\");\n }\n if (input.clearance !== undefined) {\n options.clearance = clearanceJson(input.clearance, \"session().clearance\");\n }\n if (input.sessionId !== undefined) {\n options.sessionId = requireLabel(input.sessionId, \"session().sessionId\");\n }\n if (input.agentId !== undefined) {\n options.agentId = requireLabel(input.agentId, \"session().agentId\");\n }\n if (input.requireApproval !== undefined) {\n options.requireApproval = requireApprovalJson(input.requireApproval);\n }\n if (input.issuableTools !== undefined) {\n options.issuableTools = [...input.issuableTools];\n }\n if (input.constraintBounds !== undefined) {\n options.constraintBounds = input.constraintBounds;\n }\n if (input.maxIssueDepth !== undefined) {\n options.maxIssueDepth = requireDepth(input.maxIssueDepth, \"session().maxIssueDepth\");\n }\n try {\n return new Session(this.context.mintExtended(options));\n } catch (error) {\n throw new TenuoConfigurationError(errorMessage(error));\n }\n }\n\n issue(issuer: Session, input: IssueInput): Session {\n if (!isSession(issuer)) {\n throw new TenuoConfigurationError(\"issue() requires a Tenuo Session, not a plain object\");\n }\n if (input === null || typeof input !== \"object\" || input.allow === undefined || Object.keys(input.allow).length === 0) {\n throw new TenuoConfigurationError(\"issue() requires at least one capability in allow\");\n }\n const options: WasmIssueOptions = {\n allow: input.allow,\n holder: requirePublicKey(input.holder, \"issue().holder\").hex,\n };\n if (input.ttlSeconds !== undefined) {\n options.ttlSeconds = requireTtl(input.ttlSeconds, \"issue().ttlSeconds\", 1);\n }\n if (input.maxDepth !== undefined) {\n options.maxDepth = requireDepth(input.maxDepth, \"issue().maxDepth\");\n }\n if (input.clearance !== undefined) {\n options.clearance = clearanceJson(input.clearance, \"issue().clearance\");\n }\n if (input.sessionId !== undefined) {\n options.sessionId = requireLabel(input.sessionId, \"issue().sessionId\");\n }\n if (input.agentId !== undefined) {\n options.agentId = requireLabel(input.agentId, \"issue().agentId\");\n }\n if (input.requireApproval !== undefined) {\n options.requireApproval = requireApprovalJson(input.requireApproval);\n }\n try {\n return new Session(this.context.issue(nativeSession(issuer), options));\n } catch (error) {\n throw chainError(error);\n }\n }\n\n issuerPublicKey(): PublicKeyHandle {\n if (!this.canMint) {\n throw new TenuoConfigurationError(\n \"issuerPublicKey() needs a local issuer. This context verifies against trustedRoots and does not mint.\",\n );\n }\n return { kind: \"public-key\", source: \"bytes\", hex: this.context.issuerPublicKey() };\n }\n\n sessionFromWire(input: SessionFromWireInput): Session {\n if (!(input.holderKey instanceof Uint8Array) || input.holderKey.length !== 32) {\n throw new TenuoConfigurationError(\"sessionFromWire() requires a 32-byte holderKey\");\n }\n if (typeof input.warrant === \"string\" && input.warrant.trim().length === 0) {\n throw new TenuoConfigurationError(\"sessionFromWire() requires a warrant\");\n }\n try {\n if (typeof input.warrant === \"string\") {\n return new Session(importSessionFromWire(input.warrant, input.holderKey));\n }\n if (input.warrant.length === 0) {\n throw new TenuoConfigurationError(\"sessionFromWire() requires a warrant\");\n }\n return new Session(importSessionFromChain([...input.warrant], input.holderKey));\n } catch (error) {\n throw importWireError(error);\n }\n }\n\n withSession<R>(session: Session, fn: () => R): R {\n if (!isSession(session)) {\n throw new TenuoConfigurationError(\"withSession() requires a Tenuo Session, not a plain object\");\n }\n return currentSession.run(session, fn);\n }\n\n narrow(session: Session, allow: NarrowInput, options?: NarrowOptions): Session {\n if (Object.keys(allow).length === 0) {\n throw new TenuoConfigurationError(\"tenuo.narrow() requires a non-empty allow policy\");\n }\n if (!isSession(session)) {\n throw new TenuoConfigurationError(\"narrow() requires a Tenuo Session, not a plain object\");\n }\n const native = options === undefined ? undefined : narrowOptionsJson(options);\n try {\n const child = new Session(this.context.narrow(nativeSession(session), allow, native));\n inheritSessionCollector(session, child);\n return child;\n } catch (error) {\n throw chainError(error);\n }\n }\n\n explain(session: Session, tool: string, args: Readonly<Record<string, unknown>>): Explanation {\n if (!isSession(session)) {\n throw new TenuoConfigurationError(\"explain() requires a Tenuo Session, not a plain object\");\n }\n let raw: WasmExplain;\n try {\n raw = this.context.explain(nativeSession(session), tool, args);\n } catch (error) {\n throw new TenuoConfigurationError(errorMessage(error));\n }\n const out: { -readonly [K in keyof Explanation]: Explanation[K] } = {\n tool: raw.tool,\n kind: raw.kind,\n outcome: raw.outcome,\n toolGranted: raw.tool_granted,\n fields: raw.fields.map((f) => {\n const field: { -readonly [K in keyof Explanation[\"fields\"][number]]: Explanation[\"fields\"][number][K] } = {\n field: f.field,\n kind: f.kind,\n constraint: f.constraint,\n satisfied: f.satisfied,\n };\n if (f.value !== undefined) {\n field.value = f.value;\n }\n if (f.reason !== undefined) {\n field.reason = f.reason;\n }\n if (f.reason_code !== undefined) {\n field.reasonCode = f.reason_code;\n }\n return field;\n }),\n unknownFields: [...raw.unknown_fields],\n missingFields: [...raw.missing_fields],\n expired: raw.expired,\n expiresAt: raw.expires_at,\n chainValid: raw.chain_valid,\n };\n if (raw.code !== undefined) {\n out.code = raw.code;\n }\n if (raw.field !== undefined) {\n out.field = raw.field;\n }\n if (raw.message !== undefined) {\n out.message = raw.message;\n }\n if (raw.chain_error !== undefined) {\n out.chainError = raw.chain_error;\n }\n return out;\n }\n\n approvalRequest(session: Session, tool: string, args: Readonly<Record<string, unknown>>): ApprovalRequest {\n if (!isSession(session)) {\n throw new TenuoConfigurationError(\"approvalRequest() requires a Tenuo Session, not a plain object\");\n }\n try {\n return approvalRequestFromWasm(this.context.approvalRequest(nativeSession(session), tool, args));\n } catch (error) {\n throw new TenuoConfigurationError(errorMessage(error));\n }\n }\n\n attestApprovalRequest(\n session: Session,\n tool: string,\n args: Readonly<Record<string, unknown>>,\n ): ApprovalContextAttestation {\n if (!isSession(session)) {\n throw new TenuoConfigurationError(\"attestApprovalRequest() requires a Tenuo Session, not a plain object\");\n }\n let raw: WasmAttestation;\n try {\n raw = this.context.approvalContextAttestation(nativeSession(session), tool, args);\n } catch (error) {\n throw new TenuoConfigurationError(errorMessage(error));\n }\n return {\n version: raw.version,\n canonicalization: raw.canonicalization,\n warrantId: raw.warrant_id,\n tool: raw.tool,\n requestHash: raw.request_hash,\n holderKeyHex: raw.holder_key_hex,\n argsCanonicalCborB64: raw.args_canonical_cbor_b64,\n signerKeyHex: raw.signer_key_hex,\n signatureB64: raw.signature_b64,\n };\n }\n\n present(\n session: Session,\n tool: string,\n args: Readonly<Record<string, unknown>>,\n options?: McpAttachOptions,\n ): PresentedCall {\n if (!isSession(session)) {\n throw new TenuoConfigurationError(\"present() requires a Tenuo Session, not a plain object\");\n }\n return presentCall(this.context, this.decide, session, tool, args, options, \"present()\", this)\n .presented;\n }\n\n verify(\n presented: PresentedCall,\n tool: string,\n args: Readonly<Record<string, unknown>>,\n options?: McpVerifyOptions,\n ): Promise<Readonly<Record<string, unknown>>> {\n return verifyPresented(\n this.context,\n this.decide,\n presented,\n tool,\n args,\n options,\n \"verify()\",\n this,\n );\n }\n\n revocationList(input: RevocationListInput): string {\n if (!this.canMint) {\n throw new TenuoConfigurationError(\n \"revocationList() needs a local issuer key. Use createTenuo.signRevocationList() with an explicit secret, or an issuer-key root.\",\n );\n }\n const { ids, version } = revocationInput(input);\n try {\n return this.context.signRevocationListVersioned(ids, version);\n } catch (error) {\n throw new TenuoConfigurationError(errorMessage(error));\n }\n }\n\n revoke(list: string | Uint8Array): void {\n this.context.loadRevocationList(normalizeWireBytes(list));\n }\n\n ready(): void {\n loadWasm();\n }\n}\n\nfunction requireLabel(value: string, name: string): string {\n if (typeof value !== \"string\" || value.trim().length === 0) {\n throw new TenuoConfigurationError(`${name} must be a non-empty string`);\n }\n return value;\n}\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\n/** Map a prefixed core message from narrow()/issue() to the matching error class. */\nfunction chainError(error: unknown): TenuoError {\n if (error instanceof TenuoError) {\n return error;\n }\n const message = explainChainFailure(errorMessage(error));\n for (const code of [\"TENUO_CHAIN_INVALID\", \"TENUO_DEPTH_EXCEEDED\", \"TENUO_WARRANT_EXPIRED\"] as const) {\n if (message.startsWith(code)) {\n return new AuthorizationDeniedError(code, message);\n }\n }\n return new TenuoConfigurationError(message);\n}\n\nfunction explainChainFailure(message: string): string {\n const tool = /tool '([^']+)' not in parent's tools/.exec(message)?.[1];\n if (tool !== undefined) {\n return `${message}. narrow() cannot add '${tool}': remove it or delegate from a parent that grants it.`;\n }\n if (\n message.includes(\"parent's allowed set\") ||\n message.includes(\"range expanded\") ||\n message.includes(\"would expand permissions\") ||\n message.includes(\"clearance cannot increase\")\n ) {\n return `${message}. narrow() only accepts a child policy that is equal to or stricter than its parent.`;\n }\n return message;\n}\n\nfunction revocationInput(input: RevocationListInput): { ids: string[]; version: number | undefined } {\n if (input === null || typeof input !== \"object\" || !Array.isArray(input.revoke)) {\n throw new TenuoConfigurationError(\"revocation list input must be { revoke: string[], version? }\");\n }\n const ids = input.revoke.filter((id): id is string => typeof id === \"string\" && id.length > 0);\n if (ids.length === 0 || ids.length !== input.revoke.length) {\n throw new TenuoConfigurationError(\"revoke must be a non-empty array of warrant ids\");\n }\n if (input.version !== undefined && (!Number.isInteger(input.version) || input.version < 1)) {\n throw new TenuoConfigurationError(\"revocation list version must be a positive integer\");\n }\n return { ids, version: input.version };\n}\n\nfunction plainArgs(value: unknown): Record<string, unknown> {\n if (value instanceof Map) {\n return Object.fromEntries(value);\n }\n if (value !== null && typeof value === \"object\" && !Array.isArray(value)) {\n return { ...(value as Record<string, unknown>) };\n }\n return {};\n}\n\nfunction requireApprovalJson(require: RequireApproval): WasmRequireApproval {\n if (require === null || typeof require !== \"object\") {\n throw new TenuoConfigurationError(\"requireApproval must be an object\");\n }\n if (!Array.isArray(require.approvers) || require.approvers.length === 0) {\n throw new TenuoConfigurationError(\"requireApproval.approvers must not be empty\");\n }\n if (!Number.isInteger(require.min) || require.min < 1) {\n throw new TenuoConfigurationError(\"requireApproval.min must be at least 1\");\n }\n const payload: WasmRequireApproval = {\n approvers: require.approvers.map((approver, i) => requirePublicKey(approver, `requireApproval.approvers[${i}]`).hex),\n min: require.min,\n };\n if (require.tools !== undefined) {\n payload.tools = [...require.tools];\n }\n if (require.gates !== undefined) {\n const gates: NonNullable<WasmRequireApproval[\"gates\"]> = {};\n for (const [tool, gate] of Object.entries(require.gates)) {\n const out: { message?: string; args?: Record<string, unknown> } = {};\n if (gate.message !== undefined) {\n out.message = gate.message;\n }\n if (gate.args !== undefined) {\n out.args = { ...gate.args };\n }\n gates[tool] = out;\n }\n payload.gates = gates;\n }\n return payload;\n}\n\nfunction narrowOptionsJson(options: NarrowOptions): WasmNarrowOptions {\n if (options === null || typeof options !== \"object\") {\n throw new TenuoConfigurationError(\"narrow() options must be an object\");\n }\n const known = [\"holder\", \"ttlSeconds\", \"terminal\", \"maxDepth\", \"clearance\", \"agentId\", \"addApprovers\", \"minApprovals\"];\n for (const key of Object.keys(options)) {\n if (!known.includes(key)) {\n throw new TenuoConfigurationError(\n `narrow() options: unknown key '${key}' (expected ${known.join(\", \")})`,\n );\n }\n }\n const out: WasmNarrowOptions = {};\n if (options.holder !== undefined) {\n out.holder = requirePublicKey(options.holder, \"narrow().holder\").hex;\n }\n if (options.ttlSeconds !== undefined) {\n out.ttlSeconds = requireTtl(options.ttlSeconds, \"narrow().ttlSeconds\", 1);\n }\n if (options.terminal !== undefined) {\n if (typeof options.terminal !== \"boolean\") {\n throw new TenuoConfigurationError(\"narrow().terminal must be a boolean\");\n }\n out.terminal = options.terminal;\n }\n if (options.maxDepth !== undefined) {\n out.maxDepth = requireDepth(options.maxDepth, \"narrow().maxDepth\");\n }\n if (out.terminal === true && out.maxDepth !== undefined) {\n throw new TenuoConfigurationError(\"narrow() options: pass terminal or maxDepth, not both\");\n }\n if (options.clearance !== undefined) {\n out.clearance = clearanceJson(options.clearance, \"narrow().clearance\");\n }\n if (options.agentId !== undefined) {\n out.agentId = requireLabel(options.agentId, \"narrow().agentId\");\n }\n if (options.addApprovers !== undefined) {\n out.addApprovers = options.addApprovers.map((a, i) => requirePublicKey(a, `narrow().addApprovers[${i}]`).hex);\n }\n if (options.minApprovals !== undefined) {\n if (!Number.isInteger(options.minApprovals) || options.minApprovals < 1) {\n throw new TenuoConfigurationError(\"narrow().minApprovals must be at least 1\");\n }\n out.minApprovals = options.minApprovals;\n }\n return out;\n}\n\nfunction approvalRequestFromWasm(raw: WasmApprovalRequest): ApprovalRequest {\n return {\n requestId: raw.request_id,\n warrantId: raw.warrant_id,\n tool: raw.tool,\n args: { ...raw.args },\n requestHash: raw.request_hash,\n holderPublicKey: raw.holder_public_key,\n requiredApprovers: [...raw.required_approvers],\n minApprovals: raw.min_approvals,\n warrantExpiresAt: raw.warrant_expires_at,\n createdAt: raw.created_at,\n message: raw.message,\n };\n}\n\nfunction explainDeny(message: string, field?: string): string {\n if (message.includes(\"unknown field not allowed\")) {\n const named = field !== undefined && field.length > 0 ? `'${field}'` : \"this argument\";\n return `${message}. Zero-trust: name ${named} in allow with the tightest constraint that admits the real values (wildcard() only when the value does not change what the tool does), or remove ${named} from the call if the tool does not act on it; constrained policies reject omitted fields.`;\n }\n if (message.includes(\"value does not match constraint\")) {\n return `${message}. Use tenuo.explain(session, tool, args) locally for field-level diagnostics.`;\n }\n return message;\n}\n\nfunction forwardExecuteOptions(callOptions: unknown): unknown {\n if (callOptions === null || typeof callOptions !== \"object\") {\n return callOptions;\n }\n const rest: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(callOptions as Record<string, unknown>)) {\n if (\n key === \"session\" ||\n key === \"approvals\" ||\n key === \"onReceipt\" ||\n key === \"requestId\"\n ) {\n continue;\n }\n rest[key] = value;\n }\n return Object.keys(rest).length === 0 ? undefined : rest;\n}\n\nfunction importWireError(error: unknown): TenuoError {\n const message = errorMessage(error);\n if (message.startsWith(\"TENUO_CHAIN_INVALID\") || message.includes(\"invalid warrant\")) {\n return new TenuoError(\"TENUO_CHAIN_INVALID\", message);\n }\n if (message.startsWith(\"TENUO_SIGNATURE_INVALID\")) {\n return new TenuoError(\"TENUO_SIGNATURE_INVALID\", message);\n }\n if (message.startsWith(\"TENUO_UNTRUSTED_ROOT\")) {\n return new TenuoError(\"TENUO_UNTRUSTED_ROOT\", message);\n }\n if (message.startsWith(\"TENUO_INVALID_POP\")) {\n // The warrant is fine; the key is not the one it was issued to.\n const separator = /[.!?]$/.test(message.trim()) ? \"\" : \".\";\n return new AuthorizationDeniedError(\n \"TENUO_INVALID_POP\",\n `${message}${separator} If this followed narrow(), set { holder: receiverPublicKey } for the agent that imports the child.`,\n );\n }\n return new TenuoConfigurationError(message);\n}\n\nfunction normalizeWireBytes(value: string | Uint8Array): string {\n if (typeof value === \"string\") {\n return value;\n }\n return bytesToHex(value);\n}\n\nfunction emitReceipt(\n callOptions: unknown,\n receipt: string | undefined,\n session: Session,\n host: object,\n): void {\n collectReceipt(receipt, session, host);\n if (receipt === undefined || callOptions === null || typeof callOptions !== \"object\") {\n return;\n }\n if (!(\"onReceipt\" in callOptions)) {\n return;\n }\n const onReceipt = (callOptions as { onReceipt?: unknown }).onReceipt;\n if (typeof onReceipt !== \"function\") {\n return;\n }\n emitIsolatedReceipt(onReceipt as (receipt: string) => void | Promise<void>, receipt);\n}\n\nfunction requestIdFrom(callOptions: unknown): string | undefined {\n if (callOptions !== null && typeof callOptions === \"object\" && \"requestId\" in callOptions) {\n const value = (callOptions as { requestId?: unknown }).requestId;\n if (typeof value === \"string\" && value.length > 0) {\n return value;\n }\n }\n return undefined;\n}\n\nfunction approvalsFrom(callOptions: unknown): unknown {\n if (callOptions !== null && typeof callOptions === \"object\" && \"approvals\" in callOptions) {\n return (callOptions as { approvals?: unknown }).approvals;\n }\n return undefined;\n}\n\nfunction resolveSession(callOptions: unknown): Session {\n if (callOptions !== null && typeof callOptions === \"object\" && \"session\" in callOptions) {\n const explicit = (callOptions as { session: unknown }).session;\n if (!isSession(explicit)) {\n throw new TenuoConfigurationError(\"options.session must be a Tenuo Session\");\n }\n return explicit;\n }\n const ambient = currentSession.getStore();\n if (ambient === undefined) {\n throw new TenuoConfigurationError(\n \"No session. Wrap the call in tenuo.withSession(session, ...) or pass { session }.\",\n );\n }\n return ambient;\n}\n\nfunction collectSessionAllow(input: SessionInput): { [capability: string]: AllowPolicy } {\n const allow: { [capability: string]: AllowPolicy } = { ...(input.allow ?? {}) };\n for (const tool of input.tools ?? []) {\n if (tool === null || typeof tool !== \"object\") {\n throw new TenuoConfigurationError(\"session({ tools }) requires tools from tenuo.tool()\");\n }\n const policy = toolPolicies.get(tool);\n if (policy === undefined) {\n throw new TenuoConfigurationError(\"session({ tools }) requires tools from tenuo.tool()\");\n }\n const existing = allow[policy.capability];\n if (existing !== undefined && !sameAllow(existing, policy.allow)) {\n throw new TenuoConfigurationError(\n `session() allow and tools disagree on ${policy.capability}`,\n );\n }\n allow[policy.capability] = policy.allow;\n }\n return allow;\n}\n\nfunction sameAllow(left: AllowPolicy, right: AllowPolicy): boolean {\n return JSON.stringify(sortedAllow(left)) === JSON.stringify(sortedAllow(right));\n}\n\nfunction sortedAllow(allow: AllowPolicy): AllowPolicy {\n const keys = Object.keys(allow).sort();\n const out: { [field: string]: AllowPolicy[string] } = {};\n for (const key of keys) {\n const value = allow[key];\n if (value !== undefined) {\n out[key] = value;\n }\n }\n return out;\n}\n\n// ---------------------------------------------------------------------------\n// Static helpers: approvals, revocation, receipts, control-plane wire shapes\n// ---------------------------------------------------------------------------\n\nfunction requestHashOf(request: ApprovalRequest | string): string {\n const hash = typeof request === \"string\" ? request : request.requestHash;\n const hex = hash.trim().toLowerCase();\n if (!/^[0-9a-f]{64}$/.test(hex)) {\n throw new TenuoConfigurationError(\"signApproval() needs an ApprovalRequest or a 64-hex request hash\");\n }\n return hex;\n}\n\n/** Sign an approval as an approver. The approver never needs the warrant or the holder key. */\nexport function signApproval(\n request: ApprovalRequest | string,\n approverSecret: Uint8Array,\n options: SignApprovalOptions,\n): string {\n if (!(approverSecret instanceof Uint8Array) || approverSecret.length !== 32) {\n throw new TenuoConfigurationError(\"signApproval() requires a 32-byte approver secret\");\n }\n if (options === null || typeof options !== \"object\" || typeof options.externalId !== \"string\" || options.externalId.trim().length === 0) {\n throw new TenuoConfigurationError(\"signApproval() requires options.externalId: who approved\");\n }\n if (options.ttlSeconds !== undefined && (!Number.isInteger(options.ttlSeconds) || options.ttlSeconds < 1)) {\n throw new TenuoConfigurationError(\"signApproval().ttlSeconds must be a positive integer\");\n }\n const warrantExpiresAt =\n options.warrantExpiresAt ?? (typeof request === \"object\" ? request.warrantExpiresAt : undefined);\n try {\n return loadWasm().sdkSignApprovalForRequest(\n requestHashOf(request),\n approverSecret,\n options.externalId,\n options.ttlSeconds,\n warrantExpiresAt,\n );\n } catch (error) {\n throw new TenuoConfigurationError(errorMessage(error));\n }\n}\n\n/** Decode an approval envelope. Not authorization: the call path still decides. */\nexport function inspectApproval(envelope: string | Uint8Array): ApprovalInfo {\n const text = typeof envelope === \"string\" ? envelope : Buffer.from(envelope).toString(\"base64\");\n let raw;\n try {\n raw = loadWasm().sdkInspectApproval(text);\n } catch (error) {\n throw new TenuoConfigurationError(errorMessage(error));\n }\n const out: { -readonly [K in keyof ApprovalInfo]: ApprovalInfo[K] } = {\n approverPublicKey: raw.approver_public_key,\n requestHash: raw.request_hash,\n externalId: raw.external_id,\n approvedAt: raw.approved_at,\n expiresAt: raw.expires_at,\n expired: raw.expired,\n signatureValid: raw.signature_valid,\n };\n if (raw.error !== undefined) {\n out.error = raw.error;\n }\n return out;\n}\n\n/** Sign a revocation list with an explicit issuer secret. */\nexport function signRevocationList(input: RevocationListInput, issuerSecret: Uint8Array): string {\n if (!(issuerSecret instanceof Uint8Array) || issuerSecret.length !== 32) {\n throw new TenuoConfigurationError(\"signRevocationList() requires a 32-byte issuer secret\");\n }\n const { ids, version } = revocationInput(input);\n try {\n return loadWasm().sdkSignRevocationListVersioned(ids, version, issuerSecret);\n } catch (error) {\n throw new TenuoConfigurationError(errorMessage(error));\n }\n}\n\nexport function inspectRevocationList(wire: string | Uint8Array): RevocationListInfo {\n let raw;\n try {\n raw = loadWasm().sdkInspectRevocationList(normalizeWireBytes(wire));\n } catch (error) {\n throw new TenuoConfigurationError(errorMessage(error));\n }\n return {\n version: raw.version,\n issuedAt: raw.issued_at,\n issuerPublicKey: raw.issuer_public_key,\n revokedIds: [...raw.revoked_ids],\n signatureValid: raw.signature_valid,\n };\n}\n\n/** Signature authenticity of a receipt. Not authorization. */\nexport function verifyReceipt(wire: string | Uint8Array): ReceiptInfo {\n let raw;\n try {\n raw = loadWasm().sdkVerifyReceipt(normalizeWireBytes(wire));\n } catch (error) {\n throw new TenuoConfigurationError(errorMessage(error));\n }\n const out: { -readonly [K in keyof ReceiptInfo]: ReceiptInfo[K] } = {\n authentic: true,\n signerKey: raw.signer_key,\n outcome: raw.outcome,\n action: raw.action,\n requestId: raw.request_id,\n };\n if (raw.decision_code !== undefined) out.decisionCode = raw.decision_code;\n if (raw.srl_version !== undefined) out.srlVersion = raw.srl_version;\n if (raw.srl_hash !== undefined) out.srlHash = raw.srl_hash;\n if (raw.request_hash !== undefined) out.requestHash = raw.request_hash;\n if (raw.policy_definition_hash !== undefined) out.policyDefinitionHash = raw.policy_definition_hash;\n if (raw.prev_receipt_hash !== undefined) out.prevReceiptHash = raw.prev_receipt_hash;\n if (raw.trusted_roots_hash !== undefined) out.trustedRootsHash = raw.trusted_roots_hash;\n return out;\n}\n\n/**\n * Root-anchored receipt check: the embedded warrant chain against `roots`\n * at the receipt's own decision instant. Needs no trust in the signer.\n */\nexport function verifyReceiptChain(wire: string | Uint8Array, roots: readonly PublicKeyHandle[]): ReceiptChainInfo {\n if (!Array.isArray(roots) || roots.length === 0) {\n throw new TenuoConfigurationError(\"verifyReceiptChain() requires at least one trusted root\");\n }\n let raw;\n try {\n raw = loadWasm().sdkVerifyReceiptChain(\n normalizeWireBytes(wire),\n roots.map((r, i) => requirePublicKey(r, `roots[${i}]`).hex),\n );\n } catch (error) {\n throw new TenuoConfigurationError(errorMessage(error));\n }\n const out: { -readonly [K in keyof ReceiptChainInfo]: ReceiptChainInfo[K] } = {\n signerKey: raw.signer_key,\n outcome: raw.outcome,\n timestamp: raw.timestamp,\n chainValid: raw.chain_valid,\n };\n if (raw.decision_code !== undefined) out.decisionCode = raw.decision_code;\n if (raw.chain_error !== undefined) out.chainError = raw.chain_error;\n if (raw.corroborates_denial !== undefined) out.corroboratesDenial = raw.corroborates_denial;\n if (raw.root_issuer !== undefined) out.rootIssuer = raw.root_issuer;\n if (raw.leaf_holder !== undefined) out.leafHolder = raw.leaf_holder;\n return out;\n}\n\n/**\n * The v1 JSON body a control plane's approval API accepts. Same shape the\n * Python SDK produces, so one approval service serves both.\n */\nexport function controlPlaneApprovalRequestV1(\n request: ApprovalRequest,\n options?: {\n readonly attestation?: ApprovalContextAttestation;\n readonly temporal?: Readonly<Record<string, string>>;\n },\n): ControlPlaneApprovalRequestV1 {\n if (request === null || typeof request !== \"object\" || typeof request.requestHash !== \"string\") {\n throw new TenuoConfigurationError(\"controlPlaneApprovalRequestV1() needs an ApprovalRequest from tenuo.approvalRequest()\");\n }\n const body: { -readonly [K in keyof ControlPlaneApprovalRequestV1]: ControlPlaneApprovalRequestV1[K] } = {\n schema_version: 1,\n request_id_hex: request.requestId,\n warrant_id: request.warrantId,\n tool: request.tool,\n arguments: { ...request.args },\n request_hash_hex: request.requestHash,\n holder_public_key_hex: request.holderPublicKey,\n required_approver_keys_hex: [...request.requiredApprovers],\n min_approvals: Math.max(1, request.minApprovals),\n warrant_expires_at_unix: request.warrantExpiresAt,\n created_at_unix: request.createdAt,\n };\n if (options?.attestation !== undefined) {\n const a = options.attestation;\n body.attestation = {\n version: a.version,\n canonicalization: a.canonicalization,\n warrant_id: a.warrantId,\n tool: a.tool,\n request_hash: a.requestHash,\n holder_key_hex: a.holderKeyHex,\n args_canonical_cbor_b64: a.argsCanonicalCborB64,\n signer_key_hex: a.signerKeyHex,\n signature_b64: a.signatureB64,\n // Python readers look for these two names.\n signer_key: a.signerKeyHex,\n signature: a.signatureB64,\n };\n }\n if (options?.temporal !== undefined && Object.keys(options.temporal).length > 0) {\n body.temporal = { ...options.temporal };\n }\n if (request.message.length > 0) {\n body.message = request.message;\n }\n return body;\n}\n\n/** Approval envelopes from a v1 response, ready for `{ approvals }` on the call. Empty unless status is a success. */\nexport function signedApprovalsFromResponseV1(response: ControlPlaneApprovalResponseV1): string[] {\n if (response === null || typeof response !== \"object\" || typeof response.status !== \"string\") {\n throw new TenuoConfigurationError(\"approval response must be an object with a status\");\n }\n if (response.status !== \"approved\") {\n return [];\n }\n const list = response.signed_approvals_b64;\n if (list === undefined || list === null) {\n return [];\n }\n if (!Array.isArray(list) || list.some((item) => typeof item !== \"string\" || item.length === 0)) {\n throw new TenuoConfigurationError(\"signed_approvals_b64 must be an array of base64 strings\");\n }\n return [...list];\n}\n\nfunction createTenuoImpl(options: CreateTenuoOptions = {}): Tenuo {\n if (!hasTrustAnchor(options)) {\n throw new TenuoConfigurationError(\n \"createTenuo() requires trustedRoots or root: createTenuo.devRoot(). An empty trust set is not a configuration.\",\n );\n }\n if (options.root?.kind === \"dev-root\" && !devRootAllowed(options.root)) {\n throw new TenuoConfigurationError(devRootBlockedMessage());\n }\n loadWasm();\n return new TenuoClient(options);\n}\n\nexport const createTenuo: ((options?: CreateTenuoOptions) => Tenuo) & {\n devRoot: typeof devRoot;\n publicKeyFromEnv: typeof publicKeyFromEnv;\n publicKeyFromHex: typeof publicKeyFromHex;\n publicKeyFromBytes: typeof publicKeyFromBytes;\n holderKeyFromEnv: typeof holderKeyFromEnv;\n holderKeyFromHex: typeof holderKeyFromHex;\n generateHolderKey: typeof generateHolderKey;\n generateIssuerKey: typeof generateIssuerKey;\n publicKeyFromHolderKey: typeof publicKeyFromHolderKey;\n issuerKeyFromEnv: typeof issuerKeyFromEnv;\n issuerKeyFromHex: typeof issuerKeyFromHex;\n issuerKeyFromBytes: typeof issuerKeyFromBytes;\n signApproval: typeof signApproval;\n inspectApproval: typeof inspectApproval;\n signRevocationList: typeof signRevocationList;\n inspectRevocationList: typeof inspectRevocationList;\n verifyReceipt: typeof verifyReceipt;\n verifyReceiptChain: typeof verifyReceiptChain;\n controlPlaneApprovalRequestV1: typeof controlPlaneApprovalRequestV1;\n signedApprovalsFromResponseV1: typeof signedApprovalsFromResponseV1;\n parseConnectToken: typeof parseConnectToken;\n identity: typeof identityFromKey;\n generateIdentity: typeof generateIdentity;\n runtime: (options: Parameters<typeof createRuntime>[1]) => ReturnType<typeof createRuntime>;\n} = Object.assign(createTenuoImpl, {\n devRoot,\n publicKeyFromEnv,\n publicKeyFromHex,\n publicKeyFromBytes,\n holderKeyFromEnv,\n holderKeyFromHex,\n generateHolderKey,\n generateIssuerKey,\n publicKeyFromHolderKey,\n issuerKeyFromEnv,\n issuerKeyFromHex,\n issuerKeyFromBytes,\n signApproval,\n inspectApproval,\n signRevocationList,\n inspectRevocationList,\n verifyReceipt,\n verifyReceiptChain,\n controlPlaneApprovalRequestV1,\n signedApprovalsFromResponseV1,\n parseConnectToken,\n identity: identityFromKey,\n generateIdentity,\n runtime: (options: Parameters<typeof createRuntime>[1]) => createRuntime(createTenuoImpl, options),\n});\n"]}
@@ -27,7 +27,32 @@ export declare function range(options: {
27
27
  export declare function oneOf(values: readonly string[]): OneOfConstraint;
28
28
  /** Any value except these. */
29
29
  export declare function notOneOf(values: readonly string[]): NotOneOfConstraint;
30
+ /**
31
+ * Generic string glob. `*` matches `/`; this is not path containment.
32
+ * For filesystem arguments, use `pathGlob(root, glob)`.
33
+ */
30
34
  export declare function pattern(pattern: string): PatternConstraint;
35
+ /**
36
+ * A traversal-safe filesystem glob: the value must stay under `root` and
37
+ * match `glob`.
38
+ *
39
+ * The glob is tested against the whole path, not against the part below
40
+ * `root`, so it matches at any depth:
41
+ *
42
+ * ```ts
43
+ * pathGlob("/workspace", "*.json");
44
+ * // /workspace/reports/q3.json allowed
45
+ * // /workspace/secrets.env denied (glob)
46
+ * // /etc/passwd.json denied (root)
47
+ * ```
48
+ *
49
+ * A delegatee can narrow this to a tighter `pathGlob`, or to an `exact()`
50
+ * path the parent already admits.
51
+ */
52
+ export declare function pathGlob(root: string, glob: string, options?: {
53
+ readonly caseSensitive?: boolean;
54
+ readonly allowEqual?: boolean;
55
+ }): AllConstraint;
31
56
  /** Regular expression, compiled and evaluated in core. */
32
57
  export declare function regex(source: string): RegexConstraint;
33
58
  export declare function exact(value: string | number | boolean): ExactConstraint;
@@ -1,4 +1,21 @@
1
1
  import { TenuoConfigurationError } from "./errors.js";
2
+ /**
3
+ * Builders throw on a misspelled option instead of dropping it: an option
4
+ * that vanishes silently (`urlSafe({ domains })`) widens authority. The core
5
+ * applies the same rule to raw constraint objects when the policy compiles.
6
+ */
7
+ function rejectUnknownOptions(builder, options, allowed) {
8
+ if (options === undefined || options === null) {
9
+ return;
10
+ }
11
+ if (typeof options !== "object" || Array.isArray(options)) {
12
+ throw new TenuoConfigurationError(`tenuo.${builder}() expects an options object`);
13
+ }
14
+ const unknown = Object.keys(options).find((key) => !allowed.includes(key));
15
+ if (unknown !== undefined) {
16
+ throw new TenuoConfigurationError(`tenuo.${builder}() received unknown option "${unknown}"; allowed options: ${allowed.join(", ")}`);
17
+ }
18
+ }
2
19
  /**
3
20
  * Constraint builders. These produce plain marker objects; every one is
4
21
  * evaluated by the Rust core, never in TypeScript. The set matches the
@@ -9,6 +26,7 @@ import { TenuoConfigurationError } from "./errors.js";
9
26
  */
10
27
  /** Directory prefix. Evaluated in core as Subpath — not a string prefix check in TS. */
11
28
  export function under(root, options) {
29
+ rejectUnknownOptions("under", options, ["caseSensitive", "allowEqual"]);
12
30
  if (!root.startsWith("/")) {
13
31
  throw new TenuoConfigurationError("tenuo.under() expects an absolute path (start with /)");
14
32
  }
@@ -25,6 +43,7 @@ export function under(root, options) {
25
43
  return out;
26
44
  }
27
45
  export function email(options) {
46
+ rejectUnknownOptions("email", options, ["domain"]);
28
47
  return { kind: "email", domain: options.domain };
29
48
  }
30
49
  export function max(value) {
@@ -41,6 +60,7 @@ export function min(value) {
41
60
  }
42
61
  /** Numeric interval. Bounds are inclusive unless `minExclusive` / `maxExclusive`. */
43
62
  export function range(options) {
63
+ rejectUnknownOptions("range", options, ["min", "max", "minExclusive", "maxExclusive"]);
44
64
  if (options.min === undefined && options.max === undefined) {
45
65
  throw new TenuoConfigurationError("tenuo.range() requires min, max, or both");
46
66
  }
@@ -80,12 +100,36 @@ export function notOneOf(values) {
80
100
  }
81
101
  return { kind: "notOneOf", values };
82
102
  }
103
+ /**
104
+ * Generic string glob. `*` matches `/`; this is not path containment.
105
+ * For filesystem arguments, use `pathGlob(root, glob)`.
106
+ */
83
107
  export function pattern(pattern) {
84
108
  if (pattern.length === 0) {
85
109
  throw new TenuoConfigurationError("tenuo.pattern() requires a non-empty pattern");
86
110
  }
87
111
  return { kind: "pattern", pattern };
88
112
  }
113
+ /**
114
+ * A traversal-safe filesystem glob: the value must stay under `root` and
115
+ * match `glob`.
116
+ *
117
+ * The glob is tested against the whole path, not against the part below
118
+ * `root`, so it matches at any depth:
119
+ *
120
+ * ```ts
121
+ * pathGlob("/workspace", "*.json");
122
+ * // /workspace/reports/q3.json allowed
123
+ * // /workspace/secrets.env denied (glob)
124
+ * // /etc/passwd.json denied (root)
125
+ * ```
126
+ *
127
+ * A delegatee can narrow this to a tighter `pathGlob`, or to an `exact()`
128
+ * path the parent already admits.
129
+ */
130
+ export function pathGlob(root, glob, options) {
131
+ return all([under(root, options), pattern(glob)]);
132
+ }
89
133
  /** Regular expression, compiled and evaluated in core. */
90
134
  export function regex(source) {
91
135
  if (source.length === 0) {
@@ -119,6 +163,7 @@ export function urlPattern(pattern) {
119
163
  * hosts rejected, optional allow and deny domain lists (`*.example.com`).
120
164
  */
121
165
  export function urlSafe(options) {
166
+ rejectUnknownOptions("urlSafe", options, ["schemes", "allowDomains", "denyDomains"]);
122
167
  const out = { kind: "urlSafe" };
123
168
  if (options?.schemes !== undefined) {
124
169
  out.schemes = options.schemes;
@@ -1 +1 @@
1
- {"version":3,"file":"constraints.js","sourceRoot":"","sources":["../src/constraints.ts"],"names":[],"mappings":"AAwBA,OAAO,EAAE,uBAAuB,EAAE,MAAM,aAAa,CAAC;AAEtD;;;;;;;GAOG;AAEH,wFAAwF;AACxF,MAAM,UAAU,KAAK,CACnB,IAAY,EACZ,OAA6E;IAE7E,IAAI,CAAC,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,EAAE,CAAC;QAC1B,MAAM,IAAI,uBAAuB,CAAC,uDAAuD,CAAC,CAAC;IAC7F,CAAC;IACD,MAAM,GAAG,GAAmF;QAC1F,IAAI,EAAE,OAAO;QACb,IAAI;KACL,CAAC;IACF,IAAI,OAAO,EAAE,aAAa,KAAK,SAAS,EAAE,CAAC;QACzC,GAAG,CAAC,aAAa,GAAG,OAAO,CAAC,aAAa,CAAC;IAC5C,CAAC;IACD,IAAI,OAAO,EAAE,UAAU,KAAK,SAAS,EAAE,CAAC;QACtC,GAAG,CAAC,UAAU,GAAG,OAAO,CAAC,UAAU,CAAC;IACtC,CAAC;IACD,OAAO,GAAG,CAAC;AACb,CAAC;AAED,MAAM,UAAU,KAAK,CAAC,OAA2B;IAC/C,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,EAAE,OAAO,CAAC,MAAM,EAAE,CAAC;AACnD,CAAC;AAED,MAAM,UAAU,GAAG,CAAC,KAAa;IAC/B,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC,EAAE,CAAC;QAC5B,MAAM,IAAI,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C,CAAC;AAED,uGAAuG;AACvG,MAAM,UAAU,GAAG,CAAC,UAA0B;IAC5C,OAAO,EAAE,IAAI,EAAE,KAAK,EAAE,UAAU,EAAE,CAAC;AACrC,CAAC;AAED,uFAAuF;AACvF,MAAM,UAAU,GAAG,CAAC,UAAkB;IACpC,IAAI,UAAU,CAAC,IAAI,EAAE,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QACnC,MAAM,IAAI,uBAAuB,CAAC,6CAA6C,CAAC,CAAC;IACnF,CAAC;IACD,OAAO,EAAE,IAAI,EAAE,KAAK,EAAE,UAAU,EAAE,CAAC;AACrC,CAAC","sourcesContent":["import type {\n AllConstraint,\n AnyOfConstraint,\n CelConstraint,\n CidrConstraint,\n ConstraintExpr,\n ContainsConstraint,\n EmailConstraint,\n ExactConstraint,\n MaxConstraint,\n MinConstraint,\n NotConstraint,\n NotOneOfConstraint,\n OneOfConstraint,\n PatternConstraint,\n RangeConstraint,\n RegexConstraint,\n ShlexConstraint,\n SubsetConstraint,\n UnderConstraint,\n UrlPatternConstraint,\n UrlSafeConstraint,\n WildcardConstraint,\n} from \"./api.ts\";\nimport { TenuoConfigurationError } from \"./errors.ts\";\n\n/**\n * Constraint builders. These produce plain marker objects; every one is\n * evaluated by the Rust core, never in TypeScript. The set matches the\n * Python SDK and the core `Constraint` enum one for one. Builders that\n * validate their input throw `TenuoConfigurationError` at the call site.\n * Deeper checks, such as regex syntax, run in the core when `session()`\n * compiles the policy. Nothing here makes an authorization decision.\n */\n\n/** Directory prefix. Evaluated in core as Subpath — not a string prefix check in TS. */\nexport function under(\n root: string,\n options?: { readonly caseSensitive?: boolean; readonly allowEqual?: boolean },\n): UnderConstraint {\n if (!root.startsWith(\"/\")) {\n throw new TenuoConfigurationError(\"tenuo.under() expects an absolute path (start with /)\");\n }\n const out: { kind: \"under\"; root: string; caseSensitive?: boolean; allowEqual?: boolean } = {\n kind: \"under\",\n root,\n };\n if (options?.caseSensitive !== undefined) {\n out.caseSensitive = options.caseSensitive;\n }\n if (options?.allowEqual !== undefined) {\n out.allowEqual = options.allowEqual;\n }\n return out;\n}\n\nexport function email(options: { domain: string }): EmailConstraint {\n return { kind: \"email\", domain: options.domain };\n}\n\nexport function max(value: number): MaxConstraint {\n if (!Number.isFinite(value)) {\n throw new TenuoConfigurationError(\"tenuo.max() requires a finite number\");\n }\n return { kind: \"max\", value };\n}\n\nexport function min(value: number): MinConstraint {\n if (!Number.isFinite(value)) {\n throw new TenuoConfigurationError(\"tenuo.min() requires a finite number\");\n }\n return { kind: \"min\", value };\n}\n\n/** Numeric interval. Bounds are inclusive unless `minExclusive` / `maxExclusive`. */\nexport function range(options: {\n readonly min?: number;\n readonly max?: number;\n readonly minExclusive?: boolean;\n readonly maxExclusive?: boolean;\n}): RangeConstraint {\n if (options.min === undefined && options.max === undefined) {\n throw new TenuoConfigurationError(\"tenuo.range() requires min, max, or both\");\n }\n for (const bound of [options.min, options.max]) {\n if (bound !== undefined && !Number.isFinite(bound)) {\n throw new TenuoConfigurationError(\"tenuo.range() bounds must be finite numbers\");\n }\n }\n if (options.min !== undefined && options.max !== undefined && options.min > options.max) {\n throw new TenuoConfigurationError(\"tenuo.range() min must not exceed max\");\n }\n const out: {\n kind: \"range\";\n min?: number;\n max?: number;\n minExclusive?: boolean;\n maxExclusive?: boolean;\n } = { kind: \"range\" };\n if (options.min !== undefined) {\n out.min = options.min;\n }\n if (options.max !== undefined) {\n out.max = options.max;\n }\n if (options.minExclusive === true) {\n out.minExclusive = true;\n }\n if (options.maxExclusive === true) {\n out.maxExclusive = true;\n }\n return out;\n}\n\nexport function oneOf(values: readonly string[]): OneOfConstraint {\n if (values.length === 0) {\n throw new TenuoConfigurationError(\"tenuo.oneOf() requires at least one value\");\n }\n return { kind: \"oneOf\", values };\n}\n\n/** Any value except these. */\nexport function notOneOf(values: readonly string[]): NotOneOfConstraint {\n if (values.length === 0) {\n throw new TenuoConfigurationError(\"tenuo.notOneOf() requires at least one value\");\n }\n return { kind: \"notOneOf\", values };\n}\n\nexport function pattern(pattern: string): PatternConstraint {\n if (pattern.length === 0) {\n throw new TenuoConfigurationError(\"tenuo.pattern() requires a non-empty pattern\");\n }\n return { kind: \"pattern\", pattern };\n}\n\n/** Regular expression, compiled and evaluated in core. */\nexport function regex(source: string): RegexConstraint {\n if (source.length === 0) {\n throw new TenuoConfigurationError(\"tenuo.regex() requires a non-empty expression\");\n }\n return { kind: \"regex\", source };\n}\n\nexport function exact(value: string | number | boolean): ExactConstraint {\n return { kind: \"exact\", value };\n}\n\n/** Any value at all. Name it in a zero-trust policy to allow an argument without constraining it. */\nexport function wildcard(): WildcardConstraint {\n return { kind: \"wildcard\" };\n}\n\n/** IP address inside a network, e.g. `cidr(\"10.0.0.0/8\")`. */\nexport function cidr(network: string): CidrConstraint {\n if (!network.includes(\"/\")) {\n throw new TenuoConfigurationError(\"tenuo.cidr() expects CIDR notation like 10.0.0.0/8\");\n }\n return { kind: \"cidr\", network };\n}\n\n/** URL glob, e.g. `urlPattern(\"https://*.example.com/api/*\")`. Parsed as a URL, not a string. */\nexport function urlPattern(pattern: string): UrlPatternConstraint {\n if (pattern.length === 0) {\n throw new TenuoConfigurationError(\"tenuo.urlPattern() requires a non-empty pattern\");\n }\n return { kind: \"urlPattern\", pattern };\n}\n\n/**\n * SSRF-aware URL check: http/https only by default, private and link-local\n * hosts rejected, optional allow and deny domain lists (`*.example.com`).\n */\nexport function urlSafe(options?: {\n readonly schemes?: readonly string[];\n readonly allowDomains?: readonly string[];\n readonly denyDomains?: readonly string[];\n}): UrlSafeConstraint {\n const out: {\n kind: \"urlSafe\";\n schemes?: readonly string[];\n allowDomains?: readonly string[];\n denyDomains?: readonly string[];\n } = { kind: \"urlSafe\" };\n if (options?.schemes !== undefined) {\n out.schemes = options.schemes;\n }\n if (options?.allowDomains !== undefined) {\n out.allowDomains = options.allowDomains;\n }\n if (options?.denyDomains !== undefined) {\n out.denyDomains = options.denyDomains;\n }\n return out;\n}\n\n/** Shell command whose first word must be one of `allow`. Parsed with shell quoting rules in core. */\nexport function shlex(allow: readonly string[]): ShlexConstraint {\n if (allow.length === 0) {\n throw new TenuoConfigurationError(\"tenuo.shlex() requires at least one allowed command\");\n }\n return { kind: \"shlex\", allow };\n}\n\n/** List argument that must include every one of these values. */\nexport function contains(values: readonly (string | number | boolean)[]): ContainsConstraint {\n if (values.length === 0) {\n throw new TenuoConfigurationError(\"tenuo.contains() requires at least one value\");\n }\n return { kind: \"contains\", values };\n}\n\n/** List argument whose every element must be one of these values. */\nexport function subset(values: readonly (string | number | boolean)[]): SubsetConstraint {\n if (values.length === 0) {\n throw new TenuoConfigurationError(\"tenuo.subset() requires at least one value\");\n }\n return { kind: \"subset\", values };\n}\n\n/** Satisfied when at least one inner constraint is. */\nexport function anyOf(constraints: readonly ConstraintExpr[]): AnyOfConstraint {\n if (constraints.length === 0) {\n throw new TenuoConfigurationError(\"tenuo.anyOf() requires at least one constraint\");\n }\n return { kind: \"anyOf\", constraints };\n}\n\n/** Satisfied only when every inner constraint is. */\nexport function all(constraints: readonly ConstraintExpr[]): AllConstraint {\n if (constraints.length === 0) {\n throw new TenuoConfigurationError(\"tenuo.all() requires at least one constraint\");\n }\n return { kind: \"all\", constraints };\n}\n\n/** Satisfied when the inner constraint is not. Delegation cannot narrow a `not`; prefer `notOneOf`. */\nexport function not(constraint: ConstraintExpr): NotConstraint {\n return { kind: \"not\", constraint };\n}\n\n/** Common Expression Language predicate over the argument value, evaluated in core. */\nexport function cel(expression: string): CelConstraint {\n if (expression.trim().length === 0) {\n throw new TenuoConfigurationError(\"tenuo.cel() requires a non-empty expression\");\n }\n return { kind: \"cel\", expression };\n}\n"]}
1
+ {"version":3,"file":"constraints.js","sourceRoot":"","sources":["../src/constraints.ts"],"names":[],"mappings":"AAwBA,OAAO,EAAE,uBAAuB,EAAE,MAAM,aAAa,CAAC;AAEtD;;;;GAIG;AACH,SAAS,oBAAoB,CAC3B,OAAe,EACf,OAAgB,EAChB,OAA0B;IAE1B,IAAI,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idrConstraint,\n ConstraintExpr,\n ContainsConstraint,\n EmailConstraint,\n ExactConstraint,\n MaxConstraint,\n MinConstraint,\n NotConstraint,\n NotOneOfConstraint,\n OneOfConstraint,\n PatternConstraint,\n RangeConstraint,\n RegexConstraint,\n ShlexConstraint,\n SubsetConstraint,\n UnderConstraint,\n UrlPatternConstraint,\n UrlSafeConstraint,\n WildcardConstraint,\n} from \"./api.ts\";\nimport { TenuoConfigurationError } from \"./errors.ts\";\n\n/**\n * Builders throw on a misspelled option instead of dropping it: an option\n * that vanishes silently (`urlSafe({ domains })`) widens authority. The core\n * applies the same rule to raw constraint objects when the policy compiles.\n */\nfunction rejectUnknownOptions(\n builder: string,\n options: unknown,\n allowed: readonly string[],\n): void {\n if (options === undefined || options === null) {\n return;\n }\n if (typeof options !== \"object\" || Array.isArray(options)) {\n throw new TenuoConfigurationError(`tenuo.${builder}() expects an options object`);\n }\n const unknown = Object.keys(options).find((key) => !allowed.includes(key));\n if (unknown !== undefined) {\n throw new TenuoConfigurationError(\n `tenuo.${builder}() received unknown option \"${unknown}\"; allowed options: ${allowed.join(\", \")}`,\n );\n }\n}\n\n/**\n * Constraint builders. These produce plain marker objects; every one is\n * evaluated by the Rust core, never in TypeScript. The set matches the\n * Python SDK and the core `Constraint` enum one for one. Builders that\n * validate their input throw `TenuoConfigurationError` at the call site.\n * Deeper checks, such as regex syntax, run in the core when `session()`\n * compiles the policy. Nothing here makes an authorization decision.\n */\n\n/** Directory prefix. Evaluated in core as Subpath — not a string prefix check in TS. */\nexport function under(\n root: string,\n options?: { readonly caseSensitive?: boolean; readonly allowEqual?: boolean },\n): UnderConstraint {\n rejectUnknownOptions(\"under\", options, [\"caseSensitive\", \"allowEqual\"]);\n if (!root.startsWith(\"/\")) {\n throw new TenuoConfigurationError(\"tenuo.under() expects an absolute path (start with /)\");\n }\n const out: { kind: \"under\"; root: string; caseSensitive?: boolean; allowEqual?: boolean } = {\n kind: \"under\",\n root,\n };\n if (options?.caseSensitive !== undefined) {\n out.caseSensitive = options.caseSensitive;\n }\n if (options?.allowEqual !== undefined) {\n out.allowEqual = options.allowEqual;\n }\n return out;\n}\n\nexport function email(options: { domain: string }): EmailConstraint {\n rejectUnknownOptions(\"email\", options, [\"domain\"]);\n return { kind: \"email\", domain: options.domain };\n}\n\nexport function max(value: number): MaxConstraint {\n if (!Number.isFinite(value)) {\n throw new TenuoConfigurationError(\"tenuo.max() requires a finite number\");\n }\n return { kind: \"max\", value };\n}\n\nexport function min(value: number): MinConstraint {\n if (!Number.isFinite(value)) {\n throw new TenuoConfigurationError(\"tenuo.min() requires a finite number\");\n }\n return { kind: \"min\", value };\n}\n\n/** Numeric interval. Bounds are inclusive unless `minExclusive` / `maxExclusive`. */\nexport function range(options: {\n readonly min?: number;\n readonly max?: number;\n readonly minExclusive?: boolean;\n readonly maxExclusive?: boolean;\n}): RangeConstraint {\n rejectUnknownOptions(\"range\", options, [\"min\", \"max\", \"minExclusive\", \"maxExclusive\"]);\n if (options.min === undefined && options.max === undefined) {\n throw new TenuoConfigurationError(\"tenuo.range() requires min, max, or both\");\n }\n for (const bound of [options.min, options.max]) {\n if (bound !== undefined && !Number.isFinite(bound)) {\n throw new TenuoConfigurationError(\"tenuo.range() bounds must be finite numbers\");\n }\n }\n if (options.min !== undefined && options.max !== undefined && options.min > options.max) {\n throw new TenuoConfigurationError(\"tenuo.range() min must not exceed max\");\n }\n const out: {\n kind: \"range\";\n min?: number;\n max?: number;\n minExclusive?: boolean;\n maxExclusive?: boolean;\n } = { kind: \"range\" };\n if (options.min !== undefined) {\n out.min = options.min;\n }\n if (options.max !== undefined) {\n out.max = options.max;\n }\n if (options.minExclusive === true) {\n out.minExclusive = true;\n }\n if (options.maxExclusive === true) {\n out.maxExclusive = true;\n }\n return out;\n}\n\nexport function oneOf(values: readonly string[]): OneOfConstraint {\n if (values.length === 0) {\n throw new TenuoConfigurationError(\"tenuo.oneOf() requires at least one value\");\n }\n return { kind: \"oneOf\", values };\n}\n\n/** Any value except these. */\nexport function notOneOf(values: readonly string[]): NotOneOfConstraint {\n if (values.length === 0) {\n throw new TenuoConfigurationError(\"tenuo.notOneOf() requires at least one value\");\n }\n return { kind: \"notOneOf\", values };\n}\n\n/**\n * Generic string glob. `*` matches `/`; this is not path containment.\n * For filesystem arguments, use `pathGlob(root, glob)`.\n */\nexport function pattern(pattern: string): PatternConstraint {\n if (pattern.length === 0) {\n throw new TenuoConfigurationError(\"tenuo.pattern() requires a non-empty pattern\");\n }\n return { kind: \"pattern\", pattern };\n}\n\n/**\n * A traversal-safe filesystem glob: the value must stay under `root` and\n * match `glob`.\n *\n * The glob is tested against the whole path, not against the part below\n * `root`, so it matches at any depth:\n *\n * ```ts\n * pathGlob(\"/workspace\", \"*.json\");\n * // /workspace/reports/q3.json allowed\n * // /workspace/secrets.env denied (glob)\n * // /etc/passwd.json denied (root)\n * ```\n *\n * A delegatee can narrow this to a tighter `pathGlob`, or to an `exact()`\n * path the parent already admits.\n */\nexport function pathGlob(\n root: string,\n glob: string,\n options?: { readonly caseSensitive?: boolean; readonly allowEqual?: boolean },\n): AllConstraint {\n return all([under(root, options), pattern(glob)]);\n}\n\n/** Regular expression, compiled and evaluated in core. */\nexport function regex(source: string): RegexConstraint {\n if (source.length === 0) {\n throw new TenuoConfigurationError(\"tenuo.regex() requires a non-empty expression\");\n }\n return { kind: \"regex\", source };\n}\n\nexport function exact(value: string | number | boolean): ExactConstraint {\n return { kind: \"exact\", value };\n}\n\n/** Any value at all. Name it in a zero-trust policy to allow an argument without constraining it. */\nexport function wildcard(): WildcardConstraint {\n return { kind: \"wildcard\" };\n}\n\n/** IP address inside a network, e.g. `cidr(\"10.0.0.0/8\")`. */\nexport function cidr(network: string): CidrConstraint {\n if (!network.includes(\"/\")) {\n throw new TenuoConfigurationError(\"tenuo.cidr() expects CIDR notation like 10.0.0.0/8\");\n }\n return { kind: \"cidr\", network };\n}\n\n/** URL glob, e.g. `urlPattern(\"https://*.example.com/api/*\")`. Parsed as a URL, not a string. */\nexport function urlPattern(pattern: string): UrlPatternConstraint {\n if (pattern.length === 0) {\n throw new TenuoConfigurationError(\"tenuo.urlPattern() requires a non-empty pattern\");\n }\n return { kind: \"urlPattern\", pattern };\n}\n\n/**\n * SSRF-aware URL check: http/https only by default, private and link-local\n * hosts rejected, optional allow and deny domain lists (`*.example.com`).\n */\nexport function urlSafe(options?: {\n readonly schemes?: readonly string[];\n readonly allowDomains?: readonly string[];\n readonly denyDomains?: readonly string[];\n}): UrlSafeConstraint {\n rejectUnknownOptions(\"urlSafe\", options, [\"schemes\", \"allowDomains\", \"denyDomains\"]);\n const out: {\n kind: \"urlSafe\";\n schemes?: readonly string[];\n allowDomains?: readonly string[];\n denyDomains?: readonly string[];\n } = { kind: \"urlSafe\" };\n if (options?.schemes !== undefined) {\n out.schemes = options.schemes;\n }\n if (options?.allowDomains !== undefined) {\n out.allowDomains = options.allowDomains;\n }\n if (options?.denyDomains !== undefined) {\n out.denyDomains = options.denyDomains;\n }\n return out;\n}\n\n/** Shell command whose first word must be one of `allow`. Parsed with shell quoting rules in core. */\nexport function shlex(allow: readonly string[]): ShlexConstraint {\n if (allow.length === 0) {\n throw new TenuoConfigurationError(\"tenuo.shlex() requires at least one allowed command\");\n }\n return { kind: \"shlex\", allow };\n}\n\n/** List argument that must include every one of these values. */\nexport function contains(values: readonly (string | number | boolean)[]): ContainsConstraint {\n if (values.length === 0) {\n throw new TenuoConfigurationError(\"tenuo.contains() requires at least one value\");\n }\n return { kind: \"contains\", values };\n}\n\n/** List argument whose every element must be one of these values. */\nexport function subset(values: readonly (string | number | boolean)[]): SubsetConstraint {\n if (values.length === 0) {\n throw new TenuoConfigurationError(\"tenuo.subset() requires at least one value\");\n }\n return { kind: \"subset\", values };\n}\n\n/** Satisfied when at least one inner constraint is. */\nexport function anyOf(constraints: readonly ConstraintExpr[]): AnyOfConstraint {\n if (constraints.length === 0) {\n throw new TenuoConfigurationError(\"tenuo.anyOf() requires at least one constraint\");\n }\n return { kind: \"anyOf\", constraints };\n}\n\n/** Satisfied only when every inner constraint is. */\nexport function all(constraints: readonly ConstraintExpr[]): AllConstraint {\n if (constraints.length === 0) {\n throw new TenuoConfigurationError(\"tenuo.all() requires at least one constraint\");\n }\n return { kind: \"all\", constraints };\n}\n\n/** Satisfied when the inner constraint is not. Delegation cannot narrow a `not`; prefer `notOneOf`. */\nexport function not(constraint: ConstraintExpr): NotConstraint {\n return { kind: \"not\", constraint };\n}\n\n/** Common Expression Language predicate over the argument value, evaluated in core. */\nexport function cel(expression: string): CelConstraint {\n if (expression.trim().length === 0) {\n throw new TenuoConfigurationError(\"tenuo.cel() requires a non-empty expression\");\n }\n return { kind: \"cel\", expression };\n}\n"]}
Binary file
package/dist/index.d.ts CHANGED
@@ -2,7 +2,7 @@ export type { ApprovalGateInspection, ApprovalRequirement, ApprovalRequirementSt
2
2
  export { approvalRequirement, evaluateApprovalGates, inspectApprovalGate } from "./wasm.ts";
3
3
  export type { AllConstraint, AllowPolicy, AnyOfConstraint, ApprovalContextAttestation, ApprovalInfo, ApprovalRequest, ApprovalRequestSummary, ArgApprovalGate, CelConstraint, CidrConstraint, Clearance, ConstraintExpr, ContainsConstraint, ControlPlaneApprovalRequestV1, ControlPlaneApprovalResponseV1, CreateTenuoOptions, Decision, DevRoot, EmailConstraint, ExactConstraint, ExecuteOptions, ExplainedField, Explanation, IssueInput, IssuerKey, MaxConstraint, McpAttachOptions, McpCallParams, McpHandlerPolicy, McpJsonRpcError, McpVerifyOptions, MinConstraint, NarrowInput, NarrowOptions, NonceStore, NotConstraint, NotOneOfConstraint, OneOfConstraint, PatternConstraint, PresentedCall, ProtectedTool, PublicKeyHandle, RangeConstraint, ReceiptChainInfo, ReceiptInfo, RegexConstraint, RequireApproval, RevocationListInfo, RevocationListInput, Session, SessionAllow, SessionFromWireInput, SessionInfo, SessionInput, ShlexConstraint, SignApprovalOptions, SubsetConstraint, Tenuo, LegacyTenuoErrorCode, ProtocolDenialCode, TenuoErrorCode, TenuoMcp, TenuoMcpMeta, ToolApprovalGate, ToolLike, ToolPolicy, UnderConstraint, UrlPatternConstraint, UrlSafeConstraint, WarrantPart, WildcardConstraint, } from "./api.ts";
4
4
  export { ApprovalRequiredError, AuthorizationDeniedError, TenuoConfigurationError, TenuoError, } from "./errors.ts";
5
- export { all, anyOf, cel, cidr, contains, email, exact, max, min, not, notOneOf, oneOf, pattern, range, regex, shlex, subset, under, urlPattern, urlSafe, wildcard, } from "./constraints.ts";
5
+ export { all, anyOf, cel, cidr, contains, email, exact, max, min, not, notOneOf, oneOf, pathGlob, pattern, range, regex, shlex, subset, under, urlPattern, urlSafe, wildcard, } from "./constraints.ts";
6
6
  export { memoryNonceStore } from "./nonce.ts";
7
7
  export { Session as SessionHandle, isSession } from "./session.ts";
8
8
  export { ConnectToken, parseConnectToken } from "./connect.ts";
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  export { approvalRequirement, evaluateApprovalGates, inspectApprovalGate } from "./wasm.js";
2
2
  export { ApprovalRequiredError, AuthorizationDeniedError, TenuoConfigurationError, TenuoError, } from "./errors.js";
3
- export { all, anyOf, cel, cidr, contains, email, exact, max, min, not, notOneOf, oneOf, pattern, range, regex, shlex, subset, under, urlPattern, urlSafe, wildcard, } from "./constraints.js";
3
+ export { all, anyOf, cel, cidr, contains, email, exact, max, min, not, notOneOf, oneOf, pathGlob, pattern, range, regex, shlex, subset, under, urlPattern, urlSafe, wildcard, } from "./constraints.js";
4
4
  export { memoryNonceStore } from "./nonce.js";
5
5
  export { Session as SessionHandle, isSession } from "./session.js";
6
6
  export { ConnectToken, parseConnectToken } from "./connect.js";
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAMA,OAAO,EAAE,mBAAmB,EAAE,qBAAqB,EAAE,mBAAmB,EAAE,MAAM,WAAW,CAAC;AA4E5F,OAAO,EACL,qBAAqB,EACrB,wBAAwB,EACxB,uBAAuB,EACvB,UAAU,GACX,MAAM,aAAa,CAAC;AAErB,OAAO,EACL,GAAG,EACH,KAAK,EACL,GAAG,EACH,IAAI,EACJ,QAAQ,EACR,KAAK,EACL,KAAK,EACL,GAAG,EACH,GAAG,EACH,GAAG,EACH,QAAQ,EACR,KAAK,EACL,OAAO,EACP,KAAK,EACL,KAAK,EACL,KAAK,EACL,MAAM,EACN,KAAK,EACL,UAAU,EACV,OAAO,EACP,QAAQ,GACT,MAAM,kBAAkB,CAAC;AAE1B,OAAO,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AAE9C,OAAO,EAAE,OAAO,IAAI,aAAa,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AAEnE,OAAO,EAAE,YAAY,EAAE,iBAAiB,EAAE,MAAM,cAAc,CAAC;AAG/D,OAAO,EAAE,cAAc,EAAE,gBAAgB,EAAE,eAAe,EAAE,MAAM,eAAe,CAAC;AAElF,OAAO,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AAGvC,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC","sourcesContent":["export type {\n ApprovalGateInspection,\n ApprovalRequirement,\n ApprovalRequirementStatus,\n} from \"./wasm.ts\";\n\nexport { approvalRequirement, evaluateApprovalGates, inspectApprovalGate } from \"./wasm.ts\";\n\nexport type {\n AllConstraint,\n AllowPolicy,\n AnyOfConstraint,\n ApprovalContextAttestation,\n ApprovalInfo,\n ApprovalRequest,\n ApprovalRequestSummary,\n ArgApprovalGate,\n CelConstraint,\n CidrConstraint,\n Clearance,\n ConstraintExpr,\n ContainsConstraint,\n ControlPlaneApprovalRequestV1,\n ControlPlaneApprovalResponseV1,\n CreateTenuoOptions,\n Decision,\n DevRoot,\n EmailConstraint,\n ExactConstraint,\n ExecuteOptions,\n ExplainedField,\n Explanation,\n IssueInput,\n IssuerKey,\n MaxConstraint,\n McpAttachOptions,\n McpCallParams,\n McpHandlerPolicy,\n McpJsonRpcError,\n McpVerifyOptions,\n MinConstraint,\n NarrowInput,\n NarrowOptions,\n NonceStore,\n NotConstraint,\n NotOneOfConstraint,\n OneOfConstraint,\n PatternConstraint,\n PresentedCall,\n ProtectedTool,\n PublicKeyHandle,\n RangeConstraint,\n ReceiptChainInfo,\n ReceiptInfo,\n RegexConstraint,\n RequireApproval,\n RevocationListInfo,\n RevocationListInput,\n Session,\n SessionAllow,\n SessionFromWireInput,\n SessionInfo,\n SessionInput,\n ShlexConstraint,\n SignApprovalOptions,\n SubsetConstraint,\n Tenuo,\n LegacyTenuoErrorCode,\n ProtocolDenialCode,\n TenuoErrorCode,\n TenuoMcp,\n TenuoMcpMeta,\n ToolApprovalGate,\n ToolLike,\n ToolPolicy,\n UnderConstraint,\n UrlPatternConstraint,\n UrlSafeConstraint,\n WarrantPart,\n WildcardConstraint,\n} from \"./api.ts\";\n\nexport {\n ApprovalRequiredError,\n AuthorizationDeniedError,\n TenuoConfigurationError,\n TenuoError,\n} from \"./errors.ts\";\n\nexport {\n all,\n anyOf,\n cel,\n cidr,\n contains,\n email,\n exact,\n max,\n min,\n not,\n notOneOf,\n oneOf,\n pattern,\n range,\n regex,\n shlex,\n subset,\n under,\n urlPattern,\n urlSafe,\n wildcard,\n} from \"./constraints.ts\";\n\nexport { memoryNonceStore } from \"./nonce.ts\";\n\nexport { Session as SessionHandle, isSession } from \"./session.ts\";\n\nexport { ConnectToken, parseConnectToken } from \"./connect.ts\";\nexport type { ResolveEndpointOptions } from \"./connect.ts\";\n\nexport { HolderIdentity, generateIdentity, identityFromKey } from \"./identity.ts\";\n\nexport { Runtime } from \"./runtime.ts\";\nexport type { ReceiptsMode, RuntimeOptions, SessionWarrant } from \"./runtime.ts\";\n\nexport { createTenuo } from \"./client.ts\";\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAMA,OAAO,EAAE,mBAAmB,EAAE,qBAAqB,EAAE,mBAAmB,EAAE,MAAM,WAAW,CAAC;AA4E5F,OAAO,EACL,qBAAqB,EACrB,wBAAwB,EACxB,uBAAuB,EACvB,UAAU,GACX,MAAM,aAAa,CAAC;AAErB,OAAO,EACL,GAAG,EACH,KAAK,EACL,GAAG,EACH,IAAI,EACJ,QAAQ,EACR,KAAK,EACL,KAAK,EACL,GAAG,EACH,GAAG,EACH,GAAG,EACH,QAAQ,EACR,KAAK,EACL,QAAQ,EACR,OAAO,EACP,KAAK,EACL,KAAK,EACL,KAAK,EACL,MAAM,EACN,KAAK,EACL,UAAU,EACV,OAAO,EACP,QAAQ,GACT,MAAM,kBAAkB,CAAC;AAE1B,OAAO,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AAE9C,OAAO,EAAE,OAAO,IAAI,aAAa,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AAEnE,OAAO,EAAE,YAAY,EAAE,iBAAiB,EAAE,MAAM,cAAc,CAAC;AAG/D,OAAO,EAAE,cAAc,EAAE,gBAAgB,EAAE,eAAe,EAAE,MAAM,eAAe,CAAC;AAElF,OAAO,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AAGvC,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC","sourcesContent":["export type {\n ApprovalGateInspection,\n ApprovalRequirement,\n ApprovalRequirementStatus,\n} from \"./wasm.ts\";\n\nexport { approvalRequirement, evaluateApprovalGates, inspectApprovalGate } from \"./wasm.ts\";\n\nexport type {\n AllConstraint,\n AllowPolicy,\n AnyOfConstraint,\n ApprovalContextAttestation,\n ApprovalInfo,\n ApprovalRequest,\n ApprovalRequestSummary,\n ArgApprovalGate,\n CelConstraint,\n CidrConstraint,\n Clearance,\n ConstraintExpr,\n ContainsConstraint,\n ControlPlaneApprovalRequestV1,\n ControlPlaneApprovalResponseV1,\n CreateTenuoOptions,\n Decision,\n DevRoot,\n EmailConstraint,\n ExactConstraint,\n ExecuteOptions,\n ExplainedField,\n Explanation,\n IssueInput,\n IssuerKey,\n MaxConstraint,\n McpAttachOptions,\n McpCallParams,\n McpHandlerPolicy,\n McpJsonRpcError,\n McpVerifyOptions,\n MinConstraint,\n NarrowInput,\n NarrowOptions,\n NonceStore,\n NotConstraint,\n NotOneOfConstraint,\n OneOfConstraint,\n PatternConstraint,\n PresentedCall,\n ProtectedTool,\n PublicKeyHandle,\n RangeConstraint,\n ReceiptChainInfo,\n ReceiptInfo,\n RegexConstraint,\n RequireApproval,\n RevocationListInfo,\n RevocationListInput,\n Session,\n SessionAllow,\n SessionFromWireInput,\n SessionInfo,\n SessionInput,\n ShlexConstraint,\n SignApprovalOptions,\n SubsetConstraint,\n Tenuo,\n LegacyTenuoErrorCode,\n ProtocolDenialCode,\n TenuoErrorCode,\n TenuoMcp,\n TenuoMcpMeta,\n ToolApprovalGate,\n ToolLike,\n ToolPolicy,\n UnderConstraint,\n UrlPatternConstraint,\n UrlSafeConstraint,\n WarrantPart,\n WildcardConstraint,\n} from \"./api.ts\";\n\nexport {\n ApprovalRequiredError,\n AuthorizationDeniedError,\n TenuoConfigurationError,\n TenuoError,\n} from \"./errors.ts\";\n\nexport {\n all,\n anyOf,\n cel,\n cidr,\n contains,\n email,\n exact,\n max,\n min,\n not,\n notOneOf,\n oneOf,\n pathGlob,\n pattern,\n range,\n regex,\n shlex,\n subset,\n under,\n urlPattern,\n urlSafe,\n wildcard,\n} from \"./constraints.ts\";\n\nexport { memoryNonceStore } from \"./nonce.ts\";\n\nexport { Session as SessionHandle, isSession } from \"./session.ts\";\n\nexport { ConnectToken, parseConnectToken } from \"./connect.ts\";\nexport type { ResolveEndpointOptions } from \"./connect.ts\";\n\nexport { HolderIdentity, generateIdentity, identityFromKey } from \"./identity.ts\";\n\nexport { Runtime } from \"./runtime.ts\";\nexport type { ReceiptsMode, RuntimeOptions, SessionWarrant } from \"./runtime.ts\";\n\nexport { createTenuo } from \"./client.ts\";\n"]}
package/dist/wasm.d.ts CHANGED
@@ -147,6 +147,7 @@ export type WasmExplainField = {
147
147
  constraint: unknown;
148
148
  value?: unknown;
149
149
  satisfied: boolean;
150
+ reason_code?: string;
150
151
  reason?: string;
151
152
  };
152
153
  export type WasmExplain = {
package/dist/wasm.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"wasm.js","sourceRoot":"","sources":["../src/wasm.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAC5C,OAAO,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AACrC,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAC1C,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AACzC,OAAO,EAAE,uBAAuB,EAAE,MAAM,aAAa,CAAC;AAiUtD,IAAI,MAA6B,CAAC;AAElC,SAAS,aAAa;IACpB,MAAM,IAAI,GAAG,OAAO,CAAC,aAAa,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC;IACrD,OAAO,IAAI,CAAC,IAAI,EAAE,WAAW,EAAE,eAAe,CAAC,CAAC;AAClD,CAAC;AAED,MAAM,UAAU,aAAa;IAC3B,OAAO,UAAU,CAAC,aAAa,EAAE,CAAC,CAAC;AACrC,CAAC;AAED,MAAM,cAAc,GAClB,8NAA8N,CAAC;AAEjO,MAAM,UAAU,QAAQ;IACtB,IAAI,MAAM,EAAE,CAAC;QACX,OAAO,MAAM,CAAC;IAChB,CAAC;IACD,MAAM,IAAI,GAAG,aAAa,EAAE,CAAC;IAC7B,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,EAAE,CAAC;QACtB,MAAM,IAAI,uBAAuB,CAAC,cAAc,EAAE,iBAAiB,CAAC,CAAC;IACvE,CAAC;IACD,IAAI,CAAC;QACH,MAAM,OAAO,GAAG,aAAa,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;QAC/C,MAAM,GAAG,OAAO,CAAC,IAAI,CAAc,CAAC;QACpC,OAAO,MAAM,CAAC;IAChB,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,MAAM,OA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KAAyB;IACjD,IAAI,KAAK,EAAE,CAAC;QACV,MAAM,IAAI,uBAAuB,CAAC,KAAK,CAAC,CAAC;IAC3C,CAAC;AACH,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,mBAAmB,CACjC,UAAkB,EAClB,IAAY,EACZ,IAA6B;IAE7B,MAAM,MAAM,GAAG,gBAAgB,EAAE,CAAC,oBAAoB,CAAC,UAAU,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC;IAC/E,gBAAgB,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;IAC/B,OAAO,MAAM,CAAC;AAChB,CAAC;AAED,wEAAwE;AACxE,MAAM,UAAU,mBAAmB,CAAC,UAAkB,EAAE,IAAY;IAClE,MAAM,MAAM,GAAG,gBAAgB,EAAE,CAAC,qBAAqB,CAAC,UAAU,EAAE,IAAI,CAAC,CAAC;IAC1E,gBAAgB,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;IAC/B,OAAO,MAAM,CAAC;AAChB,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,qBAAqB,CACnC,UAAkB,EAClB,IAAY,EACZ,IAA6B;IAE7B,MAAM,MAAM,GAAG,gBAAgB,EAAE,CAAC,uBAAuB,CAAC,UAAU,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC;IAClF,gBAAgB,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;IAC/B,OAAO,MAAM,CAAC,iBAAiB,CAAC;AAClC,CAAC","sourcesContent":["import { createRequire } from \"node:module\";\nimport { existsSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { TenuoConfigurationError } from \"./errors.ts\";\nimport type { TenuoErrorCode } from \"./api.ts\";\n\nexport type WasmDecision = {\n outcome: \"allow\" | \"deny\" | \"approval_required\";\n code?: TenuoErrorCode;\n field?: string;\n message?: string;\n args?: Record<string, unknown>;\n tool?: string;\n required?: number;\n received?: number;\n receipt?: string;\n};\n\nexport type WasmInspect = {\n payload_hex: string;\n signature_hex: string;\n id: string;\n};\n\nexport type WasmReceipt = {\n authentic: true;\n /** Hex key the receipt is signed under — resolve against your authorizer set. */\n signer_key: string;\n outcome: \"allow\" | \"deny\";\n action: string;\n decision_code?: string;\n request_id: string;\n /** Version of the revocation list in force, when it carried one. */\n srl_version?: number;\n /**\n * SHA-256 (hex) of the revocation list bytes in force at decision time.\n * Absent means no revocation data was loaded — a different claim from a\n * loaded list that revoked nothing.\n */\n srl_hash?: string;\n /**\n * SHA-256 (hex) commitment to the canonical invocation this decision was\n * made over. Absent when the arguments could not be canonicalized — never\n * zero-filled, so absence is a claim rather than a value.\n */\n request_hash?: string;\n /** SHA-256 (hex) of the host ceiling applied to this decision. */\n policy_definition_hash?: string;\n /**\n * SHA-256 (hex) of the previous receipt from this signer. Absent on the\n * first receipt, or when the deployment does not chain. A broken link means\n * a receipt was removed from the stream.\n */\n prev_receipt_hash?: string;\n /** SHA-256 (hex) of the trusted root set in force at decision time. */\n trusted_roots_hash?: string;\n};\n\nexport type WasmReceiptChain = {\n signer_key: string;\n outcome: \"allow\" | \"deny\";\n decision_code?: string;\n timestamp: number;\n /** The embedded chain verifies to a supplied root at the decision instant. */\n chain_valid: boolean;\n /** Canonical error name when it does not. */\n chain_error?: string;\n /**\n * Deny receipts only: the chain failure matches the stated decision_code,\n * so the embedded authority independently corroborates the refusal.\n */\n corroborates_denial?: boolean;\n root_issuer?: string;\n leaf_holder?: string;\n};\n\nexport type WasmSession = object;\n\n/** Mirrors `SessionInfoDto` in tenuo-wasm. Snake case is the WASM boundary. */\nexport type WasmSessionInfo = {\n kind: \"execution\" | \"issuer\";\n holder_public_key: string;\n root_public_key: string;\n depth: number;\n max_depth: number;\n terminal: boolean;\n expires_at: number;\n tools: string[];\n warrant_ids: string[];\n can_authorize: boolean;\n clearance?: number;\n session_id?: string;\n agent_id?: string;\n issuable_tools?: string[];\n max_issue_depth?: number;\n required_approvers?: string[];\n min_approvals?: number;\n approval_gated_tools: string[];\n};\n\n/** Security limits exported by tenuo-core; TypeScript must not redefine them. */\nexport type WasmProtocolLimits = {\n max_delegation_depth: number;\n max_warrant_ttl_seconds: number;\n};\n\n/** Mirrors `NarrowOptions` in tenuo-wasm. Unknown keys are rejected there. */\nexport type WasmNarrowOptions = {\n holder?: string;\n ttlSeconds?: number;\n terminal?: boolean;\n maxDepth?: number;\n clearance?: number | string;\n agentId?: string;\n addApprovers?: string[];\n minApprovals?: number;\n};\n\nexport type WasmRequireApproval = {\n approvers: string[];\n min: number;\n tools?: string[];\n gates?: Record<string, { message?: string; args?: Record<string, unknown> }>;\n};\n\n/** Mirrors `MintOptions` in tenuo-wasm. */\nexport type WasmMintOptions = {\n kind?: \"execution\" | \"issuer\";\n allow?: unknown;\n ttlSeconds?: number;\n holder?: string;\n maxDepth?: number;\n clearance?: number | string;\n sessionId?: string;\n agentId?: string;\n requireApproval?: WasmRequireApproval;\n issuableTools?: string[];\n constraintBounds?: unknown;\n maxIssueDepth?: number;\n};\n\n/** Mirrors `IssueOptions` in tenuo-wasm. */\nexport type WasmIssueOptions = {\n allow: unknown;\n holder: string;\n ttlSeconds?: number;\n maxDepth?: number;\n clearance?: number | string;\n sessionId?: string;\n agentId?: string;\n requireApproval?: { approvers: string[]; min: number };\n};\n\nexport type WasmExplainField = {\n field: string;\n kind: string;\n constraint: unknown;\n value?: unknown;\n satisfied: boolean;\n reason?: string;\n};\n\nexport type WasmExplain = {\n tool: string;\n kind: \"execution\" | \"issuer\";\n outcome: \"allow\" | \"deny\";\n code?: TenuoErrorCode;\n field?: string;\n message?: string;\n tool_granted: boolean;\n fields: WasmExplainField[];\n unknown_fields: string[];\n missing_fields: string[];\n expired: boolean;\n expires_at: number;\n chain_valid: boolean;\n chain_error?: TenuoErrorCode;\n};\n\nexport type WasmApprovalRequest = {\n request_id: string;\n warrant_id: string;\n tool: string;\n args: Record<string, unknown>;\n request_hash: string;\n holder_public_key: string;\n required_approvers: string[];\n min_approvals: number;\n warrant_expires_at: number;\n created_at: number;\n message: string;\n};\n\nexport type WasmAttestation = {\n version: number;\n canonicalization: string;\n warrant_id: string;\n tool: string;\n request_hash: string;\n holder_key_hex: string;\n args_canonical_cbor_b64: string;\n signer_key_hex: string;\n signature_b64: string;\n};\n\nexport type WasmApprovalInfo = {\n approver_public_key: string;\n request_hash: string;\n external_id: string;\n approved_at: number;\n expires_at: number;\n expired: boolean;\n signature_valid: boolean;\n error?: string;\n};\n\nexport type WasmSrlInfo = {\n version: number;\n issued_at: number;\n issuer_public_key: string;\n revoked_ids: string[];\n signature_valid: boolean;\n};\n\nexport type WasmContext = {\n withReceiptSigner(secret: Uint8Array): WasmContext;\n mint(\n allow: unknown,\n ttlSeconds: number,\n requireApproval?: unknown,\n holderHex?: string,\n maxDepth?: number,\n ): WasmSession;\n mintExtended(options: WasmMintOptions): WasmSession;\n narrow(session: WasmSession, allow: unknown, options?: WasmNarrowOptions): WasmSession;\n issue(issuer: WasmSession, options: WasmIssueOptions): WasmSession;\n issuerPublicKey(): string;\n explain(session: WasmSession, tool: string, args: unknown): WasmExplain;\n approvalRequest(session: WasmSession, tool: string, args: unknown): WasmApprovalRequest;\n approvalContextAttestation(session: WasmSession, tool: string, args: unknown): WasmAttestation;\n signRevocationListVersioned(ids: string[], version?: number): string;\n authorize(\n session: WasmSession,\n tool: string,\n args: unknown,\n approvals?: unknown,\n toolAllow?: unknown,\n requestId?: string,\n ): WasmDecision;\n authorizeAsOf(\n session: WasmSession,\n tool: string,\n args: unknown,\n asOf: number,\n approvals?: unknown,\n toolAllow?: unknown,\n ): WasmDecision;\n loadRevocationList(srl: string): void;\n signRevocationList(ids: string[]): string;\n signPop(session: WasmSession, tool: string, args: unknown): string;\n authorizePresented(\n warrants: unknown,\n tool: string,\n args: unknown,\n pop: string,\n approvals?: unknown,\n toolAllow?: unknown,\n requestId?: string,\n ): WasmDecision;\n};\n\ntype Generated = {\n SdkContext: {\n new (): WasmContext;\n fromTrustedRoots(roots: string[]): WasmContext;\n fromIssuerSecret(secret: Uint8Array, extraRoots?: string[]): WasmContext;\n };\n SdkSession: {\n fromWire(warrant: string, holder: Uint8Array): WasmSession;\n fromParts(payloadHex: string, signatureHex: string, holder: Uint8Array): WasmSession;\n fromChain(parts: unknown, holder: Uint8Array): WasmSession;\n };\n sdkInspectWarrant(wire: string): WasmInspect;\n sdkInspectParts(payloadHex: string, signatureHex: string): WasmInspect;\n sdkProtocolLimits(): WasmProtocolLimits;\n sdkPublicKeyFromHolderKey(holderSecret: Uint8Array): string;\n sdkSignApproval(\n session: WasmSession,\n tool: string,\n args: unknown,\n approverSecret: Uint8Array,\n externalId: string,\n asOf?: number,\n ): string;\n sdkSignApprovalForRequest(\n requestHashHex: string,\n approverSecret: Uint8Array,\n externalId: string,\n ttlSeconds?: number,\n warrantExpiresAt?: number,\n ): string;\n sdkInspectApproval(envelope: string): WasmApprovalInfo;\n sdkSignRevocationList(ids: string[], issuerSecret: Uint8Array): string;\n sdkSignRevocationListVersioned(ids: string[], version: number | undefined, issuerSecret: Uint8Array): string;\n sdkSignPublishedRevocationList(ids: string[], version: number, issuerSecret: Uint8Array): string;\n sdkInspectRevocationList(wire: string): WasmSrlInfo;\n sdkVerifyReceipt(wire: string): WasmReceipt;\n sdkVerifyReceiptChain(wire: string, roots: string[]): WasmReceiptChain;\n approval_requirement(\n warrantB64: string,\n tool: string,\n args: unknown,\n ): ApprovalRequirement & { error?: string };\n inspect_approval_gate(\n warrantB64: string,\n tool: string,\n ): ApprovalGateInspection & { error?: string };\n evaluate_approval_gates(\n warrantB64: string,\n tool: string,\n args: unknown,\n ): { approval_required: boolean; tool: string; error?: string };\n};\n\nlet loaded: Generated | undefined;\n\nfunction generatedPath(): string {\n const here = dirname(fileURLToPath(import.meta.url));\n return join(here, \"generated\", \"tenuo_wasm.js\");\n}\n\nexport function wasmAvailable(): boolean {\n return existsSync(generatedPath());\n}\n\nconst WASM_LOAD_HINT =\n \"WASM core is missing from this @tenuo/core install. @tenuo/core is Node 20+ only (not a bundler target). If this is Next.js/webpack, set serverExternalPackages: ['@tenuo/core']. Do not run wasm-pack in the consuming app.\";\n\nexport function loadWasm(): Generated {\n if (loaded) {\n return loaded;\n }\n const path = generatedPath();\n if (!existsSync(path)) {\n throw new TenuoConfigurationError(WASM_LOAD_HINT, \"TENUO_NOT_READY\");\n }\n try {\n const require = createRequire(import.meta.url);\n loaded = require(path) as Generated;\n return loaded;\n } catch (error) {\n const wrapped = new TenuoConfigurationError(WASM_LOAD_HINT, \"TENUO_NOT_READY\");\n wrapped.cause = error;\n throw wrapped;\n }\n}\n\nexport function createDevContext(receiptSigner?: Uint8Array): WasmContext {\n const { SdkContext } = loadWasm();\n let context: WasmContext = new SdkContext();\n if (receiptSigner !== undefined) {\n context = context.withReceiptSigner(receiptSigner);\n }\n return context;\n}\n\nexport function protocolLimits(): WasmProtocolLimits {\n return loadWasm().sdkProtocolLimits();\n}\n\nexport function createVerifierContext(\n rootHexes: readonly string[],\n revocationList?: string,\n receiptSigner?: Uint8Array,\n): WasmContext {\n const { SdkContext } = loadWasm();\n let context = SdkContext.fromTrustedRoots([...rootHexes]);\n if (receiptSigner !== undefined) {\n context = context.withReceiptSigner(receiptSigner);\n }\n if (revocationList !== undefined && revocationList.length > 0) {\n context.loadRevocationList(revocationList);\n }\n return context;\n}\n\nexport function createIssuerContext(\n secret: Uint8Array,\n extraRootHexes: readonly string[],\n receiptSigner?: Uint8Array,\n): WasmContext {\n const { SdkContext } = loadWasm();\n let context = SdkContext.fromIssuerSecret(secret, [...extraRootHexes]);\n if (receiptSigner !== undefined) {\n context = context.withReceiptSigner(receiptSigner);\n }\n return context;\n}\n\nexport function importSessionFromWire(warrant: string, holderKey: Uint8Array): WasmSession {\n const { SdkSession } = loadWasm();\n return SdkSession.fromWire(warrant, holderKey);\n}\n\nexport function importSessionFromParts(\n payloadHex: string,\n signatureHex: string,\n holderKey: Uint8Array,\n): WasmSession {\n const { SdkSession } = loadWasm();\n return SdkSession.fromParts(payloadHex, signatureHex, holderKey);\n}\n\nexport function importSessionFromChain(parts: unknown, holderKey: Uint8Array): WasmSession {\n const { SdkSession } = loadWasm();\n return SdkSession.fromChain(parts, holderKey);\n}\n\nexport function inspectWarrant(wire: string): WasmInspect {\n return loadWasm().sdkInspectWarrant(wire);\n}\n\nexport function inspectParts(payloadHex: string, signatureHex: string): WasmInspect {\n return loadWasm().sdkInspectParts(payloadHex, signatureHex);\n}\n\n/** Hex public key for a 32-byte holder secret. Ed25519, derived in Rust. */\nexport function publicKeyHexFromHolderKey(holderSecret: Uint8Array): string {\n return loadWasm().sdkPublicKeyFromHolderKey(holderSecret);\n}\n\nexport type ApprovalRequirementStatus = \"not_gated\" | \"exempt\" | \"required\" | \"denied\";\n\nexport type ApprovalRequirement = {\n status: ApprovalRequirementStatus;\n tool: string;\n kind?: \"whole_tool\" | \"argument\";\n argument?: string;\n arguments: string[];\n message?: string;\n code?: string;\n reason?: string;\n};\n\nexport type ApprovalGateInspection = {\n kind: \"none\" | \"whole_tool\" | \"conditional\" | \"unknown\";\n tool: string;\n arguments: string[];\n message?: string;\n};\n\nfunction loadApprovalWasm() {\n return loadWasm();\n}\n\nfunction throwIfGateError(error: string | undefined): void {\n if (error) {\n throw new TenuoConfigurationError(error);\n }\n}\n\n/**\n * Typed preflight of a warrant's approval gates for `(tool, args)`.\n *\n * Capability constraints are checked first. `denied` means the authorizer\n * will refuse the call — do not collect approval. Malformed encodings throw\n * (fail-closed).\n */\nexport function approvalRequirement(\n warrantB64: string,\n tool: string,\n args: Record<string, unknown>,\n): ApprovalRequirement {\n const result = loadApprovalWasm().approval_requirement(warrantB64, tool, args);\n throwIfGateError(result.error);\n return result;\n}\n\n/** Inspect how a warrant gates `tool`, without evaluating arguments. */\nexport function inspectApprovalGate(warrantB64: string, tool: string): ApprovalGateInspection {\n const result = loadApprovalWasm().inspect_approval_gate(warrantB64, tool);\n throwIfGateError(result.error);\n return result;\n}\n\n/**\n * Gate-map-only boolean. Does not run capability checks, so split-view\n * callers (PoP args vs constraint args) still see a firing gate. Prefer\n * {@link approvalRequirement} when the caller must distinguish `denied`.\n */\nexport function evaluateApprovalGates(\n warrantB64: string,\n tool: string,\n args: Record<string, unknown>,\n): boolean {\n const result = loadApprovalWasm().evaluate_approval_gates(warrantB64, tool, args);\n throwIfGateError(result.error);\n return result.approval_required;\n}\n"]}
1
+ {"version":3,"file":"wasm.js","sourceRoot":"","sources":["../src/wasm.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAC5C,OAAO,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AACrC,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAC1C,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AACzC,OAAO,EAAE,uBAAuB,EAAE,MAAM,aAAa,CAAC;AAkUtD,IAAI,MAA6B,CAAC;AAElC,SAAS,aAAa;IACpB,MAAM,IAAI,GAAG,OAAO,CAAC,aAAa,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC;IACrD,OAAO,IAAI,CAAC,IAAI,EAAE,WAAW,EAAE,eAAe,CAAC,CAAC;AAClD,CAAC;AAED,MAAM,UAAU,aAAa;IAC3B,OAAO,UAAU,CAAC,aAAa,EAAE,CAAC,CAAC;AACrC,CAAC;AAED,MAAM,cAAc,GAClB,8NAA8N,CAAC;AAEjO,MAAM,UAAU,QAAQ;IACtB,IAAI,MAAM,EAAE,CAAC;QACX,OAAO,MAAM,CAAC;IAChB,CAAC;IACD,MAAM,IAAI,GAAG,aAAa,EAAE,CAAC;IAC7B,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,EAAE,CAAC;QACtB,MAAM,IAAI,uBAAuB,CAAC,cAAc,EAAE,iBAAiB,CAAC,CAAC;IACvE,CAAC;IACD,IAAI,CAAC;QACH,MAAM,OAAO,GAAG,aAAa,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;QAC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AC,YAAY,CAAC,CAAC;AAC5D,CAAC;AAsBD,SAAS,gBAAgB;IACvB,OAAO,QAAQ,EAAE,CAAC;AACpB,CAAC;AAED,SAAS,gBAAgB,CAAC,KAAyB;IACjD,IAAI,KAAK,EAAE,CAAC;QACV,MAAM,IAAI,uBAAuB,CAAC,KAAK,CAAC,CAAC;IAC3C,CAAC;AACH,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,mBAAmB,CACjC,UAAkB,EAClB,IAAY,EACZ,IAA6B;IAE7B,MAAM,MAAM,GAAG,gBAAgB,EAAE,CAAC,oBAAoB,CAAC,UAAU,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC;IAC/E,gBAAgB,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;IAC/B,OAAO,MAAM,CAAC;AAChB,CAAC;AAED,wEAAwE;AACxE,MAAM,UAAU,mBAAmB,CAAC,UAAkB,EAAE,IAAY;IAClE,MAAM,MAAM,GAAG,gBAAgB,EAAE,CAAC,qBAAqB,CAAC,UAAU,EAAE,IAAI,CAAC,CAAC;IAC1E,gBAAgB,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;IAC/B,OAAO,MAAM,CAAC;AAChB,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,qBAAqB,CACnC,UAAkB,EAClB,IAAY,EACZ,IAA6B;IAE7B,MAAM,MAAM,GAAG,gBAAgB,EAAE,CAAC,uBAAuB,CAAC,UAAU,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC;IAClF,gBAAgB,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;IAC/B,OAAO,MAAM,CAAC,iBAAiB,CAAC;AAClC,CAAC","sourcesContent":["import { createRequire } from \"node:module\";\nimport { existsSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { TenuoConfigurationError } from \"./errors.ts\";\nimport type { TenuoErrorCode } from \"./api.ts\";\n\nexport type WasmDecision = {\n outcome: \"allow\" | \"deny\" | \"approval_required\";\n code?: TenuoErrorCode;\n field?: string;\n message?: string;\n args?: Record<string, unknown>;\n tool?: string;\n required?: number;\n received?: number;\n receipt?: string;\n};\n\nexport type WasmInspect = {\n payload_hex: string;\n signature_hex: string;\n id: string;\n};\n\nexport type WasmReceipt = {\n authentic: true;\n /** Hex key the receipt is signed under — resolve against your authorizer set. */\n signer_key: string;\n outcome: \"allow\" | \"deny\";\n action: string;\n decision_code?: string;\n request_id: string;\n /** Version of the revocation list in force, when it carried one. */\n srl_version?: number;\n /**\n * SHA-256 (hex) of the revocation list bytes in force at decision time.\n * Absent means no revocation data was loaded — a different claim from a\n * loaded list that revoked nothing.\n */\n srl_hash?: string;\n /**\n * SHA-256 (hex) commitment to the canonical invocation this decision was\n * made over. Absent when the arguments could not be canonicalized — never\n * zero-filled, so absence is a claim rather than a value.\n */\n request_hash?: string;\n /** SHA-256 (hex) of the host ceiling applied to this decision. */\n policy_definition_hash?: string;\n /**\n * SHA-256 (hex) of the previous receipt from this signer. Absent on the\n * first receipt, or when the deployment does not chain. A broken link means\n * a receipt was removed from the stream.\n */\n prev_receipt_hash?: string;\n /** SHA-256 (hex) of the trusted root set in force at decision time. */\n trusted_roots_hash?: string;\n};\n\nexport type WasmReceiptChain = {\n signer_key: string;\n outcome: \"allow\" | \"deny\";\n decision_code?: string;\n timestamp: number;\n /** The embedded chain verifies to a supplied root at the decision instant. */\n chain_valid: boolean;\n /** Canonical error name when it does not. */\n chain_error?: string;\n /**\n * Deny receipts only: the chain failure matches the stated decision_code,\n * so the embedded authority independently corroborates the refusal.\n */\n corroborates_denial?: boolean;\n root_issuer?: string;\n leaf_holder?: string;\n};\n\nexport type WasmSession = object;\n\n/** Mirrors `SessionInfoDto` in tenuo-wasm. Snake case is the WASM boundary. */\nexport type WasmSessionInfo = {\n kind: \"execution\" | \"issuer\";\n holder_public_key: string;\n root_public_key: string;\n depth: number;\n max_depth: number;\n terminal: boolean;\n expires_at: number;\n tools: string[];\n warrant_ids: string[];\n can_authorize: boolean;\n clearance?: number;\n session_id?: string;\n agent_id?: string;\n issuable_tools?: string[];\n max_issue_depth?: number;\n required_approvers?: string[];\n min_approvals?: number;\n approval_gated_tools: string[];\n};\n\n/** Security limits exported by tenuo-core; TypeScript must not redefine them. */\nexport type WasmProtocolLimits = {\n max_delegation_depth: number;\n max_warrant_ttl_seconds: number;\n};\n\n/** Mirrors `NarrowOptions` in tenuo-wasm. Unknown keys are rejected there. */\nexport type WasmNarrowOptions = {\n holder?: string;\n ttlSeconds?: number;\n terminal?: boolean;\n maxDepth?: number;\n clearance?: number | string;\n agentId?: string;\n addApprovers?: string[];\n minApprovals?: number;\n};\n\nexport type WasmRequireApproval = {\n approvers: string[];\n min: number;\n tools?: string[];\n gates?: Record<string, { message?: string; args?: Record<string, unknown> }>;\n};\n\n/** Mirrors `MintOptions` in tenuo-wasm. */\nexport type WasmMintOptions = {\n kind?: \"execution\" | \"issuer\";\n allow?: unknown;\n ttlSeconds?: number;\n holder?: string;\n maxDepth?: number;\n clearance?: number | string;\n sessionId?: string;\n agentId?: string;\n requireApproval?: WasmRequireApproval;\n issuableTools?: string[];\n constraintBounds?: unknown;\n maxIssueDepth?: number;\n};\n\n/** Mirrors `IssueOptions` in tenuo-wasm. */\nexport type WasmIssueOptions = {\n allow: unknown;\n holder: string;\n ttlSeconds?: number;\n maxDepth?: number;\n clearance?: number | string;\n sessionId?: string;\n agentId?: string;\n requireApproval?: { approvers: string[]; min: number };\n};\n\nexport type WasmExplainField = {\n field: string;\n kind: string;\n constraint: unknown;\n value?: unknown;\n satisfied: boolean;\n reason_code?: string;\n reason?: string;\n};\n\nexport type WasmExplain = {\n tool: string;\n kind: \"execution\" | \"issuer\";\n outcome: \"allow\" | \"deny\";\n code?: TenuoErrorCode;\n field?: string;\n message?: string;\n tool_granted: boolean;\n fields: WasmExplainField[];\n unknown_fields: string[];\n missing_fields: string[];\n expired: boolean;\n expires_at: number;\n chain_valid: boolean;\n chain_error?: TenuoErrorCode;\n};\n\nexport type WasmApprovalRequest = {\n request_id: string;\n warrant_id: string;\n tool: string;\n args: Record<string, unknown>;\n request_hash: string;\n holder_public_key: string;\n required_approvers: string[];\n min_approvals: number;\n warrant_expires_at: number;\n created_at: number;\n message: string;\n};\n\nexport type WasmAttestation = {\n version: number;\n canonicalization: string;\n warrant_id: string;\n tool: string;\n request_hash: string;\n holder_key_hex: string;\n args_canonical_cbor_b64: string;\n signer_key_hex: string;\n signature_b64: string;\n};\n\nexport type WasmApprovalInfo = {\n approver_public_key: string;\n request_hash: string;\n external_id: string;\n approved_at: number;\n expires_at: number;\n expired: boolean;\n signature_valid: boolean;\n error?: string;\n};\n\nexport type WasmSrlInfo = {\n version: number;\n issued_at: number;\n issuer_public_key: string;\n revoked_ids: string[];\n signature_valid: boolean;\n};\n\nexport type WasmContext = {\n withReceiptSigner(secret: Uint8Array): WasmContext;\n mint(\n allow: unknown,\n ttlSeconds: number,\n requireApproval?: unknown,\n holderHex?: string,\n maxDepth?: number,\n ): WasmSession;\n mintExtended(options: WasmMintOptions): WasmSession;\n narrow(session: WasmSession, allow: unknown, options?: WasmNarrowOptions): WasmSession;\n issue(issuer: WasmSession, options: WasmIssueOptions): WasmSession;\n issuerPublicKey(): string;\n explain(session: WasmSession, tool: string, args: unknown): WasmExplain;\n approvalRequest(session: WasmSession, tool: string, args: unknown): WasmApprovalRequest;\n approvalContextAttestation(session: WasmSession, tool: string, args: unknown): WasmAttestation;\n signRevocationListVersioned(ids: string[], version?: number): string;\n authorize(\n session: WasmSession,\n tool: string,\n args: unknown,\n approvals?: unknown,\n toolAllow?: unknown,\n requestId?: string,\n ): WasmDecision;\n authorizeAsOf(\n session: WasmSession,\n tool: string,\n args: unknown,\n asOf: number,\n approvals?: unknown,\n toolAllow?: unknown,\n ): WasmDecision;\n loadRevocationList(srl: string): void;\n signRevocationList(ids: string[]): string;\n signPop(session: WasmSession, tool: string, args: unknown): string;\n authorizePresented(\n warrants: unknown,\n tool: string,\n args: unknown,\n pop: string,\n approvals?: unknown,\n toolAllow?: unknown,\n requestId?: string,\n ): WasmDecision;\n};\n\ntype Generated = {\n SdkContext: {\n new (): WasmContext;\n fromTrustedRoots(roots: string[]): WasmContext;\n fromIssuerSecret(secret: Uint8Array, extraRoots?: string[]): WasmContext;\n };\n SdkSession: {\n fromWire(warrant: string, holder: Uint8Array): WasmSession;\n fromParts(payloadHex: string, signatureHex: string, holder: Uint8Array): WasmSession;\n fromChain(parts: unknown, holder: Uint8Array): WasmSession;\n };\n sdkInspectWarrant(wire: string): WasmInspect;\n sdkInspectParts(payloadHex: string, signatureHex: string): WasmInspect;\n sdkProtocolLimits(): WasmProtocolLimits;\n sdkPublicKeyFromHolderKey(holderSecret: Uint8Array): string;\n sdkSignApproval(\n session: WasmSession,\n tool: string,\n args: unknown,\n approverSecret: Uint8Array,\n externalId: string,\n asOf?: number,\n ): string;\n sdkSignApprovalForRequest(\n requestHashHex: string,\n approverSecret: Uint8Array,\n externalId: string,\n ttlSeconds?: number,\n warrantExpiresAt?: number,\n ): string;\n sdkInspectApproval(envelope: string): WasmApprovalInfo;\n sdkSignRevocationList(ids: string[], issuerSecret: Uint8Array): string;\n sdkSignRevocationListVersioned(ids: string[], version: number | undefined, issuerSecret: Uint8Array): string;\n sdkSignPublishedRevocationList(ids: string[], version: number, issuerSecret: Uint8Array): string;\n sdkInspectRevocationList(wire: string): WasmSrlInfo;\n sdkVerifyReceipt(wire: string): WasmReceipt;\n sdkVerifyReceiptChain(wire: string, roots: string[]): WasmReceiptChain;\n approval_requirement(\n warrantB64: string,\n tool: string,\n args: unknown,\n ): ApprovalRequirement & { error?: string };\n inspect_approval_gate(\n warrantB64: string,\n tool: string,\n ): ApprovalGateInspection & { error?: string };\n evaluate_approval_gates(\n warrantB64: string,\n tool: string,\n args: unknown,\n ): { approval_required: boolean; tool: string; error?: string };\n};\n\nlet loaded: Generated | undefined;\n\nfunction generatedPath(): string {\n const here = dirname(fileURLToPath(import.meta.url));\n return join(here, \"generated\", \"tenuo_wasm.js\");\n}\n\nexport function wasmAvailable(): boolean {\n return existsSync(generatedPath());\n}\n\nconst WASM_LOAD_HINT =\n \"WASM core is missing from this @tenuo/core install. @tenuo/core is Node 20+ only (not a bundler target). If this is Next.js/webpack, set serverExternalPackages: ['@tenuo/core']. Do not run wasm-pack in the consuming app.\";\n\nexport function loadWasm(): Generated {\n if (loaded) {\n return loaded;\n }\n const path = generatedPath();\n if (!existsSync(path)) {\n throw new TenuoConfigurationError(WASM_LOAD_HINT, \"TENUO_NOT_READY\");\n }\n try {\n const require = createRequire(import.meta.url);\n loaded = require(path) as Generated;\n return loaded;\n } catch (error) {\n const wrapped = new TenuoConfigurationError(WASM_LOAD_HINT, \"TENUO_NOT_READY\");\n wrapped.cause = error;\n throw wrapped;\n }\n}\n\nexport function createDevContext(receiptSigner?: Uint8Array): WasmContext {\n const { SdkContext } = loadWasm();\n let context: WasmContext = new SdkContext();\n if (receiptSigner !== undefined) {\n context = context.withReceiptSigner(receiptSigner);\n }\n return context;\n}\n\nexport function protocolLimits(): WasmProtocolLimits {\n return loadWasm().sdkProtocolLimits();\n}\n\nexport function createVerifierContext(\n rootHexes: readonly string[],\n revocationList?: string,\n receiptSigner?: Uint8Array,\n): WasmContext {\n const { SdkContext } = loadWasm();\n let context = SdkContext.fromTrustedRoots([...rootHexes]);\n if (receiptSigner !== undefined) {\n context = context.withReceiptSigner(receiptSigner);\n }\n if (revocationList !== undefined && revocationList.length > 0) {\n context.loadRevocationList(revocationList);\n }\n return context;\n}\n\nexport function createIssuerContext(\n secret: Uint8Array,\n extraRootHexes: readonly string[],\n receiptSigner?: Uint8Array,\n): WasmContext {\n const { SdkContext } = loadWasm();\n let context = SdkContext.fromIssuerSecret(secret, [...extraRootHexes]);\n if (receiptSigner !== undefined) {\n context = context.withReceiptSigner(receiptSigner);\n }\n return context;\n}\n\nexport function importSessionFromWire(warrant: string, holderKey: Uint8Array): WasmSession {\n const { SdkSession } = loadWasm();\n return SdkSession.fromWire(warrant, holderKey);\n}\n\nexport function importSessionFromParts(\n payloadHex: string,\n signatureHex: string,\n holderKey: Uint8Array,\n): WasmSession {\n const { SdkSession } = loadWasm();\n return SdkSession.fromParts(payloadHex, signatureHex, holderKey);\n}\n\nexport function importSessionFromChain(parts: unknown, holderKey: Uint8Array): WasmSession {\n const { SdkSession } = loadWasm();\n return SdkSession.fromChain(parts, holderKey);\n}\n\nexport function inspectWarrant(wire: string): WasmInspect {\n return loadWasm().sdkInspectWarrant(wire);\n}\n\nexport function inspectParts(payloadHex: string, signatureHex: string): WasmInspect {\n return loadWasm().sdkInspectParts(payloadHex, signatureHex);\n}\n\n/** Hex public key for a 32-byte holder secret. Ed25519, derived in Rust. */\nexport function publicKeyHexFromHolderKey(holderSecret: Uint8Array): string {\n return loadWasm().sdkPublicKeyFromHolderKey(holderSecret);\n}\n\nexport type ApprovalRequirementStatus = \"not_gated\" | \"exempt\" | \"required\" | \"denied\";\n\nexport type ApprovalRequirement = {\n status: ApprovalRequirementStatus;\n tool: string;\n kind?: \"whole_tool\" | \"argument\";\n argument?: string;\n arguments: string[];\n message?: string;\n code?: string;\n reason?: string;\n};\n\nexport type ApprovalGateInspection = {\n kind: \"none\" | \"whole_tool\" | \"conditional\" | \"unknown\";\n tool: string;\n arguments: string[];\n message?: string;\n};\n\nfunction loadApprovalWasm() {\n return loadWasm();\n}\n\nfunction throwIfGateError(error: string | undefined): void {\n if (error) {\n throw new TenuoConfigurationError(error);\n }\n}\n\n/**\n * Typed preflight of a warrant's approval gates for `(tool, args)`.\n *\n * Capability constraints are checked first. `denied` means the authorizer\n * will refuse the call — do not collect approval. Malformed encodings throw\n * (fail-closed).\n */\nexport function approvalRequirement(\n warrantB64: string,\n tool: string,\n args: Record<string, unknown>,\n): ApprovalRequirement {\n const result = loadApprovalWasm().approval_requirement(warrantB64, tool, args);\n throwIfGateError(result.error);\n return result;\n}\n\n/** Inspect how a warrant gates `tool`, without evaluating arguments. */\nexport function inspectApprovalGate(warrantB64: string, tool: string): ApprovalGateInspection {\n const result = loadApprovalWasm().inspect_approval_gate(warrantB64, tool);\n throwIfGateError(result.error);\n return result;\n}\n\n/**\n * Gate-map-only boolean. Does not run capability checks, so split-view\n * callers (PoP args vs constraint args) still see a firing gate. Prefer\n * {@link approvalRequirement} when the caller must distinguish `denied`.\n */\nexport function evaluateApprovalGates(\n warrantB64: string,\n tool: string,\n args: Record<string, unknown>,\n): boolean {\n const result = loadApprovalWasm().evaluate_approval_gates(warrantB64, tool, args);\n throwIfGateError(result.error);\n return result.approval_required;\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tenuo/core",
3
- "version": "0.3.0-beta.0",
3
+ "version": "0.3.1-beta.0",
4
4
  "description": "Tenuo TypeScript SDK — authorization decisions run in the Rust core (WASM).",
5
5
  "license": "Apache-2.0",
6
6
  "author": "Tenuo Contributors",
@@ -46,7 +46,7 @@
46
46
  "test": "vitest run",
47
47
  "test:watch": "vitest",
48
48
  "typecheck": "tsc --noEmit",
49
- "build": "tsc -p tsconfig.build.json && node scripts/copy-build-assets.mjs",
49
+ "build": "tsc -p tsconfig.build.json && node scripts/copy-build-assets.mjs && node scripts/write-build-info.mjs",
50
50
  "pack:smoke": "node scripts/pack-smoke.mjs",
51
51
  "publish:npm": "npm publish --access public --provenance --tag beta",
52
52
  "build:wasm": "pnpm --dir ../.. build:wasm"