@aragon-agent/cli 0.6.71 → 0.6.73
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/CHANGELOG.md +29 -0
- package/README.md +20 -0
- package/dist/account/config.d.ts +61 -0
- package/dist/account/config.js +83 -0
- package/dist/account/device-client.d.ts +113 -0
- package/dist/account/device-client.js +425 -0
- package/dist/account/format.d.ts +51 -0
- package/dist/account/format.js +102 -0
- package/dist/account/login-flow.d.ts +68 -0
- package/dist/account/login-flow.js +305 -0
- package/dist/account/session.d.ts +109 -0
- package/dist/account/session.js +109 -0
- package/dist/account/store.d.ts +86 -0
- package/dist/account/store.js +231 -0
- package/dist/app/App.js +397 -8
- package/dist/commands/account-command.d.ts +96 -0
- package/dist/commands/account-command.js +194 -0
- package/dist/commands/builtins.js +19 -0
- package/dist/commands/catalog.js +24 -0
- package/dist/config/app-paths.d.ts +15 -0
- package/dist/config/app-paths.js +17 -0
- package/package.json +3 -3
|
@@ -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,109 @@
|
|
|
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
|
+
/**
|
|
42
|
+
* Everything the header's identity row and the account panel need, read ONCE per
|
|
43
|
+
* event (tui-account-identity-and-panel D-5 / section 6.4).
|
|
44
|
+
*
|
|
45
|
+
* WHY A SECOND READER RATHER THAN A WIDER `AccountStatus`: `readAccountStatus` is
|
|
46
|
+
* consumed by `/login`, by `/logout` and by their tests, and widening its shape would
|
|
47
|
+
* be a change to a contract nobody asked to change. This one is additive, and it is
|
|
48
|
+
* deliberately NOT a credential: there is no `token` field, so a surface that receives
|
|
49
|
+
* a snapshot cannot print the secret.
|
|
50
|
+
*
|
|
51
|
+
* `expiresAt` IS THE ONLY MOVING PART. The panel derives `state` and `daysLeft` on
|
|
52
|
+
* every frame from `classifyExpiry(expiresAt, now)` - a pure function - because the
|
|
53
|
+
* clock changes without the file changing (E-3). Re-reading the file per frame would
|
|
54
|
+
* be a synchronous read on every streamed token.
|
|
55
|
+
*/
|
|
56
|
+
export interface AccountSnapshot {
|
|
57
|
+
readonly username: string;
|
|
58
|
+
readonly email: string | null;
|
|
59
|
+
readonly userId: string;
|
|
60
|
+
readonly scopes: readonly string[];
|
|
61
|
+
readonly tokenPrefix: string;
|
|
62
|
+
readonly baseUrl: string;
|
|
63
|
+
/** Epoch milliseconds. */
|
|
64
|
+
readonly issuedAt: number;
|
|
65
|
+
/** Epoch milliseconds. */
|
|
66
|
+
readonly expiresAt: number;
|
|
67
|
+
/** Absolute path of `<home>/account.json`, for the panel's `file` row. */
|
|
68
|
+
readonly accountPath: string;
|
|
69
|
+
}
|
|
70
|
+
export interface ExpiryClassification {
|
|
71
|
+
readonly state: AccountState;
|
|
72
|
+
readonly daysLeft: number;
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* `expiresAt` vs `now`, both epoch milliseconds - the pure half of the module.
|
|
76
|
+
*
|
|
77
|
+
* A non-finite `expiresAt` is treated as expired rather than as "never expires":
|
|
78
|
+
* `account.json` is hand-editable and `Number.NaN` must not read as a credential
|
|
79
|
+
* that is valid forever.
|
|
80
|
+
*/
|
|
81
|
+
export declare function classifyExpiry(expiresAt: number, now: number): ExpiryClassification;
|
|
82
|
+
/**
|
|
83
|
+
* Read the credential off disk and classify it against `now`.
|
|
84
|
+
*
|
|
85
|
+
* READS THE FILE EVERY CALL, with no process-lifetime cache: the two things that
|
|
86
|
+
* move are the clock (a session that runs for a week must notice the credential
|
|
87
|
+
* ran out) and the file itself (`/login` and `/logout` in another terminal). The
|
|
88
|
+
* file is a few hundred bytes; a cache here would buy nothing and would need an
|
|
89
|
+
* invalidation story the moment `clearAccount()` exists.
|
|
90
|
+
*/
|
|
91
|
+
export declare function readAccountStatus(now?: number): AccountStatus;
|
|
92
|
+
/**
|
|
93
|
+
* The credential's FULL public profile, or `null` while signed out.
|
|
94
|
+
*
|
|
95
|
+
* SAME NO-THROW CONTRACT AS `readAccount`: an unreadable file is `null`, which every
|
|
96
|
+
* caller renders as "not signed in". This is the ONE read the App performs, at mount
|
|
97
|
+
* and after each of the four events that can change the answer (`/login` succeeding,
|
|
98
|
+
* `/logout`, the panel's `r`, and the once-a-minute look for another terminal).
|
|
99
|
+
*/
|
|
100
|
+
export declare function readAccountSnapshot(): AccountSnapshot | null;
|
|
101
|
+
/**
|
|
102
|
+
* The `AccountStatus` view of a snapshot, for the copy that already takes one
|
|
103
|
+
* (`describeExpiry`, `startupAccountNotice`).
|
|
104
|
+
*
|
|
105
|
+
* A PURE FUNCTION, which is the point: the App can hold the snapshot in state and
|
|
106
|
+
* recompute the classification on every frame without touching the disk, and the
|
|
107
|
+
* startup notice still speaks the account layer's own sentences.
|
|
108
|
+
*/
|
|
109
|
+
export declare function statusFromSnapshot(snapshot: AccountSnapshot | null, now?: number): AccountStatus;
|
|
@@ -0,0 +1,109 @@
|
|
|
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 { getAccountPath } from '../config/app-paths.js';
|
|
23
|
+
import { readAccount } from './store.js';
|
|
24
|
+
/** Warn when the credential has this many days (or fewer) left (spec section 1). */
|
|
25
|
+
export const EXPIRY_WARN_DAYS = 3;
|
|
26
|
+
export const DAY_MS = 24 * 60 * 60 * 1000;
|
|
27
|
+
/**
|
|
28
|
+
* `expiresAt` vs `now`, both epoch milliseconds - the pure half of the module.
|
|
29
|
+
*
|
|
30
|
+
* A non-finite `expiresAt` is treated as expired rather than as "never expires":
|
|
31
|
+
* `account.json` is hand-editable and `Number.NaN` must not read as a credential
|
|
32
|
+
* that is valid forever.
|
|
33
|
+
*/
|
|
34
|
+
export function classifyExpiry(expiresAt, now) {
|
|
35
|
+
const remaining = expiresAt - now;
|
|
36
|
+
if (!Number.isFinite(remaining) || remaining <= 0) {
|
|
37
|
+
return { state: 'expired', daysLeft: 0 };
|
|
38
|
+
}
|
|
39
|
+
const daysLeft = Math.ceil(remaining / DAY_MS);
|
|
40
|
+
return { state: daysLeft <= EXPIRY_WARN_DAYS ? 'expiring' : 'valid', daysLeft };
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* Read the credential off disk and classify it against `now`.
|
|
44
|
+
*
|
|
45
|
+
* READS THE FILE EVERY CALL, with no process-lifetime cache: the two things that
|
|
46
|
+
* move are the clock (a session that runs for a week must notice the credential
|
|
47
|
+
* ran out) and the file itself (`/login` and `/logout` in another terminal). The
|
|
48
|
+
* file is a few hundred bytes; a cache here would buy nothing and would need an
|
|
49
|
+
* invalidation story the moment `clearAccount()` exists.
|
|
50
|
+
*/
|
|
51
|
+
export function readAccountStatus(now = Date.now()) {
|
|
52
|
+
const account = readAccount();
|
|
53
|
+
if (account === null) {
|
|
54
|
+
return { state: 'signed-out', daysLeft: 0, expiresAt: null, user: null, tokenPrefix: null };
|
|
55
|
+
}
|
|
56
|
+
const { state, daysLeft } = classifyExpiry(account.expiresAt, now);
|
|
57
|
+
return {
|
|
58
|
+
state,
|
|
59
|
+
daysLeft,
|
|
60
|
+
expiresAt: account.expiresAt,
|
|
61
|
+
user: { username: account.user.username },
|
|
62
|
+
tokenPrefix: account.tokenPrefix,
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* The credential's FULL public profile, or `null` while signed out.
|
|
67
|
+
*
|
|
68
|
+
* SAME NO-THROW CONTRACT AS `readAccount`: an unreadable file is `null`, which every
|
|
69
|
+
* caller renders as "not signed in". This is the ONE read the App performs, at mount
|
|
70
|
+
* and after each of the four events that can change the answer (`/login` succeeding,
|
|
71
|
+
* `/logout`, the panel's `r`, and the once-a-minute look for another terminal).
|
|
72
|
+
*/
|
|
73
|
+
export function readAccountSnapshot() {
|
|
74
|
+
const account = readAccount();
|
|
75
|
+
if (account === null)
|
|
76
|
+
return null;
|
|
77
|
+
return {
|
|
78
|
+
username: account.user.username,
|
|
79
|
+
email: account.user.email ?? null,
|
|
80
|
+
userId: account.user.id,
|
|
81
|
+
scopes: account.scopes,
|
|
82
|
+
tokenPrefix: account.tokenPrefix,
|
|
83
|
+
baseUrl: account.baseUrl,
|
|
84
|
+
issuedAt: account.issuedAt,
|
|
85
|
+
expiresAt: account.expiresAt,
|
|
86
|
+
accountPath: getAccountPath(),
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
/**
|
|
90
|
+
* The `AccountStatus` view of a snapshot, for the copy that already takes one
|
|
91
|
+
* (`describeExpiry`, `startupAccountNotice`).
|
|
92
|
+
*
|
|
93
|
+
* A PURE FUNCTION, which is the point: the App can hold the snapshot in state and
|
|
94
|
+
* recompute the classification on every frame without touching the disk, and the
|
|
95
|
+
* startup notice still speaks the account layer's own sentences.
|
|
96
|
+
*/
|
|
97
|
+
export function statusFromSnapshot(snapshot, now = Date.now()) {
|
|
98
|
+
if (snapshot === null) {
|
|
99
|
+
return { state: 'signed-out', daysLeft: 0, expiresAt: null, user: null, tokenPrefix: null };
|
|
100
|
+
}
|
|
101
|
+
const { state, daysLeft } = classifyExpiry(snapshot.expiresAt, now);
|
|
102
|
+
return {
|
|
103
|
+
state,
|
|
104
|
+
daysLeft,
|
|
105
|
+
expiresAt: snapshot.expiresAt,
|
|
106
|
+
user: { username: snapshot.username },
|
|
107
|
+
tokenPrefix: snapshot.tokenPrefix,
|
|
108
|
+
};
|
|
109
|
+
}
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `<home>/account.json` - the on-disk credential for the device-flow login (C3).
|
|
3
|
+
*
|
|
4
|
+
* FILE SHAPE (version 1, and that version field is the whole migration story):
|
|
5
|
+
*
|
|
6
|
+
* {
|
|
7
|
+
* "version": 1,
|
|
8
|
+
* "baseUrl": "https://aragonagent.com",
|
|
9
|
+
* "token": "<plaintext bearer token>",
|
|
10
|
+
* "tokenPrefix": "aragon_pat_ab12cd34ef56",
|
|
11
|
+
* "user": { "id": "usr_...", "username": "ada", "email": "ada@example.com" },
|
|
12
|
+
* "scopes": ["account:read"],
|
|
13
|
+
* "issuedAt": 1767000000000,
|
|
14
|
+
* "expiresAt": 1768728000000
|
|
15
|
+
* }
|
|
16
|
+
*
|
|
17
|
+
* THE TOKEN IS PLAINTEXT ON PURPOSE. An OS keychain would be better and is not
|
|
18
|
+
* reachable from a CLI that must also run under WSL, in CI and over SSH; what is
|
|
19
|
+
* reachable is 0600 plus an atomic write, which is what `~/.aws/credentials`,
|
|
20
|
+
* `~/.npmrc` and `gh` all do. The file never holds a refresh token, so the blast
|
|
21
|
+
* radius of a leak is one revocable credential with a 20-day ceiling.
|
|
22
|
+
*
|
|
23
|
+
* NEVER THROWS. Every failure mode here - missing file, garbage bytes, a JSON
|
|
24
|
+
* document of the wrong shape, an unwritable home - is an ANSWER, because the
|
|
25
|
+
* only caller that matters runs at startup and a throw there is a CLI that will
|
|
26
|
+
* not start because of a credential file. `readAccount()` answers `null`,
|
|
27
|
+
* `writeAccount()` answers `false`, `clearAccount()` answers whether the file is
|
|
28
|
+
* gone afterwards.
|
|
29
|
+
*/
|
|
30
|
+
/** The only shape this module reads or writes (C3). */
|
|
31
|
+
export declare const ACCOUNT_SCHEMA_VERSION = 1;
|
|
32
|
+
/** POSIX mode for a file holding a bearer token. Ignored on win32. */
|
|
33
|
+
export declare const ACCOUNT_FILE_MODE = 384;
|
|
34
|
+
export interface AccountUser {
|
|
35
|
+
readonly id: string;
|
|
36
|
+
readonly username: string;
|
|
37
|
+
readonly email?: string;
|
|
38
|
+
}
|
|
39
|
+
export interface AccountRecord {
|
|
40
|
+
readonly version: number;
|
|
41
|
+
readonly baseUrl: string;
|
|
42
|
+
readonly token: string;
|
|
43
|
+
readonly tokenPrefix: string;
|
|
44
|
+
readonly user: AccountUser;
|
|
45
|
+
readonly scopes: readonly string[];
|
|
46
|
+
/** Epoch milliseconds. */
|
|
47
|
+
readonly issuedAt: number;
|
|
48
|
+
/** Epoch milliseconds; the device grant's own lifetime, ~20 days (C2). */
|
|
49
|
+
readonly expiresAt: number;
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* The credential on disk, or `null`.
|
|
53
|
+
*
|
|
54
|
+
* `null` covers: no file, an empty file, a half-written file, a document that is
|
|
55
|
+
* not JSON, a JSON scalar, a document of the wrong shape and a document from a
|
|
56
|
+
* newer schema. Callers treat all of them the same way - "not signed in" - which
|
|
57
|
+
* is the only answer that cannot be wrong about a file it could not parse.
|
|
58
|
+
*/
|
|
59
|
+
export declare function readAccount(): AccountRecord | null;
|
|
60
|
+
/**
|
|
61
|
+
* Write the credential atomically: temp file in the same directory, then rename.
|
|
62
|
+
*
|
|
63
|
+
* WHY RENAME AND NOT `writeFileSync(path)`: a write that dies half-way (a full
|
|
64
|
+
* disk, a killed process, a power cut) leaves a TRUNCATED JSON document, and the
|
|
65
|
+
* reader above would then report `signed-out` for a user who did nothing wrong.
|
|
66
|
+
* `rename` is atomic within a directory, so a reader sees either the old file or
|
|
67
|
+
* the new one - never a torn one.
|
|
68
|
+
*
|
|
69
|
+
* THE TEMP NAME CARRIES pid AND A RANDOM SUFFIX: two `aragon` processes logging
|
|
70
|
+
* in at once (a terminal and a desktop host) must not write the same temp file.
|
|
71
|
+
*
|
|
72
|
+
* `chmodSync` AFTER the rename, matching `config/ui-state.ts`: `rename` does not
|
|
73
|
+
* preserve the mode on every platform, and a 0600 temp file renamed into place
|
|
74
|
+
* is only 0600 by luck otherwise. win32 has no POSIX mode to set, so it is
|
|
75
|
+
* skipped there rather than warned about.
|
|
76
|
+
*/
|
|
77
|
+
export declare function writeAccount(record: AccountRecord): boolean;
|
|
78
|
+
/**
|
|
79
|
+
* Delete the credential. IDEMPOTENT: `true` means "there is no credential file
|
|
80
|
+
* now", which is also the answer when there never was one.
|
|
81
|
+
*
|
|
82
|
+
* `false` means the file is still there, and the only cause is a filesystem
|
|
83
|
+
* refusal (a Windows share with an open handle, a read-only directory). The
|
|
84
|
+
* caller may then say "sign-out failed" instead of lying.
|
|
85
|
+
*/
|
|
86
|
+
export declare function clearAccount(): boolean;
|