@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
@@ -2,15 +2,42 @@ export declare class OctenError extends Error {
2
2
  }
3
3
  export declare class OctenAuthError extends OctenError {
4
4
  }
5
+ /**
6
+ * There is no credential at all — no flag, no env var, no credentials file.
7
+ *
8
+ * A subclass rather than a flag so that every existing `instanceof
9
+ * OctenAuthError` keeps matching, while the two callers that must tell "you
10
+ * have nothing" apart from "you have something that doesn't apply here"
11
+ * (`configure-mcp`, `configure-skills --set-key`) can do it without matching on
12
+ * message text. Both used to treat any OctenAuthError as "no credential", so a
13
+ * working credential plus an OCTEN_AUTH_ISSUER override produced "no API key
14
+ * found", a `${OCTEN_API_KEY}` placeholder config, exit 0 — and, in
15
+ * configure-skills, advice to run `octen login`, which cannot fix an
16
+ * OCTEN_AUTH_* override.
17
+ */
18
+ export declare class OctenNoCredentialError extends OctenAuthError {
19
+ }
5
20
  export declare class OctenValidationError extends OctenError {
6
21
  }
7
22
  export declare class OctenTimeoutError extends OctenError {
8
23
  }
9
24
  export declare class OctenNetworkError extends OctenError {
10
25
  }
26
+ /** A stream that was malformed, truncated, or carried a typed error event. */
27
+ export declare class OctenStreamError extends OctenError {
28
+ }
11
29
  export declare class OctenAPIError extends OctenError {
12
30
  status: number;
13
31
  body?: unknown | undefined;
14
32
  constructor(message: string, status: number, body?: unknown | undefined);
15
33
  }
34
+ /**
35
+ * Pull a human-readable message out of an error payload.
36
+ *
37
+ * Fixed order: `msg` -> `message` -> `detail`, then recurse into `error`, then
38
+ * the caller's fallback. Only a non-empty string is ever returned, so a nested
39
+ * object can no longer reach the terminal as "[object Object]". Visited nodes
40
+ * are tracked so a self-referential payload cannot loop.
41
+ */
42
+ export declare function errorMessage(payload: unknown, fallback: string): string;
16
43
  export declare function exitCodeFor(err: unknown): number;
@@ -2,12 +2,30 @@ export class OctenError extends Error {
2
2
  }
3
3
  export class OctenAuthError extends OctenError {
4
4
  }
5
+ /**
6
+ * There is no credential at all — no flag, no env var, no credentials file.
7
+ *
8
+ * A subclass rather than a flag so that every existing `instanceof
9
+ * OctenAuthError` keeps matching, while the two callers that must tell "you
10
+ * have nothing" apart from "you have something that doesn't apply here"
11
+ * (`configure-mcp`, `configure-skills --set-key`) can do it without matching on
12
+ * message text. Both used to treat any OctenAuthError as "no credential", so a
13
+ * working credential plus an OCTEN_AUTH_ISSUER override produced "no API key
14
+ * found", a `${OCTEN_API_KEY}` placeholder config, exit 0 — and, in
15
+ * configure-skills, advice to run `octen login`, which cannot fix an
16
+ * OCTEN_AUTH_* override.
17
+ */
18
+ export class OctenNoCredentialError extends OctenAuthError {
19
+ }
5
20
  export class OctenValidationError extends OctenError {
6
21
  }
7
22
  export class OctenTimeoutError extends OctenError {
8
23
  }
9
24
  export class OctenNetworkError extends OctenError {
10
25
  }
26
+ /** A stream that was malformed, truncated, or carried a typed error event. */
27
+ export class OctenStreamError extends OctenError {
28
+ }
11
29
  export class OctenAPIError extends OctenError {
12
30
  status;
13
31
  body;
@@ -17,6 +35,40 @@ export class OctenAPIError extends OctenError {
17
35
  this.body = body;
18
36
  }
19
37
  }
