@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.
@@ -0,0 +1,194 @@
1
+ import {
2
+ AuthorizationRequestStateStatus,
3
+ CreateAuthorizationRequest,
4
+ createAuthorizationRequestFromPayload,
5
+ CreateAuthorizationRequestPayloadSchema,
6
+ CreateAuthorizationResponsePayload,
7
+ } from '@sphereon/did-auth-siop'
8
+ import { checkAuth, ISingleEndpointOpts, sendErrorResponse } from '@sphereon/ssi-express-support'
9
+ import { uriWithBase } from '@sphereon/ssi-sdk.siopv2-oid4vp-common'
10
+ import { Request, Response, Router } from 'express'
11
+ import uuid from 'short-uuid'
12
+ import { validateData } from './middleware/validationMiddleware'
13
+ import { buildQueryIdFilter } from './siop-api-functions'
14
+ import {
15
+ AuthStatusResponse,
16
+ CreateAuthorizationRequestPayloadRequest,
17
+ CreateAuthorizationResponsePayloadResponse,
18
+ DeleteAuthorizationRequest,
19
+ GetAuthorizationRequestStatus,
20
+ ICreateAuthRequestWebappEndpointOpts,
21
+ IRequiredContext,
22
+ QRCodeOpts,
23
+ } from './types'
24
+
25
+ export function createAuthRequestUniversalOID4VPEndpoint(router: Router, context: IRequiredContext, opts?: ICreateAuthRequestWebappEndpointOpts) {
26
+ if (opts?.enabled === false) {
27
+ console.log(`createAuthRequest universal OID4VP endpoint is disabled`)
28
+ return
29
+ }
30
+
31
+ const path = opts?.path ?? '/backend/auth/requests'
32
+ router.post(
33
+ path,
34
+ checkAuth(opts?.endpoint),
35
+ validateData(CreateAuthorizationRequestPayloadSchema),
36
+ async (request: CreateAuthorizationRequestPayloadRequest, response: CreateAuthorizationResponsePayloadResponse) => {
37
+ try {
38
+ const authRequest: CreateAuthorizationRequest = createAuthorizationRequestFromPayload(request.body)
39
+ const correlationId = authRequest.correlationId ?? uuid.uuid()
40
+ const qrCodeOpts = authRequest.qrCode ? ({ ...authRequest.qrCode } satisfies QRCodeOpts) : opts?.qrCodeOpts
41
+ const queryId = authRequest.queryId
42
+
43
+ const definitionItems = await context.agent.pdmGetDefinitions({
44
+ filter: buildQueryIdFilter(queryId),
45
+ })
46
+ if (definitionItems.length === 0) {
47
+ console.log(`No query could be found for the given id. Query id: ${queryId}`)
48
+ return sendErrorResponse(response, 404, { status: 404, message: 'No query could be found' })
49
+ }
50
+
51
+ const requestByReferenceURI = uriWithBase(`/siop/queries/${queryId}/auth-requests/${correlationId}`, {
52
+ baseURI: authRequest.requestUriBase ?? opts?.siopBaseURI,
53
+ })
54
+ const responseURI = uriWithBase(`/siop/queries/${queryId}/auth-responses/${correlationId}`, { baseURI: opts?.siopBaseURI })
55
+
56
+ const authRequestURI = await context.agent.siopCreateAuthRequestURI({
57
+ queryId,
58
+ correlationId,
59
+ nonce: uuid.uuid(),
60
+ requestByReferenceURI,
61
+ responseURIType: 'response_uri',
62
+ responseURI,
63
+ ...(authRequest.directPostResponseRedirectUri && { responseRedirectURI: authRequest.directPostResponseRedirectUri }),
64
+ ...(authRequest.callback && { callback: authRequest.callback }),
65
+ })
66
+
67
+ let qrCodeDataUri: string | undefined
68
+ if (qrCodeOpts) {
69
+ const { AwesomeQR } = await import('awesome-qr')
70
+ const qrCode = new AwesomeQR({
71
+ text: authRequestURI,
72
+ size: qrCodeOpts.size ?? 250,
73
+ colorDark: qrCodeOpts.colorDark ?? '#000000',
74
+ colorLight: qrCodeOpts.colorLight ?? '#FFFFFF',
75
+ })
76
+ qrCodeDataUri = `data:image/png;base64,${(await qrCode.draw())!.toString('base64')}`
77
+ } else {
78
+ qrCodeDataUri = authRequestURI
79
+ }
80
+
81
+ const authRequestBody = {
82
+ query_id: queryId,
83
+ correlation_id: correlationId,
84
+ request_uri: authRequestURI,
85
+ status_uri: `${uriWithBase(opts?.webappAuthStatusPath ?? `/backend/auth/status/${correlationId}`, { baseURI: opts?.webappBaseURI })}`,
86
+ ...(qrCodeDataUri && { qr_uri: qrCodeDataUri }),
87
+ } satisfies CreateAuthorizationResponsePayload
88
+ console.log(`Auth Request URI data to send back: ${JSON.stringify(authRequestBody)}`)
89
+
90
+ return response.status(201).json(authRequestBody)
91
+ } catch (error) {
92
+ return sendErrorResponse(response, 500, { status: 500, message: 'Could not create an authorization request URI' }, error)
93
+ }
94
+ },
95
+ )
96
+ }
97
+
98
+ export function removeAuthRequestStateUniversalOID4VPEndpoint(router: Router, context: IRequiredContext, opts?: ISingleEndpointOpts) {
99
+ if (opts?.enabled === false) {
100
+ console.log(`removeAuthStatus universal OID4VP endpoint is disabled`)
101
+ return
102
+ }
103
+
104
+ const path = opts?.path ?? '/backend/auth/requests/:correlationId'
105
+ router.delete(path, checkAuth(opts?.endpoint), async (request: DeleteAuthorizationRequest, response: Response) => {
106
+ try {
107
+ const correlationId: string = request.params.correlationId
108
+
109
+ const authRequestState = await context.agent.siopGetAuthRequestState({
110
+ correlationId,
111
+ errorOnNotFound: false,
112
+ })
113
+ if (!authRequestState) {
114
+ console.log(`No authorization request could be found for the given correlationId. correlationId: ${correlationId}`)
115
+ return sendErrorResponse(response, 404, { status: 404, message: 'No authorization request could be found' })
116
+ }
117
+
118
+ await context.agent.siopDeleteAuthState({ correlationId })
119
+
120
+ return response.status(204).json()
121
+ } catch (error) {
122
+ return sendErrorResponse(response, 500, { status: 500, message: error.message }, error)
123
+ }
124
+ })
125
+ }
126
+
127
+ export function authStatusUniversalOID4VPEndpoint(router: Router, context: IRequiredContext, opts?: ISingleEndpointOpts) {
128
+ if (opts?.enabled === false) {
129
+ console.log(`authStatus universal OID4VP endpoint is disabled`)
130
+ return
131
+ }
132
+
133
+ const path = opts?.path ?? '/backend/auth/status/:correlationId'
134
+ router.get(path, checkAuth(opts?.endpoint), async (request: GetAuthorizationRequestStatus, response: Response) => {
135
+ try {
136
+ console.log('Received auth-status request...')
137
+ const correlationId: string = request.params.correlationId
138
+
139
+ const requestState = await context.agent.siopGetAuthRequestState({
140
+ correlationId,
141
+ errorOnNotFound: false,
142
+ })
143
+
144
+ if (!requestState) {
145
+ console.log(`No authorization request could be found for the given correlationId. correlationId: ${correlationId}`)
146
+ return sendErrorResponse(response, 404, { status: 404, message: 'No authorization request could be found' })
147
+ }
148
+
149
+ let responseState
150
+ if (requestState.status === AuthorizationRequestStateStatus.RETRIEVED) {
151
+ responseState = await context.agent.siopGetAuthResponseState({
152
+ correlationId,
153
+ errorOnNotFound: false,
154
+ })
155
+ }
156
+ const overallState = responseState ?? requestState
157
+
158
+ const statusBody = {
159
+ status: overallState.status,
160
+ correlation_id: overallState.correlationId,
161
+ query_id: overallState.queryId,
162
+ last_updated: overallState.lastUpdated,
163
+ ...('verifiedData' in overallState && { verified_data: overallState.verifiedData }),
164
+ ...(overallState.error && { message: overallState.error.message }),
165
+ } satisfies AuthStatusResponse
166
+ console.debug(`Will send auth status: ${JSON.stringify(statusBody)}`)
167
+
168
+ if (overallState.status === 'error') {
169
+ return response.status(500).json(statusBody)
170
+ }
171
+ return response.status(200).json(statusBody)
172
+ } catch (error) {
173
+ return sendErrorResponse(response, 500, { status: 500, message: error.message }, error)
174
+ }
175
+ })
176
+ }
177
+
178
+ export function getDefinitionsEndpoint(router: Router, context: IRequiredContext, opts?: ISingleEndpointOpts) {
179
+ if (opts?.enabled === false) {
180
+ console.log(`getDefinitions universal OID4VP endpoint is disabled`)
181
+ return
182
+ }
183
+
184
+ const path = opts?.path ?? '/backend/definitions'
185
+ router.get(path, checkAuth(opts?.endpoint), async (request: Request, response: Response) => {
186
+ try {
187
+ const definitions = await context.agent.pdmGetDefinitions()
188
+ response.statusCode = 200
189
+ return response.json(definitions)
190
+ } catch (error) {
191
+ return sendErrorResponse(response, 500, { status: 500, message: error.message }, error)
192
+ }
193
+ })
194
+ }
@@ -1,183 +0,0 @@
1
- import { AuthorizationRequestState, AuthorizationResponseStateStatus } from '@sphereon/did-auth-siop'
2
- import { checkAuth, ISingleEndpointOpts, sendErrorResponse } from '@sphereon/ssi-express-support'
3
- import { AuthStatusResponse, GenerateAuthRequestURIResponse, uriWithBase } from '@sphereon/ssi-sdk.siopv2-oid4vp-common'
4
- import { AuthorizationResponseStateWithVerifiedData, VerifiedDataMode } from '@sphereon/ssi-sdk.siopv2-oid4vp-rp-auth'
5
- import { Request, Response, Router } from 'express'
6
- import uuid from 'short-uuid'
7
- import { ICreateAuthRequestWebappEndpointOpts, IRequiredContext } from './types'
8
- import { shaHasher as defaultHasher } from '@sphereon/ssi-sdk.core'
9
-
10
- export function createAuthRequestWebappEndpoint(router: Router, context: IRequiredContext, opts?: ICreateAuthRequestWebappEndpointOpts) {
11
- if (opts?.enabled === false) {
12
- console.log(`createAuthRequest Webapp endpoint is disabled`)
13
- return
14
- }
15
- const path = opts?.path ?? '/webapp/definitions/:definitionId/auth-requests'
16
- router.post(path, checkAuth(opts?.endpoint), async (request: Request, response: Response) => {
17
- try {
18
- // if (!request.agent) throw Error('No agent configured')
19
- const definitionId = request.params.definitionId
20
- if (!definitionId) {
21
- return sendErrorResponse(response, 400, 'No definitionId query parameter provided')
22
- }
23
- const state: string = request.body.state ?? uuid.uuid()
24
- const correlationId = request.body.correlationId ?? state
25
- const qrCodeOpts = request.body.qrCodeOpts ?? opts?.qrCodeOpts
26
-
27
- const requestByReferenceURI = uriWithBase(`/siop/definitions/${definitionId}/auth-requests/${state}`, {
28
- baseURI: opts?.siopBaseURI,
29
- })
30
- const responseURI = uriWithBase(`/siop/definitions/${definitionId}/auth-responses/${state}`, { baseURI: opts?.siopBaseURI })
31
- // first version is for backwards compat
32
- const responseRedirectURI =
33
- ('response_redirect_uri' in request.body && (request.body.response_redirect_uri as string | undefined)) ??
34
- ('responseRedirectURI' in request.body && (request.body.responseRedirectURI as string | undefined))
35
-
36
- const authRequestURI = await context.agent.siopCreateAuthRequestURI({
37
- definitionId,
38
- correlationId,
39
- state,
40
- nonce: uuid.uuid(),
41
- requestByReferenceURI,
42
- responseURIType: 'response_uri',
43
- responseURI,
44
- ...(responseRedirectURI && { responseRedirectURI }),
45
- })
46
-
47
- let qrCodeDataUri: string | undefined
48
- if (qrCodeOpts) {
49
- const { AwesomeQR } = await import('awesome-qr')
50
- const qrCode = new AwesomeQR({ ...qrCodeOpts, text: authRequestURI })
51
- qrCodeDataUri = `data:image/png;base64,${(await qrCode.draw())!.toString('base64')}`
52
- }
53
- const authRequestBody: GenerateAuthRequestURIResponse = {
54
- correlationId,
55
- state,
56
- definitionId,
57
- authRequestURI,
58
- authStatusURI: `${uriWithBase(opts?.webappAuthStatusPath ?? '/webapp/auth-status', { baseURI: opts?.webappBaseURI })}`,
59
- ...(qrCodeDataUri && { qrCodeDataUri }),
60
- }
61
- console.log(`Auth Request URI data to send back: ${JSON.stringify(authRequestBody)}`)
62
- return response.json(authRequestBody)
63
- } catch (error) {
64
- return sendErrorResponse(response, 500, 'Could not create an authorization request URI', error)
65
- }
66
- })
67
- }
68
-
69
- export function authStatusWebappEndpoint(router: Router, context: IRequiredContext, opts?: ISingleEndpointOpts) {
70
- if (opts?.enabled === false) {
71
- console.log(`authStatus Webapp endpoint is disabled`)
72
- return
73
- }
74
- const path = opts?.path ?? '/webapp/auth-status'
75
- router.post(path, checkAuth(opts?.endpoint), async (request: Request, response: Response) => {
76
- try {
77
- console.log('Received auth-status request...')
78
- const correlationId: string = request.body.correlationId as string
79
- const definitionId: string = request.body.definitionId as string
80
-
81
- const requestState =
82
- correlationId && definitionId
83
- ? await context.agent.siopGetAuthRequestState({
84
- correlationId,
85
- definitionId,
86
- errorOnNotFound: false,
87
- })
88
- : undefined
89
- if (!requestState || !definitionId || !correlationId) {
90
- console.log(
91
- `No authentication request mapping could be found for the given URL. correlation: ${correlationId}, definitionId: ${definitionId}`,
92
- )
93
- response.statusCode = 404
94
- const statusBody: AuthStatusResponse = {
95
- status: requestState ? requestState.status : 'error',
96
- error: 'No authentication request mapping could be found for the given URL.',
97
- correlationId,
98
- definitionId,
99
- lastUpdated: requestState ? requestState.lastUpdated : Date.now(),
100
- }
101
- return response.json(statusBody)
102
- }
103
-
104
- let includeVerifiedData: VerifiedDataMode = VerifiedDataMode.NONE
105
- if ('includeVerifiedData' in request.body) {
106
- includeVerifiedData = request.body.includeVerifiedData as VerifiedDataMode
107
- }
108
-
109
- let responseState
110
- if (requestState.status === 'sent') {
111
- responseState = (await context.agent.siopGetAuthResponseState({
112
- correlationId,
113
- definitionId,
114
- includeVerifiedData: includeVerifiedData,
115
- errorOnNotFound: false,
116
- })) as AuthorizationResponseStateWithVerifiedData
117
- }
118
- const overallState: AuthorizationRequestState | AuthorizationResponseStateWithVerifiedData = responseState ?? requestState
119
-
120
- const statusBody: AuthStatusResponse = {
121
- status: overallState.status,
122
- ...(overallState.error ? { error: overallState.error?.message } : {}),
123
- correlationId,
124
- definitionId,
125
- lastUpdated: overallState.lastUpdated,
126
- ...(responseState && responseState.status === AuthorizationResponseStateStatus.VERIFIED
127
- ? {
128
- payload: await responseState.response.mergedPayloads({ hasher: defaultHasher }),
129
- verifiedData: responseState.verifiedData,
130
- }
131
- : {}),
132
- }
133
- console.debug(`Will send auth status: ${JSON.stringify(statusBody)}`)
134
- if (overallState.status === 'error') {
135
- response.statusCode = 500
136
- return response.json(statusBody)
137
- }
138
- response.statusCode = 200
139
- return response.json(statusBody)
140
- } catch (error) {
141
- return sendErrorResponse(response, 500, error.message, error)
142
- }
143
- })
144
- }
145
-
146
- export function removeAuthRequestStateWebappEndpoint(router: Router, context: IRequiredContext, opts?: ISingleEndpointOpts) {
147
- if (opts?.enabled === false) {
148
- console.log(`removeAuthStatus Webapp endpoint is disabled`)
149
- return
150
- }
151
- const path = opts?.path ?? '/webapp/definitions/:definitionId/auth-requests/:correlationId'
152
- router.delete(path, checkAuth(opts?.endpoint), async (request: Request, response: Response) => {
153
- try {
154
- const correlationId: string = request.params.correlationId
155
- const definitionId: string = request.params.definitionId
156
- if (!correlationId || !definitionId) {
157
- console.log(`No authorization request could be found for the given url. correlationId: ${correlationId}, definitionId: ${definitionId}`)
158
- return sendErrorResponse(response, 404, 'No authorization request could be found')
159
- }
160
- response.statusCode = 200
161
- return response.json(await context.agent.siopDeleteAuthState({ definitionId, correlationId }))
162
- } catch (error) {
163
- return sendErrorResponse(response, 500, error.message, error)
164
- }
165
- })
166
- }
167
-
168
- export function getDefinitionsEndpoint(router: Router, context: IRequiredContext, opts?: ISingleEndpointOpts) {
169
- if (opts?.enabled === false) {
170
- console.log(`getDefinitions Webapp endpoint is disabled`)
171
- return
172
- }
173
- const path = opts?.path ?? '/webapp/definitions'
174
- router.get(path, checkAuth(opts?.endpoint), async (request: Request, response: Response) => {
175
- try {
176
- const definitions = await context.agent.pdmGetDefinitions()
177
- response.statusCode = 200
178
- return response.json(definitions)
179
- } catch (error) {
180
- return sendErrorResponse(response, 500, error.message, error)
181
- }
182
- })
183
- }