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