Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
15 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 8 additions & 10 deletions apps/server/src/assets/AssetAccess.ts
Original file line number Diff line number Diff line change
Expand Up @@ -410,22 +410,20 @@ export const issueAssetUrl = Effect.fn("AssetAccess.issueAssetUrl")(function* (i
: /^mate-asset:([a-f0-9-]{36})$/.exec(input.resource.path)?.[1];
if (occurrenceId) {
const config = yield* ServerConfig.ServerConfig;
const store = contentAssetsAt(config.stateDir);
// A page a call published is kept apart from the pictures, under the same reference.
const occurrence = yield* Effect.tryPromise({
try: () => contentAssetsAt(config.stateDir).occurrence(occurrenceId),
try: () => store.occurrence(occurrenceId).catch(() => store.pageOccurrence(occurrenceId)),
catch: (cause) => new AssetWorkspaceAssetInspectionError({ resource: input.resource, cause }),
});
if (occurrence.original.status !== "ready")
const original = occurrence.original;
if (original.status !== "ready")
return yield* new AssetWorkspaceAssetNotFoundError({ resource: input.resource });
return {
relativeUrl: `/api/assets/objects/${occurrence.original.digest}/original`,
relativeUrl: `/api/assets/objects/${original.digest}/original`,
expiresAt: 0,
...(occurrence.original.width && occurrence.original.height
? {
imageDimensions: {
width: occurrence.original.width,
height: occurrence.original.height,
},
}
...("width" in original && original.width && original.height
? { imageDimensions: { width: original.width, height: original.height } }
: {}),
};
}
Expand Down
31 changes: 31 additions & 0 deletions apps/server/src/assets/ContentAssetHttp.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -138,3 +138,34 @@ it.effect.each([
expect(resolutions).toBe(1);
}),
);

it.effect("serves a published page as a document that runs nothing at its own address", () =>
Effect.gen(function* () {
const root = yield* Effect.promise(() =>
NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "mate-http-page-")),
);
roots.push(root);
const store = new ContentAssets(root);
// A page that opens with an SVG still is a page, never a picture.
const html = '<svg xmlns="http://www.w3.org/2000/svg"></svg><script>fetch("/api")</script>';
const page = yield* Effect.promise(() =>
store.ingestPage(["call"], Buffer.from(html), {
threadId: ThreadId.make("thread"),
ownerId: "call",
name: "page-1.html",
}),
);
const object = yield* Effect.promise(() => store.object(page.original.digest));
const response = yield* protectedContentAsset(Effect.succeed(null), Effect.succeed(object), {
method: "GET",
headers: {},
});
expect(response.status).toBe(200);
expect(response.headers["content-type"]).toBe("text/html");
expect(response.headers["content-security-policy"]).toBe("default-src 'none'; sandbox");
const bytes = yield* Effect.promise(async () =>
Buffer.from(await HttpServerResponse.toWeb(response).arrayBuffer()).toString(),
);
expect(bytes).toBe(html);
}),
);
5 changes: 5 additions & 0 deletions apps/server/src/assets/ContentAssetHttp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import type { AssetRepresentation } from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import { HttpServerResponse } from "effect/http";

import { PAGE_MIME_TYPE } from "./ContentAssets.ts";
import { openMediaFile, streamMediaFile } from "./MediaFile.ts";

