@terminal3/seal-web 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 +21 -0
- package/README.md +111 -2
- package/dist/codec.d.ts +19 -0
- package/dist/codec.js +65 -0
- package/dist/config.d.ts +75 -0
- package/dist/config.js +147 -0
- package/dist/delivery.d.ts +63 -0
- package/dist/delivery.js +135 -0
- package/dist/elements.d.ts +2 -0
- package/dist/elements.js +353 -0
- package/dist/errors.d.ts +13 -0
- package/dist/errors.js +16 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.js +12 -0
- package/dist/jwe.d.ts +69 -0
- package/dist/jwe.js +213 -0
- package/dist/passkey.d.ts +38 -0
- package/dist/passkey.js +142 -0
- package/dist/session.d.ts +26 -0
- package/dist/session.js +90 -0
- package/package.json +41 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2024 T3n Team
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,112 @@
|
|
|
1
|
-
#
|
|
1
|
+
# T3n sealed delivery for the browser
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
`@terminal3/seal-web` is the customer's side of sealed delivery: data her assistant carries but cannot read, in both directions.
|
|
4
|
+
|
|
5
|
+
- **Out, a sealed item.** T3N encrypts something sensitive (card details, a transfer to confirm) to a key that exists only in her browser. The assistant holds a reference (`sealed:…`); this package fetches the ciphertext through your app and opens it on her device.
|
|
6
|
+
- **In, a sealed request.** T3N signs a form (what it asks, who may read the answers, where they may go) and makes a form key inside its enclave. This package verifies the signature against your pinned signing key, draws the form, and encrypts her answers to the form key. The assistant only ever learns the status.
|
|
7
|
+
|
|
8
|
+
The package has no runtime dependencies. It needs WebCrypto, IndexedDB, custom elements and WebAuthn, so it runs in current browsers on a secure origin.
|
|
9
|
+
|
|
10
|
+
## Installation
|
|
11
|
+
|
|
12
|
+
```bash
|
|
13
|
+
pnpm add @terminal3/seal-web
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
## Usage
|
|
17
|
+
|
|
18
|
+
```ts
|
|
19
|
+
import * as Seal from "@terminal3/seal-web";
|
|
20
|
+
|
|
21
|
+
Seal.configure({
|
|
22
|
+
rpName: "Example Bank",
|
|
23
|
+
api: {
|
|
24
|
+
// Adds her app session; keep `init.headers`, which carries the JSON content type.
|
|
25
|
+
fetch: (url, init) => fetch(url, { ...init, headers: { ...init.headers, authorization: `Bearer ${token}` } }),
|
|
26
|
+
passkey: "/api/passkey",
|
|
27
|
+
nonce: "/api/seal/nonce",
|
|
28
|
+
bind: "/api/seal/bind",
|
|
29
|
+
item: "/api/seal/items/{ref}",
|
|
30
|
+
confirm: "/api/seal/items/{ref}/confirm",
|
|
31
|
+
describe: "/api/seal/requests/{ref}",
|
|
32
|
+
submit: "/api/seal/requests/{ref}",
|
|
33
|
+
signingKey: "/api/seal/signing-key",
|
|
34
|
+
},
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
await Seal.registerPasskey({ id: customerId, name: customerName }); // once, at sign-in
|
|
38
|
+
await Seal.startSession({ sid, nonce }); // after she allows the assistant
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
```html
|
|
42
|
+
<t3-safebox ref="sealed:…" label="Your card"></t3-safebox>
|
|
43
|
+
<t3-safebox-form ref="request:…"></t3-safebox-form>
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
Importing the package defines both elements. Call `Seal.reset()` at sign-out and when she revokes the assistant.
|
|
47
|
+
|
|
48
|
+
## `configure`
|
|
49
|
+
|
|
50
|
+
`configure({ api, rpName, rpId?, shadow? })` throws a `SealError` with code `invalid_config`, and keeps the previous configuration, if `api` or `rpName` is missing, or any part is mistyped or unknown.
|
|
51
|
+
|
|
52
|
+
| Option | |
|
|
53
|
+
| --- | --- |
|
|
54
|
+
| `api` | One endpoint per call, below. |
|
|
55
|
+
| `rpName` | Your name, shown in the passkey prompt and on both elements. |
|
|
56
|
+
| `rpId` | The passkey relying party ID; the page's host name by default. |
|
|
57
|
+
| `shadow` | `"closed"` (default) hides the elements' shadow roots from `element.shadowRoot` and the page's selectors; `"open"` lets a test drive them. Neither mode is a boundary against a script running on the page, which can instrument the page before this package runs. |
|
|
58
|
+
|
|
59
|
+
Each endpoint is a URL or path. The four that act on one item or request carry `{ref}`, which is replaced by the URL-encoded reference without its `sealed:` or `request:` prefix. POST bodies are JSON. An error answer should be a JSON object with `error` (a code) and optionally `message`.
|
|
60
|
+
|
|
61
|
+
| Entry | Method | Takes | Answers |
|
|
62
|
+
| --- | --- | --- | --- |
|
|
63
|
+
| `fetch` | | `(url, init)` | A `Response`. Optional; `fetch` by default. |
|
|
64
|
+
| `passkey` | GET | | `{ credential_id }` of her registered passkey, read before each passkey prompt; `credential_id` is `null` when she has none |
|
|
65
|
+
| `passkey` | POST | `{ nonce, registration }`, below | |
|
|
66
|
+
| `nonce` | POST | `{ purpose: "register" }` | `{ nonce }`, single-use, for her signed-in session |
|
|
67
|
+
| `nonce` | POST | `{ purpose: "bind" }` or `{ purpose: "get" }` | `{ nonce, sid }`, single-use for that purpose |
|
|
68
|
+
| `bind` | POST | `{ seal_jwk, nonce, assertion }` | |
|
|
69
|
+
| `item` | POST | `{}`, or `{ nonce, assertion }` after a fresh unlock | `{ jwe, label? }`; error `fresh_unlock_required` asks for an unlock |
|
|
70
|
+
| `confirm` | POST | `{}` | |
|
|
71
|
+
| `describe` | GET | | `{ description }`, the form's compact JWS; error `already_submitted` once answered |
|
|
72
|
+
| `submit` | POST | `{ jwe }` | `{ status, fields_present? }` |
|
|
73
|
+
| `signingKey` | GET | | `{ jwk }`, the public key forms are signed with |
|
|
74
|
+
| `sources` | GET | | Optional map of further item endpoints answering `{ jwe, label? }`, chosen by `<t3-safebox source="name">` |
|
|
75
|
+
|
|
76
|
+
Your app server verifies what the browser sends and relays each call to T3N; the browser never talks to T3N directly.
|
|
77
|
+
|
|
78
|
+
## Keys and passkeys
|
|
79
|
+
|
|
80
|
+
- **Session key.** `startSession` makes a P-256 ECDH key pair with WebCrypto as non-extractable, so the private key never exists outside the browser's key store. It lives in IndexedDB for the session (10 minutes idle, 30 minutes at most).
|
|
81
|
+
- **Registration.** `registerPasskey` runs a WebAuthn registration ceremony over a `register` nonce, with user verification required. Its challenge is SHA-256 of the JCS of `{ t: "t3n-seal/register", nonce }`. It excludes her registered credential, so a device that holds it makes no second one. It posts `{ nonce, registration }`, where `registration` is `{ credential_id, clientDataJSON, attestationObject, authenticatorData?, publicKey?, publicKeyAlgorithm?, transports }`: the binary members base64url, `publicKey` the SPKI and `publicKeyAlgorithm` its COSE algorithm where the browser reports them. Your IdP consumes the nonce, then checks that `clientDataJSON` has `type` `webauthn.create`, that challenge and your origin, and that the authenticator data has your RP ID hash and the user-present and user-verified flags. It stores the credential ID and public key from the attestation's authenticator data; `publicKey` must match them. Attestation is `none`, so the ceremony proves freshness and the origin, not the authenticator: accept a registration only within a fresh sign-in.
|
|
82
|
+
- **Binding.** Her passkey binds the session key's public half to her consent: an assertion over SHA-256 of the JCS (RFC 8785) of `{ t: "t3n-seal/bind", kid, sid, nonce }`. Your IdP verifies it against the registered passkey and only then puts `seal_jwk` in the assistant's delegation token.
|
|
83
|
+
- **Fresh unlock.** An item that asks for one (a card number) opens only after another assertion, over `{ t: "t3n-seal/get", ref, sid, nonce }`.
|
|
84
|
+
|
|
85
|
+
## Formats
|
|
86
|
+
|
|
87
|
+
- Compact JWE (RFC 7516), `alg` `ECDH-ES`, `enc` `A256GCM`, over P-256: one-round Concat KDF with empty `apu`/`apv`, the base64url protected header as the AES-GCM additional data, and the recipient key's RFC 7638 thumbprint as `kid`. Headers carry `ref`, `purpose` and optionally `exp` (Unix seconds).
|
|
88
|
+
- A form's description is a compact JWS, ES256, `typ` `t3n-seal-form+jws`, verified over the exact bytes received against the key your `signingKey` endpoint answers. That key's `kid` is `<tid>.<generation>`, and the description's header must name the same `kid`. Submitted answers carry the description's SHA-256 as `fp`.
|
|
89
|
+
- Every public key received is checked to be on P-256. A `kid` named by any key but the signing key must be its own thumbprint.
|
|
90
|
+
|
|
91
|
+
## Functions
|
|
92
|
+
|
|
93
|
+
| Function | |
|
|
94
|
+
| --- | --- |
|
|
95
|
+
| `registerPasskey({ id, name })` | Registers her passkey on this device, unless it already holds her registered credential; answers the credential ID. |
|
|
96
|
+
| `startSession({ sid, nonce })` | Makes and binds a session key; answers its public JWK. |
|
|
97
|
+
| `ensureSession()` | Binds a session key with a fresh nonce if hers is gone. |
|
|
98
|
+
| `hasSession(sid?)`, `reset()` | Whether a live session key is bound; delete it. |
|
|
99
|
+
| `openItem(ref, source?)` | Fetches and opens a sealed item: `{ content, meta }`. |
|
|
100
|
+
| `open(jwe, ref?)` | Opens a JWE with the session key. |
|
|
101
|
+
| `confirmItem(ref)` | Confirms a sealed item. |
|
|
102
|
+
| `describe(ref)`, `submit(ref, description, answers)` | Verifies a form's description; seals and submits her answers. |
|
|
103
|
+
| `thumbprint(jwk)` | RFC 7638 thumbprint of a P-256 public JWK. |
|
|
104
|
+
|
|
105
|
+
Every refusal is a `SealError` with a stable `code` and a `message` fit to show her. The format refusals are `invalid_key`, `jwe_malformed`, `header_mismatch`, `jwe_not_authentic` and `expired`; others include `no_session`, `wrong_reference`, `not_signed` and `not_configured`. A passkey prompt that is refused or fails gives `passkey_cancelled` (she dismissed it, or it timed out), `passkey_unsupported`, `passkey_not_allowed` or `passkey_failed`.
|
|
106
|
+
|
|
107
|
+
## Elements
|
|
108
|
+
|
|
109
|
+
- `<t3-safebox ref="sealed:…" label="…">` shows a sealed item once she opens it, for a minute. `auto-open` opens it on connection; `source="name"` fetches it from `api.sources.name`. An item with a `confirm` button fires `seal-confirmed` after the `confirm` endpoint answers, or `seal-confirm` (with `run_id`) for a confirmation your app runs itself.
|
|
110
|
+
- `<t3-safebox-form ref="request:…">` draws a sealed request from its verified description, and fires `seal-submitted` once the answers are sent.
|
|
111
|
+
- Both may be in the page before `configure` runs: they wait in `data-state="waiting"` and start once it has. Both render again on each later `configure`; their shadow root keeps the mode it was attached with.
|
|
112
|
+
- Both reflect their state in `data-state`, and take their accent colour from the CSS custom properties `--seal-accent` and `--seal-accent-soft`.
|
package/dist/codec.d.ts
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/** Bytes over a plain `ArrayBuffer`, as WebCrypto takes them. */
|
|
2
|
+
export type Bytes = Uint8Array<ArrayBuffer>;
|
|
3
|
+
export declare function utf8(s: string): Bytes;
|
|
4
|
+
/** Strict UTF-8 decoding: malformed input throws. */
|
|
5
|
+
export declare function fromUtf8(bytes: Uint8Array): string;
|
|
6
|
+
/** RFC 4648 §5 base64url without padding; `null` for anything else. */
|
|
7
|
+
export declare function fromB64u(s: string): Bytes | null;
|
|
8
|
+
export declare function toB64u(bytes: Uint8Array): string;
|
|
9
|
+
export declare function toB64(bytes: Uint8Array): string;
|
|
10
|
+
export declare function concatBytes(...parts: Uint8Array[]): Bytes;
|
|
11
|
+
export declare function u32be(n: number): Bytes;
|
|
12
|
+
export declare function sha256(bytes: Bytes): Promise<Bytes>;
|
|
13
|
+
export declare function isRecord(v: unknown): v is Record<string, unknown>;
|
|
14
|
+
/**
|
|
15
|
+
* JSON with every object's members in sorted order and no whitespace: RFC 8785
|
|
16
|
+
* for the strings, integers and nested objects these formats carry. Members
|
|
17
|
+
* whose value is `undefined` are left out.
|
|
18
|
+
*/
|
|
19
|
+
export declare function canonicalJson(value: unknown): string;
|
package/dist/codec.js
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
export function utf8(s) {
|
|
2
|
+
return new Uint8Array(new TextEncoder().encode(s));
|
|
3
|
+
}
|
|
4
|
+
/** Strict UTF-8 decoding: malformed input throws. */
|
|
5
|
+
export function fromUtf8(bytes) {
|
|
6
|
+
return new TextDecoder("utf-8", { fatal: true }).decode(bytes);
|
|
7
|
+
}
|
|
8
|
+
/** RFC 4648 §5 base64url without padding; `null` for anything else. */
|
|
9
|
+
export function fromB64u(s) {
|
|
10
|
+
if (!/^[A-Za-z0-9_-]*$/.test(s) || s.length % 4 === 1)
|
|
11
|
+
return null;
|
|
12
|
+
const bin = atob(s.replace(/-/g, "+").replace(/_/g, "/") + "===".slice((s.length + 3) % 4));
|
|
13
|
+
const out = new Uint8Array(bin.length);
|
|
14
|
+
for (let i = 0; i < bin.length; i++)
|
|
15
|
+
out[i] = bin.charCodeAt(i);
|
|
16
|
+
return out;
|
|
17
|
+
}
|
|
18
|
+
function binary(bytes) {
|
|
19
|
+
let bin = "";
|
|
20
|
+
for (let i = 0; i < bytes.length; i += 0x8000)
|
|
21
|
+
bin += String.fromCharCode(...bytes.subarray(i, i + 0x8000));
|
|
22
|
+
return bin;
|
|
23
|
+
}
|
|
24
|
+
export function toB64u(bytes) {
|
|
25
|
+
return btoa(binary(bytes)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
26
|
+
}
|
|
27
|
+
export function toB64(bytes) {
|
|
28
|
+
return btoa(binary(bytes));
|
|
29
|
+
}
|
|
30
|
+
export function concatBytes(...parts) {
|
|
31
|
+
const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));
|
|
32
|
+
let o = 0;
|
|
33
|
+
for (const p of parts) {
|
|
34
|
+
out.set(p, o);
|
|
35
|
+
o += p.length;
|
|
36
|
+
}
|
|
37
|
+
return out;
|
|
38
|
+
}
|
|
39
|
+
export function u32be(n) {
|
|
40
|
+
return new Uint8Array([(n >>> 24) & 255, (n >>> 16) & 255, (n >>> 8) & 255, n & 255]);
|
|
41
|
+
}
|
|
42
|
+
export async function sha256(bytes) {
|
|
43
|
+
return new Uint8Array(await crypto.subtle.digest("SHA-256", bytes));
|
|
44
|
+
}
|
|
45
|
+
export function isRecord(v) {
|
|
46
|
+
return typeof v === "object" && v !== null && !Array.isArray(v);
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* JSON with every object's members in sorted order and no whitespace: RFC 8785
|
|
50
|
+
* for the strings, integers and nested objects these formats carry. Members
|
|
51
|
+
* whose value is `undefined` are left out.
|
|
52
|
+
*/
|
|
53
|
+
export function canonicalJson(value) {
|
|
54
|
+
if (Array.isArray(value))
|
|
55
|
+
return `[${value.map(canonicalJson).join(",")}]`;
|
|
56
|
+
if (isRecord(value)) {
|
|
57
|
+
const obj = value;
|
|
58
|
+
const members = Object.keys(obj)
|
|
59
|
+
.filter((k) => obj[k] !== undefined)
|
|
60
|
+
.sort()
|
|
61
|
+
.map((k) => `${JSON.stringify(k)}:${canonicalJson(obj[k])}`);
|
|
62
|
+
return `{${members.join(",")}}`;
|
|
63
|
+
}
|
|
64
|
+
return JSON.stringify(value);
|
|
65
|
+
}
|
package/dist/config.d.ts
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
export type ShadowMode = "open" | "closed";
|
|
2
|
+
/**
|
|
3
|
+
* The integrator's endpoints, one per call. Each is a URL or path; the four
|
|
4
|
+
* that act on one item or request carry a `{ref}` placeholder, which is
|
|
5
|
+
* replaced by the URL-encoded reference.
|
|
6
|
+
*/
|
|
7
|
+
export interface SealApi {
|
|
8
|
+
/** Sends a request with the customer's app session. Defaults to `fetch`; keep `init.headers`. */
|
|
9
|
+
fetch?: (url: string, init: RequestInit) => Promise<Response>;
|
|
10
|
+
/**
|
|
11
|
+
* GET answers `{ credential_id }`, `null` when she has none; POST takes
|
|
12
|
+
* `{ nonce, registration }`, the WebAuthn registration response made over a
|
|
13
|
+
* `register` nonce.
|
|
14
|
+
*/
|
|
15
|
+
passkey: string;
|
|
16
|
+
/** POST `{ purpose: "register" }` answers `{ nonce }`; `{ purpose: "bind" }` or `{ purpose: "get" }` answers `{ nonce, sid }`. */
|
|
17
|
+
nonce: string;
|
|
18
|
+
/** POST `{ seal_jwk, nonce, assertion }`. */
|
|
19
|
+
bind: string;
|
|
20
|
+
/** POST `{}`, or `{ nonce, assertion }` for a fresh unlock, answers `{ jwe, label? }`. */
|
|
21
|
+
item: string;
|
|
22
|
+
/** POST `{}` confirms an item. */
|
|
23
|
+
confirm: string;
|
|
24
|
+
/** GET answers `{ description }`, the form's compact JWS. */
|
|
25
|
+
describe: string;
|
|
26
|
+
/** POST `{ jwe }` answers `{ status, fields_present? }`. */
|
|
27
|
+
submit: string;
|
|
28
|
+
/** GET answers `{ jwk }`, the public key forms are signed with. */
|
|
29
|
+
signingKey: string;
|
|
30
|
+
/** Further GET endpoints answering `{ jwe, label? }`, chosen by a `<t3-safebox source="…">`. */
|
|
31
|
+
sources?: Record<string, string>;
|
|
32
|
+
}
|
|
33
|
+
export interface SealConfig {
|
|
34
|
+
api: SealApi;
|
|
35
|
+
/** The relying party's name, shown in the passkey prompt and on the elements. */
|
|
36
|
+
rpName: string;
|
|
37
|
+
/** The passkey relying party ID; the page's host name by default. */
|
|
38
|
+
rpId?: string;
|
|
39
|
+
/**
|
|
40
|
+
* The elements' shadow roots: "closed" (default) hides them from
|
|
41
|
+
* `element.shadowRoot` and the page's selectors; "open" lets a test drive
|
|
42
|
+
* them. Neither mode is a boundary against a script running on the page.
|
|
43
|
+
*/
|
|
44
|
+
shadow?: ShadowMode;
|
|
45
|
+
}
|
|
46
|
+
export type EndpointName = Exclude<keyof SealApi, "fetch" | "sources">;
|
|
47
|
+
interface Resolved {
|
|
48
|
+
api: SealApi;
|
|
49
|
+
fetch: (url: string, init: RequestInit) => Promise<Response>;
|
|
50
|
+
rpName: string;
|
|
51
|
+
rpId: string | undefined;
|
|
52
|
+
shadow: ShadowMode;
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* Sets the endpoints and the relying party. Throws `invalid_config` and keeps
|
|
56
|
+
* the previous configuration if `api` or `rpName` is missing, or any part is
|
|
57
|
+
* mistyped or unknown.
|
|
58
|
+
*/
|
|
59
|
+
export declare function configure(opts: SealConfig): void;
|
|
60
|
+
/** Runs `listener` after every successful `configure`; answers a function that stops it. */
|
|
61
|
+
export declare function onConfigure(listener: () => void): () => void;
|
|
62
|
+
export declare function current(): Resolved;
|
|
63
|
+
export declare function configured(): Resolved | null;
|
|
64
|
+
export interface CallInit {
|
|
65
|
+
method: "GET" | "POST";
|
|
66
|
+
ref?: string;
|
|
67
|
+
body?: unknown;
|
|
68
|
+
}
|
|
69
|
+
/** Calls one of the integrator's endpoints and answers its JSON object; an error answer throws. */
|
|
70
|
+
export declare function call(name: EndpointName, init: CallInit): Promise<Record<string, unknown>>;
|
|
71
|
+
/** Calls a named `sources` endpoint. */
|
|
72
|
+
export declare function callSource(source: string, init: CallInit): Promise<Record<string, unknown>>;
|
|
73
|
+
/** A string member of an answer, or `bad_response`. */
|
|
74
|
+
export declare function str(out: Record<string, unknown>, name: string): string;
|
|
75
|
+
export {};
|
package/dist/config.js
ADDED
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
import { isRecord } from "./codec.js";
|
|
2
|
+
import { SealError } from "./errors.js";
|
|
3
|
+
/** Whether each endpoint acts on one reference, and so carries `{ref}`. */
|
|
4
|
+
const ENDPOINTS = {
|
|
5
|
+
passkey: false,
|
|
6
|
+
nonce: false,
|
|
7
|
+
bind: false,
|
|
8
|
+
item: true,
|
|
9
|
+
confirm: true,
|
|
10
|
+
describe: true,
|
|
11
|
+
submit: true,
|
|
12
|
+
signingKey: false,
|
|
13
|
+
};
|
|
14
|
+
const TOP_LEVEL = ["api", "rpName", "rpId", "shadow"];
|
|
15
|
+
let config = null;
|
|
16
|
+
const listeners = [];
|
|
17
|
+
function invalid(why) {
|
|
18
|
+
return new SealError("invalid_config", `Seal.configure: ${why}`);
|
|
19
|
+
}
|
|
20
|
+
function endpoint(name, value, needsRef) {
|
|
21
|
+
if (typeof value !== "string" || value.trim() === "")
|
|
22
|
+
throw invalid(`api.${name} must be a URL or path.`);
|
|
23
|
+
if (needsRef && !value.includes("{ref}"))
|
|
24
|
+
throw invalid(`api.${name} must carry a {ref} placeholder.`);
|
|
25
|
+
if (!needsRef && value.includes("{ref}"))
|
|
26
|
+
throw invalid(`api.${name} acts on no reference, so it takes no {ref}.`);
|
|
27
|
+
return value;
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* Sets the endpoints and the relying party. Throws `invalid_config` and keeps
|
|
31
|
+
* the previous configuration if `api` or `rpName` is missing, or any part is
|
|
32
|
+
* mistyped or unknown.
|
|
33
|
+
*/
|
|
34
|
+
export function configure(opts) {
|
|
35
|
+
if (!isRecord(opts))
|
|
36
|
+
throw invalid("pass { api, rpName, rpId?, shadow? }.");
|
|
37
|
+
const unknownTop = Object.keys(opts).filter((k) => !TOP_LEVEL.includes(k));
|
|
38
|
+
if (unknownTop.length)
|
|
39
|
+
throw invalid(`unknown option ${unknownTop.join(", ")}.`);
|
|
40
|
+
const api = opts.api;
|
|
41
|
+
if (!isRecord(api))
|
|
42
|
+
throw invalid("api must map each call to an endpoint.");
|
|
43
|
+
const known = [...Object.keys(ENDPOINTS), "fetch", "sources"];
|
|
44
|
+
const unknownApi = Object.keys(api).filter((k) => !known.includes(k));
|
|
45
|
+
if (unknownApi.length)
|
|
46
|
+
throw invalid(`unknown api entry ${unknownApi.join(", ")}.`);
|
|
47
|
+
const resolvedApi = {};
|
|
48
|
+
for (const [name, needsRef] of Object.entries(ENDPOINTS))
|
|
49
|
+
resolvedApi[name] = endpoint(name, api[name], needsRef);
|
|
50
|
+
if (api.sources !== undefined) {
|
|
51
|
+
if (!isRecord(api.sources))
|
|
52
|
+
throw invalid("api.sources must map names to endpoints.");
|
|
53
|
+
const sources = {};
|
|
54
|
+
for (const [name, value] of Object.entries(api.sources))
|
|
55
|
+
sources[name] = endpoint(`sources.${name}`, value, true);
|
|
56
|
+
resolvedApi.sources = sources;
|
|
57
|
+
}
|
|
58
|
+
if (api.fetch !== undefined && typeof api.fetch !== "function")
|
|
59
|
+
throw invalid("api.fetch must be a function.");
|
|
60
|
+
if (typeof opts.rpName !== "string" || opts.rpName.trim() === "")
|
|
61
|
+
throw invalid("rpName must name the relying party.");
|
|
62
|
+
if (opts.rpId !== undefined && (typeof opts.rpId !== "string" || opts.rpId.trim() === ""))
|
|
63
|
+
throw invalid("rpId must be a host name.");
|
|
64
|
+
if (opts.shadow !== undefined && opts.shadow !== "open" && opts.shadow !== "closed")
|
|
65
|
+
throw invalid('shadow must be "open" or "closed".');
|
|
66
|
+
const fetcher = api.fetch ?? ((url, init) => fetch(url, init));
|
|
67
|
+
config = {
|
|
68
|
+
api: resolvedApi,
|
|
69
|
+
fetch: fetcher,
|
|
70
|
+
rpName: opts.rpName,
|
|
71
|
+
rpId: opts.rpId,
|
|
72
|
+
shadow: opts.shadow ?? "closed",
|
|
73
|
+
};
|
|
74
|
+
for (const listener of [...listeners])
|
|
75
|
+
listener();
|
|
76
|
+
}
|
|
77
|
+
/** Runs `listener` after every successful `configure`; answers a function that stops it. */
|
|
78
|
+
export function onConfigure(listener) {
|
|
79
|
+
listeners.push(listener);
|
|
80
|
+
return () => {
|
|
81
|
+
const at = listeners.indexOf(listener);
|
|
82
|
+
if (at >= 0)
|
|
83
|
+
listeners.splice(at, 1);
|
|
84
|
+
};
|
|
85
|
+
}
|
|
86
|
+
export function current() {
|
|
87
|
+
if (!config)
|
|
88
|
+
throw new SealError("not_configured", "Seal.configure({ api, rpName }) was not called.");
|
|
89
|
+
return config;
|
|
90
|
+
}
|
|
91
|
+
export function configured() {
|
|
92
|
+
return config;
|
|
93
|
+
}
|
|
94
|
+
function urlFor(template, ref) {
|
|
95
|
+
if (!template.includes("{ref}"))
|
|
96
|
+
return template;
|
|
97
|
+
if (!ref)
|
|
98
|
+
throw new SealError("no_reference", "No reference was given for this call.");
|
|
99
|
+
return template.split("{ref}").join(encodeURIComponent(ref));
|
|
100
|
+
}
|
|
101
|
+
async function send(template, init) {
|
|
102
|
+
const cfg = current();
|
|
103
|
+
const req = { method: init.method };
|
|
104
|
+
if (init.method === "POST") {
|
|
105
|
+
req.headers = { "content-type": "application/json" };
|
|
106
|
+
req.body = JSON.stringify(init.body ?? {});
|
|
107
|
+
}
|
|
108
|
+
const res = await cfg.fetch(urlFor(template, init.ref), req);
|
|
109
|
+
const text = await res.text();
|
|
110
|
+
let out = text ? undefined : {};
|
|
111
|
+
if (text) {
|
|
112
|
+
try {
|
|
113
|
+
out = JSON.parse(text);
|
|
114
|
+
}
|
|
115
|
+
catch {
|
|
116
|
+
// An unparseable body is reported below: as the HTTP status on an error
|
|
117
|
+
// answer, as `bad_response` on a success.
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
if (!res.ok) {
|
|
121
|
+
const body = isRecord(out) ? out : {};
|
|
122
|
+
const code = typeof body.error === "string" ? body.error : `http_${res.status}`;
|
|
123
|
+
const message = typeof body.message === "string" ? body.message : typeof body.error === "string" ? body.error : `HTTP ${res.status}`;
|
|
124
|
+
throw new SealError(code, message);
|
|
125
|
+
}
|
|
126
|
+
if (!isRecord(out))
|
|
127
|
+
throw new SealError("bad_response", "The app answered with something other than a JSON object.");
|
|
128
|
+
return out;
|
|
129
|
+
}
|
|
130
|
+
/** Calls one of the integrator's endpoints and answers its JSON object; an error answer throws. */
|
|
131
|
+
export async function call(name, init) {
|
|
132
|
+
return send(current().api[name], init);
|
|
133
|
+
}
|
|
134
|
+
/** Calls a named `sources` endpoint. */
|
|
135
|
+
export async function callSource(source, init) {
|
|
136
|
+
const template = current().api.sources?.[source];
|
|
137
|
+
if (!template)
|
|
138
|
+
throw new SealError("unknown_source", `No api.sources entry is named ${source}.`);
|
|
139
|
+
return send(template, init);
|
|
140
|
+
}
|
|
141
|
+
/** A string member of an answer, or `bad_response`. */
|
|
142
|
+
export function str(out, name) {
|
|
143
|
+
const v = out[name];
|
|
144
|
+
if (typeof v !== "string" || v === "")
|
|
145
|
+
throw new SealError("bad_response", `The app's answer has no ${name}.`);
|
|
146
|
+
return v;
|
|
147
|
+
}
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
/** `ref` without its `sealed:` or `request:` prefix. */
|
|
2
|
+
export declare function bareRef(ref: string, prefix: "sealed:" | "request:"): string;
|
|
3
|
+
/**
|
|
4
|
+
* Opens a sealed item with her session key. A seal for another key, for
|
|
5
|
+
* another reference or past its expiry is refused before anything is
|
|
6
|
+
* decrypted. Answers the item's JSON content.
|
|
7
|
+
*/
|
|
8
|
+
export declare function open(jwe: string, ref?: string): Promise<unknown>;
|
|
9
|
+
export interface OpenedItem {
|
|
10
|
+
/** The item's JSON content. */
|
|
11
|
+
content: unknown;
|
|
12
|
+
/** The app's answer alongside the JWE, such as its `label`. */
|
|
13
|
+
meta: Record<string, unknown>;
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* Fetches a sealed item and opens it. `source` names an `api.sources`
|
|
17
|
+
* endpoint to fetch it from in place of `api.item`.
|
|
18
|
+
*/
|
|
19
|
+
export declare function openItem(ref: string, source?: string): Promise<OpenedItem>;
|
|
20
|
+
/** Confirms a sealed item through the `confirm` endpoint. */
|
|
21
|
+
export declare function confirmItem(ref: string): Promise<Record<string, unknown>>;
|
|
22
|
+
export interface FormField {
|
|
23
|
+
id: string;
|
|
24
|
+
label: string;
|
|
25
|
+
type?: string;
|
|
26
|
+
options?: Array<{
|
|
27
|
+
value: string;
|
|
28
|
+
label: string;
|
|
29
|
+
}>;
|
|
30
|
+
accept?: string[];
|
|
31
|
+
}
|
|
32
|
+
export interface FormPayload {
|
|
33
|
+
ref: string;
|
|
34
|
+
form_jwk: unknown;
|
|
35
|
+
form: {
|
|
36
|
+
title?: string;
|
|
37
|
+
description?: string;
|
|
38
|
+
submit_label?: string;
|
|
39
|
+
fields: FormField[];
|
|
40
|
+
one_of?: string[][];
|
|
41
|
+
};
|
|
42
|
+
recipients?: Array<{
|
|
43
|
+
name: string;
|
|
44
|
+
role?: string;
|
|
45
|
+
}>;
|
|
46
|
+
destinations?: Array<{
|
|
47
|
+
purpose: string;
|
|
48
|
+
host: string;
|
|
49
|
+
}>;
|
|
50
|
+
[member: string]: unknown;
|
|
51
|
+
}
|
|
52
|
+
export interface FormDescription {
|
|
53
|
+
payload: FormPayload;
|
|
54
|
+
/** base64url SHA-256 of the signed payload bytes, which `submit` binds the answers to. */
|
|
55
|
+
fp: string;
|
|
56
|
+
}
|
|
57
|
+
/** A form's description, verified against the pinned signing key over the exact bytes received. */
|
|
58
|
+
export declare function describe(ref: string): Promise<FormDescription>;
|
|
59
|
+
/**
|
|
60
|
+
* Seals her answers to the form key and submits them. The JWE header binds
|
|
61
|
+
* them to the request (`ref`) and to the description she saw (`fp`).
|
|
62
|
+
*/
|
|
63
|
+
export declare function submit(ref: string, description: FormDescription, answers: Record<string, unknown>): Promise<Record<string, unknown>>;
|
package/dist/delivery.js
ADDED
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
// Both directions of sealed delivery. Out: an item sealed to her session key,
|
|
2
|
+
// fetched through the integrator's app and opened here. In: a form whose
|
|
3
|
+
// description is signed with the relying party's pinned key and whose answers
|
|
4
|
+
// are sealed here to the form key, so only its named recipients can read them.
|
|
5
|
+
import { fromB64u, fromUtf8, isRecord, sha256, toB64u, utf8 } from "./codec.js";
|
|
6
|
+
import { call, callSource, current, onConfigure, str } from "./config.js";
|
|
7
|
+
import { SealError } from "./errors.js";
|
|
8
|
+
import { FORM_JWS_TYPE, checkExpiry, jweHeader, openJwe, publicJwk, seal, signingJwk, verifyJws } from "./jwe.js";
|
|
9
|
+
import { assertStatement, getStatement } from "./passkey.js";
|
|
10
|
+
import { liveSession } from "./session.js";
|
|
11
|
+
/** `ref` without its `sealed:` or `request:` prefix. */
|
|
12
|
+
export function bareRef(ref, prefix) {
|
|
13
|
+
const bare = String(ref ?? "").startsWith(prefix) ? String(ref).slice(prefix.length) : String(ref ?? "");
|
|
14
|
+
if (!bare)
|
|
15
|
+
throw new SealError("no_reference", "No reference was given.");
|
|
16
|
+
return bare;
|
|
17
|
+
}
|
|
18
|
+
/** Her live session key, or the `no_session` refusal. */
|
|
19
|
+
async function session() {
|
|
20
|
+
const rec = await liveSession();
|
|
21
|
+
if (!rec)
|
|
22
|
+
throw new SealError("no_session", "Your secure session has ended: allow the assistant again to open it.");
|
|
23
|
+
return rec;
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Opens a sealed item with her session key. A seal for another key, for
|
|
27
|
+
* another reference or past its expiry is refused before anything is
|
|
28
|
+
* decrypted. Answers the item's JSON content.
|
|
29
|
+
*/
|
|
30
|
+
export async function open(jwe, ref) {
|
|
31
|
+
return openWith(await session(), jwe, ref);
|
|
32
|
+
}
|
|
33
|
+
async function openWith(rec, jwe, ref) {
|
|
34
|
+
const header = jweHeader(jwe);
|
|
35
|
+
checkExpiry(header, Math.floor(Date.now() / 1000));
|
|
36
|
+
const want = ref ? bareRef(ref, "sealed:") : undefined;
|
|
37
|
+
if (want && header.ref !== undefined && header.ref !== want)
|
|
38
|
+
throw new SealError("wrong_reference", "This is not the item that was asked for.");
|
|
39
|
+
const { plaintext } = await openJwe(jwe, rec.privateKey, rec.jwk.kid);
|
|
40
|
+
try {
|
|
41
|
+
return JSON.parse(fromUtf8(plaintext));
|
|
42
|
+
}
|
|
43
|
+
catch {
|
|
44
|
+
throw new SealError("bad_content", "The item opened but is not JSON.");
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
/** A sealed item from the `item` endpoint, after a fresh passkey unlock when the app asks for one. */
|
|
48
|
+
async function fetchItem(ref, fresh) {
|
|
49
|
+
let body = {};
|
|
50
|
+
if (fresh) {
|
|
51
|
+
const out = await call("nonce", { method: "POST", body: { purpose: "get" } });
|
|
52
|
+
const nonce = str(out, "nonce");
|
|
53
|
+
body = { nonce, assertion: await assertStatement(getStatement(ref, str(out, "sid"), nonce)) };
|
|
54
|
+
}
|
|
55
|
+
try {
|
|
56
|
+
return await call("item", { method: "POST", ref, body });
|
|
57
|
+
}
|
|
58
|
+
catch (e) {
|
|
59
|
+
if (!fresh && e instanceof SealError && e.code === "fresh_unlock_required")
|
|
60
|
+
return fetchItem(ref, true);
|
|
61
|
+
throw e;
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* Fetches a sealed item and opens it. `source` names an `api.sources`
|
|
66
|
+
* endpoint to fetch it from in place of `api.item`.
|
|
67
|
+
*/
|
|
68
|
+
export async function openItem(ref, source) {
|
|
69
|
+
const bare = bareRef(ref, "sealed:");
|
|
70
|
+
// Refused before the app is asked: each fetch spends one of the item's reads.
|
|
71
|
+
current();
|
|
72
|
+
const rec = await session();
|
|
73
|
+
const meta = source ? await callSource(source, { method: "GET", ref: bare }) : await fetchItem(bare, false);
|
|
74
|
+
return { content: await openWith(rec, str(meta, "jwe"), bare), meta };
|
|
75
|
+
}
|
|
76
|
+
/** Confirms a sealed item through the `confirm` endpoint. */
|
|
77
|
+
export async function confirmItem(ref) {
|
|
78
|
+
return call("confirm", { method: "POST", ref: bareRef(ref, "sealed:"), body: {} });
|
|
79
|
+
}
|
|
80
|
+
let pinned = null;
|
|
81
|
+
onConfigure(() => {
|
|
82
|
+
pinned = null;
|
|
83
|
+
});
|
|
84
|
+
async function signingKey() {
|
|
85
|
+
if (pinned)
|
|
86
|
+
return pinned;
|
|
87
|
+
const out = await call("signingKey", { method: "GET" });
|
|
88
|
+
pinned = signingJwk(out.jwk);
|
|
89
|
+
return pinned;
|
|
90
|
+
}
|
|
91
|
+
/** A form's description, verified against the pinned signing key over the exact bytes received. */
|
|
92
|
+
export async function describe(ref) {
|
|
93
|
+
const bare = bareRef(ref, "request:");
|
|
94
|
+
const description = str(await call("describe", { method: "GET", ref: bare }), "description");
|
|
95
|
+
const notSigned = () => new SealError("not_signed", `This form is not signed by ${current().rpName}'s key.`);
|
|
96
|
+
let header;
|
|
97
|
+
try {
|
|
98
|
+
header = JSON.parse(fromUtf8(fromB64u(description.split(".")[0] ?? "") ?? new Uint8Array(0)));
|
|
99
|
+
}
|
|
100
|
+
catch {
|
|
101
|
+
throw notSigned();
|
|
102
|
+
}
|
|
103
|
+
const key = await signingKey();
|
|
104
|
+
if (!isRecord(header) || header.alg !== "ES256" || header.typ !== FORM_JWS_TYPE || header.kid !== key.kid)
|
|
105
|
+
throw notSigned();
|
|
106
|
+
const bytes = await verifyJws(description, key);
|
|
107
|
+
if (!bytes)
|
|
108
|
+
throw new SealError("not_signed", "This form's signature does not verify.");
|
|
109
|
+
let payload;
|
|
110
|
+
try {
|
|
111
|
+
payload = JSON.parse(fromUtf8(bytes));
|
|
112
|
+
}
|
|
113
|
+
catch {
|
|
114
|
+
throw new SealError("bad_form", "This form's description is not JSON.");
|
|
115
|
+
}
|
|
116
|
+
if (!isRecord(payload))
|
|
117
|
+
throw new SealError("bad_form", "This form's description is not an object.");
|
|
118
|
+
if (payload.ref !== bare)
|
|
119
|
+
throw new SealError("wrong_reference", "This form is for another request.");
|
|
120
|
+
if (!isRecord(payload.form) || !Array.isArray(payload.form.fields))
|
|
121
|
+
throw new SealError("bad_form", "This form has no fields.");
|
|
122
|
+
return { payload: payload, fp: toB64u(await sha256(bytes)) };
|
|
123
|
+
}
|
|
124
|
+
/**
|
|
125
|
+
* Seals her answers to the form key and submits them. The JWE header binds
|
|
126
|
+
* them to the request (`ref`) and to the description she saw (`fp`).
|
|
127
|
+
*/
|
|
128
|
+
export async function submit(ref, description, answers) {
|
|
129
|
+
const bare = bareRef(ref, "request:");
|
|
130
|
+
if (description.payload.ref !== bare)
|
|
131
|
+
throw new SealError("wrong_reference", "This form is for another request.");
|
|
132
|
+
const formKey = await publicJwk(description.payload.form_jwk);
|
|
133
|
+
const jwe = await seal(formKey, { ref: bare, fp: description.fp, purpose: "request" }, utf8(JSON.stringify(answers)));
|
|
134
|
+
return call("submit", { method: "POST", ref: bare, body: { jwe } });
|
|
135
|
+
}
|