@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.
@@ -21,6 +21,7 @@
21
21
  * * `pointer-events: none` on the container so clicks behind it
22
22
  * hit the page normally — the overlay is purely cosmetic.
23
23
  */
24
+ import { cspStyleNonce } from "./csp.js";
24
25
  let active = null;
25
26
  /** True when the overlay is currently visible. */
26
27
  export function isPointPhoneOverlayActive() {
@@ -50,6 +51,9 @@ export function openPointPhoneOverlay() {
50
51
  document.body.appendChild(host);
51
52
  const shadow = host.attachShadow({ mode: "open" });
52
53
  const style = document.createElement("style");
54
+ const nonce = cspStyleNonce();
55
+ if (nonce)
56
+ style.nonce = nonce;
53
57
  style.textContent = OVERLAY_CSS;
54
58
  shadow.appendChild(style);
55
59
  const glow = document.createElement("div");
@@ -33,6 +33,7 @@
33
33
  * * `bindMouse.dispose()` calls [closeAllOverlays] so a torn-down
34
34
  * cursor doesn't leave the overlay orphaned.
35
35
  */
36
+ import { cspStyleNonce } from "./csp.js";
36
37
  let activeOverlay = null;
37
38
  /** True when a select overlay is currently open + accepting input. */
38
39
  export function isSelectOverlayActive() {
@@ -65,6 +66,9 @@ export function openSelectOverlay(select) {
65
66
  document.body.appendChild(host);
66
67
  const shadow = host.attachShadow({ mode: "open" });
67
68
  const style = document.createElement("style");
69
+ const nonce = cspStyleNonce();
70
+ if (nonce)
71
+ style.nonce = nonce;
68
72
  style.textContent = OVERLAY_CSS;
69
73
  shadow.appendChild(style);
70
74
  // Title label: prefer the matching `<label>`, then aria-label,
package/dist/session.d.ts CHANGED
@@ -160,8 +160,11 @@ export declare class PrsonLoginSession {
160
160
  * True when the sign-in presentation didn't bind a session key (a
161
161
  * wallet older than envelope v2). The sender of inbound envelopes
162
162
  * can't be checked then, so envelopes that act on the page (`nav`,
163
- * `value`, `mouse-update`, file transfer) are ignored; everything
164
- * else still works. See SECURITY.md §4.
163
+ * `value`, `mouse-update`, file transfer) and request replies
164
+ * (`response`) are ignored, `request()` resolves with
165
+ * `{ ok: false, error: "unsupported" }` and no field values are sent
166
+ * (`focus`). Sign-in, renewals and claim updates (all verified
167
+ * presentations) and sign-out still work. See SECURITY.md §4.
165
168
  */
166
169
  private _legacyChannel;
167
170
  /** `iat` of the newest verified presentation (sign-in or renewal).
@@ -408,6 +411,9 @@ export declare class PrsonLoginSession {
408
411
  * replied. Defaults to 60 s.
409
412
  * * `session-closed` — the session shut down with this request
410
413
  * in flight.
414
+ * * `unsupported` — the wallet predates envelope v2 (it bound no
415
+ * session key into the sign-in), so its replies couldn't be told
416
+ * apart from anyone else's. Nothing is sent to it.
411
417
  *
412
418
  * Wire grammar: outbound envelope shape is
413
419
  * `{ v, msg: "request", issuedAt, domain, requestId, kind, ...kindFields }`,
package/dist/session.js CHANGED
@@ -100,8 +100,11 @@ export class PrsonLoginSession {
100
100
  * True when the sign-in presentation didn't bind a session key (a
101
101
  * wallet older than envelope v2). The sender of inbound envelopes
102
102
  * can't be checked then, so envelopes that act on the page (`nav`,
103
- * `value`, `mouse-update`, file transfer) are ignored; everything
104
- * else still works. See SECURITY.md §4.
103
+ * `value`, `mouse-update`, file transfer) and request replies
104
+ * (`response`) are ignored, `request()` resolves with
105
+ * `{ ok: false, error: "unsupported" }` and no field values are sent
106
+ * (`focus`). Sign-in, renewals and claim updates (all verified
107
+ * presentations) and sign-out still work. See SECURITY.md §4.
105
108
  */
106
109
  this._legacyChannel = false;
107
110
  /** `iat` of the newest verified presentation (sign-in or renewal).
@@ -384,6 +387,9 @@ export class PrsonLoginSession {
384
387
  * replied. Defaults to 60 s.
385
388
  * * `session-closed` — the session shut down with this request
386
389
  * in flight.
390
+ * * `unsupported` — the wallet predates envelope v2 (it bound no
391
+ * session key into the sign-in), so its replies couldn't be told
392
+ * apart from anyone else's. Nothing is sent to it.
387
393
  *
388
394
  * Wire grammar: outbound envelope shape is
389
395
  * `{ v, msg: "request", issuedAt, domain, requestId, kind, ...kindFields }`,
@@ -427,6 +433,10 @@ export class PrsonLoginSession {
427
433
  return;
428
434
  if (!this._walletSessionPk)
429
435
  return;
436
+ // A legacy wallet's key isn't bound to the sign-in, and its edits
437
+ // (`value`) are ignored anyway: don't send it the page's fields.
438
+ if (this._legacyChannel)
439
+ return;
430
440
  // Focus updates drive the wallet drawer's mirrored input — the
431
441
  // user can't edit a value the wallet never received, so we
432
442
  // ack-track these. The promise is awaited only by tests; the
@@ -560,6 +570,11 @@ export class PrsonLoginSession {
560
570
  async _sendRequest(req, opts, onMouseFrame) {
561
571
  if (this._closed)
562
572
  return { ok: false, error: "session-closed" };
573
+ // A legacy session can't check who sent a `response` (no session
574
+ // key bound in the presentation), so anyone able to box to us could
575
+ // answer. Refuse the request instead of trusting the reply.
576
+ if (this._legacyChannel)
577
+ return { ok: false, error: "unsupported" };
563
578
  const recipientPk = this._walletSessionPk;
564
579
  if (!recipientPk)
565
580
  return { ok: false, error: "no-active-session" };
@@ -1011,6 +1026,10 @@ export class PrsonLoginSession {
1011
1026
  this._handleCredentialRevoked(envelope);
1012
1027
  return;
1013
1028
  case "response":
1029
+ // Legacy sessions never send requests (see _sendRequest); a
1030
+ // `response` there is unauthenticated, so it resolves nothing.
1031
+ if (this._legacyChannel)
1032
+ return;
1014
1033
  // Wallet replied to an outbound `request`. Match by UUID
1015
1034
  // and resolve the matching promise. Late replies (after
1016
1035
  // timeout) silently no-op — the controller already
@@ -1,13 +1,3 @@
1
- /**
2
- * Browser-side WebSocket client for the Cloudflare Worker signaling
3
- * Durable Object. The wallet talks to the same Worker; the DO fans
4
- * messages between us.
5
- *
6
- * Wire format mirrors the Worker's `SignalingMessage` discriminated
7
- * union (see cloudflare-workers/signaling-worker/src/index.ts). We don't import
8
- * those types directly because cross-package type sharing would
9
- * bloat the SDK; the two definitions are kept in sync by the spec.
10
- */
11
1
  export type SignalingMessage = {
12
2
  msg: "offer";
13
3
  sdp: string;
package/dist/signaling.js CHANGED
@@ -8,6 +8,7 @@
8
8
  * those types directly because cross-package type sharing would
9
9
  * bloat the SDK; the two definitions are kept in sync by the spec.
10
10
  */
11
+ import { PrsonLoginError, closedCode } from "./errors.js";
11
12
  const WS_SUBPROTOCOL = "prson-login-v1";
12
13
  export async function connectSignaling(opts) {
13
14
  const ws = new WebSocket(opts.url, [WS_SUBPROTOCOL, opts.sigToken]);
@@ -25,7 +26,7 @@ export async function connectSignaling(opts) {
25
26
  const onErrorBefore = () => {
26
27
  ws.removeEventListener("open", onOpen);
27
28
  ws.removeEventListener("error", onErrorBefore);
28
- reject(new Error("signaling: WS upgrade failed (auth?)"));
29
+ reject(new PrsonLoginError("network", "signaling: WS upgrade failed (auth?)"));
29
30
  };
30
31
  ws.addEventListener("open", onOpen);
31
32
  ws.addEventListener("error", onErrorBefore);
@@ -57,7 +58,7 @@ export async function connectSignaling(opts) {
57
58
  const reason = evt.reason || `code-${evt.code}`;
58
59
  closedReason = reason;
59
60
  for (const w of iceWaiters.splice(0))
60
- w.reject(new Error(`signaling: closed before the code was claimed (${reason})`));
61
+ w.reject(new PrsonLoginError(closedCode(reason), `signaling: closed before the code was claimed (${reason})`));
61
62
  for (const cb of closeListeners)
62
63
  cb(reason);
63
64
  });
@@ -77,7 +78,7 @@ export async function connectSignaling(opts) {
77
78
  if (ice)
78
79
  return Promise.resolve(ice);
79
80
  if (closedReason !== null) {
80
- return Promise.reject(new Error(`signaling: closed before the code was claimed (${closedReason})`));
81
+ return Promise.reject(new PrsonLoginError(closedCode(closedReason), `signaling: closed before the code was claimed (${closedReason})`));
81
82
  }
82
83
  return new Promise((resolve, reject) => iceWaiters.push({ resolve, reject }));
83
84
  },
@@ -1,8 +1,3 @@
1
- /**
2
- * Browser-side WebRTC transport. Orchestrates the SDP offer / answer +
3
- * ICE exchange via the Cloudflare Worker signaling, and exposes a
4
- * tiny event-stream interface over the established data channel.
5
- */
6
1
  import type { SignalingConnection } from "./signaling.js";
7
2
  export interface Transport {
8
3
  /** Await the next data-channel message as a UTF-8 string. */
@@ -25,14 +20,24 @@ export interface Transport {
25
20
  close(): void;
26
21
  }
27
22
  /**
28
- * RTCPeerConnection config for the browser side. With TURN available
29
- * the browser is relay-only (`iceTransportPolicy: "relay"`, no STUN):
30
- * it gathers only relay candidates, so none of its own addresses (LAN,
31
- * public) reach the phone — the wallet has done the same since M-4.
32
- * A dev relay without TURN credentials hands out STUN only; relay-only
33
- * would find no candidates, so that case falls back to `"all"`.
23
+ * RTCPeerConnection config for the browser side. The browser is always
24
+ * relay-only (`iceTransportPolicy: "relay"`, no STUN): it gathers only
25
+ * relay candidates, so none of its own addresses (LAN, public) reach the
26
+ * phone — the wallet has done the same since M-4.
27
+ *
28
+ * A relay that sends no TURN server would leave nothing to relay
29
+ * through, and the old fallback (`"all"`) leaked the browser's
30
+ * addresses. That now fails closed: the sign-in stops with an error.
31
+ * The one exception is a page on loopback ([allowDirect], for a local
32
+ * relay without TURN credentials during development), where the direct
33
+ * candidates stay on the developer's own machine and network.
34
34
  */
35
- export declare function rtcConfigFor(iceServers: RTCIceServer[]): RTCConfiguration;
35
+ export declare function rtcConfigFor(iceServers: RTCIceServer[], opts?: {
36
+ allowDirect?: boolean;
37
+ }): RTCConfiguration;
38
+ /** True when [hostname] is this machine: `localhost` (and `*.localhost`),
39
+ * 127.0.0.0/8 or `::1`. */
40
+ export declare function isLoopbackHost(hostname: string | undefined | null): boolean;
36
41
  export declare function establishTransport(opts: {
37
42
  signaling: SignalingConnection;
38
43
  role: "browser";
package/dist/transport.js CHANGED
@@ -1,12 +1,23 @@
1
1
  /**
2
- * RTCPeerConnection config for the browser side. With TURN available
3
- * the browser is relay-only (`iceTransportPolicy: "relay"`, no STUN):
4
- * it gathers only relay candidates, so none of its own addresses (LAN,
5
- * public) reach the phone — the wallet has done the same since M-4.
6
- * A dev relay without TURN credentials hands out STUN only; relay-only
7
- * would find no candidates, so that case falls back to `"all"`.
2
+ * Browser-side WebRTC transport. Orchestrates the SDP offer / answer +
3
+ * ICE exchange via the Cloudflare Worker signaling, and exposes a
4
+ * tiny event-stream interface over the established data channel.
8
5
  */
9
- export function rtcConfigFor(iceServers) {
6
+ import { PrsonLoginError } from "./errors.js";
7
+ /**
8
+ * RTCPeerConnection config for the browser side. The browser is always
9
+ * relay-only (`iceTransportPolicy: "relay"`, no STUN): it gathers only
10
+ * relay candidates, so none of its own addresses (LAN, public) reach the
11
+ * phone — the wallet has done the same since M-4.
12
+ *
13
+ * A relay that sends no TURN server would leave nothing to relay
14
+ * through, and the old fallback (`"all"`) leaked the browser's
15
+ * addresses. That now fails closed: the sign-in stops with an error.
16
+ * The one exception is a page on loopback ([allowDirect], for a local
17
+ * relay without TURN credentials during development), where the direct
18
+ * candidates stay on the developer's own machine and network.
19
+ */
20
+ export function rtcConfigFor(iceServers, opts) {
10
21
  const urls = (s) => (Array.isArray(s.urls) ? s.urls : [s.urls]);
11
22
  const isTurn = (u) => /^turns?:/i.test(u);
12
23
  const turn = iceServers
@@ -14,13 +25,31 @@ export function rtcConfigFor(iceServers) {
14
25
  .filter((s) => s.urls.length > 0);
15
26
  if (turn.length > 0)
16
27
  return { iceServers: turn, iceTransportPolicy: "relay" };
17
- return { iceServers, iceTransportPolicy: "all" };
28
+ if (opts?.allowDirect === true)
29
+ return { iceServers, iceTransportPolicy: "all" };
30
+ throw new PrsonLoginError("network", "transport: the relay sent no TURN server; refusing a direct connection");
31
+ }
32
+ /** True when [hostname] is this machine: `localhost` (and `*.localhost`),
33
+ * 127.0.0.0/8 or `::1`. */
34
+ export function isLoopbackHost(hostname) {
35
+ if (!hostname)
36
+ return false;
37
+ const h = hostname.toLowerCase().replace(/^\[|\]$/g, "");
38
+ if (h === "localhost" || h.endsWith(".localhost"))
39
+ return true;
40
+ if (h === "::1")
41
+ return true;
42
+ return /^127(?:\.\d{1,3}){3}$/.test(h);
43
+ }
44
+ function pageIsLoopback() {
45
+ const loc = globalThis.location;
46
+ return isLoopbackHost(loc?.hostname);
18
47
  }
19
48
  /** How long a live data channel must stay silent after a `peer-gone`
20
49
  * before we believe it. The wallet pings every 2 s. */
21
50
  const PEER_GONE_CONFIRM_MS = 6000;
22
51
  export async function establishTransport(opts) {
23
- const pc = new RTCPeerConnection(rtcConfigFor(opts.iceServers));
52
+ const pc = new RTCPeerConnection(rtcConfigFor(opts.iceServers, { allowDirect: pageIsLoopback() }));
24
53
  // Browser is the initiator → opens the data channel before the
25
54
  // offer. Negotiated=false so the wallet sees `ondatachannel`.
26
55
  const dc = pc.createDataChannel("prson-login", { ordered: true });
@@ -98,7 +127,7 @@ export async function establishTransport(opts) {
98
127
  const onError = () => {
99
128
  dc.removeEventListener("open", onOpen);
100
129
  dc.removeEventListener("error", onError);
101
- reject(new Error("transport: data channel failed to open"));
130
+ reject(new PrsonLoginError("network", "transport: data channel failed to open"));
102
131
  };
103
132
  dc.addEventListener("open", onOpen);
104
133
  dc.addEventListener("error", onError);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@prson/login-sdk",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "private": false,
5
5
  "description": "Frontend-first sign-in SDK that delivers a verifiable credential from a Prson mobile wallet to your website over an end-to-end-encrypted WebRTC channel. See README.md.",
6
6
  "type": "module",
@@ -19,7 +19,7 @@
19
19
  "build:example": "esbuild src/index.ts --bundle --format=esm --target=es2020 --platform=browser --outfile=../../examples/plain-html/prson-login.js --sourcemap",
20
20
  "watch:example": "esbuild src/index.ts --bundle --format=esm --target=es2020 --platform=browser --outfile=../../examples/plain-html/prson-login.js --sourcemap --watch",
21
21
  "typecheck": "tsc --noEmit",
22
- "test": "tsc && node --test dist/session.test.js dist/status.test.js dist/notify.test.js dist/channel.test.js",
22
+ "test": "tsc && node --test dist/session.test.js dist/status.test.js dist/notify.test.js dist/channel.test.js dist/csp.test.js dist/errors.test.js",
23
23
  "prepublishOnly": "npm test && npm run build"
24
24
  },
25
25
  "dependencies": {