@octen.ai/cli 0.8.0 → 0.10.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.
Files changed (63) hide show
  1. package/README.md +272 -6
  2. package/dist/api/constants.d.ts +6 -0
  3. package/dist/api/constants.js +3 -0
  4. package/dist/api/errors.d.ts +15 -0
  5. package/dist/api/errors.js +15 -0
  6. package/dist/api/extract.d.ts +57 -0
  7. package/dist/api/extract.js +36 -1
  8. package/dist/auth/constants.d.ts +47 -0
  9. package/dist/auth/constants.js +89 -0
  10. package/dist/auth/exchange.d.ts +74 -0
  11. package/dist/auth/exchange.js +124 -0
  12. package/dist/auth/login.d.ts +64 -0
  13. package/dist/auth/login.js +163 -0
  14. package/dist/auth/loopback.d.ts +32 -0
  15. package/dist/auth/loopback.js +95 -0
  16. package/dist/auth/oauthClient.d.ts +70 -0
  17. package/dist/auth/oauthClient.js +136 -0
  18. package/dist/auth/pkce.d.ts +6 -0
  19. package/dist/auth/pkce.js +13 -0
  20. package/dist/auth/revoke.d.ts +58 -0
  21. package/dist/auth/revoke.js +91 -0
  22. package/dist/auth/store.d.ts +34 -0
  23. package/dist/auth/store.js +149 -0
  24. package/dist/cli.js +6 -0
  25. package/dist/commands/configureMcp.js +34 -18
  26. package/dist/commands/configureSkills.js +18 -4
  27. package/dist/commands/extract.js +9 -5
  28. package/dist/commands/login.d.ts +49 -0
  29. package/dist/commands/login.js +161 -0
  30. package/dist/commands/logout.d.ts +46 -0
  31. package/dist/commands/logout.js +142 -0
  32. package/dist/commands/reset.js +39 -3
  33. package/dist/commands/utils.d.ts +9 -0
  34. package/dist/commands/utils.js +16 -0
  35. package/dist/commands/whoami.d.ts +27 -0
  36. package/dist/commands/whoami.js +109 -0
  37. package/dist/config/resolve.d.ts +44 -1
  38. package/dist/config/resolve.js +80 -5
  39. package/dist/mcp/install.js +15 -2
  40. package/dist/mcp/write.js +24 -3
  41. package/dist/output/pretty/extract.d.ts +5 -1
  42. package/dist/output/pretty/extract.js +64 -4
  43. package/dist/output/pretty/whoami.d.ts +59 -0
  44. package/dist/output/pretty/whoami.js +103 -0
  45. package/dist/skills/setkey.js +5 -4
  46. package/dist/util/secretFile.d.ts +24 -0
  47. package/dist/util/secretFile.js +35 -0
  48. package/package.json +1 -1
  49. package/skills/manifest.json +5 -1
  50. package/skills/octen-design/SKILL.md +32 -9
  51. package/skills/octen-design/agents/openai.yaml +4 -0
  52. package/skills/octen-design/scripts/search.py +326 -71
  53. package/skills/octen-design/scripts/tests/test_search.py +449 -0
  54. package/skills/octen-extract/SKILL.md +178 -0
  55. package/skills/octen-extract/agents/openai.yaml +4 -0
  56. package/skills/octen-image-search/SKILL.md +125 -0
  57. package/skills/octen-image-search/agents/openai.yaml +4 -0
  58. package/skills/octen-search/SKILL.md +82 -3
  59. package/skills/octen-search/agents/openai.yaml +4 -0
  60. package/skills/octen-video-search/SKILL.md +108 -0
  61. package/skills/octen-video-search/agents/openai.yaml +4 -0
  62. package/skills/octen-web-search/SKILL.md +113 -0
  63. package/skills/octen-web-search/agents/openai.yaml +4 -0
