@terminal3/seal-web 0.1.2 → 0.3.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/README.md CHANGED
@@ -1,9 +1,9 @@
1
1
  # T3n sealed delivery for the browser
2
2
 
3
- `@terminal3/seal-web` is the customer's side of sealed delivery: data her assistant carries but cannot read, in both directions.
3
+ `@terminal3/seal-web` is the customer's side of sealed delivery: data the customer's assistant carries but cannot read, in both directions.
4
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.
5
+ - **Out, a sealed item.** T3N encrypts something sensitive (card details, a transfer to confirm) to a key that exists only in the customer's browser. The assistant holds a reference (`sealed:…`); this package fetches the ciphertext through your app and opens it on the customer's 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 the customer's answers to the form key. The assistant only ever learns the status.
7
7
 
8
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
9
 
@@ -21,7 +21,7 @@ import * as Seal from "@terminal3/seal-web";
21
21
  Seal.configure({
22
22
  rpName: "Example Bank",
23
23
  api: {
24
- // Adds her app session; keep `init.headers`, which carries the JSON content type.
24
+ // Adds the customer's app session; keep `init.headers`, which carries the JSON content type.
25
25
  fetch: (url, init) => fetch(url, { ...init, headers: { ...init.headers, authorization: `Bearer ${token}` } }),
26
26
  passkey: "/api/passkey",
27
27
  nonce: "/api/seal/nonce",
@@ -35,7 +35,7 @@ Seal.configure({
35
35
  });
36
36
 
37
37
  await Seal.registerPasskey({ id: customerId, name: customerName }); // once, at sign-in
38
- await Seal.startSession({ sid, nonce }); // after she allows the assistant
38
+ await Seal.startSession({ sid, nonce }); // after the customer allows the assistant
39
39
  ```
40
40
 
41
41
  ```html
@@ -43,7 +43,7 @@ await Seal.startSession({ sid, nonce }); // after she
43
43
  <t3-safebox-form ref="request:…"></t3-safebox-form>
44
44
  ```
45
45
 
46
- Importing the package defines both elements. Call `Seal.reset()` at sign-out and when she revokes the assistant.
46
+ Importing the package defines both elements. Call `Seal.reset()` at sign-out and when the customer revokes the assistant.
47
47
 
48
48
  ## `configure`
49
49
 
@@ -61,11 +61,11 @@ Each endpoint is a URL or path. The four that act on one item or request carry `
61
61
  | Entry | Method | Takes | Answers |
62
62
  | --- | --- | --- | --- |
63
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 |
64
+ | `passkey` | GET | | `{ credential_id }` of the customer's registered passkey, read before each passkey prompt; `credential_id` is `null` when there is none |
65
65
  | `passkey` | POST | `{ nonce, registration }`, below | |
66
- | `nonce` | POST | `{ purpose: "register" }` | `{ nonce }`, single-use, for her signed-in session |
66
+ | `nonce` | POST | `{ purpose: "register" }` | `{ nonce }`, single-use, for the customer's signed-in session |
67
67
  | `nonce` | POST | `{ purpose: "bind" }` or `{ purpose: "get" }` | `{ nonce, sid }`, single-use for that purpose |
68
- | `bind` | POST | `{ seal_jwk, nonce, assertion }` | |
68
+ | `bind` | POST | `{ seal_jwk, nonce, assertion }`, with `seal_sig_jwk` for a session bound with `signing` | |
69
69
  | `item` | POST | `{}`, or `{ nonce, assertion }` after a fresh unlock | `{ jwe, label? }`; error `fresh_unlock_required` asks for an unlock |
70
70
  | `confirm` | POST | `{}` | |
71
71
  | `describe` | GET | | `{ description }`, the form's compact JWS; error `already_submitted` once answered |
@@ -78,8 +78,9 @@ Your app server verifies what the browser sends and relays each call to T3N; the
78
78
  ## Keys and passkeys
79
79
 
80
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.
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 the customer's 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
+ - **Signing key.** `startSession({ sid, nonce, signing: true })` also makes a P-256 ECDSA key pair, non-extractable, kept in the same record for the same life, for fields the customer signs (WebCrypto cannot use one key for both).
83
+ - **Binding.** The customer's passkey binds the session key's public half to their 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. With a signing key, the one assertion covers both, over `{ t: "t3n-seal/bind", kid, sig_kid, sid, nonce }`. Your IdP builds that statement itself, deriving `kid` and `sig_kid` as the RFC 7638 thumbprints of the posted `seal_jwk` and `seal_sig_jwk`, and refuses an assertion over the statement without `sig_kid` whenever `seal_sig_jwk` is posted: that assertion does not cover the signing key. Only then does it put `seal_sig_jwk` beside `seal_jwk`, copy both into every token it exchanges, and list both in its row's `subject_claims`.
83
84
  - **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
 
85
86
  ## Formats
@@ -92,21 +93,52 @@ Your app server verifies what the browser sends and relays each call to T3N; the
92
93
 
93
94
  | Function | |
94
95
  | --- | --- |
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. |
96
+ | `registerPasskey({ id, name })` | Registers the customer's passkey on this device, unless it already holds their registered credential; answers the credential ID. |
97
+ | `startSession({ sid, nonce, signing? })` | Makes and binds a session key, and a signing key with `signing`; answers the session key's public JWK. |
98
+ | `ensureSession({ signing? })` | Binds a session key with a fresh nonce if none is live, or, with `signing`, has no signing key. |
98
99
  | `hasSession(sid?)`, `reset()` | Whether a live session key is bound; delete it. |
99
100
  | `openItem(ref, source?)` | Fetches and opens a sealed item: `{ content, meta }`. |
100
101
  | `open(jwe, ref?)` | Opens a JWE with the session key. |
101
102
  | `confirmItem(ref)` | Confirms a sealed item. |
102
- | `describe(ref)`, `submit(ref, description, answers)` | Verifies a form's description; seals and submits her answers. |
103
+ | `describe(ref)`, `submit(ref, description, answers)` | Verifies a form's description; seals and submits the customer's answers. |
104
+ | `sealField(ticket, value)` | Seals a hand-over field the customer signs, below. |
105
+ | `openHandoverReply(jwe, signer)` | Opens a reply sealed to the customer's device, below: `{ value, field, sender, ref }`. |
103
106
  | `thumbprint(jwk)` | RFC 7638 thumbprint of a P-256 public JWK. |
104
107
 
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`.
108
+ Every refusal is a `SealError` with a stable `code` and a `message` fit to show the customer. 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` (dismissed, or timed out), `passkey_unsupported`, `passkey_not_allowed` or `passkey_failed`.
109
+
110
+ ## Agent-to-agent hand-overs
111
+
112
+ `@terminal3/seal-web/handover` needs no DOM: it runs in a browser, a worker or Node 20, on WebCrypto alone.
113
+
114
+ ```ts
115
+ import { fetchSealHandoverSigner } from "@terminal3/t3n-sdk";
116
+ import { fetchKeyRecord, generateSenderKey, sealHandover } from "@terminal3/seal-web/handover";
117
+
118
+ const signer = await fetchSealHandoverSigner("testnet");
119
+ const record = await fetchKeyRecord(nodeUrl, orgDid, signer, { ensure });
120
+ const jwe = await sealHandover(record, { ref, sender, recipients, field, sid, iat, exp }, value, senderKey, { consent });
121
+ ```
122
+
123
+ | Function | |
124
+ | --- | --- |
125
+ | `generateSenderKey({ extractable? })` | A sending agent's P-256 signing key; register its `publicJwk` with the sealing service. |
126
+ | `fetchKeyRecord(baseUrl, org, signer, opts?)` | Reads an organisation's key record from the node's public reads and verifies it. With `opts.ensure`, a missing or expired record is replaced by the one `ensure` answers (for example `ensureSealKey` from `@terminal3/t3n-client`, over the sealing service's `key-ensure`), verified the same way. |
127
+ | `verifyKeyRecord(jws, signer, opts?)` | Verifies a key record against the record signer's JWKS, at `opts.nowSecs` or the clock. |
128
+ | `sealHandover(record, claims, value, sender, { consent, nowSecs? })` | Signs `value` and the customer's delegation token (`consent`, required: missing or empty is `invalid_argument`) as the sender and seals them to the record's key; refused after its `not_after`. |
129
+ | `signHandover`, `sealSigned` | The two steps of `sealHandover`. |
130
+
131
+ The envelope is a compact JWE as above, its header carrying `purpose` `handover` and the hand-over claims; its plaintext is the sender's ES256 JWS, `typ` `t3n-handover+jws`, over the same claims, `value` and `consent`. `consent` is the customer's delegation token for the sending agent, a compact JWS by the organisation's IdP, and is never in the header: the sealing service opens an envelope only while that token is live, issued by the IdP the organisation set for an actor it maps to the sender, for the envelope's `sid`, and not revoked. The recipient opens with its own credential alone. The `signer` claim names whose key signed it: `"sender"`, the sending agent's registered key, set when the claims omit it, or `"customer"`, the customer's device signing key. The `to` claim names where the value goes: `"recipient"`, set when the claims omit it, for the recipients to open, or `"customer"`, for the sealing service to re-seal to the customer's device, which needs `signer: "sender"`. A key record is an ES256 JWS, `typ` `t3n-seal-key+jws`, over `{org, kid, jwk, generation, not_after}`. A signer key carrying `exp` (Unix seconds) is an earlier signer generation kept for a grace period after a rotation, and a key without one is the current generation or the next, listed ahead of a rotation; a record it signed is refused `expired` after that, and one signed by a generation the JWKS no longer lists is refused `signature_invalid`.
132
+
133
+ ### The customer's side
134
+
135
+ A field the customer signs, such as an amount they would not type into the chat, is sealed on their device. Your app hands it a ticket from the organisation's hand-over rule for the field: `{ record, signer, consent, claims: { sender, recipients, field, sid, max_ttl_secs } }`, `record` the organisation's key record, `signer` the record signer's JWKS and `consent` the customer's delegation token for the sending agent. `sealField(ticket, value)` refuses a ticket without `consent`, verifies the record, adds `ref`, `iat`, `exp`, `signer: "customer"` and `to: "recipient"`, and signs the value and `consent` with the customer's signing key; the sending agent carries the envelope as any other. It needs a session bound with `signing`, for the ticket's `sid`.
136
+
137
+ A field sealed to the customer reaches the recipient agent as `customer_jwe` in place of its value: a compact JWE to the customer's session key, header `purpose` `handover-reply` and `exp`, whose plaintext is the record signer's ES256 JWS, `typ` `t3n-handover-reply+jws`, over `{org, ref, field, sender, sid, exp, value}`. Pass it to the customer's device unread; `openHandoverReply(jwe, signer)` opens it, verifies it against `signer` by its `kid` and refuses one for another session (`wrong_session`).
106
138
 
107
139
  ## Elements
108
140
 
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.
141
+ - `<t3-safebox ref="sealed:…" label="…">` shows a sealed item once the customer 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. `decline-label="…"` adds a second button beside an item's own confirmation (not a `run_id` one): it fires `seal-declined` with the reference and records nothing, so your app decides what a decline means.
110
142
  - `<t3-safebox-form ref="request:…">` draws a sealed request from its verified description, and fires `seal-submitted` once the answers are sent.
111
143
  - 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
144
  - Both reflect their state in `data-state`, and take their accent colour from the CSS custom properties `--seal-accent` and `--seal-accent-soft`.
@@ -0,0 +1,67 @@
1
+ import { type SessionRecord } from "./session.js";
2
+ import { type SignerJwks } from "./signer.js";
3
+ /**
4
+ * What the integrator's app hands the customer's device for one field the
5
+ * customer signs: the organisation's key record, the record signer's JWKS it
6
+ * verifies against, the customer's delegation token, and the hand-over claims
7
+ * the organisation's hand-over rule for the field gives.
8
+ */
9
+ export interface SealTicket {
10
+ /** The organisation's key record, a compact JWS by the record signer. */
11
+ record: string;
12
+ signer: SignerJwks;
13
+ /**
14
+ * The customer's delegation token for the sending agent, a compact JWS by
15
+ * the organisation's IdP. The envelope carries it as `consent`, and it must
16
+ * be live when the recipient opens the envelope.
17
+ */
18
+ consent: string;
19
+ claims: {
20
+ /** The agent that carries the field, `did:t3n`. */
21
+ sender: string;
22
+ /** The agents allowed to open it, `did:t3n`. */
23
+ recipients: string[];
24
+ field: string;
25
+ /** The customer's consent session; it must be this device's. */
26
+ sid: string;
27
+ /** How long after now the envelope lives. */
28
+ max_ttl_secs: number;
29
+ };
30
+ }
31
+ /** A reply opened on the customer's device. */
32
+ export interface HandoverReply {
33
+ value: unknown;
34
+ field: string;
35
+ /** The agent that sent the field, `did:t3n`. */
36
+ sender: string;
37
+ /** The hand-over's reference. */
38
+ ref: string;
39
+ }
40
+ /**
41
+ * Seals `value` for the hand-over `ticket` describes, signed with the
42
+ * customer's session signing key under `signer: "customer"`, for the
43
+ * recipients to open (`to: "recipient"`). Refused without a live session
44
+ * bound with `signing`, for a ticket of another session or without a consent
45
+ * token, and for a key record that does not verify or is past its
46
+ * `not_after`. Answers the envelope, a compact JWE.
47
+ */
48
+ export declare function sealField(ticket: SealTicket, value: unknown, opts?: {
49
+ nowSecs?: number;
50
+ }): Promise<string>;
51
+ /** {@link sealField} with the session record given. */
52
+ export declare function sealFieldWith(rec: SessionRecord, ticket: SealTicket, value: unknown, now: number): Promise<string>;
53
+ /**
54
+ * Opens a reply the sealing service sealed to the customer's session key.
55
+ * Refused past the `exp` of its JWE header or of its signed payload, when
56
+ * its JWS is not signed under the reply `typ` by the unexpired record-signer
57
+ * key its `signer` names, and when it is for another session.
58
+ *
59
+ * Any reply sealed to this session opens until its `exp`, including an older
60
+ * one for another field or hand-over. The app must check the answered
61
+ * `field`, `ref` and `sender` against the hand-over it expects.
62
+ */
63
+ export declare function openHandoverReply(jwe: string, signer: SignerJwks, opts?: {
64
+ nowSecs?: number;
65
+ }): Promise<HandoverReply>;
66
+ /** {@link openHandoverReply} with the session key and `sid` given. */
67
+ export declare function openReplyWith(rec: Pick<SessionRecord, "privateKey" | "jwk" | "sid">, jwe: string, signer: SignerJwks, now: number): Promise<HandoverReply>;
@@ -0,0 +1,90 @@
1
+ // The customer's side of agent-to-agent hand-overs, on the customer's session.
2
+ //
3
+ // Sealing a field: the device seals it to the organisation's key as a sending
4
+ // agent does, signed with the session's signing key under
5
+ // `signer: "customer"` and `to: "recipient"`, carrying the customer's
6
+ // delegation token as `consent`.
7
+ // The IdP puts that key's public half in the token as `seal_sig_jwk`, and the
8
+ // sealing service verifies the field against it.
9
+ //
10
+ // Opening a reply: for a field sealed to the customer, the sealing service
11
+ // answers the recipient a JWE to the customer's session key whose plaintext is
12
+ // the record signer's JWS over the value, so the device can tell a reply that
13
+ // came through the sealing service from one the carrying agent made.
14
+ import { fromUtf8, isRecord } from "./codec.js";
15
+ import { SealError } from "./errors.js";
16
+ import { HANDOVER_REPLY_JWS_TYPE, HANDOVER_REPLY_PURPOSE, SEALED_TO_RECIPIENT, SIGNED_BY_CUSTOMER, sealHandover, verifyKeyRecord } from "./handover.js";
17
+ import { checkExpiry, jweHeader, openJwe } from "./jwe.js";
18
+ import { liveSession } from "./session.js";
19
+ import { verifySignerJws } from "./signer.js";
20
+ const REF_BYTES = 16;
21
+ /** The customer's live session, or the `no_session` refusal. */
22
+ async function session() {
23
+ const rec = await liveSession();
24
+ if (!rec)
25
+ throw new SealError("no_session", "There is no secure session on this device. Ask again for a new one.");
26
+ return rec;
27
+ }
28
+ function nowSecs(opts) {
29
+ return opts.nowSecs ?? Math.floor(Date.now() / 1000);
30
+ }
31
+ /**
32
+ * Seals `value` for the hand-over `ticket` describes, signed with the
33
+ * customer's session signing key under `signer: "customer"`, for the
34
+ * recipients to open (`to: "recipient"`). Refused without a live session
35
+ * bound with `signing`, for a ticket of another session or without a consent
36
+ * token, and for a key record that does not verify or is past its
37
+ * `not_after`. Answers the envelope, a compact JWE.
38
+ */
39
+ export async function sealField(ticket, value, opts = {}) {
40
+ return sealFieldWith(await session(), ticket, value, nowSecs(opts));
41
+ }
42
+ /** {@link sealField} with the session record given. */
43
+ export async function sealFieldWith(rec, ticket, value, now) {
44
+ if (!rec.signingKey || !rec.sigJwk)
45
+ throw new SealError("no_signing_key", "This session was bound without a signing key.");
46
+ if (!isRecord(ticket) || !isRecord(ticket.claims))
47
+ throw new SealError("invalid_argument", "A ticket carries the record, the signer and the claims.");
48
+ const { max_ttl_secs: ttl, ...claims } = ticket.claims;
49
+ if (claims.sid !== rec.sid)
50
+ throw new SealError("wrong_session", "This ticket is for another session.");
51
+ if (typeof ticket.consent !== "string" || ticket.consent.length === 0)
52
+ throw new SealError("invalid_argument", "A ticket carries the customer's delegation token as consent.");
53
+ if (typeof ttl !== "number" || !Number.isSafeInteger(ttl) || ttl <= 0)
54
+ throw new SealError("invalid_argument", "max_ttl_secs must be a whole number of seconds.");
55
+ const record = await verifyKeyRecord(ticket.record, ticket.signer, { nowSecs: now });
56
+ const ref = Array.from(crypto.getRandomValues(new Uint8Array(REF_BYTES)), (b) => b.toString(16).padStart(2, "0")).join("");
57
+ const full = { ...claims, ref, iat: now, exp: now + ttl, signer: SIGNED_BY_CUSTOMER, to: SEALED_TO_RECIPIENT };
58
+ return sealHandover(record, full, value, { privateKey: rec.signingKey, publicJwk: rec.sigJwk }, { nowSecs: now, consent: ticket.consent });
59
+ }
60
+ /**
61
+ * Opens a reply the sealing service sealed to the customer's session key.
62
+ * Refused past the `exp` of its JWE header or of its signed payload, when
63
+ * its JWS is not signed under the reply `typ` by the unexpired record-signer
64
+ * key its `signer` names, and when it is for another session.
65
+ *
66
+ * Any reply sealed to this session opens until its `exp`, including an older
67
+ * one for another field or hand-over. The app must check the answered
68
+ * `field`, `ref` and `sender` against the hand-over it expects.
69
+ */
70
+ export async function openHandoverReply(jwe, signer, opts = {}) {
71
+ return openReplyWith(await session(), jwe, signer, nowSecs(opts));
72
+ }
73
+ /** {@link openHandoverReply} with the session key and `sid` given. */
74
+ export async function openReplyWith(rec, jwe, signer, now) {
75
+ const header = jweHeader(jwe);
76
+ if (header.purpose !== HANDOVER_REPLY_PURPOSE)
77
+ throw new SealError("jwe_malformed", "This is not a hand-over reply.");
78
+ checkExpiry(header, now);
79
+ const { plaintext } = await openJwe(jwe, rec.privateKey, rec.jwk.kid);
80
+ const claims = await verifySignerJws(fromUtf8(plaintext), signer, HANDOVER_REPLY_JWS_TYPE, now, "reply");
81
+ if (!("exp" in claims))
82
+ throw new SealError("jwe_malformed", "The reply's payload carries no exp.");
83
+ checkExpiry(claims, now);
84
+ if (claims.sid !== rec.sid)
85
+ throw new SealError("wrong_session", "This reply is for another session.");
86
+ const { value, field, sender, ref } = claims;
87
+ if (typeof field !== "string" || typeof sender !== "string" || typeof ref !== "string")
88
+ throw new SealError("jwe_malformed", "The reply names no field, sender or reference.");
89
+ return { value, field, sender, ref };
90
+ }
package/dist/elements.js CHANGED
@@ -1,6 +1,8 @@
1
- // <t3-safebox ref="sealed:…" label="…" source="…" auto-open>: a sealed item,
2
- // opened only in this browser and dropped from the page a minute later, or
3
- // as soon as the element leaves the page.
1
+ // <t3-safebox ref="sealed:…" label="…" source="…" decline-label="…" auto-open>:
2
+ // a sealed item, opened only in this browser and dropped from the page a
3
+ // minute later, or as soon as the element leaves the page. An item with a
4
+ // confirmation of its own (any `confirm.kind` but "run") also offers
5
+ // `decline-label`'s button, when the page sets one.
4
6
  // <t3-safebox-form ref="request:…">: a sealed request, drawn from its signed
5
7
  // description. Both wait in `data-state="waiting"` until `configure` has run,
6
8
  // then render into a shadow root of the configured mode, attached once, and
@@ -38,7 +40,8 @@ const STYLE = `
38
40
  .f span{color:#7a7a82;font-size:12.5px}
39
41
  .f b{font-weight:600;text-align:right}
40
42
  .mono{font-family:ui-monospace,"SF Mono",Menlo,monospace;letter-spacing:.02em}
41
- .row{display:flex;align-items:center;justify-content:space-between;gap:10px;margin-top:12px}
43
+ .row{display:flex;align-items:center;justify-content:space-between;gap:10px;margin-top:12px;flex-wrap:wrap}
44
+ .acts{display:flex;gap:8px;margin-left:auto}
42
45
  button{font:inherit;font-weight:600;border-radius:10px;padding:8px 14px;cursor:pointer;border:0;background:var(--seal-accent,#c8102e);color:#fff}
43
46
  button.ghost{background:#fff;color:#1d1d1f;border:1px solid #d9d3cd}
44
47
  button:disabled{opacity:.55;cursor:default}
@@ -66,7 +69,7 @@ const rpName = () => configured()?.rpName ?? "";
66
69
  const shadowMode = () => configured()?.shadow ?? "closed";
67
70
  /** Defines both elements once; a no-op where they are already defined. */
68
71
  export function defineElements() {
69
- var _T3Safebox_root, _T3Safebox_unlisten, _T3Safebox_data, _T3Safebox_label, _T3Safebox_confirmed, _T3Safebox_error, _T3Safebox_hideTimer, _T3SafeboxForm_root, _T3SafeboxForm_unlisten, _T3SafeboxForm_desc, _T3SafeboxForm_files, _T3SafeboxForm_error;
72
+ var _T3Safebox_root, _T3Safebox_unlisten, _T3Safebox_data, _T3Safebox_label, _T3Safebox_confirmed, _T3Safebox_declined, _T3Safebox_confirming, _T3Safebox_error, _T3Safebox_hideTimer, _T3SafeboxForm_root, _T3SafeboxForm_unlisten, _T3SafeboxForm_desc, _T3SafeboxForm_files, _T3SafeboxForm_error;
70
73
  class T3Safebox extends HTMLElement {
71
74
  constructor() {
72
75
  super(...arguments);
@@ -75,6 +78,8 @@ export function defineElements() {
75
78
  _T3Safebox_data.set(this, null);
76
79
  _T3Safebox_label.set(this, null);
77
80
  _T3Safebox_confirmed.set(this, false);
81
+ _T3Safebox_declined.set(this, false);
82
+ _T3Safebox_confirming.set(this, false);
78
83
  _T3Safebox_error.set(this, null);
79
84
  _T3Safebox_hideTimer.set(this, void 0);
80
85
  }
@@ -122,9 +127,12 @@ export function defineElements() {
122
127
  }
123
128
  }
124
129
  async confirm() {
125
- const btn = __classPrivateFieldGet(this, _T3Safebox_root, "f")?.querySelector("#confirm");
126
- if (btn)
127
- btn.disabled = true;
130
+ __classPrivateFieldSet(this, _T3Safebox_confirming, true, "f");
131
+ for (const id of ["#confirm", "#decline"]) {
132
+ const btn = __classPrivateFieldGet(this, _T3Safebox_root, "f")?.querySelector(id);
133
+ if (btn)
134
+ btn.disabled = true;
135
+ }
128
136
  const c = __classPrivateFieldGet(this, _T3Safebox_data, "f")?.confirm ?? {};
129
137
  const ref = this.getAttribute("ref");
130
138
  try {
@@ -144,6 +152,18 @@ export function defineElements() {
144
152
  __classPrivateFieldSet(this, _T3Safebox_error, messageOf(e), "f");
145
153
  this.render();
146
154
  }
155
+ finally {
156
+ __classPrivateFieldSet(this, _T3Safebox_confirming, false, "f");
157
+ }
158
+ }
159
+ /** The customer's "not this one", for the app to act on: nothing is recorded in T3N. */
160
+ decline() {
161
+ if (__classPrivateFieldGet(this, _T3Safebox_confirming, "f") || __classPrivateFieldGet(this, _T3Safebox_confirmed, "f"))
162
+ return;
163
+ __classPrivateFieldSet(this, _T3Safebox_declined, true, "f");
164
+ this.setAttribute("data-declined", "true");
165
+ this.dispatchEvent(new CustomEvent("seal-declined", { bubbles: true, composed: true, detail: { ref: this.getAttribute("ref") } }));
166
+ this.render();
147
167
  }
148
168
  hide() {
149
169
  __classPrivateFieldSet(this, _T3Safebox_data, null, "f");
@@ -174,12 +194,14 @@ export function defineElements() {
174
194
  else if (d) {
175
195
  const fields = Array.isArray(d.fields) ? d.fields : [];
176
196
  const c = d.confirm;
197
+ const answered = __classPrivateFieldGet(this, _T3Safebox_confirmed, "f") || __classPrivateFieldGet(this, _T3Safebox_declined, "f");
198
+ const declineLabel = c?.kind !== "run" ? this.getAttribute("decline-label") : null;
177
199
  body = `${d.summary ? `<div class="sum">${esc(d.summary)}</div>` : ""}<div class="fields">${fields
178
200
  .map((f) => `<div class="f" data-field="${esc(f.label)}"><span>${esc(f.label)}</span><b class="${f.mono ? "mono" : ""}">${esc(f.value)}</b></div>`)
179
201
  .join("")}</div>
180
- ${__classPrivateFieldGet(this, _T3Safebox_confirmed, "f") ? `<div class="ok">Confirmed</div>` : ""}
202
+ ${__classPrivateFieldGet(this, _T3Safebox_confirmed, "f") ? `<div class="ok">Confirmed</div>` : __classPrivateFieldGet(this, _T3Safebox_declined, "f") ? `<div class="note">You said this is not the one.</div>` : ""}
181
203
  <div class="row"><span class="note">Decrypted in this browser only.</span>
182
- ${c && !__classPrivateFieldGet(this, _T3Safebox_confirmed, "f") ? `<button id="confirm">${esc(c.label ?? "Confirm")}</button>` : `<button class="ghost" id="hide">Hide</button>`}</div>`;
204
+ ${c && !answered ? `<span class="acts">${declineLabel ? `<button class="ghost" id="decline">${esc(declineLabel)}</button>` : ""}<button id="confirm">${esc(c.label ?? "Confirm")}</button></span>` : `<button class="ghost" id="hide">Hide</button>`}</div>`;
183
205
  }
184
206
  else if (state === "error") {
185
207
  body = `<div class="err">${esc(__classPrivateFieldGet(this, _T3Safebox_error, "f"))}</div><div class="row"><span class="note">Only this browser can open it.</span><button id="reveal">Open</button></div>`;
@@ -196,9 +218,10 @@ export function defineElements() {
196
218
  root.querySelector("#reveal")?.addEventListener("click", () => void this.reveal());
197
219
  root.querySelector("#hide")?.addEventListener("click", () => this.hide());
198
220
  root.querySelector("#confirm")?.addEventListener("click", () => void this.confirm());
221
+ root.querySelector("#decline")?.addEventListener("click", () => this.decline());
199
222
  }
200
223
  }
201
- _T3Safebox_root = new WeakMap(), _T3Safebox_unlisten = new WeakMap(), _T3Safebox_data = new WeakMap(), _T3Safebox_label = new WeakMap(), _T3Safebox_confirmed = new WeakMap(), _T3Safebox_error = new WeakMap(), _T3Safebox_hideTimer = new WeakMap();
224
+ _T3Safebox_root = new WeakMap(), _T3Safebox_unlisten = new WeakMap(), _T3Safebox_data = new WeakMap(), _T3Safebox_label = new WeakMap(), _T3Safebox_confirmed = new WeakMap(), _T3Safebox_declined = new WeakMap(), _T3Safebox_confirming = new WeakMap(), _T3Safebox_error = new WeakMap(), _T3Safebox_hideTimer = new WeakMap();
202
225
  class T3SafeboxForm extends HTMLElement {
203
226
  constructor() {
204
227
  super(...arguments);
@@ -0,0 +1,130 @@
1
+ import { type PublicJwk, type SealOptions } from "./jwe.js";
2
+ import { type SignerJwks } from "./signer.js";
3
+ export { SealError } from "./errors.js";
4
+ export { publicJwk, thumbprint, type PublicJwk, type SealOptions } from "./jwe.js";
5
+ export type { SignerJwks } from "./signer.js";
6
+ export declare const HANDOVER_PURPOSE = "handover";
7
+ export declare const HANDOVER_JWS_TYPE = "t3n-handover+jws";
8
+ export declare const KEY_RECORD_TYPE = "t3n-seal-key+jws";
9
+ export declare const SIGNER_PURPOSE = "handover-keys";
10
+ /** The claims an envelope's header and its sender's JWS payload carry alike. */
11
+ export declare const HANDOVER_CLAIMS: readonly ["org", "gen", "ref", "sender", "recipients", "signer", "to", "field", "sid", "iat", "exp"];
12
+ /** The inner JWS payload member that carries the customer's delegation token. */
13
+ export declare const CONSENT_CLAIM = "consent";
14
+ /** The `signer` of an envelope the sending agent's registered key signed. */
15
+ export declare const SIGNED_BY_SENDER = "sender";
16
+ /** The `signer` of an envelope the customer's device signing key signed. */
17
+ export declare const SIGNED_BY_CUSTOMER = "customer";
18
+ /** The `to` of an envelope whose recipients open its value. */
19
+ export declare const SEALED_TO_RECIPIENT = "recipient";
20
+ /** The `to` of an envelope whose value the sealing service re-seals to the customer's device. */
21
+ export declare const SEALED_TO_CUSTOMER = "customer";
22
+ /** The JWE header `purpose` of a reply the sealing service seals to the customer's device. */
23
+ export declare const HANDOVER_REPLY_PURPOSE = "handover-reply";
24
+ /** The `typ` of the record signer's JWS inside a reply to the customer's device. */
25
+ export declare const HANDOVER_REPLY_JWS_TYPE = "t3n-handover-reply+jws";
26
+ /**
27
+ * Whose key signed an envelope's value: the sending agent's registered key,
28
+ * or the customer's device signing key. The header names it, and the sealing
29
+ * service verifies the value against that key.
30
+ */
31
+ export type HandoverSigner = typeof SIGNED_BY_SENDER | typeof SIGNED_BY_CUSTOMER;
32
+ /**
33
+ * Where an envelope's value goes: to its recipients, or to the customer's
34
+ * device, which needs the sending agent's signature (`signer: "sender"`).
35
+ */
36
+ export type HandoverTo = typeof SEALED_TO_RECIPIENT | typeof SEALED_TO_CUSTOMER;
37
+ /** The hand-over claims, as the sealing service reads them. */
38
+ export interface HandoverClaims {
39
+ /** The organisation, 40 lowercase hex. */
40
+ org: string;
41
+ /** The generation of the organisation key the envelope is sealed to. */
42
+ gen: number;
43
+ /** The hand-over's reference, unique per envelope. */
44
+ ref: string;
45
+ /** The sending agent's `did:t3n`. */
46
+ sender: string;
47
+ /** The agents allowed to open it, as `did:t3n`. */
48
+ recipients: string[];
49
+ /** Whose key signs the value; `"sender"` when omitted. */
50
+ signer?: HandoverSigner;
51
+ /** Where the value goes; `"recipient"` when omitted. */
52
+ to?: HandoverTo;
53
+ /** The field's name, 1 to 128 bytes. */
54
+ field: string;
55
+ /** The customer's session the hand-over acts in. */
56
+ sid: string;
57
+ /** Unix seconds. */
58
+ iat: number;
59
+ /** Unix seconds. */
60
+ exp: number;
61
+ }
62
+ /** The key that signs a hand-over, the sending agent's or the customer's device's; `publicJwk.kid` is its thumbprint. */
63
+ export interface SenderKey {
64
+ privateKey: CryptoKey;
65
+ publicJwk: PublicJwk;
66
+ }
67
+ /** An organisation's seal key, as its verified key record states it. */
68
+ export interface OrgKeyRecord {
69
+ /** 40 lowercase hex. */
70
+ org: string;
71
+ generation: number;
72
+ /** Unix seconds after which nothing is sealed to this key. */
73
+ notAfter: number;
74
+ key: PublicJwk;
75
+ }
76
+ /**
77
+ * Generates a P-256 signing key for a sending agent. Its public JWK is what
78
+ * the agent registers with the sealing service. The private key is
79
+ * extractable only when asked, for an agent that stores it itself.
80
+ */
81
+ export declare function generateSenderKey(opts?: {
82
+ extractable?: boolean;
83
+ }): Promise<SenderKey>;
84
+ /** `org` as 40 lowercase hex, from that or from its `did:t3n`. */
85
+ export declare function orgHex(org: string): string;
86
+ /**
87
+ * The sender's JWS over the hand-over claims, `value` and `consent`, the
88
+ * customer's delegation token. The sealing service refuses to open an
89
+ * envelope without one.
90
+ */
91
+ export declare function signHandover(sender: SenderKey, claims: HandoverClaims, value: unknown, consent: string): Promise<string>;
92
+ /**
93
+ * Seals the sender's JWS `inner` to the organisation key `to`. The header
94
+ * carries `purpose` and the hand-over claims, and nothing else.
95
+ */
96
+ export declare function sealSigned(to: PublicJwk, claims: HandoverClaims, inner: string, opts?: SealOptions): Promise<string>;
97
+ /**
98
+ * Seals `value` for a hand-over to the organisation key `record` names,
99
+ * signed by `sender`, carrying `opts.consent`, the customer's delegation
100
+ * token. `org` and `gen` come from the record. Refused once the record's
101
+ * `not_after` has passed.
102
+ */
103
+ export declare function sealHandover(record: OrgKeyRecord, claims: Omit<HandoverClaims, "org" | "gen">, value: unknown, sender: SenderKey, opts: SealOptions & {
104
+ nowSecs?: number;
105
+ consent: string;
106
+ }): Promise<string>;
107
+ /**
108
+ * An organisation's key record verified against the record signer's JWKS at
109
+ * `nowSecs` (default the clock): the key whose `kid` the record's header
110
+ * names must have signed it under `typ` `t3n-seal-key+jws`, and not be past
111
+ * its `exp` when it has one; the record's `jwk` must be a P-256 public key
112
+ * whose thumbprint is its `kid`.
113
+ */
114
+ export declare function verifyKeyRecord(jws: string, signer: SignerJwks, opts?: {
115
+ nowSecs?: number;
116
+ }): Promise<OrgKeyRecord>;
117
+ /**
118
+ * Fetches an organisation's key record from a node's public reads
119
+ * (`GET <baseUrl>/api/public-kv`) and verifies it against `signer`. Refused
120
+ * if the record names another organisation or is past its `not_after`.
121
+ *
122
+ * When the row is missing or its record is past its `not_after`, and
123
+ * `opts.ensure` is given, calls it once for a key record (the sealing
124
+ * service's `key-ensure` answers one) and verifies that record the same way.
125
+ */
126
+ export declare function fetchKeyRecord(baseUrl: string, org: string, signer: SignerJwks, opts?: {
127
+ fetch?: typeof fetch;
128
+ nowSecs?: number;
129
+ ensure?: () => Promise<string>;
130
+ }): Promise<OrgKeyRecord>;
@@ -0,0 +1,183 @@
1
+ // Agent-to-agent hand-overs, without the DOM: runs in a browser, a worker or
2
+ // Node, on WebCrypto alone.
3
+ //
4
+ // An organisation's seal key is published as a key record: a compact ES256
5
+ // JWS by the sealing service's record signer over `{org, kid, jwk,
6
+ // generation, not_after}`. The signer's JWKS is anchored in the network's
7
+ // trust manifest, which `@terminal3/t3n-sdk` verifies; this module takes the
8
+ // verified JWKS as given.
9
+ //
10
+ // A hand-over envelope is a compact JWE to that key whose protected header
11
+ // carries `purpose: "handover"` and the hand-over claims, and whose plaintext
12
+ // is a compact ES256 JWS over the same claims plus `value` and `consent`, by
13
+ // the key the `signer` claim names: the sending agent's registered key, or the
14
+ // customer's device signing key. The `to` claim names where the value goes: to
15
+ // the recipients, or re-sealed by the sealing service to the customer's device.
16
+ // `consent` is the customer's delegation token, naming the sender's IdP actor;
17
+ // it is signed and encrypted, never in the header.
18
+ import { canonicalJson, isRecord, toB64u, utf8 } from "./codec.js";
19
+ import { SealError } from "./errors.js";
20
+ import { publicJwk, seal } from "./jwe.js";
21
+ import { verifySignerJws } from "./signer.js";
22
+ export { SealError } from "./errors.js";
23
+ export { publicJwk, thumbprint } from "./jwe.js";
24
+ export const HANDOVER_PURPOSE = "handover";
25
+ export const HANDOVER_JWS_TYPE = "t3n-handover+jws";
26
+ export const KEY_RECORD_TYPE = "t3n-seal-key+jws";
27
+ export const SIGNER_PURPOSE = "handover-keys";
28
+ /** The claims an envelope's header and its sender's JWS payload carry alike. */
29
+ export const HANDOVER_CLAIMS = ["org", "gen", "ref", "sender", "recipients", "signer", "to", "field", "sid", "iat", "exp"];
30
+ /** The inner JWS payload member that carries the customer's delegation token. */
31
+ export const CONSENT_CLAIM = "consent";
32
+ /** The `signer` of an envelope the sending agent's registered key signed. */
33
+ export const SIGNED_BY_SENDER = "sender";
34
+ /** The `signer` of an envelope the customer's device signing key signed. */
35
+ export const SIGNED_BY_CUSTOMER = "customer";
36
+ /** The `to` of an envelope whose recipients open its value. */
37
+ export const SEALED_TO_RECIPIENT = "recipient";
38
+ /** The `to` of an envelope whose value the sealing service re-seals to the customer's device. */
39
+ export const SEALED_TO_CUSTOMER = "customer";
40
+ /** The JWE header `purpose` of a reply the sealing service seals to the customer's device. */
41
+ export const HANDOVER_REPLY_PURPOSE = "handover-reply";
42
+ /** The `typ` of the record signer's JWS inside a reply to the customer's device. */
43
+ export const HANDOVER_REPLY_JWS_TYPE = "t3n-handover-reply+jws";
44
+ const ECDSA = { name: "ECDSA", namedCurve: "P-256" };
45
+ const ORG_HEX = /^[0-9a-f]{40}$/;
46
+ const PUBLIC_KEYS_MAP = "seal_keys";
47
+ /**
48
+ * Generates a P-256 signing key for a sending agent. Its public JWK is what
49
+ * the agent registers with the sealing service. The private key is
50
+ * extractable only when asked, for an agent that stores it itself.
51
+ */
52
+ export async function generateSenderKey(opts = {}) {
53
+ const pair = await crypto.subtle.generateKey(ECDSA, opts.extractable ?? false, ["sign", "verify"]);
54
+ const jwk = await crypto.subtle.exportKey("jwk", pair.publicKey);
55
+ return { privateKey: pair.privateKey, publicJwk: await publicJwk({ kty: jwk.kty, crv: jwk.crv, x: jwk.x, y: jwk.y }) };
56
+ }
57
+ /** `org` as 40 lowercase hex, from that or from its `did:t3n`. */
58
+ export function orgHex(org) {
59
+ const hex = org.startsWith("did:t3n:") ? org.slice("did:t3n:".length) : org;
60
+ const lower = hex.toLowerCase();
61
+ if (!ORG_HEX.test(lower))
62
+ throw new SealError("invalid_org", "An organisation is 40 hex digits or its did:t3n.");
63
+ return lower;
64
+ }
65
+ function boundClaims(claims) {
66
+ const given = claims;
67
+ const extra = Object.keys(given).filter((k) => given[k] !== undefined && !HANDOVER_CLAIMS.includes(k));
68
+ if (extra.length)
69
+ throw new SealError("invalid_claims", `Not hand-over claims: ${extra.join(", ")}.`);
70
+ const out = {};
71
+ for (const k of HANDOVER_CLAIMS)
72
+ if (given[k] !== undefined)
73
+ out[k] = given[k];
74
+ out.signer ?? (out.signer = SIGNED_BY_SENDER);
75
+ out.to ?? (out.to = SEALED_TO_RECIPIENT);
76
+ if (out.to === SEALED_TO_CUSTOMER && out.signer !== SIGNED_BY_SENDER) {
77
+ throw new SealError("invalid_claims", "A value sealed to the customer is signed by the sender.");
78
+ }
79
+ return out;
80
+ }
81
+ async function es256(key, typ, kid, payload) {
82
+ const input = `${toB64u(utf8(canonicalJson({ alg: "ES256", kid, typ })))}.${toB64u(utf8(payload))}`;
83
+ const sig = new Uint8Array(await crypto.subtle.sign({ name: "ECDSA", hash: "SHA-256" }, key, utf8(input)));
84
+ return `${input}.${toB64u(sig)}`;
85
+ }
86
+ function checkedConsent(consent) {
87
+ if (typeof consent !== "string" || consent.length === 0)
88
+ throw new SealError("invalid_argument", "consent is the customer's delegation token, a compact JWS.");
89
+ return consent;
90
+ }
91
+ /**
92
+ * The sender's JWS over the hand-over claims, `value` and `consent`, the
93
+ * customer's delegation token. The sealing service refuses to open an
94
+ * envelope without one.
95
+ */
96
+ export async function signHandover(sender, claims, value, consent) {
97
+ const payload = { ...boundClaims(claims), value, [CONSENT_CLAIM]: checkedConsent(consent) };
98
+ return es256(sender.privateKey, HANDOVER_JWS_TYPE, sender.publicJwk.kid, canonicalJson(payload));
99
+ }
100
+ /**
101
+ * Seals the sender's JWS `inner` to the organisation key `to`. The header
102
+ * carries `purpose` and the hand-over claims, and nothing else.
103
+ */
104
+ export async function sealSigned(to, claims, inner, opts = {}) {
105
+ return seal(to, { ...boundClaims(claims), purpose: HANDOVER_PURPOSE }, utf8(inner), opts);
106
+ }
107
+ /**
108
+ * Seals `value` for a hand-over to the organisation key `record` names,
109
+ * signed by `sender`, carrying `opts.consent`, the customer's delegation
110
+ * token. `org` and `gen` come from the record. Refused once the record's
111
+ * `not_after` has passed.
112
+ */
113
+ export async function sealHandover(record, claims, value, sender, opts) {
114
+ const now = opts.nowSecs ?? Math.floor(Date.now() / 1000);
115
+ if (now > record.notAfter)
116
+ throw new SealError("expired", "This organisation key is past its not_after.");
117
+ const full = { ...claims, org: record.org, gen: record.generation };
118
+ const inner = await signHandover(sender, full, value, opts.consent);
119
+ return sealSigned(record.key, full, inner, opts);
120
+ }
121
+ /**
122
+ * An organisation's key record verified against the record signer's JWKS at
123
+ * `nowSecs` (default the clock): the key whose `kid` the record's header
124
+ * names must have signed it under `typ` `t3n-seal-key+jws`, and not be past
125
+ * its `exp` when it has one; the record's `jwk` must be a P-256 public key
126
+ * whose thumbprint is its `kid`.
127
+ */
128
+ export async function verifyKeyRecord(jws, signer, opts = {}) {
129
+ const claims = await verifySignerJws(jws, signer, KEY_RECORD_TYPE, opts.nowSecs ?? Math.floor(Date.now() / 1000), "key record");
130
+ const { org, generation, not_after: notAfter } = claims;
131
+ if (typeof org !== "string" || !ORG_HEX.test(org))
132
+ throw new SealError("jwe_malformed", "The key record's org is not 40 lowercase hex.");
133
+ for (const n of [generation, notAfter]) {
134
+ if (typeof n !== "number" || !Number.isSafeInteger(n) || n < 0)
135
+ throw new SealError("jwe_malformed", "The key record's generation and not_after must be whole numbers.");
136
+ }
137
+ const orgKey = await publicJwk(claims.jwk);
138
+ if (claims.kid !== orgKey.kid)
139
+ throw new SealError("invalid_key", "The key record's kid is not its key's thumbprint.");
140
+ return { org, generation: generation, notAfter: notAfter, key: orgKey };
141
+ }
142
+ /**
143
+ * Fetches an organisation's key record from a node's public reads
144
+ * (`GET <baseUrl>/api/public-kv`) and verifies it against `signer`. Refused
145
+ * if the record names another organisation or is past its `not_after`.
146
+ *
147
+ * When the row is missing or its record is past its `not_after`, and
148
+ * `opts.ensure` is given, calls it once for a key record (the sealing
149
+ * service's `key-ensure` answers one) and verifies that record the same way.
150
+ */
151
+ export async function fetchKeyRecord(baseUrl, org, signer, opts = {}) {
152
+ const hex = orgHex(org);
153
+ const now = opts.nowSecs ?? Math.floor(Date.now() / 1000);
154
+ const verified = async (jws) => {
155
+ const record = await verifyKeyRecord(jws, signer, { nowSecs: now });
156
+ if (record.org !== hex)
157
+ throw new SealError("header_mismatch", "The key record is for another organisation.");
158
+ return record;
159
+ };
160
+ const live = (record) => {
161
+ if (now > record.notAfter)
162
+ throw new SealError("expired", "This organisation key is past its not_after.");
163
+ return record;
164
+ };
165
+ const ensured = async (ensure) => live(await verified(await ensure()));
166
+ const url = `${baseUrl.replace(/\/+$/, "")}/api/public-kv?map=${PUBLIC_KEYS_MAP}&key=${hex}`;
167
+ const res = await (opts.fetch ? opts.fetch(url) : fetch(url));
168
+ if (!res.ok)
169
+ throw new SealError(`http_${res.status}`, "The organisation's key record could not be read.");
170
+ const body = await res.json();
171
+ if (!isRecord(body) || body.found !== true) {
172
+ if (opts.ensure)
173
+ return ensured(opts.ensure);
174
+ throw new SealError("not_found", "This organisation has published no seal key.");
175
+ }
176
+ const value = body.value;
177
+ if (!isRecord(value) || typeof value.record !== "string")
178
+ throw new SealError("jwe_malformed", "The organisation's key row holds no record.");
179
+ const record = await verified(value.record);
180
+ if (now > record.notAfter && opts.ensure)
181
+ return ensured(opts.ensure);
182
+ return live(record);
183
+ }
package/dist/index.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  export { configure, type SealApi, type SealConfig, type ShadowMode } from "./config.js";
2
2
  export { confirmItem, describe, open, openItem, submit, type FormDescription, type FormField, type FormPayload, type OpenedItem, } from "./delivery.js";
3
+ export { openHandoverReply, sealField, type HandoverReply, type SealTicket } from "./customer.js";
3
4
  export { defineElements } from "./elements.js";
4
5
  export { SealError } from "./errors.js";
5
6
  export { thumbprint, type PublicJwk } from "./jwe.js";
package/dist/index.js CHANGED
@@ -3,6 +3,7 @@
3
3
  import { defineElements } from "./elements.js";
4
4
  export { configure } from "./config.js";
5
5
  export { confirmItem, describe, open, openItem, submit, } from "./delivery.js";
6
+ export { openHandoverReply, sealField } from "./customer.js";
6
7
  export { defineElements } from "./elements.js";
7
8
  export { SealError } from "./errors.js";
8
9
  export { thumbprint } from "./jwe.js";
package/dist/passkey.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  /** What a registration ceremony signs. */
2
2
  export declare function registerStatement(nonce: string): Record<string, string>;
3
- /** What binding session key `kid` to consent `sid` signs. */
4
- export declare function bindStatement(kid: string, sid: string, nonce: string): Record<string, string>;
3
+ /** What binding session key `kid`, and signing key `sigKid` when given, to consent `sid` signs. */
4
+ export declare function bindStatement(kid: string, sid: string, nonce: string, sigKid?: string): Record<string, string>;
5
5
  /** What a fresh unlock of item `ref` signs. */
6
6
  export declare function getStatement(ref: string, sid: string, nonce: string): Record<string, string>;
7
7
  export interface Registration {
@@ -17,8 +17,8 @@ export interface Registration {
17
17
  transports: string[];
18
18
  }
19
19
  /**
20
- * Registers her passkey on this device and answers its credential ID. A
21
- * device that already holds her registered credential makes no other
20
+ * Registers the user's passkey on this device and answers its credential ID.
21
+ * A device that already holds the registered credential makes no other
22
22
  * (`excludeCredentials`), and that ID is answered. The ceremony's challenge
23
23
  * is SHA-256(JCS {t: "t3n-seal/register", nonce}) over a single-use
24
24
  * `register` nonce from the IdP, which verifies the ceremony and takes the
@@ -34,5 +34,5 @@ export interface Assertion {
34
34
  clientDataJSON: string;
35
35
  signature: string;
36
36
  }
37
- /** A passkey assertion over SHA-256(JCS(statement)) with her registered credential, for the IdP to verify. */
37
+ /** A passkey assertion over SHA-256(JCS(statement)) with the user's registered credential, for the IdP to verify. */
38
38
  export declare function assertStatement(statement: Record<string, string>): Promise<Assertion>;
package/dist/passkey.js CHANGED
@@ -1,7 +1,7 @@
1
- // Her passkey binds her consent: the relying party's IdP verifies each
2
- // assertion against the public key registered there, over
1
+ // The end user's passkey binds their consent: the relying party's IdP
2
+ // verifies each assertion against the public key registered there, over
3
3
  // SHA-256(JCS(statement)). The IdP's `passkey` answer is the one record of
4
- // which credential is hers.
4
+ // which credential is the user's.
5
5
  import { canonicalJson, fromB64u, sha256, toB64u, utf8 } from "./codec.js";
6
6
  import { call, current, str } from "./config.js";
7
7
  import { SealError } from "./errors.js";
@@ -9,9 +9,9 @@ import { SealError } from "./errors.js";
9
9
  export function registerStatement(nonce) {
10
10
  return { t: "t3n-seal/register", nonce };
11
11
  }
12
- /** What binding session key `kid` to consent `sid` signs. */
13
- export function bindStatement(kid, sid, nonce) {
14
- return { t: "t3n-seal/bind", kid, sid, nonce };
12
+ /** What binding session key `kid`, and signing key `sigKid` when given, to consent `sid` signs. */
13
+ export function bindStatement(kid, sid, nonce, sigKid) {
14
+ return sigKid === undefined ? { t: "t3n-seal/bind", kid, sid, nonce } : { t: "t3n-seal/bind", kid, sig_kid: sigKid, sid, nonce };
15
15
  }
16
16
  /** What a fresh unlock of item `ref` signs. */
17
17
  export function getStatement(ref, sid, nonce) {
@@ -23,7 +23,7 @@ function rpId() {
23
23
  function challengeFor(statement) {
24
24
  return sha256(utf8(canonicalJson(statement)));
25
25
  }
26
- /** Her registered credential from the `passkey` endpoint, or `null` when she has none. */
26
+ /** The user's registered credential from the `passkey` endpoint, or `null` when there is none. */
27
27
  async function registered() {
28
28
  const { credential_id: id } = await call("passkey", { method: "GET" });
29
29
  if (id === null || id === undefined)
@@ -35,8 +35,8 @@ async function registered() {
35
35
  }
36
36
  /**
37
37
  * Runs one WebAuthn call. A rejection becomes a `SealError`: `passkey_cancelled`
38
- * when she declines or the prompt times out, `passkey_exists` when this
39
- * authenticator already holds her credential, `passkey_unsupported` when the
38
+ * when the user declines or the prompt times out, `passkey_exists` when this
39
+ * authenticator already holds the user's credential, `passkey_unsupported` when the
40
40
  * authenticator cannot meet the request, `passkey_not_allowed` when the
41
41
  * relying party ID does not fit the page, and `passkey_failed` otherwise.
42
42
  */
@@ -64,8 +64,8 @@ async function ceremony(run) {
64
64
  }
65
65
  }
66
66
  /**
67
- * Registers her passkey on this device and answers its credential ID. A
68
- * device that already holds her registered credential makes no other
67
+ * Registers the user's passkey on this device and answers its credential ID.
68
+ * A device that already holds the registered credential makes no other
69
69
  * (`excludeCredentials`), and that ID is answered. The ceremony's challenge
70
70
  * is SHA-256(JCS {t: "t3n-seal/register", nonce}) over a single-use
71
71
  * `register` nonce from the IdP, which verifies the ceremony and takes the
@@ -118,7 +118,7 @@ export async function registerPasskey(user) {
118
118
  await call("passkey", { method: "POST", body: { nonce, registration } });
119
119
  return id;
120
120
  }
121
- /** A passkey assertion over SHA-256(JCS(statement)) with her registered credential, for the IdP to verify. */
121
+ /** A passkey assertion over SHA-256(JCS(statement)) with the user's registered credential, for the IdP to verify. */
122
122
  export async function assertStatement(statement) {
123
123
  const known = await registered();
124
124
  const challenge = await challengeFor(statement);
package/dist/session.d.ts CHANGED
@@ -3,24 +3,38 @@ export interface SessionRecord {
3
3
  sid: string;
4
4
  privateKey: CryptoKey;
5
5
  jwk: PublicJwk;
6
+ /** The signing key, for a session bound with `signing`. */
7
+ signingKey?: CryptoKey;
8
+ /** Its public JWK, which the IdP puts in the user's token as `seal_sig_jwk`. */
9
+ sigJwk?: PublicJwk;
6
10
  created_at: number;
7
11
  used_at: number;
8
12
  }
9
13
  /** The live session record, touched; an expired one is deleted. */
10
14
  export declare function liveSession(): Promise<SessionRecord | null>;
11
- /** Deletes her session key: at sign-out, when she revokes the assistant, when the session closes. */
15
+ /** Deletes the session key: at sign-out, when the user revokes the assistant, when the session closes. */
12
16
  export declare function reset(): Promise<void>;
13
- /** Whether a live session key is bound, for her consent `sid` when given. */
17
+ /** Whether a live session key is bound, for the consent `sid` when given. */
14
18
  export declare function hasSession(sid?: string): Promise<boolean>;
15
19
  /**
16
- * Makes a session key for her consent `sid` and binds it with her passkey
17
- * over the IdP's single-use `nonce`: an assertion over
18
- * SHA-256(JCS {t: "t3n-seal/bind", kid, sid, nonce}). Answers the public JWK
19
- * the IdP puts in the assistant's delegation token.
20
+ * Makes a session key for the user's consent `sid` and binds it with the
21
+ * user's passkey over the IdP's single-use `nonce`: an assertion over
22
+ * SHA-256(JCS {t: "t3n-seal/bind", kid, sid, nonce}), posted to `bind` with
23
+ * `{seal_jwk, nonce, assertion}`. With `signing`, a signing key is made
24
+ * beside it and the one assertion covers both, over
25
+ * SHA-256(JCS {t: "t3n-seal/bind", kid, sig_kid, sid, nonce}), posted with
26
+ * `seal_sig_jwk` as well. Answers the session key's public JWK, which the
27
+ * IdP puts in the assistant's delegation token as `seal_jwk`.
20
28
  */
21
- export declare function startSession({ sid, nonce }: {
29
+ export declare function startSession({ sid, nonce, signing }: {
22
30
  sid: string;
23
31
  nonce: string;
32
+ signing?: boolean;
33
+ }): Promise<PublicJwk>;
34
+ /**
35
+ * Binds a session key again when none is live (a reload after it expired),
36
+ * or, with `signing`, when the live one has no signing key.
37
+ */
38
+ export declare function ensureSession({ signing }?: {
39
+ signing?: boolean;
24
40
  }): Promise<PublicJwk>;
25
- /** Binds a session key again when hers is gone (a reload after it expired). */
26
- export declare function ensureSession(): Promise<PublicJwk>;
package/dist/session.js CHANGED
@@ -1,7 +1,9 @@
1
- // Her session key: a P-256 ECDH pair made with WebCrypto as non-extractable,
1
+ // The end user's session key: a P-256 ECDH pair made with WebCrypto as non-extractable,
2
2
  // so the private key never exists outside the browser's key store. It is kept
3
3
  // in IndexedDB for the session (10 minutes idle, 30 minutes at most) and
4
- // deleted by `reset`.
4
+ // deleted by `reset`. A session bound with `signing` also holds a P-256 ECDSA
5
+ // signing key, made and kept the same way in the same record: WebCrypto
6
+ // cannot use one key for both.
5
7
  import { call, str } from "./config.js";
6
8
  import { SealError } from "./errors.js";
7
9
  import { ECDH, publicJwk } from "./jwe.js";
@@ -11,6 +13,12 @@ const STORE = "sessions";
11
13
  const KEY = "current";
12
14
  const IDLE_MS = 10 * 60000;
13
15
  const MAX_MS = 30 * 60000;
16
+ const ECDSA = { name: "ECDSA", namedCurve: "P-256" };
17
+ async function generated(algorithm, usages) {
18
+ const pair = await crypto.subtle.generateKey(algorithm, false, usages);
19
+ const pub = await crypto.subtle.exportKey("jwk", pair.publicKey);
20
+ return { privateKey: pair.privateKey, jwk: await publicJwk({ kty: "EC", crv: "P-256", x: pub.x, y: pub.y }) };
21
+ }
14
22
  function openDb() {
15
23
  return new Promise((ok, fail) => {
16
24
  const req = indexedDB.open(DB_NAME, 1);
@@ -48,43 +56,54 @@ export async function liveSession() {
48
56
  await store("readwrite", (s) => s.put(rec, KEY));
49
57
  return rec;
50
58
  }
51
- /** Deletes her session key: at sign-out, when she revokes the assistant, when the session closes. */
59
+ /** Deletes the session key: at sign-out, when the user revokes the assistant, when the session closes. */
52
60
  export async function reset() {
53
61
  await store("readwrite", (s) => s.clear());
54
62
  }
55
- /** Whether a live session key is bound, for her consent `sid` when given. */
63
+ /** Whether a live session key is bound, for the consent `sid` when given. */
56
64
  export async function hasSession(sid) {
57
65
  const rec = await liveSession();
58
66
  return Boolean(rec && (!sid || rec.sid === sid));
59
67
  }
60
68
  /**
61
- * Makes a session key for her consent `sid` and binds it with her passkey
62
- * over the IdP's single-use `nonce`: an assertion over
63
- * SHA-256(JCS {t: "t3n-seal/bind", kid, sid, nonce}). Answers the public JWK
64
- * the IdP puts in the assistant's delegation token.
69
+ * Makes a session key for the user's consent `sid` and binds it with the
70
+ * user's passkey over the IdP's single-use `nonce`: an assertion over
71
+ * SHA-256(JCS {t: "t3n-seal/bind", kid, sid, nonce}), posted to `bind` with
72
+ * `{seal_jwk, nonce, assertion}`. With `signing`, a signing key is made
73
+ * beside it and the one assertion covers both, over
74
+ * SHA-256(JCS {t: "t3n-seal/bind", kid, sig_kid, sid, nonce}), posted with
75
+ * `seal_sig_jwk` as well. Answers the session key's public JWK, which the
76
+ * IdP puts in the assistant's delegation token as `seal_jwk`.
65
77
  */
66
- export async function startSession({ sid, nonce }) {
78
+ export async function startSession({ sid, nonce, signing = false }) {
67
79
  if (typeof sid !== "string" || !sid || typeof nonce !== "string" || !nonce) {
68
80
  throw new SealError("invalid_argument", "startSession needs the consent's sid and the IdP's bind nonce.");
69
81
  }
70
- const pair = await crypto.subtle.generateKey(ECDH, false, ["deriveBits"]);
71
- const pub = await crypto.subtle.exportKey("jwk", pair.publicKey);
72
- const jwk = await publicJwk({ kty: "EC", crv: "P-256", x: pub.x, y: pub.y });
73
- const assertion = await assertStatement(bindStatement(jwk.kid, sid, nonce));
74
- await call("bind", { method: "POST", body: { seal_jwk: jwk, nonce, assertion } });
82
+ const session = await generated(ECDH, ["deriveBits"]);
83
+ const sig = signing ? await generated(ECDSA, ["sign"]) : undefined;
84
+ const assertion = await assertStatement(bindStatement(session.jwk.kid, sid, nonce, sig?.jwk.kid));
85
+ const body = sig ? { seal_jwk: session.jwk, seal_sig_jwk: sig.jwk, nonce, assertion } : { seal_jwk: session.jwk, nonce, assertion };
86
+ await call("bind", { method: "POST", body });
75
87
  const now = Date.now();
76
- const rec = { sid, privateKey: pair.privateKey, jwk, created_at: now, used_at: now };
88
+ const rec = { sid, privateKey: session.privateKey, jwk: session.jwk, created_at: now, used_at: now };
89
+ if (sig) {
90
+ rec.signingKey = sig.privateKey;
91
+ rec.sigJwk = sig.jwk;
92
+ }
77
93
  await store("readwrite", (s) => {
78
94
  s.clear();
79
95
  return s.put(rec, KEY);
80
96
  });
81
- return jwk;
97
+ return session.jwk;
82
98
  }
83
- /** Binds a session key again when hers is gone (a reload after it expired). */
84
- export async function ensureSession() {
99
+ /**
100
+ * Binds a session key again when none is live (a reload after it expired),
101
+ * or, with `signing`, when the live one has no signing key.
102
+ */
103
+ export async function ensureSession({ signing = false } = {}) {
85
104
  const rec = await liveSession();
86
- if (rec)
105
+ if (rec && (!signing || rec.signingKey))
87
106
  return rec.jwk;
88
107
  const out = await call("nonce", { method: "POST", body: { purpose: "bind" } });
89
- return startSession({ sid: str(out, "sid"), nonce: str(out, "nonce") });
108
+ return startSession({ sid: str(out, "sid"), nonce: str(out, "nonce"), signing });
90
109
  }
@@ -0,0 +1,22 @@
1
+ import { type PublicJwk } from "./jwe.js";
2
+ /**
3
+ * The record signer's JWKS, `{ keys }`, from the verified trust manifest. A
4
+ * key carrying `exp` (Unix seconds) is an earlier signer generation listed
5
+ * for a grace period; no record it signed verifies after its `exp`.
6
+ */
7
+ export interface SignerJwks {
8
+ keys: unknown[];
9
+ }
10
+ /**
11
+ * The signer key whose `kid` is `kid`, refused once past its `exp` at
12
+ * `nowSecs`. `what` names the signed thing in the refusal.
13
+ */
14
+ export declare function signerKey(signer: SignerJwks, kid: unknown, nowSecs: number, what: string): Promise<PublicJwk>;
15
+ /**
16
+ * The payload of `jws`, a compact ES256 JWS by the signer key its header's
17
+ * `kid` names, verified at `nowSecs` under `typ`. Refused when that key is
18
+ * missing or past its `exp`, when the signature or `typ` does not match, and
19
+ * when the payload is not a JSON object. `what` names the signed thing in
20
+ * the refusal.
21
+ */
22
+ export declare function verifySignerJws(jws: string, signer: SignerJwks, typ: string, nowSecs: number, what: string): Promise<Record<string, unknown>>;
package/dist/signer.js ADDED
@@ -0,0 +1,59 @@
1
+ // The record signer's JWKS: the key that signs every organisation's key
2
+ // record and every reply sealed to the customer's device, one entry per generation. A
3
+ // key carrying `exp` (Unix seconds) is an earlier generation listed for a
4
+ // grace period; nothing it signed verifies after its `exp`.
5
+ import { fromUtf8, isRecord } from "./codec.js";
6
+ import { SealError } from "./errors.js";
7
+ import { jweHeader, publicJwk, verifyJws } from "./jwe.js";
8
+ /**
9
+ * The signer key whose `kid` is `kid`, refused once past its `exp` at
10
+ * `nowSecs`. `what` names the signed thing in the refusal.
11
+ */
12
+ export async function signerKey(signer, kid, nowSecs, what) {
13
+ const key = Array.isArray(signer.keys) ? signer.keys.find((k) => isRecord(k) && typeof kid === "string" && k.kid === kid) : undefined;
14
+ if (!isRecord(key))
15
+ throw new SealError("signature_invalid", `The ${what} does not verify: no signer key for its kid.`);
16
+ if (key.exp !== undefined) {
17
+ const exp = key.exp;
18
+ if (typeof exp !== "number" || !Number.isSafeInteger(exp) || exp < 0)
19
+ throw new SealError("jwe_malformed", "The signer key's exp is not a whole number.");
20
+ if (nowSecs > exp)
21
+ throw new SealError("expired", `The ${what}'s signer key is past its exp.`);
22
+ }
23
+ return publicJwk({ kty: key.kty, crv: key.crv, x: key.x, y: key.y });
24
+ }
25
+ /**
26
+ * The payload of `jws`, a compact ES256 JWS by the signer key its header's
27
+ * `kid` names, verified at `nowSecs` under `typ`. Refused when that key is
28
+ * missing or past its `exp`, when the signature or `typ` does not match, and
29
+ * when the payload is not a JSON object. `what` names the signed thing in
30
+ * the refusal.
31
+ */
32
+ export async function verifySignerJws(jws, signer, typ, nowSecs, what) {
33
+ const invalid = (why) => new SealError("signature_invalid", `The ${what} does not verify: ${why}.`);
34
+ let header;
35
+ try {
36
+ header = jweHeader(jws);
37
+ }
38
+ catch {
39
+ throw new SealError("jwe_malformed", `The ${what} is not a JWS.`);
40
+ }
41
+ if (header.alg !== "ES256")
42
+ throw invalid("alg must be ES256");
43
+ const key = await signerKey(signer, header.kid, nowSecs, what);
44
+ const payload = await verifyJws(jws, key);
45
+ if (!payload)
46
+ throw invalid("signature");
47
+ if (header.typ !== typ)
48
+ throw invalid("typ");
49
+ let claims;
50
+ try {
51
+ claims = JSON.parse(fromUtf8(payload));
52
+ }
53
+ catch {
54
+ throw new SealError("jwe_malformed", `The ${what}'s payload is not JSON.`);
55
+ }
56
+ if (!isRecord(claims))
57
+ throw new SealError("jwe_malformed", `The ${what}'s payload is not an object.`);
58
+ return claims;
59
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@terminal3/seal-web",
3
- "version": "0.1.2",
3
+ "version": "0.3.0",
4
4
  "type": "module",
5
5
  "description": "T3n sealed delivery in the browser - open items sealed to a device-bound key, and fill signed forms whose answers only their named recipients can read, with no runtime dependencies",
6
6
  "main": "dist/index.js",
@@ -9,6 +9,10 @@
9
9
  ".": {
10
10
  "types": "./dist/index.d.ts",
11
11
  "import": "./dist/index.js"
12
+ },
13
+ "./handover": {
14
+ "types": "./dist/handover.d.ts",
15
+ "import": "./dist/handover.js"
12
16
  }
13
17
  },
14
18
  "files": [