Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

2.6 KB
Raw Blame
import { mkdtempSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, expect, it, vi } from "vitest";
import { listZipSync, readZipMemberSync } from "./zip-archive.ts";
import { removeTempDir } from "./testing/cleanup.ts";
import { buildZip } from "./testing/zip-fixture.ts";

/** The sync readers share `fillBuffer`'s duty with the async ones: a filesystem may answer with fewer bytes than asked
 * (network, FUSE, an antivirus filter) and the read must carry on rather than report a sound archive as truncated. */
const reads = vi.hoisted(() => ({ limit: 3, shortcuts: 0 }));

vi.mock("node:fs", async (importOriginal) => {
  const fs = await importOriginal<typeof import("node:fs")>();
  const readSync = ((fd: number, buffer: Buffer, offset: number, length: number, position: number) => {
    const capped = Math.min(length, reads.limit);
    const bytesRead = fs.readSync(fd, buffer, offset, capped, position);
    if (bytesRead < length) reads.shortcuts += 1;
    return bytesRead;
  }) as typeof fs.readSync;
  return { ...fs, readSync };
});

let scratch = "";
afterEach(async () => {
  reads.limit = 3;
  reads.shortcuts = 0;
  if (scratch) await removeTempDir(scratch);
  scratch = "";
});

function archive(): { file: string; contents: string } {
  scratch = mkdtempSync(join(tmpdir(), "omb-zip-sync-short-"));
  const file = join(scratch, "fixture.zip");
  const contents = "complete contents\n";
  writeFileSync(file, buildZip([{ name: "nested/世界.txt", data: contents, method: 8 }]));
  return { file, contents };
}

it("lists a ZIP whose every synchronous read stops after three bytes", () => {
  const { file } = archive();
  const { total, records } = listZipSync(file, { maxEntries: 10, maxDirectoryBytes: 1 << 20 });
  expect(total).toBe(1);
  expect(records.map((record) => record.name)).toEqual(["nested/世界.txt"]);
  expect(reads.shortcuts).toBeGreaterThan(0);
});

it("reads a member whose every synchronous read stops after three bytes", () => {
  const { file, contents } = archive();
  const { records } = listZipSync(file, { maxEntries: 10, maxDirectoryBytes: 1 << 20 });
  const member = records[0]!.member!;
  expect(readZipMemberSync(file, member).toString("utf8")).toBe(contents);
});

it("still rejects a member whose declared size the file does not hold", () => {
  const { file } = archive();
  const { records } = listZipSync(file, { maxEntries: 10, maxDirectoryBytes: 1 << 20 });
  const member = records[0]!.member!;
  const beyond = { ...member, compressedBytes: member.compressedBytes + 4096 };
  expect(() => readZipMemberSync(file, beyond)).toThrow();
});