@terminal3/seal-web 0.0.0-stage → 0.1.1

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/dist/jwe.js ADDED
@@ -0,0 +1,213 @@
1
+ // The message formats, as the sealing service builds them: compact JWE
2
+ // (RFC 7516) with `alg` ECDH-ES and `enc` A256GCM over P-256 (RFC 7518 §4.6,
3
+ // one-round Concat KDF, empty apu/apv), the ASCII of the base64url protected
4
+ // header as the AES-GCM additional data and the recipient key's RFC 7638
5
+ // thumbprint as `kid`; and compact ES256 JWS for a form's signed description,
6
+ // whose `kid` is the signing key's `<tid>.<generation>`.
7
+ // Every public key received is checked to be on P-256 before it is used.
8
+ import { canonicalJson, concatBytes, fromB64u, fromUtf8, isRecord, sha256, toB64u, u32be, utf8 } from "./codec.js";
9
+ import { SealError } from "./errors.js";
10
+ export const ALG = "ECDH-ES";
11
+ export const ENC = "A256GCM";
12
+ export const FORM_JWS_TYPE = "t3n-seal-form+jws";
13
+ export const ECDH = { name: "ECDH", namedCurve: "P-256" };
14
+ const ECDSA = { name: "ECDSA", namedCurve: "P-256" };
15
+ const IV_LEN = 12;
16
+ const TAG_LEN = 16;
17
+ const COORD_LEN = 32;
18
+ const SIG_LEN = 64;
19
+ const RESERVED = ["alg", "enc", "epk", "kid"];
20
+ /** RFC 7638 thumbprint of a P-256 public JWK. */
21
+ export async function thumbprint(jwk) {
22
+ return toB64u(await sha256(utf8(`{"crv":"P-256","kty":"EC","x":"${jwk.x}","y":"${jwk.y}"}`)));
23
+ }
24
+ // P-256: y² = x³ − 3x + b over GF(p).
25
+ const P = 0xffffffff00000001000000000000000000000000ffffffffffffffffffffffffn;
26
+ const B = 0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604bn;
27
+ function bigint(bytes) {
28
+ let n = 0n;
29
+ for (const b of bytes)
30
+ n = (n << 8n) | BigInt(b);
31
+ return n;
32
+ }
33
+ function onCurve(x, y) {
34
+ if (x >= P || y >= P)
35
+ return false;
36
+ const mod = (a) => ((a % P) + P) % P;
37
+ return mod(y * y) === mod(x * x * x - 3n * x + B);
38
+ }
39
+ /** The point of `jwk`, accepted only as an EC P-256 public key on the curve. */
40
+ function ecPoint(jwk) {
41
+ const bad = (why) => new SealError("invalid_key", why);
42
+ if (!isRecord(jwk))
43
+ throw bad("A key must be a JWK object.");
44
+ if (jwk.kty !== "EC")
45
+ throw bad("A key's kty must be EC.");
46
+ if (jwk.crv !== "P-256")
47
+ throw bad("A key's crv must be P-256.");
48
+ if ("d" in jwk)
49
+ throw bad("A private key was given where a public key belongs.");
50
+ const members = jwk;
51
+ const coord = (name) => {
52
+ const v = members[name];
53
+ const bytes = typeof v === "string" ? fromB64u(v) : null;
54
+ if (typeof v !== "string" || !bytes || bytes.length !== COORD_LEN)
55
+ throw bad(`A key's ${name} must be 32 bytes of base64url.`);
56
+ return [v, bytes];
57
+ };
58
+ const [x, xb] = coord("x");
59
+ const [y, yb] = coord("y");
60
+ if (!onCurve(bigint(xb), bigint(yb)))
61
+ throw bad("The key is not a point on P-256.");
62
+ return { x, y, kid: jwk.kid };
63
+ }
64
+ /**
65
+ * Accepts `jwk` only as an EC P-256 public key whose point is on the curve and
66
+ * whose `kid`, when it names one, is its own thumbprint.
67
+ */
68
+ export async function publicJwk(jwk) {
69
+ const { x, y, kid: named } = ecPoint(jwk);
70
+ const kid = await thumbprint({ x, y });
71
+ // A non-string `kid` is ignored, as the sealing service ignores it.
72
+ if (typeof named === "string" && named !== kid)
73
+ throw new SealError("invalid_key", "The key's kid is not its thumbprint.");
74
+ return { kty: "EC", crv: "P-256", x, y, kid };
75
+ }
76
+ // `<tid>.<generation>`, the generation counting from 1.
77
+ const SIGNING_KID = /^[^.]+\.[1-9][0-9]*$/;
78
+ /**
79
+ * Accepts `jwk` as the key the sealing service signs a tenant's form
80
+ * descriptions with: an EC P-256 public key whose point is on the curve, with
81
+ * the `kid` the service names, `<tid>.<generation>`. A description's header
82
+ * must carry that same `kid`.
83
+ */
84
+ export function signingJwk(jwk) {
85
+ const { x, y, kid } = ecPoint(jwk);
86
+ if (typeof kid !== "string" || !SIGNING_KID.test(kid))
87
+ throw new SealError("invalid_key", "The signing key's kid must be <tid>.<generation>.");
88
+ return { kty: "EC", crv: "P-256", x, y, kid };
89
+ }
90
+ export function importEcdhPublic(jwk) {
91
+ return crypto.subtle.importKey("jwk", { kty: "EC", crv: "P-256", x: jwk.x, y: jwk.y }, ECDH, false, []);
92
+ }
93
+ /** RFC 7518 §4.6.2 Concat KDF, one SHA-256 round: at most 256 key bits. */
94
+ export async function concatKdf(z, algId, apu, apv, keyBits) {
95
+ if (keyBits <= 0 || keyBits > 256 || keyBits % 8 !== 0)
96
+ throw new SealError("invalid_kdf", "Concat KDF here derives 8 to 256 bits in whole bytes.");
97
+ const alg = utf8(algId);
98
+ const info = concatBytes(u32be(1), z, u32be(alg.length), alg, u32be(apu.length), apu, u32be(apv.length), apv, u32be(keyBits));
99
+ return (await sha256(info)).slice(0, keyBits / 8);
100
+ }
101
+ async function contentKey(privateKey, publicKey, usage) {
102
+ const z = new Uint8Array(await crypto.subtle.deriveBits({ name: "ECDH", public: publicKey }, privateKey, 256));
103
+ const empty = new Uint8Array(0);
104
+ return crypto.subtle.importKey("raw", await concatKdf(z, ENC, empty, empty, 256), "AES-GCM", false, [usage]);
105
+ }
106
+ /**
107
+ * Seals `plaintext` to `to` as a compact JWE. `claims` join `alg`, `enc`,
108
+ * `epk` and `kid` in the protected header, which is serialised with its
109
+ * members sorted.
110
+ */
111
+ export async function seal(to, claims, plaintext, opts = {}) {
112
+ const reserved = Object.keys(claims).filter((k) => RESERVED.includes(k));
113
+ if (reserved.length)
114
+ throw new SealError("invalid_claims", `Claims may not set ${reserved.join(", ")}.`);
115
+ const iv = opts.iv ?? crypto.getRandomValues(new Uint8Array(IV_LEN));
116
+ if (iv.length !== IV_LEN)
117
+ throw new SealError("invalid_iv", "The IV must be 12 bytes.");
118
+ const eph = opts.ephemeral ?? (await crypto.subtle.generateKey(ECDH, true, ["deriveBits"]));
119
+ const epk = await crypto.subtle.exportKey("jwk", eph.publicKey);
120
+ if (typeof epk.x !== "string" || typeof epk.y !== "string")
121
+ throw new SealError("invalid_key", "The ephemeral key did not export.");
122
+ const header = { ...claims, alg: ALG, enc: ENC, epk: { kty: "EC", crv: "P-256", x: epk.x, y: epk.y }, kid: to.kid };
123
+ const protectedB64 = toB64u(utf8(canonicalJson(header)));
124
+ const cek = await contentKey(eph.privateKey, await importEcdhPublic(to), "encrypt");
125
+ const sealed = new Uint8Array(await crypto.subtle.encrypt({ name: "AES-GCM", iv, additionalData: utf8(protectedB64) }, cek, plaintext));
126
+ const ct = sealed.subarray(0, sealed.length - TAG_LEN);
127
+ const tag = sealed.subarray(sealed.length - TAG_LEN);
128
+ return `${protectedB64}..${toB64u(iv)}.${toB64u(ct)}.${toB64u(tag)}`;
129
+ }
130
+ /** The protected header of a compact JWE, without opening it. */
131
+ export function jweHeader(jwe) {
132
+ const malformed = new SealError("jwe_malformed", "This is not a sealed item.");
133
+ const bytes = fromB64u(String(jwe).split(".")[0] ?? "");
134
+ if (!bytes)
135
+ throw malformed;
136
+ let header;
137
+ try {
138
+ header = JSON.parse(fromUtf8(bytes));
139
+ }
140
+ catch {
141
+ throw malformed;
142
+ }
143
+ if (!isRecord(header))
144
+ throw malformed;
145
+ return header;
146
+ }
147
+ /** Refuses a header whose `exp` (Unix seconds) is before `nowSecs`; one without `exp` passes. */
148
+ export function checkExpiry(header, nowSecs) {
149
+ if (!("exp" in header))
150
+ return;
151
+ const exp = header.exp;
152
+ if (typeof exp !== "number" || !Number.isSafeInteger(exp) || exp < 0)
153
+ throw new SealError("jwe_malformed", "This item's expiry is not a time.");
154
+ if (exp < nowSecs)
155
+ throw new SealError("expired", "This has expired.");
156
+ }
157
+ /**
158
+ * Opens a compact ECDH-ES/A256GCM JWE with `privateKey`, whose thumbprint is
159
+ * `kid`. The header must name that `kid` and an on-curve `epk`. Does not read
160
+ * `exp`: run {@link checkExpiry} on the {@link jweHeader} first.
161
+ */
162
+ export async function openJwe(jwe, privateKey, kid) {
163
+ const malformed = (why) => new SealError("jwe_malformed", `This is not a sealed item: ${why}.`);
164
+ const parts = String(jwe).split(".");
165
+ if (parts.length !== 5)
166
+ throw malformed("not five parts");
167
+ const [protectedB64, encryptedKey, ivB64, ctB64, tagB64] = parts;
168
+ if (encryptedKey !== "")
169
+ throw malformed("ECDH-ES carries no encrypted key");
170
+ const header = jweHeader(jwe);
171
+ if (header.alg !== ALG || header.enc !== ENC)
172
+ throw malformed("not ECDH-ES with A256GCM");
173
+ if (header.kid !== kid)
174
+ throw new SealError("header_mismatch", "This was sealed for another device or session.");
175
+ if (header.epk === undefined)
176
+ throw malformed("no epk");
177
+ const epk = await importEcdhPublic(await publicJwk(header.epk));
178
+ const iv = fromB64u(ivB64);
179
+ if (!iv || iv.length !== IV_LEN)
180
+ throw malformed("bad IV");
181
+ const ct = fromB64u(ctB64);
182
+ if (!ct)
183
+ throw malformed("bad ciphertext");
184
+ const tag = fromB64u(tagB64);
185
+ if (!tag || tag.length !== TAG_LEN)
186
+ throw malformed("bad tag");
187
+ const cek = await contentKey(privateKey, epk, "decrypt");
188
+ let plain;
189
+ try {
190
+ plain = await crypto.subtle.decrypt({ name: "AES-GCM", iv, additionalData: utf8(protectedB64) }, cek, concatBytes(ct, tag));
191
+ }
192
+ catch {
193
+ throw new SealError("jwe_not_authentic", "It does not open: changed, or not for this device.");
194
+ }
195
+ return { header, plaintext: new Uint8Array(plain) };
196
+ }
197
+ /**
198
+ * Verifies a compact ES256 JWS against `key` over the exact bytes received and
199
+ * answers its payload; `null` if it is malformed or does not verify.
200
+ */
201
+ export async function verifyJws(jws, key) {
202
+ const parts = String(jws).split(".");
203
+ if (parts.length !== 3)
204
+ return null;
205
+ const [h, p, s] = parts;
206
+ const payload = fromB64u(p);
207
+ const sig = fromB64u(s);
208
+ if (!payload || !sig || sig.length !== SIG_LEN || !fromB64u(h))
209
+ return null;
210
+ const k = await crypto.subtle.importKey("jwk", { kty: "EC", crv: "P-256", x: key.x, y: key.y }, ECDSA, false, ["verify"]);
211
+ const ok = await crypto.subtle.verify({ name: "ECDSA", hash: "SHA-256" }, k, sig, utf8(`${h}.${p}`));
212
+ return ok ? payload : null;
213
+ }
@@ -0,0 +1,38 @@
1
+ /** What a registration ceremony signs. */
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>;
5
+ /** What a fresh unlock of item `ref` signs. */
6
+ export declare function getStatement(ref: string, sid: string, nonce: string): Record<string, string>;
7
+ export interface Registration {
8
+ credential_id: string;
9
+ clientDataJSON: string;
10
+ attestationObject: string;
11
+ /** The authenticator data from the attestation, where the browser reports it. */
12
+ authenticatorData?: string;
13
+ /** The credential public key as SPKI, where the browser reports it. */
14
+ publicKey?: string;
15
+ /** The COSE algorithm of `publicKey`. */
16
+ publicKeyAlgorithm?: number;
17
+ transports: string[];
18
+ }
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
22
+ * (`excludeCredentials`), and that ID is answered. The ceremony's challenge
23
+ * is SHA-256(JCS {t: "t3n-seal/register", nonce}) over a single-use
24
+ * `register` nonce from the IdP, which verifies the ceremony and takes the
25
+ * public key from its attestation.
26
+ */
27
+ export declare function registerPasskey(user: {
28
+ id: string;
29
+ name: string;
30
+ }): Promise<string>;
31
+ export interface Assertion {
32
+ credential_id: string;
33
+ authenticatorData: string;
34
+ clientDataJSON: string;
35
+ signature: string;
36
+ }
37
+ /** A passkey assertion over SHA-256(JCS(statement)) with her registered credential, for the IdP to verify. */
38
+ export declare function assertStatement(statement: Record<string, string>): Promise<Assertion>;
@@ -0,0 +1,142 @@
1
+ // Her passkey binds her consent: the relying party's IdP verifies each
2
+ // assertion against the public key registered there, over
3
+ // SHA-256(JCS(statement)). The IdP's `passkey` answer is the one record of
4
+ // which credential is hers.
5
+ import { canonicalJson, fromB64u, sha256, toB64u, utf8 } from "./codec.js";
6
+ import { call, current, str } from "./config.js";
7
+ import { SealError } from "./errors.js";
8
+ /** What a registration ceremony signs. */
9
+ export function registerStatement(nonce) {
10
+ return { t: "t3n-seal/register", nonce };
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 };
15
+ }
16
+ /** What a fresh unlock of item `ref` signs. */
17
+ export function getStatement(ref, sid, nonce) {
18
+ return { t: "t3n-seal/get", ref, sid, nonce };
19
+ }
20
+ function rpId() {
21
+ return current().rpId ?? location.hostname;
22
+ }
23
+ function challengeFor(statement) {
24
+ return sha256(utf8(canonicalJson(statement)));
25
+ }
26
+ /** Her registered credential from the `passkey` endpoint, or `null` when she has none. */
27
+ async function registered() {
28
+ const { credential_id: id } = await call("passkey", { method: "GET" });
29
+ if (id === null || id === undefined)
30
+ return null;
31
+ const raw = typeof id === "string" ? fromB64u(id) : null;
32
+ if (typeof id !== "string" || !raw)
33
+ throw new SealError("bad_response", "The app's credential_id is not base64url.");
34
+ return { id, raw };
35
+ }
36
+ /**
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
40
+ * authenticator cannot meet the request, `passkey_not_allowed` when the
41
+ * relying party ID does not fit the page, and `passkey_failed` otherwise.
42
+ */
43
+ async function ceremony(run) {
44
+ try {
45
+ return await run();
46
+ }
47
+ catch (e) {
48
+ if (e instanceof SealError)
49
+ throw e;
50
+ const name = typeof e === "object" && e !== null && "name" in e ? String(e.name) : "";
51
+ switch (name) {
52
+ case "NotAllowedError":
53
+ case "AbortError":
54
+ throw new SealError("passkey_cancelled", "The passkey prompt was dismissed.");
55
+ case "InvalidStateError":
56
+ throw new SealError("passkey_exists", "This device already holds a passkey for you.");
57
+ case "NotSupportedError":
58
+ throw new SealError("passkey_unsupported", "This device cannot make the passkey asked for.");
59
+ case "SecurityError":
60
+ throw new SealError("passkey_not_allowed", "This page may not use passkeys for this relying party.");
61
+ default:
62
+ throw new SealError("passkey_failed", "The passkey could not be used.");
63
+ }
64
+ }
65
+ }
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
69
+ * (`excludeCredentials`), and that ID is answered. The ceremony's challenge
70
+ * is SHA-256(JCS {t: "t3n-seal/register", nonce}) over a single-use
71
+ * `register` nonce from the IdP, which verifies the ceremony and takes the
72
+ * public key from its attestation.
73
+ */
74
+ export async function registerPasskey(user) {
75
+ const cfg = current();
76
+ const known = await registered();
77
+ const nonce = str(await call("nonce", { method: "POST", body: { purpose: "register" } }), "nonce");
78
+ const challenge = await challengeFor(registerStatement(nonce));
79
+ let cred;
80
+ try {
81
+ cred = (await ceremony(() => navigator.credentials.create({
82
+ publicKey: {
83
+ rp: { name: cfg.rpName, id: rpId() },
84
+ user: { id: utf8(user.id), name: user.name, displayName: user.name },
85
+ challenge,
86
+ pubKeyCredParams: [{ type: "public-key", alg: -7 }],
87
+ excludeCredentials: known ? [{ type: "public-key", id: known.raw }] : [],
88
+ authenticatorSelection: { residentKey: "preferred", userVerification: "required" },
89
+ attestation: "none",
90
+ },
91
+ })));
92
+ }
93
+ catch (e) {
94
+ if (known && e instanceof SealError && e.code === "passkey_exists")
95
+ return known.id;
96
+ throw e;
97
+ }
98
+ if (!cred)
99
+ throw new SealError("passkey_cancelled", "No passkey was made.");
100
+ const response = cred.response;
101
+ const id = toB64u(new Uint8Array(cred.rawId));
102
+ const registration = {
103
+ credential_id: id,
104
+ clientDataJSON: toB64u(new Uint8Array(response.clientDataJSON)),
105
+ attestationObject: toB64u(new Uint8Array(response.attestationObject)),
106
+ transports: response.getTransports?.() ?? [],
107
+ };
108
+ const authData = response.getAuthenticatorData?.();
109
+ if (authData)
110
+ registration.authenticatorData = toB64u(new Uint8Array(authData));
111
+ const spki = response.getPublicKey?.();
112
+ if (spki) {
113
+ registration.publicKey = toB64u(new Uint8Array(spki));
114
+ const alg = response.getPublicKeyAlgorithm?.();
115
+ if (typeof alg === "number")
116
+ registration.publicKeyAlgorithm = alg;
117
+ }
118
+ await call("passkey", { method: "POST", body: { nonce, registration } });
119
+ return id;
120
+ }
121
+ /** A passkey assertion over SHA-256(JCS(statement)) with her registered credential, for the IdP to verify. */
122
+ export async function assertStatement(statement) {
123
+ const known = await registered();
124
+ const challenge = await challengeFor(statement);
125
+ const cred = (await ceremony(() => navigator.credentials.get({
126
+ publicKey: {
127
+ challenge,
128
+ rpId: rpId(),
129
+ userVerification: "required",
130
+ ...(known ? { allowCredentials: [{ type: "public-key", id: known.raw }] } : {}),
131
+ },
132
+ })));
133
+ if (!cred)
134
+ throw new SealError("passkey_cancelled", "The passkey was not used.");
135
+ const response = cred.response;
136
+ return {
137
+ credential_id: toB64u(new Uint8Array(cred.rawId)),
138
+ authenticatorData: toB64u(new Uint8Array(response.authenticatorData)),
139
+ clientDataJSON: toB64u(new Uint8Array(response.clientDataJSON)),
140
+ signature: toB64u(new Uint8Array(response.signature)),
141
+ };
142
+ }
@@ -0,0 +1,26 @@
1
+ import { type PublicJwk } from "./jwe.js";
2
+ export interface SessionRecord {
3
+ sid: string;
4
+ privateKey: CryptoKey;
5
+ jwk: PublicJwk;
6
+ created_at: number;
7
+ used_at: number;
8
+ }
9
+ /** The live session record, touched; an expired one is deleted. */
10
+ export declare function liveSession(): Promise<SessionRecord | null>;
11
+ /** Deletes her session key: at sign-out, when she revokes the assistant, when the session closes. */
12
+ export declare function reset(): Promise<void>;
13
+ /** Whether a live session key is bound, for her consent `sid` when given. */
14
+ export declare function hasSession(sid?: string): Promise<boolean>;
15
+ /**
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
+ */
21
+ export declare function startSession({ sid, nonce }: {
22
+ sid: string;
23
+ nonce: string;
24
+ }): Promise<PublicJwk>;
25
+ /** Binds a session key again when hers is gone (a reload after it expired). */
26
+ export declare function ensureSession(): Promise<PublicJwk>;
@@ -0,0 +1,90 @@
1
+ // Her session key: a P-256 ECDH pair made with WebCrypto as non-extractable,
2
+ // so the private key never exists outside the browser's key store. It is kept
3
+ // in IndexedDB for the session (10 minutes idle, 30 minutes at most) and
4
+ // deleted by `reset`.
5
+ import { call, str } from "./config.js";
6
+ import { SealError } from "./errors.js";
7
+ import { ECDH, publicJwk } from "./jwe.js";
8
+ import { assertStatement, bindStatement } from "./passkey.js";
9
+ const DB_NAME = "t3-seal";
10
+ const STORE = "sessions";
11
+ const KEY = "current";
12
+ const IDLE_MS = 10 * 60000;
13
+ const MAX_MS = 30 * 60000;
14
+ function openDb() {
15
+ return new Promise((ok, fail) => {
16
+ const req = indexedDB.open(DB_NAME, 1);
17
+ req.onupgradeneeded = () => req.result.createObjectStore(STORE);
18
+ req.onsuccess = () => ok(req.result);
19
+ req.onerror = () => fail(req.error);
20
+ });
21
+ }
22
+ async function store(mode, fn) {
23
+ const db = await openDb();
24
+ try {
25
+ return await new Promise((ok, fail) => {
26
+ const tx = db.transaction(STORE, mode);
27
+ const req = fn(tx.objectStore(STORE));
28
+ tx.oncomplete = () => ok(req?.result);
29
+ tx.onerror = () => fail(tx.error);
30
+ tx.onabort = () => fail(tx.error);
31
+ });
32
+ }
33
+ finally {
34
+ db.close();
35
+ }
36
+ }
37
+ /** The live session record, touched; an expired one is deleted. */
38
+ export async function liveSession() {
39
+ const rec = (await store("readonly", (s) => s.get(KEY)));
40
+ if (!rec)
41
+ return null;
42
+ const now = Date.now();
43
+ if (now - rec.created_at > MAX_MS || now - rec.used_at > IDLE_MS) {
44
+ await store("readwrite", (s) => s.delete(KEY));
45
+ return null;
46
+ }
47
+ rec.used_at = now;
48
+ await store("readwrite", (s) => s.put(rec, KEY));
49
+ return rec;
50
+ }
51
+ /** Deletes her session key: at sign-out, when she revokes the assistant, when the session closes. */
52
+ export async function reset() {
53
+ await store("readwrite", (s) => s.clear());
54
+ }
55
+ /** Whether a live session key is bound, for her consent `sid` when given. */
56
+ export async function hasSession(sid) {
57
+ const rec = await liveSession();
58
+ return Boolean(rec && (!sid || rec.sid === sid));
59
+ }
60
+ /**
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.
65
+ */
66
+ export async function startSession({ sid, nonce }) {
67
+ if (typeof sid !== "string" || !sid || typeof nonce !== "string" || !nonce) {
68
+ throw new SealError("invalid_argument", "startSession needs the consent's sid and the IdP's bind nonce.");
69
+ }
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 } });
75
+ const now = Date.now();
76
+ const rec = { sid, privateKey: pair.privateKey, jwk, created_at: now, used_at: now };
77
+ await store("readwrite", (s) => {
78
+ s.clear();
79
+ return s.put(rec, KEY);
80
+ });
81
+ return jwk;
82
+ }
83
+ /** Binds a session key again when hers is gone (a reload after it expired). */
84
+ export async function ensureSession() {
85
+ const rec = await liveSession();
86
+ if (rec)
87
+ return rec.jwk;
88
+ const out = await call("nonce", { method: "POST", body: { purpose: "bind" } });
89
+ return startSession({ sid: str(out, "sid"), nonce: str(out, "nonce") });
90
+ }
package/package.json CHANGED
@@ -1,6 +1,43 @@
1
1
  {
2
2
  "name": "@terminal3/seal-web",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "type": "module",
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
+ "main": "dist/index.js",
7
+ "types": "dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/index.d.ts",
11
+ "import": "./dist/index.js"
12
+ }
13
+ },
14
+ "files": [
15
+ "dist",
16
+ "README.md",
17
+ "LICENSE"
18
+ ],
19
+ "publishConfig": {
20
+ "access": "public"
21
+ },
22
+ "keywords": [
23
+ "t3n",
24
+ "jwe",
25
+ "webcrypto",
26
+ "passkey",
27
+ "web-components"
28
+ ],
29
+ "author": "T3n Team",
30
+ "license": "MIT",
31
+ "repository": {
32
+ "type": "git",
33
+ "url": "https://github.com/Terminal-3/trinity",
34
+ "directory": "client/seal-web"
35
+ },
36
+ "bugs": {
37
+ "url": "https://github.com/Terminal-3/trinity/issues"
38
+ },
39
+ "homepage": "https://github.com/Terminal-3/trinity/tree/main/client/seal-web#readme",
40
+ "t3n": {
41
+ "packMode": "public"
42
+ }
43
+ }