@octen.ai/cli 0.8.0 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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>;
@@ -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>;