@antasphere/cli-core 0.1.0 → 0.3.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/src/connect.ts ADDED
@@ -0,0 +1,166 @@
1
+ import { CliAuthError, type CliAuthMintedKey } from './auth.js';
2
+
3
+ /**
4
+ * The CLI cross-tool connect exchange (binding patterns §7, gcloud model):
5
+ * one `antasphere login` serves every federated tool. On demand, the hub
6
+ * API key is traded for a tool-local key in two calls:
7
+ *
8
+ * 1. POST {hub}/api/v1/sso/tool-token — auth = hub API key (Bearer),
9
+ * body `{ resource, workspaceId? }` → a single-org, 120-second JWT
10
+ * for the tool's resource URL. The token is OPAQUE to this client:
11
+ * it is relayed hub → tool, never inspected or stored.
12
+ * 2. POST {tool}/api/v1/sso/cli-connect — NO auth header (the JWT is
13
+ * the credential), body `{ token }` → the tool verifies, JIT-provisions,
14
+ * and mints an ordinary tool-local API key, returned exactly once.
15
+ *
16
+ * The hub key is sent to the HUB only — it never reaches the tool. The
17
+ * minted key is cached per (tool, hub org) in the tool's config namespace
18
+ * (config.ts `workspaceKeys`); day-to-day tool CLI calls then take the
19
+ * ordinary local API-key path with the hub out of the loop.
20
+ */
21
+
22
+ export type CliConnectStage = 'hub' | 'tool';
23
+
24
+ /**
25
+ * A failed exchange call, tagged with WHICH side rejected it so a CLI can
26
+ * pick the remedy without string-matching:
27
+ *
28
+ * - hub 400 `unknown_resource` — the resource URL is not in the registry.
29
+ * - hub 403 `no_membership` / `workspace_suspended` — the target org is
30
+ * not exchangeable for this user; pick another org.
31
+ * - `needsHubLogin` — the hub rejected the KEY itself; re-run
32
+ * `antasphere login`.
33
+ * - `needsReExchange` — the tool rejected the 120 s JWT (expired/replayed
34
+ * in transit); run the exchange again.
35
+ * - tool 429 `rate_limited` — back off and retry.
36
+ */
37
+ export class CliConnectError extends CliAuthError {
38
+ constructor(
39
+ public readonly stage: CliConnectStage,
40
+ status: number,
41
+ code: string,
42
+ message: string,
43
+ details?: unknown
44
+ ) {
45
+ super(status, code, message, details);
46
+ this.name = 'CliConnectError';
47
+ }
48
+
49
+ /**
50
+ * The hub rejected the key itself: invalid/revoked (401), or a key
51
+ * minted before the `sso:exchange` scope existed (403 insufficient_scope
52
+ * — old keys simply lack it). The fix is a fresh `antasphere login`.
53
+ */
54
+ get needsHubLogin(): boolean {
55
+ return (
56
+ this.stage === 'hub' &&
57
+ (this.status === 401 || (this.status === 403 && this.code === 'insufficient_scope'))
58
+ );
59
+ }
60
+
61
+ /** The tool rejected the JWT (expired/replayed) — run the exchange again. */
62
+ get needsReExchange(): boolean {
63
+ return this.stage === 'tool' && this.status === 401;
64
+ }
65
+ }
66
+
67
+ export interface CliToolTokenBody {
68
+ /** The tool's registry resource URL (e.g. `https://app.slideless.ai/mcp`). */
69
+ resource: string;
70
+ /** Target hub org — any live ACTIVE membership of the user (gcloud
71
+ * model); omit = the hub key's bound workspace. */
72
+ workspaceId?: string;
73
+ }
74
+
75
+ export interface CliToolTokenMinted {
76
+ /** The single-org exchange JWT — opaque, ~120 s; relay it, never keep it. */
77
+ token: string;
78
+ /** ISO expiry of the JWT (informational; the minted key outlives it). */
79
+ expiresAt: string;
80
+ /** The hub org the token was minted for (explicit target or the key's bound org). */
81
+ workspaceId: string;
82
+ }
83
+
84
+ export interface CliConnected {
85
+ /** Full tool-local key (`slk_`-style) — shown once, never retrievable. */
86
+ key: string;
87
+ apiKey: CliAuthMintedKey;
88
+ user: { id: string; email: string; name: string };
89
+ /** The tool-local workspace the key is bound to (the hub org's projection). */
90
+ workspaceId: string;
91
+ }
92
+
93
+ /** The flattened outcome of a full exchange — everything a CLI caches. */
94
+ export interface CliConnectResult {
95
+ /** Full tool-local key — cache it per (tool, `hubWorkspaceId`). */
96
+ key: string;
97
+ apiKey: CliAuthMintedKey;
98
+ user: { id: string; email: string; name: string };
99
+ /** The HUB org the exchange resolved to — the cache key (config.ts). */
100
+ hubWorkspaceId: string;
101
+ /** The tool-local workspace the minted key is bound to (informational). */
102
+ toolWorkspaceId: string;
103
+ }
104
+
105
+ export interface CliConnectClientOptions {
106
+ /** Hub origin, e.g. https://account.antasphere.com */
107
+ hubBaseUrl: string;
108
+ /** Tool instance origin, e.g. https://app.slideless.ai */
109
+ toolBaseUrl: string;
110
+ fetch?: typeof globalThis.fetch;
111
+ }
112
+
113
+ export class CliConnectClient {
114
+ private readonly hubBaseUrl: string;
115
+ private readonly toolBaseUrl: string;
116
+ private readonly fetchImpl: typeof globalThis.fetch;
117
+
118
+ constructor(options: CliConnectClientOptions) {
119
+ this.hubBaseUrl = options.hubBaseUrl.replace(/\/+$/, '');
120
+ this.toolBaseUrl = options.toolBaseUrl.replace(/\/+$/, '');
121
+ this.fetchImpl = options.fetch ?? globalThis.fetch.bind(globalThis);
122
+ }
123
+
124
+ /** Step 1 — the hub mints the 120 s single-org JWT for the tool's resource. */
125
+ toolToken(hubApiKey: string, body: CliToolTokenBody): Promise<CliToolTokenMinted> {
126
+ return this.call('hub', `${this.hubBaseUrl}/api/v1/sso/tool-token`, body, hubApiKey);
127
+ }
128
+
129
+ /** Step 2 — the tool verifies the JWT (its only credential) and mints its key. */
130
+ cliConnect(token: string): Promise<CliConnected> {
131
+ return this.call('tool', `${this.toolBaseUrl}/api/v1/sso/cli-connect`, { token });
132
+ }
133
+
134
+ /** The full two-call exchange. The hub key goes to the hub ONLY. */
135
+ async exchange(hubApiKey: string, body: CliToolTokenBody): Promise<CliConnectResult> {
136
+ const minted = await this.toolToken(hubApiKey, body);
137
+ const connected = await this.cliConnect(minted.token);
138
+ return {
139
+ key: connected.key,
140
+ apiKey: connected.apiKey,
141
+ user: connected.user,
142
+ hubWorkspaceId: minted.workspaceId,
143
+ toolWorkspaceId: connected.workspaceId
144
+ };
145
+ }
146
+
147
+ /** Mirrors CliAuthClient's parse: `{ error: { code, message, details } }` envelopes. */
148
+ private async call<T>(stage: CliConnectStage, url: string, body: unknown, apiKey?: string): Promise<T> {
149
+ const headers: Record<string, string> = { 'content-type': 'application/json' };
150
+ if (apiKey) headers['authorization'] = `Bearer ${apiKey}`;
151
+ const res = await this.fetchImpl(url, { method: 'POST', headers, body: JSON.stringify(body) });
152
+ const json = (await res.json().catch(() => null)) as
153
+ { error?: { code?: string; message?: string; details?: unknown } } | T | null;
154
+ if (!res.ok) {
155
+ const errBody = (json ?? {}) as { error?: { code?: string; message?: string; details?: unknown } };
156
+ throw new CliConnectError(
157
+ stage,
158
+ res.status,
159
+ errBody.error?.code ?? 'unknown_error',
160
+ errBody.error?.message ?? `Request failed with ${res.status}`,
161
+ errBody.error?.details
162
+ );
163
+ }
164
+ return json as T;
165
+ }
166
+ }
package/src/index.ts CHANGED
@@ -2,9 +2,12 @@
2
2
  * @antasphere/cli-core — the shared foundation every Antasphere tool CLI
