{"version":3,"file":"sign1Context.mjs","names":[],"sources":["../../../src/crypto/contexts/sign1Context.ts"],"sourcesContent":["import type { Sign1Context } from '@owf/cose'\nimport type { AgentContext } from '../../agent'\nimport { CredoError } from '../../error'\nimport {\n  KeyManagementApi,\n  type KmsJwkPublicAsymmetric,\n  type KnownCoseSignatureAlgorithm,\n  knownJwaFromCoseSignatureAlgorithm,\n  PublicJwk,\n} from '../../modules/kms'\n\nexport const getSign1Context = (agentContext: AgentContext): Sign1Context => {\n  const kms = agentContext.resolve(KeyManagementApi)\n\n  return {\n    sign: async (input) => {\n      if (!input.key.keyId) {\n        throw new CredoError('Missing required keyId on CoseKey for signing mdoc')\n      }\n\n      const algorithm = input.algorithm ?? input.key.algorithm\n      if (algorithm === undefined) {\n        throw new CredoError('Unable to sign COSE Sign1 structure. No algorithm provided or defined on the COSE key.')\n      }\n\n      const { signature } = await kms.sign({\n        data: input.toBeSigned,\n        algorithm: knownJwaFromCoseSignatureAlgorithm(algorithm as KnownCoseSignatureAlgorithm),\n        keyId: input.key.keyId,\n      })\n\n      return signature\n    },\n    verify: async (input) => {\n      // NOTE: @owf/mdoc does not forward the alg from the Sign1 protected header when verifying\n      // the device signature, so we have to fall back to the signature algorithm of the key.\n      // Device keys are single-algorithm EC/OKP keys, so this is unambiguous in practice. The\n      // fallback can be removed once @owf/mdoc passes the alg of the deviceAuth Sign1 structure.\n      const algorithm = input.algorithm ?? input.key.algorithm\n      const jwaAlgorithm = algorithm\n        ? knownJwaFromCoseSignatureAlgorithm(algorithm as KnownCoseSignatureAlgorithm)\n        : PublicJwk.fromUnknown(input.key.jwk).signatureAlgorithm\n\n      const { verified } = await kms.verify({\n        key: {\n          publicJwk: input.key.jwk as KmsJwkPublicAsymmetric,\n        },\n        data: input.toBeVerified,\n        algorithm: jwaAlgorithm,\n\n        signature: input.signature,\n      })\n\n      return verified\n    },\n  } satisfies Sign1Context\n}\n"],"mappings":";;;;;;;AAWA,MAAa,mBAAmB,iBAA6C;CAC3E,MAAM,MAAM,aAAa,QAAQ,gBAAgB;CAEjD,OAAO;EACL,MAAM,OAAO,UAAU;GACrB,IAAI,CAAC,MAAM,IAAI,OACb,MAAM,IAAI,WAAW,oDAAoD;GAG3E,MAAM,YAAY,MAAM,aAAa,MAAM,IAAI;GAC/C,IAAI,cAAc,KAAA,GAChB,MAAM,IAAI,WAAW,wFAAwF;GAG/G,MAAM,EAAE,cAAc,MAAM,IAAI,KAAK;IACnC,MAAM,MAAM;IACZ,WAAW,mCAAmC,SAAwC;IACtF,OAAO,MAAM,IAAI;GACnB,CAAC;GAED,OAAO;EACT;EACA,QAAQ,OAAO,UAAU;GAKvB,MAAM,YAAY,MAAM,aAAa,MAAM,IAAI;GAC/C,MAAM,eAAe,YACjB,mCAAmC,SAAwC,IAC3E,UAAU,YAAY,MAAM,IAAI,GAAG,CAAC,CAAC;GAEzC,MAAM,EAAE,aAAa,MAAM,IAAI,OAAO;IACpC,KAAK,EACH,WAAW,MAAM,IAAI,IACvB;IACA,MAAM,MAAM;IACZ,WAAW;IAEX,WAAW,MAAM;GACnB,CAAC;GAED,OAAO;EACT;CACF;AACF"}