@agentage/cli 0.38.0 → 0.39.0
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/dist/cli.js +5 -3
- package/dist/commands/auth/setup.d.ts +6 -14
- package/dist/commands/auth/setup.js +9 -121
- package/dist/commands/plugins/status-print.d.ts +2 -0
- package/dist/commands/plugins/status-print.js +44 -0
- package/dist/commands/plugins/status-rows.d.ts +51 -0
- package/dist/commands/plugins/status-rows.js +58 -0
- package/dist/commands/status/status.d.ts +9 -3
- package/dist/commands/status/status.js +53 -8
- package/dist/commands/update/update.d.ts +3 -1
- package/dist/commands/update/update.js +25 -22
- package/dist/core/loader/discover.d.ts +33 -0
- package/dist/core/loader/discover.js +103 -0
- package/dist/core/loader/manifest.d.ts +16 -0
- package/dist/core/loader/manifest.js +66 -0
- package/dist/core/loader/state.d.ts +12 -0
- package/dist/core/loader/state.js +21 -0
- package/dist/core/loader/states.d.ts +7 -0
- package/dist/core/loader/states.js +52 -0
- package/dist/core/paths.d.ts +4 -0
- package/dist/core/paths.js +6 -0
- package/dist/core/profile/machine.d.ts +18 -0
- package/dist/core/profile/machine.js +60 -0
- package/dist/core/profile/merge.d.ts +11 -0
- package/dist/core/profile/merge.js +16 -0
- package/dist/core/profile/profile.d.ts +6 -0
- package/dist/core/profile/profile.js +34 -0
- package/dist/core/profile/schema.d.ts +26 -0
- package/dist/core/profile/schema.js +143 -0
- package/dist/core/semver-range.d.ts +16 -0
- package/dist/core/semver-range.js +116 -0
- package/dist/lib/auth/api.d.ts +3 -2
- package/dist/lib/auth/api.js +50 -56
- package/dist/lib/auth/callback-page.d.ts +2 -0
- package/dist/lib/auth/callback-page.js +40 -0
- package/dist/lib/auth/callback-server.js +1 -4
- package/dist/lib/auth/env-match.js +1 -0
- package/dist/lib/auth/introspect.js +10 -11
- package/dist/lib/auth/oauth.d.ts +2 -0
- package/dist/lib/auth/oauth.js +30 -28
- package/dist/lib/auth/sign-in.d.ts +20 -0
- package/dist/lib/auth/sign-in.js +95 -0
- package/dist/lib/fs/config.d.ts +1 -0
- package/dist/lib/fs/config.js +14 -21
- package/dist/lib/fs/file-lock.d.ts +7 -2
- package/dist/lib/fs/file-lock.js +64 -74
- package/dist/lib/fs/json-file.d.ts +3 -0
- package/dist/lib/fs/json-file.js +43 -0
- package/dist/lib/net/fetch.d.ts +10 -0
- package/dist/lib/net/fetch.js +13 -0
- package/dist/lib/net/http.js +51 -23
- package/dist/lib/npm/npm-cli.d.ts +17 -0
- package/dist/lib/npm/npm-cli.js +77 -0
- package/dist/lib/status/status-info.js +1 -0
- package/dist/lib/update/update-cache.d.ts +1 -0
- package/dist/lib/update/update-cache.js +7 -11
- package/dist/lib/update/update-check.js +1 -4
- package/dist/program.d.ts +18 -1
- package/dist/program.js +75 -32
- package/package.json +1 -1
- package/dist/lib/update/update-lock.d.ts +0 -2
- package/dist/lib/update/update-lock.js +0 -109
package/dist/lib/auth/api.js
CHANGED
|
@@ -1,45 +1,52 @@
|
|
|
1
1
|
import { mutateAuth } from '../fs/config.js';
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
2
|
+
import { cliFetch, isRedirect } from '../net/fetch.js';
|
|
3
|
+
import {} from '../net/origins.js';
|
|
4
4
|
import { AuthRequiredError, isTerminalRefresh, TransientAuthError } from './auth-errors.js';
|
|
5
|
+
import { refreshTokens, TokenRequestError, tokensFrom } from './oauth.js';
|
|
5
6
|
export { AuthRequiredError, TransientAuthError } from './auth-errors.js';
|
|
6
|
-
|
|
7
|
-
const cliHeaders = () => requestHeaders();
|
|
8
|
-
// Refresh the stored token in place. On success mutates auth + persists and returns. On failure it
|
|
9
|
-
// throws: AuthRequiredError when the grant is dead (401/invalid_grant/invalid_client), else
|
|
10
|
-
// TransientAuthError (429/5xx/network/timeout) - a blip that must not be read as a dead session.
|
|
11
|
-
export const refreshOrThrow = async (auth, links) => {
|
|
12
|
-
if (auth.kind === 'pat')
|
|
13
|
-
throw new AuthRequiredError('personal access token expired or revoked - mint a new one in the dashboard (Settings -> API tokens)');
|
|
14
|
-
if (!auth.tokens.refreshToken)
|
|
15
|
-
throw new AuthRequiredError('no refresh token');
|
|
16
|
-
let fresh;
|
|
7
|
+
const requestTokens = async (auth, links, rt) => {
|
|
17
8
|
try {
|
|
18
|
-
|
|
9
|
+
return tokensFrom(await refreshTokens(links.auth, auth.clientId, rt), rt);
|
|
19
10
|
}
|
|
20
11
|
catch (err) {
|
|
21
12
|
if (err instanceof TokenRequestError && isTerminalRefresh(err.status, err.oauthError))
|
|
22
13
|
throw new AuthRequiredError('session expired');
|
|
23
14
|
throw new TransientAuthError('refresh temporarily failed');
|
|
24
15
|
}
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
expiresAt: fresh.expires_in ? Date.now() + fresh.expires_in * 1000 : undefined,
|
|
29
|
-
};
|
|
30
|
-
auth.tokens = tokens; // the caller retries its request with this in-memory copy
|
|
31
|
-
// Persist under the lock, folding the new tokens onto the freshly-read state so a concurrent
|
|
32
|
-
// writer's other fields (clientId, siteFqdn) are not clobbered by a stale in-memory copy. A null
|
|
33
|
-
// re-read means a sign-out won the race: skip the write rather than resurrect it (issue #236).
|
|
16
|
+
};
|
|
17
|
+
// Never resurrect a sign-out (null) or overwrite a newer sign-in by another client.
|
|
18
|
+
const persistTokens = async (clientId, tokens) => {
|
|
34
19
|
await mutateAuth((current) => {
|
|
35
|
-
if (!current)
|
|
20
|
+
if (!current || current.clientId !== clientId)
|
|
36
21
|
return null;
|
|
37
22
|
current.tokens = tokens;
|
|
38
23
|
return current;
|
|
39
24
|
});
|
|
40
25
|
};
|
|
41
|
-
|
|
42
|
-
|
|
26
|
+
const refreshAndPersist = async (auth, links, rt) => {
|
|
27
|
+
const tokens = await requestTokens(auth, links, rt);
|
|
28
|
+
await persistTokens(auth.clientId, tokens);
|
|
29
|
+
return tokens;
|
|
30
|
+
};
|
|
31
|
+
// Keyed by refresh token: parallel 401s share one grant instead of racing its rotation.
|
|
32
|
+
const inflight = new Map();
|
|
33
|
+
const sharedRefresh = (auth, links, rt) => {
|
|
34
|
+
const pending = inflight.get(rt);
|
|
35
|
+
if (pending)
|
|
36
|
+
return pending;
|
|
37
|
+
const next = refreshAndPersist(auth, links, rt).finally(() => inflight.delete(rt));
|
|
38
|
+
inflight.set(rt, next);
|
|
39
|
+
return next;
|
|
40
|
+
};
|
|
41
|
+
// Throws AuthRequiredError for a dead grant, TransientAuthError for a blip (429/5xx/network).
|
|
42
|
+
export const refreshOrThrow = async (auth, links) => {
|
|
43
|
+
if (auth.kind === 'pat')
|
|
44
|
+
throw new AuthRequiredError('personal access token expired or revoked - mint a new one in the dashboard (Settings -> API tokens)');
|
|
45
|
+
const rt = auth.tokens.refreshToken;
|
|
46
|
+
if (!rt)
|
|
47
|
+
throw new AuthRequiredError('no refresh token');
|
|
48
|
+
auth.tokens = await sharedRefresh(auth, links, rt); // the caller retries with this copy
|
|
49
|
+
};
|
|
43
50
|
const tryRefresh = async (auth, links) => {
|
|
44
51
|
try {
|
|
45
52
|
await refreshOrThrow(auth, links);
|
|
@@ -49,41 +56,28 @@ const tryRefresh = async (auth, links) => {
|
|
|
49
56
|
return false;
|
|
50
57
|
}
|
|
51
58
|
};
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
59
|
+
const withBearer = (auth, init) => ({
|
|
60
|
+
...init,
|
|
61
|
+
headers: { ...init.headers, authorization: `Bearer ${auth.tokens.accessToken}` },
|
|
62
|
+
});
|
|
63
|
+
// The raw Response after at most one refresh-and-retry on 401; callers branch on the status.
|
|
64
|
+
export const authedFetch = async (auth, links, url, init = {}) => {
|
|
65
|
+
const res = await cliFetch(url, withBearer(auth, init));
|
|
66
|
+
if (res.status !== 401 || !(await tryRefresh(auth, links)))
|
|
67
|
+
return res;
|
|
68
|
+
await res.body?.cancel();
|
|
69
|
+
return cliFetch(url, withBearer(auth, init));
|
|
70
|
+
};
|
|
71
|
+
export const authedJson = async (auth, links, url, init = {}) => {
|
|
72
|
+
const method = init.method ?? 'GET';
|
|
73
|
+
const res = await authedFetch(auth, links, url, init);
|
|
62
74
|
if (res.status === 401)
|
|
63
75
|
throw new AuthRequiredError('session expired');
|
|
64
76
|
if (isRedirect(res))
|
|
65
|
-
throw new Error(
|
|
77
|
+
throw new Error(`${method} ${url} refused redirect (${res.status})`);
|
|
66
78
|
if (!res.ok)
|
|
67
|
-
throw new Error(
|
|
79
|
+
throw new Error(`${method} ${url} failed (${res.status})`);
|
|
68
80
|
return (await res.json());
|
|
69
81
|
};
|
|
70
|
-
// A bearer POST with the same refresh-once dance as authedGet. Unlike authedGet it returns the
|
|
71
|
-
// raw Response (never throws on a non-2xx): callers branch on the status codes themselves.
|
|
72
|
-
export const authedPost = async (auth, links, url, body) => {
|
|
73
|
-
const call = () => fetch(url, {
|
|
74
|
-
method: 'POST',
|
|
75
|
-
headers: {
|
|
76
|
-
authorization: `Bearer ${auth.tokens.accessToken}`,
|
|
77
|
-
'content-type': 'application/json',
|
|
78
|
-
...cliHeaders(),
|
|
79
|
-
},
|
|
80
|
-
body: JSON.stringify(body),
|
|
81
|
-
redirect: 'manual',
|
|
82
|
-
});
|
|
83
|
-
let res = await call();
|
|
84
|
-
if (res.status === 401 && (await tryRefresh(auth, links)))
|
|
85
|
-
res = await call();
|
|
86
|
-
return res;
|
|
87
|
-
};
|
|
88
82
|
// Re-export the introspection surface so existing callers keep importing from './api.js'.
|
|
89
83
|
export { introspectToken } from './introspect.js';
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
// The one page the CLI ever serves: the sign-in result, on the design-system dark tokens.
|
|
2
|
+
const LOGO = 'M143.8 33.7a13.2 13.2 0 00-23.6 0l-92.4 184.8a13.2 13.2 0 0015.4 18.6l66-18.9a13.2 13.2 0 ' +
|
|
3
|
+
'009.5-12.7v-60.3a13.2 13.2 0 1126.4 0v60.3a13.2 13.2 0 009.6 12.7l66 18.9a13.2 13.2 0 ' +
|
|
4
|
+
'0015.4-18.6l-92.3-184.8z';
|
|
5
|
+
const STYLE = `
|
|
6
|
+
*{margin:0;padding:0;box-sizing:border-box}
|
|
7
|
+
html{color-scheme:dark}
|
|
8
|
+
body{background:oklch(0.085 0.013 277);color:oklch(0.97 0.003 277);
|
|
9
|
+
font-family:system-ui,-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif;
|
|
10
|
+
-webkit-font-smoothing:antialiased;min-height:100vh;display:grid;place-items:center;padding:24px}
|
|
11
|
+
.card{background:oklch(0.17 0.018 277);border:1px solid oklch(0.237 0.017 277);border-radius:.75rem;
|
|
12
|
+
padding:40px 32px;width:100%;max-width:400px;text-align:center;
|
|
13
|
+
box-shadow:0 10px 15px -3px oklch(0 0 0/.1),0 4px 6px -4px oklch(0 0 0/.1)}
|
|
14
|
+
.brand{display:inline-flex;align-items:center;gap:10px;margin-bottom:28px;font-weight:600;font-size:1rem}
|
|
15
|
+
.brand svg{width:28px;height:28px}
|
|
16
|
+
.icon{width:48px;height:48px;border-radius:9999px;margin:0 auto 20px;display:grid;place-items:center}
|
|
17
|
+
.ok .icon{background:oklch(0.723 0.191 149.6/.15);color:oklch(0.723 0.191 149.6)}
|
|
18
|
+
.err .icon{background:oklch(0.628 0.208 25.6/.15);color:oklch(0.628 0.208 25.6)}
|
|
19
|
+
h1{font-size:1.25rem;font-weight:600;letter-spacing:-.02em;margin-bottom:8px}
|
|
20
|
+
p{color:oklch(0.59 0.014 256);font-size:.875rem;line-height:1.5}
|
|
21
|
+
.hint{margin-top:24px;font-size:.75rem;color:oklch(0.59 0.014 256)}
|
|
22
|
+
`;
|
|
23
|
+
const ICON = {
|
|
24
|
+
ok: '<svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M20 6 9 17l-5-5"/></svg>',
|
|
25
|
+
err: '<svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M18 6 6 18M6 6l12 12"/></svg>',
|
|
26
|
+
};
|
|
27
|
+
const ESCAPES = { '&': '&', '<': '<', '>': '>', '"': '"' };
|
|
28
|
+
// The error text comes from the authorization server's redirect: never trust it as markup.
|
|
29
|
+
export const escapeHtml = (text) => text.replace(/[&<>"]/g, (c) => ESCAPES[c] ?? c);
|
|
30
|
+
export const callbackPage = (ok, detail) => {
|
|
31
|
+
const kind = ok ? 'ok' : 'err';
|
|
32
|
+
const title = ok ? 'Signed in' : 'Sign-in failed';
|
|
33
|
+
const hint = ok ? 'You can close this tab.' : 'Run agentage setup again to retry.';
|
|
34
|
+
return (`<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">` +
|
|
35
|
+
`<title>${title} - agentage</title><style>${STYLE}</style></head><body><main class="card ${kind}">` +
|
|
36
|
+
`<div class="brand"><svg viewBox="0 0 416 416" aria-hidden="true"><rect width="416" height="416" rx="83" fill="#f3a52b"/>` +
|
|
37
|
+
`<g transform="translate(25.7 25.7) scale(1.3812)"><path d="${LOGO}" fill="#000"/></g></svg>agentage</div>` +
|
|
38
|
+
`<div class="icon">${ICON[kind]}</div><h1>${title}</h1><p>${escapeHtml(detail)}</p>` +
|
|
39
|
+
`<p class="hint">${hint}</p></main></body></html>`);
|
|
40
|
+
};
|
|
@@ -1,8 +1,5 @@
|
|
|
1
1
|
import { createServer } from 'node:http';
|
|
2
|
-
|
|
3
|
-
'<body style="font-family:system-ui;display:grid;place-items:center;min-height:80vh">' +
|
|
4
|
-
`<div style="text-align:center"><h1>${ok ? 'Signed in' : 'Sign-in failed'}</h1>` +
|
|
5
|
-
`<p>${detail}</p></div></body></html>`;
|
|
2
|
+
import { callbackPage as page } from './callback-page.js';
|
|
6
3
|
export const startCallbackServer = (expectedState) => new Promise((resolveServer) => {
|
|
7
4
|
let settle = null;
|
|
8
5
|
let result = null;
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import {} from '../fs/config.js';
|
|
1
2
|
import { environment, normalizeFqdn } from '../net/origins.js';
|
|
2
3
|
// The stored credential belongs to the environment it was issued for (auth.siteFqdn); the CLI's
|
|
3
4
|
// current target comes from AGENTAGE_SITE_FQDN (production default). Introspecting a dev credential
|
|
@@ -1,4 +1,6 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import {} from '../fs/config.js';
|
|
2
|
+
import {} from '../net/origins.js';
|
|
3
|
+
import { authedJson, refreshOrThrow } from './api.js';
|
|
2
4
|
import { AuthRequiredError, TransientAuthError } from './auth-errors.js';
|
|
3
5
|
const isPast = (iso) => {
|
|
4
6
|
if (!iso)
|
|
@@ -6,17 +8,14 @@ const isPast = (iso) => {
|
|
|
6
8
|
const t = Date.parse(iso);
|
|
7
9
|
return !Number.isNaN(t) && t <= Date.now();
|
|
8
10
|
};
|
|
9
|
-
const
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
});
|
|
14
|
-
// Introspection over global fetch: a network error reflects as a transient (a blip must not read as
|
|
15
|
-
// a dead session), never letting the raw error escape to gatherStatus. Only a 401 stays terminal.
|
|
11
|
+
const RETRY_BACKOFF_MS = 300;
|
|
12
|
+
// Ref'd on purpose: an unref'd backoff let Node exit 13 mid-retry once nothing else held the loop.
|
|
13
|
+
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
14
|
+
// Any failure but a 401 is a transient: a network blip must never read as a dead session.
|
|
16
15
|
const getSession = async (auth, links) => {
|
|
17
16
|
const url = `${links.auth}/api/auth/mcp/get-session`;
|
|
18
17
|
try {
|
|
19
|
-
return await
|
|
18
|
+
return await authedJson(auth, links, url);
|
|
20
19
|
}
|
|
21
20
|
catch (err) {
|
|
22
21
|
if (err instanceof AuthRequiredError)
|
|
@@ -75,7 +74,7 @@ const introspectOnce = async (auth, links) => {
|
|
|
75
74
|
}
|
|
76
75
|
return freshenIfStale(auth, links, body);
|
|
77
76
|
};
|
|
78
|
-
// A retry-once with a short
|
|
77
|
+
// A retry-once with a short backoff absorbs a lone transient blip; a terminal error skips it.
|
|
79
78
|
export const introspectToken = async (auth, links) => {
|
|
80
79
|
try {
|
|
81
80
|
return await introspectOnce(auth, links);
|
|
@@ -83,7 +82,7 @@ export const introspectToken = async (auth, links) => {
|
|
|
83
82
|
catch (err) {
|
|
84
83
|
if (err instanceof AuthRequiredError)
|
|
85
84
|
throw err; // terminal: no point retrying a dead session
|
|
86
|
-
await sleep(
|
|
85
|
+
await sleep(RETRY_BACKOFF_MS);
|
|
87
86
|
return introspectOnce(auth, links); // one transient-only retry; a 2nd transient propagates
|
|
88
87
|
}
|
|
89
88
|
};
|
package/dist/lib/auth/oauth.d.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { type StoredTokens } from '../fs/config.js';
|
|
1
2
|
export interface PkcePair {
|
|
2
3
|
verifier: string;
|
|
3
4
|
challenge: string;
|
|
@@ -12,6 +13,7 @@ export interface TokenResponse {
|
|
|
12
13
|
export declare const DEFAULT_SCOPE = "memory:read memory:write offline_access";
|
|
13
14
|
export declare const pkcePair: () => PkcePair;
|
|
14
15
|
export declare const randomState: () => string;
|
|
16
|
+
export declare const tokensFrom: (res: TokenResponse, previousRefresh?: string) => StoredTokens;
|
|
15
17
|
export declare const registerClient: (authUrl: string, redirectUri: string) => Promise<string>;
|
|
16
18
|
export declare const buildAuthorizeUrl: (authUrl: string, params: {
|
|
17
19
|
clientId: string;
|
package/dist/lib/auth/oauth.js
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
import { createHash, randomBytes } from 'node:crypto';
|
|
2
|
-
import {
|
|
3
|
-
|
|
4
|
-
const cliHeaders = () => requestHeaders();
|
|
2
|
+
import {} from '../fs/config.js';
|
|
3
|
+
import { AUTH_TIMEOUT_MS, cliFetch } from '../net/fetch.js';
|
|
5
4
|
const REGISTER_PATH = '/api/auth/mcp/register';
|
|
6
5
|
const AUTHORIZE_PATH = '/api/auth/mcp/authorize';
|
|
7
6
|
const TOKEN_PATH = '/api/auth/mcp/token';
|
|
8
7
|
const REVOKE_PATH = '/api/auth/mcp/revoke';
|
|
8
|
+
const REVOKE_TIMEOUT_MS = 3_000;
|
|
9
9
|
export const DEFAULT_SCOPE = 'memory:read memory:write offline_access';
|
|
10
10
|
export const pkcePair = () => {
|
|
11
11
|
const verifier = randomBytes(32).toString('base64url');
|
|
@@ -13,18 +13,25 @@ export const pkcePair = () => {
|
|
|
13
13
|
return { verifier, challenge };
|
|
14
14
|
};
|
|
15
15
|
export const randomState = () => randomBytes(16).toString('base64url');
|
|
16
|
+
// A refresh that does not rotate keeps the previous refresh token.
|
|
17
|
+
export const tokensFrom = (res, previousRefresh) => ({
|
|
18
|
+
accessToken: res.access_token,
|
|
19
|
+
refreshToken: res.refresh_token ?? previousRefresh,
|
|
20
|
+
expiresAt: res.expires_in ? Date.now() + res.expires_in * 1000 : undefined,
|
|
21
|
+
});
|
|
22
|
+
const registration = (redirectUri) => JSON.stringify({
|
|
23
|
+
client_name: 'agentage CLI',
|
|
24
|
+
redirect_uris: [redirectUri],
|
|
25
|
+
token_endpoint_auth_method: 'none',
|
|
26
|
+
grant_types: ['authorization_code', 'refresh_token'],
|
|
27
|
+
response_types: ['code'],
|
|
28
|
+
});
|
|
16
29
|
export const registerClient = async (authUrl, redirectUri) => {
|
|
17
|
-
const res = await
|
|
30
|
+
const res = await cliFetch(`${authUrl}${REGISTER_PATH}`, {
|
|
18
31
|
method: 'POST',
|
|
19
|
-
headers: { 'content-type': 'application/json'
|
|
20
|
-
body:
|
|
21
|
-
|
|
22
|
-
redirect_uris: [redirectUri],
|
|
23
|
-
token_endpoint_auth_method: 'none',
|
|
24
|
-
grant_types: ['authorization_code', 'refresh_token'],
|
|
25
|
-
response_types: ['code'],
|
|
26
|
-
}),
|
|
27
|
-
});
|
|
32
|
+
headers: { 'content-type': 'application/json' },
|
|
33
|
+
body: registration(redirectUri),
|
|
34
|
+
}, { timeoutMs: AUTH_TIMEOUT_MS });
|
|
28
35
|
if (!res.ok)
|
|
29
36
|
throw new Error(`client registration failed (${res.status})`);
|
|
30
37
|
const body = (await res.json());
|
|
@@ -55,12 +62,13 @@ export class TokenRequestError extends Error {
|
|
|
55
62
|
this.name = 'TokenRequestError';
|
|
56
63
|
}
|
|
57
64
|
}
|
|
65
|
+
const formInit = (form) => ({
|
|
66
|
+
method: 'POST',
|
|
67
|
+
headers: { 'content-type': 'application/x-www-form-urlencoded' },
|
|
68
|
+
body: new URLSearchParams(form).toString(),
|
|
69
|
+
});
|
|
58
70
|
const postForm = async (url, form) => {
|
|
59
|
-
const res = await
|
|
60
|
-
method: 'POST',
|
|
61
|
-
headers: { 'content-type': 'application/x-www-form-urlencoded', ...cliHeaders() },
|
|
62
|
-
body: new URLSearchParams(form).toString(),
|
|
63
|
-
});
|
|
71
|
+
const res = await cliFetch(url, formInit(form), { timeoutMs: AUTH_TIMEOUT_MS });
|
|
64
72
|
if (!res.ok) {
|
|
65
73
|
const body = (await res.json().catch(() => null));
|
|
66
74
|
throw new TokenRequestError(res.status, body?.error);
|
|
@@ -79,18 +87,12 @@ export const refreshTokens = (authUrl, clientId, refreshToken) => postForm(`${au
|
|
|
79
87
|
refresh_token: refreshToken,
|
|
80
88
|
client_id: clientId,
|
|
81
89
|
});
|
|
82
|
-
//
|
|
83
|
-
|
|
84
|
-
export const revokeToken = async (authUrl, token, timeoutMs = 3000) => {
|
|
90
|
+
// Best-effort with a short cap: local credentials are removed whatever the server says.
|
|
91
|
+
export const revokeToken = async (authUrl, token, timeoutMs = REVOKE_TIMEOUT_MS) => {
|
|
85
92
|
try {
|
|
86
|
-
await
|
|
87
|
-
method: 'POST',
|
|
88
|
-
headers: { 'content-type': 'application/x-www-form-urlencoded', ...cliHeaders() },
|
|
89
|
-
body: new URLSearchParams({ token }).toString(),
|
|
90
|
-
signal: AbortSignal.timeout(timeoutMs),
|
|
91
|
-
});
|
|
93
|
+
await cliFetch(`${authUrl}${REVOKE_PATH}`, formInit({ token }), { timeoutMs });
|
|
92
94
|
}
|
|
93
95
|
catch {
|
|
94
|
-
//
|
|
96
|
+
// a stalled or refused revoke never blocks sign-out
|
|
95
97
|
}
|
|
96
98
|
};
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { startCallbackServer } from './callback-server.js';
|
|
2
|
+
import { introspectToken } from './introspect.js';
|
|
3
|
+
import { exchangeCode, registerClient, revokeToken } from './oauth.js';
|
|
4
|
+
export interface SignInOptions {
|
|
5
|
+
reauth?: boolean;
|
|
6
|
+
browser?: boolean;
|
|
7
|
+
}
|
|
8
|
+
export type SignInResult = 'signed-in' | 'already' | 'mismatch-resigned';
|
|
9
|
+
export interface SignInDeps {
|
|
10
|
+
register: typeof registerClient;
|
|
11
|
+
exchange: typeof exchangeCode;
|
|
12
|
+
revoke: typeof revokeToken;
|
|
13
|
+
startServer: typeof startCallbackServer;
|
|
14
|
+
openBrowser: (url: string) => Promise<void>;
|
|
15
|
+
introspect: typeof introspectToken;
|
|
16
|
+
log: (msg: string) => void;
|
|
17
|
+
}
|
|
18
|
+
export declare const signIn: (opts: SignInOptions, deps?: SignInDeps) => Promise<void>;
|
|
19
|
+
export declare const signOut: (deps?: SignInDeps) => Promise<void>;
|
|
20
|
+
export declare const ensureSignedIn: (opts: SignInOptions, deps?: SignInDeps) => Promise<SignInResult>;
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
import chalk from 'chalk';
|
|
2
|
+
import { deleteAuth, ensureConfigDir, mutateAuth, readAuth } from '../fs/config.js';
|
|
3
|
+
import { links, siteFqdn } from '../net/origins.js';
|
|
4
|
+
import { AuthRequiredError } from './auth-errors.js';
|
|
5
|
+
import { startCallbackServer } from './callback-server.js';
|
|
6
|
+
import { detectEnvMismatch } from './env-match.js';
|
|
7
|
+
import { introspectToken } from './introspect.js';
|
|
8
|
+
import { buildAuthorizeUrl, exchangeCode, pkcePair, randomState, registerClient, revokeToken, tokensFrom, } from './oauth.js';
|
|
9
|
+
const defaultDeps = {
|
|
10
|
+
register: registerClient,
|
|
11
|
+
exchange: exchangeCode,
|
|
12
|
+
revoke: revokeToken,
|
|
13
|
+
startServer: startCallbackServer,
|
|
14
|
+
openBrowser: async (url) => {
|
|
15
|
+
const { default: open } = await import('open');
|
|
16
|
+
await open(url);
|
|
17
|
+
},
|
|
18
|
+
introspect: introspectToken,
|
|
19
|
+
log: (msg) => console.log(msg),
|
|
20
|
+
};
|
|
21
|
+
const promptBrowser = async (url, opts, deps) => {
|
|
22
|
+
deps.log(`\nSign in to agentage (${siteFqdn()}):\n\n ${url}\n`);
|
|
23
|
+
if (opts.browser === false)
|
|
24
|
+
deps.log('Open the URL above in a browser to continue.');
|
|
25
|
+
else
|
|
26
|
+
await deps
|
|
27
|
+
.openBrowser(url)
|
|
28
|
+
.catch(() => deps.log('Could not open a browser - use the URL above.'));
|
|
29
|
+
deps.log('Waiting for sign-in to complete...');
|
|
30
|
+
};
|
|
31
|
+
const authorize = async (server, state, opts, deps) => {
|
|
32
|
+
const authUrl = links(siteFqdn()).auth;
|
|
33
|
+
const { verifier, challenge } = pkcePair();
|
|
34
|
+
const clientId = await deps.register(authUrl, server.redirectUri);
|
|
35
|
+
const redirectUri = server.redirectUri;
|
|
36
|
+
const url = buildAuthorizeUrl(authUrl, { clientId, redirectUri, challenge, state });
|
|
37
|
+
await promptBrowser(url, opts, deps);
|
|
38
|
+
return { clientId, verifier, code: await server.waitForCode() };
|
|
39
|
+
};
|
|
40
|
+
// A fresh DCR client per run: the redirect URI binds this run's ephemeral callback port.
|
|
41
|
+
export const signIn = async (opts, deps = defaultDeps) => {
|
|
42
|
+
const fqdn = siteFqdn();
|
|
43
|
+
ensureConfigDir();
|
|
44
|
+
const state = randomState();
|
|
45
|
+
const server = await deps.startServer(state);
|
|
46
|
+
try {
|
|
47
|
+
const { clientId, code, verifier } = await authorize(server, state, opts, deps);
|
|
48
|
+
const redirectUri = server.redirectUri;
|
|
49
|
+
const res = await deps.exchange(links(fqdn).auth, { clientId, code, redirectUri, verifier });
|
|
50
|
+
await mutateAuth(() => ({ siteFqdn: fqdn, clientId, tokens: tokensFrom(res) }));
|
|
51
|
+
deps.log(chalk.green('\nSigned in.\n'));
|
|
52
|
+
}
|
|
53
|
+
finally {
|
|
54
|
+
server.close();
|
|
55
|
+
}
|
|
56
|
+
};
|
|
57
|
+
export const signOut = async (deps = defaultDeps) => {
|
|
58
|
+
const auth = readAuth();
|
|
59
|
+
if (!auth) {
|
|
60
|
+
deps.log('Nothing to disconnect.');
|
|
61
|
+
return;
|
|
62
|
+
}
|
|
63
|
+
await deps.revoke(links(auth.siteFqdn).auth, auth.tokens.accessToken);
|
|
64
|
+
await deleteAuth();
|
|
65
|
+
deps.log('Disconnected - local credentials removed.');
|
|
66
|
+
};
|
|
67
|
+
const mismatchNote = (m) => `Signed in to ${m.credentialFqdn} (${m.credentialEnv}), but this run targets ` +
|
|
68
|
+
`${m.targetFqdn} (${m.targetEnv}) - signing you into ${m.targetEnv}.\n`;
|
|
69
|
+
// Only a dead session re-signs: a transient verify failure keeps the credentials.
|
|
70
|
+
const verifyStored = async (auth, deps) => {
|
|
71
|
+
try {
|
|
72
|
+
await deps.introspect(auth, links(auth.siteFqdn));
|
|
73
|
+
deps.log(`Already signed in. Run ${chalk.white('agentage setup --reauth')} to sign in again.\n`);
|
|
74
|
+
return true;
|
|
75
|
+
}
|
|
76
|
+
catch (err) {
|
|
77
|
+
if (err instanceof AuthRequiredError) {
|
|
78
|
+
deps.log('Session expired - signing you in again.\n');
|
|
79
|
+
return false;
|
|
80
|
+
}
|
|
81
|
+
deps.log('You appear signed in (could not fully verify - temporary).\n');
|
|
82
|
+
return true;
|
|
83
|
+
}
|
|
84
|
+
};
|
|
85
|
+
// Never introspect a credential against another environment: it would misread as expired.
|
|
86
|
+
export const ensureSignedIn = async (opts, deps = defaultDeps) => {
|
|
87
|
+
const stored = readAuth();
|
|
88
|
+
const mismatch = stored && !opts.reauth ? detectEnvMismatch(stored, siteFqdn()) : null;
|
|
89
|
+
if (mismatch)
|
|
90
|
+
deps.log(mismatchNote(mismatch));
|
|
91
|
+
else if (stored && !opts.reauth && (await verifyStored(stored, deps)))
|
|
92
|
+
return 'already';
|
|
93
|
+
await signIn(opts, deps);
|
|
94
|
+
return mismatch ? 'mismatch-resigned' : 'signed-in';
|
|
95
|
+
};
|
package/dist/lib/fs/config.d.ts
CHANGED
|
@@ -15,6 +15,7 @@ export interface AuthState {
|
|
|
15
15
|
}
|
|
16
16
|
export declare const getConfigDir: () => string;
|
|
17
17
|
export declare const ensureConfigDir: () => string;
|
|
18
|
+
export declare const isAuthState: (value: unknown) => value is AuthState;
|
|
18
19
|
export declare const readAuth: () => AuthState | null;
|
|
19
20
|
export declare const saveAuth: (state: AuthState) => void;
|
|
20
21
|
export declare const deleteAuth: () => Promise<void>;
|
package/dist/lib/fs/config.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync, } from 'node:fs';
|
|
1
|
+
import { existsSync, mkdirSync, unlinkSync } from 'node:fs';
|
|
3
2
|
import { homedir } from 'node:os';
|
|
4
3
|
import { join } from 'node:path';
|
|
5
4
|
import { withFileLock } from './file-lock.js';
|
|
5
|
+
import { isRecord, readJson, writeJsonAtomic } from './json-file.js';
|
|
6
6
|
export const getConfigDir = () => process.env['AGENTAGE_CONFIG_DIR'] || join(process.env['HOME'] || homedir(), '.agentage');
|
|
7
7
|
export const ensureConfigDir = () => {
|
|
8
8
|
const dir = getConfigDir();
|
|
@@ -11,27 +11,20 @@ export const ensureConfigDir = () => {
|
|
|
11
11
|
return dir;
|
|
12
12
|
};
|
|
13
13
|
const authPath = () => join(getConfigDir(), 'auth.json');
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
// Atomic 0600 write: a token file is never left half-written or briefly world-readable. Write a
|
|
26
|
-
// per-save sibling temp (unique name: concurrent savers can never clobber each other's tmp),
|
|
27
|
-
// chmod it 0600 BEFORE the rename, then rename over the target in one step.
|
|
14
|
+
const isOptional = (value, type) => value === undefined || typeof value === type;
|
|
15
|
+
const isStoredTokens = (value) => isRecord(value) &&
|
|
16
|
+
typeof value['accessToken'] === 'string' &&
|
|
17
|
+
isOptional(value['refreshToken'], 'string') &&
|
|
18
|
+
isOptional(value['expiresAt'], 'number');
|
|
19
|
+
// A malformed auth.json (e.g. `{}`) reads as signed out rather than crashing every command.
|
|
20
|
+
export const isAuthState = (value) => isRecord(value) &&
|
|
21
|
+
typeof value['siteFqdn'] === 'string' &&
|
|
22
|
+
typeof value['clientId'] === 'string' &&
|
|
23
|
+
isStoredTokens(value['tokens']);
|
|
24
|
+
export const readAuth = () => readJson(authPath(), isAuthState);
|
|
28
25
|
export const saveAuth = (state) => {
|
|
29
26
|
ensureConfigDir();
|
|
30
|
-
|
|
31
|
-
const tmp = `${path}.${process.pid}.${randomBytes(4).toString('hex')}.tmp`;
|
|
32
|
-
writeFileSync(tmp, JSON.stringify(state, null, 2) + '\n', { encoding: 'utf-8', mode: 0o600 });
|
|
33
|
-
chmodSync(tmp, 0o600);
|
|
34
|
-
renameSync(tmp, path);
|
|
27
|
+
writeJsonAtomic(authPath(), state);
|
|
35
28
|
};
|
|
36
29
|
// Sign-out under the same lock mutateAuth takes (issue #236), so a concurrent token refresh can
|
|
37
30
|
// never slip its re-read+save between this existence check and the unlink.
|
|
@@ -1,3 +1,8 @@
|
|
|
1
|
-
export
|
|
1
|
+
export interface LockOptions {
|
|
2
|
+
ttlMs?: number;
|
|
3
|
+
hardStaleMs?: number;
|
|
4
|
+
maxWaitMs?: number;
|
|
5
|
+
}
|
|
6
|
+
export declare const acquireFileLock: (target: string, now?: number, opts?: LockOptions) => boolean;
|
|
2
7
|
export declare const releaseFileLock: (target: string) => void;
|
|
3
|
-
export declare const withFileLock: <T>(target: string, fn: () => T) => Promise<T>;
|
|
8
|
+
export declare const withFileLock: <T>(target: string, fn: () => T, opts?: LockOptions) => Promise<T>;
|