@agentage/cli 0.50.1 → 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.js +5 -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/platform-pat.d.ts +6 -0
- package/dist/lib/auth/platform-pat.js +82 -0
- package/dist/lib/auth/sign-in.js +5 -0
- package/dist/lib/fs/config.d.ts +6 -0
- package/dist/lib/status/status-info.js +7 -0
- package/package.json +1 -1
|
@@ -3,6 +3,7 @@ import { authedFetch } from '../../lib/auth/api.js';
|
|
|
3
3
|
import { resolveAuth } from '../../lib/auth/credentials.js';
|
|
4
4
|
import { credentialLinks, detectEnvMismatch } from '../../lib/auth/env-match.js';
|
|
5
5
|
import { introspectToken } from '../../lib/auth/introspect.js';
|
|
6
|
+
import { platformFetch } from '../../lib/auth/platform-pat.js';
|
|
6
7
|
import { discoverTarget } from '../../lib/net/discovery.js';
|
|
7
8
|
import { apiOrigin, siteFqdn } from '../../lib/net/origins.js';
|
|
8
9
|
const CLIENT = { 'x-client-type': 'cli' };
|
|
@@ -21,7 +22,10 @@ export const signedInAccount = async (opts = {}) => {
|
|
|
21
22
|
const to = (base) => async (path, { headers, timeoutMs, ...init } = {}) => authedFetch(auth, target, `${await base()}${path}`, { ...init, headers: { ...CLIENT, ...headers } }, { timeoutMs });
|
|
22
23
|
const platform = async () => (await found()).platform.url;
|
|
23
24
|
const fetch = to(() => apiOrigin(fqdn));
|
|
24
|
-
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
|
+
};
|
|
25
29
|
const id = () => introspectToken(auth, target).then((s) => s.userId ?? null, () => null);
|
|
26
30
|
return { fetch, machines, platform, id };
|
|
27
31
|
};
|
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
|
|
@@ -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
|
+
};
|
package/dist/lib/auth/sign-in.js
CHANGED
|
@@ -6,6 +6,7 @@ import { AuthRequiredError } from './auth-errors.js';
|
|
|
6
6
|
import { startCallbackServer } from './callback-server.js';
|
|
7
7
|
import { credentialLinks, detectEnvMismatch } from './env-match.js';
|
|
8
8
|
import { introspectToken } from './introspect.js';
|
|
9
|
+
import { revokePlatformPats } from './platform-pat.js';
|
|
9
10
|
import { buildAuthorizeUrl, exchangeCode, pkcePair, randomState, registerClient, revokeToken, tokensFrom, } from './oauth.js';
|
|
10
11
|
const defaultDeps = {
|
|
11
12
|
register: registerClient,
|
|
@@ -50,7 +51,10 @@ export const signIn = async (opts, deps = defaultDeps) => {
|
|
|
50
51
|
const redirectUri = server.redirectUri;
|
|
51
52
|
const res = await deps.exchange(authUrl, { clientId, code, redirectUri, verifier });
|
|
52
53
|
const tokens = tokensFrom(res);
|
|
54
|
+
const old = readAuth();
|
|
53
55
|
await mutateAuth(() => ({ siteFqdn: fqdn, issuer: authUrl, clientId, tokens }));
|
|
56
|
+
if (old)
|
|
57
|
+
await revokePlatformPats(old, tokens.accessToken);
|
|
54
58
|
deps.log(chalk.green('\nSigned in.\n'));
|
|
55
59
|
}
|
|
56
60
|
finally {
|
|
@@ -63,6 +67,7 @@ export const signOut = async (deps = defaultDeps) => {
|
|
|
63
67
|
deps.log('Nothing to disconnect.');
|
|
64
68
|
return;
|
|
65
69
|
}
|
|
70
|
+
await revokePlatformPats(auth);
|
|
66
71
|
await deps.revoke(credentialLinks(auth).auth, auth.tokens.accessToken);
|
|
67
72
|
await deleteAuth();
|
|
68
73
|
deps.log('Disconnected - local credentials removed.');
|
package/dist/lib/fs/config.d.ts
CHANGED
|
@@ -3,6 +3,11 @@ 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;
|
|
8
13
|
issuer?: string;
|
|
@@ -13,6 +18,7 @@ export interface AuthState {
|
|
|
13
18
|
email: string;
|
|
14
19
|
};
|
|
15
20
|
kind?: 'pat';
|
|
21
|
+
platformPats?: Record<string, PlatformPat>;
|
|
16
22
|
}
|
|
17
23
|
export declare const getConfigDir: () => string;
|
|
18
24
|
export declare const ensureConfigDir: () => string;
|
|
@@ -1,4 +1,5 @@
|
|
|
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';
|
|
@@ -65,6 +66,12 @@ export const gatherStatus = async (auth, fqdn) => {
|
|
|
65
66
|
}
|
|
66
67
|
// Only carry `pat: true`; omit it for OAuth so existing exact-match reports stay unchanged.
|
|
67
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' } };
|
|
68
75
|
try {
|
|
69
76
|
const session = await introspectToken(auth, target);
|
|
70
77
|
report.auth = { signedIn: true, tokenExpiresAt: session.expiresAt, ...patFlag };
|