import { z } from "zod"; import { Chain, EIP1193Provider, SignTypedDataParameters } from "viem"; //#region src/core/did/types.d.ts /** A multicodec name, e.g., 'secp256k1-pub' */ type Multicodec = "secp256k1-pub"; /** * Represents a parsed did:key object. * * Reference: https://w3c-ccg.github.io/did-key-spec/ */ type DidKey = { readonly didString: string; readonly method: "key"; readonly multicodec: Multicodec; readonly publicKeyBytes: Uint8Array; readonly toJSON: () => string; }; /** * Represents a parsed did:ethr object. * * Reference: https://github.com/decentralized-identity/ethr-did-resolver/blob/master/doc/did-method-spec.md */ type DidEthr = { readonly didString: string; readonly method: "ethr"; readonly address: string; readonly toJSON: () => string; }; /** * Represents a parsed `did:nil` object. * @deprecated This will be removed in version 0.3.0. Use `DidKey` instead. */ type DidNil = { readonly didString: string; readonly method: "nil"; readonly publicKeyBytes: Uint8Array; readonly toJSON: () => string; }; /** * A union of all supported Did types. */ type Did$1 = DidKey | DidEthr | DidNil; //#endregion //#region src/core/did/did.d.ts type Did = Did$1; declare namespace Did { /** * Parses a Did string into its structured object representation. * Supports did:key, did:ethr, and did:nil methods. * * @param didString - The Did string to parse (e.g., "did:key:zDnae..." or "did:nil:03a1b2c3...") * @returns A structured Did object containing method, public key, and other metadata * @throws {Error} If the Did method is not supported * * @example * ```typescript * import { Did } from "#/core/did/did"; * * const parsedDid = Did.parse("did:key:zDnaerDaTF5BXEavCrfRZEk316dpbLsfPDZ3WJ5hRTPFU2169"); * console.log(parsedDid.method); // "key" * console.log(parsedDid.publicKeyBytes); // Uint8Array(...) * ``` */ function parse(didString: string): Did; /** * Serializes a structured Did object back into its string form. * * @param did - The structured Did object to serialize * @returns The Did as a string * * @example * ```typescript * const didString = Did.serialize(parsedDid); * console.log(didString); // "did:key:zDnae..." * ``` */ function serialize(did: Did): string; /** * Performs a semantic equality check on two structured Did objects. * For Dids with public keys (key, nil), this function compares the underlying * public keys, allowing for cross-method comparison. For other types, * it falls back to a structural equality check. * * @param a - The first Did to compare * @param b - The second Did to compare * @returns True if the Dids represent the same identity * * @example * ```typescript * const privateKey = new Uint8Array(32); * crypto.getRandomValues(privateKey); * const didKey = await Signer.fromPrivateKey(privateKey, "key").getDid(); * const didNil = await Signer.fromPrivateKey(privateKey, "nil").getDid(); * console.log(Did.areEqual(didKey, didNil)); // true * ``` */ function areEqual(a: Did, b: Did): boolean; /** * Creates a Did from a public key hex string. * * @param publicKey - The public key as a hex string * @param method - The Did method to use: "key" (default) or "nil" * @returns A structured Did object * * @example * ```typescript * const publicKey = "03a1b2c3..."; * * // Create a did:key (modern format) * const modernDid = Did.fromPublicKey(publicKey); * * // Create a did:nil (legacy format) * const legacyDid = Did.fromPublicKey(publicKey, "nil"); * ``` */ function fromPublicKey(publicKey: string, method?: "key" | "nil"): Did; /** * Zod schema for parsing and validating Did strings. * * Validates that a string matches the Did format (did:method:identifier) * and automatically transforms it into a structured Did object. * * @example * ```typescript * import { Did } from "@nillion/nuc"; * * // Use in Zod schemas * const MySchema = z.object({ * issuer: Did.Schema, * audience: Did.Schema * }); * * // Parse and validate a Did string * const did = Did.Schema.parse("did:key:zDnae..."); * ``` */ const Schema: z.ZodPipe>; } declare namespace errors_d_exports { export { InvalidContentType }; } declare class InvalidContentType extends Error { readonly response: globalThis.Response; readonly cause: Error; readonly _tag = "InvalidContentType"; constructor(response: globalThis.Response, cause: Error); } //#endregion //#region src/nuc/selector.d.ts declare const SelectorSchema: z.core.$ZodBranded; type Selector = z.infer; //#endregion //#region src/nuc/policy.d.ts /** * Simple type aliases for operators */ type Equals = readonly ["==", Selector | string, unknown]; type NotEquals = readonly ["!=", Selector | string, unknown]; type AnyOf = readonly ["anyOf", Selector | string, unknown[]]; /** * Union type for all operators */ type Operator = Equals | NotEquals | AnyOf; /** * Logical connectors for combining policies */ type And = readonly ["and", PolicyRule[]]; type Or = readonly ["or", PolicyRule[]]; type Not = readonly ["not", PolicyRule]; /** * Union type for all connectors */ type Connector = And | Or | Not; /** * A PolicyRule is either an Operator or a Connector */ type PolicyRule = Operator | Connector; /** * A Policy is an array of PolicyRules (with implicit AND) */ type Policy = PolicyRule[]; /** * Provides utilities for working with NUC token policies. * * Policies define constraints that must be satisfied when tokens are used. * They support logical operators (and, or, not) and comparison operators * (==, !=, anyOf) with JSON path selectors. * * @example * ```typescript * import { Policy } from "@nillion/nuc"; * * const policy: Policy = [ * ["==", ".command", "/db/read"], * ["!=", ".args.table", "secrets"], * ["anyOf", ".args.action", ["read", "list"]] * ]; * * const isValid = Policy.evaluatePolicy(policy, payload, context); * ``` */ declare namespace Policy { /** * Validates that a value is a valid policy rule. * * Checks the structure and arguments of operators and connectors, * recursively validating nested rules. * * @param rule - The value to validate as a policy rule * @throws {Error} If the rule structure is invalid * @example * ```typescript * Policy.validateRule(["==", ".status", "active"]); // Valid * Policy.validateRule(["and", [["==", ".a", 1], ["!=", ".b", 2]]]); // Valid * Policy.validateRule(["invalid"]); // Throws error * ``` */ function validateRule(rule: unknown): asserts rule is PolicyRule; /** * Validates that a value is a valid policy array. * * Ensures the value is an array of valid policy rules. * Empty policies are allowed (no restrictions). * * @param policy - The value to validate as a policy * @throws {Error} If the policy structure is invalid * @example * ```typescript * Policy.validate([["==", ".cmd", "/read"]]); // Valid * Policy.validate([]); // Valid (no restrictions) * Policy.validate("not an array"); // Throws error * ``` */ function validate(policy: unknown): asserts policy is Policy; /** * Zod schema for parsing and validating policies. * * Uses the runtime validation function to ensure policy structure * is correct, including all nested rules and operators. * * @example * ```typescript * import { Policy } from "@nillion/nuc"; * import { z } from "zod"; * * const TokenSchema = z.object({ * policies: Policy.Schema, * // other fields... * }); * * const policy = Policy.Schema.parse([ * ["==", ".command", "/db/read"] * ]); * ``` */ const Schema: z.ZodCustom; /** * Evaluates a policy against a record and context. * * Policies are arrays of rules with implicit AND logic. * All rules must pass for the policy to evaluate to true. * * @param policy - The policy to evaluate * @param record - The record to evaluate against (typically a payload) * @param context - Additional context for evaluation * @returns True if all policy rules are satisfied * @example * ```typescript * const policy: Policy = [ * ["==", ".status", "active"], * ["!=", ".role", "banned"] * ]; * const record = { status: "active", role: "user" }; * const context = { environment: "production" }; * * if (Policy.evaluatePolicy(policy, record, context)) { * console.log("Policy satisfied"); * } * ``` */ function evaluatePolicy(policy: Policy, record: Record, context: Record): boolean; /** * Calculates the maximum depth and width of a policy tree * * @remarks * - Depth: The longest path from root to leaf in the policy tree * - Width: The maximum number of sibling policies at any level * * @example * ```typescript * const policy: Policy = [ * ["==", ".status", "active"], * ["or", [ * ["==", ".role", "admin"], * ["==", ".role", "moderator"] * ]] * ]; * * Policy.getPolicyTreeProperties(policy); // returns { maxDepth: 3, maxWidth: 2 } * ``` */ function getPolicyTreeProperties(policy: Policy): { maxDepth: number; maxWidth: number; }; } //#endregion //#region src/nuc/payload.d.ts declare const CommandSchema: z.ZodString; type Command = z.infer; interface CommonPayload { iss: Did; aud: Did; sub: Did; nbf?: number; exp?: number; cmd: Command; meta?: Record; nonce: string; prf: string[]; } interface DelegationPayload extends CommonPayload { pol: Policy; } interface InvocationPayload extends CommonPayload { args: Record; } type Payload = DelegationPayload | InvocationPayload; /** * Provides utilities and schemas for working with NUC token payloads. * * The Payload namespace handles both delegation and invocation payloads, * providing type guards, validation schemas, and utility functions. * * @example * ```typescript * import { Payload } from "@nillion/nuc"; * * // Check payload type * if (Payload.isDelegationPayload(payload)) { * console.log("Policies:", payload.pol); * } else if (Payload.isInvocationPayload(payload)) { * console.log("Arguments:", payload.args); * } * * // Validate with Zod * const validated = Payload.Schema.parse(unknownPayload); * ``` */ declare namespace Payload { /** * The command string used for token revocation. */ const REVOKE_COMMAND: Command; /** * Zod schema for validating delegation payloads. * * Ensures the payload contains all required delegation fields * including the policy array. * * @example * ```typescript * const delegation = Payload.DelegationSchema.parse({ * iss: issuerDid, * aud: audienceDid, * sub: subjectDid, * cmd: "/nil/db/data", * pol: [["==", ".command", "/nil/db/data"]], * nonce: "abc123", * prf: [] * }); * ``` */ const DelegationSchema: z.ZodObject<{ iss: z.ZodPipe>; aud: z.ZodPipe>; sub: z.ZodPipe>; cmd: z.ZodString; nonce: z.ZodString; meta: z.ZodOptional>; prf: z.ZodDefault>; nbf: z.ZodOptional; exp: z.ZodOptional; pol: z.ZodCustom; }, z.core.$strict>; /** * Zod schema for validating invocation payloads. * * Ensures the payload contains all required invocation fields * including the arguments object. * * @example * ```typescript * const invocation = Payload.InvocationSchema.parse({ * iss: issuerDid, * aud: serviceDid, * sub: subjectDid, * cmd: "/nil/db/query", * args: { table: "users", limit: 100 }, * nonce: "xyz789", * prf: [proofHash] * }); * ``` */ const InvocationSchema: z.ZodObject<{ iss: z.ZodPipe>; aud: z.ZodPipe>; sub: z.ZodPipe>; cmd: z.ZodString; nonce: z.ZodString; meta: z.ZodOptional>; prf: z.ZodDefault>; nbf: z.ZodOptional; exp: z.ZodOptional; args: z.ZodRecord; }, z.core.$strict>; /** * Unified Zod schema for validating any NUC payload. * * Automatically determines whether the payload is a delegation * or invocation based on the presence of "pol" or "args" fields. * * @example * ```typescript * import { Payload } from "@nillion/nuc"; * * const payload = Payload.Schema.parse(unknownPayload); * * // Type is automatically narrowed * if ('pol' in payload) { * // TypeScript knows this is DelegationPayload * console.log(payload.pol); * } else { * // TypeScript knows this is InvocationPayload * console.log(payload.args); * } * ``` */ const Schema: z.ZodUnion>; aud: z.ZodPipe>; sub: z.ZodPipe>; cmd: z.ZodString; nonce: z.ZodString; meta: z.ZodOptional>; prf: z.ZodDefault>; nbf: z.ZodOptional; exp: z.ZodOptional; pol: z.ZodCustom; }, z.core.$strict>, z.ZodObject<{ iss: z.ZodPipe>; aud: z.ZodPipe>; sub: z.ZodPipe>; cmd: z.ZodString; nonce: z.ZodString; meta: z.ZodOptional>; prf: z.ZodDefault>; nbf: z.ZodOptional; exp: z.ZodOptional; args: z.ZodRecord; }, z.core.$strict>]>; /** * Checks if a command is an attenuation of a parent command. * * Commands follow a hierarchical path structure. A command is an * attenuation if it extends the parent's path with additional segments. * * @param command - The command to check * @param parent - The parent command to compare against * @returns True if command is an attenuation of parent * @example * ```typescript * Payload.isCommandAttenuationOf("/nil/db/data", "/nil/db/data/read"); // true * Payload.isCommandAttenuationOf("/nil/db/data", "/nil/db/write"); // false * ``` */ function isCommandAttenuationOf(command: Command, parent: Command): boolean; /** * Extracts proof hashes from a payload as byte arrays. * * Converts the hex-encoded proof strings to Uint8Array format * for cryptographic operations. * * @param payload - The payload containing proof references * @returns Array of proof hashes as byte arrays * @example * ```typescript * const proofBytes = Payload.getProofBytes(payload); * console.log(proofBytes.length); // Number of proofs * ``` */ function getProofBytes(payload: Payload): Uint8Array[]; /** * Type guard that checks if a payload is an invocation. * * @param payload - The payload to check * @returns True if the payload is an InvocationPayload * @example * ```typescript * if (Payload.isInvocationPayload(payload)) { * // TypeScript knows payload.args exists * console.log("Arguments:", payload.args); * } * ``` */ function isInvocationPayload(payload: Payload): payload is InvocationPayload; /** * Type guard that checks if a value is a delegation payload. * * Works with unknown values, making it safe for runtime validation. * * @param value - The value to check * @returns True if the value is a DelegationPayload * @example * ```typescript * if (Payload.isDelegationPayload(value)) { * // TypeScript knows value.pol exists * console.log("Policies:", value.pol); * } * ``` */ function isDelegationPayload(value: unknown): value is DelegationPayload; } //#endregion //#region node_modules/.pnpm/abitype@1.2.3_typescript@5.9.3_zod@4.3.6/node_modules/abitype/dist/types/register.d.ts interface Register {} type ResolvedRegister = { /** * TypeScript type to use for `address` values * @default `0x${string}` */ addressType: Register extends { addressType: infer type; } ? type : Register extends { AddressType: infer type; } ? type : DefaultRegister['addressType']; /** * TypeScript type to use for `int` and `uint` values, where `M > 48` * @default bigint */ bigIntType: Register extends { bigIntType: infer type; } ? type : Register extends { BigIntType: infer type; } ? type : DefaultRegister['bigIntType']; /** * TypeScript type to use for `bytes` values * @default { inputs: `0x${string}`; outputs: `0x${string}`; } */ bytesType: Register extends { bytesType: infer type extends { inputs: unknown; outputs: unknown; }; } ? type : Register extends { BytesType: infer type extends { inputs: unknown; outputs: unknown; }; } ? type : DefaultRegister['bytesType']; /** * TypeScript type to use for `int` and `uint` values, where `M <= 48` * @default number */ intType: Register extends { intType: infer type; } ? type : Register extends { IntType: infer type; } ? type : DefaultRegister['intType']; /** * Maximum depth for nested array types (e.g. string[][]) * * Note: You probably only want to set this to a specific number if parsed types are returning as `unknown` * and you want to figure out why. If you set this, you should probably also reduce `FixedArrayMaxLength`. * * @default false */ arrayMaxDepth: Register extends { arrayMaxDepth: infer type extends number | false; } ? type : Register extends { ArrayMaxDepth: infer type extends number | false; } ? type : DefaultRegister['arrayMaxDepth']; /** * Lower bound for fixed array length * @default 1 */ fixedArrayMinLength: Register extends { fixedArrayMinLength: infer type extends number; } ? type : Register extends { FixedArrayMinLength: infer type extends number; } ? type : DefaultRegister['fixedArrayMinLength']; /** * Upper bound for fixed array length * @default 99 */ fixedArrayMaxLength: Register extends { fixedArrayMaxLength: infer type extends number; } ? type : Register extends { FixedArrayMaxLength: infer type extends number; } ? type : DefaultRegister['fixedArrayMaxLength']; /** * Enables named tuple generation in {@link AbiParametersToPrimitiveTypes} for common ABI parameter names. * * @default false */ experimental_namedTuples: Register extends { experimental_namedTuples: infer type extends boolean; } ? type : DefaultRegister['experimental_namedTuples']; /** * When set, validates {@link AbiParameter}'s `type` against {@link AbiType} * * Note: You probably only want to set this to `true` if parsed types are returning as `unknown` * and you want to figure out why. * * @default false */ strictAbiType: Register extends { strictAbiType: infer type extends boolean; } ? type : Register extends { StrictAbiType: infer type extends boolean; } ? type : DefaultRegister['strictAbiType']; /** @deprecated Use `addressType` instead */ AddressType: ResolvedRegister['addressType']; /** @deprecated Use `addressType` instead */ BigIntType: ResolvedRegister['bigIntType']; /** @deprecated Use `bytesType` instead */ BytesType: ResolvedRegister['bytesType']; /** @deprecated Use `intType` instead */ IntType: ResolvedRegister['intType']; /** @deprecated Use `arrayMaxDepth` instead */ ArrayMaxDepth: ResolvedRegister['arrayMaxDepth']; /** @deprecated Use `fixedArrayMinLength` instead */ FixedArrayMinLength: ResolvedRegister['fixedArrayMinLength']; /** @deprecated Use `fixedArrayMaxLength` instead */ FixedArrayMaxLength: ResolvedRegister['fixedArrayMaxLength']; /** @deprecated Use `strictAbiType` instead */ StrictAbiType: ResolvedRegister['strictAbiType']; }; type DefaultRegister = { /** Maximum depth for nested array types (e.g. string[][]) */arrayMaxDepth: false; /** Lower bound for fixed array length */ fixedArrayMinLength: 1; /** Upper bound for fixed array length */ fixedArrayMaxLength: 99; /** TypeScript type to use for `address` values */ addressType: `0x${string}`; /** TypeScript type to use for `bytes` values */ bytesType: { /** TypeScript type to use for `bytes` input values */inputs: `0x${string}`; /** TypeScript type to use for `bytes` output values */ outputs: `0x${string}`; }; /** TypeScript type to use for `int` and `uint` values, where `M > 48` */ bigIntType: bigint; /** TypeScript type to use for `int` and `uint` values, where `M <= 48` */ intType: number; /** Enables named tuple generation in {@link AbiParametersToPrimitiveTypes} for common ABI parameter names */ experimental_namedTuples: false; /** When set, validates {@link AbiParameter}'s `type` against {@link AbiType} */ strictAbiType: false; /** @deprecated Use `arrayMaxDepth` instead */ ArrayMaxDepth: DefaultRegister['arrayMaxDepth']; /** @deprecated Use `fixedArrayMinLength` instead */ FixedArrayMinLength: DefaultRegister['fixedArrayMinLength']; /** @deprecated Use `fixedArrayMaxLength` instead */ FixedArrayMaxLength: DefaultRegister['fixedArrayMaxLength']; /** @deprecated Use `addressType` instead */ AddressType: DefaultRegister['addressType']; /** @deprecated Use `bytesType` instead */ BytesType: { inputs: DefaultRegister['bytesType']['inputs']; outputs: DefaultRegister['bytesType']['outputs']; }; /** @deprecated Use `bigIntType` instead */ BigIntType: DefaultRegister['bigIntType']; /** @deprecated Use `intType` instead */ IntType: DefaultRegister['intType']; /** @deprecated Use `strictAbiType` instead */ StrictAbiType: DefaultRegister['strictAbiType']; }; //#endregion //#region node_modules/.pnpm/abitype@1.2.3_typescript@5.9.3_zod@4.3.6/node_modules/abitype/dist/types/abi.d.ts type Address = ResolvedRegister['addressType']; type TypedDataDomain = { chainId?: number | bigint | undefined; name?: string | undefined; salt?: ResolvedRegister['bytesType']['outputs'] | undefined; verifyingContract?: Address | undefined; version?: string | undefined; }; //#endregion //#region src/nuc/header.d.ts /** * Zod schema for validating the NucHeader structure. This is the single source of truth. * The NucHeader specifies the token type, algorithm, and payload version, inspired by JWT. */ declare const NucHeaderSchema: z.ZodObject<{ typ: z.ZodOptional>; alg: z.ZodEnum<{ ES256K: "ES256K"; }>; ver: z.ZodOptional; meta: z.ZodOptional>; }, z.core.$strict>; type NucHeader = z.infer; /** * The default EIP-712 domain for signing Nuc payloads. * This is used for creating signatures with Web3 wallets. */ declare const NUC_EIP712_DOMAIN: TypedDataDomain; //#endregion //#region src/core/signer.d.ts /** * An abstract signer that can be used to sign Nucs. */ type Signer = { readonly header: NucHeader; readonly getDid: () => Promise; readonly sign: (data: Uint8Array) => Promise; }; /** * Interface for EIP-712 signers. */ interface Eip712Signer { readonly getAddress: () => Promise; readonly signTypedData: (params: { domain: SignTypedDataParameters["domain"]; types: SignTypedDataParameters["types"]; primaryType: string; message: Record; }) => Promise<`0x${string}`>; } declare namespace Signer { /** * Generates a new cryptographically secure Signer. * @param didMethod The Did method to use. Defaults to "key". * @returns A new Signer instance with a random private key. */ function generate(didMethod?: "key" | "nil"): Signer; /** * Creates a Signer from a private key. * @param privateKey The private key as a hex string or a Uint8Array. * @param didMethod The Did method to use. Defaults to "key". * @returns A new Signer instance. */ function fromPrivateKey(privateKey: string | Uint8Array, didMethod?: "key" | "nil"): Signer; /** * Creates an EIP-712 Signer for Ethereum wallet signing. * @param signer The EIP-712 compatible signer (e.g., ethers Wallet) * @param options.chainId Optional chainId for the EIP-712 domain. Defaults to 1 (mainnet). * @returns A Signer instance that uses EIP-712 signing */ function fromWeb3(signer: Eip712Signer, options?: { chainId?: number; }): Signer; /** * Creates a Signer instance from a browser-based Eip-1193 provider (e.g., window.ethereum). * * This simplifies integration with browser wallets by wrapping a viem WalletClient and adapting * it to the Signer interface. * * @param provider The Eip-1193 compatible provider, typically `window.ethereum`. * @param options.account Optional account address to use. If not provided, it will be requested from the wallet. * @param options.chain Optional chain to use. Defaults to mainnet. Must match the wallet's active chain. * @returns A Promise that resolves to a new `Signer` instance. * @throws If the provider is not available or the user rejects the connection request. */ function fromEip1193Provider(provider: EIP1193Provider, options?: { account?: `0x${string}`; chain?: Chain; }): Promise; } //#endregion //#region src/nuc/envelope.d.ts declare const NucSchema: z.ZodObject<{ rawHeader: z.ZodString; rawPayload: z.ZodString; signature: z.ZodCustom, Uint8Array>; payload: z.ZodUnion>; aud: z.ZodPipe>; sub: z.ZodPipe>; cmd: z.ZodString; nonce: z.ZodString; meta: z.ZodOptional>; prf: z.ZodDefault>; nbf: z.ZodOptional; exp: z.ZodOptional; pol: z.ZodCustom; }, z.core.$strict>, z.ZodObject<{ iss: z.ZodPipe>; aud: z.ZodPipe>; sub: z.ZodPipe>; cmd: z.ZodString; nonce: z.ZodString; meta: z.ZodOptional>; prf: z.ZodDefault>; nbf: z.ZodOptional; exp: z.ZodOptional; args: z.ZodRecord; }, z.core.$strict>]>; }, z.core.$strip>; type Nuc = z.infer; type Envelope = z.infer; declare const EnvelopeSchema: z.ZodObject<{ nuc: z.ZodObject<{ rawHeader: z.ZodString; rawPayload: z.ZodString; signature: z.ZodCustom, Uint8Array>; payload: z.ZodUnion>; aud: z.ZodPipe>; sub: z.ZodPipe>; cmd: z.ZodString; nonce: z.ZodString; meta: z.ZodOptional>; prf: z.ZodDefault>; nbf: z.ZodOptional; exp: z.ZodOptional; pol: z.ZodCustom; }, z.core.$strict>, z.ZodObject<{ iss: z.ZodPipe>; aud: z.ZodPipe>; sub: z.ZodPipe>; cmd: z.ZodString; nonce: z.ZodString; meta: z.ZodOptional>; prf: z.ZodDefault>; nbf: z.ZodOptional; exp: z.ZodOptional; args: z.ZodRecord; }, z.core.$strict>]>; }, z.core.$strip>; proofs: z.ZodArray, Uint8Array>; payload: z.ZodUnion>; aud: z.ZodPipe>; sub: z.ZodPipe>; cmd: z.ZodString; nonce: z.ZodString; meta: z.ZodOptional>; prf: z.ZodDefault>; nbf: z.ZodOptional; exp: z.ZodOptional; pol: z.ZodCustom; }, z.core.$strict>, z.ZodObject<{ iss: z.ZodPipe>; aud: z.ZodPipe>; sub: z.ZodPipe>; cmd: z.ZodString; nonce: z.ZodString; meta: z.ZodOptional>; prf: z.ZodDefault>; nbf: z.ZodOptional; exp: z.ZodOptional; args: z.ZodRecord; }, z.core.$strict>]>; }, z.core.$strip>>; }, z.core.$strip>; declare namespace Envelope { const Schema: z.ZodObject<{ nuc: z.ZodObject<{ rawHeader: z.ZodString; rawPayload: z.ZodString; signature: z.ZodCustom, Uint8Array>; payload: z.ZodUnion>; aud: z.ZodPipe>; sub: z.ZodPipe>; cmd: z.ZodString; nonce: z.ZodString; meta: z.ZodOptional>; prf: z.ZodDefault>; nbf: z.ZodOptional; exp: z.ZodOptional; pol: z.ZodCustom; }, z.core.$strict>, z.ZodObject<{ iss: z.ZodPipe>; aud: z.ZodPipe>; sub: z.ZodPipe>; cmd: z.ZodString; nonce: z.ZodString; meta: z.ZodOptional>; prf: z.ZodDefault>; nbf: z.ZodOptional; exp: z.ZodOptional; args: z.ZodRecord; }, z.core.$strict>]>; }, z.core.$strip>; proofs: z.ZodArray, Uint8Array>; payload: z.ZodUnion>; aud: z.ZodPipe>; sub: z.ZodPipe>; cmd: z.ZodString; nonce: z.ZodString; meta: z.ZodOptional>; prf: z.ZodDefault>; nbf: z.ZodOptional; exp: z.ZodOptional; pol: z.ZodCustom; }, z.core.$strict>, z.ZodObject<{ iss: z.ZodPipe>; aud: z.ZodPipe>; sub: z.ZodPipe>; cmd: z.ZodString; nonce: z.ZodString; meta: z.ZodOptional>; prf: z.ZodDefault>; nbf: z.ZodOptional; exp: z.ZodOptional; args: z.ZodRecord; }, z.core.$strict>]>; }, z.core.$strip>>; }, z.core.$strip>; /** * Compute a decoded Nuc's sha256 hash. */ function computeHash(nuc: Nuc): Uint8Array; } //#endregion //#region src/nuc/builder.d.ts /** * `Nuc` token builder base class. * @internal */ declare abstract class AbstractBuilder { protected _issuer?: Did$1; protected _audience?: Did$1; protected _subject?: Did$1; protected _command?: Command; protected _expiresAt?: number; protected _notBefore?: number; protected _meta?: Record; protected _nonce?: string; protected _proof?: Envelope; protected _maxLifetimeMs: number; protected abstract _getPayloadData(issuer: Did$1): Payload; /** * Specifies the token's audience (aud), the recipient of the grant. * * The audience is the principal that this token is intended for and * who is authorised to use it. In a delegation chain, the audience of * one token becomes the issuer of the next. * * @param aud The recipient's Did. * @returns This builder for method chaining. */ audience(aud: Did$1): this; /** * Specifies the token's subject (sub), the principal the token is about. * * The subject is the principal whose authority is being delegated or invoked. * This claim must remain consistent throughout a delegation chain. * * @param sub The subject's Did. * @returns This builder for method chaining. */ subject(sub: Did$1): this; /** * Specifies the command this token authorizes. * @param cmd The command string. * @returns This builder for method chaining. */ command(cmd: Command): this; /** * Specifies when the token expires. * * After this time, the token will be rejected during validation. * Use epoch milliseconds for the expiration timestamp. * * @param date - Expiration time in epoch milliseconds * @returns This builder instance for method chaining * @example * ```typescript * builder.expiresAt(Date.now() + 3600 * 1000); // Expires in 1 hour * ``` */ expiresAt(date: number): this; /** * Specifies the token's expiration as a duration from now. * * @param ms - The number of milliseconds from now when the token should expire. * @returns This builder instance for method chaining. * @example * ```typescript * builder.expiresIn(3600 * 1000); // Expires in 1 hour * ``` */ expiresIn(ms: number): this; /** * Specifies the earliest time the token becomes valid. * * The token will be rejected if used before this time. * Useful for scheduling future access. * * @param date - The earliest validity time in epoch milliseconds * @returns This builder instance for method chaining * @example * ```typescript * builder.notBefore(Date.now() + 60 * 1000); // Valid after 1 minute * ``` */ notBefore(date: number): this; /** * Attaches arbitrary metadata to the token. * * Metadata is not validated and can contain any JSON-serializable * data for application-specific purposes. * * @param meta - A record of key-value pairs * @returns This builder instance for method chaining * @example * ```typescript * builder.meta({ * requestId: "abc123", * environment: "production", * version: "1.0.0" * }); * ``` */ meta(meta: Record): this; /** * Specifies a custom nonce for the token. * * Nonces provide uniqueness and prevent replay attacks. * If not specified, a cryptographically secure random nonce is generated. * * @param nonce - The nonce string * @returns This builder instance for method chaining * @example * ```typescript * builder.nonce("unique-nonce-123"); * ``` */ nonce(nonce: string): this; /** * Sets the maximum lifetime for the token being built. * * This value cannot exceed the default maximum lifetime or the remaining * lifetime of a parent proof token. * * @param ms - The maximum lifetime in milliseconds. * @returns This builder instance for method chaining. * @throws {Error} If the provided lifetime exceeds the allowed maximum. */ maxLifetime(ms: number): this; /** * Links this token to a previous token in a delegation chain. * * The proof establishes the authority for this token based on * a previously issued delegation. * * @param proof - The previous token envelope to chain from * @returns This builder instance for method chaining * @example * ```typescript * builder.proof(previousDelegationEnvelope); * ``` */ proof(proof: Envelope): this; /** * Specifies the token's issuer (iss), the principal who creates and signs the token. * * By default, the issuer is derived from the `Signer`'s Did during the build process. * Use this method only in advanced scenarios where the issuer needs to be explicitly * set to a Did other than the signer's. * * @param iss - The Did of the issuer * @returns This builder instance for method chaining * @example * ```typescript * builder.issuer(customIssuerDid); * ``` */ issuer(iss: Did$1): this; /** * Builds and signs the token with the provided signer. * * Validates that all required fields are present, generates the token * payload, and produces a signed envelope ready for transmission. * * @param signer - The signer to sign the token with * @returns The signed token envelope * @throws {Error} "Audience, subject, and command are required fields" - If any required field is missing * @example * ```typescript * const envelope = await builder * .audience(audienceDid) * .subject(subjectDid) * .command("/db/read") * .build(signer); * ``` */ sign(signer: Signer): Promise; /** * Builds, signs, and serializes the token into a base64url string. * * Convenience method that combines building and serialization * in a single step for easier token generation. * * @param signer - The signer to sign the token with * @returns The signed and serialized token string * @throws {Error} "Audience, subject, and command are required fields" - If any required field is missing * @example * ```typescript * const tokenString = await builder * .audience(audienceDid) * .subject(subjectDid) * .command("/db/read") * .signAndSerialize(signer); * ``` * @see {@link sign} * @see {@link Codec.serializeBase64Url} */ signAndSerialize(signer: Signer): Promise; } /** * Builds delegation tokens that grant capabilities to other DIDs. * * Delegation tokens establish trust relationships and permission boundaries * through policy rules that constrain how granted capabilities can be used. * * @example * ```typescript * const token = new DelegationBuilder() * .audience(userDid) * .subject(userDid) * .command("/db/read") * .policy([["==", ".command", "/db/read"]]) * .build(signer); * ``` */ declare class DelegationBuilder extends AbstractBuilder { private _policy; /** * Replaces all policies with the provided policy array. * * Policies define constraints that must be satisfied when the delegation * is used to create invocation tokens. * * @param policy - Array of policy rules to enforce * @returns This builder instance for method chaining * @example * ```typescript * builder.policy([ * ["==", ".command", "/db/read"], * ["!=", ".args.table", "secrets"] * ]); * ``` */ policy(policy: Policy): this; /** * Appends a single policy rule to the existing policy array. * * Use this method to incrementally build up policies instead of * replacing them all at once. * * @param policy - A policy rule tuple to add * @returns This builder instance for method chaining * @example * ```typescript * builder * .addPolicy(["==", ".command", "/db/read"]) * .addPolicy(["!=", ".args.table", "secrets"]); * ``` */ addPolicy(policy: PolicyRule): this; protected _getPayloadData(issuer: Did$1): DelegationPayload; } /** * Builds invocation tokens that execute commands with arguments. * * Invocation tokens represent the actual execution of a capability * that was granted by a delegation token. They carry the command * arguments and are validated against the delegation's policies. * * @example * ```typescript * const token = new InvocationBuilder() * .audience(serviceDid) * .subject(userDid) * .command("/db/query") * .arguments({ table: "users", limit: 100 }) * .build(signer); * ``` */ declare class InvocationBuilder extends AbstractBuilder { private _args; /** * Replaces all arguments with the provided record. * * Arguments are passed to the command when the invocation is executed. * These arguments are evaluated against policies in the delegation chain. * * @param args - Record of argument key-value pairs * @returns This builder instance for method chaining * @example * ```typescript * builder.arguments({ * table: "users", * filter: { age: { $gte: 18 } }, * limit: 100 * }); * ``` */ arguments(args: Record): this; /** * Adds or updates a single argument in the arguments record. * * Use this method to incrementally build arguments or update * specific values without replacing the entire arguments object. * * @param key - The argument key to add or update * @param value - The argument value * @returns This builder instance for method chaining * @example * ```typescript * builder * .addArgument("table", "users") * .addArgument("limit", 100); * ``` */ addArgument(key: string, value: unknown): this; protected _getPayloadData(issuer: Did$1): Payload; } /** * Creates NUC token builders for constructing delegation and invocation tokens. * * This factory provides the primary API for token creation in the NUC system. * Use it to create builders for different token types and chain tokens together. * * @example * ```typescript * import { Builder, Signer } from "@nillion/nuc"; * * const signer = Signer.generate(); * const userSigner = Signer.generate(); * * // Create a delegation token * const delegation = await Builder.delegation() * .audience(audienceDid) * .subject(subjectDid) * .command("/db/read") * .policy([["==", ".command", "/db/read"]]) * .sign(signer); * * // Create an invocation token from the delegation * const invocation = await Builder.invocationFrom(delegation) * .audience(serviceDid) * .arguments({ table: "users", id: 123 }) * .sign(userSigner); * ``` */ declare const Builder: { /** * Creates a new builder for constructing delegation tokens. * * Delegation tokens grant capabilities that can be further delegated * or invoked by the audience. * * @returns A new DelegationBuilder instance * @example * ```typescript * const token = await Builder.delegation() * .audience(audienceDid) * .subject(subjectDid) * .command("/db/read") * .policy([["==", ".command", "/db/read"]]) * .build(signer); * ``` * @see {@link DelegationBuilder} */ readonly delegation: () => DelegationBuilder; /** * Creates a new builder for constructing invocation tokens. * * Invocation tokens execute commands and are typically created * from existing delegations using `invoking()` instead. * * @returns A new InvocationBuilder instance * @example * ```typescript * const token = await Builder.invocation() * .audience(serviceDid) * .subject(subjectDid) * .command("/db/execute") * .arguments({ query: "SELECT * FROM users" }) * .build(signer); * ``` * @see {@link InvocationBuilder} */ readonly invocation: () => InvocationBuilder; /** * Creates a delegation builder pre-configured from an existing delegation. * * This creates a new `DelegationBuilder` that inherits the subject and * command from the provided proof envelope. * * @param proof - The existing delegation token envelope to extend from. * @returns A pre-configured DelegationBuilder. * @throws {Error} "Cannot create a delegation from a proof that is not a delegation" - If the proof is an invocation token * @example * ```typescript * const rootToken = await Builder.delegation() * .audience(userDid) * .subject(userDid) * .command("/db/read") * .policy([["==", ".command", "/db/read"]]) * .build(rootSigner); * * const chainedToken = await Builder.delegationFrom(rootToken) * .audience(newAudience) // Override the audience * .build(userSigner); * ``` * @see {@link DelegationBuilder} */ readonly delegationFrom: (proof: Envelope) => DelegationBuilder; /** * Creates an invocation builder from a delegation token. * * This creates a new `InvocationBuilder` that inherits the subject and * command from the provided proof envelope. * * @param proof - The delegation token envelope granting the capability. * @returns A pre-configured InvocationBuilder. * @throws {Error} "Cannot invoke a capability from a proof that is not a delegation" - If the proof is not a delegation * @example * ```typescript * const delegationToken = await Builder.delegation() * .audience(userDid) * .subject(userDid) * .command("/db/read") * .policy([["==", ".command", "/db/read"]]) * .build(rootKeypair); * * const invocationToken = await Builder.invocationFrom(delegationToken) * .audience(serviceDid) * .arguments({ table: "users" }) * .build(userKeypair); * ``` * @see {@link InvocationBuilder} */ readonly invocationFrom: (proof: Envelope) => InvocationBuilder; /** * Creates a delegation builder from a serialized token string. * @param proofString - The base64url encoded delegation token string. * @returns A pre-configured DelegationBuilder. * @throws {Error} Decoding errors from {@link Codec._unsafeDecodeBase64Url} * @throws {Error} "Cannot create a delegation from a proof that is not a delegation" - If decoded token is not a delegation * @example * ```typescript * const chainedToken = await Builder.delegationFromString(tokenString) * .audience(newAudience) * .build(signer); * ``` */ readonly delegationFromString: (proofString: string) => DelegationBuilder; /** * Creates an invocation builder from a serialized token string. * @param proofString - The base64url encoded delegation token string. * @returns A pre-configured InvocationBuilder. * @throws {Error} Decoding errors from {@link Codec._unsafeDecodeBase64Url} * @throws {Error} "Cannot invoke a capability from a proof that is not a delegation" - If decoded token is not a delegation * @example * ```typescript * const invocation = await Builder.invocationFromString(tokenString) * .audience(serviceDid) * .arguments({ action: "read" }) * .build(signer); * ``` */ readonly invocationFromString: (proofString: string) => InvocationBuilder; }; //#endregion //#region src/nuc/codec.d.ts /** * Provides encoding and decoding utilities for NUC tokens. * * The Codec namespace handles the serialization and deserialization of * NUC token envelopes to and from base64url-encoded strings suitable * for network transmission. * * @example * ```typescript * import { Codec, Builder } from "@nillion/nuc"; * * // Create and serialize a token * const envelope = await Builder.delegation() * .audience(audienceDid) * .subject(subjectDid) * .command("/nil/db") * .build(keypair); * * const tokenString = Codec.serializeBase64Url(envelope); * * // Later, parse and validate it * const decoded = Validator.parse(tokenString, { * rootIssuers: ["did:key:..."] * }); * ``` */ declare namespace Codec { /** * [UNSAFE] Decodes a base64url-encoded token string into an Envelope without * performing any signature or structural validation. * * @internal * @private * @warning This function is for internal use and testing only. It does NOT * validate the token's signature, expiration, or chain of trust. * Always use `Validator.parse()` to securely parse and validate tokens. * * @param nucString - The base64url-encoded token string * @returns The decoded but **unvalidated** Envelope */ function _unsafeDecodeBase64Url(nucString: string): Envelope; /** * Serializes an Envelope into a base64url-encoded token string. * * Converts the envelope structure back to a transmittable string format. * Multiple tokens in the proof chain are joined with '/' separators. * * @param envelope - The Envelope to serialize * @returns The base64url-encoded token string * @example * ```typescript * const envelope = await Builder.invocation() * .audience(audienceDid) * .subject(subjectDid) * .command("/db/read") * .build(keypair); * * const tokenString = Codec.serializeBase64Url(envelope); * // Result: "eyJhbGc..." (or "eyJhbGc.../eyJhbGc..." if chained) * ``` */ function serializeBase64Url(envelope: Envelope): string; } //#endregion //#region src/validator/types.d.ts /** * Token requirement types */ type TokenRequirement = { type: "invocation"; audience: string; } | { type: "delegation"; audience: string; }; /** * Validation parameters configuration */ type ValidationParameters = { maxChainLength?: number; maxPolicyWidth?: number; maxPolicyDepth?: number; tokenRequirements?: TokenRequirement; }; /** * Validation options configuration */ type ValidationOptions = { rootIssuers: string[]; params?: ValidationParameters; context?: Record; timeProvider?: () => number; }; //#endregion //#region src/validator/validator.d.ts declare namespace Validator { const CHAIN_TOO_LONG = "token chain is too long"; const COMMAND_NOT_ATTENUATED = "command is not an attenuation"; const DIFFERENT_SUBJECTS = "different subjects in chain"; const ISSUER_AUDIENCE_MISMATCH = "issuer/audience mismatch"; const MISSING_PROOF = "proof is missing"; const NOT_BEFORE_BACKWARDS = "`not before` cannot move backwards"; const PROOFS_MUST_BE_DELEGATIONS = "proofs must be delegations"; const ROOT_KEY_SIGNATURE_MISSING = "root NUC is not signed by a root issuer"; const TOO_MANY_PROOFS = "up to one `prf` in a token is allowed"; const UNCHAINED_PROOFS = "extra proofs not part of chain provided"; const POLICY_TOO_DEEP = "policy is too deep"; const POLICY_TOO_WIDE = "policy is too wide"; const INVALID_SIGNATURES = "invalid signatures"; const NOT_BEFORE_NOT_MET = "`not before` date not met"; const TOKEN_EXPIRED = "token is expired"; const INVALID_AUDIENCE = "invalid audience"; const NEED_DELEGATION = "token must be a delegation"; const NEED_INVOCATION = "token must be an invocation"; const POLICY_NOT_MET = "policy not met"; /** * Parses and validates a NUC token string in a single, secure operation. * * This is the recommended method for consuming NUC tokens. It performs all * necessary checks, including signature verification, chain validation, temporal * checks, and policy evaluation. * * @param tokenString - The base64url-encoded token string to parse and validate. * @param options - The validation options, identical to `Validator.validate`. * @returns A validated `Envelope` object. * @throws Throws an error if any part of the validation fails. See `Validator.validate` for a full list of possible errors. */ function parse(tokenString: string, options: ValidationOptions): Promise; /** * Validates a NUC token envelope against requirements and policies. * * Performs comprehensive validation including signature verification, * chain validation, temporal checks, and policy evaluation. * * @param envelope - The token envelope to validate * @param options - Validation configuration * @param options.rootIssuers Array of trusted root issuer `Did` strings. * @param options.params - Optional validation parameters * @param options.params.maxChainLength - Maximum allowed chain length (default: 5) * @param options.params.maxPolicyWidth - Maximum policy width (default: 10) * @param options.params.maxPolicyDepth - Maximum policy depth (default: 5) * @param options.params.tokenRequirements - Optional token type and audience requirements * @param options.context - Optional context object for policy evaluation * @param options.timeProvider - Optional function returning current time in milliseconds (default: Date.now) * @returns void - Validation succeeds silently * @throws {Error} CHAIN_TOO_LONG - Token chain exceeds maxChainLength * @throws {Error} TOO_MANY_PROOFS - Token references multiple proofs * @throws {Error} PROOFS_MUST_BE_DELEGATIONS - Proof token is not a delegation * @throws {Error} COMMAND_NOT_ATTENUATED - Command is not properly attenuated in chain * @throws {Error} DIFFERENT_SUBJECTS - Subjects differ across the chain * @throws {Error} ISSUER_AUDIENCE_MISMATCH - Issuer/audience don't match in chain * @throws {Error} MISSING_PROOF - Required proof is missing * @throws {Error} NOT_BEFORE_BACKWARDS - notBefore times go backwards in chain * @throws {Error} ROOT_KEY_SIGNATURE_MISSING - Root signature is missing * @throws {Error} UNCHAINED_PROOFS - Proofs are not properly chained * @throws {Error} INVALID_SIGNATURES - Any signature in the chain is invalid * @throws {Error} POLICY_NOT_MET - Policy evaluation fails * @throws {Error} POLICY_TOO_DEEP - Policy depth exceeds maxPolicyDepth * @throws {Error} POLICY_TOO_WIDE - Policy width exceeds maxPolicyWidth * @throws {Error} TOKEN_EXPIRED - Token has expired * @throws {Error} NOT_BEFORE_NOT_MET - Token is not yet valid * @throws {Error} INVALID_AUDIENCE - Audience doesn't match requirements * @throws {Error} NEED_DELEGATION - Invocation provided when delegation required * @throws {Error} NEED_INVOCATION - Delegation provided when invocation required * @example * ```typescript * import { Validator, Codec } from "@nillion/nuc"; * * // Parse and validate a token in a single call * const envelope = Validator.parse(tokenString, { * rootIssuers: ["did:key:zDnae..."], * params: { * maxChainLength: 10, * tokenRequirements: { * type: "invocation", * audience: "did:key:zDnae..." * } * }, * context: { resource: "users", action: "read" } * }); * * // Or decode first, then validate separately * const decoded = Codec._unsafeDecodeBase64Url(tokenString); * try { * Validator.validate(decoded, { * rootIssuers: ["did:key:zDnae..."], * params: { * maxChainLength: 10, * tokenRequirements: { * type: "invocation", * audience: "did:key:zDnae..." * } * }, * context: { resource: "users", action: "read" } * }); * } catch (error) { * if (error instanceof Error && error.message === Validator.TOKEN_EXPIRED) { * console.error("Token has expired"); * } * } * ``` */ function validate(envelope: Envelope, options: ValidationOptions): Promise; } //#endregion export { type And, type AnyOf, Builder, Codec, type Command, type Connector, type DelegationBuilder, type DelegationPayload, Did, type DidEthr, type DidKey, type DidNil, type Eip712Signer, Envelope, type Equals, errors_d_exports as Errors, type InvocationBuilder, type InvocationPayload, type Multicodec, NUC_EIP712_DOMAIN, type Not, type NotEquals, type Nuc, type Operator, type Or, Payload, Policy, type PolicyRule, Signer, type TokenRequirement, type ValidationOptions, type ValidationParameters, Validator };