@aragon-agent/cli 0.6.71 → 0.6.72

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,61 @@
1
+ /**
2
+ * Every URL and protocol constant the CLI's account layer needs, in one place.
3
+ *
4
+ * WHY A MODULE AND NOT LITERALS AT THE CALL SITES: the base URL is user-selectable
5
+ * (`ARAGON_WEB_URL`), and the device-flow constants are a contract with `apps/web`
6
+ * (C1 / C2). Two copies of `/api/device/token` is exactly the shape that lets a
7
+ * rename land in one of them and not the other, and the failure is a login that
8
+ * polls a 404 forever.
9
+ *
10
+ * THE BASE URL IS NEVER DERIVED FROM THE RESPONSE: the server tells us where to
11
+ * send the user (`verification_uri_complete`), but `baseUrl` stays what the user
12
+ * chose, and it is what gets written into `account.json` (C3), so `aragon whoami`
13
+ * can say which site issued the credential.
14
+ *
15
+ * ASCII ONLY - `src/account/**` renders text a user reads.
16
+ */
17
+ /** Where the device flow talks when nobody says otherwise (spec section 1). */
18
+ export declare const DEFAULT_WEB_BASE_URL = "https://aragonagent.com";
19
+ /** RFC 8628 section 3.1: the client identifier the web side has allow-listed (C1). */
20
+ export declare const DEVICE_CLIENT_ID = "aragon-cli";
21
+ /** The only scope a device grant may request (C1). */
22
+ export declare const DEVICE_SCOPE = "account:read";
23
+ /** RFC 8628 section 3.4 grant type, verbatim: the server compares it byte for byte. */
24
+ export declare const DEVICE_GRANT_TYPE = "urn:ietf:params:oauth:grant-type:device_code";
25
+ export declare const DEVICE_CODE_PATH = "/api/device/code";
26
+ export declare const DEVICE_TOKEN_PATH = "/api/device/token";
27
+ export declare const ACCOUNT_ME_PATH = "/api/v1/me";
28
+ /**
29
+ * Polling bounds.
30
+ *
31
+ * `MAX_POLL_INTERVAL_SECONDS` is the SAME 60 the web side caps its own interval
32
+ * at (`DEVICE_INTERVAL_MAX_SECONDS`), and it is not negotiable from this side: a
33
+ * client that waits less than the server asked gets `slow_down` forever, and a
34
+ * client that waits more than 60 s keeps a terminal idle for no reason.
35
+ */
36
+ export declare const MIN_POLL_INTERVAL_SECONDS = 1;
37
+ export declare const MAX_POLL_INTERVAL_SECONDS = 60;
38
+ export declare const SLOW_DOWN_STEP_SECONDS = 5;
39
+ export declare const DEFAULT_POLL_INTERVAL_SECONDS = 5;
40
+ /**
41
+ * `https://host[:port][/path]` without a trailing slash, or `null` when `raw` is
42
+ * not an absolute http(s) URL.
43
+ *
44
+ * A TRAILING SLASH IS THE BUG THIS EXISTS FOR: `${base}/api/device/code` with a
45
+ * base of `https://x/` is `https://x//api/device/code`, which some servers 404
46
+ * and others rewrite, and neither failure says why. Query and fragment are
47
+ * dropped rather than rejected - they cannot be part of a base URL and a user
48
+ * who pasted one meant the origin.
49
+ */
50
+ export declare function normaliseBaseUrl(raw: string | null | undefined): string | null;
51
+ /**
52
+ * `ARAGON_WEB_URL` -> the default. Never throws, never returns `''`.
53
+ *
54
+ * AN ILLEGAL VALUE FALLS BACK RATHER THAN FAILING: the alternative is a login
55
+ * command that refuses to start because of a typo in a shell profile, and the
56
+ * user has no way to tell that from "sign-in is down". The fallback is the
57
+ * public site, which is what an unset variable means anyway.
58
+ */
59
+ export declare function resolveWebBaseUrl(env?: NodeJS.ProcessEnv): string;
60
+ /** `https://host/api/device/code`; `baseUrl` is expected to be normalised. */
61
+ export declare function apiUrl(baseUrl: string, path: string): string;
@@ -0,0 +1,83 @@
1
+ /**
2
+ * Every URL and protocol constant the CLI's account layer needs, in one place.
3
+ *
4
+ * WHY A MODULE AND NOT LITERALS AT THE CALL SITES: the base URL is user-selectable
5
+ * (`ARAGON_WEB_URL`), and the device-flow constants are a contract with `apps/web`
6
+ * (C1 / C2). Two copies of `/api/device/token` is exactly the shape that lets a
7
+ * rename land in one of them and not the other, and the failure is a login that
8
+ * polls a 404 forever.
9
+ *
10
+ * THE BASE URL IS NEVER DERIVED FROM THE RESPONSE: the server tells us where to
11
+ * send the user (`verification_uri_complete`), but `baseUrl` stays what the user
12
+ * chose, and it is what gets written into `account.json` (C3), so `aragon whoami`
13
+ * can say which site issued the credential.
14
+ *
15
+ * ASCII ONLY - `src/account/**` renders text a user reads.
16
+ */
17
+ import process from 'node:process';
18
+ /** Where the device flow talks when nobody says otherwise (spec section 1). */
19
+ export const DEFAULT_WEB_BASE_URL = 'https://aragonagent.com';
20
+ /** RFC 8628 section 3.1: the client identifier the web side has allow-listed (C1). */
21
+ export const DEVICE_CLIENT_ID = 'aragon-cli';
22
+ /** The only scope a device grant may request (C1). */
23
+ export const DEVICE_SCOPE = 'account:read';
24
+ /** RFC 8628 section 3.4 grant type, verbatim: the server compares it byte for byte. */
25
+ export const DEVICE_GRANT_TYPE = 'urn:ietf:params:oauth:grant-type:device_code';
26
+ export const DEVICE_CODE_PATH = '/api/device/code';
27
+ export const DEVICE_TOKEN_PATH = '/api/device/token';
28
+ export const ACCOUNT_ME_PATH = '/api/v1/me';
29
+ /**
30
+ * Polling bounds.
31
+ *
32
+ * `MAX_POLL_INTERVAL_SECONDS` is the SAME 60 the web side caps its own interval
33
+ * at (`DEVICE_INTERVAL_MAX_SECONDS`), and it is not negotiable from this side: a
34
+ * client that waits less than the server asked gets `slow_down` forever, and a
35
+ * client that waits more than 60 s keeps a terminal idle for no reason.
36
+ */
37
+ export const MIN_POLL_INTERVAL_SECONDS = 1;
38
+ export const MAX_POLL_INTERVAL_SECONDS = 60;
39
+ export const SLOW_DOWN_STEP_SECONDS = 5;
40
+ export const DEFAULT_POLL_INTERVAL_SECONDS = 5;
41
+ /**
42
+ * `https://host[:port][/path]` without a trailing slash, or `null` when `raw` is
43
+ * not an absolute http(s) URL.
44
+ *
45
+ * A TRAILING SLASH IS THE BUG THIS EXISTS FOR: `${base}/api/device/code` with a
46
+ * base of `https://x/` is `https://x//api/device/code`, which some servers 404
47
+ * and others rewrite, and neither failure says why. Query and fragment are
48
+ * dropped rather than rejected - they cannot be part of a base URL and a user
49
+ * who pasted one meant the origin.
50
+ */
51
+ export function normaliseBaseUrl(raw) {
52
+ const text = raw?.trim();
53
+ if (!text)
54
+ return null;
55
+ let url;
56
+ try {
57
+ url = new URL(text);
58
+ }
59
+ catch {
60
+ return null;
61
+ }
62
+ if (url.protocol !== 'https:' && url.protocol !== 'http:')
63
+ return null;
64
+ if (url.hostname.length === 0)
65
+ return null;
66
+ const path = url.pathname.replace(/\/+$/, '');
67
+ return `${url.protocol}//${url.host}${path}`;
68
+ }
69
+ /**
70
+ * `ARAGON_WEB_URL` -> the default. Never throws, never returns `''`.
71
+ *
72
+ * AN ILLEGAL VALUE FALLS BACK RATHER THAN FAILING: the alternative is a login
73
+ * command that refuses to start because of a typo in a shell profile, and the
74
+ * user has no way to tell that from "sign-in is down". The fallback is the
75
+ * public site, which is what an unset variable means anyway.
76
+ */
77
+ export function resolveWebBaseUrl(env = process.env) {
78
+ return normaliseBaseUrl(env.ARAGON_WEB_URL) ?? DEFAULT_WEB_BASE_URL;
79
+ }
80
+ /** `https://host/api/device/code`; `baseUrl` is expected to be normalised. */
81
+ export function apiUrl(baseUrl, path) {
82
+ return `${baseUrl.replace(/\/+$/, '')}${path}`;
83
+ }
@@ -0,0 +1,113 @@
1
+ /**
2
+ * The RFC 8628 device-flow client (C1), with no UI and no ambient clock.
3
+ *
4
+ * TWO CALLS AND A STATE MACHINE:
5
+ *
6
+ * start() -> POST {baseUrl}/api/device/code {client_id, scope}
7
+ * poll() -> POST {baseUrl}/api/device/token {grant_type, device_code, client_id}
8
+ *
9
+ * EVERYTHING IS INJECTED - `fetch`, the clock and `sleep`. That is not test
10
+ * decoration: the polling loop's whole contract is about TIME (the server's
11
+ * interval, the `slow_down` growth, the 60 s cap, the `expires_in` ceiling), and
12
+ * a test that waits those seconds is a test nobody runs. With `now` and `sleep`
13
+ * as dependencies the intervals are data a fake clock can measure, and the
14
+ * shipped defaults are the only place a real timer exists.
15
+ *
16
+ * WHAT THIS MODULE REFUSES TO DO, each for a reason:
17
+ *
18
+ * - Never treat a non-200 as success, and never read the site's
19
+ * `{"error":{"code":...}}` envelope (C1). The device endpoints answer in the
20
+ * OAuth shape `{"error":"authorization_pending"}`; an object where a string
21
+ * belongs means this is not the endpoint we think it is, which is an error,
22
+ * not a token.
23
+ * - Never log or embed the `device_code` or the `access_token`. The token is
24
+ * returned to the caller and registered with the redactor there; the device
25
+ * code is a 34.6-bit credential that would let anyone redeem the grant.
26
+ * - Never poll past `expires_in`. The loop stops before a wait that would end
27
+ * after the deadline, so a terminal cannot sit there one interval too long
28
+ * holding a grant the server has already deleted.
29
+ * - Never spin: `authorization_pending` waits the server's interval, 429 waits
30
+ * the server's `retry-after`, and a transport failure backs off exponentially
31
+ * from the interval, capped at the same 60 s the server caps its own interval
32
+ * at. `maxNetworkRetries` bounds the backoff.
33
+ */
34
+ /** A whole request may not hang longer than this. */
35
+ export declare const DEFAULT_REQUEST_TIMEOUT_MS = 10000;
36
+ /** Consecutive transport failures before `poll()` gives up. */
37
+ export declare const DEFAULT_MAX_NETWORK_RETRIES = 5;
38
+ /** A 429 without a usable `retry-after` header waits this long. */
39
+ export declare const DEFAULT_RETRY_AFTER_SECONDS = 5;
40
+ export interface DeviceCodeInfo {
41
+ readonly deviceCode: string;
42
+ readonly userCode: string;
43
+ readonly verificationUri: string;
44
+ readonly verificationUriComplete: string;
45
+ readonly expiresInSec: number;
46
+ readonly intervalSec: number;
47
+ }
48
+ export interface DeviceTokenInfo {
49
+ readonly accessToken: string;
50
+ readonly tokenType: string;
51
+ readonly expiresInSec: number;
52
+ readonly scope: string;
53
+ readonly tokenPrefix: string;
54
+ }
55
+ export type DeviceCodeResult = {
56
+ readonly kind: 'code';
57
+ readonly code: DeviceCodeInfo;
58
+ } | {
59
+ readonly kind: 'invalid';
60
+ readonly message: string;
61
+ } | {
62
+ readonly kind: 'network';
63
+ readonly message: string;
64
+ } | {
65
+ readonly kind: 'cancelled';
66
+ };
67
+ export type DevicePollResult = {
68
+ readonly kind: 'token';
69
+ readonly token: DeviceTokenInfo;
70
+ } | {
71
+ readonly kind: 'denied';
72
+ } | {
73
+ readonly kind: 'expired';
74
+ } | {
75
+ readonly kind: 'invalid';
76
+ readonly message: string;
77
+ } | {
78
+ readonly kind: 'network';
79
+ readonly message: string;
80
+ } | {
81
+ readonly kind: 'cancelled';
82
+ };
83
+ export interface PollInput {
84
+ readonly code: DeviceCodeInfo;
85
+ readonly signal?: AbortSignal;
86
+ readonly onProgress?: (progress: {
87
+ readonly elapsedSec: number;
88
+ }) => void;
89
+ }
90
+ export interface DeviceClientDeps {
91
+ readonly baseUrl: string;
92
+ readonly fetchImpl?: typeof fetch;
93
+ readonly now?: () => number;
94
+ /** Resolves after `ms`, or as soon as `signal` aborts. Injected in tests. */
95
+ readonly sleep?: (ms: number, signal?: AbortSignal) => Promise<void>;
96
+ readonly maxNetworkRetries?: number;
97
+ readonly requestTimeoutMs?: number;
98
+ }
99
+ export interface DeviceClient {
100
+ start(options?: {
101
+ readonly signal?: AbortSignal;
102
+ }): Promise<DeviceCodeResult>;
103
+ poll(input: PollInput): Promise<DevicePollResult>;
104
+ }
105
+ /**
106
+ * Build a client bound to one origin.
107
+ *
108
+ * A FACTORY RATHER THAN MODULE STATE: the base URL is per-login (the user may
109
+ * point `ARAGON_WEB_URL` at staging), and a module-level singleton would leak
110
+ * one login's origin into the next. The object is cheap; callers create one per
111
+ * `startLogin`.
112
+ */
113
+ export declare function createDeviceClient(deps: DeviceClientDeps): DeviceClient;
@@ -0,0 +1,425 @@
1
+ /**
2
+ * The RFC 8628 device-flow client (C1), with no UI and no ambient clock.
3
+ *
4
+ * TWO CALLS AND A STATE MACHINE:
5
+ *
6
+ * start() -> POST {baseUrl}/api/device/code {client_id, scope}
7
+ * poll() -> POST {baseUrl}/api/device/token {grant_type, device_code, client_id}
8
+ *
9
+ * EVERYTHING IS INJECTED - `fetch`, the clock and `sleep`. That is not test
10
+ * decoration: the polling loop's whole contract is about TIME (the server's
11
+ * interval, the `slow_down` growth, the 60 s cap, the `expires_in` ceiling), and
12
+ * a test that waits those seconds is a test nobody runs. With `now` and `sleep`
13
+ * as dependencies the intervals are data a fake clock can measure, and the
14
+ * shipped defaults are the only place a real timer exists.
15
+ *
16
+ * WHAT THIS MODULE REFUSES TO DO, each for a reason:
17
+ *
18
+ * - Never treat a non-200 as success, and never read the site's
19
+ * `{"error":{"code":...}}` envelope (C1). The device endpoints answer in the
20
+ * OAuth shape `{"error":"authorization_pending"}`; an object where a string
21
+ * belongs means this is not the endpoint we think it is, which is an error,
22
+ * not a token.
23
+ * - Never log or embed the `device_code` or the `access_token`. The token is
24
+ * returned to the caller and registered with the redactor there; the device
25
+ * code is a 34.6-bit credential that would let anyone redeem the grant.
26
+ * - Never poll past `expires_in`. The loop stops before a wait that would end
27
+ * after the deadline, so a terminal cannot sit there one interval too long
28
+ * holding a grant the server has already deleted.
29
+ * - Never spin: `authorization_pending` waits the server's interval, 429 waits
30
+ * the server's `retry-after`, and a transport failure backs off exponentially
31
+ * from the interval, capped at the same 60 s the server caps its own interval
32
+ * at. `maxNetworkRetries` bounds the backoff.
33
+ */
34
+ import { DEFAULT_POLL_INTERVAL_SECONDS, DEVICE_CLIENT_ID, DEVICE_CODE_PATH, DEVICE_GRANT_TYPE, DEVICE_SCOPE, DEVICE_TOKEN_PATH, MAX_POLL_INTERVAL_SECONDS, MIN_POLL_INTERVAL_SECONDS, SLOW_DOWN_STEP_SECONDS, apiUrl, } from './config.js';
35
+ import { getLogger } from '../logging/logger.js';
36
+ /** A whole request may not hang longer than this. */
37
+ export const DEFAULT_REQUEST_TIMEOUT_MS = 10_000;
38
+ /** Consecutive transport failures before `poll()` gives up. */
39
+ export const DEFAULT_MAX_NETWORK_RETRIES = 5;
40
+ /** A 429 without a usable `retry-after` header waits this long. */
41
+ export const DEFAULT_RETRY_AFTER_SECONDS = 5;
42
+ // ---------------------------------------------------------------------------
43
+ // Small pure helpers
44
+ // ---------------------------------------------------------------------------
45
+ function isRecord(value) {
46
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
47
+ }
48
+ function asString(value) {
49
+ return typeof value === 'string' && value.length > 0 ? value : null;
50
+ }
51
+ function asPositiveNumber(value) {
52
+ return typeof value === 'number' && Number.isFinite(value) && value > 0 ? value : null;
53
+ }
54
+ /** Clamp a server-supplied interval into the range the web side honours. */
55
+ function clampInterval(seconds) {
56
+ if (!Number.isFinite(seconds))
57
+ return DEFAULT_POLL_INTERVAL_SECONDS;
58
+ const whole = Math.round(seconds);
59
+ return Math.min(MAX_POLL_INTERVAL_SECONDS, Math.max(MIN_POLL_INTERVAL_SECONDS, whole));
60
+ }
61
+ /**
62
+ * The next interval after `slow_down`.
63
+ *
64
+ * BOTH SIDES OF THE `max`: the RFC says the client must increase its interval by
65
+ * its own step (5 s here, the same step the server adds), and the response also
66
+ * carries the interval the server has already recorded on the grant. Taking the
67
+ * larger of the two means a client that under-counted is corrected immediately
68
+ * instead of after another `slow_down`.
69
+ */
70
+ function slowDownInterval(currentSeconds, requestedSeconds) {
71
+ const stepped = currentSeconds + SLOW_DOWN_STEP_SECONDS;
72
+ return clampInterval(Math.max(stepped, requestedSeconds ?? 0));
73
+ }
74
+ // ---------------------------------------------------------------------------
75
+ // Transport
76
+ // ---------------------------------------------------------------------------
77
+ async function readJsonBody(response) {
78
+ try {
79
+ const text = await response.text();
80
+ if (text.trim().length === 0)
81
+ return null;
82
+ const parsed = JSON.parse(text);
83
+ return isRecord(parsed) ? parsed : null;
84
+ }
85
+ catch {
86
+ // A non-JSON 200 is handled by the caller as a malformed success, which is
87
+ // more accurate than "network error" for a body we did receive.
88
+ return null;
89
+ }
90
+ }
91
+ function readRetryAfter(response) {
92
+ const raw = response.headers.get('retry-after');
93
+ if (raw === null)
94
+ return null;
95
+ const seconds = Number.parseInt(raw.trim(), 10);
96
+ if (!Number.isFinite(seconds) || seconds < 0)
97
+ return null;
98
+ return clampInterval(seconds);
99
+ }
100
+ function describeTransportError(error) {
101
+ if (error instanceof Error && error.message.length > 0)
102
+ return error.message;
103
+ return 'the request failed without an error message';
104
+ }
105
+ /**
106
+ * One POST, bounded by `requestTimeoutMs` and by the caller's signal.
107
+ *
108
+ * THE TIMEOUT IS A SEPARATE CONTROLLER ON PURPOSE: the caller's signal means
109
+ * "the user cancelled" and answers `cancelled`; our own timer means "the server
110
+ * did not answer" and answers `network`, which the poll loop retries. Folding
111
+ * the two into one signal would make a slow server end the login instead of
112
+ * backing off.
113
+ */
114
+ async function sendJson(deps, path, payload, signal) {
115
+ if (signal?.aborted)
116
+ return { kind: 'cancelled' };
117
+ const url = apiUrl(deps.baseUrl, path);
118
+ const controller = new AbortController();
119
+ const timer = setTimeout(() => controller.abort(), deps.requestTimeoutMs);
120
+ const onAbort = () => controller.abort();
121
+ signal?.addEventListener('abort', onAbort);
122
+ try {
123
+ const response = await deps.fetchImpl(url, {
124
+ method: 'POST',
125
+ headers: {
126
+ 'content-type': 'application/json',
127
+ accept: 'application/json',
128
+ 'user-agent': `aragon-cli/${DEVICE_CLIENT_ID}`,
129
+ },
130
+ body: JSON.stringify(payload),
131
+ signal: controller.signal,
132
+ });
133
+ return {
134
+ kind: 'response',
135
+ status: response.status,
136
+ body: await readJsonBody(response),
137
+ retryAfterSec: readRetryAfter(response),
138
+ };
139
+ }
140
+ catch (error) {
141
+ if (signal?.aborted)
142
+ return { kind: 'cancelled' };
143
+ if (controller.signal.aborted) {
144
+ return {
145
+ kind: 'network',
146
+ message: `${url} did not answer within ${deps.requestTimeoutMs} ms`,
147
+ };
148
+ }
149
+ return { kind: 'network', message: describeTransportError(error) };
150
+ }
151
+ finally {
152
+ clearTimeout(timer);
153
+ signal?.removeEventListener('abort', onAbort);
154
+ }
155
+ }
156
+ // ---------------------------------------------------------------------------
157
+ // Response readers
158
+ // ---------------------------------------------------------------------------
159
+ /**
160
+ * `{error: "code"}` -> the code, or `null`.
161
+ *
162
+ * AN OBJECT UNDER `error` IS `null`, NOT A CODE: that is the site's envelope and
163
+ * this endpoint family never sends it (C1). Reading through it would make a
164
+ * `400 {"error":{"code":"E_VALIDATION"}}` look like an OAuth error we might
165
+ * interpret, and the one interpretation that matters is "success".
166
+ */
167
+ function readOAuthError(body) {
168
+ if (body === null)
169
+ return null;
170
+ const code = asString(body['error']);
171
+ if (code === null)
172
+ return null;
173
+ const description = asString(body['error_description']);
174
+ return { code, description };
175
+ }
176
+ function describeOAuthFailure(failure) {
177
+ const detail = failure.description ?? 'no description';
178
+ return `${failure.code}: ${detail}`;
179
+ }
180
+ function readCodeResponse(body) {
181
+ if (body === null)
182
+ return null;
183
+ const deviceCode = asString(body['device_code']);
184
+ const userCode = asString(body['user_code']);
185
+ const verificationUri = asString(body['verification_uri']);
186
+ const expiresInSec = asPositiveNumber(body['expires_in']);
187
+ if (deviceCode === null || userCode === null || verificationUri === null)
188
+ return null;
189
+ if (expiresInSec === null)
190
+ return null;
191
+ const complete = asString(body['verification_uri_complete']);
192
+ return {
193
+ deviceCode,
194
+ userCode,
195
+ verificationUri,
196
+ verificationUriComplete: complete ?? `${verificationUri}?user_code=${encodeURIComponent(userCode)}`,
197
+ expiresInSec: Math.floor(expiresInSec),
198
+ intervalSec: clampInterval(asPositiveNumber(body['interval']) ?? DEFAULT_POLL_INTERVAL_SECONDS),
199
+ };
200
+ }
201
+ function readTokenResponse(body) {
202
+ if (body === null)
203
+ return null;
204
+ const accessToken = asString(body['access_token']);
205
+ if (accessToken === null)
206
+ return null;
207
+ return {
208
+ accessToken,
209
+ tokenType: asString(body['token_type']) ?? 'Bearer',
210
+ expiresInSec: Math.floor(asPositiveNumber(body['expires_in']) ?? 0),
211
+ scope: asString(body['scope']) ?? '',
212
+ tokenPrefix: asString(body['token_prefix']) ?? '',
213
+ };
214
+ }
215
+ // ---------------------------------------------------------------------------
216
+ // The polling state machine
217
+ // ---------------------------------------------------------------------------
218
+ function elapsedSeconds(state) {
219
+ return Math.max(0, Math.floor((state.deps.now() - state.startedAt) / 1000));
220
+ }
221
+ /** Exponential from the interval, doubling per consecutive failure, capped. */
222
+ function backoffMs(state) {
223
+ const grown = state.intervalSec * 2 ** state.networkFailures;
224
+ return clampInterval(grown) * 1000;
225
+ }
226
+ /**
227
+ * Sleep, but never past the deadline.
228
+ *
229
+ * `expired` here is not an error: it is the deadline arriving while we were
230
+ * waiting, which is exactly the moment the grant stops being usable.
231
+ */
232
+ async function waitInPoll(state, waitMs) {
233
+ const remaining = state.deadline - state.deps.now();
234
+ if (remaining <= 0)
235
+ return 'expired';
236
+ await state.deps.sleep(Math.min(waitMs, remaining), state.signal);
237
+ if (state.signal?.aborted)
238
+ return 'cancelled';
239
+ return 'ok';
240
+ }
241
+ /**
242
+ * Turn one response into the next step.
243
+ *
244
+ * The switch is the RFC 8628 table and nothing else: `authorization_pending`
245
+ * and `slow_down` are the two that mean "poll again", `access_denied`,
246
+ * `expired_token` and `invalid_grant` are terminal, and every other code is a
247
+ * terminal client fault that retrying cannot fix.
248
+ */
249
+ function interpretPollResponse(sent, state) {
250
+ if (sent.status === 200) {
251
+ const token = readTokenResponse(sent.body);
252
+ if (token === null) {
253
+ return {
254
+ kind: 'invalid',
255
+ message: 'the token endpoint returned a malformed success response',
256
+ };
257
+ }
258
+ return { kind: 'token', token };
259
+ }
260
+ if (sent.status === 429) {
261
+ const seconds = sent.retryAfterSec ?? DEFAULT_RETRY_AFTER_SECONDS;
262
+ getLogger().debug('cli', 'account.device_poll_rate_limited', { retryAfterSec: seconds });
263
+ return { kind: 'retry', waitMs: seconds * 1000 };
264
+ }
265
+ const failure = readOAuthError(sent.body);
266
+ if (failure === null) {
267
+ return {
268
+ kind: 'invalid',
269
+ message: `the token endpoint answered HTTP ${sent.status} without an OAuth error code`,
270
+ };
271
+ }
272
+ return interpretOAuthCode(failure, sent, state);
273
+ }
274
+ function readIntervalField(body) {
275
+ if (body === null)
276
+ return null;
277
+ return asPositiveNumber(body['interval']);
278
+ }
279
+ function interpretOAuthCode(failure, sent, state) {
280
+ switch (failure.code) {
281
+ case 'authorization_pending':
282
+ return { kind: 'retry', waitMs: state.intervalSec * 1000 };
283
+ case 'slow_down': {
284
+ state.intervalSec = slowDownInterval(state.intervalSec, readIntervalField(sent.body));
285
+ getLogger().debug('cli', 'account.device_poll_slow_down', { intervalSec: state.intervalSec });
286
+ return { kind: 'retry', waitMs: state.intervalSec * 1000 };
287
+ }
288
+ case 'access_denied':
289
+ return { kind: 'denied' };
290
+ case 'expired_token':
291
+ return { kind: 'expired' };
292
+ case 'invalid_grant':
293
+ return {
294
+ kind: 'invalid',
295
+ message: 'the device code is no longer valid (it expired, or the grant was already redeemed)',
296
+ };
297
+ default:
298
+ return { kind: 'invalid', message: describeOAuthFailure(failure) };
299
+ }
300
+ }
301
+ function waitFailed(waited) {
302
+ return waited === 'cancelled' ? { kind: 'cancelled' } : { kind: 'expired' };
303
+ }
304
+ async function runPoll(state) {
305
+ for (;;) {
306
+ if (state.signal?.aborted)
307
+ return { kind: 'cancelled' };
308
+ state.onProgress?.({ elapsedSec: elapsedSeconds(state) });
309
+ if (state.deps.now() >= state.deadline)
310
+ return { kind: 'expired' };
311
+ state.attempts += 1;
312
+ const sent = await sendJson(state.deps, DEVICE_TOKEN_PATH, tokenRequestBody(state.deviceCode), state.signal);
313
+ if (sent.kind === 'cancelled')
314
+ return { kind: 'cancelled' };
315
+ if (sent.kind !== 'response' || sent.status >= 500) {
316
+ const message = sent.kind === 'network' ? sent.message : `HTTP ${sent.status} from the token endpoint`;
317
+ state.networkFailures += 1;
318
+ if (state.networkFailures > state.deps.maxNetworkRetries)
319
+ return { kind: 'network', message };
320
+ getLogger().debug('cli', 'account.device_poll_network_error', {
321
+ attempt: state.attempts,
322
+ failures: state.networkFailures,
323
+ });
324
+ const waited = await waitInPoll(state, backoffMs(state));
325
+ if (waited !== 'ok')
326
+ return waitFailed(waited);
327
+ continue;
328
+ }
329
+ // The transport works again, so the backoff ladder restarts: `maxNetworkRetries`
330
+ // is a budget for CONSECUTIVE failures, not for a login's total failures.
331
+ state.networkFailures = 0;
332
+ const step = interpretPollResponse(sent, state);
333
+ if (step.kind !== 'retry')
334
+ return step;
335
+ const waited = await waitInPoll(state, step.waitMs);
336
+ if (waited !== 'ok')
337
+ return waitFailed(waited);
338
+ }
339
+ }
340
+ function tokenRequestBody(deviceCode) {
341
+ return { grant_type: DEVICE_GRANT_TYPE, device_code: deviceCode, client_id: DEVICE_CLIENT_ID };
342
+ }
343
+ // ---------------------------------------------------------------------------
344
+ // Factory
345
+ // ---------------------------------------------------------------------------
346
+ function defaultSleep(ms, signal) {
347
+ if (ms <= 0 || signal?.aborted)
348
+ return Promise.resolve();
349
+ return new Promise((resolve) => {
350
+ const finish = () => {
351
+ clearTimeout(timer);
352
+ signal?.removeEventListener('abort', finish);
353
+ resolve();
354
+ };
355
+ const timer = setTimeout(finish, ms);
356
+ signal?.addEventListener('abort', finish, { once: true });
357
+ });
358
+ }
359
+ function resolveDeps(deps) {
360
+ return {
361
+ baseUrl: deps.baseUrl,
362
+ fetchImpl: deps.fetchImpl ?? fetch,
363
+ now: deps.now ?? Date.now,
364
+ sleep: deps.sleep ?? defaultSleep,
365
+ maxNetworkRetries: deps.maxNetworkRetries ?? DEFAULT_MAX_NETWORK_RETRIES,
366
+ requestTimeoutMs: deps.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS,
367
+ };
368
+ }
369
+ async function requestCode(deps, signal) {
370
+ if (signal?.aborted)
371
+ return { kind: 'cancelled' };
372
+ const sent = await sendJson(deps, DEVICE_CODE_PATH, { client_id: DEVICE_CLIENT_ID, scope: DEVICE_SCOPE }, signal);
373
+ if (sent.kind !== 'response')
374
+ return sent;
375
+ if (sent.status === 200) {
376
+ const code = readCodeResponse(sent.body);
377
+ if (code === null) {
378
+ return {
379
+ kind: 'invalid',
380
+ message: 'the authorisation endpoint returned a malformed code response',
381
+ };
382
+ }
383
+ getLogger().debug('cli', 'account.device_code_issued', {
384
+ baseUrl: deps.baseUrl,
385
+ expiresInSec: code.expiresInSec,
386
+ intervalSec: code.intervalSec,
387
+ });
388
+ return { kind: 'code', code };
389
+ }
390
+ const failure = readOAuthError(sent.body);
391
+ if (failure !== null)
392
+ return { kind: 'invalid', message: describeOAuthFailure(failure) };
393
+ return {
394
+ kind: 'network',
395
+ message: `the authorisation endpoint answered HTTP ${sent.status}`,
396
+ };
397
+ }
398
+ /**
399
+ * Build a client bound to one origin.
400
+ *
401
+ * A FACTORY RATHER THAN MODULE STATE: the base URL is per-login (the user may
402
+ * point `ARAGON_WEB_URL` at staging), and a module-level singleton would leak
403
+ * one login's origin into the next. The object is cheap; callers create one per
404
+ * `startLogin`.
405
+ */
406
+ export function createDeviceClient(deps) {
407
+ const resolved = resolveDeps(deps);
408
+ return {
409
+ start: (options = {}) => requestCode(resolved, options.signal),
410
+ poll: (input) => {
411
+ const startedAt = resolved.now();
412
+ return runPoll({
413
+ deps: resolved,
414
+ deviceCode: input.code.deviceCode,
415
+ signal: input.signal,
416
+ onProgress: input.onProgress,
417
+ startedAt,
418
+ deadline: startedAt + Math.max(0, input.code.expiresInSec) * 1000,
419
+ intervalSec: clampInterval(input.code.intervalSec),
420
+ networkFailures: 0,
421
+ attempts: 0,
422
+ });
423
+ },
424
+ };
425
+ }