dsh-coding-subscription-oauth 0.5.8 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (141) hide show
  1. package/CHANGELOG.md +211 -196
  2. package/CONTRIBUTING.md +120 -120
  3. package/INSTALL.md +240 -209
  4. package/LICENSE +19 -19
  5. package/NOTICE +11 -11
  6. package/README.de.md +298 -293
  7. package/README.es.md +299 -294
  8. package/README.fr.md +299 -294
  9. package/README.ja.md +299 -294
  10. package/README.ko.md +299 -294
  11. package/README.md +313 -306
  12. package/README.pt-BR.md +299 -294
  13. package/README.ru.md +299 -294
  14. package/README.zh-CN.md +311 -304
  15. package/compatibility/dsh-bom.json +43 -0
  16. package/cordis.patch.yml +13 -13
  17. package/docs/00-project-rules.md +195 -195
  18. package/docs/02-architecture.md +134 -129
  19. package/docs/02-architecture.zh-CN.md +134 -129
  20. package/lib/auth-routes.d.ts +8 -15
  21. package/lib/auth-routes.d.ts.map +1 -1
  22. package/lib/bin.js +746 -1402
  23. package/lib/bin.js.map +4 -4
  24. package/lib/capability-routes.d.ts +3 -3
  25. package/lib/capability-routes.d.ts.map +1 -1
  26. package/lib/capability-settings.d.ts +5 -4
  27. package/lib/capability-settings.d.ts.map +1 -1
  28. package/lib/client.js +27 -8
  29. package/lib/client.js.map +4 -4
  30. package/lib/compatibility.d.ts +46 -0
  31. package/lib/compatibility.d.ts.map +1 -0
  32. package/lib/dsh-host-adapter.d.ts +18 -0
  33. package/lib/dsh-host-adapter.d.ts.map +1 -0
  34. package/lib/gateway-auth.d.ts +1 -2
  35. package/lib/gateway-auth.d.ts.map +1 -1
  36. package/lib/gateway-routes.d.ts +3 -4
  37. package/lib/gateway-routes.d.ts.map +1 -1
  38. package/lib/gateway.d.ts +4 -0
  39. package/lib/gateway.d.ts.map +1 -1
  40. package/lib/ids.d.ts +3 -32
  41. package/lib/ids.d.ts.map +1 -1
  42. package/lib/imagine-routes.d.ts +2 -0
  43. package/lib/imagine-routes.d.ts.map +1 -1
  44. package/lib/index.d.ts +19 -4
  45. package/lib/index.d.ts.map +1 -1
  46. package/lib/index.js +26573 -1023
  47. package/lib/index.js.map +4 -4
  48. package/lib/invariant.js.map +1 -1
  49. package/lib/oauth-import-routes.d.ts +3 -4
  50. package/lib/oauth-import-routes.d.ts.map +1 -1
  51. package/lib/proxy.d.ts +3 -16
  52. package/lib/proxy.d.ts.map +1 -1
  53. package/lib/web-origin.d.ts +28 -4
  54. package/lib/web-origin.d.ts.map +1 -1
  55. package/lib/web-routes.d.ts.map +1 -1
  56. package/media/en/settings_accounts.png +0 -0
  57. package/media/en/settings_capabilities.png +0 -0
  58. package/media/en/settings_gateway.png +0 -0
  59. package/media/zh-CN/settings_accounts.png +0 -0
  60. package/media/zh-CN/settings_capabilities.png +0 -0
  61. package/media/zh-CN/settings_gateway.png +0 -0
  62. package/package.json +209 -172
  63. package/patches/dsh-agy@0.1.2.patch +25 -25
  64. package/scripts/release.mjs +186 -170
  65. package/scripts/smoke-deployed-routes.mjs +146 -146
  66. package/scripts/verify-deployed-catalog.mjs +87 -87
  67. package/src/adapter.ts +287 -287
  68. package/src/alias-adapter.ts +153 -153
  69. package/src/auth-routes.ts +921 -871
  70. package/src/auth.ts +67 -67
  71. package/src/bin.ts +350 -350
  72. package/src/capability-routes.ts +279 -275
  73. package/src/capability-runtime.ts +313 -313
  74. package/src/capability-settings.ts +658 -657
  75. package/src/capability-tools.ts +666 -666
  76. package/src/catalog.ts +271 -271
  77. package/src/client/GrokBuildSettings.tsx +770 -718
  78. package/src/client/api.ts +88 -88
  79. package/src/client/components/AboutTab.tsx +30 -30
  80. package/src/client/components/AccountsTab.tsx +241 -224
  81. package/src/client/components/Badge.tsx +33 -33
  82. package/src/client/components/CapabilitiesTab.tsx +265 -227
  83. package/src/client/components/CliPullPreview.tsx +116 -107
  84. package/src/client/components/CopyButton.tsx +57 -57
  85. package/src/client/components/GatewayTab.tsx +469 -409
  86. package/src/client/components/NoticeBanner.tsx +46 -46
  87. package/src/client/components/ProgressBar.tsx +53 -53
  88. package/src/client/components/ProviderCard.tsx +606 -502
  89. package/src/client/components/SettingsTabs.tsx +75 -75
  90. package/src/client/components/ToggleSwitch.tsx +71 -62
  91. package/src/client/constants.ts +224 -206
  92. package/src/client/display.ts +61 -61
  93. package/src/client/dshClientAdapter.ts +109 -0
  94. package/src/client/gatewaySnippets.ts +37 -36
  95. package/src/client/index.tsx +156 -37
  96. package/src/client/locales.ts +535 -491
  97. package/src/client/microStyles.ts +52 -33
  98. package/src/client/parsers.ts +396 -386
  99. package/src/client/styles.ts +325 -307
  100. package/src/client/types.ts +197 -185
  101. package/src/codex-http.ts +447 -447
  102. package/src/codex-images.ts +485 -485
  103. package/src/codex-model-capabilities.ts +320 -320
  104. package/src/codex-search.ts +245 -245
  105. package/src/codex-usage.ts +263 -263
  106. package/src/compatibility.ts +55 -0
  107. package/src/dsh-host-adapter.ts +171 -0
  108. package/src/gateway-anthropic-messages.ts +84 -84
  109. package/src/gateway-auth.ts +102 -100
  110. package/src/gateway-backend.ts +274 -274
  111. package/src/gateway-body.ts +49 -49
  112. package/src/gateway-config.ts +76 -76
  113. package/src/gateway-http.ts +104 -104
  114. package/src/gateway-openai-chat.ts +124 -124
  115. package/src/gateway-openai-responses.ts +53 -53
  116. package/src/gateway-parse.ts +224 -224
  117. package/src/gateway-protocol.ts +52 -52
  118. package/src/gateway-routes.ts +158 -152
  119. package/src/gateway.ts +258 -242
  120. package/src/grok-errors.ts +24 -24
  121. package/src/grok-imagine.ts +1627 -1627
  122. package/src/grok-import.ts +151 -151
  123. package/src/http-json.ts +82 -82
  124. package/src/ids.ts +59 -45
  125. package/src/imagine-routes.ts +463 -461
  126. package/src/index.ts +748 -598
  127. package/src/invariant.ts +17 -17
  128. package/src/kimi-errors.ts +26 -26
  129. package/src/media-store.ts +927 -927
  130. package/src/oauth-import-routes.ts +324 -314
  131. package/src/oauth-providers.ts +152 -152
  132. package/src/oauth-session.ts +183 -183
  133. package/src/oauth-sources.ts +1104 -1104
  134. package/src/oauth.ts +620 -620
  135. package/src/provider.ts +128 -128
  136. package/src/proxy.ts +11 -99
  137. package/src/redact.ts +72 -72
  138. package/src/session.ts +218 -218
  139. package/src/store.ts +217 -217
  140. package/src/web-origin.ts +296 -60
  141. package/src/web-routes.ts +38 -75
