@octen.ai/cli 0.7.0 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/README.md +325 -4
  2. package/dist/api/chat.d.ts +4 -1
  3. package/dist/api/client.d.ts +25 -1
  4. package/dist/api/client.js +144 -17
  5. package/dist/api/errors.d.ts +27 -0
  6. package/dist/api/errors.js +52 -0
  7. package/dist/api/search.js +5 -2
  8. package/dist/api/sse.d.ts +15 -3
  9. package/dist/api/sse.js +131 -36
  10. package/dist/auth/constants.d.ts +47 -0
  11. package/dist/auth/constants.js +89 -0
  12. package/dist/auth/exchange.d.ts +74 -0
  13. package/dist/auth/exchange.js +124 -0
  14. package/dist/auth/login.d.ts +64 -0
  15. package/dist/auth/login.js +163 -0
  16. package/dist/auth/loopback.d.ts +32 -0
  17. package/dist/auth/loopback.js +95 -0
  18. package/dist/auth/oauthClient.d.ts +70 -0
  19. package/dist/auth/oauthClient.js +136 -0
  20. package/dist/auth/pkce.d.ts +6 -0
  21. package/dist/auth/pkce.js +13 -0
  22. package/dist/auth/revoke.d.ts +58 -0
  23. package/dist/auth/revoke.js +91 -0
  24. package/dist/auth/store.d.ts +34 -0
  25. package/dist/auth/store.js +149 -0
  26. package/dist/cli.js +6 -0
  27. package/dist/commands/broadSearch.js +6 -6
  28. package/dist/commands/chat.js +12 -8
  29. package/dist/commands/configureMcp.js +38 -20
  30. package/dist/commands/configureSkills.js +25 -10
  31. package/dist/commands/imageSearch.js +3 -3
  32. package/dist/commands/login.d.ts +49 -0
  33. package/dist/commands/login.js +161 -0
  34. package/dist/commands/logout.d.ts +46 -0
  35. package/dist/commands/logout.js +142 -0
  36. package/dist/commands/reset.js +43 -5
  37. package/dist/commands/search.js +6 -6
  38. package/dist/commands/utils.d.ts +21 -2
  39. package/dist/commands/utils.js +43 -6
  40. package/dist/commands/whoami.d.ts +27 -0
  41. package/dist/commands/whoami.js +109 -0
  42. package/dist/config/resolve.d.ts +44 -1
  43. package/dist/config/resolve.js +80 -5
  44. package/dist/mcp/clients.js +7 -3
  45. package/dist/mcp/install.js +15 -2
  46. package/dist/mcp/write.js +24 -3
  47. package/dist/output/pretty/whoami.d.ts +59 -0
  48. package/dist/output/pretty/whoami.js +103 -0
  49. package/dist/skills/setkey.js +5 -4
  50. package/dist/util/secretFile.d.ts +24 -0
  51. package/dist/util/secretFile.js +35 -0
  52. package/package.json +1 -1
@@ -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
+ }
@@ -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>;