3
3
  * builds on (hub-architecture §8): the `~/.config/antasphere/` config home
4
4
  * with tool-namespaced profiles, the flag → env → profile → default URL
5
- * resolution order, the instance email-OTP auth client, and the CliIo
6
- * prompt seam. Tool commands, wire types, and API surfaces live in the
7
- * tools; this package carries only config/login plumbing, never secrets.
5
+ * resolution order, the instance email-OTP auth client, the hub→tool
6
+ * cross-tool connect exchange (+ its per-(tool, org) key cache, the
7
+ * hub-profile org context, and the connect-on-demand seam a tool CLI runs
8
+ * when no direct credential resolved), and the CliIo prompt seam. Tool
9
+ * commands, wire types, and API surfaces live in the tools; this package
10
+ * carries only config/login plumbing, never secrets.
8
11
  */
9
12
 
10
13
  export {
@@ -13,11 +16,14 @@ export {
13
16
  configPath,
14
17
  HUB_TOOL,
15
18
  loadConfig,
19
+ lookupWorkspaceKey,
16
20
  parseConfig,
17
21
  redactKey,
18
- saveConfig
22
+ removeWorkspaceKey,
23
+ saveConfig,
24
+ storeWorkspaceKey
19
25
  } from './config.js';
20
- export type { CliConfig, CliEnv, CliProfile } from './config.js';
26
+ export type { CliConfig, CliEnv, CliProfile, CliWorkspaceKey } from './config.js';
21
27
 
22
28
  export { ask, printJson } from './io.js';
23
29
  export type { CliIo } from './io.js';
@@ -36,5 +42,27 @@ export type {
36
42
  CliAuthRevoked
37
43
  } from './auth.js';
38
44
 
45
+ export { CliConnectClient, CliConnectError } from './connect.js';
46
+ export type {
47
+ CliConnectClientOptions,
48
+ CliConnected,
49
+ CliConnectResult,
50
+ CliConnectStage,
51
+ CliToolTokenBody,
52
+ CliToolTokenMinted
53
+ } from './connect.js';
54
+
55
+ export { connectOnDemand, probeToolInstance } from './connect-on-demand.js';
56
+ export type {
57
+ ConnectNoticeFacts,
58
+ ConnectOnDemandMessages,
59
+ ConnectOnDemandOptions,
60
+ ConnectOnDemandOutcome,
61
+ ToolInstanceProbe
62
+ } from './connect-on-demand.js';
63
+
64
+ export { getActiveWorkspace, resolveTargetWorkspace, setActiveWorkspace } from './org.js';
65
+ export type { OrgContextOptions, ResolveTargetWorkspaceOptions } from './org.js';
66
+
39
67
  export { migrateLegacyConfig } from './migrate.js';
40
68
  export type { LegacyMigrationSpec, MigrationResult } from './migrate.js';
package/src/org.ts ADDED
@@ -0,0 +1,73 @@
1
+ import { HUB_TOOL, loadConfig, saveConfig, type CliEnv } from './config.js';
2
+ import { CliUsageError, resolveProfile } from './resolve.js';
3
+
4
+ /**
5
+ * Org context for the cross-tool connect flow (binding patterns §7). Orgs
6
+ * are HUB-level entities and the hub login is the one credential shared
7
+ * across the tool family, so the active org lives on the HUB profile:
8
+ * `antasphere org use` sets it, every tool CLI reads it when picking the
9
+ * org to exchange for.
10
+ *
11
+ * The effective target org for an exchange resolves in this order:
12
+ *
13
+ * explicit per-invocation override (--org)
14
+ * → the hub profile's active org (`org use`)
15
+ * → the hub key's bound workspace (set at login)
16
+ * → undefined — the exchange then omits `workspaceId` and the hub
17
+ * defaults to the key's bound org server-side.
18
+ */
19
+
20
+ export interface OrgContextOptions {
21
+ /** Hub profile name; default = the hub config's active profile. */
22
+ profile?: string;
23
+ }
24
+
25
+ /**
26
+ * The hub profile's effective active org: the `org use` choice when one is
27
+ * set, else the org the hub key was bound to at login. Undefined when not
28
+ * logged in (or an explicitly named profile is missing → CliUsageError).
29
+ */
30
+ export function getActiveWorkspace(env: CliEnv, opts: OrgContextOptions = {}): string | undefined {
31
+ const { profile } = resolveProfile(loadConfig(env, HUB_TOOL), opts.profile);
32
+ return profile?.activeWorkspaceId ?? profile?.workspaceId;
33
+ }
34
+
35
+ /**
36
+ * What `antasphere org use` calls: persist the org choice on the hub
37
+ * profile (`null` clears it, falling back to the key's bound workspace).
38
+ * Every other profile field is preserved. Returns the file written.
39
+ */
40
+ export function setActiveWorkspace(
41
+ env: CliEnv,
42
+ workspaceId: string | null,
43
+ opts: OrgContextOptions = {}
44
+ ): string {
45
+ const config = loadConfig(env, HUB_TOOL);
46
+ const { name, profile } = resolveProfile(config, opts.profile);
47
+ if (!name || !profile) {
48
+ throw new CliUsageError('No hub profile to set the org on — run `antasphere login` first.');
49
+ }
50
+ if (workspaceId === null) {
51
+ const { activeWorkspaceId: _cleared, ...rest } = profile;
52
+ config.profiles[name] = rest;
53
+ } else {
54
+ config.profiles[name] = { ...profile, activeWorkspaceId: workspaceId };
55
+ }
56
+ return saveConfig(env, HUB_TOOL, config);
57
+ }
58
+
59
+ export interface ResolveTargetWorkspaceOptions extends OrgContextOptions {
60
+ /** Per-invocation override (--org). */
61
+ override?: string;
62
+ }
63
+
64
+ /**
65
+ * The org a cross-tool exchange should target: explicit override → active
66
+ * org → the hub key's bound workspace → undefined (hub decides).
67
+ */
68
+ export function resolveTargetWorkspace(
69
+ env: CliEnv,
70
+ opts: ResolveTargetWorkspaceOptions = {}
71
+ ): string | undefined {
72
+ return opts.override ?? getActiveWorkspace(env, opts);
73
+ }