@aragon-agent/cli 0.6.70 → 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.
Files changed (64) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/README.md +33 -14
  3. package/dist/account/config.d.ts +61 -0
  4. package/dist/account/config.js +83 -0
  5. package/dist/account/device-client.d.ts +113 -0
  6. package/dist/account/device-client.js +425 -0
  7. package/dist/account/format.d.ts +51 -0
  8. package/dist/account/format.js +102 -0
  9. package/dist/account/login-flow.d.ts +68 -0
  10. package/dist/account/login-flow.js +305 -0
  11. package/dist/account/session.d.ts +62 -0
  12. package/dist/account/session.js +63 -0
  13. package/dist/account/store.d.ts +86 -0
  14. package/dist/account/store.js +231 -0
  15. package/dist/agent/controller.d.ts +25 -1
  16. package/dist/agent/controller.js +78 -3
  17. package/dist/agent/project-guidance-prompt.js +97 -97
  18. package/dist/app/App.d.ts +12 -3
  19. package/dist/app/App.js +216 -3
  20. package/dist/cli.js +2 -2
  21. package/dist/commands/account-command.d.ts +86 -0
  22. package/dist/commands/account-command.js +165 -0
  23. package/dist/commands/builtins.js +15 -0
  24. package/dist/commands/catalog.js +17 -1
  25. package/dist/config/app-paths.d.ts +15 -0
  26. package/dist/config/app-paths.js +17 -0
  27. package/dist/config/cli-commands.d.ts +1 -1
  28. package/dist/config/cli-commands.js +4 -0
  29. package/dist/config/env.js +6 -0
  30. package/dist/config/load.js +36 -1
  31. package/dist/governance/engine/lifecycle.js +1 -1
  32. package/dist/governance/prompts/orchestrator-block.js +3 -3
  33. package/dist/host/controller-factory.d.ts +15 -0
  34. package/dist/host/controller-factory.js +10 -2
  35. package/dist/host/memory.d.ts +5 -1
  36. package/dist/host/memory.js +13 -0
  37. package/dist/memory/block.d.ts +38 -4
  38. package/dist/memory/block.js +52 -5
  39. package/dist/memory/command.js +56 -2
  40. package/dist/memory/journal.d.ts +58 -0
  41. package/dist/memory/journal.js +202 -0
  42. package/dist/memory/ledger.d.ts +54 -0
  43. package/dist/memory/ledger.js +105 -0
  44. package/dist/memory/paths.d.ts +10 -0
  45. package/dist/memory/paths.js +31 -0
  46. package/dist/memory/service.d.ts +54 -1
  47. package/dist/memory/service.js +156 -1
  48. package/dist/memory/store.d.ts +21 -3
  49. package/dist/memory/store.js +66 -6
  50. package/dist/memory/tools-batch.d.ts +27 -0
  51. package/dist/memory/tools-batch.js +462 -0
  52. package/dist/memory/tools-shared.d.ts +176 -0
  53. package/dist/memory/tools-shared.js +305 -0
  54. package/dist/memory/tools.d.ts +19 -28
  55. package/dist/memory/tools.js +148 -228
  56. package/dist/memory/undo.d.ts +53 -0
  57. package/dist/memory/undo.js +173 -0
  58. package/dist/redteam/prompt-template.js +16 -16
  59. package/dist/tools/index.d.ts +2 -2
  60. package/dist/tools/index.js +16 -1
  61. package/package.json +3 -3
  62. package/runtime/insecure-tls-warning.cjs +62 -62
  63. package/runtime/insecure-tls-warning.d.cts +5 -5
  64. package/skills/project-indexer/templates/artifact-hygiene-template.md +14 -14
@@ -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
+ }
@@ -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;