38
+ /** Keys that, when they hold a non-empty string, are the error message. */
39
+ const MESSAGE_KEYS = ["msg", "message", "detail"];
40
+ function nonEmptyString(value) {
41
+ return typeof value === "string" && value.trim().length > 0 ? value : undefined;
42
+ }
43
+ /**
44
+ * Pull a human-readable message out of an error payload.
45
+ *
46
+ * Fixed order: `msg` -> `message` -> `detail`, then recurse into `error`, then
47
+ * the caller's fallback. Only a non-empty string is ever returned, so a nested
48
+ * object can no longer reach the terminal as "[object Object]". Visited nodes
49
+ * are tracked so a self-referential payload cannot loop.
50
+ */
51
+ export function errorMessage(payload, fallback) {
52
+ const seen = new Set();
53
+ const walk = (node) => {
54
+ const direct = nonEmptyString(node);
55
+ if (direct)
56
+ return direct;
57
+ if (node === null || typeof node !== "object")
58
+ return undefined;
59
+ if (seen.has(node))
60
+ return undefined;
61
+ seen.add(node);
62
+ const obj = node;
63
+ for (const key of MESSAGE_KEYS) {
64
+ const found = nonEmptyString(obj[key]);
65
+ if (found)
66
+ return found;
67
+ }
68
+ return walk(obj.error);
69
+ };
70
+ return walk(payload) ?? fallback;
71
+ }
20
72
  export function exitCodeFor(err) {
21
73
  if (err instanceof OctenAuthError || err instanceof OctenValidationError)
22
74
  return 2;
@@ -76,7 +76,10 @@ export function buildSearchOptions(o) {
76
76
  return opts;
77
77
  }
78
78
  export function buildSearchRequest(query, o) {
79
- if (!query)
79
+ // Validate on the trimmed value but send the caller's text verbatim: a query
80
+ // of only whitespace is a mistake, whitespace inside a real query is not ours
81
+ // to rewrite.
82
+ if (query.trim().length === 0)
80
83
  throw new OctenValidationError("query is required");
81
84
  return { query, ...buildSearchOptions(o) };
82
85
  }
@@ -86,7 +89,7 @@ export function buildSearchRequest(query, o) {
86
89
  * `max_queries` stay at the top level.
87
90
  */
88
91
  export function buildBroadSearchRequest(query, o) {
89
- if (!query)
92
+ if (query.trim().length === 0)
90
93
  throw new OctenValidationError("query is required");
91
94
  if (o.maxQueries != null && (o.maxQueries < LIMITS.maxQueries.min || o.maxQueries > LIMITS.maxQueries.max))
92
95
  throw new OctenValidationError(`max-queries must be ${LIMITS.maxQueries.min}-${LIMITS.maxQueries.max}`);
package/dist/api/sse.d.ts CHANGED
@@ -1,6 +1,18 @@
1
1
  /**
2
- * Parse a Server-Sent Events (SSE) stream from a fetch Response.
3
- * Yields parsed JSON objects from `data:` lines, stops at `data: [DONE]`.
4
- * Tolerates non-JSON keepalive/comment lines by skipping them.
2
+ * Parse a Server-Sent Events stream from a fetch Response into parsed JSON events.
3
+ *
4
+ * Framing follows the SSE rules the chat endpoint actually uses: events are
5
+ * separated by a blank line, LF and CRLF both terminate a line, `data:` may or
6
+ * may not be followed by a space, and every `data:` line in one event is joined
7
+ * with "\n" and parsed once — so a JSON object split across data lines survives.
8
+ *
9
+ * Completion is explicit. `[DONE]` is authoritative and nothing after it is
10
+ * read; a typed `finish` event or an OpenAI-style `finish_reason` followed by
11
+ * EOF also counts as complete. A stream that just stops is a truncation error
12
+ * rather than a silently short answer. Malformed JSON is an error too, for the
13
+ * same reason: a dropped event is indistinguishable from a shorter answer.
14
+ *
15
+ * The reader is always released, and the source is cancelled whenever iteration
16
+ * stops before the body is drained — including when the consumer breaks early.
5
17
  */
6
18
  export declare function parseSSE(res: Response): AsyncGenerator<unknown>;
package/dist/api/sse.js CHANGED
@@ -1,53 +1,148 @@
1
+ import { OctenStreamError, OctenTimeoutError } from "./errors.js";
2
+ /** Prefix of an SSE data field. The single space after the colon is optional. */
3
+ const DATA_PREFIX = "data:";
4
+ const DONE_SENTINEL = "[DONE]";
5
+ /** True when an event says generation is over: typed `finish` or an OpenAI finish_reason. */
6
+ function isTerminalEvent(event) {
7
+ if (event === null || typeof event !== "object")
8
+ return false;
9
+ const obj = event;
10
+ if (obj.type === "finish")
11
+ return true;
12
+ const choices = obj.choices;
13
+ if (Array.isArray(choices)) {
14
+ return choices.some((choice) => choice !== null &&
15
+ typeof choice === "object" &&
16
+ choice.finish_reason != null);
17
+ }
18
+ return false;
19
+ }
1
20
  /**
2
- * Parse a Server-Sent Events (SSE) stream from a fetch Response.
3
- * Yields parsed JSON objects from `data:` lines, stops at `data: [DONE]`.
4
- * Tolerates non-JSON keepalive/comment lines by skipping them.
21
+ * Parse a Server-Sent Events stream from a fetch Response into parsed JSON events.
22
+ *
23
+ * Framing follows the SSE rules the chat endpoint actually uses: events are
24
+ * separated by a blank line, LF and CRLF both terminate a line, `data:` may or
25
+ * may not be followed by a space, and every `data:` line in one event is joined
26
+ * with "\n" and parsed once — so a JSON object split across data lines survives.
27
+ *
28
+ * Completion is explicit. `[DONE]` is authoritative and nothing after it is
29
+ * read; a typed `finish` event or an OpenAI-style `finish_reason` followed by
30
+ * EOF also counts as complete. A stream that just stops is a truncation error
31
+ * rather than a silently short answer. Malformed JSON is an error too, for the
32
+ * same reason: a dropped event is indistinguishable from a shorter answer.
33
+ *
34
+ * The reader is always released, and the source is cancelled whenever iteration
35
+ * stops before the body is drained — including when the consumer breaks early.
5
36
  */
6
37
  export async function* parseSSE(res) {
7
38
  const reader = res.body.getReader();
8
39
  const decoder = new TextDecoder();
9
40
  let buffer = "";
10
- while (true) {
11
- const { done, value } = await reader.read();
12
- if (done)
13
- break;
14
- buffer += decoder.decode(value, { stream: true });
15
- // SSE events are separated by double newlines
16
- const events = buffer.split("\n\n");
17
- // Keep the last (possibly incomplete) segment in the buffer
18
- buffer = events.pop() ?? "";
19
- for (const event of events) {
20
- // Gather data lines from the event block
21
- for (const line of event.split("\n")) {
22
- if (!line.startsWith("data:"))
23
- continue;
24
- const payload = line.slice("data:".length).trim();
25
- if (payload === "[DONE]")
26
- return;
27
- try {
28
- yield JSON.parse(payload);
29
- }
30
- catch {
31
- // Skip non-JSON keepalive or malformed lines
41
+ let pendingCR = false;
42
+ let sawDone = false;
43
+ let sawFinish = false;
44
+ let sourceDrained = false;
45
+ /** Normalize line endings, holding back a CR that may be half of a split CRLF. */
46
+ const feed = (text) => {
47
+ let chunk = pendingCR ? `\r${text}` : text;
48
+ pendingCR = chunk.endsWith("\r");
49
+ if (pendingCR)
50
+ chunk = chunk.slice(0, -1);
51
+ return chunk.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
52
+ };
53
+ /** Parse one event block. Returns the event, or undefined for comment-only blocks. */
54
+ const parseEvent = (block) => {
55
+ const dataLines = [];
56
+ for (const line of block.split("\n")) {
57
+ if (line.startsWith(":"))
58
+ continue;
59
+ if (!line.startsWith(DATA_PREFIX))
60
+ continue;
61
+ let value = line.slice(DATA_PREFIX.length);
62
+ if (value.startsWith(" "))
63
+ value = value.slice(1);
64
+ dataLines.push(value);
65
+ }
66
+ if (dataLines.length === 0)
67
+ return {};
68
+ const payload = dataLines.join("\n");
69
+ if (payload.trim() === DONE_SENTINEL)
70
+ return { done: true };
71
+ if (payload.trim() === "")
72
+ return {};
73
+ try {
74
+ return { event: JSON.parse(payload) };
75
+ }
76
+ catch {
77
+ throw new OctenStreamError(`stream returned a malformed event: ${payload.slice(0, 200)}`);
78
+ }
79
+ };
80
+ /** A body read aborted by the client deadline is a timeout, not a stream defect. */
81
+ const read = async () => {
82
+ try {
83
+ return await reader.read();
84
+ }
85
+ catch (err) {
86
+ const name = err?.name;
87
+ if (name === "AbortError" || name === "TimeoutError") {
88
+ throw new OctenTimeoutError("request timed out");
89
+ }
90
+ throw err;
91
+ }
92
+ };
93
+ try {
94
+ while (!sawDone) {
95
+ const { done, value } = await read();
96
+ if (done) {
97
+ sourceDrained = true;
98
+ buffer += feed(decoder.decode());
99
+ }
100
+ else {
101
+ buffer += feed(decoder.decode(value, { stream: true }));
102
+ }
103
+ const blocks = buffer.split("\n\n");
104
+ // The trailing segment may be an incomplete event; at EOF there is no more
105
+ // data coming, so it is complete by definition and gets dispatched too.
106
+ buffer = sourceDrained ? "" : (blocks.pop() ?? "");
107
+ if (sourceDrained && blocks.length > 0 && blocks[blocks.length - 1].trim() === "") {
108
+ blocks.pop();
109
+ }
110
+ for (const block of blocks) {
111
+ const { event, done: isDone } = parseEvent(block);
112
+ if (isDone) {
113
+ sawDone = true;
114
+ break;
32
115
  }
116
+ if (event === undefined)
117
+ continue;
118
+ if (isTerminalEvent(event))
119
+ sawFinish = true;
120
+ yield event;
33
121
  }
122
+ if (sourceDrained)
123
+ break;
124
+ }
125
+ if (!sawDone && !sawFinish) {
126
+ throw new OctenStreamError("stream ended before the response was complete (no [DONE] or finish event)");
34
127
  }
35
128
  }
36
- // Flush any remaining buffer content
37
- if (buffer.trim()) {
38
- for (const line of buffer.split("\n")) {
39
- if (!line.startsWith("data:"))
40
- continue;
41
- const payload = line.slice("data:".length).trim();
42
- if (payload === "[DONE]")
43
- return;
129
+ finally {
130
+ // Cancel unless the body was read to its end, so an early stop (consumer
131
+ // break, [DONE], or an error) actually releases the connection. Cleanup
132
+ // failures must not replace the error that got us here.
133
+ if (!sourceDrained) {
44
134
  try {
45
- yield JSON.parse(payload);
135
+ await reader.cancel();
46
136
  }
47
137
  catch {
48
- // Skip non-JSON keepalive or malformed lines
138
+ /* the stream is already gone */
49
139
  }
50
140
  }
141
+ try {
142
+ reader.releaseLock();
143
+ }
144
+ catch {
145
+ /* already released */
146
+ }
51
147
  }
52
- // A stream ending without [DONE] is treated as a normal end; the chat command owns user-facing truncation messaging.
53
148
  }
@@ -0,0 +1,47 @@
1
+ /**
2
+ * The pre-registered public client id. This is not a value the CLI chooses:
3
+ * it must byte-match the client row seeded on the authorization server, and a
4
+ * mismatch fails at the authorize step with `invalid_client`, before the user
5
+ * ever sees a consent screen. There is no dynamic client registration, so
6
+ * nothing negotiates this at runtime — it is a cross-repository constant.
7
+ */
8
+ export declare const CLI_CLIENT_ID = "octen-cli";
9
+ export declare const CLI_SCOPE = "octen:api_key";
10
+ export declare const REQUEST_TIMEOUT_MS = 10000;
11
+ export declare const LOOPBACK_TIMEOUT_MS: number;
12
+ /**
13
+ * Every origin that this CLI will send a credential to must be https, with the
14
+ * single exception of a loopback literal (a locally running authorization
15
+ * server, which is what the OCTEN_AUTH_ISSUER doc below invites).
16
+ *
17
+ * This is load-bearing, not hygiene. Two requests carry secrets to whatever
18
+ * this string names: `exchange.ts` sends the access token to `/api/oauth/cli/key`,
19
+ * and `revoke.ts` sends the account-wide, long-lived API key to
20
+ * `/api/oauth/cli/revoke`. Before this check existed, `OCTEN_AUTH_ISSUER=http://…`
21
+ * put both on the wire in cleartext with no warning, and `store.ts` accepted any
22
+ * non-empty string as a *stored* issuer, so a credentials file could name an
23
+ * arbitrary plaintext host and `login`/`logout` would mail the key to it.
24
+ *
25
+ * Exported because store.ts must apply the identical rule to the issuer it reads
26
+ * back off disk — one rule, one implementation, or the two drift.
27
+ */
28
+ export declare function assertSecureOrigin(name: string, value: string): string;
29
+ /**
30
+ * OCTEN_AUTH_ISSUER, default https://auth.octen.ai.
31
+ *
32
+ * Note that the pre-production and production environments share this one
33
+ * auth host — there is no `auth.pre.octen.ai`, and inventing one by analogy
34
+ * with the other per-environment hostnames will produce a DNS failure rather
35
+ * than a pre-prod login. Point this at a locally running authorization server
36
+ * for development instead.
37
+ */
38
+ export declare function authIssuer(env: NodeJS.ProcessEnv): string;
39
+ /**
40
+ * OCTEN_AUTH_RESOURCE, default https://cli.octen.ai.
41
+ *
42
+ * Unlike the issuer this is never dialled — it is an audience identifier that
43
+ * goes into the authorize request and is compared byte-for-byte on the server.
44
+ * So it gets the trailing-slash rule (a mismatch there is a silent auth
45
+ * failure) but not the https rule: nothing is ever sent *to* it.
46
+ */
47
+ export declare function authResource(env: NodeJS.ProcessEnv): string;
@@ -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>;