@narumitw/pi-codex-imagegen 0.0.0-stage → 0.0.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.
@@ -0,0 +1,480 @@
1
+ import { constants } from "node:fs";
2
+ import * as fs from "node:fs/promises";
3
+ import { dirname, isAbsolute, sep } from "node:path";
4
+ import { inflateSync } from "node:zlib";
5
+ import { createWriteTool } from "@earendil-works/pi-coding-agent";
6
+ import { getImageDimensions } from "@earendil-works/pi-tui";
7
+
8
+ export const MAX_IMAGE_BYTES = 32 * 1024 * 1024;
9
+ // Bound terminal previews: at most 16,384 pixels per side and 16 megapixels.
10
+ // PNG's largest supported raster (16-bit RGBA) is therefore at most 128 MiB.
11
+ const MAX_DIMENSION = 16_384;
12
+ const MAX_PIXELS = 16_777_216;
13
+ const MAX_BASE64_LENGTH = 4 * Math.ceil(MAX_IMAGE_BYTES / 3);
14
+
15
+ export interface DecodedImage {
16
+ bytes: Buffer;
17
+ mimeType: "image/png" | "image/jpeg" | "image/webp";
18
+ extension: "png" | "jpg" | "webp";
19
+ width: number;
20
+ height: number;
21
+ }
22
+
23
+ function invalidImage(): never {
24
+ throw new Error("Unsupported, truncated, or malformed image.");
25
+ }
26
+
27
+ function checkDimensions(width: number, height: number): void {
28
+ if (
29
+ !Number.isInteger(width) ||
30
+ !Number.isInteger(height) ||
31
+ width < 1 ||
32
+ height < 1 ||
33
+ width > MAX_DIMENSION ||
34
+ height > MAX_DIMENSION ||
35
+ width * height > MAX_PIXELS
36
+ ) {
37
+ throw new Error("Image dimensions exceed the supported limits.");
38
+ }
39
+ }
40
+
41
+ // CRC checks also detect damaged ancillary chunks without changing original bytes.
42
+ const CRC_TABLE = Array.from({ length: 256 }, (_, value) => {
43
+ for (let bit = 0; bit < 8; bit++) value = value & 1 ? 0xedb88320 ^ (value >>> 1) : value >>> 1;
44
+ return value >>> 0;
45
+ });
46
+ function crc32(bytes: Buffer): number {
47
+ let value = 0xffffffff;
48
+ for (const byte of bytes) value = (CRC_TABLE[(value ^ byte) & 255] ?? 0) ^ (value >>> 8);
49
+ return (value ^ 0xffffffff) >>> 0;
50
+ }
51
+
52
+ function validatePng(bytes: Buffer, width: number, height: number): void {
53
+ if (!bytes.subarray(0, 8).equals(Buffer.from("89504e470d0a1a0a", "hex"))) invalidImage();
54
+ let offset = 8;
55
+ let depth = 0;
56
+ let color = -1;
57
+ let interlace = 0;
58
+ let palette = false;
59
+ let endedData = false;
60
+ const data: Buffer[] = [];
61
+ while (offset + 12 <= bytes.length) {
62
+ const length = bytes.readUInt32BE(offset);
63
+ const end = offset + 12 + length;
64
+ if (end > bytes.length) invalidImage();
65
+ const type = bytes.toString("latin1", offset + 4, offset + 8);
66
+ if (!/^[A-Za-z]{4}$/.test(type) || (bytes.readUInt8(offset + 6) & 32) !== 0) invalidImage();
67
+ if (crc32(bytes.subarray(offset + 4, end - 4)) !== bytes.readUInt32BE(end - 4)) invalidImage();
68
+ const chunk = bytes.subarray(offset + 8, end - 4);
69
+ if (offset === 8 && type !== "IHDR") invalidImage();
70
+ if (type === "IHDR") {
71
+ if (offset !== 8 || length !== 13) invalidImage();
72
+ depth = chunk.readUInt8(8);
73
+ color = chunk.readUInt8(9);
74
+ interlace = chunk.readUInt8(12);
75
+ const depths: Record<number, number[]> = {
76
+ 0: [1, 2, 4, 8, 16],
77
+ 2: [8, 16],
78
+ 3: [1, 2, 4, 8],
79
+ 4: [8, 16],
80
+ 6: [8, 16],
81
+ };
82
+ if (!depths[color]?.includes(depth) || chunk[10] !== 0 || chunk[11] !== 0 || interlace > 1) invalidImage();
83
+ } else if (type === "PLTE") {
84
+ if (palette || data.length || color === 0 || color === 4 || !length || length % 3 || length > 768) invalidImage();
85
+ if (color === 3 && length / 3 > 2 ** depth) invalidImage();
86
+ palette = true;
87
+ } else if (type === "IDAT") {
88
+ if (endedData || (color === 3 && !palette)) invalidImage();
89
+ data.push(chunk);
90
+ } else if (type === "IEND") {
91
+ if (length || end !== bytes.length || !data.length) invalidImage();
92
+ const channels = ({ 0: 1, 2: 3, 3: 1, 4: 2, 6: 4 } as Record<number, number>)[color] ?? invalidImage();
93
+ const passes: [number, number, number, number][] = interlace
94
+ ? [
95
+ [0, 0, 8, 8],
96
+ [4, 0, 8, 8],
97
+ [0, 4, 4, 8],
98
+ [2, 0, 4, 4],
99
+ [0, 2, 2, 4],
100
+ [1, 0, 2, 2],
101
+ [0, 1, 1, 2],
102
+ ]
103
+ : [[0, 0, 1, 1]];
104
+ const rows = passes.map(([x, y, dx, dy]) => {
105
+ const columns = Math.max(0, Math.ceil((width - x) / dx));
106
+ const count = columns ? Math.max(0, Math.ceil((height - y) / dy)) : 0;
107
+ return { count, stride: 1 + Math.ceil((columns * channels * depth) / 8) };
108
+ });
109
+ const expected = rows.reduce((size, row) => size + row.count * row.stride, 0);
110
+ const compressed = Buffer.concat(data);
111
+ try {
112
+ const inflated = inflateSync(compressed, { maxOutputLength: expected });
113
+ if (inflated.length !== expected) invalidImage();
114
+ let position = 0;
115
+ for (const row of rows) {
116
+ for (let index = 0; index < row.count; index++, position += row.stride) {
117
+ if (inflated.readUInt8(position) > 4) invalidImage();
118
+ }
119
+ }
120
+ } catch {
121
+ invalidImage();
122
+ }
123
+ return;
124
+ } else {
125
+ // Animation can multiply the preview budget; unknown critical chunks are unsupported.
126
+ if (!(bytes.readUInt8(offset + 4) & 32) || ["acTL", "fcTL", "fdAT"].includes(type)) invalidImage();
127
+ }
128
+ if (data.length && type !== "IDAT") endedData = true;
129
+ offset = end;
130
+ }
131
+ invalidImage();
132
+ }
133
+
134
+ // Validate complete JPEG framing, not only the SOF dimensions. Entropy decoding is
135
+ // left to the image renderer; this is not a general-purpose JPEG codec validator.
136
+ function validateJpeg(bytes: Buffer): void {
137
+ let offset = 2;
138
+ let frame = false;
139
+ let scan = false;
140
+ let quantization = false;
141
+ let huffman = false;
142
+ const components = new Set<number>();
143
+ while (offset < bytes.length) {
144
+ if (bytes[offset++] !== 0xff) invalidImage();
145
+ while (bytes[offset] === 0xff) offset++;
146
+ const marker = bytes[offset++];
147
+ if (marker === 0xd9) {
148
+ if (!frame || !scan || offset !== bytes.length) invalidImage();
149
+ return;
150
+ }
151
+ if (offset + 2 > bytes.length) invalidImage();
152
+ const length = bytes.readUInt16BE(offset);
153
+ const end = offset + length;
154
+ if (length < 2 || end > bytes.length) invalidImage();
155
+ const chunk = bytes.subarray(offset + 2, end);
156
+ if (marker === 0xc0 || marker === 0xc1 || marker === 0xc2) {
157
+ const count = chunk[5];
158
+ if (frame || chunk.length < 6 || chunk[0] !== 8 || !count || count > 4 || chunk.length !== 6 + 3 * count)
159
+ invalidImage();
160
+ for (let index = 0; index < count; index++) {
161
+ const id = chunk.readUInt8(6 + 3 * index);
162
+ const sampling = chunk.readUInt8(7 + 3 * index);
163
+ if (
164
+ components.has(id) ||
165
+ !(sampling >> 4) ||
166
+ sampling >> 4 > 4 ||
167
+ !(sampling & 15) ||
168
+ (sampling & 15) > 4 ||
169
+ chunk.readUInt8(8 + 3 * index) > 3
170
+ )
171
+ invalidImage();
172
+ components.add(id);
173
+ }
174
+ frame = true;
175
+ } else if (marker === 0xdb) {
176
+ let position = 0;
177
+ while (position < chunk.length) {
178
+ const table = chunk.readUInt8(position++);
179
+ if (table >> 4 > 1 || (table & 15) > 3) invalidImage();
180
+ const size = table >> 4 ? 128 : 64;
181
+ if (position + size > chunk.length) invalidImage();
182
+ position += size;
183
+ }
184
+ if (!position) invalidImage();
185
+ quantization = true;
186
+ } else if (marker === 0xc4) {
187
+ let position = 0;
188
+ while (position < chunk.length) {
189
+ const table = chunk.readUInt8(position++);
190
+ if (table >> 4 > 1 || (table & 15) > 3 || position + 16 > chunk.length) invalidImage();
191
+ let count = 0;
192
+ let slots = 1;
193
+ for (let index = 0; index < 16; index++) {
194
+ const codes = chunk.readUInt8(position++);
195
+ slots = slots * 2 - codes;
196
+ if (slots < 0) invalidImage();
197
+ count += codes;
198
+ }
199
+ if (!count || count > 256 || position + count > chunk.length) invalidImage();
200
+ position += count;
201
+ }
202
+ if (!position) invalidImage();
203
+ huffman = true;
204
+ } else if (marker === 0xda) {
205
+ const count = chunk[0];
206
+ if (!frame || !quantization || !huffman || !count || chunk.length !== 4 + 2 * count) invalidImage();
207
+ const selected = new Set<number>();
208
+ for (let index = 0; index < count; index++) {
209
+ const id = chunk.readUInt8(1 + 2 * index);
210
+ const tables = chunk.readUInt8(2 + 2 * index);
211
+ if (!components.has(id) || selected.has(id) || tables >> 4 > 3 || (tables & 15) > 3) invalidImage();
212
+ selected.add(id);
213
+ }
214
+ if (
215
+ chunk.readUInt8(chunk.length - 3) > 63 ||
216
+ chunk.readUInt8(chunk.length - 2) > 63 ||
217
+ chunk.readUInt8(chunk.length - 1) >> 4 > 13 ||
218
+ (chunk.readUInt8(chunk.length - 1) & 15) > 13
219
+ )
220
+ invalidImage();
221
+ offset = end;
222
+ const start = offset;
223
+ while (offset < bytes.length) {
224
+ if (bytes[offset] !== 0xff) {
225
+ offset++;
226
+ continue;
227
+ }
228
+ let next = offset + 1;
229
+ while (bytes[next] === 0xff) next++;
230
+ if (
231
+ bytes[next] === 0 ||
232
+ (next < bytes.length && bytes.readUInt8(next) >= 0xd0 && bytes.readUInt8(next) <= 0xd7)
233
+ ) {
234
+ offset = next + 1;
235
+ continue;
236
+ }
237
+ break;
238
+ }
239
+ if (offset === start) invalidImage();
240
+ scan = true;
241
+ continue;
242
+ } else if (marker === 0xdd) {
243
+ if (chunk.length !== 2) invalidImage();
244
+ } else if (!(marker !== undefined && ((marker >= 0xe0 && marker <= 0xef) || marker === 0xfe))) {
245
+ invalidImage();
246
+ }
247
+ offset = end;
248
+ }
249
+ invalidImage();
250
+ }
251
+
252
+ // RIFF and bitstream headers are validated; VP8/VP8L entropy decoding is not done here.
253
+ function validateWebp(bytes: Buffer, width: number, height: number): void {
254
+ if (bytes.readUInt32LE(4) + 8 !== bytes.length) invalidImage();
255
+ let offset = 12;
256
+ let extended = false;
257
+ let image = false;
258
+ let alpha = false;
259
+ let alphaFlag = false;
260
+ while (offset + 8 <= bytes.length) {
261
+ const type = bytes.toString("latin1", offset, offset + 4);
262
+ const length = bytes.readUInt32LE(offset + 4);
263
+ const end = offset + 8 + length;
264
+ if (end + (length & 1) > bytes.length || (length & 1 && bytes[end] !== 0)) invalidImage();
265
+ const chunk = bytes.subarray(offset + 8, end);
266
+ if (type === "VP8X") {
267
+ if (offset !== 12 || length !== 10 || chunk.readUInt8(0) & 0xc3 || chunk[1] || chunk[2] || chunk[3])
268
+ invalidImage();
269
+ alphaFlag = !!(chunk.readUInt8(0) & 16);
270
+ extended = true;
271
+ } else if (type === "VP8 " || type === "VP8L") {
272
+ if (image) invalidImage();
273
+ let actualWidth: number;
274
+ let actualHeight: number;
275
+ if (type === "VP8 ") {
276
+ if (
277
+ length < 11 ||
278
+ chunk.readUInt8(0) & 1 ||
279
+ ((chunk.readUInt8(0) >> 1) & 7) > 3 ||
280
+ !(chunk.readUInt8(0) & 16) ||
281
+ !chunk.subarray(3, 6).equals(Buffer.from([0x9d, 0x01, 0x2a]))
282
+ )
283
+ invalidImage();
284
+ const partition = chunk.readUIntLE(0, 3) >>> 5;
285
+ if (!partition || partition + 10 >= length) invalidImage();
286
+ actualWidth = chunk.readUInt16LE(6) & 0x3fff;
287
+ actualHeight = chunk.readUInt16LE(8) & 0x3fff;
288
+ } else {
289
+ if (alpha || length < 6 || chunk[0] !== 0x2f || chunk.readUInt8(4) & 0xe0) invalidImage();
290
+ const bits = chunk.readUInt32LE(1);
291
+ actualWidth = (bits & 0x3fff) + 1;
292
+ actualHeight = ((bits >>> 14) & 0x3fff) + 1;
293
+ }
294
+ if (actualWidth !== width || actualHeight !== height) invalidImage();
295
+ image = true;
296
+ } else if (type === "ALPH") {
297
+ if (
298
+ !extended ||
299
+ !alphaFlag ||
300
+ alpha ||
301
+ image ||
302
+ length < 2 ||
303
+ chunk.readUInt8(0) & 0xc0 ||
304
+ (chunk.readUInt8(0) & 3) > 1 ||
305
+ ((chunk.readUInt8(0) >> 4) & 3) > 1
306
+ )
307
+ invalidImage();
308
+ if (!(chunk.readUInt8(0) & 3) && length !== 1 + width * height) invalidImage();
309
+ alpha = true;
310
+ } else if (!extended || ["ANIM", "ANMF"].includes(type)) {
311
+ invalidImage();
312
+ }
313
+ offset = end + (length & 1);
314
+ }
315
+ if (offset !== bytes.length || !image) invalidImage();
316
+ }
317
+
318
+ export function decodeImage(base64: string): DecodedImage {
319
+ if (typeof base64 !== "string" || !base64.length || base64.length > MAX_BASE64_LENGTH) {
320
+ throw new Error("Image data is empty or exceeds the 32 MiB limit.");
321
+ }
322
+ // Buffer.from() alone accepts invalid characters, missing padding, and aliases.
323
+ if (base64.length % 4 || /[^A-Za-z0-9+/=]/.test(base64)) throw new Error("Malformed base64 image data.");
324
+ const padding = base64.endsWith("==") ? 2 : base64.endsWith("=") ? 1 : 0;
325
+ const size = (base64.length / 4) * 3 - padding;
326
+ if (size > MAX_IMAGE_BYTES) throw new Error("Image data exceeds the 32 MiB limit.");
327
+ const bytes = Buffer.from(base64, "base64");
328
+ if (!size || bytes.length !== size || bytes.toString("base64") !== base64)
329
+ throw new Error("Malformed base64 image data.");
330
+ let mimeType: DecodedImage["mimeType"];
331
+ let extension: DecodedImage["extension"];
332
+ if (bytes.subarray(0, 8).equals(Buffer.from("89504e470d0a1a0a", "hex"))) {
333
+ mimeType = "image/png";
334
+ extension = "png";
335
+ } else if (bytes[0] === 0xff && bytes[1] === 0xd8) {
336
+ mimeType = "image/jpeg";
337
+ extension = "jpg";
338
+ } else if (
339
+ bytes.length >= 30 &&
340
+ bytes.toString("latin1", 0, 4) === "RIFF" &&
341
+ bytes.toString("latin1", 8, 12) === "WEBP"
342
+ ) {
343
+ mimeType = "image/webp";
344
+ extension = "webp";
345
+ } else {
346
+ invalidImage();
347
+ }
348
+ const dimensions = getImageDimensions(base64, mimeType);
349
+ if (!dimensions) invalidImage();
350
+ const { widthPx: width, heightPx: height } = dimensions;
351
+ checkDimensions(width, height);
352
+ if (mimeType === "image/png") validatePng(bytes, width, height);
353
+ else if (mimeType === "image/jpeg") validateJpeg(bytes);
354
+ else validateWebp(bytes, width, height);
355
+ return { bytes, mimeType, extension, width, height };
356
+ }
357
+
358
+ type OutputOptions = {
359
+ cwd: string;
360
+ path: string;
361
+ signal?: AbortSignal;
362
+ isCurrent?: () => boolean;
363
+ };
364
+
365
+ function checkCurrent(options: OutputOptions): void {
366
+ if (options.signal?.aborted || options.isCurrent?.() === false) {
367
+ throw new DOMException("Image publication was cancelled or is no longer current.", "AbortError");
368
+ }
369
+ }
370
+
371
+ function hasCode(error: unknown, code: string): boolean {
372
+ return typeof error === "object" && error !== null && "code" in error && error.code === code;
373
+ }
374
+
375
+ async function atOutput(options: OutputOptions, action: (destination: string) => Promise<void>): Promise<string> {
376
+ checkCurrent(options);
377
+ if (typeof options.path !== "string" || !options.path.length) throw new Error("Output path is required.");
378
+ let destination: string | undefined;
379
+ const tool = createWriteTool(options.cwd, {
380
+ operations: {
381
+ mkdir: async (directory) => {
382
+ checkCurrent(options);
383
+ await fs.mkdir(directory, { recursive: true });
384
+ checkCurrent(options);
385
+ },
386
+ writeFile: async (absolutePath) => {
387
+ checkCurrent(options);
388
+ destination = absolutePath;
389
+ await action(absolutePath);
390
+ checkCurrent(options);
391
+ },
392
+ },
393
+ });
394
+ // The public factory owns normalization and its mutation queue. Our guards also
395
+ // cover queued ownership changes; await operations to drain all in-flight I/O.
396
+ await tool.execute("codex-imagegen-output", { path: options.path, content: "" });
397
+ checkCurrent(options);
398
+ if (destination === undefined) throw new Error("Output destination was not resolved.");
399
+ return destination;
400
+ }
401
+
402
+ async function checkWritable(destination: string, options: OutputOptions): Promise<void> {
403
+ let target = destination;
404
+ for (let links = 0; links <= 40; links++) {
405
+ checkCurrent(options);
406
+ try {
407
+ const stat = await fs.stat(target);
408
+ checkCurrent(options);
409
+ if (stat.isDirectory()) {
410
+ throw Object.assign(new Error("Image destination is a directory."), { code: "EISDIR", path: target });
411
+ }
412
+ // Overwriting an existing file needs its write permission, not parent write permission.
413
+ await fs.access(target, constants.W_OK);
414
+ checkCurrent(options);
415
+ return;
416
+ } catch (error) {
417
+ if (!hasCode(error, "ENOENT")) throw error;
418
+ }
419
+ checkCurrent(options);
420
+ let entry: Awaited<ReturnType<typeof fs.lstat>>;
421
+ try {
422
+ entry = await fs.lstat(target);
423
+ checkCurrent(options);
424
+ } catch (error) {
425
+ if (!hasCode(error, "ENOENT")) throw error;
426
+ checkCurrent(options);
427
+ // A symlink target ending in a separator requires an existing directory;
428
+ // it cannot become a new file even when its containing directory is writable.
429
+ if (target.endsWith("/") || (sep === "\\" && target.endsWith("\\"))) {
430
+ throw Object.assign(new Error("Image destination is a directory."), { code: "EISDIR", path: target });
431
+ }
432
+ // A missing target requires write and search access in its actual parent.
433
+ // X_OK is ignored by Node on Windows. This check does not reserve the path.
434
+ await fs.access(dirname(target), constants.W_OK | constants.X_OK);
435
+ checkCurrent(options);
436
+ return;
437
+ }
438
+ if (!entry.isSymbolicLink()) {
439
+ await fs.access(target, constants.W_OK);
440
+ checkCurrent(options);
441
+ return;
442
+ }
443
+ const link = await fs.readlink(target);
444
+ checkCurrent(options);
445
+ // Do not lexically resolve link targets: a preceding directory symlink can
446
+ // change the meaning of `..`. Let the filesystem resolve those components.
447
+ target = isAbsolute(link) ? link : `${dirname(target)}${sep}${link}`;
448
+ }
449
+ throw Object.assign(new Error("Too many symbolic links."), { code: "ELOOP", path: destination });
450
+ }
451
+
452
+ /** Best-effort checks before HTTP; create parents, but never open or truncate the target. */
453
+ export async function preflightOutput(options: OutputOptions): Promise<void> {
454
+ await atOutput(options, (destination) => checkWritable(destination, options));
455
+ checkCurrent(options);
456
+ }
457
+
458
+ export async function publishImage(image: DecodedImage, options: OutputOptions): Promise<{ path: string }> {
459
+ checkCurrent(options);
460
+ checkDimensions(image.width, image.height);
461
+ if (!Buffer.isBuffer(image.bytes) || !image.bytes.length || image.bytes.length > MAX_IMAGE_BYTES)
462
+ throw new Error("Invalid image byte size.");
463
+ const validated = decodeImage(image.bytes.toString("base64"));
464
+ if (
465
+ validated.mimeType !== image.mimeType ||
466
+ validated.extension !== image.extension ||
467
+ validated.width !== image.width ||
468
+ validated.height !== image.height
469
+ )
470
+ invalidImage();
471
+ const path = await atOutput(options, async (destination) => {
472
+ // Native WRITE can leave truncated/partial output on failure or cancellation.
473
+ // Never unlink, roll back, or rename over the target or its symlinks.
474
+ // Unlike native text WRITE, binary writes also pass the signal to Node.
475
+ await fs.writeFile(destination, image.bytes, { signal: options.signal });
476
+ checkCurrent(options);
477
+ });
478
+ checkCurrent(options);
479
+ return { path };
480
+ }