dsh-coding-subscription-oauth 0.6.3 → 0.6.5
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/CHANGELOG.md +33 -0
- package/CONTRIBUTING.md +13 -4
- package/INSTALL.md +7 -5
- package/README.de.md +6 -6
- package/README.es.md +6 -6
- package/README.fr.md +6 -6
- package/README.ja.md +6 -6
- package/README.ko.md +6 -6
- package/README.md +6 -6
- package/README.pt-BR.md +6 -6
- package/README.ru.md +6 -6
- package/README.zh-CN.md +6 -6
- package/docs/00-project-rules.md +4 -4
- package/docs/02-architecture.md +7 -3
- package/docs/02-architecture.zh-CN.md +7 -3
- package/lib/bin.js +1333 -569
- package/lib/bin.js.map +4 -4
- package/lib/client.js +1 -1
- package/lib/client.js.map +2 -2
- package/lib/gateway-protocol.d.ts +3 -46
- package/lib/gateway-protocol.d.ts.map +1 -1
- package/lib/gateway-routes.d.ts.map +1 -1
- package/lib/grok-errors.d.ts +2 -12
- package/lib/grok-errors.d.ts.map +1 -1
- package/lib/grok-imagine/client.d.ts +73 -0
- package/lib/grok-imagine/client.d.ts.map +1 -0
- package/lib/grok-imagine/index.d.ts +8 -0
- package/lib/grok-imagine/index.d.ts.map +1 -0
- package/lib/grok-imagine/net.d.ts +10 -0
- package/lib/grok-imagine/net.d.ts.map +1 -0
- package/lib/grok-imagine/parse.d.ts +20 -0
- package/lib/grok-imagine/parse.d.ts.map +1 -0
- package/lib/grok-imagine/types.d.ts +191 -0
- package/lib/grok-imagine/types.d.ts.map +1 -0
- package/lib/grok-imagine.d.ts +3 -263
- package/lib/grok-imagine.d.ts.map +1 -1
- package/lib/http-json.d.ts +2 -9
- package/lib/http-json.d.ts.map +1 -1
- package/lib/index.js +1395 -26178
- package/lib/index.js.map +4 -4
- package/lib/kimi-errors.d.ts +2 -12
- package/lib/kimi-errors.d.ts.map +1 -1
- package/lib/runtime/gateway-protocol.d.ts +47 -0
- package/lib/runtime/gateway-protocol.d.ts.map +1 -0
- package/lib/runtime/grok-errors.d.ts +13 -0
- package/lib/runtime/grok-errors.d.ts.map +1 -0
- package/lib/runtime/http-json.d.ts +10 -0
- package/lib/runtime/http-json.d.ts.map +1 -0
- package/lib/runtime/kimi-errors.d.ts +13 -0
- package/lib/runtime/kimi-errors.d.ts.map +1 -0
- package/package.json +12 -7
- package/scripts/release.mjs +1 -0
- package/src/adapter.ts +0 -348
- package/src/alias-adapter.ts +0 -147
- package/src/auth-routes.ts +0 -921
- package/src/auth.ts +0 -67
- package/src/bin.ts +0 -350
- package/src/capability-routes.ts +0 -279
- package/src/capability-runtime.ts +0 -314
- package/src/capability-settings.ts +0 -671
- package/src/capability-tools.ts +0 -685
- package/src/catalog.ts +0 -271
- package/src/client/GrokBuildSettings.tsx +0 -771
- package/src/client/api.ts +0 -88
- package/src/client/components/AboutTab.tsx +0 -30
- package/src/client/components/AccountsTab.tsx +0 -241
- package/src/client/components/Badge.tsx +0 -33
- package/src/client/components/CapabilitiesTab.tsx +0 -265
- package/src/client/components/CliPullPreview.tsx +0 -116
- package/src/client/components/CopyButton.tsx +0 -57
- package/src/client/components/GatewayTab.tsx +0 -469
- package/src/client/components/NoticeBanner.tsx +0 -46
- package/src/client/components/ProgressBar.tsx +0 -53
- package/src/client/components/ProviderCard.tsx +0 -606
- package/src/client/components/SettingsTabs.tsx +0 -75
- package/src/client/components/ToggleSwitch.tsx +0 -71
- package/src/client/constants.ts +0 -230
- package/src/client/display.ts +0 -61
- package/src/client/dshClientAdapter.ts +0 -127
- package/src/client/gatewaySnippets.ts +0 -37
- package/src/client/index.tsx +0 -156
- package/src/client/locales.ts +0 -540
- package/src/client/microStyles.ts +0 -52
- package/src/client/parsers.ts +0 -398
- package/src/client/styles.ts +0 -325
- package/src/client/types.ts +0 -199
- package/src/codex-http.ts +0 -447
- package/src/codex-images.ts +0 -503
- package/src/codex-model-capabilities.ts +0 -320
- package/src/codex-search.ts +0 -245
- package/src/codex-usage.ts +0 -263
- package/src/compatibility.ts +0 -55
- package/src/dsh-host-adapter.ts +0 -173
- package/src/gateway-anthropic-messages.ts +0 -84
- package/src/gateway-auth.ts +0 -102
- package/src/gateway-backend.ts +0 -274
- package/src/gateway-body.ts +0 -49
- package/src/gateway-config.ts +0 -76
- package/src/gateway-http.ts +0 -104
- package/src/gateway-openai-chat.ts +0 -124
- package/src/gateway-openai-responses.ts +0 -53
- package/src/gateway-parse.ts +0 -224
- package/src/gateway-protocol.ts +0 -52
- package/src/gateway-routes.ts +0 -158
- package/src/gateway.ts +0 -258
- package/src/grok-errors.ts +0 -24
- package/src/grok-imagine.ts +0 -1627
- package/src/grok-import.ts +0 -151
- package/src/http-json.ts +0 -82
- package/src/ids.ts +0 -59
- package/src/imagine-routes.ts +0 -463
- package/src/index.ts +0 -735
- package/src/invariant.ts +0 -17
- package/src/kimi-errors.ts +0 -26
- package/src/media-store.ts +0 -927
- package/src/oauth-import-routes.ts +0 -324
- package/src/oauth-providers.ts +0 -152
- package/src/oauth-session.ts +0 -183
- package/src/oauth-sources.ts +0 -1104
- package/src/oauth.ts +0 -620
- package/src/provider.ts +0 -128
- package/src/proxy.ts +0 -11
- package/src/redact.ts +0 -72
- package/src/session.ts +0 -218
- package/src/store.ts +0 -217
- package/src/web-origin.ts +0 -296
- package/src/web-routes.ts +0 -38
package/src/provider.ts
DELETED
|
@@ -1,128 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Grok Build provider: a pi-ai provider pointed at the official Grok CLI
|
|
3
|
-
* coding backend (`cli-chat-proxy.grok.com`) carrying the CLI fingerprint
|
|
4
|
-
* headers the risk-control middleware requires.
|
|
5
|
-
* @module dsh-coding-subscription-oauth/provider
|
|
6
|
-
*/
|
|
7
|
-
|
|
8
|
-
import type { Api, Model, Provider, ThinkingLevelMap } from "@earendil-works/pi-ai";
|
|
9
|
-
import { createProvider } from "@earendil-works/pi-ai";
|
|
10
|
-
import { openAIResponsesApi } from "@earendil-works/pi-ai/api/openai-responses.lazy";
|
|
11
|
-
import { GROK_BUILD_ROUTE } from "./ids.ts";
|
|
12
|
-
|
|
13
|
-
/**
|
|
14
|
-
* Grok Build cannot disable reasoning (`reasoning_effort: "none"` is 400).
|
|
15
|
-
* pi-ai treats an absent `xhigh`/`max` key as unsupported, so those levels
|
|
16
|
-
* must be declared explicitly when the model offers them.
|
|
17
|
-
*/
|
|
18
|
-
export function grokBuildReasoningMap(levels: readonly ("low" | "medium" | "high" | "xhigh")[]): ThinkingLevelMap {
|
|
19
|
-
const offered = new Set(levels);
|
|
20
|
-
return {
|
|
21
|
-
off: null,
|
|
22
|
-
minimal: null,
|
|
23
|
-
low: offered.has("low") ? "low" : null,
|
|
24
|
-
medium: offered.has("medium") ? "medium" : null,
|
|
25
|
-
high: offered.has("high") ? "high" : null,
|
|
26
|
-
xhigh: offered.has("xhigh") ? "xhigh" : null,
|
|
27
|
-
max: null,
|
|
28
|
-
};
|
|
29
|
-
}
|
|
30
|
-
|
|
31
|
-
/** Inference backend base URL (Responses API lives under `${baseUrl}/responses`). */
|
|
32
|
-
export const GROK_BUILD_BASE_URL = "https://cli-chat-proxy.grok.com/v1";
|
|
33
|
-
|
|
34
|
-
/** Account model catalog endpoint fetched by the official CLI. */
|
|
35
|
-
export const GROK_BUILD_MODELS_URL = `${GROK_BUILD_BASE_URL}/models-v2`;
|
|
36
|
-
|
|
37
|
-
/**
|
|
38
|
-
* Official Grok CLI version this plugin fingerprints as.
|
|
39
|
-
* Track the `@xai-official/grok` npm release stream; make overridable via
|
|
40
|
-
* GROK_BUILD_CLIENT_VERSION for urgent drift fixes without a release.
|
|
41
|
-
*/
|
|
42
|
-
export const GROK_CLIENT_VERSION: string = process.env["GROK_BUILD_CLIENT_VERSION"] ?? "0.1.220";
|
|
43
|
-
|
|
44
|
-
/**
|
|
45
|
-
* Fingerprint headers required by the Grok Build middleware. Missing headers
|
|
46
|
-
* are a known 403 trigger (codex-app-transfer field notes, 2026-07).
|
|
47
|
-
*/
|
|
48
|
-
export function grokBuildFingerprintHeaders(): Record<string, string> {
|
|
49
|
-
return {
|
|
50
|
-
"X-XAI-Token-Auth": "xai-grok-cli",
|
|
51
|
-
"x-grok-client-identifier": "grok-shell",
|
|
52
|
-
"x-grok-client-version": GROK_CLIENT_VERSION,
|
|
53
|
-
"User-Agent": `grok-shell/${GROK_CLIENT_VERSION}`,
|
|
54
|
-
};
|
|
55
|
-
}
|
|
56
|
-
|
|
57
|
-
/** Static baseline catalog, used until a live `/models-v2` listing succeeds. */
|
|
58
|
-
export function grokBuildBaselineModels(): Model<"openai-responses">[] {
|
|
59
|
-
return [
|
|
60
|
-
{
|
|
61
|
-
id: "grok-4.5",
|
|
62
|
-
name: "Grok 4.5",
|
|
63
|
-
api: "openai-responses",
|
|
64
|
-
provider: GROK_BUILD_ROUTE,
|
|
65
|
-
baseUrl: GROK_BUILD_BASE_URL,
|
|
66
|
-
reasoning: true,
|
|
67
|
-
// Official xAI docs + live /models-v2: grok-4.5 is low/medium/high only.
|
|
68
|
-
thinkingLevelMap: grokBuildReasoningMap(["low", "medium", "high"]),
|
|
69
|
-
input: ["text", "image"],
|
|
70
|
-
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
|
|
71
|
-
contextWindow: 500_000,
|
|
72
|
-
maxTokens: 128_000,
|
|
73
|
-
},
|
|
74
|
-
{
|
|
75
|
-
id: "grok-4.6",
|
|
76
|
-
name: "Grok 4.6",
|
|
77
|
-
api: "openai-responses",
|
|
78
|
-
provider: GROK_BUILD_ROUTE,
|
|
79
|
-
baseUrl: GROK_BUILD_BASE_URL,
|
|
80
|
-
reasoning: true,
|
|
81
|
-
// grok-4.6 and later advertise xhigh. pi-ai hides xhigh unless this key
|
|
82
|
-
// is an explicit non-null mapping (absent !== supported).
|
|
83
|
-
thinkingLevelMap: grokBuildReasoningMap(["low", "medium", "high", "xhigh"]),
|
|
84
|
-
input: ["text", "image"],
|
|
85
|
-
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
|
|
86
|
-
contextWindow: 500_000,
|
|
87
|
-
maxTokens: 128_000,
|
|
88
|
-
},
|
|
89
|
-
{
|
|
90
|
-
id: "grok-composer-2.5-fast",
|
|
91
|
-
name: "Grok Composer 2.5 Fast",
|
|
92
|
-
api: "openai-responses",
|
|
93
|
-
provider: GROK_BUILD_ROUTE,
|
|
94
|
-
baseUrl: GROK_BUILD_BASE_URL,
|
|
95
|
-
reasoning: false,
|
|
96
|
-
input: ["text"],
|
|
97
|
-
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
|
|
98
|
-
contextWindow: 200_000,
|
|
99
|
-
maxTokens: 64_000,
|
|
100
|
-
},
|
|
101
|
-
];
|
|
102
|
-
}
|
|
103
|
-
|
|
104
|
-
/**
|
|
105
|
-
* Build the Grok Build pi-ai provider. Auth is apiKey-shaped: the OAuth
|
|
106
|
-
* access token is injected as the bearer key by the surrounding adapter
|
|
107
|
-
* (`Models.getAuth` on the login provider performs refresh under the store
|
|
108
|
-
* lock before the key ever reaches here).
|
|
109
|
-
*/
|
|
110
|
-
export function grokBuildProvider(models: readonly Model<Api>[]): Provider {
|
|
111
|
-
return createProvider({
|
|
112
|
-
id: GROK_BUILD_ROUTE,
|
|
113
|
-
name: "xAI Grok Build",
|
|
114
|
-
baseUrl: GROK_BUILD_BASE_URL,
|
|
115
|
-
headers: grokBuildFingerprintHeaders(),
|
|
116
|
-
auth: {
|
|
117
|
-
apiKey: {
|
|
118
|
-
name: "Grok Build OAuth access token",
|
|
119
|
-
async resolve({ credential }) {
|
|
120
|
-
const apiKey = credential?.key;
|
|
121
|
-
return apiKey === undefined || apiKey.length === 0 ? undefined : { auth: { apiKey }, source: "OAuth" };
|
|
122
|
-
},
|
|
123
|
-
},
|
|
124
|
-
},
|
|
125
|
-
models,
|
|
126
|
-
api: { "openai-responses": openAIResponsesApi() },
|
|
127
|
-
});
|
|
128
|
-
}
|
package/src/proxy.ts
DELETED
|
@@ -1,11 +0,0 @@
|
|
|
1
|
-
/** Compatibility facade for the shared process-wide coding OAuth proxy. */
|
|
2
|
-
|
|
3
|
-
export type { CodingOAuthProxyLease, CodingOAuthProxyOptions } from "dsh-coding-oauth-core";
|
|
4
|
-
export {
|
|
5
|
-
acquireCodingOAuthProxy,
|
|
6
|
-
codingOAuthProxyInEffect,
|
|
7
|
-
codingOAuthProxyUnreachableHint,
|
|
8
|
-
ensureCodingOAuthProxy,
|
|
9
|
-
ensureGrokBuildProxy,
|
|
10
|
-
grokBuildProxyInEffect,
|
|
11
|
-
} from "dsh-coding-oauth-core";
|
package/src/redact.ts
DELETED
|
@@ -1,72 +0,0 @@
|
|
|
1
|
-
/** Remove token-like strings from an external OAuth diagnostic. */
|
|
2
|
-
|
|
3
|
-
/**
|
|
4
|
-
* An opaque credential value run. We require the surrounding label to be one of
|
|
5
|
-
* the known credential field names AND the value to be at least this many
|
|
6
|
-
* characters so that ordinary prose ("code is fun", "token missing") is left
|
|
7
|
-
* alone. The minimum also keeps the regex from matching in code-style
|
|
8
|
-
* strings like `code: a`.
|
|
9
|
-
*/
|
|
10
|
-
const OPAQUE_TOKEN_MIN_LENGTH = 16;
|
|
11
|
-
|
|
12
|
-
/** The opaque-value class: at least the minimum chars of URL-safe alphabet. */
|
|
13
|
-
const OPAQUE_TOKEN_RUN = `[A-Za-z0-9_\\-.+]{${OPAQUE_TOKEN_MIN_LENGTH},}`;
|
|
14
|
-
|
|
15
|
-
/** Known sensitive field names that may precede an opaque credential value. */
|
|
16
|
-
const SENSITIVE_LABEL =
|
|
17
|
-
"(?:token|bearer|code|user_code|access_token|refresh_token|id_token|api[_-]?key|secret|password|client[_-]?secret|authorization)";
|
|
18
|
-
|
|
19
|
-
/**
|
|
20
|
-
* Sweep additional opaque tokens that follow a known credential label. We
|
|
21
|
-
* require the value to be long and URL-safe-shaped so that ordinary prose
|
|
22
|
-
* ("code is fun", "token missing") is left alone. This complements the short
|
|
23
|
-
* and structured sweep above — it catches longer opaque tokens that survive
|
|
24
|
-
* the more specific regexes.
|
|
25
|
-
*/
|
|
26
|
-
function redactOpaqueTokens(input: string): string {
|
|
27
|
-
let output = input.replace(
|
|
28
|
-
new RegExp(`(["']?${SENSITIVE_LABEL}["']?\\s*:\\s*["'])(${OPAQUE_TOKEN_RUN})(["'])`, "giu"),
|
|
29
|
-
`$1[redacted]$3`,
|
|
30
|
-
);
|
|
31
|
-
output = output.replace(
|
|
32
|
-
new RegExp(`\\b(${SENSITIVE_LABEL})=(${OPAQUE_TOKEN_RUN})(?=[&\\s"']|$)`, "giu"),
|
|
33
|
-
`$1=[redacted]`,
|
|
34
|
-
);
|
|
35
|
-
output = output.replace(
|
|
36
|
-
new RegExp(`\\b(${SENSITIVE_LABEL}\\s*:\\s*)(${OPAQUE_TOKEN_RUN})(?=[\\s"',}]|$)`, "giu"),
|
|
37
|
-
`$1[redacted]`,
|
|
38
|
-
);
|
|
39
|
-
output = output.replace(new RegExp(`\\b(Authorization)\\s+(${OPAQUE_TOKEN_RUN})\\b`, "giu"), `$1 [redacted]`);
|
|
40
|
-
return output;
|
|
41
|
-
}
|
|
42
|
-
|
|
43
|
-
/** Strip userinfo from a proxy URL so CLI/logs never print `user:pass@`. */
|
|
44
|
-
export function redactProxyUrl(value: string): string {
|
|
45
|
-
try {
|
|
46
|
-
const parsed = new URL(value);
|
|
47
|
-
if (parsed.username === "" && parsed.password === "") return value;
|
|
48
|
-
parsed.username = "";
|
|
49
|
-
parsed.password = "";
|
|
50
|
-
const href = parsed.href;
|
|
51
|
-
if (!value.endsWith("/") && href.endsWith("/") && parsed.pathname === "/") return href.slice(0, -1);
|
|
52
|
-
return href;
|
|
53
|
-
} catch {
|
|
54
|
-
return value.replace(/^([a-z][a-z0-9+.-]*:\/\/)[^/@\s]+@/iu, "$1");
|
|
55
|
-
}
|
|
56
|
-
}
|
|
57
|
-
|
|
58
|
-
export function safeMessage(error: unknown): string {
|
|
59
|
-
let text = (error instanceof Error ? error.message : String(error))
|
|
60
|
-
.replace(/\beyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\b/gu, "[redacted token]")
|
|
61
|
-
.replace(/\bsk-ant-oat[A-Za-z0-9_-]*\b/giu, "[redacted token]")
|
|
62
|
-
.replace(/\bsk-[A-Za-z0-9_-]{16,}\b/gu, "[redacted token]")
|
|
63
|
-
.replace(/\bxai-[A-Za-z0-9._-]{8,}\b/gu, "[redacted token]")
|
|
64
|
-
.replace(/(\bBearer\s+)[^\s"',}]+/giu, "$1[redacted]")
|
|
65
|
-
.replace(/(\b(?:code|user_code|token|id_token|refresh_token|access_token)=)[^&\s]+/giu, "$1[redacted]")
|
|
66
|
-
.replace(/(["']?(?:code|user_code|id_token|refresh_token|access_token)["']?\s*:\s*["'])[^"']+/giu, "$1[redacted]");
|
|
67
|
-
// Generic opaque sweep catches long values preceded by labels such as
|
|
68
|
-
// client_secret, api_key, password, or Authorization. The minimum length
|
|
69
|
-
// guards against ordinary prose and the case-insensitive pass handles repeats.
|
|
70
|
-
text = redactOpaqueTokens(text);
|
|
71
|
-
return text.slice(0, 1000);
|
|
72
|
-
}
|
package/src/session.ts
DELETED
|
@@ -1,218 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Shared OAuth store + live catalog for the host plugin and CLI.
|
|
3
|
-
* @module dsh-coding-subscription-oauth/session
|
|
4
|
-
*/
|
|
5
|
-
|
|
6
|
-
import { mkdir, readFile, rm } from "node:fs/promises";
|
|
7
|
-
import { dirname, join, resolve } from "node:path";
|
|
8
|
-
import { writeFileAtomic } from "@deepseek-ai/dsh-atomic-write";
|
|
9
|
-
import { resolveDshHome } from "@deepseek-ai/dsh-home-paths";
|
|
10
|
-
import type { Api, Model, MutableModels, Provider } from "@earendil-works/pi-ai";
|
|
11
|
-
import { createModels } from "@earendil-works/pi-ai";
|
|
12
|
-
import { xaiProvider } from "@earendil-works/pi-ai/providers/xai";
|
|
13
|
-
import {
|
|
14
|
-
type CatalogSource,
|
|
15
|
-
fetchLiveModels,
|
|
16
|
-
type LiveModelDescriptor,
|
|
17
|
-
materializeLiveModel,
|
|
18
|
-
mergeLiveCatalog,
|
|
19
|
-
} from "./catalog.ts";
|
|
20
|
-
import { GROK_BUILD_MODELS_CACHE_FILENAME, GROK_BUILD_ROUTE, XAI_PI_PROVIDER } from "./ids.ts";
|
|
21
|
-
import { grokBuildBaselineModels, grokBuildProvider } from "./provider.ts";
|
|
22
|
-
import { safeMessage } from "./redact.ts";
|
|
23
|
-
import { GrokBuildCredentialStore } from "./store.ts";
|
|
24
|
-
|
|
25
|
-
const MODELS_CACHE_VERSION = 2;
|
|
26
|
-
|
|
27
|
-
interface ModelsCacheDocument {
|
|
28
|
-
version: typeof MODELS_CACHE_VERSION;
|
|
29
|
-
ids: string[];
|
|
30
|
-
selected?: string[];
|
|
31
|
-
fetchedAt: number;
|
|
32
|
-
}
|
|
33
|
-
|
|
34
|
-
interface ParsedCache {
|
|
35
|
-
ids: string[];
|
|
36
|
-
selected?: string[];
|
|
37
|
-
}
|
|
38
|
-
|
|
39
|
-
function isENOENT(error: unknown): boolean {
|
|
40
|
-
return (error as NodeJS.ErrnoException | null)?.code === "ENOENT";
|
|
41
|
-
}
|
|
42
|
-
|
|
43
|
-
function modelsCachePath(dshHome?: string): string {
|
|
44
|
-
return resolve(join(resolveDshHome(dshHome), GROK_BUILD_MODELS_CACHE_FILENAME));
|
|
45
|
-
}
|
|
46
|
-
|
|
47
|
-
function parseIdList(value: unknown): string[] {
|
|
48
|
-
if (!Array.isArray(value)) return [];
|
|
49
|
-
return [...new Set(value.filter((id): id is string => typeof id === "string" && id.length > 0))];
|
|
50
|
-
}
|
|
51
|
-
|
|
52
|
-
function parseCache(text: string): ParsedCache | undefined {
|
|
53
|
-
let value: unknown;
|
|
54
|
-
try {
|
|
55
|
-
value = JSON.parse(text);
|
|
56
|
-
} catch {
|
|
57
|
-
return undefined;
|
|
58
|
-
}
|
|
59
|
-
if (typeof value !== "object" || value === null || Array.isArray(value)) return undefined;
|
|
60
|
-
const document = value as Record<string, unknown>;
|
|
61
|
-
if (document["version"] !== 1 && document["version"] !== MODELS_CACHE_VERSION) return undefined;
|
|
62
|
-
const ids = parseIdList(document["ids"]);
|
|
63
|
-
const selected = parseIdList(document["selected"]);
|
|
64
|
-
if (ids.length === 0 && selected.length === 0) return undefined;
|
|
65
|
-
return {
|
|
66
|
-
ids,
|
|
67
|
-
...(selected.length === 0 ? {} : { selected }),
|
|
68
|
-
};
|
|
69
|
-
}
|
|
70
|
-
|
|
71
|
-
function asHarnessModels(models: readonly Model<Api>[]): Model<Api>[] {
|
|
72
|
-
return models.map((model) =>
|
|
73
|
-
model.provider === GROK_BUILD_ROUTE ? model : { ...model, provider: GROK_BUILD_ROUTE },
|
|
74
|
-
);
|
|
75
|
-
}
|
|
76
|
-
|
|
77
|
-
/** One process-local owner of the credential and the account model list. */
|
|
78
|
-
export class GrokBuildSession {
|
|
79
|
-
readonly store: GrokBuildCredentialStore;
|
|
80
|
-
readonly models: MutableModels;
|
|
81
|
-
private readonly baselineCatalog: readonly Model<Api>[];
|
|
82
|
-
private liveIds: string[] | undefined;
|
|
83
|
-
private liveModels: readonly LiveModelDescriptor[] | undefined;
|
|
84
|
-
private selectedIds: string[] | undefined;
|
|
85
|
-
private source: CatalogSource = "fallback";
|
|
86
|
-
private listingError: string | undefined;
|
|
87
|
-
private readonly cacheFile: string;
|
|
88
|
-
private onCatalogChange: (() => void) | undefined;
|
|
89
|
-
|
|
90
|
-
constructor(store: GrokBuildCredentialStore = new GrokBuildCredentialStore(), onCatalogChange?: () => void) {
|
|
91
|
-
this.store = store;
|
|
92
|
-
this.cacheFile = modelsCachePath();
|
|
93
|
-
this.baselineCatalog = grokBuildBaselineModels();
|
|
94
|
-
// The built-in xai provider owns login/refresh (device flow today); the
|
|
95
|
-
// credential lives in this plugin's own file via the store above.
|
|
96
|
-
this.models = createModels({ credentials: store });
|
|
97
|
-
this.models.setProvider(xaiProvider());
|
|
98
|
-
this.onCatalogChange = onCatalogChange;
|
|
99
|
-
}
|
|
100
|
-
|
|
101
|
-
/** Secret-free listing diagnostic from the last refresh. */
|
|
102
|
-
get catalogError(): string | undefined {
|
|
103
|
-
return this.listingError;
|
|
104
|
-
}
|
|
105
|
-
|
|
106
|
-
get catalogSource(): CatalogSource {
|
|
107
|
-
return this.source;
|
|
108
|
-
}
|
|
109
|
-
|
|
110
|
-
availableModels(): Model<Api>[] {
|
|
111
|
-
return mergeLiveCatalog(this.baselineCatalog, this.liveIds, this.liveModels);
|
|
112
|
-
}
|
|
113
|
-
|
|
114
|
-
selectedModelIds(): string[] | undefined {
|
|
115
|
-
return this.selectedIds;
|
|
116
|
-
}
|
|
117
|
-
|
|
118
|
-
visibleModels(): Model<Api>[] {
|
|
119
|
-
const available = this.availableModels();
|
|
120
|
-
if (this.selectedIds === undefined || this.selectedIds.length === 0) return available;
|
|
121
|
-
const byId = new Map(available.map((model) => [model.id, model]));
|
|
122
|
-
return this.selectedIds.map((id) => byId.get(id) ?? materializeLiveModel(id, this.baselineCatalog));
|
|
123
|
-
}
|
|
124
|
-
|
|
125
|
-
/** Provider whose id matches the harness route so PiAiAdapter can list models. */
|
|
126
|
-
provider(): Provider {
|
|
127
|
-
const visible = this.visibleModels();
|
|
128
|
-
const base = grokBuildProvider(visible);
|
|
129
|
-
return {
|
|
130
|
-
...base,
|
|
131
|
-
getModels: () => asHarnessModels(this.visibleModels()),
|
|
132
|
-
};
|
|
133
|
-
}
|
|
134
|
-
|
|
135
|
-
async loadCachedCatalog(): Promise<void> {
|
|
136
|
-
try {
|
|
137
|
-
const cache = parseCache(await readFile(this.cacheFile, "utf8"));
|
|
138
|
-
if (cache === undefined) return;
|
|
139
|
-
if (cache.ids.length > 0) {
|
|
140
|
-
this.liveIds = cache.ids;
|
|
141
|
-
this.liveModels = undefined;
|
|
142
|
-
this.source = "cache";
|
|
143
|
-
}
|
|
144
|
-
this.selectedIds = cache.selected;
|
|
145
|
-
} catch (error) {
|
|
146
|
-
if (!isENOENT(error)) throw error;
|
|
147
|
-
}
|
|
148
|
-
}
|
|
149
|
-
|
|
150
|
-
async refreshLiveCatalog(signal?: AbortSignal): Promise<void> {
|
|
151
|
-
try {
|
|
152
|
-
const auth = await this.models.getAuth(XAI_PI_PROVIDER);
|
|
153
|
-
const access = auth?.auth.apiKey;
|
|
154
|
-
if (access === undefined || access.length === 0) {
|
|
155
|
-
this.listingError = undefined;
|
|
156
|
-
return;
|
|
157
|
-
}
|
|
158
|
-
const live = await fetchLiveModels(access, signal);
|
|
159
|
-
this.liveIds = live.map((model) => model.id);
|
|
160
|
-
this.liveModels = live;
|
|
161
|
-
this.source = "live";
|
|
162
|
-
this.listingError = undefined;
|
|
163
|
-
await this.writeCache();
|
|
164
|
-
} catch (error) {
|
|
165
|
-
this.listingError = safeMessage(error);
|
|
166
|
-
if (this.liveIds === undefined) this.source = "fallback";
|
|
167
|
-
} finally {
|
|
168
|
-
// Login must reveal the fallback catalog even when auth refresh or live listing fails.
|
|
169
|
-
this.onCatalogChange?.();
|
|
170
|
-
}
|
|
171
|
-
}
|
|
172
|
-
|
|
173
|
-
async setSelectedModels(ids: readonly string[]): Promise<void> {
|
|
174
|
-
const unique = [...new Set(ids.filter((id) => id.length > 0))];
|
|
175
|
-
this.selectedIds = unique.length === 0 ? undefined : unique;
|
|
176
|
-
await this.writeCache();
|
|
177
|
-
this.onCatalogChange?.();
|
|
178
|
-
}
|
|
179
|
-
|
|
180
|
-
/**
|
|
181
|
-
* Backdate the stored token's expiry so the next `getAuth()` refreshes.
|
|
182
|
-
* Called after an upstream 401 rejected a locally-valid token.
|
|
183
|
-
*/
|
|
184
|
-
async invalidateAccessToken(): Promise<void> {
|
|
185
|
-
await this.store.invalidate(XAI_PI_PROVIDER);
|
|
186
|
-
}
|
|
187
|
-
|
|
188
|
-
async logout(): Promise<void> {
|
|
189
|
-
try {
|
|
190
|
-
await this.store.delete(XAI_PI_PROVIDER);
|
|
191
|
-
this.liveIds = undefined;
|
|
192
|
-
this.liveModels = undefined;
|
|
193
|
-
this.selectedIds = undefined;
|
|
194
|
-
this.source = "fallback";
|
|
195
|
-
this.listingError = undefined;
|
|
196
|
-
await mkdir(dirname(this.cacheFile), { recursive: true, mode: 0o700 });
|
|
197
|
-
await rm(this.cacheFile, { force: true });
|
|
198
|
-
} finally {
|
|
199
|
-
// Credential deletion may succeed before cache cleanup fails. Always
|
|
200
|
-
// refresh discovery so an open selector cannot retain stale models.
|
|
201
|
-
this.onCatalogChange?.();
|
|
202
|
-
}
|
|
203
|
-
}
|
|
204
|
-
|
|
205
|
-
private async writeCache(): Promise<void> {
|
|
206
|
-
const document: ModelsCacheDocument = {
|
|
207
|
-
version: MODELS_CACHE_VERSION,
|
|
208
|
-
ids: this.liveIds === undefined ? [] : [...this.liveIds],
|
|
209
|
-
fetchedAt: Date.now(),
|
|
210
|
-
...(this.selectedIds === undefined ? {} : { selected: [...this.selectedIds] }),
|
|
211
|
-
};
|
|
212
|
-
await mkdir(dirname(this.cacheFile), { recursive: true, mode: 0o700 });
|
|
213
|
-
await writeFileAtomic(this.cacheFile, `${JSON.stringify(document)}\n`, {
|
|
214
|
-
mode: 0o600,
|
|
215
|
-
dirMode: 0o700,
|
|
216
|
-
});
|
|
217
|
-
}
|
|
218
|
-
}
|
package/src/store.ts
DELETED
|
@@ -1,217 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Owner-only persistent OAuth credential storage for coding-subscription routes.
|
|
3
|
-
* @module dsh-coding-subscription-oauth/store
|
|
4
|
-
*/
|
|
5
|
-
|
|
6
|
-
import { mkdir, rm } from "node:fs/promises";
|
|
7
|
-
import { dirname, join, resolve } from "node:path";
|
|
8
|
-
import { withFileLock, writeFileAtomic } from "@deepseek-ai/dsh-atomic-write";
|
|
9
|
-
import { resolveDshHome } from "@deepseek-ai/dsh-home-paths";
|
|
10
|
-
import type { Credential, CredentialInfo, CredentialStore, OAuthCredential } from "@earendil-works/pi-ai";
|
|
11
|
-
import { GROK_BUILD_AUTH_FILENAME, XAI_PI_PROVIDER } from "./ids.ts";
|
|
12
|
-
import { OAuthSourceError, readHardenedOAuthSourceFile } from "./oauth-sources.ts";
|
|
13
|
-
|
|
14
|
-
/** Current on-disk format; readers reject every other version. */
|
|
15
|
-
const AUTH_FORMAT_VERSION = 1;
|
|
16
|
-
|
|
17
|
-
interface AuthDocument {
|
|
18
|
-
version: typeof AUTH_FORMAT_VERSION;
|
|
19
|
-
credential: OAuthCredential;
|
|
20
|
-
}
|
|
21
|
-
|
|
22
|
-
function parseDocument(text: string, filename: string, label: string): AuthDocument {
|
|
23
|
-
let value: unknown;
|
|
24
|
-
try {
|
|
25
|
-
value = JSON.parse(text);
|
|
26
|
-
} catch {
|
|
27
|
-
throw new Error(`${label}: ${filename} is not valid JSON`);
|
|
28
|
-
}
|
|
29
|
-
if (typeof value !== "object" || value === null || Array.isArray(value)) {
|
|
30
|
-
throw new Error(`${label}: ${filename} must contain an object`);
|
|
31
|
-
}
|
|
32
|
-
const document = value as Record<string, unknown>;
|
|
33
|
-
if (document["version"] !== AUTH_FORMAT_VERSION) {
|
|
34
|
-
throw new Error(`${label}: ${filename} has unsupported auth format version ${String(document["version"])}`);
|
|
35
|
-
}
|
|
36
|
-
if (Object.keys(document).some((key) => key !== "version" && key !== "credential")) {
|
|
37
|
-
throw new Error(`${label}: ${filename} contains an unknown top-level field`);
|
|
38
|
-
}
|
|
39
|
-
const raw = document["credential"];
|
|
40
|
-
if (typeof raw !== "object" || raw === null || Array.isArray(raw)) {
|
|
41
|
-
throw new Error(`${label}: ${filename} credential must be an object`);
|
|
42
|
-
}
|
|
43
|
-
const credential = raw as Record<string, unknown>;
|
|
44
|
-
const allowed = new Set(["type", "access", "refresh", "expires", "accountId"]);
|
|
45
|
-
if (Object.keys(credential).some((key) => !allowed.has(key))) {
|
|
46
|
-
throw new Error(`${label}: ${filename} credential contains an unknown field`);
|
|
47
|
-
}
|
|
48
|
-
if (credential["type"] !== "oauth") throw new Error(`${label}: ${filename} credential type must be oauth`);
|
|
49
|
-
for (const key of ["access", "refresh"] as const) {
|
|
50
|
-
if (typeof credential[key] !== "string" || credential[key].length === 0) {
|
|
51
|
-
throw new Error(`${label}: ${filename} credential ${key} must be a non-empty string`);
|
|
52
|
-
}
|
|
53
|
-
}
|
|
54
|
-
if (
|
|
55
|
-
credential["accountId"] !== undefined &&
|
|
56
|
-
(typeof credential["accountId"] !== "string" || credential["accountId"].length === 0)
|
|
57
|
-
) {
|
|
58
|
-
throw new Error(`${label}: ${filename} credential accountId must be a non-empty string when present`);
|
|
59
|
-
}
|
|
60
|
-
if (
|
|
61
|
-
typeof credential["expires"] !== "number" ||
|
|
62
|
-
!Number.isFinite(credential["expires"]) ||
|
|
63
|
-
credential["expires"] <= 0
|
|
64
|
-
) {
|
|
65
|
-
throw new Error(`${label}: ${filename} credential expires must be a positive finite number`);
|
|
66
|
-
}
|
|
67
|
-
return { version: AUTH_FORMAT_VERSION, credential: credential as unknown as OAuthCredential };
|
|
68
|
-
}
|
|
69
|
-
|
|
70
|
-
function cloneCredential(credential: OAuthCredential): OAuthCredential {
|
|
71
|
-
return structuredClone(credential);
|
|
72
|
-
}
|
|
73
|
-
|
|
74
|
-
/** Resolve one private OAuth document path beneath DSH_HOME. */
|
|
75
|
-
export function oauthCredentialPath(basename: string, dshHome?: string): string {
|
|
76
|
-
if (
|
|
77
|
-
basename.length === 0 ||
|
|
78
|
-
basename.length > 128 ||
|
|
79
|
-
basename === "." ||
|
|
80
|
-
basename === ".." ||
|
|
81
|
-
!/^\.?[A-Za-z0-9][A-Za-z0-9._-]*$/u.test(basename)
|
|
82
|
-
) {
|
|
83
|
-
throw new TypeError("OAuth credential basename must be a safe local filename");
|
|
84
|
-
}
|
|
85
|
-
return resolve(join(resolveDshHome(dshHome), basename));
|
|
86
|
-
}
|
|
87
|
-
|
|
88
|
-
/** Resolve the legacy Grok Build OAuth document path. */
|
|
89
|
-
export function grokBuildAuthPath(dshHome?: string): string {
|
|
90
|
-
return oauthCredentialPath(GROK_BUILD_AUTH_FILENAME, dshHome);
|
|
91
|
-
}
|
|
92
|
-
|
|
93
|
-
/**
|
|
94
|
-
* File-backed pi-ai store scoped to exactly one provider id. Separate provider
|
|
95
|
-
* files prevent one corrupted or rotated credential from affecting another.
|
|
96
|
-
*/
|
|
97
|
-
export class OAuthCredentialFileStore implements CredentialStore {
|
|
98
|
-
readonly filename: string;
|
|
99
|
-
|
|
100
|
-
constructor(
|
|
101
|
-
readonly providerId: string,
|
|
102
|
-
filename: string,
|
|
103
|
-
private readonly label: string,
|
|
104
|
-
) {
|
|
105
|
-
this.filename = resolve(filename);
|
|
106
|
-
}
|
|
107
|
-
|
|
108
|
-
private async readCurrent(): Promise<OAuthCredential | undefined> {
|
|
109
|
-
return this.loadCurrent({ allowUnreadable: false });
|
|
110
|
-
}
|
|
111
|
-
|
|
112
|
-
/**
|
|
113
|
-
* Hardened load. `read`/`list` keep parse failures loud. `modify` treats a
|
|
114
|
-
* safe-but-unparseable document as absent so a confirmed replace can proceed.
|
|
115
|
-
* Unsafe/symlink/wrong-owner/too-large files still throw.
|
|
116
|
-
*/
|
|
117
|
-
private async loadCurrent(options: { allowUnreadable: boolean }): Promise<OAuthCredential | undefined> {
|
|
118
|
-
let text: string;
|
|
119
|
-
try {
|
|
120
|
-
text = (await readHardenedOAuthSourceFile(this.filename)).text;
|
|
121
|
-
} catch (error) {
|
|
122
|
-
if (error instanceof OAuthSourceError && error.code === "not_found") return undefined;
|
|
123
|
-
if (error instanceof OAuthSourceError && error.code === "unsafe_source") {
|
|
124
|
-
throw new Error(`${this.label}: credential file failed owner-only no-follow validation`);
|
|
125
|
-
}
|
|
126
|
-
throw error;
|
|
127
|
-
}
|
|
128
|
-
try {
|
|
129
|
-
return cloneCredential(parseDocument(text, this.filename, this.label).credential);
|
|
130
|
-
} catch (error) {
|
|
131
|
-
if (options.allowUnreadable) return undefined;
|
|
132
|
-
throw error;
|
|
133
|
-
}
|
|
134
|
-
}
|
|
135
|
-
|
|
136
|
-
/** Refuse a dest that became unsafe after the lock was taken and before rename. */
|
|
137
|
-
private async assertDestinationReplaceable(): Promise<void> {
|
|
138
|
-
try {
|
|
139
|
-
await readHardenedOAuthSourceFile(this.filename);
|
|
140
|
-
} catch (error) {
|
|
141
|
-
if (error instanceof OAuthSourceError && error.code === "not_found") return;
|
|
142
|
-
if (error instanceof OAuthSourceError && (error.code === "unsafe_source" || error.code === "too_large")) {
|
|
143
|
-
throw new Error(`${this.label}: credential file failed owner-only no-follow validation`);
|
|
144
|
-
}
|
|
145
|
-
throw error;
|
|
146
|
-
}
|
|
147
|
-
}
|
|
148
|
-
|
|
149
|
-
async read(providerId: string): Promise<Credential | undefined> {
|
|
150
|
-
return providerId === this.providerId ? this.readCurrent() : undefined;
|
|
151
|
-
}
|
|
152
|
-
|
|
153
|
-
async list(): Promise<readonly CredentialInfo[]> {
|
|
154
|
-
return (await this.readCurrent()) === undefined ? [] : [{ providerId: this.providerId, type: "oauth" }];
|
|
155
|
-
}
|
|
156
|
-
|
|
157
|
-
async modify(
|
|
158
|
-
providerId: string,
|
|
159
|
-
fn: (current: Credential | undefined) => Promise<Credential | undefined>,
|
|
160
|
-
): Promise<Credential | undefined> {
|
|
161
|
-
if (providerId !== this.providerId) {
|
|
162
|
-
throw new Error(`${this.label}: credential store does not own provider "${providerId}"`);
|
|
163
|
-
}
|
|
164
|
-
await mkdir(dirname(this.filename), { recursive: true, mode: 0o700 });
|
|
165
|
-
return withFileLock(this.filename, async () => {
|
|
166
|
-
const current = await this.loadCurrent({ allowUnreadable: true });
|
|
167
|
-
const candidate = await fn(current);
|
|
168
|
-
if (candidate === undefined) return current;
|
|
169
|
-
const document = parseDocument(
|
|
170
|
-
JSON.stringify({
|
|
171
|
-
version: AUTH_FORMAT_VERSION,
|
|
172
|
-
credential: candidate,
|
|
173
|
-
}),
|
|
174
|
-
this.filename,
|
|
175
|
-
this.label,
|
|
176
|
-
);
|
|
177
|
-
await this.assertDestinationReplaceable();
|
|
178
|
-
await writeFileAtomic(this.filename, `${JSON.stringify(document, null, 2)}\n`, {
|
|
179
|
-
mode: 0o600,
|
|
180
|
-
dirMode: 0o700,
|
|
181
|
-
});
|
|
182
|
-
return cloneCredential(document.credential);
|
|
183
|
-
});
|
|
184
|
-
}
|
|
185
|
-
|
|
186
|
-
/**
|
|
187
|
-
* Force the next `getAuth()` to refresh by backdating `expires` into the past.
|
|
188
|
-
* Used after an upstream 401: the stored access token was rejected even though
|
|
189
|
-
* the local expiry had not yet passed (server-side revocation or skew). The
|
|
190
|
-
* access/refresh pair is preserved — only the freshness marker moves — so the
|
|
191
|
-
* refresh token can still mint a replacement. Returns true when a credential
|
|
192
|
-
* was actually backdated; false when nothing is stored.
|
|
193
|
-
*/
|
|
194
|
-
async invalidate(providerId: string): Promise<boolean> {
|
|
195
|
-
if (providerId !== this.providerId) return false;
|
|
196
|
-
let invalidated = false;
|
|
197
|
-
await this.modify(providerId, async (current) => {
|
|
198
|
-
if (current?.type !== "oauth") return undefined;
|
|
199
|
-
invalidated = true;
|
|
200
|
-
return { ...current, expires: Date.now() - 1000 };
|
|
201
|
-
});
|
|
202
|
-
return invalidated;
|
|
203
|
-
}
|
|
204
|
-
|
|
205
|
-
async delete(providerId: string): Promise<void> {
|
|
206
|
-
if (providerId !== this.providerId) return;
|
|
207
|
-
await mkdir(dirname(this.filename), { recursive: true, mode: 0o700 });
|
|
208
|
-
await withFileLock(this.filename, () => rm(this.filename, { force: true }));
|
|
209
|
-
}
|
|
210
|
-
}
|
|
211
|
-
|
|
212
|
-
/** Legacy-named store retained for existing imports and credential migration. */
|
|
213
|
-
export class GrokBuildCredentialStore extends OAuthCredentialFileStore {
|
|
214
|
-
constructor(filename: string = grokBuildAuthPath()) {
|
|
215
|
-
super(XAI_PI_PROVIDER, filename, "grok-build");
|
|
216
|
-
}
|
|
217
|
-
}
|