authjs-corepass-provider 0.1.2 → 0.1.3
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/README.md +22 -6
- package/dist/index.d.ts +8 -1
- package/dist/index.js +91 -38
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
# authjs-corepass-provider
|
|
2
2
|
|
|
3
|
-
CorePass provider
|
|
3
|
+
CorePass provider and server helpers for [Auth.js](https://authjs.dev/) (`@auth/core`). This package adds a WebAuthn/Passkey provider (CorePass) and the **pending-by-default** registration flow to your app. You install it in the same project where you use Auth.js and mount the provided handlers on your routes.
|
|
4
|
+
|
|
5
|
+
**Flow in short:**
|
|
4
6
|
|
|
5
7
|
- CorePass first checks **`HEAD /passkey/data`**: **200** = enrichment available (pending mode), **404** = enrichment not available (e.g. `allowImmediateFinalize` enabled).
|
|
6
8
|
- **If enrichment available (200):** browser does WebAuthn attestation via `POST /webauthn/start` and `POST /webauthn/finish` → server stores a **pending registration** → CorePass app finalizes by calling **`POST /passkey/data`** with an **Ed448-signed** payload.
|
|
@@ -78,16 +80,26 @@ sequenceDiagram
|
|
|
78
80
|
Note over Auth: (optional) POST login webhook { coreId, refId? } (loginWebhookRetries, default 3)
|
|
79
81
|
```
|
|
80
82
|
|
|
83
|
+
## Requirements
|
|
84
|
+
|
|
85
|
+
- **Node.js** 18+ (ESM, native `crypto`).
|
|
86
|
+
- **Auth.js**: `@auth/core` (peer dependency). Use a version compatible with the provider (e.g. `^0.34.3`).
|
|
87
|
+
- **SimpleWebAuthn** (server) **v10+** required. The package uses `generateRegistrationOptions` with a `Uint8Array` userID; this is provided by `@auth/core` when it depends on `@simplewebauthn/server` v10+.
|
|
88
|
+
- **Frontend**: `@simplewebauthn/browser` in the app that calls your WebAuthn endpoints (e.g. for `startRegistration` / `finishRegistration`).
|
|
89
|
+
|
|
90
|
+
The package brings in its own runtime dependencies (e.g. `@noble/curves`, `cbor-x`, `blockchain-wallet-validator`) for Ed448 verification and CBOR; you do not install those yourself.
|
|
91
|
+
|
|
81
92
|
## Install
|
|
82
93
|
|
|
83
94
|
```bash
|
|
84
95
|
npm install authjs-corepass-provider
|
|
85
96
|
```
|
|
86
97
|
|
|
87
|
-
|
|
98
|
+
Install peer and frontend deps in your app if not already present:
|
|
88
99
|
|
|
89
|
-
|
|
90
|
-
|
|
100
|
+
```bash
|
|
101
|
+
npm install @auth/core @simplewebauthn/browser
|
|
102
|
+
```
|
|
91
103
|
|
|
92
104
|
## Auth.js configuration
|
|
93
105
|
|
|
@@ -121,13 +133,14 @@ const corepass = createCorePassServer({
|
|
|
121
133
|
// - postgresCorePassStore(pg) for Postgres (node-postgres, etc)
|
|
122
134
|
// - supabaseCorePassStore(supabase) for Supabase client
|
|
123
135
|
store: /* CorePassStore implementation */,
|
|
124
|
-
challengeStore: /* CorePassChallengeStore
|
|
136
|
+
challengeStore: /* CorePassChallengeStore (optional if allowImmediateFinalize: true; then set secret) */,
|
|
125
137
|
rpID: "example.com",
|
|
126
138
|
rpName: "Example",
|
|
127
139
|
expectedOrigin: "https://example.com",
|
|
128
140
|
|
|
129
141
|
// default: pending registrations are required
|
|
130
142
|
allowImmediateFinalize: false,
|
|
143
|
+
// secret: required when allowImmediateFinalize is true and challengeStore is omitted (challenge in signed cookie)
|
|
131
144
|
})
|
|
132
145
|
|
|
133
146
|
// Optional: login webhook (call from Auth.js events.signIn)
|
|
@@ -181,6 +194,8 @@ store uses the same DB client you pass in.
|
|
|
181
194
|
|
|
182
195
|
## `challengeStore` (what it is, and what it supports)
|
|
183
196
|
|
|
197
|
+
When **allowImmediateFinalize** is **true**, `challengeStore` is **optional**: if omitted, the WebAuthn challenge is carried in a **signed cookie** instead (you must set **`secret`** for signing). When **allowImmediateFinalize** is false, `challengeStore` is **required**.
|
|
198
|
+
|
|
184
199
|
`challengeStore` is **not an Auth.js provider** and it is **not tied to WebAuthn/Passkey provider IDs**.
|
|
185
200
|
It’s a minimal storage interface used by this package’s custom endpoints to persist the WebAuthn challenge
|
|
186
201
|
between:
|
|
@@ -387,7 +402,8 @@ This adds:
|
|
|
387
402
|
- **`residentKey`**: `"preferred"` (default), `"required"`, or `"discouraged"`.
|
|
388
403
|
- **`userVerification`**: `"required"` (default), `"preferred"`, or `"discouraged"`.
|
|
389
404
|
- **`registrationTimeout`**: milliseconds; default `60000` (60 seconds).
|
|
390
|
-
- **`allowImmediateFinalize`**: if enabled, `finishRegistration` may finalize immediately if `coreId` is provided in the browser payload. This is **disabled by default** because it weakens the CoreID ownership guarantee (the default flow requires the Ed448-signed `/passkey/data` request). When enabled, `HEAD /passkey/data` (checkEnrichment) returns **404** (enrichment not available).
|
|
405
|
+
- **`allowImmediateFinalize`**: if enabled, `finishRegistration` may finalize immediately if `coreId` is provided in the browser payload. This is **disabled by default** because it weakens the CoreID ownership guarantee (the default flow requires the Ed448-signed `/passkey/data` request). When enabled, `HEAD /passkey/data` (checkEnrichment) returns **404** (enrichment not available). When **true**, **`challengeStore`** may be omitted (see **`secret`**).
|
|
406
|
+
- **`secret`**: required when **`allowImmediateFinalize`** is true and **`challengeStore`** is not provided. Used to sign the cookie that carries the WebAuthn challenge between start and finish (no server-side challenge store needed).
|
|
391
407
|
- **`emailRequired`**: defaults to `false` (email can arrive later via `/passkey/data`). If no email is provided, the user is created with email undefined; when a real email is provided later it is updated.
|
|
392
408
|
- **`requireO18y`**: defaults to `false`. If enabled, `/passkey/data` must include `userData.o18y=true` or finalization is rejected. Not enforced for immediate-finalize.
|
|
393
409
|
- **`requireO21y`**: defaults to `false`. If enabled, `/passkey/data` must include `userData.o21y=true` or finalization is rejected. Not enforced for immediate-finalize.
|
package/dist/index.d.ts
CHANGED
|
@@ -56,8 +56,15 @@ type CreateCorePassServerOptions = {
|
|
|
56
56
|
store: CorePassStore;
|
|
57
57
|
/**
|
|
58
58
|
* Store for short-lived WebAuthn challenges (KV/Redis/DB/etc).
|
|
59
|
+
* Optional when **allowImmediateFinalize** is true: if omitted, the challenge is carried in a
|
|
60
|
+
* signed cookie instead (you must set **secret** for signing).
|
|
59
61
|
*/
|
|
60
|
-
challengeStore
|
|
62
|
+
challengeStore?: CorePassChallengeStore;
|
|
63
|
+
/**
|
|
64
|
+
* Secret for signing the challenge cookie when **allowImmediateFinalize** is true and
|
|
65
|
+
* **challengeStore** is not provided. Required in that case.
|
|
66
|
+
*/
|
|
67
|
+
secret?: string;
|
|
61
68
|
rpID: string;
|
|
62
69
|
rpName: string;
|
|
63
70
|
expectedOrigin: string;
|
package/dist/index.js
CHANGED
|
@@ -403,6 +403,20 @@ function createCorePassServer(options) {
|
|
|
403
403
|
const timestampFutureSkewMs = options.timestampFutureSkewMs ?? 2 * 60 * 1e3;
|
|
404
404
|
const allowedAaguids = options.allowedAaguids ?? COREPASS_DEFAULT_AAGUID;
|
|
405
405
|
const pubKeyCredAlgs = options.pubKeyCredAlgs ?? [-257, -7, -8];
|
|
406
|
+
const allowImmediateFinalize = options.allowImmediateFinalize ?? false;
|
|
407
|
+
const challengeStore = options.challengeStore ?? null;
|
|
408
|
+
const useChallengeCookie = allowImmediateFinalize && !challengeStore;
|
|
409
|
+
if (!challengeStore && !useChallengeCookie) {
|
|
410
|
+
throw new Error(
|
|
411
|
+
"createCorePassServer: challengeStore is required when allowImmediateFinalize is not true"
|
|
412
|
+
);
|
|
413
|
+
}
|
|
414
|
+
if (useChallengeCookie && !options.secret) {
|
|
415
|
+
throw new Error(
|
|
416
|
+
"createCorePassServer: secret is required when allowImmediateFinalize is true and challengeStore is not provided (challenge is stored in a signed cookie)"
|
|
417
|
+
);
|
|
418
|
+
}
|
|
419
|
+
const challengeCookieSecret = useChallengeCookie ? options.secret : "";
|
|
406
420
|
const sw = WebAuthn({}).simpleWebAuthn;
|
|
407
421
|
if (postRegistrationWebhooks && !registrationWebhookUrl) {
|
|
408
422
|
throw new Error(
|
|
@@ -452,6 +466,38 @@ function createCorePassServer(options) {
|
|
|
452
466
|
const sig = await crypto.subtle.sign("HMAC", key, new TextEncoder().encode(message));
|
|
453
467
|
return [...new Uint8Array(sig)].map((b) => b.toString(16).padStart(2, "0")).join("");
|
|
454
468
|
};
|
|
469
|
+
async function signChallengeCookie(payload) {
|
|
470
|
+
const b64 = bytesToBase64Url(new TextEncoder().encode(JSON.stringify(payload)));
|
|
471
|
+
const sig = await hmacSha256Hex(challengeCookieSecret, b64);
|
|
472
|
+
return `${b64}.${sig}`;
|
|
473
|
+
}
|
|
474
|
+
async function verifyChallengeCookie(value) {
|
|
475
|
+
const dot = value.indexOf(".");
|
|
476
|
+
if (dot <= 0) return null;
|
|
477
|
+
const b64 = value.slice(0, dot);
|
|
478
|
+
const sig = value.slice(dot + 1);
|
|
479
|
+
const expectedSig = await hmacSha256Hex(challengeCookieSecret, b64);
|
|
480
|
+
if (sig !== expectedSig) return null;
|
|
481
|
+
try {
|
|
482
|
+
const json2 = new TextDecoder().decode(base64UrlToBytes(b64));
|
|
483
|
+
const payload = JSON.parse(json2);
|
|
484
|
+
if (typeof payload.challenge !== "string") return null;
|
|
485
|
+
return {
|
|
486
|
+
challenge: payload.challenge,
|
|
487
|
+
email: payload.email ?? null,
|
|
488
|
+
refId: payload.refId ?? null
|
|
489
|
+
};
|
|
490
|
+
} catch {
|
|
491
|
+
return null;
|
|
492
|
+
}
|
|
493
|
+
}
|
|
494
|
+
function withClearChallengeCookieIfUsed(res) {
|
|
495
|
+
if (!useChallengeCookie) return res;
|
|
496
|
+
const clearCookie = serializeCookie(cookieName, "", { path: "/", maxAge: 0 });
|
|
497
|
+
const headers = new Headers(res.headers);
|
|
498
|
+
headers.append("set-cookie", clearCookie);
|
|
499
|
+
return new Response(res.body, { status: res.status, headers });
|
|
500
|
+
}
|
|
455
501
|
async function postWebhook(args) {
|
|
456
502
|
const { url, secret, retries, payload } = args;
|
|
457
503
|
const body = JSON.stringify(payload);
|
|
@@ -525,11 +571,13 @@ ${body}`;
|
|
|
525
571
|
}
|
|
526
572
|
const challenge = randomChallenge();
|
|
527
573
|
const sid = crypto.randomUUID();
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
574
|
+
if (challengeStore) {
|
|
575
|
+
await challengeStore.put(
|
|
576
|
+
`reg:${sid}`,
|
|
577
|
+
JSON.stringify({ challenge, email, refId }),
|
|
578
|
+
pendingTtlSeconds
|
|
579
|
+
);
|
|
580
|
+
}
|
|
533
581
|
const attestationType = options.attestationType ?? "none";
|
|
534
582
|
const authenticatorAttachment = options.authenticatorAttachment ?? "cross-platform";
|
|
535
583
|
const residentKey = options.residentKey ?? "preferred";
|
|
@@ -538,7 +586,7 @@ ${body}`;
|
|
|
538
586
|
const creationOptions = await sw.generateRegistrationOptions({
|
|
539
587
|
rpID: options.rpID,
|
|
540
588
|
rpName: options.rpName,
|
|
541
|
-
userID:
|
|
589
|
+
userID: randomBytes(32),
|
|
542
590
|
userName: email ?? "CorePass",
|
|
543
591
|
userDisplayName: email ?? "CorePass User",
|
|
544
592
|
challenge,
|
|
@@ -552,40 +600,45 @@ ${body}`;
|
|
|
552
600
|
timeout: registrationTimeout,
|
|
553
601
|
excludeCredentials: []
|
|
554
602
|
});
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
})
|
|
566
|
-
}
|
|
567
|
-
);
|
|
603
|
+
const cookieValue = challengeStore ? sid : await signChallengeCookie({ sid, challenge, email, refId });
|
|
604
|
+
return json(200, creationOptions, {
|
|
605
|
+
"set-cookie": serializeCookie(cookieName, cookieValue, {
|
|
606
|
+
httpOnly: true,
|
|
607
|
+
secure: true,
|
|
608
|
+
sameSite: "Lax",
|
|
609
|
+
path: "/",
|
|
610
|
+
maxAge: pendingTtlSeconds
|
|
611
|
+
})
|
|
612
|
+
});
|
|
568
613
|
}
|
|
569
614
|
async function finishRegistration(req) {
|
|
570
615
|
const body = await req.json().catch(() => null);
|
|
571
616
|
const attestation = body?.attestation;
|
|
572
|
-
if (!attestation) return json(400, { ok: false, error: "Bad request" });
|
|
617
|
+
if (!attestation) return withClearChallengeCookieIfUsed(json(400, { ok: false, error: "Bad request" }));
|
|
573
618
|
const cookies = parseCookies(req.headers.get("cookie"));
|
|
574
|
-
const
|
|
575
|
-
if (!
|
|
576
|
-
|
|
577
|
-
if (
|
|
578
|
-
|
|
579
|
-
|
|
619
|
+
const cookieVal = cookies[cookieName];
|
|
620
|
+
if (!cookieVal) return withClearChallengeCookieIfUsed(json(400, { ok: false, error: "No session" }));
|
|
621
|
+
let saved;
|
|
622
|
+
if (challengeStore) {
|
|
623
|
+
const sid = cookieVal;
|
|
624
|
+
const raw = await challengeStore.get(`reg:${sid}`);
|
|
625
|
+
if (!raw) return withClearChallengeCookieIfUsed(json(400, { ok: false, error: "Challenge expired" }));
|
|
626
|
+
await challengeStore.delete(`reg:${sid}`);
|
|
627
|
+
saved = JSON.parse(raw);
|
|
628
|
+
} else {
|
|
629
|
+
const payload = await verifyChallengeCookie(cookieVal);
|
|
630
|
+
if (!payload) return withClearChallengeCookieIfUsed(json(400, { ok: false, error: "Challenge expired or invalid" }));
|
|
631
|
+
saved = payload;
|
|
632
|
+
}
|
|
580
633
|
const expectedChallenge = saved.challenge;
|
|
581
634
|
const aaguid = extractAaguidFromAttestationObject(attestation?.response?.attestationObject);
|
|
582
635
|
if (!validateAaguidAllowlist(aaguid, allowedAaguids)) {
|
|
583
|
-
return json(400, {
|
|
636
|
+
return withClearChallengeCookieIfUsed(json(400, {
|
|
584
637
|
ok: false,
|
|
585
638
|
error: "AAGUID not allowed",
|
|
586
639
|
aaguid,
|
|
587
640
|
allowedAaguids: allowedAaguids ?? null
|
|
588
|
-
});
|
|
641
|
+
}));
|
|
589
642
|
}
|
|
590
643
|
const requireUserVerification = options.userVerification !== "discouraged";
|
|
591
644
|
let verification;
|
|
@@ -598,10 +651,10 @@ ${body}`;
|
|
|
598
651
|
requireUserVerification
|
|
599
652
|
});
|
|
600
653
|
} catch {
|
|
601
|
-
return json(400, { ok: false, error: "Invalid registration response" });
|
|
654
|
+
return withClearChallengeCookieIfUsed(json(400, { ok: false, error: "Invalid registration response" }));
|
|
602
655
|
}
|
|
603
656
|
if (!verification.verified || !verification.registrationInfo) {
|
|
604
|
-
return json(400, { ok: false, error: "Registration not verified" });
|
|
657
|
+
return withClearChallengeCookieIfUsed(json(400, { ok: false, error: "Registration not verified" }));
|
|
605
658
|
}
|
|
606
659
|
const credentialIdBase64 = bytesToBase64(verification.registrationInfo.credentialID);
|
|
607
660
|
const credentialPublicKeyBase64 = bytesToBase64(verification.registrationInfo.credentialPublicKey);
|
|
@@ -616,17 +669,17 @@ ${body}`;
|
|
|
616
669
|
transports
|
|
617
670
|
};
|
|
618
671
|
const coreIdFromBody = typeof body?.coreId === "string" ? body.coreId.trim() : null;
|
|
619
|
-
const
|
|
620
|
-
if (
|
|
672
|
+
const allowImmediateFinalize2 = options.allowImmediateFinalize ?? false;
|
|
673
|
+
if (allowImmediateFinalize2 && coreIdFromBody) {
|
|
621
674
|
if (!validateCoreIdMainnet(coreIdFromBody)) {
|
|
622
|
-
return json(400, { ok: false, error: "Invalid Core ID (mainnet)" });
|
|
675
|
+
return withClearChallengeCookieIfUsed(json(400, { ok: false, error: "Invalid Core ID (mainnet)" }));
|
|
623
676
|
}
|
|
624
677
|
const emailFromBody = parseEmail(body?.email);
|
|
625
678
|
if (body?.email !== void 0 && body?.email !== null && !emailFromBody) {
|
|
626
|
-
return json(400, { ok: false, error: "Invalid email" });
|
|
679
|
+
return withClearChallengeCookieIfUsed(json(400, { ok: false, error: "Invalid email" }));
|
|
627
680
|
}
|
|
628
681
|
const finalEmail = emailFromBody || saved.email || null;
|
|
629
|
-
if (emailRequired && !finalEmail) return json(400, { ok: false, error: "Missing email" });
|
|
682
|
+
if (emailRequired && !finalEmail) return withClearChallengeCookieIfUsed(json(400, { ok: false, error: "Missing email" }));
|
|
630
683
|
const result = await finalizeToAuthJs(options, {
|
|
631
684
|
coreId: coreIdFromBody,
|
|
632
685
|
credentialId: credentialIdBase64,
|
|
@@ -644,7 +697,7 @@ ${body}`;
|
|
|
644
697
|
coreId: coreIdFromBody,
|
|
645
698
|
refId: enableRefId ? storedIdentity?.refId ?? null : null
|
|
646
699
|
});
|
|
647
|
-
return json(200, { ok: true, finalized: true, userId: result.userId, coreId: coreIdFromBody });
|
|
700
|
+
return withClearChallengeCookieIfUsed(json(200, { ok: true, finalized: true, userId: result.userId, coreId: coreIdFromBody }));
|
|
648
701
|
}
|
|
649
702
|
const token = crypto.randomUUID();
|
|
650
703
|
const createdAt = nowSec();
|
|
@@ -664,12 +717,12 @@ ${body}`;
|
|
|
664
717
|
expiresAt
|
|
665
718
|
};
|
|
666
719
|
await options.store.createPendingRegistration(pending);
|
|
667
|
-
return json(200, {
|
|
720
|
+
return withClearChallengeCookieIfUsed(json(200, {
|
|
668
721
|
ok: true,
|
|
669
722
|
pending: true,
|
|
670
723
|
enrichToken: token,
|
|
671
724
|
credentialId: credentialIdBase64
|
|
672
|
-
});
|
|
725
|
+
}));
|
|
673
726
|
}
|
|
674
727
|
async function enrichRegistration(req) {
|
|
675
728
|
const rawBody = await req.text();
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/server/create-corepass-server.ts","../src/server/base64.ts","../src/server/canonical-json.ts","../src/server/cookies.ts","../src/server/coreid.ts","../src/server/ed448.ts","../src/server/aaguid.ts","../src/server/challenge-stores.ts","../src/server/stores.ts","../src/server/factories.ts"],"sourcesContent":["import WebAuthn from \"@auth/core/providers/webauthn\"\nimport type { AdapterAccount, AdapterAuthenticator, AdapterUser } from \"@auth/core/adapters\"\n\nimport { bytesToBase64, bytesToBase64Url, normalizeCredentialId } from \"./base64.js\"\nimport { canonicalizeForSignature, canonicalizeJSON } from \"./canonical-json.js\"\nimport { parseCookies, serializeCookie } from \"./cookies.js\"\nimport { deriveEd448PublicKeyFromCoreId, validateCoreIdMainnet } from \"./coreid.js\"\nimport { parseEd448Signature, verifyEd448Signature } from \"./ed448.js\"\nimport { extractAaguidFromAttestationObject, validateAaguidAllowlist } from \"./aaguid.js\"\n\nimport type {\n\tCorePassFinalizeArgs,\n\tCorePassFinalizeResult,\n\tCorePassPendingRegistration,\n\tCreateCorePassServerOptions,\n} from \"./types.js\"\n\nconst COREPASS_DEFAULT_AAGUID = \"636f7265-7061-7373-6964-656e74696679\"\n\nfunction nowMs(): number {\n\treturn Date.now()\n}\n\nfunction nowSec(): number {\n\treturn Math.floor(nowMs() / 1000)\n}\n\nfunction nowUs(): number {\n\treturn nowMs() * 1000\n}\n\nfunction json(status: number, body: unknown, headers?: HeadersInit): Response {\n\treturn new Response(JSON.stringify(body), {\n\t\tstatus,\n\t\theaders: { \"content-type\": \"application/json\", ...(headers ?? {}) },\n\t})\n}\n\nfunction randomBytes(n: number): Uint8Array {\n\tconst a = new Uint8Array(n)\n\tcrypto.getRandomValues(a)\n\treturn a\n}\n\nfunction randomChallenge(): string {\n\treturn bytesToBase64Url(randomBytes(32))\n}\n\nfunction parseEmail(input: unknown): string | null {\n\tif (typeof input !== \"string\") return null\n\tconst email = input.trim()\n\tif (!email) return null\n\tif (!/^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/.test(email)) return null\n\treturn email\n}\n\nfunction parseBool(input: unknown): boolean | null {\n\tif (input === undefined || input === null) return null\n\tif (typeof input === \"boolean\") return input\n\tif (typeof input === \"number\") return input === 1 ? true : input === 0 ? false : null\n\tif (typeof input === \"string\") {\n\t\tconst v = input.trim().toLowerCase()\n\t\tif (v === \"true\" || v === \"1\" || v === \"yes\") return true\n\t\tif (v === \"false\" || v === \"0\" || v === \"no\") return false\n\t}\n\treturn null\n}\n\nfunction parseDataExpMinutes(input: unknown): number | null {\n\tif (input === undefined || input === null) return null\n\tconst n = typeof input === \"number\" ? input : parseInt(String(input), 10)\n\tif (!Number.isFinite(n)) return null\n\tif (n <= 0) return null\n\treturn Math.floor(n)\n}\n\nfunction computeProvidedTillFromDataExp(dataExpMinutes: number | null): number | null {\n\tif (dataExpMinutes === null) return null\n\treturn nowSec() + dataExpMinutes * 60\n}\n\nfunction transportsToString(transports: unknown): string | null {\n\tif (!Array.isArray(transports)) return null\n\tconst items = transports.filter((t) => typeof t === \"string\") as string[]\n\treturn items.length ? items.join(\",\") : null\n}\n\nasync function finalizeToAuthJs(\n\toptions: CreateCorePassServerOptions,\n\targs: CorePassFinalizeArgs\n): Promise<CorePassFinalizeResult> {\n\tconst providerId = options.providerId ?? \"corepass\"\n\tconst { adapter, store } = options\n\tconst enableRefId = options.enableRefId ?? false\n\n\t// 1) Find or create user by CoreID mapping\n\tlet identity = await store.getIdentityByCoreId(args.coreId)\n\tlet user: AdapterUser | null = identity ? await adapter.getUser(identity.userId) : null\n\n\tif (!identity || !user) {\n\t\tconst emailRequired = options.emailRequired ?? false\n\t\tif (emailRequired && !args.email) throw new Error(\"Missing email\")\n\n\t\tuser = await adapter.createUser({\n\t\t\t// Most adapters will ignore provided id and generate their own.\n\t\t\t// CoreID is stored in corepass_identities instead.\n\t\t\temail: args.email ?? undefined,\n\t\t\temailVerified: null,\n\t\t\tname: args.coreId.toUpperCase(),\n\t\t\timage: null,\n\t\t} as any)\n\n\t\tconst refId = enableRefId ? args.refId ?? crypto.randomUUID() : null\n\t\tidentity = { coreId: args.coreId, userId: user.id, refId }\n\t\tawait store.upsertIdentity(identity)\n\t} else {\n\t\t// Keep refId if newly available\n\t\tif (enableRefId && args.refId && !identity.refId) {\n\t\t\tidentity = { ...identity, refId: args.refId }\n\t\t\tawait store.upsertIdentity(identity)\n\t\t}\n\t\tif (enableRefId && !identity.refId) {\n\t\t\tidentity = { ...identity, refId: crypto.randomUUID() }\n\t\t\tawait store.upsertIdentity(identity)\n\t\t}\n\t}\n\n\t// 2) Update user email if we have it and it differs\n\tif (args.email && user.email !== args.email) {\n\t\tuser = await adapter.updateUser({ id: user.id, email: args.email } as any)\n\t}\n\n\t// 3) Link the WebAuthn account (providerAccountId = credentialId base64)\n\tconst providerAccountId = args.credentialId\n\tconst existingUserByAccount = await adapter.getUserByAccount({\n\t\tprovider: providerId,\n\t\tproviderAccountId,\n\t})\n\tif (existingUserByAccount && existingUserByAccount.id !== user.id) {\n\t\tthrow new Error(\"Credential already linked to a different user\")\n\t}\n\n\tconst account: AdapterAccount = {\n\t\tuserId: user.id,\n\t\tprovider: providerId,\n\t\tproviderAccountId,\n\t\ttype: \"webauthn\",\n\t}\n\tif (!existingUserByAccount) {\n\t\tawait adapter.linkAccount(account)\n\t}\n\n\t// 4) Create authenticator (idempotent best-effort; adapter may enforce uniqueness)\n\tconst existingAuthenticator = await adapter.getAuthenticator(providerAccountId)\n\tif (!existingAuthenticator) {\n\t\tawait adapter.createAuthenticator({\n\t\t\t...args.authenticator,\n\t\t\tuserId: user.id,\n\t\t} as AdapterAuthenticator)\n\t}\n\n\t// 5) Store CorePass profile metadata (optional)\n\tawait store.upsertProfile({\n\t\tuserId: user.id,\n\t\tcoreId: args.coreId,\n\t\to18y: args.o18y,\n\t\to21y: args.o21y,\n\t\tkyc: args.kyc,\n\t\tkycDoc: args.kycDoc,\n\t\tprovidedTill: computeProvidedTillFromDataExp(args.dataExpMinutes),\n\t})\n\n\treturn { userId: user.id, account }\n}\n\nexport function createCorePassServer(options: CreateCorePassServerOptions) {\n\tconst cookieName = \"corepass.sid\"\n\n\tconst pendingTtlSeconds = options.pendingTtlSeconds ?? 600\n\tconst emailRequired = options.emailRequired ?? false\n\tconst requireO18y = options.requireO18y ?? false\n\tconst requireO21y = options.requireO21y ?? false\n\tconst requireKyc = options.requireKyc ?? false\n\tconst enableRefId = options.enableRefId ?? false\n\tconst postRegistrationWebhooks = options.postRegistrationWebhooks ?? false\n\tconst registrationWebhookUrl = options.registrationWebhookUrl\n\tconst registrationWebhookSecret = options.registrationWebhookSecret\n\tconst registrationWebhookRetriesRaw = options.registrationWebhookRetries ?? 3\n\n\tconst postLoginWebhooks = options.postLoginWebhooks ?? false\n\tconst loginWebhookUrl = options.loginWebhookUrl\n\tconst loginWebhookSecret = options.loginWebhookSecret\n\tconst loginWebhookRetriesRaw = options.loginWebhookRetries ?? 3\n\n\tconst postLogoutWebhooks = options.postLogoutWebhooks ?? false\n\tconst logoutWebhookUrl = options.logoutWebhookUrl\n\tconst logoutWebhookSecret = options.logoutWebhookSecret\n\tconst logoutWebhookRetriesRaw = options.logoutWebhookRetries ?? 3\n\tconst signaturePath = options.signaturePath ?? \"/passkey/data\"\n\tconst timestampWindowMs = options.timestampWindowMs ?? 10 * 60 * 1000\n\tconst timestampFutureSkewMs = options.timestampFutureSkewMs ?? 2 * 60 * 1000\n\tconst allowedAaguids = options.allowedAaguids ?? COREPASS_DEFAULT_AAGUID\n\tconst pubKeyCredAlgs = options.pubKeyCredAlgs ?? [-257, -7, -8]\n\n\tconst sw = WebAuthn({}).simpleWebAuthn\n\n\tif (postRegistrationWebhooks && !registrationWebhookUrl) {\n\t\tthrow new Error(\n\t\t\t\"createCorePassServer: postRegistrationWebhooks=true requires registrationWebhookUrl\"\n\t\t)\n\t}\n\tif (postLoginWebhooks && !loginWebhookUrl) {\n\t\tthrow new Error(\"createCorePassServer: postLoginWebhooks=true requires loginWebhookUrl\")\n\t}\n\tif (postLoginWebhooks && typeof options.store.getIdentityByUserId !== \"function\") {\n\t\tthrow new Error(\n\t\t\t\"createCorePassServer: postLoginWebhooks=true requires store.getIdentityByUserId(userId)\"\n\t\t)\n\t}\n\tif (postLogoutWebhooks && !logoutWebhookUrl) {\n\t\tthrow new Error(\"createCorePassServer: postLogoutWebhooks=true requires logoutWebhookUrl\")\n\t}\n\tif (postLogoutWebhooks && typeof options.store.getIdentityByUserId !== \"function\") {\n\t\tthrow new Error(\n\t\t\t\"createCorePassServer: postLogoutWebhooks=true requires store.getIdentityByUserId(userId)\"\n\t\t)\n\t}\n\n\tif (\n\t\t!Number.isInteger(registrationWebhookRetriesRaw) ||\n\t\tregistrationWebhookRetriesRaw < 1 ||\n\t\tregistrationWebhookRetriesRaw > 10\n\t) {\n\t\tthrow new Error(\n\t\t\t\"createCorePassServer: registrationWebhookRetries must be an integer between 1 and 10\"\n\t\t)\n\t}\n\tif (!Number.isInteger(loginWebhookRetriesRaw) || loginWebhookRetriesRaw < 1 || loginWebhookRetriesRaw > 10) {\n\t\tthrow new Error(\"createCorePassServer: loginWebhookRetries must be an integer between 1 and 10\")\n\t}\n\tif (\n\t\t!Number.isInteger(logoutWebhookRetriesRaw) ||\n\t\tlogoutWebhookRetriesRaw < 1 ||\n\t\tlogoutWebhookRetriesRaw > 10\n\t) {\n\t\tthrow new Error(\"createCorePassServer: logoutWebhookRetries must be an integer between 1 and 10\")\n\t}\n\tconst registrationWebhookRetries = registrationWebhookRetriesRaw\n\tconst loginWebhookRetries = loginWebhookRetriesRaw\n\tconst logoutWebhookRetries = logoutWebhookRetriesRaw\n\n\tconst sleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms))\n\tconst retryDelayMs = (attempt: number) => Math.min(2000, 200 * 2 ** (attempt - 1))\n\n\tconst hmacSha256Hex = async (secret: string, message: string): Promise<string> => {\n\t\tconst key = await crypto.subtle.importKey(\n\t\t\t\"raw\",\n\t\t\tnew TextEncoder().encode(secret),\n\t\t\t{ name: \"HMAC\", hash: \"SHA-256\" },\n\t\t\tfalse,\n\t\t\t[\"sign\"]\n\t\t)\n\t\tconst sig = await crypto.subtle.sign(\"HMAC\", key, new TextEncoder().encode(message))\n\t\treturn [...new Uint8Array(sig)].map((b) => b.toString(16).padStart(2, \"0\")).join(\"\")\n\t}\n\n\tasync function postWebhook(args: {\n\t\turl: string\n\t\tsecret?: string\n\t\tretries: number\n\t\tpayload: Record<string, unknown>\n\t}): Promise<void> {\n\t\tconst { url, secret, retries, payload } = args\n\t\tconst body = JSON.stringify(payload)\n\n\t\tfor (let attempt = 1; attempt <= retries; attempt++) {\n\t\t\ttry {\n\t\t\t\tconst headers: Record<string, string> = { \"content-type\": \"application/json\" }\n\t\t\t\tif (secret) {\n\t\t\t\t\tconst ts = String(nowSec())\n\t\t\t\t\tconst signatureInput = `${ts}\\n${body}`\n\t\t\t\t\tconst sigHex = await hmacSha256Hex(secret, signatureInput)\n\t\t\t\t\theaders[\"X-Webhook-Timestamp\"] = ts\n\t\t\t\t\theaders[\"X-Webhook-Signature\"] = `sha256=${sigHex}`\n\t\t\t\t}\n\n\t\t\t\tconst res = await fetch(url, {\n\t\t\t\t\tmethod: \"POST\",\n\t\t\t\t\theaders,\n\t\t\t\t\tbody,\n\t\t\t\t})\n\t\t\t\tif (res.ok) return\n\t\t\t} catch {\n\t\t\t\t// retry below\n\t\t\t}\n\n\t\t\tif (attempt < retries) {\n\t\t\t\tawait sleep(retryDelayMs(attempt))\n\t\t\t}\n\t\t}\n\t}\n\n\tasync function maybePostRegistrationWebhook(args: { coreId: string; refId: string | null }): Promise<void> {\n\t\tif (!postRegistrationWebhooks || !registrationWebhookUrl) return\n\t\tconst payload: Record<string, unknown> = { coreId: args.coreId }\n\t\tif (args.refId) payload.refId = args.refId\n\t\tawait postWebhook({\n\t\t\turl: registrationWebhookUrl,\n\t\t\tretries: registrationWebhookRetries,\n\t\t\tpayload,\n\t\t\t...(registrationWebhookSecret ? { secret: registrationWebhookSecret } : {}),\n\t\t})\n\t}\n\n\tasync function postLoginWebhook(args: { userId: string }): Promise<void> {\n\t\tif (!postLoginWebhooks || !loginWebhookUrl) return\n\t\tconst identity = await options.store.getIdentityByUserId?.(args.userId)\n\t\tif (!identity) return\n\t\tconst payload: Record<string, unknown> = { coreId: identity.coreId }\n\t\tif (identity.refId) payload.refId = identity.refId\n\t\tawait postWebhook({\n\t\t\turl: loginWebhookUrl,\n\t\t\tretries: loginWebhookRetries,\n\t\t\tpayload,\n\t\t\t...(loginWebhookSecret ? { secret: loginWebhookSecret } : {}),\n\t\t})\n\t}\n\n\tasync function postLogoutWebhook(args: { userId: string }): Promise<void> {\n\t\tif (!postLogoutWebhooks || !logoutWebhookUrl) return\n\t\tconst identity = await options.store.getIdentityByUserId?.(args.userId)\n\t\tif (!identity) return\n\t\tconst payload: Record<string, unknown> = { coreId: identity.coreId }\n\t\tif (identity.refId) payload.refId = identity.refId\n\t\tawait postWebhook({\n\t\t\turl: logoutWebhookUrl,\n\t\t\tretries: logoutWebhookRetries,\n\t\t\tpayload,\n\t\t\t...(logoutWebhookSecret ? { secret: logoutWebhookSecret } : {}),\n\t\t})\n\t}\n\n\tasync function startRegistration(req: Request): Promise<Response> {\n\t\tconst body = (await req.json().catch(() => null)) as any\n\t\tconst email = parseEmail(body?.email)\n\t\tconst refId =\n\t\t\tenableRefId && typeof body?.refId === \"string\" ? body.refId.trim() || null : null\n\n\t\tif (body?.email !== undefined && body?.email !== null && !email) {\n\t\t\treturn json(400, { ok: false, error: \"Invalid email\" })\n\t\t}\n\n\t\tconst challenge = randomChallenge()\n\t\tconst sid = crypto.randomUUID()\n\n\t\tawait options.challengeStore.put(\n\t\t\t`reg:${sid}`,\n\t\t\tJSON.stringify({ challenge, email, refId }),\n\t\t\tpendingTtlSeconds\n\t\t)\n\n\t\tconst attestationType = options.attestationType ?? \"none\"\n\t\tconst authenticatorAttachment = options.authenticatorAttachment ?? \"cross-platform\"\n\t\tconst residentKey = options.residentKey ?? \"preferred\"\n\t\tconst userVerification = options.userVerification ?? \"required\"\n\t\tconst registrationTimeout = options.registrationTimeout ?? 60_000\n\n\t\tconst creationOptions = await sw.generateRegistrationOptions({\n\t\t\trpID: options.rpID,\n\t\t\trpName: options.rpName,\n\t\t\tuserID: bytesToBase64Url(randomBytes(32)),\n\t\t\tuserName: email ?? \"CorePass\",\n\t\t\tuserDisplayName: email ?? \"CorePass User\",\n\t\t\tchallenge,\n\t\t\tpubKeyCredParams: pubKeyCredAlgs.map((alg) => ({ alg, type: \"public-key\" })),\n\t\t\tauthenticatorSelection: {\n\t\t\t\tauthenticatorAttachment,\n\t\t\t\tresidentKey,\n\t\t\t\tuserVerification,\n\t\t\t},\n\t\t\tattestationType,\n\t\t\ttimeout: registrationTimeout,\n\t\t\texcludeCredentials: [],\n\t\t})\n\n\t\treturn json(\n\t\t\t200,\n\t\t\tcreationOptions,\n\t\t\t{\n\t\t\t\t\"set-cookie\": serializeCookie(cookieName, sid, {\n\t\t\t\t\thttpOnly: true,\n\t\t\t\t\tsecure: true,\n\t\t\t\t\tsameSite: \"Lax\",\n\t\t\t\t\tpath: \"/\",\n\t\t\t\t\tmaxAge: pendingTtlSeconds,\n\t\t\t\t}),\n\t\t\t}\n\t\t)\n\t}\n\n\tasync function finishRegistration(req: Request): Promise<Response> {\n\t\tconst body = (await req.json().catch(() => null)) as any\n\t\tconst attestation = body?.attestation as any\n\t\tif (!attestation) return json(400, { ok: false, error: \"Bad request\" })\n\n\t\tconst cookies = parseCookies(req.headers.get(\"cookie\"))\n\t\tconst sid = cookies[cookieName]\n\t\tif (!sid) return json(400, { ok: false, error: \"No session\" })\n\n\t\tconst raw = await options.challengeStore.get(`reg:${sid}`)\n\t\tif (!raw) return json(400, { ok: false, error: \"Challenge expired\" })\n\t\tawait options.challengeStore.delete(`reg:${sid}`)\n\n\t\tconst saved = JSON.parse(raw) as {\n\t\t\tchallenge: string\n\t\t\temail: string | null\n\t\t\trefId: string | null\n\t\t}\n\t\tconst expectedChallenge = saved.challenge\n\n\t\t// Validate AAGUID allowlist (CorePass app gate)\n\t\tconst aaguid = extractAaguidFromAttestationObject((attestation as any)?.response?.attestationObject)\n\t\tif (!validateAaguidAllowlist(aaguid, allowedAaguids)) {\n\t\t\treturn json(400, {\n\t\t\t\tok: false,\n\t\t\t\terror: \"AAGUID not allowed\",\n\t\t\t\taaguid,\n\t\t\t\tallowedAaguids: allowedAaguids ?? null,\n\t\t\t})\n\t\t}\n\n\t\tconst requireUserVerification = options.userVerification !== \"discouraged\"\n\t\tlet verification: Awaited<ReturnType<(typeof sw)[\"verifyRegistrationResponse\"]>>\n\t\ttry {\n\t\t\tverification = await sw.verifyRegistrationResponse({\n\t\t\t\tresponse: attestation,\n\t\t\t\texpectedChallenge,\n\t\t\t\texpectedOrigin: options.expectedOrigin,\n\t\t\t\texpectedRPID: options.rpID,\n\t\t\t\trequireUserVerification,\n\t\t\t})\n\t\t} catch {\n\t\t\treturn json(400, { ok: false, error: \"Invalid registration response\" })\n\t\t}\n\n\t\tif (!verification.verified || !verification.registrationInfo) {\n\t\t\treturn json(400, { ok: false, error: \"Registration not verified\" })\n\t\t}\n\n\t\tconst credentialIdBase64 = bytesToBase64(verification.registrationInfo.credentialID)\n\t\tconst credentialPublicKeyBase64 = bytesToBase64(verification.registrationInfo.credentialPublicKey)\n\t\tconst transports = transportsToString((attestation as any)?.response?.transports)\n\n\t\tconst authenticator: Omit<AdapterAuthenticator, \"userId\"> = {\n\t\t\tproviderAccountId: credentialIdBase64,\n\t\t\tcredentialID: credentialIdBase64,\n\t\t\tcredentialPublicKey: credentialPublicKeyBase64,\n\t\t\tcounter: verification.registrationInfo.counter,\n\t\t\tcredentialDeviceType: verification.registrationInfo.credentialDeviceType,\n\t\t\tcredentialBackedUp: verification.registrationInfo.credentialBackedUp,\n\t\t\ttransports,\n\t\t}\n\n\t\tconst coreIdFromBody = typeof body?.coreId === \"string\" ? body.coreId.trim() : null\n\t\tconst allowImmediateFinalize = options.allowImmediateFinalize ?? false\n\n\t\tif (allowImmediateFinalize && coreIdFromBody) {\n\t\t\tif (!validateCoreIdMainnet(coreIdFromBody)) {\n\t\t\t\treturn json(400, { ok: false, error: \"Invalid Core ID (mainnet)\" })\n\t\t\t}\n\n\t\t\tconst emailFromBody = parseEmail(body?.email)\n\t\t\tif (body?.email !== undefined && body?.email !== null && !emailFromBody) {\n\t\t\t\treturn json(400, { ok: false, error: \"Invalid email\" })\n\t\t\t}\n\t\t\tconst finalEmail = emailFromBody || saved.email || null\n\t\t\tif (emailRequired && !finalEmail) return json(400, { ok: false, error: \"Missing email\" })\n\n\t\t\tconst result = await finalizeToAuthJs(options, {\n\t\t\t\tcoreId: coreIdFromBody,\n\t\t\t\tcredentialId: credentialIdBase64,\n\t\t\t\tauthenticator,\n\t\t\t\temail: finalEmail,\n\t\t\t\trefId: enableRefId ? saved.refId : null,\n\t\t\t\to18y: parseBool(body?.o18y),\n\t\t\t\to21y: parseBool(body?.o21y),\n\t\t\t\tkyc: parseBool(body?.kyc),\n\t\t\t\tkycDoc: typeof body?.kycDoc === \"string\" ? body.kycDoc.trim() || null : null,\n\t\t\t\tdataExpMinutes: parseDataExpMinutes(body?.dataExp),\n\t\t\t})\n\n\t\t\tconst storedIdentity = await options.store.getIdentityByCoreId(coreIdFromBody)\n\t\t\tawait maybePostRegistrationWebhook({\n\t\t\t\tcoreId: coreIdFromBody,\n\t\t\t\trefId: enableRefId ? storedIdentity?.refId ?? null : null,\n\t\t\t})\n\n\t\t\treturn json(200, { ok: true, finalized: true, userId: result.userId, coreId: coreIdFromBody })\n\t\t}\n\n\t\tconst token = crypto.randomUUID()\n\t\tconst createdAt = nowSec()\n\t\tconst expiresAt = createdAt + pendingTtlSeconds\n\t\tconst pending: CorePassPendingRegistration = {\n\t\t\ttoken,\n\t\t\tcredentialId: credentialIdBase64,\n\t\t\tcredentialPublicKey: credentialPublicKeyBase64,\n\t\t\tcounter: authenticator.counter,\n\t\t\tcredentialDeviceType: authenticator.credentialDeviceType,\n\t\t\tcredentialBackedUp: authenticator.credentialBackedUp,\n\t\t\ttransports: authenticator.transports ?? null,\n\t\t\temail: saved.email,\n\t\t\trefId: enableRefId ? saved.refId : null,\n\t\t\taaguid,\n\t\t\tcreatedAt,\n\t\t\texpiresAt,\n\t\t}\n\t\tawait options.store.createPendingRegistration(pending)\n\n\t\treturn json(200, {\n\t\t\tok: true,\n\t\t\tpending: true,\n\t\t\tenrichToken: token,\n\t\t\tcredentialId: credentialIdBase64,\n\t\t})\n\t}\n\n\tasync function enrichRegistration(req: Request): Promise<Response> {\n\t\tconst rawBody = await req.text()\n\t\tlet body: any\n\t\ttry {\n\t\t\tbody = JSON.parse(rawBody)\n\t\t} catch {\n\t\t\treturn json(400, { ok: false, error: \"Invalid JSON\" })\n\t\t}\n\n\t\tconst coreId = typeof body?.coreId === \"string\" ? body.coreId.trim() : null\n\t\tconst credentialIdRaw = typeof body?.credentialId === \"string\" ? body.credentialId.trim() : null\n\t\tconst timestamp = body?.timestamp as unknown\n\t\tconst userData = body?.userData ?? {}\n\n\t\tif (!coreId || !credentialIdRaw || typeof timestamp !== \"number\") {\n\t\t\treturn json(400, { ok: false, error: \"Missing required fields: coreId, credentialId, timestamp\" })\n\t\t}\n\n\t\tif (!validateCoreIdMainnet(coreId)) {\n\t\t\treturn json(400, { ok: false, error: \"Invalid Core ID (mainnet)\" })\n\t\t}\n\n\t\tconst credentialIdNormalized = normalizeCredentialId(credentialIdRaw)\n\t\tif (!credentialIdNormalized) return json(400, { ok: false, error: \"Invalid credentialId encoding\" })\n\t\tconst credentialIdBase64 = credentialIdNormalized.base64\n\n\t\t// Timestamp must be integer microseconds since Unix epoch\n\t\tif (!Number.isSafeInteger(timestamp) || timestamp <= 0) {\n\t\t\treturn json(400, { ok: false, error: \"Invalid timestamp (microseconds)\" })\n\t\t}\n\n\t\tconst tNowUs = nowUs()\n\t\tconst windowUs = timestampWindowMs * 1000\n\t\tconst futureSkewUs = timestampFutureSkewMs * 1000\n\t\tif (tNowUs - timestamp > windowUs) return json(400, { ok: false, error: \"Timestamp too old\" })\n\t\tif (timestamp - tNowUs > futureSkewUs) return json(400, { ok: false, error: \"Timestamp too far in future\" })\n\n\t\tconst signatureHeader = req.headers.get(\"X-Signature\")\n\t\tif (!signatureHeader) return json(400, { ok: false, error: \"Missing X-Signature header\" })\n\n\t\tconst signatureBytes = parseEd448Signature(signatureHeader)\n\t\tif (!signatureBytes) return json(400, { ok: false, error: \"Invalid signature format\" })\n\t\tif (signatureBytes.length !== 114) return json(400, { ok: false, error: \"Invalid signature length\" })\n\n\t\tconst publicKeyBytes = deriveEd448PublicKeyFromCoreId(coreId)\n\t\tif (!publicKeyBytes) return json(400, { ok: false, error: \"Failed to derive public key from CoreID\" })\n\n\t\tconst canonicalBody = canonicalizeJSON(body)\n\t\tconst signatureInput = canonicalizeForSignature(\"POST\", signaturePath, canonicalBody)\n\t\tconst messageBytes = new TextEncoder().encode(signatureInput)\n\t\tconst valid = await verifyEd448Signature({ publicKeyBytes, messageBytes, signatureBytes })\n\t\tif (!valid) return json(400, { ok: false, error: \"Invalid signature\" })\n\n\t\tconst pending = await options.store.getPendingRegistrationByCredentialId(credentialIdBase64)\n\t\tif (!pending) return json(400, { ok: false, error: \"Pending registration not found\" })\n\n\t\tif (pending.expiresAt < nowSec()) {\n\t\t\tawait options.store.deletePendingRegistrationByToken(pending.token)\n\t\t\treturn json(400, { ok: false, error: \"Pending registration expired\" })\n\t\t}\n\n\t\tconst emailFromBody = parseEmail(userData?.email)\n\t\tconst o18yFromBody = parseBool(userData?.o18y)\n\t\tconst o21yFromBody = parseBool(userData?.o21y)\n\t\tconst kycFromBody = parseBool(userData?.kyc)\n\t\tconst kycDocFromBody = typeof userData?.kycDoc === \"string\" ? userData.kycDoc.trim() || null : null\n\t\tconst dataExpMinutes = parseDataExpMinutes(userData?.dataExp)\n\t\tconst refIdFromBody =\n\t\t\tenableRefId && typeof userData?.refId === \"string\" ? userData.refId.trim() || null : null\n\n\t\tconst failAndCleanup = async (status: number, error: string): Promise<Response> => {\n\t\t\tawait options.store.deletePendingRegistrationByToken(pending.token)\n\t\t\treturn json(status, { ok: false, error })\n\t\t}\n\n\t\t// Validate parsed fields (and cleanup pending on failure)\n\t\tif (userData?.email !== undefined && userData?.email !== null && !emailFromBody) {\n\t\t\treturn await failAndCleanup(400, \"Invalid email format\")\n\t\t}\n\t\tif (userData?.o18y !== undefined && userData?.o18y !== null && o18yFromBody === null) {\n\t\t\treturn await failAndCleanup(400, \"Invalid o18y\")\n\t\t}\n\t\tif (userData?.o21y !== undefined && userData?.o21y !== null && o21yFromBody === null) {\n\t\t\treturn await failAndCleanup(400, \"Invalid o21y\")\n\t\t}\n\t\tif (userData?.kyc !== undefined && userData?.kyc !== null && kycFromBody === null) {\n\t\t\treturn await failAndCleanup(400, \"Invalid kyc\")\n\t\t}\n\t\tif (userData?.dataExp !== undefined && userData?.dataExp !== null && dataExpMinutes === null) {\n\t\t\treturn await failAndCleanup(400, \"Invalid dataExp\")\n\t\t}\n\n\t\t// Policy gates (enrich/pending path only; not enforced for immediate-finalize)\n\t\tif (requireO18y && o18yFromBody !== true) {\n\t\t\treturn await failAndCleanup(403, \"o18y required\")\n\t\t}\n\t\tif (requireO21y && o21yFromBody !== true) {\n\t\t\treturn await failAndCleanup(403, \"o21y required\")\n\t\t}\n\t\tif (requireKyc && kycFromBody !== true) {\n\t\t\treturn await failAndCleanup(403, \"kyc required\")\n\t\t}\n\n\t\tconst finalEmail = emailFromBody || pending.email || null\n\t\tif (emailRequired && !finalEmail) {\n\t\t\tawait options.store.deletePendingRegistrationByToken(pending.token)\n\t\t\treturn json(400, { ok: false, error: \"Missing email\" })\n\t\t}\n\n\t\tconst refId = enableRefId ? refIdFromBody || pending.refId || null : null\n\n\t\tawait options.store.deletePendingRegistrationByToken(pending.token)\n\n\t\tconst authenticator: Omit<AdapterAuthenticator, \"userId\"> = {\n\t\t\tproviderAccountId: pending.credentialId,\n\t\t\tcredentialID: pending.credentialId,\n\t\t\tcredentialPublicKey: pending.credentialPublicKey,\n\t\t\tcounter: pending.counter,\n\t\t\tcredentialDeviceType: pending.credentialDeviceType,\n\t\t\tcredentialBackedUp: pending.credentialBackedUp,\n\t\t\ttransports: pending.transports,\n\t\t}\n\n\t\tconst result = await finalizeToAuthJs(options, {\n\t\t\tcoreId,\n\t\t\tcredentialId: pending.credentialId,\n\t\t\tauthenticator,\n\t\t\temail: finalEmail,\n\t\t\trefId,\n\t\t\to18y: o18yFromBody,\n\t\t\to21y: o21yFromBody,\n\t\t\tkyc: kycFromBody,\n\t\t\tkycDoc: kycDocFromBody,\n\t\t\tdataExpMinutes,\n\t\t})\n\n\t\tconst storedIdentity = await options.store.getIdentityByCoreId(coreId)\n\t\tawait maybePostRegistrationWebhook({ coreId, refId: storedIdentity?.refId ?? null })\n\n\t\treturn json(200, {\n\t\t\tok: true,\n\t\t\tcoreId,\n\t\t\temail: finalEmail,\n\t\t\tuserId: result.userId,\n\t\t})\n\t}\n\n\tfunction checkEnrichment(): Response {\n\t\tconst available = !(options.allowImmediateFinalize ?? false)\n\t\treturn new Response(null, { status: available ? 200 : 404 })\n\t}\n\n\treturn { startRegistration, finishRegistration, enrichRegistration, postLoginWebhook, postLogoutWebhook, checkEnrichment }\n}\n","function hasAtobBtoa(): boolean {\n\treturn typeof globalThis.atob === \"function\" && typeof globalThis.btoa === \"function\"\n}\n\nfunction bytesToBinaryString(bytes: Uint8Array): string {\n\tlet s = \"\"\n\tfor (let i = 0; i < bytes.length; i++) s += String.fromCharCode(bytes[i]!)\n\treturn s\n}\n\nfunction binaryStringToBytes(bin: string): Uint8Array {\n\tconst bytes = new Uint8Array(bin.length)\n\tfor (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i)\n\treturn bytes\n}\n\nexport function bytesToBase64(bytes: Uint8Array): string {\n\tif (hasAtobBtoa()) {\n\t\treturn globalThis.btoa(bytesToBinaryString(bytes))\n\t}\n\treturn Buffer.from(bytes).toString(\"base64\")\n}\n\nexport function base64ToBytes(base64: string): Uint8Array {\n\tif (hasAtobBtoa()) {\n\t\treturn binaryStringToBytes(globalThis.atob(base64))\n\t}\n\treturn new Uint8Array(Buffer.from(base64, \"base64\"))\n}\n\nexport function bytesToBase64Url(bytes: Uint8Array): string {\n\treturn bytesToBase64(bytes).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/g, \"\")\n}\n\nexport function base64UrlToBytes(base64url: string): Uint8Array {\n\tconst pad = \"=\".repeat((4 - (base64url.length % 4)) % 4)\n\tconst base64 = (base64url + pad).replace(/-/g, \"+\").replace(/_/g, \"/\")\n\treturn base64ToBytes(base64)\n}\n\nexport function tryDecodeBase64OrBase64Url(input: string): Uint8Array | null {\n\ttry {\n\t\tif (!input || typeof input !== \"string\") return null\n\t\tconst s = input.trim()\n\t\tif (!s) return null\n\n\t\tif (/^[0-9A-Za-z+/]+=*$/.test(s) && s.length % 4 === 0) {\n\t\t\treturn base64ToBytes(s)\n\t\t}\n\t\tif (/^[0-9A-Za-z_-]+$/.test(s)) {\n\t\t\treturn base64UrlToBytes(s)\n\t\t}\n\t\treturn null\n\t} catch {\n\t\treturn null\n\t}\n}\n\nexport function normalizeCredentialId(id: string): {\n\tbytes: Uint8Array\n\tbase64: string\n\tbase64url: string\n} | null {\n\tconst bytes = tryDecodeBase64OrBase64Url(id)\n\tif (!bytes) return null\n\treturn { bytes, base64: bytesToBase64(bytes), base64url: bytesToBase64Url(bytes) }\n}\n","function sortKeysRecursive(value: unknown): unknown {\n\tif (value === null || typeof value !== \"object\") return value\n\tif (Array.isArray(value)) return value.map(sortKeysRecursive)\n\n\tconst obj = value as Record<string, unknown>\n\tconst out: Record<string, unknown> = {}\n\tfor (const key of Object.keys(obj).sort()) {\n\t\tout[key] = sortKeysRecursive(obj[key])\n\t}\n\treturn out\n}\n\nexport function canonicalizeJSON(value: unknown): string {\n\treturn JSON.stringify(sortKeysRecursive(value))\n}\n\nexport function canonicalizeForSignature(method: string, path: string, canonicalBody: string): string {\n\treturn `${method}\\n${path}\\n${canonicalBody}`\n}\n","export function parseCookies(header: string | null): Record<string, string> {\n\tconst out: Record<string, string> = {}\n\tif (!header) return out\n\tfor (const part of header.split(\";\")) {\n\t\tconst [k, ...rest] = part.trim().split(\"=\")\n\t\tif (!k) continue\n\t\tout[k] = decodeURIComponent(rest.join(\"=\") || \"\")\n\t}\n\treturn out\n}\n\nexport type CookieOptions = {\n\thttpOnly?: boolean\n\tsecure?: boolean\n\tsameSite?: \"Lax\" | \"Strict\" | \"None\"\n\tpath?: string\n\tmaxAge?: number\n}\n\nexport function serializeCookie(name: string, value: string, options: CookieOptions = {}): string {\n\tconst attrs: string[] = [`${name}=${encodeURIComponent(value)}`]\n\tif (options.maxAge !== undefined) attrs.push(`Max-Age=${Math.floor(options.maxAge)}`)\n\tattrs.push(`Path=${options.path ?? \"/\"}`)\n\tif (options.httpOnly !== false) attrs.push(\"HttpOnly\")\n\tif (options.secure !== false) attrs.push(\"Secure\")\n\tif (options.sameSite) attrs.push(`SameSite=${options.sameSite}`)\n\treturn attrs.join(\"; \")\n}\n","import { validateWalletAddress } from \"blockchain-wallet-validator\"\n\nfunction isDigits2(s: string): boolean {\n\treturn /^[0-9]{2}$/.test(s)\n}\n\nfunction isHex(s: string): boolean {\n\treturn /^[0-9a-fA-F]+$/.test(s)\n}\n\nfunction hexToBytes(hex: string): Uint8Array | null {\n\tif (!hex || (hex.length % 2) !== 0) return null\n\tif (!isHex(hex)) return null\n\n\tconst bytes = new Uint8Array(hex.length / 2)\n\tfor (let i = 0; i < hex.length; i += 2) {\n\t\tbytes[i / 2] = parseInt(hex.slice(i, i + 2), 16)\n\t}\n\treturn bytes\n}\n\nexport function validateCoreIdMainnet(coreId: string): boolean {\n\ttry {\n\t\tif (typeof coreId !== \"string\" || !coreId.trim()) return false\n\t\tconst res = validateWalletAddress(coreId.trim(), { network: [\"xcb\"], testnet: false })\n\t\treturn !!(res && (res as any).isValid)\n\t} catch {\n\t\treturn false\n\t}\n}\n\nexport function parseCoreIdIcan(coreId: string): { prefix: \"cb\"; checksum: string; bban: string } | null {\n\tif (typeof coreId !== \"string\") return null\n\tconst s = coreId.trim()\n\tif (s.length < 5) return null\n\tconst prefix = s.slice(0, 2).toLowerCase()\n\tconst checksum = s.slice(2, 4)\n\tconst bban = s.slice(4)\n\n\tif (prefix !== \"cb\") return null\n\tif (!isDigits2(checksum)) return null\n\tif (!bban) return null\n\treturn { prefix: \"cb\", checksum, bban }\n}\n\n/**\n * Default CorePass derivation:\n * - Validate CoreID as mainnet ICAN\n * - Treat BBAN as hex encoding of the raw 57-byte Ed448 public key (114 hex chars)\n */\nexport function deriveEd448PublicKeyFromCoreId(coreId: string): Uint8Array | null {\n\tif (!validateCoreIdMainnet(coreId)) return null\n\tconst parts = parseCoreIdIcan(coreId)\n\tif (!parts) return null\n\n\tconst pk = hexToBytes(parts.bban)\n\tif (!pk) return null\n\tif (pk.length !== 57) return null\n\treturn pk\n}\n","import { ed448 } from \"@noble/curves/ed448.js\"\nimport { tryDecodeBase64OrBase64Url } from \"./base64.js\"\n\nfunction isHex(s: string): boolean {\n\treturn /^[0-9a-fA-F]+$/.test(s)\n}\n\nfunction hexToBytes(hex: string): Uint8Array | null {\n\tif (!hex || (hex.length % 2) !== 0) return null\n\tif (!isHex(hex)) return null\n\tconst bytes = new Uint8Array(hex.length / 2)\n\tfor (let i = 0; i < hex.length; i += 2) {\n\t\tbytes[i / 2] = parseInt(hex.slice(i, i + 2), 16)\n\t}\n\treturn bytes\n}\n\nexport function parseEd448Signature(signature: string): Uint8Array | null {\n\tif (typeof signature !== \"string\") return null\n\tconst s = signature.trim()\n\tif (!s) return null\n\n\tif (isHex(s)) return hexToBytes(s)\n\treturn tryDecodeBase64OrBase64Url(s)\n}\n\nasync function verifyWithWebCrypto(\n\tpublicKeyBytes: Uint8Array,\n\tmessageBytes: Uint8Array,\n\tsignatureBytes: Uint8Array\n): Promise<boolean> {\n\ttry {\n\t\tconst toArrayBuffer = (u8: Uint8Array): ArrayBuffer =>\n\t\t\tu8.buffer.slice(u8.byteOffset, u8.byteOffset + u8.byteLength) as ArrayBuffer\n\n\t\tconst key = await crypto.subtle.importKey(\n\t\t\t\"raw\",\n\t\t\ttoArrayBuffer(publicKeyBytes),\n\t\t\t{ name: \"Ed448\" },\n\t\t\tfalse,\n\t\t\t[\"verify\"]\n\t\t)\n\t\treturn await crypto.subtle.verify(\n\t\t\t{ name: \"Ed448\" },\n\t\t\tkey,\n\t\t\ttoArrayBuffer(signatureBytes),\n\t\t\ttoArrayBuffer(messageBytes)\n\t\t)\n\t} catch {\n\t\treturn false\n\t}\n}\n\nexport async function verifyEd448Signature(args: {\n\tpublicKeyBytes: Uint8Array\n\tmessageBytes: Uint8Array\n\tsignatureBytes: Uint8Array\n}): Promise<boolean> {\n\tconst { publicKeyBytes, messageBytes, signatureBytes } = args\n\tif (!(publicKeyBytes instanceof Uint8Array) || publicKeyBytes.length !== 57) return false\n\tif (!(signatureBytes instanceof Uint8Array) || signatureBytes.length !== 114) return false\n\tif (!(messageBytes instanceof Uint8Array)) return false\n\n\tif (crypto?.subtle) {\n\t\tconst ok = await verifyWithWebCrypto(publicKeyBytes, messageBytes, signatureBytes)\n\t\tif (ok) return true\n\t}\n\n\ttry {\n\t\treturn ed448.verify(signatureBytes, messageBytes, publicKeyBytes)\n\t} catch {\n\t\treturn false\n\t}\n}\n","import { decode as cborDecode } from \"cbor-x\"\nimport { base64UrlToBytes } from \"./base64.js\"\n\nfunction bytesToHex(bytes: Uint8Array): string {\n\treturn [...bytes].map((b) => b.toString(16).padStart(2, \"0\")).join(\"\")\n}\n\nfunction hexToUuid(hex32: string): string {\n\treturn [\n\t\thex32.slice(0, 8),\n\t\thex32.slice(8, 12),\n\t\thex32.slice(12, 16),\n\t\thex32.slice(16, 20),\n\t\thex32.slice(20),\n\t].join(\"-\")\n}\n\nfunction bytes16ToUuid(bytes16: Uint8Array): string {\n\treturn hexToUuid(bytesToHex(bytes16))\n}\n\n/**\n * Extract the AAGUID from a WebAuthn attestationObject (base64url).\n */\nexport function extractAaguidFromAttestationObject(attestationObjectB64Url?: string): string | null {\n\tif (!attestationObjectB64Url) return null\n\ttry {\n\t\tconst attestationBytes = base64UrlToBytes(attestationObjectB64Url)\n\t\tconst attObj = cborDecode(attestationBytes) as any\n\t\tconst authData: Uint8Array | undefined = attObj?.authData\n\t\tif (!authData || authData.length < 37) return null\n\n\t\tconst flags = authData[32] ?? 0\n\t\tconst AT_FLAG = 0x40\n\t\tif ((flags & AT_FLAG) === 0) return null\n\n\t\tconst aaguidOffset = 32 + 1 + 4\n\t\tconst aaguidBytes = authData.slice(aaguidOffset, aaguidOffset + 16)\n\t\tif (aaguidBytes.length !== 16) return null\n\n\t\treturn bytes16ToUuid(aaguidBytes)\n\t} catch {\n\t\treturn null\n\t}\n}\n\nexport function validateAaguidAllowlist(\n\taaguid: string | null,\n\tallowedAaguids?: string | string[] | false\n): boolean {\n\tif (allowedAaguids === false) return true\n\tif (!allowedAaguids) return true\n\tif (!aaguid) return false\n\n\tconst normalized = aaguid.trim().toLowerCase()\n\tconst allowed = Array.isArray(allowedAaguids)\n\t\t? allowedAaguids.map((s) => String(s).trim().toLowerCase()).filter(Boolean)\n\t\t: [allowedAaguids.trim().toLowerCase()].filter(Boolean)\n\n\treturn allowed.includes(normalized)\n}\n","import type { CorePassChallengeStore } from \"./types.js\"\n\nexport function memoryChallengeStore(): CorePassChallengeStore {\n\tconst m = new Map<string, { value: string; expiresAtMs: number }>()\n\n\treturn {\n\t\tasync put(key, value, ttlSeconds) {\n\t\t\tm.set(key, { value, expiresAtMs: Date.now() + ttlSeconds * 1000 })\n\t\t},\n\t\tasync get(key) {\n\t\t\tconst row = m.get(key)\n\t\t\tif (!row) return null\n\t\t\tif (Date.now() > row.expiresAtMs) {\n\t\t\t\tm.delete(key)\n\t\t\t\treturn null\n\t\t\t}\n\t\t\treturn row.value\n\t\t},\n\t\tasync delete(key) {\n\t\t\tm.delete(key)\n\t\t},\n\t}\n}\n\nexport type RedisLike = {\n\tset: (key: string, value: string, opts: { ex: number }) => Promise<unknown>\n\tget: (key: string) => Promise<string | null>\n\tdel: (key: string) => Promise<unknown>\n}\n\nexport function redisChallengeStore(redis: RedisLike): CorePassChallengeStore {\n\treturn {\n\t\tasync put(key, value, ttlSeconds) {\n\t\t\tawait redis.set(key, value, { ex: ttlSeconds })\n\t\t},\n\t\tasync get(key) {\n\t\t\treturn await redis.get(key)\n\t\t},\n\t\tasync delete(key) {\n\t\t\tawait redis.del(key)\n\t\t},\n\t}\n}\n\nexport type KvLike = {\n\tput: (key: string, value: string, opts: { expirationTtl: number }) => Promise<unknown>\n\tget: (key: string) => Promise<string | null>\n\tdelete: (key: string) => Promise<unknown>\n}\n\nexport function kvChallengeStore(kv: KvLike): CorePassChallengeStore {\n\treturn {\n\t\tasync put(key, value, ttlSeconds) {\n\t\t\tawait kv.put(key, value, { expirationTtl: ttlSeconds })\n\t\t},\n\t\tasync get(key) {\n\t\t\treturn await kv.get(key)\n\t\t},\n\t\tasync delete(key) {\n\t\t\tawait kv.delete(key)\n\t\t},\n\t}\n}\n\n/**\n * Vercel KV client shape (based on `@vercel/kv`).\n * We intentionally don't import `@vercel/kv` to avoid a hard dependency.\n */\nexport type VercelKvLike = {\n\tset: (key: string, value: string, opts: { ex: number }) => Promise<unknown>\n\tget: <T = string>(key: string) => Promise<T | null>\n\tdel: (key: string) => Promise<unknown>\n}\n\nexport function vercelKvChallengeStore(kv: VercelKvLike): CorePassChallengeStore {\n\treturn {\n\t\tasync put(key, value, ttlSeconds) {\n\t\t\tawait kv.set(key, value, { ex: ttlSeconds })\n\t\t},\n\t\tasync get(key) {\n\t\t\tconst v = await kv.get<string>(key)\n\t\t\treturn typeof v === \"string\" ? v : v === null ? null : String(v)\n\t\t},\n\t\tasync delete(key) {\n\t\t\tawait kv.del(key)\n\t\t},\n\t}\n}\n\n/**\n * Upstash Redis REST client shape (based on `@upstash/redis`).\n * We intentionally don't import `@upstash/redis` to avoid a hard dependency.\n */\nexport type UpstashRedisLike = {\n\tset: (key: string, value: string, opts: { ex: number }) => Promise<unknown>\n\tget: <T = string>(key: string) => Promise<T | null>\n\tdel: (key: string) => Promise<unknown>\n}\n\nexport function upstashRedisChallengeStore(redis: UpstashRedisLike): CorePassChallengeStore {\n\treturn {\n\t\tasync put(key, value, ttlSeconds) {\n\t\t\tawait redis.set(key, value, { ex: ttlSeconds })\n\t\t},\n\t\tasync get(key) {\n\t\t\tconst v = await redis.get<string>(key)\n\t\t\treturn typeof v === \"string\" ? v : v === null ? null : String(v)\n\t\t},\n\t\tasync delete(key) {\n\t\t\tawait redis.del(key)\n\t\t},\n\t}\n}\n\n/**\n * Durable Object stub shape (Cloudflare).\n * Your Durable Object must implement these routes:\n * - POST /challenge/put { key, value, ttlSeconds }\n * - GET /challenge/get?key=...\n * - POST /challenge/delete { key }\n */\nexport type DurableObjectStubLike = {\n\tfetch: (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>\n}\n\nexport function durableObjectChallengeStore(stub: DurableObjectStubLike): CorePassChallengeStore {\n\treturn {\n\t\tasync put(key, value, ttlSeconds) {\n\t\t\tconst res = await stub.fetch(\"https://do/challenge/put\", {\n\t\t\t\tmethod: \"POST\",\n\t\t\t\theaders: { \"content-type\": \"application/json\" },\n\t\t\t\tbody: JSON.stringify({ key, value, ttlSeconds }),\n\t\t\t})\n\t\t\tif (!res.ok) throw new Error(\"durableObjectChallengeStore: put failed\")\n\t\t},\n\t\tasync get(key) {\n\t\t\tconst res = await stub.fetch(\n\t\t\t\t`https://do/challenge/get?key=${encodeURIComponent(key)}`\n\t\t\t)\n\t\t\tif (!res.ok) return null\n\t\t\tconst data = (await res.json()) as { value: string | null }\n\t\t\treturn data.value\n\t\t},\n\t\tasync delete(key) {\n\t\t\tawait stub.fetch(\"https://do/challenge/delete\", {\n\t\t\t\tmethod: \"POST\",\n\t\t\t\theaders: { \"content-type\": \"application/json\" },\n\t\t\t\tbody: JSON.stringify({ key }),\n\t\t\t})\n\t\t},\n\t}\n}\n\n/**\n * DynamoDB-style store (pluggable).\n * This avoids hard-depending on AWS SDK packages while still making wiring easy.\n */\nexport type DynamoLike = {\n\tput: (args: { key: string; value: string; expiresAt: number }) => Promise<unknown>\n\tget: (key: string) => Promise<{ value: string; expiresAt: number } | null>\n\tdelete: (key: string) => Promise<unknown>\n}\n\nexport function dynamoChallengeStore(dynamo: DynamoLike): CorePassChallengeStore {\n\tconst nowSec = () => Math.floor(Date.now() / 1000)\n\treturn {\n\t\tasync put(key, value, ttlSeconds) {\n\t\t\tawait dynamo.put({ key, value, expiresAt: nowSec() + ttlSeconds })\n\t\t},\n\t\tasync get(key) {\n\t\t\tconst row = await dynamo.get(key)\n\t\t\tif (!row) return null\n\t\t\tif (row.expiresAt < nowSec()) return null\n\t\t\treturn row.value\n\t\t},\n\t\tasync delete(key) {\n\t\t\tawait dynamo.delete(key)\n\t\t},\n\t}\n}\n","import type {\n\tCorePassPendingRegistration,\n\tCorePassProfile,\n\tCorePassStore,\n\tCorePassUserIdentity,\n} from \"./types.js\"\n\ntype BoolDb = 0 | 1 | boolean | null\n\nfunction boolToDb(v: boolean | null): 0 | 1 | null {\n\tif (v === null) return null\n\treturn v ? 1 : 0\n}\n\nfunction boolFromDb(v: BoolDb): boolean | null {\n\tif (v === null) return null\n\tif (typeof v === \"boolean\") return v\n\treturn v === 1 ? true : v === 0 ? false : null\n}\n\nfunction nowSec(): number {\n\treturn Math.floor(Date.now() / 1000)\n}\n\n// -----------------------------\n// D1 / SQLite\n// -----------------------------\n\nexport type D1Like = {\n\tprepare: (sql: string) => {\n\t\tbind: (...params: unknown[]) => {\n\t\t\trun: () => Promise<unknown>\n\t\t\tfirst: <T = unknown>() => Promise<T | null>\n\t\t\tall?: <T = unknown>() => Promise<{ results: T[] }>\n\t\t}\n\t}\n}\n\nexport function d1CorePassStore(db: D1Like): CorePassStore {\n\treturn {\n\t\tasync createPendingRegistration(reg) {\n\t\t\tawait db\n\t\t\t\t.prepare(\n\t\t\t\t\t`INSERT INTO corepass_pending_registrations\n\t\t\t\t\t(token, credential_id, credential_public_key, counter, credential_device_type, credential_backed_up, transports, email, ref_id, aaguid, created_at, expires_at)\n\t\t\t\t\tVALUES\n\t\t\t\t\t(?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12)`\n\t\t\t\t)\n\t\t\t\t.bind(\n\t\t\t\t\treg.token,\n\t\t\t\t\treg.credentialId,\n\t\t\t\t\treg.credentialPublicKey,\n\t\t\t\t\treg.counter,\n\t\t\t\t\treg.credentialDeviceType,\n\t\t\t\t\treg.credentialBackedUp ? 1 : 0,\n\t\t\t\t\treg.transports,\n\t\t\t\t\treg.email,\n\t\t\t\t\treg.refId,\n\t\t\t\t\treg.aaguid,\n\t\t\t\t\treg.createdAt,\n\t\t\t\t\treg.expiresAt\n\t\t\t\t)\n\t\t\t\t.run()\n\t\t},\n\n\t\tasync getPendingRegistrationByCredentialId(credentialId) {\n\t\t\tconst row = (await db\n\t\t\t\t.prepare(\n\t\t\t\t\t`SELECT token, credential_id, credential_public_key, counter, credential_device_type, credential_backed_up, transports, email, ref_id, aaguid, created_at, expires_at\n\t\t\t\t\tFROM corepass_pending_registrations\n\t\t\t\t\tWHERE credential_id = ?1`\n\t\t\t\t)\n\t\t\t\t.bind(credentialId)\n\t\t\t\t.first()) as\n\t\t\t\t| {\n\t\t\t\t\t\ttoken: string\n\t\t\t\t\t\tcredential_id: string\n\t\t\t\t\t\tcredential_public_key: string\n\t\t\t\t\t\tcounter: number\n\t\t\t\t\t\tcredential_device_type: string\n\t\t\t\t\t\tcredential_backed_up: number\n\t\t\t\t\t\ttransports: string | null\n\t\t\t\t\t\temail: string | null\n\t\t\t\t\t\tref_id: string | null\n\t\t\t\t\t\taaguid: string | null\n\t\t\t\t\t\tcreated_at: number\n\t\t\t\t\t\texpires_at: number\n\t\t\t\t }\n\t\t\t\t| null\n\n\t\t\tif (!row) return null\n\t\t\treturn {\n\t\t\t\ttoken: row.token,\n\t\t\t\tcredentialId: row.credential_id,\n\t\t\t\tcredentialPublicKey: row.credential_public_key,\n\t\t\t\tcounter: row.counter ?? 0,\n\t\t\t\tcredentialDeviceType: row.credential_device_type,\n\t\t\t\tcredentialBackedUp: (row.credential_backed_up ?? 0) === 1,\n\t\t\t\ttransports: row.transports ?? null,\n\t\t\t\temail: row.email ?? null,\n\t\t\t\trefId: row.ref_id ?? null,\n\t\t\t\taaguid: row.aaguid ?? null,\n\t\t\t\tcreatedAt: row.created_at ?? nowSec(),\n\t\t\t\texpiresAt: row.expires_at ?? nowSec(),\n\t\t\t} satisfies CorePassPendingRegistration\n\t\t},\n\n\t\tasync deletePendingRegistrationByToken(token) {\n\t\t\tawait db\n\t\t\t\t.prepare(`DELETE FROM corepass_pending_registrations WHERE token = ?1`)\n\t\t\t\t.bind(token)\n\t\t\t\t.run()\n\t\t},\n\n\t\tasync getIdentityByCoreId(coreId) {\n\t\t\tconst row = (await db\n\t\t\t\t.prepare(`SELECT core_id, user_id, ref_id FROM corepass_identities WHERE core_id = ?1`)\n\t\t\t\t.bind(coreId)\n\t\t\t\t.first()) as { core_id: string; user_id: string; ref_id: string | null } | null\n\t\t\tif (!row) return null\n\t\t\treturn { coreId: row.core_id, userId: row.user_id, refId: row.ref_id ?? null } satisfies CorePassUserIdentity\n\t\t},\n\n\t\tasync getIdentityByUserId(userId) {\n\t\t\tconst row = (await db\n\t\t\t\t.prepare(`SELECT core_id, user_id, ref_id FROM corepass_identities WHERE user_id = ?1`)\n\t\t\t\t.bind(userId)\n\t\t\t\t.first()) as { core_id: string; user_id: string; ref_id: string | null } | null\n\t\t\tif (!row) return null\n\t\t\treturn { coreId: row.core_id, userId: row.user_id, refId: row.ref_id ?? null } satisfies CorePassUserIdentity\n\t\t},\n\n\t\tasync upsertIdentity(identity) {\n\t\t\tawait db\n\t\t\t\t.prepare(\n\t\t\t\t\t`INSERT INTO corepass_identities (core_id, user_id, ref_id, created_at, updated_at)\n\t\t\t\t\tVALUES (?1, ?2, ?3, strftime('%s','now'), strftime('%s','now'))\n\t\t\t\t\tON CONFLICT(core_id) DO UPDATE SET\n\t\t\t\t\t\tuser_id = excluded.user_id,\n\t\t\t\t\t\tref_id = COALESCE(corepass_identities.ref_id, excluded.ref_id),\n\t\t\t\t\t\tupdated_at = strftime('%s','now')`\n\t\t\t\t)\n\t\t\t\t.bind(identity.coreId, identity.userId, identity.refId)\n\t\t\t\t.run()\n\t\t},\n\n\t\tasync upsertProfile(profile) {\n\t\t\tawait db\n\t\t\t\t.prepare(\n\t\t\t\t\t`INSERT INTO corepass_profiles\n\t\t\t\t\t(user_id, core_id, o18y, o21y, kyc, kyc_doc, provided_till, created_at, updated_at)\n\t\t\t\t\tVALUES\n\t\t\t\t\t(?1, ?2, ?3, ?4, ?5, ?6, ?7, strftime('%s','now'), strftime('%s','now'))\n\t\t\t\t\tON CONFLICT(user_id) DO UPDATE SET\n\t\t\t\t\t\tcore_id = excluded.core_id,\n\t\t\t\t\t\to18y = excluded.o18y,\n\t\t\t\t\t\to21y = excluded.o21y,\n\t\t\t\t\t\tkyc = excluded.kyc,\n\t\t\t\t\t\tkyc_doc = excluded.kyc_doc,\n\t\t\t\t\t\tprovided_till = excluded.provided_till,\n\t\t\t\t\t\tupdated_at = strftime('%s','now')`\n\t\t\t\t)\n\t\t\t\t.bind(\n\t\t\t\t\tprofile.userId,\n\t\t\t\t\tprofile.coreId,\n\t\t\t\t\tboolToDb(profile.o18y),\n\t\t\t\t\tboolToDb(profile.o21y),\n\t\t\t\t\tboolToDb(profile.kyc),\n\t\t\t\t\tprofile.kycDoc,\n\t\t\t\t\tprofile.providedTill\n\t\t\t\t)\n\t\t\t\t.run()\n\t\t},\n\t}\n}\n\n// -----------------------------\n// Postgres (node-postgres / any SQL client)\n// -----------------------------\n\nexport type PgLike = {\n\tquery: (text: string, params?: unknown[]) => Promise<{ rows: any[] }>\n}\n\nexport function postgresCorePassStore(pg: PgLike): CorePassStore {\n\treturn {\n\t\tasync createPendingRegistration(reg) {\n\t\t\tawait pg.query(\n\t\t\t\t`INSERT INTO corepass_pending_registrations\n\t\t\t\t(token, credential_id, credential_public_key, counter, credential_device_type, credential_backed_up, transports, email, ref_id, aaguid, created_at, expires_at)\n\t\t\t\tVALUES\n\t\t\t\t($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12)`,\n\t\t\t\t[\n\t\t\t\t\treg.token,\n\t\t\t\t\treg.credentialId,\n\t\t\t\t\treg.credentialPublicKey,\n\t\t\t\t\treg.counter,\n\t\t\t\t\treg.credentialDeviceType,\n\t\t\t\t\treg.credentialBackedUp,\n\t\t\t\t\treg.transports,\n\t\t\t\t\treg.email,\n\t\t\t\t\treg.refId,\n\t\t\t\t\treg.aaguid,\n\t\t\t\t\treg.createdAt,\n\t\t\t\t\treg.expiresAt,\n\t\t\t\t]\n\t\t\t)\n\t\t},\n\n\t\tasync getPendingRegistrationByCredentialId(credentialId) {\n\t\t\tconst res = await pg.query(\n\t\t\t\t`SELECT token, credential_id, credential_public_key, counter, credential_device_type, credential_backed_up, transports, email, ref_id, aaguid, created_at, expires_at\n\t\t\t\tFROM corepass_pending_registrations\n\t\t\t\tWHERE credential_id = $1`,\n\t\t\t\t[credentialId]\n\t\t\t)\n\t\t\tconst row = res.rows[0]\n\t\t\tif (!row) return null\n\t\t\treturn {\n\t\t\t\ttoken: row.token,\n\t\t\t\tcredentialId: row.credential_id,\n\t\t\t\tcredentialPublicKey: row.credential_public_key,\n\t\t\t\tcounter: Number(row.counter ?? 0),\n\t\t\t\tcredentialDeviceType: row.credential_device_type,\n\t\t\t\tcredentialBackedUp: Boolean(row.credential_backed_up),\n\t\t\t\ttransports: row.transports ?? null,\n\t\t\t\temail: row.email ?? null,\n\t\t\t\trefId: row.ref_id ?? null,\n\t\t\t\taaguid: row.aaguid ?? null,\n\t\t\t\tcreatedAt: Number(row.created_at ?? nowSec()),\n\t\t\t\texpiresAt: Number(row.expires_at ?? nowSec()),\n\t\t\t} satisfies CorePassPendingRegistration\n\t\t},\n\n\t\tasync deletePendingRegistrationByToken(token) {\n\t\t\tawait pg.query(`DELETE FROM corepass_pending_registrations WHERE token = $1`, [token])\n\t\t},\n\n\t\tasync getIdentityByCoreId(coreId) {\n\t\t\tconst res = await pg.query(\n\t\t\t\t`SELECT core_id, user_id, ref_id FROM corepass_identities WHERE core_id = $1`,\n\t\t\t\t[coreId]\n\t\t\t)\n\t\t\tconst row = res.rows[0]\n\t\t\tif (!row) return null\n\t\t\treturn { coreId: row.core_id, userId: row.user_id, refId: row.ref_id ?? null } satisfies CorePassUserIdentity\n\t\t},\n\n\t\tasync getIdentityByUserId(userId) {\n\t\t\tconst res = await pg.query(\n\t\t\t\t`SELECT core_id, user_id, ref_id FROM corepass_identities WHERE user_id = $1`,\n\t\t\t\t[userId]\n\t\t\t)\n\t\t\tconst row = res.rows[0]\n\t\t\tif (!row) return null\n\t\t\treturn { coreId: row.core_id, userId: row.user_id, refId: row.ref_id ?? null } satisfies CorePassUserIdentity\n\t\t},\n\n\t\tasync upsertIdentity(identity) {\n\t\t\tawait pg.query(\n\t\t\t\t`INSERT INTO corepass_identities (core_id, user_id, ref_id, created_at, updated_at)\n\t\t\t\tVALUES ($1,$2,$3, EXTRACT(EPOCH FROM NOW())::BIGINT, EXTRACT(EPOCH FROM NOW())::BIGINT)\n\t\t\t\tON CONFLICT (core_id) DO UPDATE SET\n\t\t\t\t\tuser_id = EXCLUDED.user_id,\n\t\t\t\t\tref_id = COALESCE(corepass_identities.ref_id, EXCLUDED.ref_id),\n\t\t\t\t\tupdated_at = EXTRACT(EPOCH FROM NOW())::BIGINT`,\n\t\t\t\t[identity.coreId, identity.userId, identity.refId]\n\t\t\t)\n\t\t},\n\n\t\tasync upsertProfile(profile) {\n\t\t\tawait pg.query(\n\t\t\t\t`INSERT INTO corepass_profiles (user_id, core_id, o18y, o21y, kyc, kyc_doc, provided_till, created_at, updated_at)\n\t\t\t\tVALUES ($1,$2,$3,$4,$5,$6,$7, EXTRACT(EPOCH FROM NOW())::BIGINT, EXTRACT(EPOCH FROM NOW())::BIGINT)\n\t\t\t\tON CONFLICT (user_id) DO UPDATE SET\n\t\t\t\t\tcore_id = EXCLUDED.core_id,\n\t\t\t\t\to18y = EXCLUDED.o18y,\n\t\t\t\t\to21y = EXCLUDED.o21y,\n\t\t\t\t\tkyc = EXCLUDED.kyc,\n\t\t\t\t\tkyc_doc = EXCLUDED.kyc_doc,\n\t\t\t\t\tprovided_till = EXCLUDED.provided_till,\n\t\t\t\t\tupdated_at = EXTRACT(EPOCH FROM NOW())::BIGINT`,\n\t\t\t\t[\n\t\t\t\t\tprofile.userId,\n\t\t\t\t\tprofile.coreId,\n\t\t\t\t\tprofile.o18y,\n\t\t\t\t\tprofile.o21y,\n\t\t\t\t\tprofile.kyc,\n\t\t\t\t\tprofile.kycDoc,\n\t\t\t\t\tprofile.providedTill,\n\t\t\t\t]\n\t\t\t)\n\t\t},\n\t}\n}\n\n// -----------------------------\n// Supabase (Postgres)\n// -----------------------------\n\nexport type SupabaseLike = {\n\tfrom: (table: string) => any\n}\n\nexport function supabaseCorePassStore(supabase: SupabaseLike): CorePassStore {\n\tconst tablePending = \"corepass_pending_registrations\"\n\tconst tableIdentities = \"corepass_identities\"\n\tconst tableProfiles = \"corepass_profiles\"\n\n\tconst maybeSingle = async (q: any) => {\n\t\tif (typeof q.maybeSingle === \"function\") return await q.maybeSingle()\n\t\treturn await q.single()\n\t}\n\n\treturn {\n\t\tasync createPendingRegistration(reg) {\n\t\t\tawait supabase.from(tablePending).insert({\n\t\t\t\ttoken: reg.token,\n\t\t\t\tcredential_id: reg.credentialId,\n\t\t\t\tcredential_public_key: reg.credentialPublicKey,\n\t\t\t\tcounter: reg.counter,\n\t\t\t\tcredential_device_type: reg.credentialDeviceType,\n\t\t\t\tcredential_backed_up: reg.credentialBackedUp,\n\t\t\t\ttransports: reg.transports,\n\t\t\t\temail: reg.email,\n\t\t\t\tref_id: reg.refId,\n\t\t\t\taaguid: reg.aaguid,\n\t\t\t\tcreated_at: reg.createdAt,\n\t\t\t\texpires_at: reg.expiresAt,\n\t\t\t})\n\t\t},\n\n\t\tasync getPendingRegistrationByCredentialId(credentialId) {\n\t\t\tconst res = await maybeSingle(\n\t\t\t\tsupabase\n\t\t\t\t\t.from(tablePending)\n\t\t\t\t\t.select(\n\t\t\t\t\t\t\"token, credential_id, credential_public_key, counter, credential_device_type, credential_backed_up, transports, email, ref_id, aaguid, created_at, expires_at\"\n\t\t\t\t\t)\n\t\t\t\t\t.eq(\"credential_id\", credentialId)\n\t\t\t)\n\t\t\tconst row = (res?.data ?? null) as any\n\t\t\tif (!row) return null\n\t\t\treturn {\n\t\t\t\ttoken: row.token,\n\t\t\t\tcredentialId: row.credential_id,\n\t\t\t\tcredentialPublicKey: row.credential_public_key,\n\t\t\t\tcounter: Number(row.counter ?? 0),\n\t\t\t\tcredentialDeviceType: row.credential_device_type,\n\t\t\t\tcredentialBackedUp: Boolean(row.credential_backed_up),\n\t\t\t\ttransports: row.transports ?? null,\n\t\t\t\temail: row.email ?? null,\n\t\t\t\trefId: row.ref_id ?? null,\n\t\t\t\taaguid: row.aaguid ?? null,\n\t\t\t\tcreatedAt: Number(row.created_at ?? nowSec()),\n\t\t\t\texpiresAt: Number(row.expires_at ?? nowSec()),\n\t\t\t} satisfies CorePassPendingRegistration\n\t\t},\n\n\t\tasync deletePendingRegistrationByToken(token) {\n\t\t\tawait supabase.from(tablePending).delete().eq(\"token\", token)\n\t\t},\n\n\t\tasync getIdentityByCoreId(coreId) {\n\t\t\tconst res = await maybeSingle(\n\t\t\t\tsupabase.from(tableIdentities).select(\"core_id, user_id, ref_id\").eq(\"core_id\", coreId)\n\t\t\t)\n\t\t\tconst row = (res?.data ?? null) as any\n\t\t\tif (!row) return null\n\t\t\treturn { coreId: row.core_id, userId: row.user_id, refId: row.ref_id ?? null } satisfies CorePassUserIdentity\n\t\t},\n\n\t\tasync getIdentityByUserId(userId) {\n\t\t\tconst res = await maybeSingle(\n\t\t\t\tsupabase.from(tableIdentities).select(\"core_id, user_id, ref_id\").eq(\"user_id\", userId)\n\t\t\t)\n\t\t\tconst row = (res?.data ?? null) as any\n\t\t\tif (!row) return null\n\t\t\treturn { coreId: row.core_id, userId: row.user_id, refId: row.ref_id ?? null } satisfies CorePassUserIdentity\n\t\t},\n\n\t\tasync upsertIdentity(identity) {\n\t\t\tawait supabase\n\t\t\t\t.from(tableIdentities)\n\t\t\t\t.upsert(\n\t\t\t\t\t{\n\t\t\t\t\t\tcore_id: identity.coreId,\n\t\t\t\t\t\tuser_id: identity.userId,\n\t\t\t\t\t\tref_id: identity.refId,\n\t\t\t\t\t\tupdated_at: nowSec(),\n\t\t\t\t\t},\n\t\t\t\t\t{ onConflict: \"core_id\" }\n\t\t\t\t)\n\t\t},\n\n\t\tasync upsertProfile(profile) {\n\t\t\tawait supabase\n\t\t\t\t.from(tableProfiles)\n\t\t\t\t.upsert(\n\t\t\t\t\t{\n\t\t\t\t\t\tuser_id: profile.userId,\n\t\t\t\t\t\tcore_id: profile.coreId,\n\t\t\t\t\t\to18y: profile.o18y,\n\t\t\t\t\t\to21y: profile.o21y,\n\t\t\t\t\t\tkyc: profile.kyc,\n\t\t\t\t\t\tkyc_doc: profile.kycDoc,\n\t\t\t\t\t\tprovided_till: profile.providedTill,\n\t\t\t\t\t\tupdated_at: nowSec(),\n\t\t\t\t\t},\n\t\t\t\t\t{ onConflict: \"user_id\" }\n\t\t\t\t)\n\t\t},\n\t}\n}\n","import { createCorePassServer } from \"./create-corepass-server.js\"\nimport { d1CorePassStore, postgresCorePassStore, supabaseCorePassStore } from \"./stores.js\"\nimport type { CreateCorePassServerOptions } from \"./types.js\"\nimport type { D1Like, PgLike, SupabaseLike } from \"./stores.js\"\nimport {\n\tkvChallengeStore,\n\tredisChallengeStore,\n\tupstashRedisChallengeStore,\n\tvercelKvChallengeStore,\n\ttype KvLike,\n\ttype RedisLike,\n\ttype UpstashRedisLike,\n\ttype VercelKvLike,\n} from \"./challenge-stores.js\"\n\ntype WithoutStore<T> = Omit<T, \"store\">\ntype WithoutStoreAndChallengeStore<T> = Omit<T, \"store\" | \"challengeStore\">\n\nexport function createCorePassServerD1(\n\toptions: WithoutStore<CreateCorePassServerOptions> & { db: D1Like }\n) {\n\tconst { db, ...rest } = options\n\treturn createCorePassServer({ ...rest, store: d1CorePassStore(db) })\n}\n\nexport function createCorePassServerPostgres(\n\toptions: WithoutStore<CreateCorePassServerOptions> & { pg: PgLike }\n) {\n\tconst { pg, ...rest } = options\n\treturn createCorePassServer({ ...rest, store: postgresCorePassStore(pg) })\n}\n\nexport function createCorePassServerSupabase(\n\toptions: WithoutStore<CreateCorePassServerOptions> & { supabase: SupabaseLike }\n) {\n\tconst { supabase, ...rest } = options\n\treturn createCorePassServer({ ...rest, store: supabaseCorePassStore(supabase) })\n}\n\n/**\n * Popular stack factory: Cloudflare Workers (D1 + KV)\n */\nexport function createCorePassServerCloudflareD1Kv(\n\toptions: WithoutStoreAndChallengeStore<CreateCorePassServerOptions> & { db: D1Like; kv: KvLike }\n) {\n\tconst { db, kv, ...rest } = options\n\treturn createCorePassServer({\n\t\t...rest,\n\t\tstore: d1CorePassStore(db),\n\t\tchallengeStore: kvChallengeStore(kv),\n\t})\n}\n\n/**\n * Popular stack factory: Postgres + Redis\n */\nexport function createCorePassServerPostgresRedis(\n\toptions: WithoutStoreAndChallengeStore<CreateCorePassServerOptions> & { pg: PgLike; redis: RedisLike }\n) {\n\tconst { pg, redis, ...rest } = options\n\treturn createCorePassServer({\n\t\t...rest,\n\t\tstore: postgresCorePassStore(pg),\n\t\tchallengeStore: redisChallengeStore(redis),\n\t})\n}\n\n/**\n * Popular stack factory: Supabase (Postgres) + Upstash Redis REST\n */\nexport function createCorePassServerSupabaseUpstash(\n\toptions: WithoutStoreAndChallengeStore<CreateCorePassServerOptions> & {\n\t\tsupabase: SupabaseLike\n\t\tredis: UpstashRedisLike\n\t}\n) {\n\tconst { supabase, redis, ...rest } = options\n\treturn createCorePassServer({\n\t\t...rest,\n\t\tstore: supabaseCorePassStore(supabase),\n\t\tchallengeStore: upstashRedisChallengeStore(redis),\n\t})\n}\n\n/**\n * Popular stack factory: Supabase (Postgres) + Vercel KV\n */\nexport function createCorePassServerSupabaseVercelKv(\n\toptions: WithoutStoreAndChallengeStore<CreateCorePassServerOptions> & {\n\t\tsupabase: SupabaseLike\n\t\tkv: VercelKvLike\n\t}\n) {\n\tconst { supabase, kv, ...rest } = options\n\treturn createCorePassServer({\n\t\t...rest,\n\t\tstore: supabaseCorePassStore(supabase),\n\t\tchallengeStore: vercelKvChallengeStore(kv),\n\t})\n}\n"],"mappings":";;;;;AAAA,OAAO,cA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B,GAAG;AAAA,IACH,OAAO,sBAAsB,QAAQ;AAAA,IACrC,gBAAgB,uBAAuB,EAAE;AAAA,EAC1C,CAAC;AACF;","names":["isHex","hexToBytes","nowSec","nowSec"]}
|
|
1
|
+
{"version":3,"sources":["../src/server/create-corepass-server.ts","../src/server/base64.ts","../src/server/canonical-json.ts","../src/server/cookies.ts","../src/server/coreid.ts","../src/server/ed448.ts","../src/server/aaguid.ts","../src/server/challenge-stores.ts","../src/server/stores.ts","../src/server/factories.ts"],"sourcesContent":["import WebAuthn from \"@auth/core/providers/webauthn\"\nimport type { AdapterAccount, AdapterAuthenticator, AdapterUser } from \"@auth/core/adapters\"\n\nimport { base64UrlToBytes, bytesToBase64, bytesToBase64Url, normalizeCredentialId } from \"./base64.js\"\nimport { canonicalizeForSignature, canonicalizeJSON } from \"./canonical-json.js\"\nimport { parseCookies, serializeCookie } from \"./cookies.js\"\nimport { deriveEd448PublicKeyFromCoreId, validateCoreIdMainnet } from \"./coreid.js\"\nimport { parseEd448Signature, verifyEd448Signature } from \"./ed448.js\"\nimport { extractAaguidFromAttestationObject, validateAaguidAllowlist } from \"./aaguid.js\"\n\nimport type {\n\tCorePassFinalizeArgs,\n\tCorePassFinalizeResult,\n\tCorePassPendingRegistration,\n\tCreateCorePassServerOptions,\n} from \"./types.js\"\n\nconst COREPASS_DEFAULT_AAGUID = \"636f7265-7061-7373-6964-656e74696679\"\n\nfunction nowMs(): number {\n\treturn Date.now()\n}\n\nfunction nowSec(): number {\n\treturn Math.floor(nowMs() / 1000)\n}\n\nfunction nowUs(): number {\n\treturn nowMs() * 1000\n}\n\nfunction json(status: number, body: unknown, headers?: HeadersInit): Response {\n\treturn new Response(JSON.stringify(body), {\n\t\tstatus,\n\t\theaders: { \"content-type\": \"application/json\", ...(headers ?? {}) },\n\t})\n}\n\nfunction randomBytes(n: number): Uint8Array {\n\tconst a = new Uint8Array(n)\n\tcrypto.getRandomValues(a)\n\treturn a\n}\n\nfunction randomChallenge(): string {\n\treturn bytesToBase64Url(randomBytes(32))\n}\n\nfunction parseEmail(input: unknown): string | null {\n\tif (typeof input !== \"string\") return null\n\tconst email = input.trim()\n\tif (!email) return null\n\tif (!/^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/.test(email)) return null\n\treturn email\n}\n\nfunction parseBool(input: unknown): boolean | null {\n\tif (input === undefined || input === null) return null\n\tif (typeof input === \"boolean\") return input\n\tif (typeof input === \"number\") return input === 1 ? true : input === 0 ? false : null\n\tif (typeof input === \"string\") {\n\t\tconst v = input.trim().toLowerCase()\n\t\tif (v === \"true\" || v === \"1\" || v === \"yes\") return true\n\t\tif (v === \"false\" || v === \"0\" || v === \"no\") return false\n\t}\n\treturn null\n}\n\nfunction parseDataExpMinutes(input: unknown): number | null {\n\tif (input === undefined || input === null) return null\n\tconst n = typeof input === \"number\" ? input : parseInt(String(input), 10)\n\tif (!Number.isFinite(n)) return null\n\tif (n <= 0) return null\n\treturn Math.floor(n)\n}\n\nfunction computeProvidedTillFromDataExp(dataExpMinutes: number | null): number | null {\n\tif (dataExpMinutes === null) return null\n\treturn nowSec() + dataExpMinutes * 60\n}\n\nfunction transportsToString(transports: unknown): string | null {\n\tif (!Array.isArray(transports)) return null\n\tconst items = transports.filter((t) => typeof t === \"string\") as string[]\n\treturn items.length ? items.join(\",\") : null\n}\n\nasync function finalizeToAuthJs(\n\toptions: CreateCorePassServerOptions,\n\targs: CorePassFinalizeArgs\n): Promise<CorePassFinalizeResult> {\n\tconst providerId = options.providerId ?? \"corepass\"\n\tconst { adapter, store } = options\n\tconst enableRefId = options.enableRefId ?? false\n\n\t// 1) Find or create user by CoreID mapping\n\tlet identity = await store.getIdentityByCoreId(args.coreId)\n\tlet user: AdapterUser | null = identity ? await adapter.getUser(identity.userId) : null\n\n\tif (!identity || !user) {\n\t\tconst emailRequired = options.emailRequired ?? false\n\t\tif (emailRequired && !args.email) throw new Error(\"Missing email\")\n\n\t\tuser = await adapter.createUser({\n\t\t\t// Most adapters will ignore provided id and generate their own.\n\t\t\t// CoreID is stored in corepass_identities instead.\n\t\t\temail: args.email ?? undefined,\n\t\t\temailVerified: null,\n\t\t\tname: args.coreId.toUpperCase(),\n\t\t\timage: null,\n\t\t} as any)\n\n\t\tconst refId = enableRefId ? args.refId ?? crypto.randomUUID() : null\n\t\tidentity = { coreId: args.coreId, userId: user.id, refId }\n\t\tawait store.upsertIdentity(identity)\n\t} else {\n\t\t// Keep refId if newly available\n\t\tif (enableRefId && args.refId && !identity.refId) {\n\t\t\tidentity = { ...identity, refId: args.refId }\n\t\t\tawait store.upsertIdentity(identity)\n\t\t}\n\t\tif (enableRefId && !identity.refId) {\n\t\t\tidentity = { ...identity, refId: crypto.randomUUID() }\n\t\t\tawait store.upsertIdentity(identity)\n\t\t}\n\t}\n\n\t// 2) Update user email if we have it and it differs\n\tif (args.email && user.email !== args.email) {\n\t\tuser = await adapter.updateUser({ id: user.id, email: args.email } as any)\n\t}\n\n\t// 3) Link the WebAuthn account (providerAccountId = credentialId base64)\n\tconst providerAccountId = args.credentialId\n\tconst existingUserByAccount = await adapter.getUserByAccount({\n\t\tprovider: providerId,\n\t\tproviderAccountId,\n\t})\n\tif (existingUserByAccount && existingUserByAccount.id !== user.id) {\n\t\tthrow new Error(\"Credential already linked to a different user\")\n\t}\n\n\tconst account: AdapterAccount = {\n\t\tuserId: user.id,\n\t\tprovider: providerId,\n\t\tproviderAccountId,\n\t\ttype: \"webauthn\",\n\t}\n\tif (!existingUserByAccount) {\n\t\tawait adapter.linkAccount(account)\n\t}\n\n\t// 4) Create authenticator (idempotent best-effort; adapter may enforce uniqueness)\n\tconst existingAuthenticator = await adapter.getAuthenticator(providerAccountId)\n\tif (!existingAuthenticator) {\n\t\tawait adapter.createAuthenticator({\n\t\t\t...args.authenticator,\n\t\t\tuserId: user.id,\n\t\t} as AdapterAuthenticator)\n\t}\n\n\t// 5) Store CorePass profile metadata (optional)\n\tawait store.upsertProfile({\n\t\tuserId: user.id,\n\t\tcoreId: args.coreId,\n\t\to18y: args.o18y,\n\t\to21y: args.o21y,\n\t\tkyc: args.kyc,\n\t\tkycDoc: args.kycDoc,\n\t\tprovidedTill: computeProvidedTillFromDataExp(args.dataExpMinutes),\n\t})\n\n\treturn { userId: user.id, account }\n}\n\nexport function createCorePassServer(options: CreateCorePassServerOptions) {\n\tconst cookieName = \"corepass.sid\"\n\n\tconst pendingTtlSeconds = options.pendingTtlSeconds ?? 600\n\tconst emailRequired = options.emailRequired ?? false\n\tconst requireO18y = options.requireO18y ?? false\n\tconst requireO21y = options.requireO21y ?? false\n\tconst requireKyc = options.requireKyc ?? false\n\tconst enableRefId = options.enableRefId ?? false\n\tconst postRegistrationWebhooks = options.postRegistrationWebhooks ?? false\n\tconst registrationWebhookUrl = options.registrationWebhookUrl\n\tconst registrationWebhookSecret = options.registrationWebhookSecret\n\tconst registrationWebhookRetriesRaw = options.registrationWebhookRetries ?? 3\n\n\tconst postLoginWebhooks = options.postLoginWebhooks ?? false\n\tconst loginWebhookUrl = options.loginWebhookUrl\n\tconst loginWebhookSecret = options.loginWebhookSecret\n\tconst loginWebhookRetriesRaw = options.loginWebhookRetries ?? 3\n\n\tconst postLogoutWebhooks = options.postLogoutWebhooks ?? false\n\tconst logoutWebhookUrl = options.logoutWebhookUrl\n\tconst logoutWebhookSecret = options.logoutWebhookSecret\n\tconst logoutWebhookRetriesRaw = options.logoutWebhookRetries ?? 3\n\tconst signaturePath = options.signaturePath ?? \"/passkey/data\"\n\tconst timestampWindowMs = options.timestampWindowMs ?? 10 * 60 * 1000\n\tconst timestampFutureSkewMs = options.timestampFutureSkewMs ?? 2 * 60 * 1000\n\tconst allowedAaguids = options.allowedAaguids ?? COREPASS_DEFAULT_AAGUID\n\tconst pubKeyCredAlgs = options.pubKeyCredAlgs ?? [-257, -7, -8]\n\tconst allowImmediateFinalize = options.allowImmediateFinalize ?? false\n\tconst challengeStore = options.challengeStore ?? null\n\tconst useChallengeCookie = allowImmediateFinalize && !challengeStore\n\tif (!challengeStore && !useChallengeCookie) {\n\t\tthrow new Error(\n\t\t\t\"createCorePassServer: challengeStore is required when allowImmediateFinalize is not true\"\n\t\t)\n\t}\n\tif (useChallengeCookie && !options.secret) {\n\t\tthrow new Error(\n\t\t\t\"createCorePassServer: secret is required when allowImmediateFinalize is true and challengeStore is not provided (challenge is stored in a signed cookie)\"\n\t\t)\n\t}\n\tconst challengeCookieSecret = useChallengeCookie ? options.secret! : \"\"\n\n\tconst sw = WebAuthn({}).simpleWebAuthn\n\n\tif (postRegistrationWebhooks && !registrationWebhookUrl) {\n\t\tthrow new Error(\n\t\t\t\"createCorePassServer: postRegistrationWebhooks=true requires registrationWebhookUrl\"\n\t\t)\n\t}\n\tif (postLoginWebhooks && !loginWebhookUrl) {\n\t\tthrow new Error(\"createCorePassServer: postLoginWebhooks=true requires loginWebhookUrl\")\n\t}\n\tif (postLoginWebhooks && typeof options.store.getIdentityByUserId !== \"function\") {\n\t\tthrow new Error(\n\t\t\t\"createCorePassServer: postLoginWebhooks=true requires store.getIdentityByUserId(userId)\"\n\t\t)\n\t}\n\tif (postLogoutWebhooks && !logoutWebhookUrl) {\n\t\tthrow new Error(\"createCorePassServer: postLogoutWebhooks=true requires logoutWebhookUrl\")\n\t}\n\tif (postLogoutWebhooks && typeof options.store.getIdentityByUserId !== \"function\") {\n\t\tthrow new Error(\n\t\t\t\"createCorePassServer: postLogoutWebhooks=true requires store.getIdentityByUserId(userId)\"\n\t\t)\n\t}\n\n\tif (\n\t\t!Number.isInteger(registrationWebhookRetriesRaw) ||\n\t\tregistrationWebhookRetriesRaw < 1 ||\n\t\tregistrationWebhookRetriesRaw > 10\n\t) {\n\t\tthrow new Error(\n\t\t\t\"createCorePassServer: registrationWebhookRetries must be an integer between 1 and 10\"\n\t\t)\n\t}\n\tif (!Number.isInteger(loginWebhookRetriesRaw) || loginWebhookRetriesRaw < 1 || loginWebhookRetriesRaw > 10) {\n\t\tthrow new Error(\"createCorePassServer: loginWebhookRetries must be an integer between 1 and 10\")\n\t}\n\tif (\n\t\t!Number.isInteger(logoutWebhookRetriesRaw) ||\n\t\tlogoutWebhookRetriesRaw < 1 ||\n\t\tlogoutWebhookRetriesRaw > 10\n\t) {\n\t\tthrow new Error(\"createCorePassServer: logoutWebhookRetries must be an integer between 1 and 10\")\n\t}\n\tconst registrationWebhookRetries = registrationWebhookRetriesRaw\n\tconst loginWebhookRetries = loginWebhookRetriesRaw\n\tconst logoutWebhookRetries = logoutWebhookRetriesRaw\n\n\tconst sleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms))\n\tconst retryDelayMs = (attempt: number) => Math.min(2000, 200 * 2 ** (attempt - 1))\n\n\tconst hmacSha256Hex = async (secret: string, message: string): Promise<string> => {\n\t\tconst key = await crypto.subtle.importKey(\n\t\t\t\"raw\",\n\t\t\tnew TextEncoder().encode(secret),\n\t\t\t{ name: \"HMAC\", hash: \"SHA-256\" },\n\t\t\tfalse,\n\t\t\t[\"sign\"]\n\t\t)\n\t\tconst sig = await crypto.subtle.sign(\"HMAC\", key, new TextEncoder().encode(message))\n\t\treturn [...new Uint8Array(sig)].map((b) => b.toString(16).padStart(2, \"0\")).join(\"\")\n\t}\n\n\tasync function signChallengeCookie(payload: { sid: string; challenge: string; email: string | null; refId: string | null }): Promise<string> {\n\t\tconst b64 = bytesToBase64Url(new TextEncoder().encode(JSON.stringify(payload)))\n\t\tconst sig = await hmacSha256Hex(challengeCookieSecret, b64)\n\t\treturn `${b64}.${sig}`\n\t}\n\n\tasync function verifyChallengeCookie(value: string): Promise<{ challenge: string; email: string | null; refId: string | null } | null> {\n\t\tconst dot = value.indexOf(\".\")\n\t\tif (dot <= 0) return null\n\t\tconst b64 = value.slice(0, dot)\n\t\tconst sig = value.slice(dot + 1)\n\t\tconst expectedSig = await hmacSha256Hex(challengeCookieSecret, b64)\n\t\tif (sig !== expectedSig) return null\n\t\ttry {\n\t\t\tconst json = new TextDecoder().decode(base64UrlToBytes(b64))\n\t\t\tconst payload = JSON.parse(json) as { sid?: string; challenge?: string; email?: string | null; refId?: string | null }\n\t\t\tif (typeof payload.challenge !== \"string\") return null\n\t\t\treturn {\n\t\t\t\tchallenge: payload.challenge,\n\t\t\t\temail: payload.email ?? null,\n\t\t\t\trefId: payload.refId ?? null,\n\t\t\t}\n\t\t} catch {\n\t\t\treturn null\n\t\t}\n\t}\n\n\tfunction withClearChallengeCookieIfUsed(res: Response): Response {\n\t\tif (!useChallengeCookie) return res\n\t\tconst clearCookie = serializeCookie(cookieName, \"\", { path: \"/\", maxAge: 0 })\n\t\tconst headers = new Headers(res.headers)\n\t\theaders.append(\"set-cookie\", clearCookie)\n\t\treturn new Response(res.body, { status: res.status, headers })\n\t}\n\n\tasync function postWebhook(args: {\n\t\turl: string\n\t\tsecret?: string\n\t\tretries: number\n\t\tpayload: Record<string, unknown>\n\t}): Promise<void> {\n\t\tconst { url, secret, retries, payload } = args\n\t\tconst body = JSON.stringify(payload)\n\n\t\tfor (let attempt = 1; attempt <= retries; attempt++) {\n\t\t\ttry {\n\t\t\t\tconst headers: Record<string, string> = { \"content-type\": \"application/json\" }\n\t\t\t\tif (secret) {\n\t\t\t\t\tconst ts = String(nowSec())\n\t\t\t\t\tconst signatureInput = `${ts}\\n${body}`\n\t\t\t\t\tconst sigHex = await hmacSha256Hex(secret, signatureInput)\n\t\t\t\t\theaders[\"X-Webhook-Timestamp\"] = ts\n\t\t\t\t\theaders[\"X-Webhook-Signature\"] = `sha256=${sigHex}`\n\t\t\t\t}\n\n\t\t\t\tconst res = await fetch(url, {\n\t\t\t\t\tmethod: \"POST\",\n\t\t\t\t\theaders,\n\t\t\t\t\tbody,\n\t\t\t\t})\n\t\t\t\tif (res.ok) return\n\t\t\t} catch {\n\t\t\t\t// retry below\n\t\t\t}\n\n\t\t\tif (attempt < retries) {\n\t\t\t\tawait sleep(retryDelayMs(attempt))\n\t\t\t}\n\t\t}\n\t}\n\n\tasync function maybePostRegistrationWebhook(args: { coreId: string; refId: string | null }): Promise<void> {\n\t\tif (!postRegistrationWebhooks || !registrationWebhookUrl) return\n\t\tconst payload: Record<string, unknown> = { coreId: args.coreId }\n\t\tif (args.refId) payload.refId = args.refId\n\t\tawait postWebhook({\n\t\t\turl: registrationWebhookUrl,\n\t\t\tretries: registrationWebhookRetries,\n\t\t\tpayload,\n\t\t\t...(registrationWebhookSecret ? { secret: registrationWebhookSecret } : {}),\n\t\t})\n\t}\n\n\tasync function postLoginWebhook(args: { userId: string }): Promise<void> {\n\t\tif (!postLoginWebhooks || !loginWebhookUrl) return\n\t\tconst identity = await options.store.getIdentityByUserId?.(args.userId)\n\t\tif (!identity) return\n\t\tconst payload: Record<string, unknown> = { coreId: identity.coreId }\n\t\tif (identity.refId) payload.refId = identity.refId\n\t\tawait postWebhook({\n\t\t\turl: loginWebhookUrl,\n\t\t\tretries: loginWebhookRetries,\n\t\t\tpayload,\n\t\t\t...(loginWebhookSecret ? { secret: loginWebhookSecret } : {}),\n\t\t})\n\t}\n\n\tasync function postLogoutWebhook(args: { userId: string }): Promise<void> {\n\t\tif (!postLogoutWebhooks || !logoutWebhookUrl) return\n\t\tconst identity = await options.store.getIdentityByUserId?.(args.userId)\n\t\tif (!identity) return\n\t\tconst payload: Record<string, unknown> = { coreId: identity.coreId }\n\t\tif (identity.refId) payload.refId = identity.refId\n\t\tawait postWebhook({\n\t\t\turl: logoutWebhookUrl,\n\t\t\tretries: logoutWebhookRetries,\n\t\t\tpayload,\n\t\t\t...(logoutWebhookSecret ? { secret: logoutWebhookSecret } : {}),\n\t\t})\n\t}\n\n\tasync function startRegistration(req: Request): Promise<Response> {\n\t\tconst body = (await req.json().catch(() => null)) as any\n\t\tconst email = parseEmail(body?.email)\n\t\tconst refId =\n\t\t\tenableRefId && typeof body?.refId === \"string\" ? body.refId.trim() || null : null\n\n\t\tif (body?.email !== undefined && body?.email !== null && !email) {\n\t\t\treturn json(400, { ok: false, error: \"Invalid email\" })\n\t\t}\n\n\t\tconst challenge = randomChallenge()\n\t\tconst sid = crypto.randomUUID()\n\n\t\tif (challengeStore) {\n\t\t\tawait challengeStore.put(\n\t\t\t\t`reg:${sid}`,\n\t\t\t\tJSON.stringify({ challenge, email, refId }),\n\t\t\t\tpendingTtlSeconds\n\t\t\t)\n\t\t}\n\n\t\tconst attestationType = options.attestationType ?? \"none\"\n\t\tconst authenticatorAttachment = options.authenticatorAttachment ?? \"cross-platform\"\n\t\tconst residentKey = options.residentKey ?? \"preferred\"\n\t\tconst userVerification = options.userVerification ?? \"required\"\n\t\tconst registrationTimeout = options.registrationTimeout ?? 60_000\n\n\t\tconst creationOptions = await sw.generateRegistrationOptions({\n\t\t\trpID: options.rpID,\n\t\t\trpName: options.rpName,\n\t\t\tuserID: randomBytes(32),\n\t\t\tuserName: email ?? \"CorePass\",\n\t\t\tuserDisplayName: email ?? \"CorePass User\",\n\t\t\tchallenge,\n\t\t\tpubKeyCredParams: pubKeyCredAlgs.map((alg) => ({ alg, type: \"public-key\" })),\n\t\t\tauthenticatorSelection: {\n\t\t\t\tauthenticatorAttachment,\n\t\t\t\tresidentKey,\n\t\t\t\tuserVerification,\n\t\t\t},\n\t\t\tattestationType,\n\t\t\ttimeout: registrationTimeout,\n\t\t\texcludeCredentials: [],\n\t\t})\n\n\t\tconst cookieValue = challengeStore\n\t\t\t? sid\n\t\t\t: await signChallengeCookie({ sid, challenge, email, refId })\n\t\treturn json(200, creationOptions, {\n\t\t\t\"set-cookie\": serializeCookie(cookieName, cookieValue, {\n\t\t\t\thttpOnly: true,\n\t\t\t\tsecure: true,\n\t\t\t\tsameSite: \"Lax\",\n\t\t\t\tpath: \"/\",\n\t\t\t\tmaxAge: pendingTtlSeconds,\n\t\t\t}),\n\t\t})\n\t}\n\n\tasync function finishRegistration(req: Request): Promise<Response> {\n\t\tconst body = (await req.json().catch(() => null)) as any\n\t\tconst attestation = body?.attestation as any\n\t\tif (!attestation) return withClearChallengeCookieIfUsed(json(400, { ok: false, error: \"Bad request\" }))\n\n\t\tconst cookies = parseCookies(req.headers.get(\"cookie\"))\n\t\tconst cookieVal = cookies[cookieName]\n\t\tif (!cookieVal) return withClearChallengeCookieIfUsed(json(400, { ok: false, error: \"No session\" }))\n\n\t\tlet saved: { challenge: string; email: string | null; refId: string | null }\n\t\tif (challengeStore) {\n\t\t\tconst sid = cookieVal\n\t\t\tconst raw = await challengeStore.get(`reg:${sid}`)\n\t\t\tif (!raw) return withClearChallengeCookieIfUsed(json(400, { ok: false, error: \"Challenge expired\" }))\n\t\t\tawait challengeStore.delete(`reg:${sid}`)\n\t\t\tsaved = JSON.parse(raw) as { challenge: string; email: string | null; refId: string | null }\n\t\t} else {\n\t\t\tconst payload = await verifyChallengeCookie(cookieVal)\n\t\t\tif (!payload) return withClearChallengeCookieIfUsed(json(400, { ok: false, error: \"Challenge expired or invalid\" }))\n\t\t\tsaved = payload\n\t\t}\n\t\tconst expectedChallenge = saved.challenge\n\n\t\t// Validate AAGUID allowlist (CorePass app gate)\n\t\tconst aaguid = extractAaguidFromAttestationObject((attestation as any)?.response?.attestationObject)\n\t\tif (!validateAaguidAllowlist(aaguid, allowedAaguids)) {\n\t\t\treturn withClearChallengeCookieIfUsed(json(400, {\n\t\t\t\tok: false,\n\t\t\t\terror: \"AAGUID not allowed\",\n\t\t\t\taaguid,\n\t\t\t\tallowedAaguids: allowedAaguids ?? null,\n\t\t\t}))\n\t\t}\n\n\t\tconst requireUserVerification = options.userVerification !== \"discouraged\"\n\t\tlet verification: Awaited<ReturnType<(typeof sw)[\"verifyRegistrationResponse\"]>>\n\t\ttry {\n\t\t\tverification = await sw.verifyRegistrationResponse({\n\t\t\t\tresponse: attestation,\n\t\t\t\texpectedChallenge,\n\t\t\t\texpectedOrigin: options.expectedOrigin,\n\t\t\t\texpectedRPID: options.rpID,\n\t\t\t\trequireUserVerification,\n\t\t\t})\n\t\t} catch {\n\t\t\treturn withClearChallengeCookieIfUsed(json(400, { ok: false, error: \"Invalid registration response\" }))\n\t\t}\n\n\t\tif (!verification.verified || !verification.registrationInfo) {\n\t\t\treturn withClearChallengeCookieIfUsed(json(400, { ok: false, error: \"Registration not verified\" }))\n\t\t}\n\n\t\tconst credentialIdBase64 = bytesToBase64(verification.registrationInfo.credentialID)\n\t\tconst credentialPublicKeyBase64 = bytesToBase64(verification.registrationInfo.credentialPublicKey)\n\t\tconst transports = transportsToString((attestation as any)?.response?.transports)\n\n\t\tconst authenticator: Omit<AdapterAuthenticator, \"userId\"> = {\n\t\t\tproviderAccountId: credentialIdBase64,\n\t\t\tcredentialID: credentialIdBase64,\n\t\t\tcredentialPublicKey: credentialPublicKeyBase64,\n\t\t\tcounter: verification.registrationInfo.counter,\n\t\t\tcredentialDeviceType: verification.registrationInfo.credentialDeviceType,\n\t\t\tcredentialBackedUp: verification.registrationInfo.credentialBackedUp,\n\t\t\ttransports,\n\t\t}\n\n\t\tconst coreIdFromBody = typeof body?.coreId === \"string\" ? body.coreId.trim() : null\n\t\tconst allowImmediateFinalize = options.allowImmediateFinalize ?? false\n\n\t\tif (allowImmediateFinalize && coreIdFromBody) {\n\t\t\tif (!validateCoreIdMainnet(coreIdFromBody)) {\n\t\t\t\treturn withClearChallengeCookieIfUsed(json(400, { ok: false, error: \"Invalid Core ID (mainnet)\" }))\n\t\t\t}\n\n\t\t\tconst emailFromBody = parseEmail(body?.email)\n\t\t\tif (body?.email !== undefined && body?.email !== null && !emailFromBody) {\n\t\t\t\treturn withClearChallengeCookieIfUsed(json(400, { ok: false, error: \"Invalid email\" }))\n\t\t\t}\n\t\t\tconst finalEmail = emailFromBody || saved.email || null\n\t\t\tif (emailRequired && !finalEmail) return withClearChallengeCookieIfUsed(json(400, { ok: false, error: \"Missing email\" }))\n\n\t\t\tconst result = await finalizeToAuthJs(options, {\n\t\t\t\tcoreId: coreIdFromBody,\n\t\t\t\tcredentialId: credentialIdBase64,\n\t\t\t\tauthenticator,\n\t\t\t\temail: finalEmail,\n\t\t\t\trefId: enableRefId ? saved.refId : null,\n\t\t\t\to18y: parseBool(body?.o18y),\n\t\t\t\to21y: parseBool(body?.o21y),\n\t\t\t\tkyc: parseBool(body?.kyc),\n\t\t\t\tkycDoc: typeof body?.kycDoc === \"string\" ? body.kycDoc.trim() || null : null,\n\t\t\t\tdataExpMinutes: parseDataExpMinutes(body?.dataExp),\n\t\t\t})\n\n\t\t\tconst storedIdentity = await options.store.getIdentityByCoreId(coreIdFromBody)\n\t\t\tawait maybePostRegistrationWebhook({\n\t\t\t\tcoreId: coreIdFromBody,\n\t\t\t\trefId: enableRefId ? storedIdentity?.refId ?? null : null,\n\t\t\t})\n\n\t\t\treturn withClearChallengeCookieIfUsed(json(200, { ok: true, finalized: true, userId: result.userId, coreId: coreIdFromBody }))\n\t\t}\n\n\t\tconst token = crypto.randomUUID()\n\t\tconst createdAt = nowSec()\n\t\tconst expiresAt = createdAt + pendingTtlSeconds\n\t\tconst pending: CorePassPendingRegistration = {\n\t\t\ttoken,\n\t\t\tcredentialId: credentialIdBase64,\n\t\t\tcredentialPublicKey: credentialPublicKeyBase64,\n\t\t\tcounter: authenticator.counter,\n\t\t\tcredentialDeviceType: authenticator.credentialDeviceType,\n\t\t\tcredentialBackedUp: authenticator.credentialBackedUp,\n\t\t\ttransports: authenticator.transports ?? null,\n\t\t\temail: saved.email,\n\t\t\trefId: enableRefId ? saved.refId : null,\n\t\t\taaguid,\n\t\t\tcreatedAt,\n\t\t\texpiresAt,\n\t\t}\n\t\tawait options.store.createPendingRegistration(pending)\n\n\t\treturn withClearChallengeCookieIfUsed(json(200, {\n\t\t\tok: true,\n\t\t\tpending: true,\n\t\t\tenrichToken: token,\n\t\t\tcredentialId: credentialIdBase64,\n\t\t}))\n\t}\n\n\tasync function enrichRegistration(req: Request): Promise<Response> {\n\t\tconst rawBody = await req.text()\n\t\tlet body: any\n\t\ttry {\n\t\t\tbody = JSON.parse(rawBody)\n\t\t} catch {\n\t\t\treturn json(400, { ok: false, error: \"Invalid JSON\" })\n\t\t}\n\n\t\tconst coreId = typeof body?.coreId === \"string\" ? body.coreId.trim() : null\n\t\tconst credentialIdRaw = typeof body?.credentialId === \"string\" ? body.credentialId.trim() : null\n\t\tconst timestamp = body?.timestamp as unknown\n\t\tconst userData = body?.userData ?? {}\n\n\t\tif (!coreId || !credentialIdRaw || typeof timestamp !== \"number\") {\n\t\t\treturn json(400, { ok: false, error: \"Missing required fields: coreId, credentialId, timestamp\" })\n\t\t}\n\n\t\tif (!validateCoreIdMainnet(coreId)) {\n\t\t\treturn json(400, { ok: false, error: \"Invalid Core ID (mainnet)\" })\n\t\t}\n\n\t\tconst credentialIdNormalized = normalizeCredentialId(credentialIdRaw)\n\t\tif (!credentialIdNormalized) return json(400, { ok: false, error: \"Invalid credentialId encoding\" })\n\t\tconst credentialIdBase64 = credentialIdNormalized.base64\n\n\t\t// Timestamp must be integer microseconds since Unix epoch\n\t\tif (!Number.isSafeInteger(timestamp) || timestamp <= 0) {\n\t\t\treturn json(400, { ok: false, error: \"Invalid timestamp (microseconds)\" })\n\t\t}\n\n\t\tconst tNowUs = nowUs()\n\t\tconst windowUs = timestampWindowMs * 1000\n\t\tconst futureSkewUs = timestampFutureSkewMs * 1000\n\t\tif (tNowUs - timestamp > windowUs) return json(400, { ok: false, error: \"Timestamp too old\" })\n\t\tif (timestamp - tNowUs > futureSkewUs) return json(400, { ok: false, error: \"Timestamp too far in future\" })\n\n\t\tconst signatureHeader = req.headers.get(\"X-Signature\")\n\t\tif (!signatureHeader) return json(400, { ok: false, error: \"Missing X-Signature header\" })\n\n\t\tconst signatureBytes = parseEd448Signature(signatureHeader)\n\t\tif (!signatureBytes) return json(400, { ok: false, error: \"Invalid signature format\" })\n\t\tif (signatureBytes.length !== 114) return json(400, { ok: false, error: \"Invalid signature length\" })\n\n\t\tconst publicKeyBytes = deriveEd448PublicKeyFromCoreId(coreId)\n\t\tif (!publicKeyBytes) return json(400, { ok: false, error: \"Failed to derive public key from CoreID\" })\n\n\t\tconst canonicalBody = canonicalizeJSON(body)\n\t\tconst signatureInput = canonicalizeForSignature(\"POST\", signaturePath, canonicalBody)\n\t\tconst messageBytes = new TextEncoder().encode(signatureInput)\n\t\tconst valid = await verifyEd448Signature({ publicKeyBytes, messageBytes, signatureBytes })\n\t\tif (!valid) return json(400, { ok: false, error: \"Invalid signature\" })\n\n\t\tconst pending = await options.store.getPendingRegistrationByCredentialId(credentialIdBase64)\n\t\tif (!pending) return json(400, { ok: false, error: \"Pending registration not found\" })\n\n\t\tif (pending.expiresAt < nowSec()) {\n\t\t\tawait options.store.deletePendingRegistrationByToken(pending.token)\n\t\t\treturn json(400, { ok: false, error: \"Pending registration expired\" })\n\t\t}\n\n\t\tconst emailFromBody = parseEmail(userData?.email)\n\t\tconst o18yFromBody = parseBool(userData?.o18y)\n\t\tconst o21yFromBody = parseBool(userData?.o21y)\n\t\tconst kycFromBody = parseBool(userData?.kyc)\n\t\tconst kycDocFromBody = typeof userData?.kycDoc === \"string\" ? userData.kycDoc.trim() || null : null\n\t\tconst dataExpMinutes = parseDataExpMinutes(userData?.dataExp)\n\t\tconst refIdFromBody =\n\t\t\tenableRefId && typeof userData?.refId === \"string\" ? userData.refId.trim() || null : null\n\n\t\tconst failAndCleanup = async (status: number, error: string): Promise<Response> => {\n\t\t\tawait options.store.deletePendingRegistrationByToken(pending.token)\n\t\t\treturn json(status, { ok: false, error })\n\t\t}\n\n\t\t// Validate parsed fields (and cleanup pending on failure)\n\t\tif (userData?.email !== undefined && userData?.email !== null && !emailFromBody) {\n\t\t\treturn await failAndCleanup(400, \"Invalid email format\")\n\t\t}\n\t\tif (userData?.o18y !== undefined && userData?.o18y !== null && o18yFromBody === null) {\n\t\t\treturn await failAndCleanup(400, \"Invalid o18y\")\n\t\t}\n\t\tif (userData?.o21y !== undefined && userData?.o21y !== null && o21yFromBody === null) {\n\t\t\treturn await failAndCleanup(400, \"Invalid o21y\")\n\t\t}\n\t\tif (userData?.kyc !== undefined && userData?.kyc !== null && kycFromBody === null) {\n\t\t\treturn await failAndCleanup(400, \"Invalid kyc\")\n\t\t}\n\t\tif (userData?.dataExp !== undefined && userData?.dataExp !== null && dataExpMinutes === null) {\n\t\t\treturn await failAndCleanup(400, \"Invalid dataExp\")\n\t\t}\n\n\t\t// Policy gates (enrich/pending path only; not enforced for immediate-finalize)\n\t\tif (requireO18y && o18yFromBody !== true) {\n\t\t\treturn await failAndCleanup(403, \"o18y required\")\n\t\t}\n\t\tif (requireO21y && o21yFromBody !== true) {\n\t\t\treturn await failAndCleanup(403, \"o21y required\")\n\t\t}\n\t\tif (requireKyc && kycFromBody !== true) {\n\t\t\treturn await failAndCleanup(403, \"kyc required\")\n\t\t}\n\n\t\tconst finalEmail = emailFromBody || pending.email || null\n\t\tif (emailRequired && !finalEmail) {\n\t\t\tawait options.store.deletePendingRegistrationByToken(pending.token)\n\t\t\treturn json(400, { ok: false, error: \"Missing email\" })\n\t\t}\n\n\t\tconst refId = enableRefId ? refIdFromBody || pending.refId || null : null\n\n\t\tawait options.store.deletePendingRegistrationByToken(pending.token)\n\n\t\tconst authenticator: Omit<AdapterAuthenticator, \"userId\"> = {\n\t\t\tproviderAccountId: pending.credentialId,\n\t\t\tcredentialID: pending.credentialId,\n\t\t\tcredentialPublicKey: pending.credentialPublicKey,\n\t\t\tcounter: pending.counter,\n\t\t\tcredentialDeviceType: pending.credentialDeviceType,\n\t\t\tcredentialBackedUp: pending.credentialBackedUp,\n\t\t\ttransports: pending.transports,\n\t\t}\n\n\t\tconst result = await finalizeToAuthJs(options, {\n\t\t\tcoreId,\n\t\t\tcredentialId: pending.credentialId,\n\t\t\tauthenticator,\n\t\t\temail: finalEmail,\n\t\t\trefId,\n\t\t\to18y: o18yFromBody,\n\t\t\to21y: o21yFromBody,\n\t\t\tkyc: kycFromBody,\n\t\t\tkycDoc: kycDocFromBody,\n\t\t\tdataExpMinutes,\n\t\t})\n\n\t\tconst storedIdentity = await options.store.getIdentityByCoreId(coreId)\n\t\tawait maybePostRegistrationWebhook({ coreId, refId: storedIdentity?.refId ?? null })\n\n\t\treturn json(200, {\n\t\t\tok: true,\n\t\t\tcoreId,\n\t\t\temail: finalEmail,\n\t\t\tuserId: result.userId,\n\t\t})\n\t}\n\n\tfunction checkEnrichment(): Response {\n\t\tconst available = !(options.allowImmediateFinalize ?? false)\n\t\treturn new Response(null, { status: available ? 200 : 404 })\n\t}\n\n\treturn { startRegistration, finishRegistration, enrichRegistration, postLoginWebhook, postLogoutWebhook, checkEnrichment }\n}\n","function hasAtobBtoa(): boolean {\n\treturn typeof globalThis.atob === \"function\" && typeof globalThis.btoa === \"function\"\n}\n\nfunction bytesToBinaryString(bytes: Uint8Array): string {\n\tlet s = \"\"\n\tfor (let i = 0; i < bytes.length; i++) s += String.fromCharCode(bytes[i]!)\n\treturn s\n}\n\nfunction binaryStringToBytes(bin: string): Uint8Array {\n\tconst bytes = new Uint8Array(bin.length)\n\tfor (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i)\n\treturn bytes\n}\n\nexport function bytesToBase64(bytes: Uint8Array): string {\n\tif (hasAtobBtoa()) {\n\t\treturn globalThis.btoa(bytesToBinaryString(bytes))\n\t}\n\treturn Buffer.from(bytes).toString(\"base64\")\n}\n\nexport function base64ToBytes(base64: string): Uint8Array {\n\tif (hasAtobBtoa()) {\n\t\treturn binaryStringToBytes(globalThis.atob(base64))\n\t}\n\treturn new Uint8Array(Buffer.from(base64, \"base64\"))\n}\n\nexport function bytesToBase64Url(bytes: Uint8Array): string {\n\treturn bytesToBase64(bytes).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/g, \"\")\n}\n\nexport function base64UrlToBytes(base64url: string): Uint8Array {\n\tconst pad = \"=\".repeat((4 - (base64url.length % 4)) % 4)\n\tconst base64 = (base64url + pad).replace(/-/g, \"+\").replace(/_/g, \"/\")\n\treturn base64ToBytes(base64)\n}\n\nexport function tryDecodeBase64OrBase64Url(input: string): Uint8Array | null {\n\ttry {\n\t\tif (!input || typeof input !== \"string\") return null\n\t\tconst s = input.trim()\n\t\tif (!s) return null\n\n\t\tif (/^[0-9A-Za-z+/]+=*$/.test(s) && s.length % 4 === 0) {\n\t\t\treturn base64ToBytes(s)\n\t\t}\n\t\tif (/^[0-9A-Za-z_-]+$/.test(s)) {\n\t\t\treturn base64UrlToBytes(s)\n\t\t}\n\t\treturn null\n\t} catch {\n\t\treturn null\n\t}\n}\n\nexport function normalizeCredentialId(id: string): {\n\tbytes: Uint8Array\n\tbase64: string\n\tbase64url: string\n} | null {\n\tconst bytes = tryDecodeBase64OrBase64Url(id)\n\tif (!bytes) return null\n\treturn { bytes, base64: bytesToBase64(bytes), base64url: bytesToBase64Url(bytes) }\n}\n","function sortKeysRecursive(value: unknown): unknown {\n\tif (value === null || typeof value !== \"object\") return value\n\tif (Array.isArray(value)) return value.map(sortKeysRecursive)\n\n\tconst obj = value as Record<string, unknown>\n\tconst out: Record<string, unknown> = {}\n\tfor (const key of Object.keys(obj).sort()) {\n\t\tout[key] = sortKeysRecursive(obj[key])\n\t}\n\treturn out\n}\n\nexport function canonicalizeJSON(value: unknown): string {\n\treturn JSON.stringify(sortKeysRecursive(value))\n}\n\nexport function canonicalizeForSignature(method: string, path: string, canonicalBody: string): string {\n\treturn `${method}\\n${path}\\n${canonicalBody}`\n}\n","export function parseCookies(header: string | null): Record<string, string> {\n\tconst out: Record<string, string> = {}\n\tif (!header) return out\n\tfor (const part of header.split(\";\")) {\n\t\tconst [k, ...rest] = part.trim().split(\"=\")\n\t\tif (!k) continue\n\t\tout[k] = decodeURIComponent(rest.join(\"=\") || \"\")\n\t}\n\treturn out\n}\n\nexport type CookieOptions = {\n\thttpOnly?: boolean\n\tsecure?: boolean\n\tsameSite?: \"Lax\" | \"Strict\" | \"None\"\n\tpath?: string\n\tmaxAge?: number\n}\n\nexport function serializeCookie(name: string, value: string, options: CookieOptions = {}): string {\n\tconst attrs: string[] = [`${name}=${encodeURIComponent(value)}`]\n\tif (options.maxAge !== undefined) attrs.push(`Max-Age=${Math.floor(options.maxAge)}`)\n\tattrs.push(`Path=${options.path ?? \"/\"}`)\n\tif (options.httpOnly !== false) attrs.push(\"HttpOnly\")\n\tif (options.secure !== false) attrs.push(\"Secure\")\n\tif (options.sameSite) attrs.push(`SameSite=${options.sameSite}`)\n\treturn attrs.join(\"; \")\n}\n","import { validateWalletAddress } from \"blockchain-wallet-validator\"\n\nfunction isDigits2(s: string): boolean {\n\treturn /^[0-9]{2}$/.test(s)\n}\n\nfunction isHex(s: string): boolean {\n\treturn /^[0-9a-fA-F]+$/.test(s)\n}\n\nfunction hexToBytes(hex: string): Uint8Array | null {\n\tif (!hex || (hex.length % 2) !== 0) return null\n\tif (!isHex(hex)) return null\n\n\tconst bytes = new Uint8Array(hex.length / 2)\n\tfor (let i = 0; i < hex.length; i += 2) {\n\t\tbytes[i / 2] = parseInt(hex.slice(i, i + 2), 16)\n\t}\n\treturn bytes\n}\n\nexport function validateCoreIdMainnet(coreId: string): boolean {\n\ttry {\n\t\tif (typeof coreId !== \"string\" || !coreId.trim()) return false\n\t\tconst res = validateWalletAddress(coreId.trim(), { network: [\"xcb\"], testnet: false })\n\t\treturn !!(res && (res as any).isValid)\n\t} catch {\n\t\treturn false\n\t}\n}\n\nexport function parseCoreIdIcan(coreId: string): { prefix: \"cb\"; checksum: string; bban: string } | null {\n\tif (typeof coreId !== \"string\") return null\n\tconst s = coreId.trim()\n\tif (s.length < 5) return null\n\tconst prefix = s.slice(0, 2).toLowerCase()\n\tconst checksum = s.slice(2, 4)\n\tconst bban = s.slice(4)\n\n\tif (prefix !== \"cb\") return null\n\tif (!isDigits2(checksum)) return null\n\tif (!bban) return null\n\treturn { prefix: \"cb\", checksum, bban }\n}\n\n/**\n * Default CorePass derivation:\n * - Validate CoreID as mainnet ICAN\n * - Treat BBAN as hex encoding of the raw 57-byte Ed448 public key (114 hex chars)\n */\nexport function deriveEd448PublicKeyFromCoreId(coreId: string): Uint8Array | null {\n\tif (!validateCoreIdMainnet(coreId)) return null\n\tconst parts = parseCoreIdIcan(coreId)\n\tif (!parts) return null\n\n\tconst pk = hexToBytes(parts.bban)\n\tif (!pk) return null\n\tif (pk.length !== 57) return null\n\treturn pk\n}\n","import { ed448 } from \"@noble/curves/ed448.js\"\nimport { tryDecodeBase64OrBase64Url } from \"./base64.js\"\n\nfunction isHex(s: string): boolean {\n\treturn /^[0-9a-fA-F]+$/.test(s)\n}\n\nfunction hexToBytes(hex: string): Uint8Array | null {\n\tif (!hex || (hex.length % 2) !== 0) return null\n\tif (!isHex(hex)) return null\n\tconst bytes = new Uint8Array(hex.length / 2)\n\tfor (let i = 0; i < hex.length; i += 2) {\n\t\tbytes[i / 2] = parseInt(hex.slice(i, i + 2), 16)\n\t}\n\treturn bytes\n}\n\nexport function parseEd448Signature(signature: string): Uint8Array | null {\n\tif (typeof signature !== \"string\") return null\n\tconst s = signature.trim()\n\tif (!s) return null\n\n\tif (isHex(s)) return hexToBytes(s)\n\treturn tryDecodeBase64OrBase64Url(s)\n}\n\nasync function verifyWithWebCrypto(\n\tpublicKeyBytes: Uint8Array,\n\tmessageBytes: Uint8Array,\n\tsignatureBytes: Uint8Array\n): Promise<boolean> {\n\ttry {\n\t\tconst toArrayBuffer = (u8: Uint8Array): ArrayBuffer =>\n\t\t\tu8.buffer.slice(u8.byteOffset, u8.byteOffset + u8.byteLength) as ArrayBuffer\n\n\t\tconst key = await crypto.subtle.importKey(\n\t\t\t\"raw\",\n\t\t\ttoArrayBuffer(publicKeyBytes),\n\t\t\t{ name: \"Ed448\" },\n\t\t\tfalse,\n\t\t\t[\"verify\"]\n\t\t)\n\t\treturn await crypto.subtle.verify(\n\t\t\t{ name: \"Ed448\" },\n\t\t\tkey,\n\t\t\ttoArrayBuffer(signatureBytes),\n\t\t\ttoArrayBuffer(messageBytes)\n\t\t)\n\t} catch {\n\t\treturn false\n\t}\n}\n\nexport async function verifyEd448Signature(args: {\n\tpublicKeyBytes: Uint8Array\n\tmessageBytes: Uint8Array\n\tsignatureBytes: Uint8Array\n}): Promise<boolean> {\n\tconst { publicKeyBytes, messageBytes, signatureBytes } = args\n\tif (!(publicKeyBytes instanceof Uint8Array) || publicKeyBytes.length !== 57) return false\n\tif (!(signatureBytes instanceof Uint8Array) || signatureBytes.length !== 114) return false\n\tif (!(messageBytes instanceof Uint8Array)) return false\n\n\tif (crypto?.subtle) {\n\t\tconst ok = await verifyWithWebCrypto(publicKeyBytes, messageBytes, signatureBytes)\n\t\tif (ok) return true\n\t}\n\n\ttry {\n\t\treturn ed448.verify(signatureBytes, messageBytes, publicKeyBytes)\n\t} catch {\n\t\treturn false\n\t}\n}\n","import { decode as cborDecode } from \"cbor-x\"\nimport { base64UrlToBytes } from \"./base64.js\"\n\nfunction bytesToHex(bytes: Uint8Array): string {\n\treturn [...bytes].map((b) => b.toString(16).padStart(2, \"0\")).join(\"\")\n}\n\nfunction hexToUuid(hex32: string): string {\n\treturn [\n\t\thex32.slice(0, 8),\n\t\thex32.slice(8, 12),\n\t\thex32.slice(12, 16),\n\t\thex32.slice(16, 20),\n\t\thex32.slice(20),\n\t].join(\"-\")\n}\n\nfunction bytes16ToUuid(bytes16: Uint8Array): string {\n\treturn hexToUuid(bytesToHex(bytes16))\n}\n\n/**\n * Extract the AAGUID from a WebAuthn attestationObject (base64url).\n */\nexport function extractAaguidFromAttestationObject(attestationObjectB64Url?: string): string | null {\n\tif (!attestationObjectB64Url) return null\n\ttry {\n\t\tconst attestationBytes = base64UrlToBytes(attestationObjectB64Url)\n\t\tconst attObj = cborDecode(attestationBytes) as any\n\t\tconst authData: Uint8Array | undefined = attObj?.authData\n\t\tif (!authData || authData.length < 37) return null\n\n\t\tconst flags = authData[32] ?? 0\n\t\tconst AT_FLAG = 0x40\n\t\tif ((flags & AT_FLAG) === 0) return null\n\n\t\tconst aaguidOffset = 32 + 1 + 4\n\t\tconst aaguidBytes = authData.slice(aaguidOffset, aaguidOffset + 16)\n\t\tif (aaguidBytes.length !== 16) return null\n\n\t\treturn bytes16ToUuid(aaguidBytes)\n\t} catch {\n\t\treturn null\n\t}\n}\n\nexport function validateAaguidAllowlist(\n\taaguid: string | null,\n\tallowedAaguids?: string | string[] | false\n): boolean {\n\tif (allowedAaguids === false) return true\n\tif (!allowedAaguids) return true\n\tif (!aaguid) return false\n\n\tconst normalized = aaguid.trim().toLowerCase()\n\tconst allowed = Array.isArray(allowedAaguids)\n\t\t? allowedAaguids.map((s) => String(s).trim().toLowerCase()).filter(Boolean)\n\t\t: [allowedAaguids.trim().toLowerCase()].filter(Boolean)\n\n\treturn allowed.includes(normalized)\n}\n","import type { CorePassChallengeStore } from \"./types.js\"\n\nexport function memoryChallengeStore(): CorePassChallengeStore {\n\tconst m = new Map<string, { value: string; expiresAtMs: number }>()\n\n\treturn {\n\t\tasync put(key, value, ttlSeconds) {\n\t\t\tm.set(key, { value, expiresAtMs: Date.now() + ttlSeconds * 1000 })\n\t\t},\n\t\tasync get(key) {\n\t\t\tconst row = m.get(key)\n\t\t\tif (!row) return null\n\t\t\tif (Date.now() > row.expiresAtMs) {\n\t\t\t\tm.delete(key)\n\t\t\t\treturn null\n\t\t\t}\n\t\t\treturn row.value\n\t\t},\n\t\tasync delete(key) {\n\t\t\tm.delete(key)\n\t\t},\n\t}\n}\n\nexport type RedisLike = {\n\tset: (key: string, value: string, opts: { ex: number }) => Promise<unknown>\n\tget: (key: string) => Promise<string | null>\n\tdel: (key: string) => Promise<unknown>\n}\n\nexport function redisChallengeStore(redis: RedisLike): CorePassChallengeStore {\n\treturn {\n\t\tasync put(key, value, ttlSeconds) {\n\t\t\tawait redis.set(key, value, { ex: ttlSeconds })\n\t\t},\n\t\tasync get(key) {\n\t\t\treturn await redis.get(key)\n\t\t},\n\t\tasync delete(key) {\n\t\t\tawait redis.del(key)\n\t\t},\n\t}\n}\n\nexport type KvLike = {\n\tput: (key: string, value: string, opts: { expirationTtl: number }) => Promise<unknown>\n\tget: (key: string) => Promise<string | null>\n\tdelete: (key: string) => Promise<unknown>\n}\n\nexport function kvChallengeStore(kv: KvLike): CorePassChallengeStore {\n\treturn {\n\t\tasync put(key, value, ttlSeconds) {\n\t\t\tawait kv.put(key, value, { expirationTtl: ttlSeconds })\n\t\t},\n\t\tasync get(key) {\n\t\t\treturn await kv.get(key)\n\t\t},\n\t\tasync delete(key) {\n\t\t\tawait kv.delete(key)\n\t\t},\n\t}\n}\n\n/**\n * Vercel KV client shape (based on `@vercel/kv`).\n * We intentionally don't import `@vercel/kv` to avoid a hard dependency.\n */\nexport type VercelKvLike = {\n\tset: (key: string, value: string, opts: { ex: number }) => Promise<unknown>\n\tget: <T = string>(key: string) => Promise<T | null>\n\tdel: (key: string) => Promise<unknown>\n}\n\nexport function vercelKvChallengeStore(kv: VercelKvLike): CorePassChallengeStore {\n\treturn {\n\t\tasync put(key, value, ttlSeconds) {\n\t\t\tawait kv.set(key, value, { ex: ttlSeconds })\n\t\t},\n\t\tasync get(key) {\n\t\t\tconst v = await kv.get<string>(key)\n\t\t\treturn typeof v === \"string\" ? v : v === null ? null : String(v)\n\t\t},\n\t\tasync delete(key) {\n\t\t\tawait kv.del(key)\n\t\t},\n\t}\n}\n\n/**\n * Upstash Redis REST client shape (based on `@upstash/redis`).\n * We intentionally don't import `@upstash/redis` to avoid a hard dependency.\n */\nexport type UpstashRedisLike = {\n\tset: (key: string, value: string, opts: { ex: number }) => Promise<unknown>\n\tget: <T = string>(key: string) => Promise<T | null>\n\tdel: (key: string) => Promise<unknown>\n}\n\nexport function upstashRedisChallengeStore(redis: UpstashRedisLike): CorePassChallengeStore {\n\treturn {\n\t\tasync put(key, value, ttlSeconds) {\n\t\t\tawait redis.set(key, value, { ex: ttlSeconds })\n\t\t},\n\t\tasync get(key) {\n\t\t\tconst v = await redis.get<string>(key)\n\t\t\treturn typeof v === \"string\" ? v : v === null ? null : String(v)\n\t\t},\n\t\tasync delete(key) {\n\t\t\tawait redis.del(key)\n\t\t},\n\t}\n}\n\n/**\n * Durable Object stub shape (Cloudflare).\n * Your Durable Object must implement these routes:\n * - POST /challenge/put { key, value, ttlSeconds }\n * - GET /challenge/get?key=...\n * - POST /challenge/delete { key }\n */\nexport type DurableObjectStubLike = {\n\tfetch: (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>\n}\n\nexport function durableObjectChallengeStore(stub: DurableObjectStubLike): CorePassChallengeStore {\n\treturn {\n\t\tasync put(key, value, ttlSeconds) {\n\t\t\tconst res = await stub.fetch(\"https://do/challenge/put\", {\n\t\t\t\tmethod: \"POST\",\n\t\t\t\theaders: { \"content-type\": \"application/json\" },\n\t\t\t\tbody: JSON.stringify({ key, value, ttlSeconds }),\n\t\t\t})\n\t\t\tif (!res.ok) throw new Error(\"durableObjectChallengeStore: put failed\")\n\t\t},\n\t\tasync get(key) {\n\t\t\tconst res = await stub.fetch(\n\t\t\t\t`https://do/challenge/get?key=${encodeURIComponent(key)}`\n\t\t\t)\n\t\t\tif (!res.ok) return null\n\t\t\tconst data = (await res.json()) as { value: string | null }\n\t\t\treturn data.value\n\t\t},\n\t\tasync delete(key) {\n\t\t\tawait stub.fetch(\"https://do/challenge/delete\", {\n\t\t\t\tmethod: \"POST\",\n\t\t\t\theaders: { \"content-type\": \"application/json\" },\n\t\t\t\tbody: JSON.stringify({ key }),\n\t\t\t})\n\t\t},\n\t}\n}\n\n/**\n * DynamoDB-style store (pluggable).\n * This avoids hard-depending on AWS SDK packages while still making wiring easy.\n */\nexport type DynamoLike = {\n\tput: (args: { key: string; value: string; expiresAt: number }) => Promise<unknown>\n\tget: (key: string) => Promise<{ value: string; expiresAt: number } | null>\n\tdelete: (key: string) => Promise<unknown>\n}\n\nexport function dynamoChallengeStore(dynamo: DynamoLike): CorePassChallengeStore {\n\tconst nowSec = () => Math.floor(Date.now() / 1000)\n\treturn {\n\t\tasync put(key, value, ttlSeconds) {\n\t\t\tawait dynamo.put({ key, value, expiresAt: nowSec() + ttlSeconds })\n\t\t},\n\t\tasync get(key) {\n\t\t\tconst row = await dynamo.get(key)\n\t\t\tif (!row) return null\n\t\t\tif (row.expiresAt < nowSec()) return null\n\t\t\treturn row.value\n\t\t},\n\t\tasync delete(key) {\n\t\t\tawait dynamo.delete(key)\n\t\t},\n\t}\n}\n","import type {\n\tCorePassPendingRegistration,\n\tCorePassProfile,\n\tCorePassStore,\n\tCorePassUserIdentity,\n} from \"./types.js\"\n\ntype BoolDb = 0 | 1 | boolean | null\n\nfunction boolToDb(v: boolean | null): 0 | 1 | null {\n\tif (v === null) return null\n\treturn v ? 1 : 0\n}\n\nfunction boolFromDb(v: BoolDb): boolean | null {\n\tif (v === null) return null\n\tif (typeof v === \"boolean\") return v\n\treturn v === 1 ? true : v === 0 ? false : null\n}\n\nfunction nowSec(): number {\n\treturn Math.floor(Date.now() / 1000)\n}\n\n// -----------------------------\n// D1 / SQLite\n// -----------------------------\n\nexport type D1Like = {\n\tprepare: (sql: string) => {\n\t\tbind: (...params: unknown[]) => {\n\t\t\trun: () => Promise<unknown>\n\t\t\tfirst: <T = unknown>() => Promise<T | null>\n\t\t\tall?: <T = unknown>() => Promise<{ results: T[] }>\n\t\t}\n\t}\n}\n\nexport function d1CorePassStore(db: D1Like): CorePassStore {\n\treturn {\n\t\tasync createPendingRegistration(reg) {\n\t\t\tawait db\n\t\t\t\t.prepare(\n\t\t\t\t\t`INSERT INTO corepass_pending_registrations\n\t\t\t\t\t(token, credential_id, credential_public_key, counter, credential_device_type, credential_backed_up, transports, email, ref_id, aaguid, created_at, expires_at)\n\t\t\t\t\tVALUES\n\t\t\t\t\t(?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12)`\n\t\t\t\t)\n\t\t\t\t.bind(\n\t\t\t\t\treg.token,\n\t\t\t\t\treg.credentialId,\n\t\t\t\t\treg.credentialPublicKey,\n\t\t\t\t\treg.counter,\n\t\t\t\t\treg.credentialDeviceType,\n\t\t\t\t\treg.credentialBackedUp ? 1 : 0,\n\t\t\t\t\treg.transports,\n\t\t\t\t\treg.email,\n\t\t\t\t\treg.refId,\n\t\t\t\t\treg.aaguid,\n\t\t\t\t\treg.createdAt,\n\t\t\t\t\treg.expiresAt\n\t\t\t\t)\n\t\t\t\t.run()\n\t\t},\n\n\t\tasync getPendingRegistrationByCredentialId(credentialId) {\n\t\t\tconst row = (await db\n\t\t\t\t.prepare(\n\t\t\t\t\t`SELECT token, credential_id, credential_public_key, counter, credential_device_type, credential_backed_up, transports, email, ref_id, aaguid, created_at, expires_at\n\t\t\t\t\tFROM corepass_pending_registrations\n\t\t\t\t\tWHERE credential_id = ?1`\n\t\t\t\t)\n\t\t\t\t.bind(credentialId)\n\t\t\t\t.first()) as\n\t\t\t\t| {\n\t\t\t\t\t\ttoken: string\n\t\t\t\t\t\tcredential_id: string\n\t\t\t\t\t\tcredential_public_key: string\n\t\t\t\t\t\tcounter: number\n\t\t\t\t\t\tcredential_device_type: string\n\t\t\t\t\t\tcredential_backed_up: number\n\t\t\t\t\t\ttransports: string | null\n\t\t\t\t\t\temail: string | null\n\t\t\t\t\t\tref_id: string | null\n\t\t\t\t\t\taaguid: string | null\n\t\t\t\t\t\tcreated_at: number\n\t\t\t\t\t\texpires_at: number\n\t\t\t\t }\n\t\t\t\t| null\n\n\t\t\tif (!row) return null\n\t\t\treturn {\n\t\t\t\ttoken: row.token,\n\t\t\t\tcredentialId: row.credential_id,\n\t\t\t\tcredentialPublicKey: row.credential_public_key,\n\t\t\t\tcounter: row.counter ?? 0,\n\t\t\t\tcredentialDeviceType: row.credential_device_type,\n\t\t\t\tcredentialBackedUp: (row.credential_backed_up ?? 0) === 1,\n\t\t\t\ttransports: row.transports ?? null,\n\t\t\t\temail: row.email ?? null,\n\t\t\t\trefId: row.ref_id ?? null,\n\t\t\t\taaguid: row.aaguid ?? null,\n\t\t\t\tcreatedAt: row.created_at ?? nowSec(),\n\t\t\t\texpiresAt: row.expires_at ?? nowSec(),\n\t\t\t} satisfies CorePassPendingRegistration\n\t\t},\n\n\t\tasync deletePendingRegistrationByToken(token) {\n\t\t\tawait db\n\t\t\t\t.prepare(`DELETE FROM corepass_pending_registrations WHERE token = ?1`)\n\t\t\t\t.bind(token)\n\t\t\t\t.run()\n\t\t},\n\n\t\tasync getIdentityByCoreId(coreId) {\n\t\t\tconst row = (await db\n\t\t\t\t.prepare(`SELECT core_id, user_id, ref_id FROM corepass_identities WHERE core_id = ?1`)\n\t\t\t\t.bind(coreId)\n\t\t\t\t.first()) as { core_id: string; user_id: string; ref_id: string | null } | null\n\t\t\tif (!row) return null\n\t\t\treturn { coreId: row.core_id, userId: row.user_id, refId: row.ref_id ?? null } satisfies CorePassUserIdentity\n\t\t},\n\n\t\tasync getIdentityByUserId(userId) {\n\t\t\tconst row = (await db\n\t\t\t\t.prepare(`SELECT core_id, user_id, ref_id FROM corepass_identities WHERE user_id = ?1`)\n\t\t\t\t.bind(userId)\n\t\t\t\t.first()) as { core_id: string; user_id: string; ref_id: string | null } | null\n\t\t\tif (!row) return null\n\t\t\treturn { coreId: row.core_id, userId: row.user_id, refId: row.ref_id ?? null } satisfies CorePassUserIdentity\n\t\t},\n\n\t\tasync upsertIdentity(identity) {\n\t\t\tawait db\n\t\t\t\t.prepare(\n\t\t\t\t\t`INSERT INTO corepass_identities (core_id, user_id, ref_id, created_at, updated_at)\n\t\t\t\t\tVALUES (?1, ?2, ?3, strftime('%s','now'), strftime('%s','now'))\n\t\t\t\t\tON CONFLICT(core_id) DO UPDATE SET\n\t\t\t\t\t\tuser_id = excluded.user_id,\n\t\t\t\t\t\tref_id = COALESCE(corepass_identities.ref_id, excluded.ref_id),\n\t\t\t\t\t\tupdated_at = strftime('%s','now')`\n\t\t\t\t)\n\t\t\t\t.bind(identity.coreId, identity.userId, identity.refId)\n\t\t\t\t.run()\n\t\t},\n\n\t\tasync upsertProfile(profile) {\n\t\t\tawait db\n\t\t\t\t.prepare(\n\t\t\t\t\t`INSERT INTO corepass_profiles\n\t\t\t\t\t(user_id, core_id, o18y, o21y, kyc, kyc_doc, provided_till, created_at, updated_at)\n\t\t\t\t\tVALUES\n\t\t\t\t\t(?1, ?2, ?3, ?4, ?5, ?6, ?7, strftime('%s','now'), strftime('%s','now'))\n\t\t\t\t\tON CONFLICT(user_id) DO UPDATE SET\n\t\t\t\t\t\tcore_id = excluded.core_id,\n\t\t\t\t\t\to18y = excluded.o18y,\n\t\t\t\t\t\to21y = excluded.o21y,\n\t\t\t\t\t\tkyc = excluded.kyc,\n\t\t\t\t\t\tkyc_doc = excluded.kyc_doc,\n\t\t\t\t\t\tprovided_till = excluded.provided_till,\n\t\t\t\t\t\tupdated_at = strftime('%s','now')`\n\t\t\t\t)\n\t\t\t\t.bind(\n\t\t\t\t\tprofile.userId,\n\t\t\t\t\tprofile.coreId,\n\t\t\t\t\tboolToDb(profile.o18y),\n\t\t\t\t\tboolToDb(profile.o21y),\n\t\t\t\t\tboolToDb(profile.kyc),\n\t\t\t\t\tprofile.kycDoc,\n\t\t\t\t\tprofile.providedTill\n\t\t\t\t)\n\t\t\t\t.run()\n\t\t},\n\t}\n}\n\n// -----------------------------\n// Postgres (node-postgres / any SQL client)\n// -----------------------------\n\nexport type PgLike = {\n\tquery: (text: string, params?: unknown[]) => Promise<{ rows: any[] }>\n}\n\nexport function postgresCorePassStore(pg: PgLike): CorePassStore {\n\treturn {\n\t\tasync createPendingRegistration(reg) {\n\t\t\tawait pg.query(\n\t\t\t\t`INSERT INTO corepass_pending_registrations\n\t\t\t\t(token, credential_id, credential_public_key, counter, credential_device_type, credential_backed_up, transports, email, ref_id, aaguid, created_at, expires_at)\n\t\t\t\tVALUES\n\t\t\t\t($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12)`,\n\t\t\t\t[\n\t\t\t\t\treg.token,\n\t\t\t\t\treg.credentialId,\n\t\t\t\t\treg.credentialPublicKey,\n\t\t\t\t\treg.counter,\n\t\t\t\t\treg.credentialDeviceType,\n\t\t\t\t\treg.credentialBackedUp,\n\t\t\t\t\treg.transports,\n\t\t\t\t\treg.email,\n\t\t\t\t\treg.refId,\n\t\t\t\t\treg.aaguid,\n\t\t\t\t\treg.createdAt,\n\t\t\t\t\treg.expiresAt,\n\t\t\t\t]\n\t\t\t)\n\t\t},\n\n\t\tasync getPendingRegistrationByCredentialId(credentialId) {\n\t\t\tconst res = await pg.query(\n\t\t\t\t`SELECT token, credential_id, credential_public_key, counter, credential_device_type, credential_backed_up, transports, email, ref_id, aaguid, created_at, expires_at\n\t\t\t\tFROM corepass_pending_registrations\n\t\t\t\tWHERE credential_id = $1`,\n\t\t\t\t[credentialId]\n\t\t\t)\n\t\t\tconst row = res.rows[0]\n\t\t\tif (!row) return null\n\t\t\treturn {\n\t\t\t\ttoken: row.token,\n\t\t\t\tcredentialId: row.credential_id,\n\t\t\t\tcredentialPublicKey: row.credential_public_key,\n\t\t\t\tcounter: Number(row.counter ?? 0),\n\t\t\t\tcredentialDeviceType: row.credential_device_type,\n\t\t\t\tcredentialBackedUp: Boolean(row.credential_backed_up),\n\t\t\t\ttransports: row.transports ?? null,\n\t\t\t\temail: row.email ?? null,\n\t\t\t\trefId: row.ref_id ?? null,\n\t\t\t\taaguid: row.aaguid ?? null,\n\t\t\t\tcreatedAt: Number(row.created_at ?? nowSec()),\n\t\t\t\texpiresAt: Number(row.expires_at ?? nowSec()),\n\t\t\t} satisfies CorePassPendingRegistration\n\t\t},\n\n\t\tasync deletePendingRegistrationByToken(token) {\n\t\t\tawait pg.query(`DELETE FROM corepass_pending_registrations WHERE token = $1`, [token])\n\t\t},\n\n\t\tasync getIdentityByCoreId(coreId) {\n\t\t\tconst res = await pg.query(\n\t\t\t\t`SELECT core_id, user_id, ref_id FROM corepass_identities WHERE core_id = $1`,\n\t\t\t\t[coreId]\n\t\t\t)\n\t\t\tconst row = res.rows[0]\n\t\t\tif (!row) return null\n\t\t\treturn { coreId: row.core_id, userId: row.user_id, refId: row.ref_id ?? null } satisfies CorePassUserIdentity\n\t\t},\n\n\t\tasync getIdentityByUserId(userId) {\n\t\t\tconst res = await pg.query(\n\t\t\t\t`SELECT core_id, user_id, ref_id FROM corepass_identities WHERE user_id = $1`,\n\t\t\t\t[userId]\n\t\t\t)\n\t\t\tconst row = res.rows[0]\n\t\t\tif (!row) return null\n\t\t\treturn { coreId: row.core_id, userId: row.user_id, refId: row.ref_id ?? null } satisfies CorePassUserIdentity\n\t\t},\n\n\t\tasync upsertIdentity(identity) {\n\t\t\tawait pg.query(\n\t\t\t\t`INSERT INTO corepass_identities (core_id, user_id, ref_id, created_at, updated_at)\n\t\t\t\tVALUES ($1,$2,$3, EXTRACT(EPOCH FROM NOW())::BIGINT, EXTRACT(EPOCH FROM NOW())::BIGINT)\n\t\t\t\tON CONFLICT (core_id) DO UPDATE SET\n\t\t\t\t\tuser_id = EXCLUDED.user_id,\n\t\t\t\t\tref_id = COALESCE(corepass_identities.ref_id, EXCLUDED.ref_id),\n\t\t\t\t\tupdated_at = EXTRACT(EPOCH FROM NOW())::BIGINT`,\n\t\t\t\t[identity.coreId, identity.userId, identity.refId]\n\t\t\t)\n\t\t},\n\n\t\tasync upsertProfile(profile) {\n\t\t\tawait pg.query(\n\t\t\t\t`INSERT INTO corepass_profiles (user_id, core_id, o18y, o21y, kyc, kyc_doc, provided_till, created_at, updated_at)\n\t\t\t\tVALUES ($1,$2,$3,$4,$5,$6,$7, EXTRACT(EPOCH FROM NOW())::BIGINT, EXTRACT(EPOCH FROM NOW())::BIGINT)\n\t\t\t\tON CONFLICT (user_id) DO UPDATE SET\n\t\t\t\t\tcore_id = EXCLUDED.core_id,\n\t\t\t\t\to18y = EXCLUDED.o18y,\n\t\t\t\t\to21y = EXCLUDED.o21y,\n\t\t\t\t\tkyc = EXCLUDED.kyc,\n\t\t\t\t\tkyc_doc = EXCLUDED.kyc_doc,\n\t\t\t\t\tprovided_till = EXCLUDED.provided_till,\n\t\t\t\t\tupdated_at = EXTRACT(EPOCH FROM NOW())::BIGINT`,\n\t\t\t\t[\n\t\t\t\t\tprofile.userId,\n\t\t\t\t\tprofile.coreId,\n\t\t\t\t\tprofile.o18y,\n\t\t\t\t\tprofile.o21y,\n\t\t\t\t\tprofile.kyc,\n\t\t\t\t\tprofile.kycDoc,\n\t\t\t\t\tprofile.providedTill,\n\t\t\t\t]\n\t\t\t)\n\t\t},\n\t}\n}\n\n// -----------------------------\n// Supabase (Postgres)\n// -----------------------------\n\nexport type SupabaseLike = {\n\tfrom: (table: string) => any\n}\n\nexport function supabaseCorePassStore(supabase: SupabaseLike): CorePassStore {\n\tconst tablePending = \"corepass_pending_registrations\"\n\tconst tableIdentities = \"corepass_identities\"\n\tconst tableProfiles = \"corepass_profiles\"\n\n\tconst maybeSingle = async (q: any) => {\n\t\tif (typeof q.maybeSingle === \"function\") return await q.maybeSingle()\n\t\treturn await q.single()\n\t}\n\n\treturn {\n\t\tasync createPendingRegistration(reg) {\n\t\t\tawait supabase.from(tablePending).insert({\n\t\t\t\ttoken: reg.token,\n\t\t\t\tcredential_id: reg.credentialId,\n\t\t\t\tcredential_public_key: reg.credentialPublicKey,\n\t\t\t\tcounter: reg.counter,\n\t\t\t\tcredential_device_type: reg.credentialDeviceType,\n\t\t\t\tcredential_backed_up: reg.credentialBackedUp,\n\t\t\t\ttransports: reg.transports,\n\t\t\t\temail: reg.email,\n\t\t\t\tref_id: reg.refId,\n\t\t\t\taaguid: reg.aaguid,\n\t\t\t\tcreated_at: reg.createdAt,\n\t\t\t\texpires_at: reg.expiresAt,\n\t\t\t})\n\t\t},\n\n\t\tasync getPendingRegistrationByCredentialId(credentialId) {\n\t\t\tconst res = await maybeSingle(\n\t\t\t\tsupabase\n\t\t\t\t\t.from(tablePending)\n\t\t\t\t\t.select(\n\t\t\t\t\t\t\"token, credential_id, credential_public_key, counter, credential_device_type, credential_backed_up, transports, email, ref_id, aaguid, created_at, expires_at\"\n\t\t\t\t\t)\n\t\t\t\t\t.eq(\"credential_id\", credentialId)\n\t\t\t)\n\t\t\tconst row = (res?.data ?? null) as any\n\t\t\tif (!row) return null\n\t\t\treturn {\n\t\t\t\ttoken: row.token,\n\t\t\t\tcredentialId: row.credential_id,\n\t\t\t\tcredentialPublicKey: row.credential_public_key,\n\t\t\t\tcounter: Number(row.counter ?? 0),\n\t\t\t\tcredentialDeviceType: row.credential_device_type,\n\t\t\t\tcredentialBackedUp: Boolean(row.credential_backed_up),\n\t\t\t\ttransports: row.transports ?? null,\n\t\t\t\temail: row.email ?? null,\n\t\t\t\trefId: row.ref_id ?? null,\n\t\t\t\taaguid: row.aaguid ?? null,\n\t\t\t\tcreatedAt: Number(row.created_at ?? nowSec()),\n\t\t\t\texpiresAt: Number(row.expires_at ?? nowSec()),\n\t\t\t} satisfies CorePassPendingRegistration\n\t\t},\n\n\t\tasync deletePendingRegistrationByToken(token) {\n\t\t\tawait supabase.from(tablePending).delete().eq(\"token\", token)\n\t\t},\n\n\t\tasync getIdentityByCoreId(coreId) {\n\t\t\tconst res = await maybeSingle(\n\t\t\t\tsupabase.from(tableIdentities).select(\"core_id, user_id, ref_id\").eq(\"core_id\", coreId)\n\t\t\t)\n\t\t\tconst row = (res?.data ?? null) as any\n\t\t\tif (!row) return null\n\t\t\treturn { coreId: row.core_id, userId: row.user_id, refId: row.ref_id ?? null } satisfies CorePassUserIdentity\n\t\t},\n\n\t\tasync getIdentityByUserId(userId) {\n\t\t\tconst res = await maybeSingle(\n\t\t\t\tsupabase.from(tableIdentities).select(\"core_id, user_id, ref_id\").eq(\"user_id\", userId)\n\t\t\t)\n\t\t\tconst row = (res?.data ?? null) as any\n\t\t\tif (!row) return null\n\t\t\treturn { coreId: row.core_id, userId: row.user_id, refId: row.ref_id ?? null } satisfies CorePassUserIdentity\n\t\t},\n\n\t\tasync upsertIdentity(identity) {\n\t\t\tawait supabase\n\t\t\t\t.from(tableIdentities)\n\t\t\t\t.upsert(\n\t\t\t\t\t{\n\t\t\t\t\t\tcore_id: identity.coreId,\n\t\t\t\t\t\tuser_id: identity.userId,\n\t\t\t\t\t\tref_id: identity.refId,\n\t\t\t\t\t\tupdated_at: nowSec(),\n\t\t\t\t\t},\n\t\t\t\t\t{ onConflict: \"core_id\" }\n\t\t\t\t)\n\t\t},\n\n\t\tasync upsertProfile(profile) {\n\t\t\tawait supabase\n\t\t\t\t.from(tableProfiles)\n\t\t\t\t.upsert(\n\t\t\t\t\t{\n\t\t\t\t\t\tuser_id: profile.userId,\n\t\t\t\t\t\tcore_id: profile.coreId,\n\t\t\t\t\t\to18y: profile.o18y,\n\t\t\t\t\t\to21y: profile.o21y,\n\t\t\t\t\t\tkyc: profile.kyc,\n\t\t\t\t\t\tkyc_doc: profile.kycDoc,\n\t\t\t\t\t\tprovided_till: profile.providedTill,\n\t\t\t\t\t\tupdated_at: nowSec(),\n\t\t\t\t\t},\n\t\t\t\t\t{ onConflict: \"user_id\" }\n\t\t\t\t)\n\t\t},\n\t}\n}\n","import { createCorePassServer } from \"./create-corepass-server.js\"\nimport { d1CorePassStore, postgresCorePassStore, supabaseCorePassStore } from \"./stores.js\"\nimport type { CreateCorePassServerOptions } from \"./types.js\"\nimport type { D1Like, PgLike, SupabaseLike } from \"./stores.js\"\nimport {\n\tkvChallengeStore,\n\tredisChallengeStore,\n\tupstashRedisChallengeStore,\n\tvercelKvChallengeStore,\n\ttype KvLike,\n\ttype RedisLike,\n\ttype UpstashRedisLike,\n\ttype VercelKvLike,\n} from \"./challenge-stores.js\"\n\ntype WithoutStore<T> = Omit<T, \"store\">\ntype WithoutStoreAndChallengeStore<T> = Omit<T, \"store\" | \"challengeStore\">\n\nexport function createCorePassServerD1(\n\toptions: WithoutStore<CreateCorePassServerOptions> & { db: D1Like }\n) {\n\tconst { db, ...rest } = options\n\treturn createCorePassServer({ ...rest, store: d1CorePassStore(db) })\n}\n\nexport function createCorePassServerPostgres(\n\toptions: WithoutStore<CreateCorePassServerOptions> & { pg: PgLike }\n) {\n\tconst { pg, ...rest } = options\n\treturn createCorePassServer({ ...rest, store: postgresCorePassStore(pg) })\n}\n\nexport function createCorePassServerSupabase(\n\toptions: WithoutStore<CreateCorePassServerOptions> & { supabase: SupabaseLike }\n) {\n\tconst { supabase, ...rest } = options\n\treturn createCorePassServer({ ...rest, store: supabaseCorePassStore(supabase) })\n}\n\n/**\n * Popular stack factory: Cloudflare Workers (D1 + KV)\n */\nexport function createCorePassServerCloudflareD1Kv(\n\toptions: WithoutStoreAndChallengeStore<CreateCorePassServerOptions> & { db: D1Like; kv: KvLike }\n) {\n\tconst { db, kv, ...rest } = options\n\treturn createCorePassServer({\n\t\t...rest,\n\t\tstore: d1CorePassStore(db),\n\t\tchallengeStore: kvChallengeStore(kv),\n\t})\n}\n\n/**\n * Popular stack factory: Postgres + Redis\n */\nexport function createCorePassServerPostgresRedis(\n\toptions: WithoutStoreAndChallengeStore<CreateCorePassServerOptions> & { pg: PgLike; redis: RedisLike }\n) {\n\tconst { pg, redis, ...rest } = options\n\treturn createCorePassServer({\n\t\t...rest,\n\t\tstore: postgresCorePassStore(pg),\n\t\tchallengeStore: redisChallengeStore(redis),\n\t})\n}\n\n/**\n * Popular stack factory: Supabase (Postgres) + Upstash Redis REST\n */\nexport function createCorePassServerSupabaseUpstash(\n\toptions: WithoutStoreAndChallengeStore<CreateCorePassServerOptions> & {\n\t\tsupabase: SupabaseLike\n\t\tredis: UpstashRedisLike\n\t}\n) {\n\tconst { supabase, redis, ...rest } = options\n\treturn createCorePassServer({\n\t\t...rest,\n\t\tstore: supabaseCorePassStore(supabase),\n\t\tchallengeStore: upstashRedisChallengeStore(redis),\n\t})\n}\n\n/**\n * Popular stack factory: Supabase (Postgres) + Vercel KV\n */\nexport function createCorePassServerSupabaseVercelKv(\n\toptions: WithoutStoreAndChallengeStore<CreateCorePassServerOptions> & {\n\t\tsupabase: SupabaseLike\n\t\tkv: VercelKvLike\n\t}\n) {\n\tconst { supabase, kv, ...rest } = options\n\treturn createCorePassServer({\n\t\t...rest,\n\t\tstore: supabaseCorePassStore(supabase),\n\t\tchallengeStore: vercelKvChallengeStore(kv),\n\t})\n}\n"],"mappings":";;;;;AAAA,OAAO,cAAc;;;ACArB,SAAS,cAAuB;AAC/B,SAAO,OAAO,WAAW,SAAS,cAAc,OAAO,WAAW,SAAS;AAC5E;AAEA,SAAS,oBAAoB,OAA2B;AACvD,MAAI,IA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