export const contentAssetFailure = (code: string, status: number) =>
Expand Down Expand Up @@ -32,6 +33,10 @@ export const contentAssetResponse = Effect.fn("contentAssetResponse")(function*
...(object.mimeType === "image/svg+xml"
? { "Content-Security-Policy": "default-src 'none'; style-src 'unsafe-inline'; sandbox" }
: {}),
// A page is read by its conversation's frame, never opened here: at this address it runs nothing.
...(object.mimeType === PAGE_MIME_TYPE
? { "Content-Security-Policy": "default-src 'none'; sandbox" }
: {}),
};
if (
request.headers["if-none-match"]
Expand Down
54 changes: 53 additions & 1 deletion apps/server/src/assets/ContentAssets.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import * as NodePath from "node:path";

import { ThreadId } from "@t3tools/contracts";
import sharp from "sharp";
import { afterEach, expect, it } from "vite-plus/test";
import { afterEach, describe, expect, it } from "vite-plus/test";

import { ContentAssets } from "./ContentAssets.ts";

Expand Down Expand Up @@ -240,3 +240,55 @@ it("a pressure retry of the preview recipe never publishes a reference to reclai
await NodeFSP.rm(directory, { recursive: true, force: true });
}
});

describe("a page an agent published, in the asset store", () => {
const pageOwner = { threadId: ThreadId.make("thread"), ownerId: "call", name: "page-1.html" };

it("is kept apart from the pictures, so a build that reads only pictures never meets it", async () => {
const { root, store } = await fixture();
const picture = await store.ingestBytes(await image(), owner);
const page = await store.ingestPage(["call"], Buffer.from("<h1>Plan</h1>"), pageOwner);
const pictures = await NodeFSP.readdir(NodePath.join(root, "home", "occurrences"));
expect(pictures).toEqual([`${picture.id}.json`]);
expect(await store.pageOccurrence(page.id)).toEqual(page);
expect(await store.pageOwners(page.original.digest)).toEqual([page]);
expect(await store.owners(page.original.digest)).toEqual([]);
});

it("is kept once for the same call, however often it is told", async () => {
const { store } = await fixture();
const first = await store.ingestPage(["call"], Buffer.from("<h1>Plan</h1>"), pageOwner);
const again = await store.ingestPage(["call"], Buffer.from("<h1>Plan</h1>"), pageOwner);
expect(again.id).toBe(first.id);
});

it("is never the same object as the same bytes kept as a picture", async () => {
const { store } = await fixture();
const svg = Buffer.from('<svg xmlns="http://www.w3.org/2000/svg" width="2" height="2"/>');
const picture = await store.ingestBytes(svg, { ...owner, name: "dot.svg" });
const page = await store.ingestPage(["call"], svg, pageOwner);
if (picture.original.status !== "ready") throw new Error("picture refused");
expect(page.original.digest).not.toBe(picture.original.digest);
expect((await store.object(picture.original.digest)).mimeType).toBe("image/svg+xml");
expect((await store.object(page.original.digest)).mimeType).toBe("text/html");
});
});

it("an occurrence this build cannot read never hides every other picture's readers", async () => {
const { root, store } = await fixture();
const picture = await store.ingestBytes(await image(), owner);
if (picture.original.status !== "ready") throw new Error("picture refused");
await NodeFSP.writeFile(
NodePath.join(root, "home", "occurrences", "00000000-0000-4000-8000-000000000000.json"),
JSON.stringify({
...picture,
id: "x",
original: { ...picture.original, mimeType: "text/x-newer" },
}),
);
expect(
(await new ContentAssets(NodePath.join(root, "home")).owners(picture.original.digest)).map(
(each) => each.id,
),
).toEqual([picture.id]);
});
102 changes: 99 additions & 3 deletions apps/server/src/assets/ContentAssets.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,18 +4,23 @@ import * as NodeFS from "node:fs";
import * as NodeFSP from "node:fs/promises";
import * as NodePath from "node:path";

import type { AssetRepresentation, ImageOccurrence } from "@t3tools/contracts";
import type { AssetRepresentation, ImageOccurrence, PageOccurrence } from "@t3tools/contracts";
import {
ImageOccurrence as OccurrenceSchema,
PageOccurrence as PageOccurrenceSchema,
AssetRepresentation as RepresentationSchema,
} from "@t3tools/contracts";
import * as Schema from "effect/Schema";
import { mediaMimeTypeFromExtension } from "@t3tools/shared/filePreview";
import sharp, { type Metadata } from "sharp";