@@ -1,461 +1,463 @@
1
- /**
2
- * Same-origin GET routes for generated Imagine images and video artifacts.
3
- * The Host webServer only accepts exact paths, so this registrar keeps a
4
- * bounded table of opaque ids and registers one exact disposer per remembered
5
- * image ref or media artifact.
6
- * @module dsh-coding-subscription-oauth/imagine-routes
7
- */
8
-
9
- import type { IncomingMessage, ServerResponse } from "node:http";
10
- import type { ImageAttachmentRef } from "@deepseek-ai/dsh-attachment";
11
- import {
12
- DEFAULT_IMAGE_DOWNLOAD_MAX_BYTES,
13
- type ImagineImageAttachmentRef,
14
- type ImagineImageMediaType,
15
- imagineImageDownloadHeaders,
16
- imagineImagePath,
17
- isSafeImagineAttachmentId,
18
- parseImagineImagePath,
19
- } from "./grok-imagine.ts";
20
- import {
21
- createTrustedImagineAuthz,
22
- imagineMediaPath,
23
- isSafeMediaArtifactId,
24
- MEDIA_STORE_MAX_BYTES,
25
- type MediaArtifactMeta,
26
- type MediaDownloadView,
27
- MediaStoreError,
28
- type MediaStoreVideoType,
29
- mediaDownloadHeaders,
30
- parseImagineMediaPath,
31
- type TrustedImagineAuthz,
32
- } from "./media-store.ts";
33
- import { isTrustedLoopbackWebRequest } from "./web-origin.ts";
34
-
35
- /** Hard ceiling for live exact download routes. Callers cannot raise this. */
36
- export const IMAGINE_ROUTE_MAX_ENTRIES = 64;
37
-
38
- /** Hard ceiling for remembered image routes. Callers cannot raise this. */
39
- export const IMAGINE_IMAGE_ROUTE_TTL_MS = 60 * 60 * 1000;
40
-
41
- const IMAGE_MEDIA_TYPES = new Set<string>(["image/png", "image/jpeg", "image/webp", "image/gif"]);
42
- const VIDEO_MEDIA_TYPES = new Set<string>(["video/mp4", "video/webm"]);
43
-
44
- /** Structural `ctx.webServer` + optional `ctx.effect` surface used by the registrar. */
45
- export interface ImagineRouteContext {
46
- readonly webServer: {
47
- register(route: {
48
- kind: "exact";
49
- path: string;
50
- handler: (req: IncomingMessage, res: ServerResponse) => void | Promise<void>;
51
- }): () => void;
52
- };
53
- effect?(setup: () => () => void | Promise<void>, label?: string): unknown;
54
- }
55
-
56
- /** Attachment seam used at GET time. Only metadata is retained in the registry. */
57
- export interface ImagineRouteAttachmentStore {
58
- readonly imageLimits?: { readonly maxImageBytes?: number };
59
- readImage(
60
- ref: ImagineImageAttachmentRef,
61
- signal?: AbortSignal,
62
- ): Promise<{ ref: ImagineImageAttachmentRef; data: Uint8Array }>;
63
- }
64
-
65
- /** Structural media download seam. Production adapts `MediaStore.openDownload`. */
66
- export interface ImagineMediaDownloadStore {
67
- readForDownload(artifactId: string, authz: TrustedImagineAuthz): Promise<MediaDownloadView>;
68
- }
69
-
70
- export interface ImagineRouteOptions {
71
- readonly attachments: ImagineRouteAttachmentStore;
72
- readonly media: ImagineMediaDownloadStore;
73
- readonly now?: () => number;
74
- /** Capped at {@link IMAGINE_ROUTE_MAX_ENTRIES}. */
75
- readonly maxEntries?: number;
76
- /** Capped at {@link IMAGINE_IMAGE_ROUTE_TTL_MS}. */
77
- readonly imageTtlMs?: number;
78
- }
79
-
80
- export interface ImagineRouteRegistry {
81
- rememberImages(refs: readonly ImageAttachmentRef[] | readonly ImagineImageAttachmentRef[]): void;
82
- rememberArtifact(meta: MediaArtifactMeta): void;
83
- revokeImages(): void;
84
- revokeArtifacts(): void;
85
- dispose(): void;
86
- }
87
-
88
- interface ImageRouteEntry {
89
- readonly kind: "image";
90
- readonly id: string;
91
- readonly path: string;
92
- readonly routeToken: symbol;
93
- ref: ImagineImageAttachmentRef;
94
- expiresAt: number;
95
- readonly disposeRoute: () => void;
96
- }
97
-
98
- interface MediaRouteEntry {
99
- readonly kind: "media";
100
- readonly id: string;
101
- readonly path: string;
102
- readonly routeToken: symbol;
103
- meta: MediaArtifactMeta;
104
- expiresAt: number;
105
- readonly disposeRoute: () => void;
106
- }
107
-
108
- type RouteEntry = ImageRouteEntry | MediaRouteEntry;
109
-
110
- type RouteHandler = (req: IncomingMessage, res: ServerResponse) => void | Promise<void>;
111
-
112
- /** Register the bounded exact-path Imagine download registry. */
113
- export function registerImagineRoutes(ctx: ImagineRouteContext, options: ImagineRouteOptions): ImagineRouteRegistry {
114
- const now = options.now ?? Date.now;
115
- const maxEntries = clampPositive(options.maxEntries, IMAGINE_ROUTE_MAX_ENTRIES);
116
- const imageTtlMs = clampPositive(options.imageTtlMs, IMAGINE_IMAGE_ROUTE_TTL_MS);
117
- const entries = new Map<string, RouteEntry>();
118
- let disposed = false;
119
-
120
- const wrapDisposer = (release: () => void): (() => void) => {
121
- let released = false;
122
- return () => {
123
- if (released) return;
124
- released = true;
125
- try {
126
- release();
127
- } catch {
128
- // One route disposer must not strand the rest of the table.
129
- }
130
- };
131
- };
132
-
133
- const evict = (key: string): void => {
134
- const entry = entries.get(key);
135
- if (entry === undefined) return;
136
- entries.delete(key);
137
- entry.disposeRoute();
138
- };
139
-
140
- const evictExpired = (at: number): void => {
141
- for (const [key, entry] of [...entries]) {
142
- if (entry.expiresAt <= at) evict(key);
143
- }
144
- };
145
-
146
- const evictOldest = (): void => {
147
- const oldest = entries.keys().next().value;
148
- if (oldest !== undefined) evict(oldest);
149
- };
150
-
151
- const lookupKey = (kind: RouteEntry["kind"], id: string): string => `${kind}:${id}`;
152
-
153
- const registerExact = (path: string, handler: RouteHandler): (() => void) =>
154
- wrapDisposer(
155
- ctx.webServer.register({
156
- kind: "exact",
157
- path,
158
- handler,
159
- }),
160
- );
161
-
162
- const isCurrent = (kind: RouteEntry["kind"], id: string, routeToken: symbol): boolean => {
163
- if (disposed) return false;
164
- const entry = entries.get(lookupKey(kind, id));
165
- return entry !== undefined && entry.kind === kind && entry.routeToken === routeToken && entry.expiresAt > now();
166
- };
167
-
168
- const handleGet = async (
169
- kind: RouteEntry["kind"],
170
- id: string,
171
- routeToken: symbol,
172
- req: IncomingMessage,
173
- res: ServerResponse,
174
- ): Promise<void> => {
175
- if ((req.method ?? "") !== "GET") {
176
- json(res, 405, { error: "method not allowed" });
177
- return;
178
- }
179
- if (!isTrustedLoopbackWebRequest(req)) {
180
- json(res, 403, { error: "forbidden" });
181
- return;
182
- }
183
- if (!isCurrent(kind, id, routeToken)) {
184
- const key = lookupKey(kind, id);
185
- const current = entries.get(key);
186
- if (current?.routeToken === routeToken && current.expiresAt <= now()) evict(key);
187
- json(res, 404, { error: "not found" });
188
- return;
189
- }
190
- const key = lookupKey(kind, id);
191
- const entry = entries.get(key);
192
- if (entry === undefined || entry.kind !== kind) {
193
- json(res, 404, { error: "not found" });
194
- return;
195
- }
196
- try {
197
- if (entry.kind === "image") {
198
- await serveImage(options.attachments, entry, req, res, () => isCurrent(kind, id, routeToken));
199
- } else {
200
- await serveMedia(options.media, entry, res, () => isCurrent(kind, id, routeToken));
201
- }
202
- } catch (error: unknown) {
203
- if (res.headersSent) return;
204
- if (!isCurrent(kind, id, routeToken)) {
205
- json(res, 404, { error: "not found" });
206
- return;
207
- }
208
- json(res, statusFor(error), { error: publicErrorMessage(error) });
209
- }
210
- };
211
-
212
- const rememberImage = (input: ImageAttachmentRef | ImagineImageAttachmentRef): void => {
213
- if (disposed) return;
214
- const at = now();
215
- evictExpired(at);
216
- const ref = cloneImageRef(input);
217
- if (ref === undefined) return;
218
- if (ref.bytes > maxImageBytes(options.attachments)) return;
219
- let path: string;
220
- try {
221
- path = imagineImagePath(ref.attachmentId);
222
- } catch {
223
- return;
224
- }
225
- if (parseImagineImagePath(path) !== ref.attachmentId) return;
226
- const key = lookupKey("image", ref.attachmentId);
227
- const existing = entries.get(key);
228
- if (existing?.kind === "image") {
229
- entries.delete(key);
230
- existing.ref = ref;
231
- existing.expiresAt = at + imageTtlMs;
232
- entries.set(key, existing);
233
- return;
234
- }
235
- while (entries.size >= maxEntries) evictOldest();
236
- const routeToken = Symbol(ref.attachmentId);
237
- const release = registerExact(path, (req, res) => handleGet("image", ref.attachmentId, routeToken, req, res));
238
- entries.set(key, {
239
- kind: "image",
240
- id: ref.attachmentId,
241
- path,
242
- routeToken,
243
- ref,
244
- expiresAt: at + imageTtlMs,
245
- disposeRoute: release,
246
- });
247
- };
248
-
249
- const rememberArtifact = (input: MediaArtifactMeta): void => {
250
- if (disposed) return;
251
- const at = now();
252
- evictExpired(at);
253
- const meta = cloneArtifactMeta(input);
254
- if (meta === undefined || meta.expiresAt <= at) return;
255
- let path: string;
256
- try {
257
- path = imagineMediaPath(meta.artifactId);
258
- } catch {
259
- return;
260
- }
261
- if (parseImagineMediaPath(path) !== meta.artifactId) return;
262
- const key = lookupKey("media", meta.artifactId);
263
- const existing = entries.get(key);
264
- if (existing?.kind === "media") {
265
- entries.delete(key);
266
- existing.meta = meta;
267
- existing.expiresAt = meta.expiresAt;
268
- entries.set(key, existing);
269
- return;
270
- }
271
- while (entries.size >= maxEntries) evictOldest();
272
- const routeToken = Symbol(meta.artifactId);
273
- const release = registerExact(path, (req, res) => handleGet("media", meta.artifactId, routeToken, req, res));
274
- entries.set(key, {
275
- kind: "media",
276
- id: meta.artifactId,
277
- path,
278
- routeToken,
279
- meta,
280
- expiresAt: meta.expiresAt,
281
- disposeRoute: release,
282
- });
283
- };
284
-
285
- const dispose = (): void => {
286
- if (disposed) return;
287
- disposed = true;
288
- for (const key of [...entries.keys()]) evict(key);
289
- };
290
-
291
- if (typeof ctx.effect === "function") {
292
- ctx.effect(() => dispose, "dsh-coding-subscription-oauth: imagine download routes");
293
- }
294
-
295
- return {
296
- rememberImages(refs) {
297
- for (const ref of refs) rememberImage(ref);
298
- },
299
- rememberArtifact,
300
- revokeImages() {
301
- for (const [key, entry] of [...entries]) {
302
- if (entry.kind === "image") evict(key);
303
- }
304
- },
305
- revokeArtifacts() {
306
- for (const [key, entry] of [...entries]) {
307
- if (entry.kind === "media") evict(key);
308
- }
309
- },
310
- dispose,
311
- };
312
- }
313
-
314
- async function serveImage(
315
- attachments: ImagineRouteAttachmentStore,
316
- entry: ImageRouteEntry,
317
- req: IncomingMessage,
318
- res: ServerResponse,
319
- alive: () => boolean,
320
- ): Promise<void> {
321
- const limit = maxImageBytes(attachments);
322
- if (entry.ref.bytes > limit) {
323
- json(res, 404, { error: "not found" });
324
- return;
325
- }
326
- const stored = await attachments.readImage(cloneImageRef(entry.ref) ?? entry.ref, requestSignal(req));
327
- if (res.headersSent) return;
328
- if (!alive()) {
329
- json(res, 404, { error: "not found" });
330
- return;
331
- }
332
- if (!sameImageIdentity(entry.ref, stored.ref) || stored.data.byteLength > limit) {
333
- json(res, 404, { error: "not found" });
334
- return;
335
- }
336
- const headers = imagineImageDownloadHeaders({
337
- ...stored.ref,
338
- bytes: stored.data.byteLength,
339
- });
340
- res.writeHead(200, {
341
- "Content-Type": headers["Content-Type"],
342
- "Content-Length": String(stored.data.byteLength),
343
- "Cache-Control": headers["Cache-Control"],
344
- "X-Content-Type-Options": headers["X-Content-Type-Options"],
345
- });
346
- res.end(Buffer.from(stored.data));
347
- }
348
-
349
- async function serveMedia(
350
- media: ImagineMediaDownloadStore,
351
- entry: MediaRouteEntry,
352
- res: ServerResponse,
353
- alive: () => boolean,
354
- ): Promise<void> {
355
- const authz = createTrustedImagineAuthz({ authorized: true });
356
- const view = await media.readForDownload(entry.id, authz);
357
- if (res.headersSent) return;
358
- if (!alive()) {
359
- json(res, 404, { error: "not found" });
360
- return;
361
- }
362
- if (
363
- view.meta.artifactId !== entry.id ||
364
- view.meta.mediaType !== entry.meta.mediaType ||
365
- view.meta.bytes !== view.body.byteLength ||
366
- view.body.byteLength > MEDIA_STORE_MAX_BYTES
367
- ) {
368
- json(res, 404, { error: "not found" });
369
- return;
370
- }
371
- const headers = mediaDownloadHeaders({ ...entry.meta, bytes: view.body.byteLength });
372
- res.writeHead(200, {
373
- "Content-Type": headers["Content-Type"],
374
- "Content-Length": headers["Content-Length"],
375
- "Content-Disposition": headers["Content-Disposition"],
376
- "Cache-Control": headers["Cache-Control"],
377
- "X-Content-Type-Options": headers["X-Content-Type-Options"],
378
- });
379
- res.end(Buffer.from(view.body));
380
- }
381
-
382
- function requestSignal(req: IncomingMessage): AbortSignal | undefined {
383
- const candidate = req as IncomingMessage & { signal?: unknown };
384
- return candidate.signal instanceof AbortSignal ? candidate.signal : undefined;
385
- }
386
-
387
- function maxImageBytes(attachments: ImagineRouteAttachmentStore): number {
388
- const configured = attachments.imageLimits?.maxImageBytes;
389
- if (typeof configured !== "number" || !Number.isFinite(configured) || configured <= 0) {
390
- return DEFAULT_IMAGE_DOWNLOAD_MAX_BYTES;
391
- }
392
- return Math.min(Math.floor(configured), DEFAULT_IMAGE_DOWNLOAD_MAX_BYTES);
393
- }
394
-
395
- function cloneImageRef(input: ImageAttachmentRef | ImagineImageAttachmentRef): ImagineImageAttachmentRef | undefined {
396
- if (typeof input.attachmentId !== "string" || !isSafeImagineAttachmentId(input.attachmentId)) return undefined;
397
- if (!IMAGE_MEDIA_TYPES.has(input.mediaType)) return undefined;
398
- if (!Number.isFinite(input.bytes) || input.bytes < 0) return undefined;
399
- if (!Number.isFinite(input.width) || !Number.isFinite(input.height)) return undefined;
400
- const cloned: ImagineImageAttachmentRef = {
401
- attachmentId: input.attachmentId,
402
- mediaType: input.mediaType as ImagineImageMediaType,
403
- bytes: Math.trunc(input.bytes),
404
- width: Math.trunc(input.width),
405
- height: Math.trunc(input.height),
406
- };
407
- if (typeof input.name === "string") cloned.name = input.name;
408
- return cloned;
409
- }
410
-
411
- function cloneArtifactMeta(input: MediaArtifactMeta): MediaArtifactMeta | undefined {
412
- if (typeof input.artifactId !== "string" || !isSafeMediaArtifactId(input.artifactId)) return undefined;
413
- if (!VIDEO_MEDIA_TYPES.has(input.mediaType)) return undefined;
414
- if (!Number.isFinite(input.bytes) || input.bytes <= 0) return undefined;
415
- if (!Number.isFinite(input.createdAt) || input.createdAt <= 0) return undefined;
416
- if (!Number.isFinite(input.expiresAt) || input.expiresAt <= input.createdAt) return undefined;
417
- const cloned: MediaArtifactMeta = {
418
- artifactId: input.artifactId,
419
- mediaType: input.mediaType as MediaStoreVideoType,
420
- bytes: Math.trunc(input.bytes),
421
- createdAt: input.createdAt,
422
- expiresAt: input.expiresAt,
423
- };
424
- if (typeof input.name === "string") cloned.name = input.name;
425
- return cloned;
426
- }
427
-
428
- function sameImageIdentity(expected: ImagineImageAttachmentRef, actual: ImagineImageAttachmentRef): boolean {
429
- return actual.attachmentId === expected.attachmentId && IMAGE_MEDIA_TYPES.has(actual.mediaType);
430
- }
431
-
432
- function statusFor(error: unknown): number {
433
- if (error instanceof MediaStoreError) {
434
- if (error.code === "NOT_FOUND" || error.code === "EXPIRED" || error.code === "INVALID_ID") return 404;
435
- if (error.code === "FORBIDDEN") return 403;
436
- }
437
- return 500;
438
- }
439
-
440
- function publicErrorMessage(error: unknown): string {
441
- if (error instanceof MediaStoreError) {
442
- if (error.code === "NOT_FOUND" || error.code === "EXPIRED" || error.code === "INVALID_ID") return "not found";
443
- if (error.code === "FORBIDDEN") return "forbidden";
444
- }
445
- return "download failed";
446
- }
447
-
448
- function clampPositive(value: number | undefined, ceiling: number): number {
449
- if (typeof value !== "number" || !Number.isFinite(value) || value <= 0) return ceiling;
450
- return Math.min(Math.floor(value), ceiling);
451
- }
452
-
453
- function json(res: ServerResponse, status: number, value: unknown): void {
454
- if (res.headersSent) return;
455
- res.writeHead(status, {
456
- "content-type": "application/json; charset=utf-8",
457
- "cache-control": "no-store",
458
- "x-content-type-options": "nosniff",
459
- });
460
- res.end(JSON.stringify(value));
461
- }
1
+ /**
2
+ * Same-origin GET routes for generated Imagine images and video artifacts.
3
+ * The Host webServer only accepts exact paths, so this registrar keeps a
4
+ * bounded table of opaque ids and registers one exact disposer per remembered
5
+ * image ref or media artifact.
6
+ * @module dsh-coding-subscription-oauth/imagine-routes
7
+ */
8
+
9
+ import type { IncomingMessage, ServerResponse } from "node:http";
10
+ import type { ImageAttachmentRef } from "@deepseek-ai/dsh-attachment";
11
+ import {
12
+ DEFAULT_IMAGE_DOWNLOAD_MAX_BYTES,
13
+ type ImagineImageAttachmentRef,
14
+ type ImagineImageMediaType,
15
+ imagineImageDownloadHeaders,
16
+ imagineImagePath,
17
+ isSafeImagineAttachmentId,
18
+ parseImagineImagePath,
19
+ } from "./grok-imagine.ts";
20
+ import {
21
+ createTrustedImagineAuthz,
22
+ imagineMediaPath,
23
+ isSafeMediaArtifactId,
24
+ MEDIA_STORE_MAX_BYTES,
25
+ type MediaArtifactMeta,
26
+ type MediaDownloadView,
27
+ MediaStoreError,
28
+ type MediaStoreVideoType,
29
+ mediaDownloadHeaders,
30
+ parseImagineMediaPath,
31
+ type TrustedImagineAuthz,
32
+ } from "./media-store.ts";
33
+ import { LOOPBACK_OWNER_REQUEST_POLICY, type OwnerRequestPolicy } from "./web-origin.ts";
34
+
35
+ /** Hard ceiling for live exact download routes. Callers cannot raise this. */
36
+ export const IMAGINE_ROUTE_MAX_ENTRIES = 64;
37
+
38
+ /** Hard ceiling for remembered image routes. Callers cannot raise this. */
39
+ export const IMAGINE_IMAGE_ROUTE_TTL_MS = 60 * 60 * 1000;
40
+
41
+ const IMAGE_MEDIA_TYPES = new Set<string>(["image/png", "image/jpeg", "image/webp", "image/gif"]);
42
+ const VIDEO_MEDIA_TYPES = new Set<string>(["video/mp4", "video/webm"]);
43
+
44
+ /** Structural `ctx.webServer` + optional `ctx.effect` surface used by the registrar. */
45
+ export interface ImagineRouteContext {
46
+ readonly webServer: {
47
+ register(route: {
48
+ kind: "exact";
49
+ path: string;
50
+ handler: (req: IncomingMessage, res: ServerResponse) => void | Promise<void>;
51
+ }): () => void;
52
+ };
53
+ effect?(setup: () => () => void | Promise<void>, label?: string): unknown;
54
+ }
55
+
56
+ /** Attachment seam used at GET time. Only metadata is retained in the registry. */
57
+ export interface ImagineRouteAttachmentStore {
58
+ readonly imageLimits?: { readonly maxImageBytes?: number };
59
+ readImage(
60
+ ref: ImagineImageAttachmentRef,
61
+ signal?: AbortSignal,
62
+ ): Promise<{ ref: ImagineImageAttachmentRef; data: Uint8Array }>;
63
+ }
64
+
65
+ /** Structural media download seam. Production adapts `MediaStore.openDownload`. */
66
+ export interface ImagineMediaDownloadStore {
67
+ readForDownload(artifactId: string, authz: TrustedImagineAuthz): Promise<MediaDownloadView>;
68
+ }
69
+
70
+ export interface ImagineRouteOptions {
71
+ readonly attachments: ImagineRouteAttachmentStore;
72
+ readonly media: ImagineMediaDownloadStore;
73
+ readonly now?: () => number;
74
+ /** Capped at {@link IMAGINE_ROUTE_MAX_ENTRIES}. */
75
+ readonly maxEntries?: number;
76
+ /** Capped at {@link IMAGINE_IMAGE_ROUTE_TTL_MS}. */
77
+ readonly imageTtlMs?: number;
78
+ readonly ownerRequestPolicy?: OwnerRequestPolicy;
79
+ }
80
+
81
+ export interface ImagineRouteRegistry {
82
+ rememberImages(refs: readonly ImageAttachmentRef[] | readonly ImagineImageAttachmentRef[]): void;
83
+ rememberArtifact(meta: MediaArtifactMeta): void;
84
+ revokeImages(): void;
85
+ revokeArtifacts(): void;
86
+ dispose(): void;
87
+ }
88
+
89
+ interface ImageRouteEntry {
90
+ readonly kind: "image";
91
+ readonly id: string;
92
+ readonly path: string;
93
+ readonly routeToken: symbol;
94
+ ref: ImagineImageAttachmentRef;
95
+ expiresAt: number;
96
+ readonly disposeRoute: () => void;
97
+ }
98
+
99
+ interface MediaRouteEntry {
100
+ readonly kind: "media";
101
+ readonly id: string;
102
+ readonly path: string;
103
+ readonly routeToken: symbol;
104
+ meta: MediaArtifactMeta;
105
+ expiresAt: number;
106
+ readonly disposeRoute: () => void;
107
+ }
108
+
109
+ type RouteEntry = ImageRouteEntry | MediaRouteEntry;
110
+
111
+ type RouteHandler = (req: IncomingMessage, res: ServerResponse) => void | Promise<void>;
112
+
113
+ /** Register the bounded exact-path Imagine download registry. */
114
+ export function registerImagineRoutes(ctx: ImagineRouteContext, options: ImagineRouteOptions): ImagineRouteRegistry {
115
+ const now = options.now ?? Date.now;
116
+ const maxEntries = clampPositive(options.maxEntries, IMAGINE_ROUTE_MAX_ENTRIES);
117
+ const imageTtlMs = clampPositive(options.imageTtlMs, IMAGINE_IMAGE_ROUTE_TTL_MS);
118
+ const ownerRequestPolicy = options.ownerRequestPolicy ?? LOOPBACK_OWNER_REQUEST_POLICY;
119
+ const entries = new Map<string, RouteEntry>();
120
+ let disposed = false;
121
+
122
+ const wrapDisposer = (release: () => void): (() => void) => {
123
+ let released = false;
124
+ return () => {
125
+ if (released) return;
126
+ released = true;
127
+ try {
128
+ release();
129
+ } catch {
130
+ // One route disposer must not strand the rest of the table.
131
+ }
132
+ };
133
+ };
134
+
135
+ const evict = (key: string): void => {
136
+ const entry = entries.get(key);
137
+ if (entry === undefined) return;
138
+ entries.delete(key);
139
+ entry.disposeRoute();
140
+ };
141
+
142
+ const evictExpired = (at: number): void => {
143
+ for (const [key, entry] of [...entries]) {
144
+ if (entry.expiresAt <= at) evict(key);
145
+ }
146
+ };
147
+
148
+ const evictOldest = (): void => {
149
+ const oldest = entries.keys().next().value;
150
+ if (oldest !== undefined) evict(oldest);
151
+ };
152
+
153
+ const lookupKey = (kind: RouteEntry["kind"], id: string): string => `${kind}:${id}`;
154
+
155
+ const registerExact = (path: string, handler: RouteHandler): (() => void) =>
156
+ wrapDisposer(
157
+ ctx.webServer.register({
158
+ kind: "exact",
159
+ path,
160
+ handler,
161
+ }),
162
+ );
163
+
164
+ const isCurrent = (kind: RouteEntry["kind"], id: string, routeToken: symbol): boolean => {
165
+ if (disposed) return false;
166
+ const entry = entries.get(lookupKey(kind, id));
167
+ return entry !== undefined && entry.kind === kind && entry.routeToken === routeToken && entry.expiresAt > now();
168
+ };
169
+
170
+ const handleGet = async (
171
+ kind: RouteEntry["kind"],
172
+ id: string,
173
+ routeToken: symbol,
174
+ req: IncomingMessage,
175
+ res: ServerResponse,
176
+ ): Promise<void> => {
177
+ if ((req.method ?? "") !== "GET") {
178
+ json(res, 405, { error: "method not allowed" });
179
+ return;
180
+ }
181
+ if (!ownerRequestPolicy.authorize(req).authorized) {
182
+ json(res, 403, { error: "forbidden" });
183
+ return;
184
+ }
185
+ if (!isCurrent(kind, id, routeToken)) {
186
+ const key = lookupKey(kind, id);
187
+ const current = entries.get(key);
188
+ if (current?.routeToken === routeToken && current.expiresAt <= now()) evict(key);
189
+ json(res, 404, { error: "not found" });
190
+ return;
191
+ }
192
+ const key = lookupKey(kind, id);
193
+ const entry = entries.get(key);
194
+ if (entry === undefined || entry.kind !== kind) {
195
+ json(res, 404, { error: "not found" });
196
+ return;
197
+ }
198
+ try {
199
+ if (entry.kind === "image") {
200
+ await serveImage(options.attachments, entry, req, res, () => isCurrent(kind, id, routeToken));
201
+ } else {
202
+ await serveMedia(options.media, entry, res, () => isCurrent(kind, id, routeToken));
203
+ }
204
+ } catch (error: unknown) {
205
+ if (res.headersSent) return;
206
+ if (!isCurrent(kind, id, routeToken)) {
207
+ json(res, 404, { error: "not found" });
208
+ return;
209
+ }
210
+ json(res, statusFor(error), { error: publicErrorMessage(error) });
211
+ }
212
+ };
213
+
214
+ const rememberImage = (input: ImageAttachmentRef | ImagineImageAttachmentRef): void => {
215
+ if (disposed) return;
216
+ const at = now();
217
+ evictExpired(at);
218
+ const ref = cloneImageRef(input);
219
+ if (ref === undefined) return;
220
+ if (ref.bytes > maxImageBytes(options.attachments)) return;
221
+ let path: string;
222
+ try {
223
+ path = imagineImagePath(ref.attachmentId);
224
+ } catch {
225
+ return;
226
+ }
227
+ if (parseImagineImagePath(path) !== ref.attachmentId) return;
228
+ const key = lookupKey("image", ref.attachmentId);
229
+ const existing = entries.get(key);
230
+ if (existing?.kind === "image") {
231
+ entries.delete(key);
232
+ existing.ref = ref;
233
+ existing.expiresAt = at + imageTtlMs;
234
+ entries.set(key, existing);
235
+ return;
236
+ }
237
+ while (entries.size >= maxEntries) evictOldest();
238
+ const routeToken = Symbol(ref.attachmentId);
239
+ const release = registerExact(path, (req, res) => handleGet("image", ref.attachmentId, routeToken, req, res));
240
+ entries.set(key, {
241
+ kind: "image",
242
+ id: ref.attachmentId,
243
+ path,
244
+ routeToken,
245
+ ref,
246
+ expiresAt: at + imageTtlMs,
247
+ disposeRoute: release,
248
+ });
249
+ };
250
+
251
+ const rememberArtifact = (input: MediaArtifactMeta): void => {
252
+ if (disposed) return;
253
+ const at = now();
254
+ evictExpired(at);
255
+ const meta = cloneArtifactMeta(input);
256
+ if (meta === undefined || meta.expiresAt <= at) return;
257
+ let path: string;
258
+ try {
259
+ path = imagineMediaPath(meta.artifactId);
260
+ } catch {
261
+ return;
262
+ }
263
+ if (parseImagineMediaPath(path) !== meta.artifactId) return;
264
+ const key = lookupKey("media", meta.artifactId);
265
+ const existing = entries.get(key);
266
+ if (existing?.kind === "media") {
267
+ entries.delete(key);
268
+ existing.meta = meta;
269
+ existing.expiresAt = meta.expiresAt;
270
+ entries.set(key, existing);
271
+ return;
272
+ }
273
+ while (entries.size >= maxEntries) evictOldest();
274
+ const routeToken = Symbol(meta.artifactId);
275
+ const release = registerExact(path, (req, res) => handleGet("media", meta.artifactId, routeToken, req, res));
276
+ entries.set(key, {
277
+ kind: "media",
278
+ id: meta.artifactId,
279
+ path,
280
+ routeToken,
281
+ meta,
282
+ expiresAt: meta.expiresAt,
283
+ disposeRoute: release,
284
+ });
285
+ };
286
+
287
+ const dispose = (): void => {
288
+ if (disposed) return;
289
+ disposed = true;
290
+ for (const key of [...entries.keys()]) evict(key);
291
+ };
292
+
293
+ if (typeof ctx.effect === "function") {
294
+ ctx.effect(() => dispose, "dsh-coding-subscription-oauth: imagine download routes");
295
+ }
296
+
297
+ return {
298
+ rememberImages(refs) {
299
+ for (const ref of refs) rememberImage(ref);
300
+ },
301
+ rememberArtifact,
302
+ revokeImages() {
303
+ for (const [key, entry] of [...entries]) {
304
+ if (entry.kind === "image") evict(key);
305
+ }
306
+ },
307
+ revokeArtifacts() {
308
+ for (const [key, entry] of [...entries]) {
309
+ if (entry.kind === "media") evict(key);
310
+ }
311
+ },
312
+ dispose,
313
+ };
314
+ }
315
+
316
+ async function serveImage(
317
+ attachments: ImagineRouteAttachmentStore,
318
+ entry: ImageRouteEntry,
319
+ req: IncomingMessage,
320
+ res: ServerResponse,
321
+ alive: () => boolean,
322
+ ): Promise<void> {
323
+ const limit = maxImageBytes(attachments);
324
+ if (entry.ref.bytes > limit) {
325
+ json(res, 404, { error: "not found" });
326
+ return;
327
+ }
328
+ const stored = await attachments.readImage(cloneImageRef(entry.ref) ?? entry.ref, requestSignal(req));
329
+ if (res.headersSent) return;
330
+ if (!alive()) {
331
+ json(res, 404, { error: "not found" });
332
+ return;
333
+ }
334
+ if (!sameImageIdentity(entry.ref, stored.ref) || stored.data.byteLength > limit) {
335
+ json(res, 404, { error: "not found" });
336
+ return;
337
+ }
338
+ const headers = imagineImageDownloadHeaders({
339
+ ...stored.ref,
340
+ bytes: stored.data.byteLength,
341
+ });
342
+ res.writeHead(200, {
343
+ "Content-Type": headers["Content-Type"],
344
+ "Content-Length": String(stored.data.byteLength),
345
+ "Cache-Control": headers["Cache-Control"],
346
+ "X-Content-Type-Options": headers["X-Content-Type-Options"],
347
+ });
348
+ res.end(Buffer.from(stored.data));
349
+ }
350
+
351
+ async function serveMedia(
352
+ media: ImagineMediaDownloadStore,
353
+ entry: MediaRouteEntry,
354
+ res: ServerResponse,
355
+ alive: () => boolean,
356
+ ): Promise<void> {
357
+ const authz = createTrustedImagineAuthz({ authorized: true });
358
+ const view = await media.readForDownload(entry.id, authz);
359
+ if (res.headersSent) return;
360
+ if (!alive()) {
361
+ json(res, 404, { error: "not found" });
362
+ return;
363
+ }
364
+ if (
365
+ view.meta.artifactId !== entry.id ||
366
+ view.meta.mediaType !== entry.meta.mediaType ||
367
+ view.meta.bytes !== view.body.byteLength ||
368
+ view.body.byteLength > MEDIA_STORE_MAX_BYTES
369
+ ) {
370
+ json(res, 404, { error: "not found" });
371
+ return;
372
+ }
373
+ const headers = mediaDownloadHeaders({ ...entry.meta, bytes: view.body.byteLength });
374
+ res.writeHead(200, {
375
+ "Content-Type": headers["Content-Type"],
376
+ "Content-Length": headers["Content-Length"],
377
+ "Content-Disposition": headers["Content-Disposition"],
378
+ "Cache-Control": headers["Cache-Control"],
379
+ "X-Content-Type-Options": headers["X-Content-Type-Options"],
380
+ });
381
+ res.end(Buffer.from(view.body));
382
+ }
383
+
384
+ function requestSignal(req: IncomingMessage): AbortSignal | undefined {
385
+ const candidate = req as IncomingMessage & { signal?: unknown };
386
+ return candidate.signal instanceof AbortSignal ? candidate.signal : undefined;
387
+ }
388
+
389
+ function maxImageBytes(attachments: ImagineRouteAttachmentStore): number {
390
+ const configured = attachments.imageLimits?.maxImageBytes;
391
+ if (typeof configured !== "number" || !Number.isFinite(configured) || configured <= 0) {
392
+ return DEFAULT_IMAGE_DOWNLOAD_MAX_BYTES;
393
+ }
394
+ return Math.min(Math.floor(configured), DEFAULT_IMAGE_DOWNLOAD_MAX_BYTES);
395
+ }
396
+
397
+ function cloneImageRef(input: ImageAttachmentRef | ImagineImageAttachmentRef): ImagineImageAttachmentRef | undefined {
398
+ if (typeof input.attachmentId !== "string" || !isSafeImagineAttachmentId(input.attachmentId)) return undefined;
399
+ if (!IMAGE_MEDIA_TYPES.has(input.mediaType)) return undefined;
400
+ if (!Number.isFinite(input.bytes) || input.bytes < 0) return undefined;
401
+ if (!Number.isFinite(input.width) || !Number.isFinite(input.height)) return undefined;
402
+ const cloned: ImagineImageAttachmentRef = {
403
+ attachmentId: input.attachmentId,
404
+ mediaType: input.mediaType as ImagineImageMediaType,
405
+ bytes: Math.trunc(input.bytes),
406
+ width: Math.trunc(input.width),
407
+ height: Math.trunc(input.height),
408
+ };
409
+ if (typeof input.name === "string") cloned.name = input.name;
410
+ return cloned;
411
+ }
412
+
413
+ function cloneArtifactMeta(input: MediaArtifactMeta): MediaArtifactMeta | undefined {
414
+ if (typeof input.artifactId !== "string" || !isSafeMediaArtifactId(input.artifactId)) return undefined;
415
+ if (!VIDEO_MEDIA_TYPES.has(input.mediaType)) return undefined;
416
+ if (!Number.isFinite(input.bytes) || input.bytes <= 0) return undefined;
417
+ if (!Number.isFinite(input.createdAt) || input.createdAt <= 0) return undefined;
418
+ if (!Number.isFinite(input.expiresAt) || input.expiresAt <= input.createdAt) return undefined;
419
+ const cloned: MediaArtifactMeta = {
420
+ artifactId: input.artifactId,
421
+ mediaType: input.mediaType as MediaStoreVideoType,
422
+ bytes: Math.trunc(input.bytes),
423
+ createdAt: input.createdAt,
424
+ expiresAt: input.expiresAt,
425
+ };
426
+ if (typeof input.name === "string") cloned.name = input.name;
427
+ return cloned;
428
+ }
429
+
430
+ function sameImageIdentity(expected: ImagineImageAttachmentRef, actual: ImagineImageAttachmentRef): boolean {
431
+ return actual.attachmentId === expected.attachmentId && IMAGE_MEDIA_TYPES.has(actual.mediaType);
432
+ }
433
+
434
+ function statusFor(error: unknown): number {
435
+ if (error instanceof MediaStoreError) {
436
+ if (error.code === "NOT_FOUND" || error.code === "EXPIRED" || error.code === "INVALID_ID") return 404;
437
+ if (error.code === "FORBIDDEN") return 403;
438
+ }
439
+ return 500;
440
+ }
441
+
442
+ function publicErrorMessage(error: unknown): string {
443
+ if (error instanceof MediaStoreError) {
444
+ if (error.code === "NOT_FOUND" || error.code === "EXPIRED" || error.code === "INVALID_ID") return "not found";
445
+ if (error.code === "FORBIDDEN") return "forbidden";
446
+ }
447
+ return "download failed";
448
+ }
449
+
450
+ function clampPositive(value: number | undefined, ceiling: number): number {
451
+ if (typeof value !== "number" || !Number.isFinite(value) || value <= 0) return ceiling;
452
+ return Math.min(Math.floor(value), ceiling);
453
+ }
454
+
455
+ function json(res: ServerResponse, status: number, value: unknown): void {
456
+ if (res.headersSent) return;
457
+ res.writeHead(status, {
458
+ "content-type": "application/json; charset=utf-8",
459
+ "cache-control": "no-store",
460
+ "x-content-type-options": "nosniff",
461
+ });
462
+ res.end(JSON.stringify(value));
463
+ }