{"version":3,"file":"OpenId4VcVerifierModule.mjs","names":[],"sources":["../../src/openid4vc-verifier/OpenId4VcVerifierModule.ts"],"sourcesContent":["import type { AgentContext, DependencyManager, Module } from '@credo-ts/core'\nimport type { NextFunction, Response } from 'express'\nimport { getAgentContextForActorId, getRequestContext, importExpress } from '../shared/router'\nimport { OpenId4VcVerifierApi } from './OpenId4VcVerifierApi'\nimport type { InternalOpenId4VcVerifierModuleConfigOptions } from './OpenId4VcVerifierModuleConfig'\nimport { OpenId4VcVerifierModuleConfig } from './OpenId4VcVerifierModuleConfig'\nimport { OpenId4VpVerifierService } from './OpenId4VpVerifierService'\nimport { OpenId4VcVerifierRepository } from './repository'\nimport type { OpenId4VcVerificationRequest } from './router'\nimport { configureAuthorizationEndpoint } from './router'\nimport { configureAuthorizationRequestEndpoint } from './router/authorizationRequestEndpoint'\n\n/**\n * @public\n */\nexport class OpenId4VcVerifierModule implements Module {\n  public readonly config: OpenId4VcVerifierModuleConfig\n\n  public constructor(options: InternalOpenId4VcVerifierModuleConfigOptions | OpenId4VcVerifierModuleConfig) {\n    this.config =\n      options instanceof OpenId4VcVerifierModuleConfig ? options : new OpenId4VcVerifierModuleConfig(options)\n  }\n\n  /**\n   * Registers the dependencies of the openid4vc verifier module on the dependency manager.\n   */\n  public register(dependencyManager: DependencyManager) {\n    // Since the OpenID4VC module is a nested module (a module consisting of three modules) we register the API\n    // manually. In the future we may disallow resolving the sub-api, but for now it allows for a cleaner migration path\n    dependencyManager.registerContextScoped(OpenId4VcVerifierApi)\n\n    // Register config\n    dependencyManager.registerInstance(OpenId4VcVerifierModuleConfig, this.config)\n\n    // Services\n    dependencyManager.registerSingleton(OpenId4VpVerifierService)\n\n    // Repository\n    dependencyManager.registerSingleton(OpenId4VcVerifierRepository)\n  }\n\n  public async initialize(rootAgentContext: AgentContext): Promise<void> {\n    this.configureRouter(rootAgentContext)\n  }\n\n  /**\n   * Registers the endpoints on the router passed to this module.\n   */\n  private configureRouter(rootAgentContext: AgentContext) {\n    const { Router, json, urlencoded } = importExpress()\n\n    // FIXME: it is currently not possible to initialize an agent\n    // shut it down, and then start it again, as the\n    // express router is configured with a specific `AgentContext` instance\n    // and dependency manager. One option is to always create a new router\n    // but then users cannot pass their own router implementation.\n    // We need to find a proper way to fix this.\n\n    const basePath = new URL(this.config.baseUrl).pathname\n\n    // We use separate context router and endpoint router. Context router handles the linking of the request\n    // to a specific agent context. Endpoint router only knows about a single context\n    const verifierEndpointRouter = Router()\n    const verifierContextRouter = Router()\n\n    // parse application/x-www-form-urlencoded\n    verifierContextRouter.use(urlencoded({ extended: false }))\n    // parse application/json\n    verifierContextRouter.use(json())\n\n    verifierContextRouter.param('verifierId', this.getVerifierIdParamHandler(rootAgentContext))\n    verifierContextRouter.use('/:verifierId', verifierEndpointRouter)\n\n    // Configure endpoints\n    configureAuthorizationEndpoint(verifierEndpointRouter, this.config)\n    configureAuthorizationRequestEndpoint(verifierEndpointRouter, this.config)\n\n    // First one will be called for all requests (when next is called)\n    verifierContextRouter.use(async (req: OpenId4VcVerificationRequest, _res: unknown, next) => {\n      const { agentContext } = getRequestContext(req)\n      await agentContext.endSession()\n      next()\n    })\n\n    // This one will be called for all errors that are thrown\n    verifierContextRouter.use(\n      async (_error: unknown, req: OpenId4VcVerificationRequest, res: Response, next: NextFunction) => {\n        const { agentContext } = getRequestContext(req)\n\n        if (!res.headersSent) {\n          agentContext.config.logger.warn(\n            'Error was thrown but openid4vci endpoint did not send a response. Sending generic server_error.'\n          )\n\n          res.status(500).json({\n            error: 'server_error',\n            error_description: 'An unexpected error occurred on the server.',\n          })\n        }\n\n        await agentContext.endSession()\n        next()\n      }\n    )\n\n    this.config.app.use(basePath, verifierContextRouter)\n  }\n\n  private getVerifierIdParamHandler =\n    (rootAgentContext: AgentContext) =>\n    async (req: OpenId4VcVerificationRequest, res: Response, next: NextFunction, verifierId: string) => {\n      if (!verifierId) {\n        rootAgentContext.config.logger.debug(\n          'No verifierId provided for incoming authorization response, returning 404'\n        )\n        return res.status(404).send('Not found')\n      }\n\n      let agentContext: AgentContext | undefined\n\n      try {\n        agentContext = await getAgentContextForActorId(rootAgentContext, verifierId)\n        const verifierApi = agentContext.dependencyManager.resolve(OpenId4VcVerifierApi)\n        const verifier = await verifierApi.getVerifierByVerifierId(verifierId)\n\n        req.requestContext = {\n          agentContext,\n          verifier,\n        }\n      } catch (error) {\n        agentContext?.config.logger.error(\n          'Failed to correlate incoming openid request to existing tenant and verifier',\n          {\n            error,\n          }\n        )\n        // If the opening failed\n        await agentContext?.endSession()\n        return res.status(404).send('Not found')\n      }\n\n      next()\n    }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAeA,IAAa,0BAAb,MAAuD;CAGrD,AAAO,YAAY,SAAuF;OA0FlG,6BACL,qBACD,OAAO,KAAmC,KAAe,MAAoB,eAAuB;AAClG,OAAI,CAAC,YAAY;AACf,qBAAiB,OAAO,OAAO,MAC7B,4EACD;AACD,WAAO,IAAI,OAAO,IAAI,CAAC,KAAK,YAAY;;GAG1C,IAAI;AAEJ,OAAI;AACF,mBAAe,MAAM,0BAA0B,kBAAkB,WAAW;IAE5E,MAAM,WAAW,MADG,aAAa,kBAAkB,QAAQ,qBAAqB,CAC7C,wBAAwB,WAAW;AAEtE,QAAI,iBAAiB;KACnB;KACA;KACD;YACM,OAAO;AACd,kBAAc,OAAO,OAAO,MAC1B,+EACA,EACE,OACD,CACF;AAED,UAAM,cAAc,YAAY;AAChC,WAAO,IAAI,OAAO,IAAI,CAAC,KAAK,YAAY;;AAG1C,SAAM;;AA1HR,OAAK,SACH,mBAAmB,gCAAgC,UAAU,IAAI,8BAA8B,QAAQ;;;;;CAM3G,AAAO,SAAS,mBAAsC;AAGpD,oBAAkB,sBAAsB,qBAAqB;AAG7D,oBAAkB,iBAAiB,+BAA+B,KAAK,OAAO;AAG9E,oBAAkB,kBAAkB,yBAAyB;AAG7D,oBAAkB,kBAAkB,4BAA4B;;CAGlE,MAAa,WAAW,kBAA+C;AACrE,OAAK,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