@octen.ai/cli 0.7.0 → 0.9.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 +325 -4
- package/dist/api/chat.d.ts +4 -1
- package/dist/api/client.d.ts +25 -1
- package/dist/api/client.js +144 -17
- package/dist/api/errors.d.ts +27 -0
- package/dist/api/errors.js +52 -0
- package/dist/api/search.js +5 -2
- package/dist/api/sse.d.ts +15 -3
- package/dist/api/sse.js +131 -36
- package/dist/auth/constants.d.ts +47 -0
- package/dist/auth/constants.js +89 -0
- package/dist/auth/exchange.d.ts +74 -0
- package/dist/auth/exchange.js +124 -0
- package/dist/auth/login.d.ts +64 -0
- package/dist/auth/login.js +163 -0
- package/dist/auth/loopback.d.ts +32 -0
- package/dist/auth/loopback.js +95 -0
- package/dist/auth/oauthClient.d.ts +70 -0
- package/dist/auth/oauthClient.js +136 -0
- package/dist/auth/pkce.d.ts +6 -0
- package/dist/auth/pkce.js +13 -0
- package/dist/auth/revoke.d.ts +58 -0
- package/dist/auth/revoke.js +91 -0
- package/dist/auth/store.d.ts +34 -0
- package/dist/auth/store.js +149 -0
- package/dist/cli.js +6 -0
- package/dist/commands/broadSearch.js +6 -6
- package/dist/commands/chat.js +12 -8
- package/dist/commands/configureMcp.js +38 -20
- package/dist/commands/configureSkills.js +25 -10
- package/dist/commands/imageSearch.js +3 -3
- package/dist/commands/login.d.ts +49 -0
- package/dist/commands/login.js +161 -0
- package/dist/commands/logout.d.ts +46 -0
- package/dist/commands/logout.js +142 -0
- package/dist/commands/reset.js +43 -5
- package/dist/commands/search.js +6 -6
- package/dist/commands/utils.d.ts +21 -2
- package/dist/commands/utils.js +43 -6
- package/dist/commands/whoami.d.ts +27 -0
- package/dist/commands/whoami.js +109 -0
- package/dist/config/resolve.d.ts +44 -1
- package/dist/config/resolve.js +80 -5
- package/dist/mcp/clients.js +7 -3
- package/dist/mcp/install.js +15 -2
- package/dist/mcp/write.js +24 -3
- package/dist/output/pretty/whoami.d.ts +59 -0
- package/dist/output/pretty/whoami.js +103 -0
- package/dist/skills/setkey.js +5 -4
- package/dist/util/secretFile.d.ts +24 -0
- package/dist/util/secretFile.js +35 -0
- package/package.json +1 -1
|
@@ -4,7 +4,9 @@ import { MCP_CLIENTS } from "../mcp/clients.js";
|
|
|
4
4
|
import { installMcp } from "../mcp/install.js";
|
|
5
5
|
import { mcpStatus } from "../mcp/detect.js";
|
|
6
6
|
import { resolveApiKey } from "../config/resolve.js";
|
|
7
|
+
import { OctenNoCredentialError } from "../api/errors.js";
|
|
7
8
|
import { isClientInstalled } from "../util/detectClient.js";
|
|
9
|
+
import { parseScopeOpt } from "./utils.js";
|
|
8
10
|
import { quotePath } from "../util/quotePath.js";
|
|
9
11
|
// Exported so tests can call with injected dirs
|
|
10
12
|
export function registerConfigureMcp(program, internal = {}) {
|
|
@@ -18,31 +20,19 @@ export function registerConfigureMcp(program, internal = {}) {
|
|
|
18
20
|
.option("--windsurf", "configure Windsurf")
|
|
19
21
|
.option("--vscode", "configure VS Code")
|
|
20
22
|
.option("--codex", "configure Codex")
|
|
21
|
-
.option("--scope <s>", "config scope: user | project (default: user)", "user")
|
|
23
|
+
.option("--scope <s>", "config scope: user | project (default: user)", parseScopeOpt("--scope"), "user")
|
|
22
24
|
.option("--pin <ver>", "pin octen-mcp to a specific version, e.g. 0.2.1")
|
|
23
25
|
.option("--force", "configure even if the client is not detected")
|
|
24
26
|
.action(async (_opts, command) => {
|
|
25
27
|
const g = command.optsWithGlobals();
|
|
26
28
|
const opts = command.opts();
|
|
27
|
-
|
|
29
|
+
// Parsed and validated by parseScopeOpt at option-parse time.
|
|
30
|
+
const scope = opts.scope;
|
|
28
31
|
const pin = opts.pin;
|
|
29
|
-
//
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
key = resolveApiKey(g.apiKey, process.env);
|
|
34
|
-
}
|
|
35
|
-
catch {
|
|
36
|
-
key = "${OCTEN_API_KEY}";
|
|
37
|
-
keyMissing = true;
|
|
38
|
-
}
|
|
39
|
-
// Build the MCP server entry
|
|
40
|
-
const entry = {
|
|
41
|
-
command: "npx",
|
|
42
|
-
args: ["-y", pin ? `octen-mcp@${pin}` : "octen-mcp"],
|
|
43
|
-
env: { OCTEN_API_KEY: key },
|
|
44
|
-
};
|
|
45
|
-
// Determine the effective home/cwd
|
|
32
|
+
// Determine the effective home/cwd. `home` is computed before the key
|
|
33
|
+
// resolution below so it can be threaded into resolveApiKey: without
|
|
34
|
+
// it that call fell back to os.homedir() and read the real machine's
|
|
35
|
+
// credentials file, which is not this command's to read under test.
|
|
46
36
|
const home = internal.home ?? os.homedir();
|
|
47
37
|
const cwd = internal.cwd ?? process.cwd();
|
|
48
38
|
const isInstalled = internal.isInstalled ?? ((id) => isClientInstalled(id, { home }));
|
|
@@ -71,7 +61,35 @@ export function registerConfigureMcp(program, internal = {}) {
|
|
|
71
61
|
}
|
|
72
62
|
return;
|
|
73
63
|
}
|
|
74
|
-
// INSTALL MODE
|
|
64
|
+
// INSTALL MODE. Everything below needs a key; STATUS MODE above
|
|
65
|
+
// deliberately returns first, so a broken credentials file never fails
|
|
66
|
+
// a read-only status listing that does not consult it.
|
|
67
|
+
// Resolve API key — tolerate a missing one, but only a missing one.
|
|
68
|
+
let key;
|
|
69
|
+
let keyMissing = false;
|
|
70
|
+
try {
|
|
71
|
+
key = resolveApiKey(g.apiKey, process.env, { home });
|
|
72
|
+
}
|
|
73
|
+
catch (err) {
|
|
74
|
+
// ONLY a total absence of credentials becomes the ${OCTEN_API_KEY}
|
|
75
|
+
// placeholder. This used to test `instanceof OctenAuthError`, which
|
|
76
|
+
// also matches expiry and issuer/resource mismatch — so a user with a
|
|
77
|
+
// working credential and an OCTEN_AUTH_ISSUER override got
|
|
78
|
+
// "no API key found", a placeholder config, and exit 0, while the
|
|
79
|
+
// actual cause went unmentioned. Those errors name themselves; let them.
|
|
80
|
+
// Symmetric with configureSkills.ts's --set-key branch.
|
|
81
|
+
if (!(err instanceof OctenNoCredentialError))
|
|
82
|
+
throw err;
|
|
83
|
+
key = "${OCTEN_API_KEY}";
|
|
84
|
+
keyMissing = true;
|
|
85
|
+
}
|
|
86
|
+
// Build the MCP server entry
|
|
87
|
+
const entry = {
|
|
88
|
+
command: "npx",
|
|
89
|
+
args: ["-y", pin ? `octen-mcp@${pin}` : "octen-mcp"],
|
|
90
|
+
env: { OCTEN_API_KEY: key },
|
|
91
|
+
};
|
|
92
|
+
// Determine which clients to act on, gated by detection.
|
|
75
93
|
let selected;
|
|
76
94
|
if (opts.all) {
|
|
77
95
|
// Start from the full registry, then filter to installed ones.
|
|
@@ -6,9 +6,11 @@ import { SKILL_CLIENTS } from "../skills/clients.js";
|
|
|
6
6
|
import { resolveSkillsDir } from "../skills/source.js";
|
|
7
7
|
import { installSkills, skillStatus } from "../skills/install.js";
|
|
8
8
|
import { setClientEnvKey } from "../skills/setkey.js";
|
|
9
|
-
import {
|
|
9
|
+
import { resolveApiKey } from "../config/resolve.js";
|
|
10
|
+
import { OctenValidationError, OctenNoCredentialError } from "../api/errors.js";
|
|
10
11
|
import { isClientInstalled } from "../util/detectClient.js";
|
|
11
12
|
import { quotePath } from "../util/quotePath.js";
|
|
13
|
+
import { parseCsvOpt, parseScopeOpt } from "./utils.js";
|
|
12
14
|
// Exported so tests can call with injected dirs
|
|
13
15
|
export function registerConfigureSkills(program, internal = {}) {
|
|
14
16
|
program
|
|
@@ -22,8 +24,8 @@ export function registerConfigureSkills(program, internal = {}) {
|
|
|
22
24
|
.option("--openclaw", "install into OpenClaw")
|
|
23
25
|
.option("--hermes", "install into Hermes")
|
|
24
26
|
.option("--skills-dir <path>", "use a custom skills source directory")
|
|
25
|
-
.option("--scope <s>", "config scope: user | project (default: user)", "user")
|
|
26
|
-
.option("--only <names>", "comma-separated list of skill names to install (e.g. octen-search,octen-design)")
|
|
27
|
+
.option("--scope <s>", "config scope: user | project (default: user)", parseScopeOpt("--scope"), "user")
|
|
28
|
+
.option("--only <names>", "comma-separated list of skill names to install (e.g. octen-search,octen-design)", parseCsvOpt("--only"))
|
|
27
29
|
.option("--ref <ref>", "upstream git ref to fetch skills from", "main")
|
|
28
30
|
.option("--bundled", "force use of bundled (vendored) skills — no network")
|
|
29
31
|
.option("--offline", "alias for --bundled")
|
|
@@ -31,12 +33,12 @@ export function registerConfigureSkills(program, internal = {}) {
|
|
|
31
33
|
.option("--force", "configure even if the client is not detected")
|
|
32
34
|
.action(async (_opts, command) => {
|
|
33
35
|
const opts = command.opts();
|
|
34
|
-
|
|
36
|
+
// Parsed and validated by parseScopeOpt at option-parse time.
|
|
37
|
+
const scope = opts.scope;
|
|
35
38
|
const ref = opts.ref;
|
|
36
39
|
const offline = !!(opts.bundled || opts.offline);
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
: undefined;
|
|
40
|
+
// parseCsvOpt already trimmed the names and rejected an all-empty list.
|
|
41
|
+
const only = opts.only;
|
|
40
42
|
const home = internal.home ?? os.homedir();
|
|
41
43
|
const cwd = internal.cwd ?? process.cwd();
|
|
42
44
|
const isInstalled = internal.isInstalled ?? ((id) => isClientInstalled(id, { home }));
|
|
@@ -151,9 +153,22 @@ export function registerConfigureSkills(program, internal = {}) {
|
|
|
151
153
|
}
|
|
152
154
|
if (opts.setKey) {
|
|
153
155
|
const g = command.optsWithGlobals();
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
156
|
+
let key;
|
|
157
|
+
try {
|
|
158
|
+
key = resolveApiKey(g.apiKey, process.env, { home });
|
|
159
|
+
}
|
|
160
|
+
catch (err) {
|
|
161
|
+
// ONLY a total absence of credentials becomes the generic "needs a
|
|
162
|
+
// key" message. This used to test `instanceof OctenAuthError`, which
|
|
163
|
+
// also matches expiry and issuer/resource mismatch — so a user with a
|
|
164
|
+
// perfectly good credential and an OCTEN_AUTH_ISSUER override was told
|
|
165
|
+
// to run `octen login`, which cannot fix an OCTEN_AUTH_* override.
|
|
166
|
+
// Those errors already carry a message naming the real problem
|
|
167
|
+
// (resolve.ts's `mismatchMessage` exists for exactly this); rethrow
|
|
168
|
+
// and let it be seen.
|
|
169
|
+
if (!(err instanceof OctenNoCredentialError))
|
|
170
|
+
throw err;
|
|
171
|
+
throw new OctenValidationError("--set-key needs a key: pass --api-key, set OCTEN_API_KEY, or run `octen login`");
|
|
157
172
|
}
|
|
158
173
|
for (const client of selected) {
|
|
159
174
|
const result = setClientEnvKey(client.id, key, scope, home, cwd);
|
|
@@ -2,7 +2,7 @@ import { ENDPOINTS } from "../api/constants.js";
|
|
|
2
2
|
import { buildImageSearchRequest, } from "../api/mediaSearch.js";
|
|
3
3
|
import { chooseMode, emit } from "../output/render.js";
|
|
4
4
|
import { renderImageSearch } from "../output/pretty/imageSearch.js";
|
|
5
|
-
import { makeClient, parseIntOpt } from "./utils.js";
|
|
5
|
+
import { makeClient, parseCsvOpt, parseIntOpt } from "./utils.js";
|
|
6
6
|
export function registerImageSearch(program) {
|
|
7
7
|
program
|
|
8
8
|
.command("image-search")
|
|
@@ -11,8 +11,8 @@ export function registerImageSearch(program) {
|
|
|
11
11
|
.option("--image <url|path>", "image input: public URL or local file path")
|
|
12
12
|
.option("--topic <t>", "general|design")
|
|
13
13
|
.option("-n, --count <n>", "results 1-10", parseIntOpt("--count"))
|
|
14
|
-
.option("--include-domains <list>", "comma list", (
|
|
15
|
-
.option("--exclude-domains <list>", "comma list", (
|
|
14
|
+
.option("--include-domains <list>", "comma list", parseCsvOpt("--include-domains"))
|
|
15
|
+
.option("--exclude-domains <list>", "comma list", parseCsvOpt("--exclude-domains"))
|
|
16
16
|
.option("--safesearch <s>", "off|strict")
|
|
17
17
|
.option("--html-snippet", "include HTML snippet for each result")
|
|
18
18
|
.option("--html-snippet-max-tokens <n>", "max tokens per HTML snippet", parseIntOpt("--html-snippet-max-tokens"))
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import type { Command } from "commander";
|
|
2
|
+
export interface LoginInternalOpts {
|
|
3
|
+
/** Injected home dir (for testing); defaults to os.homedir(). */
|
|
4
|
+
home?: string;
|
|
5
|
+
/** Injected env (for testing); defaults to process.env. */
|
|
6
|
+
env?: NodeJS.ProcessEnv;
|
|
7
|
+
/** Injected fetch (for testing); defaults to global fetch. */
|
|
8
|
+
fetchImpl?: typeof fetch;
|
|
9
|
+
/** Injected browser opener (for testing); defaults to spawning the OS opener. */
|
|
10
|
+
openBrowser?: (url: string, onFailure: (err: unknown) => void) => void;
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* Build the argv for opening `url` in the platform's default browser. Pure
|
|
14
|
+
* so each platform can be asserted without spawning anything.
|
|
15
|
+
*
|
|
16
|
+
* win32 is `rundll32 url.dll,FileProtocolHandler`, deliberately NOT
|
|
17
|
+
* `cmd /c start`: `cmd` treats `&` as a command separator, and the
|
|
18
|
+
* authorize URL's query string is full of them — the URL would arrive
|
|
19
|
+
* truncated at the first `&`.
|
|
20
|
+
*/
|
|
21
|
+
export declare function browserCommand(platform: NodeJS.Platform, url: string): [cmd: string, args: string[]];
|
|
22
|
+
/**
|
|
23
|
+
* Spawn `cmd args` detached and ignored (`stdio: "ignore"`, `unref()`), so
|
|
24
|
+
* the CLI never waits on the child. Reports a failure — sync OR async — via
|
|
25
|
+
* `onFailure` instead of letting it propagate.
|
|
26
|
+
*
|
|
27
|
+
* This is the piece the original implementation got wrong: `spawn()` only
|
|
28
|
+
* throws synchronously for a narrow set of argument-validation failures. A
|
|
29
|
+
* missing binary (ENOENT — the common case: a headless box or a slim
|
|
30
|
+
* container without `xdg-open`, exactly the environment this fallback
|
|
31
|
+
* exists for) is reported asynchronously via the child's `'error'` event.
|
|
32
|
+
* An EventEmitter with no `'error'` listener turns that into an uncaught
|
|
33
|
+
* exception that kills the process — so the listener below is not optional.
|
|
34
|
+
*/
|
|
35
|
+
export declare function spawnDetached(cmd: string, args: string[], onFailure: (err: unknown) => void): void;
|
|
36
|
+
/**
|
|
37
|
+
* Open `url` in the platform's default browser. `onFailure` is called for
|
|
38
|
+
* either a synchronous spawn error or (the common real-world case) an
|
|
39
|
+
* asynchronous one, and the caller (`src/auth/login.ts`) routes both to the
|
|
40
|
+
* same "print the URL instead" fallback.
|
|
41
|
+
*
|
|
42
|
+
* `resolveCommand` defaults to `browserCommand` and exists only so a test
|
|
43
|
+
* can drive this real function — real `spawnDetached`, real `spawn`, real
|
|
44
|
+
* `'error'` handling — against a guaranteed-nonexistent command, instead of
|
|
45
|
+
* a real platform opener (`xdg-open`, `open`, `rundll32`) whose presence on
|
|
46
|
+
* the machine running the suite is not something a test controls.
|
|
47
|
+
*/
|
|
48
|
+
export declare function openBrowser(url: string, onFailure: (err: unknown) => void, platform?: NodeJS.Platform, resolveCommand?: (platform: NodeJS.Platform, url: string) => [string, string[]]): void;
|
|
49
|
+
export declare function registerLogin(program: Command, internal?: LoginInternalOpts): void;
|
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
import os from "node:os";
|
|
2
|
+
import { spawn } from "node:child_process";
|
|
3
|
+
import { login } from "../auth/login.js";
|
|
4
|
+
import { CREDENTIALS_VERSION, credentialsPath, readCredentials, writeCredentials } from "../auth/store.js";
|
|
5
|
+
import { assertRange } from "../api/search.js";
|
|
6
|
+
import { parseIntOpt } from "./utils.js";
|
|
7
|
+
/**
|
|
8
|
+
* Build the argv for opening `url` in the platform's default browser. Pure
|
|
9
|
+
* so each platform can be asserted without spawning anything.
|
|
10
|
+
*
|
|
11
|
+
* win32 is `rundll32 url.dll,FileProtocolHandler`, deliberately NOT
|
|
12
|
+
* `cmd /c start`: `cmd` treats `&` as a command separator, and the
|
|
13
|
+
* authorize URL's query string is full of them — the URL would arrive
|
|
14
|
+
* truncated at the first `&`.
|
|
15
|
+
*/
|
|
16
|
+
export function browserCommand(platform, url) {
|
|
17
|
+
if (platform === "win32")
|
|
18
|
+
return ["rundll32", ["url.dll,FileProtocolHandler", url]];
|
|
19
|
+
if (platform === "linux")
|
|
20
|
+
return ["xdg-open", [url]];
|
|
21
|
+
return ["open", [url]];
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* Spawn `cmd args` detached and ignored (`stdio: "ignore"`, `unref()`), so
|
|
25
|
+
* the CLI never waits on the child. Reports a failure — sync OR async — via
|
|
26
|
+
* `onFailure` instead of letting it propagate.
|
|
27
|
+
*
|
|
28
|
+
* This is the piece the original implementation got wrong: `spawn()` only
|
|
29
|
+
* throws synchronously for a narrow set of argument-validation failures. A
|
|
30
|
+
* missing binary (ENOENT — the common case: a headless box or a slim
|
|
31
|
+
* container without `xdg-open`, exactly the environment this fallback
|
|
32
|
+
* exists for) is reported asynchronously via the child's `'error'` event.
|
|
33
|
+
* An EventEmitter with no `'error'` listener turns that into an uncaught
|
|
34
|
+
* exception that kills the process — so the listener below is not optional.
|
|
35
|
+
*/
|
|
36
|
+
export function spawnDetached(cmd, args, onFailure) {
|
|
37
|
+
let child;
|
|
38
|
+
try {
|
|
39
|
+
child = spawn(cmd, args, { detached: true, stdio: "ignore" });
|
|
40
|
+
}
|
|
41
|
+
catch (err) {
|
|
42
|
+
onFailure(err);
|
|
43
|
+
return;
|
|
44
|
+
}
|
|
45
|
+
child.on("error", onFailure);
|
|
46
|
+
child.unref();
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* Open `url` in the platform's default browser. `onFailure` is called for
|
|
50
|
+
* either a synchronous spawn error or (the common real-world case) an
|
|
51
|
+
* asynchronous one, and the caller (`src/auth/login.ts`) routes both to the
|
|
52
|
+
* same "print the URL instead" fallback.
|
|
53
|
+
*
|
|
54
|
+
* `resolveCommand` defaults to `browserCommand` and exists only so a test
|
|
55
|
+
* can drive this real function — real `spawnDetached`, real `spawn`, real
|
|
56
|
+
* `'error'` handling — against a guaranteed-nonexistent command, instead of
|
|
57
|
+
* a real platform opener (`xdg-open`, `open`, `rundll32`) whose presence on
|
|
58
|
+
* the machine running the suite is not something a test controls.
|
|
59
|
+
*/
|
|
60
|
+
export function openBrowser(url, onFailure, platform = process.platform, resolveCommand = browserCommand) {
|
|
61
|
+
const [cmd, args] = resolveCommand(platform, url);
|
|
62
|
+
spawnDetached(cmd, args, onFailure);
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* A credential written while `OCTEN_API_KEY` is exported will never be read
|
|
66
|
+
* by any command: `resolveApiKey` returns the env var before it touches the
|
|
67
|
+
* file (src/config/resolve.ts:31-32). Reporting an unqualified "Logged in"
|
|
68
|
+
* for that would tell the user a browser consent flow accomplished something
|
|
69
|
+
* it did not. Warns on stderr only — stdout keeps carrying just the result,
|
|
70
|
+
* so a script parsing stdout is unaffected — and never echoes either key.
|
|
71
|
+
*/
|
|
72
|
+
function warnIfEnvKeyShadows(env) {
|
|
73
|
+
if (!env.OCTEN_API_KEY)
|
|
74
|
+
return;
|
|
75
|
+
process.stderr.write("warning: OCTEN_API_KEY is set in the environment and takes precedence over the stored " +
|
|
76
|
+
"credential, so nothing will use the credential just saved. Unset OCTEN_API_KEY for this " +
|
|
77
|
+
"login to take effect (`octen whoami` shows which source is in effect).\n");
|
|
78
|
+
}
|
|
79
|
+
/**
|
|
80
|
+
* `login --api-key` overwrites whatever is on disk. When that is a
|
|
81
|
+
* `source: "login"` credential, the file being replaced is the only place
|
|
82
|
+
* this machine records its `grantId` — the authorization stays listed in the
|
|
83
|
+
* dashboard and, once the file is gone, nothing here can name it any more
|
|
84
|
+
* — the same stranding `octen logout --local` prints the id to avoid.
|
|
85
|
+
*
|
|
86
|
+
* Costs zero network requests, which is what keeps this branch's contract
|
|
87
|
+
* intact: `--api-key` exists so a machine with no browser and no outbound
|
|
88
|
+
* access to the auth server can still be configured, so it must stay a pure
|
|
89
|
+
* local file operation. Reading the old file before overwriting it is still
|
|
90
|
+
* just a file read; the grant is deliberately NOT revoked here, which the
|
|
91
|
+
* README's "Switching from a browser login to a pasted key" section
|
|
92
|
+
* documents. An unreadable file is tolerated the way `octen logout` tolerates
|
|
93
|
+
* it — there is no grantId to extract from it either way.
|
|
94
|
+
*/
|
|
95
|
+
function warnIfOverwritingLoginGrant(home) {
|
|
96
|
+
let existing;
|
|
97
|
+
try {
|
|
98
|
+
existing = readCredentials(home);
|
|
99
|
+
}
|
|
100
|
+
catch {
|
|
101
|
+
return;
|
|
102
|
+
}
|
|
103
|
+
if (existing?.source !== "login")
|
|
104
|
+
return;
|
|
105
|
+
process.stderr.write(`warning: this replaces a browser login. Grant ${existing.grantId} was not revoked — ` +
|
|
106
|
+
"`octen login --api-key` makes no network request. It can still mint a new credential " +
|
|
107
|
+
"without a fresh consent screen; revoke it from the dashboard's authorization list if " +
|
|
108
|
+
"you want to close it out. (Run `octen logout` first to revoke it properly.)\n");
|
|
109
|
+
}
|
|
110
|
+
export function registerLogin(program, internal = {}) {
|
|
111
|
+
program
|
|
112
|
+
.command("login")
|
|
113
|
+
.description("Log in via your browser and store the resulting API key")
|
|
114
|
+
.option("--port <n>", "pin the loopback callback port (for ssh -L forwarding)", parseIntOpt("--port"))
|
|
115
|
+
.option("--no-browser", "print the authorize URL instead of opening it")
|
|
116
|
+
.addHelpText("after", [
|
|
117
|
+
"",
|
|
118
|
+
"Environment:",
|
|
119
|
+
" OCTEN_AUTH_ISSUER authorization server (default: https://auth.octen.ai)",
|
|
120
|
+
" OCTEN_AUTH_RESOURCE token audience (default: https://cli.octen.ai)",
|
|
121
|
+
"",
|
|
122
|
+
" Both are for local development only and must have no trailing slash. A stored",
|
|
123
|
+
" credential minted for a different issuer/resource pair is ignored (never used,",
|
|
124
|
+
" never deleted) — see the README's Auth section.",
|
|
125
|
+
"",
|
|
126
|
+
].join("\n"))
|
|
127
|
+
.action(async (_opts, command) => {
|
|
128
|
+
const g = command.optsWithGlobals();
|
|
129
|
+
const home = internal.home ?? os.homedir();
|
|
130
|
+
const env = internal.env ?? process.env;
|
|
131
|
+
// --api-key is a separate branch: no loopback server, no network
|
|
132
|
+
// request, just write the file and return. This is the path for CI, a
|
|
133
|
+
// container, or any machine where a browser flow is not possible.
|
|
134
|
+
if (g.apiKey) {
|
|
135
|
+
warnIfOverwritingLoginGrant(home);
|
|
136
|
+
writeCredentials(home, { version: CREDENTIALS_VERSION, source: "api-key", apiKey: g.apiKey });
|
|
137
|
+
process.stdout.write("API key saved.\n");
|
|
138
|
+
warnIfEnvKeyShadows(env);
|
|
139
|
+
return;
|
|
140
|
+
}
|
|
141
|
+
// A bad --port names itself instead of surfacing as Node's own
|
|
142
|
+
// ERR_SOCKET_BAD_PORT, or (for 0) silently picking a random port and
|
|
143
|
+
// quietly defeating the `ssh -L` pinning the flag exists for.
|
|
144
|
+
assertRange("--port", g.port, { min: 1, max: 65535 });
|
|
145
|
+
const { credentials: creds, accountName } = await login({
|
|
146
|
+
home,
|
|
147
|
+
env,
|
|
148
|
+
fetchImpl: internal.fetchImpl,
|
|
149
|
+
openBrowser: internal.openBrowser ?? ((url, onFailure) => openBrowser(url, onFailure)),
|
|
150
|
+
noBrowser: g.browser === false,
|
|
151
|
+
port: g.port,
|
|
152
|
+
});
|
|
153
|
+
// Prefer the server's human-readable name ("Octen family", "Personal")
|
|
154
|
+
// over the raw id, but keep the id as the fallback: the name is optional
|
|
155
|
+
// on the wire, and it is absent both against a server that predates the
|
|
156
|
+
// field and whenever the name could not be loaded.
|
|
157
|
+
const account = creds.source === "login" ? (accountName ?? creds.accountId) : undefined;
|
|
158
|
+
process.stdout.write(`Logged in${account ? ` as ${account}` : ""}. Credentials saved to ${credentialsPath(home)}\n`);
|
|
159
|
+
warnIfEnvKeyShadows(env);
|
|
160
|
+
});
|
|
161
|
+
}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import type { Command } from "commander";
|
|
2
|
+
export interface LogoutInternalOpts {
|
|
3
|
+
/** Injected home dir (for testing); defaults to os.homedir(). */
|
|
4
|
+
home?: string;
|
|
5
|
+
/**
|
|
6
|
+
* Injected fetch (for testing); defaults to global fetch. Never invoked
|
|
7
|
+
* for a `source: "api-key"` credential (no grant exists to revoke), when
|
|
8
|
+
* `--local` is passed, or when the stored file is unreadable — all three
|
|
9
|
+
* branches make zero network requests, because in each of them there is
|
|
10
|
+
* either no grant to revoke or no way left to name it.
|
|
11
|
+
*/
|
|
12
|
+
fetchImpl?: typeof fetch;
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* `octen logout` — revoke this device's authorization, then remove the
|
|
16
|
+
* local credential.
|
|
17
|
+
*
|
|
18
|
+
* The copy here is a hard requirement, not polish: this command clears a
|
|
19
|
+
* local file and revokes a *grant* (which only blocks the CLI from silently
|
|
20
|
+
* minting a new credential without a fresh consent screen). It never
|
|
21
|
+
* deactivates the underlying API key — that key is the user's own
|
|
22
|
+
* account-wide, long-lived key, and is very likely also sitting in other
|
|
23
|
+
* machines, production code, and the AI-client configs `octen
|
|
24
|
+
* configure-mcp` wrote. So the output must never claim to have revoked
|
|
25
|
+
* *access*, only "this authorization". Telling a user their access was
|
|
26
|
+
* revoked when the key is still live everywhere else would be the most
|
|
27
|
+
* damaging kind of wrong: they would stop looking for the exposure.
|
|
28
|
+
*
|
|
29
|
+
* Whether a failed revocation should keep or delete the file depends on
|
|
30
|
+
* whether the failure is retriable: `OctenNetworkError` is a transport
|
|
31
|
+
* fault, and a transport fault must never be read as "the credential is
|
|
32
|
+
* invalid" — deleting a working credential because the network was down
|
|
33
|
+
* would leave the user with nothing and no way back without re-consenting.
|
|
34
|
+
* So the file is kept and `--local` is suggested. Every
|
|
35
|
+
* other failure `revokeCliGrant` can throw is `OctenAuthError` from one of
|
|
36
|
+
* three deterministic causes (401/403/400 in revoke.ts) — the stored
|
|
37
|
+
* key is no longer valid, the grant isn't bound to it, or the grant id
|
|
38
|
+
* isn't recognized. All three fail identically on every retry of plain
|
|
39
|
+
* `octen logout`, so keeping the file there would strand the user with
|
|
40
|
+
* `--local` as the only escape hatch (and a lie for the 400 case, where the
|
|
41
|
+
* authorization was already gone). Those branches delete the file and say
|
|
42
|
+
* precisely why revocation didn't happen, printing the `grantId` so the
|
|
43
|
+
* user can still find and clean up the authorization in the dashboard if
|
|
44
|
+
* it's still listed as active there.
|
|
45
|
+
*/
|
|
46
|
+
export declare function registerLogout(program: Command, internal?: LogoutInternalOpts): void;
|
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
import os from "node:os";
|
|
2
|
+
import { readCredentials, deleteCredentials } from "../auth/store.js";
|
|
3
|
+
// The 400 case ("the grant is already gone server-side", so logout's goal
|
|
4
|
+
// is already met) is identified by importing revoke.ts's own constant rather
|
|
5
|
+
// than re-typing its sentence: editing that copy now breaks the build here
|
|
6
|
+
// instead of silently downgrading this branch to the generic 401/403 message
|
|
7
|
+
// with no test failure.
|
|
8
|
+
import { revokeCliGrant, GRANT_NOT_RECOGNIZED_MESSAGE } from "../auth/revoke.js";
|
|
9
|
+
import { OctenNetworkError } from "../api/errors.js";
|
|
10
|
+
/**
|
|
11
|
+
* `octen logout` — revoke this device's authorization, then remove the
|
|
12
|
+
* local credential.
|
|
13
|
+
*
|
|
14
|
+
* The copy here is a hard requirement, not polish: this command clears a
|
|
15
|
+
* local file and revokes a *grant* (which only blocks the CLI from silently
|
|
16
|
+
* minting a new credential without a fresh consent screen). It never
|
|
17
|
+
* deactivates the underlying API key — that key is the user's own
|
|
18
|
+
* account-wide, long-lived key, and is very likely also sitting in other
|
|
19
|
+
* machines, production code, and the AI-client configs `octen
|
|
20
|
+
* configure-mcp` wrote. So the output must never claim to have revoked
|
|
21
|
+
* *access*, only "this authorization". Telling a user their access was
|
|
22
|
+
* revoked when the key is still live everywhere else would be the most
|
|
23
|
+
* damaging kind of wrong: they would stop looking for the exposure.
|
|
24
|
+
*
|
|
25
|
+
* Whether a failed revocation should keep or delete the file depends on
|
|
26
|
+
* whether the failure is retriable: `OctenNetworkError` is a transport
|
|
27
|
+
* fault, and a transport fault must never be read as "the credential is
|
|
28
|
+
* invalid" — deleting a working credential because the network was down
|
|
29
|
+
* would leave the user with nothing and no way back without re-consenting.
|
|
30
|
+
* So the file is kept and `--local` is suggested. Every
|
|
31
|
+
* other failure `revokeCliGrant` can throw is `OctenAuthError` from one of
|
|
32
|
+
* three deterministic causes (401/403/400 in revoke.ts) — the stored
|
|
33
|
+
* key is no longer valid, the grant isn't bound to it, or the grant id
|
|
34
|
+
* isn't recognized. All three fail identically on every retry of plain
|
|
35
|
+
* `octen logout`, so keeping the file there would strand the user with
|
|
36
|
+
* `--local` as the only escape hatch (and a lie for the 400 case, where the
|
|
37
|
+
* authorization was already gone). Those branches delete the file and say
|
|
38
|
+
* precisely why revocation didn't happen, printing the `grantId` so the
|
|
39
|
+
* user can still find and clean up the authorization in the dashboard if
|
|
40
|
+
* it's still listed as active there.
|
|
41
|
+
*/
|
|
42
|
+
export function registerLogout(program, internal = {}) {
|
|
43
|
+
program
|
|
44
|
+
.command("logout")
|
|
45
|
+
.description("Revoke this device's authorization and remove the locally stored credential")
|
|
46
|
+
.option("--local", "remove only the local credential file; skip revoking the authorization")
|
|
47
|
+
.action(async (opts) => {
|
|
48
|
+
const home = internal.home ?? os.homedir();
|
|
49
|
+
let creds;
|
|
50
|
+
try {
|
|
51
|
+
creds = readCredentials(home);
|
|
52
|
+
}
|
|
53
|
+
catch (err) {
|
|
54
|
+
// Corrupt JSON or an unrecognized CREDENTIALS_VERSION: logout's job
|
|
55
|
+
// is to remove the file, not diagnose it — symmetric with
|
|
56
|
+
// src/auth/login.ts's tolerance of the same failure. There is no
|
|
57
|
+
// apiKey/grantId to extract from an unreadable file, so no
|
|
58
|
+
// revocation is attempted (or even possible) either way, regardless
|
|
59
|
+
// of --local.
|
|
60
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
61
|
+
process.stderr.write(`warning: ignoring an unreadable credentials file (removing it): ${msg}\n`);
|
|
62
|
+
deleteCredentials(home);
|
|
63
|
+
process.stdout.write("Cleared local credentials.\n");
|
|
64
|
+
return;
|
|
65
|
+
}
|
|
66
|
+
if (!creds) {
|
|
67
|
+
process.stdout.write("Not logged in; nothing to do.\n");
|
|
68
|
+
return;
|
|
69
|
+
}
|
|
70
|
+
if (creds.source === "api-key") {
|
|
71
|
+
// A pasted key has no grant behind it — nothing to revoke, and the
|
|
72
|
+
// copy must never claim otherwise, or the user is told an
|
|
73
|
+
// authorization was closed that never existed. Zero network requests
|
|
74
|
+
// on this branch.
|
|
75
|
+
deleteCredentials(home);
|
|
76
|
+
process.stdout.write("Cleared local credentials.\n");
|
|
77
|
+
return;
|
|
78
|
+
}
|
|
79
|
+
// source === "login"
|
|
80
|
+
if (opts.local) {
|
|
81
|
+
const grantId = creds.grantId;
|
|
82
|
+
deleteCredentials(home);
|
|
83
|
+
process.stdout.write(`Cleared local credentials (--local: the authorization was not revoked). ` +
|
|
84
|
+
`Grant ${grantId} can still mint a new credential without a fresh consent screen — ` +
|
|
85
|
+
`revoke it from the dashboard if you want to close it out.\n`);
|
|
86
|
+
return;
|
|
87
|
+
}
|
|
88
|
+
try {
|
|
89
|
+
await revokeCliGrant({
|
|
90
|
+
issuer: creds.issuer,
|
|
91
|
+
apiKey: creds.apiKey,
|
|
92
|
+
grantId: creds.grantId,
|
|
93
|
+
fetchImpl: internal.fetchImpl,
|
|
94
|
+
});
|
|
95
|
+
}
|
|
96
|
+
catch (err) {
|
|
97
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
98
|
+
if (err instanceof OctenNetworkError) {
|
|
99
|
+
// A failed revocation does not mean the credential is invalid —
|
|
100
|
+
// deleting it here would strand the user with no working key and
|
|
101
|
+
// no way to get a new one without re-consenting. Keep the file.
|
|
102
|
+
process.stderr.write(`Could not revoke this authorization: ${msg}\n` +
|
|
103
|
+
"Local credentials were kept. Retry, or run `octen logout --local` to remove them without revoking.\n");
|
|
104
|
+
process.exitCode = 1;
|
|
105
|
+
return;
|
|
106
|
+
}
|
|
107
|
+
// Every other failure is deterministic (OctenAuthError from
|
|
108
|
+
// revoke.ts: 401/403/400) — retrying plain `octen logout` fails
|
|
109
|
+
// identically every time, so keeping the file only strands the
|
|
110
|
+
// user. Delete it, and say exactly why revocation didn't happen.
|
|
111
|
+
deleteCredentials(home);
|
|
112
|
+
if (msg === GRANT_NOT_RECOGNIZED_MESSAGE) {
|
|
113
|
+
// Do NOT say "already gone". The server's 400 is ambiguous by
|
|
114
|
+
// construction (see GRANT_NOT_RECOGNIZED_MESSAGE in auth/revoke.ts):
|
|
115
|
+
// it covers both "that id is unknown" and "the id is real and still
|
|
116
|
+
// active, but this key may no longer act on it" — the latter happens
|
|
117
|
+
// when the user has been removed from the organization that owns the
|
|
118
|
+
// key. Telling those users there is nothing left to revoke leaves a
|
|
119
|
+
// live grant behind that can still mint credentials, which is exactly
|
|
120
|
+
// what this command's doc comment above promises never to do.
|
|
121
|
+
process.stdout.write(`Cleared local credentials, but the server did not accept the revocation of ` +
|
|
122
|
+
`grant ${creds.grantId}.\n` +
|
|
123
|
+
` Most often the authorization no longer exists. It can also mean the ` +
|
|
124
|
+
`authorization is still active\n while this key may no longer act on it — for ` +
|
|
125
|
+
`example after you were removed from the\n organization that owns it. ` +
|
|
126
|
+
`Check that grant id in the dashboard if you need to be sure.\n`);
|
|
127
|
+
}
|
|
128
|
+
else {
|
|
129
|
+
process.stdout.write(`Cleared local credentials. This credential could not revoke its authorization ` +
|
|
130
|
+
`(${msg}) — if grant ${creds.grantId} still shows as active in the dashboard, ` +
|
|
131
|
+
`revoke it there.\n`);
|
|
132
|
+
}
|
|
133
|
+
return;
|
|
134
|
+
}
|
|
135
|
+
deleteCredentials(home);
|
|
136
|
+
process.stdout.write("Cleared local credentials and revoked this authorization. " +
|
|
137
|
+
"This does not deactivate the API key itself: the same key still works on " +
|
|
138
|
+
"other machines, in production code, and in AI-client configs written by " +
|
|
139
|
+
"`octen configure-mcp`. If you suspect it was exposed, deactivate or rotate the " +
|
|
140
|
+
"key from the dashboard.\n");
|
|
141
|
+
});
|
|
142
|
+
}
|