@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.
- package/LICENSE +202 -0
- package/README.md +348 -2
- package/dist/api.d.ts +59 -0
- package/dist/api.js +40 -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/index.d.ts +345 -0
- package/dist/index.js +6102 -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 +157 -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 +426 -0
- package/dist/session.d.ts +639 -0
- package/dist/session.js +1436 -0
- package/dist/signaling.d.ts +59 -0
- package/dist/signaling.js +91 -0
- package/dist/status.d.ts +48 -0
- package/dist/status.js +105 -0
- package/dist/transport.d.ts +45 -0
- package/dist/transport.js +183 -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
package/dist/crypto.d.ts
ADDED
|
@@ -0,0 +1,352 @@
|
|
|
1
|
+
export type EphemeralKeys = {
|
|
2
|
+
/** The X25519 secret key (32 bytes). Never serialised; never logged. */
|
|
3
|
+
secretKey: Uint8Array;
|
|
4
|
+
/** The matching public key (32 bytes). */
|
|
5
|
+
publicKey: Uint8Array;
|
|
6
|
+
/** Base64url-encoded public key for use in QRs + the verifier request. */
|
|
7
|
+
publicKeyB64u: string;
|
|
8
|
+
};
|
|
9
|
+
export declare function generateEphemeralKeypair(): Promise<EphemeralKeys>;
|
|
10
|
+
/** Wire shape (matches what the wallet emits — see ARCHITECTURE.md §4.2). */
|
|
11
|
+
export type EncryptedEnvelope = {
|
|
12
|
+
/** The sender's X25519 session pk, base64url. Envelope v2: always the
|
|
13
|
+
* sender's session key (`walletSessionPk` from the wallet, `browserPk`
|
|
14
|
+
* from the browser). Older wallets put a fresh per-message key here. */
|
|
15
|
+
ephPk: string;
|
|
16
|
+
/** 24-byte nonce, base64url. */
|
|
17
|
+
nonce24: string;
|
|
18
|
+
/** Boxed ciphertext + Poly1305 tag, base64url. */
|
|
19
|
+
ct: string;
|
|
20
|
+
};
|
|
21
|
+
/** Decrypted plaintext envelope — see ARCHITECTURE.md §4.2.
|
|
22
|
+
*
|
|
23
|
+
* Three of the `msg` types are post-sign-in lifecycle events
|
|
24
|
+
* (`claim-update`, `display-update`, `credential-revoked`) per the
|
|
25
|
+
* roadmap §1. They flow on the same WebRTC channel as the initial
|
|
26
|
+
* `presentation` + renewals, framed with the same NaCl-boxed
|
|
27
|
+
* envelope so the wallet doesn't need a separate transport for live
|
|
28
|
+
* profile / claim updates.
|
|
29
|
+
*
|
|
30
|
+
* Important: any event whose payload includes claim VALUES (today
|
|
31
|
+
* only `claim-update`) MUST carry a `presentation` field, and the
|
|
32
|
+
* SDK MUST re-verify that presentation before firing any listener.
|
|
33
|
+
* Bare claim deltas without a fresh SD-JWT-VC backing them are NOT
|
|
34
|
+
* trusted — see ROADMAP §1.3 and SECURITY.md §7.
|
|
35
|
+
*/
|
|
36
|
+
export type DecryptedEnvelope = {
|
|
37
|
+
v: string;
|
|
38
|
+
msg: "presentation" | "renewal" | "revoke" | "decline" | "claim-update" | "display-update" | "credential-revoked" | "response" | "mouse-update" | "nav" | "value" | "logout"
|
|
39
|
+
/**
|
|
40
|
+
* Browser→wallet pause-state notification. Fired on
|
|
41
|
+
* `window.blur` / `window.focus` so the wallet's mouse
|
|
42
|
+
* controller can show "Remote control paused" while the page
|
|
43
|
+
* is in the background. Body: `paused: boolean`.
|
|
44
|
+
*/
|
|
45
|
+
| "control-status"
|
|
46
|
+
/**
|
|
47
|
+
* Browser→wallet "I'm going away" signal. Fired synchronously
|
|
48
|
+
* from `window.pagehide` (refresh, tab close, navigation)
|
|
49
|
+
* before the transport collapses, so the wallet can close the
|
|
50
|
+
* session immediately instead of waiting for the slower
|
|
51
|
+
* `peer-gone` / WS-close pathway. Body: `reason: string`
|
|
52
|
+
* (free-form short code, currently always `"page_unload"`).
|
|
53
|
+
*/
|
|
54
|
+
| "browser-revoke"
|
|
55
|
+
/**
|
|
56
|
+
* File-transfer wire grammar. Wallet→browser; used when the
|
|
57
|
+
* host's focused element is `<input type="file">` and the user
|
|
58
|
+
* picks something on the phone. The three-stage envelope keeps
|
|
59
|
+
* memory pressure low — neither peer ever materialises the full
|
|
60
|
+
* file in a contiguous buffer:
|
|
61
|
+
*
|
|
62
|
+
* * `file-begin` — metadata: `name`, `mimeType`, `size`,
|
|
63
|
+
* `totalChunks`, `chunkSize`, plus an
|
|
64
|
+
* optional `attestation` SD-JWT-VC for
|
|
65
|
+
* identity-bound files (see notes below
|
|
66
|
+
* on VC MIME standards).
|
|
67
|
+
* * `file-chunk` — one chunk: `index` (0-based) +
|
|
68
|
+
* base64-encoded `data`. The wallet
|
|
69
|
+
* stream-reads the source file, so chunks
|
|
70
|
+
* leave the device one at a time without
|
|
71
|
+
* ever loading the whole thing.
|
|
72
|
+
* * `file-end` — `sha256` over the whole file, hex-encoded.
|
|
73
|
+
* The browser verifies the assembled Blob
|
|
74
|
+
* against this digest before assigning to
|
|
75
|
+
* the focused input.
|
|
76
|
+
*
|
|
77
|
+
* Per-chunk ack via the existing reliability layer gives
|
|
78
|
+
* natural backpressure: the wallet doesn't queue chunk N+1
|
|
79
|
+
* until chunk N is confirmed. Loss of any one chunk retries
|
|
80
|
+
* just that chunk, not the file.
|
|
81
|
+
*
|
|
82
|
+
* VC MIME context (host integrators occasionally ask):
|
|
83
|
+
* * `application/vc+ld+json` — W3C VCDM JSON-LD form
|
|
84
|
+
* * `application/vc+jwt` — W3C VCDM JWT form
|
|
85
|
+
* * `application/vc+sd-jwt` — IETF SD-JWT-VC (what the
|
|
86
|
+
* Prson identity stack issues)
|
|
87
|
+
* * `application/pdf` + PAdES — signed-PDF form
|
|
88
|
+
* * C2PA bundles for media (image / video provenance)
|
|
89
|
+
*
|
|
90
|
+
* There is no widely-deployed standard MIME for "binary file
|
|
91
|
+
* with an attached presentation". The `attestation` field on
|
|
92
|
+
* `file-begin` is our convention for piggy-backing one — the
|
|
93
|
+
* wallet sends the file bytes AND a separate SD-JWT-VC whose
|
|
94
|
+
* disclosed claims include the file's SHA-256. The verifier
|
|
95
|
+
* (host page) re-hashes the received bytes and checks the
|
|
96
|
+
* digest matches the disclosed claim before trusting the
|
|
97
|
+
* provenance metadata.
|
|
98
|
+
*/
|
|
99
|
+
| "file-begin" | "file-chunk" | "file-end"
|
|
100
|
+
/** Transport-layer reliability primitive: the peer's confirmation
|
|
101
|
+
* that the envelope with id [ackOf] was received. The session
|
|
102
|
+
* layer auto-emits these for inbound messages carrying an `id`
|
|
103
|
+
* (other than ping / pong / ack themselves) and resolves
|
|
104
|
+
* pending-ack promises on the sender side. See session.ts. */
|
|
105
|
+
| "ack"
|
|
106
|
+
/** Liveness probe. Sender keeps a fresh `id` per ping and times
|
|
107
|
+
* the matching pong to derive RTT. The receiver echoes as
|
|
108
|
+
* `pong` with `ackOf` set to the ping's `id`. */
|
|
109
|
+
| "ping"
|
|
110
|
+
/** Liveness echo. `ackOf` references the ping's id; `recvTs`
|
|
111
|
+
* is the peer's wall-clock receipt time. Recipient computes
|
|
112
|
+
* RTT = now − sendTs cached against [ackOf]. */
|
|
113
|
+
| "pong";
|
|
114
|
+
issuedAt: number;
|
|
115
|
+
ttlMinutes?: number;
|
|
116
|
+
domain?: string;
|
|
117
|
+
/** Transport-layer envelope id (UUID v4). Present on every wire
|
|
118
|
+
* message that is ack-tracked or dedupe-tracked; absent on
|
|
119
|
+
* mouse-update (high-frequency broadcast where loss is OK) and
|
|
120
|
+
* on the protocol primitives `ack` / `pong` (which carry
|
|
121
|
+
* [ackOf] instead). The receiver dedupes by this id; the sender
|
|
122
|
+
* retransmits until the matching [ack] arrives. */
|
|
123
|
+
id?: string;
|
|
124
|
+
/** Reference to the originating envelope's [id]. Set on `ack`,
|
|
125
|
+
* `pong`, and `response` envelopes. */
|
|
126
|
+
ackOf?: string;
|
|
127
|
+
/** Ping send-time wall-clock (epoch ms). The pong copies this
|
|
128
|
+
* verbatim so the sender doesn't need to maintain a separate
|
|
129
|
+
* ts cache for an RTT calculation. */
|
|
130
|
+
ts?: number;
|
|
131
|
+
/** Pong-only: the responder's wall-clock receipt time (epoch ms).
|
|
132
|
+
* Useful for one-way delay estimates if the host wants finer
|
|
133
|
+
* diagnostics than RTT alone. */
|
|
134
|
+
recvTs?: number;
|
|
135
|
+
/** Present for `presentation`, `renewal`, and `claim-update`. */
|
|
136
|
+
presentation?: string;
|
|
137
|
+
fragments?: unknown[];
|
|
138
|
+
/**
|
|
139
|
+
* Wallet's session-long X25519 public key (base64url, 32 bytes).
|
|
140
|
+
* Present only in the INITIAL `presentation` envelope at sign-in
|
|
141
|
+
* (and on `renewal` if the wallet rotates its session key). The
|
|
142
|
+
* browser SDK extracts + caches this on the session so subsequent
|
|
143
|
+
* outbound `request` envelopes can NaCl-box to it. Without this
|
|
144
|
+
* the browser→wallet direction has no destination key and the
|
|
145
|
+
* request channel can't open.
|
|
146
|
+
*
|
|
147
|
+
* Advisory only: the key the SDK pins is the one the signed
|
|
148
|
+
* presentation binds (KB-JWT `prson_wsk`, or the anonymous
|
|
149
|
+
* credential's `prson_wsk`). This field must agree with it, and a
|
|
150
|
+
* value on any later envelope is ignored — a rotation is accepted
|
|
151
|
+
* only from a verified renewal presentation carrying the new key.
|
|
152
|
+
*/
|
|
153
|
+
walletSessionPk?: string;
|
|
154
|
+
/**
|
|
155
|
+
* User's preferred UI language as a BCP-47 language tag (e.g.
|
|
156
|
+
* `"en"`, `"pt-PT"`, `"fr-CA"`). The wallet sets this from the
|
|
157
|
+
* device's active locale on the initial `presentation` envelope
|
|
158
|
+
* and may rotate it on `renewal` if the device language changes
|
|
159
|
+
* mid-session. The host site can read it via
|
|
160
|
+
* `session.preferredLanguage` to localise its UI without an
|
|
161
|
+
* extra round-trip.
|
|
162
|
+
*
|
|
163
|
+
* Same convention applies to the `displayName` + `avatar` fields
|
|
164
|
+
* below: they originated as the `display-update` envelope body,
|
|
165
|
+
* but the wallet stamps them onto the initial `presentation`
|
|
166
|
+
* envelope too so the host has them on first paint without a
|
|
167
|
+
* separate round-trip.
|
|
168
|
+
*/
|
|
169
|
+
preferredLanguage?: string;
|
|
170
|
+
/** `claim-update` body: per-claim **name-only** delta. The
|
|
171
|
+
* wallet MUST NOT include claim values here — the SDK ignores
|
|
172
|
+
* the delta entirely and recomputes from the re-verified VC
|
|
173
|
+
* for correctness, and emits name-only events to keep raw
|
|
174
|
+
* claim values out of telemetry/log surfaces. The wire field
|
|
175
|
+
* is kept (typed as name-only) so future wallets can hint at
|
|
176
|
+
* what changed without an SDK bump, but the SDK never trusts
|
|
177
|
+
* the hint as authoritative. */
|
|
178
|
+
delta?: {
|
|
179
|
+
added?: string[];
|
|
180
|
+
removed?: string[];
|
|
181
|
+
updated?: string[];
|
|
182
|
+
};
|
|
183
|
+
/** `display-update` body. Either field independently optional;
|
|
184
|
+
* absent means "no change". Pass `null` to clear. No crypto
|
|
185
|
+
* re-verify required — display-only hints for the host UI. */
|
|
186
|
+
displayName?: string | null;
|
|
187
|
+
avatar?: {
|
|
188
|
+
url: string;
|
|
189
|
+
hash: string;
|
|
190
|
+
} | null;
|
|
191
|
+
/** `credential-revoked` body. Closes the session with the
|
|
192
|
+
* matching ExpiryReason. */
|
|
193
|
+
reason?: "alias_transferred" | "user_revoked" | "key_compromised";
|
|
194
|
+
/** `response` body. The wallet's reply to an earlier outbound
|
|
195
|
+
* `request` envelope. Paired by `requestId` (RFC-4122 v4 UUID,
|
|
196
|
+
* echoed verbatim from the request). Either `result` (success
|
|
197
|
+
* payload, kind-dependent shape) or `error` (short string code)
|
|
198
|
+
* is set; both being absent is treated as `error: "unsupported"`. */
|
|
199
|
+
requestId?: string;
|
|
200
|
+
result?: unknown;
|
|
201
|
+
error?: string;
|
|
202
|
+
/**
|
|
203
|
+
* `mouse-update` body. Streamed continuously by the wallet while
|
|
204
|
+
* a `kind: "mouse"` drawer is open, paired by `requestId` to the
|
|
205
|
+
* originating request. The browser SDK's `bindMouse` helper
|
|
206
|
+
* consumes these and applies them to a CSS-positioned virtual
|
|
207
|
+
* cursor on the page.
|
|
208
|
+
*
|
|
209
|
+
* Coordinates are deltas — pixels relative to the previous
|
|
210
|
+
* position — rather than absolute, so phone resolution and page
|
|
211
|
+
* resolution don't need to match. `event` distinguishes
|
|
212
|
+
* pointer-motion frames (`move`) from discrete actions
|
|
213
|
+
* (`click` / `double-click` / `scroll`); `scroll.dy` is positive
|
|
214
|
+
* for downward scroll, matching `WheelEvent.deltaY`.
|
|
215
|
+
*/
|
|
216
|
+
mouse?: {
|
|
217
|
+
/**
|
|
218
|
+
* Pointer-stream events.
|
|
219
|
+
*
|
|
220
|
+
* * `move` / `click` / `double-click` / `scroll` — pointer
|
|
221
|
+
* events that move the on-page cursor or fire synthetic
|
|
222
|
+
* mouse events.
|
|
223
|
+
* * `begin` / `end` — wallet-side stream lifecycle markers
|
|
224
|
+
* for the pre-grant flow (`SignInOptions.mouseControl`).
|
|
225
|
+
* Subscribers ignore them as no-op pointer events.
|
|
226
|
+
* * `hide` / `show` — visibility toggles. The wallet emits
|
|
227
|
+
* `hide` when the user lifts the phone into a non-pointing
|
|
228
|
+
* pose (gravity-based pose detector) and re-emits `show`
|
|
229
|
+
* when wand pose returns. The browser pulls the cursor
|
|
230
|
+
* off the page on `hide` AND surfaces a "point your phone
|
|
231
|
+
* at the screen" hint with a soft blue glow on the
|
|
232
|
+
* viewport edge.
|
|
233
|
+
*/
|
|
234
|
+
event: "move" | "click" | "double-click" | "scroll" | "begin" | "end" | "show" | "hide";
|
|
235
|
+
dx?: number;
|
|
236
|
+
dy?: number;
|
|
237
|
+
/** Active mode at the time of the event (the wallet drawer can
|
|
238
|
+
* toggle mid-session). */
|
|
239
|
+
mode?: "touch" | "magic";
|
|
240
|
+
};
|
|
241
|
+
/**
|
|
242
|
+
* `control-status` body. Browser-emitted; the wallet listens via
|
|
243
|
+
* `LoginSession.inbound` and dims its controller surface while
|
|
244
|
+
* `paused: true`. Fired on `window.blur` / `window.focus` so the
|
|
245
|
+
* user can see, on the phone, that the page is no longer
|
|
246
|
+
* accepting their cursor input.
|
|
247
|
+
*/
|
|
248
|
+
paused?: boolean;
|
|
249
|
+
/**
|
|
250
|
+
* `file-begin` body. Sent ONCE per file transfer right before the
|
|
251
|
+
* `file-chunk` stream starts. `chunkSize` is the wallet's raw
|
|
252
|
+
* (pre-base64) bytes-per-chunk so the browser can preallocate
|
|
253
|
+
* timing buffers; `totalChunks` lets it render a progress bar
|
|
254
|
+
* without listening for `file-end`. `attestation` is reserved
|
|
255
|
+
* for the future SD-JWT-VC piggy-back contract — host code
|
|
256
|
+
* should treat the field as opaque until the verifier-side
|
|
257
|
+
* verification path lands.
|
|
258
|
+
*/
|
|
259
|
+
fileBegin?: {
|
|
260
|
+
name: string;
|
|
261
|
+
mimeType: string;
|
|
262
|
+
size: number;
|
|
263
|
+
totalChunks: number;
|
|
264
|
+
chunkSize: number;
|
|
265
|
+
/** Optional SD-JWT-VC bound to the file's SHA-256 — see the
|
|
266
|
+
* `file-begin` msg comment. */
|
|
267
|
+
attestation?: string;
|
|
268
|
+
};
|
|
269
|
+
/**
|
|
270
|
+
* `file-chunk` body. `data` is the chunk's raw bytes base64-
|
|
271
|
+
* encoded (URL-safe, padded — same convention the rest of the
|
|
272
|
+
* wire grammar uses). `index` is the zero-based ordinal.
|
|
273
|
+
*/
|
|
274
|
+
fileChunk?: {
|
|
275
|
+
index: number;
|
|
276
|
+
data: string;
|
|
277
|
+
};
|
|
278
|
+
/**
|
|
279
|
+
* `file-end` body. `sha256` is hex-encoded (64 lowercase chars).
|
|
280
|
+
* The browser verifies the assembled Blob against this digest
|
|
281
|
+
* before assigning to the focused `<input type="file">`.
|
|
282
|
+
*/
|
|
283
|
+
fileEnd?: {
|
|
284
|
+
sha256: string;
|
|
285
|
+
};
|
|
286
|
+
/**
|
|
287
|
+
* `nav` body — wallet's remote-navigation command. Sent when the
|
|
288
|
+
* user taps Prev / Next / Submit on the persistent banner drawer.
|
|
289
|
+
*
|
|
290
|
+
* * `"prev"` / `"next"` — move DOM focus to the previous /
|
|
291
|
+
* next tabbable input on the page. Semantically equivalent
|
|
292
|
+
* to Shift+Tab / Tab. SDK fires the matching `focus` event
|
|
293
|
+
* on the new element so reactive UIs pick up the move.
|
|
294
|
+
* * `"submit"` — fire `requestSubmit()` on the closest enclosing
|
|
295
|
+
* `<form>` of the currently focused element. Semantically
|
|
296
|
+
* equivalent to Enter.
|
|
297
|
+
*
|
|
298
|
+
* Only meaningful when the verifier opted in to
|
|
299
|
+
* `remoteNavigation: true` at sign-in time AND the SDK side called
|
|
300
|
+
* `enableRemoteNavigation(session)`.
|
|
301
|
+
*/
|
|
302
|
+
action?: "prev" | "next" | "submit";
|
|
303
|
+
/**
|
|
304
|
+
* `value` body — wallet's edit of the currently-focused input. The
|
|
305
|
+
* SDK applies it via `el.value = ...` + an `input` / `change`
|
|
306
|
+
* event pair. The wallet streams these on every keystroke so the
|
|
307
|
+
* page updates live.
|
|
308
|
+
*
|
|
309
|
+
* Empty string is a valid "clear the field" message and is
|
|
310
|
+
* propagated as-is. A `null` `value` means "no change" — the SDK
|
|
311
|
+
* ignores it; used by the wallet to ack a focus push without
|
|
312
|
+
* actually editing.
|
|
313
|
+
*/
|
|
314
|
+
value?: string | null;
|
|
315
|
+
};
|
|
316
|
+
/**
|
|
317
|
+
* Open a wallet envelope. With [expectedSenderPkB64u] (the pinned
|
|
318
|
+
* `walletSessionPk`), only an envelope whose `ephPk` is that key AND
|
|
319
|
+
* whose box opens with it is accepted: anything else (another key, a
|
|
320
|
+
* forged `ephPk`) throws. Without it, any sender is accepted — used for
|
|
321
|
+
* the first envelope, whose sender is checked against the verified
|
|
322
|
+
* presentation afterwards (index.ts), and for old wallets.
|
|
323
|
+
*/
|
|
324
|
+
export declare function decryptEnvelope(raw: string, keys: EphemeralKeys, expectedSenderPkB64u?: string): Promise<DecryptedEnvelope>;
|
|
325
|
+
/** [decryptEnvelope], also returning the sender key the box opened with. */
|
|
326
|
+
export declare function openEnvelope(raw: string, keys: EphemeralKeys, expectedSenderPkB64u?: string): Promise<{
|
|
327
|
+
envelope: DecryptedEnvelope;
|
|
328
|
+
senderPk: string;
|
|
329
|
+
}>;
|
|
330
|
+
/**
|
|
331
|
+
* Box a JSON-serialisable [plaintext] to the wallet's session X25519
|
|
332
|
+
* public key. Mirror of the wallet's `LoginEnvelope.encryptToBrowser`
|
|
333
|
+
* primitive (NaCl `box`, XSalsa20-Poly1305, random 24-byte nonce) —
|
|
334
|
+
* the wallet decrypts with its stored session secret. Returns the same
|
|
335
|
+
* JSON-encoded envelope shape the browser already RECEIVES from the
|
|
336
|
+
* wallet:
|
|
337
|
+
*
|
|
338
|
+
* { ephPk: <base64url>, nonce24: <base64url>, ct: <base64url> }
|
|
339
|
+
*
|
|
340
|
+
* Envelope v2: with [sender] (this sign-in's browser keys — the
|
|
341
|
+
* `browserPk` the QR carried), the box is made BY that key, so `ephPk`
|
|
342
|
+
* is the browser's session key and the wallet can check the envelope
|
|
343
|
+
* came from the browser that showed the code. Without [sender] (legacy),
|
|
344
|
+
* a fresh per-message keypair is used.
|
|
345
|
+
*
|
|
346
|
+
* Both session keys are themselves fresh for each sign-in and live only
|
|
347
|
+
* in memory, so a leaked key exposes that one session, never another.
|
|
348
|
+
*
|
|
349
|
+
* [walletSessionPkB64u] is the wallet's session key, pinned from the
|
|
350
|
+
* verified sign-in presentation (KB-JWT `prson_wsk`).
|
|
351
|
+
*/
|
|
352
|
+
export declare function boxToWallet(walletSessionPkB64u: string, plaintext: string, sender?: Pick<EphemeralKeys, "secretKey" | "publicKey">): string;
|
package/dist/crypto.js
ADDED
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Browser-side crypto for the login SDK:
|
|
3
|
+
*
|
|
4
|
+
* • generateEphemeralKeypair — X25519 keypair for the duration of
|
|
5
|
+
* one sign-in. Held in memory; discarded on session.close() or page
|
|
6
|
+
* unload. The public key is the value the wallet boxes its envelope
|
|
7
|
+
* to.
|
|
8
|
+
*
|
|
9
|
+
* • decryptEnvelope — open the wallet's NaCl `box` ciphertext
|
|
10
|
+
* and parse the resulting JSON. Once the wallet's session key is
|
|
11
|
+
* pinned (see session.ts), only envelopes boxed BY that key open.
|
|
12
|
+
*
|
|
13
|
+
* • boxToWallet — box a JSON envelope to the wallet's
|
|
14
|
+
* session key, sent by this browser's session key.
|
|
15
|
+
*
|
|
16
|
+
* Envelope v2 (both directions): NaCl `box` between the two session
|
|
17
|
+
* keys — the browser's per-sign-in X25519 key (`browserPk`, in the QR)
|
|
18
|
+
* and the wallet's per-session X25519 key (`walletSessionPk`, bound
|
|
19
|
+
* into the signed presentation as the KB-JWT `prson_wsk` claim). The
|
|
20
|
+
* wire field `ephPk` keeps its name for compatibility but now carries
|
|
21
|
+
* the SENDER's session key, so the recipient can check who sent it:
|
|
22
|
+
* a box only opens with the matching sender key, which makes it mutual
|
|
23
|
+
* authentication, not just confidentiality.
|
|
24
|
+
*
|
|
25
|
+
* Uses `@stablelib/nacl` for the box / open primitives — a reviewed
|
|
26
|
+
* pure-JS implementation that runs in every browser without WebCrypto
|
|
27
|
+
* dependency gaps (Web Crypto doesn't ship X25519 in all engines).
|
|
28
|
+
*/
|
|
29
|
+
import { box, openBox } from "@stablelib/nacl";
|
|
30
|
+
import { generateKeyPair } from "@stablelib/x25519";
|
|
31
|
+
import { randomBytes } from "@stablelib/random";
|
|
32
|
+
import { decodeURLSafe as b64uDecode, encodeURLSafe as b64uEncode } from "@stablelib/base64";
|
|
33
|
+
export async function generateEphemeralKeypair() {
|
|
34
|
+
// @stablelib's generateKeyPair pulls entropy from a CSPRNG (window.crypto
|
|
35
|
+
// via @stablelib/random). For environments without crypto.getRandomValues
|
|
36
|
+
// (none we support), this would throw — that's correct behaviour.
|
|
37
|
+
void randomBytes(1); // touch the entropy source so a misconfigured browser fails fast
|
|
38
|
+
const kp = generateKeyPair();
|
|
39
|
+
return {
|
|
40
|
+
secretKey: kp.secretKey,
|
|
41
|
+
publicKey: kp.publicKey,
|
|
42
|
+
publicKeyB64u: stripPad(b64uEncode(kp.publicKey)),
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* Open a wallet envelope. With [expectedSenderPkB64u] (the pinned
|
|
47
|
+
* `walletSessionPk`), only an envelope whose `ephPk` is that key AND
|
|
48
|
+
* whose box opens with it is accepted: anything else (another key, a
|
|
49
|
+
* forged `ephPk`) throws. Without it, any sender is accepted — used for
|
|
50
|
+
* the first envelope, whose sender is checked against the verified
|
|
51
|
+
* presentation afterwards (index.ts), and for old wallets.
|
|
52
|
+
*/
|
|
53
|
+
export async function decryptEnvelope(raw, keys, expectedSenderPkB64u) {
|
|
54
|
+
return (await openEnvelope(raw, keys, expectedSenderPkB64u)).envelope;
|
|
55
|
+
}
|
|
56
|
+
/** [decryptEnvelope], also returning the sender key the box opened with. */
|
|
57
|
+
export async function openEnvelope(raw, keys, expectedSenderPkB64u) {
|
|
58
|
+
let parsed;
|
|
59
|
+
try {
|
|
60
|
+
parsed = JSON.parse(raw);
|
|
61
|
+
}
|
|
62
|
+
catch {
|
|
63
|
+
throw new Error("decryptEnvelope: not a JSON envelope");
|
|
64
|
+
}
|
|
65
|
+
if (typeof parsed.ephPk !== "string" || typeof parsed.nonce24 !== "string" || typeof parsed.ct !== "string") {
|
|
66
|
+
throw new Error("decryptEnvelope: missing required fields {ephPk, nonce24, ct}");
|
|
67
|
+
}
|
|
68
|
+
const ephPk = b64uDecode(addPad(parsed.ephPk));
|
|
69
|
+
const nonce = b64uDecode(addPad(parsed.nonce24));
|
|
70
|
+
const ct = b64uDecode(addPad(parsed.ct));
|
|
71
|
+
if (ephPk.length !== 32)
|
|
72
|
+
throw new Error("decryptEnvelope: bad ephPk length");
|
|
73
|
+
if (nonce.length !== 24)
|
|
74
|
+
throw new Error("decryptEnvelope: bad nonce length");
|
|
75
|
+
let senderPk = ephPk;
|
|
76
|
+
if (expectedSenderPkB64u !== undefined) {
|
|
77
|
+
const expected = b64uDecode(addPad(expectedSenderPkB64u));
|
|
78
|
+
if (expected.length !== 32 || !bytesEqual(expected, ephPk)) {
|
|
79
|
+
throw new Error("decryptEnvelope: not sent by the pinned wallet key");
|
|
80
|
+
}
|
|
81
|
+
senderPk = expected;
|
|
82
|
+
}
|
|
83
|
+
// NaCl `openBox` returns null on bad ciphertext / wrong key — never
|
|
84
|
+
// throws. We must check + raise ourselves. A box only opens with the
|
|
85
|
+
// sender key it was made with, so a pinned sender is authenticated.
|
|
86
|
+
const pt = openBox(senderPk, keys.secretKey, nonce, ct);
|
|
87
|
+
if (!pt)
|
|
88
|
+
throw new Error("decryptEnvelope: authentication failed (wrong key or tampered ciphertext)");
|
|
89
|
+
let envelope;
|
|
90
|
+
try {
|
|
91
|
+
envelope = JSON.parse(new TextDecoder().decode(pt));
|
|
92
|
+
}
|
|
93
|
+
catch {
|
|
94
|
+
throw new Error("decryptEnvelope: decrypted but not JSON");
|
|
95
|
+
}
|
|
96
|
+
return { envelope, senderPk: stripPad(b64uEncode(senderPk)) };
|
|
97
|
+
}
|
|
98
|
+
function bytesEqual(a, b) {
|
|
99
|
+
if (a.length !== b.length)
|
|
100
|
+
return false;
|
|
101
|
+
let diff = 0;
|
|
102
|
+
for (let i = 0; i < a.length; i++)
|
|
103
|
+
diff |= a[i] ^ b[i];
|
|
104
|
+
return diff === 0;
|
|
105
|
+
}
|
|
106
|
+
function stripPad(s) {
|
|
107
|
+
return s.replace(/=+$/, "");
|
|
108
|
+
}
|
|
109
|
+
function addPad(s) {
|
|
110
|
+
const mod = s.length % 4;
|
|
111
|
+
return mod === 0 ? s : s + "=".repeat(4 - mod);
|
|
112
|
+
}
|
|
113
|
+
/**
|
|
114
|
+
* Box a JSON-serialisable [plaintext] to the wallet's session X25519
|
|
115
|
+
* public key. Mirror of the wallet's `LoginEnvelope.encryptToBrowser`
|
|
116
|
+
* primitive (NaCl `box`, XSalsa20-Poly1305, random 24-byte nonce) —
|
|
117
|
+
* the wallet decrypts with its stored session secret. Returns the same
|
|
118
|
+
* JSON-encoded envelope shape the browser already RECEIVES from the
|
|
119
|
+
* wallet:
|
|
120
|
+
*
|
|
121
|
+
* { ephPk: <base64url>, nonce24: <base64url>, ct: <base64url> }
|
|
122
|
+
*
|
|
123
|
+
* Envelope v2: with [sender] (this sign-in's browser keys — the
|
|
124
|
+
* `browserPk` the QR carried), the box is made BY that key, so `ephPk`
|
|
125
|
+
* is the browser's session key and the wallet can check the envelope
|
|
126
|
+
* came from the browser that showed the code. Without [sender] (legacy),
|
|
127
|
+
* a fresh per-message keypair is used.
|
|
128
|
+
*
|
|
129
|
+
* Both session keys are themselves fresh for each sign-in and live only
|
|
130
|
+
* in memory, so a leaked key exposes that one session, never another.
|
|
131
|
+
*
|
|
132
|
+
* [walletSessionPkB64u] is the wallet's session key, pinned from the
|
|
133
|
+
* verified sign-in presentation (KB-JWT `prson_wsk`).
|
|
134
|
+
*/
|
|
135
|
+
export function boxToWallet(walletSessionPkB64u, plaintext, sender) {
|
|
136
|
+
const recipientPk = b64uDecode(addPad(walletSessionPkB64u));
|
|
137
|
+
if (recipientPk.length !== 32) {
|
|
138
|
+
throw new Error("boxToWallet: bad walletSessionPk length");
|
|
139
|
+
}
|
|
140
|
+
const ephemeral = sender ?? generateKeyPair();
|
|
141
|
+
const nonce = randomBytes(24);
|
|
142
|
+
const pt = new TextEncoder().encode(plaintext);
|
|
143
|
+
// `@stablelib/nacl` box signature is
|
|
144
|
+
// box(theirPublicKey, mySecretKey, nonce, data)
|
|
145
|
+
// — RECIPIENT pk first, SENDER sk second. Mirror of `openBox` (which
|
|
146
|
+
// we already call correctly in `decryptEnvelope`). An earlier draft
|
|
147
|
+
// had these swapped, producing a junk shared key that PineNaCl's
|
|
148
|
+
// `Box.decrypt` could never match — every browser→wallet envelope
|
|
149
|
+
// failed Poly1305 authentication on the wallet side. Keep the
|
|
150
|
+
// argument names explicit at the call site so the bug can't recur.
|
|
151
|
+
const ct = box(
|
|
152
|
+
/* theirPublicKey */ recipientPk,
|
|
153
|
+
/* mySecretKey */ ephemeral.secretKey, nonce, pt);
|
|
154
|
+
return JSON.stringify({
|
|
155
|
+
ephPk: stripPad(b64uEncode(ephemeral.publicKey)),
|
|
156
|
+
nonce24: stripPad(b64uEncode(nonce)),
|
|
157
|
+
ct: stripPad(b64uEncode(ct)),
|
|
158
|
+
});
|
|
159
|
+
}
|