@sphereon/ssi-sdk.siopv2-oid4vp-rp-rest-api 0.34.1-next.88 → 0.36.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/siop-api-functions.ts","../src/webapp-api-functions.ts","../src/siopv2-rp-api-server.ts"],"sourcesContent":["import { AuthorizationResponsePayload } from '@sphereon/did-auth-siop'\nimport { checkAuth, ISingleEndpointOpts, sendErrorResponse } from '@sphereon/ssi-express-support'\nimport { CredentialMapper } from '@sphereon/ssi-types'\nimport { AuthorizationChallengeValidationResponse } from '@sphereon/ssi-sdk.siopv2-oid4vp-common'\nimport { Request, Response, Router } from 'express'\nimport { IRequiredContext } from './types'\n\nconst parseAuthorizationResponse = (request: Request): AuthorizationResponsePayload => {\n const contentType = request.header('content-type')\n\n if (contentType === 'application/json') {\n const payload = typeof request.body === 'string' ? JSON.parse(request.body) : request.body\n return payload as AuthorizationResponsePayload\n }\n\n if (contentType === 'application/x-www-form-urlencoded') {\n const payload = request.body as AuthorizationResponsePayload\n\n // Parse presentation_submission if it's a string\n if (typeof payload.presentation_submission === 'string') {\n console.log(`Supplied presentation_submission was a string instead of JSON. Correcting, but external party should fix their implementation!`)\n payload.presentation_submission = JSON.parse(payload.presentation_submission)\n }\n\n // when using FORM_URL_ENCODED, vp_token comes back as string not matter whether the input was string, object or array. Handled below.\n if (typeof payload.vp_token === 'string') {\n const { vp_token } = payload\n\n // The only use case where vp_object is an object is JsonLdAsString atm. For arrays, any objects will be parsed along with the array\n // (Leaving the vp_token JsonLdAsString causes problems because the original credential will remain string and will be interpreted as JWT in some parts of the code)\n if ((vp_token.startsWith('[') && vp_token.endsWith(']')) || CredentialMapper.isJsonLdAsString(vp_token)) {\n payload.vp_token = JSON.parse(vp_token)\n }\n }\n\n return payload\n }\n\n throw new Error(\n `Unsupported content type: ${contentType}. Currently only application/x-www-form-urlencoded and application/json (for direct_post) are supported`,\n )\n}\n\nexport function verifyAuthResponseSIOPv2Endpoint(router: Router, context: IRequiredContext, opts?: ISingleEndpointOpts) {\n if (opts?.enabled === false) {\n console.log(`verifyAuthResponse SIOP endpoint is disabled`)\n return\n }\n const path = opts?.path ?? '/siop/definitions/:definitionId/auth-responses/:correlationId'\n router.post(path, checkAuth(opts?.endpoint), async (request: Request, response: Response) => {\n try {\n const { correlationId, definitionId, tenantId, version, credentialQueryId } = request.params // TODO Can credentialQueryId be a request param\n if (!correlationId || !definitionId) {\n console.log(`No authorization request could be found for the given url. correlationId: ${correlationId}, definitionId: ${definitionId}`)\n return sendErrorResponse(response, 404, 'No authorization request could be found')\n }\n console.log('Authorization Response (siop-sessions')\n console.log(JSON.stringify(request.body, null, 2))\n const definitionItems = await context.agent.pdmGetDefinitions({ filter: [{ definitionId, tenantId, version }] })\n if (definitionItems.length === 0) {\n console.log(`Could not get definition ${definitionId} from agent. Will return 404`)\n response.statusCode = 404\n response.statusMessage = `No definition ${definitionId}`\n return response.send()\n }\n\n const authorizationResponse = parseAuthorizationResponse(request)\n console.log(`URI: ${JSON.stringify(authorizationResponse)}`)\n\n const definitionItem = definitionItems[0]\n const verifiedResponse = await context.agent.siopVerifyAuthResponse({\n authorizationResponse,\n correlationId,\n definitionId,\n dcqlQuery: definitionItem.dcqlPayload,\n })\n\n const wrappedPresentation = verifiedResponse?.oid4vpSubmission?.presentation[credentialQueryId]\n if (wrappedPresentation) {\n // const credentialSubject = wrappedPresentation.presentation.verifiableCredential[0]?.credential?.credentialSubject\n // console.log(JSON.stringify(credentialSubject, null, 2))\n console.log('PRESENTATION:' + JSON.stringify(wrappedPresentation.presentation, null, 2))\n response.statusCode = 200\n\n const authorizationChallengeValidationResponse: AuthorizationChallengeValidationResponse = {\n presentation_during_issuance_session: verifiedResponse.correlationId,\n }\n if (authorizationResponse.is_first_party) {\n response.setHeader('Content-Type', 'application/json')\n return response.send(JSON.stringify(authorizationChallengeValidationResponse))\n }\n\n const responseRedirectURI = await context.agent.siopGetRedirectURI({ correlationId, definitionId, state: verifiedResponse.state })\n if (responseRedirectURI) {\n response.setHeader('Content-Type', 'application/json')\n return response.send(JSON.stringify({ redirect_uri: responseRedirectURI }))\n }\n // todo: delete session\n } else {\n console.log('Missing Presentation (Verifiable Credentials)')\n response.statusCode = 500\n response.statusMessage = 'Missing Presentation (Verifiable Credentials)'\n }\n return response.send()\n } catch (error) {\n console.error(error)\n return sendErrorResponse(response, 500, 'Could not verify auth status', error)\n }\n })\n}\n\nexport function getAuthRequestSIOPv2Endpoint(router: Router, context: IRequiredContext, opts?: ISingleEndpointOpts) {\n if (opts?.enabled === false) {\n console.log(`getAuthRequest SIOP endpoint is disabled`)\n return\n }\n const path = opts?.path ?? '/siop/definitions/:definitionId/auth-requests/:correlationId'\n router.get(path, checkAuth(opts?.endpoint), async (request: Request, response: Response) => {\n try {\n const correlationId = request.params.correlationId\n const definitionId = request.params.definitionId\n if (!correlationId || !definitionId) {\n console.log(`No authorization request could be found for the given url. correlationId: ${correlationId}, definitionId: ${definitionId}`)\n return sendErrorResponse(response, 404, 'No authorization request could be found')\n }\n const requestState = await context.agent.siopGetAuthRequestState({\n correlationId,\n definitionId,\n errorOnNotFound: false,\n })\n if (!requestState) {\n console.log(\n `No authorization request could be found for the given url in the state manager. correlationId: ${correlationId}, definitionId: ${definitionId}`,\n )\n return sendErrorResponse(response, 404, `No authorization request could be found`)\n }\n const requestObject = await requestState.request?.requestObject?.toJwt()\n console.log('JWT Request object:')\n console.log(requestObject)\n\n let error: string | undefined\n try {\n response.statusCode = 200\n response.setHeader('Content-Type', 'application/jwt')\n return response.send(requestObject)\n } catch (e) {\n error = typeof e === 'string' ? e : e instanceof Error ? e.message : undefined\n return sendErrorResponse(response, 500, 'Could not get authorization request', e)\n } finally {\n await context.agent.siopUpdateAuthRequestState({\n correlationId,\n definitionId,\n state: 'sent',\n error,\n })\n }\n } catch (error) {\n return sendErrorResponse(response, 500, 'Could not get authorization request', error)\n }\n })\n}\n","import { AuthorizationRequestState, AuthorizationResponseStateStatus } from '@sphereon/did-auth-siop'\nimport { checkAuth, ISingleEndpointOpts, sendErrorResponse } from '@sphereon/ssi-express-support'\nimport { AuthStatusResponse, GenerateAuthRequestURIResponse, uriWithBase } from '@sphereon/ssi-sdk.siopv2-oid4vp-common'\nimport { AuthorizationResponseStateWithVerifiedData, VerifiedDataMode } from '@sphereon/ssi-sdk.siopv2-oid4vp-rp-auth'\nimport { Request, Response, Router } from 'express'\nimport uuid from 'short-uuid'\nimport { ICreateAuthRequestWebappEndpointOpts, IRequiredContext } from './types'\nimport { shaHasher as defaultHasher } from '@sphereon/ssi-sdk.core'\n\nexport function createAuthRequestWebappEndpoint(router: Router, context: IRequiredContext, opts?: ICreateAuthRequestWebappEndpointOpts) {\n if (opts?.enabled === false) {\n console.log(`createAuthRequest Webapp endpoint is disabled`)\n return\n }\n const path = opts?.path ?? '/webapp/definitions/:definitionId/auth-requests'\n router.post(path, checkAuth(opts?.endpoint), async (request: Request, response: Response) => {\n try {\n // if (!request.agent) throw Error('No agent configured')\n const definitionId = request.params.definitionId\n if (!definitionId) {\n return sendErrorResponse(response, 400, 'No definitionId query parameter provided')\n }\n const state: string = request.body.state ?? uuid.uuid()\n const correlationId = request.body.correlationId ?? state\n const qrCodeOpts = request.body.qrCodeOpts ?? opts?.qrCodeOpts\n\n const requestByReferenceURI = uriWithBase(`/siop/definitions/${definitionId}/auth-requests/${state}`, {\n baseURI: opts?.siopBaseURI,\n })\n const responseURI = uriWithBase(`/siop/definitions/${definitionId}/auth-responses/${state}`, { baseURI: opts?.siopBaseURI })\n // first version is for backwards compat\n const responseRedirectURI =\n ('response_redirect_uri' in request.body && (request.body.response_redirect_uri as string | undefined)) ??\n ('responseRedirectURI' in request.body && (request.body.responseRedirectURI as string | undefined))\n\n const authRequestURI = await context.agent.siopCreateAuthRequestURI({\n definitionId,\n correlationId,\n state,\n nonce: uuid.uuid(),\n requestByReferenceURI,\n responseURIType: 'response_uri',\n responseURI,\n ...(responseRedirectURI && { responseRedirectURI }),\n })\n\n let qrCodeDataUri: string | undefined\n if (qrCodeOpts) {\n const { AwesomeQR } = await import('awesome-qr')\n const qrCode = new AwesomeQR({ ...qrCodeOpts, text: authRequestURI })\n qrCodeDataUri = `data:image/png;base64,${(await qrCode.draw())!.toString('base64')}`\n }\n const authRequestBody: GenerateAuthRequestURIResponse = {\n correlationId,\n state,\n definitionId,\n authRequestURI,\n authStatusURI: `${uriWithBase(opts?.webappAuthStatusPath ?? '/webapp/auth-status', { baseURI: opts?.webappBaseURI })}`,\n ...(qrCodeDataUri && { qrCodeDataUri }),\n }\n console.log(`Auth Request URI data to send back: ${JSON.stringify(authRequestBody)}`)\n return response.json(authRequestBody)\n } catch (error) {\n return sendErrorResponse(response, 500, 'Could not create an authorization request URI', error)\n }\n })\n}\n\nexport function authStatusWebappEndpoint(router: Router, context: IRequiredContext, opts?: ISingleEndpointOpts) {\n if (opts?.enabled === false) {\n console.log(`authStatus Webapp endpoint is disabled`)\n return\n }\n const path = opts?.path ?? '/webapp/auth-status'\n router.post(path, checkAuth(opts?.endpoint), async (request: Request, response: Response) => {\n try {\n console.log('Received auth-status request...')\n const correlationId: string = request.body.correlationId as string\n const definitionId: string = request.body.definitionId as string\n\n const requestState =\n correlationId && definitionId\n ? await context.agent.siopGetAuthRequestState({\n correlationId,\n definitionId,\n errorOnNotFound: false,\n })\n : undefined\n if (!requestState || !definitionId || !correlationId) {\n console.log(\n `No authentication request mapping could be found for the given URL. correlation: ${correlationId}, definitionId: ${definitionId}`,\n )\n response.statusCode = 404\n const statusBody: AuthStatusResponse = {\n status: requestState ? requestState.status : 'error',\n error: 'No authentication request mapping could be found for the given URL.',\n correlationId,\n definitionId,\n lastUpdated: requestState ? requestState.lastUpdated : Date.now(),\n }\n return response.json(statusBody)\n }\n\n let includeVerifiedData: VerifiedDataMode = VerifiedDataMode.NONE\n if ('includeVerifiedData' in request.body) {\n includeVerifiedData = request.body.includeVerifiedData as VerifiedDataMode\n }\n\n let responseState\n if (requestState.status === 'sent') {\n responseState = (await context.agent.siopGetAuthResponseState({\n correlationId,\n definitionId,\n includeVerifiedData: includeVerifiedData,\n errorOnNotFound: false,\n })) as AuthorizationResponseStateWithVerifiedData\n }\n const overallState: AuthorizationRequestState | AuthorizationResponseStateWithVerifiedData = responseState ?? requestState\n\n const statusBody: AuthStatusResponse = {\n status: overallState.status,\n ...(overallState.error ? { error: overallState.error?.message } : {}),\n correlationId,\n definitionId,\n lastUpdated: overallState.lastUpdated,\n ...(responseState && responseState.status === AuthorizationResponseStateStatus.VERIFIED\n ? {\n payload: await responseState.response.mergedPayloads({ hasher: defaultHasher }),\n verifiedData: responseState.verifiedData,\n }\n : {}),\n }\n console.debug(`Will send auth status: ${JSON.stringify(statusBody)}`)\n if (overallState.status === 'error') {\n response.statusCode = 500\n return response.json(statusBody)\n }\n response.statusCode = 200\n return response.json(statusBody)\n } catch (error) {\n return sendErrorResponse(response, 500, error.message, error)\n }\n })\n}\n\nexport function removeAuthRequestStateWebappEndpoint(router: Router, context: IRequiredContext, opts?: ISingleEndpointOpts) {\n if (opts?.enabled === false) {\n console.log(`removeAuthStatus Webapp endpoint is disabled`)\n return\n }\n const path = opts?.path ?? '/webapp/definitions/:definitionId/auth-requests/:correlationId'\n router.delete(path, checkAuth(opts?.endpoint), async (request: Request, response: Response) => {\n try {\n const correlationId: string = request.params.correlationId\n const definitionId: string = request.params.definitionId\n if (!correlationId || !definitionId) {\n console.log(`No authorization request could be found for the given url. correlationId: ${correlationId}, definitionId: ${definitionId}`)\n return sendErrorResponse(response, 404, 'No authorization request could be found')\n }\n response.statusCode = 200\n return response.json(await context.agent.siopDeleteAuthState({ definitionId, correlationId }))\n } catch (error) {\n return sendErrorResponse(response, 500, error.message, error)\n }\n })\n}\n\nexport function getDefinitionsEndpoint(router: Router, context: IRequiredContext, opts?: ISingleEndpointOpts) {\n if (opts?.enabled === false) {\n console.log(`getDefinitions Webapp endpoint is disabled`)\n return\n }\n const path = opts?.path ?? '/webapp/definitions'\n router.get(path, checkAuth(opts?.endpoint), async (request: Request, response: Response) => {\n try {\n const definitions = await context.agent.pdmGetDefinitions()\n response.statusCode = 200\n return response.json(definitions)\n } catch (error) {\n return sendErrorResponse(response, 500, error.message, error)\n }\n })\n}\n","import { agentContext } from '@sphereon/ssi-sdk.core'\nimport { copyGlobalAuthToEndpoints, ExpressSupport } from '@sphereon/ssi-express-support'\nimport { IPresentationExchange } from '@sphereon/ssi-sdk.presentation-exchange'\nimport { ISIOPv2RP } from '@sphereon/ssi-sdk.siopv2-oid4vp-rp-auth'\nimport { TAgent } from '@veramo/core'\nimport express, { Express, Request, Response, Router } from 'express'\nimport { getAuthRequestSIOPv2Endpoint, verifyAuthResponseSIOPv2Endpoint } from './siop-api-functions'\nimport { IRequiredPlugins, ISIOPv2RPRestAPIOpts } from './types'\nimport {\n authStatusWebappEndpoint,\n createAuthRequestWebappEndpoint,\n getDefinitionsEndpoint,\n removeAuthRequestStateWebappEndpoint,\n} from './webapp-api-functions'\nimport swaggerUi from 'swagger-ui-express'\n\nexport class SIOPv2RPApiServer {\n private readonly _express: Express\n private readonly _router: Router\n private readonly _agent: TAgent<IPresentationExchange & ISIOPv2RP>\n private readonly _opts?: ISIOPv2RPRestAPIOpts\n private readonly _basePath: string\n\n private readonly OID4VP_SWAGGER_URL = 'https://api.swaggerhub.com/apis/SphereonInt/OID4VP/0.1.0'\n constructor(args: { agent: TAgent<IRequiredPlugins>; expressSupport: ExpressSupport; opts?: ISIOPv2RPRestAPIOpts }) {\n const { agent, opts } = args\n this._agent = agent\n copyGlobalAuthToEndpoints({ opts, keys: ['webappCreateAuthRequest', 'webappAuthStatus', 'webappDeleteAuthRequest'] })\n if (opts?.endpointOpts?.globalAuth?.secureSiopEndpoints) {\n copyGlobalAuthToEndpoints({ opts, keys: ['siopGetAuthRequest', 'siopVerifyAuthResponse'] })\n }\n\n this._opts = opts\n this._express = args.expressSupport.express\n this._router = express.Router()\n const context = agentContext(agent)\n\n const features = opts?.enableFeatures ?? ['rp-status', 'siop']\n console.log(`SIOPv2 API enabled, with features: ${JSON.stringify(features)}}`)\n\n // Webapp endpoints\n if (features.includes('rp-status')) {\n createAuthRequestWebappEndpoint(this._router, context, opts?.endpointOpts?.webappCreateAuthRequest)\n authStatusWebappEndpoint(this._router, context, opts?.endpointOpts?.webappAuthStatus)\n removeAuthRequestStateWebappEndpoint(this._router, context, opts?.endpointOpts?.webappDeleteAuthRequest)\n getDefinitionsEndpoint(this._router, context, opts?.endpointOpts?.webappGetDefinitions)\n }\n\n // SIOPv2 endpoints\n if (features.includes('siop')) {\n getAuthRequestSIOPv2Endpoint(this._router, context, opts?.endpointOpts?.siopGetAuthRequest)\n verifyAuthResponseSIOPv2Endpoint(this._router, context, opts?.endpointOpts?.siopVerifyAuthResponse)\n }\n this._basePath = opts?.endpointOpts?.basePath ?? ''\n this._express.use(this._basePath, this.router)\n this._express.set('trust proxy', opts?.endpointOpts?.trustProxy ?? true)\n this.setupSwaggerUi()\n }\n\n private setupSwaggerUi() {\n fetch(this.OID4VP_SWAGGER_URL)\n .then((res) => res.json())\n .then((swagger: any) => {\n const apiDocs = `${this._basePath}/api-docs`\n console.log(`[OID4P] API docs available at ${apiDocs}`)\n\n this._router.use(\n '/api-docs',\n (req: Request, res: Response, next: any) => {\n const regex = `${apiDocs.replace(/\\//, '\\/')}`.replace('/oid4vp', '').replace(/\\/api-docs.*/, '')\n swagger.servers = [{ url: `${req.protocol}://${req.get('host')}${regex}`, description: 'This server' }]\n // @ts-ignore\n req.swaggerDoc = swagger\n next()\n },\n swaggerUi.serveFiles(swagger, options),\n swaggerUi.setup(),\n )\n })\n .catch((err) => {\n console.log(`[OID4VP] Unable to fetch swagger document: ${err}. Will not host api-docs on this instance`)\n })\n const options = {\n // customCss: '.swagger-ui .topbar { display: none }',\n }\n }\n get express(): Express {\n return this._express\n }\n\n get router(): Router {\n return this._router\n }\n\n get agent(): TAgent<IPresentationExchange & ISI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AKL;EACd;EAEA,IAAIM,OAAyC;AAC3C,WAAO,KAAKL;EACd;AACF;","names":["checkAuth","sendErrorResponse","CredentialMapper","parseAuthorizationResponse","request","contentType","header","payload","body","JSON","parse","presentation_submission","console","log","vp_token","startsWith","endsWith","CredentialMapper","isJsonLdAsString","Error","verifyAuthResponseSIOPv2Endpoint","router","context","opts","enabled","path","post","checkAuth","endpoint","response","correlationId","definitionId","tenantId","version","credentialQueryId","params","sendErrorResponse","stringify","definitionItems","agent","pdmGetDefinitions","filter","length","statusCode","statusMessage","send","authorizationResponse","definitionItem","verifiedResponse","siopVerifyAuthResponse","dcqlQuery","dcqlPayload","wrappedPresentation","oid4vpSubmission","presentation","authorizationChallengeValidationResponse","presentation_during_issuance_session","is_first_party","setHeader","responseRedirectURI","siopGetRedirectURI","state","redirect_uri","error","getAuthRequestSIOPv2Endpoint","get","requestState","siopGetAuthRequestState","errorOnNotFound","requestObject","toJwt","e","message","undefined","siopUpdateAuthRequestState","AuthorizationResponseStateStatus","checkAuth","sendErrorResponse","uriWithBase","VerifiedDataMode","uuid","shaHasher","defaultHasher","createAuthRequestWebappEndpoint","router","context","opts","enabled","console","log","path","post","checkAuth","endpoint","request","response","definitionId","params","sendErrorResponse","state","body","uuid","correlationId","qrCodeOpts","requestByReferenceURI","uriWithBase","baseURI","siopBaseURI","responseURI","responseRedirectURI","response_redirect_uri","authRequestURI","agent","siopCreateAuthRequestURI","nonce","responseURIType","qrCodeDataUri","AwesomeQR","qrCode","text","draw","toString","authRequestBody","authStatusURI","webappAuthStatusPath","webappBaseURI","JSON","stringify","json","error","authStatusWebappEndpoint","requestState","siopGetAuthRequestState","errorOnNotFound","undefined","statusCode","statusBody","status","lastUpdated","Date","now","includeVerifiedData","VerifiedDataMode","NONE","responseState","siopGetAuthResponseState","overallState","message","AuthorizationResponseStateStatus","VERIFIED","payload","mergedPayloads","hasher","defaultHasher","verifiedData","debug","removeAuthRequestStateWebappEndpoint","delete","siopDeleteAuthState","getDefinitionsEndpoint","get","definitions","pdmGetDefinitions","agentContext","copyGlobalAuthToEndpoints","express","swaggerUi","SIOPv2RPApiServer","_express","_router","_agent","_opts","_basePath","OID4VP_SWAGGER_URL","args","agent","opts","copyGlobalAuthToEndpoints","keys","endpointOpts","globalAuth","secureSiopEndpoints","expressSupport","express","Router","context","agentContext","features","enableFeatures","console","log","JSON","stringify","includes","createAuthRequestWebappEndpoint","webappCreateAuthRequest","authStatusWebappEndpoint","webappAuthStatus","removeAuthRequestStateWebappEndpoint","webappDeleteAuthRequest","getDefinitionsEndpoint","webappGetDefinitions","getAuthRequestSIOPv2Endpoint","siopGetAuthRequest","verifyAuthResponseSIOPv2Endpoint","siopVerifyAuthResponse","basePath","use","router","set","trustProxy","setupSwaggerUi","fetch","then","res","json","swagger","apiDocs","req","next","regex","replace","servers","url","protocol","get","description","swaggerDoc","swaggerUi","serveFiles","options","setup","catch","err"]}
1
+ {"version":3,"sources":["../src/siop-api-functions.ts","../src/universal-oid4vp-api-functions.ts","../src/middleware/validationMiddleware.ts","../src/siopv2-rp-api-server.ts"],"sourcesContent":["import { AuthorizationResponsePayload, PresentationSubmission } from '@sphereon/did-auth-siop'\nimport { checkAuth, ISingleEndpointOpts, sendErrorResponse } from '@sphereon/ssi-express-support'\nimport { AuthorizationChallengeValidationResponse } from '@sphereon/ssi-sdk.siopv2-oid4vp-common'\nimport { CredentialMapper } from '@sphereon/ssi-types'\nimport { Request, Response, Router } from 'express'\nimport { validate as isValidUUID } from 'uuid'\nimport { IRequiredContext } from './types'\nimport { DcqlQuery } from 'dcql'\n\nconst parseAuthorizationResponse = (request: Request): AuthorizationResponsePayload => {\n const contentType = request.header('content-type')\n\n if (contentType?.startsWith('application/json')) {\n const payload = typeof request.body === 'string' ? JSON.parse(request.body) : request.body\n return payload as AuthorizationResponsePayload\n }\n\n if (contentType?.startsWith('application/x-www-form-urlencoded')) {\n const payload = request.body as AuthorizationResponsePayload\n\n // Parse presentation_submission if it's a string\n if (typeof payload.presentation_submission === 'string') {\n console.log(`Supplied presentation_submission was a string instead of JSON. Correcting, but external party should fix their implementation!`)\n payload.presentation_submission = JSON.parse(payload.presentation_submission)\n }\n\n // when using FORM_URL_ENCODED, vp_token comes back as string not matter whether the input was string, object or array. Handled below.\n if (typeof payload.vp_token === 'string') {\n const { vp_token } = payload\n\n // The only use case where vp_object is an object is JsonLdAsString atm. For arrays, any objects will be parsed along with the array\n // (Leaving the vp_token JsonLdAsString causes problems because the original credential will remain string and will be interpreted as JWT in some parts of the code)\n if ((vp_token.startsWith('[') && vp_token.endsWith(']')) || CredentialMapper.isJsonLdAsString(vp_token)) {\n payload.vp_token = JSON.parse(vp_token)\n }\n }\n\n return payload\n }\n\n throw new Error(\n `Unsupported content type: ${contentType}. Currently only application/x-www-form-urlencoded and application/json (for direct_post) are supported`,\n )\n}\n\nconst validatePresentationSubmission = (query: DcqlQuery, submission: PresentationSubmission): boolean => {\n return query.credentials.every((credential) => credential.id in submission)\n}\n\nexport function verifyAuthResponseSIOPv2Endpoint(router: Router, context: IRequiredContext, opts?: ISingleEndpointOpts) {\n if (opts?.enabled === false) {\n console.log(`verifyAuthResponse SIOP endpoint is disabled`)\n return\n }\n const path = opts?.path ?? '/siop/queries/:queryId/auth-responses/:correlationId'\n router.post(path, checkAuth(opts?.endpoint), async (request: Request, response: Response) => {\n try {\n const { correlationId, queryId, tenantId, version } = request.params\n if (!correlationId) {\n console.log(`No authorization request could be found for the given url. correlationId: ${correlationId}`)\n return sendErrorResponse(response, 404, 'No authorization request could be found')\n }\n console.debug('Authorization Response (siop-sessions') // TODO use logger\n console.debug(JSON.stringify(request.body, null, 2))\n const definitionItems = await context.agent.pdmGetDefinitions({\n filter: buildQueryIdFilter(queryId, tenantId, version),\n })\n if (definitionItems.length === 0) {\n console.log(`Could not get dcql query with id ${queryId} from agent. Will return 404`)\n response.statusCode = 404\n response.statusMessage = `No definition ${queryId}`\n return response.send()\n }\n\n const authorizationResponse = parseAuthorizationResponse(request)\n console.log(`URI: ${JSON.stringify(authorizationResponse)}`)\n\n const definitionItem = definitionItems[0]\n const verifiedResponse = await context.agent.siopVerifyAuthResponse({\n authorizationResponse,\n correlationId,\n dcqlQuery: definitionItem.query,\n })\n\n const presentation = verifiedResponse?.oid4vpSubmission?.presentation\n if (presentation && validatePresentationSubmission(definitionItem.query, presentation)) {\n console.log('PRESENTATIONS:' + JSON.stringify(presentation, null, 2))\n response.statusCode = 200\n\n const authorizationChallengeValidationResponse: AuthorizationChallengeValidationResponse = {\n presentation_during_issuance_session: verifiedResponse.correlationId,\n }\n if (authorizationResponse.is_first_party) {\n response.setHeader('Content-Type', 'application/json')\n return response.send(JSON.stringify(authorizationChallengeValidationResponse))\n }\n\n const responseRedirectURI = await context.agent.siopGetRedirectURI({ correlationId, state: verifiedResponse.state })\n if (responseRedirectURI) {\n response.setHeader('Content-Type', 'application/json')\n return response.send(JSON.stringify({ redirect_uri: responseRedirectURI }))\n }\n // todo: delete session\n } else {\n console.log('Missing Presentation (Verifiable Credentials)')\n response.statusCode = 500\n response.statusMessage = 'Missing Presentation (Verifiable Credentials)'\n }\n return response.send()\n } catch (error) {\n console.error(error)\n return sendErrorResponse(response, 500, 'Could not verify auth status', error)\n }\n })\n}\n\nexport function getAuthRequestSIOPv2Endpoint(router: Router, context: IRequiredContext, opts?: ISingleEndpointOpts) {\n if (opts?.enabled === false) {\n console.log(`getAuthRequest SIOP endpoint is disabled`)\n return\n }\n const path = opts?.path ?? '/siop/queries/:queryId/auth-requests/:correlationId'\n router.get(path, checkAuth(opts?.endpoint), async (request: Request, response: Response) => {\n try {\n const correlationId = request.params.correlationId\n const queryId = request.params.queryId\n if (!correlationId || !queryId) {\n console.log(`No authorization request could be found for the given url. correlationId: ${correlationId}, queryId: ${queryId}`)\n return sendErrorResponse(response, 404, 'No authorization request could be found')\n }\n const requestState = await context.agent.siopGetAuthRequestState({\n correlationId,\n errorOnNotFound: false,\n })\n if (!requestState) {\n console.log(\n `No authorization request could be found for the given url in the state manager. correlationId: ${correlationId}, definitionId: ${queryId}`,\n )\n return sendErrorResponse(response, 404, `No authorization request could be found`)\n }\n\n const definitionItems = await context.agent.pdmGetDefinitions({ filter: buildQueryIdFilter(queryId) })\n if (definitionItems.length === 0) {\n console.log(`Could not get dcql query with id ${queryId} from agent. Will return 404`)\n response.statusCode = 404\n response.statusMessage = `No definition ${queryId}`\n return response.send()\n }\n const payload = requestState.request?.requestObject?.getPayload()!\n payload.dcql_query = definitionItems[0].query\n const requestObject = await requestState.request?.requestObject?.toJwt()\n console.log('JWT Request object:')\n console.log(requestObject)\n\n let error: string | undefined\n try {\n response.statusCode = 200\n response.setHeader('Content-Type', 'application/jwt')\n return response.send(requestObject)\n } catch (e) {\n error = typeof e === 'string' ? e : e instanceof Error ? e.message : undefined\n return sendErrorResponse(response, 500, 'Could not get authorization request', e)\n } finally {\n await context.agent.siopUpdateAuthRequestState({\n correlationId,\n state: 'authorization_request_created',\n error,\n })\n }\n } catch (error) {\n return sendErrorResponse(response, 500, 'Could not get authorization request', error)\n }\n })\n}\n\nexport function buildQueryIdFilter(queryId: string, tenantId?: string, version?: string) {\n const queryFilter = {\n queryId,\n ...(tenantId ? { tenantId } : {}),\n ...(version ? { version } : {}),\n }\n\n return [queryFilter, ...(isValidUUID(queryId) ? [{ id: queryId }] : [])] // Allow both PK (unique queryId + version combi) or just plain queryId which assumes the latest version\n}\n","import {\n AuthorizationRequestStateStatus,\n CreateAuthorizationRequest,\n createAuthorizationRequestFromPayload,\n CreateAuthorizationRequestPayloadSchema,\n CreateAuthorizationResponsePayload,\n} from '@sphereon/did-auth-siop'\nimport { checkAuth, ISingleEndpointOpts, sendErrorResponse } from '@sphereon/ssi-express-support'\nimport { uriWithBase } from '@sphereon/ssi-sdk.siopv2-oid4vp-common'\nimport { Request, Response, Router } from 'express'\nimport uuid from 'short-uuid'\nimport { validateData } from './middleware/validationMiddleware'\nimport { buildQueryIdFilter } from './siop-api-functions'\nimport {\n AuthStatusResponse,\n CreateAuthorizationRequestPayloadRequest,\n CreateAuthorizationResponsePayloadResponse,\n DeleteAuthorizationRequest,\n GetAuthorizationRequestStatus,\n ICreateAuthRequestWebappEndpointOpts,\n IRequiredContext,\n QRCodeOpts,\n} from './types'\n\nexport function createAuthRequestUniversalOID4VPEndpoint(router: Router, context: IRequiredContext, opts?: ICreateAuthRequestWebappEndpointOpts) {\n if (opts?.enabled === false) {\n console.log(`createAuthRequest universal OID4VP endpoint is disabled`)\n return\n }\n\n const path = opts?.path ?? '/backend/auth/requests'\n router.post(\n path,\n checkAuth(opts?.endpoint),\n validateData(CreateAuthorizationRequestPayloadSchema),\n async (request: CreateAuthorizationRequestPayloadRequest, response: CreateAuthorizationResponsePayloadResponse) => {\n try {\n const authRequest: CreateAuthorizationRequest = createAuthorizationRequestFromPayload(request.body)\n const correlationId = authRequest.correlationId ?? uuid.uuid()\n const qrCodeOpts = authRequest.qrCode ? ({ ...authRequest.qrCode } satisfies QRCodeOpts) : opts?.qrCodeOpts\n const queryId = authRequest.queryId\n\n const definitionItems = await context.agent.pdmGetDefinitions({\n filter: buildQueryIdFilter(queryId),\n })\n if (definitionItems.length === 0) {\n console.log(`No query could be found for the given id. Query id: ${queryId}`)\n return sendErrorResponse(response, 404, { status: 404, message: 'No query could be found' })\n }\n\n const requestByReferenceURI = uriWithBase(`/siop/queries/${queryId}/auth-requests/${correlationId}`, {\n baseURI: authRequest.requestUriBase ?? opts?.siopBaseURI,\n })\n const responseURI = uriWithBase(`/siop/queries/${queryId}/auth-responses/${correlationId}`, { baseURI: opts?.siopBaseURI })\n\n const authRequestURI = await context.agent.siopCreateAuthRequestURI({\n queryId,\n correlationId,\n nonce: uuid.uuid(),\n requestByReferenceURI,\n responseURIType: 'response_uri',\n responseURI,\n ...(authRequest.directPostResponseRedirectUri && { responseRedirectURI: authRequest.directPostResponseRedirectUri }),\n ...(authRequest.callback && { callback: authRequest.callback }),\n })\n\n let qrCodeDataUri: string | undefined\n if (qrCodeOpts) {\n const { AwesomeQR } = await import('awesome-qr')\n const qrCode = new AwesomeQR({\n text: authRequestURI,\n size: qrCodeOpts.size ?? 250,\n colorDark: qrCodeOpts.colorDark ?? '#000000',\n colorLight: qrCodeOpts.colorLight ?? '#FFFFFF',\n })\n qrCodeDataUri = `data:image/png;base64,${(await qrCode.draw())!.toString('base64')}`\n } else {\n qrCodeDataUri = authRequestURI\n }\n\n const authRequestBody = {\n query_id: queryId,\n correlation_id: correlationId,\n request_uri: authRequestURI,\n status_uri: `${uriWithBase(opts?.webappAuthStatusPath ?? `/backend/auth/status/${correlationId}`, { baseURI: opts?.webappBaseURI })}`,\n ...(qrCodeDataUri && { qr_uri: qrCodeDataUri }),\n } satisfies CreateAuthorizationResponsePayload\n console.log(`Auth Request URI data to send back: ${JSON.stringify(authRequestBody)}`)\n\n return response.status(201).json(authRequestBody)\n } catch (error) {\n return sendErrorResponse(response, 500, { status: 500, message: 'Could not create an authorization request URI' }, error)\n }\n },\n )\n}\n\nexport function removeAuthRequestStateUniversalOID4VPEndpoint(router: Router, context: IRequiredContext, opts?: ISingleEndpointOpts) {\n if (opts?.enabled === false) {\n console.log(`removeAuthStatus universal OID4VP endpoint is disabled`)\n return\n }\n\n const path = opts?.path ?? '/backend/auth/requests/:correlationId'\n router.delete(path, checkAuth(opts?.endpoint), async (request: DeleteAuthorizationRequest, response: Response) => {\n try {\n const correlationId: string = request.params.correlationId\n\n const authRequestState = await context.agent.siopGetAuthRequestState({\n correlationId,\n errorOnNotFound: false,\n })\n if (!authRequestState) {\n console.log(`No authorization request could be found for the given correlationId. correlationId: ${correlationId}`)\n return sendErrorResponse(response, 404, { status: 404, message: 'No authorization request could be found' })\n }\n\n await context.agent.siopDeleteAuthState({ correlationId })\n\n return response.status(204).json()\n } catch (error) {\n return sendErrorResponse(response, 500, { status: 500, message: error.message }, error)\n }\n })\n}\n\nexport function authStatusUniversalOID4VPEndpoint(router: Router, context: IRequiredContext, opts?: ISingleEndpointOpts) {\n if (opts?.enabled === false) {\n console.log(`authStatus universal OID4VP endpoint is disabled`)\n return\n }\n\n const path = opts?.path ?? '/backend/auth/status/:correlationId'\n router.get(path, checkAuth(opts?.endpoint), async (request: GetAuthorizationRequestStatus, response: Response) => {\n try {\n console.log('Received auth-status request...')\n const correlationId: string = request.params.correlationId\n\n const requestState = await context.agent.siopGetAuthRequestState({\n correlationId,\n errorOnNotFound: false,\n })\n\n if (!requestState) {\n console.log(`No authorization request could be found for the given correlationId. correlationId: ${correlationId}`)\n return sendErrorResponse(response, 404, { status: 404, message: 'No authorization request could be found' })\n }\n\n let responseState\n if (requestState.status === AuthorizationRequestStateStatus.RETRIEVED) {\n responseState = await context.agent.siopGetAuthResponseState({\n correlationId,\n errorOnNotFound: false,\n })\n }\n const overallState = responseState ?? requestState\n\n const statusBody = {\n status: overallState.status,\n correlation_id: overallState.correlationId,\n query_id: overallState.queryId,\n last_updated: overallState.lastUpdated,\n ...('verifiedData' in overallState && { verified_data: overallState.verifiedData }),\n ...(overallState.error && { message: overallState.error.message }),\n } satisfies AuthStatusResponse\n console.debug(`Will send auth status: ${JSON.stringify(statusBody)}`)\n\n if (overallState.status === 'error') {\n return response.status(500).json(statusBody)\n }\n return response.status(200).json(statusBody)\n } catch (error) {\n return sendErrorResponse(response, 500, { status: 500, message: error.message }, error)\n }\n })\n}\n\nexport function getDefinitionsEndpoint(router: Router, context: IRequiredContext, opts?: ISingleEndpointOpts) {\n if (opts?.enabled === false) {\n console.log(`getDefinitions universal OID4VP endpoint is disabled`)\n return\n }\n\n const path = opts?.path ?? '/backend/definitions'\n router.get(path, checkAuth(opts?.endpoint), async (request: Request, response: Response) => {\n try {\n const definitions = await context.agent.pdmGetDefinitions()\n response.statusCode = 200\n return response.json(definitions)\n } catch (error) {\n return sendErrorResponse(response, 500, { status: 500, message: error.message }, error)\n }\n })\n}\n","import { Request, Response, NextFunction } from 'express'\nimport { z, ZodError } from 'zod'\n\nexport const validateData = (schema: z.ZodObject<any, any>) => {\n return (req: Request, res: Response, next: NextFunction) => {\n try {\n schema.parse(req.body)\n next()\n } catch (error) {\n if (error instanceof ZodError) {\n const errorMessages = error.issues.map((issue: any) => ({\n message: `${issue.path.join('.')} is ${issue.message}`,\n }))\n res.status(400).json({ status: 400, message: 'Invalid data', error_details: errorMessages[0].message })\n } else {\n res.status(500).json({ status: 500, message: 'Internal Server Error' })\n }\n }\n }\n}\n","import { agentContext } from '@sphereon/ssi-sdk.core'\nimport { copyGlobalAuthToEndpoints, ExpressSupport } from '@sphereon/ssi-express-support'\nimport { ISIOPv2RP } from '@sphereon/ssi-sdk.siopv2-oid4vp-rp-auth'\nimport { TAgent } from '@veramo/core'\nimport express, { Express, Request, Response, Router } from 'express'\nimport { getAuthRequestSIOPv2Endpoint, verifyAuthResponseSIOPv2Endpoint } from './siop-api-functions'\nimport { IRequiredPlugins, ISIOPv2RPRestAPIOpts } from './types'\nimport {\n authStatusUniversalOID4VPEndpoint,\n createAuthRequestUniversalOID4VPEndpoint,\n getDefinitionsEndpoint,\n removeAuthRequestStateUniversalOID4VPEndpoint,\n} from './universal-oid4vp-api-functions'\nimport swaggerUi from 'swagger-ui-express'\n\nexport class SIOPv2RPApiServer {\n private readonly _express: Express\n private readonly _router: Router\n private readonly _agent: TAgent<ISIOPv2RP>\n private readonly _opts?: ISIOPv2RPRestAPIOpts\n private readonly _basePath: string\n\n private readonly OID4VP_SWAGGER_URL = 'https://api.swaggerhub.com/apis/SphereonInt/OID4VP/0.1.0'\n constructor(args: { agent: TAgent<IRequiredPlugins>; expressSupport: ExpressSupport; opts?: ISIOPv2RPRestAPIOpts }) {\n const { agent, opts } = args\n this._agent = agent\n copyGlobalAuthToEndpoints({ opts, keys: ['webappCreateAuthRequest', 'webappAuthStatus', 'webappDeleteAuthRequest'] })\n if (opts?.endpointOpts?.globalAuth?.secureSiopEndpoints) {\n copyGlobalAuthToEndpoints({ opts, keys: ['siopGetAuthRequest', 'siopVerifyAuthResponse'] })\n }\n\n this._opts = opts\n this._express = args.expressSupport.express\n this._router = express.Router()\n const context = agentContext(agent)\n\n const features = opts?.enableFeatures ?? ['rp-status', 'siop']\n console.log(`SIOPv2 API enabled, with features: ${JSON.stringify(features)}}`)\n\n // Webapp endpoints\n if (features.includes('rp-status')) {\n createAuthRequestUniversalOID4VPEndpoint(this._router, context, opts?.endpointOpts?.webappCreateAuthRequest)\n authStatusUniversalOID4VPEndpoint(this._router, context, opts?.endpointOpts?.webappAuthStatus)\n removeAuthRequestStateUniversalOID4VPEndpoint(this._router, context, opts?.endpointOpts?.webappDeleteAuthRequest)\n getDefinitionsEndpoint(this._router, context, opts?.endpointOpts?.webappGetDefinitions)\n }\n\n // SIOPv2 endpoints\n if (features.includes('siop')) {\n getAuthRequestSIOPv2Endpoint(this._router, context, opts?.endpointOpts?.siopGetAuthRequest)\n verifyAuthResponseSIOPv2Endpoint(this._router, context, opts?.endpointOpts?.siopVerifyAuthResponse)\n }\n this._basePath = opts?.endpointOpts?.basePath ?? ''\n this._express.use(this._basePath, this.router)\n this._express.set('trust proxy', opts?.endpointOpts?.trustProxy ?? true)\n this.setupSwaggerUi()\n }\n\n private setupSwaggerUi() {\n fetch(this.OID4VP_SWAGGER_URL)\n .then((res) => res.json())\n .then((swagger: any) => {\n const apiDocs = `${this._basePath}/api-docs`\n console.log(`[OID4P] API docs available at ${apiDocs}`)\n\n this._router.use(\n '/api-docs',\n (req: Request, res: Response, next: any) => {\n const regex = `${apiDocs.replace(/\\//, '\\/')}`.replace('/oid4vp', '').replace(/\\/api-docs.*/, '')\n swagger.servers = [{ url: `${req.protocol}://${req.get('host')}${regex}`, description: 'This server' }]\n // @ts-ignore\n req.swaggerDoc = swagger\n next()\n },\n swaggerUi.serveFiles(swagger, options),\n swaggerUi.setup(),\n )\n })\n .catch((err) => {\n console.log(`[OID4VP] Unable to fetch swagger document: ${err}. Will not host api-docs on this instance`)\n })\n const options = {\n // customCss: '.swagger-ui .topbar { display: none }',\n }\n }\n get express(): Express {\n return this._express\n }\n\n get router(): Router {\n return this._router\n }\n\n get agent(): TAgent<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AWb,SAASc,OAAAA,GAC9BF,UAAUG,MAAK,CAAA;IAEnB,CAAA,EACCC,MAAM,CAACC,QAAAA;AACN5C,cAAQC,IAAI,8CAA8C2C,GAAAA,2CAA8C;IAC1G,CAAA;AACF,UAAMH,UAAU,CAEhB;EACF;EACA,IAAI/C,UAAmB;AACrB,WAAO,KAAKf;EACd;EAEA,IAAIwC,SAAiB;AACnB,WAAO,KAAKvC;EACd;EAEA,IAAIM,QAA2B;AAC7B,WAAO,KAAKL;EACd;EAEA,IAAIM,OAAyC;AAC3C,WAAO,KAAKL;EACd;AACF;","names":["checkAuth","sendErrorResponse","CredentialMapper","validate","isValidUUID","parseAuthorizationResponse","request","contentType","header","startsWith","payload","body","JSON","parse","presentation_submission","console","log","vp_token","endsWith","CredentialMapper","isJsonLdAsString","Error","validatePresentationSubmission","query","submission","credentials","every","credential","id","verifyAuthResponseSIOPv2Endpoint","router","context","opts","enabled","path","post","checkAuth","endpoint","response","correlationId","queryId","tenantId","version","params","sendErrorResponse","debug","stringify","definitionItems","agent","pdmGetDefinitions","filter","buildQueryIdFilter","length","statusCode","statusMessage","send","authorizationResponse","definitionItem","verifiedResponse","siopVerifyAuthResponse","dcqlQuery","presentation","oid4vpSubmission","authorizationChallengeValidationResponse","presentation_during_issuance_session","is_first_party","setHeader","responseRedirectURI","siopGetRedirectURI","state","redirect_uri","error","getAuthRequestSIOPv2Endpoint","get","requestState","siopGetAuthRequestState","errorOnNotFound","requestObject","getPayload","dcql_query","toJwt","e","message","undefined","siopUpdateAuthRequestState","queryFilter","isValidUUID","AuthorizationRequestStateStatus","createAuthorizationRequestFromPayload","CreateAuthorizationRequestPayloadSchema","checkAuth","sendErrorResponse","uriWithBase","uuid","ZodError","validateData","schema","req","res","next","parse","body","error","ZodError","errorMessages","issues","map","issue","message","path","join","status","json","error_details","createAuthRequestUniversalOID4VPEndpoint","router","context","opts","enabled","console","log","path","post","checkAuth","endpoint","validateData","CreateAuthorizationRequestPayloadSchema","request","response","authRequest","createAuthorizationRequestFromPayload","body","correlationId","uuid","qrCodeOpts","qrCode","queryId","definitionItems","agent","pdmGetDefinitions","filter","buildQueryIdFilter","length","sendErrorResponse","status","message","requestByReferenceURI","uriWithBase","baseURI","requestUriBase","siopBaseURI","responseURI","authRequestURI","siopCreateAuthRequestURI","nonce","responseURIType","directPostResponseRedirectUri","responseRedirectURI","callback","qrCodeDataUri","AwesomeQR","text","size","colorDark","colorLight","draw","toString","authRequestBody","query_id","correlation_id","request_uri","status_uri","webappAuthStatusPath","webappBaseURI","qr_uri","JSON","stringify","json","error","removeAuthRequestStateUniversalOID4VPEndpoint","delete","params","authRequestState","siopGetAuthRequestState","errorOnNotFound","siopDeleteAuthState","authStatusUniversalOID4VPEndpoint","get","requestState","responseState","AuthorizationRequestStateStatus","RETRIEVED","siopGetAuthResponseState","overallState","statusBody","last_updated","lastUpdated","verified_data","verifiedData","debug","getDefinitionsEndpoint","definitions","statusCode","agentContext","copyGlobalAuthToEndpoints","express","swaggerUi","SIOPv2RPApiServer","_express","_router","_agent","_opts","_basePath","OID4VP_SWAGGER_URL","args","agent","opts","copyGlobalAuthToEndpoints","keys","endpointOpts","globalAuth","secureSiopEndpoints","expressSupport","express","Router","context","agentContext","features","enableFeatures","console","log","JSON","stringify","includes","createAuthRequestUniversalOID4VPEndpoint","webappCreateAuthRequest","authStatusUniversalOID4VPEndpoint","webappAuthStatus","removeAuthRequestStateUniversalOID4VPEndpoint","webappDeleteAuthRequest","getDefinitionsEndpoint","webappGetDefinitions","getAuthRequestSIOPv2Endpoint","siopGetAuthRequest","verifyAuthResponseSIOPv2Endpoint","siopVerifyAuthResponse","basePath","use","router","set","trustProxy","setupSwaggerUi","fetch","then","res","json","swagger","apiDocs","req","next","regex","replace","servers","url","protocol","get","description","swaggerDoc","swaggerUi","serveFiles","options","setup","catch","err"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sphereon/ssi-sdk.siopv2-oid4vp-rp-rest-api",
3
- "version": "0.34.1-next.88+7d5f01ed",
3
+ "version": "0.36.0",
4
4
  "source": "src/index.ts",
5
5
  "type": "module",
6
6
  "main": "./dist/index.cjs",
@@ -23,16 +23,16 @@
23
23
  "start:dev": "ts-node __tests__/RestAPI.ts"
24
24
  },
25
25
  "dependencies": {
26
- "@sphereon/did-auth-siop": "0.19.1-feature.SSISDK.45.86",
27
- "@sphereon/ssi-express-support": "0.34.1-next.88+7d5f01ed",
28
- "@sphereon/ssi-sdk.core": "0.34.1-next.88+7d5f01ed",
29
- "@sphereon/ssi-sdk.credential-validation": "0.34.1-next.88+7d5f01ed",
30
- "@sphereon/ssi-sdk.kv-store-temp": "0.34.1-next.88+7d5f01ed",
31
- "@sphereon/ssi-sdk.pd-manager": "0.34.1-next.88+7d5f01ed",
32
- "@sphereon/ssi-sdk.presentation-exchange": "0.34.1-next.88+7d5f01ed",
33
- "@sphereon/ssi-sdk.siopv2-oid4vp-common": "0.34.1-next.88+7d5f01ed",
34
- "@sphereon/ssi-sdk.siopv2-oid4vp-rp-auth": "0.34.1-next.88+7d5f01ed",
35
- "@sphereon/ssi-types": "0.34.1-next.88+7d5f01ed",
26
+ "@sphereon/did-auth-siop": "0.20.0",
27
+ "@sphereon/ssi-express-support": "0.36.0",
28
+ "@sphereon/ssi-sdk.core": "0.36.0",
29
+ "@sphereon/ssi-sdk.credential-validation": "0.36.0",
30
+ "@sphereon/ssi-sdk.kv-store-temp": "0.36.0",
31
+ "@sphereon/ssi-sdk.pd-manager": "0.36.0",
32
+ "@sphereon/ssi-sdk.presentation-exchange": "0.36.0",
33
+ "@sphereon/ssi-sdk.siopv2-oid4vp-common": "0.36.0",
34
+ "@sphereon/ssi-sdk.siopv2-oid4vp-rp-auth": "0.36.0",
35
+ "@sphereon/ssi-types": "0.36.0",
36
36
  "@veramo/core": "4.2.0",
37
37
  "@veramo/credential-w3c": "4.2.0",
38
38
  "awesome-qr": "^2.1.5-rc.0",
@@ -40,22 +40,27 @@
40
40
  "cookie-parser": "^1.4.6",
41
41
  "cors": "^2.8.5",
42
42
  "cross-fetch": "^4.1.0",
43
+ "dcql": "1.0.1",
43
44
  "dotenv-flow": "^3.3.0",
44
45
  "express": "^4.19.2",
45
46
  "short-uuid": "^4.2.2",
46
47
  "swagger-ui-express": "^5.0.1",
47
- "uuid": "^9.0.1"
48
+ "uuid": "^9.0.1",
49
+ "zod": "^4.1.5"
48
50
  },
49
51
  "devDependencies": {
50
52
  "@decentralized-identity/ion-sdk": "^0.6.0",
51
- "@sphereon/did-auth-siop-adapter": "0.19.1-feature.SSISDK.45.86",
53
+ "@sphereon/did-auth-siop-adapter": "0.20.0",
52
54
  "@sphereon/did-uni-client": "^0.6.3",
53
55
  "@sphereon/pex": "5.0.0-unstable.28",
54
56
  "@sphereon/pex-models": "^2.3.2",
55
- "@sphereon/ssi-sdk-ext.did-provider-jwk": "0.34.1-next.88+7d5f01ed",
56
- "@sphereon/ssi-sdk.credential-vcdm": "0.34.1-next.88+7d5f01ed",
57
- "@sphereon/ssi-sdk.credential-vcdm-jsonld-provider": "0.34.1-next.88+7d5f01ed",
58
- "@sphereon/ssi-sdk.data-store": "0.34.1-next.88+7d5f01ed",
57
+ "@sphereon/ssi-sdk-ext.did-provider-jwk": "0.36.0",
58
+ "@sphereon/ssi-sdk-ext.identifier-resolution": "0.36.0",
59
+ "@sphereon/ssi-sdk-ext.jwt-service": "0.36.0",
60
+ "@sphereon/ssi-sdk.credential-vcdm": "0.36.0",
61
+ "@sphereon/ssi-sdk.credential-vcdm-jsonld-provider": "0.36.0",
62
+ "@sphereon/ssi-sdk.data-store": "0.36.0",
63
+ "@sphereon/ssi-sdk.data-store-types": "0.36.0",
59
64
  "@types/body-parser": "^1.19.5",
60
65
  "@types/cookie-parser": "^1.4.7",
61
66
  "@types/cors": "^2.8.17",
@@ -114,5 +119,5 @@
114
119
  "OpenID Connect",
115
120
  "Authenticator"
116
121
  ],
117
- "gitHead": "7d5f01eddab106d7ef084dcef21191ab8dd5f20f"
122
+ "gitHead": "f713d3a83948ef69aaa7d435700b16d5655ac863"
118
123
  }
package/src/index.ts CHANGED
@@ -2,6 +2,6 @@
2
2
  * @public
3
3
  */
4
4
  export * from './siop-api-functions'
5
- export * from './webapp-api-functions'
5
+ export * from './universal-oid4vp-api-functions'
6
6
  export * from './types'
7
7
  export * from './siopv2-rp-api-server'
@@ -0,0 +1,20 @@
1
+ import { Request, Response, NextFunction } from 'express'
2
+ import { z, ZodError } from 'zod'
3
+
4
+ export const validateData = (schema: z.ZodObject<any, any>) => {
5
+ return (req: Request, res: Response, next: NextFunction) => {
6
+ try {
7
+ schema.parse(req.body)
8
+ next()
9
+ } catch (error) {
10
+ if (error instanceof ZodError) {
11
+ const errorMessages = error.issues.map((issue: any) => ({
12
+ message: `${issue.path.join('.')} is ${issue.message}`,
13
+ }))
14
+ res.status(400).json({ status: 400, message: 'Invalid data', error_details: errorMessages[0].message })
15
+ } else {
16
+ res.status(500).json({ status: 500, message: 'Internal Server Error' })
17
+ }
18
+ }
19
+ }
20
+ }
@@ -1,19 +1,21 @@
1
- import { AuthorizationResponsePayload } from '@sphereon/did-auth-siop'
1
+ import { AuthorizationResponsePayload, PresentationSubmission } from '@sphereon/did-auth-siop'
2
2
  import { checkAuth, ISingleEndpointOpts, sendErrorResponse } from '@sphereon/ssi-express-support'
3
- import { CredentialMapper } from '@sphereon/ssi-types'
4
3
  import { AuthorizationChallengeValidationResponse } from '@sphereon/ssi-sdk.siopv2-oid4vp-common'
4
+ import { CredentialMapper } from '@sphereon/ssi-types'
5
5
  import { Request, Response, Router } from 'express'
6
+ import { validate as isValidUUID } from 'uuid'
6
7
  import { IRequiredContext } from './types'
8
+ import { DcqlQuery } from 'dcql'
7
9
 
8
10
  const parseAuthorizationResponse = (request: Request): AuthorizationResponsePayload => {
9
11
  const contentType = request.header('content-type')
10
12
 
11
- if (contentType === 'application/json') {
13
+ if (contentType?.startsWith('application/json')) {
12
14
  const payload = typeof request.body === 'string' ? JSON.parse(request.body) : request.body
13
15
  return payload as AuthorizationResponsePayload
14
16
  }
15
17
 
16
- if (contentType === 'application/x-www-form-urlencoded') {
18
+ if (contentType?.startsWith('application/x-www-form-urlencoded')) {
17
19
  const payload = request.body as AuthorizationResponsePayload
18
20
 
19
21
  // Parse presentation_submission if it's a string
@@ -41,26 +43,32 @@ const parseAuthorizationResponse = (request: Request): AuthorizationResponsePayl
41
43
  )
42
44
  }
43
45
 
46
+ const validatePresentationSubmission = (query: DcqlQuery, submission: PresentationSubmission): boolean => {
47
+ return query.credentials.every((credential) => credential.id in submission)
48
+ }
49
+
44
50
  export function verifyAuthResponseSIOPv2Endpoint(router: Router, context: IRequiredContext, opts?: ISingleEndpointOpts) {
45
51
  if (opts?.enabled === false) {
46
52
  console.log(`verifyAuthResponse SIOP endpoint is disabled`)
47
53
  return
48
54
  }
49
- const path = opts?.path ?? '/siop/definitions/:definitionId/auth-responses/:correlationId'
55
+ const path = opts?.path ?? '/siop/queries/:queryId/auth-responses/:correlationId'
50
56
  router.post(path, checkAuth(opts?.endpoint), async (request: Request, response: Response) => {
51
57
  try {
52
- const { correlationId, definitionId, tenantId, version, credentialQueryId } = request.params // TODO Can credentialQueryId be a request param
53
- if (!correlationId || !definitionId) {
54
- console.log(`No authorization request could be found for the given url. correlationId: ${correlationId}, definitionId: ${definitionId}`)
58
+ const { correlationId, queryId, tenantId, version } = request.params
59
+ if (!correlationId) {
60
+ console.log(`No authorization request could be found for the given url. correlationId: ${correlationId}`)
55
61
  return sendErrorResponse(response, 404, 'No authorization request could be found')
56
62
  }
57
- console.log('Authorization Response (siop-sessions')
58
- console.log(JSON.stringify(request.body, null, 2))
59
- const definitionItems = await context.agent.pdmGetDefinitions({ filter: [{ definitionId, tenantId, version }] })
63
+ console.debug('Authorization Response (siop-sessions') // TODO use logger
64
+ console.debug(JSON.stringify(request.body, null, 2))
65
+ const definitionItems = await context.agent.pdmGetDefinitions({
66
+ filter: buildQueryIdFilter(queryId, tenantId, version),
67
+ })
60
68
  if (definitionItems.length === 0) {
61
- console.log(`Could not get definition ${definitionId} from agent. Will return 404`)
69
+ console.log(`Could not get dcql query with id ${queryId} from agent. Will return 404`)
62
70
  response.statusCode = 404
63
- response.statusMessage = `No definition ${definitionId}`
71
+ response.statusMessage = `No definition ${queryId}`
64
72
  return response.send()
65
73
  }
66
74
 
@@ -71,15 +79,12 @@ export function verifyAuthResponseSIOPv2Endpoint(router: Router, context: IRequi
71
79
  const verifiedResponse = await context.agent.siopVerifyAuthResponse({
72
80
  authorizationResponse,
73
81
  correlationId,
74
- definitionId,
75
- dcqlQuery: definitionItem.dcqlPayload,
82
+ dcqlQuery: definitionItem.query,
76
83
  })
77
84
 
78
- const wrappedPresentation = verifiedResponse?.oid4vpSubmission?.presentation[credentialQueryId]
79
- if (wrappedPresentation) {
80
- // const credentialSubject = wrappedPresentation.presentation.verifiableCredential[0]?.credential?.credentialSubject
81
- // console.log(JSON.stringify(credentialSubject, null, 2))
82
- console.log('PRESENTATION:' + JSON.stringify(wrappedPresentation.presentation, null, 2))
85
+ const presentation = verifiedResponse?.oid4vpSubmission?.presentation
86
+ if (presentation && validatePresentationSubmission(definitionItem.query, presentation)) {
87
+ console.log('PRESENTATIONS:' + JSON.stringify(presentation, null, 2))
83
88
  response.statusCode = 200
84
89
 
85
90
  const authorizationChallengeValidationResponse: AuthorizationChallengeValidationResponse = {
@@ -90,7 +95,7 @@ export function verifyAuthResponseSIOPv2Endpoint(router: Router, context: IRequi
90
95
  return response.send(JSON.stringify(authorizationChallengeValidationResponse))
91
96
  }
92
97
 
93
- const responseRedirectURI = await context.agent.siopGetRedirectURI({ correlationId, definitionId, state: verifiedResponse.state })
98
+ const responseRedirectURI = await context.agent.siopGetRedirectURI({ correlationId, state: verifiedResponse.state })
94
99
  if (responseRedirectURI) {
95
100
  response.setHeader('Content-Type', 'application/json')
96
101
  return response.send(JSON.stringify({ redirect_uri: responseRedirectURI }))
@@ -114,26 +119,35 @@ export function getAuthRequestSIOPv2Endpoint(router: Router, context: IRequiredC
114
119
  console.log(`getAuthRequest SIOP endpoint is disabled`)
115
120
  return
116
121
  }
117
- const path = opts?.path ?? '/siop/definitions/:definitionId/auth-requests/:correlationId'
122
+ const path = opts?.path ?? '/siop/queries/:queryId/auth-requests/:correlationId'
118
123
  router.get(path, checkAuth(opts?.endpoint), async (request: Request, response: Response) => {
119
124
  try {
120
125
  const correlationId = request.params.correlationId
121
- const definitionId = request.params.definitionId
122
- if (!correlationId || !definitionId) {
123
- console.log(`No authorization request could be found for the given url. correlationId: ${correlationId}, definitionId: ${definitionId}`)
126
+ const queryId = request.params.queryId
127
+ if (!correlationId || !queryId) {
128
+ console.log(`No authorization request could be found for the given url. correlationId: ${correlationId}, queryId: ${queryId}`)
124
129
  return sendErrorResponse(response, 404, 'No authorization request could be found')
125
130
  }
126
131
  const requestState = await context.agent.siopGetAuthRequestState({
127
132
  correlationId,
128
- definitionId,
129
133
  errorOnNotFound: false,
130
134
  })
131
135
  if (!requestState) {
132
136
  console.log(
133
- `No authorization request could be found for the given url in the state manager. correlationId: ${correlationId}, definitionId: ${definitionId}`,
137
+ `No authorization request could be found for the given url in the state manager. correlationId: ${correlationId}, definitionId: ${queryId}`,
134
138
  )
135
139
  return sendErrorResponse(response, 404, `No authorization request could be found`)
136
140
  }
141
+
142
+ const definitionItems = await context.agent.pdmGetDefinitions({ filter: buildQueryIdFilter(queryId) })
143
+ if (definitionItems.length === 0) {
144
+ console.log(`Could not get dcql query with id ${queryId} from agent. Will return 404`)
145
+ response.statusCode = 404
146
+ response.statusMessage = `No definition ${queryId}`
147
+ return response.send()
148
+ }
149
+ const payload = requestState.request?.requestObject?.getPayload()!
150
+ payload.dcql_query = definitionItems[0].query
137
151
  const requestObject = await requestState.request?.requestObject?.toJwt()
138
152
  console.log('JWT Request object:')
139
153
  console.log(requestObject)
@@ -149,8 +163,7 @@ export function getAuthRequestSIOPv2Endpoint(router: Router, context: IRequiredC
149
163
  } finally {
150
164
  await context.agent.siopUpdateAuthRequestState({
151
165
  correlationId,
152
- definitionId,
153
- state: 'sent',
166
+ state: 'authorization_request_created',
154
167
  error,
155
168
  })
156
169
  }
@@ -159,3 +172,13 @@ export function getAuthRequestSIOPv2Endpoint(router: Router, context: IRequiredC
159
172
  }
160
173
  })
161
174
  }
175
+
176
+ export function buildQueryIdFilter(queryId: string, tenantId?: string, version?: string) {
177
+ const queryFilter = {
178
+ queryId,
179
+ ...(tenantId ? { tenantId } : {}),
180
+ ...(version ? { version } : {}),
181
+ }
182
+
183
+ return [queryFilter, ...(isValidUUID(queryId) ? [{ id: queryId }] : [])] // Allow both PK (unique queryId + version combi) or just plain queryId which assumes the latest version
184
+ }
@@ -1,23 +1,22 @@
1
1
  import { agentContext } from '@sphereon/ssi-sdk.core'
2
2
  import { copyGlobalAuthToEndpoints, ExpressSupport } from '@sphereon/ssi-express-support'
3
- import { IPresentationExchange } from '@sphereon/ssi-sdk.presentation-exchange'
4
3
  import { ISIOPv2RP } from '@sphereon/ssi-sdk.siopv2-oid4vp-rp-auth'
5
4
  import { TAgent } from '@veramo/core'
6
5
  import express, { Express, Request, Response, Router } from 'express'
7
6
  import { getAuthRequestSIOPv2Endpoint, verifyAuthResponseSIOPv2Endpoint } from './siop-api-functions'
8
7
  import { IRequiredPlugins, ISIOPv2RPRestAPIOpts } from './types'
9
8
  import {
10
- authStatusWebappEndpoint,
11
- createAuthRequestWebappEndpoint,
9
+ authStatusUniversalOID4VPEndpoint,
10
+ createAuthRequestUniversalOID4VPEndpoint,
12
11
  getDefinitionsEndpoint,
13
- removeAuthRequestStateWebappEndpoint,
14
- } from './webapp-api-functions'
12
+ removeAuthRequestStateUniversalOID4VPEndpoint,
13
+ } from './universal-oid4vp-api-functions'
15
14
  import swaggerUi from 'swagger-ui-express'
16
15
 
17
16
  export class SIOPv2RPApiServer {
18
17
  private readonly _express: Express
19
18
  private readonly _router: Router
20
- private readonly _agent: TAgent<IPresentationExchange & ISIOPv2RP>
19
+ private readonly _agent: TAgent<ISIOPv2RP>
21
20
  private readonly _opts?: ISIOPv2RPRestAPIOpts
22
21
  private readonly _basePath: string
23
22
 
@@ -40,9 +39,9 @@ export class SIOPv2RPApiServer {
40
39
 
41
40
  // Webapp endpoints
42
41
  if (features.includes('rp-status')) {
43
- createAuthRequestWebappEndpoint(this._router, context, opts?.endpointOpts?.webappCreateAuthRequest)
44
- authStatusWebappEndpoint(this._router, context, opts?.endpointOpts?.webappAuthStatus)
45
- removeAuthRequestStateWebappEndpoint(this._router, context, opts?.endpointOpts?.webappDeleteAuthRequest)
42
+ createAuthRequestUniversalOID4VPEndpoint(this._router, context, opts?.endpointOpts?.webappCreateAuthRequest)
43
+ authStatusUniversalOID4VPEndpoint(this._router, context, opts?.endpointOpts?.webappAuthStatus)
44
+ removeAuthRequestStateUniversalOID4VPEndpoint(this._router, context, opts?.endpointOpts?.webappDeleteAuthRequest)
46
45
  getDefinitionsEndpoint(this._router, context, opts?.endpointOpts?.webappGetDefinitions)
47
46
  }
48
47
 
@@ -92,7 +91,7 @@ export class SIOPv2RPApiServer {
92
91
  return this._router
93
92
  }
94
93
 
95
- get agent(): TAgent<IPresentationExchange & ISIOPv2RP> {
94
+ get agent(): TAgent<ISIOPv2RP> {
96
95
  return this._agent
97
96
  }
98
97
 
@@ -1,11 +1,15 @@
1
+ import { CreateAuthorizationRequestPayload, CreateAuthorizationResponsePayload } from '@sphereon/did-auth-siop'
1
2
  import { GenericAuthArgs, ISingleEndpointOpts } from '@sphereon/ssi-express-support'
2
- import { IPresentationExchange } from '@sphereon/ssi-sdk.presentation-exchange'
3
+ import { IPDManager } from '@sphereon/ssi-sdk.pd-manager'
4
+ import { AuthorizationRequestStateStatus, AuthorizationResponseStateStatus } from '@sphereon/ssi-sdk.siopv2-oid4vp-common'
3
5
  import { ISIOPv2RP } from '@sphereon/ssi-sdk.siopv2-oid4vp-rp-auth'
4
6
  import { IAgentContext, ICredentialVerifier } from '@veramo/core'
5
- import { IPDManager } from '@sphereon/ssi-sdk.pd-manager'
7
+ import { Request, Response } from 'express'
6
8
  import { QRCodeOpts } from './QRCode.types'
9
+ import { VerifiedData } from '@sphereon/did-auth-siop'
7
10
 
8
11
  export type SiopFeatures = 'rp-status' | 'siop'
12
+
9
13
  export interface ISIOPv2RPRestAPIOpts {
10
14
  enableFeatures?: SiopFeatures[]
11
15
  endpointOpts?: {
@@ -28,5 +32,36 @@ export interface ICreateAuthRequestWebappEndpointOpts extends ISingleEndpointOpt
28
32
  responseRedirectURI?: string
29
33
  }
30
34
 
31
- export type IRequiredPlugins = ICredentialVerifier & ISIOPv2RP & IPresentationExchange & IPDManager
35
+ export type IRequiredPlugins = ICredentialVerifier & ISIOPv2RP & IPDManager
32
36
  export type IRequiredContext = IAgentContext<IRequiredPlugins>
37
+
38
+ export type CreateAuthorizationRequestPayloadRequest = Request<Record<string, never>, any, CreateAuthorizationRequestPayload, Record<string, never>>
39
+
40
+ export type CreateAuthorizationResponsePayloadResponse = Response<CreateAuthorizationResponsePayload>
41
+
42
+ export type DeleteAuthorizationRequest = Request<DeleteAuthorizationRequestPathParameters, any, Record<string, any>, Record<string, any>>
43
+
44
+ export type DeleteAuthorizationRequestPathParameters = {
45
+ correlationId: string
46
+ }
47
+
48
+ export type GetAuthorizationRequestStatus = Request<GetAuthorizationRequestStatusPathParameters, any, Record<string, any>, Record<string, any>>
49
+
50
+ export type GetAuthorizationRequestStatusPathParameters = {
51
+ correlationId: string
52
+ }
53
+
54
+ export type RequestError = {
55
+ status: number
56
+ message: string
57
+ error_details?: string
58
+ }
59
+
60
+ export interface AuthStatusResponse {
61
+ status: AuthorizationRequestStateStatus | AuthorizationResponseStateStatus
62
+ correlation_id: string
63
+ query_id: string
64
+ last_updated: number
65
+ verified_data?: VerifiedData
66
+ error?: RequestError
67
+ }