@coffre/client 0.10.2 → 0.12.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/dist/dpop-C5Zyaixy.d.ts +183 -0
- package/dist/dpop.d.ts +2 -0
- package/dist/dpop.js +290 -0
- package/dist/{index-D86fJBDd.d.ts → index-DxSvWq3r.d.ts} +227 -15
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -485
- package/dist/routes.d.ts +1 -1
- package/dist/routes.js +13 -0
- package/dist/src-CjUBSxZs.js +493 -0
- package/dist/workload-9LPBYMmN.d.ts +250 -0
- package/dist/workload-postgres.d.ts +54 -0
- package/dist/workload-postgres.js +210 -0
- package/dist/workload-rRw-uFfr.js +1018 -0
- package/dist/workload.d.ts +3 -0
- package/dist/workload.js +3 -0
- package/package.json +16 -1
- package/src/api.ts +179 -10
- package/src/dpop.ts +301 -0
- package/src/index.ts +5 -3
- package/src/routes.ts +10 -0
- package/src/workload-postgres.ts +254 -0
- package/src/workload-proofs.ts +365 -0
- package/src/workload.ts +711 -0
package/src/workload.ts
ADDED
|
@@ -0,0 +1,711 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A workload's session with coffre (docs/design/workload-access.md, section
|
|
3
|
+
* 9.1): it proves who it is once, gets a session bound to a key that never
|
|
4
|
+
* leaves this process, and from then on uses its credentials through coffre,
|
|
5
|
+
* every request signed. The app holds no secret that works anywhere else.
|
|
6
|
+
*
|
|
7
|
+
* import { workload, enrollment } from '@coffre/client/workload';
|
|
8
|
+
*
|
|
9
|
+
* const coffre = await workload({ url: 'https://secrets.acme.example', service: 'api-prod', proof: enrollment(process.env.COFFRE_ENROLL) });
|
|
10
|
+
* const openai = new OpenAI({ apiKey: 'coffre', baseURL: coffre.url('openai'), fetch: coffre.fetch });
|
|
11
|
+
* const charge = await coffre.credential('stripe').fetch('/v1/charges', { method: 'POST', body: new URLSearchParams({ amount: '2000' }) });
|
|
12
|
+
*
|
|
13
|
+
* What it does for the app, so the app does nothing:
|
|
14
|
+
*
|
|
15
|
+
* - a P-256 key made here, non-extractable; the key, the session's token
|
|
16
|
+
* and the gate's nonce live in this closure only, never on disk or in
|
|
17
|
+
* the environment;
|
|
18
|
+
* - the exchange, retried while an enrollment code is `full` (5 minutes)
|
|
19
|
+
* or its session awaits approval (10), and after a spent projected token,
|
|
20
|
+
* once the kubelet writes the next;
|
|
21
|
+
* - renewal at half-life, every 30 seconds for an enrollment session, whose
|
|
22
|
+
* expiry is its liveness; a fresh proof, with the same key, before the
|
|
23
|
+
* session's hard end, `notAfter`; and a new session whenever the old one
|
|
24
|
+
* is lost (revoked, frozen, expired while the process slept);
|
|
25
|
+
* - each request under `<url>/use/` signed whole (method, URL, query, the
|
|
26
|
+
* headers it was given, the body), with the newest nonce, and sent again
|
|
27
|
+
* once if the gate asks for a fresh one;
|
|
28
|
+
* - logout on `close()`, and on SIGTERM.
|
|
29
|
+
*/
|
|
30
|
+
import { base64url, bodyDigest, bodyLine, createProof, generateProofKey, thumbprint, type ProofKey, type PublicJwk } from './dpop.ts';
|
|
31
|
+
import { CoffreError } from './index.ts';
|
|
32
|
+
import type { Proof, ProofContext } from './workload-proofs.ts';
|
|
33
|
+
|
|
34
|
+
export { aws, azure, enrollment, fly, gcp, github, keyAudience, kubernetes, KUBERNETES_TOKEN, oidc, vercel } from './workload-proofs.ts';
|
|
35
|
+
export type { AwsCredentials, PlatformProof, Proof, ProofContext } from './workload-proofs.ts';
|
|
36
|
+
export { CoffreError } from './index.ts';
|
|
37
|
+
|
|
38
|
+
type Fetch = typeof fetch;
|
|
39
|
+
|
|
40
|
+
export type WorkloadOptions = {
|
|
41
|
+
/** The instance: `https://secrets.acme.example`. */
|
|
42
|
+
url: string;
|
|
43
|
+
/** The service account the workload signs in as: `api-prod`, or `token:api-prod`. */
|
|
44
|
+
service: string;
|
|
45
|
+
/** How it proves who it is: `kubernetes()`, `aws()`, `gcp()`, `enrollment(code)`… (`./workload-proofs.ts`). */
|
|
46
|
+
proof: Proof;
|
|
47
|
+
/** Which of the binding's environments `url`, `credential` and `read` mean, when it has several: `market/prod`. */
|
|
48
|
+
place?: string;
|
|
49
|
+
fetch?: Fetch;
|
|
50
|
+
/** Where it says what it waits for (a full code, an approval, a spent token): stderr unless set. */
|
|
51
|
+
log?: (line: string) => void;
|
|
52
|
+
/** `false` for a process that ends its own way, and calls `close()` itself: no logout on SIGTERM. */
|
|
53
|
+
sigterm?: boolean;
|
|
54
|
+
};
|
|
55
|
+
|
|
56
|
+
export type NarrowOptions = {
|
|
57
|
+
places?: string[];
|
|
58
|
+
credentials?: string[];
|
|
59
|
+
methods?: string[];
|
|
60
|
+
/** Path prefixes of the upstream, matched by whole segments: `/v1/refunds`. */
|
|
61
|
+
paths?: string[];
|
|
62
|
+
/** Seconds; never past the parent's end. */
|
|
63
|
+
expiresIn?: number;
|
|
64
|
+
/** What the service's page calls it: `refund-agent`. */
|
|
65
|
+
label?: string;
|
|
66
|
+
};
|
|
67
|
+
|
|
68
|
+
export interface Workload {
|
|
69
|
+
readonly service: string;
|
|
70
|
+
/** The environments the session reaches. */
|
|
71
|
+
readonly places: readonly string[];
|
|
72
|
+
/**
|
|
73
|
+
* A `fetch` that signs every request under `<url>/use/` and passes anything
|
|
74
|
+
* else through untouched: give it to any SDK that takes one.
|
|
75
|
+
*/
|
|
76
|
+
readonly fetch: Fetch;
|
|
77
|
+
/** A credential's URL on coffre's proxy, an SDK's base URL: `<url>/use/<name>`, or `<url>/use/<project>/<env>/<name>` with several places. */
|
|
78
|
+
url(name: string): string;
|
|
79
|
+
credential(name: string): UsedCredential;
|
|
80
|
+
/** The escape hatch: a plain value, or one the binding lists in `reads`. Anything else rejects with `use_only`. */
|
|
81
|
+
read(key: string): Promise<string>;
|
|
82
|
+
/**
|
|
83
|
+
* A session with less authority (section 8.4), for a part of the app that
|
|
84
|
+
* needs less: in this process, a `Workload` of its own key; for another
|
|
85
|
+
* process, which made the key and sends only its public half, the child's
|
|
86
|
+
* token, which that process uses with its own key.
|
|
87
|
+
*/
|
|
88
|
+
narrow(options: NarrowOptions & { key: PublicJwk }): Promise<{ token: string; expiresAt: string }>;
|
|
89
|
+
narrow(options: NarrowOptions): Promise<Workload>;
|
|
90
|
+
/** Logs out: the session ends now, and its children with it. */
|
|
91
|
+
close(): Promise<void>;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
export interface UsedCredential {
|
|
95
|
+
/** `<credential's URL>/<path>`, signed: the proxy forwards it to the upstream with the real key. */
|
|
96
|
+
fetch(path: string, init?: RequestInit): Promise<Response>;
|
|
97
|
+
/** A signature by a signer's private key, which stays in coffre: base64url, as `credential.sign` gives. */
|
|
98
|
+
sign(message: string | Uint8Array): Promise<string>;
|
|
99
|
+
/** Whether `signature` is a verifier's over `message`: an inbound webhook's, checked without reading its secret. */
|
|
100
|
+
verify(message: string | Uint8Array, signature: string): Promise<boolean>;
|
|
101
|
+
/** A presigned GET or HEAD of `path` under an AWS-signed credential's upstream: the upstream's own URL, for anyone until `expiresAt`. */
|
|
102
|
+
presign(path: string, options?: { expiresIn?: number; method?: 'GET' | 'HEAD'; query?: Record<string, string> }): Promise<{ url: string; expiresAt: string }>;
|
|
103
|
+
/** A short-lived child of a minter (an AWS session, a GitHub installation token), where the binding lists it. */
|
|
104
|
+
mint<T = Record<string, string>>(): Promise<T & { expiresAt: string }>;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** A session as the exchange answers it. */
|
|
108
|
+
type Session = { token: string; expiresAt: number; notAfter: number; places: string[]; issuedAt: number };
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* The gate's newest nonce, and when the request that brought it went out: a
|
|
112
|
+
* nonce is good for at least the 2 minutes from then until the gate's next
|
|
113
|
+
* rotation. Each request is numbered as it goes out, and an answer to an
|
|
114
|
+
* earlier one than the request that set the nonce never replaces it, so a
|
|
115
|
+
* late answer cannot bring an old nonce back, nor make it look new.
|
|
116
|
+
*/
|
|
117
|
+
type Nonces = { value: string | undefined; at: number; seq: number; sent: number };
|
|
118
|
+
/** A request's place in that order, and its time, taken as it goes out. */
|
|
119
|
+
type Sent = { seq: number; at: number };
|
|
120
|
+
const dispatch = (nonces: Nonces): Sent => ({ seq: ++nonces.sent, at: Date.now() });
|
|
121
|
+
|
|
122
|
+
/** How long a nonce is taken as fresh, for a request that cannot be sent again (a stream, a WebSocket's upgrade): under the 2 minutes it lasts. */
|
|
123
|
+
const FRESH_NONCE_MS = 100_000;
|
|
124
|
+
/** How long the exchange waits out a full enrollment code, and a session awaiting approval. */
|
|
125
|
+
const FULL_MS = 5 * 60_000;
|
|
126
|
+
const PENDING_MS = 10 * 60_000;
|
|
127
|
+
/** An enrollment session renews every 30 seconds: its expiry, 90 seconds past its last renewal, is its liveness. */
|
|
128
|
+
const ENROLLMENT_RENEW_MS = 30_000;
|
|
129
|
+
/** Refusals no new proof can change: the code was superseded by a newer deploy's. */
|
|
130
|
+
const FINAL = new Set(['superseded']);
|
|
131
|
+
|
|
132
|
+
/** How long a logout may take: a process stopping waits no longer for it. */
|
|
133
|
+
const LOGOUT_MS = 3000;
|
|
134
|
+
/** The redirects fetch follows, and how many it follows at most. */
|
|
135
|
+
const REDIRECTS = new Set([301, 302, 303, 307, 308]);
|
|
136
|
+
const MOST_REDIRECTS = 20;
|
|
137
|
+
|
|
138
|
+
/** Each session's SIGTERM handler: a process whose every handler is one of these ends on SIGTERM once they have logged out. */
|
|
139
|
+
const TERMINATING = new WeakSet<object>();
|
|
140
|
+
|
|
141
|
+
/** What `upgradeHeaders` and `upgradeRefused` reach, for each workload: its own, never on the object. */
|
|
142
|
+
const UPGRADES = new WeakMap<Workload, { sign: (url: string) => Promise<Record<string, string>>; refused: () => void }>();
|
|
143
|
+
|
|
144
|
+
/**
|
|
145
|
+
* Sign in as `service`, with `proof`, and hold the session for as long as
|
|
146
|
+
* the process runs. Rejects if the first exchange is refused.
|
|
147
|
+
*/
|
|
148
|
+
export async function workload(options: WorkloadOptions): Promise<Workload> {
|
|
149
|
+
const url = new URL(options.url);
|
|
150
|
+
// A proof, a code above all, crosses only TLS, or stays on this machine.
|
|
151
|
+
if (url.protocol !== 'https:' && !(url.protocol === 'http:' && /^(localhost|127(\.\d{1,3}){3}|\[::1\])$/.test(url.hostname))) {
|
|
152
|
+
throw new TypeError(`workload() talks to coffre over https, or http on this machine: not ${url.origin}`);
|
|
153
|
+
}
|
|
154
|
+
const origin = url.origin;
|
|
155
|
+
const base: Fetch = options.fetch ?? ((input, init) => fetch(input, init));
|
|
156
|
+
const log = options.log ?? ((line: string) => console.error(line));
|
|
157
|
+
const key = await generateProofKey();
|
|
158
|
+
/** Aborted by `close()`: an exchange, its waits and its proof's stop with it. */
|
|
159
|
+
const lifetime = new AbortController();
|
|
160
|
+
// A proof's own requests (a metadata server's) end with the session too.
|
|
161
|
+
const proofFetch: ProofContext['fetch'] = (input, init = {}) => base(input, { ...init, signal: init.signal ? anySignal([init.signal, lifetime.signal]) : lifetime.signal });
|
|
162
|
+
const context: ProofContext = { audience: origin, jkt: await thumbprint(key.jwk), fetch: proofFetch, log, signal: lifetime.signal };
|
|
163
|
+
const nonces: Nonces = { value: undefined, at: 0, seq: 0, sent: 0 };
|
|
164
|
+
const enrolled = options.proof.kind === 'enrollment';
|
|
165
|
+
const api = apiOf({ origin, base, key, nonces });
|
|
166
|
+
|
|
167
|
+
/** Trade a fresh proof for a session, waiting out what the design says to wait out; throws a refusal, with the server's words. */
|
|
168
|
+
const exchange = async (): Promise<Session> => {
|
|
169
|
+
const start = Date.now();
|
|
170
|
+
const said = new Set<string>();
|
|
171
|
+
const say = (line: string) => void (said.has(line) || (said.add(line), log(line)));
|
|
172
|
+
for (;;) {
|
|
173
|
+
lifetime.signal.throwIfAborted();
|
|
174
|
+
const proof = await options.proof.prove(context);
|
|
175
|
+
const url = `${origin}/api/auth/workload`;
|
|
176
|
+
const sent = dispatch(nonces);
|
|
177
|
+
const response = await base(url, {
|
|
178
|
+
method: 'POST',
|
|
179
|
+
headers: { 'content-type': 'application/json', accept: 'application/json', dpop: await createProof(key, { method: 'POST', url }) },
|
|
180
|
+
body: JSON.stringify({ service: options.service, proof }),
|
|
181
|
+
signal: lifetime.signal,
|
|
182
|
+
// A proof, a code above all, goes to this URL alone: never where a redirect points.
|
|
183
|
+
redirect: 'error',
|
|
184
|
+
});
|
|
185
|
+
note(nonces, response, sent);
|
|
186
|
+
const body = (await response.json().catch(() => null)) as Record<string, unknown> | null;
|
|
187
|
+
const [expiresAt, notAfter] = [Date.parse(String(body?.expiresAt)), Date.parse(String(body?.notAfter))];
|
|
188
|
+
if (response.status === 200 && typeof body?.token === 'string' && Number.isFinite(expiresAt) && Number.isFinite(notAfter)) {
|
|
189
|
+
const places = Array.isArray(body.places) ? body.places.filter((place): place is string => typeof place === 'string') : [];
|
|
190
|
+
return { token: body.token, expiresAt, notAfter, places, issuedAt: Date.now() };
|
|
191
|
+
}
|
|
192
|
+
const reason = typeof body?.reason === 'string' ? body.reason : undefined;
|
|
193
|
+
if (response.status === 202 && Date.now() - start < PENDING_MS) {
|
|
194
|
+
say(`coffre: ${options.service}'s session waits for a person to approve it${typeof body?.approve === 'string' ? `, at ${body.approve}` : ''}`);
|
|
195
|
+
await sleep(5000, lifetime.signal);
|
|
196
|
+
continue;
|
|
197
|
+
}
|
|
198
|
+
if (response.status === 429 && reason === 'full' && Date.now() - start < FULL_MS) {
|
|
199
|
+
say(`coffre: ${options.service}'s enrollment code holds all the sessions it admits; waiting for one to end, up to 5 minutes`);
|
|
200
|
+
await sleep(retryAfter(response, 30_000), lifetime.signal);
|
|
201
|
+
continue;
|
|
202
|
+
}
|
|
203
|
+
if (reason === 'replayed' && options.proof.spent !== undefined && (await options.proof.spent(context))) continue;
|
|
204
|
+
throw refusal(response.status, body, `${origin} would not sign ${options.service} in with its ${options.proof.name} proof`);
|
|
205
|
+
}
|
|
206
|
+
};
|
|
207
|
+
|
|
208
|
+
let session: Session | null = await exchange();
|
|
209
|
+
if (options.place !== undefined && !session.places.includes(options.place)) {
|
|
210
|
+
throw new Error(`${options.service} reaches ${session.places.join(', ') || 'no environment'}, not ${options.place}`);
|
|
211
|
+
}
|
|
212
|
+
/** The environments of the newest session, kept while a lost one is proved again. */
|
|
213
|
+
let places = session.places;
|
|
214
|
+
/**
|
|
215
|
+
* Every session proved and not past its hard end: a new proof leaves the
|
|
216
|
+
* old one to finish its requests, and close() ends them all, their
|
|
217
|
+
* children with them. Not pruned by their expiry, which a renewal answered
|
|
218
|
+
* late may have pushed on: a session already ended answers 401, which is
|
|
219
|
+
* an end too.
|
|
220
|
+
*/
|
|
221
|
+
let roots: Session[] = [session];
|
|
222
|
+
let closed = false;
|
|
223
|
+
/** The exchange in flight, which requests without a session wait for; and why the last one failed, while none holds. */
|
|
224
|
+
let attempt: Promise<Session> | null = null;
|
|
225
|
+
let failure: unknown = null;
|
|
226
|
+
/** A refusal no new proof can change (a superseded code, a proof given once and spent), once seen. */
|
|
227
|
+
let final: unknown = null;
|
|
228
|
+
let tries = 0;
|
|
229
|
+
/** The renewal in flight for each session: one each, so that an old session's renewal answered late takes no new session's turn. */
|
|
230
|
+
const renewals = new WeakMap<Session, Promise<void>>();
|
|
231
|
+
const timers = { renew: undefined as Timer | undefined, prove: undefined as Timer | undefined, retry: undefined as Timer | undefined };
|
|
232
|
+
const at = (which: keyof typeof timers, when: number, run: () => unknown) => {
|
|
233
|
+
clearTimeout(timers[which]);
|
|
234
|
+
if (closed) return;
|
|
235
|
+
timers[which] = setTimeout(() => void run(), Math.max(0, when - Date.now()));
|
|
236
|
+
(timers[which] as { unref?: () => void }).unref?.();
|
|
237
|
+
};
|
|
238
|
+
|
|
239
|
+
/** Renew at half-life, or every 30 seconds for an enrollment; prove again at 90% of the way to `notAfter`. */
|
|
240
|
+
const plan = (held: Session) => {
|
|
241
|
+
const now = Date.now();
|
|
242
|
+
at('renew', enrolled ? now + ENROLLMENT_RENEW_MS : now + Math.max(1000, (held.expiresAt - now) / 2), renew);
|
|
243
|
+
// An enrollment's `notAfter` is its code's end, which no new proof passes. A projected token's next is written at 80% of its life.
|
|
244
|
+
if (!enrolled) at('prove', held.notAfter - (held.notAfter - held.issuedAt) / 10, () => prove().catch(() => undefined));
|
|
245
|
+
};
|
|
246
|
+
|
|
247
|
+
/** A new session, with a fresh proof and the same key: requests in flight finish on the old one. Retried with backoff while it fails, unless it cannot change. */
|
|
248
|
+
const prove = (): Promise<Session> => {
|
|
249
|
+
// A refusal no new proof changes stands: no later renewal or request asks again.
|
|
250
|
+
if (final !== null) return Promise.reject(final);
|
|
251
|
+
attempt ??= exchange()
|
|
252
|
+
.then((next) => {
|
|
253
|
+
// Closed while it was asked for: it ends now, as the one it replaced did.
|
|
254
|
+
if (closed) {
|
|
255
|
+
void logout(api, next.token).catch(() => undefined);
|
|
256
|
+
throw new Error(`${options.service}'s session with coffre is closed`);
|
|
257
|
+
}
|
|
258
|
+
session = next;
|
|
259
|
+
places = next.places;
|
|
260
|
+
roots = [...roots.filter((root) => root.notAfter > Date.now()), next];
|
|
261
|
+
failure = null;
|
|
262
|
+
tries = 0;
|
|
263
|
+
plan(next);
|
|
264
|
+
return next;
|
|
265
|
+
})
|
|
266
|
+
.catch((error: unknown) => {
|
|
267
|
+
failure = error;
|
|
268
|
+
// A proof spent, from a platform that gives no fresh one (a token given once), is as final as a superseded code.
|
|
269
|
+
const spent = error instanceof CoffreError && error.reason === 'replayed' && options.proof.spent === undefined;
|
|
270
|
+
if (spent) log(`coffre: ${options.service}'s ${options.proof.name} proof was spent, and it gives no fresh one: the session ends at its expiry`);
|
|
271
|
+
if (spent || (error instanceof CoffreError && FINAL.has(error.reason ?? ''))) final = error;
|
|
272
|
+
else if (!closed) at('retry', Date.now() + backoff(tries++), () => prove().catch(() => undefined));
|
|
273
|
+
throw error;
|
|
274
|
+
})
|
|
275
|
+
.finally(() => (attempt = null));
|
|
276
|
+
return attempt;
|
|
277
|
+
};
|
|
278
|
+
|
|
279
|
+
/** Push the session's expiry on; a session coffre no longer renews is lost, and proved again. */
|
|
280
|
+
const renew = (): Promise<void> => {
|
|
281
|
+
const held = session;
|
|
282
|
+
if (held === null || closed) return Promise.resolve();
|
|
283
|
+
const running = renewals.get(held);
|
|
284
|
+
if (running !== undefined) return running;
|
|
285
|
+
const renewal = (async () => {
|
|
286
|
+
try {
|
|
287
|
+
const { response, body } = await api('/api/auth/workload/renew', held.token);
|
|
288
|
+
if (response.ok && typeof body?.expiresAt === 'string') {
|
|
289
|
+
held.expiresAt = Date.parse(body.expiresAt);
|
|
290
|
+
if (session === held) at('renew', enrolled ? Date.now() + ENROLLMENT_RENEW_MS : Date.now() + Math.max(1000, (held.expiresAt - Date.now()) / 2), renew);
|
|
291
|
+
return;
|
|
292
|
+
}
|
|
293
|
+
// Asked for a nonce once more, it says nothing of the session: tried again soon, as when coffre is out of reach.
|
|
294
|
+
if ((response.status !== 401 && response.status !== 403) || askedNonce(response)) throw new Error(`renewal answered ${response.status}`);
|
|
295
|
+
if (session === held) lose();
|
|
296
|
+
} catch {
|
|
297
|
+
// coffre unreachable for now: try again soon, and once the session is gone, prove again.
|
|
298
|
+
if (session !== held) return;
|
|
299
|
+
if (Date.now() >= held.expiresAt) return lose();
|
|
300
|
+
at('renew', Math.min(Date.now() + (enrolled ? 5000 : 30_000), held.expiresAt), renew);
|
|
301
|
+
}
|
|
302
|
+
})().finally(() => renewals.delete(held));
|
|
303
|
+
renewals.set(held, renewal);
|
|
304
|
+
return renewal;
|
|
305
|
+
};
|
|
306
|
+
|
|
307
|
+
const lose = () => {
|
|
308
|
+
if (closed) return;
|
|
309
|
+
session = null;
|
|
310
|
+
clearTimeout(timers.renew);
|
|
311
|
+
clearTimeout(timers.prove);
|
|
312
|
+
prove().catch(() => undefined);
|
|
313
|
+
};
|
|
314
|
+
|
|
315
|
+
/** The session to sign with: the one held, the exchange in flight, or, while exchanges fail, why. */
|
|
316
|
+
const current = async (): Promise<Session> => {
|
|
317
|
+
if (closed) throw new Error(`${options.service}'s session with coffre is closed`);
|
|
318
|
+
// A process frozen past its session's expiry (Lambda between invocations) proves again before its request.
|
|
319
|
+
if (session !== null && Date.now() < session.expiresAt - 5000) return session;
|
|
320
|
+
if (attempt !== null) return attempt;
|
|
321
|
+
if (failure !== null) throw failure;
|
|
322
|
+
return prove();
|
|
323
|
+
};
|
|
324
|
+
|
|
325
|
+
plan(session);
|
|
326
|
+
|
|
327
|
+
const signals = (globalThis as { process?: NodeJS.Process }).process;
|
|
328
|
+
let closing: Promise<void> | null = null;
|
|
329
|
+
// One logout, however many ask for it (the app, and SIGTERM): each waits for it.
|
|
330
|
+
// Rejects if coffre did not confirm every session's end, each asked for at most 3 seconds.
|
|
331
|
+
const close = () =>
|
|
332
|
+
(closing ??= (async () => {
|
|
333
|
+
closed = true;
|
|
334
|
+
lifetime.abort();
|
|
335
|
+
for (const timer of Object.values(timers)) clearTimeout(timer);
|
|
336
|
+
session = null;
|
|
337
|
+
try {
|
|
338
|
+
const ended = await Promise.allSettled(roots.filter((root) => root.notAfter > Date.now()).map((root) => logout(api, root.token)));
|
|
339
|
+
const failed = ended.find((each): each is PromiseRejectedResult => each.status === 'rejected');
|
|
340
|
+
if (failed !== undefined) throw failed.reason;
|
|
341
|
+
} finally {
|
|
342
|
+
// Its handler goes once it has logged out: until then, SIGTERM waits for it.
|
|
343
|
+
signals?.off?.('SIGTERM', onTerm);
|
|
344
|
+
TERMINATING.delete(onTerm);
|
|
345
|
+
}
|
|
346
|
+
})());
|
|
347
|
+
// A graceful stop logs out at once. Where every handler is a session's, the last to log out ends the process with SIGTERM, as it would have ended without them.
|
|
348
|
+
const onTerm = () => {
|
|
349
|
+
const alone = signals!.listeners('SIGTERM').every((listener) => TERMINATING.has(listener));
|
|
350
|
+
void close()
|
|
351
|
+
.catch(() => undefined)
|
|
352
|
+
.finally(() => alone && signals!.listenerCount('SIGTERM') === 0 && signals!.kill(signals!.pid, 'SIGTERM'));
|
|
353
|
+
};
|
|
354
|
+
if (options.sigterm !== false) {
|
|
355
|
+
TERMINATING.add(onTerm);
|
|
356
|
+
signals?.on?.('SIGTERM', onTerm);
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
return surface({
|
|
360
|
+
origin,
|
|
361
|
+
base,
|
|
362
|
+
key,
|
|
363
|
+
nonces,
|
|
364
|
+
api,
|
|
365
|
+
service: options.service,
|
|
366
|
+
place: options.place,
|
|
367
|
+
current,
|
|
368
|
+
places: () => places,
|
|
369
|
+
// A renewal answers the gate's newest nonce, and keeps the session besides.
|
|
370
|
+
refresh: renew,
|
|
371
|
+
close,
|
|
372
|
+
});
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
type Timer = ReturnType<typeof setTimeout>;
|
|
376
|
+
|
|
377
|
+
/** What a session's requests need, a root's or a child's. */
|
|
378
|
+
type Core = {
|
|
379
|
+
origin: string;
|
|
380
|
+
base: Fetch;
|
|
381
|
+
key: ProofKey;
|
|
382
|
+
nonces: Nonces;
|
|
383
|
+
api: Api;
|
|
384
|
+
service: string;
|
|
385
|
+
place: string | undefined;
|
|
386
|
+
current: () => Promise<Session>;
|
|
387
|
+
places: () => string[];
|
|
388
|
+
/** Fetch the gate's newest nonce, for a request that cannot be sent again. */
|
|
389
|
+
refresh: () => Promise<void>;
|
|
390
|
+
close: () => Promise<void>;
|
|
391
|
+
};
|
|
392
|
+
|
|
393
|
+
function surface(core: Core): Workload {
|
|
394
|
+
const { origin, key, nonces } = core;
|
|
395
|
+
const under = (url: string) => {
|
|
396
|
+
try {
|
|
397
|
+
const parsed = new URL(url);
|
|
398
|
+
return parsed.origin === origin && parsed.pathname.startsWith('/use/');
|
|
399
|
+
} catch {
|
|
400
|
+
return false;
|
|
401
|
+
}
|
|
402
|
+
};
|
|
403
|
+
const fresh = async () => {
|
|
404
|
+
if (Date.now() - nonces.at > FRESH_NONCE_MS) await core.refresh().catch(() => undefined);
|
|
405
|
+
};
|
|
406
|
+
|
|
407
|
+
/** A request under `/use/`, signed; or any other, as given. Redirects come back through here, so each hop is signed for itself. */
|
|
408
|
+
const go = async (input: RequestInfo | URL, init: RequestInit | undefined, hops: number): Promise<Response> => {
|
|
409
|
+
const url = input instanceof Request ? input.url : input instanceof URL ? input.href : String(input);
|
|
410
|
+
if (!under(url)) return core.base(input, init);
|
|
411
|
+
// As fetch would send it: the headers fetch adds for its body (a form's content-type) are the app's, and signed.
|
|
412
|
+
const request = new Request(input, init);
|
|
413
|
+
// A request to an AWS-signed credential declares its body's digest, which coffre takes as the body's line, and which S3 checks
|
|
414
|
+
// against the bytes; any other declared value leaves the body unsigned. Only such a request streams; any other body is read whole.
|
|
415
|
+
const declared = request.headers.get('x-amz-content-sha256');
|
|
416
|
+
const streamed = init?.body instanceof ReadableStream || (input instanceof Request && init?.body === undefined);
|
|
417
|
+
const stream = declared !== null && request.body !== null && streamed ? request.body : null;
|
|
418
|
+
const bytes = stream === null && request.body !== null ? new Uint8Array(await request.arrayBuffer()) : null;
|
|
419
|
+
// The body's length as known: the bytes read, or a stream's content-length, which coffre holds it to; none stated, none known.
|
|
420
|
+
const stated = request.headers.get('content-length');
|
|
421
|
+
const length = stream === null ? (bytes?.length ?? 0) : stated !== null && /^\d+$/.test(stated) ? Number(stated) : null;
|
|
422
|
+
const line = await bodyLine({ declared, length, bytes });
|
|
423
|
+
const send = async () => {
|
|
424
|
+
const { token } = await core.current();
|
|
425
|
+
const headers = new Headers(request.headers);
|
|
426
|
+
headers.set('authorization', `DPoP ${token}`);
|
|
427
|
+
headers.set('dpop', await createProof(key, { method: request.method, url: request.url, token, nonce: nonces.value, content: { headers: request.headers, body: line } }));
|
|
428
|
+
const sent = dispatch(nonces);
|
|
429
|
+
const response = await core.base(request.url, {
|
|
430
|
+
method: request.method,
|
|
431
|
+
headers,
|
|
432
|
+
body: stream ?? (bytes as Uint8Array<ArrayBuffer> | null),
|
|
433
|
+
signal: request.signal,
|
|
434
|
+
// A proof signs one URL: fetch following a redirect itself would send it to another.
|
|
435
|
+
redirect: 'manual',
|
|
436
|
+
...(stream === null ? {} : { duplex: 'half' }),
|
|
437
|
+
} as RequestInit);
|
|
438
|
+
note(nonces, response, sent);
|
|
439
|
+
return response;
|
|
440
|
+
};
|
|
441
|
+
let response: Response;
|
|
442
|
+
if (stream !== null) {
|
|
443
|
+
// A stream is sent once: it goes with a nonce fresh enough that the gate takes it.
|
|
444
|
+
await fresh();
|
|
445
|
+
response = await send();
|
|
446
|
+
} else {
|
|
447
|
+
response = await send();
|
|
448
|
+
if (askedNonce(response)) {
|
|
449
|
+
await response.body?.cancel();
|
|
450
|
+
response = await send();
|
|
451
|
+
}
|
|
452
|
+
}
|
|
453
|
+
const location = response.headers.get('location');
|
|
454
|
+
if (request.redirect === 'manual' || !REDIRECTS.has(response.status) || location === null) return response;
|
|
455
|
+
await response.body?.cancel();
|
|
456
|
+
if (request.redirect === 'error') throw new TypeError(`fetch failed: ${request.url} redirects, and redirect is "error"`);
|
|
457
|
+
if (hops >= MOST_REDIRECTS) throw new TypeError(`fetch failed: more than ${MOST_REDIRECTS} redirects`);
|
|
458
|
+
// As fetch follows one: a 303, or a POST's 301 or 302, becomes a GET without its body; a stream cannot be sent again.
|
|
459
|
+
const asGet = (response.status === 303 && request.method !== 'HEAD') || ((response.status === 301 || response.status === 302) && request.method === 'POST');
|
|
460
|
+
if (!asGet && stream !== null) throw new TypeError(`fetch failed: ${request.url} redirects a streamed body, which cannot be sent again`);
|
|
461
|
+
const next = new URL(location, request.url);
|
|
462
|
+
const headers = new Headers(request.headers);
|
|
463
|
+
if (asGet) for (const name of ['content-type', 'content-length', 'content-encoding', 'content-language', 'content-location']) headers.delete(name);
|
|
464
|
+
// As fetch does: credentials the app set go to no other origin.
|
|
465
|
+
if (next.origin !== new URL(request.url).origin) for (const name of ['authorization', 'cookie', 'proxy-authorization']) headers.delete(name);
|
|
466
|
+
// The next hop, signed afresh if it is coffre's, and sent with the app's own headers alone if it is not.
|
|
467
|
+
return go(next, { method: asGet ? 'GET' : request.method, headers, body: asGet ? null : (bytes as Uint8Array<ArrayBuffer> | null), signal: request.signal, redirect: 'follow' }, hops + 1);
|
|
468
|
+
};
|
|
469
|
+
const signed: Fetch = (input, init) => go(input, init, 0);
|
|
470
|
+
|
|
471
|
+
const placeOf = (): string => {
|
|
472
|
+
const places = core.places();
|
|
473
|
+
const place = core.place ?? (places.length === 1 ? places[0] : undefined);
|
|
474
|
+
if (place === undefined) throw new Error(`${core.service} reaches ${places.join(', ') || 'no environment'}: name the one to use, workload({ place })`);
|
|
475
|
+
return place;
|
|
476
|
+
};
|
|
477
|
+
const placeUrl = () => `${origin}/use/${placeOf().split('/').map(encodeURIComponent).join('/')}`;
|
|
478
|
+
const url = (name: string) => (core.places().length === 1 ? `${origin}/use/${encodeURIComponent(name)}` : `${placeUrl()}/${encodeURIComponent(name)}`);
|
|
479
|
+
|
|
480
|
+
/** What coffre makes with the environment's values, at the environment's URL: a signature, a verdict, a presigned URL, a minted child. */
|
|
481
|
+
const compute = async (asked: Record<string, unknown>, what: string): Promise<Record<string, unknown>> => {
|
|
482
|
+
const response = await signed(placeUrl(), { method: 'POST', headers: { 'content-type': 'application/json', accept: 'application/json' }, body: JSON.stringify(asked) });
|
|
483
|
+
const body = (await response.json().catch(() => null)) as Record<string, unknown> | null;
|
|
484
|
+
if (!response.ok || body === null) throw refusal(response.status, body, `coffre ${what} nothing`);
|
|
485
|
+
return body;
|
|
486
|
+
};
|
|
487
|
+
|
|
488
|
+
const workload: Workload = {
|
|
489
|
+
service: core.service,
|
|
490
|
+
get places() {
|
|
491
|
+
return core.places();
|
|
492
|
+
},
|
|
493
|
+
fetch: signed,
|
|
494
|
+
url,
|
|
495
|
+
credential: (name) => ({
|
|
496
|
+
fetch: async (path, init) => {
|
|
497
|
+
// A path stays under its credential: `/../stripe/…`, from an object key or a file name, would otherwise spend another.
|
|
498
|
+
const base = url(name);
|
|
499
|
+
const target = new URL(`${base}${path.startsWith('/') ? '' : '/'}${path}`);
|
|
500
|
+
const under = new URL(base).pathname;
|
|
501
|
+
if (target.pathname !== under && !target.pathname.startsWith(`${under}/`)) throw new TypeError(`${JSON.stringify(path)} leaves ${name}'s URL: a credential's fetch reaches its own upstream only`);
|
|
502
|
+
return signed(target.href, init);
|
|
503
|
+
},
|
|
504
|
+
sign: async (message) => {
|
|
505
|
+
const body = await compute({ sign: { credential: name, message: bytesOf(message) } }, 'signed');
|
|
506
|
+
if (typeof body.signature !== 'string') throw new Error('coffre signed nothing');
|
|
507
|
+
return body.signature;
|
|
508
|
+
},
|
|
509
|
+
verify: async (message, signature) => (await compute({ verify: { credential: name, message: bytesOf(message), signature } }, 'verified')).valid === true,
|
|
510
|
+
presign: async (path, options = {}) => {
|
|
511
|
+
const body = await compute({ presign: { credential: name, path, ...options } }, 'presigned');
|
|
512
|
+
if (typeof body.url !== 'string' || typeof body.expiresAt !== 'string') throw new Error('coffre presigned nothing');
|
|
513
|
+
return { url: body.url, expiresAt: body.expiresAt };
|
|
514
|
+
},
|
|
515
|
+
mint: async <T>() => (await compute({ mint: { credential: name } }, 'minted')) as T & { expiresAt: string },
|
|
516
|
+
}),
|
|
517
|
+
read: async (name) => {
|
|
518
|
+
const response = await signed(placeUrl(), { headers: { accept: 'application/json' } });
|
|
519
|
+
const body = (await response.json().catch(() => null)) as { values?: Record<string, unknown> } | null;
|
|
520
|
+
if (!response.ok) throw refusal(response.status, body as Record<string, unknown> | null, `coffre answered no plan for ${placeOf()}`);
|
|
521
|
+
const value = body?.values?.[name];
|
|
522
|
+
if (typeof value === 'string') return value;
|
|
523
|
+
throw new CoffreError(403, 'forbidden', `${core.service} reads no ${name} in ${placeOf()}: it reads plain values and those its binding lists in reads, and uses every other through coffre`, 'use_only');
|
|
524
|
+
},
|
|
525
|
+
narrow: (async (options: NarrowOptions & { key?: PublicJwk }) => {
|
|
526
|
+
const own = options.key === undefined ? await generateProofKey() : null;
|
|
527
|
+
const { token } = await core.current();
|
|
528
|
+
const { key: given, expiresIn, label, ...constraints } = options;
|
|
529
|
+
const { response, body } = await core.api('/api/auth/workload/narrow', token, { key: given ?? own!.jwk, label, constraints, expiresIn });
|
|
530
|
+
if (!response.ok || typeof body?.token !== 'string' || typeof body.expiresAt !== 'string') throw refusal(response.status, body, `coffre narrowed ${core.service} to nothing`);
|
|
531
|
+
if (own === null) return { token: body.token, expiresAt: body.expiresAt };
|
|
532
|
+
return child(core, own, body.token, Date.parse(body.expiresAt), options.places ?? core.places());
|
|
533
|
+
}) as Workload['narrow'],
|
|
534
|
+
close: core.close,
|
|
535
|
+
};
|
|
536
|
+
UPGRADES.set(workload, {
|
|
537
|
+
sign: async (target) => {
|
|
538
|
+
await fresh();
|
|
539
|
+
const { token } = await core.current();
|
|
540
|
+
const url = target.replace(/^ws/, 'http');
|
|
541
|
+
return { authorization: `DPoP ${token}`, dpop: await createProof(key, { method: 'GET', url, token, nonce: nonces.value }) };
|
|
542
|
+
},
|
|
543
|
+
// When a refusal's nonce came cannot be told against the answers since: the next upgrade asks the gate's newest first.
|
|
544
|
+
refused: () => (nonces.at = 0),
|
|
545
|
+
});
|
|
546
|
+
return workload;
|
|
547
|
+
}
|
|
548
|
+
|
|
549
|
+
/** A narrowed session in this process: its own key, no renewal, and its end its parent's or its own. */
|
|
550
|
+
function child(parent: Core, key: ProofKey, token: string, expiresAt: number, places: string[]): Workload {
|
|
551
|
+
let closed = false;
|
|
552
|
+
let closing: Promise<void> | null = null;
|
|
553
|
+
const held: Session = { token, expiresAt, notAfter: expiresAt, places, issuedAt: Date.now() };
|
|
554
|
+
// Its own proofs, with its own key, at the gate it shares with its parent.
|
|
555
|
+
const api = apiOf({ origin: parent.origin, base: parent.base, key, nonces: parent.nonces });
|
|
556
|
+
return surface({
|
|
557
|
+
...parent,
|
|
558
|
+
key,
|
|
559
|
+
api,
|
|
560
|
+
places: () => places,
|
|
561
|
+
place: parent.place !== undefined && places.includes(parent.place) ? parent.place : undefined,
|
|
562
|
+
current: async () => {
|
|
563
|
+
if (closed || Date.now() >= held.expiresAt) throw new Error(`this narrowed session of ${parent.service} has ended`);
|
|
564
|
+
return held;
|
|
565
|
+
},
|
|
566
|
+
// A child renews nothing: its parent's renewal brings the gate's newest nonce, which they share. A parent that ended ended it too.
|
|
567
|
+
refresh: parent.refresh,
|
|
568
|
+
close: () =>
|
|
569
|
+
(closing ??= (async () => {
|
|
570
|
+
closed = true;
|
|
571
|
+
await logout(api, token);
|
|
572
|
+
})()),
|
|
573
|
+
});
|
|
574
|
+
}
|
|
575
|
+
|
|
576
|
+
/**
|
|
577
|
+
* The headers that sign a WebSocket's upgrade to `url` (a tunnel's), made
|
|
578
|
+
* outside `coffre.fetch`: the session, and a proof of a GET at its `https`
|
|
579
|
+
* form with a nonce fresh enough that the gate takes it, since an upgrade
|
|
580
|
+
* refused cannot be told why and sent again.
|
|
581
|
+
*/
|
|
582
|
+
export function upgradeHeaders(coffre: Workload, url: string): Promise<Record<string, string>> {
|
|
583
|
+
const upgrade = UPGRADES.get(coffre);
|
|
584
|
+
if (upgrade === undefined) throw new TypeError('upgradeHeaders takes a workload() session');
|
|
585
|
+
return upgrade.sign(url);
|
|
586
|
+
}
|
|
587
|
+
|
|
588
|
+
/**
|
|
589
|
+
* Say that coffre refused an upgrade, or that it never opened: its nonce may
|
|
590
|
+
* be the gate's no longer, so the next upgrade, which cannot be sent again
|
|
591
|
+
* either, first asks for the newest.
|
|
592
|
+
*/
|
|
593
|
+
export function upgradeRefused(coffre: Workload): void {
|
|
594
|
+
UPGRADES.get(coffre)?.refused();
|
|
595
|
+
}
|
|
596
|
+
|
|
597
|
+
/**
|
|
598
|
+
* An AWS SDK credential provider over delivered minting (section 7.2): a
|
|
599
|
+
* minter's short-lived children, where the binding lists it, each kept
|
|
600
|
+
* until a minute before it expires.
|
|
601
|
+
*
|
|
602
|
+
* const s3 = new S3Client({ region: 'eu-west-3', credentials: fromCoffre(coffre, 'aws') });
|
|
603
|
+
*/
|
|
604
|
+
export function fromCoffre(coffre: Workload, minter: string): () => Promise<{ accessKeyId: string; secretAccessKey: string; sessionToken?: string; expiration: Date }> {
|
|
605
|
+
let held: { value: { accessKeyId: string; secretAccessKey: string; sessionToken?: string; expiration: Date }; until: number } | null = null;
|
|
606
|
+
return async () => {
|
|
607
|
+
if (held !== null && Date.now() < held.until) return held.value;
|
|
608
|
+
const minted = await coffre.credential(minter).mint<{ accessKeyId: string; secretAccessKey: string; sessionToken?: string }>();
|
|
609
|
+
if (typeof minted.accessKeyId !== 'string' || typeof minted.secretAccessKey !== 'string') throw new Error(`${minter} minted no AWS credentials`);
|
|
610
|
+
const expiration = new Date(minted.expiresAt);
|
|
611
|
+
held = { value: { accessKeyId: minted.accessKeyId, secretAccessKey: minted.secretAccessKey, sessionToken: minted.sessionToken, expiration }, until: expiration.getTime() - 60_000 };
|
|
612
|
+
return held.value;
|
|
613
|
+
};
|
|
614
|
+
}
|
|
615
|
+
|
|
616
|
+
/** Keep the gate's newest nonce: every answer from coffre carries it, and the newest is the one to a request sent last. */
|
|
617
|
+
function note(nonces: Nonces, response: { headers: { get(name: string): string | null } }, sent: Sent): void {
|
|
618
|
+
const nonce = response.headers.get('dpop-nonce');
|
|
619
|
+
if (nonce !== null && nonce !== '' && sent.seq > nonces.seq) {
|
|
620
|
+
nonces.value = nonce;
|
|
621
|
+
nonces.at = sent.at;
|
|
622
|
+
nonces.seq = sent.seq;
|
|
623
|
+
}
|
|
624
|
+
}
|
|
625
|
+
|
|
626
|
+
/** A POST to coffre's own API with a session (renew, narrow, logout), signed by its key. */
|
|
627
|
+
type Api = (path: string, token: string, body?: unknown, signal?: AbortSignal) => Promise<{ response: Response; body: Record<string, unknown> | null }>;
|
|
628
|
+
|
|
629
|
+
/**
|
|
630
|
+
* Its proof signs the token and the newest nonce, and a body where there is
|
|
631
|
+
* one (`hdr` and `req`: narrow's, the key and the limits it gives a child),
|
|
632
|
+
* so no one who sees the request can make it say anything else; sent again
|
|
633
|
+
* once if the gate asks for a fresh nonce.
|
|
634
|
+
*/
|
|
635
|
+
function apiOf({ origin, base, key, nonces }: { origin: string; base: Fetch; key: ProofKey; nonces: Nonces }): Api {
|
|
636
|
+
return async (path, token, body, signal) => {
|
|
637
|
+
const url = `${origin}${path}`;
|
|
638
|
+
const json = body === undefined ? undefined : JSON.stringify(body);
|
|
639
|
+
const headers = { accept: 'application/json', ...(json === undefined ? {} : { 'content-type': 'application/json' }) };
|
|
640
|
+
const content = json === undefined ? undefined : { headers, body: await bodyDigest(json) };
|
|
641
|
+
const send = async () => {
|
|
642
|
+
const sent = dispatch(nonces);
|
|
643
|
+
const response = await base(url, {
|
|
644
|
+
method: 'POST',
|
|
645
|
+
headers: { ...headers, authorization: `DPoP ${token}`, dpop: await createProof(key, { method: 'POST', url, token, nonce: nonces.value, content }) },
|
|
646
|
+
body: json,
|
|
647
|
+
signal,
|
|
648
|
+
redirect: 'error',
|
|
649
|
+
});
|
|
650
|
+
note(nonces, response, sent);
|
|
651
|
+
return response;
|
|
652
|
+
};
|
|
653
|
+
let response = await send();
|
|
654
|
+
if (askedNonce(response)) {
|
|
655
|
+
await response.body?.cancel();
|
|
656
|
+
response = await send();
|
|
657
|
+
}
|
|
658
|
+
return { response, body: (await response.json().catch(() => null)) as Record<string, unknown> | null };
|
|
659
|
+
};
|
|
660
|
+
}
|
|
661
|
+
|
|
662
|
+
/** End a session, waiting 3 seconds at most; rejects unless coffre says it ended, or had already (401). */
|
|
663
|
+
async function logout(api: Api, token: string): Promise<void> {
|
|
664
|
+
const { response, body } = await api('/api/auth/logout', token, undefined, AbortSignal.timeout(LOGOUT_MS));
|
|
665
|
+
// A 401 says the session is over, unless it asks for a nonce yet again: then nothing ended.
|
|
666
|
+
if (!response.ok && (response.status !== 401 || askedNonce(response))) throw refusal(response.status, body, 'coffre did not end the session');
|
|
667
|
+
}
|
|
668
|
+
|
|
669
|
+
/** Whether coffre refused a proof for its nonce alone (RFC 9449, section 8): sent again once, with the nonce it gave. */
|
|
670
|
+
function askedNonce(response: Response): boolean {
|
|
671
|
+
return response.status === 401 && /error="?use_dpop_nonce/.test(response.headers.get('www-authenticate') ?? '') && response.headers.has('dpop-nonce');
|
|
672
|
+
}
|
|
673
|
+
|
|
674
|
+
function refusal(status: number, body: Record<string, unknown> | null, what: string): CoffreError {
|
|
675
|
+
const reason = typeof body?.reason === 'string' ? body.reason : undefined;
|
|
676
|
+
const message = typeof body?.message === 'string' ? body.message : `status ${status}`;
|
|
677
|
+
return new CoffreError(status, typeof body?.error === 'string' ? body.error : 'refused', `${what}${reason === undefined ? '' : ` (${reason})`}: ${message}`, reason);
|
|
678
|
+
}
|
|
679
|
+
|
|
680
|
+
/** `Retry-After`, in milliseconds, or `fallback`. */
|
|
681
|
+
function retryAfter(response: Response, fallback: number): number {
|
|
682
|
+
const seconds = Number(response.headers.get('retry-after'));
|
|
683
|
+
return Number.isFinite(seconds) && seconds > 0 ? Math.min(seconds, 300) * 1000 : fallback;
|
|
684
|
+
}
|
|
685
|
+
|
|
686
|
+
/** 1, 2, 4… seconds, at most a minute, a little jittered so that a fleet's replicas spread out. */
|
|
687
|
+
function backoff(tries: number): number {
|
|
688
|
+
return Math.min(60_000, 1000 * 2 ** tries) * (0.75 + Math.random() / 2);
|
|
689
|
+
}
|
|
690
|
+
|
|
691
|
+
/** A message as coffre's `sign` and `verify` take it: a string's UTF-8, base64url. */
|
|
692
|
+
const bytesOf = (message: string | Uint8Array) => base64url(typeof message === 'string' ? new TextEncoder().encode(message) : message);
|
|
693
|
+
|
|
694
|
+
/** A signal that aborts with the first of `signals`: `AbortSignal.any`, where the runtime has it (Node 20.3 and later). */
|
|
695
|
+
function anySignal(signals: AbortSignal[]): AbortSignal {
|
|
696
|
+
if (typeof AbortSignal.any === 'function') return AbortSignal.any(signals);
|
|
697
|
+
const controller = new AbortController();
|
|
698
|
+
for (const signal of signals) {
|
|
699
|
+
if (signal.aborted) controller.abort(signal.reason);
|
|
700
|
+
else signal.addEventListener('abort', () => controller.abort(signal.reason), { once: true });
|
|
701
|
+
}
|
|
702
|
+
return controller.signal;
|
|
703
|
+
}
|
|
704
|
+
|
|
705
|
+
/** A wait that `signal` ends early, rejecting. */
|
|
706
|
+
const sleep = (ms: number, signal: AbortSignal) =>
|
|
707
|
+
new Promise<void>((resolve, reject) => {
|
|
708
|
+
const timer = setTimeout(() => (signal.removeEventListener('abort', stop), resolve()), ms);
|
|
709
|
+
const stop = () => (clearTimeout(timer), reject(signal.reason as Error));
|
|
710
|
+
signal.addEventListener('abort', stop, { once: true });
|
|
711
|
+
});
|