dsh-coding-subscription-oauth 0.5.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 (178) hide show
  1. package/CHANGELOG.md +136 -0
  2. package/CONTRIBUTING.md +109 -0
  3. package/INSTALL.md +220 -0
  4. package/LICENSE +19 -0
  5. package/NOTICE +11 -0
  6. package/README.de.md +254 -0
  7. package/README.es.md +254 -0
  8. package/README.fr.md +254 -0
  9. package/README.ja.md +254 -0
  10. package/README.ko.md +254 -0
  11. package/README.md +286 -0
  12. package/README.pt-BR.md +254 -0
  13. package/README.ru.md +254 -0
  14. package/README.zh-CN.md +271 -0
  15. package/cordis.patch.yml +13 -0
  16. package/docs/00-project-rules.md +195 -0
  17. package/docs/02-architecture.md +132 -0
  18. package/docs/02-architecture.zh-CN.md +128 -0
  19. package/lib/adapter.d.ts +24 -0
  20. package/lib/adapter.d.ts.map +1 -0
  21. package/lib/alias-adapter.d.ts +43 -0
  22. package/lib/alias-adapter.d.ts.map +1 -0
  23. package/lib/auth-routes.d.ts +155 -0
  24. package/lib/auth-routes.d.ts.map +1 -0
  25. package/lib/auth.d.ts +29 -0
  26. package/lib/auth.d.ts.map +1 -0
  27. package/lib/bin.d.ts +6 -0
  28. package/lib/bin.d.ts.map +1 -0
  29. package/lib/bin.js +27591 -0
  30. package/lib/bin.js.map +7 -0
  31. package/lib/capability-routes.d.ts +43 -0
  32. package/lib/capability-routes.d.ts.map +1 -0
  33. package/lib/capability-runtime.d.ts +56 -0
  34. package/lib/capability-runtime.d.ts.map +1 -0
  35. package/lib/capability-settings.d.ts +263 -0
  36. package/lib/capability-settings.d.ts.map +1 -0
  37. package/lib/capability-tools.d.ts +50 -0
  38. package/lib/capability-tools.d.ts.map +1 -0
  39. package/lib/catalog.d.ts +53 -0
  40. package/lib/catalog.d.ts.map +1 -0
  41. package/lib/client.js +3 -0
  42. package/lib/client.js.map +7 -0
  43. package/lib/codex-http.d.ts +77 -0
  44. package/lib/codex-http.d.ts.map +1 -0
  45. package/lib/codex-images.d.ts +109 -0
  46. package/lib/codex-images.d.ts.map +1 -0
  47. package/lib/codex-model-capabilities.d.ts +112 -0
  48. package/lib/codex-model-capabilities.d.ts.map +1 -0
  49. package/lib/codex-search.d.ts +96 -0
  50. package/lib/codex-search.d.ts.map +1 -0
  51. package/lib/codex-usage.d.ts +79 -0
  52. package/lib/codex-usage.d.ts.map +1 -0
  53. package/lib/gateway-anthropic-messages.d.ts +8 -0
  54. package/lib/gateway-anthropic-messages.d.ts.map +1 -0
  55. package/lib/gateway-auth.d.ts +22 -0
  56. package/lib/gateway-auth.d.ts.map +1 -0
  57. package/lib/gateway-backend.d.ts +62 -0
  58. package/lib/gateway-backend.d.ts.map +1 -0
  59. package/lib/gateway-body.d.ts +9 -0
  60. package/lib/gateway-body.d.ts.map +1 -0
  61. package/lib/gateway-config.d.ts +24 -0
  62. package/lib/gateway-config.d.ts.map +1 -0
  63. package/lib/gateway-http.d.ts +16 -0
  64. package/lib/gateway-http.d.ts.map +1 -0
  65. package/lib/gateway-openai-chat.d.ts +8 -0
  66. package/lib/gateway-openai-chat.d.ts.map +1 -0
  67. package/lib/gateway-openai-responses.d.ts +8 -0
  68. package/lib/gateway-openai-responses.d.ts.map +1 -0
  69. package/lib/gateway-parse.d.ts +10 -0
  70. package/lib/gateway-parse.d.ts.map +1 -0
  71. package/lib/gateway-protocol.d.ts +47 -0
  72. package/lib/gateway-protocol.d.ts.map +1 -0
  73. package/lib/gateway-routes.d.ts +21 -0
  74. package/lib/gateway-routes.d.ts.map +1 -0
  75. package/lib/gateway.d.ts +48 -0
  76. package/lib/gateway.d.ts.map +1 -0
  77. package/lib/grok-imagine.d.ts +271 -0
  78. package/lib/grok-imagine.d.ts.map +1 -0
  79. package/lib/grok-import.d.ts +21 -0
  80. package/lib/grok-import.d.ts.map +1 -0
  81. package/lib/http-json.d.ts +10 -0
  82. package/lib/http-json.d.ts.map +1 -0
  83. package/lib/ids.d.ts +33 -0
  84. package/lib/ids.d.ts.map +1 -0
  85. package/lib/imagine-routes.d.ts +59 -0
  86. package/lib/imagine-routes.d.ts.map +1 -0
  87. package/lib/index.d.ts +69 -0
  88. package/lib/index.d.ts.map +1 -0
  89. package/lib/index.js +35355 -0
  90. package/lib/index.js.map +7 -0
  91. package/lib/invariant.d.ts +9 -0
  92. package/lib/invariant.d.ts.map +1 -0
  93. package/lib/invariant.js +14 -0
  94. package/lib/invariant.js.map +7 -0
  95. package/lib/kimi-errors.d.ts +13 -0
  96. package/lib/kimi-errors.d.ts.map +1 -0
  97. package/lib/media-store.d.ts +130 -0
  98. package/lib/media-store.d.ts.map +1 -0
  99. package/lib/oauth-import-routes.d.ts +52 -0
  100. package/lib/oauth-import-routes.d.ts.map +1 -0
  101. package/lib/oauth-providers.d.ts +26 -0
  102. package/lib/oauth-providers.d.ts.map +1 -0
  103. package/lib/oauth-session.d.ts +40 -0
  104. package/lib/oauth-session.d.ts.map +1 -0
  105. package/lib/oauth-sources.d.ts +205 -0
  106. package/lib/oauth-sources.d.ts.map +1 -0
  107. package/lib/oauth.d.ts +79 -0
  108. package/lib/oauth.d.ts.map +1 -0
  109. package/lib/provider.d.ts +38 -0
  110. package/lib/provider.d.ts.map +1 -0
  111. package/lib/proxy.d.ts +17 -0
  112. package/lib/proxy.d.ts.map +1 -0
  113. package/lib/redact.d.ts +5 -0
  114. package/lib/redact.d.ts.map +1 -0
  115. package/lib/session.d.ts +40 -0
  116. package/lib/session.d.ts.map +1 -0
  117. package/lib/store.d.ts +46 -0
  118. package/lib/store.d.ts.map +1 -0
  119. package/lib/web-origin.d.ts +10 -0
  120. package/lib/web-origin.d.ts.map +1 -0
  121. package/lib/web-routes.d.ts +20 -0
  122. package/lib/web-routes.d.ts.map +1 -0
  123. package/package.json +185 -0
  124. package/patches/dsh-agy@0.1.2.patch +25 -0
  125. package/scripts/release.mjs +166 -0
  126. package/scripts/smoke-deployed-routes.mjs +146 -0
  127. package/scripts/verify-deployed-catalog.mjs +87 -0
  128. package/src/adapter.ts +282 -0
  129. package/src/alias-adapter.ts +152 -0
  130. package/src/auth-routes.ts +871 -0
  131. package/src/auth.ts +67 -0
  132. package/src/bin.ts +350 -0
  133. package/src/capability-routes.ts +275 -0
  134. package/src/capability-runtime.ts +313 -0
  135. package/src/capability-settings.ts +657 -0
  136. package/src/capability-tools.ts +666 -0
  137. package/src/catalog.ts +271 -0
  138. package/src/client/GrokBuildSettings.tsx +2221 -0
  139. package/src/client/index.tsx +37 -0
  140. package/src/client/locales.ts +421 -0
  141. package/src/codex-http.ts +447 -0
  142. package/src/codex-images.ts +485 -0
  143. package/src/codex-model-capabilities.ts +320 -0
  144. package/src/codex-search.ts +245 -0
  145. package/src/codex-usage.ts +263 -0
  146. package/src/gateway-anthropic-messages.ts +84 -0
  147. package/src/gateway-auth.ts +100 -0
  148. package/src/gateway-backend.ts +274 -0
  149. package/src/gateway-body.ts +49 -0
  150. package/src/gateway-config.ts +76 -0
  151. package/src/gateway-http.ts +104 -0
  152. package/src/gateway-openai-chat.ts +124 -0
  153. package/src/gateway-openai-responses.ts +53 -0
  154. package/src/gateway-parse.ts +224 -0
  155. package/src/gateway-protocol.ts +52 -0
  156. package/src/gateway-routes.ts +152 -0
  157. package/src/gateway.ts +242 -0
  158. package/src/grok-imagine.ts +1627 -0
  159. package/src/grok-import.ts +151 -0
  160. package/src/http-json.ts +82 -0
  161. package/src/ids.ts +45 -0
  162. package/src/imagine-routes.ts +461 -0
  163. package/src/index.ts +598 -0
  164. package/src/invariant.ts +17 -0
  165. package/src/kimi-errors.ts +26 -0
  166. package/src/media-store.ts +927 -0
  167. package/src/oauth-import-routes.ts +314 -0
  168. package/src/oauth-providers.ts +152 -0
  169. package/src/oauth-session.ts +183 -0
  170. package/src/oauth-sources.ts +1104 -0
  171. package/src/oauth.ts +620 -0
  172. package/src/provider.ts +128 -0
  173. package/src/proxy.ts +99 -0
  174. package/src/redact.ts +72 -0
  175. package/src/session.ts +218 -0
  176. package/src/store.ts +217 -0
  177. package/src/web-origin.ts +60 -0
  178. package/src/web-routes.ts +75 -0
