dsh-coding-subscription-oauth 0.6.2 → 0.6.3

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 (121) hide show
  1. package/CHANGELOG.md +222 -206
  2. package/CONTRIBUTING.md +129 -120
  3. package/INSTALL.md +218 -218
  4. package/LICENSE +19 -19
  5. package/NOTICE +11 -11
  6. package/README.de.md +289 -289
  7. package/README.es.md +290 -290
  8. package/README.fr.md +290 -290
  9. package/README.ja.md +290 -290
  10. package/README.ko.md +290 -290
  11. package/README.md +304 -304
  12. package/README.pt-BR.md +290 -290
  13. package/README.ru.md +290 -290
  14. package/README.zh-CN.md +302 -302
  15. package/compatibility/dsh-bom.json +0 -0
  16. package/cordis.patch.yml +13 -13
  17. package/docs/00-project-rules.md +212 -195
  18. package/docs/02-architecture.md +130 -130
  19. package/docs/02-architecture.zh-CN.md +130 -130
  20. package/lib/bin.js.map +1 -1
  21. package/lib/capability-settings.d.ts +8 -2
  22. package/lib/capability-settings.d.ts.map +1 -1
  23. package/lib/capability-tools.d.ts +7 -2
  24. package/lib/capability-tools.d.ts.map +1 -1
  25. package/lib/client.js +3 -3
  26. package/lib/client.js.map +2 -2
  27. package/lib/codex-images.d.ts +8 -0
  28. package/lib/codex-images.d.ts.map +1 -1
  29. package/lib/index.js +32 -7
  30. package/lib/index.js.map +2 -2
  31. package/lib/invariant.js.map +1 -1
  32. package/media/en/settings_accounts.png +0 -0
  33. package/media/en/settings_capabilities.png +0 -0
  34. package/media/en/settings_gateway.png +0 -0
  35. package/media/settings_accounts.png +0 -0
  36. package/media/settings_capabilities.png +0 -0
  37. package/media/settings_gateway.png +0 -0
  38. package/media/settings_overview.png +0 -0
  39. package/media/zh-CN/settings_accounts.png +0 -0
  40. package/media/zh-CN/settings_capabilities.png +0 -0
  41. package/media/zh-CN/settings_gateway.png +0 -0
  42. package/package.json +148 -148
  43. package/patches/dsh-agy@0.1.2.patch +25 -25
  44. package/scripts/release.mjs +186 -186
  45. package/scripts/smoke-deployed-routes.mjs +146 -146
  46. package/scripts/verify-deployed-catalog.mjs +87 -87
  47. package/src/adapter.ts +273 -273
  48. package/src/alias-adapter.ts +130 -130
  49. package/src/auth-routes.ts +921 -921
  50. package/src/auth.ts +67 -67
  51. package/src/bin.ts +350 -350
  52. package/src/capability-routes.ts +279 -279
  53. package/src/capability-runtime.ts +314 -313
  54. package/src/capability-settings.ts +671 -658
  55. package/src/capability-tools.ts +685 -666
  56. package/src/catalog.ts +271 -271
  57. package/src/client/GrokBuildSettings.tsx +771 -770
  58. package/src/client/api.ts +88 -88
  59. package/src/client/components/AboutTab.tsx +30 -30
  60. package/src/client/components/AccountsTab.tsx +241 -241
  61. package/src/client/components/Badge.tsx +33 -33
  62. package/src/client/components/CapabilitiesTab.tsx +265 -265
  63. package/src/client/components/CliPullPreview.tsx +116 -116
  64. package/src/client/components/CopyButton.tsx +57 -57
  65. package/src/client/components/GatewayTab.tsx +469 -469
  66. package/src/client/components/NoticeBanner.tsx +46 -46
  67. package/src/client/components/ProgressBar.tsx +53 -53
  68. package/src/client/components/ProviderCard.tsx +606 -606
  69. package/src/client/components/SettingsTabs.tsx +75 -75
  70. package/src/client/components/ToggleSwitch.tsx +71 -71
  71. package/src/client/constants.ts +230 -224
  72. package/src/client/display.ts +61 -61
  73. package/src/client/dshClientAdapter.ts +127 -127
  74. package/src/client/gatewaySnippets.ts +37 -37
  75. package/src/client/index.tsx +156 -156
  76. package/src/client/locales.ts +540 -535
  77. package/src/client/microStyles.ts +52 -52
  78. package/src/client/parsers.ts +398 -396
  79. package/src/client/styles.ts +325 -325
  80. package/src/client/types.ts +199 -197
  81. package/src/codex-http.ts +447 -447
  82. package/src/codex-images.ts +503 -485
  83. package/src/codex-model-capabilities.ts +320 -320
  84. package/src/codex-search.ts +245 -245
  85. package/src/codex-usage.ts +263 -263
  86. package/src/compatibility.ts +41 -41
  87. package/src/dsh-host-adapter.ts +173 -173
  88. package/src/gateway-anthropic-messages.ts +84 -84
  89. package/src/gateway-auth.ts +102 -102
  90. package/src/gateway-backend.ts +274 -274
  91. package/src/gateway-body.ts +49 -49
  92. package/src/gateway-config.ts +76 -76
  93. package/src/gateway-http.ts +104 -104
  94. package/src/gateway-openai-chat.ts +124 -124
  95. package/src/gateway-openai-responses.ts +53 -53
  96. package/src/gateway-parse.ts +224 -224
  97. package/src/gateway-protocol.ts +52 -52
  98. package/src/gateway-routes.ts +158 -158
  99. package/src/gateway.ts +258 -258
  100. package/src/grok-errors.ts +24 -24
  101. package/src/grok-imagine.ts +1627 -1627
  102. package/src/grok-import.ts +151 -151
  103. package/src/http-json.ts +82 -82
  104. package/src/ids.ts +59 -59
  105. package/src/imagine-routes.ts +463 -463
  106. package/src/index.ts +709 -709
  107. package/src/invariant.ts +17 -17
  108. package/src/kimi-errors.ts +26 -26
  109. package/src/media-store.ts +927 -927
  110. package/src/oauth-import-routes.ts +324 -324
  111. package/src/oauth-providers.ts +152 -152
  112. package/src/oauth-session.ts +183 -183
  113. package/src/oauth-sources.ts +1104 -1104
  114. package/src/oauth.ts +620 -620
  115. package/src/provider.ts +128 -128
  116. package/src/proxy.ts +11 -11
  117. package/src/redact.ts +72 -72
  118. package/src/session.ts +218 -218
  119. package/src/store.ts +217 -217
  120. package/src/web-origin.ts +296 -296
  121. package/src/web-routes.ts +38 -38
