@prson/login-sdk 0.1.0 → 0.2.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/README.md CHANGED
@@ -48,8 +48,10 @@ type SignInOptions = {
48
48
  /** What you require from the holder. The SDK presents this to the
49
49
  * user in the wallet's login drawer — the user can refuse. */
50
50
  required?: {
51
- /** 1..6. Default: no minimum. Use 5 to force NFC-backed VC. */
52
- minVerificationLevel?: 1 | 2 | 3 | 4 | 5 | 6;
51
+ /** 0..6. Omitted ⇒ 1 (a live selfie, checked on the phone). 5 needs a
52
+ * chip-checked passport or ID card. See "Choose your level" in the
53
+ * top-level README. */
54
+ minVerificationLevel?: 0 | 1 | 2 | 3 | 4 | 5 | 6;
53
55
 
54
56
  /** Standard SD-JWT-VC claim names (e.g. "given_name", "birthdate").
55
57
  * Omit to ask for `verified_human` only. */
@@ -61,6 +63,12 @@ type SignInOptions = {
61
63
 
62
64
  /** Default: "personal". */
63
65
  identityType?: "personal" | "organization";
66
+
67
+ /** Ask for a unique-human id: the same `uniqueIdHash` for one person
68
+ * on your site whatever phone or install they use (level 5+).
69
+ * `result.prsonId` is NOT one per person; this is. Verify it on your
70
+ * server with `verifyUniqueHumanId`. */
71
+ uniqueHumanId?: boolean;
64
72
  };
65
73
 
66
74
  /** If `true`, the SDK ALSO accepts a self-signed **anonymous-wallet**
@@ -219,6 +227,14 @@ class PrsonLogin {
219
227
 
220
228
  ## Behaviour notes
221
229
 
230
+ - **Content-Security-Policy.** A site with a CSP must allow Prson's hosts
231
+ in `connect-src` and give the injected styles a nonce
232
+ (`<meta property="csp-nonce" nonce="…">`). The exact lines are in the
233
+ top-level README, under "Content-Security-Policy". A blocked request
234
+ makes `signIn()` reject with `PrsonCspError`, which says what to add.
235
+ - **Codes last 3 minutes** and work once. The dialog offers "Get a new
236
+ code" when one expires, and `signIn()` keeps waiting.
237
+
222
238
  - **Same-device detection.** If the SDK detects a touch device + the
223
239
  Prson app is installed (universal-link probe), the QR is replaced
224
240
  by a "Sign in with Prson" button. The user taps it, the wallet
package/dist/api.js CHANGED
@@ -6,6 +6,7 @@
6
6
  * /session/claim for the wallet. See `../../../../cloudflare-workers/signaling-worker`
7
7
  * for the server impl and `../../ARCHITECTURE.md` for the spec.
8
8
  */
9
+ import { PrsonLoginError } from "./errors.js";
9
10
  import { SIGNALING_BASE } from "./index.js";
10
11
  /**
11
12
  * POST /session/draft on the Cloudflare Worker. Anonymous + IP rate-
@@ -24,9 +25,9 @@ export async function createDraft(request, opts = {}) {
24
25
  if (!res.ok) {
25
26
  const text = await safeText(res);
26
27
  if (res.status === 429) {
27
- throw new Error("Too many login sessions from this network — please retry shortly.");
28
+ throw new PrsonLoginError("rate_limited", "Too many login sessions from this network — please retry shortly.");
28
29
  }
29
- throw new Error(`createDraft failed: HTTP ${res.status} ${text || res.statusText}`);
30
+ throw new PrsonLoginError("network", `createDraft failed: HTTP ${res.status} ${text || res.statusText}`);
30
31
  }
31
32
  return (await res.json());
32
33
  }
package/dist/csp.d.ts ADDED
@@ -0,0 +1,39 @@
1
+ /**
2
+ * Content-Security-Policy help.
3
+ *
4
+ * A page whose CSP doesn't allow Prson's hosts sees a plain "Failed to
5
+ * fetch" or a WebSocket error. While a sign-in runs, the SDK listens for
6
+ * the browser's `securitypolicyviolation` events; when one names a Prson
7
+ * host, the failure is reported as a `PrsonCspError` that says which
8
+ * directive blocked what and which sources to add.
9
+ */
10
+ import { PrsonLoginError } from "./errors.js";
11
+ /** Hosts the browser SDK talks to in production (see the README's CSP section). */
12
+ export declare const PRSON_CONNECT_SRC: readonly ["https://signaling.prson.net", "wss://signaling.prson.net", "https://app.prson.net", "https://api.prson.net"];
13
+ /** Thrown by `signIn()` when the page's Content-Security-Policy blocked Prson. */
14
+ export declare class PrsonCspError extends PrsonLoginError {
15
+ readonly directive: string;
16
+ readonly blockedUri: string;
17
+ readonly allow: string[];
18
+ constructor(directive: string, blockedUri: string, allow: string[]);
19
+ }
20
+ /** The connect-src sources a sign-in against `signalingBase` needs. */
21
+ export declare function connectSourcesFor(signalingBase: string, issuerJwksUri?: string): string[];
22
+ export type CspWatch = {
23
+ /** The error to throw instead of `err` when a CSP block explains it, else `err`. */
24
+ explain(err: unknown): Promise<unknown>;
25
+ stop(): void;
26
+ };
27
+ /**
28
+ * Watch for CSP blocks of Prson hosts during a sign-in. A no-op outside
29
+ * a browser.
30
+ */
31
+ export declare function watchCsp(signalingBase: string, issuerJwksUri?: string): CspWatch;
32
+ /**
33
+ * The nonce for injected `<style>` elements, for pages whose `style-src`
34
+ * uses a nonce. Read from the `nonce` attribute of
35
+ * `<meta property="csp-nonce" nonce="…">` (the convention Vite uses).
36
+ * Only the `nonce` attribute: browsers hide it from CSS selectors, while a
37
+ * nonce in `content` could be read out by injected CSS.
38
+ */
39
+ export declare function cspStyleNonce(): string | undefined;
package/dist/csp.js ADDED
@@ -0,0 +1,125 @@
1
+ /**
2
+ * Content-Security-Policy help.
3
+ *
4
+ * A page whose CSP doesn't allow Prson's hosts sees a plain "Failed to
5
+ * fetch" or a WebSocket error. While a sign-in runs, the SDK listens for
6
+ * the browser's `securitypolicyviolation` events; when one names a Prson
7
+ * host, the failure is reported as a `PrsonCspError` that says which
8
+ * directive blocked what and which sources to add.
9
+ */
10
+ import { PrsonLoginError } from "./errors.js";
11
+ /** Hosts the browser SDK talks to in production (see the README's CSP section). */
12
+ export const PRSON_CONNECT_SRC = [
13
+ "https://signaling.prson.net",
14
+ "wss://signaling.prson.net",
15
+ "https://app.prson.net",
16
+ "https://api.prson.net",
17
+ ];
18
+ /** Thrown by `signIn()` when the page's Content-Security-Policy blocked Prson. */
19
+ export class PrsonCspError extends PrsonLoginError {
20
+ constructor(directive, blockedUri, allow) {
21
+ super("csp_blocked", `This page's Content-Security-Policy blocked Prson sign-in: ${directive} doesn't allow ${blockedUri}. ` +
22
+ `Add to connect-src: ${allow.join(" ")}`);
23
+ this.name = "PrsonCspError";
24
+ this.directive = directive;
25
+ this.blockedUri = blockedUri;
26
+ this.allow = allow;
27
+ }
28
+ }
29
+ /** The connect-src sources a sign-in against `signalingBase` needs. */
30
+ export function connectSourcesFor(signalingBase, issuerJwksUri) {
31
+ const out = new Set();
32
+ try {
33
+ const u = new URL(signalingBase);
34
+ out.add(u.origin);
35
+ out.add(`${u.protocol === "http:" ? "ws" : "wss"}://${u.host}`);
36
+ }
37
+ catch {
38
+ /* a bad base fails elsewhere with its own error */
39
+ }
40
+ if (issuerJwksUri) {
41
+ // The dev issuer: its keys and revocation lists are on the dev API.
42
+ try {
43
+ out.add(new URL(issuerJwksUri).origin);
44
+ }
45
+ catch {
46
+ /* ignore a bad override */
47
+ }
48
+ }
49
+ else {
50
+ out.add("https://app.prson.net");
51
+ out.add("https://api.prson.net");
52
+ }
53
+ return [...out];
54
+ }
55
+ function hostOf(uri) {
56
+ try {
57
+ return new URL(uri).host;
58
+ }
59
+ catch {
60
+ return null;
61
+ }
62
+ }
63
+ function originOf(uri) {
64
+ try {
65
+ const u = new URL(uri);
66
+ return `${u.protocol}//${u.host}`;
67
+ }
68
+ catch {
69
+ return "(unknown)";
70
+ }
71
+ }
72
+ /**
73
+ * Watch for CSP blocks of Prson hosts during a sign-in. A no-op outside
74
+ * a browser.
75
+ */
76
+ export function watchCsp(signalingBase, issuerJwksUri) {
77
+ if (typeof document === "undefined" || typeof document.addEventListener !== "function") {
78
+ return { explain: async (e) => e, stop: () => { } };
79
+ }
80
+ const allow = connectSourcesFor(signalingBase, issuerJwksUri);
81
+ const prsonHosts = new Set(allow.map(hostOf).filter((h) => !!h));
82
+ let seen = null;
83
+ const onViolation = (ev) => {
84
+ // Only the browser's own reports: a page script can dispatch a fake one.
85
+ if (!ev.isTrusted)
86
+ return;
87
+ const e = ev;
88
+ const host = hostOf(e.blockedURI);
89
+ if (!seen && host && (prsonHosts.has(host) || host.endsWith(".prson.net"))) {
90
+ // The origin only: the path can carry a request id.
91
+ seen = { directive: e.effectiveDirective || e.violatedDirective, blockedUri: originOf(e.blockedURI) };
92
+ }
93
+ };
94
+ document.addEventListener("securitypolicyviolation", onViolation);
95
+ return {
96
+ async explain(err) {
97
+ // The violation event can arrive just after the failed fetch or
98
+ // WebSocket rejects: give it a turn of the event loop.
99
+ if (!seen)
100
+ await new Promise((r) => setTimeout(r, 0));
101
+ if (!seen)
102
+ return err;
103
+ const s = seen;
104
+ return new PrsonCspError(s.directive, s.blockedUri, allow);
105
+ },
106
+ stop() {
107
+ document.removeEventListener("securitypolicyviolation", onViolation);
108
+ },
109
+ };
110
+ }
111
+ /**
112
+ * The nonce for injected `<style>` elements, for pages whose `style-src`
113
+ * uses a nonce. Read from the `nonce` attribute of
114
+ * `<meta property="csp-nonce" nonce="…">` (the convention Vite uses).
115
+ * Only the `nonce` attribute: browsers hide it from CSS selectors, while a
116
+ * nonce in `content` could be read out by injected CSS.
117
+ */
118
+ export function cspStyleNonce() {
119
+ if (typeof document === "undefined")
120
+ return undefined;
121
+ const m = document.querySelector('meta[property="csp-nonce"]');
122
+ if (!m)
123
+ return undefined;
124
+ return m.nonce || m.getAttribute("nonce") || undefined;
125
+ }
@@ -0,0 +1,40 @@
1
+ /**
2
+ * Every error `signIn()` rejects with carries a stable `code`, so a site
3
+ * can branch on it instead of matching message text. Messages may change;
4
+ * codes don't (new codes may be added).
5
+ */
6
+ export type PrsonLoginErrorCode =
7
+ /** A newer signIn() call, or the person closed the dialog. */
8
+ "aborted"
9
+ /** The page's Content-Security-Policy blocked a Prson host (PrsonCspError). */
10
+ | "csp_blocked"
11
+ /** The code ran out before anyone approved it. */
12
+ | "expired"
13
+ /** Too many sign-ins from this network; retry shortly. */
14
+ | "rate_limited"
15
+ /** Prson's relay or the phone couldn't be reached. */
16
+ | "network"
17
+ /** The credential failed a check; `reason` says which (verifier reasons, e.g. aud_mismatch). */
18
+ | "presentation_rejected"
19
+ /** The person's verification level is below `required.minVerificationLevel`. */
20
+ | "level_too_low"
21
+ /** `required.uniqueHumanId` was set and no unique-human id came back. */
22
+ | "unique_human_missing"
23
+ /** The phone sent something the SDK doesn't understand. */
24
+ | "protocol"
25
+ /** A signIn() option is wrong (nonce, returnUrl). */
26
+ | "invalid_options"
27
+ /** Anything else; `cause` holds the original error. */
28
+ | "unknown";
29
+ export declare class PrsonLoginError extends Error {
30
+ readonly code: PrsonLoginErrorCode;
31
+ /** For presentation_rejected: the verifier's reason, such as "nonce_mismatch". */
32
+ readonly reason?: string;
33
+ /** For "unknown" (and wrapped errors): the original error. */
34
+ readonly cause?: unknown;
35
+ constructor(code: PrsonLoginErrorCode, message: string, reason?: string, cause?: unknown);
36
+ }
37
+ /** The code for an error from the relay or the connection (signaling closes name a reason). */
38
+ export declare function closedCode(reason: string): PrsonLoginErrorCode;
39
+ /** Any error as a PrsonLoginError: a failed fetch is "network", anything else "unknown" (the original is its cause). */
40
+ export declare function asLoginError(e: unknown): PrsonLoginError;
package/dist/errors.js ADDED
@@ -0,0 +1,28 @@
1
+ /**
2
+ * Every error `signIn()` rejects with carries a stable `code`, so a site
3
+ * can branch on it instead of matching message text. Messages may change;
4
+ * codes don't (new codes may be added).
5
+ */
6
+ export class PrsonLoginError extends Error {
7
+ constructor(code, message, reason, cause) {
8
+ super(message);
9
+ this.name = "PrsonLoginError";
10
+ this.code = code;
11
+ if (reason !== undefined)
12
+ this.reason = reason;
13
+ if (cause !== undefined)
14
+ this.cause = cause;
15
+ }
16
+ }
17
+ /** The code for an error from the relay or the connection (signaling closes name a reason). */
18
+ export function closedCode(reason) {
19
+ return /expir/i.test(reason) ? "expired" : "network";
20
+ }
21
+ /** Any error as a PrsonLoginError: a failed fetch is "network", anything else "unknown" (the original is its cause). */
22
+ export function asLoginError(e) {
23
+ if (e instanceof PrsonLoginError)
24
+ return e;
25
+ const message = e instanceof Error ? e.message : String(e);
26
+ const code = /Failed to fetch|NetworkError|Load failed/i.test(message) ? "network" : "unknown";
27
+ return new PrsonLoginError(code, message, undefined, e);
28
+ }
package/dist/index.d.ts CHANGED
@@ -16,6 +16,7 @@
16
16
  * for the wire spec.
17
17
  */
18
18
  import { PrsonLoginSession, type ExpiryReason, type Renewal } from "./session.js";
19
+ import { PrsonLoginError } from "./errors.js";
19
20
  export type SignInOptions = {
20
21
  domain?: string;
21
22
  /**
@@ -94,21 +95,25 @@ export type SignInOptions = {
94
95
  */
95
96
  allowAnonymous?: boolean;
96
97
  /**
97
- * If `true`, the wallet generates a **fresh random Ed25519 keypair**
98
- * for this single login instead of the deterministic per-domain
99
- * HKDF derivation. The credential's `cnf.jwk` is therefore
100
- * **different on every sign-in attempt** — there is no stable per-
101
- * user id, and a future mnemonic compromise cannot retroactively
102
- * link the user across sessions on this site.
98
+ * If `true`, the wallet signs in with a **device-only key for your
99
+ * site** instead of the per-site key derived from the person's
100
+ * recovery phrase. The wallet makes a random Ed25519 keypair on the
101
+ * first sign-in to your domain, keeps its seed in this phone's secure
102
+ * storage only, and reuses it on later sign-ins from the same phone,
103
+ * so `cnf.jwk.x` stays the same there and the person returns to the
104
+ * same account. A new key is made after the person revokes your site
105
+ * in the wallet, on another phone, or after reinstalling the app.
103
106
  *
104
- * Trade-off: `cnf.jwk.x` is no longer a per-user identifier on this
105
- * domain. Sites that key sessions off `cnf.jwk.x` must derive a
106
- * usable account id by some other means (e.g. a user-chosen
107
- * username on first visit). Best fit for read-only / single-use
108
- * flows where re-identification on return is irrelevant.
107
+ * What it buys: the key isn't derived from the recovery phrase, so a
108
+ * future phrase compromise can't retroactively link the person to
109
+ * your site, and no notification handle (one per wallet and site) is
110
+ * offered. What it doesn't: sign-ins from the same phone are linkable
111
+ * by `cnf.jwk.x`, like the default — it is not a one-time key.
109
112
  *
110
- * Combine with `allowAnonymous: true` for a fully unlinkable
111
- * anonymous flow. Default false.
113
+ * Trade-off: the account is tied to the phone. Losing the phone or
114
+ * the app loses the key, so pair it with your own recovery path.
115
+ * Combine with `allowAnonymous: true` for an account that carries no
116
+ * identity at all. Default false.
112
117
  *
113
118
  * Closes [SECURITY-AUDIT §M-5](../../SECURITY-AUDIT-2026-05-28.md).
114
119
  */
@@ -283,6 +288,17 @@ export declare const PROTOCOL_VERSION = "prson_vp_v1";
283
288
  */
284
289
  export declare const ENVELOPE_VERSION = 2;
285
290
  export declare const TRUSTED_ISSUER = "did:web:app.prson.net";
291
+ /** The dev API's issuer and where it publishes its keys. Trusted only with
292
+ * `environment: "dev"`; never accept dev credentials in production. */
293
+ export declare const TRUSTED_ISSUER_DEV = "did:web:prson-app-dev.web.app:.well-known:dev";
294
+ export declare const ISSUER_JWKS_DEV = "https://prson-api-dev.powerhouse.workers.dev/.well-known/jwt-vc-issuer";
295
+ /** Which issuer a sign-in trusts: production's, or the dev API's with `environment: "dev"`. */
296
+ export declare function issuerFor(opts: {
297
+ environment?: "production" | "dev";
298
+ }): {
299
+ trustedIssuer: string;
300
+ jwksUri?: string;
301
+ };
286
302
  export declare const KNOWN_VCTS: readonly ["https://app.prson.net/credentials/verified-human/v1", "https://app.prson.net/credentials/verified-identity/v1"];
287
303
  /** Self-signed wallet credential — accepted only when the SDK is
288
304
  * invoked with `allowAnonymous: true`. Carries only `cnf.jwk` + the
@@ -307,7 +323,7 @@ export declare function resolveSignalingBase(opts: {
307
323
  * this — the user's second click is the cancellation signal — but
308
324
  * the typed error lets you distinguish it from real failures.
309
325
  */
310
- export declare class LoginAbortedError extends Error {
326
+ export declare class LoginAbortedError extends PrsonLoginError {
311
327
  constructor(message?: string);
312
328
  }
313
329
  export declare class PrsonLogin {
@@ -337,6 +353,8 @@ export declare class PrsonLogin {
337
353
  /** Where "Don't have Prson? Get it" points unless `ui.getAppUrl` says otherwise. */
338
354
  export declare const GET_APP_URL = "https://app.prson.net/";
339
355
  export { PrsonLoginSession };
356
+ export { PrsonCspError, PRSON_CONNECT_SRC, connectSourcesFor, cspStyleNonce } from "./csp.js";
357
+ export { PrsonLoginError, type PrsonLoginErrorCode } from "./errors.js";
340
358
  export { NOTIFY_HANDLE, notifyHandleFrom } from "./notify.js";
341
359
  export type { LoginQrContext, LoginQrHandle, LoginQrRenderer, LoginUiState } from "./qr.js";
342
360
  export type { Renewal };