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
@@ -0,0 +1,224 @@
1
+ /**
2
+ * Parse OpenAI / Anthropic request bodies into the gateway completion shape.
3
+ * @module dsh-coding-subscription-oauth/gateway-parse
4
+ */
5
+
6
+ import { GatewayRequestError } from "./gateway-backend.ts";
7
+ import type { GatewayChatMessage, GatewayCompletionRequest, GatewayTool, GatewayToolCall } from "./gateway-protocol.ts";
8
+
9
+ export function parseOpenAiChatRequest(payload: Record<string, unknown>): GatewayCompletionRequest {
10
+ const model = requiredModel(payload["model"]);
11
+ const tools = parseOpenAiTools(payload["tools"]);
12
+ const reasoning = reasoningOf(payload);
13
+ return {
14
+ model,
15
+ messages: parseOpenAiMessages(payload["messages"]),
16
+ ...(tools === undefined ? {} : { tools }),
17
+ ...(reasoning === undefined ? {} : { reasoning }),
18
+ };
19
+ }
20
+
21
+ export function parseOpenAiResponsesRequest(payload: Record<string, unknown>): GatewayCompletionRequest {
22
+ const model = requiredModel(payload["model"]);
23
+ const input = payload["input"];
24
+ if (typeof input === "string") {
25
+ return { model, messages: [{ role: "user", content: input }] };
26
+ }
27
+ if (Array.isArray(input)) {
28
+ const tools = parseOpenAiTools(payload["tools"]);
29
+ const reasoning = reasoningOf(payload);
30
+ return {
31
+ model,
32
+ messages: parseOpenAiMessages(input),
33
+ ...(tools === undefined ? {} : { tools }),
34
+ ...(reasoning === undefined ? {} : { reasoning }),
35
+ };
36
+ }
37
+ throw new GatewayRequestError(400, "invalid_request", "input must be a string or message array");
38
+ }
39
+
40
+ export function parseAnthropicMessagesRequest(payload: Record<string, unknown>): GatewayCompletionRequest {
41
+ const model = requiredModel(payload["model"]);
42
+ const messages = parseAnthropicMessages(payload["messages"]);
43
+ const system = payload["system"];
44
+ if (typeof system === "string" && system.length > 0) {
45
+ messages.unshift({ role: "system", content: system });
46
+ }
47
+ const tools = parseAnthropicTools(payload["tools"]);
48
+ const reasoning = reasoningOf(payload);
49
+ return {
50
+ model,
51
+ messages,
52
+ ...(tools === undefined ? {} : { tools }),
53
+ ...(reasoning === undefined ? {} : { reasoning }),
54
+ };
55
+ }
56
+
57
+ export function anthropicMaxTokens(payload: Record<string, unknown>): number {
58
+ const value = payload["max_tokens"];
59
+ if (typeof value === "number" && Number.isSafeInteger(value) && value > 0) return Math.min(value, 32_768);
60
+ return 4096;
61
+ }
62
+
63
+ function requiredModel(value: unknown): string {
64
+ if (typeof value !== "string" || value.length === 0) {
65
+ throw new GatewayRequestError(400, "invalid_request", "model is required");
66
+ }
67
+ return value;
68
+ }
69
+
70
+ function reasoningOf(payload: Record<string, unknown>): string | undefined {
71
+ if (typeof payload["reasoning_effort"] === "string") return payload["reasoning_effort"];
72
+ if (typeof payload["reasoning"] === "string") return payload["reasoning"];
73
+ return undefined;
74
+ }
75
+
76
+ function parseOpenAiMessages(value: unknown): GatewayChatMessage[] {
77
+ if (!Array.isArray(value) || value.length === 0) {
78
+ throw new GatewayRequestError(400, "invalid_request", "messages must be a non-empty array");
79
+ }
80
+ return value.map((item) => {
81
+ if (typeof item !== "object" || item === null) {
82
+ throw new GatewayRequestError(400, "invalid_request", "message must be an object");
83
+ }
84
+ const record = item as Record<string, unknown>;
85
+ const role = record["role"];
86
+ if (typeof role !== "string")
87
+ throw new GatewayRequestError(400, "invalid_request", "message role must be a string");
88
+ const toolCalls = parseToolCalls(record["tool_calls"]);
89
+ return {
90
+ role,
91
+ content: contentToString(record["content"]),
92
+ ...(toolCalls === undefined ? {} : { tool_calls: toolCalls }),
93
+ ...(typeof record["reasoning_content"] === "string" ? { reasoning_content: record["reasoning_content"] } : {}),
94
+ ...(typeof record["tool_call_id"] === "string" ? { tool_call_id: record["tool_call_id"] } : {}),
95
+ ...(typeof record["name"] === "string" ? { tool_name: record["name"] } : {}),
96
+ };
97
+ });
98
+ }
99
+
100
+ function parseAnthropicMessages(value: unknown): GatewayChatMessage[] {
101
+ if (!Array.isArray(value) || value.length === 0) {
102
+ throw new GatewayRequestError(400, "invalid_request", "messages must be a non-empty array");
103
+ }
104
+ const mapped: GatewayChatMessage[] = [];
105
+ for (const item of value) {
106
+ if (typeof item !== "object" || item === null) {
107
+ throw new GatewayRequestError(400, "invalid_request", "message must be an object");
108
+ }
109
+ const record = item as Record<string, unknown>;
110
+ const role = record["role"];
111
+ if (role !== "user" && role !== "assistant") {
112
+ throw new GatewayRequestError(400, "invalid_request", "anthropic message role must be user or assistant");
113
+ }
114
+ const blocks = Array.isArray(record["content"]) ? record["content"] : [{ type: "text", text: record["content"] }];
115
+ const texts: string[] = [];
116
+ const toolCalls: GatewayToolCall[] = [];
117
+ let reasoning: string | undefined;
118
+ for (const block of blocks) {
119
+ if (typeof block !== "object" || block === null) continue;
120
+ const entry = block as Record<string, unknown>;
121
+ if (entry["type"] === "text" && typeof entry["text"] === "string") texts.push(entry["text"]);
122
+ if (entry["type"] === "thinking" && typeof entry["thinking"] === "string") reasoning = entry["thinking"];
123
+ if (entry["type"] === "tool_use" && typeof entry["id"] === "string" && typeof entry["name"] === "string") {
124
+ toolCalls.push({
125
+ id: entry["id"],
126
+ name: entry["name"],
127
+ arguments: typeof entry["input"] === "string" ? entry["input"] : JSON.stringify(entry["input"] ?? {}),
128
+ });
129
+ }
130
+ if (entry["type"] === "tool_result" && typeof entry["tool_use_id"] === "string") {
131
+ mapped.push({
132
+ role: "tool",
133
+ content: typeof entry["content"] === "string" ? entry["content"] : JSON.stringify(entry["content"] ?? ""),
134
+ tool_call_id: entry["tool_use_id"],
135
+ });
136
+ }
137
+ }
138
+ mapped.push({
139
+ role,
140
+ content: texts.join(""),
141
+ ...(toolCalls.length === 0 ? {} : { tool_calls: toolCalls }),
142
+ ...(reasoning === undefined ? {} : { reasoning_content: reasoning }),
143
+ });
144
+ }
145
+ return mapped;
146
+ }
147
+
148
+ function parseOpenAiTools(value: unknown): GatewayTool[] | undefined {
149
+ if (!Array.isArray(value) || value.length === 0) return undefined;
150
+ const tools: GatewayTool[] = [];
151
+ for (const item of value) {
152
+ if (typeof item !== "object" || item === null) continue;
153
+ const record = item as Record<string, unknown>;
154
+ const fn =
155
+ typeof record["function"] === "object" && record["function"] !== null
156
+ ? (record["function"] as Record<string, unknown>)
157
+ : record;
158
+ if (typeof fn["name"] !== "string") continue;
159
+ tools.push({
160
+ name: fn["name"],
161
+ description: typeof fn["description"] === "string" ? fn["description"] : "",
162
+ parameters:
163
+ typeof fn["parameters"] === "object" && fn["parameters"] !== null
164
+ ? (fn["parameters"] as Record<string, unknown>)
165
+ : {},
166
+ });
167
+ }
168
+ return tools.length === 0 ? undefined : tools;
169
+ }
170
+
171
+ function parseAnthropicTools(value: unknown): GatewayTool[] | undefined {
172
+ if (!Array.isArray(value) || value.length === 0) return undefined;
173
+ const tools: GatewayTool[] = [];
174
+ for (const item of value) {
175
+ if (typeof item !== "object" || item === null) continue;
176
+ const record = item as Record<string, unknown>;
177
+ if (typeof record["name"] !== "string") continue;
178
+ tools.push({
179
+ name: record["name"],
180
+ description: typeof record["description"] === "string" ? record["description"] : "",
181
+ parameters:
182
+ typeof record["input_schema"] === "object" && record["input_schema"] !== null
183
+ ? (record["input_schema"] as Record<string, unknown>)
184
+ : {},
185
+ });
186
+ }
187
+ return tools.length === 0 ? undefined : tools;
188
+ }
189
+
190
+ function parseToolCalls(value: unknown): GatewayToolCall[] | undefined {
191
+ if (!Array.isArray(value) || value.length === 0) return undefined;
192
+ const calls: GatewayToolCall[] = [];
193
+ for (const item of value) {
194
+ if (typeof item !== "object" || item === null) continue;
195
+ const record = item as Record<string, unknown>;
196
+ const fn =
197
+ typeof record["function"] === "object" && record["function"] !== null
198
+ ? (record["function"] as Record<string, unknown>)
199
+ : record;
200
+ if (typeof record["id"] !== "string" || typeof fn["name"] !== "string") continue;
201
+ calls.push({
202
+ id: record["id"],
203
+ name: fn["name"],
204
+ arguments: typeof fn["arguments"] === "string" ? fn["arguments"] : JSON.stringify(fn["arguments"] ?? {}),
205
+ });
206
+ }
207
+ return calls.length === 0 ? undefined : calls;
208
+ }
209
+
210
+ function contentToString(value: unknown): string {
211
+ if (typeof value === "string") return value;
212
+ if (Array.isArray(value)) {
213
+ return value
214
+ .map((part) => {
215
+ if (typeof part === "string") return part;
216
+ if (typeof part === "object" && part !== null && typeof (part as { text?: unknown }).text === "string") {
217
+ return (part as { text: string }).text;
218
+ }
219
+ return "";
220
+ })
221
+ .join("");
222
+ }
223
+ return "";
224
+ }
@@ -0,0 +1,52 @@
1
+ /**
2
+ * Shared request/stream types for the local coding-subscription gateway.
3
+ * @module dsh-coding-subscription-oauth/gateway-protocol
4
+ */
5
+
6
+ export interface GatewayToolCall {
7
+ id: string;
8
+ name: string;
9
+ arguments: string;
10
+ }
11
+
12
+ export interface GatewayTool {
13
+ name: string;
14
+ description: string;
15
+ parameters: Record<string, unknown>;
16
+ }
17
+
18
+ export interface GatewayChatMessage {
19
+ role: string;
20
+ content: string;
21
+ tool_calls?: readonly GatewayToolCall[];
22
+ reasoning_content?: string;
23
+ tool_call_id?: string;
24
+ tool_name?: string;
25
+ }
26
+
27
+ export interface GatewayCompletionRequest {
28
+ model: string;
29
+ messages: readonly GatewayChatMessage[];
30
+ tools?: readonly GatewayTool[];
31
+ reasoning?: string;
32
+ }
33
+
34
+ export type GatewayStreamPart =
35
+ | { type: "text"; text: string }
36
+ | { type: "thinking"; text: string }
37
+ | { type: "tool_call"; index: number; id: string; name: string; arguments: string }
38
+ | { type: "done"; finish: "stop" | "tool_calls" | "length" };
39
+
40
+ export type GatewayThinkingLevel = "off" | "minimal" | "low" | "medium" | "high" | "xhigh" | "max";
41
+
42
+ export function isThinkingLevel(value: string): value is GatewayThinkingLevel {
43
+ return (
44
+ value === "off" ||
45
+ value === "minimal" ||
46
+ value === "low" ||
47
+ value === "medium" ||
48
+ value === "high" ||
49
+ value === "xhigh" ||
50
+ value === "max"
51
+ );
52
+ }
@@ -0,0 +1,152 @@
1
+ /**
2
+ * Settings-facing routes for the opt-in local API gateway.
3
+ * @module dsh-coding-subscription-oauth/gateway-routes
4
+ */
5
+
6
+ import type { IncomingMessage, ServerResponse } from "node:http";
7
+ import type { CodingOAuthGatewayController } from "./gateway.ts";
8
+ import { assertGatewayPort } from "./gateway-config.ts";
9
+ import { readJsonRequest, requestErrorStatus } from "./http-json.ts";
10
+ import { safeMessage } from "./redact.ts";
11
+ import { isTrustedLoopbackWebRequest } from "./web-origin.ts";
12
+ import { registerWebRouteSetupAtomically } from "./web-routes.ts";
13
+
14
+ export const GATEWAY_SETTINGS_PATH = "/plugins/dsh-grok-build/gateway";
15
+ export const GATEWAY_REVEAL_PATH = "/plugins/dsh-grok-build/gateway/reveal";
16
+ export const GATEWAY_ROTATE_PATH = "/plugins/dsh-grok-build/gateway/rotate";
17
+
18
+ export interface GatewayRouteContext {
19
+ readonly webServer: {
20
+ register(route: {
21
+ kind: "exact" | "prefix";
22
+ path: string;
23
+ handler: (req: IncomingMessage, res: ServerResponse) => void | Promise<void>;
24
+ }): () => void;
25
+ };
26
+ effect(callback: () => () => void | Promise<void>, label?: string): unknown;
27
+ }
28
+
29
+ export function registerGatewayRoutes(ctx: GatewayRouteContext, controller: CodingOAuthGatewayController): () => void {
30
+ let dispose = (): void => undefined;
31
+ ctx.effect(() => {
32
+ dispose = registerWebRouteSetupAtomically(ctx.webServer, (webServer) => {
33
+ webServer.register({
34
+ kind: "exact",
35
+ path: GATEWAY_SETTINGS_PATH,
36
+ handler: (req, res) => handleGatewaySettings(req, res, controller),
37
+ });
38
+ webServer.register({
39
+ kind: "exact",
40
+ path: GATEWAY_REVEAL_PATH,
41
+ handler: (req, res) => handleGatewayReveal(req, res, controller),
42
+ });
43
+ webServer.register({
44
+ kind: "exact",
45
+ path: GATEWAY_ROTATE_PATH,
46
+ handler: (req, res) => handleGatewayRotate(req, res, controller),
47
+ });
48
+ });
49
+ return dispose;
50
+ }, "dsh-coding-subscription-oauth: gateway settings routes");
51
+ return () => dispose();
52
+ }
53
+
54
+ async function handleGatewaySettings(
55
+ req: IncomingMessage,
56
+ res: ServerResponse,
57
+ controller: CodingOAuthGatewayController,
58
+ ): Promise<void> {
59
+ if (!isTrustedLoopbackWebRequest(req)) {
60
+ json(res, 403, { error: "forbidden" });
61
+ return;
62
+ }
63
+ try {
64
+ if (req.method === "GET") {
65
+ json(res, 200, await controller.status());
66
+ return;
67
+ }
68
+ if (req.method === "PATCH") {
69
+ const raw = await readJsonRequest(req);
70
+ const payload = typeof raw === "object" && raw !== null ? (raw as { enabled?: unknown; port?: unknown }) : {};
71
+ const enabled = payload.enabled;
72
+ const port = payload.port;
73
+ if (enabled === undefined && port === undefined) {
74
+ json(res, 400, { error: "enabled or port is required" });
75
+ return;
76
+ }
77
+ if (enabled !== undefined && typeof enabled !== "boolean") {
78
+ json(res, 400, { error: "enabled must be a boolean" });
79
+ return;
80
+ }
81
+ if (port !== undefined) {
82
+ if (typeof port !== "number" || !Number.isSafeInteger(port)) {
83
+ json(res, 400, { error: "port must be an integer" });
84
+ return;
85
+ }
86
+ try {
87
+ assertGatewayPort(port);
88
+ } catch (error) {
89
+ json(res, 400, { error: safeMessage(error) });
90
+ return;
91
+ }
92
+ await controller.setPort(port);
93
+ }
94
+ const status = typeof enabled === "boolean" ? await controller.setEnabled(enabled) : await controller.status();
95
+ json(res, 200, status);
96
+ return;
97
+ }
98
+ json(res, 405, { error: "method not allowed" });
99
+ } catch (error) {
100
+ json(res, requestErrorStatus(error, 500), { error: safeMessage(error) });
101
+ }
102
+ }
103
+
104
+ async function handleGatewayReveal(
105
+ req: IncomingMessage,
106
+ res: ServerResponse,
107
+ controller: CodingOAuthGatewayController,
108
+ ): Promise<void> {
109
+ if (!isTrustedLoopbackWebRequest(req)) {
110
+ json(res, 403, { error: "forbidden" });
111
+ return;
112
+ }
113
+ if (req.method !== "POST") {
114
+ json(res, 405, { error: "method not allowed" });
115
+ return;
116
+ }
117
+ try {
118
+ json(res, 200, await controller.revealKey());
119
+ } catch (error) {
120
+ json(res, requestErrorStatus(error, 500), { error: safeMessage(error) });
121
+ }
122
+ }
123
+
124
+ async function handleGatewayRotate(
125
+ req: IncomingMessage,
126
+ res: ServerResponse,
127
+ controller: CodingOAuthGatewayController,
128
+ ): Promise<void> {
129
+ if (!isTrustedLoopbackWebRequest(req)) {
130
+ json(res, 403, { error: "forbidden" });
131
+ return;
132
+ }
133
+ if (req.method !== "POST") {
134
+ json(res, 405, { error: "method not allowed" });
135
+ return;
136
+ }
137
+ try {
138
+ json(res, 200, await controller.rotateKey());
139
+ } catch (error) {
140
+ json(res, requestErrorStatus(error, 500), { error: safeMessage(error) });
141
+ }
142
+ }
143
+
144
+ function json(res: ServerResponse, status: number, value: unknown): void {
145
+ const body = Buffer.from(`${JSON.stringify(value)}\n`);
146
+ res.writeHead(status, {
147
+ "content-type": "application/json; charset=utf-8",
148
+ "content-length": body.byteLength,
149
+ "cache-control": "no-store",
150
+ });
151
+ res.end(body);
152
+ }
package/src/gateway.ts ADDED
@@ -0,0 +1,242 @@
1
+ /**
2
+ * Start, stop, and rotate the opt-in local coding-subscription API gateway.
3
+ * @module dsh-coding-subscription-oauth/gateway
4
+ */
5
+
6
+ import type { Server } from "node:http";
7
+ import {
8
+ gatewayKeyPath,
9
+ generateGatewayApiKey,
10
+ loadGatewayKeyDocument,
11
+ loadOrCreateGatewayApiKey,
12
+ maskGatewayApiKey,
13
+ persistGatewayKeyDocument,
14
+ } from "./gateway-auth.ts";
15
+ import { createSessionGatewayBackend, type GatewayBackend } from "./gateway-backend.ts";
16
+ import { assertGatewayPort, type GatewayConfig, resolveGatewayConfig } from "./gateway-config.ts";
17
+ import { closeGateway, createGatewayHttpServer, listenGateway } from "./gateway-http.ts";
18
+ import type { OAuthProviderSession } from "./oauth-session.ts";
19
+ import type { GrokBuildSession } from "./session.ts";
20
+
21
+ export const GATEWAY_TOS_WARNING =
22
+ "local API gateway is enabled; exposing a subscription as a local API can violate provider ToS and consumes your quota";
23
+
24
+ export interface StartGatewayOptions {
25
+ config?: Partial<GatewayConfig>;
26
+ dshHome?: string;
27
+ backend?: GatewayBackend;
28
+ grok?: GrokBuildSession;
29
+ subscriptions?: readonly OAuthProviderSession[];
30
+ onError?: (error: unknown) => void;
31
+ }
32
+
33
+ export interface StartedGateway {
34
+ close(): Promise<void>;
35
+ readonly bind: string;
36
+ readonly port: number;
37
+ }
38
+
39
+ export interface GatewayPublicStatus {
40
+ enabled: boolean;
41
+ running: boolean;
42
+ bind: string;
43
+ port: number;
44
+ keyHint: string;
45
+ warning: string;
46
+ }
47
+
48
+ export interface CodingOAuthGatewayController {
49
+ status(): Promise<GatewayPublicStatus>;
50
+ startIfEnabled(): Promise<StartedGateway | undefined>;
51
+ setEnabled(enabled: boolean): Promise<GatewayPublicStatus>;
52
+ setPort(port: number): Promise<GatewayPublicStatus>;
53
+ revealKey(): Promise<{ apiKey: string; keyHint: string }>;
54
+ rotateKey(): Promise<{ apiKey: string; keyHint: string }>;
55
+ stop(): Promise<void>;
56
+ }
57
+
58
+ export async function startCodingOAuthGateway(options: StartGatewayOptions): Promise<StartedGateway | undefined> {
59
+ const controller = createCodingOAuthGatewayController(options);
60
+ return controller.startIfEnabled();
61
+ }
62
+
63
+ export function createCodingOAuthGatewayController(options: StartGatewayOptions): CodingOAuthGatewayController {
64
+ const yaml = resolveGatewayConfig(options.config);
65
+ const path = gatewayKeyPath(options.dshHome);
66
+ const backend = (): GatewayBackend => {
67
+ if (options.backend !== undefined) return options.backend;
68
+ if (options.grok === undefined) throw new Error("gateway requires a backend or Grok session");
69
+ return createSessionGatewayBackend(options.grok, options.subscriptions ?? []);
70
+ };
71
+ let server: Server | undefined;
72
+ let apiKey = yaml.apiKey ?? "";
73
+ let port = yaml.port;
74
+ let lock: Promise<void> = Promise.resolve();
75
+
76
+ const withLock = async <T>(work: () => Promise<T>): Promise<T> => {
77
+ const previous = lock;
78
+ let release: () => void = () => undefined;
79
+ lock = new Promise<void>((resolve) => {
80
+ release = resolve;
81
+ });
82
+ await previous;
83
+ try {
84
+ return await work();
85
+ } finally {
86
+ release();
87
+ }
88
+ };
89
+
90
+ const closeServer = async (): Promise<void> => {
91
+ if (server === undefined) return;
92
+ const current = server;
93
+ server = undefined;
94
+ await closeGateway(current).catch(() => undefined);
95
+ };
96
+
97
+ const activeConfig = (): GatewayConfig => ({ ...yaml, port });
98
+
99
+ const snapshot = async (enabled?: boolean): Promise<GatewayPublicStatus> => ({
100
+ enabled: enabled ?? (await desiredEnabled()),
101
+ running: server !== undefined,
102
+ bind: yaml.bind,
103
+ port,
104
+ keyHint: apiKey.length === 0 ? "" : maskGatewayApiKey(apiKey),
105
+ warning: GATEWAY_TOS_WARNING,
106
+ });
107
+
108
+ const persistState = async (next: { enabled?: boolean; port?: number; apiKey?: string }): Promise<void> => {
109
+ const document = await loadGatewayKeyDocument(path);
110
+ const nextKey = next.apiKey ?? (apiKey.length === 0 ? document?.apiKey : apiKey);
111
+ if (nextKey === undefined || nextKey.length === 0) throw new Error("gateway api key is missing");
112
+ apiKey = nextKey;
113
+ const nextEnabled = next.enabled ?? document?.enabled;
114
+ const nextPort = next.port ?? document?.port ?? port;
115
+ port = nextPort;
116
+ await persistGatewayKeyDocument(path, {
117
+ version: 1,
118
+ apiKey: nextKey,
119
+ ...(nextEnabled === undefined ? {} : { enabled: nextEnabled }),
120
+ port: nextPort,
121
+ });
122
+ };
123
+
124
+ const listen = async (): Promise<StartedGateway> => {
125
+ if (apiKey.length === 0) apiKey = await loadOrCreateGatewayApiKey(path, yaml.apiKey);
126
+ const config = activeConfig();
127
+ const http = createGatewayHttpServer({ config, apiKey, backend: backend() });
128
+ try {
129
+ await listenGateway(http, config);
130
+ } catch (error) {
131
+ await closeGateway(http).catch(() => undefined);
132
+ options.onError?.(error);
133
+ throw error;
134
+ }
135
+ server = http;
136
+ return { bind: config.bind, port: config.port, close: () => closeServer() };
137
+ };
138
+
139
+ const desiredEnabled = async (): Promise<boolean> => {
140
+ const document = await loadGatewayKeyDocument(path);
141
+ return document?.enabled ?? yaml.enabled;
142
+ };
143
+
144
+ const hydratePort = async (): Promise<void> => {
145
+ const document = await loadGatewayKeyDocument(path);
146
+ if (document?.port !== undefined) port = document.port;
147
+ };
148
+
149
+ return {
150
+ async status() {
151
+ await hydratePort();
152
+ if (apiKey.length === 0) {
153
+ const document = await loadGatewayKeyDocument(path);
154
+ apiKey = document?.apiKey ?? "";
155
+ }
156
+ return snapshot();
157
+ },
158
+ startIfEnabled() {
159
+ return withLock(async () => {
160
+ await hydratePort();
161
+ if (!(await desiredEnabled())) return undefined;
162
+ if (server !== undefined) return { bind: yaml.bind, port, close: () => closeServer() };
163
+ try {
164
+ return await listen();
165
+ } catch {
166
+ return undefined;
167
+ }
168
+ });
169
+ },
170
+ setEnabled(enabled) {
171
+ return withLock(async () => {
172
+ await hydratePort();
173
+ if (apiKey.length === 0) apiKey = await loadOrCreateGatewayApiKey(path, yaml.apiKey);
174
+ await persistState({ enabled });
175
+ if (enabled && server === undefined) {
176
+ try {
177
+ await listen();
178
+ } catch {
179
+ // status.running stays false; caller sees the public snapshot.
180
+ }
181
+ }
182
+ if (!enabled) await closeServer();
183
+ return snapshot(enabled);
184
+ });
185
+ },
186
+ setPort(nextPort) {
187
+ return withLock(async () => {
188
+ await hydratePort();
189
+ const wanted = assertGatewayPort(nextPort);
190
+ if (apiKey.length === 0) apiKey = await loadOrCreateGatewayApiKey(path, yaml.apiKey);
191
+ const previous = port;
192
+ const shouldRun = server !== undefined;
193
+ await persistState({ port: wanted });
194
+ if (!shouldRun) return snapshot();
195
+ await closeServer();
196
+ try {
197
+ await listen();
198
+ return snapshot();
199
+ } catch (error) {
200
+ port = previous;
201
+ await persistState({ port: previous });
202
+ try {
203
+ await listen();
204
+ } catch {
205
+ // previous port may also fail; status.running reflects reality
206
+ }
207
+ throw error;
208
+ }
209
+ });
210
+ },
211
+ revealKey() {
212
+ return withLock(async () => {
213
+ if (apiKey.length === 0) apiKey = await loadOrCreateGatewayApiKey(path, yaml.apiKey);
214
+ return { apiKey, keyHint: maskGatewayApiKey(apiKey) };
215
+ });
216
+ },
217
+ rotateKey() {
218
+ return withLock(async () => {
219
+ await hydratePort();
220
+ const next = generateGatewayApiKey();
221
+ const document = await loadGatewayKeyDocument(path);
222
+ await persistState({
223
+ apiKey: next,
224
+ ...(document?.enabled === undefined ? {} : { enabled: document.enabled }),
225
+ });
226
+ const shouldRun = server !== undefined;
227
+ await closeServer();
228
+ if (shouldRun) {
229
+ try {
230
+ await listen();
231
+ } catch {
232
+ // rotated key is persisted even if listen fails
233
+ }
234
+ }
235
+ return { apiKey: next, keyHint: maskGatewayApiKey(next) };
236
+ });
237
+ },
238
+ stop() {
239
+ return withLock(() => closeServer());
240
+ },
241
+ };
242
+ }