@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.
- package/README.md +325 -4
- package/dist/api/chat.d.ts +4 -1
- package/dist/api/client.d.ts +25 -1
- package/dist/api/client.js +144 -17
- package/dist/api/errors.d.ts +27 -0
- package/dist/api/errors.js +52 -0
- package/dist/api/search.js +5 -2
- package/dist/api/sse.d.ts +15 -3
- package/dist/api/sse.js +131 -36
- package/dist/auth/constants.d.ts +47 -0
- package/dist/auth/constants.js +89 -0
- package/dist/auth/exchange.d.ts +74 -0
- package/dist/auth/exchange.js +124 -0
- package/dist/auth/login.d.ts +64 -0
- package/dist/auth/login.js +163 -0
- package/dist/auth/loopback.d.ts +32 -0
- package/dist/auth/loopback.js +95 -0
- package/dist/auth/oauthClient.d.ts +70 -0
- package/dist/auth/oauthClient.js +136 -0
- package/dist/auth/pkce.d.ts +6 -0
- package/dist/auth/pkce.js +13 -0
- package/dist/auth/revoke.d.ts +58 -0
- package/dist/auth/revoke.js +91 -0
- package/dist/auth/store.d.ts +34 -0
- package/dist/auth/store.js +149 -0
- package/dist/cli.js +6 -0
- package/dist/commands/broadSearch.js +6 -6
- package/dist/commands/chat.js +12 -8
- package/dist/commands/configureMcp.js +38 -20
- package/dist/commands/configureSkills.js +25 -10
- package/dist/commands/imageSearch.js +3 -3
- package/dist/commands/login.d.ts +49 -0
- package/dist/commands/login.js +161 -0
- package/dist/commands/logout.d.ts +46 -0
- package/dist/commands/logout.js +142 -0
- package/dist/commands/reset.js +43 -5
- package/dist/commands/search.js +6 -6
- package/dist/commands/utils.d.ts +21 -2
- package/dist/commands/utils.js +43 -6
- package/dist/commands/whoami.d.ts +27 -0
- package/dist/commands/whoami.js +109 -0
- package/dist/config/resolve.d.ts +44 -1
- package/dist/config/resolve.js +80 -5
- package/dist/mcp/clients.js +7 -3
- package/dist/mcp/install.js +15 -2
- package/dist/mcp/write.js +24 -3
- package/dist/output/pretty/whoami.d.ts +59 -0
- package/dist/output/pretty/whoami.js +103 -0
- package/dist/skills/setkey.js +5 -4
- package/dist/util/secretFile.d.ts +24 -0
- package/dist/util/secretFile.js +35 -0
- package/package.json +1 -1
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
import { OctenAuthError, OctenNetworkError } from "../api/errors.js";
|
|
2
|
+
import { CLI_CLIENT_ID, REQUEST_TIMEOUT_MS } from "./constants.js";
|
|
3
|
+
/**
|
|
4
|
+
* Build the `GET {issuer}/oauth/authorize` URL for the loopback flow.
|
|
5
|
+
*
|
|
6
|
+
* `client_id` is fixed to `CLI_CLIENT_ID` and is deliberately NOT a
|
|
7
|
+
* parameter: this CLI is a single pre-registered public client whose row is
|
|
8
|
+
* seeded server-side, and there is no dynamic client registration anywhere in
|
|
9
|
+
* this flow. Making it a parameter would imply a per-install client identity
|
|
10
|
+
* that does not exist. Every other value here is genuinely per-flow.
|
|
11
|
+
*/
|
|
12
|
+
export function authorizeUrl(a) {
|
|
13
|
+
const u = new URL(`${a.issuer}/oauth/authorize`);
|
|
14
|
+
u.searchParams.set("client_id", CLI_CLIENT_ID);
|
|
15
|
+
u.searchParams.set("response_type", "code");
|
|
16
|
+
u.searchParams.set("redirect_uri", a.redirectUri);
|
|
17
|
+
u.searchParams.set("code_challenge", a.challenge);
|
|
18
|
+
u.searchParams.set("code_challenge_method", "S256");
|
|
19
|
+
u.searchParams.set("state", a.state);
|
|
20
|
+
u.searchParams.set("resource", a.resource);
|
|
21
|
+
u.searchParams.set("scope", a.scope);
|
|
22
|
+
return u.toString();
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* Read an OAuth `error` code out of a token-endpoint error body, if present.
|
|
26
|
+
* Never throws — an unparseable or unexpected shape just yields `undefined`.
|
|
27
|
+
*/
|
|
28
|
+
function oauthErrorCode(payload) {
|
|
29
|
+
if (payload === null || typeof payload !== "object")
|
|
30
|
+
return undefined;
|
|
31
|
+
const value = payload.error;
|
|
32
|
+
return typeof value === "string" ? value : undefined;
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* Exchange an authorization code for an access token at
|
|
36
|
+
* `POST {issuer}/api/oauth/token`.
|
|
37
|
+
*
|
|
38
|
+
* Error classification — by transport layer FIRST, then body. The ordering is
|
|
39
|
+
* the point: an `OctenAuthError` tells the caller "this credential is no good",
|
|
40
|
+
* which is grounds for deleting it, while an `OctenNetworkError` means "try
|
|
41
|
+
* again later". Letting a response body decide that would let a struggling
|
|
42
|
+
* server delete a perfectly valid credential.
|
|
43
|
+
*
|
|
44
|
+
* - a fetch-level failure (DNS, connection reset, our own timeout) is
|
|
45
|
+
* always `OctenNetworkError`.
|
|
46
|
+
* - any 3xx (or an opaque redirect from `redirect: "manual"`) is treated as
|
|
47
|
+
* a transport-layer fault, never followed: a POST carrying the code and
|
|
48
|
+
* the PKCE verifier must not be forwarded to an unintended host.
|
|
49
|
+
* - 408 / 429 / 5xx are always `OctenNetworkError`, EVEN IF the body claims
|
|
50
|
+
* `invalid_grant` — a server fault dressed up as `invalid_grant` must
|
|
51
|
+
* never trigger credential deletion downstream.
|
|
52
|
+
* - 403 is always `OctenAuthError` (audience/scope/client mismatch;
|
|
53
|
+
* retrying cannot help), independent of the body.
|
|
54
|
+
* - any other 4xx whose body's `error` is `invalid_grant` or
|
|
55
|
+
* `invalid_client` is `OctenAuthError`.
|
|
56
|
+
* - any other 4xx falls back to `OctenAuthError` too: it is not one of the
|
|
57
|
+
* retryable transport codes above, so per "classify by transport first"
|
|
58
|
+
* it can never land in the network bucket.
|
|
59
|
+
*
|
|
60
|
+
* No error message here ever includes `a.code`, `a.verifier`, or a returned
|
|
61
|
+
* access token.
|
|
62
|
+
*/
|
|
63
|
+
export async function exchangeCode(a) {
|
|
64
|
+
const f = a.fetchImpl ?? fetch;
|
|
65
|
+
const body = new URLSearchParams({
|
|
66
|
+
grant_type: "authorization_code",
|
|
67
|
+
code: a.code,
|
|
68
|
+
redirect_uri: a.redirectUri,
|
|
69
|
+
client_id: CLI_CLIENT_ID,
|
|
70
|
+
code_verifier: a.verifier,
|
|
71
|
+
resource: a.resource,
|
|
72
|
+
});
|
|
73
|
+
let res;
|
|
74
|
+
try {
|
|
75
|
+
res = await f(`${a.issuer}/api/oauth/token`, {
|
|
76
|
+
method: "POST",
|
|
77
|
+
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
|
78
|
+
body: body.toString(),
|
|
79
|
+
// The body carries the code and verifier — never let a redirect
|
|
80
|
+
// silently forward them to a different host.
|
|
81
|
+
redirect: "manual",
|
|
82
|
+
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
|
|
83
|
+
});
|
|
84
|
+
}
|
|
85
|
+
catch {
|
|
86
|
+
throw new OctenNetworkError("Could not reach the authorization server; please try again.");
|
|
87
|
+
}
|
|
88
|
+
// redirect: "manual" surfaces a same-implementation 3xx as an
|
|
89
|
+
// "opaqueredirect" response (status 0, no body); a mocked/proxied fetch may
|
|
90
|
+
// instead hand back the raw 3xx directly. Treat either as an error.
|
|
91
|
+
if (res.type === "opaqueredirect" || (res.status >= 300 && res.status < 400)) {
|
|
92
|
+
throw new OctenNetworkError("The authorization server returned an unexpected redirect; please try again.");
|
|
93
|
+
}
|
|
94
|
+
if (res.ok) {
|
|
95
|
+
let payload;
|
|
96
|
+
try {
|
|
97
|
+
payload = await res.json();
|
|
98
|
+
}
|
|
99
|
+
catch {
|
|
100
|
+
throw new OctenNetworkError("The authorization server returned an invalid response; please try again.");
|
|
101
|
+
}
|
|
102
|
+
const accessToken = payload !== null && typeof payload === "object"
|
|
103
|
+
? payload.access_token
|
|
104
|
+
: undefined;
|
|
105
|
+
if (typeof accessToken !== "string" || accessToken.length === 0) {
|
|
106
|
+
throw new OctenNetworkError("The authorization server did not return an access token; please try again.");
|
|
107
|
+
}
|
|
108
|
+
return { accessToken };
|
|
109
|
+
}
|
|
110
|
+
// Transport-layer classification wins over the body, even when the body
|
|
111
|
+
// claims invalid_grant. A 5xx (or 408/429) is a server or infrastructure
|
|
112
|
+
// fault: whatever its body says, the credential is not known to be bad, and
|
|
113
|
+
// classifying it as an auth failure here would propagate upward into
|
|
114
|
+
// deleting a credential that was fine all along.
|
|
115
|
+
if (res.status === 408 || res.status === 429 || res.status >= 500) {
|
|
116
|
+
throw new OctenNetworkError("The authorization server is unavailable; please try again later.");
|
|
117
|
+
}
|
|
118
|
+
if (res.status === 403) {
|
|
119
|
+
throw new OctenAuthError("Authorization was refused. Run `octen login` again.");
|
|
120
|
+
}
|
|
121
|
+
const rawText = await res.text().catch(() => "");
|
|
122
|
+
let payload;
|
|
123
|
+
try {
|
|
124
|
+
payload = rawText ? JSON.parse(rawText) : undefined;
|
|
125
|
+
}
|
|
126
|
+
catch {
|
|
127
|
+
payload = undefined;
|
|
128
|
+
}
|
|
129
|
+
const errorCode = oauthErrorCode(payload);
|
|
130
|
+
if (errorCode === "invalid_grant" || errorCode === "invalid_client") {
|
|
131
|
+
throw new OctenAuthError("The authorization code is no longer valid. Run `octen login` again.");
|
|
132
|
+
}
|
|
133
|
+
// Any remaining 4xx: not one of the recognized transport-retryable codes
|
|
134
|
+
// above, so it is never classified as a network error.
|
|
135
|
+
throw new OctenAuthError(`Token exchange failed (HTTP ${res.status}). Run \`octen login\` again.`);
|
|
136
|
+
}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
/** RFC 7636 code_verifier: 32 random bytes, base64url-encoded (43 chars, >=43 required). */
|
|
2
|
+
export declare function createVerifier(): string;
|
|
3
|
+
/** RFC 7636 S256 code_challenge: base64url(SHA-256(verifier)). */
|
|
4
|
+
export declare function challengeFor(verifier: string): string;
|
|
5
|
+
/** 32 random bytes, base64url-encoded — the OAuth `state` parameter. */
|
|
6
|
+
export declare function createState(): string;
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { randomBytes, createHash } from "node:crypto";
|
|
2
|
+
/** RFC 7636 code_verifier: 32 random bytes, base64url-encoded (43 chars, >=43 required). */
|
|
3
|
+
export function createVerifier() {
|
|
4
|
+
return randomBytes(32).toString("base64url");
|
|
5
|
+
}
|
|
6
|
+
/** RFC 7636 S256 code_challenge: base64url(SHA-256(verifier)). */
|
|
7
|
+
export function challengeFor(verifier) {
|
|
8
|
+
return createHash("sha256").update(verifier).digest("base64url");
|
|
9
|
+
}
|
|
10
|
+
/** 32 random bytes, base64url-encoded — the OAuth `state` parameter. */
|
|
11
|
+
export function createState() {
|
|
12
|
+
return randomBytes(32).toString("base64url");
|
|
13
|
+
}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The 400 response's message.
|
|
3
|
+
*
|
|
4
|
+
* This deliberately does NOT say "already gone". The server returns 400 from
|
|
5
|
+
* three places and the response carries no body to tell them apart:
|
|
6
|
+
*
|
|
7
|
+
* 1. the grant id is unknown → it really is gone
|
|
8
|
+
* 2. the body/grant_id was unparseable → unreachable from this client
|
|
9
|
+
* 3. the revoke was refused after the row was found — e.g. the subject is no
|
|
10
|
+
* longer a joined member of the organization that owns the key, or that
|
|
11
|
+
* organization is deactivated. **The grant is still `active` in this case.**
|
|
12
|
+
*
|
|
13
|
+
* An earlier version asserted case 1 for all three, so a user who had been
|
|
14
|
+
* removed from an organization was told "nothing left to revoke" while a live
|
|
15
|
+
* grant kept its ability to mint credentials — the exact outcome this command's
|
|
16
|
+
* own doc comment says must never happen.
|
|
17
|
+
*
|
|
18
|
+
* Exported because `octen logout` branches on this case for wording. That
|
|
19
|
+
* branch used to match the literal string, so editing this sentence would have
|
|
20
|
+
* silently changed behaviour with no test failure anywhere; importing the
|
|
21
|
+
* constant makes the coupling break at compile time instead.
|
|
22
|
+
*/
|
|
23
|
+
export declare const GRANT_NOT_RECOGNIZED_MESSAGE = "The server did not accept that grant id.";
|
|
24
|
+
/**
|
|
25
|
+
* Revoke a CLI OAuth grant at `POST {issuer}/api/oauth/cli/revoke`.
|
|
26
|
+
*
|
|
27
|
+
* Deliberately not RFC 7009 token revocation. RFC 7009 wants a token to
|
|
28
|
+
* revoke, and by this point `octen logout` has none: the access token was
|
|
29
|
+
* used once at login and discarded, and no refresh token is ever stored — an
|
|
30
|
+
* ostensible refresh token would expire after 30 days anyway, so keeping one
|
|
31
|
+
* for logout would give a revocation path that looks available and silently
|
|
32
|
+
* stops working on idle machines, which are exactly the ones a user logs out
|
|
33
|
+
* from. So this authenticates with the long-lived `apiKey`
|
|
34
|
+
* (header `x-api-key`) and self-certifies via `{ grant_id }` in the body —
|
|
35
|
+
* the server checks that the grant's `api_key_id` matches the key's own id.
|
|
36
|
+
*
|
|
37
|
+
* 200 with `{}` means success, and it is idempotent: revoking an
|
|
38
|
+
* already-revoked grant is also 200.
|
|
39
|
+
*
|
|
40
|
+
* Error classification (mirrors `exchangeForApiKey` in ./exchange.ts):
|
|
41
|
+
* - a fetch-level failure, a redirect, or 408/429/5xx is always
|
|
42
|
+
* `OctenNetworkError` — a transport/infrastructure fault.
|
|
43
|
+
* - 401 (key missing/unknown/inactive), 403 (grant not bound to that key,
|
|
44
|
+
* or not a CLI grant), and 400 (unknown/malformed grant_id) are all
|
|
45
|
+
* `OctenAuthError`.
|
|
46
|
+
*
|
|
47
|
+
* Callers that use this for a best-effort revoke (`octen login`'s step 1)
|
|
48
|
+
* must catch every rejection themselves — nothing here is ever meant to
|
|
49
|
+
* block a caller that only wants "try, and don't wait".
|
|
50
|
+
*
|
|
51
|
+
* No error message here ever includes `a.apiKey` or `a.grantId`.
|
|
52
|
+
*/
|
|
53
|
+
export declare function revokeCliGrant(a: {
|
|
54
|
+
issuer: string;
|
|
55
|
+
apiKey: string;
|
|
56
|
+
grantId: string;
|
|
57
|
+
fetchImpl?: typeof fetch;
|
|
58
|
+
}): Promise<void>;
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
import { OctenAuthError, OctenNetworkError } from "../api/errors.js";
|
|
2
|
+
import { REQUEST_TIMEOUT_MS } from "./constants.js";
|
|
3
|
+
/**
|
|
4
|
+
* The 400 response's message.
|
|
5
|
+
*
|
|
6
|
+
* This deliberately does NOT say "already gone". The server returns 400 from
|
|
7
|
+
* three places and the response carries no body to tell them apart:
|
|
8
|
+
*
|
|
9
|
+
* 1. the grant id is unknown → it really is gone
|
|
10
|
+
* 2. the body/grant_id was unparseable → unreachable from this client
|
|
11
|
+
* 3. the revoke was refused after the row was found — e.g. the subject is no
|
|
12
|
+
* longer a joined member of the organization that owns the key, or that
|
|
13
|
+
* organization is deactivated. **The grant is still `active` in this case.**
|
|
14
|
+
*
|
|
15
|
+
* An earlier version asserted case 1 for all three, so a user who had been
|
|
16
|
+
* removed from an organization was told "nothing left to revoke" while a live
|
|
17
|
+
* grant kept its ability to mint credentials — the exact outcome this command's
|
|
18
|
+
* own doc comment says must never happen.
|
|
19
|
+
*
|
|
20
|
+
* Exported because `octen logout` branches on this case for wording. That
|
|
21
|
+
* branch used to match the literal string, so editing this sentence would have
|
|
22
|
+
* silently changed behaviour with no test failure anywhere; importing the
|
|
23
|
+
* constant makes the coupling break at compile time instead.
|
|
24
|
+
*/
|
|
25
|
+
export const GRANT_NOT_RECOGNIZED_MESSAGE = "The server did not accept that grant id.";
|
|
26
|
+
/**
|
|
27
|
+
* Revoke a CLI OAuth grant at `POST {issuer}/api/oauth/cli/revoke`.
|
|
28
|
+
*
|
|
29
|
+
* Deliberately not RFC 7009 token revocation. RFC 7009 wants a token to
|
|
30
|
+
* revoke, and by this point `octen logout` has none: the access token was
|
|
31
|
+
* used once at login and discarded, and no refresh token is ever stored — an
|
|
32
|
+
* ostensible refresh token would expire after 30 days anyway, so keeping one
|
|
33
|
+
* for logout would give a revocation path that looks available and silently
|
|
34
|
+
* stops working on idle machines, which are exactly the ones a user logs out
|
|
35
|
+
* from. So this authenticates with the long-lived `apiKey`
|
|
36
|
+
* (header `x-api-key`) and self-certifies via `{ grant_id }` in the body —
|
|
37
|
+
* the server checks that the grant's `api_key_id` matches the key's own id.
|
|
38
|
+
*
|
|
39
|
+
* 200 with `{}` means success, and it is idempotent: revoking an
|
|
40
|
+
* already-revoked grant is also 200.
|
|
41
|
+
*
|
|
42
|
+
* Error classification (mirrors `exchangeForApiKey` in ./exchange.ts):
|
|
43
|
+
* - a fetch-level failure, a redirect, or 408/429/5xx is always
|
|
44
|
+
* `OctenNetworkError` — a transport/infrastructure fault.
|
|
45
|
+
* - 401 (key missing/unknown/inactive), 403 (grant not bound to that key,
|
|
46
|
+
* or not a CLI grant), and 400 (unknown/malformed grant_id) are all
|
|
47
|
+
* `OctenAuthError`.
|
|
48
|
+
*
|
|
49
|
+
* Callers that use this for a best-effort revoke (`octen login`'s step 1)
|
|
50
|
+
* must catch every rejection themselves — nothing here is ever meant to
|
|
51
|
+
* block a caller that only wants "try, and don't wait".
|
|
52
|
+
*
|
|
53
|
+
* No error message here ever includes `a.apiKey` or `a.grantId`.
|
|
54
|
+
*/
|
|
55
|
+
export async function revokeCliGrant(a) {
|
|
56
|
+
const f = a.fetchImpl ?? fetch;
|
|
57
|
+
let res;
|
|
58
|
+
try {
|
|
59
|
+
res = await f(`${a.issuer}/api/oauth/cli/revoke`, {
|
|
60
|
+
method: "POST",
|
|
61
|
+
headers: { "x-api-key": a.apiKey, "content-type": "application/json" },
|
|
62
|
+
body: JSON.stringify({ grant_id: a.grantId }),
|
|
63
|
+
// This request carries a long-lived API key — never let a redirect
|
|
64
|
+
// silently forward it to a different host.
|
|
65
|
+
redirect: "manual",
|
|
66
|
+
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
|
|
67
|
+
});
|
|
68
|
+
}
|
|
69
|
+
catch {
|
|
70
|
+
throw new OctenNetworkError("Could not reach the authorization server; please try again.");
|
|
71
|
+
}
|
|
72
|
+
if (res.type === "opaqueredirect" || (res.status >= 300 && res.status < 400)) {
|
|
73
|
+
throw new OctenNetworkError("The authorization server returned an unexpected redirect; please try again.");
|
|
74
|
+
}
|
|
75
|
+
if (res.status === 408 || res.status === 429 || res.status >= 500) {
|
|
76
|
+
throw new OctenNetworkError("The authorization server is unavailable; please retry later.");
|
|
77
|
+
}
|
|
78
|
+
if (res.status === 401) {
|
|
79
|
+
throw new OctenAuthError("The stored API key is no longer valid.");
|
|
80
|
+
}
|
|
81
|
+
if (res.status === 403) {
|
|
82
|
+
throw new OctenAuthError("That grant is not bound to the stored API key.");
|
|
83
|
+
}
|
|
84
|
+
if (res.status === 400) {
|
|
85
|
+
throw new OctenAuthError(GRANT_NOT_RECOGNIZED_MESSAGE);
|
|
86
|
+
}
|
|
87
|
+
if (!res.ok) {
|
|
88
|
+
throw new OctenAuthError(`Revoke failed (HTTP ${res.status}).`);
|
|
89
|
+
}
|
|
90
|
+
// 200: success, idempotent. Body is `{}` and carries nothing to read.
|
|
91
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
export declare const CREDENTIALS_VERSION = 1;
|
|
2
|
+
export type Credentials = {
|
|
3
|
+
version: 1;
|
|
4
|
+
source: "api-key";
|
|
5
|
+
apiKey: string;
|
|
6
|
+
} | {
|
|
7
|
+
version: 1;
|
|
8
|
+
source: "login";
|
|
9
|
+
issuer: string;
|
|
10
|
+
resource: string;
|
|
11
|
+
apiKey: string;
|
|
12
|
+
/**
|
|
13
|
+
* Epoch seconds, or `null` for "does not expire" — which is what the
|
|
14
|
+
* server sends for every credential today. Kept as a real field so
|
|
15
|
+
* that if short-lived keys ever ship, the stored format already
|
|
16
|
+
* carries the deadline and no migration is needed.
|
|
17
|
+
*/
|
|
18
|
+
apiKeyExpiresAt: number | null;
|
|
19
|
+
/**
|
|
20
|
+
* The OAuth grant behind this credential. This is the only record on
|
|
21
|
+
* the machine of which dashboard authorization corresponds to this
|
|
22
|
+
* install, so `octen whoami` prints it and `octen logout` revokes by
|
|
23
|
+
* it. Any command that destroys this file must print it first:
|
|
24
|
+
* afterwards the grant is still listed server-side with nothing local
|
|
25
|
+
* able to name it.
|
|
26
|
+
*/
|
|
27
|
+
grantId: string;
|
|
28
|
+
accountId?: string;
|
|
29
|
+
accountType?: string;
|
|
30
|
+
};
|
|
31
|
+
export declare function credentialsPath(home: string): string;
|
|
32
|
+
export declare function readCredentials(home: string): Credentials | undefined;
|
|
33
|
+
export declare function writeCredentials(home: string, c: Credentials): void;
|
|
34
|
+
export declare function deleteCredentials(home: string): boolean;
|
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
import { mkdirSync, writeFileSync, renameSync, readFileSync, existsSync, unlinkSync } from "node:fs";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import { randomBytes } from "node:crypto";
|
|
4
|
+
import { OctenValidationError } from "../api/errors.js";
|
|
5
|
+
import { assertSecureOrigin } from "./constants.js";
|
|
6
|
+
export const CREDENTIALS_VERSION = 1;
|
|
7
|
+
/** The way out of any corrupt/unreadable/unknown-version credentials file. */
|
|
8
|
+
const RECOVERY_HINT = "delete ~/.octen/credentials.json and run `octen login` again.";
|
|
9
|
+
export function credentialsPath(home) {
|
|
10
|
+
return join(home, ".octen", "credentials.json");
|
|
11
|
+
}
|
|
12
|
+
function fail(reason) {
|
|
13
|
+
// Never echo file contents here — only a fixed, generic reason plus the recovery hint.
|
|
14
|
+
throw new OctenValidationError(`Invalid credentials file (${reason}); ${RECOVERY_HINT}`);
|
|
15
|
+
}
|
|
16
|
+
function isNonEmptyString(value) {
|
|
17
|
+
return typeof value === "string" && value.length > 0;
|
|
18
|
+
}
|
|
19
|
+
function isOptionalString(value) {
|
|
20
|
+
return value === undefined || typeof value === "string";
|
|
21
|
+
}
|
|
22
|
+
function isValidExpiry(value) {
|
|
23
|
+
return value === null || (typeof value === "number" && Number.isFinite(value) && Number.isInteger(value) && value > 0);
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Validate a parsed credentials object field by field, per `source`. Never
|
|
27
|
+
* half-reads: a file missing a required field throws rather than producing an
|
|
28
|
+
* object with `undefined` in later branches.
|
|
29
|
+
*/
|
|
30
|
+
function validate(obj) {
|
|
31
|
+
if (obj === null || typeof obj !== "object")
|
|
32
|
+
fail("not an object");
|
|
33
|
+
const rec = obj;
|
|
34
|
+
if (rec.version !== CREDENTIALS_VERSION)
|
|
35
|
+
fail("unknown version");
|
|
36
|
+
if (rec.source === "api-key") {
|
|
37
|
+
if (!isNonEmptyString(rec.apiKey))
|
|
38
|
+
fail("missing apiKey");
|
|
39
|
+
return { version: 1, source: "api-key", apiKey: rec.apiKey };
|
|
40
|
+
}
|
|
41
|
+
if (rec.source === "login") {
|
|
42
|
+
if (!isNonEmptyString(rec.issuer))
|
|
43
|
+
fail("missing issuer");
|
|
44
|
+
// The stored issuer is not inert data: `login`'s step-1 cleanup and
|
|
45
|
+
// `logout` both POST this credential's API key to it. So it gets exactly
|
|
46
|
+
// the same https-or-loopback rule as OCTEN_AUTH_ISSUER — a file naming a
|
|
47
|
+
// plaintext host would otherwise be a standing instruction to mail an
|
|
48
|
+
// account-wide key there in the clear.
|
|
49
|
+
try {
|
|
50
|
+
assertSecureOrigin("credentials.issuer", rec.issuer);
|
|
51
|
+
}
|
|
52
|
+
catch {
|
|
53
|
+
fail("insecure issuer");
|
|
54
|
+
}
|
|
55
|
+
if (!isNonEmptyString(rec.resource))
|
|
56
|
+
fail("missing resource");
|
|
57
|
+
if (!isNonEmptyString(rec.apiKey))
|
|
58
|
+
fail("missing apiKey");
|
|
59
|
+
if (!isValidExpiry(rec.apiKeyExpiresAt))
|
|
60
|
+
fail("invalid apiKeyExpiresAt");
|
|
61
|
+
if (!isNonEmptyString(rec.grantId))
|
|
62
|
+
fail("missing grantId");
|
|
63
|
+
if (!isOptionalString(rec.accountId))
|
|
64
|
+
fail("invalid accountId");
|
|
65
|
+
if (!isOptionalString(rec.accountType))
|
|
66
|
+
fail("invalid accountType");
|
|
67
|
+
const creds = {
|
|
68
|
+
version: 1,
|
|
69
|
+
source: "login",
|
|
70
|
+
issuer: rec.issuer,
|
|
71
|
+
resource: rec.resource,
|
|
72
|
+
apiKey: rec.apiKey,
|
|
73
|
+
apiKeyExpiresAt: rec.apiKeyExpiresAt,
|
|
74
|
+
grantId: rec.grantId,
|
|
75
|
+
};
|
|
76
|
+
if (rec.accountId !== undefined)
|
|
77
|
+
creds.accountId = rec.accountId;
|
|
78
|
+
if (rec.accountType !== undefined)
|
|
79
|
+
creds.accountType = rec.accountType;
|
|
80
|
+
return creds;
|
|
81
|
+
}
|
|
82
|
+
fail("unknown source");
|
|
83
|
+
}
|
|
84
|
+
/**
|
|
85
|
+
* Whitelist exactly the fields that belong to each source, so an accidental
|
|
86
|
+
* extra property on the passed-in object (e.g. a smuggled `refreshToken`)
|
|
87
|
+
* never reaches disk. The one that matters is a refresh token: this design
|
|
88
|
+
* never stores one, and an accidental property on a passed-in object must
|
|
89
|
+
* not be able to quietly introduce a second long-lived secret into the
|
|
90
|
+
* credentials file.
|
|
91
|
+
*/
|
|
92
|
+
function serialize(c) {
|
|
93
|
+
const obj = c.source === "api-key"
|
|
94
|
+
? { version: c.version, source: c.source, apiKey: c.apiKey }
|
|
95
|
+
: {
|
|
96
|
+
version: c.version,
|
|
97
|
+
source: c.source,
|
|
98
|
+
issuer: c.issuer,
|
|
99
|
+
resource: c.resource,
|
|
100
|
+
apiKey: c.apiKey,
|
|
101
|
+
apiKeyExpiresAt: c.apiKeyExpiresAt,
|
|
102
|
+
grantId: c.grantId,
|
|
103
|
+
...(c.accountId !== undefined ? { accountId: c.accountId } : {}),
|
|
104
|
+
...(c.accountType !== undefined ? { accountType: c.accountType } : {}),
|
|
105
|
+
};
|
|
106
|
+
return JSON.stringify(obj, null, 2);
|
|
107
|
+
}
|
|
108
|
+
export function readCredentials(home) {
|
|
109
|
+
const path = credentialsPath(home);
|
|
110
|
+
if (!existsSync(path))
|
|
111
|
+
return undefined;
|
|
112
|
+
const raw = readFileSync(path, "utf8");
|
|
113
|
+
let parsed;
|
|
114
|
+
try {
|
|
115
|
+
parsed = JSON.parse(raw);
|
|
116
|
+
}
|
|
117
|
+
catch {
|
|
118
|
+
fail("corrupt JSON");
|
|
119
|
+
}
|
|
120
|
+
return validate(parsed);
|
|
121
|
+
}
|
|
122
|
+
export function writeCredentials(home, c) {
|
|
123
|
+
const dir = join(home, ".octen");
|
|
124
|
+
mkdirSync(dir, { recursive: true });
|
|
125
|
+
const path = credentialsPath(home);
|
|
126
|
+
const tmp = join(dir, `.credentials.json.tmp-${process.pid}-${randomBytes(6).toString("hex")}`);
|
|
127
|
+
const json = serialize(c);
|
|
128
|
+
try {
|
|
129
|
+
writeFileSync(tmp, json, { mode: 0o600 });
|
|
130
|
+
renameSync(tmp, path);
|
|
131
|
+
}
|
|
132
|
+
catch (err) {
|
|
133
|
+
try {
|
|
134
|
+
if (existsSync(tmp))
|
|
135
|
+
unlinkSync(tmp);
|
|
136
|
+
}
|
|
137
|
+
catch {
|
|
138
|
+
// best-effort cleanup only
|
|
139
|
+
}
|
|
140
|
+
throw err;
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
export function deleteCredentials(home) {
|
|
144
|
+
const path = credentialsPath(home);
|
|
145
|
+
if (!existsSync(path))
|
|
146
|
+
return false;
|
|
147
|
+
unlinkSync(path);
|
|
148
|
+
return true;
|
|
149
|
+
}
|
package/dist/cli.js
CHANGED
|
@@ -16,6 +16,9 @@ import { registerVideoSearch } from "./commands/videoSearch.js";
|
|
|
16
16
|
import { registerConfigureMcp } from "./commands/configureMcp.js";
|
|
17
17
|
import { registerConfigureSkills } from "./commands/configureSkills.js";
|
|
18
18
|
import { registerReset } from "./commands/reset.js";
|
|
19
|
+
import { registerLogin } from "./commands/login.js";
|
|
20
|
+
import { registerLogout } from "./commands/logout.js";
|
|
21
|
+
import { registerWhoami } from "./commands/whoami.js";
|
|
19
22
|
import { registerCompletion } from "./commands/completion.js";
|
|
20
23
|
function resolveVersion() {
|
|
21
24
|
if (typeof __OCTEN_VERSION__ !== "undefined")
|
|
@@ -45,6 +48,9 @@ registerEmbed(program);
|
|
|
45
48
|
registerVlEmbed(program);
|
|
46
49
|
registerImageSearch(program);
|
|
47
50
|
registerVideoSearch(program);
|
|
51
|
+
registerLogin(program);
|
|
52
|
+
registerLogout(program);
|
|
53
|
+
registerWhoami(program);
|
|
48
54
|
// Register LAST so introspection sees every command and its flags.
|
|
49
55
|
registerCompletion(program);
|
|
50
56
|
program.parseAsync().catch((err) => {
|
|
@@ -2,7 +2,7 @@ import { ENDPOINTS } from "../api/constants.js";
|
|
|
2
2
|
import { buildBroadSearchRequest, } from "../api/search.js";
|
|
3
3
|
import { chooseMode, emit } from "../output/render.js";
|
|
4
4
|
import { renderBroadSearch } from "../output/pretty/broadSearch.js";
|
|
5
|
-
import { makeClient, parseIntOpt } from "./utils.js";
|
|
5
|
+
import { makeClient, parseCsvOpt, parseIntOpt } from "./utils.js";
|
|
6
6
|
export function registerBroadSearch(program) {
|
|
7
7
|
program.command("broad-search")
|
|
8
8
|
.alias("broad")
|
|
@@ -11,15 +11,15 @@ export function registerBroadSearch(program) {
|
|
|
11
11
|
.option("--max-queries <n>", "decompose into up to N sub-queries (1-30; default 5, raise toward 30 for surveys/research)", parseIntOpt("--max-queries"))
|
|
12
12
|
.option("--topic <t>", "general|news")
|
|
13
13
|
.option("-n, --count <n>", "results per sub-query 1-100", parseIntOpt("--count"))
|
|
14
|
-
.option("--include-domains <list>", "comma list", (
|
|
15
|
-
.option("--exclude-domains <list>", "comma list", (
|
|
16
|
-
.option("--include-text <list>", "comma list", (
|
|
17
|
-
.option("--exclude-text <list>", "comma list", (
|
|
14
|
+
.option("--include-domains <list>", "comma list", parseCsvOpt("--include-domains"))
|
|
15
|
+
.option("--exclude-domains <list>", "comma list", parseCsvOpt("--exclude-domains"))
|
|
16
|
+
.option("--include-text <list>", "comma list", parseCsvOpt("--include-text"))
|
|
17
|
+
.option("--exclude-text <list>", "comma list", parseCsvOpt("--exclude-text"))
|
|
18
18
|
.option("--time-basis <b>", "auto|published|crawled").option("--time-range <r>", "day|week|month|year (or d|w|m|y)")
|
|
19
19
|
.option("--start-time <when>", "YYYY-MM-DD or ISO datetime (e.g. 2024-01-01T00:00:00Z)")
|
|
20
20
|
.option("--end-time <when>", "YYYY-MM-DD or ISO datetime (e.g. 2024-12-31T23:59:59Z)")
|
|
21
21
|
.option("--format <f>", "text|markdown").option("--safesearch <s>", "off|strict")
|
|
22
|
-
.option("--language <list>", "ISO 639-1 codes, comma-separated, e.g. en,ja", (
|
|
22
|
+
.option("--language <list>", "ISO 639-1 codes, comma-separated, e.g. en,ja", parseCsvOpt("--language"))
|
|
23
23
|
.option("--highlight").option("--highlight-max-tokens <n>", "max tokens per highlight", parseIntOpt("--highlight-max-tokens"))
|
|
24
24
|
.option("--full-content").option("--full-content-max-tokens <n>", "max tokens per result", parseIntOpt("--full-content-max-tokens"))
|
|
25
25
|
.option("--images")
|
package/dist/commands/chat.js
CHANGED
|
@@ -3,11 +3,10 @@ import { ENDPOINTS } from "../api/constants.js";
|
|
|
3
3
|
import { buildChatRequest, } from "../api/chat.js";
|
|
4
4
|
import pc from "picocolors";
|
|
5
5
|
import { parseSSE } from "../api/sse.js";
|
|
6
|
-
import { OctenValidationError } from "../api/errors.js";
|
|
6
|
+
import { errorMessage, OctenStreamError, OctenValidationError } from "../api/errors.js";
|
|
7
7
|
import { chooseMode, emit } from "../output/render.js";
|
|
8
8
|
import { renderChat } from "../output/pretty/chat.js";
|
|
9
|
-
import { makeClient, parseIntOpt, parseFloatOpt } from "./utils.js";
|
|
10
|
-
const splitList = (v) => v.split(",").map((s) => s.trim()).filter(Boolean);
|
|
9
|
+
import { makeClient, parseCsvOpt, parseIntOpt, parseFloatOpt } from "./utils.js";
|
|
11
10
|
/**
|
|
12
11
|
* Drive an interactive chat REPL until the input closes (EOF, /exit, /quit).
|
|
13
12
|
* `send` performs one round-trip given the running history and returns the reply.
|
|
@@ -85,17 +84,17 @@ export function registerChat(program) {
|
|
|
85
84
|
.option("--search-max-queries <n>", "octen_broad_search: max sub-queries (1-30, default 5)", parseIntOpt("--search-max-queries"))
|
|
86
85
|
.option("--search-topic <t>", "search tools: general|news")
|
|
87
86
|
.option("--search-count <n>", "search tools: results per search (1-100)", parseIntOpt("--search-count"))
|
|
88
|
-
.option("--search-include-domains <list>", "search tools: comma-separated domains to include",
|
|
89
|
-
.option("--search-exclude-domains <list>", "search tools: comma-separated domains to exclude",
|
|
90
|
-
.option("--search-include-text <list>", "search tools: comma-separated phrases to require (max 5)",
|
|
91
|
-
.option("--search-exclude-text <list>", "search tools: comma-separated phrases to exclude (max 5)",
|
|
87
|
+
.option("--search-include-domains <list>", "search tools: comma-separated domains to include", parseCsvOpt("--search-include-domains"))
|
|
88
|
+
.option("--search-exclude-domains <list>", "search tools: comma-separated domains to exclude", parseCsvOpt("--search-exclude-domains"))
|
|
89
|
+
.option("--search-include-text <list>", "search tools: comma-separated phrases to require (max 5)", parseCsvOpt("--search-include-text"))
|
|
90
|
+
.option("--search-exclude-text <list>", "search tools: comma-separated phrases to exclude (max 5)", parseCsvOpt("--search-exclude-text"))
|
|
92
91
|
.option("--search-time-basis <b>", "search tools: auto|published|crawled")
|
|
93
92
|
.option("--search-time-range <r>", "search tools: day|week|month|year (or d|w|m|y)")
|
|
94
93
|
.option("--search-start-time <when>", "search tools: start time filter")
|
|
95
94
|
.option("--search-end-time <when>", "search tools: end time filter")
|
|
96
95
|
.option("--search-format <f>", "search tools: markdown|text")
|
|
97
96
|
.option("--search-safesearch <s>", "search tools: off|strict")
|
|
98
|
-
.option("--search-language <list>", "search tools: ISO 639-1 codes, comma-separated, e.g. en,ja",
|
|
97
|
+
.option("--search-language <list>", "search tools: ISO 639-1 codes, comma-separated, e.g. en,ja", parseCsvOpt("--search-language"))
|
|
99
98
|
.option("--search-include-images", "search tools: include image results")
|
|
100
99
|
.option("--search-full-content", "search tools: include full page content")
|
|
101
100
|
.option("--search-full-content-max-tokens <n>", "search tools: max tokens for full content", parseIntOpt("--search-full-content-max-tokens"))
|
|
@@ -205,6 +204,11 @@ export function registerChat(program) {
|
|
|
205
204
|
const sources = [];
|
|
206
205
|
for await (const ev of parseSSE(httpRes)) {
|
|
207
206
|
const e = ev;
|
|
207
|
+
// A typed error event ends the turn as a failure. Content already
|
|
208
|
+
// written to stdout stays; the non-zero exit is what callers check.
|
|
209
|
+
if (e.type === "error" || e.error != null) {
|
|
210
|
+
throw new OctenStreamError(errorMessage(e.error ?? e, "stream returned an error"));
|
|
211
|
+
}
|
|
208
212
|
if (e.type === "search_done") {
|
|
209
213
|
if (!noted) {
|
|
210
214
|
process.stderr.write("(web search complete)\n");
|