@prson/login-sdk 0.0.0-stage → 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.
@@ -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
+ }
@@ -0,0 +1,363 @@
1
+ /**
2
+ * @prson/login-sdk — browser runtime.
3
+ *
4
+ * Top-level entry point: `PrsonLogin.signIn(opts)` orchestrates the
5
+ * whole flow. The pieces underneath are:
6
+ *
7
+ * ┌── ./session.ts — PrsonLoginSession (state machine + events)
8
+ * ├── ./signaling.ts — WebSocket to the Cloudflare Worker
9
+ * ├── ./transport.ts — RTCPeerConnection + data channel
10
+ * ├── ./crypto.ts — X25519 ephemeral keypair + NaCl box decrypt
11
+ * ├── ./verify.ts — verify issuer JWS + KB-JWT in the browser
12
+ * ├── ./qr.ts — render the https://app.prson.net/login/v1?... QR
13
+ * └── ./api.ts — typed createLoginSession + resolveLoginSession
14
+ *
15
+ * See ../../README.md for integration. See ../../../ARCHITECTURE.md
16
+ * for the wire spec.
17
+ */
18
+ import { PrsonLoginSession, type ExpiryReason, type Renewal } from "./session.js";
19
+ import { PrsonLoginError } from "./errors.js";
20
+ export type SignInOptions = {
21
+ domain?: string;
22
+ /**
23
+ * A one-time value your BACKEND made for this sign-in (at least 16 random
24
+ * bytes, base64url: 22-128 characters of `A-Z a-z 0-9 - _`). Store it
25
+ * server-side, then verify the presentation there with
26
+ * `verifyPresentation(presentation, { expectedNonce, expectedAudience })`
27
+ * and delete it, so a captured presentation can't be replayed to your
28
+ * backend. Omitted: the SDK makes one in the browser, which only protects
29
+ * the in-browser check — not enough for a backend that trusts the result.
30
+ *
31
+ * May also be a function returning one (sync or async). The SDK then
32
+ * calls it once per code it shows, so a refreshed code (after expiry or
33
+ * an error) gets a fresh backend nonce without your page calling
34
+ * `signIn()` again. `SignInResult.nonce` says which one the presentation
35
+ * is bound to.
36
+ */
37
+ nonce?: string | (() => string | Promise<string>);
38
+ /**
39
+ * Which Prson backend environment to sign in against. `"dev"` points
40
+ * the flow at the dev signaling Worker (`signaling-dev.prson.net`);
41
+ * omit (or `"production"`) for the live environment. For a custom /
42
+ * local Worker, set `signalingBase` instead (it takes precedence).
43
+ * Default `"production"`.
44
+ */
45
+ environment?: "production" | "dev";
46
+ /**
47
+ * Explicit signaling Worker base URL — overrides `environment`. Use
48
+ * for a local Worker (`https://localhost:8787`) or any non-standard
49
+ * deployment. The Worker returns the matching WebSocket URL in its
50
+ * draft response, so this single value steers the whole flow.
51
+ */
52
+ signalingBase?: string;
53
+ required?: {
54
+ /**
55
+ * Minimum identity verification level (0–6). Omitted ⇒ 1.
56
+ *
57
+ * `0` opts into **pseudonymous identity sign-in**: the wallet may
58
+ * present an UNVERIFIED identity, and the minted credential
59
+ * honestly claims `verified_human: false` / `verification_level: 0`.
60
+ * You still get the stable per-domain `sub` (cnf.jwk continuity) —
61
+ * what you give up is any assurance a real, unique human is behind
62
+ * it. Distinct from `allowAnonymous`, which is identity-less: a
63
+ * level-0 identity sign-in carries the user's chosen identity and
64
+ * survives across sessions; anonymous carries only a key.
65
+ */
66
+ minVerificationLevel?: 0 | 1 | 2 | 3 | 4 | 5 | 6;
67
+ requiredClaims?: string[];
68
+ predicates?: string[];
69
+ identityType?: "personal" | "organization";
70
+ /**
71
+ * Require a **domain-scoped unique-human id**: a notary-signed
72
+ * pairwise identifier anchored to the user's verified government
73
+ * document. Proves "one unique, document-verified human at YOUR
74
+ * domain" (sybil resistance) without any cross-site correlation
75
+ * handle. The wallet only offers document-backed identities
76
+ * (level ≥ 4) when this is set; the result carries
77
+ * `uniqueHumanId` for SERVER-SIDE verification.
78
+ */
79
+ uniqueHumanId?: boolean;
80
+ };
81
+ /**
82
+ * If `true`, the SDK ALSO accepts an **anonymous-wallet** credential
83
+ * — a self-signed JWT issued by the wallet's per-domain Ed25519 key,
84
+ * with no notary involvement. The wallet's login drawer surfaces an
85
+ * "Sign in anonymously" option to the user. The credential carries
86
+ * only `cnf.jwk` + `aud` + `nonce` + `iat` + `exp` (no
87
+ * `verified_human`, no document fields, no predicates). The
88
+ * verifier treats `cnf.jwk.x` as the stable per-user identifier on
89
+ * this domain.
90
+ *
91
+ * If a verified credential is presented when `allowAnonymous: true`
92
+ * AND `required.*` constraints are set, the verified credential is
93
+ * still checked against those constraints — the relaxation only
94
+ * applies to the anonymous fallback. Default false.
95
+ */
96
+ allowAnonymous?: boolean;
97
+ /**
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.
106
+ *
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.
112
+ *
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.
117
+ *
118
+ * Closes [SECURITY-AUDIT §M-5](../../SECURITY-AUDIT-2026-05-28.md).
119
+ */
120
+ ephemeralIdentity?: boolean;
121
+ /**
122
+ * Sponsorship: pay for premium verifications your users need.
123
+ *
124
+ * If your `required.predicates` include facts that need a PAID
125
+ * verification the user may not have yet (e.g. `phone_verified` —
126
+ * SMS costs credits), create a **sponsorship grant** from your
127
+ * company wallet (Prson app → `createSponsorshipGrant`) and put its
128
+ * id here. The user's wallet then routes those verification costs
129
+ * to your grant instead of the user.
130
+ *
131
+ * Safe to expose in page source: the grantId authorises nothing by
132
+ * itself. Every redemption is validated server-side against the
133
+ * STORED grant — bound to YOUR domain, capped per user (default
134
+ * once), capped in total budget, expiring, and instantly revocable.
135
+ */
136
+ sponsorship?: {
137
+ grantId: string;
138
+ };
139
+ /**
140
+ * **App-to-app return leg** (same-device native flows). An HTTPS URL
141
+ * on YOUR login domain that the wallet opens after the credential
142
+ * has been delivered — typically your Universal Link / Android App
143
+ * Link, so the OS bounces the user straight back into your native
144
+ * app (only the app your domain vouches for via AASA /
145
+ * assetlinks.json receives it).
146
+ *
147
+ * Constraints (enforced both here and in the wallet):
148
+ * - `https://` only — custom schemes are refused (any installed
149
+ * app could claim a custom scheme; app links are domain-proven).
150
+ * - The URL's host MUST equal the login domain exactly.
151
+ *
152
+ * Only set this for same-device flows (your site opened inside a
153
+ * Custom Tab / SFSafariViewController from your app). In cross-device
154
+ * QR flows the wallet is on a different phone — it would open your
155
+ * site there, which is harmless but pointless.
156
+ */
157
+ returnUrl?: string;
158
+ ttlMinutes?: number;
159
+ ui?: {
160
+ /**
161
+ * Render the code inline in this element instead of the SDK's own
162
+ * dialog. The dialog is the default and the recommended experience.
163
+ */
164
+ mountQrInto?: string | HTMLElement;
165
+ /** `"auto"` (default) follows `prefers-color-scheme`. The code itself is always dark on white. */
166
+ theme?: "light" | "dark" | "auto";
167
+ /** Where "Don't have Prson? Get it" points. Default https://app.prson.net/. */
168
+ getAppUrl?: string;
169
+ };
170
+ defer?: boolean;
171
+ /**
172
+ * QR-mode only: opt in to **remote navigation**. The wallet shows a
173
+ * persistent banner that opens a bottom drawer with Prev / Next /
174
+ * Submit (Enter) / Logout / (optional) Mouse buttons. The host
175
+ * page's currently-focused input is mirrored on the phone so the
176
+ * user can edit / clear / replace the value with the phone
177
+ * keyboard, and edits stream back into the DOM in real time.
178
+ *
179
+ * Auto-wires when the SDK detects a QR-mode sign-in (the QR encodes
180
+ * `remoteNavigation: true` for the wallet to honour). Same-device
181
+ * universal-link flows ignore the flag — the banner would be
182
+ * redundant when the wallet is on the same device as the page.
183
+ *
184
+ * Pair with [`enableRemoteNavigation`] to install the DOM focus
185
+ * listeners that mirror the active input. Default false.
186
+ */
187
+ remoteNavigation?: boolean;
188
+ /**
189
+ * **Mouse control pre-granted at sign-in.** When true, the wallet's
190
+ * persistent banner drawer enables the Touchpad / Magic wand
191
+ * buttons from the moment the session lands, so the user can
192
+ * start driving the cursor without the host ever issuing a
193
+ * `kind: "mouse"` request.
194
+ *
195
+ * The capability **persists** for the session lifetime — closing
196
+ * the controller doesn't revoke it; the user can re-open it from
197
+ * the drawer at any time. The host still calls [`bindMouse`] to
198
+ * mount the on-page cursor; when this flag is set, that call
199
+ * installs an *ambient* mouse-update subscriber so wallet-
200
+ * initiated streams (which carry no `requestId` matched to a
201
+ * pending `request()`) land correctly. Existing `requestMouse`
202
+ * round-trips still work in parallel.
203
+ *
204
+ * The wallet shows a chip in the sign-in drawer so the user
205
+ * sees mouse control will be active before they approve.
206
+ *
207
+ * Default false.
208
+ */
209
+ mouseControl?: boolean;
210
+ /**
211
+ * **Ask to send notifications.** The wallet's sign-in sheet shows an
212
+ * unticked "Let {site} send you notifications" row; nothing is sent
213
+ * unless the person ticks it. When they do, `SignInResult.notifications`
214
+ * carries a handle for this person at your domain: random, so it can't
215
+ * be linked to the same person's handle on any other site. Send it to
216
+ * your backend with the presentation and call
217
+ * `POST https://api.prson.net/v1/notify { handle, title, body, url? }`
218
+ * with an API key that has `notify:write`, for an app whose registered
219
+ * domains include this one. Plain text only (title up to 60
220
+ * characters, body up to 180), `url` only on this sign-in domain itself
221
+ * (the app asks the person before opening it), about 3
222
+ * a day per person. A 410 means the person turned you off: forget the
223
+ * handle. Default false.
224
+ */
225
+ notifications?: boolean;
226
+ };
227
+ export type CnfJwk = {
228
+ kty: "OKP";
229
+ crv: "Ed25519";
230
+ x: string;
231
+ };
232
+ export type SignInResult = {
233
+ sdJwtVc: string;
234
+ /** The nonce the presentation is bound to (yours when you passed `nonce`). */
235
+ nonce: string;
236
+ /**
237
+ * The person's Prson ID for your site: stable across sign-ins, different on
238
+ * every other site. Check the presentation on your server and use the
239
+ * verifier's `prsonId` there; this copy is for your page. (`cnf.jwk.x`.)
240
+ *
241
+ * Show who is signed in (this ID, or the account/name your backend maps
242
+ * it to) right after sign-in, also from the `signed_in` event: whoever
243
+ * scans the code first signs in, so the person at the screen must be able
244
+ * to see it's them.
245
+ */
246
+ prsonId: string;
247
+ claims: Record<string, unknown>;
248
+ cnf: {
249
+ jwk: CnfJwk;
250
+ };
251
+ credential: {
252
+ vct: string;
253
+ iss: string;
254
+ kid: string;
255
+ expiresAt: number;
256
+ };
257
+ /**
258
+ * Present when the host set `required.uniqueHumanId: true`: a
259
+ * notary-signed, domain-scoped uniqueness credential. OPAQUE
260
+ * pass-through — verify it SERVER-SIDE with
261
+ * `@prson/login-verifier`'s `verifyUniqueHumanId({...},
262
+ * { expectedAudience: "your.host" })`, then use
263
+ * `envelope.uniqueIdHash` as the sybil-resistant account key.
264
+ * Stable for this human at your domain; uncorrelatable anywhere else.
265
+ */
266
+ uniqueHumanId?: {
267
+ envelope: Record<string, unknown>;
268
+ signature: string;
269
+ kid: string;
270
+ } | null;
271
+ /**
272
+ * Present when you set `notifications: true` and the person ticked "Let
273
+ * {site} send you notifications": the handle your backend sends with
274
+ * (see SignInOptions.notifications). null when they didn't.
275
+ */
276
+ notifications?: {
277
+ handle: string;
278
+ } | null;
279
+ session: PrsonLoginSession;
280
+ };
281
+ export type { ExpiryReason } from "./session.js";
282
+ export declare const PROTOCOL_VERSION = "prson_vp_v1";
283
+ /**
284
+ * Data-channel envelope version this SDK speaks, announced to the wallet
285
+ * in the request (`envelopeVersion`). 2 = both sides box with their
286
+ * session keys (sender-authenticated), and the wallet binds its session
287
+ * key into the signed presentation (`prson_wsk`). See SECURITY.md §4.
288
+ */
289
+ export declare const ENVELOPE_VERSION = 2;
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
+ };
302
+ export declare const KNOWN_VCTS: readonly ["https://app.prson.net/credentials/verified-human/v1", "https://app.prson.net/credentials/verified-identity/v1"];
303
+ /** Self-signed wallet credential — accepted only when the SDK is
304
+ * invoked with `allowAnonymous: true`. Carries only `cnf.jwk` + the
305
+ * KB-JWT fields; no notary signature. */
306
+ export declare const ANONYMOUS_WALLET_VCT = "https://app.prson.net/credentials/anonymous-wallet/v1";
307
+ export declare const DEFAULT_TTL_MINUTES = 2;
308
+ export declare const MAX_TTL_MINUTES = 2;
309
+ /** Cloudflare Worker single-API-surface base URL (production). */
310
+ export declare const SIGNALING_BASE = "https://signaling.prson.net";
311
+ /** Dev environment Worker base. Selected via `signIn({ environment: "dev" })`,
312
+ * or override either env with an explicit `signalingBase` (e.g. a local
313
+ * Worker at `https://localhost:8787`). */
314
+ export declare const SIGNALING_BASE_DEV = "https://signaling-dev.prson.net";
315
+ /** Map an `environment` shorthand to its Worker base URL. */
316
+ export declare function resolveSignalingBase(opts: {
317
+ environment?: "production" | "dev";
318
+ signalingBase?: string;
319
+ }): string;
320
+ /**
321
+ * Thrown by `PrsonLogin.signIn()` when a NEWER `signIn()` call
322
+ * displaces the current in-flight one. Host pages typically ignore
323
+ * this — the user's second click is the cancellation signal — but
324
+ * the typed error lets you distinguish it from real failures.
325
+ */
326
+ export declare class LoginAbortedError extends PrsonLoginError {
327
+ constructor(message?: string);
328
+ }
329
+ export declare class PrsonLogin {
330
+ /**
331
+ * Drive a full sign-in. The promise resolves once the wallet has
332
+ * delivered a verified SD-JWT-VC; the returned session lives until
333
+ * one of the four `ExpiryReason` triggers.
334
+ *
335
+ * Without `ui.mountQrInto` the SDK shows its own dialog and handles
336
+ * everything in it: an expired code or a failure offers a fresh code
337
+ * (a new draft, and a new nonce when `nonce` is a function) while this
338
+ * promise keeps waiting; closing the dialog rejects with
339
+ * `LoginAbortedError` (or with the error on screen, if one was shown).
340
+ */
341
+ static signIn(opts?: SignInOptions): Promise<SignInResult>;
342
+ /**
343
+ * Rebind to a session that was previously established for the same
344
+ * holder pk. Phase 2 placeholder — the SDK has no cross-page-load
345
+ * state today; callers should redirect through `signIn` on each
346
+ * page load (the cookie-on-the-server is the source of truth).
347
+ */
348
+ static restore(_opts: {
349
+ cnfJwk: CnfJwk;
350
+ onExpiry?: (reason: ExpiryReason) => void;
351
+ }): Promise<PrsonLoginSession | null>;
352
+ }
353
+ /** Where "Don't have Prson? Get it" points unless `ui.getAppUrl` says otherwise. */
354
+ export declare const GET_APP_URL = "https://app.prson.net/";
355
+ export { PrsonLoginSession };
356
+ export { PrsonCspError, PRSON_CONNECT_SRC, connectSourcesFor, cspStyleNonce } from "./csp.js";
357
+ export { PrsonLoginError, type PrsonLoginErrorCode } from "./errors.js";
358
+ export { NOTIFY_HANDLE, notifyHandleFrom } from "./notify.js";
359
+ export type { LoginQrContext, LoginQrHandle, LoginQrRenderer, LoginUiState } from "./qr.js";
360
+ export type { Renewal };
361
+ export type { LoginRequest, LoginResponse, RequestOptions, InputType, InputOption, InputFormField, } from "./requests.js";
362
+ export { bindInput, bindForm, bindMouse, enableRemoteNavigation, isSensitiveField, type BindController, type BindMouseOptions, type RemoteNavController, type RemoteNavOptions, } from "./bind.js";
363
+ export { awaitVerification, VerificationAbortedError, VerificationClosedError, type AwaitVerificationOptions, type VerificationStatus, } from "./verification.js";