{
  "version": 3,
  "sources": ["../src/util.ts"],
  "sourcesContent": ["import type { VerifiableDID } from 'iso-did/types'\nimport type { SignatureType } from 'iso-signatures/types'\nimport type { Resolver } from 'iso-signatures/verifiers/resolver.js'\nimport type { Resolver as DidResolver } from 'iso-did'\nimport type { CID } from 'multiformats/cid'\nimport * as dagCbor from '@ipld/dag-cbor'\nimport { DID } from 'iso-did'\nimport { sha256 } from 'multiformats/hashes/sha2'\nimport { CID as CIDClass } from 'multiformats/cid'\nimport { z } from 'zod/v4'\nimport * as Envelope from './envelope.js'\nimport * as varsig from './index.js'\nimport type {\n    PayloadSpec,\n    DecodedEnvelope,\n    CborValue,\n    Statement,\n    SignaturePayload\n} from './types.js'\n\n/**\n * Create the signature payload for a given envelope\n */\nexport function signaturePayload (envelope:DecodedEnvelope<PayloadSpec>) {\n    const payloadTag = `ucan/${envelope.spec}@${envelope.version}` as const\n    const payload = {\n        h: varsig.encode({\n            enc: envelope.enc,\n            alg: envelope.alg,\n        }),\n        [payloadTag]: envelope.payload,\n    } as SignaturePayload\n    return payload\n}\n\nexport function nowInSeconds ():number {\n    return Math.floor(Date.now() / 1000)\n}\n\nexport async function cid (envelope:DecodedEnvelope<PayloadSpec>):Promise<CID> {\n    const bytes = Envelope.encode({\n        signature: envelope.signature,\n        signaturePayload: signaturePayload(envelope),\n    })\n    const hash = await sha256.digest(bytes)\n\n    return CIDClass.create(1, dagCbor.code, hash)\n}\n\n/**\n * Check if a DID and signature type are compatible\n */\nexport function isSigAndDidCompatible (did:VerifiableDID, sigType:SignatureType):boolean {\n    if (did.verifiableDid.type === 'Ed25519' && sigType === 'Ed25519') {\n        return true\n    }\n\n    if (did.verifiableDid.type === 'secp256k1' && sigType === 'ES256K') {\n        return true\n    }\n\n    if (did.verifiableDid.type === 'P-256' && sigType === 'ES256') {\n        return true\n    }\n\n    if (did.verifiableDid.type === 'P-384' && sigType === 'ES384') {\n        return true\n    }\n\n    if (did.verifiableDid.type === 'P-521' && sigType === 'ES512') {\n        return true\n    }\n\n    if (did.verifiableDid.type === 'RSA' && sigType === 'RS256') {\n        return true\n    }\n    if (did.verifiableDid.type === 'secp256k1' && sigType === 'EIP191') {\n        return true\n    }\n\n    return false\n}\n\n/**\n * Validate the expiration of a UCAN\n */\nexport function assertExpiration (exp:number | null):void {\n    const now = nowInSeconds()\n    if (exp !== null && !Number.isSafeInteger(exp)) {\n        throw new TypeError(\n      `UCAN expiration must be null or a safe integer. Received: ${exp}`\n        )\n    }\n\n    if (exp !== null && exp < now) {\n        throw new TypeError(\n      `UCAN expiration must be in the future. Received: ${exp} but current time is ${now}`\n        )\n    }\n}\n\n/**\n * Validate the not before time of a UCAN\n */\nexport function assertNotBefore (nbf?:number):void {\n    if (nbf && nbf > nowInSeconds()) {\n        throw new Error('UCAN not valid yet')\n    }\n}\n\n/**\n * Validate the issuer and signature of a UCAN\n */\nexport async function validateIssuerAndSignature (\n    envelope:DecodedEnvelope<PayloadSpec>,\n    didResolver?:DidResolver\n):Promise<VerifiableDID> {\n    const issuer = await DID.fromString(envelope.payload.iss, didResolver)\n\n    if (!isSigAndDidCompatible(issuer, envelope.alg)) {\n        throw new Error(\n      `UCAN issuer type mismatch: DID ${issuer.verifiableDid.type} and Signature ${envelope.alg} are not compatible`\n        )\n    }\n\n    return issuer\n}\n\n/**\n * Verify the signature of a UCAN and that issuer is compatible with the signature\n */\nexport async function verifySignature (\n    envelope:DecodedEnvelope<PayloadSpec>,\n    signatureVerifierResolver:Resolver,\n    didResolver?:DidResolver\n):Promise<boolean> {\n    const issuer = await validateIssuerAndSignature(envelope, didResolver)\n    const isVerified = await signatureVerifierResolver.verify({\n        signature: envelope.signature,\n        message: dagCbor.encode(signaturePayload(envelope)),\n        did: issuer,\n        type: envelope.alg,\n    })\n\n    if (!isVerified) {\n        throw new Error('UCAN signature verification failed')\n    }\n\n    return true\n}\n\n/**\n * Asserts that a UCAN command string is syntactically valid.\n * If the command is invalid, it throws a descriptive error.\n *\n * Rules:\n * - Commands MUST begin with a slash (/).\n * - Commands MUST be lowercase.\n * - A trailing slash MUST NOT be present, unless the command is exactly \"/\".\n * - Segments MUST be separated by a slash (e.g., no empty segments like \"//\").\n *\n * @throws Error if the command is syntactically invalid.\n */\nexport function assertIsValidCommand (command:string):void {\n    // Rule: Must be a string\n    if (typeof command !== 'string') {\n        throw new TypeError(\n      `Invalid command: Input must be a string, but received type ${typeof command}`\n        )\n    }\n\n    // Rule: Must begin with a slash\n    if (!command.startsWith('/')) {\n        throw new TypeError(\n      `Invalid command: Must begin with a slash (/). Received: \"${command}\"`\n        )\n    }\n\n    // Rule: No trailing slash, unless the command is exactly \"/\"\n    if (command.length > 1 && command.endsWith('/')) {\n        throw new TypeError(\n      `Invalid command: Must not have a trailing slash. Received: \"${command}\"`\n        )\n    }\n\n    // Rule: Must be lowercase\n    if (command !== command.toLowerCase()) {\n        throw new TypeError(\n      `Invalid command: Must be lowercase. Received: \"${command}\"`\n        )\n    }\n\n    // Rule: No empty segments\n    if (command.includes('//')) {\n        throw new TypeError(\n      `Invalid command: Must not contain empty segments (e.g., \"//\"). Received: \"${command}\"`\n        )\n    }\n\n    // If no error was thrown, the command is valid.\n}\n\n/**\n * Assert that the input is a Uint8Array.\n *\n * @throws Error if nonce is not a Uint8Array.\n *\n * @example\n * ```ts twoslash\n * import { assertNonce } from 'iso-ucan/utils'\n * assertNonce(new Uint8Array([1,2,3])) // ok\n * assertNonce('foo') // throws\n * ```\n */\nexport function assertNonce (nonce:unknown):void {\n    if (!(nonce instanceof Uint8Array)) {\n        throw new TypeError(\n      `Invalid nonce: Expected Uint8Array, got ${Object.prototype.toString.call(nonce)}`\n        )\n    }\n}\n\n/**\n * Assert that args is a CBOR serializable object.\n */\nexport function assertArgs (args:unknown):void {\n    const parsed = cborObject.safeParse(args)\n    if (parsed.error) {\n        const pretty = z.prettifyError(parsed.error)\n\n        throw new TypeError(`Invalid args: ${pretty}`, { cause: parsed.error })\n    }\n}\n\n/**\n * Assert that the input is a Record<PropertyKey, unknown>.\n *\n * @throws Error if meta is not a Record<PropertyKey, unknown>.\n */\nexport function assertMeta (meta:unknown):void {\n    if (meta) {\n        const parsed = cborObject.safeParse(meta)\n        if (parsed.error) {\n            const pretty = z.prettifyError(parsed.error)\n\n            throw new TypeError(`Invalid meta: ${pretty}`, { cause: parsed.error })\n        }\n    }\n}\n\n/**\n * Assert that the input is not revoked.\n */\nexport async function assertNotRevoked (cid:CID, isRevokedFn?:(cid:CID) => Promise<boolean>):Promise<void> {\n    isRevokedFn = isRevokedFn ?? (async () => false)\n    const isRevoked = await isRevokedFn(cid)\n    if (isRevoked) {\n        throw new Error('UCAN revoked')\n    }\n}\n\n/**\n * Expiration or TTL (default 300 seconds)\n */\nexport function expOrTtl ({ exp, ttl }:{ exp?:number | null; ttl?:number }):number | null {\n    if (exp === null) {\n        return exp\n    }\n    const currentTimeInSeconds = Math.floor(Date.now() / 1000)\n    const expiration = exp ?? currentTimeInSeconds + (ttl ?? 300)\n\n    return expiration\n}\n\nexport const cborValue: z.ZodType<CborValue> = z.lazy(() => {\n    return z.union([\n        z.string(),\n        z.number(),\n        z.boolean(),\n        z.null(),\n        z.bigint(),\n        z.instanceof(Uint8Array),\n        z.array(cborValue),\n        z.record(z.string(), cborValue),\n    ])\n})\n\nexport const cborObject = z.record(z.string(), cborValue)\n\nexport const selector = z.union([\n    z.literal('.'),\n    z.string().regex(/^\\.([a-zA-Z0-9_]+)$/),\n])\n\nexport type Selector = z.infer<typeof selector>\n\n/**\n * Statement\n */\nexport const statement:z.ZodType<Statement<unknown>> = z.lazy(() => {\n    return z.union([\n        z.tuple([\n            z.union([z.literal('=='), z.literal('!=')]),\n            z.literal('.'),\n            z.unknown(),\n        ]), // Equality\n        z.tuple([\n            z.union([\n                z.literal('<'),\n                z.literal('<='),\n                z.literal('>'),\n                z.literal('>='),\n            ]),\n            z.literal('.'),\n            z.number(),\n        ]), // Inequality\n        z.tuple([z.literal('like'), z.literal('.'), z.string()]), // Like\n        z.tuple([z.literal('not'), statement]),\n        z.tuple([z.literal('and'), z.array(statement)]),\n        z.tuple([z.literal('or'), z.array(statement)]),\n        z.tuple([z.literal('all'), z.literal('.'), statement]),\n        z.tuple([z.literal('any'), z.literal('.'), statement]),\n    ]) as z.ZodType<Statement<unknown>>\n})\n\nexport const policySchema = z.array(statement)\n\nexport function assertPolicy (policy:unknown):void {\n    const parsed = policySchema.safeParse(policy)\n    if (parsed.error) {\n        const pretty = z.prettifyError(parsed.error)\n\n        throw new TypeError(`Invalid policy: ${pretty}`, { cause: parsed.error })\n    }\n}\n\n/**\n * A type guard for Record<PropertyKey, unknown>.\n *\n * @returns Whether the specified value has a runtime type of `object` and is\n * neither `null` nor an `Array`.\n */\nexport function isObject (value:unknown):value is Record<PropertyKey, unknown> {\n    return Boolean(value) && typeof value === 'object' && !Array.isArray(value)\n}\n"],
  "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAKA,cAAyB;AACzB,qBAAoB;AACpB,kBAAuB;AACvB,iBAAgC;AAChC,gBAAkB;AAClB,eAA0B;AAC1B,aAAwB;AAYjB,SAAS,iBAAkB,UAAuC;AACrE,QAAM,aAAa,QAAQ,SAAS,IAAI,IAAI,SAAS,OAAO;AAC5D,QAAM,UAAU;AAAA,IACZ,GAAG,OAAO,OAAO;AAAA,MACb,KAAK,SAAS;AAAA,MACd,KAAK,SAAS;AAAA,IAClB,CAAC;AAAA,IACD,CAAC,UAAU,GAAG,SAAS;AAAA,EAC3B;AACA,SAAO;AACX;AAVgB;AAYT,SAAS,eAAuB;AACnC,SAAO,KAAK,MAAM,KAAK,IAAI,IAAI,GAAI;AACvC;AAFgB;AAIhB,eAAsB,IAAK,UAAoD;AAC3E,QAAM,QAAQ,SAAS,OAAO;AAAA,IAC1B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