{
  "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": "6mBAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,gBAAAE,EAAA,qBAAAC,EAAA,yBAAAC,EAAA,eAAAC,EAAA,gBAAAC,EAAA,oBAAAC,EAAA,qBAAAC,EAAA,iBAAAC,EAAA,eAAAC,EAAA,cAAAC,EAAA,QAAAC,EAAA,aAAAC,EAAA,aAAAC,EAAA,0BAAAC,EAAA,iBAAAC,EAAA,iBAAAC,EAAA,aAAAC,EAAA,qBAAAC,EAAA,cAAAC,EAAA,+BAAAC,EAAA,oBAAAC,IAAA,eAAAC,EAAAvB,GAKA,IAAAwB,EAAyB,+BACzBC,EAAoB,mBACpBC,EAAuB,oCACvBC,EAAgC,4BAChCC,EAAkB,kBAClBC,EAA0B,8BAC1BC,EAAwB,2BAYjB,SAASC,EAAkBC,EAAuC,CACrE,MAAMC,EAAa,QAAQD,EAAS,IAAI,IAAIA,EAAS,OAAO,GAQ5D,MAPgB,CACZ,EAAGF,EAAO,OAAO,CACb,IAAKE,EAAS,IACd,IAAKA,EAAS,GAClB,CAAC,EACD,CAACC,CAAU,EAAGD,EAAS,OAC3B,CAEJ,CAVgBE,EAAAH,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,GAAU,UAAY,CAAC,MAAM,QAAQA,CAAK,CAC9E,CAFgB1C,EAAAyC,EAAA",
  "names": ["util_exports", "__export", "assertArgs", "assertExpiration", "assertIsValidCommand", "assertMeta", "assertNonce", "assertNotBefore", "assertNotRevoked", "assertPolicy", "cborObject", "cborValue", "cid", "expOrTtl", "isObject", "isSigAndDidCompatible", "nowInSeconds", "policySchema", "selector", "signaturePayload", "statement", "validateIssuerAndSignature", "verifySignature", "__toCommonJS", "dagCbor", "import_iso_did", "import_sha2", "import_cid", "import_v4", "Envelope", "varsig", "signaturePayload", "envelope", "payloadTag", "__name", "nowInSeconds", "cid", "bytes", "hash", "CIDClass", "isSigAndDidCompatible", "did", "sigType", "assertExpiration", "exp", "now", "assertNotBefore", "nbf", "validateIssuerAndSignature", "didResolver", "issuer", "verifySignature", "signatureVerifierResolver", "assertIsValidCommand", "command", "assertNonce", "nonce", "assertArgs", "args", "parsed", "cborObject", "pretty", "assertMeta", "meta", "assertNotRevoked", "isRevokedFn", "expOrTtl", "ttl", "currentTimeInSeconds", "cborValue", "selector", "statement", "policySchema", "assertPolicy", "policy", "isObject", "value"]
}
