@prson/login-sdk 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +202 -0
- package/README.md +348 -2
- package/dist/api.d.ts +59 -0
- package/dist/api.js +40 -0
- package/dist/bind.d.ts +224 -0
- package/dist/bind.js +1384 -0
- package/dist/crypto.d.ts +352 -0
- package/dist/crypto.js +159 -0
- package/dist/index.d.ts +345 -0
- package/dist/index.js +6102 -0
- package/dist/index.js.map +7 -0
- package/dist/notify.d.ts +8 -0
- package/dist/notify.js +17 -0
- package/dist/point_phone_overlay.d.ts +41 -0
- package/dist/point_phone_overlay.js +157 -0
- package/dist/qr.d.ts +105 -0
- package/dist/qr.js +149 -0
- package/dist/requests.d.ts +279 -0
- package/dist/requests.js +128 -0
- package/dist/select_overlay.d.ts +70 -0
- package/dist/select_overlay.js +426 -0
- package/dist/session.d.ts +639 -0
- package/dist/session.js +1436 -0
- package/dist/signaling.d.ts +59 -0
- package/dist/signaling.js +91 -0
- package/dist/status.d.ts +48 -0
- package/dist/status.js +105 -0
- package/dist/transport.d.ts +45 -0
- package/dist/transport.js +183 -0
- package/dist/verification.d.ts +56 -0
- package/dist/verification.js +169 -0
- package/dist/verify.d.ts +69 -0
- package/dist/verify.js +331 -0
- package/package.json +59 -4
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Show a person a Prson **verification** (an organisation's request made
|
|
3
|
+
* with POST /v1/verifications — prove your age, show your ID, sign this
|
|
4
|
+
* PDF with your verified name) and wait until they answer it.
|
|
5
|
+
*
|
|
6
|
+
* The verification is created by YOUR SERVER with your API key; the key
|
|
7
|
+
* never reaches the browser. Your page gets the `share_url` from your
|
|
8
|
+
* server, and `checkStatus` asks your server for the status (your server
|
|
9
|
+
* calls GET /v1/verifications/{id}, or keeps what the verification.*
|
|
10
|
+
* webhooks told it). On a computer the link shows as a QR code to scan
|
|
11
|
+
* with the phone; on a phone, as a button that opens the Prson app.
|
|
12
|
+
*
|
|
13
|
+
* const { share_url, id } = await (await fetch("/api/contract/sign", { method: "POST" })).json();
|
|
14
|
+
* await awaitVerification({
|
|
15
|
+
* shareUrl: share_url,
|
|
16
|
+
* title: "Sign the rental agreement",
|
|
17
|
+
* checkStatus: async (signal) => (await (await fetch(`/api/verifications/${id}`, { signal })).json()).status,
|
|
18
|
+
* });
|
|
19
|
+
* // fulfilled: your server downloads the signed PDF (the response's signature.download_path).
|
|
20
|
+
*
|
|
21
|
+
* Resolves with the status once `until` holds (default: "fulfilled");
|
|
22
|
+
* rejects with VerificationClosedError when it was cancelled or expired,
|
|
23
|
+
* and VerificationAbortedError when the person closes the dialog or
|
|
24
|
+
* `signal` aborts.
|
|
25
|
+
*/
|
|
26
|
+
import { createModalQrMount, renderLoginQr } from "./qr.js";
|
|
27
|
+
export class VerificationAbortedError extends Error {
|
|
28
|
+
constructor(message = "The verification dialog was closed") {
|
|
29
|
+
super(message);
|
|
30
|
+
this.name = "VerificationAbortedError";
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
export class VerificationClosedError extends Error {
|
|
34
|
+
constructor(status) {
|
|
35
|
+
super(`The verification is ${status}`);
|
|
36
|
+
this.status = status;
|
|
37
|
+
this.name = "VerificationClosedError";
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
function checkShareUrl(url) {
|
|
41
|
+
let parsed;
|
|
42
|
+
try {
|
|
43
|
+
parsed = new URL(url);
|
|
44
|
+
}
|
|
45
|
+
catch {
|
|
46
|
+
throw new Error(`shareUrl is not a URL: ${url}`);
|
|
47
|
+
}
|
|
48
|
+
if (parsed.protocol !== "https:")
|
|
49
|
+
throw new Error("shareUrl must be https:// (the share_url Prson returned)");
|
|
50
|
+
return parsed.toString();
|
|
51
|
+
}
|
|
52
|
+
function isPhone() {
|
|
53
|
+
try {
|
|
54
|
+
return window.matchMedia("(pointer: coarse)").matches && window.matchMedia("(max-width: 820px)").matches;
|
|
55
|
+
}
|
|
56
|
+
catch {
|
|
57
|
+
return false;
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
/** The card: title, the QR (computer) or an "Open in Prson" button (phone), and a status line. */
|
|
61
|
+
function renderCard(mount, o) {
|
|
62
|
+
const dark = o.theme === "dark" || (o.theme === "auto" && window.matchMedia?.("(prefers-color-scheme: dark)").matches);
|
|
63
|
+
const card = document.createElement("div");
|
|
64
|
+
card.setAttribute("data-prson-verification", "1");
|
|
65
|
+
card.style.cssText =
|
|
66
|
+
"box-sizing:border-box;max-width:360px;width:100%;padding:24px;border-radius:16px;font-family:system-ui,-apple-system,sans-serif;text-align:center;" +
|
|
67
|
+
(dark ? "background:#14161b;color:#f2f3f5;" : "background:#fff;color:#14161b;") +
|
|
68
|
+
"box-shadow:0 12px 40px rgba(0,0,0,0.25);";
|
|
69
|
+
if (o.title) {
|
|
70
|
+
const h = document.createElement("div");
|
|
71
|
+
h.style.cssText = "font-size:17px;font-weight:600;margin-bottom:6px;line-height:1.3;";
|
|
72
|
+
h.textContent = o.title;
|
|
73
|
+
card.append(h);
|
|
74
|
+
}
|
|
75
|
+
const hint = document.createElement("div");
|
|
76
|
+
hint.style.cssText = "font-size:14px;opacity:0.75;margin-bottom:16px;line-height:1.4;";
|
|
77
|
+
hint.textContent = o.phone ? "Open the request in the Prson app on this phone." : "Scan with your phone's camera to open it in the Prson app.";
|
|
78
|
+
card.append(hint);
|
|
79
|
+
let qr = null;
|
|
80
|
+
if (o.phone) {
|
|
81
|
+
const a = document.createElement("a");
|
|
82
|
+
a.href = o.url;
|
|
83
|
+
a.rel = "noopener";
|
|
84
|
+
a.textContent = "Open in Prson";
|
|
85
|
+
a.style.cssText = "display:inline-block;padding:12px 20px;border-radius:999px;background:#2949b8;color:#fff;font-weight:600;text-decoration:none;font-size:15px;";
|
|
86
|
+
card.append(a);
|
|
87
|
+
}
|
|
88
|
+
else {
|
|
89
|
+
const qrMount = document.createElement("div");
|
|
90
|
+
qrMount.style.cssText = "display:flex;justify-content:center;margin:4px 0 8px;";
|
|
91
|
+
card.append(qrMount);
|
|
92
|
+
qr = renderLoginQr(o.url, qrMount, o.theme);
|
|
93
|
+
const link = document.createElement("a");
|
|
94
|
+
link.href = o.url;
|
|
95
|
+
link.target = "_blank";
|
|
96
|
+
link.rel = "noopener";
|
|
97
|
+
link.textContent = "On this device? Open the link";
|
|
98
|
+
link.style.cssText = "display:inline-block;margin-top:4px;font-size:13px;color:inherit;opacity:0.7;";
|
|
99
|
+
card.append(link);
|
|
100
|
+
}
|
|
101
|
+
const status = document.createElement("div");
|
|
102
|
+
status.setAttribute("role", "status");
|
|
103
|
+
status.style.cssText = "font-size:13px;opacity:0.7;margin-top:16px;";
|
|
104
|
+
status.textContent = "Waiting for an answer…";
|
|
105
|
+
card.append(status);
|
|
106
|
+
mount.append(card);
|
|
107
|
+
return {
|
|
108
|
+
setStatus: (s) => {
|
|
109
|
+
status.textContent = s === "partially_fulfilled" ? "Partly answered, waiting for the rest…" : "Waiting for an answer…";
|
|
110
|
+
},
|
|
111
|
+
dispose: () => {
|
|
112
|
+
qr?.dispose();
|
|
113
|
+
card.remove();
|
|
114
|
+
},
|
|
115
|
+
};
|
|
116
|
+
}
|
|
117
|
+
export async function awaitVerification(opts) {
|
|
118
|
+
const url = checkShareUrl(opts.shareUrl);
|
|
119
|
+
const interval = Math.max(1000, opts.intervalMs ?? 3000);
|
|
120
|
+
const until = opts.until ?? ((s) => s === "fulfilled");
|
|
121
|
+
const controller = new AbortController();
|
|
122
|
+
const abort = (reason) => controller.abort(reason);
|
|
123
|
+
opts.signal?.addEventListener("abort", () => abort(new VerificationAbortedError("Aborted")), { once: true });
|
|
124
|
+
let modal = null;
|
|
125
|
+
let mount = null;
|
|
126
|
+
if (opts.mountInto)
|
|
127
|
+
mount = typeof opts.mountInto === "string" ? document.querySelector(opts.mountInto) : opts.mountInto;
|
|
128
|
+
if (!mount) {
|
|
129
|
+
modal = createModalQrMount({ onDismiss: () => abort(new VerificationAbortedError()) });
|
|
130
|
+
mount = modal.mount;
|
|
131
|
+
}
|
|
132
|
+
const card = renderCard(mount, { url, title: opts.title, phone: opts.layout ? opts.layout === "phone" : isPhone(), theme: opts.theme ?? "auto" });
|
|
133
|
+
const timer = opts.timeoutMs ? setTimeout(() => abort(new VerificationAbortedError("Timed out waiting for an answer")), opts.timeoutMs) : null;
|
|
134
|
+
const sleep = (ms) => new Promise((resolve, reject) => {
|
|
135
|
+
if (controller.signal.aborted)
|
|
136
|
+
return reject(controller.signal.reason);
|
|
137
|
+
const t = setTimeout(resolve, ms);
|
|
138
|
+
controller.signal.addEventListener("abort", () => (clearTimeout(t), reject(controller.signal.reason)), { once: true });
|
|
139
|
+
});
|
|
140
|
+
try {
|
|
141
|
+
for (;;) {
|
|
142
|
+
if (controller.signal.aborted)
|
|
143
|
+
throw controller.signal.reason;
|
|
144
|
+
let status = null;
|
|
145
|
+
try {
|
|
146
|
+
status = String(await opts.checkStatus(controller.signal));
|
|
147
|
+
}
|
|
148
|
+
catch (e) {
|
|
149
|
+
if (controller.signal.aborted)
|
|
150
|
+
throw controller.signal.reason;
|
|
151
|
+
// A failed check (network, your server) is retried at the next tick.
|
|
152
|
+
}
|
|
153
|
+
if (status !== null) {
|
|
154
|
+
if (until(status))
|
|
155
|
+
return { status };
|
|
156
|
+
if (status === "cancelled" || status === "expired")
|
|
157
|
+
throw new VerificationClosedError(status);
|
|
158
|
+
card.setStatus(status);
|
|
159
|
+
}
|
|
160
|
+
await sleep(interval);
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
finally {
|
|
164
|
+
if (timer)
|
|
165
|
+
clearTimeout(timer);
|
|
166
|
+
card.dispose();
|
|
167
|
+
modal?.dispose();
|
|
168
|
+
}
|
|
169
|
+
}
|
package/dist/verify.d.ts
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Browser-side SD-JWT-VC verification. The SDK enforces all five rules
|
|
3
|
+
* from SECURITY.md §7 before resolving signIn(); the verifier-node
|
|
4
|
+
* package re-enforces them server-side.
|
|
5
|
+
*
|
|
6
|
+
* We do this in the browser too — even though the host site must
|
|
7
|
+
* re-verify on its backend — because:
|
|
8
|
+
*
|
|
9
|
+
* (a) failing fast in the SDK gives partners better DX (clear errors
|
|
10
|
+
* before anything reaches their backend); and
|
|
11
|
+
* (b) the cnf.jwk we expose to the host as the user identifier MUST
|
|
12
|
+
* have actually signed the presentation we deliver, otherwise
|
|
13
|
+
* sloppy callers could be tricked into trusting a forged cnf.
|
|
14
|
+
*
|
|
15
|
+
* Implementation uses Web Crypto for RS256 + Ed25519 verification.
|
|
16
|
+
* Web Crypto's Ed25519 support landed in all major browsers in 2023+;
|
|
17
|
+
* for older targets we'd polyfill with `@stablelib/ed25519`.
|
|
18
|
+
*/
|
|
19
|
+
import type { CnfJwk } from "./index.js";
|
|
20
|
+
import { type StatusPolicy } from "./status.js";
|
|
21
|
+
export type VerifyOptions = {
|
|
22
|
+
expectedAudience: string;
|
|
23
|
+
expectedNonce: string;
|
|
24
|
+
acceptedVcts: string[];
|
|
25
|
+
trustedIssuer: string;
|
|
26
|
+
maxKbAgeSeconds?: number;
|
|
27
|
+
jwksUri?: string;
|
|
28
|
+
/**
|
|
29
|
+
* Revocation (the credential's Token Status List entry, status.ts).
|
|
30
|
+
* onUnavailable: when the list can't be fetched or verified; default
|
|
31
|
+
* "fail-closed" for verified humans (level 5+), "fail-open" below.
|
|
32
|
+
* cacheSeconds: how long a list is reused (default 60).
|
|
33
|
+
*/
|
|
34
|
+
status?: {
|
|
35
|
+
onUnavailable?: StatusPolicy;
|
|
36
|
+
cacheSeconds?: number;
|
|
37
|
+
};
|
|
38
|
+
};
|
|
39
|
+
export type VerifyOk = {
|
|
40
|
+
ok: true;
|
|
41
|
+
claims: Record<string, unknown>;
|
|
42
|
+
cnf: {
|
|
43
|
+
jwk: CnfJwk;
|
|
44
|
+
};
|
|
45
|
+
/**
|
|
46
|
+
* The holder-signed binding: what the cnf key signed for THIS
|
|
47
|
+
* presentation (the KB-JWT, or the anonymous credential's payload).
|
|
48
|
+
* `walletSessionPk` is the `prson_wsk` claim — the wallet's X25519
|
|
49
|
+
* session key the data channel must come from; absent from wallets
|
|
50
|
+
* that predate it.
|
|
51
|
+
*/
|
|
52
|
+
binding: {
|
|
53
|
+
iat: number;
|
|
54
|
+
nonce: string;
|
|
55
|
+
walletSessionPk?: string;
|
|
56
|
+
};
|
|
57
|
+
credential: {
|
|
58
|
+
vct: string;
|
|
59
|
+
iss: string;
|
|
60
|
+
kid: string;
|
|
61
|
+
expiresAt: number;
|
|
62
|
+
};
|
|
63
|
+
};
|
|
64
|
+
export type VerifyErr = {
|
|
65
|
+
ok: false;
|
|
66
|
+
reason: "malformed" | "issuer_key_resolve_failed" | "issuer_sig_invalid" | "vc_expired" | "vct_not_accepted" | "typ_not_accepted" | "disclosure_unmatched" | "kb_missing" | "kb_sig_invalid" | "aud_mismatch" | "nonce_mismatch" | "sd_hash_mismatch" | "kb_iat_stale" | "vc_revoked" | "status_unavailable";
|
|
67
|
+
};
|
|
68
|
+
export type VerifyResult = VerifyOk | VerifyErr;
|
|
69
|
+
export declare function verifyPresentation(sdJwt: string, opts: VerifyOptions): Promise<VerifyResult>;
|
package/dist/verify.js
ADDED
|
@@ -0,0 +1,331 @@
|
|
|
1
|
+
import { checkCredentialStatus } from "./status.js";
|
|
2
|
+
/** VCT for the self-signed anonymous-wallet credential — kept here as
|
|
3
|
+
* well as in index.ts so verifier callers don't have to import both. */
|
|
4
|
+
const ANONYMOUS_WALLET_VCT = "https://app.prson.net/credentials/anonymous-wallet/v1";
|
|
5
|
+
export async function verifyPresentation(sdJwt, opts) {
|
|
6
|
+
// ── Anonymous-wallet credential path ─────────────────────────────
|
|
7
|
+
// No SD-JWT tildes — it's a plain JWS. We accept this ONLY when the
|
|
8
|
+
// calling site opted in via `acceptedVcts` containing the anonymous
|
|
9
|
+
// VCT. Verification is structurally simpler: cnf.jwk IS the signer,
|
|
10
|
+
// so the JWS signature + cnf-binding check collapse into one step.
|
|
11
|
+
if (!sdJwt.includes("~") && opts.acceptedVcts.includes(ANONYMOUS_WALLET_VCT)) {
|
|
12
|
+
return verifyAnonymousWallet(sdJwt, opts);
|
|
13
|
+
}
|
|
14
|
+
const parts = sdJwt.split("~");
|
|
15
|
+
if (parts.length < 2)
|
|
16
|
+
return { ok: false, reason: "malformed" };
|
|
17
|
+
const jws = parts[0];
|
|
18
|
+
const tail = parts.slice(1);
|
|
19
|
+
const last = tail[tail.length - 1];
|
|
20
|
+
let kbJwt;
|
|
21
|
+
let discTokens;
|
|
22
|
+
if (last === "" || last === undefined) {
|
|
23
|
+
discTokens = tail.slice(0, -1);
|
|
24
|
+
return { ok: false, reason: "kb_missing" };
|
|
25
|
+
}
|
|
26
|
+
else if (last.includes(".")) {
|
|
27
|
+
kbJwt = last;
|
|
28
|
+
discTokens = tail.slice(0, -1);
|
|
29
|
+
}
|
|
30
|
+
else {
|
|
31
|
+
return { ok: false, reason: "kb_missing" };
|
|
32
|
+
}
|
|
33
|
+
// ── 1. Parse the issuer JWS ─────────────────────────────────────
|
|
34
|
+
const [hB64, pB64, sigB64] = jws.split(".");
|
|
35
|
+
if (!hB64 || !pB64 || !sigB64)
|
|
36
|
+
return { ok: false, reason: "malformed" };
|
|
37
|
+
let header;
|
|
38
|
+
let payload;
|
|
39
|
+
try {
|
|
40
|
+
header = JSON.parse(new TextDecoder().decode(b64uBytes(hB64)));
|
|
41
|
+
payload = JSON.parse(new TextDecoder().decode(b64uBytes(pB64)));
|
|
42
|
+
}
|
|
43
|
+
catch {
|
|
44
|
+
return { ok: false, reason: "malformed" };
|
|
45
|
+
}
|
|
46
|
+
// SD-JWT VC media type (draft-ietf-oauth-sd-jwt-vc): dc+sd-jwt, or the older vc+sd-jwt.
|
|
47
|
+
if (header.typ !== "dc+sd-jwt" && header.typ !== "vc+sd-jwt") {
|
|
48
|
+
return { ok: false, reason: "typ_not_accepted" };
|
|
49
|
+
}
|
|
50
|
+
if (typeof payload.iss !== "string" || payload.iss !== opts.trustedIssuer) {
|
|
51
|
+
return { ok: false, reason: "issuer_key_resolve_failed" };
|
|
52
|
+
}
|
|
53
|
+
if (typeof payload.vct !== "string" || !opts.acceptedVcts.includes(payload.vct)) {
|
|
54
|
+
return { ok: false, reason: "vct_not_accepted" };
|
|
55
|
+
}
|
|
56
|
+
// Prson always sets an expiry; a credential without one is not Prson's.
|
|
57
|
+
if (typeof payload.exp !== "number")
|
|
58
|
+
return { ok: false, reason: "malformed" };
|
|
59
|
+
if (payload.exp * 1000 < Date.now()) {
|
|
60
|
+
return { ok: false, reason: "vc_expired" };
|
|
61
|
+
}
|
|
62
|
+
// ── 2. Resolve the issuer JWK + verify the JWS signature ───────
|
|
63
|
+
const issuerJwk = await resolveIssuerJwk(header.kid ?? "", opts);
|
|
64
|
+
if (!issuerJwk)
|
|
65
|
+
return { ok: false, reason: "issuer_key_resolve_failed" };
|
|
66
|
+
const issuerKey = await crypto.subtle.importKey("jwk", issuerJwk, { name: "RSASSA-PKCS1-v1_5", hash: "SHA-256" }, false, ["verify"]);
|
|
67
|
+
const issuerOk = await crypto.subtle.verify("RSASSA-PKCS1-v1_5", issuerKey, b64uBytes(sigB64), new TextEncoder().encode(`${hB64}.${pB64}`));
|
|
68
|
+
if (!issuerOk)
|
|
69
|
+
return { ok: false, reason: "issuer_sig_invalid" };
|
|
70
|
+
// ── 2b. Not revoked (the issuer's Token Status List) ─────────────
|
|
71
|
+
const status = await checkCredentialStatus(payload, {
|
|
72
|
+
resolveKey: (kid) => resolveIssuerJwk(kid, opts),
|
|
73
|
+
onUnavailable: opts.status?.onUnavailable,
|
|
74
|
+
cacheSeconds: opts.status?.cacheSeconds,
|
|
75
|
+
});
|
|
76
|
+
if (!status.ok)
|
|
77
|
+
return { ok: false, reason: status.reason };
|
|
78
|
+
// ── 3. Verify every Disclosure digest is in the JWS's _sd ──────
|
|
79
|
+
const sdSet = collectSdDigests(payload);
|
|
80
|
+
const disclosed = [];
|
|
81
|
+
for (const t of discTokens) {
|
|
82
|
+
if (!t)
|
|
83
|
+
continue;
|
|
84
|
+
const arr = JSON.parse(new TextDecoder().decode(b64uBytes(t)));
|
|
85
|
+
if (!Array.isArray(arr) || arr.length < 2) {
|
|
86
|
+
return { ok: false, reason: "disclosure_unmatched" };
|
|
87
|
+
}
|
|
88
|
+
const digest = b64uEncode(new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(t))));
|
|
89
|
+
if (!sdSet.has(digest))
|
|
90
|
+
return { ok: false, reason: "disclosure_unmatched" };
|
|
91
|
+
if (arr.length === 3 && typeof arr[1] === "string") {
|
|
92
|
+
disclosed.push({ name: arr[1], value: arr[2] });
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
// ── 4. Verify the KB-JWT ───────────────────────────────────────
|
|
96
|
+
if (!kbJwt)
|
|
97
|
+
return { ok: false, reason: "kb_missing" };
|
|
98
|
+
const cnf = payload.cnf?.jwk;
|
|
99
|
+
if (!cnf || cnf.kty !== "OKP" || cnf.crv !== "Ed25519") {
|
|
100
|
+
return { ok: false, reason: "kb_missing" };
|
|
101
|
+
}
|
|
102
|
+
const [kbH, kbP, kbS] = kbJwt.split(".");
|
|
103
|
+
if (!kbH || !kbP || !kbS)
|
|
104
|
+
return { ok: false, reason: "kb_sig_invalid" };
|
|
105
|
+
let kbHeader;
|
|
106
|
+
let kbPayload;
|
|
107
|
+
try {
|
|
108
|
+
kbHeader = JSON.parse(new TextDecoder().decode(b64uBytes(kbH)));
|
|
109
|
+
kbPayload = JSON.parse(new TextDecoder().decode(b64uBytes(kbP)));
|
|
110
|
+
}
|
|
111
|
+
catch {
|
|
112
|
+
return { ok: false, reason: "kb_sig_invalid" };
|
|
113
|
+
}
|
|
114
|
+
if (kbHeader.alg !== "EdDSA" || kbHeader.typ !== "kb+jwt") {
|
|
115
|
+
return { ok: false, reason: "kb_sig_invalid" };
|
|
116
|
+
}
|
|
117
|
+
if (kbPayload.aud !== opts.expectedAudience)
|
|
118
|
+
return { ok: false, reason: "aud_mismatch" };
|
|
119
|
+
if (kbPayload.nonce !== opts.expectedNonce)
|
|
120
|
+
return { ok: false, reason: "nonce_mismatch" };
|
|
121
|
+
if (typeof kbPayload.iat !== "number")
|
|
122
|
+
return { ok: false, reason: "kb_iat_stale" };
|
|
123
|
+
const maxAge = opts.maxKbAgeSeconds ?? 60;
|
|
124
|
+
if (Math.abs(Date.now() / 1000 - kbPayload.iat) > maxAge) {
|
|
125
|
+
return { ok: false, reason: "kb_iat_stale" };
|
|
126
|
+
}
|
|
127
|
+
// Per SD-JWT-VC: prefix is "<JWS>~<D_1>~...~<D_n>~" with exactly
|
|
128
|
+
// ONE trailing tilde — N tildes total for N-1 disclosures. The
|
|
129
|
+
// naive `${jws}~${discTokens.join("~")}~` produces TWO trailing
|
|
130
|
+
// tildes when `discTokens.length === 0` (since `[].join === ""`),
|
|
131
|
+
// breaking every no-disclosure presentation (verified-human only,
|
|
132
|
+
// anonymous, anything where the holder filtered out all
|
|
133
|
+
// disclosures). Build it from parts directly so it stays correct
|
|
134
|
+
// at n=0.
|
|
135
|
+
const prefixParts = discTokens.length === 0
|
|
136
|
+
? [jws]
|
|
137
|
+
: [jws, ...discTokens];
|
|
138
|
+
const presentationPrefix = `${prefixParts.join("~")}~`;
|
|
139
|
+
const sdHash = b64uEncode(new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(presentationPrefix))));
|
|
140
|
+
if (kbPayload.sd_hash !== sdHash)
|
|
141
|
+
return { ok: false, reason: "sd_hash_mismatch" };
|
|
142
|
+
const holderKey = await crypto.subtle.importKey("jwk", cnf, { name: "Ed25519" }, false, ["verify"]);
|
|
143
|
+
const kbOk = await crypto.subtle.verify("Ed25519", holderKey, b64uBytes(kbS), new TextEncoder().encode(`${kbH}.${kbP}`));
|
|
144
|
+
if (!kbOk)
|
|
145
|
+
return { ok: false, reason: "kb_sig_invalid" };
|
|
146
|
+
// ── 5. Reassemble disclosed claims ──────────────────────────────
|
|
147
|
+
const claims = {};
|
|
148
|
+
// Always-visible top-level claims from the JWS (minus SD internals).
|
|
149
|
+
for (const [k, v] of Object.entries(payload)) {
|
|
150
|
+
if (k === "_sd" || k === "_sd_alg" || k === "cnf")
|
|
151
|
+
continue;
|
|
152
|
+
if (["iss", "vct", "iat", "exp"].includes(k))
|
|
153
|
+
continue;
|
|
154
|
+
claims[k] = v;
|
|
155
|
+
}
|
|
156
|
+
for (const d of disclosed)
|
|
157
|
+
claims[d.name] = d.value;
|
|
158
|
+
return {
|
|
159
|
+
ok: true,
|
|
160
|
+
claims,
|
|
161
|
+
cnf: { jwk: cnf },
|
|
162
|
+
binding: {
|
|
163
|
+
iat: kbPayload.iat,
|
|
164
|
+
nonce: kbPayload.nonce,
|
|
165
|
+
...walletSessionKeyClaim(kbPayload.prson_wsk),
|
|
166
|
+
},
|
|
167
|
+
credential: {
|
|
168
|
+
vct: payload.vct,
|
|
169
|
+
iss: payload.iss,
|
|
170
|
+
kid: (header.kid ?? ""),
|
|
171
|
+
expiresAt: typeof payload.exp === "number" ? payload.exp * 1000 : 0,
|
|
172
|
+
},
|
|
173
|
+
};
|
|
174
|
+
}
|
|
175
|
+
/**
|
|
176
|
+
* The `prson_wsk` claim: the wallet's X25519 session key (32 bytes,
|
|
177
|
+
* base64url without padding), signed by the cnf key so the data channel
|
|
178
|
+
* can be tied to the holder. Anything malformed counts as absent.
|
|
179
|
+
*/
|
|
180
|
+
function walletSessionKeyClaim(v) {
|
|
181
|
+
if (typeof v !== "string" || !/^[A-Za-z0-9_-]{43}$/.test(v))
|
|
182
|
+
return {};
|
|
183
|
+
return { walletSessionPk: v };
|
|
184
|
+
}
|
|
185
|
+
/** Lazy in-memory cache of the Prson issuer JWKS. 1 h TTL. */
|
|
186
|
+
const jwksCache = new Map();
|
|
187
|
+
async function resolveIssuerJwk(kid, opts) {
|
|
188
|
+
if (!kid)
|
|
189
|
+
return null;
|
|
190
|
+
// did:web:app.prson.net → https://app.prson.net/.well-known/jwt-vc-issuer.
|
|
191
|
+
const host = opts.trustedIssuer.replace(/^did:web:/, "");
|
|
192
|
+
const uri = opts.jwksUri ?? `https://${host}/.well-known/jwt-vc-issuer`;
|
|
193
|
+
const cached = jwksCache.get(uri);
|
|
194
|
+
if (cached && Date.now() - cached.fetchedAt < 60 * 60 * 1000) {
|
|
195
|
+
return cached.keys[kid] ?? null;
|
|
196
|
+
}
|
|
197
|
+
const res = await fetch(uri);
|
|
198
|
+
if (!res.ok)
|
|
199
|
+
return null;
|
|
200
|
+
const body = (await res.json());
|
|
201
|
+
const keys = body.jwks?.keys ?? body.keys ?? [];
|
|
202
|
+
const map = {};
|
|
203
|
+
for (const k of keys) {
|
|
204
|
+
const id = k.kid;
|
|
205
|
+
if (id)
|
|
206
|
+
map[id] = k;
|
|
207
|
+
}
|
|
208
|
+
jwksCache.set(uri, { fetchedAt: Date.now(), keys: map });
|
|
209
|
+
return map[kid] ?? null;
|
|
210
|
+
}
|
|
211
|
+
function collectSdDigests(payload, out = new Set()) {
|
|
212
|
+
if (!payload || typeof payload !== "object")
|
|
213
|
+
return out;
|
|
214
|
+
if (Array.isArray(payload)) {
|
|
215
|
+
for (const v of payload)
|
|
216
|
+
collectSdDigests(v, out);
|
|
217
|
+
return out;
|
|
218
|
+
}
|
|
219
|
+
const obj = payload;
|
|
220
|
+
for (const [k, v] of Object.entries(obj)) {
|
|
221
|
+
if (k === "_sd" && Array.isArray(v)) {
|
|
222
|
+
for (const digest of v) {
|
|
223
|
+
if (typeof digest === "string")
|
|
224
|
+
out.add(digest);
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
else if (typeof v === "object") {
|
|
228
|
+
collectSdDigests(v, out);
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
return out;
|
|
232
|
+
}
|
|
233
|
+
// Returns an ArrayBuffer-backed Uint8Array so it's `BufferSource`-typed
|
|
234
|
+
// under TypeScript 5.7+'s stricter typings (SharedArrayBuffer-backed
|
|
235
|
+
// views are rejected by SubtleCrypto's `verify` signature).
|
|
236
|
+
function b64uBytes(s) {
|
|
237
|
+
const pad = (4 - (s.length % 4)) % 4;
|
|
238
|
+
const std = (s + "=".repeat(pad)).replace(/-/g, "+").replace(/_/g, "/");
|
|
239
|
+
const bin = atob(std);
|
|
240
|
+
const buf = new ArrayBuffer(bin.length);
|
|
241
|
+
const out = new Uint8Array(buf);
|
|
242
|
+
for (let i = 0; i < bin.length; i++)
|
|
243
|
+
out[i] = bin.charCodeAt(i);
|
|
244
|
+
return out;
|
|
245
|
+
}
|
|
246
|
+
function b64uEncode(bytes) {
|
|
247
|
+
let s = "";
|
|
248
|
+
for (let i = 0; i < bytes.length; i++)
|
|
249
|
+
s += String.fromCharCode(bytes[i]);
|
|
250
|
+
return btoa(s).replace(/=+$/g, "").replace(/\+/g, "-").replace(/\//g, "_");
|
|
251
|
+
}
|
|
252
|
+
/**
|
|
253
|
+
* Verify a self-signed anonymous-wallet credential. Spec:
|
|
254
|
+
*
|
|
255
|
+
* header = { typ: "anon-wallet+jwt", alg: "EdDSA" }
|
|
256
|
+
* payload = { iss: <domain>, aud, nonce, iat, exp,
|
|
257
|
+
* vct: ANONYMOUS_WALLET_VCT,
|
|
258
|
+
* cnf: { jwk: <Ed25519 OKP JWK> } }
|
|
259
|
+
*
|
|
260
|
+
* The signing key IS cnf.jwk — there's no separate issuer key to
|
|
261
|
+
* resolve. The verifier checks aud/nonce/exp and the Ed25519 sig.
|
|
262
|
+
*
|
|
263
|
+
* This is only accepted by [verifyPresentation] when `acceptedVcts`
|
|
264
|
+
* includes ANONYMOUS_WALLET_VCT, which only happens when the host
|
|
265
|
+
* site passed `allowAnonymous: true` to PrsonLogin.signIn().
|
|
266
|
+
*/
|
|
267
|
+
async function verifyAnonymousWallet(jws, opts) {
|
|
268
|
+
const [hB64, pB64, sigB64] = jws.split(".");
|
|
269
|
+
if (!hB64 || !pB64 || !sigB64)
|
|
270
|
+
return { ok: false, reason: "malformed" };
|
|
271
|
+
let header;
|
|
272
|
+
let payload;
|
|
273
|
+
try {
|
|
274
|
+
header = JSON.parse(new TextDecoder().decode(b64uBytes(hB64)));
|
|
275
|
+
payload = JSON.parse(new TextDecoder().decode(b64uBytes(pB64)));
|
|
276
|
+
}
|
|
277
|
+
catch {
|
|
278
|
+
return { ok: false, reason: "malformed" };
|
|
279
|
+
}
|
|
280
|
+
if (header.alg !== "EdDSA" || header.typ !== "anon-wallet+jwt") {
|
|
281
|
+
return { ok: false, reason: "malformed" };
|
|
282
|
+
}
|
|
283
|
+
if (payload.vct !== ANONYMOUS_WALLET_VCT) {
|
|
284
|
+
return { ok: false, reason: "vct_not_accepted" };
|
|
285
|
+
}
|
|
286
|
+
const cnf = payload.cnf?.jwk;
|
|
287
|
+
if (!cnf || cnf.kty !== "OKP" || cnf.crv !== "Ed25519") {
|
|
288
|
+
return { ok: false, reason: "kb_missing" };
|
|
289
|
+
}
|
|
290
|
+
if (payload.aud !== opts.expectedAudience) {
|
|
291
|
+
return { ok: false, reason: "aud_mismatch" };
|
|
292
|
+
}
|
|
293
|
+
if (payload.nonce !== opts.expectedNonce) {
|
|
294
|
+
return { ok: false, reason: "nonce_mismatch" };
|
|
295
|
+
}
|
|
296
|
+
const nowSec = Math.floor(Date.now() / 1000);
|
|
297
|
+
if (typeof payload.exp !== "number" || payload.exp < nowSec) {
|
|
298
|
+
return { ok: false, reason: "vc_expired" };
|
|
299
|
+
}
|
|
300
|
+
if (typeof payload.iat !== "number" || Math.abs(nowSec - payload.iat) > (opts.maxKbAgeSeconds ?? 60)) {
|
|
301
|
+
return { ok: false, reason: "kb_iat_stale" };
|
|
302
|
+
}
|
|
303
|
+
// The signing key is cnf.jwk itself — no separate issuer key to
|
|
304
|
+
// resolve. A correct signature here proves the holder controls the
|
|
305
|
+
// pk they're claiming.
|
|
306
|
+
const key = await crypto.subtle.importKey("jwk", cnf, { name: "Ed25519" }, false, ["verify"]);
|
|
307
|
+
const ok = await crypto.subtle.verify("Ed25519", key, b64uBytes(sigB64), new TextEncoder().encode(`${hB64}.${pB64}`));
|
|
308
|
+
if (!ok)
|
|
309
|
+
return { ok: false, reason: "issuer_sig_invalid" };
|
|
310
|
+
return {
|
|
311
|
+
ok: true,
|
|
312
|
+
claims: {
|
|
313
|
+
// Anonymous credentials carry no profile data — just the marker
|
|
314
|
+
// that the user controls the signing key. The host site treats
|
|
315
|
+
// cnf.jwk.x as the stable per-user id on this domain.
|
|
316
|
+
anonymous: true,
|
|
317
|
+
},
|
|
318
|
+
cnf: { jwk: cnf },
|
|
319
|
+
binding: {
|
|
320
|
+
iat: payload.iat,
|
|
321
|
+
nonce: payload.nonce,
|
|
322
|
+
...walletSessionKeyClaim(payload.prson_wsk),
|
|
323
|
+
},
|
|
324
|
+
credential: {
|
|
325
|
+
vct: ANONYMOUS_WALLET_VCT,
|
|
326
|
+
iss: typeof payload.iss === "string" ? payload.iss : opts.trustedIssuer,
|
|
327
|
+
kid: "",
|
|
328
|
+
expiresAt: payload.exp * 1000,
|
|
329
|
+
},
|
|
330
|
+
};
|
|
331
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,61 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@prson/login-sdk",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"description": "
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"private": false,
|
|
5
|
+
"description": "Frontend-first sign-in SDK that delivers a verifiable credential from a Prson mobile wallet to your website over an end-to-end-encrypted WebRTC channel. See README.md.",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"main": "./dist/index.js",
|
|
8
|
+
"module": "./dist/index.js",
|
|
9
|
+
"types": "./dist/index.d.ts",
|
|
10
|
+
"files": [
|
|
11
|
+
"dist",
|
|
12
|
+
"!dist/**/*.test.*",
|
|
13
|
+
"!dist/test",
|
|
14
|
+
"README.md",
|
|
15
|
+
"LICENSE"
|
|
16
|
+
],
|
|
17
|
+
"scripts": {
|
|
18
|
+
"build": "tsc && esbuild src/index.ts --bundle --format=esm --target=es2020 --platform=browser --outfile=dist/index.js --sourcemap",
|
|
19
|
+
"build:example": "esbuild src/index.ts --bundle --format=esm --target=es2020 --platform=browser --outfile=../../examples/plain-html/prson-login.js --sourcemap",
|
|
20
|
+
"watch:example": "esbuild src/index.ts --bundle --format=esm --target=es2020 --platform=browser --outfile=../../examples/plain-html/prson-login.js --sourcemap --watch",
|
|
21
|
+
"typecheck": "tsc --noEmit",
|
|
22
|
+
"test": "tsc && node --test dist/session.test.js dist/status.test.js dist/notify.test.js dist/channel.test.js",
|
|
23
|
+
"prepublishOnly": "npm test && npm run build"
|
|
24
|
+
},
|
|
25
|
+
"dependencies": {
|
|
26
|
+
"@stablelib/base64": "^1.0.1",
|
|
27
|
+
"@stablelib/nacl": "^1.0.4",
|
|
28
|
+
"@stablelib/random": "^1.0.2"
|
|
29
|
+
},
|
|
30
|
+
"devDependencies": {
|
|
31
|
+
"@types/node": "^25.9.1",
|
|
32
|
+
"esbuild": "^0.24.0",
|
|
33
|
+
"typescript": "^5.4.0"
|
|
34
|
+
},
|
|
35
|
+
"keywords": [
|
|
36
|
+
"sd-jwt-vc",
|
|
37
|
+
"verifiable-credentials",
|
|
38
|
+
"openid4vp",
|
|
39
|
+
"passwordless",
|
|
40
|
+
"prson",
|
|
41
|
+
"webrtc",
|
|
42
|
+
"cloudflare-turn",
|
|
43
|
+
"sign-in"
|
|
44
|
+
],
|
|
45
|
+
"repository": {
|
|
46
|
+
"type": "git",
|
|
47
|
+
"url": "git+https://github.com/Yumankind/prson-sdk.git",
|
|
48
|
+
"directory": "packages/browser"
|
|
49
|
+
},
|
|
50
|
+
"license": "Apache-2.0",
|
|
51
|
+
"author": "Yumankind OÜ <support@prson.net>",
|
|
52
|
+
"homepage": "https://prson.net/developers",
|
|
53
|
+
"bugs": {
|
|
54
|
+
"url": "https://github.com/Yumankind/prson-sdk/issues",
|
|
55
|
+
"email": "security@yumankind.com"
|
|
56
|
+
},
|
|
57
|
+
"publishConfig": {
|
|
58
|
+
"access": "public",
|
|
59
|
+
"provenance": true
|
|
60
|
+
}
|
|
61
|
+
}
|