@coffre/client 0.10.1 → 0.11.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.
@@ -0,0 +1,183 @@
1
+ //#region src/dpop.d.ts
2
+ /**
3
+ * The signing half of a workload's proofs (docs/design/workload-access.md,
4
+ * section 5.1): DPoP (RFC 9449) with two claims of coffre's own, `hdr` and
5
+ * `req`, which sign the request's headers, query and body as well as its
6
+ * method and URL. The SDK and the server run this one canonicalization, so
7
+ * what a workload signs is exactly what coffre recomputes and forwards;
8
+ * the server's verifier is `verifyProof` in `@coffre/core/identity`.
9
+ *
10
+ * WebCrypto only, and no dependency, like the rest of the client.
11
+ *
12
+ * A proof is a compact JWS:
13
+ *
14
+ * { "typ": "dpop+jwt", "alg": "ES256", "jwk": { "kty": "EC", "crv": "P-256", "x": "…", "y": "…" } }
15
+ * { "jti": "pA6p8w2Yb3fQe1kHn0S9qg", "htm": "POST", "htu": "https://secrets.acme.example/use/stripe/v1/charges",
16
+ * "iat": 1792805400, "ath": "fUHy…", "nonce": "g1.7Hq2…",
17
+ * "hdr": "content-type idempotency-key", "req": "kq9V…" }
18
+ */
19
+ /** The longest proof, in characters, which the verifier refuses past and the signer never makes. */
20
+ declare const MAX_PROOF_LENGTH = 2048;
21
+ /** The most headers one proof signs: the verifier refuses more, and the signer signs no more. */
22
+ declare const MAX_SIGNED_HEADERS = 32;
23
+ /** A P-256 public key, as a proof carries it: these four members and nothing else. */
24
+ type PublicJwk = {
25
+ kty: 'EC';
26
+ crv: 'P-256';
27
+ x: string;
28
+ y: string;
29
+ };
30
+ /** A workload's key: the private half non-extractable, and the public half as a proof names it. */
31
+ type ProofKey = {
32
+ privateKey: CryptoKey;
33
+ jwk: PublicJwk;
34
+ };
35
+ /** What a proof's payload holds. `ath` signs the token, `hdr` and `req` the rest of the request. */
36
+ type ProofClaims = {
37
+ jti: string;
38
+ htm: string;
39
+ htu: string;
40
+ iat: number;
41
+ ath?: string;
42
+ nonce?: string;
43
+ hdr?: string;
44
+ req?: string;
45
+ };
46
+ /**
47
+ * Headers a proof never signs, so neither forwards: those the transport
48
+ * owns and an intermediary may rewrite, the credentials of the request to
49
+ * coffre itself, and cookies. Coffre sets the transport's own on the way out.
50
+ */
51
+ declare const UNSIGNED_HEADERS: ReadonlySet<string>;
52
+ /** Bytes as base64url, without padding. */
53
+ declare function base64url(bytes: Uint8Array): string;
54
+ /**
55
+ * Base64url without padding, back to bytes; null for anything else, or for a
56
+ * spelling that is not the one `base64url` writes (stray bits in its last
57
+ * character), so that one value has one spelling.
58
+ */
59
+ declare function fromBase64url(text: string): Uint8Array | null;
60
+ /** The key's RFC 7638 thumbprint, `jkt`: base64url SHA-256 of its required members in this order, 43 characters. */
61
+ declare function thumbprint(jwk: PublicJwk): Promise<string>;
62
+ /** A new key for a process: P-256, its private half never exportable, never written anywhere. */
63
+ declare function generateProofKey(): Promise<ProofKey>;
64
+ /** A method, as RFC 9110 writes one: a token, of any length the proof's own limit leaves. */
65
+ declare const METHOD_TOKEN: RegExp;
66
+ /**
67
+ * A URL as `htu` names it: scheme and host lowercased, no default port, no
68
+ * user, query or fragment, and its path as Cloudflare's zones normalize an
69
+ * incoming one by default, in their order: an escaped unreserved character
70
+ * decoded and every other escape's hex in upper case (RFC 3986, section
71
+ * 6.2.2), `\` made `/`, runs of `/` merged, then dot segments removed.
72
+ * Both sides sign this form, so a zone's normalization changes nothing, and
73
+ * a mismatch fails closed. Idempotent. Throws on a URL that is not http or
74
+ * https, and on a `%` that two hex digits do not follow, which would let
75
+ * two paths read as one.
76
+ *
77
+ * canonicalHtu('HTTPS://Secrets.Acme.Example:443//use/%7estripe/a%2fb?x=1')
78
+ * === 'https://secrets.acme.example/use/~stripe/a%2Fb'
79
+ * canonicalHtu('https://secrets.acme.example/hello//../path')
80
+ * === 'https://secrets.acme.example/path'
81
+ */
82
+ declare function canonicalHtu(input: string | URL): string;
83
+ /**
84
+ * A method as `htm` names it, and the Fetch API sends it: one of DELETE,
85
+ * GET, HEAD, OPTIONS, POST and PUT in upper case, whatever case it was
86
+ * given in, and any other exactly as given. Methods are case-sensitive
87
+ * (RFC 9110, section 9.1), so `patch` is not `PATCH`, and a proof signs one.
88
+ */
89
+ declare function fetchMethod(method: string): string;
90
+ /** The SHA-256 of a buffered body, in hex, as a canonical request's last line holds it. */
91
+ declare function bodyDigest(body: Uint8Array | string): Promise<string>;
92
+ /** `ath`: base64url SHA-256 of the session token the proof is sent with. */
93
+ declare function tokenDigest(token: string): Promise<string>;
94
+ /**
95
+ * A canonical request's last line for a body no digest binds: a streamed
96
+ * upload whose SigV4 `x-amz-content-sha256` is `UNSIGNED-PAYLOAD` or
97
+ * `STREAMING-…`. Coffre takes it only through a credential that says
98
+ * `unsignedUploads`, whose page notes what that leaves open.
99
+ */
100
+ declare const UNSIGNED_BODY = "UNSIGNED-PAYLOAD";
101
+ /**
102
+ * A body's line in `req` (section 5.1), one rule for the SDK and coffre,
103
+ * each from what it knows of the body:
104
+ *
105
+ * - `declared`: its `x-amz-content-sha256`, given only through a credential
106
+ * `sigv4` signs; null otherwise, or when it sets none.
107
+ * - `length`: its bytes as known: those read, a stream's `content-length`,
108
+ * or null for a stream of no stated length.
109
+ *
110
+ * A body of no bytes signs the empty body's digest, whatever it declares.
111
+ * One that declares a hash signs it, which S3 checks against the bytes, so
112
+ * it may stream: 64 lower-case hex digits, or `UNSIGNED_BODY` for any other
113
+ * value. Every other body signs its bytes' digest (`bytes`, none for none).
114
+ *
115
+ * bodyLine({ declared: null, length: 6, bytes }) bodyDigest(bytes)
116
+ * bodyLine({ declared: 'UNSIGNED-PAYLOAD', length: 0 }) bodyDigest('')
117
+ * bodyLine({ declared: 'UNSIGNED-PAYLOAD', length: null }) UNSIGNED_BODY
118
+ * bodyLine({ declared: '9f86…0f00a08', length: 4 }) '9f86…0f00a08'
119
+ */
120
+ declare function bodyLine(body: {
121
+ declared: string | null;
122
+ length: number | null;
123
+ bytes?: Uint8Array | null;
124
+ }): Promise<string>;
125
+ /**
126
+ * What `req` signs, one line each:
127
+ *
128
+ * <the path as sent, as the WHATWG parser writes it: every slash and escape kept>
129
+ * <the raw query string as sent, without "?", or empty>
130
+ * <name>:<value> for each header `hdr` names, in its order, its value as received
131
+ * <the body's SHA-256, in lower-case hex>
132
+ *
133
+ * `htu` signs the path as a zone normalizes it, so a proof still holds
134
+ * behind one; this line signs it as it goes upstream, so `/use/s3/a/b` and
135
+ * `/use/s3/a//b`, one object and another to S3, are two requests. A path a
136
+ * zone changed fails closed. The body's line is its buffered bytes' digest
137
+ * (`bodyDigest`), or, for a streamed upload through a credential `sigv4`
138
+ * signs, the 64 hex digits its `x-amz-content-sha256` declares, which S3
139
+ * checks against the bytes; any other declared value is `UNSIGNED_BODY`. A
140
+ * header sent several times is one value, joined by `, `, as `Headers`
141
+ * gives it. No line holds a line break, so no two requests read as one;
142
+ * throws on one that does, or on a body line that is neither.
143
+ */
144
+ declare function canonicalRequest(request: {
145
+ path: string;
146
+ query: string;
147
+ headers: readonly (readonly [string, string])[];
148
+ body: string;
149
+ }): string;
150
+ /** The path and the query a URL sends, as `canonicalRequest` signs them. */
151
+ declare function sentTarget(url: string | URL): {
152
+ path: string;
153
+ query: string;
154
+ };
155
+ /** `req`: base64url SHA-256 of the canonical request. */
156
+ declare function requestDigest(request: Parameters<typeof canonicalRequest>[0]): Promise<string>;
157
+ /** The headers a proof signs from what the app set: every one but `UNSIGNED_HEADERS`, lowercased, in `Headers`' order. */
158
+ declare function signedHeaders(headers: HeadersInit): [string, string][];
159
+ /**
160
+ * A proof for one request, signed by `key`.
161
+ *
162
+ * - `token` adds `ath`, for a request made with a session; the exchange has none.
163
+ * - `nonce` is the gate's newest, from the last answer's `DPoP-Nonce`.
164
+ * - `content` adds `hdr` and `req`: the headers the app set, and the body's
165
+ * line (`bodyDigest`, a streamed SigV4 upload's declared digest, or
166
+ * `UNSIGNED_BODY`).
167
+ * Whatever it names is all coffre forwards.
168
+ */
169
+ declare function createProof(key: ProofKey, request: {
170
+ method: string;
171
+ url: string | URL;
172
+ token?: string;
173
+ nonce?: string;
174
+ content?: {
175
+ headers: HeadersInit;
176
+ body: string;
177
+ };
178
+ /** For tests: the proof's time, in seconds, and its ID. */
179
+ iat?: number;
180
+ jti?: string;
181
+ }): Promise<string>;
182
+ //#endregion
183
+ export { tokenDigest as S, generateProofKey as _, ProofKey as a, signedHeaders as b, UNSIGNED_HEADERS as c, bodyLine as d, canonicalHtu as f, fromBase64url as g, fetchMethod as h, ProofClaims as i, base64url as l, createProof as m, MAX_SIGNED_HEADERS as n, PublicJwk as o, canonicalRequest as p, METHOD_TOKEN as r, UNSIGNED_BODY as s, MAX_PROOF_LENGTH as t, bodyDigest as u, requestDigest as v, thumbprint as x, sentTarget as y };
package/dist/dpop.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ import { S as tokenDigest, _ as generateProofKey, a as ProofKey, b as signedHeaders, c as UNSIGNED_HEADERS, d as bodyLine, f as canonicalHtu, g as fromBase64url, h as fetchMethod, i as ProofClaims, l as base64url, m as createProof, n as MAX_SIGNED_HEADERS, o as PublicJwk, p as canonicalRequest, r as METHOD_TOKEN, s as UNSIGNED_BODY, t as MAX_PROOF_LENGTH, u as bodyDigest, v as requestDigest, x as thumbprint, y as sentTarget } from "./dpop-C5Zyaixy.js";
2
+ export { MAX_PROOF_LENGTH, MAX_SIGNED_HEADERS, METHOD_TOKEN, ProofClaims, ProofKey, PublicJwk, UNSIGNED_BODY, UNSIGNED_HEADERS, base64url, bodyDigest, bodyLine, canonicalHtu, canonicalRequest, createProof, fetchMethod, fromBase64url, generateProofKey, requestDigest, sentTarget, signedHeaders, thumbprint, tokenDigest };
package/dist/dpop.js ADDED
@@ -0,0 +1,290 @@
1
+ //#region src/dpop.ts
2
+ /**
3
+ * The signing half of a workload's proofs (docs/design/workload-access.md,
4
+ * section 5.1): DPoP (RFC 9449) with two claims of coffre's own, `hdr` and
5
+ * `req`, which sign the request's headers, query and body as well as its
6
+ * method and URL. The SDK and the server run this one canonicalization, so
7
+ * what a workload signs is exactly what coffre recomputes and forwards;
8
+ * the server's verifier is `verifyProof` in `@coffre/core/identity`.
9
+ *
10
+ * WebCrypto only, and no dependency, like the rest of the client.
11
+ *
12
+ * A proof is a compact JWS:
13
+ *
14
+ * { "typ": "dpop+jwt", "alg": "ES256", "jwk": { "kty": "EC", "crv": "P-256", "x": "…", "y": "…" } }
15
+ * { "jti": "pA6p8w2Yb3fQe1kHn0S9qg", "htm": "POST", "htu": "https://secrets.acme.example/use/stripe/v1/charges",
16
+ * "iat": 1792805400, "ath": "fUHy…", "nonce": "g1.7Hq2…",
17
+ * "hdr": "content-type idempotency-key", "req": "kq9V…" }
18
+ */
19
+ /** The longest proof, in characters, which the verifier refuses past and the signer never makes. */
20
+ const MAX_PROOF_LENGTH = 2048;
21
+ /** The most headers one proof signs: the verifier refuses more, and the signer signs no more. */
22
+ const MAX_SIGNED_HEADERS = 32;
23
+ /**
24
+ * Headers a proof never signs, so neither forwards: those the transport
25
+ * owns and an intermediary may rewrite, the credentials of the request to
26
+ * coffre itself, and cookies. Coffre sets the transport's own on the way out.
27
+ */
28
+ const UNSIGNED_HEADERS = /* @__PURE__ */ new Set([
29
+ "accept-encoding",
30
+ "authorization",
31
+ "connection",
32
+ "content-length",
33
+ "cookie",
34
+ "dpop",
35
+ "host",
36
+ "keep-alive",
37
+ "proxy-authenticate",
38
+ "proxy-authorization",
39
+ "proxy-connection",
40
+ "te",
41
+ "trailer",
42
+ "transfer-encoding",
43
+ "upgrade"
44
+ ]);
45
+ const ENCODER = new TextEncoder();
46
+ /** Bytes as base64url, without padding. */
47
+ function base64url(bytes) {
48
+ let binary = "";
49
+ for (const byte of bytes) binary += String.fromCharCode(byte);
50
+ return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
51
+ }
52
+ /**
53
+ * Base64url without padding, back to bytes; null for anything else, or for a
54
+ * spelling that is not the one `base64url` writes (stray bits in its last
55
+ * character), so that one value has one spelling.
56
+ */
57
+ function fromBase64url(text) {
58
+ if (!/^[A-Za-z0-9_-]*$/.test(text) || text.length % 4 === 1) return null;
59
+ const binary = atob(text.replace(/-/g, "+").replace(/_/g, "/"));
60
+ const bytes = Uint8Array.from(binary, (char) => char.charCodeAt(0));
61
+ return base64url(bytes) === text ? bytes : null;
62
+ }
63
+ async function sha256(data) {
64
+ const bytes = typeof data === "string" ? ENCODER.encode(data) : data;
65
+ return new Uint8Array(await crypto.subtle.digest("SHA-256", bytes));
66
+ }
67
+ function hex(bytes) {
68
+ return Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
69
+ }
70
+ /** The key's RFC 7638 thumbprint, `jkt`: base64url SHA-256 of its required members in this order, 43 characters. */
71
+ async function thumbprint(jwk) {
72
+ return base64url(await sha256(JSON.stringify({
73
+ crv: jwk.crv,
74
+ kty: jwk.kty,
75
+ x: jwk.x,
76
+ y: jwk.y
77
+ })));
78
+ }
79
+ /** A new key for a process: P-256, its private half never exportable, never written anywhere. */
80
+ async function generateProofKey() {
81
+ const pair = await crypto.subtle.generateKey({
82
+ name: "ECDSA",
83
+ namedCurve: "P-256"
84
+ }, false, ["sign", "verify"]);
85
+ const { kty, crv, x, y } = await crypto.subtle.exportKey("jwk", pair.publicKey);
86
+ return {
87
+ privateKey: pair.privateKey,
88
+ jwk: {
89
+ kty,
90
+ crv,
91
+ x,
92
+ y
93
+ }
94
+ };
95
+ }
96
+ /** A method, as RFC 9110 writes one: a token, of any length the proof's own limit leaves. */
97
+ const METHOD_TOKEN = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;
98
+ /** RFC 3986's unreserved characters, which an escape never needs. */
99
+ const UNRESERVED = /^[A-Za-z0-9\-._~]$/;
100
+ /**
101
+ * A URL as `htu` names it: scheme and host lowercased, no default port, no
102
+ * user, query or fragment, and its path as Cloudflare's zones normalize an
103
+ * incoming one by default, in their order: an escaped unreserved character
104
+ * decoded and every other escape's hex in upper case (RFC 3986, section
105
+ * 6.2.2), `\` made `/`, runs of `/` merged, then dot segments removed.
106
+ * Both sides sign this form, so a zone's normalization changes nothing, and
107
+ * a mismatch fails closed. Idempotent. Throws on a URL that is not http or
108
+ * https, and on a `%` that two hex digits do not follow, which would let
109
+ * two paths read as one.
110
+ *
111
+ * canonicalHtu('HTTPS://Secrets.Acme.Example:443//use/%7estripe/a%2fb?x=1')
112
+ * === 'https://secrets.acme.example/use/~stripe/a%2Fb'
113
+ * canonicalHtu('https://secrets.acme.example/hello//../path')
114
+ * === 'https://secrets.acme.example/path'
115
+ */
116
+ function canonicalHtu(input) {
117
+ const url = new URL(String(input));
118
+ if (url.protocol !== "https:" && url.protocol !== "http:") throw new TypeError(`a proof signs an http or https URL, not ${url.protocol}`);
119
+ const raw = typeof input === "string" ? /^[^:/\\?#]+:[/\\]{2,}[^/\\?#]*([^?#]*)/.exec(input)?.[1] ?? url.pathname : url.pathname;
120
+ if (/%(?![0-9A-Fa-f]{2})/.test(raw)) throw new TypeError("a URL a proof signs escapes a character with % and two hex digits, never a lone %");
121
+ const merged = raw.replace(/%([0-9A-Fa-f]{2})/g, (_, code) => {
122
+ const char = String.fromCharCode(parseInt(code, 16));
123
+ return UNRESERVED.test(char) ? char : `%${code.toUpperCase()}`;
124
+ }).replace(/\\/g, "/").replace(/\/{2,}/g, "/");
125
+ return `${url.protocol}//${url.host}${new URL(withoutDotSegments(merged.startsWith("/") ? merged : `/${merged}`), url.origin).pathname}`;
126
+ }
127
+ /** RFC 3986's `remove_dot_segments` (section 5.2.4), on an absolute path. */
128
+ function withoutDotSegments(path) {
129
+ const kept = [];
130
+ const parts = path.split("/").slice(1);
131
+ parts.forEach((part, i) => {
132
+ if (part !== "." && part !== "..") kept.push(part);
133
+ else {
134
+ if (part === "..") kept.pop();
135
+ if (i === parts.length - 1) kept.push("");
136
+ }
137
+ });
138
+ return `/${kept.join("/")}`;
139
+ }
140
+ /**
141
+ * A method as `htm` names it, and the Fetch API sends it: one of DELETE,
142
+ * GET, HEAD, OPTIONS, POST and PUT in upper case, whatever case it was
143
+ * given in, and any other exactly as given. Methods are case-sensitive
144
+ * (RFC 9110, section 9.1), so `patch` is not `PATCH`, and a proof signs one.
145
+ */
146
+ function fetchMethod(method) {
147
+ if (!METHOD_TOKEN.test(method)) throw new TypeError(`${JSON.stringify(method)} is no HTTP method: a method is a token (RFC 9110, section 9.1)`);
148
+ const upper = method.toUpperCase();
149
+ return [
150
+ "DELETE",
151
+ "GET",
152
+ "HEAD",
153
+ "OPTIONS",
154
+ "POST",
155
+ "PUT"
156
+ ].includes(upper) ? upper : method;
157
+ }
158
+ /** The SHA-256 of a buffered body, in hex, as a canonical request's last line holds it. */
159
+ async function bodyDigest(body) {
160
+ return hex(await sha256(body));
161
+ }
162
+ /** `ath`: base64url SHA-256 of the session token the proof is sent with. */
163
+ async function tokenDigest(token) {
164
+ return base64url(await sha256(token));
165
+ }
166
+ /**
167
+ * A canonical request's last line for a body no digest binds: a streamed
168
+ * upload whose SigV4 `x-amz-content-sha256` is `UNSIGNED-PAYLOAD` or
169
+ * `STREAMING-…`. Coffre takes it only through a credential that says
170
+ * `unsignedUploads`, whose page notes what that leaves open.
171
+ */
172
+ const UNSIGNED_BODY = "UNSIGNED-PAYLOAD";
173
+ const SHA256_HEX = /^[0-9a-f]{64}$/;
174
+ /**
175
+ * A body's line in `req` (section 5.1), one rule for the SDK and coffre,
176
+ * each from what it knows of the body:
177
+ *
178
+ * - `declared`: its `x-amz-content-sha256`, given only through a credential
179
+ * `sigv4` signs; null otherwise, or when it sets none.
180
+ * - `length`: its bytes as known: those read, a stream's `content-length`,
181
+ * or null for a stream of no stated length.
182
+ *
183
+ * A body of no bytes signs the empty body's digest, whatever it declares.
184
+ * One that declares a hash signs it, which S3 checks against the bytes, so
185
+ * it may stream: 64 lower-case hex digits, or `UNSIGNED_BODY` for any other
186
+ * value. Every other body signs its bytes' digest (`bytes`, none for none).
187
+ *
188
+ * bodyLine({ declared: null, length: 6, bytes }) bodyDigest(bytes)
189
+ * bodyLine({ declared: 'UNSIGNED-PAYLOAD', length: 0 }) bodyDigest('')
190
+ * bodyLine({ declared: 'UNSIGNED-PAYLOAD', length: null }) UNSIGNED_BODY
191
+ * bodyLine({ declared: '9f86…0f00a08', length: 4 }) '9f86…0f00a08'
192
+ */
193
+ async function bodyLine(body) {
194
+ if (body.declared !== null && body.length !== 0) return SHA256_HEX.test(body.declared) ? body.declared : UNSIGNED_BODY;
195
+ return bodyDigest(body.bytes ?? /* @__PURE__ */ new Uint8Array());
196
+ }
197
+ /**
198
+ * What `req` signs, one line each:
199
+ *
200
+ * <the path as sent, as the WHATWG parser writes it: every slash and escape kept>
201
+ * <the raw query string as sent, without "?", or empty>
202
+ * <name>:<value> for each header `hdr` names, in its order, its value as received
203
+ * <the body's SHA-256, in lower-case hex>
204
+ *
205
+ * `htu` signs the path as a zone normalizes it, so a proof still holds
206
+ * behind one; this line signs it as it goes upstream, so `/use/s3/a/b` and
207
+ * `/use/s3/a//b`, one object and another to S3, are two requests. A path a
208
+ * zone changed fails closed. The body's line is its buffered bytes' digest
209
+ * (`bodyDigest`), or, for a streamed upload through a credential `sigv4`
210
+ * signs, the 64 hex digits its `x-amz-content-sha256` declares, which S3
211
+ * checks against the bytes; any other declared value is `UNSIGNED_BODY`. A
212
+ * header sent several times is one value, joined by `, `, as `Headers`
213
+ * gives it. No line holds a line break, so no two requests read as one;
214
+ * throws on one that does, or on a body line that is neither.
215
+ */
216
+ function canonicalRequest(request) {
217
+ const lines = [
218
+ request.path,
219
+ request.query,
220
+ ...request.headers.map(([name, value]) => `${name}:${value}`)
221
+ ];
222
+ if (lines.some((line) => /[\r\n]/.test(line))) throw new TypeError("a signed request holds no line break in its path, query or headers");
223
+ if (!SHA256_HEX.test(request.body) && request.body !== "UNSIGNED-PAYLOAD") throw new TypeError("a signed request's body is a SHA-256 in hex, or UNSIGNED_BODY");
224
+ return `${lines.map((line) => `${line}\n`).join("")}${request.body}`;
225
+ }
226
+ /** The path and the query a URL sends, as `canonicalRequest` signs them. */
227
+ function sentTarget(url) {
228
+ const parsed = new URL(String(url));
229
+ return {
230
+ path: parsed.pathname,
231
+ query: parsed.search.slice(1)
232
+ };
233
+ }
234
+ /** `req`: base64url SHA-256 of the canonical request. */
235
+ async function requestDigest(request) {
236
+ return base64url(await sha256(canonicalRequest(request)));
237
+ }
238
+ /** The headers a proof signs from what the app set: every one but `UNSIGNED_HEADERS`, lowercased, in `Headers`' order. */
239
+ function signedHeaders(headers) {
240
+ return [...new Headers(headers)].filter(([name]) => !UNSIGNED_HEADERS.has(name));
241
+ }
242
+ /**
243
+ * A proof for one request, signed by `key`.
244
+ *
245
+ * - `token` adds `ath`, for a request made with a session; the exchange has none.
246
+ * - `nonce` is the gate's newest, from the last answer's `DPoP-Nonce`.
247
+ * - `content` adds `hdr` and `req`: the headers the app set, and the body's
248
+ * line (`bodyDigest`, a streamed SigV4 upload's declared digest, or
249
+ * `UNSIGNED_BODY`).
250
+ * Whatever it names is all coffre forwards.
251
+ */
252
+ async function createProof(key, request) {
253
+ const header = {
254
+ typ: "dpop+jwt",
255
+ alg: "ES256",
256
+ jwk: {
257
+ kty: key.jwk.kty,
258
+ crv: key.jwk.crv,
259
+ x: key.jwk.x,
260
+ y: key.jwk.y
261
+ }
262
+ };
263
+ const claims = {
264
+ jti: request.jti ?? base64url(crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(16))),
265
+ htm: fetchMethod(request.method),
266
+ htu: canonicalHtu(request.url),
267
+ iat: request.iat ?? Math.floor(Date.now() / 1e3)
268
+ };
269
+ if (request.token !== void 0) claims.ath = await tokenDigest(request.token);
270
+ if (request.nonce !== void 0) claims.nonce = request.nonce;
271
+ if (request.content !== void 0) {
272
+ const headers = signedHeaders(request.content.headers);
273
+ if (headers.length > 32) throw new TypeError(`a proof signs at most 32 headers: this request sets ${headers.length}`);
274
+ claims.hdr = headers.map(([name]) => name).join(" ");
275
+ claims.req = await requestDigest({
276
+ ...sentTarget(request.url),
277
+ headers,
278
+ body: request.content.body
279
+ });
280
+ }
281
+ const input = `${base64url(ENCODER.encode(JSON.stringify(header)))}.${base64url(ENCODER.encode(JSON.stringify(claims)))}`;
282
+ if (input.length + 87 > 2048) throw new TypeError(`a proof is at most ${MAX_PROOF_LENGTH} characters: this request's URL or headers are too long to sign`);
283
+ const signature = await crypto.subtle.sign({
284
+ name: "ECDSA",
285
+ hash: "SHA-256"
286
+ }, key.privateKey, ENCODER.encode(input));
287
+ return `${input}.${base64url(new Uint8Array(signature))}`;
288
+ }
289
+ //#endregion
290
+ export { MAX_PROOF_LENGTH, MAX_SIGNED_HEADERS, METHOD_TOKEN, UNSIGNED_BODY, UNSIGNED_HEADERS, base64url, bodyDigest, bodyLine, canonicalHtu, canonicalRequest, createProof, fetchMethod, fromBase64url, generateProofKey, requestDigest, sentTarget, signedHeaders, thumbprint, tokenDigest };