dsh-coding-subscription-oauth 0.6.3 → 0.6.4

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 (116) hide show
  1. package/CHANGELOG.md +258 -250
  2. package/CONTRIBUTING.md +129 -129
  3. package/INSTALL.md +256 -255
  4. package/LICENSE +19 -19
  5. package/NOTICE +11 -11
  6. package/README.de.md +303 -303
  7. package/README.es.md +304 -304
  8. package/README.fr.md +304 -304
  9. package/README.ja.md +304 -304
  10. package/README.ko.md +304 -304
  11. package/README.md +320 -320
  12. package/README.pt-BR.md +304 -304
  13. package/README.ru.md +304 -304
  14. package/README.zh-CN.md +318 -318
  15. package/compatibility/dsh-bom.json +30 -30
  16. package/cordis.patch.yml +13 -13
  17. package/docs/00-project-rules.md +212 -212
  18. package/docs/02-architecture.md +138 -138
  19. package/docs/02-architecture.zh-CN.md +138 -138
  20. package/lib/bin.js +1333 -569
  21. package/lib/bin.js.map +4 -4
  22. package/lib/client.js +1 -1
  23. package/lib/client.js.map +2 -2
  24. package/lib/index.js +689 -25492
  25. package/lib/index.js.map +4 -4
  26. package/lib/invariant.js.map +1 -1
  27. package/media/en/settings_accounts.png +0 -0
  28. package/media/en/settings_capabilities.png +0 -0
  29. package/media/en/settings_gateway.png +0 -0
  30. package/media/settings_accounts.png +0 -0
  31. package/media/settings_capabilities.png +0 -0
  32. package/media/settings_gateway.png +0 -0
  33. package/media/settings_overview.png +0 -0
  34. package/media/zh-CN/settings_accounts.png +0 -0
  35. package/media/zh-CN/settings_capabilities.png +0 -0
  36. package/media/zh-CN/settings_gateway.png +0 -0
  37. package/package.json +223 -223
  38. package/patches/dsh-agy@0.1.2.patch +25 -25
  39. package/scripts/release.mjs +186 -186
  40. package/scripts/smoke-deployed-routes.mjs +146 -146
  41. package/scripts/verify-deployed-catalog.mjs +87 -87
  42. package/src/adapter.ts +348 -348
  43. package/src/alias-adapter.ts +147 -147
  44. package/src/auth-routes.ts +921 -921
  45. package/src/auth.ts +67 -67
  46. package/src/bin.ts +350 -350
  47. package/src/capability-routes.ts +279 -279
  48. package/src/capability-runtime.ts +314 -314
  49. package/src/capability-settings.ts +671 -671
  50. package/src/capability-tools.ts +685 -685
  51. package/src/catalog.ts +271 -271
  52. package/src/client/GrokBuildSettings.tsx +771 -771
  53. package/src/client/api.ts +88 -88
  54. package/src/client/components/AboutTab.tsx +30 -30
  55. package/src/client/components/AccountsTab.tsx +241 -241
  56. package/src/client/components/Badge.tsx +33 -33
  57. package/src/client/components/CapabilitiesTab.tsx +265 -265
  58. package/src/client/components/CliPullPreview.tsx +116 -116
  59. package/src/client/components/CopyButton.tsx +57 -57
  60. package/src/client/components/GatewayTab.tsx +469 -469
  61. package/src/client/components/NoticeBanner.tsx +46 -46
  62. package/src/client/components/ProgressBar.tsx +53 -53
  63. package/src/client/components/ProviderCard.tsx +606 -606
  64. package/src/client/components/SettingsTabs.tsx +75 -75
  65. package/src/client/components/ToggleSwitch.tsx +71 -71
  66. package/src/client/constants.ts +230 -230
  67. package/src/client/display.ts +61 -61
  68. package/src/client/dshClientAdapter.ts +127 -127
  69. package/src/client/gatewaySnippets.ts +37 -37
  70. package/src/client/index.tsx +156 -156
  71. package/src/client/locales.ts +540 -540
  72. package/src/client/microStyles.ts +52 -52
  73. package/src/client/parsers.ts +398 -398
  74. package/src/client/styles.ts +325 -325
  75. package/src/client/types.ts +199 -199
  76. package/src/codex-http.ts +447 -447
  77. package/src/codex-images.ts +503 -503
  78. package/src/codex-model-capabilities.ts +320 -320
  79. package/src/codex-search.ts +245 -245
  80. package/src/codex-usage.ts +263 -263
  81. package/src/compatibility.ts +55 -55
  82. package/src/dsh-host-adapter.ts +173 -173
  83. package/src/gateway-anthropic-messages.ts +84 -84
  84. package/src/gateway-auth.ts +102 -102
  85. package/src/gateway-backend.ts +274 -274
  86. package/src/gateway-body.ts +49 -49
  87. package/src/gateway-config.ts +76 -76
  88. package/src/gateway-http.ts +104 -104
  89. package/src/gateway-openai-chat.ts +124 -124
  90. package/src/gateway-openai-responses.ts +53 -53
  91. package/src/gateway-parse.ts +224 -224
  92. package/src/gateway-protocol.ts +52 -52
  93. package/src/gateway-routes.ts +158 -158
  94. package/src/gateway.ts +258 -258
  95. package/src/grok-errors.ts +24 -24
  96. package/src/grok-imagine.ts +1627 -1627
  97. package/src/grok-import.ts +151 -151
  98. package/src/http-json.ts +82 -82
  99. package/src/ids.ts +59 -59
  100. package/src/imagine-routes.ts +463 -463
  101. package/src/index.ts +735 -735
  102. package/src/invariant.ts +17 -17
  103. package/src/kimi-errors.ts +26 -26
  104. package/src/media-store.ts +927 -927
  105. package/src/oauth-import-routes.ts +324 -324
  106. package/src/oauth-providers.ts +152 -152
  107. package/src/oauth-session.ts +183 -183
  108. package/src/oauth-sources.ts +1104 -1104
  109. package/src/oauth.ts +620 -620
  110. package/src/provider.ts +128 -128
  111. package/src/proxy.ts +11 -11
  112. package/src/redact.ts +72 -72
  113. package/src/session.ts +218 -218
  114. package/src/store.ts +217 -217
  115. package/src/web-origin.ts +296 -296
  116. 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
+ }