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,263 @@
1
+ /**
2
+ * Optional ChatGPT Codex quota reader (`GET /backend-api/wham/usage`).
3
+ * Normalizes unknown/malformed optional fields instead of failing the card.
4
+ *
5
+ * Cache semantics:
6
+ * - A successful `read()` stores the projection until `ttlMs` elapses.
7
+ * - Concurrent non-force `read()` calls share one in-flight GET.
8
+ * - `read({ force: true })` always issues a new GET and never joins an
9
+ * existing in-flight read (forced or not). A later completion of the
10
+ * abandoned in-flight GET cannot overwrite the forced result.
11
+ * - `clear()` drops the stored projection and detaches any in-flight GET so
12
+ * its later completion cannot repopulate the cache.
13
+ *
14
+ * @module dsh-coding-subscription-oauth/codex-usage
15
+ */
16
+
17
+ import { LlmError } from "@deepseek-ai/dsh-llm";
18
+ import {
19
+ type CodexAuthSession,
20
+ type CodexFetch,
21
+ type CodexHttpClient,
22
+ createCodexHttpClient,
23
+ isRecord,
24
+ optionalNonEmptyString,
25
+ } from "./codex-http.ts";
26
+
27
+ /** Official ChatGPT rate-limit usage endpoint used by the Codex client. */
28
+ export const CODEX_USAGE_URL = "https://chatgpt.com/backend-api/wham/usage";
29
+
30
+ export interface CodexRateLimitWindow {
31
+ readonly usedPercent: number;
32
+ readonly remainingPercent: number;
33
+ readonly windowSeconds: number;
34
+ readonly resetsAt?: number;
35
+ }
36
+
37
+ export interface CodexRateLimit {
38
+ readonly id: string;
39
+ readonly name?: string;
40
+ readonly windows: readonly CodexRateLimitWindow[];
41
+ }
42
+
43
+ export interface CodexCredits {
44
+ readonly unlimited: boolean;
45
+ readonly balance?: string;
46
+ }
47
+
48
+ export interface CodexIndividualLimit {
49
+ readonly limit: string;
50
+ readonly used: string;
51
+ readonly remaining?: string;
52
+ readonly remainingPercent: number;
53
+ readonly resetsAt?: number;
54
+ }
55
+
56
+ export interface CodexUsage {
57
+ readonly rateLimits: readonly CodexRateLimit[];
58
+ readonly credits?: CodexCredits;
59
+ readonly individualLimit?: CodexIndividualLimit;
60
+ readonly spendControlReached?: boolean;
61
+ readonly resetCredits?: { readonly availableCount: number };
62
+ readonly fetchedAt: number;
63
+ }
64
+
65
+ export interface CodexUsageReaderOptions {
66
+ readonly auth: CodexAuthSession;
67
+ readonly http?: CodexHttpClient;
68
+ readonly fetchImpl?: CodexFetch;
69
+ readonly originator?: string;
70
+ readonly userAgent?: string;
71
+ readonly sleep?: (ms: number, signal?: AbortSignal) => Promise<void>;
72
+ readonly now?: () => number;
73
+ readonly ttlMs?: number;
74
+ }
75
+
76
+ export interface CodexUsageReader {
77
+ read(options?: { force?: boolean; signal?: AbortSignal }): Promise<CodexUsage>;
78
+ clear(): void;
79
+ }
80
+
81
+ const DEFAULT_TTL_MS = 60_000;
82
+
83
+ function finitePercent(value: unknown): number | undefined {
84
+ return typeof value === "number" && Number.isFinite(value) && value >= 0 && value <= 100 ? value : undefined;
85
+ }
86
+
87
+ function positiveInt(value: unknown): number | undefined {
88
+ return typeof value === "number" && Number.isSafeInteger(value) && value > 0 ? value : undefined;
89
+ }
90
+
91
+ function epochSeconds(value: unknown): number | undefined {
92
+ if (value === undefined || value === null || value === 0) return undefined;
93
+ return typeof value === "number" && Number.isSafeInteger(value) && value > 0 ? value : undefined;
94
+ }
95
+
96
+ function decimalAmount(value: unknown): string | undefined {
97
+ return typeof value === "string" && value.length > 0 && value.length <= 64 && /^-?\d+(?:\.\d+)?$/u.test(value)
98
+ ? value
99
+ : undefined;
100
+ }
101
+
102
+ function parseWindow(value: unknown): CodexRateLimitWindow | undefined {
103
+ if (!isRecord(value)) return undefined;
104
+ const usedPercent = finitePercent(value["used_percent"]);
105
+ const windowSeconds = positiveInt(value["limit_window_seconds"]);
106
+ if (usedPercent === undefined || windowSeconds === undefined) return undefined;
107
+ const resetsAt = epochSeconds(value["reset_at"]);
108
+ return {
109
+ usedPercent,
110
+ remainingPercent: 100 - usedPercent,
111
+ windowSeconds,
112
+ ...(resetsAt === undefined ? {} : { resetsAt }),
113
+ };
114
+ }
115
+
116
+ function parseLimit(id: string, name: string | undefined, value: unknown): CodexRateLimit | undefined {
117
+ if (!isRecord(value)) return undefined;
118
+ const windows = [parseWindow(value["primary_window"]), parseWindow(value["secondary_window"])].filter(
119
+ (window): window is CodexRateLimitWindow => window !== undefined,
120
+ );
121
+ if (windows.length === 0) return undefined;
122
+ return { id, ...(name === undefined ? {} : { name }), windows };
123
+ }
124
+
125
+ function parseCredits(value: unknown): CodexCredits | undefined {
126
+ if (!isRecord(value) || value["has_credits"] !== true || typeof value["unlimited"] !== "boolean") return undefined;
127
+ const balance = decimalAmount(value["balance"]);
128
+ return {
129
+ unlimited: value["unlimited"],
130
+ ...(balance === undefined ? {} : { balance }),
131
+ };
132
+ }
133
+
134
+ function parseIndividualLimit(value: unknown): CodexIndividualLimit | undefined {
135
+ if (!isRecord(value)) return undefined;
136
+ const individual = value["individual_limit"];
137
+ if (!isRecord(individual)) return undefined;
138
+ const remainingPercent = finitePercent(individual["remaining_percent"]);
139
+ const limit = decimalAmount(individual["limit"]);
140
+ const used = decimalAmount(individual["used"]);
141
+ if (remainingPercent === undefined || limit === undefined || used === undefined) return undefined;
142
+ const remaining = decimalAmount(individual["remaining"]);
143
+ const resetsAt = epochSeconds(individual["reset_at"]);
144
+ return {
145
+ limit,
146
+ used,
147
+ remainingPercent,
148
+ ...(remaining === undefined ? {} : { remaining }),
149
+ ...(resetsAt === undefined ? {} : { resetsAt }),
150
+ };
151
+ }
152
+
153
+ function copyUsage(usage: CodexUsage): CodexUsage {
154
+ return { ...usage, rateLimits: [...usage.rateLimits] };
155
+ }
156
+
157
+ /**
158
+ * Reduce an opaque `wham/usage` payload to a secret-free quota projection.
159
+ * Unknown extra fields are ignored; malformed optional buckets are skipped.
160
+ */
161
+ export function normalizeCodexUsage(value: unknown, fetchedAt = Date.now()): CodexUsage {
162
+ if (!isRecord(value)) {
163
+ throw new LlmError("Codex returned a malformed usage response", "SERVER");
164
+ }
165
+ const rateLimits: CodexRateLimit[] = [];
166
+ const seen = new Set<string>();
167
+ const add = (limit: CodexRateLimit | undefined): void => {
168
+ if (limit === undefined || seen.has(limit.id)) return;
169
+ seen.add(limit.id);
170
+ rateLimits.push(limit);
171
+ };
172
+ add(parseLimit("codex", "Codex", value["rate_limit"]));
173
+ const additional = value["additional_rate_limits"];
174
+ if (Array.isArray(additional)) {
175
+ for (const entry of additional) {
176
+ if (!isRecord(entry)) continue;
177
+ const id = optionalNonEmptyString(entry["metered_feature"]);
178
+ if (id === undefined) continue;
179
+ const name = optionalNonEmptyString(entry["limit_name"]);
180
+ add(parseLimit(id, name, entry["rate_limit"]));
181
+ }
182
+ }
183
+ add(parseLimit("code_review", "Code review", value["code_review_rate_limit"]));
184
+ const credits = parseCredits(value["credits"]);
185
+ const individualLimit = parseIndividualLimit(value["spend_control"]);
186
+ const spendControlReached =
187
+ isRecord(value["spend_control"]) && typeof value["spend_control"]["reached"] === "boolean"
188
+ ? value["spend_control"]["reached"]
189
+ : undefined;
190
+ const resetRaw = value["rate_limit_reset_credits"];
191
+ const resetCount = isRecord(resetRaw) ? resetRaw["available_count"] : undefined;
192
+ const resetCredits =
193
+ typeof resetCount === "number" && Number.isSafeInteger(resetCount) && resetCount >= 0
194
+ ? { availableCount: resetCount }
195
+ : undefined;
196
+ return {
197
+ rateLimits,
198
+ fetchedAt,
199
+ ...(credits === undefined ? {} : { credits }),
200
+ ...(individualLimit === undefined ? {} : { individualLimit }),
201
+ ...(spendControlReached === undefined ? {} : { spendControlReached }),
202
+ ...(resetCredits === undefined ? {} : { resetCredits }),
203
+ };
204
+ }
205
+
206
+ /**
207
+ * Cached, injectable usage reader. Failures do not invent quota numbers.
208
+ *
209
+ * See the module doc for `force` / `clear` cache semantics.
210
+ */
211
+ export function createCodexUsageReader(options: CodexUsageReaderOptions): CodexUsageReader {
212
+ const http =
213
+ options.http ??
214
+ createCodexHttpClient({
215
+ auth: options.auth,
216
+ ...(options.fetchImpl === undefined ? {} : { fetchImpl: options.fetchImpl }),
217
+ ...(options.originator === undefined ? {} : { originator: options.originator }),
218
+ ...(options.userAgent === undefined ? {} : { userAgent: options.userAgent }),
219
+ ...(options.sleep === undefined ? {} : { sleep: options.sleep }),
220
+ ...(options.now === undefined ? {} : { now: options.now }),
221
+ });
222
+ const now = options.now ?? Date.now;
223
+ const ttlMs = options.ttlMs ?? DEFAULT_TTL_MS;
224
+ let cached: CodexUsage | undefined;
225
+ let inFlight: Promise<CodexUsage> | undefined;
226
+ let epoch = 0;
227
+
228
+ const load = async (signal?: AbortSignal): Promise<CodexUsage> => {
229
+ const payload = await http.requestJson({
230
+ url: CODEX_USAGE_URL,
231
+ method: "GET",
232
+ headers: { "cache-control": "no-store" },
233
+ ...(signal === undefined ? {} : { signal }),
234
+ });
235
+ return normalizeCodexUsage(payload, now());
236
+ };
237
+
238
+ return {
239
+ read({ force = false, signal } = {}) {
240
+ if (!force && cached !== undefined && now() - cached.fetchedAt < ttlMs) {
241
+ return Promise.resolve(copyUsage(cached));
242
+ }
243
+ if (!force && inFlight !== undefined) return inFlight;
244
+ if (force) epoch += 1;
245
+ const started = epoch;
246
+ const current = load(signal)
247
+ .then((value) => {
248
+ if (started === epoch) cached = value;
249
+ return value;
250
+ })
251
+ .finally(() => {
252
+ if (inFlight === current) inFlight = undefined;
253
+ });
254
+ inFlight = current;
255
+ return current;
256
+ },
257
+ clear() {
258
+ epoch += 1;
259
+ cached = undefined;
260
+ inFlight = undefined;
261
+ },
262
+ };
263
+ }
@@ -0,0 +1,84 @@
1
+ /**
2
+ * Anthropic Messages API subset for the local gateway.
3
+ * @module dsh-coding-subscription-oauth/gateway-anthropic-messages
4
+ */
5
+
6
+ import type { IncomingMessage, ServerResponse } from "node:http";
7
+ import { type GatewayBackend, gatewayErrorEnvelope } from "./gateway-backend.ts";
8
+ import { beginGatewaySse, readGatewayJsonBody, writeGatewayJson } from "./gateway-body.ts";
9
+ import { anthropicMaxTokens, parseAnthropicMessagesRequest } from "./gateway-parse.ts";
10
+
11
+ export async function handleAnthropicMessages(
12
+ req: IncomingMessage,
13
+ res: ServerResponse,
14
+ backend: GatewayBackend,
15
+ ): Promise<void> {
16
+ const payload = await readGatewayJsonBody(req);
17
+ const request = parseAnthropicMessagesRequest(payload);
18
+ const maxTokens = anthropicMaxTokens(payload);
19
+ const stream = payload["stream"] === true;
20
+ const id = `msg_gateway_${Date.now().toString(36)}`;
21
+ if (!stream) {
22
+ let text = "";
23
+ const toolUses: Array<{ id: string; name: string; input: unknown }> = [];
24
+ let stop = "end_turn";
25
+ for await (const part of backend.stream(request)) {
26
+ if (part.type === "text") text += part.text;
27
+ if (part.type === "tool_call") {
28
+ let input: unknown = {};
29
+ try {
30
+ input = JSON.parse(part.arguments) as unknown;
31
+ } catch {
32
+ input = { value: part.arguments };
33
+ }
34
+ toolUses.push({ id: part.id, name: part.name, input });
35
+ }
36
+ if (part.type === "done" && part.finish === "tool_calls") stop = "tool_use";
37
+ }
38
+ writeGatewayJson(res, 200, {
39
+ id,
40
+ type: "message",
41
+ role: "assistant",
42
+ model: request.model,
43
+ content: [
44
+ ...(text.length === 0 ? [] : [{ type: "text", text }]),
45
+ ...toolUses.map((tool) => ({ type: "tool_use", id: tool.id, name: tool.name, input: tool.input })),
46
+ ],
47
+ stop_reason: stop,
48
+ usage: { input_tokens: 0, output_tokens: 0 },
49
+ max_tokens: maxTokens,
50
+ });
51
+ return;
52
+ }
53
+ beginGatewaySse(res);
54
+ try {
55
+ res.write(
56
+ `event: message_start\ndata: ${JSON.stringify({ type: "message_start", message: { id, type: "message", role: "assistant", model: request.model, content: [] } })}\n\n`,
57
+ );
58
+ let started = false;
59
+ for await (const part of backend.stream(request)) {
60
+ if (part.type === "text") {
61
+ if (!started) {
62
+ res.write(
63
+ `event: content_block_start\ndata: ${JSON.stringify({ type: "content_block_start", index: 0, content_block: { type: "text", text: "" } })}\n\n`,
64
+ );
65
+ started = true;
66
+ }
67
+ res.write(
68
+ `event: content_block_delta\ndata: ${JSON.stringify({ type: "content_block_delta", index: 0, delta: { type: "text_delta", text: part.text } })}\n\n`,
69
+ );
70
+ }
71
+ }
72
+ if (started) {
73
+ res.write(`event: content_block_stop\ndata: ${JSON.stringify({ type: "content_block_stop", index: 0 })}\n\n`);
74
+ }
75
+ res.write(
76
+ `event: message_delta\ndata: ${JSON.stringify({ type: "message_delta", delta: { stop_reason: "end_turn" } })}\n\n`,
77
+ );
78
+ res.write(`event: message_stop\ndata: ${JSON.stringify({ type: "message_stop" })}\n\n`);
79
+ res.end();
80
+ } catch (error) {
81
+ res.write(`event: error\ndata: ${JSON.stringify(gatewayErrorEnvelope(error).body)}\n\n`);
82
+ res.end();
83
+ }
84
+ }
@@ -0,0 +1,100 @@
1
+ /**
2
+ * Owner-only gateway API key file.
3
+ * @module dsh-coding-subscription-oauth/gateway-auth
4
+ */
5
+
6
+ import { randomBytes, timingSafeEqual } from "node:crypto";
7
+ import { mkdir } from "node:fs/promises";
8
+ import { dirname, join, resolve } from "node:path";
9
+ import { writeFileAtomic } from "@deepseek-ai/dsh-atomic-write";
10
+ import { resolveDshHome } from "@deepseek-ai/dsh-home-paths";
11
+ import { OAuthSourceError, readHardenedOAuthSourceFile } from "./oauth-sources.ts";
12
+
13
+ export const GATEWAY_KEY_FILENAME = ".coding-oauth-gateway.json";
14
+ const KEY_FORMAT_VERSION = 1;
15
+
16
+ export interface GatewayKeyDocument {
17
+ version: typeof KEY_FORMAT_VERSION;
18
+ apiKey: string;
19
+ enabled?: boolean;
20
+ port?: number;
21
+ }
22
+
23
+ export function gatewayKeyPath(dshHome?: string): string {
24
+ return resolve(join(resolveDshHome(dshHome), GATEWAY_KEY_FILENAME));
25
+ }
26
+
27
+ export function generateGatewayApiKey(): string {
28
+ return randomBytes(32).toString("base64url");
29
+ }
30
+
31
+ export function gatewayKeysEqual(left: string, right: string): boolean {
32
+ const a = Buffer.from(left);
33
+ const b = Buffer.from(right);
34
+ return a.length === b.length && a.length > 0 && timingSafeEqual(a, b);
35
+ }
36
+
37
+ export function maskGatewayApiKey(apiKey: string): string {
38
+ if (apiKey.length <= 4) return "****";
39
+ return `****${apiKey.slice(-4)}`;
40
+ }
41
+
42
+ export async function loadGatewayKeyDocument(path: string): Promise<GatewayKeyDocument | undefined> {
43
+ try {
44
+ const text = (await readHardenedOAuthSourceFile(path)).text;
45
+ const value = JSON.parse(text) as unknown;
46
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
47
+ throw new Error("gateway key file must contain an object");
48
+ }
49
+ const document = value as Record<string, unknown>;
50
+ if (
51
+ document["version"] !== KEY_FORMAT_VERSION ||
52
+ typeof document["apiKey"] !== "string" ||
53
+ document["apiKey"].length === 0
54
+ ) {
55
+ throw new Error("gateway key file is invalid");
56
+ }
57
+ const port = document["port"];
58
+ return {
59
+ version: KEY_FORMAT_VERSION,
60
+ apiKey: document["apiKey"],
61
+ ...(typeof document["enabled"] === "boolean" ? { enabled: document["enabled"] } : {}),
62
+ ...(typeof port === "number" && Number.isSafeInteger(port) && port >= 1024 && port <= 65_535 ? { port } : {}),
63
+ };
64
+ } catch (error) {
65
+ if (error instanceof OAuthSourceError && error.code === "not_found") return undefined;
66
+ throw error;
67
+ }
68
+ }
69
+
70
+ export async function loadOrCreateGatewayApiKey(path: string, configured?: string): Promise<string> {
71
+ const existing = await loadGatewayKeyDocument(path);
72
+ if (configured !== undefined) {
73
+ await persistGatewayKeyDocument(path, {
74
+ version: KEY_FORMAT_VERSION,
75
+ apiKey: configured,
76
+ ...(existing?.enabled === undefined ? {} : { enabled: existing.enabled }),
77
+ ...(existing?.port === undefined ? {} : { port: existing.port }),
78
+ });
79
+ return configured;
80
+ }
81
+ if (existing !== undefined) return existing.apiKey;
82
+ const created = generateGatewayApiKey();
83
+ await persistGatewayKeyDocument(path, { version: KEY_FORMAT_VERSION, apiKey: created });
84
+ return created;
85
+ }
86
+
87
+ export async function persistGatewayApiKey(path: string, apiKey: string): Promise<void> {
88
+ const existing = await loadGatewayKeyDocument(path);
89
+ await persistGatewayKeyDocument(path, {
90
+ version: KEY_FORMAT_VERSION,
91
+ apiKey,
92
+ ...(existing?.enabled === undefined ? {} : { enabled: existing.enabled }),
93
+ ...(existing?.port === undefined ? {} : { port: existing.port }),
94
+ });
95
+ }
96
+
97
+ export async function persistGatewayKeyDocument(path: string, document: GatewayKeyDocument): Promise<void> {
98
+ await mkdir(dirname(path), { recursive: true, mode: 0o700 });
99
+ await writeFileAtomic(path, `${JSON.stringify(document)}\n`, { mode: 0o600 });
100
+ }