package/src/auth.ts ADDED
@@ -0,0 +1,67 @@
1
+ /**
2
+ * Grok Build OAuth orchestration shared by the plugin and standalone CLI.
3
+ * @module dsh-coding-subscription-oauth/auth
4
+ */
5
+
6
+ import type { AuthInteraction } from "@earendil-works/pi-ai";
7
+ import { createModels } from "@earendil-works/pi-ai";
8
+ import { xaiProvider } from "@earendil-works/pi-ai/providers/xai";
9
+ import { importGrokAuth } from "./grok-import.ts";
10
+ import { XAI_PI_PROVIDER } from "./ids.ts";
11
+ import type { GrokBuildSession } from "./session.ts";
12
+ import { GrokBuildCredentialStore } from "./store.ts";
13
+
14
+ /** Non-secret login state shown by the launcher. */
15
+ export interface GrokBuildAuthStatus {
16
+ authenticated: boolean;
17
+ expiresAt?: Date;
18
+ }
19
+
20
+ /**
21
+ * Complete the xAI device-code OAuth flow and persist the credential.
22
+ * The Grok Build backend accepts the same auth.x.ai tokens (scope
23
+ * `grok-cli:access`); the PKCE authorization-code flow lands in a later
24
+ * milestone as the primary path.
25
+ */
26
+ export async function loginGrokBuild(
27
+ interaction: AuthInteraction,
28
+ store: GrokBuildCredentialStore = new GrokBuildCredentialStore(),
29
+ ): Promise<void> {
30
+ const models = createModels({ credentials: store });
31
+ models.setProvider(xaiProvider());
32
+ await models.login(XAI_PI_PROVIDER, "oauth", interaction);
33
+ }
34
+
35
+ /** Copy ~/.grok/auth.json into the dsh store. Does not modify the Grok file. */
36
+ export async function importGrokBuildFromGrok(
37
+ store: GrokBuildCredentialStore = new GrokBuildCredentialStore(),
38
+ filename?: string,
39
+ ): Promise<void> {
40
+ await importGrokAuth(store, filename);
41
+ }
42
+
43
+ /** Remove the stored Grok Build credential. */
44
+ export async function logoutGrokBuild(store: GrokBuildCredentialStore = new GrokBuildCredentialStore()): Promise<void> {
45
+ await store.delete(XAI_PI_PROVIDER);
46
+ }
47
+
48
+ /** Read non-secret login state without refreshing the token. */
49
+ export async function grokBuildAuthStatus(
50
+ store: GrokBuildCredentialStore = new GrokBuildCredentialStore(),
51
+ ): Promise<GrokBuildAuthStatus> {
52
+ const credential = await store.read(XAI_PI_PROVIDER);
53
+ return credential?.type === "oauth"
54
+ ? { authenticated: true, expiresAt: new Date(credential.expires) }
55
+ : { authenticated: false };
56
+ }
57
+
58
+ /** Login then refresh the account model list when a session is available. */
59
+ export async function loginGrokBuildSession(interaction: AuthInteraction, session: GrokBuildSession): Promise<void> {
60
+ await loginGrokBuild(interaction, session.store);
61
+ await session.refreshLiveCatalog();
62
+ }
63
+
64
+ export async function importGrokBuildSession(session: GrokBuildSession, filename?: string): Promise<void> {
65
+ await importGrokBuildFromGrok(session.store, filename);
66
+ await session.refreshLiveCatalog();
67
+ }
package/src/bin.ts ADDED
@@ -0,0 +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
+ }
@@ -0,0 +1,275 @@
1
+ /**
2
+ * Plugin-owned same-origin Web routes for the capability-settings namespace.
3
+ * Arbitrary Host settings namespaces are not remotely exposed, so this plugin
4
+ * publishes only the secret-free snapshot and the two optional read surfaces.
5
+ * @module dsh-coding-subscription-oauth/capability-routes
6
+ */
7
+
8
+ import type { IncomingMessage, ServerResponse } from "node:http";
9
+ import {
10
+ assertCapabilitySettingsPatch,
11
+ type CapabilitySettings,
12
+ type CapabilitySettingsPatch,
13
+ type CapabilitySettingsSnapshot,
14
+ isCapabilitySettingsConflictError,
15
+ isCapabilitySettingsReadOnlyError,
16
+ normalizeCapabilitySettingsPatch,
17
+ } from "./capability-settings.ts";
18
+ import { readJsonRequest, requestErrorStatus } from "./http-json.ts";
19
+ import { safeMessage } from "./redact.ts";
20
+ import { isTrustedLoopbackWebRequest } from "./web-origin.ts";
21
+ import { registerWebRouteSetupAtomically } from "./web-routes.ts";
22
+
23
+ export const CAPABILITY_SETTINGS_PATH = "/plugins/dsh-grok-build/capabilities";
24
+ export const CODEX_USAGE_PATH = "/plugins/dsh-grok-build/codex/usage";
25
+ export const IMAGINE_CREDENTIAL_STATUS_PATH = "/plugins/dsh-grok-build/imagine/credential-status";
26
+
27
+ /** Structural `ctx.webServer` + `ctx.effect` surface used by the registrar. */
28
+ export interface CapabilityRouteContext {
29
+ readonly webServer: {
30
+ register(route: {
31
+ kind: "exact" | "prefix";
32
+ path: string;
33
+ handler: (req: IncomingMessage, res: ServerResponse) => void | Promise<void>;
34
+ }): () => void;
35
+ };
36
+ effect(callback: () => () => void | Promise<void>, label?: string): unknown;
37
+ }
38
+
39
+ /** Owner-facing subset of {@link import("./capability-settings.ts").CapabilitySettingsController}. */
40
+ export interface CapabilityRouteController {
41
+ snapshot(): CapabilitySettingsSnapshot;
42
+ current(): CapabilitySettings;
43
+ patch(patch: CapabilitySettingsPatch, expectedRevision: number): Promise<CapabilitySettingsSnapshot>;
44
+ replace(section: CapabilitySettingsPatch, expectedRevision: number): Promise<CapabilitySettingsSnapshot>;
45
+ }
46
+
47
+ /** Secret-free Imagine credential probe returned on the optional status route. */
48
+ export interface ImagineCredentialStatus {
49
+ readonly configured: boolean;
50
+ readonly source: string;
51
+ readonly writable: boolean;
52
+ }
53
+
54
+ export interface CapabilityRouteOptions {
55
+ readonly controller: CapabilityRouteController;
56
+ readonly usage?: () => unknown | Promise<unknown>;
57
+ readonly credentialInfo?: () => unknown | Promise<unknown>;
58
+ }
59
+
60
+ class CapabilityRouteRequestError extends Error {
61
+ readonly statusCode: number;
62
+
63
+ constructor(statusCode: number, message: string) {
64
+ super(message);
65
+ this.name = "CapabilityRouteRequestError";
66
+ this.statusCode = statusCode;
67
+ }
68
+ }
69
+
70
+ /** Register the plugin-owned capability routes. Owns and returns the route disposer. */
71
+ export function registerCapabilityRoutes(ctx: CapabilityRouteContext, options: CapabilityRouteOptions): () => void {
72
+ const { controller, usage, credentialInfo } = options;
73
+ let dispose = (): void => undefined;
74
+ ctx.effect(() => {
75
+ dispose = registerWebRouteSetupAtomically(ctx.webServer, (webServer) => {
76
+ webServer.register({
77
+ kind: "exact",
78
+ path: CAPABILITY_SETTINGS_PATH,
79
+ handler: (req, res) => handleCapabilities(req, res, controller),
80
+ });
81
+ if (usage !== undefined) {
82
+ webServer.register({
83
+ kind: "exact",
84
+ path: CODEX_USAGE_PATH,
85
+ handler: (req, res) => handleUsage(req, res, controller, usage),
86
+ });
87
+ }
88
+ if (credentialInfo !== undefined) {
89
+ webServer.register({
90
+ kind: "exact",
91
+ path: IMAGINE_CREDENTIAL_STATUS_PATH,
92
+ handler: (req, res) => handleCredentialStatus(req, res, credentialInfo),
93
+ });
94
+ }
95
+ });
96
+ return dispose;
97
+ }, "dsh-coding-subscription-oauth: capability routes");
98
+ return () => dispose();
99
+ }
100
+
101
+ async function handleCapabilities(
102
+ req: IncomingMessage,
103
+ res: ServerResponse,
104
+ controller: CapabilityRouteController,
105
+ ): Promise<void> {
106
+ const method = req.method ?? "";
107
+ if (method !== "GET" && method !== "PATCH" && method !== "PUT") {
108
+ json(res, 405, { error: "method not allowed" });
109
+ return;
110
+ }
111
+ if (!isTrustedLoopbackWebRequest(req)) {
112
+ json(res, 403, { error: "forbidden" });
113
+ return;
114
+ }
115
+ try {
116
+ if (method === "GET") {
117
+ json(res, 200, controller.snapshot());
118
+ return;
119
+ }
120
+ const body = await readJsonRequest(req);
121
+ if (method === "PATCH") {
122
+ const { expectedRevision, payload } = readWriteEnvelope(body, "patch");
123
+ json(res, 200, await controller.patch(admitCapabilitySection(payload, "patch"), expectedRevision));
124
+ return;
125
+ }
126
+ const { expectedRevision, payload } = readWriteEnvelope(body, "value");
127
+ json(res, 200, await controller.replace(admitCapabilitySection(payload, "value"), expectedRevision));
128
+ } catch (error: unknown) {
129
+ const status = statusFor(error);
130
+ json(res, status, errorBody(error, status));
131
+ }
132
+ }
133
+
134
+ async function handleUsage(
135
+ req: IncomingMessage,
136
+ res: ServerResponse,
137
+ controller: CapabilityRouteController,
138
+ usage: () => unknown | Promise<unknown>,
139
+ ): Promise<void> {
140
+ if (req.method !== "GET") {
141
+ json(res, 405, { error: "method not allowed" });
142
+ return;
143
+ }
144
+ if (!isTrustedLoopbackWebRequest(req)) {
145
+ json(res, 403, { error: "forbidden" });
146
+ return;
147
+ }
148
+ try {
149
+ if (controller.current().codexUsage !== true) {
150
+ json(res, 404, { error: "disabled" });
151
+ return;
152
+ }
153
+ json(res, 200, await usage());
154
+ } catch (error: unknown) {
155
+ const status = statusFor(error);
156
+ json(res, status, errorBody(error, status));
157
+ }
158
+ }
159
+
160
+ async function handleCredentialStatus(
161
+ req: IncomingMessage,
162
+ res: ServerResponse,
163
+ credentialInfo: () => unknown | Promise<unknown>,
164
+ ): Promise<void> {
165
+ if (req.method !== "GET") {
166
+ json(res, 405, { error: "method not allowed" });
167
+ return;
168
+ }
169
+ if (!isTrustedLoopbackWebRequest(req)) {
170
+ json(res, 403, { error: "forbidden" });
171
+ return;
172
+ }
173
+ try {
174
+ json(res, 200, publicCredentialStatus(await credentialInfo()));
175
+ } catch (error: unknown) {
176
+ const status = statusFor(error);
177
+ json(res, status, errorBody(error, status));
178
+ }
179
+ }
180
+
181
+ function readWriteEnvelope(
182
+ body: unknown,
183
+ payloadKey: "patch" | "value",
184
+ ): { expectedRevision: number; payload: Record<string, unknown> } {
185
+ if (!isPlainObject(body)) {
186
+ throw new CapabilityRouteRequestError(400, "request body must be a JSON object");
187
+ }
188
+ const expectedRevision = body["expectedRevision"];
189
+ if (typeof expectedRevision !== "number" || !Number.isInteger(expectedRevision) || expectedRevision < 0) {
190
+ throw new CapabilityRouteRequestError(400, "expectedRevision must be a nonnegative integer");
191
+ }
192
+ const payload = body[payloadKey];
193
+ if (!isPlainObject(payload)) {
194
+ throw new CapabilityRouteRequestError(400, `${payloadKey} must be a JSON object`);
195
+ }
196
+ return { expectedRevision, payload };
197
+ }
198
+
199
+ /** Admit a wire section without silently coercing, truncating, or clamping it. */
200
+ function admitCapabilitySection(input: Record<string, unknown>, label: string): CapabilitySettingsPatch {
201
+ try {
202
+ assertCapabilitySettingsPatch(input, label);
203
+ } catch (error) {
204
+ throw new CapabilityRouteRequestError(400, safeMessage(error));
205
+ }
206
+ return normalizeCapabilitySettingsPatch(input);
207
+ }
208
+
209
+ function publicCredentialStatus(info: unknown): ImagineCredentialStatus {
210
+ const record = isPlainObject(info) ? info : {};
211
+ const source = record["source"];
212
+ return {
213
+ configured: record["configured"] === true,
214
+ source: typeof source === "string" && source.length <= 40 && /^[a-z0-9._-]+$/iu.test(source) ? source : "unknown",
215
+ writable: record["writable"] === true,
216
+ };
217
+ }
218
+
219
+ function statusFor(error: unknown): number {
220
+ if (error instanceof CapabilityRouteRequestError) return error.statusCode;
221
+ const jsonStatus = requestErrorStatus(error, 0);
222
+ if (jsonStatus !== 0) return jsonStatus;
223
+ if (conflictInfo(error) !== undefined) return 409;
224
+ if (isCapabilitySettingsReadOnlyError(error)) {
225
+ return error.reason === "read-only" ? 403 : 503;
226
+ }
227
+ if (typeof error === "object" && error !== null) {
228
+ const code = (error as { code?: unknown }).code;
229
+ if (code === "SETTINGS_READ_ONLY") return 403;
230
+ if (code === "SETTINGS_PROVIDER_ABSENT" || code === "SETTINGS_DISPOSED") return 503;
231
+ }
232
+ if (error instanceof TypeError) return 400;
233
+ return 500;
234
+ }
235
+
236
+ function errorBody(error: unknown, status: number): Record<string, unknown> {
237
+ const body: Record<string, unknown> = { error: status >= 500 ? "request failed" : safeMessage(error) };
238
+ const conflict = conflictInfo(error);
239
+ if (conflict !== undefined) {
240
+ body["code"] = "SETTINGS_CONFLICT";
241
+ body["expected"] = conflict.expected;
242
+ body["actual"] = conflict.actual;
243
+ return body;
244
+ }
245
+ if (isCapabilitySettingsReadOnlyError(error)) {
246
+ body["code"] = error.code;
247
+ }
248
+ return body;
249
+ }
250
+
251
+ function conflictInfo(error: unknown): { expected: number; actual: number } | undefined {
252
+ if (isCapabilitySettingsConflictError(error)) {
253
+ return { expected: error.expected, actual: error.actual };
254
+ }
255
+ if (typeof error !== "object" || error === null) return undefined;
256
+ const candidate = error as { code?: unknown; expected?: unknown; actual?: unknown };
257
+ if (candidate.code !== "SETTINGS_CONFLICT") return undefined;
258
+ if (typeof candidate.expected !== "number" || typeof candidate.actual !== "number") return undefined;
259
+ return { expected: candidate.expected, actual: candidate.actual };
260
+ }
261
+
262
+ function isPlainObject(value: unknown): value is Record<string, unknown> {
263
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
264
+ const proto = Object.getPrototypeOf(value);
265
+ return proto === Object.prototype || proto === null;
266
+ }
267
+
268
+ function json(res: ServerResponse, status: number, value: unknown): void {
269
+ res.writeHead(status, {
270
+ "content-type": "application/json; charset=utf-8",
271
+ "cache-control": "no-store",
272
+ "x-content-type-options": "nosniff",
273
+ });
274
+ res.end(JSON.stringify(value));
275
+ }