@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,51 @@
1
+ /**
2
+ * The account layer's user-facing copy - pure functions, no I/O, no clock (C4).
3
+ *
4
+ * WHY COPY LIVES IN ITS OWN MODULE: three surfaces render the same four states
5
+ * (the `/login` transcript, the startup notice, the status line) and they must
6
+ * not each invent a sentence for "expiring". A pure function is also the only
7
+ * part of this layer a test can pin without a filesystem, a fake clock and a
8
+ * fake server at the same time.
9
+ *
10
+ * ENGLISH, ASCII ONLY, and no trailing period after a path or a URL: these
11
+ * strings reach a terminal whose width and font the CLI does not control.
12
+ */
13
+ import { type AccountStatus } from './session.js';
14
+ /** Closed set; `login-flow.ts` maps every failure onto exactly one of these. */
15
+ export type LoginFailureReason = 'denied' | 'expired' | 'network' | 'cancelled' | 'invalid';
16
+ /** `2027-01-05`, or `unknown` for a value that is not a timestamp. */
17
+ export declare function formatIsoDate(epochMs: number | null): string;
18
+ /**
19
+ * The one line every surface can print (C4).
20
+ *
21
+ * `describeExpiry` names the state first, then the fact that changes what the
22
+ * user should do - days left, or the date it stopped working. The `expiring`
23
+ * sentence names `/login` because that is the entire point of warning three days
24
+ * ahead instead of at zero.
25
+ */
26
+ export declare function describeExpiry(status: AccountStatus): string;
27
+ /**
28
+ * The startup notice, or `null` when there is nothing to say.
29
+ *
30
+ * ONLY `expiring` PRODUCES A LINE, and that is the spec's decision (one prompt
31
+ * per launch at three days, not a banner on every start). `expired` is
32
+ * deliberately silent here: a terminal that greets a user with "your token
33
+ * expired" every single launch is nagging, and `/login` still works.
34
+ */
35
+ export declare function describeStartupNotice(status: AccountStatus): string | null;
36
+ /** Why a login failed, in the words the transcript shows under the code. */
37
+ export declare function describeLoginFailure(reason: LoginFailureReason, baseUrl: string): string;
38
+ /** A token arrived but the profile call did not answer - no file was written. */
39
+ export declare function describeTokenRejected(baseUrl: string): string;
40
+ /**
41
+ * The credential is valid but the disk refused it.
42
+ *
43
+ * NAMING THE PATH IS THE POINT: the usual cause is a read-only or full home
44
+ * directory, and the user cannot fix that from a message that only says "error".
45
+ */
46
+ export declare function describeSaveFailure(path: string): string;
47
+ /** The code box above the polling spinner: what to open, and what to type. */
48
+ export declare function describeDeviceCode(code: {
49
+ code: string;
50
+ link: string;
51
+ }): string;
@@ -0,0 +1,102 @@
1
+ /**
2
+ * The account layer's user-facing copy - pure functions, no I/O, no clock (C4).
3
+ *
4
+ * WHY COPY LIVES IN ITS OWN MODULE: three surfaces render the same four states
5
+ * (the `/login` transcript, the startup notice, the status line) and they must
6
+ * not each invent a sentence for "expiring". A pure function is also the only
7
+ * part of this layer a test can pin without a filesystem, a fake clock and a
8
+ * fake server at the same time.
9
+ *
10
+ * ENGLISH, ASCII ONLY, and no trailing period after a path or a URL: these
11
+ * strings reach a terminal whose width and font the CLI does not control.
12
+ */
13
+ import { EXPIRY_WARN_DAYS } from './session.js';
14
+ const REASON_COPY = {
15
+ 'signed-out': 'Not signed in.',
16
+ valid: 'Signed in.',
17
+ expiring: 'Signed in, token nearly expired.',
18
+ expired: 'Signed in, but the token has expired.',
19
+ };
20
+ function plural(count, singular) {
21
+ return count === 1 ? `1 ${singular}` : `${count} ${singular}s`;
22
+ }
23
+ /** `2027-01-05`, or `unknown` for a value that is not a timestamp. */
24
+ export function formatIsoDate(epochMs) {
25
+ if (epochMs === null || !Number.isFinite(epochMs))
26
+ return 'unknown';
27
+ const iso = new Date(epochMs).toISOString();
28
+ return iso.slice(0, 10);
29
+ }
30
+ function whoIsSignedIn(status) {
31
+ return status.user === null ? 'your account' : status.user.username;
32
+ }
33
+ /**
34
+ * The one line every surface can print (C4).
35
+ *
36
+ * `describeExpiry` names the state first, then the fact that changes what the
37
+ * user should do - days left, or the date it stopped working. The `expiring`
38
+ * sentence names `/login` because that is the entire point of warning three days
39
+ * ahead instead of at zero.
40
+ */
41
+ export function describeExpiry(status) {
42
+ const head = REASON_COPY[status.state];
43
+ switch (status.state) {
44
+ case 'signed-out':
45
+ return `${head} Run /login to connect an AragonAgent account.`;
46
+ case 'valid':
47
+ return `${head} ${whoIsSignedIn(status)} - token expires in ${plural(status.daysLeft, 'day')} (${formatIsoDate(status.expiresAt)}).`;
48
+ case 'expiring':
49
+ return `${head} ${whoIsSignedIn(status)} - ${plural(status.daysLeft, 'day')} left (${formatIsoDate(status.expiresAt)}). Run /login to renew before it stops working.`;
50
+ case 'expired':
51
+ return `${head} The token for ${whoIsSignedIn(status)} expired on ${formatIsoDate(status.expiresAt)}. Run /login to sign in again.`;
52
+ }
53
+ }
54
+ /**
55
+ * The startup notice, or `null` when there is nothing to say.
56
+ *
57
+ * ONLY `expiring` PRODUCES A LINE, and that is the spec's decision (one prompt
58
+ * per launch at three days, not a banner on every start). `expired` is
59
+ * deliberately silent here: a terminal that greets a user with "your token
60
+ * expired" every single launch is nagging, and `/login` still works.
61
+ */
62
+ export function describeStartupNotice(status) {
63
+ if (status.state !== 'expiring')
64
+ return null;
65
+ return (`${whoIsSignedIn(status)}: your AragonAgent token expires in ` +
66
+ `${plural(status.daysLeft, 'day')} (${formatIsoDate(status.expiresAt)}). ` +
67
+ `Run /login within ${EXPIRY_WARN_DAYS} days to stay signed in.`);
68
+ }
69
+ /** Why a login failed, in the words the transcript shows under the code. */
70
+ export function describeLoginFailure(reason, baseUrl) {
71
+ switch (reason) {
72
+ case 'denied':
73
+ return 'Sign-in was denied in the browser. Nothing was saved. Run /login to try again.';
74
+ case 'expired':
75
+ return 'The sign-in code expired before it was approved. Run /login to get a new one.';
76
+ case 'network':
77
+ return `Could not reach ${baseUrl}. Check your network and run /login again.`;
78
+ case 'cancelled':
79
+ return 'Sign-in cancelled. No credentials were saved.';
80
+ case 'invalid':
81
+ return `${baseUrl} rejected the sign-in request. Run /login to try again.`;
82
+ }
83
+ }
84
+ /** A token arrived but the profile call did not answer - no file was written. */
85
+ export function describeTokenRejected(baseUrl) {
86
+ return (`${baseUrl} issued a token but refused to describe the account it belongs to. ` +
87
+ 'Nothing was saved. Run /login to try again.');
88
+ }
89
+ /**
90
+ * The credential is valid but the disk refused it.
91
+ *
92
+ * NAMING THE PATH IS THE POINT: the usual cause is a read-only or full home
93
+ * directory, and the user cannot fix that from a message that only says "error".
94
+ */
95
+ export function describeSaveFailure(path) {
96
+ return (`Signed in, but the credential could not be saved to ${path}. ` +
97
+ 'Check permissions and run /login again.');
98
+ }
99
+ /** The code box above the polling spinner: what to open, and what to type. */
100
+ export function describeDeviceCode(code) {
101
+ return `Open ${code.link} and enter the code ${code.code}.`;
102
+ }
@@ -0,0 +1,68 @@
1
+ /**
2
+ * `startLogin()` - the orchestration behind `/login` (C4).
3
+ *
4
+ * 1. ask the server for a device code and hand it to the caller's `onCode`
5
+ * 2. poll until the person approves, refuses, or the code expires
6
+ * 3. register the token with the redactor, then read back who it belongs to
7
+ * 4. write `<home>/account.json` atomically (C3) and answer the username
8
+ *
9
+ * THE ORDER IS THE CONTRACT. Nothing is written until step 4 has everything the
10
+ * file needs, so every failure in steps 1-3 leaves the filesystem untouched:
11
+ * "cancel or fail, and no new file exists" is a property of the ORDER, not of a
12
+ * cleanup handler that could itself fail. An existing credential is never
13
+ * modified by a failed login either - a user who starts a second login and
14
+ * cancels it still has the first one.
15
+ *
16
+ * WHY `/api/v1/me` IS MANDATORY: `account.json` records who the credential
17
+ * belongs to, and the only trustworthy source for that is the server that just
18
+ * issued it; a username typed by the caller would be a claim, not a fact. If
19
+ * that call fails after the token was issued, the token is DISCARDED rather than
20
+ * stored half-described - it is one revocable 20-day credential, and asking the
21
+ * person to approve again costs them one tap on their phone.
22
+ */
23
+ import { type LoginFailureReason } from './format.js';
24
+ /** How many times the profile call is attempted before the login is abandoned. */
25
+ export declare const ME_ATTEMPTS = 2;
26
+ /** Wait before the second profile attempt. */
27
+ export declare const ME_RETRY_DELAY_MS = 1000;
28
+ export interface LoginCode {
29
+ readonly link: string;
30
+ readonly code: string;
31
+ readonly expiresInSec: number;
32
+ }
33
+ export interface StartLoginInput {
34
+ readonly baseUrl?: string;
35
+ readonly signal?: AbortSignal;
36
+ /** Called ONCE, before polling starts, with what the person must open and type. */
37
+ readonly onCode: (code: LoginCode) => void;
38
+ /** Called on every poll iteration; `elapsedSec` is since the poll started. */
39
+ readonly onProgress?: (progress: {
40
+ readonly elapsedSec: number;
41
+ }) => void;
42
+ }
43
+ export interface LoginAccount {
44
+ readonly username: string;
45
+ readonly expiresAt: number;
46
+ }
47
+ export type LoginResult = {
48
+ readonly ok: true;
49
+ readonly account: LoginAccount;
50
+ } | {
51
+ readonly ok: false;
52
+ readonly reason: LoginFailureReason;
53
+ readonly message: string;
54
+ };
55
+ export interface LoginDeps {
56
+ readonly fetchImpl?: typeof fetch;
57
+ readonly now?: () => number;
58
+ readonly sleep?: (ms: number, signal?: AbortSignal) => Promise<void>;
59
+ readonly maxNetworkRetries?: number;
60
+ readonly requestTimeoutMs?: number;
61
+ }
62
+ /**
63
+ * Run one device-flow login. Never throws: every failure is a `LoginResult`.
64
+ *
65
+ * `onCode` IS CALLED BEFORE THE FIRST POLL, and the poll is awaited after it, so
66
+ * the UI can paint the code and the spinner while the network is already moving.
67
+ */
68
+ export declare function startLogin(input: StartLoginInput, deps?: LoginDeps): Promise<LoginResult>;
@@ -0,0 +1,305 @@
1
+ /**
2
+ * `startLogin()` - the orchestration behind `/login` (C4).
3
+ *
4
+ * 1. ask the server for a device code and hand it to the caller's `onCode`
5
+ * 2. poll until the person approves, refuses, or the code expires
6
+ * 3. register the token with the redactor, then read back who it belongs to
7
+ * 4. write `<home>/account.json` atomically (C3) and answer the username
8
+ *
9
+ * THE ORDER IS THE CONTRACT. Nothing is written until step 4 has everything the
10
+ * file needs, so every failure in steps 1-3 leaves the filesystem untouched:
11
+ * "cancel or fail, and no new file exists" is a property of the ORDER, not of a
12
+ * cleanup handler that could itself fail. An existing credential is never
13
+ * modified by a failed login either - a user who starts a second login and
14
+ * cancels it still has the first one.
15
+ *
16
+ * WHY `/api/v1/me` IS MANDATORY: `account.json` records who the credential
17
+ * belongs to, and the only trustworthy source for that is the server that just
18
+ * issued it; a username typed by the caller would be a claim, not a fact. If
19
+ * that call fails after the token was issued, the token is DISCARDED rather than
20
+ * stored half-described - it is one revocable 20-day credential, and asking the
21
+ * person to approve again costs them one tap on their phone.
22
+ */
23
+ import { registerSecret } from '@aragon-agent/tui/model/logging/secret-registry';
24
+ import { ACCOUNT_ME_PATH, apiUrl, normaliseBaseUrl, resolveWebBaseUrl } from './config.js';
25
+ import { DEFAULT_REQUEST_TIMEOUT_MS, createDeviceClient, } from './device-client.js';
26
+ import { describeLoginFailure, describeSaveFailure, describeTokenRejected, } from './format.js';
27
+ import { writeAccount } from './store.js';
28
+ import { getAccountPath } from '../config/app-paths.js';
29
+ import { getLogger } from '../logging/logger.js';
30
+ /** How many times the profile call is attempted before the login is abandoned. */
31
+ export const ME_ATTEMPTS = 2;
32
+ /** Wait before the second profile attempt. */
33
+ export const ME_RETRY_DELAY_MS = 1_000;
34
+ // ---------------------------------------------------------------------------
35
+ // Failure helpers
36
+ // ---------------------------------------------------------------------------
37
+ function failed(reason, message) {
38
+ return { ok: false, reason, message };
39
+ }
40
+ /** Map one terminal poll answer onto the caller's closed reason set (C4). */
41
+ function pollFailure(result, baseUrl) {
42
+ switch (result.kind) {
43
+ case 'denied':
44
+ return failed('denied', describeLoginFailure('denied', baseUrl));
45
+ case 'expired':
46
+ return failed('expired', describeLoginFailure('expired', baseUrl));
47
+ case 'cancelled':
48
+ return failed('cancelled', describeLoginFailure('cancelled', baseUrl));
49
+ case 'network':
50
+ return failed('network', `${describeLoginFailure('network', baseUrl)} (${result.message})`);
51
+ case 'invalid':
52
+ return failed('invalid', `${describeLoginFailure('invalid', baseUrl)} (${result.message})`);
53
+ }
54
+ }
55
+ // ---------------------------------------------------------------------------
56
+ // /api/v1/me
57
+ // ---------------------------------------------------------------------------
58
+ function asRecord(value) {
59
+ return typeof value === 'object' && value !== null ? value : null;
60
+ }
61
+ function asText(value) {
62
+ return typeof value === 'string' && value.trim().length > 0 ? value : null;
63
+ }
64
+ function readScopes(value) {
65
+ if (!Array.isArray(value))
66
+ return [];
67
+ return value.filter((entry) => typeof entry === 'string');
68
+ }
69
+ /**
70
+ * `{user, token}` -> the fields `account.json` needs, or `null` when the shape
71
+ * is not the one `/api/v1/me` publishes.
72
+ *
73
+ * THE EMAIL IS OPTIONAL AND `''` IS NEVER STORED: the endpoint answers `null`
74
+ * for an account with no address (C3's `email?`), and writing `''` would make
75
+ * "has an address" and "has an empty one" indistinguishable on disk.
76
+ */
77
+ function readMe(body) {
78
+ const root = asRecord(body);
79
+ if (root === null)
80
+ return null;
81
+ const user = asRecord(root['user']);
82
+ const token = asRecord(root['token']);
83
+ if (user === null)
84
+ return null;
85
+ const userId = asText(user['id']);
86
+ const username = asText(user['username']);
87
+ if (userId === null || username === null)
88
+ return null;
89
+ const expiresAt = token === null ? null : token['expiresAt'];
90
+ return {
91
+ userId,
92
+ username,
93
+ email: asText(user['email']),
94
+ expiresAt: typeof expiresAt === 'number' && Number.isFinite(expiresAt) ? expiresAt : null,
95
+ scopes: token === null ? [] : readScopes(token['scopes']),
96
+ tokenPrefix: token === null ? null : asText(token['prefix']),
97
+ };
98
+ }
99
+ async function fetchMeOnce(baseUrl, token, deps, signal) {
100
+ if (signal?.aborted)
101
+ return { kind: 'cancelled' };
102
+ const controller = new AbortController();
103
+ const timer = setTimeout(() => controller.abort(), deps.requestTimeoutMs);
104
+ const onAbort = () => controller.abort();
105
+ signal?.addEventListener('abort', onAbort);
106
+ try {
107
+ const response = await deps.fetchImpl(apiUrl(baseUrl, ACCOUNT_ME_PATH), {
108
+ method: 'GET',
109
+ headers: {
110
+ authorization: `Bearer ${token}`,
111
+ accept: 'application/json',
112
+ 'user-agent': 'aragon-cli',
113
+ },
114
+ signal: controller.signal,
115
+ });
116
+ if (response.status === 401 || response.status === 403)
117
+ return { kind: 'rejected' };
118
+ if (!response.ok)
119
+ return { kind: 'network' };
120
+ const me = readMe(JSON.parse(await response.text()));
121
+ return me === null ? { kind: 'rejected' } : { kind: 'ok', me };
122
+ }
123
+ catch (error) {
124
+ if (signal?.aborted)
125
+ return { kind: 'cancelled' };
126
+ // The error NAME only: a fetch rejection can carry the URL, and while the
127
+ // URL is not a credential, a record that says "TypeError" is enough to tell
128
+ // a transport bug from a 500.
129
+ getLogger().debug('cli', 'account.me_request_failed', {
130
+ reason: error instanceof Error ? error.name : 'unknown',
131
+ });
132
+ return { kind: 'network' };
133
+ }
134
+ finally {
135
+ clearTimeout(timer);
136
+ signal?.removeEventListener('abort', onAbort);
137
+ }
138
+ }
139
+ function defaultSleep(ms, signal) {
140
+ if (ms <= 0 || signal?.aborted)
141
+ return Promise.resolve();
142
+ return new Promise((resolve) => {
143
+ const timer = setTimeout(resolve, ms);
144
+ signal?.addEventListener('abort', () => {
145
+ clearTimeout(timer);
146
+ resolve();
147
+ }, { once: true });
148
+ });
149
+ }
150
+ /**
151
+ * The profile call, with exactly one retry.
152
+ *
153
+ * ONE RETRY, NOT A BACKOFF LADDER: by the time we are here the person has
154
+ * already approved on their phone, and every extra wait is a spinner in front of
155
+ * someone who has done their part. A single retry covers the transient hiccup a
156
+ * fresh token occasionally meets; anything worse is "run /login again".
157
+ */
158
+ async function fetchMe(baseUrl, token, deps, signal) {
159
+ const http = {
160
+ fetchImpl: deps.fetchImpl ?? fetch,
161
+ requestTimeoutMs: deps.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS,
162
+ };
163
+ const sleep = deps.sleep ?? defaultSleep;
164
+ for (let attempt = 1; attempt <= ME_ATTEMPTS; attempt += 1) {
165
+ const result = await fetchMeOnce(baseUrl, token, http, signal);
166
+ if (result.kind !== 'network' || attempt === ME_ATTEMPTS)
167
+ return result;
168
+ await sleep(ME_RETRY_DELAY_MS, signal);
169
+ if (signal?.aborted)
170
+ return { kind: 'cancelled' };
171
+ }
172
+ return { kind: 'network' };
173
+ }
174
+ // ---------------------------------------------------------------------------
175
+ // The credential
176
+ // ---------------------------------------------------------------------------
177
+ function splitScopes(scope) {
178
+ return scope
179
+ .split(/\s+/)
180
+ .map((entry) => entry.trim())
181
+ .filter((entry) => entry.length > 0);
182
+ }
183
+ /**
184
+ * Assemble the C3 document.
185
+ *
186
+ * `expiresAt` PREFERS THE SERVER'S NUMBER. `expires_in` counts from the moment
187
+ * the server minted the token, so a client that computes `now + expires_in`
188
+ * after a slow round trip believes the token lives slightly longer than it does.
189
+ * When `/api/v1/me` reports the row's own `expiresAt`, that is the truth; the
190
+ * fallback exists for a server that omits it.
191
+ */
192
+ function buildRecord(baseUrl, token, me, issuedAt) {
193
+ const fallback = issuedAt + Math.max(0, token.expiresInSec) * 1000;
194
+ return {
195
+ version: 1,
196
+ baseUrl,
197
+ token: token.accessToken,
198
+ tokenPrefix: token.tokenPrefix.length > 0 ? token.tokenPrefix : (me.tokenPrefix ?? ''),
199
+ user: {
200
+ id: me.userId,
201
+ username: me.username,
202
+ ...(me.email === null ? {} : { email: me.email }),
203
+ },
204
+ scopes: me.scopes.length > 0 ? [...me.scopes] : splitScopes(token.scope),
205
+ issuedAt,
206
+ expiresAt: me.expiresAt !== null && me.expiresAt > 0 ? me.expiresAt : fallback,
207
+ };
208
+ }
209
+ // ---------------------------------------------------------------------------
210
+ // Orchestration
211
+ // ---------------------------------------------------------------------------
212
+ function announceCode(onCode, code, baseUrl) {
213
+ try {
214
+ onCode({
215
+ link: code.verificationUriComplete,
216
+ code: code.userCode,
217
+ expiresInSec: code.expiresInSec,
218
+ });
219
+ }
220
+ catch (error) {
221
+ // A throwing renderer must not throw away an approval the person is about to
222
+ // give on their phone; the login continues and the transcript says nothing.
223
+ getLogger().warn('cli', 'account.on_code_failed', {
224
+ baseUrl,
225
+ reason: error instanceof Error ? error.name : 'unknown',
226
+ });
227
+ }
228
+ }
229
+ /** Steps 1-2: get a code, announce it, and wait for the decision. */
230
+ async function authorizeDevice(input, baseUrl, deps, now) {
231
+ const client = createDeviceClient({
232
+ baseUrl,
233
+ fetchImpl: deps.fetchImpl,
234
+ now,
235
+ sleep: deps.sleep,
236
+ maxNetworkRetries: deps.maxNetworkRetries,
237
+ requestTimeoutMs: deps.requestTimeoutMs,
238
+ });
239
+ const started = await client.start({ signal: input.signal });
240
+ if (started.kind === 'cancelled') {
241
+ return { ok: false, failure: failed('cancelled', describeLoginFailure('cancelled', baseUrl)) };
242
+ }
243
+ if (started.kind === 'network') {
244
+ const hint = describeLoginFailure('network', baseUrl);
245
+ return { ok: false, failure: failed('network', `${hint} (${started.message})`) };
246
+ }
247
+ if (started.kind === 'invalid') {
248
+ const hint = describeLoginFailure('invalid', baseUrl);
249
+ return { ok: false, failure: failed('invalid', `${hint} (${started.message})`) };
250
+ }
251
+ announceCode(input.onCode, started.code, baseUrl);
252
+ const polled = await client.poll({
253
+ code: started.code,
254
+ signal: input.signal,
255
+ onProgress: input.onProgress,
256
+ });
257
+ if (polled.kind === 'token')
258
+ return { ok: true, token: polled.token };
259
+ return { ok: false, failure: pollFailure(polled, baseUrl) };
260
+ }
261
+ /**
262
+ * Run one device-flow login. Never throws: every failure is a `LoginResult`.
263
+ *
264
+ * `onCode` IS CALLED BEFORE THE FIRST POLL, and the poll is awaited after it, so
265
+ * the UI can paint the code and the spinner while the network is already moving.
266
+ */
267
+ export async function startLogin(input, deps = {}) {
268
+ const baseUrl = normaliseBaseUrl(input.baseUrl) ?? resolveWebBaseUrl();
269
+ const now = deps.now ?? Date.now;
270
+ getLogger().info('cli', 'account.login_started', { baseUrl });
271
+ const authorized = await authorizeDevice(input, baseUrl, deps, now);
272
+ if (!authorized.ok) {
273
+ getLogger().warn('cli', 'account.login_failed', { baseUrl, reason: authorized.failure.reason });
274
+ return authorized.failure;
275
+ }
276
+ // Registered BEFORE any further I/O: from here on the token is in the process,
277
+ // and every record written from now on - including one from a bug below - has
278
+ // to be redacted.
279
+ registerSecret(authorized.token.accessToken);
280
+ const me = await fetchMe(baseUrl, authorized.token.accessToken, deps, input.signal);
281
+ if (me.kind === 'cancelled') {
282
+ return failed('cancelled', describeLoginFailure('cancelled', baseUrl));
283
+ }
284
+ if (me.kind === 'rejected') {
285
+ getLogger().warn('cli', 'account.login_failed', { baseUrl, reason: 'me_rejected' });
286
+ return failed('invalid', describeTokenRejected(baseUrl));
287
+ }
288
+ if (me.kind === 'network') {
289
+ getLogger().warn('cli', 'account.login_failed', { baseUrl, reason: 'me_network' });
290
+ return failed('network', describeTokenRejected(baseUrl));
291
+ }
292
+ const record = buildRecord(baseUrl, authorized.token, me.me, now());
293
+ if (!writeAccount(record)) {
294
+ getLogger().warn('cli', 'account.login_failed', { baseUrl, reason: 'save' });
295
+ return failed('invalid', describeSaveFailure(getAccountPath()));
296
+ }
297
+ getLogger().info('cli', 'account.login_succeeded', {
298
+ baseUrl,
299
+ username: record.user.username,
300
+ tokenPrefix: record.tokenPrefix,
301
+ expiresAt: record.expiresAt,
302
+ scopes: record.scopes.length,
303
+ });
304
+ return { ok: true, account: { username: record.user.username, expiresAt: record.expiresAt } };
305
+ }
@@ -0,0 +1,62 @@
1
+ /**
2
+ * The four account states, and the "3 days left" line of the spec (C4).
3
+ *
4
+ * PURE CLASSIFICATION, NO CLOCK READ: `readAccountStatus(now)` takes the time as
5
+ * an argument (defaulting to `Date.now()` only at the boundary), so every
6
+ * boundary case is testable without freezing globals, and the UI can render a
7
+ * countdown by passing the time it already has.
8
+ *
9
+ * THE BOUNDARIES ARE WRITTEN DOWN HERE BECAUSE THE COPY DEPENDS ON THEM:
10
+ *
11
+ * remaining = expiresAt - now
12
+ * remaining <= 0 -> expired (0 and negative included)
13
+ * ceil(remaining / DAY) <= 3 -> expiring (exactly 3 days included)
14
+ * otherwise -> valid
15
+ *
16
+ * `ceil` is what makes "exactly 3 days" land on the right side: 3 days minus one
17
+ * millisecond rounds up to 3, 3 days plus one millisecond rounds up to 4. The
18
+ * result is that `expiring` means exactly `remaining <= 3 days`, and `daysLeft`
19
+ * means "calendar days of use left, a partial day counts as one" - which is the
20
+ * number a user reads as "expires in 3 days".
21
+ */
22
+ /** Warn when the credential has this many days (or fewer) left (spec section 1). */
23
+ export declare const EXPIRY_WARN_DAYS = 3;
24
+ export declare const DAY_MS: number;
25
+ export type AccountState = 'signed-out' | 'valid' | 'expiring' | 'expired';
26
+ /**
27
+ * What every surface renders from: the slash command, the startup notice and the
28
+ * status line. `expiresAt` / `user` / `tokenPrefix` are `null` only when
29
+ * `state === 'signed-out'`; an EXPIRED credential still reports who it belonged
30
+ * to, because "the login for ada expired" is more useful than "signed out".
31
+ */
32
+ export interface AccountStatus {
33
+ readonly state: AccountState;
34
+ readonly daysLeft: number;
35
+ readonly expiresAt: number | null;
36
+ readonly user: {
37
+ readonly username: string;
38
+ } | null;
39
+ readonly tokenPrefix: string | null;
40
+ }
41
+ export interface ExpiryClassification {
42
+ readonly state: AccountState;
43
+ readonly daysLeft: number;
44
+ }
45
+ /**
46
+ * `expiresAt` vs `now`, both epoch milliseconds - the pure half of the module.
47
+ *
48
+ * A non-finite `expiresAt` is treated as expired rather than as "never expires":
49
+ * `account.json` is hand-editable and `Number.NaN` must not read as a credential
50
+ * that is valid forever.
51
+ */
52
+ export declare function classifyExpiry(expiresAt: number, now: number): ExpiryClassification;
53
+ /**
54
+ * Read the credential off disk and classify it against `now`.
55
+ *
56
+ * READS THE FILE EVERY CALL, with no process-lifetime cache: the two things that
57
+ * move are the clock (a session that runs for a week must notice the credential
58
+ * ran out) and the file itself (`/login` and `/logout` in another terminal). The
59
+ * file is a few hundred bytes; a cache here would buy nothing and would need an
60
+ * invalidation story the moment `clearAccount()` exists.
61
+ */
62
+ export declare function readAccountStatus(now?: number): AccountStatus;
@@ -0,0 +1,63 @@
1
+ /**
2
+ * The four account states, and the "3 days left" line of the spec (C4).
3
+ *
4
+ * PURE CLASSIFICATION, NO CLOCK READ: `readAccountStatus(now)` takes the time as
5
+ * an argument (defaulting to `Date.now()` only at the boundary), so every
6
+ * boundary case is testable without freezing globals, and the UI can render a
7
+ * countdown by passing the time it already has.
8
+ *
9
+ * THE BOUNDARIES ARE WRITTEN DOWN HERE BECAUSE THE COPY DEPENDS ON THEM:
10
+ *
11
+ * remaining = expiresAt - now
12
+ * remaining <= 0 -> expired (0 and negative included)
13
+ * ceil(remaining / DAY) <= 3 -> expiring (exactly 3 days included)
14
+ * otherwise -> valid
15
+ *
16
+ * `ceil` is what makes "exactly 3 days" land on the right side: 3 days minus one
17
+ * millisecond rounds up to 3, 3 days plus one millisecond rounds up to 4. The
18
+ * result is that `expiring` means exactly `remaining <= 3 days`, and `daysLeft`
19
+ * means "calendar days of use left, a partial day counts as one" - which is the
20
+ * number a user reads as "expires in 3 days".
21
+ */
22
+ import { readAccount } from './store.js';
23
+ /** Warn when the credential has this many days (or fewer) left (spec section 1). */
24
+ export const EXPIRY_WARN_DAYS = 3;
25
+ export const DAY_MS = 24 * 60 * 60 * 1000;
26
+ /**
27
+ * `expiresAt` vs `now`, both epoch milliseconds - the pure half of the module.
28
+ *
29
+ * A non-finite `expiresAt` is treated as expired rather than as "never expires":
30
+ * `account.json` is hand-editable and `Number.NaN` must not read as a credential
31
+ * that is valid forever.
32
+ */
33
+ export function classifyExpiry(expiresAt, now) {
34
+ const remaining = expiresAt - now;
35
+ if (!Number.isFinite(remaining) || remaining <= 0) {
36
+ return { state: 'expired', daysLeft: 0 };
37
+ }
38
+ const daysLeft = Math.ceil(remaining / DAY_MS);
39
+ return { state: daysLeft <= EXPIRY_WARN_DAYS ? 'expiring' : 'valid', daysLeft };
40
+ }
41
+ /**
42
+ * Read the credential off disk and classify it against `now`.
43
+ *
44
+ * READS THE FILE EVERY CALL, with no process-lifetime cache: the two things that
45
+ * move are the clock (a session that runs for a week must notice the credential
46
+ * ran out) and the file itself (`/login` and `/logout` in another terminal). The
47
+ * file is a few hundred bytes; a cache here would buy nothing and would need an
48
+ * invalidation story the moment `clearAccount()` exists.
49
+ */
50
+ export function readAccountStatus(now = Date.now()) {
51
+ const account = readAccount();
52
+ if (account === null) {
53
+ return { state: 'signed-out', daysLeft: 0, expiresAt: null, user: null, tokenPrefix: null };
54
+ }
55
+ const { state, daysLeft } = classifyExpiry(account.expiresAt, now);
56
+ return {
57
+ state,
58
+ daysLeft,
59
+ expiresAt: account.expiresAt,
60
+ user: { username: account.user.username },
61
+ tokenPrefix: account.tokenPrefix,
62
+ };
63
+ }