@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,279 @@
1
+ /**
2
+ * Verifier → wallet REQUEST channel.
3
+ *
4
+ * After sign-in the host site can ask the wallet for things that
5
+ * weren't part of the initial disclosure (a specific claim value, a
6
+ * predicate check, a document presence assertion, a document
7
+ * signature, a free-form input typed on the phone). Each request
8
+ * carries a UUID; the wallet replies with a matching `response`
9
+ * envelope whose `requestId` references it.
10
+ *
11
+ * Three protocol invariants the wallet enforces:
12
+ *
13
+ * * **At most one request per second** — inter-arrival throttle on
14
+ * the wallet side. Inbound requests that violate this are silently
15
+ * dropped (no response sent); the browser SDK's per-call timeout
16
+ * surfaces them as `error: "timeout"`.
17
+ *
18
+ * * **At most five outstanding requests** in the wallet's queue.
19
+ * Once five drawers are open, further incoming requests are
20
+ * ignored on the floor.
21
+ *
22
+ * * **Requests fire ONLY while a web session is active.** No
23
+ * background requests, no pre-sign-in requests. The session's
24
+ * transport going away invalidates every pending request with
25
+ * `error: "no-active-session"`.
26
+ *
27
+ * Browser SDK shape (this file): public types + the in-flight
28
+ * controller that pairs outbound requests with their wallet replies.
29
+ * The session's `_sendToWallet` is the cipher path.
30
+ */
31
+ import type { DecryptedEnvelope } from "./crypto.js";
32
+ /**
33
+ * Output wire format for a signed predicate (fragment). See
34
+ * `functions/utils/predicateFormatters.js` for the formatter registry
35
+ * the server uses; the verifier-node package decodes the matching
36
+ * shape with `verifySignedFragment` / `verifyFragmentCredential`.
37
+ */
38
+ export type PredicateFormat = "native" | "vc+jwt" | "vc+sd-jwt";
39
+ /**
40
+ * Free-form text/numeric input typed on the phone — the "kiosk
41
+ * companion" use case. Mirrors a subset of the HTML input element
42
+ * so the wallet UI can pick a sensible keyboard / validator.
43
+ *
44
+ * `select` is included to cover `<select>` elements: the wallet UI
45
+ * renders an options picker (radio-style on phone) and returns the
46
+ * chosen option's `value`.
47
+ */
48
+ export type InputType = "text" | "search" | "email" | "tel" | "url" | "number" | "password" | "select";
49
+ /** One choice in a `select` field. */
50
+ export interface InputOption {
51
+ /** Wire value — what the wallet returns and the host fills. */
52
+ value: string;
53
+ /** Display label shown in the wallet picker. Defaults to `value`. */
54
+ label?: string;
55
+ }
56
+ /**
57
+ * One field inside a multi-input `input-form` request. Same surface
58
+ * as a single `kind: "input"` request, plus an optional `name` (used
59
+ * as the reply key) and a `defaultValue` (pre-fill).
60
+ *
61
+ * Two shapes — the discriminator is `inputType`:
62
+ *
63
+ * * Text/numeric inputs: `text` | `search` | `email` | `tel` |
64
+ * `url` | `number` | `password` — validation knobs match the
65
+ * HTML5 attribute set the host can read off a DOM `<input>`.
66
+ *
67
+ * * Select picker: `inputType: "select"` requires `options` and
68
+ * ignores the validation knobs that don't apply (`pattern`,
69
+ * `minLength`, `maxLength`).
70
+ */
71
+ export type InputFormField = {
72
+ name: string;
73
+ inputType: Exclude<InputType, "select">;
74
+ label: string;
75
+ placeholder?: string;
76
+ defaultValue?: string;
77
+ minLength?: number;
78
+ maxLength?: number;
79
+ min?: number;
80
+ max?: number;
81
+ pattern?: string;
82
+ required?: boolean;
83
+ } | {
84
+ name: string;
85
+ inputType: "select";
86
+ label: string;
87
+ options: InputOption[];
88
+ defaultValue?: string;
89
+ required?: boolean;
90
+ };
91
+ export type LoginRequest =
92
+ /**
93
+ * Ask the wallet to reveal the raw value of a single claim. Used
94
+ * by host sites that want a stale claim refreshed without a
95
+ * full re-sign-in — e.g. "what's your current verification
96
+ * level?". The wallet prompts the user before answering.
97
+ */
98
+ {
99
+ kind: "claim-value";
100
+ name: string;
101
+ /** Human-readable reason shown in the wallet drawer. */
102
+ reason?: string;
103
+ }
104
+ /**
105
+ * Predicate check against a fragment the wallet has signed.
106
+ * Returns the matching signed fragment so the verifier can
107
+ * re-verify the signature server-side.
108
+ *
109
+ * `format` selects the wire shape the wallet asks the notary to
110
+ * mint:
111
+ * * `native` — Prson-flat shape (RSA-SHA256 over the canonical
112
+ * bytes). Smallest, default for back-compat.
113
+ * * `vc+jwt` — W3C VC Data Model 2.0 JWS.
114
+ * * `vc+sd-jwt` — IETF SD-JWT-VC with one disclosure.
115
+ * The choice flows server-side via the
116
+ * `signPropertyFragment` Cloud Function's `format` parameter and is
117
+ * verified browser-side by `@prson/login-verifier`'s
118
+ * `verifySignedFragment` (native) / `verifyFragmentCredential` (jwt).
119
+ */
120
+ | {
121
+ kind: "fragment-check";
122
+ fragmentName: string;
123
+ format?: PredicateFormat;
124
+ reason?: string;
125
+ }
126
+ /**
127
+ * Ask the wallet whether a verified document of the given shape
128
+ * is present. The user can also pick a document; if none
129
+ * matches, the wallet may offer to scan one via NFC (if the
130
+ * device is compatible). Reply carries either the document's
131
+ * notarised metadata or an error.
132
+ */
133
+ | {
134
+ kind: "document-presence";
135
+ /** Filter — `"passport"`, `"national_id"`, etc. */
136
+ type?: string;
137
+ /** ISO-3 country code, optional. */
138
+ country?: string;
139
+ reason?: string;
140
+ }
141
+ /**
142
+ * Document signing — the host hands the wallet either the raw
143
+ * bytes (for tiny files) or a short-lived upload URL. The wallet
144
+ * signs with the identity's PAdES-bound EC key (see
145
+ * `mobile-app/prson_app/docs/identity_pdf_signing.md`).
146
+ */
147
+ | {
148
+ kind: "document-sign";
149
+ document: {
150
+ bytes: Uint8Array;
151
+ } | {
152
+ uploadUrl: string;
153
+ size?: number;
154
+ sha256?: string;
155
+ };
156
+ visibleCue?: string;
157
+ reason?: string;
158
+ }
159
+ /**
160
+ * Generic single input request — kiosk pattern. The wallet shows
161
+ * a keyboard sized to the type + the constraints, returns the
162
+ * typed value. No notary signature — the host trusts the
163
+ * channel + the user.
164
+ *
165
+ * For `inputType: "select"`, supply `options`. The wallet
166
+ * renders a radio-style picker on the phone and the reply's
167
+ * `value` is the chosen option's `value` string.
168
+ */
169
+ | {
170
+ kind: "input";
171
+ inputType: InputType;
172
+ label: string;
173
+ placeholder?: string;
174
+ defaultValue?: string;
175
+ /** HTML5-style validation constraints — wallet enforces. */
176
+ minLength?: number;
177
+ maxLength?: number;
178
+ /** For `inputType: "number"`. */
179
+ min?: number;
180
+ max?: number;
181
+ /** Regex; wallet uses to gate the submit button. */
182
+ pattern?: string;
183
+ required?: boolean;
184
+ /** Required when `inputType === "select"`. */
185
+ options?: InputOption[];
186
+ reason?: string;
187
+ }
188
+ /**
189
+ * Multi-input form — one wallet drawer, prev/next/send
190
+ * navigation, fills every field at once when the user taps
191
+ * Send. The reply's `value` is `Record<fieldName, string>`.
192
+ *
193
+ * Drives the `session.bindForm(...)` helper, which walks a
194
+ * `<form>` / container element and synthesises one of these
195
+ * requests from the DOM. The host can also build them by
196
+ * hand — useful for verifier-side flows where the inputs are
197
+ * decided at runtime rather than rendered on the page.
198
+ */
199
+ | {
200
+ kind: "input-form";
201
+ fields: InputFormField[];
202
+ /** Label on the final "Send" button. Defaults to "Send". */
203
+ submitLabel?: string;
204
+ reason?: string;
205
+ }
206
+ /**
207
+ * Virtual pointer / cursor. The wallet sources pointer events
208
+ * from the phone and streams them through `mouse-update`
209
+ * envelopes (paired by `requestId`) until the user closes the
210
+ * drawer; the final `response` carries the session totals.
211
+ *
212
+ * Two modes:
213
+ *
214
+ * * `"touch"` — the phone screen becomes a touchpad. Drag the
215
+ * finger to move the cursor; single-tap = click;
216
+ * double-tap = double-click; two-finger drag = scroll. The
217
+ * [`bindMouse`] helper renders a small circular cursor over
218
+ * the page and applies the streamed deltas.
219
+ *
220
+ * * `"magic"` — phone gyro + accelerometer drive a "magic
221
+ * wand". Tap on the phone screen = click; double-tap =
222
+ * double-click; swipe up / down on the phone = scroll.
223
+ * Bigger learning curve but no thumb-on-screen
224
+ * drag — useful for hands-free presentation control.
225
+ *
226
+ * The host requests a mode; the wallet UI honours it but may
227
+ * surface a toggle to switch mid-session (in which case the
228
+ * streamed envelopes carry the actual mode in `mode`).
229
+ */
230
+ | {
231
+ kind: "mouse";
232
+ mode: "touch" | "magic";
233
+ reason?: string;
234
+ };
235
+ export type LoginResponse =
236
+ /** Success — `value` shape depends on the request kind. */
237
+ {
238
+ ok: true;
239
+ value: unknown;
240
+ }
241
+ /** Failure — `error` is a short machine-readable code. */
242
+ | {
243
+ ok: false;
244
+ error: "declined" | "not-present" | "expired" | "rate-limited" | "queue-full" | "no-active-session" | "timeout" | "session-closed" | "unsupported" | string;
245
+ };
246
+ export interface RequestOptions {
247
+ /**
248
+ * Hard deadline for the wallet reply. Default 60 s — generous
249
+ * because the wallet drawer is on the user's phone and they may
250
+ * need to scan an NFC document. Callers expecting a fast reply
251
+ * (e.g. kiosk text input) can tighten this.
252
+ */
253
+ timeoutMs?: number;
254
+ }
255
+ /**
256
+ * Pairs outbound `request` envelopes with their matching
257
+ * `response` envelopes by UUID. Held privately on a
258
+ * `PrsonLoginSession`; not part of the public surface.
259
+ */
260
+ export declare class RequestController {
261
+ private _pending;
262
+ private _closed;
263
+ /**
264
+ * Wire up a new outbound request. Returns the requestId to put in
265
+ * the envelope + a `promise` that resolves when the wallet replies
266
+ * (or times out / the session closes).
267
+ */
268
+ enqueue(timeoutMs: number): {
269
+ requestId: string;
270
+ promise: Promise<LoginResponse>;
271
+ };
272
+ /** Resolve a pending request when a wallet `response` envelope arrives. */
273
+ resolve(envelope: DecryptedEnvelope): void;
274
+ /**
275
+ * Reject every in-flight request with the given reason. Typically
276
+ * called with `"session-closed"` from session teardown.
277
+ */
278
+ closeAll(reason: string): void;
279
+ }
@@ -0,0 +1,128 @@
1
+ /**
2
+ * Verifier → wallet REQUEST channel.
3
+ *
4
+ * After sign-in the host site can ask the wallet for things that
5
+ * weren't part of the initial disclosure (a specific claim value, a
6
+ * predicate check, a document presence assertion, a document
7
+ * signature, a free-form input typed on the phone). Each request
8
+ * carries a UUID; the wallet replies with a matching `response`
9
+ * envelope whose `requestId` references it.
10
+ *
11
+ * Three protocol invariants the wallet enforces:
12
+ *
13
+ * * **At most one request per second** — inter-arrival throttle on
14
+ * the wallet side. Inbound requests that violate this are silently
15
+ * dropped (no response sent); the browser SDK's per-call timeout
16
+ * surfaces them as `error: "timeout"`.
17
+ *
18
+ * * **At most five outstanding requests** in the wallet's queue.
19
+ * Once five drawers are open, further incoming requests are
20
+ * ignored on the floor.
21
+ *
22
+ * * **Requests fire ONLY while a web session is active.** No
23
+ * background requests, no pre-sign-in requests. The session's
24
+ * transport going away invalidates every pending request with
25
+ * `error: "no-active-session"`.
26
+ *
27
+ * Browser SDK shape (this file): public types + the in-flight
28
+ * controller that pairs outbound requests with their wallet replies.
29
+ * The session's `_sendToWallet` is the cipher path.
30
+ */
31
+ /**
32
+ * Pairs outbound `request` envelopes with their matching
33
+ * `response` envelopes by UUID. Held privately on a
34
+ * `PrsonLoginSession`; not part of the public surface.
35
+ */
36
+ export class RequestController {
37
+ constructor() {
38
+ this._pending = new Map();
39
+ this._closed = false;
40
+ }
41
+ /**
42
+ * Wire up a new outbound request. Returns the requestId to put in
43
+ * the envelope + a `promise` that resolves when the wallet replies
44
+ * (or times out / the session closes).
45
+ */
46
+ enqueue(timeoutMs) {
47
+ const requestId = newUuid();
48
+ // `setTimeout` accepts up to int32-max milliseconds (~24.8 days)
49
+ // before silently overflowing and firing on the next tick. Any
50
+ // caller passing a credential-exp-derived budget (90-day VC
51
+ // credentials yield ~7.8 billion ms) would otherwise see an
52
+ // immediate `error: "timeout"`. Clamp defensively here so the
53
+ // contract holds regardless of caller hygiene.
54
+ const MAX_SAFE_TIMEOUT = 2147483000;
55
+ const safeTimeoutMs = Math.min(Math.max(0, timeoutMs), MAX_SAFE_TIMEOUT);
56
+ const promise = new Promise((resolve) => {
57
+ if (this._closed) {
58
+ resolve({ ok: false, error: "session-closed" });
59
+ return;
60
+ }
61
+ const entry = {
62
+ requestId,
63
+ resolve,
64
+ timer: setTimeout(() => {
65
+ const p = this._pending.get(requestId);
66
+ if (!p)
67
+ return;
68
+ this._pending.delete(requestId);
69
+ resolve({ ok: false, error: "timeout" });
70
+ }, safeTimeoutMs),
71
+ };
72
+ this._pending.set(requestId, entry);
73
+ });
74
+ return { requestId, promise };
75
+ }
76
+ /** Resolve a pending request when a wallet `response` envelope arrives. */
77
+ resolve(envelope) {
78
+ if (envelope.msg !== "response")
79
+ return;
80
+ const requestId = envelope.requestId;
81
+ if (!requestId)
82
+ return;
83
+ const entry = this._pending.get(requestId);
84
+ if (!entry)
85
+ return; // unknown id — late reply after timeout, ignore
86
+ this._pending.delete(requestId);
87
+ if (entry.timer)
88
+ clearTimeout(entry.timer);
89
+ if (envelope.error) {
90
+ entry.resolve({ ok: false, error: envelope.error });
91
+ }
92
+ else {
93
+ entry.resolve({ ok: true, value: envelope.result });
94
+ }
95
+ }
96
+ /**
97
+ * Reject every in-flight request with the given reason. Typically
98
+ * called with `"session-closed"` from session teardown.
99
+ */
100
+ closeAll(reason) {
101
+ if (this._closed)
102
+ return;
103
+ this._closed = true;
104
+ for (const entry of this._pending.values()) {
105
+ if (entry.timer)
106
+ clearTimeout(entry.timer);
107
+ entry.resolve({ ok: false, error: reason });
108
+ }
109
+ this._pending.clear();
110
+ }
111
+ }
112
+ /**
113
+ * RFC-4122 v4 UUID via `crypto.randomUUID` when present, else a
114
+ * `getRandomValues`-based fallback for older browsers. The wire
115
+ * carries the canonical hex-with-dashes form.
116
+ */
117
+ function newUuid() {
118
+ if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
119
+ return crypto.randomUUID();
120
+ }
121
+ const b = new Uint8Array(16);
122
+ crypto.getRandomValues(b);
123
+ // version + variant bits per RFC 4122
124
+ b[6] = (b[6] & 0x0f) | 0x40;
125
+ b[8] = (b[8] & 0x3f) | 0x80;
126
+ const h = Array.from(b, (x) => x.toString(16).padStart(2, "0")).join("");
127
+ return `${h.slice(0, 8)}-${h.slice(8, 12)}-${h.slice(12, 16)}-${h.slice(16, 20)}-${h.slice(20)}`;
128
+ }
@@ -0,0 +1,70 @@
1
+ /**
2
+ * Virtual-cursor-friendly overlay for native `<select>` elements.
3
+ *
4
+ * Why this exists: native `<select>` dropdowns are rendered by the OS
5
+ * shell, not the DOM. Synthetic `click` events from `bindMouse`'s
6
+ * virtual cursor cannot open them, and even if they did the OS-drawn
7
+ * option list is outside the page's coordinate system — the virtual
8
+ * cursor couldn't navigate it. We replace the native dropdown with a
9
+ * pure-DOM overlay sized for cursor accuracy:
10
+ *
11
+ * * Each option is a large (≥56 px tall) button — easy to land on
12
+ * with the wand or trackpad.
13
+ * * "Previous page" / "Next page" buttons step through long option
14
+ * lists one viewport-sized chunk at a time.
15
+ * * An "X" button closes without committing a choice.
16
+ * * The overlay sits at the top of the body z-index stack and
17
+ * traps clicks: while it's open, the rest of the page is
18
+ * non-interactive — the cursor's click router only considers
19
+ * overlay elements.
20
+ * * The overlay is rendered inside a Shadow DOM root with
21
+ * `:host { all: initial; }` so the host page's stylesheets
22
+ * cannot bleed in. The page can neither restyle nor read the
23
+ * overlay (closed-mode shadow), beyond what we deliberately
24
+ * expose via attributes.
25
+ *
26
+ * Wiring from `bindMouse`:
27
+ *
28
+ * * Move frames re-route the snap target into the overlay via
29
+ * [findNearestClickableInOverlay] when the overlay is open.
30
+ * * Click frames detect `<select>` snap targets and open the
31
+ * overlay instead of dispatching a click. When the overlay is
32
+ * open, subsequent clicks route through it.
33
+ * * `bindMouse.dispose()` calls [closeAllOverlays] so a torn-down
34
+ * cursor doesn't leave the overlay orphaned.
35
+ */
36
+ interface OverlayHandle {
37
+ host: HTMLElement;
38
+ shadow: ShadowRoot;
39
+ close: () => void;
40
+ }
41
+ /** True when a select overlay is currently open + accepting input. */
42
+ export declare function isSelectOverlayActive(): boolean;
43
+ /** Close any currently-open overlay. No-op when none is open. */
44
+ export declare function closeAllOverlays(): void;
45
+ /**
46
+ * Mount the overlay for [select]. Replaces any existing overlay.
47
+ * Returns the handle so callers can close it programmatically (e.g.
48
+ * if the cursor disposes while the overlay is still up). The
49
+ * overlay self-closes when the user picks an option or taps X.
50
+ */
51
+ export declare function openSelectOverlay(select: HTMLSelectElement): OverlayHandle;
52
+ /**
53
+ * Snap-target lookup *inside* the active overlay. Bind.ts swaps
54
+ * the regular `findNearestClickable` for this when an overlay is
55
+ * open so the magic-mode highlight tracks the overlay's option
56
+ * buttons instead of the (no-longer-interactive) page underneath.
57
+ *
58
+ * No radius cap — when the overlay is open the cursor MUST land on
59
+ * something useful, so we always return a snap target if any
60
+ * candidate exists.
61
+ */
62
+ export declare function findNearestClickableInOverlay(x: number, y: number): Element | null;
63
+ /**
64
+ * Highlight an element inside the active overlay by setting the
65
+ * shared `data-prson-magic-snap` attribute. The overlay's own CSS
66
+ * (inside the shadow) provides the visible style — the page's
67
+ * stylesheet for that attribute cannot reach in.
68
+ */
69
+ export declare function setOverlaySnap(target: Element | null): void;
70
+ export {};