@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.
- package/LICENSE +202 -0
- package/README.md +364 -2
- package/dist/api.d.ts +59 -0
- package/dist/api.js +41 -0
- package/dist/bind.d.ts +224 -0
- package/dist/bind.js +1384 -0
- package/dist/crypto.d.ts +352 -0
- package/dist/crypto.js +159 -0
- package/dist/csp.d.ts +39 -0
- package/dist/csp.js +125 -0
- package/dist/errors.d.ts +40 -0
- package/dist/errors.js +28 -0
- package/dist/index.d.ts +363 -0
- package/dist/index.js +6278 -0
- package/dist/index.js.map +7 -0
- package/dist/notify.d.ts +8 -0
- package/dist/notify.js +17 -0
- package/dist/point_phone_overlay.d.ts +41 -0
- package/dist/point_phone_overlay.js +161 -0
- package/dist/qr.d.ts +105 -0
- package/dist/qr.js +149 -0
- package/dist/requests.d.ts +279 -0
- package/dist/requests.js +128 -0
- package/dist/select_overlay.d.ts +70 -0
- package/dist/select_overlay.js +430 -0
- package/dist/session.d.ts +645 -0
- package/dist/session.js +1455 -0
- package/dist/signaling.d.ts +49 -0
- package/dist/signaling.js +92 -0
- package/dist/status.d.ts +48 -0
- package/dist/status.js +105 -0
- package/dist/transport.d.ts +50 -0
- package/dist/transport.js +212 -0
- package/dist/verification.d.ts +56 -0
- package/dist/verification.js +169 -0
- package/dist/verify.d.ts +69 -0
- package/dist/verify.js +331 -0
- package/package.json +59 -4
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
export type SignalingMessage = {
|
|
2
|
+
msg: "offer";
|
|
3
|
+
sdp: string;
|
|
4
|
+
} | {
|
|
5
|
+
msg: "answer";
|
|
6
|
+
sdp: string;
|
|
7
|
+
} | {
|
|
8
|
+
msg: "candidate";
|
|
9
|
+
candidate: unknown;
|
|
10
|
+
} | {
|
|
11
|
+
msg: "peer-ready";
|
|
12
|
+
} | {
|
|
13
|
+
msg: "peer-gone";
|
|
14
|
+
} | {
|
|
15
|
+
msg: "error";
|
|
16
|
+
reason: string;
|
|
17
|
+
};
|
|
18
|
+
/**
|
|
19
|
+
* Relay → browser, once a wallet has claimed the code:
|
|
20
|
+
* `{ "type": "ice", "iceServers": [...] }` — the TURN servers the
|
|
21
|
+
* browser must use (relay-only, so its addresses never reach the
|
|
22
|
+
* phone). Newer relays send no TURN at draft time; older ones put it
|
|
23
|
+
* in the draft response instead and never send this.
|
|
24
|
+
*/
|
|
25
|
+
export type IceMessage = {
|
|
26
|
+
type: "ice";
|
|
27
|
+
iceServers: RTCIceServer[];
|
|
28
|
+
};
|
|
29
|
+
export interface SignalingConnection {
|
|
30
|
+
/** Push a message to the other peer through the relay. */
|
|
31
|
+
send(m: SignalingMessage): void;
|
|
32
|
+
/** Subscribe to messages from the other peer. */
|
|
33
|
+
onMessage(cb: (m: SignalingMessage) => void): void;
|
|
34
|
+
/** Subscribe to terminal-close events from either side or the worker. */
|
|
35
|
+
onClose(cb: (reason: string) => void): void;
|
|
36
|
+
/**
|
|
37
|
+
* Resolves with the relay's `ice` servers (the first `ice` message,
|
|
38
|
+
* buffered if it arrived before this was called). Rejects if the
|
|
39
|
+
* socket closes first.
|
|
40
|
+
*/
|
|
41
|
+
awaitIce(): Promise<RTCIceServer[]>;
|
|
42
|
+
/** Close the WS. Does not tear down the underlying RTCPeerConnection. */
|
|
43
|
+
close(): void;
|
|
44
|
+
}
|
|
45
|
+
export declare function connectSignaling(opts: {
|
|
46
|
+
url: string;
|
|
47
|
+
role: "browser";
|
|
48
|
+
sigToken: string;
|
|
49
|
+
}): Promise<SignalingConnection>;
|
|
@@ -0,0 +1,92 @@
|
|
|
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
|
+
import { PrsonLoginError, closedCode } from "./errors.js";
|
|
12
|
+
const WS_SUBPROTOCOL = "prson-login-v1";
|
|
13
|
+
export async function connectSignaling(opts) {
|
|
14
|
+
const ws = new WebSocket(opts.url, [WS_SUBPROTOCOL, opts.sigToken]);
|
|
15
|
+
const msgListeners = [];
|
|
16
|
+
const closeListeners = [];
|
|
17
|
+
let ice = null;
|
|
18
|
+
let closedReason = null;
|
|
19
|
+
const iceWaiters = [];
|
|
20
|
+
await new Promise((resolve, reject) => {
|
|
21
|
+
const onOpen = () => {
|
|
22
|
+
ws.removeEventListener("open", onOpen);
|
|
23
|
+
ws.removeEventListener("error", onErrorBefore);
|
|
24
|
+
resolve();
|
|
25
|
+
};
|
|
26
|
+
const onErrorBefore = () => {
|
|
27
|
+
ws.removeEventListener("open", onOpen);
|
|
28
|
+
ws.removeEventListener("error", onErrorBefore);
|
|
29
|
+
reject(new PrsonLoginError("network", "signaling: WS upgrade failed (auth?)"));
|
|
30
|
+
};
|
|
31
|
+
ws.addEventListener("open", onOpen);
|
|
32
|
+
ws.addEventListener("error", onErrorBefore);
|
|
33
|
+
});
|
|
34
|
+
ws.addEventListener("message", (evt) => {
|
|
35
|
+
let parsed;
|
|
36
|
+
try {
|
|
37
|
+
parsed = JSON.parse(String(evt.data));
|
|
38
|
+
}
|
|
39
|
+
catch {
|
|
40
|
+
return; // bad frame from the Worker; ignore
|
|
41
|
+
}
|
|
42
|
+
if (parsed && parsed.type === "ice") {
|
|
43
|
+
// Only the first one counts: the peer connection is built from it.
|
|
44
|
+
const servers = parsed.iceServers;
|
|
45
|
+
if (ice || !Array.isArray(servers))
|
|
46
|
+
return;
|
|
47
|
+
ice = servers.filter((x) => x && (typeof x.urls === "string" || Array.isArray(x.urls)));
|
|
48
|
+
for (const w of iceWaiters.splice(0))
|
|
49
|
+
w.resolve(ice);
|
|
50
|
+
return;
|
|
51
|
+
}
|
|
52
|
+
if (!parsed || typeof parsed.msg !== "string")
|
|
53
|
+
return;
|
|
54
|
+
for (const cb of msgListeners)
|
|
55
|
+
cb(parsed);
|
|
56
|
+
});
|
|
57
|
+
ws.addEventListener("close", (evt) => {
|
|
58
|
+
const reason = evt.reason || `code-${evt.code}`;
|
|
59
|
+
closedReason = reason;
|
|
60
|
+
for (const w of iceWaiters.splice(0))
|
|
61
|
+
w.reject(new PrsonLoginError(closedCode(reason), `signaling: closed before the code was claimed (${reason})`));
|
|
62
|
+
for (const cb of closeListeners)
|
|
63
|
+
cb(reason);
|
|
64
|
+
});
|
|
65
|
+
return {
|
|
66
|
+
send(m) {
|
|
67
|
+
if (ws.readyState !== WebSocket.OPEN)
|
|
68
|
+
return;
|
|
69
|
+
ws.send(JSON.stringify(m));
|
|
70
|
+
},
|
|
71
|
+
onMessage(cb) {
|
|
72
|
+
msgListeners.push(cb);
|
|
73
|
+
},
|
|
74
|
+
onClose(cb) {
|
|
75
|
+
closeListeners.push(cb);
|
|
76
|
+
},
|
|
77
|
+
awaitIce() {
|
|
78
|
+
if (ice)
|
|
79
|
+
return Promise.resolve(ice);
|
|
80
|
+
if (closedReason !== null) {
|
|
81
|
+
return Promise.reject(new PrsonLoginError(closedCode(closedReason), `signaling: closed before the code was claimed (${closedReason})`));
|
|
82
|
+
}
|
|
83
|
+
return new Promise((resolve, reject) => iceWaiters.push({ resolve, reject }));
|
|
84
|
+
},
|
|
85
|
+
close() {
|
|
86
|
+
try {
|
|
87
|
+
ws.close(1000, "client_close");
|
|
88
|
+
}
|
|
89
|
+
catch { /* */ }
|
|
90
|
+
},
|
|
91
|
+
};
|
|
92
|
+
}
|
package/dist/status.d.ts
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Revocation check: IETF Token Status List (draft-ietf-oauth-status-list).
|
|
3
|
+
*
|
|
4
|
+
* Every credential Prson issues carries
|
|
5
|
+
* status: { status_list: { idx, uri } }
|
|
6
|
+
* and `uri` serves a Status List Token: a JWT (typ statuslist+jwt) signed by
|
|
7
|
+
* the same issuer key as the credential, whose status_list.lst is a
|
|
8
|
+
* base64url, DEFLATE (ZLIB) compressed bitstring (`bits` bits per entry,
|
|
9
|
+
* index 0 in the lowest bits of byte 0). 0 = VALID; anything else (1
|
|
10
|
+
* INVALID, 2 SUSPENDED) means the credential must not be accepted.
|
|
11
|
+
*
|
|
12
|
+
* Lists are cached briefly (default 60 s, never longer than the token's own
|
|
13
|
+
* ttl). When the list can't be fetched or checked, `onUnavailable` decides:
|
|
14
|
+
* "fail-closed" rejects, "fail-open" accepts. The default is closed for
|
|
15
|
+
* verified humans (verification_level 5 or more, or verified_human: true)
|
|
16
|
+
* and open below that.
|
|
17
|
+
*/
|
|
18
|
+
export type StatusPolicy = "fail-open" | "fail-closed";
|
|
19
|
+
export type StatusCheckOptions = {
|
|
20
|
+
/** What to do when the status list can't be fetched or verified. Default: closed at level 5+, open below. */
|
|
21
|
+
onUnavailable?: StatusPolicy;
|
|
22
|
+
/** How long a fetched list is reused (seconds, default 60; capped by the token's ttl). */
|
|
23
|
+
cacheSeconds?: number;
|
|
24
|
+
/** The issuer's key for a kid (the same keys that sign credentials). */
|
|
25
|
+
resolveKey: (kid: string) => Promise<JsonWebKey | null>;
|
|
26
|
+
/** Override fetch (tests, proxies). */
|
|
27
|
+
fetch?: (uri: string) => Promise<{
|
|
28
|
+
ok: boolean;
|
|
29
|
+
status: number;
|
|
30
|
+
text(): Promise<string>;
|
|
31
|
+
}>;
|
|
32
|
+
/** Clock override (ms). */
|
|
33
|
+
now?: () => number;
|
|
34
|
+
};
|
|
35
|
+
export type StatusCheckResult = {
|
|
36
|
+
ok: true;
|
|
37
|
+
checked: boolean;
|
|
38
|
+
unavailable?: string;
|
|
39
|
+
} | {
|
|
40
|
+
ok: false;
|
|
41
|
+
reason: "vc_revoked" | "status_unavailable";
|
|
42
|
+
detail?: string;
|
|
43
|
+
};
|
|
44
|
+
/** Tests: forget cached lists. */
|
|
45
|
+
export declare function clearStatusCache(): void;
|
|
46
|
+
/** Whether the credential's claims describe a verified human (where an unknown status fails closed by default). */
|
|
47
|
+
export declare function isStrongCredential(payload: Record<string, unknown>): boolean;
|
|
48
|
+
export declare function checkCredentialStatus(payload: Record<string, unknown>, opts: StatusCheckOptions): Promise<StatusCheckResult>;
|
package/dist/status.js
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Revocation check: IETF Token Status List (draft-ietf-oauth-status-list).
|
|
3
|
+
*
|
|
4
|
+
* Every credential Prson issues carries
|
|
5
|
+
* status: { status_list: { idx, uri } }
|
|
6
|
+
* and `uri` serves a Status List Token: a JWT (typ statuslist+jwt) signed by
|
|
7
|
+
* the same issuer key as the credential, whose status_list.lst is a
|
|
8
|
+
* base64url, DEFLATE (ZLIB) compressed bitstring (`bits` bits per entry,
|
|
9
|
+
* index 0 in the lowest bits of byte 0). 0 = VALID; anything else (1
|
|
10
|
+
* INVALID, 2 SUSPENDED) means the credential must not be accepted.
|
|
11
|
+
*
|
|
12
|
+
* Lists are cached briefly (default 60 s, never longer than the token's own
|
|
13
|
+
* ttl). When the list can't be fetched or checked, `onUnavailable` decides:
|
|
14
|
+
* "fail-closed" rejects, "fail-open" accepts. The default is closed for
|
|
15
|
+
* verified humans (verification_level 5 or more, or verified_human: true)
|
|
16
|
+
* and open below that.
|
|
17
|
+
*/
|
|
18
|
+
const cache = new Map();
|
|
19
|
+
/** Tests: forget cached lists. */
|
|
20
|
+
export function clearStatusCache() {
|
|
21
|
+
cache.clear();
|
|
22
|
+
}
|
|
23
|
+
/** Whether the credential's claims describe a verified human (where an unknown status fails closed by default). */
|
|
24
|
+
export function isStrongCredential(payload) {
|
|
25
|
+
return payload.verified_human === true || (typeof payload.verification_level === "number" && payload.verification_level >= 5);
|
|
26
|
+
}
|
|
27
|
+
export async function checkCredentialStatus(payload, opts) {
|
|
28
|
+
const ref = payload.status?.status_list;
|
|
29
|
+
if (!ref)
|
|
30
|
+
return { ok: true, checked: false };
|
|
31
|
+
const policy = opts.onUnavailable ?? (isStrongCredential(payload) ? "fail-closed" : "fail-open");
|
|
32
|
+
const unavailable = (detail) => policy === "fail-open" ? { ok: true, checked: false, unavailable: detail } : { ok: false, reason: "status_unavailable", detail };
|
|
33
|
+
const idx = ref.idx;
|
|
34
|
+
const uri = ref.uri;
|
|
35
|
+
if (typeof idx !== "number" || !Number.isInteger(idx) || idx < 0 || typeof uri !== "string" || !/^https:\/\//.test(uri)) {
|
|
36
|
+
return { ok: false, reason: "status_unavailable", detail: "malformed status reference" };
|
|
37
|
+
}
|
|
38
|
+
let entry;
|
|
39
|
+
try {
|
|
40
|
+
entry = await statusList(uri, opts);
|
|
41
|
+
}
|
|
42
|
+
catch (e) {
|
|
43
|
+
return unavailable(e.message);
|
|
44
|
+
}
|
|
45
|
+
const bitOffset = idx * entry.bits;
|
|
46
|
+
const byte = entry.list[bitOffset >> 3];
|
|
47
|
+
if (byte === undefined)
|
|
48
|
+
return unavailable("index outside the list");
|
|
49
|
+
const value = (byte >> (bitOffset & 7)) & ((1 << entry.bits) - 1);
|
|
50
|
+
if (value !== 0)
|
|
51
|
+
return { ok: false, reason: "vc_revoked", detail: value === 2 ? "suspended" : "invalid" };
|
|
52
|
+
return { ok: true, checked: true };
|
|
53
|
+
}
|
|
54
|
+
async function statusList(uri, opts) {
|
|
55
|
+
const now = opts.now?.() ?? Date.now();
|
|
56
|
+
const cached = cache.get(uri);
|
|
57
|
+
if (cached && now - cached.fetchedAt < cached.ttlMs && (cached.exp === null || cached.exp * 1000 > now))
|
|
58
|
+
return cached;
|
|
59
|
+
const doFetch = opts.fetch ?? ((u) => fetch(u, { headers: { Accept: "application/statuslist+jwt" } }));
|
|
60
|
+
const res = await doFetch(uri);
|
|
61
|
+
if (!res.ok)
|
|
62
|
+
throw new Error(`status list HTTP ${res.status}`);
|
|
63
|
+
const jwt = (await res.text()).trim();
|
|
64
|
+
const [h, p, s] = jwt.split(".");
|
|
65
|
+
if (!h || !p || !s)
|
|
66
|
+
throw new Error("status list token malformed");
|
|
67
|
+
const header = JSON.parse(utf8(b64uBytes(h)));
|
|
68
|
+
const payload = JSON.parse(utf8(b64uBytes(p)));
|
|
69
|
+
if (header.typ !== "statuslist+jwt" || header.alg !== "RS256" || !header.kid)
|
|
70
|
+
throw new Error("status list token header");
|
|
71
|
+
const jwk = await opts.resolveKey(header.kid);
|
|
72
|
+
if (!jwk)
|
|
73
|
+
throw new Error("status list key unknown");
|
|
74
|
+
const key = await crypto.subtle.importKey("jwk", jwk, { name: "RSASSA-PKCS1-v1_5", hash: "SHA-256" }, false, ["verify"]);
|
|
75
|
+
if (!(await crypto.subtle.verify("RSASSA-PKCS1-v1_5", key, b64uBytes(s), new TextEncoder().encode(`${h}.${p}`))))
|
|
76
|
+
throw new Error("status list signature");
|
|
77
|
+
if (payload.sub !== uri)
|
|
78
|
+
throw new Error("status list subject");
|
|
79
|
+
if (typeof payload.exp === "number" && payload.exp * 1000 <= now)
|
|
80
|
+
throw new Error("status list expired");
|
|
81
|
+
const bits = payload.status_list?.bits;
|
|
82
|
+
if (bits !== 1 && bits !== 2 && bits !== 4 && bits !== 8)
|
|
83
|
+
throw new Error("status list bits");
|
|
84
|
+
if (typeof payload.status_list?.lst !== "string")
|
|
85
|
+
throw new Error("status list lst");
|
|
86
|
+
const list = await inflate(b64uBytes(payload.status_list.lst));
|
|
87
|
+
const want = (opts.cacheSeconds ?? 60) * 1000;
|
|
88
|
+
const ttlMs = typeof payload.ttl === "number" ? Math.min(want, payload.ttl * 1000) : want;
|
|
89
|
+
const entry = { fetchedAt: now, ttlMs, exp: typeof payload.exp === "number" ? payload.exp : null, bits, list };
|
|
90
|
+
cache.set(uri, entry);
|
|
91
|
+
return entry;
|
|
92
|
+
}
|
|
93
|
+
async function inflate(bytes) {
|
|
94
|
+
const stream = new Blob([bytes]).stream().pipeThrough(new DecompressionStream("deflate"));
|
|
95
|
+
return new Uint8Array(await new Response(stream).arrayBuffer());
|
|
96
|
+
}
|
|
97
|
+
const utf8 = (b) => new TextDecoder().decode(b);
|
|
98
|
+
function b64uBytes(s) {
|
|
99
|
+
const pad = (4 - (s.length % 4)) % 4;
|
|
100
|
+
const bin = atob((s + "=".repeat(pad)).replace(/-/g, "+").replace(/_/g, "/"));
|
|
101
|
+
const out = new Uint8Array(new ArrayBuffer(bin.length));
|
|
102
|
+
for (let i = 0; i < bin.length; i++)
|
|
103
|
+
out[i] = bin.charCodeAt(i);
|
|
104
|
+
return out;
|
|
105
|
+
}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import type { SignalingConnection } from "./signaling.js";
|
|
2
|
+
export interface Transport {
|
|
3
|
+
/** Await the next data-channel message as a UTF-8 string. */
|
|
4
|
+
awaitNextMessage(): Promise<string>;
|
|
5
|
+
/** Await the first data-channel message; convenience wrapper. */
|
|
6
|
+
awaitFirstMessage(): Promise<string>;
|
|
7
|
+
/** Subscribe to all data-channel messages as they arrive. */
|
|
8
|
+
onMessage(cb: (raw: string) => void): void;
|
|
9
|
+
/** Subscribe to terminal-close events from either side or the
|
|
10
|
+
* Worker. Fires exactly once per transport with a short string
|
|
11
|
+
* reason — the SDK's session layer maps this to the matching
|
|
12
|
+
* `signed_out` reason code so the host gets a lifecycle event
|
|
13
|
+
* the moment the wire dies (rather than waiting for the
|
|
14
|
+
* credential's exp timer, which runs days from now and never
|
|
15
|
+
* matches the much-shorter session TTL). */
|
|
16
|
+
onClose(cb: (reason: string) => void): void;
|
|
17
|
+
/** Send a UTF-8 string over the data channel (used by `revoke` etc.). */
|
|
18
|
+
send(raw: string): void;
|
|
19
|
+
/** Close the RTCPeerConnection + the data channel. */
|
|
20
|
+
close(): void;
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
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
|
+
*/
|
|
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;
|
|
41
|
+
export declare function establishTransport(opts: {
|
|
42
|
+
signaling: SignalingConnection;
|
|
43
|
+
role: "browser";
|
|
44
|
+
/**
|
|
45
|
+
* ICE servers from the relay: the `ice` message it sends once a wallet
|
|
46
|
+
* claimed the code, or (older relays) the draft response's `turn`.
|
|
47
|
+
* See [rtcConfigFor] and ../../SECURITY.md §6.
|
|
48
|
+
*/
|
|
49
|
+
iceServers: RTCIceServer[];
|
|
50
|
+
}): Promise<Transport>;
|
|
@@ -0,0 +1,212 @@
|
|
|
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
|
+
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) {
|
|
21
|
+
const urls = (s) => (Array.isArray(s.urls) ? s.urls : [s.urls]);
|
|
22
|
+
const isTurn = (u) => /^turns?:/i.test(u);
|
|
23
|
+
const turn = iceServers
|
|
24
|
+
.map((s) => ({ ...s, urls: urls(s).filter(isTurn) }))
|
|
25
|
+
.filter((s) => s.urls.length > 0);
|
|
26
|
+
if (turn.length > 0)
|
|
27
|
+
return { iceServers: turn, iceTransportPolicy: "relay" };
|
|
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);
|
|
47
|
+
}
|
|
48
|
+
/** How long a live data channel must stay silent after a `peer-gone`
|
|
49
|
+
* before we believe it. The wallet pings every 2 s. */
|
|
50
|
+
const PEER_GONE_CONFIRM_MS = 6000;
|
|
51
|
+
export async function establishTransport(opts) {
|
|
52
|
+
const pc = new RTCPeerConnection(rtcConfigFor(opts.iceServers, { allowDirect: pageIsLoopback() }));
|
|
53
|
+
// Browser is the initiator → opens the data channel before the
|
|
54
|
+
// offer. Negotiated=false so the wallet sees `ondatachannel`.
|
|
55
|
+
const dc = pc.createDataChannel("prson-login", { ordered: true });
|
|
56
|
+
// Trickle ICE → signaling.
|
|
57
|
+
pc.addEventListener("icecandidate", (e) => {
|
|
58
|
+
if (e.candidate)
|
|
59
|
+
opts.signaling.send({ msg: "candidate", candidate: e.candidate.toJSON() });
|
|
60
|
+
});
|
|
61
|
+
// Bridge inbound signaling → peer connection.
|
|
62
|
+
opts.signaling.onMessage(async (m) => {
|
|
63
|
+
if (m.msg === "answer") {
|
|
64
|
+
await pc.setRemoteDescription({ type: "answer", sdp: m.sdp });
|
|
65
|
+
}
|
|
66
|
+
else if (m.msg === "candidate") {
|
|
67
|
+
try {
|
|
68
|
+
await pc.addIceCandidate(m.candidate);
|
|
69
|
+
}
|
|
70
|
+
catch {
|
|
71
|
+
// Late or duplicate candidates can be ignored — the SDP path
|
|
72
|
+
// covered the gathered ones.
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
else if (m.msg === "peer-gone") {
|
|
76
|
+
// `peer-gone` is the relay's word that the wallet's socket went
|
|
77
|
+
// away. It travels the same socket as the wallet's own messages,
|
|
78
|
+
// so it isn't proof: once the data channel is up, the channel
|
|
79
|
+
// itself decides — if the wallet stays silent (it pings every
|
|
80
|
+
// 2 s), it's gone; if it keeps talking, the notice is ignored.
|
|
81
|
+
// `error` frames are never acted on.
|
|
82
|
+
if (dc.readyState === "open") {
|
|
83
|
+
confirmPeerGone();
|
|
84
|
+
return;
|
|
85
|
+
}
|
|
86
|
+
// Wallet vanished — close the data channel so the host knows.
|
|
87
|
+
// Fire the explicit teardown FIRST with a wallet-side reason
|
|
88
|
+
// so the SDK maps it to `wallet_signed_out` (the dc close
|
|
89
|
+
// alone would degrade to the generic `network_loss`).
|
|
90
|
+
fireClose("wallet_signed_out");
|
|
91
|
+
try {
|
|
92
|
+
dc.close();
|
|
93
|
+
}
|
|
94
|
+
catch { /* */ }
|
|
95
|
+
}
|
|
96
|
+
});
|
|
97
|
+
let lastDcMessageAt = 0;
|
|
98
|
+
let peerGoneTimer = null;
|
|
99
|
+
function confirmPeerGone() {
|
|
100
|
+
if (peerGoneTimer)
|
|
101
|
+
return;
|
|
102
|
+
const noticeAt = Date.now();
|
|
103
|
+
peerGoneTimer = setTimeout(() => {
|
|
104
|
+
peerGoneTimer = null;
|
|
105
|
+
if (lastDcMessageAt >= noticeAt)
|
|
106
|
+
return; // still talking: not gone
|
|
107
|
+
fireClose("wallet_signed_out");
|
|
108
|
+
try {
|
|
109
|
+
dc.close();
|
|
110
|
+
}
|
|
111
|
+
catch { /* */ }
|
|
112
|
+
}, PEER_GONE_CONFIRM_MS);
|
|
113
|
+
}
|
|
114
|
+
// Generate + post the SDP offer.
|
|
115
|
+
const offer = await pc.createOffer();
|
|
116
|
+
await pc.setLocalDescription(offer);
|
|
117
|
+
opts.signaling.send({ msg: "offer", sdp: offer.sdp });
|
|
118
|
+
// Wait for the data channel to open.
|
|
119
|
+
await new Promise((resolve, reject) => {
|
|
120
|
+
if (dc.readyState === "open")
|
|
121
|
+
return resolve();
|
|
122
|
+
const onOpen = () => {
|
|
123
|
+
dc.removeEventListener("open", onOpen);
|
|
124
|
+
dc.removeEventListener("error", onError);
|
|
125
|
+
resolve();
|
|
126
|
+
};
|
|
127
|
+
const onError = () => {
|
|
128
|
+
dc.removeEventListener("open", onOpen);
|
|
129
|
+
dc.removeEventListener("error", onError);
|
|
130
|
+
reject(new PrsonLoginError("network", "transport: data channel failed to open"));
|
|
131
|
+
};
|
|
132
|
+
dc.addEventListener("open", onOpen);
|
|
133
|
+
dc.addEventListener("error", onError);
|
|
134
|
+
});
|
|
135
|
+
// Message bookkeeping: split between one-shot waiters (the initial
|
|
136
|
+
// presentation) and steady-state subscribers (renewals).
|
|
137
|
+
const oneShotWaiters = [];
|
|
138
|
+
const allListeners = [];
|
|
139
|
+
// Terminal-close fan-out. Three triggers map onto the same
|
|
140
|
+
// notification: signaling close (WS code 4000 = Worker DO alarm
|
|
141
|
+
// fired at session TTL), peer-gone signaling message (wallet
|
|
142
|
+
// revoked), and the data channel itself closing for any other
|
|
143
|
+
// reason. Fired at most once — the latch prevents duplicate
|
|
144
|
+
// signed_out events in the SDK's session layer.
|
|
145
|
+
const closeListeners = [];
|
|
146
|
+
let closeFired = false;
|
|
147
|
+
function fireClose(reason) {
|
|
148
|
+
if (closeFired)
|
|
149
|
+
return;
|
|
150
|
+
closeFired = true;
|
|
151
|
+
for (const cb of closeListeners) {
|
|
152
|
+
try {
|
|
153
|
+
cb(reason);
|
|
154
|
+
}
|
|
155
|
+
catch { /* swallow */ }
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
opts.signaling.onClose((reason) => fireClose(reason));
|
|
159
|
+
dc.addEventListener("close", () => fireClose("network_loss"));
|
|
160
|
+
dc.addEventListener("message", (evt) => {
|
|
161
|
+
lastDcMessageAt = Date.now();
|
|
162
|
+
const raw = typeof evt.data === "string"
|
|
163
|
+
? evt.data
|
|
164
|
+
: new TextDecoder().decode(evt.data);
|
|
165
|
+
while (oneShotWaiters.length > 0) {
|
|
166
|
+
const cb = oneShotWaiters.shift();
|
|
167
|
+
cb(raw);
|
|
168
|
+
}
|
|
169
|
+
for (const cb of allListeners)
|
|
170
|
+
cb(raw);
|
|
171
|
+
});
|
|
172
|
+
return {
|
|
173
|
+
awaitNextMessage() {
|
|
174
|
+
return new Promise((resolve) => oneShotWaiters.push(resolve));
|
|
175
|
+
},
|
|
176
|
+
awaitFirstMessage() {
|
|
177
|
+
return new Promise((resolve) => oneShotWaiters.push(resolve));
|
|
178
|
+
},
|
|
179
|
+
onMessage(cb) {
|
|
180
|
+
allListeners.push(cb);
|
|
181
|
+
},
|
|
182
|
+
onClose(cb) {
|
|
183
|
+
// Late subscribers still get the notification: if the close
|
|
184
|
+
// already fired, dispatch on the next microtask so the
|
|
185
|
+
// subscriber's await chain sees a single deterministic
|
|
186
|
+
// ordering (analogous to `signed_in` being microtask-deferred).
|
|
187
|
+
if (closeFired) {
|
|
188
|
+
queueMicrotask(() => cb("network_loss"));
|
|
189
|
+
}
|
|
190
|
+
else {
|
|
191
|
+
closeListeners.push(cb);
|
|
192
|
+
}
|
|
193
|
+
},
|
|
194
|
+
send(raw) {
|
|
195
|
+
if (dc.readyState === "open")
|
|
196
|
+
dc.send(raw);
|
|
197
|
+
},
|
|
198
|
+
close() {
|
|
199
|
+
if (peerGoneTimer)
|
|
200
|
+
clearTimeout(peerGoneTimer);
|
|
201
|
+
try {
|
|
202
|
+
dc.close();
|
|
203
|
+
}
|
|
204
|
+
catch { /* */ }
|
|
205
|
+
try {
|
|
206
|
+
pc.close();
|
|
207
|
+
}
|
|
208
|
+
catch { /* */ }
|
|
209
|
+
opts.signaling.close();
|
|
210
|
+
},
|
|
211
|
+
};
|
|
212
|
+
}
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Show a person a Prson **verification** (an organisation's request made
|
|
3
|
+
* with POST /v1/verifications — prove your age, show your ID, sign this
|
|
4
|
+
* PDF with your verified name) and wait until they answer it.
|
|
5
|
+
*
|
|
6
|
+
* The verification is created by YOUR SERVER with your API key; the key
|
|
7
|
+
* never reaches the browser. Your page gets the `share_url` from your
|
|
8
|
+
* server, and `checkStatus` asks your server for the status (your server
|
|
9
|
+
* calls GET /v1/verifications/{id}, or keeps what the verification.*
|
|
10
|
+
* webhooks told it). On a computer the link shows as a QR code to scan
|
|
11
|
+
* with the phone; on a phone, as a button that opens the Prson app.
|
|
12
|
+
*
|
|
13
|
+
* const { share_url, id } = await (await fetch("/api/contract/sign", { method: "POST" })).json();
|
|
14
|
+
* await awaitVerification({
|
|
15
|
+
* shareUrl: share_url,
|
|
16
|
+
* title: "Sign the rental agreement",
|
|
17
|
+
* checkStatus: async (signal) => (await (await fetch(`/api/verifications/${id}`, { signal })).json()).status,
|
|
18
|
+
* });
|
|
19
|
+
* // fulfilled: your server downloads the signed PDF (the response's signature.download_path).
|
|
20
|
+
*
|
|
21
|
+
* Resolves with the status once `until` holds (default: "fulfilled");
|
|
22
|
+
* rejects with VerificationClosedError when it was cancelled or expired,
|
|
23
|
+
* and VerificationAbortedError when the person closes the dialog or
|
|
24
|
+
* `signal` aborts.
|
|
25
|
+
*/
|
|
26
|
+
export type VerificationStatus = "open" | "partially_fulfilled" | "fulfilled" | "cancelled" | "expired";
|
|
27
|
+
export interface AwaitVerificationOptions {
|
|
28
|
+
/** The verification's `share_url`, from your server. */
|
|
29
|
+
shareUrl: string;
|
|
30
|
+
/** Your server's view of the verification's status. Called every `intervalMs`; a throw is retried. */
|
|
31
|
+
checkStatus: (signal: AbortSignal) => Promise<VerificationStatus | string>;
|
|
32
|
+
/** Shown above the code: what the person is asked for (e.g. "Sign the rental agreement"). */
|
|
33
|
+
title?: string;
|
|
34
|
+
/** Where to render; default: a modal over the page (Esc or a click outside closes it). */
|
|
35
|
+
mountInto?: string | HTMLElement;
|
|
36
|
+
/** How often to call `checkStatus`, in ms (default 3000, at least 1000). */
|
|
37
|
+
intervalMs?: number;
|
|
38
|
+
/** Stop after this long (ms) with VerificationAbortedError; default: wait until it closes. */
|
|
39
|
+
timeoutMs?: number;
|
|
40
|
+
/** When to stop waiting (default: status === "fulfilled"). */
|
|
41
|
+
until?: (status: string) => boolean;
|
|
42
|
+
signal?: AbortSignal;
|
|
43
|
+
theme?: "light" | "dark" | "auto";
|
|
44
|
+
/** Force the phone (button) or computer (QR) layout; default: guessed from the pointer. */
|
|
45
|
+
layout?: "phone" | "computer";
|
|
46
|
+
}
|
|
47
|
+
export declare class VerificationAbortedError extends Error {
|
|
48
|
+
constructor(message?: string);
|
|
49
|
+
}
|
|
50
|
+
export declare class VerificationClosedError extends Error {
|
|
51
|
+
readonly status: "cancelled" | "expired";
|
|
52
|
+
constructor(status: "cancelled" | "expired");
|
|
53
|
+
}
|
|
54
|
+
export declare function awaitVerification(opts: AwaitVerificationOptions): Promise<{
|
|
55
|
+
status: string;
|
|
56
|
+
}>;
|