@agentage/cli 0.50.0 → 0.50.1

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.
@@ -1,5 +1,5 @@
1
1
  import { type Account } from '../../core/profile/cloud.js';
2
2
  export type AccountOf = (opts?: {
3
3
  token?: string;
4
- }) => Account | null;
4
+ }) => Promise<Account | null>;
5
5
  export declare const signedInAccount: AccountOf;
@@ -1,24 +1,27 @@
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 { discoverPlatform } from '../../lib/net/discovery.js';
7
- import { apiOrigin, links, siteFqdn } from '../../lib/net/origins.js';
6
+ import { discoverTarget } from '../../lib/net/discovery.js';
7
+ import { apiOrigin, siteFqdn } from '../../lib/net/origins.js';
8
8
  const CLIENT = { 'x-client-type': 'cli' };
9
9
  // Read before any extension loads: the token is captured here, the fetch at CLI start.
10
- export const signedInAccount = (opts = {}) => {
10
+ export const signedInAccount = async (opts = {}) => {
11
11
  const auth = resolveAuth(opts);
12
12
  const fqdn = siteFqdn();
13
- if (auth === null || detectEnvMismatch(auth, fqdn) !== null)
13
+ if (auth === null)
14
14
  return null;
15
- const target = links(fqdn);
15
+ const found = () => discoverTarget(fqdn);
16
+ // Discovery is asked only when the derived issuer differs from the credential's.
17
+ const derived = detectEnvMismatch(auth, fqdn) !== null;
18
+ if (derived && detectEnvMismatch(auth, fqdn, (await found()).links.auth) !== null)
19
+ return null;
20
+ const target = credentialLinks(auth);
16
21
  const to = (base) => async (path, { headers, timeoutMs, ...init } = {}) => authedFetch(auth, target, `${await base()}${path}`, { ...init, headers: { ...CLIENT, ...headers } }, { timeoutMs });
17
- let found;
18
- const discovered = () => (found ??= discoverPlatform(fqdn));
19
- const platform = async () => (await discovered()).url;
22
+ const platform = async () => (await found()).platform.url;
20
23
  const fetch = to(() => apiOrigin(fqdn));
21
- const machines = to(async () => (await discovered()).machines);
24
+ const machines = to(async () => (await found()).platform.machines);
22
25
  const id = () => introspectToken(auth, target).then((s) => s.userId ?? null, () => null);
23
26
  return { fetch, machines, platform, id };
24
27
  };
@@ -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 ? gatherWithAccount(signedInAccount({ token: opts.token })) : gatherExtensions(),
57
+ extensions: (opts) => account ? signedInAccount({ token: opts.token }).then(gatherWithAccount) : gatherExtensions(),
58
58
  });
