@agentage/cli 0.50.0 → 0.50.2
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/commands/extension/account.d.ts +1 -1
- package/dist/commands/extension/account.js +17 -10
- package/dist/commands/extension/setup-cloud.js +2 -2
- package/dist/commands/extension/sync.js +1 -1
- package/dist/commands/status/status.js +1 -1
- package/dist/lib/auth/api.d.ts +1 -0
- package/dist/lib/auth/api.js +7 -6
- package/dist/lib/auth/credentials.d.ts +1 -0
- package/dist/lib/auth/credentials.js +11 -0
- package/dist/lib/auth/env-match.d.ts +3 -2
- package/dist/lib/auth/env-match.js +10 -7
- package/dist/lib/auth/platform-pat.d.ts +6 -0
- package/dist/lib/auth/platform-pat.js +82 -0
- package/dist/lib/auth/sign-in.d.ts +2 -0
- package/dist/lib/auth/sign-in.js +23 -12
- package/dist/lib/fs/config.d.ts +7 -0
- package/dist/lib/fs/config.js +1 -0
- package/dist/lib/net/discovery.d.ts +9 -1
- package/dist/lib/net/discovery.js +51 -9
- package/dist/lib/status/status-info.js +20 -8
- package/package.json +2 -2
|
@@ -1,24 +1,31 @@
|
|
|
1
1
|
import {} from '../../core/profile/cloud.js';
|
|
2
2
|
import { authedFetch } from '../../lib/auth/api.js';
|
|
3
3
|
import { resolveAuth } from '../../lib/auth/credentials.js';
|
|
4
|
-
import { detectEnvMismatch } from '../../lib/auth/env-match.js';
|
|
4
|
+
import { credentialLinks, detectEnvMismatch } from '../../lib/auth/env-match.js';
|
|
5
5
|
import { introspectToken } from '../../lib/auth/introspect.js';
|
|
6
|
-
import {
|
|
7
|
-
import {
|
|
6
|
+
import { platformFetch } from '../../lib/auth/platform-pat.js';
|
|
7
|
+
import { discoverTarget } from '../../lib/net/discovery.js';
|
|
8
|
+
import { apiOrigin, siteFqdn } from '../../lib/net/origins.js';
|
|
8
9
|
const CLIENT = { 'x-client-type': 'cli' };
|
|
9
10
|
// Read before any extension loads: the token is captured here, the fetch at CLI start.
|
|
10
|
-
export const signedInAccount = (opts = {}) => {
|
|
11
|
+
export const signedInAccount = async (opts = {}) => {
|
|
11
12
|
const auth = resolveAuth(opts);
|
|
12
13
|
const fqdn = siteFqdn();
|
|
13
|
-
if (auth === null
|
|
14
|
+
if (auth === null)
|
|
14
15
|
return null;
|
|
15
|
-
const
|
|
16
|
+
const found = () => discoverTarget(fqdn);
|
|
17
|
+
// Discovery is asked only when the derived issuer differs from the credential's.
|
|
18
|
+
const derived = detectEnvMismatch(auth, fqdn) !== null;
|
|
19
|
+
if (derived && detectEnvMismatch(auth, fqdn, (await found()).links.auth) !== null)
|
|
20
|
+
return null;
|
|
21
|
+
const target = credentialLinks(auth);
|
|
16
22
|
const to = (base) => async (path, { headers, timeoutMs, ...init } = {}) => authedFetch(auth, target, `${await base()}${path}`, { ...init, headers: { ...CLIENT, ...headers } }, { timeoutMs });
|
|
17
|
-
|
|
18
|
-
const discovered = () => (found ??= discoverPlatform(fqdn));
|
|
19
|
-
const platform = async () => (await discovered()).url;
|
|
23
|
+
const platform = async () => (await found()).platform.url;
|
|
20
24
|
const fetch = to(() => apiOrigin(fqdn));
|
|
21
|
-
const machines =
|
|
25
|
+
const machines = async (path, { headers, timeoutMs, ...init } = {}) => {
|
|
26
|
+
const sent = { ...init, headers: { ...CLIENT, ...headers } };
|
|
27
|
+
return platformFetch(auth, target, await found(), path, sent, { timeoutMs });
|
|
28
|
+
};
|
|
22
29
|
const id = () => introspectToken(auth, target).then((s) => s.userId ?? null, () => null);
|
|
23
30
|
return { fetch, machines, platform, id };
|
|
24
31
|
};
|
|
@@ -74,7 +74,7 @@ const connect = async (account) => {
|
|
|
74
74
|
};
|
|
75
75
|
// Registration runs alongside the profile, so it never delays setup by more than its 2 s.
|
|
76
76
|
export const accountSetup = async (deps) => {
|
|
77
|
-
const account = deps.account();
|
|
77
|
+
const account = await deps.account();
|
|
78
78
|
if (account === null)
|
|
79
79
|
return fromLocalCopy('not signed in', deps);
|
|
80
80
|
const platform = await account.platform();
|
|
@@ -91,7 +91,7 @@ export const accountSetup = async (deps) => {
|
|
|
91
91
|
// setup --disconnect: the account marks this machine disconnected, then it forgets the account.
|
|
92
92
|
export const disconnect = async (deps) => {
|
|
93
93
|
const machine = readMachine();
|
|
94
|
-
const account = deps.account();
|
|
94
|
+
const account = await deps.account();
|
|
95
95
|
if (machine !== null && account !== null)
|
|
96
96
|
await disconnectMachine(account.machines, machine.id);
|
|
97
97
|
await deps.signOut();
|
|
@@ -26,7 +26,7 @@ export const pullForEdit = async (deps) => {
|
|
|
26
26
|
const machine = await loadMachine();
|
|
27
27
|
if (machine.profileSource !== 'cloud')
|
|
28
28
|
return null;
|
|
29
|
-
const account = deps.account();
|
|
29
|
+
const account = await deps.account();
|
|
30
30
|
if (account === null)
|
|
31
31
|
throw new Error(NOT_SIGNED_IN);
|
|
32
32
|
await checkAccount(account, machine);
|
|
@@ -54,7 +54,7 @@ export const printStatus = (report) => {
|
|
|
54
54
|
// `account` false: the report that closes setup, which reached the account already.
|
|
55
55
|
export const statusDeps = (account = true) => ({
|
|
56
56
|
gather: (opts) => gatherStatus(resolveAuth({ token: opts.token }), siteFqdn()),
|
|
57
|
-
extensions: (opts) => account ?
|
|
57
|
+
extensions: (opts) => account ? signedInAccount({ token: opts.token }).then(gatherWithAccount) : gatherExtensions(),
|
|
58
58
|
});
|
|
59
59
|
const settle = async (deps, opts) => {
|
|
60
60
|
try {
|
package/dist/lib/auth/api.d.ts
CHANGED
|
@@ -2,6 +2,7 @@ import { type AuthState } from '../fs/config.js';
|
|
|
2
2
|
import { type CliFetchOptions, type CliRequestInit } from '../net/fetch.js';
|
|
3
3
|
import { type Links } from '../net/origins.js';
|
|
4
4
|
export { AuthRequiredError, TransientAuthError } from './auth-errors.js';
|
|
5
|
+
export declare const updateSession: (clientId: string, change: (current: AuthState) => void) => Promise<AuthState | null>;
|
|
5
6
|
export declare const refreshOrThrow: (auth: AuthState, links: Links) => Promise<void>;
|
|
6
7
|
export declare const authedFetch: (auth: AuthState, links: Links, url: string, init?: CliRequestInit, opts?: CliFetchOptions) => Promise<Response>;
|
|
7
8
|
export declare const authedJson: <T>(auth: AuthState, links: Links, url: string, init?: CliRequestInit) => Promise<T>;
|
package/dist/lib/auth/api.js
CHANGED
|
@@ -15,13 +15,14 @@ const requestTokens = async (auth, links, rt) => {
|
|
|
15
15
|
}
|
|
16
16
|
};
|
|
17
17
|
// Never resurrect a sign-out (null) or overwrite a newer sign-in by another client.
|
|
18
|
+
export const updateSession = (clientId, change) => mutateAuth((current) => {
|
|
19
|
+
if (!current || current.clientId !== clientId)
|
|
20
|
+
return null;
|
|
21
|
+
change(current);
|
|
22
|
+
return current;
|
|
23
|
+
});
|
|
18
24
|
const persistTokens = async (clientId, tokens) => {
|
|
19
|
-
await
|
|
20
|
-
if (!current || current.clientId !== clientId)
|
|
21
|
-
return null;
|
|
22
|
-
current.tokens = tokens;
|
|
23
|
-
return current;
|
|
24
|
-
});
|
|
25
|
+
await updateSession(clientId, (current) => void (current.tokens = tokens));
|
|
25
26
|
};
|
|
26
27
|
const refreshAndPersist = async (auth, links, rt) => {
|
|
27
28
|
const tokens = await requestTokens(auth, links, rt);
|
|
@@ -8,5 +8,6 @@ export declare const isPatShape: (value: string) => boolean;
|
|
|
8
8
|
export declare const assertPatShape: (value: string) => string;
|
|
9
9
|
export declare const rawPatToken: (opts?: PatOptions) => string | undefined;
|
|
10
10
|
export declare const patAuthState: (token: string, fqdn?: string) => AuthState;
|
|
11
|
+
export declare const jwtPatExpiry: (token: string) => string | null;
|
|
11
12
|
export declare const isPatAuth: (auth: AuthState | null) => boolean;
|
|
12
13
|
export declare const resolveAuth: (opts?: PatOptions, read?: () => AuthState | null) => AuthState | null;
|
|
@@ -38,6 +38,17 @@ export const patAuthState = (token, fqdn = siteFqdn()) => ({
|
|
|
38
38
|
kind: 'pat',
|
|
39
39
|
tokens: { accessToken: assertPatShape(token) },
|
|
40
40
|
});
|
|
41
|
+
// A JWT PAT (aga_<jwt>) is not introspectable: its exp is read here, the platform verifies it.
|
|
42
|
+
export const jwtPatExpiry = (token) => {
|
|
43
|
+
const payload = token.slice(PAT_PREFIX.length).split('.')[1] ?? '';
|
|
44
|
+
try {
|
|
45
|
+
const { exp } = JSON.parse(Buffer.from(payload, 'base64url').toString());
|
|
46
|
+
return typeof exp === 'number' ? new Date(exp * 1000).toISOString() : null;
|
|
47
|
+
}
|
|
48
|
+
catch {
|
|
49
|
+
return null;
|
|
50
|
+
}
|
|
51
|
+
};
|
|
41
52
|
export const isPatAuth = (auth) => auth?.kind === 'pat';
|
|
42
53
|
// Resolve the active credential with precedence flag > env PAT > stored OAuth. When a PAT is
|
|
43
54
|
// present the OAuth/DCR flow is skipped entirely and the PAT is the bearer; otherwise fall back to
|
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
import { type AuthState } from '../fs/config.js';
|
|
2
|
-
import { type Env } from '../net/origins.js';
|
|
2
|
+
import { type Env, type Links } from '../net/origins.js';
|
|
3
3
|
export interface AuthEnvMismatch {
|
|
4
4
|
credentialFqdn: string;
|
|
5
5
|
credentialEnv: Env;
|
|
6
6
|
targetFqdn: string;
|
|
7
7
|
targetEnv: Env;
|
|
8
8
|
}
|
|
9
|
-
export declare const
|
|
9
|
+
export declare const credentialLinks: (auth: AuthState) => Links;
|
|
10
|
+
export declare const detectEnvMismatch: (auth: AuthState, targetFqdn: string, targetIssuer?: string) => AuthEnvMismatch | null;
|
|
@@ -1,13 +1,16 @@
|
|
|
1
1
|
import {} from '../fs/config.js';
|
|
2
|
-
import { environment, normalizeFqdn } from '../net/origins.js';
|
|
3
|
-
//
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
2
|
+
import { environment, links, normalizeFqdn } from '../net/origins.js';
|
|
3
|
+
// A credential stored before the issuer field was kept reads as issued by auth.<its siteFqdn>.
|
|
4
|
+
export const credentialLinks = (auth) => {
|
|
5
|
+
const own = links(normalizeFqdn(auth.siteFqdn));
|
|
6
|
+
return { ...own, auth: auth.issuer ?? own.auth };
|
|
7
|
+
};
|
|
8
|
+
// A credential belongs to its issuer, so one session serves every target naming that issuer.
|
|
9
|
+
// Introspecting it against another issuer would misread as "expired": detect that first.
|
|
10
|
+
export const detectEnvMismatch = (auth, targetFqdn, targetIssuer = links(normalizeFqdn(targetFqdn)).auth) => {
|
|
8
11
|
const credentialFqdn = normalizeFqdn(auth.siteFqdn);
|
|
9
12
|
const target = normalizeFqdn(targetFqdn);
|
|
10
|
-
if (
|
|
13
|
+
if (auth.kind === 'pat' || credentialLinks(auth).auth === targetIssuer)
|
|
11
14
|
return null;
|
|
12
15
|
return {
|
|
13
16
|
credentialFqdn,
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import { type AuthState } from '../fs/config.js';
|
|
2
|
+
import { type Target } from '../net/discovery.js';
|
|
3
|
+
import { type CliFetchOptions, type CliRequestInit } from '../net/fetch.js';
|
|
4
|
+
import { type Links } from '../net/origins.js';
|
|
5
|
+
export declare const revokePlatformPats: (auth: AuthState, bearer?: string) => Promise<void>;
|
|
6
|
+
export declare const platformFetch: (auth: AuthState, links: Links, found: Target, path: string, init: CliRequestInit, opts: CliFetchOptions) => Promise<Response>;
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import {} from '../fs/config.js';
|
|
2
|
+
import {} from '../net/discovery.js';
|
|
3
|
+
import { cliFetch } from '../net/fetch.js';
|
|
4
|
+
import {} from '../net/origins.js';
|
|
5
|
+
import { VERSION } from '../../utils/version.js';
|
|
6
|
+
import { authedFetch, updateSession } from './api.js';
|
|
7
|
+
const DAY_MS = 86_400_000;
|
|
8
|
+
const SCOPES = ['platform:read', 'platform:write'];
|
|
9
|
+
const MINT = JSON.stringify({
|
|
10
|
+
label: 'agentage cli',
|
|
11
|
+
format: 'jwt',
|
|
12
|
+
scopes: SCOPES,
|
|
13
|
+
expiresInDays: 30,
|
|
14
|
+
});
|
|
15
|
+
const withBearer = (init, token) => ({
|
|
16
|
+
...init,
|
|
17
|
+
headers: { ...init.headers, authorization: `Bearer ${token}` },
|
|
18
|
+
});
|
|
19
|
+
const revokePat = (bearer, issuer, id) => cliFetch(`${issuer}/account/pat/${id}`, withBearer({ method: 'DELETE' }, bearer), {
|
|
20
|
+
timeoutMs: 5_000,
|
|
21
|
+
}).then((res) => res.body?.cancel(), () => undefined);
|
|
22
|
+
// Best-effort, before the session that minted them is dropped or replaced.
|
|
23
|
+
export const revokePlatformPats = async (auth, bearer = auth.tokens.accessToken) => {
|
|
24
|
+
const pats = Object.entries(auth.platformPats ?? {});
|
|
25
|
+
await Promise.all(pats.map(([issuer, pat]) => revokePat(bearer, issuer, pat.id)));
|
|
26
|
+
};
|
|
27
|
+
// Once refused, a run stops asking: one line, no second mint, no fallback to the OAuth bearer.
|
|
28
|
+
const refused = new Map();
|
|
29
|
+
const refuse = (issuer, reason) => {
|
|
30
|
+
const err = refused.get(issuer) ?? new Error(reason);
|
|
31
|
+
if (!refused.has(issuer))
|
|
32
|
+
console.error(reason);
|
|
33
|
+
refused.set(issuer, err);
|
|
34
|
+
return err;
|
|
35
|
+
};
|
|
36
|
+
const mint = async (auth, links, opts) => {
|
|
37
|
+
const init = { method: 'POST', headers: { 'content-type': 'application/json' }, body: MINT };
|
|
38
|
+
const res = await authedFetch(auth, links, `${links.auth}/account/pat`, init, opts);
|
|
39
|
+
if (res.status === 201)
|
|
40
|
+
return (await res.json()).data;
|
|
41
|
+
await res.body?.cancel();
|
|
42
|
+
const reason = `platform token refused (${res.status}): auth may be older than ${VERSION}`;
|
|
43
|
+
throw refuse(links.auth, reason);
|
|
44
|
+
};
|
|
45
|
+
// The stored token while it has over a day left, else a new one; the old one is revoked unawaited.
|
|
46
|
+
const tokenFor = async (auth, links, renew, opts) => {
|
|
47
|
+
const old = auth.platformPats?.[links.auth];
|
|
48
|
+
if (!renew && old && Date.parse(old.expiresAt) - Date.now() > DAY_MS)
|
|
49
|
+
return null;
|
|
50
|
+
const { id, token, expiresAt } = await mint(auth, links, opts);
|
|
51
|
+
const pats = { ...auth.platformPats, [links.auth]: { id, token, expiresAt } };
|
|
52
|
+
auth.platformPats = pats;
|
|
53
|
+
await updateSession(auth.clientId, (current) => void (current.platformPats = pats));
|
|
54
|
+
if (old)
|
|
55
|
+
void revokePat(auth.tokens.accessToken, links.auth, old.id);
|
|
56
|
+
return token;
|
|
57
|
+
};
|
|
58
|
+
// A discovered platform takes only a JWT PAT the session mints; an env PAT goes as is.
|
|
59
|
+
export const platformFetch = async (auth, links, found, path, init, opts) => {
|
|
60
|
+
const url = `${found.platform.machines}${path}`;
|
|
61
|
+
if (!found.discovered || auth.kind === 'pat')
|
|
62
|
+
return authedFetch(auth, links, url, init, opts);
|
|
63
|
+
if (found.links.auth !== links.auth)
|
|
64
|
+
throw refuse(links.auth, `platform token: the site's issuer is ${found.links.auth}`);
|
|
65
|
+
const prior = refused.get(links.auth);
|
|
66
|
+
if (prior)
|
|
67
|
+
throw prior;
|
|
68
|
+
const call = async (renew) => {
|
|
69
|
+
const minted = await tokenFor(auth, links, renew, opts);
|
|
70
|
+
const token = minted ?? auth.platformPats[links.auth].token;
|
|
71
|
+
return { minted, res: await cliFetch(url, withBearer(init, token), opts) };
|
|
72
|
+
};
|
|
73
|
+
let { minted, res } = await call(false);
|
|
74
|
+
if (res.status === 401 && minted === null) {
|
|
75
|
+
await res.body?.cancel();
|
|
76
|
+
({ minted, res } = await call(true));
|
|
77
|
+
}
|
|
78
|
+
if (res.status !== 401)
|
|
79
|
+
return res;
|
|
80
|
+
await res.body?.cancel();
|
|
81
|
+
throw refuse(links.auth, 'platform token refused (401) by the platform');
|
|
82
|
+
};
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { type Links } from '../net/origins.js';
|
|
1
2
|
import { startCallbackServer } from './callback-server.js';
|
|
2
3
|
import { introspectToken } from './introspect.js';
|
|
3
4
|
import { exchangeCode, registerClient, revokeToken } from './oauth.js';
|
|
@@ -13,6 +14,7 @@ export interface SignInDeps {
|
|
|
13
14
|
startServer: typeof startCallbackServer;
|
|
14
15
|
openBrowser: (url: string) => Promise<void>;
|
|
15
16
|
introspect: typeof introspectToken;
|
|
17
|
+
discover: (fqdn: string) => Promise<Links>;
|
|
16
18
|
log: (msg: string) => void;
|
|
17
19
|
}
|
|
18
20
|
export declare const signIn: (opts: SignInOptions, deps?: SignInDeps) => Promise<void>;
|
package/dist/lib/auth/sign-in.js
CHANGED
|
@@ -1,10 +1,12 @@
|
|
|
1
1
|
import chalk from 'chalk';
|
|
2
2
|
import { deleteAuth, ensureConfigDir, mutateAuth, readAuth } from '../fs/config.js';
|
|
3
|
-
import {
|
|
3
|
+
import { discoverTarget } from '../net/discovery.js';
|
|
4
|
+
import { siteFqdn } from '../net/origins.js';
|
|
4
5
|
import { AuthRequiredError } from './auth-errors.js';
|
|
5
6
|
import { startCallbackServer } from './callback-server.js';
|
|
6
|
-
import { detectEnvMismatch } from './env-match.js';
|
|
7
|
+
import { credentialLinks, detectEnvMismatch } from './env-match.js';
|
|
7
8
|
import { introspectToken } from './introspect.js';
|
|
9
|
+
import { revokePlatformPats } from './platform-pat.js';
|
|
8
10
|
import { buildAuthorizeUrl, exchangeCode, pkcePair, randomState, registerClient, revokeToken, tokensFrom, } from './oauth.js';
|
|
9
11
|
const defaultDeps = {
|
|
10
12
|
register: registerClient,
|
|
@@ -16,6 +18,7 @@ const defaultDeps = {
|
|
|
16
18
|
await open(url);
|
|
17
19
|
},
|
|
18
20
|
introspect: introspectToken,
|
|
21
|
+
discover: async (fqdn) => (await discoverTarget(fqdn)).links,
|
|
19
22
|
log: (msg) => console.log(msg),
|
|
20
23
|
};
|
|
21
24
|
const promptBrowser = async (url, opts, deps) => {
|
|
@@ -28,8 +31,7 @@ const promptBrowser = async (url, opts, deps) => {
|
|
|
28
31
|
.catch(() => deps.log('Could not open a browser - use the URL above.'));
|
|
29
32
|
deps.log('Waiting for sign-in to complete...');
|
|
30
33
|
};
|
|
31
|
-
const authorize = async (server, state, opts, deps) => {
|
|
32
|
-
const authUrl = links(siteFqdn()).auth;
|
|
34
|
+
const authorize = async (server, state, opts, deps, authUrl) => {
|
|
33
35
|
const { verifier, challenge } = pkcePair();
|
|
34
36
|
const clientId = await deps.register(authUrl, server.redirectUri);
|
|
35
37
|
const redirectUri = server.redirectUri;
|
|
@@ -40,14 +42,19 @@ const authorize = async (server, state, opts, deps) => {
|
|
|
40
42
|
// A fresh DCR client per run: the redirect URI binds this run's ephemeral callback port.
|
|
41
43
|
export const signIn = async (opts, deps = defaultDeps) => {
|
|
42
44
|
const fqdn = siteFqdn();
|
|
45
|
+
const authUrl = (await deps.discover(fqdn)).auth;
|
|
43
46
|
ensureConfigDir();
|
|
44
47
|
const state = randomState();
|
|
45
48
|
const server = await deps.startServer(state);
|
|
46
49
|
try {
|
|
47
|
-
const { clientId, code, verifier } = await authorize(server, state, opts, deps);
|
|
50
|
+
const { clientId, code, verifier } = await authorize(server, state, opts, deps, authUrl);
|
|
48
51
|
const redirectUri = server.redirectUri;
|
|
49
|
-
const res = await deps.exchange(
|
|
50
|
-
|
|
52
|
+
const res = await deps.exchange(authUrl, { clientId, code, redirectUri, verifier });
|
|
53
|
+
const tokens = tokensFrom(res);
|
|
54
|
+
const old = readAuth();
|
|
55
|
+
await mutateAuth(() => ({ siteFqdn: fqdn, issuer: authUrl, clientId, tokens }));
|
|
56
|
+
if (old)
|
|
57
|
+
await revokePlatformPats(old, tokens.accessToken);
|
|
51
58
|
deps.log(chalk.green('\nSigned in.\n'));
|
|
52
59
|
}
|
|
53
60
|
finally {
|
|
@@ -60,7 +67,8 @@ export const signOut = async (deps = defaultDeps) => {
|
|
|
60
67
|
deps.log('Nothing to disconnect.');
|
|
61
68
|
return;
|
|
62
69
|
}
|
|
63
|
-
await
|
|
70
|
+
await revokePlatformPats(auth);
|
|
71
|
+
await deps.revoke(credentialLinks(auth).auth, auth.tokens.accessToken);
|
|
64
72
|
await deleteAuth();
|
|
65
73
|
deps.log('Disconnected - local credentials removed.');
|
|
66
74
|
};
|
|
@@ -69,7 +77,7 @@ const mismatchNote = (m) => `Signed in to ${m.credentialFqdn} (${m.credentialEnv
|
|
|
69
77
|
// Only a dead session re-signs: a transient verify failure keeps the credentials.
|
|
70
78
|
const verifyStored = async (auth, deps) => {
|
|
71
79
|
try {
|
|
72
|
-
await deps.introspect(auth,
|
|
80
|
+
await deps.introspect(auth, credentialLinks(auth));
|
|
73
81
|
deps.log(`Already signed in. Run ${chalk.white('agentage setup --reauth')} to sign in again.\n`);
|
|
74
82
|
return true;
|
|
75
83
|
}
|
|
@@ -84,11 +92,14 @@ const verifyStored = async (auth, deps) => {
|
|
|
84
92
|
};
|
|
85
93
|
// Never introspect a credential against another environment: it would misread as expired.
|
|
86
94
|
export const ensureSignedIn = async (opts, deps = defaultDeps) => {
|
|
87
|
-
const stored = readAuth();
|
|
88
|
-
const
|
|
95
|
+
const stored = opts.reauth ? null : readAuth();
|
|
96
|
+
const fqdn = siteFqdn();
|
|
97
|
+
// Discovery is asked only when the derived issuer differs from the credential's, or to sign in.
|
|
98
|
+
const derived = stored && detectEnvMismatch(stored, fqdn);
|
|
99
|
+
const mismatch = derived && detectEnvMismatch(stored, fqdn, (await deps.discover(fqdn)).auth);
|
|
89
100
|
if (mismatch)
|
|
90
101
|
deps.log(mismatchNote(mismatch));
|
|
91
|
-
else if (stored &&
|
|
102
|
+
else if (stored && (await verifyStored(stored, deps)))
|
|
92
103
|
return 'already';
|
|
93
104
|
await signIn(opts, deps);
|
|
94
105
|
return mismatch ? 'mismatch-resigned' : 'signed-in';
|
package/dist/lib/fs/config.d.ts
CHANGED
|
@@ -3,8 +3,14 @@ export interface StoredTokens {
|
|
|
3
3
|
refreshToken?: string;
|
|
4
4
|
expiresAt?: number;
|
|
5
5
|
}
|
|
6
|
+
export interface PlatformPat {
|
|
7
|
+
id: string;
|
|
8
|
+
token: string;
|
|
9
|
+
expiresAt: string;
|
|
10
|
+
}
|
|
6
11
|
export interface AuthState {
|
|
7
12
|
siteFqdn: string;
|
|
13
|
+
issuer?: string;
|
|
8
14
|
clientId: string;
|
|
9
15
|
tokens: StoredTokens;
|
|
10
16
|
user?: {
|
|
@@ -12,6 +18,7 @@ export interface AuthState {
|
|
|
12
18
|
email: string;
|
|
13
19
|
};
|
|
14
20
|
kind?: 'pat';
|
|
21
|
+
platformPats?: Record<string, PlatformPat>;
|
|
15
22
|
}
|
|
16
23
|
export declare const getConfigDir: () => string;
|
|
17
24
|
export declare const ensureConfigDir: () => string;
|
package/dist/lib/fs/config.js
CHANGED
|
@@ -19,6 +19,7 @@ const isStoredTokens = (value) => isRecord(value) &&
|
|
|
19
19
|
// A malformed auth.json (e.g. `{}`) reads as signed out rather than crashing every command.
|
|
20
20
|
export const isAuthState = (value) => isRecord(value) &&
|
|
21
21
|
typeof value['siteFqdn'] === 'string' &&
|
|
22
|
+
isOptional(value['issuer'], 'string') &&
|
|
22
23
|
typeof value['clientId'] === 'string' &&
|
|
23
24
|
isStoredTokens(value['tokens']);
|
|
24
25
|
export const readAuth = () => readJson(authPath(), isAuthState);
|
|
@@ -1,7 +1,15 @@
|
|
|
1
|
+
import { type Links } from './origins.js';
|
|
1
2
|
type Get = (url: string) => Promise<Response>;
|
|
2
3
|
export interface Platform {
|
|
3
4
|
url: string;
|
|
4
5
|
machines: string;
|
|
5
6
|
}
|
|
6
|
-
export declare const
|
|
7
|
+
export declare const issuerAllowed: (issuer: string, site: string) => boolean;
|
|
8
|
+
export interface Target {
|
|
9
|
+
links: Links;
|
|
10
|
+
platform: Platform;
|
|
11
|
+
discovered: boolean;
|
|
12
|
+
}
|
|
13
|
+
export declare const derivedTarget: (fqdn: string) => Target;
|
|
14
|
+
export declare const discoverTarget: (fqdn: string, get?: Get) => Promise<Target>;
|
|
7
15
|
export {};
|
|
@@ -13,6 +13,23 @@ const sameSite = (platform, site) => {
|
|
|
13
13
|
return (p.protocol === s.protocol &&
|
|
14
14
|
(p.hostname === s.hostname || p.hostname.endsWith(`.${s.hostname}`)));
|
|
15
15
|
};
|
|
16
|
+
const isIp = (host) => /^[\d.]+$/.test(host) || host.startsWith('[');
|
|
17
|
+
// The parent rule needs a 3+ label site, so a 2-label parent is never a public suffix like co.uk.
|
|
18
|
+
const underParent = (host, site) => {
|
|
19
|
+
const labels = site.split('.');
|
|
20
|
+
if (isIp(site) || labels.length < 3)
|
|
21
|
+
return false;
|
|
22
|
+
return host.endsWith(`.${labels.slice(1).join('.')}`);
|
|
23
|
+
};
|
|
24
|
+
// The issuer: the site, a subdomain of it, or (3+ label site) of its parent; no userinfo, no other port.
|
|
25
|
+
export const issuerAllowed = (issuer, site) => {
|
|
26
|
+
if (!URL.canParse(issuer))
|
|
27
|
+
return false;
|
|
28
|
+
const [i, s] = [new URL(issuer), new URL(site)];
|
|
29
|
+
if (i.username || i.password || i.port !== s.port)
|
|
30
|
+
return false;
|
|
31
|
+
return (sameSite(issuer, site) || (i.protocol === s.protocol && underParent(i.hostname, s.hostname)));
|
|
32
|
+
};
|
|
16
33
|
const read = async (url, get) => {
|
|
17
34
|
try {
|
|
18
35
|
const res = await get(url);
|
|
@@ -26,18 +43,43 @@ const read = async (url, get) => {
|
|
|
26
43
|
}
|
|
27
44
|
return undefined;
|
|
28
45
|
};
|
|
29
|
-
|
|
30
|
-
export const discoverPlatform = async (fqdn, get = cliFetch) => {
|
|
31
|
-
const site = links(fqdn).site;
|
|
32
|
-
const url = `${site}/.well-known/agentage.json`;
|
|
33
|
-
const doc = await read(url, get);
|
|
34
|
-
if (doc === undefined) {
|
|
35
|
-
const api = apiOrigin(fqdn);
|
|
36
|
-
return { url: api, machines: `${api}/v1/machines` };
|
|
37
|
-
}
|
|
46
|
+
const platformOf = (doc, site, url) => {
|
|
38
47
|
const platform = isRecord(doc) ? doc['platform'] : undefined;
|
|
39
48
|
if (typeof platform !== 'string' || !sameSite(platform, site))
|
|
40
49
|
throw new Error(`FAIL discovery: ${url} has no "platform"`);
|
|
41
50
|
const origin = new URL(platform).origin;
|
|
42
51
|
return { url: origin, machines: `${origin}/api/v1/machines` };
|
|
43
52
|
};
|
|
53
|
+
const issuerOf = (doc, base, url) => {
|
|
54
|
+
const issuer = isRecord(doc) ? doc['issuer'] : undefined;
|
|
55
|
+
if (issuer === undefined)
|
|
56
|
+
return base.auth;
|
|
57
|
+
if (typeof issuer !== 'string' || !issuerAllowed(issuer, base.site))
|
|
58
|
+
throw new Error(`FAIL discovery: ${url} names an issuer outside the site`);
|
|
59
|
+
return new URL(issuer).origin;
|
|
60
|
+
};
|
|
61
|
+
// The origins derived from the fqdn alone, as before discovery.
|
|
62
|
+
export const derivedTarget = (fqdn) => {
|
|
63
|
+
const api = apiOrigin(fqdn);
|
|
64
|
+
const platform = { url: api, machines: `${api}/v1/machines` };
|
|
65
|
+
return { links: links(fqdn), platform, discovered: false };
|
|
66
|
+
};
|
|
67
|
+
const fetchTarget = async (fqdn, get) => {
|
|
68
|
+
const base = links(fqdn);
|
|
69
|
+
const url = `${base.site}/.well-known/agentage.json`;
|
|
70
|
+
const doc = await read(url, get);
|
|
71
|
+
if (doc === undefined)
|
|
72
|
+
return derivedTarget(fqdn);
|
|
73
|
+
const platform = platformOf(doc, base.site, url);
|
|
74
|
+
return { links: { ...base, auth: issuerOf(doc, base, url) }, platform, discovered: true };
|
|
75
|
+
};
|
|
76
|
+
const once = new Map();
|
|
77
|
+
// Fetched once per run; an unserved document (404, 5xx, unreachable) keeps the derived origins,
|
|
78
|
+
// a served one without a valid platform or issuer fails closed.
|
|
79
|
+
export const discoverTarget = (fqdn, get = cliFetch) => {
|
|
80
|
+
if (get !== cliFetch)
|
|
81
|
+
return fetchTarget(fqdn, get);
|
|
82
|
+
const found = once.get(fqdn) ?? fetchTarget(fqdn, get);
|
|
83
|
+
once.set(fqdn, found);
|
|
84
|
+
return found;
|
|
85
|
+
};
|
|
@@ -1,8 +1,10 @@
|
|
|
1
1
|
import { AuthRequiredError, introspectToken } from '../auth/api.js';
|
|
2
|
+
import { jwtPatExpiry } from '../auth/credentials.js';
|
|
2
3
|
import { detectEnvMismatch } from '../auth/env-match.js';
|
|
3
4
|
import {} from '../fs/config.js';
|
|
4
5
|
import { fetchJsonUnref } from '../net/http.js';
|
|
5
6
|
import { requestHeaders } from '../net/user-agent.js';
|
|
7
|
+
import { derivedTarget, discoverTarget } from '../net/discovery.js';
|
|
6
8
|
import { environment, links } from '../net/origins.js';
|
|
7
9
|
import { checkForUpdate } from '../update/update-check.js';
|
|
8
10
|
import { VERSION } from '../../utils/version.js';
|
|
@@ -31,35 +33,45 @@ const mismatchAuth = (m) => ({
|
|
|
31
33
|
note: `signed in to ${m.credentialFqdn} - CLI targets ${m.targetFqdn} (${m.targetEnv}); ` +
|
|
32
34
|
`run: agentage setup to sign into ${m.targetEnv}, or set AGENTAGE_SITE_FQDN=${m.credentialFqdn}`,
|
|
33
35
|
});
|
|
36
|
+
// Discovery runs beside the derived probes, so a 404 costs no extra round trip.
|
|
34
37
|
export const gatherStatus = async (auth, fqdn) => {
|
|
35
|
-
const
|
|
38
|
+
const derived = links(fqdn);
|
|
36
39
|
const env = environment(fqdn);
|
|
37
40
|
const headers = requestHeaders();
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
checkSite(target.site, headers),
|
|
41
|
+
const [found, apiUp, siteReachable, update] = await Promise.all([
|
|
42
|
+
discoverTarget(fqdn).catch(() => derivedTarget(fqdn)),
|
|
43
|
+
checkEndpoint(derived.api, headers),
|
|
44
|
+
checkSite(derived.site, headers),
|
|
43
45
|
checkForUpdate(VERSION),
|
|
44
46
|
]);
|
|
47
|
+
const { links: target, platform, discovered } = found;
|
|
48
|
+
// A discovered platform has no /health: its host answering is enough.
|
|
49
|
+
const endpoint = discovered ? platform.url : target.api;
|
|
50
|
+
const reachable = discovered ? await checkSite(endpoint, headers) : apiUp;
|
|
45
51
|
const report = {
|
|
46
52
|
version: VERSION,
|
|
47
53
|
fqdn,
|
|
48
54
|
env,
|
|
49
55
|
target: { fqdn, env, reachable: siteReachable },
|
|
50
56
|
auth: { signedIn: false, note: 'not signed in - run: agentage setup' },
|
|
51
|
-
endpoint: { url:
|
|
57
|
+
endpoint: { url: endpoint, reachable },
|
|
52
58
|
update,
|
|
53
59
|
};
|
|
54
60
|
if (!auth)
|
|
55
61
|
return report;
|
|
56
|
-
const mismatch = detectEnvMismatch(auth, fqdn);
|
|
62
|
+
const mismatch = detectEnvMismatch(auth, fqdn, target.auth);
|
|
57
63
|
if (mismatch) {
|
|
58
64
|
report.auth = mismatchAuth(mismatch);
|
|
59
65
|
return report;
|
|
60
66
|
}
|
|
61
67
|
// Only carry `pat: true`; omit it for OAuth so existing exact-match reports stay unchanged.
|
|
62
68
|
const patFlag = auth.kind === 'pat' ? { pat: true } : {};
|
|
69
|
+
// A JWT PAT is judged by its own expiry, never introspected as a session.
|
|
70
|
+
const exp = auth.kind === 'pat' ? jwtPatExpiry(auth.tokens.accessToken) : null;
|
|
71
|
+
if (exp && Date.parse(exp) > Date.now())
|
|
72
|
+
return { ...report, auth: { signedIn: true, tokenExpiresAt: exp, pat: true } };
|
|
73
|
+
if (exp)
|
|
74
|
+
return { ...report, auth: { signedIn: false, pat: true, note: 'token expired' } };
|
|
63
75
|
try {
|
|
64
76
|
const session = await introspectToken(auth, target);
|
|
65
77
|
report.auth = { signedIn: true, tokenExpiresAt: session.expiresAt, ...patFlag };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@agentage/cli",
|
|
3
|
-
"version": "0.50.
|
|
3
|
+
"version": "0.50.2",
|
|
4
4
|
"description": "The agentage CLI - connect this machine to agentage from the terminal",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -55,7 +55,7 @@
|
|
|
55
55
|
"prepublishOnly": "npm run verify"
|
|
56
56
|
},
|
|
57
57
|
"dependencies": {
|
|
58
|
-
"@agentage/extension": "^0.
|
|
58
|
+
"@agentage/extension": "^0.11.0",
|
|
59
59
|
"chalk": "^6.0.0",
|
|
60
60
|
"commander": "^15.0.0",
|
|
61
61
|
"open": "^11.0.0"
|