@agentage/cli 0.50.1 → 0.50.3

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.
@@ -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 = to(async () => (await found()).platform.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
  };
@@ -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>;
@@ -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 mutateAuth((current) => {
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, links: Links) => Promise<void>;
6
+ export declare const platformFetch: (auth: AuthState, links: Links, found: Target, path: string, init: CliRequestInit, opts: CliFetchOptions) => Promise<Response>;
@@ -0,0 +1,97 @@
1
+ import {} from '../fs/config.js';
2
+ import { isRecord } from '../fs/json-file.js';
3
+ import {} from '../net/discovery.js';
4
+ import { cliFetch } from '../net/fetch.js';
5
+ import {} from '../net/origins.js';
6
+ import { VERSION } from '../../utils/version.js';
7
+ import { authedFetch, updateSession } from './api.js';
8
+ const DAY_MS = 86_400_000;
9
+ const SCOPES = ['platform:read', 'platform:write'];
10
+ const MINT = JSON.stringify({
11
+ label: 'agentage cli',
12
+ format: 'jwt',
13
+ scopes: SCOPES,
14
+ expiresInDays: 30,
15
+ });
16
+ const isPat = (v) => isRecord(v) &&
17
+ [v['id'], v['token']].every((s) => typeof s === 'string' && s !== '') &&
18
+ typeof v['expiresAt'] === 'string' &&
19
+ !Number.isNaN(Date.parse(v['expiresAt']));
20
+ const withBearer = (init, token) => ({
21
+ ...init,
22
+ headers: { ...init.headers, authorization: `Bearer ${token}` },
23
+ });
24
+ // A malformed entry reads as absent: it is re-minted, never sent.
25
+ const storedPat = (auth, issuer) => {
26
+ const pat = auth.platformPats?.[issuer];
27
+ return isPat(pat) ? pat : undefined;
28
+ };
29
+ const revokePat = (auth, links, id) => {
30
+ const url = `${links.auth}/account/pat/${id}`;
31
+ return authedFetch(auth, links, url, { method: 'DELETE' }, { timeoutMs: 5_000 }).then((res) => res.body?.cancel(), () => undefined);
32
+ };
33
+ // Best-effort; only the issuer of the session's bearer ever receives it.
34
+ export const revokePlatformPats = async (auth, links) => {
35
+ const pat = storedPat(auth, links.auth);
36
+ if (pat)
37
+ await revokePat(auth, links, pat.id);
38
+ };
39
+ // Once refused, a run stops asking: one line, no second mint, no fallback to the OAuth bearer.
40
+ const refused = new Map();
41
+ const refuse = (issuer, reason) => {
42
+ const err = refused.get(issuer) ?? new Error(reason);
43
+ if (!refused.has(issuer))
44
+ console.error(reason);
45
+ refused.set(issuer, err);
46
+ return err;
47
+ };
48
+ const mint = async (auth, links, opts) => {
49
+ const init = { method: 'POST', headers: { 'content-type': 'application/json' }, body: MINT };
50
+ const res = await authedFetch(auth, links, `${links.auth}/account/pat`, init, opts);
51
+ if (res.status !== 201)
52
+ await res.body?.cancel();
53
+ else {
54
+ const reply = await res.json().catch(() => null);
55
+ if (isRecord(reply) && isPat(reply['data']))
56
+ return reply['data'];
57
+ }
58
+ const reason = `platform token refused (${res.status}): auth may be older than ${VERSION}`;
59
+ throw refuse(links.auth, reason);
60
+ };
61
+ // The stored token while it has over a day left, else a new one; the old one is revoked unawaited.
62
+ const tokenFor = async (auth, links, renew, opts) => {
63
+ const old = storedPat(auth, links.auth);
64
+ if (!renew && old && Date.parse(old.expiresAt) - Date.now() > DAY_MS)
65
+ return { minted: false, token: old.token };
66
+ const { id, token, expiresAt } = await mint(auth, links, opts);
67
+ const pats = { ...auth.platformPats, [links.auth]: { id, token, expiresAt } };
68
+ auth.platformPats = pats;
69
+ await updateSession(auth.clientId, (current) => void (current.platformPats = pats));
70
+ if (old)
71
+ void revokePat(auth, links, old.id);
72
+ return { minted: true, token };
73
+ };
74
+ // A discovered platform takes only a JWT PAT the session mints; an env PAT goes as is.
75
+ export const platformFetch = async (auth, links, found, path, init, opts) => {
76
+ const url = `${found.platform.machines}${path}`;
77
+ if (!found.discovered || auth.kind === 'pat')
78
+ return authedFetch(auth, links, url, init, opts);
79
+ if (found.links.auth !== links.auth)
80
+ throw refuse(links.auth, `platform token: the site's issuer is ${found.links.auth}`);
81
+ const prior = refused.get(links.auth);
82
+ if (prior)
83
+ throw prior;
84
+ const call = async (renew) => {
85
+ const { minted, token } = await tokenFor(auth, links, renew, opts);
86
+ return { minted, res: await cliFetch(url, withBearer(init, token), opts) };
87
+ };
88
+ let { minted, res } = await call(false);
89
+ if (res.status === 401 && !minted) {
90
+ await res.body?.cancel();
91
+ ({ minted, res } = await call(true));
92
+ }
93
+ if (res.status !== 401)
94
+ return res;
95
+ await res.body?.cancel();
96
+ throw refuse(links.auth, 'platform token refused (401) by the platform');
97
+ };
@@ -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,
@@ -41,7 +42,8 @@ const authorize = async (server, state, opts, deps, authUrl) => {
41
42
  // A fresh DCR client per run: the redirect URI binds this run's ephemeral callback port.
42
43
  export const signIn = async (opts, deps = defaultDeps) => {
43
44
  const fqdn = siteFqdn();
44
- const authUrl = (await deps.discover(fqdn)).auth;
45
+ const to = await deps.discover(fqdn);
46
+ const authUrl = to.auth;
45
47
  ensureConfigDir();
46
48
  const state = randomState();
47
49
  const server = await deps.startServer(state);
@@ -50,7 +52,10 @@ export const signIn = async (opts, deps = defaultDeps) => {
50
52
  const redirectUri = server.redirectUri;
51
53
  const res = await deps.exchange(authUrl, { clientId, code, redirectUri, verifier });
52
54
  const tokens = tokensFrom(res);
55
+ const old = readAuth();
53
56
  await mutateAuth(() => ({ siteFqdn: fqdn, issuer: authUrl, clientId, tokens }));
57
+ if (old)
58
+ await revokePlatformPats({ ...old, clientId, tokens }, to);
54
59
  deps.log(chalk.green('\nSigned in.\n'));
55
60
  }
56
61
  finally {
@@ -63,6 +68,7 @@ export const signOut = async (deps = defaultDeps) => {
63
68
  deps.log('Nothing to disconnect.');
64
69
  return;
65
70
  }
71
+ await revokePlatformPats(auth, credentialLinks(auth));
66
72
  await deps.revoke(credentialLinks(auth).auth, auth.tokens.accessToken);
67
73
  await deleteAuth();
68
74
  deps.log('Disconnected - local credentials removed.');
@@ -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, unknown>;
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 };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agentage/cli",
3
- "version": "0.50.1",
3
+ "version": "0.50.3",
4
4
  "description": "The agentage CLI - connect this machine to agentage from the terminal",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",