@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,8 @@
1
+ /** What a notification handle looks like: `nh_` and 32 random bytes, base64url. */
2
+ export declare const NOTIFY_HANDLE: RegExp;
3
+ /**
4
+ * The handle in the wallet's sign-in envelope, or null when the person didn't
5
+ * tick "Let {site} send you notifications" (or the wallet is older). Anything
6
+ * that isn't a well-formed handle reads as null.
7
+ */
8
+ export declare function notifyHandleFrom(envelope: unknown): string | null;
package/dist/notify.js ADDED
@@ -0,0 +1,17 @@
1
+ // Website notifications (SignInOptions.notifications): the wallet answers an
2
+ // opted-in sign-in with a handle, random per wallet and site, that the site's
3
+ // backend uses with POST https://api.prson.net/v1/notify (an API key with
4
+ // notify:write). See documentation/SITE_NOTIFICATIONS.md.
5
+ /** What a notification handle looks like: `nh_` and 32 random bytes, base64url. */
6
+ export const NOTIFY_HANDLE = /^nh_[A-Za-z0-9_-]{43}$/;
7
+ /**
8
+ * The handle in the wallet's sign-in envelope, or null when the person didn't
9
+ * tick "Let {site} send you notifications" (or the wallet is older). Anything
10
+ * that isn't a well-formed handle reads as null.
11
+ */
12
+ export function notifyHandleFrom(envelope) {
13
+ if (!envelope || typeof envelope !== "object")
14
+ return null;
15
+ const value = envelope.notifyHandle;
16
+ return typeof value === "string" && NOTIFY_HANDLE.test(value) ? value : null;
17
+ }
@@ -0,0 +1,41 @@
1
+ /**
2
+ * "Point your phone at the screen" overlay shown when the wallet's
3
+ * magic wand emits a `hide` event (the phone is in a non-pointing
4
+ * pose). The visual signals to the user that the cursor is paused
5
+ * and what to do to resume it.
6
+ *
7
+ * Design:
8
+ * * Full-viewport, fixed-position shadow-DOM container — page
9
+ * stylesheets cannot leak in.
10
+ * * A soft inner blue glow on the viewport edge (inset box-shadow
11
+ * + a thin border) signals "the page is in remote-control mode,
12
+ * waiting for input".
13
+ * * A black pill centred in the viewport with the prompt text.
14
+ * * Auto-dismisses on three triggers:
15
+ * 1. Wallet emits the matching `show` event (handled by
16
+ * `bindMouse` directly — it calls `close()`).
17
+ * 2. The user moves the real (OS) mouse — `mousemove`
18
+ * listener calls `close()`.
19
+ * 3. 15-second timeout elapses, so a forgotten controller
20
+ * doesn't leave the glow on indefinitely.
21
+ * * `pointer-events: none` on the container so clicks behind it
22
+ * hit the page normally — the overlay is purely cosmetic.
23
+ */
24
+ interface OverlayHandle {
25
+ host: HTMLElement;
26
+ close: () => void;
27
+ }
28
+ /** True when the overlay is currently visible. */
29
+ export declare function isPointPhoneOverlayActive(): boolean;
30
+ /** Close any active overlay. Safe to call from anywhere. */
31
+ export declare function closePointPhoneOverlay(): void;
32
+ /**
33
+ * Mount the "point your phone" overlay. Replaces any prior overlay
34
+ * so re-firing `hide` while one is up is a no-op visually.
35
+ *
36
+ * Returns the handle so the caller can close it programmatically;
37
+ * the overlay also self-closes on real mouse movement or after the
38
+ * 15-second timeout.
39
+ */
40
+ export declare function openPointPhoneOverlay(): OverlayHandle;
41
+ export {};
@@ -0,0 +1,161 @@
1
+ /**
2
+ * "Point your phone at the screen" overlay shown when the wallet's
3
+ * magic wand emits a `hide` event (the phone is in a non-pointing
4
+ * pose). The visual signals to the user that the cursor is paused
5
+ * and what to do to resume it.
6
+ *
7
+ * Design:
8
+ * * Full-viewport, fixed-position shadow-DOM container — page
9
+ * stylesheets cannot leak in.
10
+ * * A soft inner blue glow on the viewport edge (inset box-shadow
11
+ * + a thin border) signals "the page is in remote-control mode,
12
+ * waiting for input".
13
+ * * A black pill centred in the viewport with the prompt text.
14
+ * * Auto-dismisses on three triggers:
15
+ * 1. Wallet emits the matching `show` event (handled by
16
+ * `bindMouse` directly — it calls `close()`).
17
+ * 2. The user moves the real (OS) mouse — `mousemove`
18
+ * listener calls `close()`.
19
+ * 3. 15-second timeout elapses, so a forgotten controller
20
+ * doesn't leave the glow on indefinitely.
21
+ * * `pointer-events: none` on the container so clicks behind it
22
+ * hit the page normally — the overlay is purely cosmetic.
23
+ */
24
+ import { cspStyleNonce } from "./csp.js";
25
+ let active = null;
26
+ /** True when the overlay is currently visible. */
27
+ export function isPointPhoneOverlayActive() {
28
+ return active !== null;
29
+ }
30
+ /** Close any active overlay. Safe to call from anywhere. */
31
+ export function closePointPhoneOverlay() {
32
+ active?.close();
33
+ }
34
+ /**
35
+ * Mount the "point your phone" overlay. Replaces any prior overlay
36
+ * so re-firing `hide` while one is up is a no-op visually.
37
+ *
38
+ * Returns the handle so the caller can close it programmatically;
39
+ * the overlay also self-closes on real mouse movement or after the
40
+ * 15-second timeout.
41
+ */
42
+ export function openPointPhoneOverlay() {
43
+ if (active)
44
+ return active;
45
+ const host = document.createElement("div");
46
+ host.setAttribute("data-prson-point-phone-overlay", "");
47
+ host.style.position = "fixed";
48
+ host.style.inset = "0";
49
+ host.style.zIndex = "2147483645"; // below the cursor (-1) and below the select overlay (-1)
50
+ host.style.pointerEvents = "none";
51
+ document.body.appendChild(host);
52
+ const shadow = host.attachShadow({ mode: "open" });
53
+ const style = document.createElement("style");
54
+ const nonce = cspStyleNonce();
55
+ if (nonce)
56
+ style.nonce = nonce;
57
+ style.textContent = OVERLAY_CSS;
58
+ shadow.appendChild(style);
59
+ const glow = document.createElement("div");
60
+ glow.className = "glow";
61
+ shadow.appendChild(glow);
62
+ const pill = document.createElement("div");
63
+ pill.className = "pill";
64
+ pill.innerHTML = `
65
+ <span class="dot"></span>
66
+ <span class="text">Point your phone at the screen to use Magic wand</span>
67
+ `;
68
+ shadow.appendChild(pill);
69
+ let closed = false;
70
+ let timer = null;
71
+ function close() {
72
+ if (closed)
73
+ return;
74
+ closed = true;
75
+ if (timer)
76
+ clearTimeout(timer);
77
+ window.removeEventListener("mousemove", onRealMouseMove);
78
+ // Tiny fade for polish.
79
+ host.style.transition = "opacity 180ms ease";
80
+ host.style.opacity = "0";
81
+ setTimeout(() => host.remove(), 200);
82
+ if (active && active.host === host)
83
+ active = null;
84
+ }
85
+ function onRealMouseMove(_e) {
86
+ // Any real OS mouse motion → user is no longer relying on the
87
+ // wand; dismiss so the page doesn't keep nagging.
88
+ close();
89
+ }
90
+ window.addEventListener("mousemove", onRealMouseMove);
91
+ timer = setTimeout(close, 15000);
92
+ const handle = { host, close };
93
+ active = handle;
94
+ return handle;
95
+ }
96
+ // Shadow-DOM CSS. Sized for clear legibility on any host page;
97
+ // values picked to match the blue accent of the virtual cursor +
98
+ // the snap-preview outline so the user reads the overlay as part
99
+ // of the same "remote control" UI family.
100
+ const OVERLAY_CSS = `
101
+ :host { all: initial; }
102
+ * { box-sizing: border-box; }
103
+ /* Inner-glow viewport border. Two stacked inset shadows: the
104
+ wide soft halo + a thin defined edge. */
105
+ .glow {
106
+ position: fixed;
107
+ inset: 0;
108
+ pointer-events: none;
109
+ box-shadow:
110
+ inset 0 0 0 2px rgba(59, 130, 246, 0.75),
111
+ inset 0 0 28px 6px rgba(59, 130, 246, 0.35),
112
+ inset 0 0 80px 24px rgba(59, 130, 246, 0.18);
113
+ animation: prson-glow-pulse 2.4s ease-in-out infinite;
114
+ }
115
+ @keyframes prson-glow-pulse {
116
+ 0%, 100% { opacity: 0.85; }
117
+ 50% { opacity: 1; }
118
+ }
119
+ .pill {
120
+ position: fixed;
121
+ top: 50%;
122
+ left: 50%;
123
+ transform: translate(-50%, -50%);
124
+ display: flex;
125
+ align-items: center;
126
+ gap: 14px;
127
+ padding: 18px 28px;
128
+ border-radius: 999px;
129
+ background: #0f172a;
130
+ color: #ffffff;
131
+ font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;
132
+ font-size: 16px;
133
+ font-weight: 600;
134
+ letter-spacing: 0.1px;
135
+ box-shadow:
136
+ 0 18px 40px rgba(15, 23, 42, 0.45),
137
+ 0 0 0 1px rgba(255, 255, 255, 0.06) inset;
138
+ /* Pulse-fade in so the pill doesn't pop harshly. */
139
+ animation: prson-pill-fade-in 240ms ease-out both;
140
+ }
141
+ @keyframes prson-pill-fade-in {
142
+ from { opacity: 0; transform: translate(-50%, calc(-50% + 6px)); }
143
+ to { opacity: 1; transform: translate(-50%, -50%); }
144
+ }
145
+ .dot {
146
+ width: 10px;
147
+ height: 10px;
148
+ border-radius: 50%;
149
+ background: rgba(59, 130, 246, 1);
150
+ box-shadow: 0 0 0 4px rgba(59, 130, 246, 0.25);
151
+ animation: prson-dot-pulse 1.4s ease-in-out infinite;
152
+ flex: none;
153
+ }
154
+ @keyframes prson-dot-pulse {
155
+ 0%, 100% { transform: scale(1); opacity: 1; }
156
+ 50% { transform: scale(1.3); opacity: 0.65; }
157
+ }
158
+ .text {
159
+ line-height: 1.25;
160
+ }
161
+ `;
package/dist/qr.d.ts ADDED
@@ -0,0 +1,105 @@
1
+ /**
2
+ * Minimal QR rendering surface. We deliberately don't bundle a full
3
+ * QR library here — the SDK is tiny and most sites already have one.
4
+ * Instead, we expose a render adapter that the host page can override.
5
+ *
6
+ * Default behaviour: render a placeholder `<div>` with the URL as
7
+ * text + a copy-to-clipboard affordance, and emit a `console.warn`
8
+ * pointing partners at the QR-renderer hook. Production deployments
9
+ * pass a real QR renderer (e.g. `qrcode-svg`, `qr-creator`) via
10
+ * `PrsonLogin.signIn({ ui: { mountQrInto } })` + a global override
11
+ * on `window.__prsonLoginQrRenderer`.
12
+ */
13
+ export interface LoginQrHandle {
14
+ /** Tear the QR down (called automatically when the SDK no longer needs it). */
15
+ dispose(): void;
16
+ /**
17
+ * Optional (renderers written before 0.2 don't have it): the SDK
18
+ * reports progress so the UI can show it. For `"success"` the renderer
19
+ * may return a promise; the SDK waits for it (at most 1.5 s) before
20
+ * tearing the UI down, so a check animation can finish.
21
+ */
22
+ update?(state: LoginUiState): void | Promise<void>;
23
+ }
24
+ /**
25
+ * What the sign-in is doing, as far as the browser can tell:
26
+ *
27
+ * waiting the code is on screen
28
+ * scanned a wallet claimed the code (the person approved on the
29
+ * phone, which is now connecting)
30
+ * approving the encrypted channel to the phone is open; the phone is
31
+ * preparing its signed proof
32
+ * verifying the proof arrived; the SDK is checking it
33
+ * success checked; the UI is about to close
34
+ * error something failed; `message` says what, in plain words
35
+ *
36
+ * Expiry isn't sent: the renderer runs the countdown from the code's own
37
+ * server timestamp (`t=`).
38
+ */
39
+ export type LoginUiState = {
40
+ state: "waiting";
41
+ } | {
42
+ state: "scanned";
43
+ } | {
44
+ state: "approving";
45
+ } | {
46
+ state: "verifying";
47
+ } | {
48
+ state: "success";
49
+ domain: string;
50
+ } | {
51
+ state: "error";
52
+ message: string;
53
+ };
54
+ /** The optional fourth argument the SDK passes to a renderer. */
55
+ export interface LoginQrContext {
56
+ /** `"modal"`: inside the SDK's own dialog. `"inline"`: in the host's `mountQrInto`. */
57
+ mode: "modal" | "inline";
58
+ /** The domain the person is signing in to (the same as the code's `d=`). */
59
+ domain: string;
60
+ /**
61
+ * Ask for a fresh code (after expiry or an error): the SDK makes a new
62
+ * draft and renders again, and `signIn()` keeps waiting. The renderer
63
+ * should first dispatch the bubbling `prson-login-refresh-requested`
64
+ * DOM event (the 0.1 contract); if the host re-called `signIn()` from
65
+ * that event, this is a no-op.
66
+ */
67
+ refresh?: () => void;
68
+ /** Close the sign-in: `signIn()` rejects with `LoginAbortedError`. */
69
+ cancel?: () => void;
70
+ /** Where "Don't have Prson? Get it" points. */
71
+ getAppUrl: string;
72
+ /** The id the card's title should carry, so the modal is labelled by it. */
73
+ titleId: string;
74
+ }
75
+ export type LoginQrRenderer = (url: string, mount: HTMLElement, theme: "light" | "dark" | "auto", context?: LoginQrContext) => LoginQrHandle;
76
+ /**
77
+ * Create a centred modal scrim and return the inner mount element +
78
+ * a dispose handle. Used as the default QR presentation when the
79
+ * host page didn't pass `mountQrInto` — the SDK calls this, then
80
+ * hands the inner mount to `renderLoginQr` exactly like an inline
81
+ * mount.
82
+ *
83
+ * The scrim:
84
+ * * darkens the page with a 50%-black overlay + a 4 px backdrop
85
+ * blur (so the partner UI fades into the background but stays
86
+ * contextual),
87
+ * * dismisses on **Esc** (any focused field is bypassed via
88
+ * capture-phase listener — works even with another input
89
+ * focused),
90
+ * * dismisses on **click outside** the card,
91
+ * * sits above every layout via `z-index: 2147483647`.
92
+ *
93
+ * Dismissing fires [onDismiss] — the SDK wires this to abort the
94
+ * in-flight `signIn()` so the host's `await signIn(...)` rejects
95
+ * with `LoginAbortedError` rather than hanging.
96
+ */
97
+ export declare function createModalQrMount(opts: {
98
+ onDismiss: () => void;
99
+ /** The id of the card's title: the dialog is labelled by it. */
100
+ titleId?: string;
101
+ }): {
102
+ mount: HTMLElement;
103
+ dispose: () => void;
104
+ };
105
+ export declare function renderLoginQr(url: string, mount: HTMLElement, theme: "light" | "dark" | "auto", context?: LoginQrContext): LoginQrHandle;
package/dist/qr.js ADDED
@@ -0,0 +1,149 @@
1
+ /**
2
+ * Minimal QR rendering surface. We deliberately don't bundle a full
3
+ * QR library here — the SDK is tiny and most sites already have one.
4
+ * Instead, we expose a render adapter that the host page can override.
5
+ *
6
+ * Default behaviour: render a placeholder `<div>` with the URL as
7
+ * text + a copy-to-clipboard affordance, and emit a `console.warn`
8
+ * pointing partners at the QR-renderer hook. Production deployments
9
+ * pass a real QR renderer (e.g. `qrcode-svg`, `qr-creator`) via
10
+ * `PrsonLogin.signIn({ ui: { mountQrInto } })` + a global override
11
+ * on `window.__prsonLoginQrRenderer`.
12
+ */
13
+ /**
14
+ * Create a centred modal scrim and return the inner mount element +
15
+ * a dispose handle. Used as the default QR presentation when the
16
+ * host page didn't pass `mountQrInto` — the SDK calls this, then
17
+ * hands the inner mount to `renderLoginQr` exactly like an inline
18
+ * mount.
19
+ *
20
+ * The scrim:
21
+ * * darkens the page with a 50%-black overlay + a 4 px backdrop
22
+ * blur (so the partner UI fades into the background but stays
23
+ * contextual),
24
+ * * dismisses on **Esc** (any focused field is bypassed via
25
+ * capture-phase listener — works even with another input
26
+ * focused),
27
+ * * dismisses on **click outside** the card,
28
+ * * sits above every layout via `z-index: 2147483647`.
29
+ *
30
+ * Dismissing fires [onDismiss] — the SDK wires this to abort the
31
+ * in-flight `signIn()` so the host's `await signIn(...)` rejects
32
+ * with `LoginAbortedError` rather than hanging.
33
+ */
34
+ export function createModalQrMount(opts) {
35
+ const scrim = document.createElement("div");
36
+ scrim.setAttribute("data-prson-login-modal", "1");
37
+ // Phones get a bottom sheet (thumb-reachable); larger screens a centred card.
38
+ const sheet = typeof window.matchMedia === "function" && window.matchMedia("(max-width: 480px)").matches;
39
+ scrim.style.cssText =
40
+ "position:fixed;inset:0;background:rgba(10,10,10,0.45);" +
41
+ "backdrop-filter:blur(6px);-webkit-backdrop-filter:blur(6px);" +
42
+ "z-index:2147483647;display:flex;overflow-y:auto;box-sizing:border-box;" +
43
+ "justify-content:center;" +
44
+ (sheet ? "align-items:flex-end;padding:0;" : "align-items:center;padding:24px 16px;");
45
+ // An accessible dialog: role, aria-modal, labelled by the card's title,
46
+ // focus moved in and kept there (Tab wraps), restored on close.
47
+ const mount = document.createElement("div");
48
+ mount.setAttribute("data-prson-login-modal-mount", "1");
49
+ mount.setAttribute("role", "dialog");
50
+ mount.setAttribute("aria-modal", "true");
51
+ if (opts.titleId)
52
+ mount.setAttribute("aria-labelledby", opts.titleId);
53
+ else
54
+ mount.setAttribute("aria-label", "Sign in with Prson");
55
+ mount.tabIndex = -1;
56
+ // The QR card renderer manages its own width via CSS — give it
57
+ // the natural sizing it expects.
58
+ mount.style.cssText =
59
+ "display:flex;align-items:center;justify-content:center;outline:none;max-width:100%;" +
60
+ (sheet ? "width:100%;" : "margin:auto 0;");
61
+ scrim.append(mount);
62
+ const previouslyFocused = document.activeElement instanceof HTMLElement ? document.activeElement : null;
63
+ const root = document.documentElement;
64
+ const prevOverflow = root.style.overflow;
65
+ root.style.overflow = "hidden";
66
+ document.body.append(scrim);
67
+ // Focus the dialog itself, so a screen reader starts at its title and a
68
+ // stray Enter doesn't press anything.
69
+ setTimeout(() => {
70
+ if (!disposed && !mount.contains(document.activeElement))
71
+ mount.focus({ preventScroll: true });
72
+ }, 0);
73
+ let disposed = false;
74
+ function dispose() {
75
+ if (disposed)
76
+ return;
77
+ disposed = true;
78
+ document.removeEventListener("keydown", onKey, true);
79
+ scrim.remove();
80
+ root.style.overflow = prevOverflow;
81
+ try {
82
+ previouslyFocused?.focus({ preventScroll: true });
83
+ }
84
+ catch {
85
+ /* gone from the page */
86
+ }
87
+ }
88
+ function onKey(e) {
89
+ if (e.key === "Escape" || e.key === "Esc") {
90
+ e.preventDefault();
91
+ e.stopPropagation();
92
+ opts.onDismiss();
93
+ return;
94
+ }
95
+ if (e.key !== "Tab")
96
+ return;
97
+ const focusable = Array.from(mount.querySelectorAll('a[href], button:not([disabled]), input:not([disabled]), [tabindex]:not([tabindex="-1"])')).filter((el) => el.getClientRects().length > 0);
98
+ const first = focusable[0];
99
+ const last = focusable[focusable.length - 1];
100
+ if (!first || !last) {
101
+ e.preventDefault();
102
+ mount.focus();
103
+ return;
104
+ }
105
+ const active = document.activeElement;
106
+ if (e.shiftKey && (active === first || active === mount || !mount.contains(active))) {
107
+ e.preventDefault();
108
+ last.focus();
109
+ }
110
+ else if (!e.shiftKey && (active === last || !mount.contains(active))) {
111
+ e.preventDefault();
112
+ first.focus();
113
+ }
114
+ }
115
+ scrim.addEventListener("click", (e) => {
116
+ // Click directly on the scrim (not the card) dismisses. Card
117
+ // taps bubble up from the inner mount; we ignore them.
118
+ if (e.target === scrim || e.target === mount) {
119
+ opts.onDismiss();
120
+ }
121
+ });
122
+ document.addEventListener("keydown", onKey, true);
123
+ return { mount, dispose };
124
+ }
125
+ export function renderLoginQr(url, mount, theme, context) {
126
+ const override = window
127
+ .__prsonLoginQrRenderer;
128
+ if (override)
129
+ return override(url, mount, theme, context);
130
+ // Fallback: text + click-to-copy. Good enough for development;
131
+ // partners should install a real QR renderer.
132
+ // eslint-disable-next-line no-console
133
+ console.warn("[@prson/login-sdk] No QR renderer installed. Set window.__prsonLoginQrRenderer " +
134
+ "to a function (url, mount, theme) => { dispose: () => void } before calling signIn().");
135
+ const root = document.createElement("div");
136
+ root.setAttribute("data-prson-qr-fallback", "1");
137
+ root.style.cssText = "font-family:system-ui,sans-serif;font-size:12px;padding:12px;border:1px dashed currentColor;border-radius:8px;word-break:break-all;cursor:pointer;";
138
+ root.textContent = url;
139
+ root.title = "Click to copy. Install a real QR renderer for the production UX.";
140
+ root.addEventListener("click", () => {
141
+ void navigator.clipboard?.writeText(url);
142
+ });
143
+ mount.append(root);
144
+ return {
145
+ dispose() {
146
+ root.remove();
147
+ },
148
+ };
149
+ }