dsh-coding-subscription-oauth 0.6.3 → 0.6.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (127) hide show
  1. package/CHANGELOG.md +33 -0
  2. package/CONTRIBUTING.md +13 -4
  3. package/INSTALL.md +7 -5
  4. package/README.de.md +6 -6
  5. package/README.es.md +6 -6
  6. package/README.fr.md +6 -6
  7. package/README.ja.md +6 -6
  8. package/README.ko.md +6 -6
  9. package/README.md +6 -6
  10. package/README.pt-BR.md +6 -6
  11. package/README.ru.md +6 -6
  12. package/README.zh-CN.md +6 -6
  13. package/docs/00-project-rules.md +4 -4
  14. package/docs/02-architecture.md +7 -3
  15. package/docs/02-architecture.zh-CN.md +7 -3
  16. package/lib/bin.js +1333 -569
  17. package/lib/bin.js.map +4 -4
  18. package/lib/client.js +1 -1
  19. package/lib/client.js.map +2 -2
  20. package/lib/gateway-protocol.d.ts +3 -46
  21. package/lib/gateway-protocol.d.ts.map +1 -1
  22. package/lib/gateway-routes.d.ts.map +1 -1
  23. package/lib/grok-errors.d.ts +2 -12
  24. package/lib/grok-errors.d.ts.map +1 -1
  25. package/lib/grok-imagine/client.d.ts +73 -0
  26. package/lib/grok-imagine/client.d.ts.map +1 -0
  27. package/lib/grok-imagine/index.d.ts +8 -0
  28. package/lib/grok-imagine/index.d.ts.map +1 -0
  29. package/lib/grok-imagine/net.d.ts +10 -0
  30. package/lib/grok-imagine/net.d.ts.map +1 -0
  31. package/lib/grok-imagine/parse.d.ts +20 -0
  32. package/lib/grok-imagine/parse.d.ts.map +1 -0
  33. package/lib/grok-imagine/types.d.ts +191 -0
  34. package/lib/grok-imagine/types.d.ts.map +1 -0
  35. package/lib/grok-imagine.d.ts +3 -263
  36. package/lib/grok-imagine.d.ts.map +1 -1
  37. package/lib/http-json.d.ts +2 -9
  38. package/lib/http-json.d.ts.map +1 -1
  39. package/lib/index.js +1395 -26178
  40. package/lib/index.js.map +4 -4
  41. package/lib/kimi-errors.d.ts +2 -12
  42. package/lib/kimi-errors.d.ts.map +1 -1
  43. package/lib/runtime/gateway-protocol.d.ts +47 -0
  44. package/lib/runtime/gateway-protocol.d.ts.map +1 -0
  45. package/lib/runtime/grok-errors.d.ts +13 -0
  46. package/lib/runtime/grok-errors.d.ts.map +1 -0
  47. package/lib/runtime/http-json.d.ts +10 -0
  48. package/lib/runtime/http-json.d.ts.map +1 -0
  49. package/lib/runtime/kimi-errors.d.ts +13 -0
  50. package/lib/runtime/kimi-errors.d.ts.map +1 -0
  51. package/package.json +12 -7
  52. package/scripts/release.mjs +1 -0
  53. package/src/adapter.ts +0 -348
  54. package/src/alias-adapter.ts +0 -147
  55. package/src/auth-routes.ts +0 -921
  56. package/src/auth.ts +0 -67
  57. package/src/bin.ts +0 -350
  58. package/src/capability-routes.ts +0 -279
  59. package/src/capability-runtime.ts +0 -314
  60. package/src/capability-settings.ts +0 -671
  61. package/src/capability-tools.ts +0 -685
  62. package/src/catalog.ts +0 -271
  63. package/src/client/GrokBuildSettings.tsx +0 -771
  64. package/src/client/api.ts +0 -88
  65. package/src/client/components/AboutTab.tsx +0 -30
  66. package/src/client/components/AccountsTab.tsx +0 -241
  67. package/src/client/components/Badge.tsx +0 -33
  68. package/src/client/components/CapabilitiesTab.tsx +0 -265
  69. package/src/client/components/CliPullPreview.tsx +0 -116
  70. package/src/client/components/CopyButton.tsx +0 -57
  71. package/src/client/components/GatewayTab.tsx +0 -469
  72. package/src/client/components/NoticeBanner.tsx +0 -46
  73. package/src/client/components/ProgressBar.tsx +0 -53
  74. package/src/client/components/ProviderCard.tsx +0 -606
  75. package/src/client/components/SettingsTabs.tsx +0 -75
  76. package/src/client/components/ToggleSwitch.tsx +0 -71
  77. package/src/client/constants.ts +0 -230
  78. package/src/client/display.ts +0 -61
  79. package/src/client/dshClientAdapter.ts +0 -127
  80. package/src/client/gatewaySnippets.ts +0 -37
  81. package/src/client/index.tsx +0 -156
  82. package/src/client/locales.ts +0 -540
  83. package/src/client/microStyles.ts +0 -52
  84. package/src/client/parsers.ts +0 -398
  85. package/src/client/styles.ts +0 -325
  86. package/src/client/types.ts +0 -199
  87. package/src/codex-http.ts +0 -447
  88. package/src/codex-images.ts +0 -503
  89. package/src/codex-model-capabilities.ts +0 -320
  90. package/src/codex-search.ts +0 -245
  91. package/src/codex-usage.ts +0 -263
  92. package/src/compatibility.ts +0 -55
  93. package/src/dsh-host-adapter.ts +0 -173
  94. package/src/gateway-anthropic-messages.ts +0 -84
  95. package/src/gateway-auth.ts +0 -102
  96. package/src/gateway-backend.ts +0 -274
  97. package/src/gateway-body.ts +0 -49
  98. package/src/gateway-config.ts +0 -76
  99. package/src/gateway-http.ts +0 -104
  100. package/src/gateway-openai-chat.ts +0 -124
  101. package/src/gateway-openai-responses.ts +0 -53
  102. package/src/gateway-parse.ts +0 -224
  103. package/src/gateway-protocol.ts +0 -52
  104. package/src/gateway-routes.ts +0 -158
  105. package/src/gateway.ts +0 -258
  106. package/src/grok-errors.ts +0 -24
  107. package/src/grok-imagine.ts +0 -1627
  108. package/src/grok-import.ts +0 -151
  109. package/src/http-json.ts +0 -82
  110. package/src/ids.ts +0 -59
  111. package/src/imagine-routes.ts +0 -463
  112. package/src/index.ts +0 -735
  113. package/src/invariant.ts +0 -17
  114. package/src/kimi-errors.ts +0 -26
  115. package/src/media-store.ts +0 -927
  116. package/src/oauth-import-routes.ts +0 -324
  117. package/src/oauth-providers.ts +0 -152
  118. package/src/oauth-session.ts +0 -183
  119. package/src/oauth-sources.ts +0 -1104
  120. package/src/oauth.ts +0 -620
  121. package/src/provider.ts +0 -128
  122. package/src/proxy.ts +0 -11
  123. package/src/redact.ts +0 -72
  124. package/src/session.ts +0 -218
  125. package/src/store.ts +0 -217
  126. package/src/web-origin.ts +0 -296
  127. package/src/web-routes.ts +0 -38
