@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/README.md +41 -7
- package/dist/config.d.ts +41 -0
- package/dist/config.d.ts.map +1 -1
- package/dist/config.js +54 -0
- package/dist/config.js.map +1 -1
- package/dist/connect-on-demand.d.ts +114 -0
- package/dist/connect-on-demand.d.ts.map +1 -0
- package/dist/connect-on-demand.js +130 -0
- package/dist/connect-on-demand.js.map +1 -0
- package/dist/connect.d.ts +109 -0
- package/dist/connect.d.ts.map +1 -0
- package/dist/connect.js +79 -0
- package/dist/connect.js.map +1 -0
- package/dist/index.d.ts +14 -5
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +10 -4
- package/dist/index.js.map +1 -1
- package/dist/org.d.ts +42 -0
- package/dist/org.d.ts.map +1 -0
- package/dist/org.js +39 -0
- package/dist/org.js.map +1 -0
- package/package.json +2 -2
- package/src/config.ts +84 -0
- package/src/connect-on-demand.ts +250 -0
- package/src/connect.ts +166 -0
- package/src/index.ts +33 -5
- package/src/org.ts +73 -0
package/dist/connect.js
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import { CliAuthError } from './auth.js';
|
|
2
|
+
/**
|
|
3
|
+
* A failed exchange call, tagged with WHICH side rejected it so a CLI can
|
|
4
|
+
* pick the remedy without string-matching:
|
|
5
|
+
*
|
|
6
|
+
* - hub 400 `unknown_resource` — the resource URL is not in the registry.
|
|
7
|
+
* - hub 403 `no_membership` / `workspace_suspended` — the target org is
|
|
8
|
+
* not exchangeable for this user; pick another org.
|
|
9
|
+
* - `needsHubLogin` — the hub rejected the KEY itself; re-run
|
|
10
|
+
* `antasphere login`.
|
|
11
|
+
* - `needsReExchange` — the tool rejected the 120 s JWT (expired/replayed
|
|
12
|
+
* in transit); run the exchange again.
|
|
13
|
+
* - tool 429 `rate_limited` — back off and retry.
|
|
14
|
+
*/
|
|
15
|
+
export class CliConnectError extends CliAuthError {
|
|
16
|
+
stage;
|
|
17
|
+
constructor(stage, status, code, message, details) {
|
|
18
|
+
super(status, code, message, details);
|
|
19
|
+
this.stage = stage;
|
|
20
|
+
this.name = 'CliConnectError';
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* The hub rejected the key itself: invalid/revoked (401), or a key
|
|
24
|
+
* minted before the `sso:exchange` scope existed (403 insufficient_scope
|
|
25
|
+
* — old keys simply lack it). The fix is a fresh `antasphere login`.
|
|
26
|
+
*/
|
|
27
|
+
get needsHubLogin() {
|
|
28
|
+
return (this.stage === 'hub' &&
|
|
29
|
+
(this.status === 401 || (this.status === 403 && this.code === 'insufficient_scope')));
|
|
30
|
+
}
|
|
31
|
+
/** The tool rejected the JWT (expired/replayed) — run the exchange again. */
|
|
32
|
+
get needsReExchange() {
|
|
33
|
+
return this.stage === 'tool' && this.status === 401;
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
export class CliConnectClient {
|
|
37
|
+
hubBaseUrl;
|
|
38
|
+
toolBaseUrl;
|
|
39
|
+
fetchImpl;
|
|
40
|
+
constructor(options) {
|
|
41
|
+
this.hubBaseUrl = options.hubBaseUrl.replace(/\/+$/, '');
|
|
42
|
+
this.toolBaseUrl = options.toolBaseUrl.replace(/\/+$/, '');
|
|
43
|
+
this.fetchImpl = options.fetch ?? globalThis.fetch.bind(globalThis);
|
|
44
|
+
}
|
|
45
|
+
/** Step 1 — the hub mints the 120 s single-org JWT for the tool's resource. */
|
|
46
|
+
toolToken(hubApiKey, body) {
|
|
47
|
+
return this.call('hub', `${this.hubBaseUrl}/api/v1/sso/tool-token`, body, hubApiKey);
|
|
48
|
+
}
|
|
49
|
+
/** Step 2 — the tool verifies the JWT (its only credential) and mints its key. */
|
|
50
|
+
cliConnect(token) {
|
|
51
|
+
return this.call('tool', `${this.toolBaseUrl}/api/v1/sso/cli-connect`, { token });
|
|
52
|
+
}
|
|
53
|
+
/** The full two-call exchange. The hub key goes to the hub ONLY. */
|
|
54
|
+
async exchange(hubApiKey, body) {
|
|
55
|
+
const minted = await this.toolToken(hubApiKey, body);
|
|
56
|
+
const connected = await this.cliConnect(minted.token);
|
|
57
|
+
return {
|
|
58
|
+
key: connected.key,
|
|
59
|
+
apiKey: connected.apiKey,
|
|
60
|
+
user: connected.user,
|
|
61
|
+
hubWorkspaceId: minted.workspaceId,
|
|
62
|
+
toolWorkspaceId: connected.workspaceId
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
/** Mirrors CliAuthClient's parse: `{ error: { code, message, details } }` envelopes. */
|
|
66
|
+
async call(stage, url, body, apiKey) {
|
|
67
|
+
const headers = { 'content-type': 'application/json' };
|
|
68
|
+
if (apiKey)
|
|
69
|
+
headers['authorization'] = `Bearer ${apiKey}`;
|
|
70
|
+
const res = await this.fetchImpl(url, { method: 'POST', headers, body: JSON.stringify(body) });
|
|
71
|
+
const json = (await res.json().catch(() => null));
|
|
72
|
+
if (!res.ok) {
|
|
73
|
+
const errBody = (json ?? {});
|
|
74
|
+
throw new CliConnectError(stage, res.status, errBody.error?.code ?? 'unknown_error', errBody.error?.message ?? `Request failed with ${res.status}`, errBody.error?.details);
|
|
75
|
+
}
|
|
76
|
+
return json;
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
//# sourceMappingURL=connect.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"connect.js","sourceRoot":"","sources":["../src/connect.ts"],"names":[],"mappings":"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"}
|
package/dist/index.d.ts
CHANGED
|
@@ -2,18 +2,27 @@
|
|
|
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,
|
|
6
|
-
*
|
|
7
|
-
*
|
|
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
|
-
export { assertToolNamespace, clearConfig, configPath, HUB_TOOL, loadConfig, parseConfig, redactKey, saveConfig } from './config.js';
|
|
10
|
-
export type { CliConfig, CliEnv, CliProfile } from './config.js';
|
|
12
|
+
export { assertToolNamespace, clearConfig, configPath, HUB_TOOL, loadConfig, lookupWorkspaceKey, parseConfig, redactKey, removeWorkspaceKey, saveConfig, storeWorkspaceKey } from './config.js';
|
|
13
|
+
export type { CliConfig, CliEnv, CliProfile, CliWorkspaceKey } from './config.js';
|
|
11
14
|
export { ask, printJson } from './io.js';
|
|
12
15
|
export type { CliIo } from './io.js';
|
|
13
16
|
export { CliUsageError, DEFAULT_PROFILE, resolveApiKey, resolveBaseUrl, resolveProfile } from './resolve.js';
|
|
14
17
|
export type { ResolveApiKeyOptions, ResolveBaseUrlOptions, ResolvedProfile } from './resolve.js';
|
|
15
18
|
export { CliAuthClient, CliAuthError } from './auth.js';
|
|
16
19
|
export type { CliAuthClientOptions, CliAuthCompleteBody, CliAuthCompleted, CliAuthMintedKey, CliAuthRequestBody, CliAuthRequested, CliAuthRevoked } from './auth.js';
|
|
20
|
+
export { CliConnectClient, CliConnectError } from './connect.js';
|
|
21
|
+
export type { CliConnectClientOptions, CliConnected, CliConnectResult, CliConnectStage, CliToolTokenBody, CliToolTokenMinted } from './connect.js';
|
|
22
|
+
export { connectOnDemand, probeToolInstance } from './connect-on-demand.js';
|
|
23
|
+
export type { ConnectNoticeFacts, ConnectOnDemandMessages, ConnectOnDemandOptions, ConnectOnDemandOutcome, ToolInstanceProbe } from './connect-on-demand.js';
|
|
24
|
+
export { getActiveWorkspace, resolveTargetWorkspace, setActiveWorkspace } from './org.js';
|
|
25
|
+
export type { OrgContextOptions, ResolveTargetWorkspaceOptions } from './org.js';
|
|
17
26
|
export { migrateLegacyConfig } from './migrate.js';
|
|
18
27
|
export type { LegacyMigrationSpec, MigrationResult } from './migrate.js';
|
|
19
28
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,OAAO,EACL,mBAAmB,EACnB,WAAW,EACX,UAAU,EACV,QAAQ,EACR,UAAU,EACV,kBAAkB,EAClB,WAAW,EACX,SAAS,EACT,kBAAkB,EAClB,UAAU,EACV,iBAAiB,EAClB,MAAM,aAAa,CAAC;AACrB,YAAY,EAAE,SAAS,EAAE,MAAM,EAAE,UAAU,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAElF,OAAO,EAAE,GAAG,EAAE,SAAS,EAAE,MAAM,SAAS,CAAC;AACzC,YAAY,EAAE,KAAK,EAAE,MAAM,SAAS,CAAC;AAErC,OAAO,EAAE,aAAa,EAAE,eAAe,EAAE,aAAa,EAAE,cAAc,EAAE,cAAc,EAAE,MAAM,cAAc,CAAC;AAC7G,YAAY,EAAE,oBAAoB,EAAE,qBAAqB,EAAE,eAAe,EAAE,MAAM,cAAc,CAAC;AAEjG,OAAO,EAAE,aAAa,EAAE,YAAY,EAAE,MAAM,WAAW,CAAC;AACxD,YAAY,EACV,oBAAoB,EACpB,mBAAmB,EACnB,gBAAgB,EAChB,gBAAgB,EAChB,kBAAkB,EAClB,gBAAgB,EAChB,cAAc,EACf,MAAM,WAAW,CAAC;AAEnB,OAAO,EAAE,gBAAgB,EAAE,eAAe,EAAE,MAAM,cAAc,CAAC;AACjE,YAAY,EACV,uBAAuB,EACvB,YAAY,EACZ,gBAAgB,EAChB,eAAe,EACf,gBAAgB,EAChB,kBAAkB,EACnB,MAAM,cAAc,CAAC;AAEtB,OAAO,EAAE,eAAe,EAAE,iBAAiB,EAAE,MAAM,wBAAwB,CAAC;AAC5E,YAAY,EACV,kBAAkB,EAClB,uBAAuB,EACvB,sBAAsB,EACtB,sBAAsB,EACtB,iBAAiB,EAClB,MAAM,wBAAwB,CAAC;AAEhC,OAAO,EAAE,kBAAkB,EAAE,sBAAsB,EAAE,kBAAkB,EAAE,MAAM,UAAU,CAAC;AAC1F,YAAY,EAAE,iBAAiB,EAAE,6BAA6B,EAAE,MAAM,UAAU,CAAC;AAEjF,OAAO,EAAE,mBAAmB,EAAE,MAAM,cAAc,CAAC;AACnD,YAAY,EAAE,mBAAmB,EAAE,eAAe,EAAE,MAAM,cAAc,CAAC"}
|
package/dist/index.js
CHANGED
|
@@ -2,13 +2,19 @@
|
|
|
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,
|
|
6
|
-
*
|
|
7
|
-
*
|
|
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
|
-
export { assertToolNamespace, clearConfig, configPath, HUB_TOOL, loadConfig, parseConfig, redactKey, saveConfig } from './config.js';
|
|
12
|
+
export { assertToolNamespace, clearConfig, configPath, HUB_TOOL, loadConfig, lookupWorkspaceKey, parseConfig, redactKey, removeWorkspaceKey, saveConfig, storeWorkspaceKey } from './config.js';
|
|
10
13
|
export { ask, printJson } from './io.js';
|
|
11
14
|
export { CliUsageError, DEFAULT_PROFILE, resolveApiKey, resolveBaseUrl, resolveProfile } from './resolve.js';
|
|
12
15
|
export { CliAuthClient, CliAuthError } from './auth.js';
|
|
16
|
+
export { CliConnectClient, CliConnectError } from './connect.js';
|
|
17
|
+
export { connectOnDemand, probeToolInstance } from './connect-on-demand.js';
|
|
18
|
+
export { getActiveWorkspace, resolveTargetWorkspace, setActiveWorkspace } from './org.js';
|
|
13
19
|
export { migrateLegacyConfig } from './migrate.js';
|
|
14
20
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,OAAO,EACL,mBAAmB,EACnB,WAAW,EACX,UAAU,EACV,QAAQ,EACR,UAAU,EACV,kBAAkB,EAClB,WAAW,EACX,SAAS,EACT,kBAAkB,EAClB,UAAU,EACV,iBAAiB,EAClB,MAAM,aAAa,CAAC;AAGrB,OAAO,EAAE,GAAG,EAAE,SAAS,EAAE,MAAM,SAAS,CAAC;AAGzC,OAAO,EAAE,aAAa,EAAE,eAAe,EAAE,aAAa,EAAE,cAAc,EAAE,cAAc,EAAE,MAAM,cAAc,CAAC;AAG7G,OAAO,EAAE,aAAa,EAAE,YAAY,EAAE,MAAM,WAAW,CAAC;AAWxD,OAAO,EAAE,gBAAgB,EAAE,eAAe,EAAE,MAAM,cAAc,CAAC;AAUjE,OAAO,EAAE,eAAe,EAAE,iBAAiB,EAAE,MAAM,wBAAwB,CAAC;AAS5E,OAAO,EAAE,kBAAkB,EAAE,sBAAsB,EAAE,kBAAkB,EAAE,MAAM,UAAU,CAAC;AAG1F,OAAO,EAAE,mBAAmB,EAAE,MAAM,cAAc,CAAC"}
|
package/dist/org.d.ts
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { type CliEnv } from './config.js';
|
|
2
|
+
/**
|
|
3
|
+
* Org context for the cross-tool connect flow (binding patterns §7). Orgs
|
|
4
|
+
* are HUB-level entities and the hub login is the one credential shared
|
|
5
|
+
* across the tool family, so the active org lives on the HUB profile:
|
|
6
|
+
* `antasphere org use` sets it, every tool CLI reads it when picking the
|
|
7
|
+
* org to exchange for.
|
|
8
|
+
*
|
|
9
|
+
* The effective target org for an exchange resolves in this order:
|
|
10
|
+
*
|
|
11
|
+
* explicit per-invocation override (--org)
|
|
12
|
+
* → the hub profile's active org (`org use`)
|
|
13
|
+
* → the hub key's bound workspace (set at login)
|
|
14
|
+
* → undefined — the exchange then omits `workspaceId` and the hub
|
|
15
|
+
* defaults to the key's bound org server-side.
|
|
16
|
+
*/
|
|
17
|
+
export interface OrgContextOptions {
|
|
18
|
+
/** Hub profile name; default = the hub config's active profile. */
|
|
19
|
+
profile?: string;
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* The hub profile's effective active org: the `org use` choice when one is
|
|
23
|
+
* set, else the org the hub key was bound to at login. Undefined when not
|
|
24
|
+
* logged in (or an explicitly named profile is missing → CliUsageError).
|
|
25
|
+
*/
|
|
26
|
+
export declare function getActiveWorkspace(env: CliEnv, opts?: OrgContextOptions): string | undefined;
|
|
27
|
+
/**
|
|
28
|
+
* What `antasphere org use` calls: persist the org choice on the hub
|
|
29
|
+
* profile (`null` clears it, falling back to the key's bound workspace).
|
|
30
|
+
* Every other profile field is preserved. Returns the file written.
|
|
31
|
+
*/
|
|
32
|
+
export declare function setActiveWorkspace(env: CliEnv, workspaceId: string | null, opts?: OrgContextOptions): string;
|
|
33
|
+
export interface ResolveTargetWorkspaceOptions extends OrgContextOptions {
|
|
34
|
+
/** Per-invocation override (--org). */
|
|
35
|
+
override?: string;
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* The org a cross-tool exchange should target: explicit override → active
|
|
39
|
+
* org → the hub key's bound workspace → undefined (hub decides).
|
|
40
|
+
*/
|
|
41
|
+
export declare function resolveTargetWorkspace(env: CliEnv, opts?: ResolveTargetWorkspaceOptions): string | undefined;
|
|
42
|
+
//# sourceMappingURL=org.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"org.d.ts","sourceRoot":"","sources":["../src/org.ts"],"names":[],"mappings":"AAAA,OAAO,EAAoC,KAAK,MAAM,EAAE,MAAM,aAAa,CAAC;AAG5E;;;;;;;;;;;;;;GAcG;AAEH,MAAM,WAAW,iBAAiB;IAChC,mEAAmE;IACnE,OAAO,CAAC,EAAE,MAAM,CAAC;CAClB;AAED;;;;GAIG;AACH,wBAAgB,kBAAkB,CAAC,GAAG,EAAE,MAAM,EAAE,IAAI,GAAE,iBAAsB,GAAG,MAAM,GAAG,SAAS,CAGhG;AAED;;;;GAIG;AACH,wBAAgB,kBAAkB,CAChC,GAAG,EAAE,MAAM,EACX,WAAW,EAAE,MAAM,GAAG,IAAI,EAC1B,IAAI,GAAE,iBAAsB,GAC3B,MAAM,CAaR;AAED,MAAM,WAAW,6BAA8B,SAAQ,iBAAiB;IACtE,uCAAuC;IACvC,QAAQ,CAAC,EAAE,MAAM,CAAC;CACnB;AAED;;;GAGG;AACH,wBAAgB,sBAAsB,CACpC,GAAG,EAAE,MAAM,EACX,IAAI,GAAE,6BAAkC,GACvC,MAAM,GAAG,SAAS,CAEpB"}
|
package/dist/org.js
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { HUB_TOOL, loadConfig, saveConfig } from './config.js';
|
|
2
|
+
import { CliUsageError, resolveProfile } from './resolve.js';
|
|
3
|
+
/**
|
|
4
|
+
* The hub profile's effective active org: the `org use` choice when one is
|
|
5
|
+
* set, else the org the hub key was bound to at login. Undefined when not
|
|
6
|
+
* logged in (or an explicitly named profile is missing → CliUsageError).
|
|
7
|
+
*/
|
|
8
|
+
export function getActiveWorkspace(env, opts = {}) {
|
|
9
|
+
const { profile } = resolveProfile(loadConfig(env, HUB_TOOL), opts.profile);
|
|
10
|
+
return profile?.activeWorkspaceId ?? profile?.workspaceId;
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* What `antasphere org use` calls: persist the org choice on the hub
|
|
14
|
+
* profile (`null` clears it, falling back to the key's bound workspace).
|
|
15
|
+
* Every other profile field is preserved. Returns the file written.
|
|
16
|
+
*/
|
|
17
|
+
export function setActiveWorkspace(env, workspaceId, opts = {}) {
|
|
18
|
+
const config = loadConfig(env, HUB_TOOL);
|
|
19
|
+
const { name, profile } = resolveProfile(config, opts.profile);
|
|
20
|
+
if (!name || !profile) {
|
|
21
|
+
throw new CliUsageError('No hub profile to set the org on — run `antasphere login` first.');
|
|
22
|
+
}
|
|
23
|
+
if (workspaceId === null) {
|
|
24
|
+
const { activeWorkspaceId: _cleared, ...rest } = profile;
|
|
25
|
+
config.profiles[name] = rest;
|
|
26
|
+
}
|
|
27
|
+
else {
|
|
28
|
+
config.profiles[name] = { ...profile, activeWorkspaceId: workspaceId };
|
|
29
|
+
}
|
|
30
|
+
return saveConfig(env, HUB_TOOL, config);
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* The org a cross-tool exchange should target: explicit override → active
|
|
34
|
+
* org → the hub key's bound workspace → undefined (hub decides).
|
|
35
|
+
*/
|
|
36
|
+
export function resolveTargetWorkspace(env, opts = {}) {
|
|
37
|
+
return opts.override ?? getActiveWorkspace(env, opts);
|
|
38
|
+
}
|
|
39
|
+
//# sourceMappingURL=org.js.map
|
package/dist/org.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"org.js","sourceRoot":"","sources":["../src/org.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,UAAU,EAAE,UAAU,EAAe,MAAM,aAAa,CAAC;AAC5E,OAAO,EAAE,aAAa,EAAE,cAAc,EAAE,MAAM,cAAc,CAAC;AAuB7D;;;;GAIG;AACH,MAAM,UAAU,kBAAkB,CAAC,GAAW,EAAE,OAA0B,EAAE;IAC1E,MAAM,EAAE,OAAO,EAAE,GAAG,cAAc,CAAC,UAAU,CAAC,GAAG,EAAE,QAAQ,CAAC,EAAE,IAAI,CAAC,OAAO,CAAC,CAAC;IAC5E,OAAO,OAAO,EAAE,iBAAiB,IAAI,OAAO,EAAE,WAAW,CAAC;AAC5D,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,kBAAkB,CAChC,GAAW,EACX,WAA0B,EAC1B,OAA0B,EAAE;IAE5B,MAAM,MAAM,GAAG,UAAU,CAAC,GAAG,EAAE,QAAQ,CAAC,CAAC;IACzC,MAAM,EAAE,IAAI,EAAE,OAAO,EAAE,GAAG,cAAc,CAAC,MAAM,EAAE,IAAI,CAAC,OAAO,CAAC,CAAC;IAC/D,IAAI,CAAC,IAAI,IAAI,CAAC,OAAO,EAAE,CAAC;QACtB,MAAM,IAAI,aAAa,CAAC,kEAAkE,CAAC,CAAC;IAC9F,CAAC;IACD,IAAI,WAAW,KAAK,IAAI,EAAE,CAAC;QACzB,MAAM,EAAE,iBAAiB,EAAE,QAAQ,EAAE,GAAG,IAAI,EAAE,GAAG,OAAO,CAAC;QACzD,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC;IAC/B,CAAC;SAAM,CAAC;QACN,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC,GAAG,EAAE,GAAG,OAAO,EAAE,iBAAiB,EAAE,WAAW,EAAE,CAAC;IACzE,CAAC;IACD,OAAO,UAAU,CAAC,GAAG,EAAE,QAAQ,EAAE,MAAM,CAAC,CAAC;AAC3C,CAAC;AAOD;;;GAGG;AACH,MAAM,UAAU,sBAAsB,CACpC,GAAW,EACX,OAAsC,EAAE;IAExC,OAAO,IAAI,CAAC,QAAQ,IAAI,kBAAkB,CAAC,GAAG,EAAE,IAAI,CAAC,CAAC;AACxD,CAAC"}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@antasphere/cli-core",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "Shared CLI foundation for Antasphere tool CLIs: the ~/.config/antasphere config home, tool-namespaced profiles, URL resolution, the instance email-OTP auth client, and the CliIo prompt seam",
|
|
3
|
+
"version": "0.3.0",
|
|
4
|
+
"description": "Shared CLI foundation for Antasphere tool CLIs: the ~/.config/antasphere config home, tool-namespaced profiles, URL resolution, the instance email-OTP auth client, the hub→tool cross-tool connect exchange with its connect-on-demand seam, and the CliIo prompt seam",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"repository": {
|
|
7
7
|
"type": "git",
|
package/src/config.ts
CHANGED
|
@@ -28,6 +28,22 @@ import { dirname, join } from 'node:path';
|
|
|
28
28
|
|
|
29
29
|
export type CliEnv = Record<string, string | undefined>;
|
|
30
30
|
|
|
31
|
+
/**
|
|
32
|
+
* A tool-local key minted by the cross-tool connect exchange (binding
|
|
33
|
+
* patterns §7), cached in the tool's profile under the HUB org it was
|
|
34
|
+
* exchanged for. Every field beyond the key itself is informational.
|
|
35
|
+
*/
|
|
36
|
+
export interface CliWorkspaceKey {
|
|
37
|
+
/** Full tool-local API key (`slk_`-style) — shown once at mint, cached here. */
|
|
38
|
+
apiKey: string;
|
|
39
|
+
/** The tool-local workspace the key is bound to (the hub org's projection). */
|
|
40
|
+
toolWorkspaceId?: string;
|
|
41
|
+
/** The signed-in account's email at mint. */
|
|
42
|
+
email?: string;
|
|
43
|
+
/** ISO timestamp of the exchange that minted the key. */
|
|
44
|
+
mintedAt?: string;
|
|
45
|
+
}
|
|
46
|
+
|
|
31
47
|
export interface CliProfile {
|
|
32
48
|
/** `<prefix>_...` API key for this profile. */
|
|
33
49
|
apiKey?: string;
|
|
@@ -37,6 +53,12 @@ export interface CliProfile {
|
|
|
37
53
|
email?: string;
|
|
38
54
|
/** The org/workspace the key is bound to (one workspace per credential). */
|
|
39
55
|
workspaceId?: string;
|
|
56
|
+
/** Hub profiles only: the org selected via `antasphere org use` (overrides
|
|
57
|
+
* the key's bound `workspaceId` as the default exchange target). */
|
|
58
|
+
activeWorkspaceId?: string;
|
|
59
|
+
/** Tool profiles only: exchange-minted keys, one per HUB org — the
|
|
60
|
+
* per-(tool, org) cache of the cross-tool connect flow. */
|
|
61
|
+
workspaceKeys?: Record<string, CliWorkspaceKey>;
|
|
40
62
|
}
|
|
41
63
|
|
|
42
64
|
export interface CliConfig {
|
|
@@ -123,3 +145,65 @@ export function redactKey(key: string): string {
|
|
|
123
145
|
if (key.length <= 16) return '****';
|
|
124
146
|
return `${key.slice(0, 13)}…${key.slice(-4)}`;
|
|
125
147
|
}
|
|
148
|
+
|
|
149
|
+
/**
|
|
150
|
+
* The cached tool-local key for a HUB org, if any. Strictly org-matched:
|
|
151
|
+
* the per-org cache first, then the legacy single `apiKey` — but ONLY when
|
|
152
|
+
* the profile's `workspaceId` says it is bound to exactly this workspace.
|
|
153
|
+
* A key whose binding is unknown is never returned for an org lookup.
|
|
154
|
+
*/
|
|
155
|
+
export function lookupWorkspaceKey(profile: CliProfile | undefined, workspaceId: string): string | undefined {
|
|
156
|
+
if (!profile) return undefined;
|
|
157
|
+
const entry = profile.workspaceKeys?.[workspaceId];
|
|
158
|
+
if (entry?.apiKey) return entry.apiKey;
|
|
159
|
+
if (profile.apiKey && profile.workspaceId === workspaceId) return profile.apiKey;
|
|
160
|
+
return undefined;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/**
|
|
164
|
+
* Cache an exchange-minted tool key under (profile, hub org), creating the
|
|
165
|
+
* profile on first contact (and making it active when no profile is active
|
|
166
|
+
* yet — first cloud connect on a fresh machine). Every other profile field
|
|
167
|
+
* is preserved untouched. Returns the file written.
|
|
168
|
+
*/
|
|
169
|
+
export function storeWorkspaceKey(
|
|
170
|
+
env: CliEnv,
|
|
171
|
+
tool: string,
|
|
172
|
+
profileName: string,
|
|
173
|
+
workspaceId: string,
|
|
174
|
+
entry: CliWorkspaceKey
|
|
175
|
+
): string {
|
|
176
|
+
const config = loadConfig(env, tool);
|
|
177
|
+
const profile = config.profiles[profileName] ?? {};
|
|
178
|
+
config.profiles[profileName] = {
|
|
179
|
+
...profile,
|
|
180
|
+
workspaceKeys: { ...profile.workspaceKeys, [workspaceId]: entry }
|
|
181
|
+
};
|
|
182
|
+
if (!config.activeProfile) config.activeProfile = profileName;
|
|
183
|
+
return saveConfig(env, tool, config);
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/**
|
|
187
|
+
* Drop one org's cached key from a profile (tool logout for that org).
|
|
188
|
+
* Returns whether anything was removed; the legacy single `apiKey` is never
|
|
189
|
+
* touched — it belongs to the tool's own login flow.
|
|
190
|
+
*/
|
|
191
|
+
export function removeWorkspaceKey(
|
|
192
|
+
env: CliEnv,
|
|
193
|
+
tool: string,
|
|
194
|
+
profileName: string,
|
|
195
|
+
workspaceId: string
|
|
196
|
+
): boolean {
|
|
197
|
+
const config = loadConfig(env, tool);
|
|
198
|
+
const profile = config.profiles[profileName];
|
|
199
|
+
if (!profile?.workspaceKeys || !(workspaceId in profile.workspaceKeys)) return false;
|
|
200
|
+
const { [workspaceId]: _dropped, ...rest } = profile.workspaceKeys;
|
|
201
|
+
if (Object.keys(rest).length === 0) {
|
|
202
|
+
const { workspaceKeys: _empty, ...bare } = profile;
|
|
203
|
+
config.profiles[profileName] = bare;
|
|
204
|
+
} else {
|
|
205
|
+
config.profiles[profileName] = { ...profile, workspaceKeys: rest };
|
|
206
|
+
}
|
|
207
|
+
saveConfig(env, tool, config);
|
|
208
|
+
return true;
|
|
209
|
+
}
|
|
@@ -0,0 +1,250 @@
|
|
|
1
|
+
import { assertToolNamespace, HUB_TOOL, loadConfig, saveConfig, storeWorkspaceKey } from './config.js';
|
|
2
|
+
import type { CliEnv } from './config.js';
|
|
3
|
+
import { CliConnectClient, CliConnectError } from './connect.js';
|
|
4
|
+
import type { CliConnectResult } from './connect.js';
|
|
5
|
+
import { CliUsageError, DEFAULT_PROFILE, resolveProfile } from './resolve.js';
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Connect-on-demand (binding patterns §7, gcloud model), extracted from the
|
|
9
|
+
* Slideless CLI so every Antasphere tool CLI inherits "one `antasphere login`
|
|
10
|
+
* serves every federated tool". When a tool CLI resolves NO credential of its
|
|
11
|
+
* own, it calls `connectOnDemand`:
|
|
12
|
+
*
|
|
13
|
+
* 1. Discovery gates the flow: only an Antasphere-CLOUD instance can mint
|
|
14
|
+
* keys through the hub (unauthenticated GET /instance — never guess).
|
|
15
|
+
* Unreachable, foreign, or self-hosted instances answer `not_cloud`
|
|
16
|
+
* and the tool raises its classic no-key error unchanged.
|
|
17
|
+
* 2. The hub credential is what `antasphere login` stored on the hub
|
|
18
|
+
* profile (the config home's HUB_TOOL namespace) — hub URL included,
|
|
19
|
+
* never a hardcoded constant here.
|
|
20
|
+
* 3. `CliConnectClient.exchange` trades it for a tool-local key (one
|
|
21
|
+
* re-exchange retry when the 120 s JWT dies in transit; a rejected hub
|
|
22
|
+
* credential maps to guided `antasphere login` advice).
|
|
23
|
+
* 4. The minted key is cached per (tool, HUB org) — but only onto a
|
|
24
|
+
* profile that names THIS instance (a fresh profile gets pinned to it);
|
|
25
|
+
* a profile pointing elsewhere never receives it.
|
|
26
|
+
*
|
|
27
|
+
* A new tool needs only its namespace, base URL, and copy — the flow itself
|
|
28
|
+
* is tool-agnostic.
|
|
29
|
+
*/
|
|
30
|
+
|
|
31
|
+
/** What the unauthenticated discovery probe learned about a tool instance. */
|
|
32
|
+
export interface ToolInstanceProbe {
|
|
33
|
+
/** Whether the instance signs in through the Antasphere hub (advertises
|
|
34
|
+
* the `antasphere` auth method, or calls itself the cloud edition). */
|
|
35
|
+
cloud: boolean;
|
|
36
|
+
/** The instance's self-reported edition (`cloud`, `oss`, …). */
|
|
37
|
+
edition: string | undefined;
|
|
38
|
+
/** The advertised auth methods (open enum — unknown entries kept). */
|
|
39
|
+
authMethods: string[];
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Probe a tool instance's unauthenticated discovery endpoint
|
|
44
|
+
* (`GET {toolBaseUrl}/api/v1/instance`). Returns what it advertises, or
|
|
45
|
+
* `null` when the instance is unreachable or answers a foreign shape —
|
|
46
|
+
* callers treat both exactly like "not cloud".
|
|
47
|
+
*/
|
|
48
|
+
export async function probeToolInstance(
|
|
49
|
+
toolBaseUrl: string,
|
|
50
|
+
fetchImpl?: typeof globalThis.fetch
|
|
51
|
+
): Promise<ToolInstanceProbe | null> {
|
|
52
|
+
const f = fetchImpl ?? globalThis.fetch.bind(globalThis);
|
|
53
|
+
try {
|
|
54
|
+
const res = await f(`${toolBaseUrl.replace(/\/+$/, '')}/api/v1/instance`, {
|
|
55
|
+
method: 'GET',
|
|
56
|
+
// Discovery is served cacheable for CLI/MCP clients, but the probe
|
|
57
|
+
// must see live state (mirrors the tool SDKs' discovery call).
|
|
58
|
+
cache: 'no-store'
|
|
59
|
+
});
|
|
60
|
+
if (!res.ok) return null;
|
|
61
|
+
const info = (await res.json().catch(() => null)) as {
|
|
62
|
+
edition?: unknown;
|
|
63
|
+
auth?: { methods?: unknown };
|
|
64
|
+
} | null;
|
|
65
|
+
const methods = info?.auth?.methods;
|
|
66
|
+
if (!Array.isArray(methods)) return null;
|
|
67
|
+
const authMethods = methods.filter((m): m is string => typeof m === 'string');
|
|
68
|
+
const edition = typeof info?.edition === 'string' ? info.edition : undefined;
|
|
69
|
+
return { cloud: authMethods.includes('antasphere') || edition === 'cloud', edition, authMethods };
|
|
70
|
+
} catch {
|
|
71
|
+
return null;
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** The facts the connected notice is rendered from. */
|
|
76
|
+
export interface ConnectNoticeFacts {
|
|
77
|
+
/** The tool instance the exchange connected to (origin-normalized). */
|
|
78
|
+
toolBaseUrl: string;
|
|
79
|
+
/** The signed-in account's email at mint. */
|
|
80
|
+
email: string;
|
|
81
|
+
/** The HUB org the exchange resolved to. */
|
|
82
|
+
hubWorkspaceId: string;
|
|
83
|
+
/** Whether the minted key was cached (per (tool, hub org)). */
|
|
84
|
+
cached: boolean;
|
|
85
|
+
/** The tool profile the cache targeted. */
|
|
86
|
+
profileName: string;
|
|
87
|
+
/** When NOT cached: the other instance the profile points at. */
|
|
88
|
+
profileBaseUrl?: string;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* Branded copy seams. Defaults reproduce the Slideless CLI's strings modulo
|
|
93
|
+
* the tool name (the tool namespace stands in for the display name, and the
|
|
94
|
+
* key-env-var name is derived from it: `slideless` → `SLIDELESS_API_KEY`).
|
|
95
|
+
*/
|
|
96
|
+
export interface ConnectOnDemandMessages {
|
|
97
|
+
/** `CliUsageError` text when the instance is cloud but no `antasphere
|
|
98
|
+
* login` credential is stored on the hub profile. */
|
|
99
|
+
missingHubLogin?: string;
|
|
100
|
+
/** `CliUsageError` text when the hub rejected the stored credential. */
|
|
101
|
+
hubLoginRejected?: string;
|
|
102
|
+
/** Renders the success notice handed to `notify` (newline included). */
|
|
103
|
+
connected?: (facts: ConnectNoticeFacts) => string;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
function defaultMissingHubLogin(tool: string): string {
|
|
107
|
+
const envVar = `${tool.replace(/-/g, '_').toUpperCase()}_API_KEY`;
|
|
108
|
+
return (
|
|
109
|
+
`This ${tool} instance signs in through the Antasphere hub. Run \`antasphere login\` once, ` +
|
|
110
|
+
`then retry — or pass --api-key / set ${envVar}.`
|
|
111
|
+
);
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
const DEFAULT_HUB_LOGIN_REJECTED =
|
|
115
|
+
'The stored Antasphere hub credential was rejected — run `antasphere login` again, then retry.';
|
|
116
|
+
|
|
117
|
+
function defaultConnected(facts: ConnectNoticeFacts): string {
|
|
118
|
+
return (
|
|
119
|
+
`Connected to ${facts.toolBaseUrl} as ${facts.email} via Antasphere (org ${facts.hubWorkspaceId})` +
|
|
120
|
+
(facts.cached
|
|
121
|
+
? ''
|
|
122
|
+
: ` — key NOT cached: profile '${facts.profileName}' points at ${facts.profileBaseUrl}`) +
|
|
123
|
+
'.\n'
|
|
124
|
+
);
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
export interface ConnectOnDemandOptions {
|
|
128
|
+
/** The tool's config namespace (lowercase slug — it names the cache file). */
|
|
129
|
+
tool: string;
|
|
130
|
+
/** The resolved tool instance origin the CLI is talking to. */
|
|
131
|
+
toolBaseUrl: string;
|
|
132
|
+
/** The exchange resource URL; default = this instance's MCP endpoint,
|
|
133
|
+
* `${toolBaseUrl}/mcp` (the tool's registered resource URL). */
|
|
134
|
+
resource?: string;
|
|
135
|
+
/** Target hub org for the exchange (`--org` → `antasphere org use` → the
|
|
136
|
+
* hub key's bound org — resolve via `resolveTargetWorkspace`); omit =
|
|
137
|
+
* the hub defaults to the key's bound org server-side. */
|
|
138
|
+
org?: string;
|
|
139
|
+
/** The tool profile the minted key is cached on; default `DEFAULT_PROFILE`. */
|
|
140
|
+
profileName?: string;
|
|
141
|
+
env: CliEnv;
|
|
142
|
+
fetch?: typeof globalThis.fetch;
|
|
143
|
+
/** Receives the human "Connected to …" notice (tools wire their stderr);
|
|
144
|
+
* omitted = silent. Machine output stays untouched either way. */
|
|
145
|
+
notify?: (line: string) => void;
|
|
146
|
+
messages?: ConnectOnDemandMessages;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
export type ConnectOnDemandOutcome =
|
|
150
|
+
| {
|
|
151
|
+
outcome: 'connected';
|
|
152
|
+
/** The minted tool-local key — this invocation's credential. */
|
|
153
|
+
key: string;
|
|
154
|
+
/** The full exchange result (user, hub org, tool workspace, key meta). */
|
|
155
|
+
result: CliConnectResult;
|
|
156
|
+
/** Whether the key was cached per (tool, hub org) for the next run. */
|
|
157
|
+
cached: boolean;
|
|
158
|
+
}
|
|
159
|
+
| {
|
|
160
|
+
/** Not an Antasphere-cloud instance (or unreachable): the caller
|
|
161
|
+
* raises its classic no-key error unchanged. */
|
|
162
|
+
outcome: 'not_cloud';
|
|
163
|
+
};
|
|
164
|
+
|
|
165
|
+
/**
|
|
166
|
+
* The hub → tool exchange fallback a tool CLI runs when no direct credential
|
|
167
|
+
* resolved. Returns `not_cloud` when the instance is not an Antasphere-cloud
|
|
168
|
+
* one (or unreachable). Throws a guided `CliUsageError` when the instance IS
|
|
169
|
+
* cloud but the hub login is missing or rejected; every other exchange
|
|
170
|
+
* failure propagates as its `CliConnectError`.
|
|
171
|
+
*/
|
|
172
|
+
export async function connectOnDemand(opts: ConnectOnDemandOptions): Promise<ConnectOnDemandOutcome> {
|
|
173
|
+
assertToolNamespace(opts.tool);
|
|
174
|
+
const toolBaseUrl = opts.toolBaseUrl.replace(/\/+$/, '');
|
|
175
|
+
const messages = opts.messages ?? {};
|
|
176
|
+
|
|
177
|
+
// 1. Only a CLOUD instance can mint keys through the hub — ask discovery,
|
|
178
|
+
// never guess. An unreachable or foreign instance is `not_cloud`.
|
|
179
|
+
const probe = await probeToolInstance(toolBaseUrl, opts.fetch);
|
|
180
|
+
if (!probe?.cloud) return { outcome: 'not_cloud' };
|
|
181
|
+
|
|
182
|
+
// 2. The hub credential is what `antasphere login` stored on the hub
|
|
183
|
+
// profile (HUB_TOOL namespace) — one login for the whole tool family.
|
|
184
|
+
// The hub URL comes from that same profile, never from a constant here.
|
|
185
|
+
const { profile: hubProfile } = resolveProfile(loadConfig(opts.env, HUB_TOOL), undefined);
|
|
186
|
+
const hubKey = hubProfile?.apiKey;
|
|
187
|
+
const hubBaseUrl = hubProfile?.baseUrl;
|
|
188
|
+
if (!hubKey || !hubBaseUrl) {
|
|
189
|
+
throw new CliUsageError(messages.missingHubLogin ?? defaultMissingHubLogin(opts.tool));
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
// 3. The exchange resource defaults to THIS instance's registered resource
|
|
193
|
+
// URL — its MCP endpoint, derived from the resolved instance origin.
|
|
194
|
+
const resource = opts.resource ?? `${toolBaseUrl}/mcp`;
|
|
195
|
+
const connect = new CliConnectClient({
|
|
196
|
+
hubBaseUrl,
|
|
197
|
+
toolBaseUrl,
|
|
198
|
+
...(opts.fetch ? { fetch: opts.fetch } : {})
|
|
199
|
+
});
|
|
200
|
+
const body = { resource, ...(opts.org ? { workspaceId: opts.org } : {}) };
|
|
201
|
+
let result: CliConnectResult;
|
|
202
|
+
try {
|
|
203
|
+
result = await connect.exchange(hubKey, body);
|
|
204
|
+
} catch (e) {
|
|
205
|
+
if (e instanceof CliConnectError && e.needsReExchange) {
|
|
206
|
+
// The 120 s JWT died in transit (expired/replayed) — one fresh
|
|
207
|
+
// exchange; a second rejection propagates.
|
|
208
|
+
result = await connect.exchange(hubKey, body);
|
|
209
|
+
} else if (e instanceof CliConnectError && e.needsHubLogin) {
|
|
210
|
+
throw new CliUsageError(messages.hubLoginRejected ?? DEFAULT_HUB_LOGIN_REJECTED);
|
|
211
|
+
} else {
|
|
212
|
+
throw e;
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
// 4. Cache the minted key per (tool, hub org) — but only onto a profile
|
|
217
|
+
// that names THIS instance (or a fresh one, which gets pinned to it),
|
|
218
|
+
// never onto a profile pointing somewhere else.
|
|
219
|
+
const profileName = opts.profileName ?? DEFAULT_PROFILE;
|
|
220
|
+
const existing = loadConfig(opts.env, opts.tool).profiles[profileName];
|
|
221
|
+
const cached = !existing?.baseUrl || existing.baseUrl.replace(/\/+$/, '') === toolBaseUrl;
|
|
222
|
+
if (cached) {
|
|
223
|
+
storeWorkspaceKey(opts.env, opts.tool, profileName, result.hubWorkspaceId, {
|
|
224
|
+
apiKey: result.key,
|
|
225
|
+
toolWorkspaceId: result.toolWorkspaceId,
|
|
226
|
+
email: result.user.email,
|
|
227
|
+
mintedAt: new Date().toISOString()
|
|
228
|
+
});
|
|
229
|
+
if (!existing?.baseUrl) {
|
|
230
|
+
// First contact: pin the profile to this instance so the next
|
|
231
|
+
// invocation resolves the URL and the cached key with no flags.
|
|
232
|
+
const cfg = loadConfig(opts.env, opts.tool);
|
|
233
|
+
cfg.profiles[profileName] = { ...cfg.profiles[profileName], baseUrl: toolBaseUrl };
|
|
234
|
+
saveConfig(opts.env, opts.tool, cfg);
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
const facts: ConnectNoticeFacts = {
|
|
239
|
+
toolBaseUrl,
|
|
240
|
+
email: result.user.email,
|
|
241
|
+
hubWorkspaceId: result.hubWorkspaceId,
|
|
242
|
+
cached,
|
|
243
|
+
profileName,
|
|
244
|
+
// `cached` is false only when the profile names another instance.
|
|
245
|
+
...(cached ? {} : { profileBaseUrl: existing?.baseUrl })
|
|
246
|
+
};
|
|
247
|
+
opts.notify?.((messages.connected ?? defaultConnected)(facts));
|
|
248
|
+
|
|
249
|
+
return { outcome: 'connected', key: result.key, result, cached };
|
|
250
|
+
}
|