dsh-coding-subscription-oauth 0.5.8 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (141) hide show
  1. package/CHANGELOG.md +211 -196
  2. package/CONTRIBUTING.md +120 -120
  3. package/INSTALL.md +240 -209
  4. package/LICENSE +19 -19
  5. package/NOTICE +11 -11
  6. package/README.de.md +298 -293
  7. package/README.es.md +299 -294
  8. package/README.fr.md +299 -294
  9. package/README.ja.md +299 -294
  10. package/README.ko.md +299 -294
  11. package/README.md +313 -306
  12. package/README.pt-BR.md +299 -294
  13. package/README.ru.md +299 -294
  14. package/README.zh-CN.md +311 -304
  15. package/compatibility/dsh-bom.json +43 -0
  16. package/cordis.patch.yml +13 -13
  17. package/docs/00-project-rules.md +195 -195
  18. package/docs/02-architecture.md +134 -129
  19. package/docs/02-architecture.zh-CN.md +134 -129
  20. package/lib/auth-routes.d.ts +8 -15
  21. package/lib/auth-routes.d.ts.map +1 -1
  22. package/lib/bin.js +746 -1402
  23. package/lib/bin.js.map +4 -4
  24. package/lib/capability-routes.d.ts +3 -3
  25. package/lib/capability-routes.d.ts.map +1 -1
  26. package/lib/capability-settings.d.ts +5 -4
  27. package/lib/capability-settings.d.ts.map +1 -1
  28. package/lib/client.js +27 -8
  29. package/lib/client.js.map +4 -4
  30. package/lib/compatibility.d.ts +46 -0
  31. package/lib/compatibility.d.ts.map +1 -0
  32. package/lib/dsh-host-adapter.d.ts +18 -0
  33. package/lib/dsh-host-adapter.d.ts.map +1 -0
  34. package/lib/gateway-auth.d.ts +1 -2
  35. package/lib/gateway-auth.d.ts.map +1 -1
  36. package/lib/gateway-routes.d.ts +3 -4
  37. package/lib/gateway-routes.d.ts.map +1 -1
  38. package/lib/gateway.d.ts +4 -0
  39. package/lib/gateway.d.ts.map +1 -1
  40. package/lib/ids.d.ts +3 -32
  41. package/lib/ids.d.ts.map +1 -1
  42. package/lib/imagine-routes.d.ts +2 -0
  43. package/lib/imagine-routes.d.ts.map +1 -1
  44. package/lib/index.d.ts +19 -4
  45. package/lib/index.d.ts.map +1 -1
  46. package/lib/index.js +26573 -1023
  47. package/lib/index.js.map +4 -4
  48. package/lib/invariant.js.map +1 -1
  49. package/lib/oauth-import-routes.d.ts +3 -4
  50. package/lib/oauth-import-routes.d.ts.map +1 -1
  51. package/lib/proxy.d.ts +3 -16
  52. package/lib/proxy.d.ts.map +1 -1
  53. package/lib/web-origin.d.ts +28 -4
  54. package/lib/web-origin.d.ts.map +1 -1
  55. package/lib/web-routes.d.ts.map +1 -1
  56. package/media/en/settings_accounts.png +0 -0
  57. package/media/en/settings_capabilities.png +0 -0
  58. package/media/en/settings_gateway.png +0 -0
  59. package/media/zh-CN/settings_accounts.png +0 -0
  60. package/media/zh-CN/settings_capabilities.png +0 -0
  61. package/media/zh-CN/settings_gateway.png +0 -0
  62. package/package.json +209 -172
  63. package/patches/dsh-agy@0.1.2.patch +25 -25
  64. package/scripts/release.mjs +186 -170
  65. package/scripts/smoke-deployed-routes.mjs +146 -146
  66. package/scripts/verify-deployed-catalog.mjs +87 -87
  67. package/src/adapter.ts +287 -287
  68. package/src/alias-adapter.ts +153 -153
  69. package/src/auth-routes.ts +921 -871
  70. package/src/auth.ts +67 -67
  71. package/src/bin.ts +350 -350
  72. package/src/capability-routes.ts +279 -275
  73. package/src/capability-runtime.ts +313 -313
  74. package/src/capability-settings.ts +658 -657
  75. package/src/capability-tools.ts +666 -666
  76. package/src/catalog.ts +271 -271
  77. package/src/client/GrokBuildSettings.tsx +770 -718
  78. package/src/client/api.ts +88 -88
  79. package/src/client/components/AboutTab.tsx +30 -30
  80. package/src/client/components/AccountsTab.tsx +241 -224
  81. package/src/client/components/Badge.tsx +33 -33
  82. package/src/client/components/CapabilitiesTab.tsx +265 -227
  83. package/src/client/components/CliPullPreview.tsx +116 -107
  84. package/src/client/components/CopyButton.tsx +57 -57
  85. package/src/client/components/GatewayTab.tsx +469 -409
  86. package/src/client/components/NoticeBanner.tsx +46 -46
  87. package/src/client/components/ProgressBar.tsx +53 -53
  88. package/src/client/components/ProviderCard.tsx +606 -502
  89. package/src/client/components/SettingsTabs.tsx +75 -75
  90. package/src/client/components/ToggleSwitch.tsx +71 -62
  91. package/src/client/constants.ts +224 -206
  92. package/src/client/display.ts +61 -61
  93. package/src/client/dshClientAdapter.ts +109 -0
  94. package/src/client/gatewaySnippets.ts +37 -36
  95. package/src/client/index.tsx +156 -37
  96. package/src/client/locales.ts +535 -491
  97. package/src/client/microStyles.ts +52 -33
  98. package/src/client/parsers.ts +396 -386
  99. package/src/client/styles.ts +325 -307
  100. package/src/client/types.ts +197 -185
  101. package/src/codex-http.ts +447 -447
  102. package/src/codex-images.ts +485 -485
  103. package/src/codex-model-capabilities.ts +320 -320
  104. package/src/codex-search.ts +245 -245
  105. package/src/codex-usage.ts +263 -263
  106. package/src/compatibility.ts +55 -0
  107. package/src/dsh-host-adapter.ts +171 -0
  108. package/src/gateway-anthropic-messages.ts +84 -84
  109. package/src/gateway-auth.ts +102 -100
  110. package/src/gateway-backend.ts +274 -274
  111. package/src/gateway-body.ts +49 -49
  112. package/src/gateway-config.ts +76 -76
  113. package/src/gateway-http.ts +104 -104
  114. package/src/gateway-openai-chat.ts +124 -124
  115. package/src/gateway-openai-responses.ts +53 -53
  116. package/src/gateway-parse.ts +224 -224
  117. package/src/gateway-protocol.ts +52 -52
  118. package/src/gateway-routes.ts +158 -152
  119. package/src/gateway.ts +258 -242
  120. package/src/grok-errors.ts +24 -24
  121. package/src/grok-imagine.ts +1627 -1627
  122. package/src/grok-import.ts +151 -151
  123. package/src/http-json.ts +82 -82
  124. package/src/ids.ts +59 -45
  125. package/src/imagine-routes.ts +463 -461
  126. package/src/index.ts +748 -598
  127. package/src/invariant.ts +17 -17
  128. package/src/kimi-errors.ts +26 -26
  129. package/src/media-store.ts +927 -927
  130. package/src/oauth-import-routes.ts +324 -314
  131. package/src/oauth-providers.ts +152 -152
  132. package/src/oauth-session.ts +183 -183
  133. package/src/oauth-sources.ts +1104 -1104
  134. package/src/oauth.ts +620 -620
  135. package/src/provider.ts +128 -128
  136. package/src/proxy.ts +11 -99
  137. package/src/redact.ts +72 -72
  138. package/src/session.ts +218 -218
  139. package/src/store.ts +217 -217
  140. package/src/web-origin.ts +296 -60
  141. package/src/web-routes.ts +38 -75
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
+ }