@nodii/dev 0.6.10 → 0.6.11
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +8 -1
- package/bin/nodii-dev +11 -1
- package/dist/core.js +1 -1
- package/dist/oauth.js +163 -28
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -29,7 +29,14 @@ every nodii-dev process on the machine shares it instead of refreshing on each
|
|
|
29
29
|
run; refreshes take turns under a per-user lock. A refresh clears the saved
|
|
30
30
|
sign-in only when nodii-auth answers `invalid_grant` (expired, revoked or
|
|
31
31
|
replayed). A 429, 5xx, timeout, network error or proxy error page keeps it and
|
|
32
|
-
fails with `OAUTH_REFRESH_UNAVAILABLE` (exit 1)
|
|
32
|
+
fails with `OAUTH_REFRESH_UNAVAILABLE` (exit 1). Only answers that show the
|
|
33
|
+
token was not used are retried at once (a connection that never opened, 429,
|
|
34
|
+
500, 503, a proxy's non-JSON 4xx). After a timeout, a dropped connection, a
|
|
35
|
+
gateway timeout or a 2xx without tokens, nodii-auth may already have rotated
|
|
36
|
+
the token; it is not sent again by that command, though the next one will
|
|
37
|
+
present it, and a rotation whose answer was lost does end the sign-in.
|
|
38
|
+
SIGINT, SIGTERM and SIGHUP wait while a token is in flight and until its
|
|
39
|
+
successor is stored. Every API
|
|
33
40
|
call goes to the edge's `/devops` prefix with the OAuth bearer and the
|
|
34
41
|
registered `x-agent-id`; signing in again as the same person keeps that
|
|
35
42
|
registration. `logout` revokes the refresh chain before erasing local
|
package/bin/nodii-dev
CHANGED
|
@@ -7,6 +7,16 @@ while [ -L "$self" ]; do
|
|
|
7
7
|
link=$(readlink "$self")
|
|
8
8
|
case "$link" in /*) self="$link" ;; *) self="$(dirname "$self")/$link" ;; esac
|
|
9
9
|
done
|
|
10
|
-
|
|
10
|
+
root="$(cd "$(dirname "$self")/.." && pwd)"
|
|
11
|
+
entry="$root/dist/nodii-dev.js"
|
|
12
|
+
# A checkout's own build can be older than its package.json (Dev issue 88: a
|
|
13
|
+
# stale 0.3.1 build once answered `npx @nodii/dev@0.6.10` inside a nodii-clis
|
|
14
|
+
# worktree). Refuse to run one.
|
|
15
|
+
built=$(sed -n 's/^export const VERSION = "\(.*\)";$/\1/p' "$root/dist/core.js" 2>/dev/null)
|
|
16
|
+
wanted=$(sed -n 's/^ "version": "\(.*\)",$/\1/p' "$root/package.json" 2>/dev/null)
|
|
17
|
+
if [ -n "$built" ] && [ -n "$wanted" ] && [ "$built" != "$wanted" ]; then
|
|
18
|
+
echo "nodii-dev: the build at $root is $built but its package.json says $wanted. Run 'npm run build' there, or run npx outside the nodii-clis repo." >&2
|
|
19
|
+
exit 2
|
|
20
|
+
fi
|
|
11
21
|
if command -v bun >/dev/null 2>&1; then exec bun "$entry" "$@"; fi
|
|
12
22
|
exec node "$entry" "$@"
|
package/dist/core.js
CHANGED
|
@@ -4,7 +4,7 @@ import { chmod, mkdir, readFile, rm, writeFile } from "node:fs/promises";
|
|
|
4
4
|
import { homedir, platform } from "node:os";
|
|
5
5
|
import { dirname, join } from "node:path";
|
|
6
6
|
|
|
7
|
-
export const VERSION = "0.6.
|
|
7
|
+
export const VERSION = "0.6.11";
|
|
8
8
|
export const configPath = () =>
|
|
9
9
|
process.env.NODII_DEV_CONFIG_PATH ??
|
|
10
10
|
join(homedir(), ".config/nodii-dev/config.json");
|
package/dist/oauth.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { spawn } from "node:child_process";
|
|
2
|
-
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
3
3
|
import { mkdir, open, readFile, rm, stat, utimes } from "node:fs/promises";
|
|
4
4
|
import { homedir, platform } from "node:os";
|
|
5
5
|
import { dirname, join } from "node:path";
|
|
@@ -45,73 +45,159 @@ function run(command, args, { input } = {}) {
|
|
|
45
45
|
});
|
|
46
46
|
}
|
|
47
47
|
|
|
48
|
-
|
|
48
|
+
// `security -i` reads each command line into a 4096-byte buffer. A longer line
|
|
49
|
+
// is cut there: the item is stored TRUNCATED and the rest of the line runs as a
|
|
50
|
+
// second, failing command (Dev issue 88: the access-token cache, once the
|
|
51
|
+
// JWT outgrew 4 KB, was stored cut short, every process read it as empty, and
|
|
52
|
+
// every command rotated the shared refresh token). Lines stay well under it.
|
|
53
|
+
export const SECURITY_LINE_MAX = 4000;
|
|
54
|
+
// A secret longer than one line is stored in parts, then a header naming the
|
|
55
|
+
// part count and the digest of the whole; a reader that sees a torn or partial
|
|
56
|
+
// set (a writer mid-way) gets nothing rather than a wrong secret.
|
|
57
|
+
const MAX_PARTS = 64;
|
|
58
|
+
const CHUNKED = "chunked:v1:";
|
|
59
|
+
const TOKEN_ALPHABET = /^[A-Za-z0-9._~+/=-]+$/;
|
|
60
|
+
const part = (name, i) => `${name}:part:${i}`;
|
|
61
|
+
const sha256 = (value) => createHash("sha256").update(value).digest("hex");
|
|
62
|
+
const addLine = (name, svc, secret) => `add-generic-password -U -a ${name} -s ${svc} -w ${secret}`;
|
|
63
|
+
// Whether `security -i` takes the secret whole on one stdin line.
|
|
64
|
+
const fitsOneLine = (name, svc, secret) => TOKEN_ALPHABET.test(secret) && addLine(name, svc, secret).length <= SECURITY_LINE_MAX;
|
|
65
|
+
const checkName = (name) => {
|
|
66
|
+
if (!/^[A-Za-z0-9_.:-]+$/.test(name)) throw new CliError("KEYCHAIN_UNAVAILABLE", "The OAuth client id has characters the Keychain helper cannot take; nothing was stored.", 2);
|
|
67
|
+
};
|
|
68
|
+
|
|
69
|
+
async function keychainPut(name, secret, os, { exec, svc }) {
|
|
49
70
|
if (os === "darwin") {
|
|
50
|
-
|
|
71
|
+
checkName(name);
|
|
51
72
|
// Through `security -i` on stdin, so the secret never appears in argv
|
|
52
73
|
// (visible to `ps`). The interactive parser splits on whitespace and reads
|
|
53
74
|
// quotes, so a secret outside a token's own alphabet falls back to argv
|
|
54
75
|
// rather than being dropped (it may be a refresh token just rotated).
|
|
55
|
-
if (
|
|
56
|
-
else await
|
|
76
|
+
if (fitsOneLine(name, svc, secret)) await exec("security", ["-i"], { input: `${addLine(name, svc, secret)}\n` });
|
|
77
|
+
else await exec("security", ["add-generic-password", "-U", "-a", name, "-s", svc, "-w", secret]);
|
|
57
78
|
return "macOS Keychain";
|
|
58
79
|
}
|
|
59
80
|
if (os === "linux") {
|
|
60
81
|
try {
|
|
61
|
-
await
|
|
82
|
+
await exec("secret-tool", ["store", "--label=nodii-dev OAuth", "service", svc, "account", name], { input: secret });
|
|
62
83
|
return "Secret Service";
|
|
63
84
|
} catch {}
|
|
64
85
|
}
|
|
65
86
|
throw new CliError("KEYCHAIN_UNAVAILABLE", "OAuth refresh tokens require macOS Keychain or Linux Secret Service. No credential was stored; re-run login when a keychain is available.", 2);
|
|
66
87
|
}
|
|
67
88
|
|
|
68
|
-
async function
|
|
69
|
-
if (os === "darwin") return (await
|
|
70
|
-
if (os === "linux") return (await
|
|
89
|
+
async function keychainGet(name, os, { exec, svc }) {
|
|
90
|
+
if (os === "darwin") return (await exec("security", ["find-generic-password", "-a", name, "-s", svc, "-w"])).trim();
|
|
91
|
+
if (os === "linux") return (await exec("secret-tool", ["lookup", "service", svc, "account", name])).trim();
|
|
71
92
|
throw new Error("no keychain");
|
|
72
93
|
}
|
|
73
94
|
|
|
74
|
-
async function
|
|
95
|
+
async function removeItem(name, os, { exec, svc }) {
|
|
75
96
|
try {
|
|
76
|
-
if (os === "darwin") await
|
|
77
|
-
else if (os === "linux") await
|
|
78
|
-
|
|
97
|
+
if (os === "darwin") await exec("security", ["delete-generic-password", "-a", name, "-s", svc]);
|
|
98
|
+
else if (os === "linux") await exec("secret-tool", ["clear", "service", svc, "account", name]);
|
|
99
|
+
return true;
|
|
100
|
+
} catch {
|
|
101
|
+
return false;
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
// Parts are numbered from 1 without gaps, so the first one missing ends the
|
|
106
|
+
// sweep, whatever header (or none) the parts were written under.
|
|
107
|
+
async function removeParts(name, from, os, kc) {
|
|
108
|
+
if (os !== "darwin") return;
|
|
109
|
+
for (let i = from; i <= MAX_PARTS && (await removeItem(part(name, i), os, kc)); i++);
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
export async function keychainStore(name, secret, os = platform(), { exec = run, svc = service } = {}) {
|
|
113
|
+
const kc = { exec, svc };
|
|
114
|
+
if (os !== "darwin" || !TOKEN_ALPHABET.test(secret) || fitsOneLine(name, svc, secret)) {
|
|
115
|
+
const stored = await keychainPut(name, secret, os, kc);
|
|
116
|
+
await removeParts(name, 1, os, kc);
|
|
117
|
+
return stored;
|
|
118
|
+
}
|
|
119
|
+
checkName(name);
|
|
120
|
+
const size = SECURITY_LINE_MAX - addLine(part(name, MAX_PARTS), svc, "").length;
|
|
121
|
+
const parts = [];
|
|
122
|
+
if (size >= 256) for (let i = 0; i < secret.length && parts.length <= MAX_PARTS; i += size) parts.push(secret.slice(i, i + size));
|
|
123
|
+
if (!parts.length || parts.length > MAX_PARTS) throw new CliError("KEYCHAIN_UNAVAILABLE", "The secret is too long for the Keychain helper; nothing was stored.", 2);
|
|
124
|
+
// The parts in one `security` run, then, only once they are all in, the
|
|
125
|
+
// header that names them (`security -i` goes on past a failed line).
|
|
126
|
+
await exec("security", ["-i"], { input: `${parts.map((chunk, i) => addLine(part(name, i + 1), svc, chunk)).join("\n")}\n` });
|
|
127
|
+
await exec("security", ["-i"], { input: `${addLine(name, svc, `${CHUNKED}${parts.length}:${sha256(secret)}`)}\n` });
|
|
128
|
+
await removeParts(name, parts.length + 1, os, kc);
|
|
129
|
+
return "macOS Keychain";
|
|
79
130
|
}
|
|
80
131
|
|
|
81
|
-
export async function
|
|
82
|
-
|
|
132
|
+
export async function keychainLoad(name, os = platform(), { exec = run, svc = service } = {}) {
|
|
133
|
+
const value = await keychainGet(name, os, { exec, svc });
|
|
134
|
+
if (!value.startsWith(CHUNKED)) return value;
|
|
135
|
+
const [count, digest] = value.slice(CHUNKED.length).split(":");
|
|
136
|
+
const n = Number.parseInt(count, 10);
|
|
137
|
+
if (!Number.isInteger(n) || n < 1 || n > MAX_PARTS) throw new Error("bad chunk header");
|
|
138
|
+
let secret = "";
|
|
139
|
+
for (let i = 1; i <= n; i++) secret += await keychainGet(part(name, i), os, { exec, svc });
|
|
140
|
+
if (sha256(secret) !== digest) throw new Error("chunks do not match their header");
|
|
141
|
+
return secret;
|
|
83
142
|
}
|
|
84
143
|
|
|
85
|
-
export async function
|
|
144
|
+
export async function keychainDelete(name, os = platform(), { exec = run, svc = service } = {}) {
|
|
145
|
+
const kc = { exec, svc };
|
|
146
|
+
await removeItem(name, os, kc);
|
|
147
|
+
await removeParts(name, 1, os, kc);
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
// Read back after writing: a store that "succeeds" but keeps something else (a
|
|
151
|
+
// truncated write) loses the rotated token, and the next refresh replays the
|
|
152
|
+
// old one, which revokes the whole chain.
|
|
153
|
+
export async function storeRefreshToken(clientId, token, os = platform(), keychain = {}) {
|
|
154
|
+
const stored = await keychainStore(account(clientId), token, os, keychain);
|
|
155
|
+
if ((await keychainLoad(account(clientId), os, keychain).catch(() => null)) !== token)
|
|
156
|
+
throw new CliError("KEYCHAIN_WRITE_FAILED", "The refresh token read back from the keychain differs from the one written.", 1);
|
|
157
|
+
return stored;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
export async function loadRefreshToken(clientId, os = platform(), keychain = {}) {
|
|
86
161
|
try {
|
|
87
|
-
const token = await keychainLoad(account(clientId), os);
|
|
162
|
+
const token = await keychainLoad(account(clientId), os, keychain);
|
|
88
163
|
if (token) return token;
|
|
89
164
|
} catch {}
|
|
90
165
|
throw new CliError("OAUTH_LOGIN_REQUIRED", "OAuth credentials are unavailable; run `nodii-dev login` again.", 2);
|
|
91
166
|
}
|
|
92
167
|
|
|
93
|
-
export async function deleteRefreshToken(clientId, os = platform()) {
|
|
94
|
-
await keychainDelete(account(clientId), os);
|
|
168
|
+
export async function deleteRefreshToken(clientId, os = platform(), keychain = {}) {
|
|
169
|
+
await keychainDelete(account(clientId), os, keychain);
|
|
95
170
|
}
|
|
96
171
|
|
|
97
172
|
// The access token is cached beside the refresh token so that every nodii-dev
|
|
98
173
|
// process on the machine shares one: without it each command rotated the
|
|
99
174
|
// refresh token, and N lanes rotated it N times as often.
|
|
100
|
-
export async function loadAccessToken(clientId, os = platform()) {
|
|
175
|
+
export async function loadAccessToken(clientId, os = platform(), keychain = {}) {
|
|
101
176
|
try {
|
|
102
|
-
const cached = JSON.parse(Buffer.from(await keychainLoad(accessAccount(clientId), os), "base64url").toString("utf8"));
|
|
177
|
+
const cached = JSON.parse(Buffer.from(await keychainLoad(accessAccount(clientId), os, keychain), "base64url").toString("utf8"));
|
|
103
178
|
return typeof cached?.token === "string" && Number.isFinite(cached.expiresAt) ? cached : null;
|
|
104
179
|
} catch {
|
|
105
180
|
return null;
|
|
106
181
|
}
|
|
107
182
|
}
|
|
108
183
|
|
|
109
|
-
|
|
110
|
-
|
|
184
|
+
let cacheWarned = false;
|
|
185
|
+
|
|
186
|
+
// A cache that cannot be written is not fatal to this command, but every other
|
|
187
|
+
// process would then refresh too, so it is said once, on stderr.
|
|
188
|
+
export async function storeAccessToken(clientId, cached, os = platform(), keychain = {}) {
|
|
189
|
+
const value = Buffer.from(JSON.stringify(cached)).toString("base64url");
|
|
190
|
+
try {
|
|
191
|
+
await keychainStore(accessAccount(clientId), value, os, keychain);
|
|
192
|
+
if ((await keychainLoad(accessAccount(clientId), os, keychain)) === value) return;
|
|
193
|
+
} catch {}
|
|
194
|
+
if (cacheWarned) return;
|
|
195
|
+
cacheWarned = true;
|
|
196
|
+
process.stderr.write("nodii-dev: warning: the access token could not be cached in the keychain, so every nodii-dev process will refresh the sign-in.\n");
|
|
111
197
|
}
|
|
112
198
|
|
|
113
|
-
export async function deleteAccessToken(clientId, os = platform()) {
|
|
114
|
-
await keychainDelete(accessAccount(clientId), os);
|
|
199
|
+
export async function deleteAccessToken(clientId, os = platform(), keychain = {}) {
|
|
200
|
+
await keychainDelete(accessAccount(clientId), os, keychain);
|
|
115
201
|
}
|
|
116
202
|
|
|
117
203
|
async function oauthPost(authUrl, path, fields, fetchImpl = fetch, timeoutMs = REFRESH_TIMEOUT_MS) {
|
|
@@ -326,7 +412,10 @@ export async function withRefreshLock(fn, { clientId, path = refreshLockPath(cli
|
|
|
326
412
|
// grant, so the credential is kept.
|
|
327
413
|
const DEAD_GRANT_ERRORS = new Set(["invalid_grant", "expired_token", "token_revoked"]);
|
|
328
414
|
const RETRYABLE_STATUS = new Set([408, 425, 429, 500, 502, 503, 504]);
|
|
329
|
-
|
|
415
|
+
// A refresh is never cut off early: once the request is sent, nodii-auth may
|
|
416
|
+
// rotate the token whether or not the answer arrives, so aborting it at 10 s
|
|
417
|
+
// lost the successor and the next run replayed the old token (Dev issue 88).
|
|
418
|
+
export const REFRESH_TIMEOUT_MS = 20_000;
|
|
330
419
|
const REFRESH_ATTEMPTS = 4;
|
|
331
420
|
const RETRY_AFTER_CAP_MS = 5_000;
|
|
332
421
|
// The whole refresh, retries included, fits well inside the lock's wait
|
|
@@ -353,7 +442,10 @@ async function postRefresh(authUrl, clientId, refreshToken, fetchImpl, timeoutMs
|
|
|
353
442
|
signal: AbortSignal.timeout(timeoutMs),
|
|
354
443
|
});
|
|
355
444
|
} catch (error) {
|
|
356
|
-
|
|
445
|
+
// Only a connection that never opened is known not to have reached the
|
|
446
|
+
// server; a timeout or a dropped connection may follow a rotation.
|
|
447
|
+
const reason = error?.name === "TimeoutError" ? "timeout" : UNSENT_CODES.has(error?.cause?.code ?? error?.code) ? "unsent" : "unreachable";
|
|
448
|
+
return { ok: false, status: 0, body: {}, json: false, reason };
|
|
357
449
|
}
|
|
358
450
|
let raw = "";
|
|
359
451
|
try { raw = await response.text(); } catch {}
|
|
@@ -364,12 +456,44 @@ async function postRefresh(authUrl, clientId, refreshToken, fetchImpl, timeoutMs
|
|
|
364
456
|
return { ok: response.ok, status: response.status, body, json, retryAfterMs: Number.isFinite(retryAfter) ? retryAfter * 1000 : undefined };
|
|
365
457
|
}
|
|
366
458
|
|
|
459
|
+
// Node's (undici) and Bun's codes for a connection that never opened.
|
|
460
|
+
const UNSENT_CODES = new Set(["ECONNREFUSED", "ENOTFOUND", "EAI_AGAIN", "EHOSTUNREACH", "ENETUNREACH", "UND_ERR_CONNECT_TIMEOUT", "ConnectionRefused", "FailedToOpenSocket"]);
|
|
461
|
+
// The answers that show the token was not used, so it may be sent again: the
|
|
462
|
+
// edge's rate limit, nodii-auth failing before it commits (500, 503), and a
|
|
463
|
+
// non-JSON 4xx (a proxy or WAF refusing before nodii-auth; it answers JSON).
|
|
464
|
+
// Anything else that is not an answer (a gateway timeout, a 2xx without
|
|
465
|
+
// tokens, an HTML page) may follow a rotation, and is not sent again here.
|
|
466
|
+
const RESEND_STATUS = new Set([429, 500, 503]);
|
|
467
|
+
const mayResend = (result) => (result.status === 0 ? result.reason === "unsent" : RESEND_STATUS.has(result.status) || (result.status >= 400 && result.status < 500 && !result.json));
|
|
468
|
+
|
|
469
|
+
// From the moment a refresh token is presented until its successor is stored,
|
|
470
|
+
// the process must not die: nodii-auth has already marked the old token used,
|
|
471
|
+
// so losing the new one means the next refresh replays the old one and the
|
|
472
|
+
// server revokes the whole chain, signing out every process on the machine.
|
|
473
|
+
// SIGINT, SIGTERM and SIGHUP are held over that window and re-raised on
|
|
474
|
+
// release, which comes after the refresh lock is let go. SIGHUP is re-raised
|
|
475
|
+
// only with a terminal attached: under nohup (no terminal) it was meant to be
|
|
476
|
+
// ignored, and re-raising it would kill what nohup kept alive.
|
|
477
|
+
export function holdSignals() {
|
|
478
|
+
const signals = ["SIGINT", "SIGTERM", "SIGHUP"];
|
|
479
|
+
let caught = null;
|
|
480
|
+
const hold = (signal) => { caught ??= signal; };
|
|
481
|
+
for (const signal of signals) process.on(signal, hold);
|
|
482
|
+
return {
|
|
483
|
+
release() {
|
|
484
|
+
for (const signal of signals) process.off(signal, hold);
|
|
485
|
+
if (caught && (caught !== "SIGHUP" || process.stdin.isTTY || process.stdout.isTTY)) process.kill(process.pid, caught);
|
|
486
|
+
},
|
|
487
|
+
};
|
|
488
|
+
}
|
|
489
|
+
|
|
367
490
|
const describe = (result) => result.status === 0 ? (result.reason === "timeout" ? "timed out" : "nodii-auth unreachable") : `HTTP ${result.status}${result.json && typeof result.body.error === "string" ? ` ${result.body.error}` : ""}`;
|
|
368
491
|
|
|
369
492
|
export class OAuthAuthProvider {
|
|
370
493
|
#accessToken;
|
|
371
494
|
#expiresAt = 0;
|
|
372
495
|
#refreshPromise;
|
|
496
|
+
#signals;
|
|
373
497
|
constructor({ fetchImpl = fetch, loadToken = loadRefreshToken, storeToken = storeRefreshToken, deleteToken = deleteRefreshToken, lock = withRefreshLock,
|
|
374
498
|
loadAccess, storeAccess, deleteAccess, sleep = wait, timeoutMs = REFRESH_TIMEOUT_MS, budgetMs = REFRESH_BUDGET_MS } = {}) {
|
|
375
499
|
// Injected token storage (tests) gets no shared access cache unless one is
|
|
@@ -397,7 +521,7 @@ export class OAuthAuthProvider {
|
|
|
397
521
|
// rotated the refresh token and cached the access token it got.
|
|
398
522
|
if (this.#usable(await this.loadAccess(config.clientId))) return this.#accessToken;
|
|
399
523
|
return this.#refresh(config, held ?? (async () => true));
|
|
400
|
-
}, { clientId: config.clientId });
|
|
524
|
+
}, { clientId: config.clientId }).finally(() => this.#release());
|
|
401
525
|
})().finally(() => { this.#refreshPromise = undefined; });
|
|
402
526
|
return this.#refreshPromise;
|
|
403
527
|
}
|
|
@@ -409,9 +533,15 @@ export class OAuthAuthProvider {
|
|
|
409
533
|
// Never present the refresh token without the lock: a second holder
|
|
410
534
|
// would present the same one, and the server revokes the chain on reuse.
|
|
411
535
|
if (!(await held())) throw new CliError("OAUTH_REFRESH_BUSY", "Lost the refresh lock to another nodii-dev process; the saved sign-in was kept. Retry the command.", 1);
|
|
536
|
+
// Signals wait while a token is in flight; on success, until it is stored.
|
|
537
|
+
this.#signals ??= holdSignals();
|
|
412
538
|
result = await postRefresh(config.authUrl, config.clientId, refresh, this.fetchImpl, Math.max(floor, Math.min(this.timeoutMs, deadline - Date.now())));
|
|
413
539
|
const kind = classifyRefresh(result);
|
|
540
|
+
if (kind !== "ok") this.#release();
|
|
414
541
|
if (kind !== "retry" || attempt >= REFRESH_ATTEMPTS) return { kind, result, attempts: attempt };
|
|
542
|
+
// A request that may have reached the server is not sent again with the
|
|
543
|
+
// same token: if it was rotated, that is a replay and revokes the chain.
|
|
544
|
+
if (!mayResend(result)) return { kind, result, attempts: attempt };
|
|
415
545
|
const backoff = 500 * 2 ** (attempt - 1) + Math.floor(Math.random() * 250);
|
|
416
546
|
const pause = Math.min(Math.max(backoff, result.retryAfterMs ?? 0), RETRY_AFTER_CAP_MS);
|
|
417
547
|
if (Date.now() + pause + floor > deadline) return { kind, result, attempts: attempt };
|
|
@@ -461,6 +591,11 @@ export class OAuthAuthProvider {
|
|
|
461
591
|
await this.storeAccess(config.clientId, { token: this.#accessToken, expiresAt: this.#expiresAt });
|
|
462
592
|
return this.#accessToken;
|
|
463
593
|
}
|
|
594
|
+
#release() {
|
|
595
|
+
const signals = this.#signals;
|
|
596
|
+
this.#signals = undefined;
|
|
597
|
+
signals?.release();
|
|
598
|
+
}
|
|
464
599
|
async headers() {
|
|
465
600
|
const config = await readConfig();
|
|
466
601
|
return { authorization: `Bearer ${await this.accessToken()}`, ...(config.agentId ? { "x-agent-id": config.agentId } : {}) };
|