@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,89 @@
1
+ import { OctenValidationError } from "../api/errors.js";
2
+ /**
3
+ * The pre-registered public client id. This is not a value the CLI chooses:
4
+ * it must byte-match the client row seeded on the authorization server, and a
5
+ * mismatch fails at the authorize step with `invalid_client`, before the user
6
+ * ever sees a consent screen. There is no dynamic client registration, so
7
+ * nothing negotiates this at runtime — it is a cross-repository constant.
8
+ */
9
+ export const CLI_CLIENT_ID = "octen-cli";
10
+ export const CLI_SCOPE = "octen:api_key";
11
+ export const REQUEST_TIMEOUT_MS = 10_000;
12
+ export const LOOPBACK_TIMEOUT_MS = 5 * 60 * 1000;
13
+ const DEFAULT_ISSUER = "https://auth.octen.ai";
14
+ const DEFAULT_RESOURCE = "https://cli.octen.ai";
15
+ /**
16
+ * Reject a trailing slash rather than trimming it. A sibling project shipped a
17
+ * bug where a trailing slash turned the JWKS URL into `//api/oauth/jwks` and
18
+ * made the issuer comparison fail byte-for-byte — loud failure beats silent
19
+ * correction.
20
+ */
21
+ function rejectTrailingSlash(name, value) {
22
+ if (value.endsWith("/")) {
23
+ throw new OctenValidationError(`${name} must not have a trailing slash: ${value}`);
24
+ }
25
+ return value;
26
+ }
27
+ /** RFC 8252 §8.3 loopback literals. `localhost` is deliberately absent: it can be
28
+ * redirected via the hosts file, so it earns no plaintext exemption. */
29
+ function isLoopbackHost(hostname) {
30
+ return hostname === "127.0.0.1" || hostname === "::1" || hostname === "[::1]";
31
+ }
32
+ /**
33
+ * Every origin that this CLI will send a credential to must be https, with the
34
+ * single exception of a loopback literal (a locally running authorization
35
+ * server, which is what the OCTEN_AUTH_ISSUER doc below invites).
36
+ *
37
+ * This is load-bearing, not hygiene. Two requests carry secrets to whatever
38
+ * this string names: `exchange.ts` sends the access token to `/api/oauth/cli/key`,
39
+ * and `revoke.ts` sends the account-wide, long-lived API key to
40
+ * `/api/oauth/cli/revoke`. Before this check existed, `OCTEN_AUTH_ISSUER=http://…`
41
+ * put both on the wire in cleartext with no warning, and `store.ts` accepted any
42
+ * non-empty string as a *stored* issuer, so a credentials file could name an
43
+ * arbitrary plaintext host and `login`/`logout` would mail the key to it.
44
+ *
45
+ * Exported because store.ts must apply the identical rule to the issuer it reads
46
+ * back off disk — one rule, one implementation, or the two drift.
47
+ */
48
+ export function assertSecureOrigin(name, value) {
49
+ let url;
50
+ try {
51
+ url = new URL(value);
52
+ }
53
+ catch {
54
+ throw new OctenValidationError(`${name} must be an absolute URL: ${value}`);
55
+ }
56
+ if (url.username || url.password) {
57
+ throw new OctenValidationError(`${name} must not contain credentials: ${value}`);
58
+ }
59
+ if (url.protocol === "https:")
60
+ return value;
61
+ if (url.protocol === "http:" && isLoopbackHost(url.hostname))
62
+ return value;
63
+ throw new OctenValidationError(`${name} must use https (or http on a 127.0.0.1 loopback address for local development): ${value}`);
64
+ }
65
+ /**
66
+ * OCTEN_AUTH_ISSUER, default https://auth.octen.ai.
67
+ *
68
+ * Note that the pre-production and production environments share this one
69
+ * auth host — there is no `auth.pre.octen.ai`, and inventing one by analogy
70
+ * with the other per-environment hostnames will produce a DNS failure rather
71
+ * than a pre-prod login. Point this at a locally running authorization server
72
+ * for development instead.
73
+ */
74
+ export function authIssuer(env) {
75
+ const value = env.OCTEN_AUTH_ISSUER ?? DEFAULT_ISSUER;
76
+ return assertSecureOrigin("OCTEN_AUTH_ISSUER", rejectTrailingSlash("OCTEN_AUTH_ISSUER", value));
77
+ }
78
+ /**
79
+ * OCTEN_AUTH_RESOURCE, default https://cli.octen.ai.
80
+ *
81
+ * Unlike the issuer this is never dialled — it is an audience identifier that
82
+ * goes into the authorize request and is compared byte-for-byte on the server.
83
+ * So it gets the trailing-slash rule (a mismatch there is a silent auth
84
+ * failure) but not the https rule: nothing is ever sent *to* it.
85
+ */
86
+ export function authResource(env) {
87
+ const value = env.OCTEN_AUTH_RESOURCE ?? DEFAULT_RESOURCE;
88
+ return rejectTrailingSlash("OCTEN_AUTH_RESOURCE", value);
89
+ }
@@ -0,0 +1,74 @@
1
+ /**
2
+ * The account's long-lived API key, resolved from an access token via
3
+ * `POST {issuer}/api/oauth/cli/key`.
4
+ */
5
+ export interface ExchangeResult {
6
+ apiKey: string;
7
+ /**
8
+ * Epoch seconds, or `null` for "does not expire". The server returns null
9
+ * for every credential it mints today — this is a forward-compatibility
10
+ * slot, kept so that if short-lived API keys ever ship, the client already
11
+ * records the deadline instead of needing a storage-format change.
12
+ */
13
+ expiresAt: number | null;
14
+ /**
15
+ * The id of the OAuth grant behind this credential. Stored on disk and
16
+ * surfaced by `octen whoami`, and it is the only thing `octen logout` can
17
+ * use to name the authorization it wants revoked — no refresh token is ever
18
+ * kept, so this id plus the API key is the whole revocation credential.
19
+ */
20
+ grantId: string;
21
+ accountId?: string;
22
+ accountType?: string;
23
+ /**
24
+ * Human-readable name for the account — "Octen family", or "Personal" for a
25
+ * user account. Display-only, and deliberately NOT written to disk: the
26
+ * login confirmation line is the only thing that renders it, so a name that
27
+ * drifts after the organization is renamed can never be shown.
28
+ *
29
+ * Optional in both directions. A server older than the field omits it, so
30
+ * does a current server that could not load the name, and prod omits it
31
+ * until this ships there — every caller must fall back to `accountId`.
32
+ */
33
+ accountName?: string;
34
+ }
35
+ /**
36
+ * Exchange an access token for the account's own long-lived API key at
37
+ * `POST {issuer}/api/oauth/cli/key`.
38
+ *
39
+ * This is the public counterpart of the server's existing internal
40
+ * `/internal/oauth/resolve-key` service call: same authorization facts,
41
+ * different authentication — a Bearer access token instead of a shared
42
+ * service secret. The server reads the grant id out of
43
+ * the token's own session, never from the caller, so this request carries no
44
+ * body at all.
45
+ *
46
+ * Error classification — by transport layer FIRST, then body, mirroring
47
+ * `exchangeCode` in `./oauthClient.ts`. The ordering matters because an
48
+ * `OctenAuthError` is grounds for discarding a credential while an
49
+ * `OctenNetworkError` means "retry later": if a response body were allowed to
50
+ * decide, a struggling server could talk the CLI into throwing away a
51
+ * credential that was never invalid.
52
+ * - a fetch-level failure (DNS, connection reset, our own timeout) is
53
+ * always `OctenNetworkError`.
54
+ * - any 3xx (or an opaque redirect from `redirect: "manual"`) is treated as
55
+ * a transport-layer fault, never followed: a request carrying a bearer
56
+ * token must not be forwarded to an unintended host.
57
+ * - 408 / 429 / 5xx are always `OctenNetworkError`, EVEN IF the body claims
58
+ * `active: false` — a server fault dressed up as a credential problem
59
+ * must never trigger credential deletion downstream.
60
+ * - 401 is always `OctenAuthError`: missing/non-Bearer/unusable token, or
61
+ * (via the 200 path below) a grant that no longer resolves.
62
+ * - 403 is always `OctenAuthError`: audience/scope/client mismatch,
63
+ * independent of the body; retrying cannot help.
64
+ * - a 200 body with `active: false` is `OctenAuthError` too.
65
+ * - a 200 body missing `api_key`, or whose `expires_at` cannot be parsed,
66
+ * is `OctenNetworkError` — a contract violation, never silently absorbed.
67
+ *
68
+ * No error message here ever includes `a.accessToken` or a returned API key.
69
+ */
70
+ export declare function exchangeForApiKey(a: {
71
+ issuer: string;
72
+ accessToken: string;
73
+ fetchImpl?: typeof fetch;
74
+ }): Promise<ExchangeResult>;
@@ -0,0 +1,124 @@
1
+ import { OctenAuthError, OctenNetworkError } from "../api/errors.js";
2
+ import { REQUEST_TIMEOUT_MS } from "./constants.js";
3
+ /**
4
+ * Convert the server's ISO-8601 `expires_at` to epoch seconds. `null` stays
5
+ * `null` and means "does not expire" — the only value the server sends today.
6
+ *
7
+ * Anything else that fails to parse returns `undefined`, deliberately
8
+ * distinct from `null`, so the caller can treat it as a contract violation.
9
+ * The alternative — falling back to a locally computed deadline — would
10
+ * invent an expiry the server never stated and expire a working credential.
11
+ */
12
+ function parseExpiresAt(value) {
13
+ if (value === null)
14
+ return null;
15
+ if (typeof value !== "string")
16
+ return undefined;
17
+ const ms = Date.parse(value);
18
+ if (Number.isNaN(ms))
19
+ return undefined;
20
+ return Math.floor(ms / 1000);
21
+ }
22
+ /**
23
+ * Exchange an access token for the account's own long-lived API key at
24
+ * `POST {issuer}/api/oauth/cli/key`.
25
+ *
26
+ * This is the public counterpart of the server's existing internal
27
+ * `/internal/oauth/resolve-key` service call: same authorization facts,
28
+ * different authentication — a Bearer access token instead of a shared
29
+ * service secret. The server reads the grant id out of
30
+ * the token's own session, never from the caller, so this request carries no
31
+ * body at all.
32
+ *
33
+ * Error classification — by transport layer FIRST, then body, mirroring
34
+ * `exchangeCode` in `./oauthClient.ts`. The ordering matters because an
35
+ * `OctenAuthError` is grounds for discarding a credential while an
36
+ * `OctenNetworkError` means "retry later": if a response body were allowed to
37
+ * decide, a struggling server could talk the CLI into throwing away a
38
+ * credential that was never invalid.
39
+ * - a fetch-level failure (DNS, connection reset, our own timeout) is
40
+ * always `OctenNetworkError`.
41
+ * - any 3xx (or an opaque redirect from `redirect: "manual"`) is treated as
42
+ * a transport-layer fault, never followed: a request carrying a bearer
43
+ * token must not be forwarded to an unintended host.
44
+ * - 408 / 429 / 5xx are always `OctenNetworkError`, EVEN IF the body claims
45
+ * `active: false` — a server fault dressed up as a credential problem
46
+ * must never trigger credential deletion downstream.
47
+ * - 401 is always `OctenAuthError`: missing/non-Bearer/unusable token, or
48
+ * (via the 200 path below) a grant that no longer resolves.
49
+ * - 403 is always `OctenAuthError`: audience/scope/client mismatch,
50
+ * independent of the body; retrying cannot help.
51
+ * - a 200 body with `active: false` is `OctenAuthError` too.
52
+ * - a 200 body missing `api_key`, or whose `expires_at` cannot be parsed,
53
+ * is `OctenNetworkError` — a contract violation, never silently absorbed.
54
+ *
55
+ * No error message here ever includes `a.accessToken` or a returned API key.
56
+ */
57
+ export async function exchangeForApiKey(a) {
58
+ const f = a.fetchImpl ?? fetch;
59
+ let res;
60
+ try {
61
+ res = await f(`${a.issuer}/api/oauth/cli/key`, {
62
+ method: "POST",
63
+ headers: { Authorization: `Bearer ${a.accessToken}` },
64
+ // This request carries a bearer token — never let a redirect silently
65
+ // forward it to a different host.
66
+ redirect: "manual",
67
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
68
+ });
69
+ }
70
+ catch {
71
+ throw new OctenNetworkError("Could not reach the authorization server; please try again.");
72
+ }
73
+ if (res.type === "opaqueredirect" || (res.status >= 300 && res.status < 400)) {
74
+ throw new OctenNetworkError("The authorization server returned an unexpected redirect; please try again.");
75
+ }
76
+ // Transport-layer classification wins over the body, even when the body
77
+ // claims a credential problem: a 5xx/408/429 is a server or infrastructure
78
+ // fault, and nothing about it establishes that the token or key is bad.
79
+ if (res.status === 408 || res.status === 429 || res.status >= 500) {
80
+ throw new OctenNetworkError("The authorization server is unavailable; please retry later.");
81
+ }
82
+ if (res.status === 401) {
83
+ throw new OctenAuthError("Your session is no longer valid. Run `octen login` again.");
84
+ }
85
+ if (res.status === 403) {
86
+ throw new OctenAuthError("Authorization was refused. Run `octen login` again.");
87
+ }
88
+ if (!res.ok) {
89
+ throw new OctenAuthError(`Key exchange failed (HTTP ${res.status}). Run \`octen login\` again.`);
90
+ }
91
+ let payload;
92
+ try {
93
+ payload = await res.json();
94
+ }
95
+ catch {
96
+ throw new OctenNetworkError("The authorization server returned an invalid response; please try again.");
97
+ }
98
+ const body = payload !== null && typeof payload === "object" ? payload : {};
99
+ if (body.active === false) {
100
+ throw new OctenAuthError("Your session is no longer valid. Run `octen login` again.");
101
+ }
102
+ const apiKey = body.api_key;
103
+ if (typeof apiKey !== "string" || apiKey.length === 0) {
104
+ throw new OctenNetworkError("The authorization server did not return an API key; please try again.");
105
+ }
106
+ const grantId = body.grant_id;
107
+ if (typeof grantId !== "string" || grantId.length === 0) {
108
+ throw new OctenNetworkError("The authorization server did not return a grant id; please try again.");
109
+ }
110
+ const expiresAt = parseExpiresAt(body.expires_at);
111
+ if (expiresAt === undefined) {
112
+ throw new OctenNetworkError("The authorization server returned an invalid expiry; please try again.");
113
+ }
114
+ const accountId = typeof body.account_id === "string" ? body.account_id : undefined;
115
+ const accountType = typeof body.account_type === "string" ? body.account_type : undefined;
116
+ // Unlike the fields above, a blank name is normalized away rather than
117
+ // passed through: it is only ever interpolated into a sentence, and
118
+ // "Logged in as ." is worse than falling back to the account id. This is a
119
+ // display default, never a contract violation — the server omits the field
120
+ // by design whenever it has no name to give.
121
+ const rawAccountName = typeof body.account_name === "string" ? body.account_name.trim() : "";
122
+ const accountName = rawAccountName.length > 0 ? rawAccountName : undefined;
123
+ return { apiKey, expiresAt, grantId, accountId, accountType, accountName };
124
+ }
@@ -0,0 +1,64 @@
1
+ import { type Credentials } from "./store.js";
2
+ export interface LoginDeps {
3
+ /** Injected home dir (for testing); credentials live at `<home>/.octen/credentials.json`. */
4
+ home: string;
5
+ /** Injected env (for testing); defaults are read through `authIssuer`/`authResource`. */
6
+ env: NodeJS.ProcessEnv;
7
+ /** Injected fetch (for testing); defaults to global fetch. */
8
+ fetchImpl?: typeof fetch;
9
+ /**
10
+ * Opens the authorize URL in a browser. Real-world spawn failures (e.g. a
11
+ * missing browser binary) surface asynchronously, so this reports a
12
+ * failure either by throwing synchronously OR by calling the `onFailure`
13
+ * callback it's given — neither one fails the login, both fall back to
14
+ * printing the URL. A machine with no browser (CI, a container, a headless
15
+ * box over ssh) is a supported way to log in, not an error: the user can
16
+ * always copy the printed URL to a browser elsewhere.
17
+ */
18
+ openBrowser: (url: string, onFailure: (err: unknown) => void) => void;
19
+ /** `--no-browser`: print the URL instead of calling `openBrowser` at all. */
20
+ noBrowser?: boolean;
21
+ /** `--port`: pin the loopback callback port (for `ssh -L` forwarding). */
22
+ port?: number;
23
+ /** Progress/warning sink (for testing); defaults to writing to stderr. Never stdout. */
24
+ log?: (line: string) => void;
25
+ }
26
+ export interface LoginResult {
27
+ /** Exactly what was written to disk. */
28
+ credentials: Credentials;
29
+ /**
30
+ * The account's display name, when the server supplied one. Returned
31
+ * alongside the credentials rather than inside them because it is
32
+ * deliberately not persisted: it exists only for the caller's confirmation
33
+ * line, and a stored copy would go stale the moment an organization is
34
+ * renamed. Callers must fall back to `credentials.accountId`.
35
+ */
36
+ accountName?: string;
37
+ }
38
+ /**
39
+ * Orchestrates the eight-step loopback login flow:
40
+ *
41
+ * 1. best-effort revoke of an existing `source: "login"` grant — never
42
+ * blocks a new login, a failure is only logged. It exists so repeated
43
+ * logins on one machine don't pile up orphaned authorizations in the
44
+ * dashboard, which is a tidiness goal, never a correctness one: if the
45
+ * old grant cannot be revoked, the right outcome is still a working new
46
+ * login.
47
+ * 2. start the loopback server
48
+ * 3. build the authorize URL (fixed client_id, PKCE challenge, state,
49
+ * resource, scope)
50
+ * 4. open the browser (or print the URL, on `--no-browser` or a spawn
51
+ * failure)
52
+ * 5. wait for the authorization code
53
+ * 6. exchange the code for an access token
54
+ * 7. exchange the access token for the account's API key
55
+ * 8. write credentials — THE ONLY DISK WRITE. A failure at any earlier
56
+ * step propagates and nothing is written, so there is no two-phase
57
+ * partial state to reconcile and no cleanup path to get wrong. This is
58
+ * what the whole design rests on: because the flow either writes one
59
+ * complete credential or writes nothing, and because what it writes is
60
+ * a long-lived key that is afterwards only ever read, credential
61
+ * resolution stays synchronous, lock-free, and free of any refresh
62
+ * logic. Nothing here may acquire a second write path.
63
+ */
64
+ export declare function login(deps: LoginDeps): Promise<LoginResult>;
@@ -0,0 +1,163 @@
1
+ import { authIssuer, authResource, CLI_SCOPE } from "./constants.js";
2
+ import { createState, createVerifier, challengeFor } from "./pkce.js";
3
+ import { startLoopback } from "./loopback.js";
4
+ import { authorizeUrl, exchangeCode } from "./oauthClient.js";
5
+ import { exchangeForApiKey } from "./exchange.js";
6
+ import { revokeCliGrant } from "./revoke.js";
7
+ import { CREDENTIALS_VERSION, readCredentials, writeCredentials } from "./store.js";
8
+ /**
9
+ * Orchestrates the eight-step loopback login flow:
10
+ *
11
+ * 1. best-effort revoke of an existing `source: "login"` grant — never
12
+ * blocks a new login, a failure is only logged. It exists so repeated
13
+ * logins on one machine don't pile up orphaned authorizations in the
14
+ * dashboard, which is a tidiness goal, never a correctness one: if the
15
+ * old grant cannot be revoked, the right outcome is still a working new
16
+ * login.
17
+ * 2. start the loopback server
18
+ * 3. build the authorize URL (fixed client_id, PKCE challenge, state,
19
+ * resource, scope)
20
+ * 4. open the browser (or print the URL, on `--no-browser` or a spawn
21
+ * failure)
22
+ * 5. wait for the authorization code
23
+ * 6. exchange the code for an access token
24
+ * 7. exchange the access token for the account's API key
25
+ * 8. write credentials — THE ONLY DISK WRITE. A failure at any earlier
26
+ * step propagates and nothing is written, so there is no two-phase
27
+ * partial state to reconcile and no cleanup path to get wrong. This is
28
+ * what the whole design rests on: because the flow either writes one
29
+ * complete credential or writes nothing, and because what it writes is
30
+ * a long-lived key that is afterwards only ever read, credential
31
+ * resolution stays synchronous, lock-free, and free of any refresh
32
+ * logic. Nothing here may acquire a second write path.
33
+ */
34
+ export async function login(deps) {
35
+ const log = deps.log ?? ((line) => { process.stderr.write(`${line}\n`); });
36
+ const issuer = authIssuer(deps.env);
37
+ const resource = authResource(deps.env);
38
+ // Step 1: best-effort revoke of a prior login grant so repeated logins
39
+ // don't accumulate orphaned authorizations. Every failure mode here is
40
+ // non-blocking — network error, 401, 403, 400, 503 all just log and carry
41
+ // on. Blocking a new login because an old grant could not be tidied up
42
+ // would turn a cosmetic problem into a lockout.
43
+ //
44
+ // Reading the existing file is itself guarded: `octen login` is precisely
45
+ // the command that must not depend on an old file being readable, since
46
+ // step 8 is about to overwrite it regardless. A corrupt file or one from
47
+ // a future CREDENTIALS_VERSION must not make login the one command that
48
+ // can't recover from it.
49
+ let existing;
50
+ try {
51
+ existing = readCredentials(deps.home);
52
+ }
53
+ catch (err) {
54
+ log(`warning: ignoring an unreadable existing credentials file (continuing): ${err.message}`);
55
+ }
56
+ if (existing?.source === "login" && existing.issuer !== issuer) {
57
+ // A credential minted against a different issuer is another environment's,
58
+ // and `resolveApiKey` already refuses to *use* it for exactly that reason
59
+ // (config/resolve.ts: "never use it… it isn't ours to manage"). Sending its
60
+ // API key to the host that file happens to name would be the same
61
+ // credential being trusted in the one direction that leaks it. So: don't.
62
+ //
63
+ // Say so loudly rather than silently, because step 8 is about to overwrite
64
+ // the only local record of that grant's id.
65
+ log(`warning: the existing credential was issued by ${existing.issuer}, not ${issuer} — leaving it alone.\n` +
66
+ ` Grant ${existing.grantId} is NOT revoked. To close it out, run \`octen logout\` with\n` +
67
+ ` OCTEN_AUTH_ISSUER=${existing.issuer} before logging in here, or revoke it in that\n` +
68
+ ` environment's dashboard by that id.`);
69
+ }
70
+ else if (existing?.source === "login" && existing.resource !== resource) {
71
+ log(`warning: the existing credential names audience ${existing.resource}, not ${resource} — leaving it alone.\n` +
72
+ ` Grant ${existing.grantId} is NOT revoked; revoke it in the dashboard by that id.`);
73
+ }
74
+ else if (existing?.source === "login") {
75
+ try {
76
+ await revokeCliGrant({
77
+ issuer: existing.issuer,
78
+ apiKey: existing.apiKey,
79
+ grantId: existing.grantId,
80
+ fetchImpl: deps.fetchImpl,
81
+ });
82
+ }
83
+ catch (err) {
84
+ // Name the grant. The file holding this id is about to be overwritten
85
+ // by step 8, so this line is the last chance the user has to learn
86
+ // which dashboard authorization was left behind — without it the grant
87
+ // stays listed server-side with nothing local able to identify it.
88
+ log(`warning: could not revoke the previous login grant (continuing): ${err.message}\n` +
89
+ ` Grant ${existing.grantId} may still be active — revoke it in the dashboard by that id.`);
90
+ }
91
+ }
92
+ // Step 2: start the loopback server.
93
+ const state = createState();
94
+ const verifier = createVerifier();
95
+ const challenge = challengeFor(verifier);
96
+ const loop = await startLoopback({ state, port: deps.port });
97
+ try {
98
+ // Step 3: build the authorize URL.
99
+ const url = authorizeUrl({
100
+ issuer,
101
+ redirectUri: loop.redirectUri,
102
+ challenge,
103
+ state,
104
+ resource,
105
+ scope: CLI_SCOPE,
106
+ });
107
+ // Step 4: open the browser, or print the URL. A spawn failure is
108
+ // usually asynchronous (e.g. ENOENT for a missing binary), so both the
109
+ // synchronous-throw path and the async onFailure callback route to this
110
+ // one fallback — there is exactly one "print the URL instead" message.
111
+ if (deps.noBrowser) {
112
+ log(`Open this URL to log in:\n${url}`);
113
+ }
114
+ else {
115
+ const printFallback = () => log(`Could not open your browser automatically. Open this URL to log in:\n${url}`);
116
+ try {
117
+ deps.openBrowser(url, printFallback);
118
+ log("Opening your browser to continue login...");
119
+ }
120
+ catch {
121
+ printFallback();
122
+ }
123
+ }
124
+ // Step 5: wait for the authorization code.
125
+ log("Waiting for the browser redirect...");
126
+ const code = await loop.waitForCode();
127
+ // Step 6: exchange the code for an access token.
128
+ const tokenSet = await exchangeCode({
129
+ issuer,
130
+ redirectUri: loop.redirectUri,
131
+ code,
132
+ verifier,
133
+ resource,
134
+ fetchImpl: deps.fetchImpl,
135
+ });
136
+ // Step 7: exchange the access token for the account's API key.
137
+ const result = await exchangeForApiKey({
138
+ issuer,
139
+ accessToken: tokenSet.accessToken,
140
+ fetchImpl: deps.fetchImpl,
141
+ });
142
+ // Step 8: THE single disk write.
143
+ const creds = {
144
+ version: CREDENTIALS_VERSION,
145
+ source: "login",
146
+ issuer,
147
+ resource,
148
+ apiKey: result.apiKey,
149
+ apiKeyExpiresAt: result.expiresAt,
150
+ grantId: result.grantId,
151
+ ...(result.accountId !== undefined ? { accountId: result.accountId } : {}),
152
+ ...(result.accountType !== undefined ? { accountType: result.accountType } : {}),
153
+ };
154
+ writeCredentials(deps.home, creds);
155
+ return { credentials: creds, accountName: result.accountName };
156
+ }
157
+ finally {
158
+ // Idempotent: the server already closed itself on the success path
159
+ // (loopback.ts finalizes on code receipt). This covers every other
160
+ // exit — an error/timeout from waitForCode, or a later step throwing.
161
+ loop.close();
162
+ }
163
+ }
@@ -0,0 +1,32 @@
1
+ export interface LoopbackServer {
2
+ port: number;
3
+ /** http://127.0.0.1:<port>/callback — literal IP per RFC 8252 §8.3, never `localhost`. */
4
+ redirectUri: string;
5
+ /** Same promise on every call. Settles exactly once: code, error, timeout or close(). */
6
+ waitForCode(): Promise<string>;
7
+ /** Idempotent. Releases the port through the same path as every other exit. */
8
+ close(): void;
9
+ }
10
+ /**
11
+ * A one-shot HTTP server on 127.0.0.1 that answers exactly one OAuth
12
+ * authorization-code redirect on /callback, then shuts itself down.
13
+ *
14
+ * Security notes (127.0.0.1 is reachable by every local process, not just
15
+ * the browser):
16
+ * - `state` is validated BEFORE an `error` parameter is honoured, so a
17
+ * forged `?error=access_denied&state=wrong` from another local process
18
+ * cannot fail a real login.
19
+ * - A wrong-state request gets 400 and the server keeps listening —
20
+ * it never exits on a forged callback.
21
+ * - There is no cap on wrong-state attempts, only the deadline — a fixed
22
+ * cap would itself be an attack ("send N bogus callbacks to kill any
23
+ * login").
24
+ * - Every exit path (success, error, timeout, external close()) settles
25
+ * through the same `finalize`, which clears the timer and closes the
26
+ * server exactly once.
27
+ */
28
+ export declare function startLoopback(opts: {
29
+ state: string;
30
+ port?: number;
31
+ timeoutMs?: number;
32
+ }): Promise<LoopbackServer>;
@@ -0,0 +1,95 @@
1
+ import { createServer } from "node:http";
2
+ import { LOOPBACK_TIMEOUT_MS } from "./constants.js";
3
+ const SUCCESS_HTML = "<!doctype html><html><body><p>Login successful. You can close this tab.</p></body></html>";
4
+ const FAILURE_HTML = "<!doctype html><html><body><p>Login failed. You can close this tab and return to the terminal.</p></body></html>";
5
+ /**
6
+ * A one-shot HTTP server on 127.0.0.1 that answers exactly one OAuth
7
+ * authorization-code redirect on /callback, then shuts itself down.
8
+ *
9
+ * Security notes (127.0.0.1 is reachable by every local process, not just
10
+ * the browser):
11
+ * - `state` is validated BEFORE an `error` parameter is honoured, so a
12
+ * forged `?error=access_denied&state=wrong` from another local process
13
+ * cannot fail a real login.
14
+ * - A wrong-state request gets 400 and the server keeps listening —
15
+ * it never exits on a forged callback.
16
+ * - There is no cap on wrong-state attempts, only the deadline — a fixed
17
+ * cap would itself be an attack ("send N bogus callbacks to kill any
18
+ * login").
19
+ * - Every exit path (success, error, timeout, external close()) settles
20
+ * through the same `finalize`, which clears the timer and closes the
21
+ * server exactly once.
22
+ */
23
+ export function startLoopback(opts) {
24
+ const { state, port = 0, timeoutMs = LOOPBACK_TIMEOUT_MS } = opts;
25
+ return new Promise((resolveStart, rejectStart) => {
26
+ let settled = false;
27
+ let resolveCode;
28
+ let rejectCode;
29
+ const codePromise = new Promise((res, rej) => {
30
+ resolveCode = res;
31
+ rejectCode = rej;
32
+ });
33
+ // A caller that never calls waitForCode() (e.g. the timeout/close path
34
+ // fires before anyone awaits it) must not produce an unhandled rejection.
35
+ codePromise.catch(() => { });
36
+ let timer;
37
+ let server;
38
+ function finalize(settle) {
39
+ if (settled)
40
+ return;
41
+ settled = true;
42
+ clearTimeout(timer);
43
+ settle();
44
+ // Force-close any lingering keep-alive sockets so the port is free the
45
+ // instant this returns, not whenever the client happens to disconnect.
46
+ server.closeAllConnections?.();
47
+ server.close();
48
+ }
49
+ server = createServer((req, res) => {
50
+ const url = new URL(req.url ?? "/", "http://127.0.0.1");
51
+ if (url.pathname !== "/callback") {
52
+ res.writeHead(404).end();
53
+ return;
54
+ }
55
+ const reqState = url.searchParams.get("state");
56
+ if (reqState !== state) {
57
+ // Keep listening: this may be a forgery from another local process,
58
+ // not the real browser redirect.
59
+ res.writeHead(400, { "content-type": "text/plain" }).end("invalid state");
60
+ return;
61
+ }
62
+ const error = url.searchParams.get("error");
63
+ if (error) {
64
+ res.writeHead(200, { "content-type": "text/html" }).end(FAILURE_HTML);
65
+ finalize(() => rejectCode(new Error(`OAuth error: ${error}`)));
66
+ return;
67
+ }
68
+ const code = url.searchParams.get("code");
69
+ if (!code) {
70
+ res.writeHead(400, { "content-type": "text/plain" }).end("missing code");
71
+ return;
72
+ }
73
+ res.writeHead(200, { "content-type": "text/html" }).end(SUCCESS_HTML);
74
+ finalize(() => resolveCode(code));
75
+ });
76
+ server.on("error", (err) => {
77
+ rejectStart(err);
78
+ });
79
+ // Literal 127.0.0.1, never "localhost" — RFC 8252 §8.3: localhost can be
80
+ // redirected via the hosts file, 127.0.0.1 cannot.
81
+ server.listen(port, "127.0.0.1", () => {
82
+ const actualPort = server.address().port;
83
+ timer = setTimeout(() => {
84
+ finalize(() => rejectCode(new Error("Login timed out waiting for the browser redirect")));
85
+ }, timeoutMs);
86
+ timer.unref();
87
+ resolveStart({
88
+ port: actualPort,
89
+ redirectUri: `http://127.0.0.1:${actualPort}/callback`,
90
+ waitForCode: () => codePromise,
91
+ close: () => finalize(() => rejectCode(new Error("Loopback server closed"))),
92
+ });
93
+ });
94
+ });
95
+ }