package/src/auth.ts DELETED
@@ -1,67 +0,0 @@
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 DELETED
@@ -1,350 +0,0 @@
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,279 +0,0 @@
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 { CAPABILITY_SETTINGS_PATH, CODEX_USAGE_PATH, IMAGINE_CREDENTIAL_STATUS_PATH } from "./ids.ts";
20
- import { safeMessage } from "./redact.ts";
21
- import { LOOPBACK_OWNER_REQUEST_POLICY, type OwnerRequestPolicy } from "./web-origin.ts";
22
- import { registerWebRouteSetupAtomically } from "./web-routes.ts";
23
-
24
- export { CAPABILITY_SETTINGS_PATH, CODEX_USAGE_PATH, IMAGINE_CREDENTIAL_STATUS_PATH } from "./ids.ts";
25
-
26
- /** Structural `ctx.webServer` + `ctx.effect` surface used by the registrar. */
27
- export interface CapabilityRouteContext {
28
- readonly webServer: {
29
- register(route: {
30
- kind: "exact" | "prefix";
31
- path: string;
32
- handler: (req: IncomingMessage, res: ServerResponse) => void | Promise<void>;
33
- }): () => void;
34
- };
35
- effect(callback: () => () => void | Promise<void>, label?: string): unknown;
36
- }
37
-
38
- /** Owner-facing subset of {@link import("./capability-settings.ts").CapabilitySettingsController}. */
39
- export interface CapabilityRouteController {
40
- snapshot(): CapabilitySettingsSnapshot;
41
- current(): CapabilitySettings;
42
- patch(patch: CapabilitySettingsPatch, expectedRevision: number): Promise<CapabilitySettingsSnapshot>;
43
- replace(section: CapabilitySettingsPatch, expectedRevision: number): Promise<CapabilitySettingsSnapshot>;
44
- }
45
-
46
- /** Secret-free Imagine credential probe returned on the optional status route. */
47
- export interface ImagineCredentialStatus {
48
- readonly configured: boolean;
49
- readonly source: string;
50
- readonly writable: boolean;
51
- }
52
-
53
- export interface CapabilityRouteOptions {
54
- readonly controller: CapabilityRouteController;
55
- readonly usage?: () => unknown | Promise<unknown>;
56
- readonly credentialInfo?: () => unknown | Promise<unknown>;
57
- readonly ownerRequestPolicy?: OwnerRequestPolicy;
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
- const ownerRequestPolicy = options.ownerRequestPolicy ?? LOOPBACK_OWNER_REQUEST_POLICY;
74
- let dispose = (): void => undefined;
75
- ctx.effect(() => {
76
- dispose = registerWebRouteSetupAtomically(ctx.webServer, (webServer) => {
77
- webServer.register({
78
- kind: "exact",
79
- path: CAPABILITY_SETTINGS_PATH,
80
- handler: (req, res) => handleCapabilities(req, res, controller, ownerRequestPolicy),
81
- });
82
- if (usage !== undefined) {
83
- webServer.register({
84
- kind: "exact",
85
- path: CODEX_USAGE_PATH,
86
- handler: (req, res) => handleUsage(req, res, controller, usage, ownerRequestPolicy),
87
- });
88
- }
89
- if (credentialInfo !== undefined) {
90
- webServer.register({
91
- kind: "exact",
92
- path: IMAGINE_CREDENTIAL_STATUS_PATH,
93
- handler: (req, res) => handleCredentialStatus(req, res, credentialInfo, ownerRequestPolicy),
94
- });
95
- }
96
- });
97
- return dispose;
98
- }, "dsh-coding-subscription-oauth: capability routes");
99
- return () => dispose();
100
- }
101
-
102
- async function handleCapabilities(
103
- req: IncomingMessage,
104
- res: ServerResponse,
105
- controller: CapabilityRouteController,
106
- ownerRequestPolicy: OwnerRequestPolicy,
107
- ): Promise<void> {
108
- const method = req.method ?? "";
109
- if (method !== "GET" && method !== "PATCH" && method !== "PUT") {
110
- json(res, 405, { error: "method not allowed" });
111
- return;
112
- }
113
- if (!ownerRequestPolicy.authorize(req).authorized) {
114
- json(res, 403, { error: "forbidden" });
115
- return;
116
- }
117
- try {
118
- if (method === "GET") {
119
- json(res, 200, controller.snapshot());
120
- return;
121
- }
122
- const body = await readJsonRequest(req);
123
- if (method === "PATCH") {
124
- const { expectedRevision, payload } = readWriteEnvelope(body, "patch");
125
- json(res, 200, await controller.patch(admitCapabilitySection(payload, "patch"), expectedRevision));
126
- return;
127
- }
128
- const { expectedRevision, payload } = readWriteEnvelope(body, "value");
129
- json(res, 200, await controller.replace(admitCapabilitySection(payload, "value"), expectedRevision));
130
- } catch (error: unknown) {
131
- const status = statusFor(error);
132
- json(res, status, errorBody(error, status));
133
- }
134
- }
135
-
136
- async function handleUsage(
137
- req: IncomingMessage,
138
- res: ServerResponse,
139
- controller: CapabilityRouteController,
140
- usage: () => unknown | Promise<unknown>,
141
- ownerRequestPolicy: OwnerRequestPolicy,
142
- ): Promise<void> {
143
- if (req.method !== "GET") {
144
- json(res, 405, { error: "method not allowed" });
145
- return;
146
- }
147
- if (!ownerRequestPolicy.authorize(req).authorized) {
148
- json(res, 403, { error: "forbidden" });
149
- return;
150
- }
151
- try {
152
- if (controller.current().codexUsage !== true) {
153
- json(res, 404, { error: "disabled" });
154
- return;
155
- }
156
- json(res, 200, await usage());
157
- } catch (error: unknown) {
158
- const status = statusFor(error);
159
- json(res, status, errorBody(error, status));
160
- }
161
- }
162
-
163
- async function handleCredentialStatus(
164
- req: IncomingMessage,
165
- res: ServerResponse,
166
- credentialInfo: () => unknown | Promise<unknown>,
167
- ownerRequestPolicy: OwnerRequestPolicy,
168
- ): Promise<void> {
169
- if (req.method !== "GET") {
170
- json(res, 405, { error: "method not allowed" });
171
- return;
172
- }
173
- if (!ownerRequestPolicy.authorize(req).authorized) {
174
- json(res, 403, { error: "forbidden" });
175
- return;
176
- }
177
- try {
178
- json(res, 200, publicCredentialStatus(await credentialInfo()));
179
- } catch (error: unknown) {
180
- const status = statusFor(error);
181
- json(res, status, errorBody(error, status));
182
- }
183
- }
184
-
185
- function readWriteEnvelope(
186
- body: unknown,
187
- payloadKey: "patch" | "value",
188
- ): { expectedRevision: number; payload: Record<string, unknown> } {
189
- if (!isPlainObject(body)) {
190
- throw new CapabilityRouteRequestError(400, "request body must be a JSON object");
191
- }
192
- const expectedRevision = body["expectedRevision"];
193
- if (typeof expectedRevision !== "number" || !Number.isInteger(expectedRevision) || expectedRevision < 0) {
194
- throw new CapabilityRouteRequestError(400, "expectedRevision must be a nonnegative integer");
195
- }
196
- const payload = body[payloadKey];
197
- if (!isPlainObject(payload)) {
198
- throw new CapabilityRouteRequestError(400, `${payloadKey} must be a JSON object`);
199
- }
200
- return { expectedRevision, payload };
201
- }
202
-
203
- /** Admit a wire section without silently coercing, truncating, or clamping it. */
204
- function admitCapabilitySection(input: Record<string, unknown>, label: string): CapabilitySettingsPatch {
205
- try {
206
- assertCapabilitySettingsPatch(input, label);
207
- } catch (error) {
208
- throw new CapabilityRouteRequestError(400, safeMessage(error));
209
- }
210
- return normalizeCapabilitySettingsPatch(input);
211
- }
212
-
213
- function publicCredentialStatus(info: unknown): ImagineCredentialStatus {
214
- const record = isPlainObject(info) ? info : {};
215
- const source = record["source"];
216
- return {
217
- configured: record["configured"] === true,
218
- source: typeof source === "string" && source.length <= 40 && /^[a-z0-9._-]+$/iu.test(source) ? source : "unknown",
219
- writable: record["writable"] === true,
220
- };
221
- }
222
-
223
- function statusFor(error: unknown): number {
224
- if (error instanceof CapabilityRouteRequestError) return error.statusCode;
225
- const jsonStatus = requestErrorStatus(error, 0);
226
- if (jsonStatus !== 0) return jsonStatus;
227
- if (conflictInfo(error) !== undefined) return 409;
228
- if (isCapabilitySettingsReadOnlyError(error)) {
229
- return error.reason === "read-only" ? 403 : 503;
230
- }
231
- if (typeof error === "object" && error !== null) {
232
- const code = (error as { code?: unknown }).code;
233
- if (code === "SETTINGS_READ_ONLY") return 403;
234
- if (code === "SETTINGS_PROVIDER_ABSENT" || code === "SETTINGS_DISPOSED") return 503;
235
- }
236
- if (error instanceof TypeError) return 400;
237
- return 500;
238
- }
239
-
240
- function errorBody(error: unknown, status: number): Record<string, unknown> {
241
- const body: Record<string, unknown> = { error: status >= 500 ? "request failed" : safeMessage(error) };
242
- const conflict = conflictInfo(error);
243
- if (conflict !== undefined) {
244
- body["code"] = "SETTINGS_CONFLICT";
245
- body["expected"] = conflict.expected;
246
- body["actual"] = conflict.actual;
247
- return body;
248
- }
249
- if (isCapabilitySettingsReadOnlyError(error)) {
250
- body["code"] = error.code;
251
- }
252
- return body;
253
- }
254
-
255
- function conflictInfo(error: unknown): { expected: number; actual: number } | undefined {
256
- if (isCapabilitySettingsConflictError(error)) {
257
- return { expected: error.expected, actual: error.actual };
258
- }
259
- if (typeof error !== "object" || error === null) return undefined;
260
- const candidate = error as { code?: unknown; expected?: unknown; actual?: unknown };
261
- if (candidate.code !== "SETTINGS_CONFLICT") return undefined;
262
- if (typeof candidate.expected !== "number" || typeof candidate.actual !== "number") return undefined;
263
- return { expected: candidate.expected, actual: candidate.actual };
264
- }
265
-
266
- function isPlainObject(value: unknown): value is Record<string, unknown> {
267
- if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
268
- const proto = Object.getPrototypeOf(value);
269
- return proto === Object.prototype || proto === null;
270
- }
271
-
272
- function json(res: ServerResponse, status: number, value: unknown): void {
273
- res.writeHead(status, {
274
- "content-type": "application/json; charset=utf-8",
275
- "cache-control": "no-store",
276
- "x-content-type-options": "nosniff",
277
- });
278
- res.end(JSON.stringify(value));
279
- }