59
59
  const settle = async (deps, opts) => {
60
60
  try {
@@ -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 detectEnvMismatch: (auth: AuthState, targetFqdn: string) => AuthEnvMismatch | null;
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
- // The stored credential belongs to the environment it was issued for (auth.siteFqdn); the CLI's
4
- // current target comes from AGENTAGE_SITE_FQDN (production default). Introspecting a dev credential
5
- // against production rejects it and misreads as "expired" - so detect the mismatch by normalized
6
- // fqdn BEFORE any introspection. Returns null when the credential matches the current target.
7
- export const detectEnvMismatch = (auth, targetFqdn) => {
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 (credentialFqdn === target)
13
+ if (auth.kind === 'pat' || credentialLinks(auth).auth === targetIssuer)
11
14
  return null;
12
15
  return {
13
16
  credentialFqdn,
@@ -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>;
@@ -1,9 +1,10 @@
1
1
  import chalk from 'chalk';
2
2
  import { deleteAuth, ensureConfigDir, mutateAuth, readAuth } from '../fs/config.js';
3
- import { links, siteFqdn } from '../net/origins.js';
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';
8
9
  import { buildAuthorizeUrl, exchangeCode, pkcePair, randomState, registerClient, revokeToken, tokensFrom, } from './oauth.js';
9
10
  const defaultDeps = {
@@ -16,6 +17,7 @@ const defaultDeps = {
16
17
  await open(url);
17
18
  },
18
19
  introspect: introspectToken,
20
+ discover: async (fqdn) => (await discoverTarget(fqdn)).links,
19
21
  log: (msg) => console.log(msg),
20
22
  };
21
23
  const promptBrowser = async (url, opts, deps) => {
@@ -28,8 +30,7 @@ const promptBrowser = async (url, opts, deps) => {
28
30
  .catch(() => deps.log('Could not open a browser - use the URL above.'));
29
31
  deps.log('Waiting for sign-in to complete...');
30
32
  };
31
- const authorize = async (server, state, opts, deps) => {
32
- const authUrl = links(siteFqdn()).auth;
33
+ const authorize = async (server, state, opts, deps, authUrl) => {
33
34
  const { verifier, challenge } = pkcePair();
34
35
  const clientId = await deps.register(authUrl, server.redirectUri);
35
36
  const redirectUri = server.redirectUri;
@@ -40,14 +41,16 @@ const authorize = async (server, state, opts, deps) => {
40
41
  // A fresh DCR client per run: the redirect URI binds this run's ephemeral callback port.
41
42
  export const signIn = async (opts, deps = defaultDeps) => {
42
43
  const fqdn = siteFqdn();
44
+ const authUrl = (await deps.discover(fqdn)).auth;
43
45
  ensureConfigDir();
44
46
  const state = randomState();
45
47
  const server = await deps.startServer(state);
46
48
  try {
47
- const { clientId, code, verifier } = await authorize(server, state, opts, deps);
49
+ const { clientId, code, verifier } = await authorize(server, state, opts, deps, authUrl);
48
50
  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
+ const res = await deps.exchange(authUrl, { clientId, code, redirectUri, verifier });
52
+ const tokens = tokensFrom(res);
53
+ await mutateAuth(() => ({ siteFqdn: fqdn, issuer: authUrl, clientId, tokens }));
51
54
  deps.log(chalk.green('\nSigned in.\n'));
52
55
  }
53
56
  finally {
@@ -60,7 +63,7 @@ export const signOut = async (deps = defaultDeps) => {
60
63
  deps.log('Nothing to disconnect.');
61
64
  return;
62
65
  }
63
- await deps.revoke(links(auth.siteFqdn).auth, auth.tokens.accessToken);
66
+ await deps.revoke(credentialLinks(auth).auth, auth.tokens.accessToken);
64
67
  await deleteAuth();
65
68
  deps.log('Disconnected - local credentials removed.');
66
69
  };
@@ -69,7 +72,7 @@ const mismatchNote = (m) => `Signed in to ${m.credentialFqdn} (${m.credentialEnv
69
72
  // Only a dead session re-signs: a transient verify failure keeps the credentials.
70
73
  const verifyStored = async (auth, deps) => {
71
74
  try {
72
- await deps.introspect(auth, links(auth.siteFqdn));
75
+ await deps.introspect(auth, credentialLinks(auth));
73
76
  deps.log(`Already signed in. Run ${chalk.white('agentage setup --reauth')} to sign in again.\n`);
74
77
  return true;
75
78
  }
@@ -84,11 +87,14 @@ const verifyStored = async (auth, deps) => {
84
87
  };
85
88
  // Never introspect a credential against another environment: it would misread as expired.
86
89
  export const ensureSignedIn = async (opts, deps = defaultDeps) => {
87
- const stored = readAuth();
88
- const mismatch = stored && !opts.reauth ? detectEnvMismatch(stored, siteFqdn()) : null;
90
+ const stored = opts.reauth ? null : readAuth();
91
+ const fqdn = siteFqdn();
92
+ // Discovery is asked only when the derived issuer differs from the credential's, or to sign in.
93
+ const derived = stored && detectEnvMismatch(stored, fqdn);
94
+ const mismatch = derived && detectEnvMismatch(stored, fqdn, (await deps.discover(fqdn)).auth);
89
95
  if (mismatch)
90
96
  deps.log(mismatchNote(mismatch));
91
- else if (stored && !opts.reauth && (await verifyStored(stored, deps)))
97
+ else if (stored && (await verifyStored(stored, deps)))
92
98
  return 'already';
93
99
  await signIn(opts, deps);
94
100
  return mismatch ? 'mismatch-resigned' : 'signed-in';
@@ -5,6 +5,7 @@ export interface StoredTokens {
5
5
  }
6
6
  export interface AuthState {
7
7
  siteFqdn: string;
8
+ issuer?: string;
8
9
  clientId: string;
9
10
  tokens: StoredTokens;
10
11
  user?: {
@@ -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 discoverPlatform: (fqdn: string, get?: Get) => Promise<Platform>;
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
- // An unserved document (404, 5xx, redirect, unreachable) keeps the api origin; a served one without a platform fails.
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
+ };
@@ -3,6 +3,7 @@ import { detectEnvMismatch } from '../auth/env-match.js';
3
3
  import {} from '../fs/config.js';
4
4
  import { fetchJsonUnref } from '../net/http.js';
5
5
  import { requestHeaders } from '../net/user-agent.js';
6
+ import { derivedTarget, discoverTarget } from '../net/discovery.js';
6
7
  import { environment, links } from '../net/origins.js';
7
8
  import { checkForUpdate } from '../update/update-check.js';
8
9
  import { VERSION } from '../../utils/version.js';
@@ -31,29 +32,33 @@ const mismatchAuth = (m) => ({
31
32
  note: `signed in to ${m.credentialFqdn} - CLI targets ${m.targetFqdn} (${m.targetEnv}); ` +
32
33
  `run: agentage setup to sign into ${m.targetEnv}, or set AGENTAGE_SITE_FQDN=${m.credentialFqdn}`,
33
34
  });
35
+ // Discovery runs beside the derived probes, so a 404 costs no extra round trip.
34
36
  export const gatherStatus = async (auth, fqdn) => {
35
- const target = links(fqdn);
37
+ const derived = links(fqdn);
36
38
  const env = environment(fqdn);
37
39
  const headers = requestHeaders();
38
- // Endpoint reachability and the (npm-registry) update check are independent - run them
39
- // together so `status` stays snappy.
40
- const [reachable, siteReachable, update] = await Promise.all([
41
- checkEndpoint(target.api, headers),
42
- checkSite(target.site, headers),
40
+ const [found, apiUp, siteReachable, update] = await Promise.all([
41
+ discoverTarget(fqdn).catch(() => derivedTarget(fqdn)),
42
+ checkEndpoint(derived.api, headers),
43
+ checkSite(derived.site, headers),
43
44
  checkForUpdate(VERSION),
44
45
  ]);
46
+ const { links: target, platform, discovered } = found;
47
+ // A discovered platform has no /health: its host answering is enough.
48
+ const endpoint = discovered ? platform.url : target.api;
49
+ const reachable = discovered ? await checkSite(endpoint, headers) : apiUp;
45
50
  const report = {
46
51
  version: VERSION,
47
52
  fqdn,
48
53
  env,
49
54
  target: { fqdn, env, reachable: siteReachable },
50
55
  auth: { signedIn: false, note: 'not signed in - run: agentage setup' },
51
- endpoint: { url: target.api, reachable },
56
+ endpoint: { url: endpoint, reachable },
52
57
  update,
53
58
  };
54
59
  if (!auth)
55
60
  return report;
56
- const mismatch = detectEnvMismatch(auth, fqdn);
61
+ const mismatch = detectEnvMismatch(auth, fqdn, target.auth);
57
62
  if (mismatch) {
58
63
  report.auth = mismatchAuth(mismatch);
59
64
  return report;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agentage/cli",
3
- "version": "0.50.0",
3
+ "version": "0.50.1",
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.10.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"