@octen.ai/cli 0.8.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 +250 -4
- package/dist/api/errors.d.ts +15 -0
- package/dist/api/errors.js +15 -0
- 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/configureMcp.js +34 -18
- package/dist/commands/configureSkills.js +18 -4
- 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 +39 -3
- 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/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
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
import { OctenAuthError, OctenNetworkError } from "../api/errors.js";
|
|
2
|
+
import { REQUEST_TIMEOUT_MS } from "./constants.js";
|
|
3
|
+
/**
|
|
4
|
+
* The 400 response's message.
|
|
5
|
+
*
|
|
6
|
+
* This deliberately does NOT say "already gone". The server returns 400 from
|
|
7
|
+
* three places and the response carries no body to tell them apart:
|
|
8
|
+
*
|
|
9
|
+
* 1. the grant id is unknown → it really is gone
|
|
10
|
+
* 2. the body/grant_id was unparseable → unreachable from this client
|
|
11
|
+
* 3. the revoke was refused after the row was found — e.g. the subject is no
|
|
12
|
+
* longer a joined member of the organization that owns the key, or that
|
|
13
|
+
* organization is deactivated. **The grant is still `active` in this case.**
|
|
14
|
+
*
|
|
15
|
+
* An earlier version asserted case 1 for all three, so a user who had been
|
|
16
|
+
* removed from an organization was told "nothing left to revoke" while a live
|
|
17
|
+
* grant kept its ability to mint credentials — the exact outcome this command's
|
|
18
|
+
* own doc comment says must never happen.
|
|
19
|
+
*
|
|
20
|
+
* Exported because `octen logout` branches on this case for wording. That
|
|
21
|
+
* branch used to match the literal string, so editing this sentence would have
|
|
22
|
+
* silently changed behaviour with no test failure anywhere; importing the
|
|
23
|
+
* constant makes the coupling break at compile time instead.
|
|
24
|
+
*/
|
|
25
|
+
export const GRANT_NOT_RECOGNIZED_MESSAGE = "The server did not accept that grant id.";
|
|
26
|
+
/**
|
|
27
|
+
* Revoke a CLI OAuth grant at `POST {issuer}/api/oauth/cli/revoke`.
|
|
28
|
+
*
|
|
29
|
+
* Deliberately not RFC 7009 token revocation. RFC 7009 wants a token to
|
|
30
|
+
* revoke, and by this point `octen logout` has none: the access token was
|
|
31
|
+
* used once at login and discarded, and no refresh token is ever stored — an
|
|
32
|
+
* ostensible refresh token would expire after 30 days anyway, so keeping one
|
|
33
|
+
* for logout would give a revocation path that looks available and silently
|
|
34
|
+
* stops working on idle machines, which are exactly the ones a user logs out
|
|
35
|
+
* from. So this authenticates with the long-lived `apiKey`
|
|
36
|
+
* (header `x-api-key`) and self-certifies via `{ grant_id }` in the body —
|
|
37
|
+
* the server checks that the grant's `api_key_id` matches the key's own id.
|
|
38
|
+
*
|
|
39
|
+
* 200 with `{}` means success, and it is idempotent: revoking an
|
|
40
|
+
* already-revoked grant is also 200.
|
|
41
|
+
*
|
|
42
|
+
* Error classification (mirrors `exchangeForApiKey` in ./exchange.ts):
|
|
43
|
+
* - a fetch-level failure, a redirect, or 408/429/5xx is always
|
|
44
|
+
* `OctenNetworkError` — a transport/infrastructure fault.
|
|
45
|
+
* - 401 (key missing/unknown/inactive), 403 (grant not bound to that key,
|
|
46
|
+
* or not a CLI grant), and 400 (unknown/malformed grant_id) are all
|
|
47
|
+
* `OctenAuthError`.
|
|
48
|
+
*
|
|
49
|
+
* Callers that use this for a best-effort revoke (`octen login`'s step 1)
|
|
50
|
+
* must catch every rejection themselves — nothing here is ever meant to
|
|
51
|
+
* block a caller that only wants "try, and don't wait".
|
|
52
|
+
*
|
|
53
|
+
* No error message here ever includes `a.apiKey` or `a.grantId`.
|
|
54
|
+
*/
|
|
55
|
+
export async function revokeCliGrant(a) {
|
|
56
|
+
const f = a.fetchImpl ?? fetch;
|
|
57
|
+
let res;
|
|
58
|
+
try {
|
|
59
|
+
res = await f(`${a.issuer}/api/oauth/cli/revoke`, {
|
|
60
|
+
method: "POST",
|
|
61
|
+
headers: { "x-api-key": a.apiKey, "content-type": "application/json" },
|
|
62
|
+
body: JSON.stringify({ grant_id: a.grantId }),
|
|
63
|
+
// This request carries a long-lived API key — never let a redirect
|
|
64
|
+
// silently forward it to a different host.
|
|
65
|
+
redirect: "manual",
|
|
66
|
+
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
|
|
67
|
+
});
|
|
68
|
+
}
|
|
69
|
+
catch {
|
|
70
|
+
throw new OctenNetworkError("Could not reach the authorization server; please try again.");
|
|
71
|
+
}
|
|
72
|
+
if (res.type === "opaqueredirect" || (res.status >= 300 && res.status < 400)) {
|
|
73
|
+
throw new OctenNetworkError("The authorization server returned an unexpected redirect; please try again.");
|
|
74
|
+
}
|
|
75
|
+
if (res.status === 408 || res.status === 429 || res.status >= 500) {
|
|
76
|
+
throw new OctenNetworkError("The authorization server is unavailable; please retry later.");
|
|
77
|
+
}
|
|
78
|
+
if (res.status === 401) {
|
|
79
|
+
throw new OctenAuthError("The stored API key is no longer valid.");
|
|
80
|
+
}
|
|
81
|
+
if (res.status === 403) {
|
|
82
|
+
throw new OctenAuthError("That grant is not bound to the stored API key.");
|
|
83
|
+
}
|
|
84
|
+
if (res.status === 400) {
|
|
85
|
+
throw new OctenAuthError(GRANT_NOT_RECOGNIZED_MESSAGE);
|
|
86
|
+
}
|
|
87
|
+
if (!res.ok) {
|
|
88
|
+
throw new OctenAuthError(`Revoke failed (HTTP ${res.status}).`);
|
|
89
|
+
}
|
|
90
|
+
// 200: success, idempotent. Body is `{}` and carries nothing to read.
|
|
91
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
export declare const CREDENTIALS_VERSION = 1;
|
|
2
|
+
export type Credentials = {
|
|
3
|
+
version: 1;
|
|
4
|
+
source: "api-key";
|
|
5
|
+
apiKey: string;
|
|
6
|
+
} | {
|
|
7
|
+
version: 1;
|
|
8
|
+
source: "login";
|
|
9
|
+
issuer: string;
|
|
10
|
+
resource: string;
|
|
11
|
+
apiKey: string;
|
|
12
|
+
/**
|
|
13
|
+
* Epoch seconds, or `null` for "does not expire" — which is what the
|
|
14
|
+
* server sends for every credential today. Kept as a real field so
|
|
15
|
+
* that if short-lived keys ever ship, the stored format already
|
|
16
|
+
* carries the deadline and no migration is needed.
|
|
17
|
+
*/
|
|
18
|
+
apiKeyExpiresAt: number | null;
|
|
19
|
+
/**
|
|
20
|
+
* The OAuth grant behind this credential. This is the only record on
|
|
21
|
+
* the machine of which dashboard authorization corresponds to this
|
|
22
|
+
* install, so `octen whoami` prints it and `octen logout` revokes by
|
|
23
|
+
* it. Any command that destroys this file must print it first:
|
|
24
|
+
* afterwards the grant is still listed server-side with nothing local
|
|
25
|
+
* able to name it.
|
|
26
|
+
*/
|
|
27
|
+
grantId: string;
|
|
28
|
+
accountId?: string;
|
|
29
|
+
accountType?: string;
|
|
30
|
+
};
|
|
31
|
+
export declare function credentialsPath(home: string): string;
|
|
32
|
+
export declare function readCredentials(home: string): Credentials | undefined;
|
|
33
|
+
export declare function writeCredentials(home: string, c: Credentials): void;
|
|
34
|
+
export declare function deleteCredentials(home: string): boolean;
|
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
import { mkdirSync, writeFileSync, renameSync, readFileSync, existsSync, unlinkSync } from "node:fs";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import { randomBytes } from "node:crypto";
|
|
4
|
+
import { OctenValidationError } from "../api/errors.js";
|
|
5
|
+
import { assertSecureOrigin } from "./constants.js";
|
|
6
|
+
export const CREDENTIALS_VERSION = 1;
|
|
7
|
+
/** The way out of any corrupt/unreadable/unknown-version credentials file. */
|
|
8
|
+
const RECOVERY_HINT = "delete ~/.octen/credentials.json and run `octen login` again.";
|
|
9
|
+
export function credentialsPath(home) {
|
|
10
|
+
return join(home, ".octen", "credentials.json");
|
|
11
|
+
}
|
|
12
|
+
function fail(reason) {
|
|
13
|
+
// Never echo file contents here — only a fixed, generic reason plus the recovery hint.
|
|
14
|
+
throw new OctenValidationError(`Invalid credentials file (${reason}); ${RECOVERY_HINT}`);
|
|
15
|
+
}
|
|
16
|
+
function isNonEmptyString(value) {
|
|
17
|
+
return typeof value === "string" && value.length > 0;
|
|
18
|
+
}
|
|
19
|
+
function isOptionalString(value) {
|
|
20
|
+
return value === undefined || typeof value === "string";
|
|
21
|
+
}
|
|
22
|
+
function isValidExpiry(value) {
|
|
23
|
+
return value === null || (typeof value === "number" && Number.isFinite(value) && Number.isInteger(value) && value > 0);
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Validate a parsed credentials object field by field, per `source`. Never
|
|
27
|
+
* half-reads: a file missing a required field throws rather than producing an
|
|
28
|
+
* object with `undefined` in later branches.
|
|
29
|
+
*/
|
|
30
|
+
function validate(obj) {
|
|
31
|
+
if (obj === null || typeof obj !== "object")
|
|
32
|
+
fail("not an object");
|
|
33
|
+
const rec = obj;
|
|
34
|
+
if (rec.version !== CREDENTIALS_VERSION)
|
|
35
|
+
fail("unknown version");
|
|
36
|
+
if (rec.source === "api-key") {
|
|
37
|
+
if (!isNonEmptyString(rec.apiKey))
|
|
38
|
+
fail("missing apiKey");
|
|
39
|
+
return { version: 1, source: "api-key", apiKey: rec.apiKey };
|
|
40
|
+
}
|
|
41
|
+
if (rec.source === "login") {
|
|
42
|
+
if (!isNonEmptyString(rec.issuer))
|
|
43
|
+
fail("missing issuer");
|
|
44
|
+
// The stored issuer is not inert data: `login`'s step-1 cleanup and
|
|
45
|
+
// `logout` both POST this credential's API key to it. So it gets exactly
|
|
46
|
+
// the same https-or-loopback rule as OCTEN_AUTH_ISSUER — a file naming a
|
|
47
|
+
// plaintext host would otherwise be a standing instruction to mail an
|
|
48
|
+
// account-wide key there in the clear.
|
|
49
|
+
try {
|
|
50
|
+
assertSecureOrigin("credentials.issuer", rec.issuer);
|
|
51
|
+
}
|
|
52
|
+
catch {
|
|
53
|
+
fail("insecure issuer");
|
|
54
|
+
}
|
|
55
|
+
if (!isNonEmptyString(rec.resource))
|
|
56
|
+
fail("missing resource");
|
|
57
|
+
if (!isNonEmptyString(rec.apiKey))
|
|
58
|
+
fail("missing apiKey");
|
|
59
|
+
if (!isValidExpiry(rec.apiKeyExpiresAt))
|
|
60
|
+
fail("invalid apiKeyExpiresAt");
|
|
61
|
+
if (!isNonEmptyString(rec.grantId))
|
|
62
|
+
fail("missing grantId");
|
|
63
|
+
if (!isOptionalString(rec.accountId))
|
|
64
|
+
fail("invalid accountId");
|
|
65
|
+
if (!isOptionalString(rec.accountType))
|
|
66
|
+
fail("invalid accountType");
|
|
67
|
+
const creds = {
|
|
68
|
+
version: 1,
|
|
69
|
+
source: "login",
|
|
70
|
+
issuer: rec.issuer,
|
|
71
|
+
resource: rec.resource,
|
|
72
|
+
apiKey: rec.apiKey,
|
|
73
|
+
apiKeyExpiresAt: rec.apiKeyExpiresAt,
|
|
74
|
+
grantId: rec.grantId,
|
|
75
|
+
};
|
|
76
|
+
if (rec.accountId !== undefined)
|
|
77
|
+
creds.accountId = rec.accountId;
|
|
78
|
+
if (rec.accountType !== undefined)
|
|
79
|
+
creds.accountType = rec.accountType;
|
|
80
|
+
return creds;
|
|
81
|
+
}
|
|
82
|
+
fail("unknown source");
|
|
83
|
+
}
|
|
84
|
+
/**
|
|
85
|
+
* Whitelist exactly the fields that belong to each source, so an accidental
|
|
86
|
+
* extra property on the passed-in object (e.g. a smuggled `refreshToken`)
|
|
87
|
+
* never reaches disk. The one that matters is a refresh token: this design
|
|
88
|
+
* never stores one, and an accidental property on a passed-in object must
|
|
89
|
+
* not be able to quietly introduce a second long-lived secret into the
|
|
90
|
+
* credentials file.
|
|
91
|
+
*/
|
|
92
|
+
function serialize(c) {
|
|
93
|
+
const obj = c.source === "api-key"
|
|
94
|
+
? { version: c.version, source: c.source, apiKey: c.apiKey }
|
|
95
|
+
: {
|
|
96
|
+
version: c.version,
|
|
97
|
+
source: c.source,
|
|
98
|
+
issuer: c.issuer,
|
|
99
|
+
resource: c.resource,
|
|
100
|
+
apiKey: c.apiKey,
|
|
101
|
+
apiKeyExpiresAt: c.apiKeyExpiresAt,
|
|
102
|
+
grantId: c.grantId,
|
|
103
|
+
...(c.accountId !== undefined ? { accountId: c.accountId } : {}),
|
|
104
|
+
...(c.accountType !== undefined ? { accountType: c.accountType } : {}),
|
|
105
|
+
};
|
|
106
|
+
return JSON.stringify(obj, null, 2);
|
|
107
|
+
}
|
|
108
|
+
export function readCredentials(home) {
|
|
109
|
+
const path = credentialsPath(home);
|
|
110
|
+
if (!existsSync(path))
|
|
111
|
+
return undefined;
|
|
112
|
+
const raw = readFileSync(path, "utf8");
|
|
113
|
+
let parsed;
|
|
114
|
+
try {
|
|
115
|
+
parsed = JSON.parse(raw);
|
|
116
|
+
}
|
|
117
|
+
catch {
|
|
118
|
+
fail("corrupt JSON");
|
|
119
|
+
}
|
|
120
|
+
return validate(parsed);
|
|
121
|
+
}
|
|
122
|
+
export function writeCredentials(home, c) {
|
|
123
|
+
const dir = join(home, ".octen");
|
|
124
|
+
mkdirSync(dir, { recursive: true });
|
|
125
|
+
const path = credentialsPath(home);
|
|
126
|
+
const tmp = join(dir, `.credentials.json.tmp-${process.pid}-${randomBytes(6).toString("hex")}`);
|
|
127
|
+
const json = serialize(c);
|
|
128
|
+
try {
|
|
129
|
+
writeFileSync(tmp, json, { mode: 0o600 });
|
|
130
|
+
renameSync(tmp, path);
|
|
131
|
+
}
|
|
132
|
+
catch (err) {
|
|
133
|
+
try {
|
|
134
|
+
if (existsSync(tmp))
|
|
135
|
+
unlinkSync(tmp);
|
|
136
|
+
}
|
|
137
|
+
catch {
|
|
138
|
+
// best-effort cleanup only
|
|
139
|
+
}
|
|
140
|
+
throw err;
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
export function deleteCredentials(home) {
|
|
144
|
+
const path = credentialsPath(home);
|
|
145
|
+
if (!existsSync(path))
|
|
146
|
+
return false;
|
|
147
|
+
unlinkSync(path);
|
|
148
|
+
return true;
|
|
149
|
+
}
|
package/dist/cli.js
CHANGED
|
@@ -16,6 +16,9 @@ import { registerVideoSearch } from "./commands/videoSearch.js";
|
|
|
16
16
|
import { registerConfigureMcp } from "./commands/configureMcp.js";
|
|
17
17
|
import { registerConfigureSkills } from "./commands/configureSkills.js";
|
|
18
18
|
import { registerReset } from "./commands/reset.js";
|
|
19
|
+
import { registerLogin } from "./commands/login.js";
|
|
20
|
+
import { registerLogout } from "./commands/logout.js";
|
|
21
|
+
import { registerWhoami } from "./commands/whoami.js";
|
|
19
22
|
import { registerCompletion } from "./commands/completion.js";
|
|
20
23
|
function resolveVersion() {
|
|
21
24
|
if (typeof __OCTEN_VERSION__ !== "undefined")
|
|
@@ -45,6 +48,9 @@ registerEmbed(program);
|
|
|
45
48
|
registerVlEmbed(program);
|
|
46
49
|
registerImageSearch(program);
|
|
47
50
|
registerVideoSearch(program);
|
|
51
|
+
registerLogin(program);
|
|
52
|
+
registerLogout(program);
|
|
53
|
+
registerWhoami(program);
|
|
48
54
|
// Register LAST so introspection sees every command and its flags.
|
|
49
55
|
registerCompletion(program);
|
|
50
56
|
program.parseAsync().catch((err) => {
|
|
@@ -4,6 +4,7 @@ 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";
|
|
8
9
|
import { parseScopeOpt } from "./utils.js";
|
|
9
10
|
import { quotePath } from "../util/quotePath.js";
|
|
@@ -28,23 +29,10 @@ export function registerConfigureMcp(program, internal = {}) {
|
|
|
28
29
|
// Parsed and validated by parseScopeOpt at option-parse time.
|
|
29
30
|
const scope = opts.scope;
|
|
30
31
|
const pin = opts.pin;
|
|
31
|
-
//
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
key = resolveApiKey(g.apiKey, process.env);
|
|
36
|
-
}
|
|
37
|
-
catch {
|
|
38
|
-
key = "${OCTEN_API_KEY}";
|
|
39
|
-
keyMissing = true;
|
|
40
|
-
}
|
|
41
|
-
// Build the MCP server entry
|
|
42
|
-
const entry = {
|
|
43
|
-
command: "npx",
|
|
44
|
-
args: ["-y", pin ? `octen-mcp@${pin}` : "octen-mcp"],
|
|
45
|
-
env: { OCTEN_API_KEY: key },
|
|
46
|
-
};
|
|
47
|
-
// 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.
|
|
48
36
|
const home = internal.home ?? os.homedir();
|
|
49
37
|
const cwd = internal.cwd ?? process.cwd();
|
|
50
38
|
const isInstalled = internal.isInstalled ?? ((id) => isClientInstalled(id, { home }));
|
|
@@ -73,7 +61,35 @@ export function registerConfigureMcp(program, internal = {}) {
|
|
|
73
61
|
}
|
|
74
62
|
return;
|
|
75
63
|
}
|
|
76
|
-
// 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.
|
|
77
93
|
let selected;
|
|
78
94
|
if (opts.all) {
|
|
79
95
|
// Start from the full registry, then filter to installed ones.
|
|
@@ -6,7 +6,8 @@ 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";
|
|
12
13
|
import { parseCsvOpt, parseScopeOpt } from "./utils.js";
|
|
@@ -152,9 +153,22 @@ export function registerConfigureSkills(program, internal = {}) {
|
|
|
152
153
|
}
|
|
153
154
|
if (opts.setKey) {
|
|
154
155
|
const g = command.optsWithGlobals();
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
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`");
|
|
158
172
|
}
|
|
159
173
|
for (const client of selected) {
|
|
160
174
|
const result = setClientEnvKey(client.id, key, scope, home, cwd);
|
|
@@ -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;
|