package/src/bin.ts CHANGED
@@ -1,350 +1,350 @@
1
- #!/usr/bin/env node
2
- /** Standalone credential CLI for the coding-subscription bundle. */
3
-
4
- import { spawn } from "node:child_process";
5
- import { realpathSync } from "node:fs";
6
- import { createInterface } from "node:readline/promises";
7
- import { fileURLToPath } from "node:url";
8
- import type { AuthEvent, AuthPrompt } from "@earendil-works/pi-ai";
9
- import { grokBuildAuthStatus, importGrokBuildSession, loginGrokBuildSession } from "./auth.ts";
10
- import { GATEWAY_TOS_WARNING } from "./gateway.ts";
11
- import { GATEWAY_DEFAULT_BIND, GATEWAY_DEFAULT_PORT } from "./gateway-config.ts";
12
- import { grokAuthPath } from "./grok-import.ts";
13
- import { XAI_PI_PROVIDER } from "./ids.ts";
14
- import { loginGrokBuildPkce } from "./oauth.ts";
15
- import { oauthProviderDefinition, type SubscriptionLoginMethod } from "./oauth-providers.ts";
16
- import { OAuthProviderSession } from "./oauth-session.ts";
17
- import { codingOAuthProxyInEffect, ensureCodingOAuthProxy } from "./proxy.ts";
18
- import { redactProxyUrl, safeMessage } from "./redact.ts";
19
- import { GrokBuildSession } from "./session.ts";
20
- import { grokBuildAuthPath } from "./store.ts";
21
-
22
- export type CliAction = "login" | "logout" | "status" | "import";
23
- export type CliProvider = "all" | "grok" | "codex" | "kimi" | "claude";
24
-
25
- function openBrowser(rawUrl: string): void {
26
- const url = new URL(rawUrl);
27
- if (url.protocol !== "https:") throw new Error(`refusing to open non-HTTPS authorization URL from ${url.host}`);
28
- const command =
29
- process.platform === "win32"
30
- ? { file: "rundll32.exe", args: ["url.dll,FileProtocolHandler", url.href] }
31
- : process.platform === "darwin"
32
- ? { file: "open", args: [url.href] }
33
- : { file: "xdg-open", args: [url.href] };
34
- try {
35
- const child = spawn(command.file, command.args, {
36
- detached: true,
37
- stdio: "ignore",
38
- windowsHide: true,
39
- });
40
- child.on("error", () => {});
41
- child.unref();
42
- } catch {
43
- // The printed URL remains the manual fallback.
44
- }
45
- }
46
-
47
- function notify(event: AuthEvent, useBrowser: boolean): void {
48
- switch (event.type) {
49
- case "auth_url":
50
- process.stdout.write(`Open this URL to sign in:\n${event.url}\n`);
51
- if (event.instructions !== undefined) process.stdout.write(`${event.instructions}\n`);
52
- if (useBrowser) openBrowser(event.url);
53
- break;
54
- case "device_code":
55
- process.stdout.write(`Open this URL to sign in:\n${event.verificationUri}\n`);
56
- if (event.userCode.length > 0) process.stdout.write(`Enter code: ${event.userCode}\n`);
57
- if (useBrowser) openBrowser(event.verificationUri);
58
- break;
59
- case "info":
60
- case "progress":
61
- process.stdout.write(`${event.message}\n`);
62
- break;
63
- default:
64
- event satisfies never;
65
- }
66
- }
67
-
68
- function selectLoginOption(prompt: Extract<AuthPrompt, { type: "select" }>, method?: SubscriptionLoginMethod): string {
69
- if (method !== undefined) {
70
- const exact = method === "device" ? ["device_code", "device-code", "device"] : ["browser", "browser_login"];
71
- for (const id of exact) if (prompt.options.some((option) => option.id === id)) return id;
72
- const label = method === "device" ? /device|headless/iu : /browser|pkce/iu;
73
- const match = prompt.options.find((option) => label.test(option.label));
74
- if (match !== undefined) return match.id;
75
- }
76
- const oauth = prompt.options.find((option) => option.id === "oauth" || option.id.includes("oauth"));
77
- return oauth?.id ?? prompt.options[0]?.id ?? "";
78
- }
79
-
80
- async function answerPrompt(
81
- prompt: AuthPrompt,
82
- question: (text: string, options: { signal?: AbortSignal }) => Promise<string>,
83
- method?: SubscriptionLoginMethod,
84
- ): Promise<string> {
85
- if (prompt.type === "select") return selectLoginOption(prompt, method);
86
- const suffix = prompt.placeholder === undefined ? "" : ` (${prompt.placeholder})`;
87
- return question(`${prompt.message}${suffix}: `, {
88
- ...(prompt.signal === undefined ? {} : { signal: prompt.signal }),
89
- });
90
- }
91
-
92
- function printHelp(): void {
93
- process.stdout.write(
94
- [
95
- "Usage: dsh-coding-oauth <login|logout|status|import> [provider] [options]",
96
- "(legacy command name: dsh-grok-build)",
97
- "",
98
- "Providers: grok (default), codex, kimi, claude; status also accepts all.",
99
- "",
100
- " login grok [--pkce|--device-auth]",
101
- " login codex [--device-auth|--browser] (device code is the default)",
102
- " login kimi (device code)",
103
- " login claude [--browser] (PKCE + redirect paste fallback)",
104
- " import [grok] import ~/.grok/auth.json only",
105
- " logout [provider]",
106
- " status [provider|all]",
107
- "",
108
- "Network: set CODING_OAUTH_PROXY, GROK_BUILD_PROXY, or HTTPS_PROXY.",
109
- "Only audited subscription hosts use the proxy; Kimi stays direct by default.",
110
- "",
111
- ].join("\n"),
112
- );
113
- }
114
-
115
- function parseProvider(raw: string | undefined, action: CliAction): CliProvider {
116
- if (raw === undefined || raw.startsWith("--")) return "grok";
117
- if (raw === "all" && action === "status") return raw;
118
- if (raw === "grok" || raw === "codex" || raw === "kimi" || raw === "claude") return raw;
119
- throw new Error(`unknown provider ${JSON.stringify(raw)}`);
120
- }
121
-
122
- function loginMethod(provider: CliProvider, flags: readonly string[]): SubscriptionLoginMethod | undefined {
123
- if (provider === "codex") return flags.includes("--browser") ? "browser" : "device";
124
- if (provider === "kimi") return "device";
125
- if (provider === "claude") return "browser";
126
- return undefined;
127
- }
128
-
129
- function allowedFlags(action: CliAction, provider: CliProvider): readonly string[] {
130
- if (action !== "login") return [];
131
- if (provider === "grok") return ["--pkce", "--device-auth"];
132
- if (provider === "codex") return ["--device-auth", "--browser"];
133
- if (provider === "kimi") return ["--device-auth"];
134
- if (provider === "claude") return ["--browser"];
135
- return [];
136
- }
137
-
138
- async function subscriptionStatus(provider: Exclude<CliProvider, "all" | "grok">): Promise<boolean> {
139
- const definition = oauthProviderDefinition(provider);
140
- if (definition === undefined) throw new Error(`provider ${provider} is not configured`);
141
- const session = new OAuthProviderSession(definition);
142
- await session.loadCachedModels();
143
- const status = await session.status();
144
- if (!status.authenticated) {
145
- process.stdout.write(`${definition.displayName} for dsh: signed out\n`);
146
- return false;
147
- }
148
- const suffix =
149
- status.expiresAt === undefined
150
- ? ""
151
- : `; access token expires ${new Date(status.expiresAt).toISOString()} (refresh is automatic)`;
152
- process.stdout.write(`${definition.displayName} for dsh: signed in${suffix}\n`);
153
- process.stdout.write(
154
- `models: ${session
155
- .visibleModels()
156
- .map((model) => model.id)
157
- .join(", ")}\n`,
158
- );
159
- return true;
160
- }
161
-
162
- async function printGatewayWarning(): Promise<void> {
163
- try {
164
- const response = await fetch(`http://${GATEWAY_DEFAULT_BIND}:${String(GATEWAY_DEFAULT_PORT)}/healthz`, {
165
- signal: AbortSignal.timeout(200),
166
- });
167
- if (!response.ok) return;
168
- process.stdout.write(`WARNING: ${GATEWAY_TOS_WARNING}\n`);
169
- } catch {
170
- // Gateway is off or not on the default loopback port.
171
- }
172
- }
173
-
174
- async function grokStatus(): Promise<boolean> {
175
- const session = new GrokBuildSession();
176
- await session.loadCachedCatalog();
177
- const status = await grokBuildAuthStatus(session.store);
178
- if (!status.authenticated) {
179
- process.stdout.write("Grok Build for dsh: signed out\n");
180
- return false;
181
- }
182
- await session.refreshLiveCatalog();
183
- const expires = status.expiresAt;
184
- const suffix =
185
- expires === undefined || Number.isNaN(expires.valueOf())
186
- ? ""
187
- : `; access token expires ${expires.toISOString()} (refresh is automatic)`;
188
- process.stdout.write(`Grok Build for dsh: signed in${suffix}\n`);
189
- process.stdout.write(
190
- `models (${session.catalogSource}): ${session
191
- .visibleModels()
192
- .map((model) => model.id)
193
- .join(", ")}\n`,
194
- );
195
- if (session.catalogError !== undefined) {
196
- process.stderr.write(`dsh-coding-oauth: live models-v2 failed: ${session.catalogError}\n`);
197
- }
198
- return true;
199
- }
200
-
201
- async function loginSubscription(
202
- provider: Exclude<CliProvider, "all" | "grok">,
203
- flags: readonly string[],
204
- ): Promise<void> {
205
- const definition = oauthProviderDefinition(provider);
206
- if (definition === undefined) throw new Error(`provider ${provider} is not configured`);
207
- const method = loginMethod(provider, flags);
208
- const session = new OAuthProviderSession(definition);
209
- await session.loadCachedModels();
210
- const readline = createInterface({ input: process.stdin, output: process.stdout });
211
- try {
212
- await session.login({
213
- prompt: (prompt) => answerPrompt(prompt, (text, options) => readline.question(text, options), method),
214
- notify: (event) => notify(event, true),
215
- });
216
- } finally {
217
- readline.close();
218
- }
219
- process.stdout.write(
220
- `${definition.displayName} for dsh: signed in; credentials saved to ${session.store.filename}\n`,
221
- );
222
- process.stdout.write(
223
- `models: ${session
224
- .visibleModels()
225
- .map((model) => model.id)
226
- .join(", ")}\n`,
227
- );
228
- }
229
-
230
- async function loginGrok(flags: readonly string[]): Promise<void> {
231
- const usePkce = flags.includes("--pkce");
232
- const session = new GrokBuildSession();
233
- const readline = createInterface({ input: process.stdin, output: process.stdout });
234
- try {
235
- if (usePkce) {
236
- const credential = await loginGrokBuildPkce({
237
- onAuthorizeUrl: (url) => {
238
- process.stdout.write(`Open this URL to sign in:\n${url}\n`);
239
- openBrowser(url);
240
- },
241
- awaitCode: (signal) =>
242
- readline.question("After authorizing, paste the code or full redirect URL: ", { signal }),
243
- });
244
- const written = await session.store.modify(XAI_PI_PROVIDER, async () => credential);
245
- if (written === undefined) throw new Error("credential store refused the login credential");
246
- await session.refreshLiveCatalog();
247
- } else {
248
- await loginGrokBuildSession(
249
- {
250
- prompt: (prompt) => answerPrompt(prompt, (text, options) => readline.question(text, options)),
251
- notify: (event) => notify(event, true),
252
- },
253
- session,
254
- );
255
- }
256
- } finally {
257
- readline.close();
258
- }
259
- process.stdout.write(`Grok Build for dsh: signed in; credentials saved to ${grokBuildAuthPath()}\n`);
260
- process.stdout.write(
261
- `models (${session.catalogSource}): ${session
262
- .visibleModels()
263
- .map((model) => model.id)
264
- .join(", ")}\n`,
265
- );
266
- }
267
-
268
- export async function run(argv: readonly string[]): Promise<number> {
269
- ensureCodingOAuthProxy();
270
- if (argv.length === 0 || argv[0] === "--help" || argv[0] === "-h") {
271
- printHelp();
272
- return 0;
273
- }
274
- const rawAction = argv[0];
275
- if (rawAction !== "login" && rawAction !== "logout" && rawAction !== "status" && rawAction !== "import") {
276
- process.stderr.write(
277
- `dsh-coding-oauth: expected login, logout, status, or import; got ${JSON.stringify(rawAction)}\n`,
278
- );
279
- return 1;
280
- }
281
- const action: CliAction = rawAction;
282
- try {
283
- const provider = parseProvider(argv[1], action);
284
- const flags = argv[1]?.startsWith("--") === true ? argv.slice(1) : argv.slice(2);
285
- const allowed = allowedFlags(action, provider);
286
- if (flags.some((flag) => !allowed.includes(flag))) {
287
- throw new Error(`invalid options for ${action} ${provider}: ${flags.join(" ")}`);
288
- }
289
- if (action === "import" && provider !== "grok") throw new Error("import is supported only for Grok Build");
290
- if (action !== "status" && provider === "all") throw new Error(`${action} does not accept provider all`);
291
-
292
- if (action === "status") {
293
- if (provider === "all") {
294
- const results = await Promise.all([
295
- grokStatus(),
296
- subscriptionStatus("codex"),
297
- subscriptionStatus("kimi"),
298
- subscriptionStatus("claude"),
299
- ]);
300
- await printGatewayWarning();
301
- return results.some(Boolean) ? 0 : 1;
302
- }
303
- const signedIn = provider === "grok" ? await grokStatus() : await subscriptionStatus(provider);
304
- await printGatewayWarning();
305
- return signedIn ? 0 : 1;
306
- }
307
-
308
- if (action === "logout") {
309
- if (provider === "grok") {
310
- await new GrokBuildSession().logout();
311
- process.stdout.write(`Grok Build for dsh: signed out; removed ${grokBuildAuthPath()}\n`);
312
- } else {
313
- const definition = oauthProviderDefinition(provider);
314
- if (definition === undefined) throw new Error(`provider ${provider} is not configured`);
315
- const session = new OAuthProviderSession(definition);
316
- await session.logout();
317
- process.stdout.write(`${definition.displayName} for dsh: signed out; removed ${session.store.filename}\n`);
318
- }
319
- return 0;
320
- }
321
-
322
- if (action === "import") {
323
- const session = new GrokBuildSession();
324
- await importGrokBuildSession(session);
325
- process.stdout.write(`Grok Build for dsh: imported ${grokAuthPath()} into ${grokBuildAuthPath()}\n`);
326
- process.stdout.write("The Grok CLI file was not modified. Later dsh refresh may rotate the token.\n");
327
- process.stdout.write(
328
- `models (${session.catalogSource}): ${session
329
- .visibleModels()
330
- .map((model) => model.id)
331
- .join(", ")}\n`,
332
- );
333
- return 0;
334
- }
335
-
336
- const proxy = codingOAuthProxyInEffect();
337
- if (proxy !== undefined) process.stdout.write(`Using scoped coding OAuth proxy ${redactProxyUrl(proxy)}\n`);
338
- if (provider === "all") throw new Error("login does not accept provider all");
339
- if (provider === "grok") await loginGrok(flags);
340
- else await loginSubscription(provider, flags);
341
- return 0;
342
- } catch (error: unknown) {
343
- process.stderr.write(`dsh-coding-oauth: ${action} failed: ${safeMessage(error)}\n`);
344
- return 1;
345
- }
346
- }
347
-
348
- if (process.argv[1] !== undefined && fileURLToPath(import.meta.url) === realpathSync(process.argv[1])) {
349
- process.exitCode = await run(process.argv.slice(2));
350
- }
1
+ #!/usr/bin/env node
2
+ /** Standalone credential CLI for the coding-subscription bundle. */
3
+
4
+ import { spawn } from "node:child_process";
5
+ import { realpathSync } from "node:fs";
6
+ import { createInterface } from "node:readline/promises";
7
+ import { fileURLToPath } from "node:url";
8
+ import type { AuthEvent, AuthPrompt } from "@earendil-works/pi-ai";
9
+ import { grokBuildAuthStatus, importGrokBuildSession, loginGrokBuildSession } from "./auth.ts";
10
+ import { GATEWAY_TOS_WARNING } from "./gateway.ts";
11
+ import { GATEWAY_DEFAULT_BIND, GATEWAY_DEFAULT_PORT } from "./gateway-config.ts";
12
+ import { grokAuthPath } from "./grok-import.ts";
13
+ import { XAI_PI_PROVIDER } from "./ids.ts";
14
+ import { loginGrokBuildPkce } from "./oauth.ts";
15
+ import { oauthProviderDefinition, type SubscriptionLoginMethod } from "./oauth-providers.ts";
16
+ import { OAuthProviderSession } from "./oauth-session.ts";
17
+ import { codingOAuthProxyInEffect, ensureCodingOAuthProxy } from "./proxy.ts";
18
+ import { redactProxyUrl, safeMessage } from "./redact.ts";
19
+ import { GrokBuildSession } from "./session.ts";
20
+ import { grokBuildAuthPath } from "./store.ts";
21
+
22
+ export type CliAction = "login" | "logout" | "status" | "import";
23
+ export type CliProvider = "all" | "grok" | "codex" | "kimi" | "claude";
24
+
25
+ function openBrowser(rawUrl: string): void {
26
+ const url = new URL(rawUrl);
27
+ if (url.protocol !== "https:") throw new Error(`refusing to open non-HTTPS authorization URL from ${url.host}`);
28
+ const command =
29
+ process.platform === "win32"
30
+ ? { file: "rundll32.exe", args: ["url.dll,FileProtocolHandler", url.href] }
31
+ : process.platform === "darwin"
32
+ ? { file: "open", args: [url.href] }
33
+ : { file: "xdg-open", args: [url.href] };
34
+ try {
35
+ const child = spawn(command.file, command.args, {
36
+ detached: true,
37
+ stdio: "ignore",
38
+ windowsHide: true,
39
+ });
40
+ child.on("error", () => {});
41
+ child.unref();
42
+ } catch {
43
+ // The printed URL remains the manual fallback.
44
+ }
45
+ }
46
+
47
+ function notify(event: AuthEvent, useBrowser: boolean): void {
48
+ switch (event.type) {
49
+ case "auth_url":
50
+ process.stdout.write(`Open this URL to sign in:\n${event.url}\n`);
51
+ if (event.instructions !== undefined) process.stdout.write(`${event.instructions}\n`);
52
+ if (useBrowser) openBrowser(event.url);
53
+ break;
54
+ case "device_code":
55
+ process.stdout.write(`Open this URL to sign in:\n${event.verificationUri}\n`);
56
+ if (event.userCode.length > 0) process.stdout.write(`Enter code: ${event.userCode}\n`);
57
+ if (useBrowser) openBrowser(event.verificationUri);
58
+ break;
59
+ case "info":
60
+ case "progress":
61
+ process.stdout.write(`${event.message}\n`);
62
+ break;
63
+ default:
64
+ event satisfies never;
65
+ }
66
+ }
67
+
68
+ function selectLoginOption(prompt: Extract<AuthPrompt, { type: "select" }>, method?: SubscriptionLoginMethod): string {
69
+ if (method !== undefined) {
70
+ const exact = method === "device" ? ["device_code", "device-code", "device"] : ["browser", "browser_login"];
71
+ for (const id of exact) if (prompt.options.some((option) => option.id === id)) return id;
72
+ const label = method === "device" ? /device|headless/iu : /browser|pkce/iu;
73
+ const match = prompt.options.find((option) => label.test(option.label));
74
+ if (match !== undefined) return match.id;
75
+ }
76
+ const oauth = prompt.options.find((option) => option.id === "oauth" || option.id.includes("oauth"));
77
+ return oauth?.id ?? prompt.options[0]?.id ?? "";
78
+ }
79
+
80
+ async function answerPrompt(
81
+ prompt: AuthPrompt,
82
+ question: (text: string, options: { signal?: AbortSignal }) => Promise<string>,
83
+ method?: SubscriptionLoginMethod,
84
+ ): Promise<string> {
85
+ if (prompt.type === "select") return selectLoginOption(prompt, method);
86
+ const suffix = prompt.placeholder === undefined ? "" : ` (${prompt.placeholder})`;
87
+ return question(`${prompt.message}${suffix}: `, {
88
+ ...(prompt.signal === undefined ? {} : { signal: prompt.signal }),
89
+ });
90
+ }
91
+
92
+ function printHelp(): void {
93
+ process.stdout.write(
94
+ [
95
+ "Usage: dsh-coding-oauth <login|logout|status|import> [provider] [options]",
96
+ "(legacy command name: dsh-grok-build)",
97
+ "",
98
+ "Providers: grok (default), codex, kimi, claude; status also accepts all.",
99
+ "",
100
+ " login grok [--pkce|--device-auth]",
101
+ " login codex [--device-auth|--browser] (device code is the default)",
102
+ " login kimi (device code)",
103
+ " login claude [--browser] (PKCE + redirect paste fallback)",
104
+ " import [grok] import ~/.grok/auth.json only",
105
+ " logout [provider]",
106
+ " status [provider|all]",
107
+ "",
108
+ "Network: set CODING_OAUTH_PROXY, GROK_BUILD_PROXY, or HTTPS_PROXY.",
109
+ "Only audited subscription hosts use the proxy; Kimi stays direct by default.",
110
+ "",
111
+ ].join("\n"),
112
+ );
113
+ }
114
+
115
+ function parseProvider(raw: string | undefined, action: CliAction): CliProvider {
116
+ if (raw === undefined || raw.startsWith("--")) return "grok";
117
+ if (raw === "all" && action === "status") return raw;
118
+ if (raw === "grok" || raw === "codex" || raw === "kimi" || raw === "claude") return raw;
119
+ throw new Error(`unknown provider ${JSON.stringify(raw)}`);
120
+ }
121
+
122
+ function loginMethod(provider: CliProvider, flags: readonly string[]): SubscriptionLoginMethod | undefined {
123
+ if (provider === "codex") return flags.includes("--browser") ? "browser" : "device";
124
+ if (provider === "kimi") return "device";
125
+ if (provider === "claude") return "browser";
126
+ return undefined;
127
+ }
128
+
129
+ function allowedFlags(action: CliAction, provider: CliProvider): readonly string[] {
130
+ if (action !== "login") return [];
131
+ if (provider === "grok") return ["--pkce", "--device-auth"];
132
+ if (provider === "codex") return ["--device-auth", "--browser"];
133
+ if (provider === "kimi") return ["--device-auth"];
134
+ if (provider === "claude") return ["--browser"];
135
+ return [];
136
+ }
137
+
138
+ async function subscriptionStatus(provider: Exclude<CliProvider, "all" | "grok">): Promise<boolean> {
139
+ const definition = oauthProviderDefinition(provider);
140
+ if (definition === undefined) throw new Error(`provider ${provider} is not configured`);
141
+ const session = new OAuthProviderSession(definition);
142
+ await session.loadCachedModels();
143
+ const status = await session.status();
144
+ if (!status.authenticated) {
145
+ process.stdout.write(`${definition.displayName} for dsh: signed out\n`);
146
+ return false;
147
+ }
148
+ const suffix =
149
+ status.expiresAt === undefined
150
+ ? ""
151
+ : `; access token expires ${new Date(status.expiresAt).toISOString()} (refresh is automatic)`;
152
+ process.stdout.write(`${definition.displayName} for dsh: signed in${suffix}\n`);
153
+ process.stdout.write(
154
+ `models: ${session
155
+ .visibleModels()
156
+ .map((model) => model.id)
157
+ .join(", ")}\n`,
158
+ );
159
+ return true;
160
+ }
161
+
162
+ async function printGatewayWarning(): Promise<void> {
163
+ try {
164
+ const response = await fetch(`http://${GATEWAY_DEFAULT_BIND}:${String(GATEWAY_DEFAULT_PORT)}/healthz`, {
165
+ signal: AbortSignal.timeout(200),
166
+ });
167
+ if (!response.ok) return;
168
+ process.stdout.write(`WARNING: ${GATEWAY_TOS_WARNING}\n`);
169
+ } catch {
170
+ // Gateway is off or not on the default loopback port.
171
+ }
172
+ }
173
+
174
+ async function grokStatus(): Promise<boolean> {
175
+ const session = new GrokBuildSession();
176
+ await session.loadCachedCatalog();
177
+ const status = await grokBuildAuthStatus(session.store);
178
+ if (!status.authenticated) {
179
+ process.stdout.write("Grok Build for dsh: signed out\n");
180
+ return false;
181
+ }
182
+ await session.refreshLiveCatalog();
183
+ const expires = status.expiresAt;
184
+ const suffix =
185
+ expires === undefined || Number.isNaN(expires.valueOf())
186
+ ? ""
187
+ : `; access token expires ${expires.toISOString()} (refresh is automatic)`;
188
+ process.stdout.write(`Grok Build for dsh: signed in${suffix}\n`);
189
+ process.stdout.write(
190
+ `models (${session.catalogSource}): ${session
191
+ .visibleModels()
192
+ .map((model) => model.id)
193
+ .join(", ")}\n`,
194
+ );
195
+ if (session.catalogError !== undefined) {
196
+ process.stderr.write(`dsh-coding-oauth: live models-v2 failed: ${session.catalogError}\n`);
197
+ }
198
+ return true;
199
+ }
200
+
201
+ async function loginSubscription(
202
+ provider: Exclude<CliProvider, "all" | "grok">,
203
+ flags: readonly string[],
204
+ ): Promise<void> {
205
+ const definition = oauthProviderDefinition(provider);
206
+ if (definition === undefined) throw new Error(`provider ${provider} is not configured`);
207
+ const method = loginMethod(provider, flags);
208
+ const session = new OAuthProviderSession(definition);
209
+ await session.loadCachedModels();
210
+ const readline = createInterface({ input: process.stdin, output: process.stdout });
211
+ try {
212
+ await session.login({
213
+ prompt: (prompt) => answerPrompt(prompt, (text, options) => readline.question(text, options), method),
214
+ notify: (event) => notify(event, true),
215
+ });
216
+ } finally {
217
+ readline.close();
218
+ }
219
+ process.stdout.write(
220
+ `${definition.displayName} for dsh: signed in; credentials saved to ${session.store.filename}\n`,
221
+ );
222
+ process.stdout.write(
223
+ `models: ${session
224
+ .visibleModels()
225
+ .map((model) => model.id)
226
+ .join(", ")}\n`,
227
+ );
228
+ }
229
+
230
+ async function loginGrok(flags: readonly string[]): Promise<void> {
231
+ const usePkce = flags.includes("--pkce");
232
+ const session = new GrokBuildSession();
233
+ const readline = createInterface({ input: process.stdin, output: process.stdout });
234
+ try {
235
+ if (usePkce) {
236
+ const credential = await loginGrokBuildPkce({
237
+ onAuthorizeUrl: (url) => {
238
+ process.stdout.write(`Open this URL to sign in:\n${url}\n`);
239
+ openBrowser(url);
240
+ },
241
+ awaitCode: (signal) =>
242
+ readline.question("After authorizing, paste the code or full redirect URL: ", { signal }),
243
+ });
244
+ const written = await session.store.modify(XAI_PI_PROVIDER, async () => credential);
245
+ if (written === undefined) throw new Error("credential store refused the login credential");
246
+ await session.refreshLiveCatalog();
247
+ } else {
248
+ await loginGrokBuildSession(
249
+ {
250
+ prompt: (prompt) => answerPrompt(prompt, (text, options) => readline.question(text, options)),
251
+ notify: (event) => notify(event, true),
252
+ },
253
+ session,
254
+ );
255
+ }
256
+ } finally {
257
+ readline.close();
258
+ }
259
+ process.stdout.write(`Grok Build for dsh: signed in; credentials saved to ${grokBuildAuthPath()}\n`);
260
+ process.stdout.write(
261
+ `models (${session.catalogSource}): ${session
262
+ .visibleModels()
263
+ .map((model) => model.id)
264
+ .join(", ")}\n`,
265
+ );
266
+ }
267
+
268
+ export async function run(argv: readonly string[]): Promise<number> {
269
+ ensureCodingOAuthProxy();
270
+ if (argv.length === 0 || argv[0] === "--help" || argv[0] === "-h") {
271
+ printHelp();
272
+ return 0;
273
+ }
274
+ const rawAction = argv[0];
275
+ if (rawAction !== "login" && rawAction !== "logout" && rawAction !== "status" && rawAction !== "import") {
276
+ process.stderr.write(
277
+ `dsh-coding-oauth: expected login, logout, status, or import; got ${JSON.stringify(rawAction)}\n`,
278
+ );
279
+ return 1;
280
+ }
281
+ const action: CliAction = rawAction;
282
+ try {
283
+ const provider = parseProvider(argv[1], action);
284
+ const flags = argv[1]?.startsWith("--") === true ? argv.slice(1) : argv.slice(2);
285
+ const allowed = allowedFlags(action, provider);
286
+ if (flags.some((flag) => !allowed.includes(flag))) {
287
+ throw new Error(`invalid options for ${action} ${provider}: ${flags.join(" ")}`);
288
+ }
289
+ if (action === "import" && provider !== "grok") throw new Error("import is supported only for Grok Build");
290
+ if (action !== "status" && provider === "all") throw new Error(`${action} does not accept provider all`);
291
+
292
+ if (action === "status") {
293
+ if (provider === "all") {
294
+ const results = await Promise.all([
295
+ grokStatus(),
296
+ subscriptionStatus("codex"),
297
+ subscriptionStatus("kimi"),
298
+ subscriptionStatus("claude"),
299
+ ]);
300
+ await printGatewayWarning();
301
+ return results.some(Boolean) ? 0 : 1;
302
+ }
303
+ const signedIn = provider === "grok" ? await grokStatus() : await subscriptionStatus(provider);
304
+ await printGatewayWarning();
305
+ return signedIn ? 0 : 1;
306
+ }
307
+
308
+ if (action === "logout") {
309
+ if (provider === "grok") {
310
+ await new GrokBuildSession().logout();
311
+ process.stdout.write(`Grok Build for dsh: signed out; removed ${grokBuildAuthPath()}\n`);
312
+ } else {
313
+ const definition = oauthProviderDefinition(provider);
314
+ if (definition === undefined) throw new Error(`provider ${provider} is not configured`);
315
+ const session = new OAuthProviderSession(definition);
316
+ await session.logout();
317
+ process.stdout.write(`${definition.displayName} for dsh: signed out; removed ${session.store.filename}\n`);
318
+ }
319
+ return 0;
320
+ }
321
+
322
+ if (action === "import") {
323
+ const session = new GrokBuildSession();
324
+ await importGrokBuildSession(session);
325
+ process.stdout.write(`Grok Build for dsh: imported ${grokAuthPath()} into ${grokBuildAuthPath()}\n`);
326
+ process.stdout.write("The Grok CLI file was not modified. Later dsh refresh may rotate the token.\n");
327
+ process.stdout.write(
328
+ `models (${session.catalogSource}): ${session
329
+ .visibleModels()
330
+ .map((model) => model.id)
331
+ .join(", ")}\n`,
332
+ );
333
+ return 0;
334
+ }
335
+
336
+ const proxy = codingOAuthProxyInEffect();
337
+ if (proxy !== undefined) process.stdout.write(`Using scoped coding OAuth proxy ${redactProxyUrl(proxy)}\n`);
338
+ if (provider === "all") throw new Error("login does not accept provider all");
339
+ if (provider === "grok") await loginGrok(flags);
340
+ else await loginSubscription(provider, flags);
341
+ return 0;
342
+ } catch (error: unknown) {
343
+ process.stderr.write(`dsh-coding-oauth: ${action} failed: ${safeMessage(error)}\n`);
344
+ return 1;
345
+ }
346
+ }
347
+
348
+ if (process.argv[1] !== undefined && fileURLToPath(import.meta.url) === realpathSync(process.argv[1])) {
349
+ process.exitCode = await run(process.argv.slice(2));
350
+ }