@eudi-verify/server 0.1.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/LICENSE ADDED
@@ -0,0 +1,184 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship made available under
36
+ the License, as indicated by a copyright notice that is included in
37
+ or attached to the work (an example is provided in the Appendix below).
38
+
39
+ "Derivative Works" shall mean any work, whether in Source or Object
40
+ form, that is based on (or derived from) the Work and for which the
41
+ editorial revisions, annotations, elaborations, or other modifications
42
+ represent, as a whole, an original work of authorship. For the purposes
43
+ of this License, Derivative Works shall not include works that remain
44
+ separable from, or merely link (or bind by name) to the interfaces of,
45
+ the Work and Derivative Works thereof.
46
+
47
+ "Contribution" shall mean, as submitted to the Licensor for inclusion
48
+ in the Work by the copyright owner or by an individual or Legal Entity
49
+ authorized to submit on behalf of the copyright owner. For the purposes
50
+ of this definition, "submitted" means any form of electronic, verbal,
51
+ or written communication sent to the Licensor or its representatives,
52
+ including but not limited to communication on electronic mailing lists,
53
+ source code control systems, and issue tracking systems that are managed
54
+ by, or on behalf of, the Licensor for the purpose of recording and
55
+ tracking Contributions to the Work, but excluding communication that is
56
+ conspicuously marked or designated in writing by the copyright owner as
57
+ "Not a Contribution."
58
+
59
+ "Contributor" shall mean Licensor and any Legal Entity on behalf of
60
+ whom a Contribution has been received by the Licensor and included
61
+ within the Work.
62
+
63
+ 2. Grant of Copyright License. Subject to the terms and conditions of
64
+ this License, each Contributor hereby grants to You a perpetual,
65
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
66
+ copyright license to reproduce, prepare Derivative Works of,
67
+ publicly display, publicly perform, sublicense, and distribute the
68
+ Work and such Derivative Works in Source or Object form.
69
+
70
+ 3. Grant of Patent License. Subject to the terms and conditions of
71
+ this License, each Contributor hereby grants to You a perpetual,
72
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
73
+ (except as stated in this section) patent license to make, have made,
74
+ use, offer to sell, sell, import, and otherwise transfer the Work,
75
+ where such license applies only to those patent claims licensable
76
+ by such Contributor that are necessarily infringed by their
77
+ Contribution(s) alone or by the combination of their Contribution(s)
78
+ with the Work to which such Contribution(s) was submitted. If You
79
+ institute patent litigation against any entity (including a cross-claim
80
+ or counterclaim in a lawsuit) alleging that the Work or any such
81
+ Contribution as incorporated in the Work constitutes direct or
82
+ contributory patent infringement, then any patent licenses granted to
83
+ You under this License for that Work shall terminate as of the date
84
+ such litigation is filed.
85
+
86
+ 4. Redistribution. You may reproduce and distribute copies of the
87
+ Work or Derivative Works thereof in any medium, with or without
88
+ modifications, and in Source or Object form, provided that You
89
+ meet the following conditions:
90
+
91
+ (a) You must give any other recipients of the Work or Derivative
92
+ Works a copy of this License; and
93
+
94
+ (b) You must cause any modified files to carry prominent notices
95
+ stating that You changed the files; and
96
+
97
+ (c) You must retain, in the Source form of any Derivative Works
98
+ that You distribute, all copyright, patent, trademark, and
99
+ attribution notices from the Source form of the Work,
100
+ excluding those notices that do not pertain to any part of
101
+ the Derivative Works; and
102
+
103
+ (d) If the Work includes a "NOTICE" text file as part of its
104
+ distribution, You must include a readable copy of the
105
+ attribution notices contained within such NOTICE file, in
106
+ at least one of the following places: within a NOTICE text
107
+ file distributed as part of the Derivative Works; within
108
+ the Source form or documentation, if provided along with the
109
+ Derivative Works; or, within a display generated by the
110
+ Derivative Works, if and wherever such third-party notices
111
+ normally appear. The contents of the NOTICE file are for
112
+ informational purposes only and do not modify the License.
113
+ You may add Your own attribution notices within Derivative
114
+ Works that You distribute, alongside or in addition to the
115
+ NOTICE text from the Work, provided that such additional
116
+ attribution notices cannot be construed as modifying the
117
+ License.
118
+
119
+ You may add Your own license statement for Your modifications and
120
+ may provide additional grant of rights to use, copy, modify, merge,
121
+ publish, distribute, sublicense, and/or sell copies of the
122
+ Contribution, either on its own or as part of the Work.
123
+
124
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
125
+ any Contribution intentionally submitted for inclusion in the Work
126
+ by You to the Licensor shall be under the terms and conditions of
127
+ this License, without any additional terms or conditions.
128
+ Notwithstanding the above, nothing herein shall supersede or modify
129
+ the terms of any separate license agreement you may have executed
130
+ with Licensor regarding such Contributions.
131
+
132
+ 6. Trademarks. This License does not grant permission to use the trade
133
+ names, trademarks, service marks, or product names of the Licensor,
134
+ except as required for reasonable and customary use in describing the
135
+ origin of the Work and reproducing the content of the NOTICE file.
136
+
137
+ 7. Disclaimer of Warranty. Unless required by applicable law or
138
+ agreed to in writing, Licensor provides the Work (and each
139
+ Contributor provides its Contributions) on an "AS IS" BASIS,
140
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
141
+ implied, including, without limitation, any conditions of TITLE,
142
+ NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR
143
+ PURPOSE. You are solely responsible for determining the
144
+ appropriateness of using or reproducing the Work and assume any
145
+ risks associated with Your exercise of permissions under this License.
146
+
147
+ 8. Limitation of Liability. In no event and under no legal theory,
148
+ whether in tort (including negligence), contract, or otherwise,
149
+ unless required by applicable law (such as deliberate and grossly
150
+ negligent acts) or agreed to in writing, shall any Contributor be
151
+ liable to You for damages, including any direct, indirect, special,
152
+ incidental, or exemplary damages of any character arising as a
153
+ result of this License or out of the use or inability to use the
154
+ Work (including but not limited to damages for loss of goodwill,
155
+ work stoppage, computer failure or malfunction, or all other
156
+ commercial damages or losses), even if such Contributor has been
157
+ advised of the possibility of such damages.
158
+
159
+ 9. Accepting Warranty or Liability. While redistributing the Work or
160
+ Derivative Works thereof, You may choose to offer, and charge a fee
161
+ for, acceptance of support, warranty, indemnity, or other liability
162
+ obligations and/or rights consistent with this License. However, in
163
+ accepting such obligations, You may offer such obligations only on
164
+ Your own behalf and on Your sole responsibility, not on behalf of
165
+ any other Contributor, and only if You agree to indemnify, defend,
166
+ and hold each Contributor harmless for any liability incurred by, or
167
+ claims asserted against, such Contributor by reason of your accepting
168
+ any such warranty or additional liability.
169
+
170
+ END OF TERMS AND CONDITIONS
171
+
172
+ Copyright 2024 EUDI Wallet Verifier Kit Contributors
173
+
174
+ Licensed under the Apache License, Version 2.0 (the "License");
175
+ you may not use this file except in compliance with the License.
176
+ You may obtain a copy of the License at
177
+
178
+ http://www.apache.org/licenses/LICENSE-2.0
179
+
180
+ Unless required by applicable law or agreed to in writing, software
181
+ distributed under the License is distributed on an "AS IS" BASIS,
182
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
183
+ See the License for the specific language governing permissions and
184
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,258 @@
1
+ # @eudi-verify/server
2
+
3
+ Framework-agnostic EUDI Wallet verifier API handlers.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ pnpm add @eudi-verify/server
9
+ ```
10
+
11
+ ## Quick Start
12
+
13
+ ```ts
14
+ import {
15
+ createVerifierHandlers,
16
+ OpenEudiEngine,
17
+ MemoryKVStore,
18
+ } from '@eudi-verify/server';
19
+
20
+ // 1. Create engine and store
21
+ const BASE_URL = process.env.BASE_URL || 'http://localhost:3000/api/eudi';
22
+ const engine = new OpenEudiEngine({ mode: 'demo', baseUrl: BASE_URL });
23
+ const store = new MemoryKVStore();
24
+
25
+ // 2. Create handlers
26
+ const handlers = createVerifierHandlers({
27
+ engine,
28
+ store,
29
+ baseUrl: BASE_URL,
30
+ mode: 'demo',
31
+ tokenSecret: process.env.TOKEN_SECRET!, // 32+ chars
32
+ });
33
+
34
+ // 3. Mount on your framework
35
+ // See framework examples below
36
+ ```
37
+
38
+ ## Framework Integration
39
+
40
+ ### Node.js HTTP
41
+
42
+ ```ts
43
+ import http from 'node:http';
44
+
45
+ function buildContext(req, params = {}, body = undefined) {
46
+ return {
47
+ ip: req.socket.remoteAddress ?? '127.0.0.1',
48
+ origin: req.headers.origin,
49
+ params,
50
+ body,
51
+ };
52
+ }
53
+
54
+ const server = http.createServer(async (req, res) => {
55
+ const url = new URL(req.url!, `http://${req.headers.host}`);
56
+
57
+ // Route to handlers
58
+ if (url.pathname === '/sessions' && req.method === 'POST') {
59
+ const body = await readBody(req);
60
+ const result = await handlers.createSession(buildContext(req, {}, JSON.parse(body)));
61
+ sendJson(res, result.status, result.body, result.headers);
62
+ }
63
+ // ... other routes
64
+ });
65
+ ```
66
+
67
+ ### Express
68
+
69
+ ```ts
70
+ import express from 'express';
71
+
72
+ const app = express();
73
+ app.use(express.json());
74
+
75
+ function buildContext(req, params = {}, body = undefined) {
76
+ return {
77
+ ip: req.ip ?? '127.0.0.1',
78
+ origin: req.headers.origin,
79
+ params,
80
+ body,
81
+ };
82
+ }
83
+
84
+ app.post('/sessions', async (req, res) => {
85
+ const result = await handlers.createSession(buildContext(req, {}, req.body));
86
+ res.status(result.status).set(result.headers).json(result.body);
87
+ });
88
+
89
+ app.get('/sessions/:id', async (req, res) => {
90
+ const result = await handlers.getSession(buildContext(req, { sessionId: req.params.id }));
91
+ res.status(result.status).set(result.headers).json(result.body);
92
+ });
93
+
94
+ app.post('/sessions/:id/cancel', async (req, res) => {
95
+ const result = await handlers.cancelSession(buildContext(req, { sessionId: req.params.id }));
96
+ res.status(result.status).set(result.headers).json(result.body);
97
+ });
98
+
99
+ app.post('/tokens/verify', async (req, res) => {
100
+ const result = await handlers.verifyToken(buildContext(req, {}, req.body));
101
+ res.status(result.status).json(result.body);
102
+ });
103
+ ```
104
+
105
+ ### Hono
106
+
107
+ ```ts
108
+ import { Hono } from 'hono';
109
+
110
+ const app = new Hono();
111
+
112
+ function buildContext(c, params = {}, body = undefined) {
113
+ return {
114
+ ip: c.req.header('x-forwarded-for') ?? '127.0.0.1',
115
+ origin: c.req.header('origin'),
116
+ params,
117
+ body,
118
+ };
119
+ }
120
+
121
+ app.post('/sessions', async (c) => {
122
+ const result = await handlers.createSession(buildContext(c, {}, await c.req.json()));
123
+ return c.json(result.body, result.status, result.headers);
124
+ });
125
+
126
+ // ... other routes
127
+ ```
128
+
129
+ ## Configuration
130
+
131
+ ```ts
132
+ interface VerifierConfig {
133
+ engine: VerifierEngine; // OpenEudiEngine or MockEngine
134
+ store: IKVStore; // MemoryKVStore (or Redis for production)
135
+ baseUrl: string; // Public callback URL (e.g., https://example.com/api/eudi)
136
+ mode: 'demo' | 'production';
137
+ tokenSecret: string; // HMAC secret, 32+ characters
138
+ tokenTtlMs?: number; // Default: 300000 (5 min)
139
+ sessionTtlMs?: number; // Default: 300000 (5 min)
140
+ rateLimit?: {
141
+ maxRequests: number; // Default: 10
142
+ windowMs: number; // Default: 60000 (1 min)
143
+ };
144
+ allowedOrigins?: string[]; // CORS/Origin check (empty = allow all)
145
+ }
146
+ ```
147
+
148
+ ## Handlers
149
+
150
+ | Handler | Route | Description |
151
+ |---------|-------|-------------|
152
+ | `createSession(body, ctx)` | `POST /sessions` | Create verification session |
153
+ | `getSession(id)` | `GET /sessions/:id` | Get session status |
154
+ | `cancelSession(id)` | `POST /sessions/:id/cancel` | Cancel active session |
155
+ | `verifyToken(body)` | `POST /tokens/verify` | Validate verification token |
156
+ | `handleCallback(data)` | `POST /callback` | Wallet callback (internal) |
157
+
158
+ ## Error Boundaries
159
+
160
+ Handlers return `{ status, headers?, body }` — they **never throw**. Your framework route is the integration boundary.
161
+
162
+ ### Three error shapes
163
+
164
+ **1. HTTP errors** — returned as `{ error, message, details? }` with 4xx/5xx status:
165
+
166
+ | Status | `error` code | Typical cause |
167
+ |--------|--------------|---------------|
168
+ | 400 | `bad_request` | Invalid input |
169
+ | 403 | `forbidden` | Origin not in `allowedOrigins` |
170
+ | 404 | `not_found` | Session missing |
171
+ | 409 | `conflict` | Cancel on terminal session |
172
+ | 429 | `rate_limited` | Rate limit exceeded |
173
+ | 500 | `internal_error` | Engine failure on create |
174
+
175
+ **2. Session outcomes** — HTTP 200, check `body.status`:
176
+
177
+ | `status` | Meaning |
178
+ |----------|---------|
179
+ | `rejected` | User declined in wallet |
180
+ | `expired` | Session TTL elapsed |
181
+ | `error` | VP validation or engine failure |
182
+
183
+ These surface to your frontend via `GET /sessions/:id` polling, not via callback HTTP status.
184
+
185
+ **3. Token soft failures** — `verifyToken` returns HTTP 200 with `{ valid: false, error: 'invalid_token' | 'expired' | 'already_consumed' | ... }`.
186
+
187
+ ### Wallet callback (`POST /callback`)
188
+
189
+ Called by the wallet during OpenID4VP — **not by your application code**.
190
+
191
+ - **400** — callback could not be processed (missing body, parse error, unknown session).
192
+ - **200** `{ status: 'ok' }` — callback received; verification outcome is stored on the session.
193
+
194
+ A verification failure (bad VP, crypto error) still returns **200** to the wallet. The session moves to `status: 'error'` or `'rejected'`. Your page discovers this when polling `getSession`.
195
+
196
+ To report callback-path failures server-side, inspect the session after handling the callback (or rely on frontend polling to surface `error` state).
197
+
198
+ ### Route adapter pattern
199
+
200
+ ```ts
201
+ app.post('/sessions', async (req, res) => {
202
+ const result = await handlers.createSession(buildContext(req, {}, req.body));
203
+
204
+ if (result.status >= 400 && 'error' in result.body) {
205
+ // Your error reporting hook
206
+ reportError({ handler: 'createSession', ...result.body });
207
+ }
208
+
209
+ res.status(result.status).set(result.headers).json(result.body);
210
+ });
211
+ ```
212
+
213
+ Internal failures are logged to `console.error` with a `[eudi-verify]` prefix. There is no built-in logger injection — wrap handler calls for structured reporting.
214
+
215
+ ## Token Verification
216
+
217
+ **Important:** There are two different tokens in the flow:
218
+
219
+ 1. **VP Token** (Verifiable Presentation) — Comes from the EUDI Wallet, verified by the engine using cryptographic signatures and trust lists
220
+ 2. **Verification Token** — Minted by your server after VP verification succeeds, HMAC-signed with `TOKEN_SECRET`, returned to client as proof of successful verification
221
+
222
+ The `tokenSecret` config parameter is for signing the **Verification Token** only.
223
+
224
+ After the widget emits a `verified` event with a token, validate it server-side:
225
+
226
+ ```ts
227
+ // In your protected endpoint
228
+ app.post('/checkout', async (req, res) => {
229
+ const { eudiToken } = req.body;
230
+
231
+ const result = await handlers.verifyToken({ token: eudiToken });
232
+
233
+ if (result.body.valid) {
234
+ // Token is valid, claims are verified
235
+ const { age_over_18, nationality } = result.body.claims;
236
+ // Proceed with checkout...
237
+ } else {
238
+ // Token invalid, expired, or already used
239
+ res.status(401).json({ error: result.body.error });
240
+ }
241
+ });
242
+ ```
243
+
244
+ ## Demo Mode Warning
245
+
246
+ ⚠️ Demo mode accepts simulated credentials. **Never use in production.**
247
+
248
+ Demo mode is indicated by:
249
+ - Console warning on startup
250
+ - `X-Eudi-Mode: demo` header on all responses
251
+
252
+ ## API Reference
253
+
254
+ See [openapi/eudi-verifier.yaml](../../openapi/eudi-verifier.yaml) for the full OpenAPI 3.1 specification.
255
+
256
+ ## License
257
+
258
+ Apache-2.0