@@ -0,0 +1,70 @@
1
+ /**
2
+ * The result of a code->token exchange. Deliberately just the access token,
3
+ * which is used once (to exchange for the account's API key) and then
4
+ * discarded.
5
+ *
6
+ * There is no refresh token here, and no field to put one in, because there
7
+ * is nothing for a refresh to accomplish: the credential this flow ultimately
8
+ * stores is the user's own long-lived API key, which does not expire. Keeping
9
+ * a refresh token would add a second secret to protect, on disk, whose only
10
+ * use would be to re-mint something that never needs re-minting — and which
11
+ * would itself expire after 30 days, leaving behind a credential that looks
12
+ * usable and silently is not.
13
+ */
14
+ export interface TokenSet {
15
+ accessToken: string;
16
+ }
17
+ /**
18
+ * Build the `GET {issuer}/oauth/authorize` URL for the loopback flow.
19
+ *
20
+ * `client_id` is fixed to `CLI_CLIENT_ID` and is deliberately NOT a
21
+ * parameter: this CLI is a single pre-registered public client whose row is
22
+ * seeded server-side, and there is no dynamic client registration anywhere in
23
+ * this flow. Making it a parameter would imply a per-install client identity
24
+ * that does not exist. Every other value here is genuinely per-flow.
25
+ */
26
+ export declare function authorizeUrl(a: {
27
+ issuer: string;
28
+ redirectUri: string;
29
+ challenge: string;
30
+ state: string;
31
+ resource: string;
32
+ scope: string;
33
+ }): string;
34
+ /**
35
+ * Exchange an authorization code for an access token at
36
+ * `POST {issuer}/api/oauth/token`.
37
+ *
38
+ * Error classification — by transport layer FIRST, then body. The ordering is
39
+ * the point: an `OctenAuthError` tells the caller "this credential is no good",
40
+ * which is grounds for deleting it, while an `OctenNetworkError` means "try
41
+ * again later". Letting a response body decide that would let a struggling
42
+ * server delete a perfectly valid credential.
43
+ *
44
+ * - a fetch-level failure (DNS, connection reset, our own timeout) is
45
+ * always `OctenNetworkError`.
46
+ * - any 3xx (or an opaque redirect from `redirect: "manual"`) is treated as
47
+ * a transport-layer fault, never followed: a POST carrying the code and
48
+ * the PKCE verifier must not be forwarded to an unintended host.
49
+ * - 408 / 429 / 5xx are always `OctenNetworkError`, EVEN IF the body claims
50
+ * `invalid_grant` — a server fault dressed up as `invalid_grant` must
51
+ * never trigger credential deletion downstream.
52
+ * - 403 is always `OctenAuthError` (audience/scope/client mismatch;
53
+ * retrying cannot help), independent of the body.
54
+ * - any other 4xx whose body's `error` is `invalid_grant` or
55
+ * `invalid_client` is `OctenAuthError`.
56
+ * - any other 4xx falls back to `OctenAuthError` too: it is not one of the
57
+ * retryable transport codes above, so per "classify by transport first"
58
+ * it can never land in the network bucket.
59
+ *
60
+ * No error message here ever includes `a.code`, `a.verifier`, or a returned
61
+ * access token.
62
+ */
63
+ export declare function exchangeCode(a: {
64
+ issuer: string;
65
+ redirectUri: string;
66
+ code: string;
67
+ verifier: string;
68
+ resource: string;
69
+ fetchImpl?: typeof fetch;
70
+ }): Promise<TokenSet>;
@@ -0,0 +1,136 @@
1
+ import { OctenAuthError, OctenNetworkError } from "../api/errors.js";
2
+ import { CLI_CLIENT_ID, REQUEST_TIMEOUT_MS } from "./constants.js";
3
+ /**
4
+ * Build the `GET {issuer}/oauth/authorize` URL for the loopback flow.
5
+ *
6
+ * `client_id` is fixed to `CLI_CLIENT_ID` and is deliberately NOT a
7
+ * parameter: this CLI is a single pre-registered public client whose row is
8
+ * seeded server-side, and there is no dynamic client registration anywhere in
9
+ * this flow. Making it a parameter would imply a per-install client identity
10
+ * that does not exist. Every other value here is genuinely per-flow.
11
+ */
12
+ export function authorizeUrl(a) {
13
+ const u = new URL(`${a.issuer}/oauth/authorize`);
14
+ u.searchParams.set("client_id", CLI_CLIENT_ID);
15
+ u.searchParams.set("response_type", "code");
16
+ u.searchParams.set("redirect_uri", a.redirectUri);
17
+ u.searchParams.set("code_challenge", a.challenge);
18
+ u.searchParams.set("code_challenge_method", "S256");
19
+ u.searchParams.set("state", a.state);
20
+ u.searchParams.set("resource", a.resource);
21
+ u.searchParams.set("scope", a.scope);
22
+ return u.toString();
23
+ }
24
+ /**
25
+ * Read an OAuth `error` code out of a token-endpoint error body, if present.
26
+ * Never throws — an unparseable or unexpected shape just yields `undefined`.
27
+ */
28
+ function oauthErrorCode(payload) {
29
+ if (payload === null || typeof payload !== "object")
30
+ return undefined;
31
+ const value = payload.error;
32
+ return typeof value === "string" ? value : undefined;
33
+ }
34
+ /**
35
+ * Exchange an authorization code for an access token at
36
+ * `POST {issuer}/api/oauth/token`.
37
+ *
38
+ * Error classification — by transport layer FIRST, then body. The ordering is
39
+ * the point: an `OctenAuthError` tells the caller "this credential is no good",
40
+ * which is grounds for deleting it, while an `OctenNetworkError` means "try
41
+ * again later". Letting a response body decide that would let a struggling
42
+ * server delete a perfectly valid credential.
43
+ *
44
+ * - a fetch-level failure (DNS, connection reset, our own timeout) is
45
+ * always `OctenNetworkError`.
46
+ * - any 3xx (or an opaque redirect from `redirect: "manual"`) is treated as
47
+ * a transport-layer fault, never followed: a POST carrying the code and
48
+ * the PKCE verifier must not be forwarded to an unintended host.
49
+ * - 408 / 429 / 5xx are always `OctenNetworkError`, EVEN IF the body claims
50
+ * `invalid_grant` — a server fault dressed up as `invalid_grant` must
51
+ * never trigger credential deletion downstream.
52
+ * - 403 is always `OctenAuthError` (audience/scope/client mismatch;
53
+ * retrying cannot help), independent of the body.
54
+ * - any other 4xx whose body's `error` is `invalid_grant` or
55
+ * `invalid_client` is `OctenAuthError`.
56
+ * - any other 4xx falls back to `OctenAuthError` too: it is not one of the
57
+ * retryable transport codes above, so per "classify by transport first"
58
+ * it can never land in the network bucket.
59
+ *
60
+ * No error message here ever includes `a.code`, `a.verifier`, or a returned
61
+ * access token.
62
+ */
63
+ export async function exchangeCode(a) {
64
+ const f = a.fetchImpl ?? fetch;
65
+ const body = new URLSearchParams({
66
+ grant_type: "authorization_code",
67
+ code: a.code,
68
+ redirect_uri: a.redirectUri,
69
+ client_id: CLI_CLIENT_ID,
70
+ code_verifier: a.verifier,
71
+ resource: a.resource,
72
+ });
73
+ let res;
74
+ try {
75
+ res = await f(`${a.issuer}/api/oauth/token`, {
76
+ method: "POST",
77
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
78
+ body: body.toString(),
79
+ // The body carries the code and verifier — never let a redirect
80
+ // silently forward them to a different host.
81
+ redirect: "manual",
82
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
83
+ });
84
+ }
85
+ catch {
86
+ throw new OctenNetworkError("Could not reach the authorization server; please try again.");
87
+ }
88
+ // redirect: "manual" surfaces a same-implementation 3xx as an
89
+ // "opaqueredirect" response (status 0, no body); a mocked/proxied fetch may
90
+ // instead hand back the raw 3xx directly. Treat either as an error.
91
+ if (res.type === "opaqueredirect" || (res.status >= 300 && res.status < 400)) {
92
+ throw new OctenNetworkError("The authorization server returned an unexpected redirect; please try again.");
93
+ }
94
+ if (res.ok) {
95
+ let payload;
96
+ try {
97
+ payload = await res.json();
98
+ }
99
+ catch {
100
+ throw new OctenNetworkError("The authorization server returned an invalid response; please try again.");
101
+ }
102
+ const accessToken = payload !== null && typeof payload === "object"
103
+ ? payload.access_token
104
+ : undefined;
105
+ if (typeof accessToken !== "string" || accessToken.length === 0) {
106
+ throw new OctenNetworkError("The authorization server did not return an access token; please try again.");
107
+ }
108
+ return { accessToken };
109
+ }
110
+ // Transport-layer classification wins over the body, even when the body
111
+ // claims invalid_grant. A 5xx (or 408/429) is a server or infrastructure
112
+ // fault: whatever its body says, the credential is not known to be bad, and
113
+ // classifying it as an auth failure here would propagate upward into
114
+ // deleting a credential that was fine all along.
115
+ if (res.status === 408 || res.status === 429 || res.status >= 500) {
116
+ throw new OctenNetworkError("The authorization server is unavailable; please try again later.");
117
+ }
118
+ if (res.status === 403) {
119
+ throw new OctenAuthError("Authorization was refused. Run `octen login` again.");
120
+ }
121
+ const rawText = await res.text().catch(() => "");
122
+ let payload;
123
+ try {
124
+ payload = rawText ? JSON.parse(rawText) : undefined;
125
+ }
126
+ catch {
127
+ payload = undefined;
128
+ }
129
+ const errorCode = oauthErrorCode(payload);
130
+ if (errorCode === "invalid_grant" || errorCode === "invalid_client") {
131
+ throw new OctenAuthError("The authorization code is no longer valid. Run `octen login` again.");
132
+ }
133
+ // Any remaining 4xx: not one of the recognized transport-retryable codes
134
+ // above, so it is never classified as a network error.
135
+ throw new OctenAuthError(`Token exchange failed (HTTP ${res.status}). Run \`octen login\` again.`);
136
+ }
@@ -0,0 +1,6 @@
1
+ /** RFC 7636 code_verifier: 32 random bytes, base64url-encoded (43 chars, >=43 required). */
2
+ export declare function createVerifier(): string;
3
+ /** RFC 7636 S256 code_challenge: base64url(SHA-256(verifier)). */
4
+ export declare function challengeFor(verifier: string): string;
5
+ /** 32 random bytes, base64url-encoded — the OAuth `state` parameter. */
6
+ export declare function createState(): string;
@@ -0,0 +1,13 @@
1
+ import { randomBytes, createHash } from "node:crypto";
2
+ /** RFC 7636 code_verifier: 32 random bytes, base64url-encoded (43 chars, >=43 required). */
3
+ export function createVerifier() {
4
+ return randomBytes(32).toString("base64url");
5
+ }
6
+ /** RFC 7636 S256 code_challenge: base64url(SHA-256(verifier)). */
7
+ export function challengeFor(verifier) {
8
+ return createHash("sha256").update(verifier).digest("base64url");
9
+ }
10
+ /** 32 random bytes, base64url-encoded — the OAuth `state` parameter. */
11
+ export function createState() {
12
+ return randomBytes(32).toString("base64url");
13
+ }
@@ -0,0 +1,58 @@
1
+ /**
2
+ * The 400 response's message.
3
+ *
4
+ * This deliberately does NOT say "already gone". The server returns 400 from
5
+ * three places and the response carries no body to tell them apart:
6
+ *
7
+ * 1. the grant id is unknown → it really is gone
8
+ * 2. the body/grant_id was unparseable → unreachable from this client
9
+ * 3. the revoke was refused after the row was found — e.g. the subject is no
10
+ * longer a joined member of the organization that owns the key, or that
11
+ * organization is deactivated. **The grant is still `active` in this case.**
12
+ *
13
+ * An earlier version asserted case 1 for all three, so a user who had been
14
+ * removed from an organization was told "nothing left to revoke" while a live
15
+ * grant kept its ability to mint credentials — the exact outcome this command's
16
+ * own doc comment says must never happen.
17
+ *
18
+ * Exported because `octen logout` branches on this case for wording. That
19
+ * branch used to match the literal string, so editing this sentence would have
20
+ * silently changed behaviour with no test failure anywhere; importing the
21
+ * constant makes the coupling break at compile time instead.
22
+ */
23
+ export declare const GRANT_NOT_RECOGNIZED_MESSAGE = "The server did not accept that grant id.";
24
+ /**
25
+ * Revoke a CLI OAuth grant at `POST {issuer}/api/oauth/cli/revoke`.
26
+ *
27
+ * Deliberately not RFC 7009 token revocation. RFC 7009 wants a token to
28
+ * revoke, and by this point `octen logout` has none: the access token was
29
+ * used once at login and discarded, and no refresh token is ever stored — an
30
+ * ostensible refresh token would expire after 30 days anyway, so keeping one
31
+ * for logout would give a revocation path that looks available and silently
32
+ * stops working on idle machines, which are exactly the ones a user logs out
33
+ * from. So this authenticates with the long-lived `apiKey`
34
+ * (header `x-api-key`) and self-certifies via `{ grant_id }` in the body —
35
+ * the server checks that the grant's `api_key_id` matches the key's own id.
36
+ *
37
+ * 200 with `{}` means success, and it is idempotent: revoking an
38
+ * already-revoked grant is also 200.
39
+ *
40
+ * Error classification (mirrors `exchangeForApiKey` in ./exchange.ts):
41
+ * - a fetch-level failure, a redirect, or 408/429/5xx is always
42
+ * `OctenNetworkError` — a transport/infrastructure fault.
43
+ * - 401 (key missing/unknown/inactive), 403 (grant not bound to that key,
44
+ * or not a CLI grant), and 400 (unknown/malformed grant_id) are all
45
+ * `OctenAuthError`.
46
+ *
47
+ * Callers that use this for a best-effort revoke (`octen login`'s step 1)
48
+ * must catch every rejection themselves — nothing here is ever meant to
49
+ * block a caller that only wants "try, and don't wait".
50
+ *
51
+ * No error message here ever includes `a.apiKey` or `a.grantId`.
52
+ */
53
+ export declare function revokeCliGrant(a: {
54
+ issuer: string;
55
+ apiKey: string;
56
+ grantId: string;
57
+ fetchImpl?: typeof fetch;
58
+ }): Promise<void>;
@@ -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
- // Resolve API key — tolerate missing
32
- let key;
33
- let keyMissing = false;
34
- try {
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 — determine which clients to act on, gated by detection.
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.