feat: file blocks (#10)
Phase 3, part 2 (`docs/design.md`, "Next"): file blocks. Moderators block a file network-wide by its sha256, so a removed product can't come back under another name or catalog.
**Blocking**
- A file's page (Console → Blocks → a file) shows whether it's blocked and the products using it, so a moderator sees what a block removes before confirming ("Block and remove 2 products").
- Moderators reach it from a product's files (each has a Block link for them) or by pasting a sha256 into the Blocks tab, which also lists blocked files.
- Blocking a file:
- removes every product with a revision using it. Each removal is audited as `product.remove` with the file, so creators are notified and can appeal it as before.
- puts a `{type: "block", sha256}` change in the changes feed of every catalog hosting it, meaning: delete it whatever uses it. (t5de-catalog doesn't read the feed yet.)
- refuses uploads with it from then on (409 `blocked`). Each attempt is audited as `file.blocked_upload` with the person and catalog, so moderators see who tried.
- Unblocking lets the file in again. The products it removed stay removed until a moderator restores them, one by one.
- Who: `product:remove` hub-wide (moderators and admins). The Blocks tab shows only for them.
**API**: `GET /api/v1/blocks`, and `GET`/`PUT`/`DELETE /api/v1/blocks/:sha256` (`docs/products.md`).
**Migration** `0013_file_blocks`: the `file_block` table, and a GIN index on revisions' file lists, so finding the products using a file doesn't scan every revision.
**Checks**
- 53 API tests pass. The new `blocks.test.ts` covers:
- who may block
- the preview of what a block removes
- removal of every product using the file, across catalogs and creators
- the changes feed, notifications and appeals
- refused uploads and their audit entry
- unblocking, and restoring a removed product afterwards
- Type checks pass.
- On a local hub, through the website's own forms:
- the Block link on a product's files, for moderators only
- the Blocks tab, for moderators only (404 for the creator)
- the file's page, then blocking: the product is gone, its creator notified and offered Appeal
- a re-upload through the catalog API: refused, and audited
- unblocking, then Restore
- Fixed along the way: an empty reason gave a generic "Some of that isn't right"; it now says "Give a reason."
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Phase 3, part 2 (`docs/design.md`, "Next"): file blocks. Moderators block a file network-wide by its sha256, so a removed product can't come back under another name or catalog.
**Blocking**
- A file's page (Console → Blocks → a file) shows whether it's blocked and the products using it, so a moderator sees what a block removes before confirming ("Block and remove 2 products").
- Moderators reach it from a product's files (each has a Block link for them) or by pasting a sha256 into the Blocks tab, which also lists blocked files.
- Blocking a file:
- removes every product with a revision using it. Each removal is audited as `product.remove` with the file, so creators are notified and can appeal it as before.
- puts a `{type: "block", sha256}` change in the changes feed of every catalog hosting it, meaning: delete it whatever uses it. (t5de-catalog doesn't read the feed yet.)
- refuses uploads with it from then on (409 `blocked`). Each attempt is audited as `file.blocked_upload` with the person and catalog, so moderators see who tried.
- Unblocking lets the file in again. The products it removed stay removed until a moderator restores them, one by one.
- Who: `product:remove` hub-wide (moderators and admins). The Blocks tab shows only for them.
**API**: `GET /api/v1/blocks`, and `GET`/`PUT`/`DELETE /api/v1/blocks/:sha256` (`docs/products.md`).
**Migration** `0013_file_blocks`: the `file_block` table, and a GIN index on revisions' file lists, so finding the products using a file doesn't scan every revision.
**Checks**
- 53 API tests pass. The new `blocks.test.ts` covers:
- who may block
- the preview of what a block removes
- removal of every product using the file, across catalogs and creators
- the changes feed, notifications and appeals
- refused uploads and their audit entry
- unblocking, and restoring a removed product afterwards
- Type checks pass.
- On a local hub, through the website's own forms:
- the Block link on a product's files, for moderators only
- the Blocks tab, for moderators only (404 for the creator)
- the file's page, then blocking: the product is gone, its creator notified and offered Appeal
- a re-upload through the catalog API: refused, and audited
- unblocking, then Restore
- Fixed along the way: an empty reason gave a generic "Some of that isn't right"; it now says "Give a reason."
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-authored-by: dhkatz <[email protected]>
This commit was merged in pull request #10.
This commit is contained in:
1 parent
7299e10b08
commit
58a3e70a63
18 files changed
+4074
-10
No files matched your search
+71
-3
@@ -26,7 +26,8 @@ import { ImvuClient, ImvuUnavailable, NoSuchImvuUser } from "./imvu";
|
||||
import { Realtime } from "./realtime";
|
||||
import { isAdultRoom, Rooms } from "./rooms";
|
||||
import { Signer } from "./keys";
|
||||
import { availableTo, ProductError, Products, type EditRights, type ProductViewer } from "./products";
|
||||
import { Blocks, isSha256 } from "./blocks";
|
||||
import { availableTo, BlockedUpload, ProductError, Products, type EditRights, type ProductViewer } from "./products";
|
||||
import {
|
||||
chatId,
|
||||
HostedError,
|
||||
@@ -182,6 +183,7 @@ export function createApp({
|
||||
});
|
||||
const limiter = new Limiter();
|
||||
const cases = new Cases(db, perms);
|
||||
const blocks = new Blocks(db);
|
||||
const notifications = new Notifications(db, (userId, message) => realtime.notify(userId, message));
|
||||
|
||||
/** Tells a product's creator that someone else changed it. */
|
||||
@@ -407,7 +409,15 @@ export function createApp({
|
||||
url: `${(webURL ?? "").replace(/\/+$/, "")}/catalogs/${i.catalogId}?invite=${i.code}`,
|
||||
});
|
||||
|
||||
type ConsoleSection = "overview" | "products" | "catalogs" | "cases" | "people" | "audit" | "settings";
|
||||
type ConsoleSection = "overview" | "products" | "catalogs" | "cases" | "people" | "blocks" | "audit" | "settings";
|
||||
|
||||
const blockParam = t.Object({ sha256: t.String({ pattern: "^[0-9a-f]{64}$" }) });
|
||||
const blockView = (b: { block: typeof schema.fileBlock.$inferSelect; by: string | null }) => ({
|
||||
sha256: b.block.sha256,
|
||||
reason: b.block.reason,
|
||||
by: b.by,
|
||||
at: b.block.createdAt.toISOString(),
|
||||
});
|
||||
|
||||
const caseParam = t.Object({ id: t.Numeric({ minimum: 1, multipleOf: 1 }) });
|
||||
|
||||
@@ -1719,7 +1729,16 @@ export function createApp({
|
||||
async ({ request, body, set }) => {
|
||||
const c = await products.catalogFor(request.headers.get("authorization"));
|
||||
if (!c) throw new Problem(401, "forbidden", "Not an approved catalog.");
|
||||
const r = await productCall(() => products.registerRevision(c, body));
|
||||
const r = await productCall(async () => {
|
||||
try {
|
||||
return await products.registerRevision(c, body);
|
||||
} catch (e) {
|
||||
// Someone tried a blocked file again: moderators see who, and from which catalog.
|
||||
if (e instanceof BlockedUpload)
|
||||
await audited(e.personId, "file.blocked_upload", c.id, { files: e.files }, { catalog: c.id, person: e.personId });
|
||||
throw e;
|
||||
}
|
||||
});
|
||||
set.status = 201;
|
||||
return r;
|
||||
},
|
||||
@@ -1976,6 +1995,54 @@ export function createApp({
|
||||
},
|
||||
{ moderator: true, params: productParam, body: t.Object({ reason: t.String({ minLength: 1, maxLength: 500 }) }) },
|
||||
)
|
||||
// File blocks: moderation blocks a file network-wide (docs/products.md).
|
||||
.get(
|
||||
"/blocks",
|
||||
async ({ me, query }) => {
|
||||
await need(me, "product:remove", hubScope);
|
||||
const limit = 50;
|
||||
const rows = await blocks.list({ before: query.before ? new Date(query.before) : undefined, limit });
|
||||
return { blocks: rows.map(blockView), before: rows.length === limit ? rows.at(-1)!.block.createdAt.toISOString() : null };
|
||||
},
|
||||
{ signedIn: true, query: t.Object({ before: t.Optional(t.String({ format: "date-time" })) }) },
|
||||
)
|
||||
// A file's block, if any, and the products using it (what blocking it removes).
|
||||
.get(
|
||||
"/blocks/:sha256",
|
||||
async ({ me, params }) => {
|
||||
await need(me, "product:remove", hubScope);
|
||||
const b = await blocks.get(params.sha256);
|
||||
return { block: b ? blockView(b) : null, products: await blocks.usedBy(params.sha256) };
|
||||
},
|
||||
{ signedIn: true, params: blockParam },
|
||||
)
|
||||
.put(
|
||||
"/blocks/:sha256",
|
||||
async ({ me, params, body }) => {
|
||||
await need(me, "product:remove", hubScope);
|
||||
const reason = body.reason.trim();
|
||||
if (!reason || !isSha256(params.sha256)) throw new Problem(400, "invalid", "Give a reason.");
|
||||
const removed = await productCall(() => blocks.block(params.sha256, reason, me.id));
|
||||
await audited(me.id, "file.block", params.sha256, { reason, removed: removed.map((p) => p.id) });
|
||||
for (const p of removed) {
|
||||
await audited(me.id, "product.remove", p.id, { reason, file: params.sha256 }, { product: p.id, person: p.creatorId });
|
||||
await notifications.add(p.creatorId, "product_removed", { product: p.id, name: p.name, reason }, { product: p.id }, me.id);
|
||||
}
|
||||
return { removed: removed.map((p) => ({ id: p.id, name: p.name })) };
|
||||
},
|
||||
{ signedIn: true, params: blockParam, body: t.Object({ reason: t.String({ maxLength: 500 }) }) },
|
||||
)
|
||||
.delete(
|
||||
"/blocks/:sha256",
|
||||
async ({ me, params, body, set }) => {
|
||||
await need(me, "product:remove", hubScope);
|
||||
await productCall(() => blocks.unblock(params.sha256));
|
||||
const reason = body?.reason?.trim() ?? "";
|
||||
await audited(me.id, "file.unblock", params.sha256, reason ? { reason } : {});
|
||||
set.status = 204;
|
||||
},
|
||||
{ signedIn: true, params: blockParam, body: t.Optional(t.Object({ reason: t.Optional(t.String({ maxLength: 500 })) })) },
|
||||
)
|
||||
// Moderation restores a removed product (an upheld appeal, a mistake).
|
||||
.post(
|
||||
"/products/:id/unremove",
|
||||
@@ -2458,6 +2525,7 @@ export function createApp({
|
||||
if (mod || scope.catalogs.length || scope.products.length || (await cases.list(me, { limit: 1 })).length)
|
||||
sections.push("cases");
|
||||
if (mod) sections.push("people");
|
||||
if (await perms.can(me, "product:remove", hubScope)) sections.push("blocks");
|
||||
if (sections.length > 1 || scope.rooms.length) sections.push("audit");
|
||||
if (me.role === "admin") sections.push("settings");
|
||||
if (sections.length === 1)
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
// File blocks (docs/products.md): moderation blocks a file network-wide by its sha256, so a removed product can't
|
||||
// come back under another name. Revisions with a blocked file can't be registered, products using it are removed,
|
||||
// and the catalogs hosting it are told to delete it. The routes in app.ts check permissions, audit and notify.
|
||||
import { and, desc, eq, inArray, isNull, lt, sql, schema, type Database } from "@t5de/db";
|
||||
import { ProductError } from "./products";
|
||||
|
||||
const { catalogChange, fileBlock, hosting, product, productRevision, user } = schema;
|
||||
|
||||
export const isSha256 = (s: string) => /^[0-9a-f]{64}$/.test(s);
|
||||
|
||||
/** A product with a revision using a file. */
|
||||
export type FileUse = {
|
||||
id: string;
|
||||
name: string;
|
||||
creatorId: string;
|
||||
creatorUsername: string | null;
|
||||
removed: boolean;
|
||||
revisions: number[];
|
||||
};
|
||||
|
||||
export class Blocks {
|
||||
constructor(private db: Database) {}
|
||||
|
||||
async get(sha256: string) {
|
||||
const [b] = await this.db
|
||||
.select({ block: fileBlock, by: user.username })
|
||||
.from(fileBlock)
|
||||
.leftJoin(user, eq(user.id, fileBlock.byId))
|
||||
.where(eq(fileBlock.sha256, sha256));
|
||||
return b;
|
||||
}
|
||||
|
||||
/** Which of these files are blocked. */
|
||||
async blocked(sha256s: string[]): Promise<string[]> {
|
||||
if (sha256s.length === 0) return [];
|
||||
const rows = await this.db.select({ sha256: fileBlock.sha256 }).from(fileBlock).where(inArray(fileBlock.sha256, sha256s));
|
||||
return rows.map((r) => r.sha256);
|
||||
}
|
||||
|
||||
/** The products with a revision using a file (what blocking it would remove), newest first. */
|
||||
async usedBy(sha256: string): Promise<FileUse[]> {
|
||||
const rows = await this.db
|
||||
.select({ p: product, creatorUsername: user.username, number: productRevision.number })
|
||||
.from(productRevision)
|
||||
.innerJoin(product, eq(product.id, productRevision.productId))
|
||||
.leftJoin(user, eq(user.id, product.creatorId))
|
||||
.where(sql`${productRevision.files} @> ${JSON.stringify([{ sha256 }])}::jsonb`)
|
||||
.orderBy(desc(product.createdAt), productRevision.number);
|
||||
const out = new Map<string, FileUse>();
|
||||
for (const r of rows) {
|
||||
if (r.p.deletedAt && !r.p.removedAt) continue; // deleted by its creator: nothing to remove
|
||||
const u = out.get(r.p.id) ?? {
|
||||
id: r.p.id,
|
||||
name: r.p.name,
|
||||
creatorId: r.p.creatorId,
|
||||
creatorUsername: r.creatorUsername,
|
||||
removed: r.p.removedAt !== null,
|
||||
revisions: [],
|
||||
};
|
||||
u.revisions.push(r.number);
|
||||
out.set(r.p.id, u);
|
||||
}
|
||||
return [...out.values()];
|
||||
}
|
||||
|
||||
/**
|
||||
* Blocks a file: removes the products using it (those not removed already, which are returned) and tells the
|
||||
* catalogs hosting it to delete it (a `block` change).
|
||||
*/
|
||||
async block(sha256: string, reason: string, byId: string): Promise<FileUse[]> {
|
||||
if (!isSha256(sha256)) throw new ProductError(400, "invalid", "That isn't a file's sha256 (64 hex digits).");
|
||||
const uses = await this.usedBy(sha256);
|
||||
const ids = uses.map((u) => u.id);
|
||||
const removed = uses.filter((u) => !u.removed);
|
||||
await this.db.transaction(async (tx) => {
|
||||
const [made] = await tx.insert(fileBlock).values({ sha256, reason, byId }).onConflictDoNothing().returning();
|
||||
if (!made) throw new ProductError(409, "blocked", "That file is blocked already.");
|
||||
if (removed.length)
|
||||
await tx
|
||||
.update(product)
|
||||
.set({ removedAt: new Date(), removedReason: reason })
|
||||
.where(and(inArray(product.id, removed.map((u) => u.id)), isNull(product.removedAt)));
|
||||
if (ids.length) {
|
||||
const hosts = await tx
|
||||
.selectDistinct({ catalogId: hosting.catalogId })
|
||||
.from(hosting)
|
||||
.innerJoin(productRevision, and(eq(productRevision.productId, hosting.productId), eq(productRevision.number, hosting.number)))
|
||||
.where(and(inArray(hosting.productId, ids), sql`${productRevision.files} @> ${JSON.stringify([{ sha256 }])}::jsonb`));
|
||||
if (hosts.length) await tx.insert(catalogChange).values(hosts.map((h) => ({ catalogId: h.catalogId, data: { type: "block", sha256 } })));
|
||||
}
|
||||
});
|
||||
return removed;
|
||||
}
|
||||
|
||||
/** Unblocks a file. Products it removed stay removed (moderators restore them one by one); catalogs aren't told,
|
||||
* since they deleted the file and get it again only with a new upload. */
|
||||
async unblock(sha256: string) {
|
||||
const [gone] = await this.db.delete(fileBlock).where(eq(fileBlock.sha256, sha256)).returning();
|
||||
if (!gone) throw new ProductError(404, "not_found", "That file isn't blocked.");
|
||||
return gone;
|
||||
}
|
||||
|
||||
/** Blocks, newest first. */
|
||||
async list(opts: { before?: Date; limit?: number } = {}) {
|
||||
return this.db
|
||||
.select({ block: fileBlock, by: user.username })
|
||||
.from(fileBlock)
|
||||
.leftJoin(user, eq(user.id, fileBlock.byId))
|
||||
.where(opts.before ? lt(fileBlock.createdAt, opts.before) : undefined)
|
||||
.orderBy(desc(fileBlock.createdAt))
|
||||
.limit(opts.limit ?? 50);
|
||||
}
|
||||
}
|
||||
@@ -20,7 +20,7 @@ import { cleanHTML, maxDescription } from "./html";
|
||||
import type { ImvuClient } from "./imvu";
|
||||
import type { Signer } from "./keys";
|
||||
|
||||
const { catalog, catalogChange, catalogMember, product, productInfoChange, productRevision, hosting, library, roleAssignment, user } =
|
||||
const { catalog, catalogChange, catalogMember, fileBlock, product, productInfoChange, productRevision, hosting, library, roleAssignment, user } =
|
||||
schema;
|
||||
|
||||
export type Catalog = typeof catalog.$inferSelect;
|
||||
@@ -63,6 +63,17 @@ export class ProductError extends Error {
|
||||
}
|
||||
}
|
||||
|
||||
/** An upload with a blocked file (docs/products.md): refused, and the route audits who tried. */
|
||||
export class BlockedUpload extends ProductError {
|
||||
constructor(
|
||||
readonly personId: string,
|
||||
readonly catalogId: string,
|
||||
readonly files: FileEntry[],
|
||||
) {
|
||||
super(409, "blocked", "This upload has a file T5DE blocks.");
|
||||
}
|
||||
}
|
||||
|
||||
const base32 = "abcdefghijklmnopqrstuvwxyz234567";
|
||||
export const newProductID = () =>
|
||||
[...crypto.getRandomValues(new Uint8Array(10))].map((b) => base32[b & 31]).join("");
|
||||
@@ -260,6 +271,15 @@ export class Products {
|
||||
const parent = Number.isSafeInteger(body.parent) && body.parent > 0 ? body.parent : 0;
|
||||
const notes = (typeof body.notes === "string" ? body.notes.trim() : "").slice(0, 2000);
|
||||
const personId = claims.sub;
|
||||
const blocked = new Set(
|
||||
(
|
||||
await this.db
|
||||
.select({ sha256: fileBlock.sha256 })
|
||||
.from(fileBlock)
|
||||
.where(inArray(fileBlock.sha256, [...new Set(files.map((f) => f.sha256))]))
|
||||
).map((b) => b.sha256),
|
||||
);
|
||||
if (blocked.size) throw new BlockedUpload(personId, c.id, files.filter((f) => blocked.has(f.sha256)));
|
||||
|
||||
const made = await this.db.transaction(async (tx) => {
|
||||
let p: Product;
|
||||
|
||||
Reference in new issue
Block a user