const decodeOccurrence = Schema.decodeUnknownSync(OccurrenceSchema);
const decodePageOccurrence = Schema.decodeUnknownSync(PageOccurrenceSchema);
const decodeRepresentation = Schema.decodeUnknownSync(RepresentationSchema);
const digestOf = (bytes: Uint8Array) => NodeCrypto.createHash("sha256").update(bytes).digest("hex");
/** A page's object identity: its bytes as a page, never the same object as the same bytes as a picture. */
const pageDigestOf = (bytes: Uint8Array) =>
NodeCrypto.createHash("sha256").update("mate-page\0").update(bytes).digest("hex");
const hasCode = (error: unknown, code: string) =>
typeof error === "object" && error !== null && "code" in error && error.code === code;
export class ContentAssetError extends Error {
Expand Down Expand Up @@ -56,6 +61,8 @@ export function isStorageFull(error: unknown): boolean {
return false;
}
type Owner = Omit<ImageOccurrence, "id" | "original"> & { readonly mimeType?: string };
/** The one kind of original besides a picture: a page an agent published. */
export const PAGE_MIME_TYPE = "text/html";
type StoredObject = AssetRepresentation & { readonly path: string };
const stores = new Map<string, ContentAssets>();
export const contentAssetsAt = (stateDir: string) => {
Expand All @@ -72,6 +79,7 @@ export const contentAssetsAt = (stateDir: string) => {
export class ContentAssets {
private mutation: Promise<void> = Promise.resolve();
private ownership: Promise<Map<string, ImageOccurrence[]>> | undefined;
private pageOwnership: Promise<Map<string, PageOccurrence[]>> | undefined;
private previewOwnership: Promise<Map<string, Set<string>>> | undefined;
private readonly backfilling = new Map<string, Promise<ImageOccurrence>>();
private readonly encoding = new Map<string, Promise<AssetRepresentation>>();
Expand Down Expand Up @@ -374,6 +382,93 @@ export class ContentAssets {
);
}

/**
* A page an agent published, kept as its bytes came and never read as a picture, even one that
* opens with an SVG. It is kept apart from the pictures: its object's identity says it is a page
* (`pageDigestOf`), and its occurrence lives in `pages/`, an index a build that reads only
* pictures never opens. Kept once per `key`: the same call told again keeps nothing twice.
*/
async ingestPage(
key: ReadonlyArray<unknown>,
bytes: Uint8Array,
owner: Omit<PageOccurrence, "id" | "original" | "provenance">,
): Promise<PageOccurrence> {
const binding = NodePath.join(
this.directory,
"pages",
"bindings",
`${digestOf(Buffer.from(JSON.stringify(key)))}.json`,
);
const bound = await NodeFSP.readFile(binding, "utf8")
.then((text) => this.pageOccurrence((JSON.parse(text) as { id: string }).id))
.catch(() => null);
if (bound !== null) return bound;
const digest = pageDigestOf(bytes);
const file = NodePath.join(this.directory, "originals", digest);
const exists = await this.object(digest).then(
(object) => object.mimeType === PAGE_MIME_TYPE,
() => false,
);
if (!exists) {
await this.atomic(file, bytes);
await NodeFSP.chmod(file, 0o444);
const representation: AssetRepresentation = {
digest,
mimeType: PAGE_MIME_TYPE,
sizeBytes: bytes.byteLength,
relativeUrl: `/api/assets/objects/${digest}/original`,
};
await this.atomic(`${file}.json`, Buffer.from(JSON.stringify(representation)));
}
const occurrence: PageOccurrence = {
...owner,
id: NodeCrypto.randomUUID(),
provenance: "capture",
original: { status: "ready", digest, mimeType: PAGE_MIME_TYPE, sizeBytes: bytes.byteLength },
};
await this.atomic(
NodePath.join(this.directory, "pages", `${occurrence.id}.json`),
Buffer.from(JSON.stringify(occurrence)),
);
await this.atomic(binding, Buffer.from(JSON.stringify({ id: occurrence.id })));
if (this.pageOwnership) {
const owners = await this.pageOwnership.catch(() => null);
owners?.set(digest, [...(owners.get(digest) ?? []), occurrence]);
}
return occurrence;
}

async pageOccurrence(id: string): Promise<PageOccurrence> {
if (!/^[a-f0-9-]{36}$/.test(id)) throw new ContentAssetError("object-missing");
try {
return decodePageOccurrence(
JSON.parse(
await NodeFSP.readFile(NodePath.join(this.directory, "pages", `${id}.json`), "utf8"),
),
);
} catch {
throw new ContentAssetError("object-missing");
}
}

/** The pages whose object is `digest`: who may read it. */
async pageOwners(digest: string): Promise<ReadonlyArray<PageOccurrence>> {
this.pageOwnership ??= (async () => {
const owners = new Map<string, PageOccurrence[]>();
const files = await NodeFSP.readdir(NodePath.join(this.directory, "pages")).catch(() => []);
for (const file of files.filter((name) => name.endsWith(".json"))) {
const page = await this.pageOccurrence(file.slice(0, -5)).catch(() => null);
if (page === null) continue;
owners.set(page.original.digest, [...(owners.get(page.original.digest) ?? []), page]);
}
return owners;
})().catch((error) => {
this.pageOwnership = undefined;
throw error;
});
return (await this.pageOwnership).get(digest) ?? [];
}

async occurrence(id: string): Promise<ImageOccurrence> {
if (!/^[a-f0-9-]{36}$/.test(id)) throw new ContentAssetError("object-missing");
try {
Expand Down Expand Up @@ -421,8 +516,9 @@ export class ContentAssets {
const owners = new Map<string, ImageOccurrence[]>();
const files = await NodeFSP.readdir(NodePath.join(this.directory, "occurrences"));
for (const file of files.filter((name) => name.endsWith(".json"))) {
const occurrence = await this.occurrence(file.slice(0, -5));
if (occurrence.original.status !== "ready") continue;
// Each on its own: one occurrence this build cannot read never hides every other.
const occurrence = await this.occurrence(file.slice(0, -5)).catch(() => null);
if (occurrence === null || occurrence.original.status !== "ready") continue;
const values = owners.get(occurrence.original.digest) ?? [];
values.push(occurrence);
owners.set(occurrence.original.digest, values);
Expand Down
21 changes: 21 additions & 0 deletions apps/server/src/assets/ImageAsset.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,27 @@ export const resolveImageAsset = Effect.fn("resolveImageAsset")(function* (
: /^mate-asset:[a-f0-9-]{36}:(source-missing|source-changed|storage-full|unsupported|persistence-failed)$/.exec(
resource.path,
)?.[1];
// A page a call published, under the same reference as a picture: its document, no picture's
// occurrence, to its own conversation alone.
const page =
occurrenceId && resource._tag !== "attachment" && resource._tag !== "project-favicon"
? yield* Effect.promise(() => store.pageOccurrence(occurrenceId).catch(() => null))
: null;
if (page !== null) {
if (!(input.ownsThread ? input.ownsThread(page.threadId) : page.threadId === threadId))
return yield* Effect.fail(new ContentAssetError("object-missing"));
const relativeUrl = `/api/assets/objects/${page.original.digest}/original`;
return {
relativeUrl,
expiresAt: 0,
representation: {
digest: page.original.digest,
mimeType: page.original.mimeType,
sizeBytes: page.original.sizeBytes,
relativeUrl,
},
} satisfies AssetCreateUrlResult;
}
let occurrence;
if (occurrenceId) {
occurrence = yield* Effect.tryPromise({
Expand Down
Loading
Loading