dsh-coding-subscription-oauth 0.6.3 → 0.6.4

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 (116) hide show
  1. package/CHANGELOG.md +258 -250
  2. package/CONTRIBUTING.md +129 -129
  3. package/INSTALL.md +256 -255
  4. package/LICENSE +19 -19
  5. package/NOTICE +11 -11
  6. package/README.de.md +303 -303
  7. package/README.es.md +304 -304
  8. package/README.fr.md +304 -304
  9. package/README.ja.md +304 -304
  10. package/README.ko.md +304 -304
  11. package/README.md +320 -320
  12. package/README.pt-BR.md +304 -304
  13. package/README.ru.md +304 -304
  14. package/README.zh-CN.md +318 -318
  15. package/compatibility/dsh-bom.json +30 -30
  16. package/cordis.patch.yml +13 -13
  17. package/docs/00-project-rules.md +212 -212
  18. package/docs/02-architecture.md +138 -138
  19. package/docs/02-architecture.zh-CN.md +138 -138
  20. package/lib/bin.js +1333 -569
  21. package/lib/bin.js.map +4 -4
  22. package/lib/client.js +1 -1
  23. package/lib/client.js.map +2 -2
  24. package/lib/index.js +689 -25492
  25. package/lib/index.js.map +4 -4
  26. package/lib/invariant.js.map +1 -1
  27. package/media/en/settings_accounts.png +0 -0
  28. package/media/en/settings_capabilities.png +0 -0
  29. package/media/en/settings_gateway.png +0 -0
  30. package/media/settings_accounts.png +0 -0
  31. package/media/settings_capabilities.png +0 -0
  32. package/media/settings_gateway.png +0 -0
  33. package/media/settings_overview.png +0 -0
  34. package/media/zh-CN/settings_accounts.png +0 -0
  35. package/media/zh-CN/settings_capabilities.png +0 -0
  36. package/media/zh-CN/settings_gateway.png +0 -0
  37. package/package.json +223 -223
  38. package/patches/dsh-agy@0.1.2.patch +25 -25
  39. package/scripts/release.mjs +186 -186
  40. package/scripts/smoke-deployed-routes.mjs +146 -146
  41. package/scripts/verify-deployed-catalog.mjs +87 -87
  42. package/src/adapter.ts +348 -348
  43. package/src/alias-adapter.ts +147 -147
  44. package/src/auth-routes.ts +921 -921
  45. package/src/auth.ts +67 -67
  46. package/src/bin.ts +350 -350
  47. package/src/capability-routes.ts +279 -279
  48. package/src/capability-runtime.ts +314 -314
  49. package/src/capability-settings.ts +671 -671
  50. package/src/capability-tools.ts +685 -685
  51. package/src/catalog.ts +271 -271
  52. package/src/client/GrokBuildSettings.tsx +771 -771
  53. package/src/client/api.ts +88 -88
  54. package/src/client/components/AboutTab.tsx +30 -30
  55. package/src/client/components/AccountsTab.tsx +241 -241
  56. package/src/client/components/Badge.tsx +33 -33
  57. package/src/client/components/CapabilitiesTab.tsx +265 -265
  58. package/src/client/components/CliPullPreview.tsx +116 -116
  59. package/src/client/components/CopyButton.tsx +57 -57
  60. package/src/client/components/GatewayTab.tsx +469 -469
  61. package/src/client/components/NoticeBanner.tsx +46 -46
  62. package/src/client/components/ProgressBar.tsx +53 -53
  63. package/src/client/components/ProviderCard.tsx +606 -606
  64. package/src/client/components/SettingsTabs.tsx +75 -75
  65. package/src/client/components/ToggleSwitch.tsx +71 -71
  66. package/src/client/constants.ts +230 -230
  67. package/src/client/display.ts +61 -61
  68. package/src/client/dshClientAdapter.ts +127 -127
  69. package/src/client/gatewaySnippets.ts +37 -37
  70. package/src/client/index.tsx +156 -156
  71. package/src/client/locales.ts +540 -540
  72. package/src/client/microStyles.ts +52 -52
  73. package/src/client/parsers.ts +398 -398
  74. package/src/client/styles.ts +325 -325
  75. package/src/client/types.ts +199 -199
  76. package/src/codex-http.ts +447 -447
  77. package/src/codex-images.ts +503 -503
  78. package/src/codex-model-capabilities.ts +320 -320
  79. package/src/codex-search.ts +245 -245
  80. package/src/codex-usage.ts +263 -263
  81. package/src/compatibility.ts +55 -55
  82. package/src/dsh-host-adapter.ts +173 -173
  83. package/src/gateway-anthropic-messages.ts +84 -84
  84. package/src/gateway-auth.ts +102 -102
  85. package/src/gateway-backend.ts +274 -274
  86. package/src/gateway-body.ts +49 -49
  87. package/src/gateway-config.ts +76 -76
  88. package/src/gateway-http.ts +104 -104
  89. package/src/gateway-openai-chat.ts +124 -124
  90. package/src/gateway-openai-responses.ts +53 -53
  91. package/src/gateway-parse.ts +224 -224
  92. package/src/gateway-protocol.ts +52 -52
  93. package/src/gateway-routes.ts +158 -158
  94. package/src/gateway.ts +258 -258
  95. package/src/grok-errors.ts +24 -24
  96. package/src/grok-imagine.ts +1627 -1627
  97. package/src/grok-import.ts +151 -151
  98. package/src/http-json.ts +82 -82
  99. package/src/ids.ts +59 -59
  100. package/src/imagine-routes.ts +463 -463
  101. package/src/index.ts +735 -735
  102. package/src/invariant.ts +17 -17
  103. package/src/kimi-errors.ts +26 -26
  104. package/src/media-store.ts +927 -927
  105. package/src/oauth-import-routes.ts +324 -324
  106. package/src/oauth-providers.ts +152 -152
  107. package/src/oauth-session.ts +183 -183
  108. package/src/oauth-sources.ts +1104 -1104
  109. package/src/oauth.ts +620 -620
  110. package/src/provider.ts +128 -128
  111. package/src/proxy.ts +11 -11
  112. package/src/redact.ts +72 -72
  113. package/src/session.ts +218 -218
  114. package/src/store.ts +217 -217
  115. package/src/web-origin.ts +296 -296
  116. package/src/web-routes.ts +38 -38
@@ -1,463 +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 { 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
- }
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
+ }