@openeudi/core 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,190 @@
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, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to the Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by the Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding any notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ Copyright 2026 OpenEUDI Contributors
179
+
180
+ Licensed under the Apache License, Version 2.0 (the "License");
181
+ you may not use this file except in compliance with the License.
182
+ You may obtain a copy of the License at
183
+
184
+ http://www.apache.org/licenses/LICENSE-2.0
185
+
186
+ Unless required by applicable law or agreed to in writing, software
187
+ distributed under the License is distributed on an "AS IS" BASIS,
188
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
189
+ See the License for the specific language governing permissions and
190
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,198 @@
1
+ # @openeudi/core
2
+
3
+ Framework-agnostic EUDI Wallet verification protocol engine.
4
+
5
+ ```bash
6
+ npm install @openeudi/core
7
+ ```
8
+
9
+ ## Quick Start
10
+
11
+ ```ts
12
+ import { VerificationService, DemoMode, VerificationType } from "@openeudi/core";
13
+
14
+ const service = new VerificationService({ mode: new DemoMode() });
15
+
16
+ service.on("session:verified", (session, result) => {
17
+ console.log(`Verified: ${result.country}, age: ${result.ageVerified}`);
18
+ });
19
+
20
+ const session = await service.createSession({ type: VerificationType.BOTH });
21
+ console.log(session.walletUrl); // openid4vp://verify?session=<uuid>
22
+ ```
23
+
24
+ ## Modes
25
+
26
+ ### DemoMode
27
+
28
+ Auto-completes sessions with randomized EU citizen data after a configurable delay. Ideal for product demos and landing pages.
29
+
30
+ ```ts
31
+ import { DemoMode } from "@openeudi/core";
32
+
33
+ const mode = new DemoMode({
34
+ delayMs: 2000, // auto-complete after 2s (default: 3000)
35
+ });
36
+ ```
37
+
38
+ ### MockMode
39
+
40
+ Returns deterministic results for integration testing. Supports global defaults and per-session overrides.
41
+
42
+ ```ts
43
+ import { MockMode } from "@openeudi/core";
44
+
45
+ const mode = new MockMode({
46
+ defaultResult: { verified: true, country: "FR", ageVerified: true },
47
+ delayMs: 100,
48
+ });
49
+
50
+ const service = new VerificationService({ mode });
51
+ const session = await service.createSession({ type: VerificationType.AGE });
52
+
53
+ // Override result for a specific session
54
+ mode.setSessionResult(session.id, {
55
+ verified: false,
56
+ rejectionReason: "underage",
57
+ });
58
+
59
+ // Clean up override
60
+ mode.clearSessionResult(session.id);
61
+ ```
62
+
63
+ ## Custom Mode
64
+
65
+ Implement `IVerificationMode` to connect to a real EUDI Wallet relying party:
66
+
67
+ ```ts
68
+ import type { IVerificationMode, VerificationSession, VerificationResult } from "@openeudi/core";
69
+
70
+ class ProductionMode implements IVerificationMode {
71
+ readonly name = "production";
72
+
73
+ async processCallback(session: VerificationSession, walletResponse: unknown): Promise<VerificationResult> {
74
+ const claims = await verifyVPToken(walletResponse); // your OpenID4VP logic
75
+ return { verified: true, country: claims.country, ageVerified: claims.age >= 18 };
76
+ }
77
+ }
78
+ ```
79
+
80
+ ## Custom Storage
81
+
82
+ The default `InMemorySessionStore` works for single-process deployments. Implement `ISessionStore` for Redis, PostgreSQL, etc:
83
+
84
+ ```ts
85
+ import type { ISessionStore, VerificationSession } from "@openeudi/core";
86
+
87
+ class RedisSessionStore implements ISessionStore {
88
+ constructor(private redis: Redis) {}
89
+
90
+ async get(id: string): Promise<VerificationSession | null> {
91
+ const data = await this.redis.get(`session:${id}`);
92
+ return data ? JSON.parse(data) : null;
93
+ }
94
+ async set(session: VerificationSession): Promise<void> {
95
+ const ttl = Math.max(0, session.expiresAt.getTime() - Date.now());
96
+ await this.redis.set(`session:${session.id}`, JSON.stringify(session), "PX", ttl);
97
+ }
98
+ async delete(id: string): Promise<void> {
99
+ await this.redis.del(`session:${id}`);
100
+ }
101
+ }
102
+
103
+ const service = new VerificationService({
104
+ mode: new DemoMode(),
105
+ store: new RedisSessionStore(new Redis()),
106
+ });
107
+ ```
108
+
109
+ ## Events
110
+
111
+ `VerificationService` extends `EventEmitter`. Subscribe to lifecycle events:
112
+
113
+ | Event | Handler Signature | Description |
114
+ | ------------------ | -------------------------------------------------------------------- | ------------------------------ |
115
+ | `session:created` | `(session: VerificationSession) => void` | Session created, QR code ready |
116
+ | `session:verified` | `(session: VerificationSession, result: VerificationResult) => void` | Verification passed |
117
+ | `session:rejected` | `(session: VerificationSession, reason?: string) => void` | Verification rejected |
118
+ | `session:expired` | `(session: VerificationSession) => void` | Session TTL exceeded |
119
+
120
+ ```ts
121
+ service.on("session:created", (session) => sendSSE(session.id, { walletUrl: session.walletUrl }));
122
+ service.on("session:verified", (session, result) =>
123
+ sendSSE(session.id, { status: "verified", country: result.country })
124
+ );
125
+ service.on("session:rejected", (session, reason) => sendSSE(session.id, { status: "rejected", reason }));
126
+ service.on("session:expired", (session) => sendSSE(session.id, { status: "expired" }));
127
+ ```
128
+
129
+ ## QR Code
130
+
131
+ Optional helper to generate QR code data URIs. Requires the `qrcode` peer dependency:
132
+
133
+ ```bash
134
+ npm install qrcode
135
+ ```
136
+
137
+ ```ts
138
+ import { generateQRCode } from "@openeudi/core/qr";
139
+
140
+ const session = await service.createSession({ type: VerificationType.AGE });
141
+ const dataUri = await generateQRCode(session.walletUrl);
142
+ // => "data:image/png;base64,..."
143
+ ```
144
+
145
+ ## API Reference
146
+
147
+ ### `VerificationService`
148
+
149
+ | Method | Returns | Description |
150
+ | ------------------------------------------- | ------------------------------ | ------------------------------------------------------------------------------ |
151
+ | `constructor(config)` | `VerificationService` | Create service with mode, optional store and TTL |
152
+ | `createSession(input)` | `Promise<VerificationSession>` | Create a new verification session |
153
+ | `getSession(id)` | `Promise<VerificationSession>` | Retrieve session by ID (throws `SessionNotFoundError`) |
154
+ | `handleCallback(sessionId, walletResponse)` | `Promise<VerificationResult>` | Process wallet callback (throws `SessionNotFoundError`, `SessionExpiredError`) |
155
+ | `cleanupExpired()` | `Promise<number>` | Remove expired sessions, returns count cleaned |
156
+
157
+ ### Configuration
158
+
159
+ ```ts
160
+ interface VerificationServiceConfig {
161
+ mode: IVerificationMode; // Required — DemoMode, MockMode, or custom
162
+ store?: ISessionStore; // Default: InMemorySessionStore
163
+ sessionTtlMs?: number; // Default: 300_000 (5 minutes)
164
+ walletBaseUrl?: string; // Default: 'openid4vp://verify'
165
+ }
166
+ ```
167
+
168
+ ## Types
169
+
170
+ All types are exported from the main entry point:
171
+
172
+ ```ts
173
+ import type {
174
+ VerificationSession, // Full session object
175
+ VerificationResult, // Outcome of a verification
176
+ CreateSessionInput, // Input for createSession()
177
+ VerificationServiceConfig, // Constructor config
178
+ IVerificationMode, // Strategy interface for modes
179
+ ISessionStore, // Storage adapter interface
180
+ DemoModeConfig, // DemoMode constructor options
181
+ MockModeConfig, // MockMode constructor options
182
+ } from "@openeudi/core";
183
+
184
+ import {
185
+ VerificationType, // AGE | COUNTRY | BOTH
186
+ VerificationStatus, // PENDING | SCANNED | VERIFIED | REJECTED | EXPIRED
187
+ SessionNotFoundError, // Thrown by getSession / handleCallback
188
+ SessionExpiredError, // Thrown by handleCallback
189
+ } from "@openeudi/core";
190
+ ```
191
+
192
+ ## License
193
+
194
+ [Apache 2.0](./LICENSE)
195
+
196
+ ## Related
197
+
198
+ [eIDAS Pro](https://eidas-pro.eu) -- managed verification service with WooCommerce/Shopify plugins, admin dashboard, and compliance tools built on `@openeudi/core`.
package/dist/index.cjs ADDED
@@ -0,0 +1,278 @@
1
+ 'use strict';
2
+
3
+ var events = require('events');
4
+ var uuid = require('uuid');
5
+
6
+ // src/types/verification.ts
7
+ var VerificationType = /* @__PURE__ */ ((VerificationType2) => {
8
+ VerificationType2["AGE"] = "AGE";
9
+ VerificationType2["COUNTRY"] = "COUNTRY";
10
+ VerificationType2["BOTH"] = "BOTH";
11
+ return VerificationType2;
12
+ })(VerificationType || {});
13
+ var VerificationStatus = /* @__PURE__ */ ((VerificationStatus2) => {
14
+ VerificationStatus2["PENDING"] = "PENDING";
15
+ VerificationStatus2["SCANNED"] = "SCANNED";
16
+ VerificationStatus2["VERIFIED"] = "VERIFIED";
17
+ VerificationStatus2["REJECTED"] = "REJECTED";
18
+ VerificationStatus2["EXPIRED"] = "EXPIRED";
19
+ return VerificationStatus2;
20
+ })(VerificationStatus || {});
21
+
22
+ // src/errors.ts
23
+ var SessionNotFoundError = class extends Error {
24
+ constructor(sessionId) {
25
+ super(`Session not found: ${sessionId}`);
26
+ this.name = "SessionNotFoundError";
27
+ Object.setPrototypeOf(this, new.target.prototype);
28
+ }
29
+ };
30
+ var SessionExpiredError = class extends Error {
31
+ constructor(sessionId) {
32
+ super(`Session expired: ${sessionId}`);
33
+ this.name = "SessionExpiredError";
34
+ Object.setPrototypeOf(this, new.target.prototype);
35
+ }
36
+ };
37
+
38
+ // src/storage/memory.store.ts
39
+ var InMemorySessionStore = class {
40
+ sessions = /* @__PURE__ */ new Map();
41
+ async get(id) {
42
+ return this.sessions.get(id) ?? null;
43
+ }
44
+ async set(session) {
45
+ this.sessions.set(session.id, session);
46
+ }
47
+ async delete(id) {
48
+ this.sessions.delete(id);
49
+ }
50
+ };
51
+
52
+ // src/modes/demo.mode.ts
53
+ var EU_COUNTRIES = [
54
+ "AT",
55
+ "BE",
56
+ "BG",
57
+ "HR",
58
+ "CY",
59
+ "CZ",
60
+ "DK",
61
+ "EE",
62
+ "FI",
63
+ "FR",
64
+ "DE",
65
+ "GR",
66
+ "HU",
67
+ "IE",
68
+ "IT",
69
+ "LV",
70
+ "LT",
71
+ "LU",
72
+ "MT",
73
+ "NL",
74
+ "PL",
75
+ "PT",
76
+ "RO",
77
+ "SK",
78
+ "SI",
79
+ "ES",
80
+ "SE"
81
+ ];
82
+ var DemoMode = class {
83
+ name = "demo";
84
+ delayMs;
85
+ constructor(config = {}) {
86
+ this.delayMs = config.delayMs ?? 3e3;
87
+ }
88
+ async processCallback(session, _walletResponse) {
89
+ const country = this.pickCountry(session.countryWhitelist);
90
+ return this.buildResult(session.type, country);
91
+ }
92
+ async simulateCompletion(session) {
93
+ await new Promise((resolve) => setTimeout(resolve, this.delayMs));
94
+ return this.processCallback(session, {});
95
+ }
96
+ pickCountry(whitelist) {
97
+ const pool = whitelist && whitelist.length > 0 ? whitelist : EU_COUNTRIES;
98
+ return pool[Math.floor(Math.random() * pool.length)];
99
+ }
100
+ buildResult(type, country) {
101
+ const includeAge = type === "AGE" /* AGE */ || type === "BOTH" /* BOTH */;
102
+ const includeCountry = type === "COUNTRY" /* COUNTRY */ || type === "BOTH" /* BOTH */;
103
+ return {
104
+ verified: true,
105
+ country,
106
+ ageVerified: includeAge ? true : void 0,
107
+ countryVerified: includeCountry ? true : void 0
108
+ };
109
+ }
110
+ };
111
+
112
+ // src/modes/mock.mode.ts
113
+ var DEFAULT_RESULT = {
114
+ verified: true,
115
+ country: "DE",
116
+ ageVerified: true,
117
+ countryVerified: true
118
+ };
119
+ var MockMode = class {
120
+ name = "mock";
121
+ defaultResult;
122
+ delayMs;
123
+ sessionOverrides = /* @__PURE__ */ new Map();
124
+ constructor(config = {}) {
125
+ this.defaultResult = config.defaultResult ?? { ...DEFAULT_RESULT };
126
+ this.delayMs = config.delayMs ?? 0;
127
+ }
128
+ /** Set a per-session result override */
129
+ setSessionResult(sessionId, result) {
130
+ this.sessionOverrides.set(sessionId, result);
131
+ }
132
+ /** Clear a per-session result override */
133
+ clearSessionResult(sessionId) {
134
+ this.sessionOverrides.delete(sessionId);
135
+ }
136
+ async processCallback(session, _walletResponse) {
137
+ if (this.delayMs > 0) {
138
+ await new Promise((resolve) => setTimeout(resolve, this.delayMs));
139
+ }
140
+ return this.sessionOverrides.get(session.id) ?? { ...this.defaultResult };
141
+ }
142
+ async simulateCompletion(session) {
143
+ return this.processCallback(session, {});
144
+ }
145
+ };
146
+ var DEFAULT_TTL_MS = 3e5;
147
+ var DEFAULT_WALLET_BASE_URL = "openid4vp://verify";
148
+ var VerificationService = class extends events.EventEmitter {
149
+ store;
150
+ mode;
151
+ sessionTtlMs;
152
+ walletBaseUrl;
153
+ /** Track session IDs for cleanup (store interface has no list method) */
154
+ sessionIds = /* @__PURE__ */ new Set();
155
+ constructor(config) {
156
+ super();
157
+ this.mode = config.mode;
158
+ this.store = config.store ?? new InMemorySessionStore();
159
+ this.sessionTtlMs = config.sessionTtlMs ?? DEFAULT_TTL_MS;
160
+ this.walletBaseUrl = config.walletBaseUrl ?? DEFAULT_WALLET_BASE_URL;
161
+ }
162
+ /**
163
+ * Create a new verification session
164
+ */
165
+ async createSession(input) {
166
+ const id = uuid.v4();
167
+ const now = /* @__PURE__ */ new Date();
168
+ const session = {
169
+ id,
170
+ type: input.type,
171
+ status: "PENDING" /* PENDING */,
172
+ walletUrl: "",
173
+ // set below, may be async from mode
174
+ countryWhitelist: input.countryWhitelist,
175
+ countryBlacklist: input.countryBlacklist,
176
+ redirectUrl: input.redirectUrl,
177
+ metadata: input.metadata,
178
+ createdAt: now,
179
+ expiresAt: new Date(now.getTime() + this.sessionTtlMs)
180
+ };
181
+ session.walletUrl = this.mode.buildWalletUrl ? await this.mode.buildWalletUrl(id, input) : `${this.walletBaseUrl}?session=${id}`;
182
+ await this.store.set(session);
183
+ this.sessionIds.add(id);
184
+ this.emit("session:created", session);
185
+ if (this.mode.simulateCompletion) {
186
+ this.mode.simulateCompletion(session).then(async (result) => {
187
+ const current = await this.store.get(id);
188
+ if (current && current.status === "PENDING" /* PENDING */) {
189
+ await this.completeSession(current, result);
190
+ }
191
+ }).catch(() => {
192
+ });
193
+ }
194
+ return session;
195
+ }
196
+ /**
197
+ * Get a session by ID
198
+ * @throws SessionNotFoundError
199
+ */
200
+ async getSession(id) {
201
+ const session = await this.store.get(id);
202
+ if (!session) {
203
+ throw new SessionNotFoundError(id);
204
+ }
205
+ return session;
206
+ }
207
+ /**
208
+ * Handle a callback from the wallet
209
+ * @throws SessionNotFoundError
210
+ * @throws SessionExpiredError
211
+ */
212
+ async handleCallback(sessionId, walletResponse) {
213
+ const session = await this.store.get(sessionId);
214
+ if (!session) {
215
+ throw new SessionNotFoundError(sessionId);
216
+ }
217
+ if (/* @__PURE__ */ new Date() > session.expiresAt) {
218
+ throw new SessionExpiredError(sessionId);
219
+ }
220
+ const result = await this.mode.processCallback(session, walletResponse);
221
+ await this.completeSession(session, result);
222
+ return result;
223
+ }
224
+ /**
225
+ * Remove expired sessions from the store
226
+ * @returns Number of sessions cleaned up
227
+ */
228
+ async cleanupExpired() {
229
+ const now = /* @__PURE__ */ new Date();
230
+ let count = 0;
231
+ for (const id of this.sessionIds) {
232
+ const session = await this.store.get(id);
233
+ if (!session) {
234
+ this.sessionIds.delete(id);
235
+ continue;
236
+ }
237
+ if (now > session.expiresAt && session.status === "PENDING" /* PENDING */) {
238
+ const expired = { ...session, status: "EXPIRED" /* EXPIRED */ };
239
+ await this.store.set(expired);
240
+ await this.store.delete(id);
241
+ this.sessionIds.delete(id);
242
+ this.emit("session:expired", expired);
243
+ count++;
244
+ }
245
+ }
246
+ return count;
247
+ }
248
+ async completeSession(session, result) {
249
+ const status = result.verified ? "VERIFIED" /* VERIFIED */ : "REJECTED" /* REJECTED */;
250
+ const updated = {
251
+ ...session,
252
+ status,
253
+ completedAt: /* @__PURE__ */ new Date(),
254
+ result
255
+ };
256
+ await this.store.set(updated);
257
+ if (result.verified) {
258
+ this.emit("session:verified", updated, result);
259
+ } else {
260
+ this.emit("session:rejected", updated, result.rejectionReason);
261
+ }
262
+ }
263
+ };
264
+
265
+ // src/index.ts
266
+ var VERSION = "0.1.0";
267
+
268
+ exports.DemoMode = DemoMode;
269
+ exports.InMemorySessionStore = InMemorySessionStore;
270
+ exports.MockMode = MockMode;
271
+ exports.SessionExpiredError = SessionExpiredError;
272
+ exports.SessionNotFoundError = SessionNotFoundError;
273
+ exports.VERSION = VERSION;
274
+ exports.VerificationService = VerificationService;
275
+ exports.VerificationStatus = VerificationStatus;
276
+ exports.VerificationType = VerificationType;
277
+ //# sourceMappingURL=index.cjs.map
278
+ //# sourceMappingURL=index.cjs.map