From 7cf19951ccf498a3e47466b9bd2fe7c44f6a7acb Mon Sep 17 00:00:00 2001 From: Travis Rich Date: Mon, 30 Nov 2026 23:08:46 -0500 Subject: [PATCH 1/4] Add uses: tables, API, and social images --- packages/server/drizzle/0041_uses.sql | 36 + .../server/drizzle/meta/0041_snapshot.json | 4499 +++++++++++++++++ packages/server/drizzle/meta/_journal.json | 7 + packages/server/src/api/avatars.ts | 77 +- packages/server/src/api/collections.ts | 3 + packages/server/src/api/uses.ts | 410 ++ packages/server/src/app.ts | 2 + packages/server/src/db/schema.ts | 73 + packages/server/src/handlers.ts | 1 + packages/server/src/lib/slug.ts | 1 + packages/server/src/uses/social-image.ts | 211 + packages/server/src/uses/uses.ts | 348 ++ packages/server/test/uses.test.ts | 353 ++ 13 files changed, 5991 insertions(+), 30 deletions(-) create mode 100644 packages/server/drizzle/0041_uses.sql create mode 100644 packages/server/drizzle/meta/0041_snapshot.json create mode 100644 packages/server/src/api/uses.ts create mode 100644 packages/server/src/uses/social-image.ts create mode 100644 packages/server/src/uses/uses.ts create mode 100644 packages/server/test/uses.test.ts diff --git a/packages/server/drizzle/0041_uses.sql b/packages/server/drizzle/0041_uses.sql new file mode 100644 index 00000000..2b954e86 --- /dev/null +++ b/packages/server/drizzle/0041_uses.sql @@ -0,0 +1,36 @@ +CREATE TABLE `use_collections` ( + `use_id` text NOT NULL, + `collection_id` text NOT NULL, + `major` integer DEFAULT false NOT NULL, + `minor` integer DEFAULT false NOT NULL, + `patch` integer DEFAULT false NOT NULL, + `created_at` integer DEFAULT (unixepoch('subsec') * 1000) NOT NULL, + PRIMARY KEY(`use_id`, `collection_id`), + FOREIGN KEY (`use_id`) REFERENCES `uses`(`id`) ON UPDATE no action ON DELETE cascade, + FOREIGN KEY (`collection_id`) REFERENCES `collections`(`id`) ON UPDATE no action ON DELETE cascade +); +--> statement-breakpoint +CREATE INDEX `use_collections_collection_idx` ON `use_collections` (`collection_id`);--> statement-breakpoint +CREATE TABLE `uses` ( + `id` text PRIMARY KEY NOT NULL, + `made_by` text NOT NULL, + `managed_by` text NOT NULL, + `organization_id` text, + `name` text NOT NULL, + `description` text, + `link` text, + `image_url` text, + `image_source` text, + `social_image_checked_at` integer, + `public` integer DEFAULT true NOT NULL, + `declared_in` text DEFAULT 'form' NOT NULL, + `taken_over_at` integer, + `created_at` integer DEFAULT (unixepoch('subsec') * 1000) NOT NULL, + `updated_at` integer NOT NULL, + FOREIGN KEY (`organization_id`) REFERENCES `organization`(`id`) ON UPDATE no action ON DELETE cascade +); +--> statement-breakpoint +CREATE INDEX `uses_made_by_idx` ON `uses` (`made_by`);--> statement-breakpoint +CREATE INDEX `uses_managed_by_idx` ON `uses` (`managed_by`);--> statement-breakpoint +CREATE INDEX `uses_org_idx` ON `uses` (`organization_id`);--> statement-breakpoint +ALTER TABLE `organization` ADD `pinned_uses` text; \ No newline at end of file diff --git a/packages/server/drizzle/meta/0041_snapshot.json b/packages/server/drizzle/meta/0041_snapshot.json new file mode 100644 index 00000000..75c362e7 --- /dev/null +++ b/packages/server/drizzle/meta/0041_snapshot.json @@ -0,0 +1,4499 @@ +{ + "version": "6", + "dialect": "sqlite", + "id": "740dceec-c3cc-4699-a3d6-3d88cb16bcc5", + "prevId": "fc04b827-9f34-4591-8e26-6cc91bd20a71", + "tables": { + "abuse_reports": { + "name": "abuse_reports", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "hash": { + "name": "hash", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "url": { + "name": "url", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "reason": { + "name": "reason", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "contact": { + "name": "contact", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "reporter_id": { + "name": "reporter_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'open'" + }, + "resolved_by": { + "name": "resolved_by", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "resolved_at": { + "name": "resolved_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(unixepoch('subsec') * 1000)" + } + }, + "indexes": { + "abuse_reports_status_idx": { + "name": "abuse_reports_status_idx", + "columns": ["status", "created_at"], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "account": { + "name": "account", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "account_id": { + "name": "account_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "provider_id": { + "name": "provider_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "access_token": { + "name": "access_token", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "refresh_token": { + "name": "refresh_token", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "id_token": { + "name": "id_token", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "access_token_expires_at": { + "name": "access_token_expires_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "refresh_token_expires_at": { + "name": "refresh_token_expires_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "scope": { + "name": "scope", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "password": { + "name": "password", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(unixepoch('subsec') * 1000)" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "account_user_id_idx": { + "name": "account_user_id_idx", + "columns": ["user_id"], + "isUnique": false + } + }, + "foreignKeys": { + "account_user_id_user_id_fk": { + "name": "account_user_id_user_id_fk", + "tableFrom": "account", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "apikey": { + "name": "apikey", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "config_id": { + "name": "config_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'default'" + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "start": { + "name": "start", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "reference_id": { + "name": "reference_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "prefix": { + "name": "prefix", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "key": { + "name": "key", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "refill_interval": { + "name": "refill_interval", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "refill_amount": { + "name": "refill_amount", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_refill_at": { + "name": "last_refill_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "enabled": { + "name": "enabled", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": true + }, + "rate_limit_enabled": { + "name": "rate_limit_enabled", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": true + }, + "rate_limit_time_window": { + "name": "rate_limit_time_window", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": 86400000 + }, + "rate_limit_max": { + "name": "rate_limit_max", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": 10 + }, + "request_count": { + "name": "request_count", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": 0 + }, + "remaining": { + "name": "remaining", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_request": { + "name": "last_request", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "expires_at": { + "name": "expires_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(unixepoch('subsec') * 1000)" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "permissions": { + "name": "permissions", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "metadata": { + "name": "metadata", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "apikey_key_idx": { + "name": "apikey_key_idx", + "columns": ["key"], + "isUnique": false + }, + "apikey_reference_id_idx": { + "name": "apikey_reference_id_idx", + "columns": ["reference_id"], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "ark_collections": { + "name": "ark_collections", + "columns": { + "collection_id": { + "name": "collection_id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "ark_id": { + "name": "ark_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "enabled": { + "name": "enabled", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": true + }, + "custom_url": { + "name": "custom_url", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(unixepoch('subsec') * 1000)" + } + }, + "indexes": { + "ark_collections_ark_id_unique": { + "name": "ark_collections_ark_id_unique", + "columns": ["ark_id"], + "isUnique": true + } + }, + "foreignKeys": { + "ark_collections_collection_id_collections_id_fk": { + "name": "ark_collections_collection_id_collections_id_fk", + "tableFrom": "ark_collections", + "tableTo": "collections", + "columnsFrom": ["collection_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "ark_record_types": { + "name": "ark_record_types", + "columns": { + "collection_id": { + "name": "collection_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "record_type": { + "name": "record_type", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "redirect_url_field": { + "name": "redirect_url_field", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": { + "ark_record_types_collection_id_collections_id_fk": { + "name": "ark_record_types_collection_id_collections_id_fk", + "tableFrom": "ark_record_types", + "tableTo": "collections", + "columnsFrom": ["collection_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "ark_record_types_collection_id_record_type_pk": { + "columns": ["collection_id", "record_type"], + "name": "ark_record_types_collection_id_record_type_pk" + } + }, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "ark_shoulders": { + "name": "ark_shoulders", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "shoulder": { + "name": "shoulder", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(unixepoch('subsec') * 1000)" + } + }, + "indexes": { + "ark_shoulders_shoulder_unique": { + "name": "ark_shoulders_shoulder_unique", + "columns": ["shoulder"], + "isUnique": true + } + }, + "foreignKeys": { + "ark_shoulders_organization_id_organization_id_fk": { + "name": "ark_shoulders_organization_id_organization_id_fk", + "tableFrom": "ark_shoulders", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "ark_tombstones": { + "name": "ark_tombstones", + "columns": { + "ark_id": { + "name": "ark_id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "shoulder": { + "name": "shoulder", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "naan": { + "name": "naan", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "collection_id": { + "name": "collection_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "owner_name": { + "name": "owner_name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "collection_name": { + "name": "collection_name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "deleted_at": { + "name": "deleted_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "cleanup_runs": { + "name": "cleanup_runs", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "step": { + "name": "step", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'queued'" + }, + "trigger": { + "name": "trigger", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "dry_run": { + "name": "dry_run", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "requested_by": { + "name": "requested_by", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "mark_run_id": { + "name": "mark_run_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "state": { + "name": "state", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "seq": { + "name": "seq", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "lease": { + "name": "lease", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "stats": { + "name": "stats", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "started_at": { + "name": "started_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "finished_at": { + "name": "finished_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(unixepoch('subsec') * 1000)" + } + }, + "indexes": { + "cleanup_runs_created_idx": { + "name": "cleanup_runs_created_idx", + "columns": ["created_at"], + "isUnique": false + }, + "cleanup_runs_step_idx": { + "name": "cleanup_runs_step_idx", + "columns": ["step", "status"], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "collection_tombstones": { + "name": "collection_tombstones", + "columns": { + "collection_id": { + "name": "collection_id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "slug": { + "name": "slug", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "ref_events": { + "name": "ref_events", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "ref_bytes": { + "name": "ref_bytes", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "versions": { + "name": "versions", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "total_bytes": { + "name": "total_bytes", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "deleted_by": { + "name": "deleted_by", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "deleted_at": { + "name": "deleted_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "record_layout": { + "name": "record_layout", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'today'" + }, + "records_dropped_at": { + "name": "records_dropped_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "collection_webhooks": { + "name": "collection_webhooks", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "collection_id": { + "name": "collection_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "url": { + "name": "url", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "bump_filter": { + "name": "bump_filter", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "secret": { + "name": "secret", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "enabled": { + "name": "enabled", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": true + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(unixepoch('subsec') * 1000)" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "last_delivery_at": { + "name": "last_delivery_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "collection_webhooks_collection_idx": { + "name": "collection_webhooks_collection_idx", + "columns": ["collection_id"], + "isUnique": false + } + }, + "foreignKeys": { + "collection_webhooks_collection_id_collections_id_fk": { + "name": "collection_webhooks_collection_id_collections_id_fk", + "tableFrom": "collection_webhooks", + "tableTo": "collections", + "columnsFrom": ["collection_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "collections": { + "name": "collections", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "slug": { + "name": "slug", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "public": { + "name": "public", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "head_version_id": { + "name": "head_version_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "private_salt": { + "name": "private_salt", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "public_files_root": { + "name": "public_files_root", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "summary": { + "name": "summary", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "ref_events": { + "name": "ref_events", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "ref_bytes": { + "name": "ref_bytes", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "version_count": { + "name": "version_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "history_bytes": { + "name": "history_bytes", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "stored_bytes": { + "name": "stored_bytes", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "stored_at": { + "name": "stored_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_push_at": { + "name": "last_push_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "reconcile_started_at": { + "name": "reconcile_started_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "reconciled_at": { + "name": "reconciled_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "reconcile_report": { + "name": "reconcile_report", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "reconcile_state": { + "name": "reconcile_state", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "reconciled_seq": { + "name": "reconciled_seq", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "reconciled_files_root": { + "name": "reconciled_files_root", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "record_layout": { + "name": "record_layout", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'today'" + }, + "deleted_at": { + "name": "deleted_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(unixepoch('subsec') * 1000)" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "collections_org_slug_uq": { + "name": "collections_org_slug_uq", + "columns": ["organization_id", "slug"], + "isUnique": true + }, + "collections_public_updated_idx": { + "name": "collections_public_updated_idx", + "columns": ["public", "updated_at"], + "isUnique": false + } + }, + "foreignKeys": { + "collections_organization_id_organization_id_fk": { + "name": "collections_organization_id_organization_id_fk", + "tableFrom": "collections", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "commit_units": { + "name": "commit_units", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "session_id": { + "name": "session_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "plan_id": { + "name": "plan_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "set": { + "name": "set", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "type": { + "name": "type", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "ord": { + "name": "ord", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "after": { + "name": "after", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "through": { + "name": "through", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "gap": { + "name": "gap", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'pending'" + }, + "slices_key": { + "name": "slices_key", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "output_key": { + "name": "output_key", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "queued_at": { + "name": "queued_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "attempts": { + "name": "attempts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(unixepoch('subsec') * 1000)" + } + }, + "indexes": { + "commit_units_plan_idx": { + "name": "commit_units_plan_idx", + "columns": ["plan_id", "set", "type", "ord"], + "isUnique": false + }, + "commit_units_status_idx": { + "name": "commit_units_status_idx", + "columns": ["session_id", "status", "queued_at"], + "isUnique": false + } + }, + "foreignKeys": { + "commit_units_session_id_push_sessions_id_fk": { + "name": "commit_units_session_id_push_sessions_id_fk", + "tableFrom": "commit_units", + "tableTo": "push_sessions", + "columnsFrom": ["session_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "denylist": { + "name": "denylist", + "columns": { + "hash": { + "name": "hash", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "reason": { + "name": "reason", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(unixepoch('subsec') * 1000)" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "file_uploads": { + "name": "file_uploads", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "collection_id": { + "name": "collection_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "session_id": { + "name": "session_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "hash": { + "name": "hash", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "size": { + "name": "size", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "mime_type": { + "name": "mime_type", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "storage_key": { + "name": "storage_key", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "multipart_upload_id": { + "name": "multipart_upload_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'pending'" + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(unixepoch('subsec') * 1000)" + } + }, + "indexes": { + "file_uploads_hash_idx": { + "name": "file_uploads_hash_idx", + "columns": ["hash"], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "files": { + "name": "files", + "columns": { + "hash": { + "name": "hash", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "size": { + "name": "size", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "mime_type": { + "name": "mime_type", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "storage_key": { + "name": "storage_key", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "verified_at": { + "name": "verified_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(unixepoch('subsec') * 1000)" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "forks": { + "name": "forks", + "columns": { + "child_collection_id": { + "name": "child_collection_id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "parent_collection_id": { + "name": "parent_collection_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "parent_seq": { + "name": "parent_seq", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "sets": { + "name": "sets", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'public'" + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(unixepoch('subsec') * 1000)" + } + }, + "indexes": {}, + "foreignKeys": { + "forks_child_collection_id_collections_id_fk": { + "name": "forks_child_collection_id_collections_id_fk", + "tableFrom": "forks", + "tableTo": "collections", + "columnsFrom": ["child_collection_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "instance_settings": { + "name": "instance_settings", + "columns": { + "key": { + "name": "key", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "value": { + "name": "value", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "invitation": { + "name": "invitation", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "email": { + "name": "email", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "role": { + "name": "role", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'pending'" + }, + "expires_at": { + "name": "expires_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(unixepoch('subsec') * 1000)" + }, + "inviter_id": { + "name": "inviter_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "invitation_organization_id_idx": { + "name": "invitation_organization_id_idx", + "columns": ["organization_id"], + "isUnique": false + } + }, + "foreignKeys": { + "invitation_organization_id_organization_id_fk": { + "name": "invitation_organization_id_organization_id_fk", + "tableFrom": "invitation", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "invitation_inviter_id_user_id_fk": { + "name": "invitation_inviter_id_user_id_fk", + "tableFrom": "invitation", + "tableTo": "user", + "columnsFrom": ["inviter_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "jobs": { + "name": "jobs", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "type": { + "name": "type", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "payload": { + "name": "payload", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'queued'" + }, + "attempts": { + "name": "attempts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "run_at": { + "name": "run_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "locked_until": { + "name": "locked_until", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(unixepoch('subsec') * 1000)" + } + }, + "indexes": { + "jobs_ready_idx": { + "name": "jobs_ready_idx", + "columns": ["status", "run_at"], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "member": { + "name": "member", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "role": { + "name": "role", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'member'" + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(unixepoch('subsec') * 1000)" + }, + "public_membership": { + "name": "public_membership", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + } + }, + "indexes": { + "member_organization_id_idx": { + "name": "member_organization_id_idx", + "columns": ["organization_id"], + "isUnique": false + }, + "member_user_id_idx": { + "name": "member_user_id_idx", + "columns": ["user_id"], + "isUnique": false + }, + "member_org_user_uq": { + "name": "member_org_user_uq", + "columns": ["organization_id", "user_id"], + "isUnique": true + } + }, + "foreignKeys": { + "member_organization_id_organization_id_fk": { + "name": "member_organization_id_organization_id_fk", + "tableFrom": "member", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "member_user_id_user_id_fk": { + "name": "member_user_id_user_id_fk", + "tableFrom": "member", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "organization": { + "name": "organization", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "slug": { + "name": "slug", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "logo": { + "name": "logo", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(unixepoch('subsec') * 1000)" + }, + "metadata": { + "name": "metadata", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "bio": { + "name": "bio", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "website": { + "name": "website", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "avatar_url": { + "name": "avatar_url", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "tagline": { + "name": "tagline", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "location": { + "name": "location", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "cover_color": { + "name": "cover_color", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "cover_image_url": { + "name": "cover_image_url", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "cover_tint": { + "name": "cover_tint", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": true + }, + "provenance_note": { + "name": "provenance_note", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "pinned": { + "name": "pinned", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "pinned_uses": { + "name": "pinned_uses", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "ark_naan": { + "name": "ark_naan", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "ark_kf_naan": { + "name": "ark_kf_naan", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "kf_org_id": { + "name": "kf_org_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "is_default": { + "name": "is_default", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": false + } + }, + "indexes": { + "organization_slug_unique": { + "name": "organization_slug_unique", + "columns": ["slug"], + "isUnique": true + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "pending_members": { + "name": "pending_members", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "email": { + "name": "email", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "role": { + "name": "role", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'member'" + }, + "added_by": { + "name": "added_by", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(unixepoch('subsec') * 1000)" + } + }, + "indexes": { + "pending_members_org_email_uq": { + "name": "pending_members_org_email_uq", + "columns": ["organization_id", "email"], + "isUnique": true + }, + "pending_members_email_idx": { + "name": "pending_members_email_idx", + "columns": ["email"], + "isUnique": false + } + }, + "foreignKeys": { + "pending_members_organization_id_organization_id_fk": { + "name": "pending_members_organization_id_organization_id_fk", + "tableFrom": "pending_members", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "placements": { + "name": "placements", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "collection_id": { + "name": "collection_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "location_id": { + "name": "location_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "role": { + "name": "role", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "sets": { + "name": "sets", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "state": { + "name": "state", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'active'" + }, + "synced_seq": { + "name": "synced_seq", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "cursor": { + "name": "cursor", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "lease_until": { + "name": "lease_until", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_error": { + "name": "last_error", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "placements_one_primary_uq": { + "name": "placements_one_primary_uq", + "columns": ["collection_id"], + "isUnique": true, + "where": "\"placements\".\"role\" = 'primary' AND \"placements\".\"collection_id\" IS NOT NULL" + }, + "placements_collection_location_uq": { + "name": "placements_collection_location_uq", + "columns": ["collection_id", "location_id"], + "isUnique": true, + "where": "\"placements\".\"collection_id\" IS NOT NULL" + }, + "placements_org_location_uq": { + "name": "placements_org_location_uq", + "columns": ["organization_id", "location_id"], + "isUnique": true, + "where": "\"placements\".\"organization_id\" IS NOT NULL" + }, + "placements_location_idx": { + "name": "placements_location_idx", + "columns": ["location_id"], + "isUnique": false + } + }, + "foreignKeys": { + "placements_collection_id_collections_id_fk": { + "name": "placements_collection_id_collections_id_fk", + "tableFrom": "placements", + "tableTo": "collections", + "columnsFrom": ["collection_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "placements_organization_id_organization_id_fk": { + "name": "placements_organization_id_organization_id_fk", + "tableFrom": "placements", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "placements_location_id_storage_locations_id_fk": { + "name": "placements_location_id_storage_locations_id_fk", + "tableFrom": "placements", + "tableTo": "storage_locations", + "columnsFrom": ["location_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "push_packs": { + "name": "push_packs", + "columns": { + "session_id": { + "name": "session_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "pack_id": { + "name": "pack_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "record_set": { + "name": "record_set", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "records": { + "name": "records", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "bytes": { + "name": "bytes", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "raw": { + "name": "raw", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "record_type": { + "name": "record_type", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(unixepoch('subsec') * 1000)" + } + }, + "indexes": {}, + "foreignKeys": { + "push_packs_session_id_push_sessions_id_fk": { + "name": "push_packs_session_id_push_sessions_id_fk", + "tableFrom": "push_packs", + "tableTo": "push_sessions", + "columnsFrom": ["session_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "push_packs_session_id_pack_id_pk": { + "columns": ["session_id", "pack_id"], + "name": "push_packs_session_id_pack_id_pk" + } + }, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "push_runs": { + "name": "push_runs", + "columns": { + "session_id": { + "name": "session_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "seq": { + "name": "seq", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "object_key": { + "name": "object_key", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "count": { + "name": "count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "bytes": { + "name": "bytes", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "first_key": { + "name": "first_key", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "last_key": { + "name": "last_key", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "tier": { + "name": "tier", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "merging_into": { + "name": "merging_into", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "claimed_at": { + "name": "claimed_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(unixepoch('subsec') * 1000)" + } + }, + "indexes": { + "push_runs_tier_idx": { + "name": "push_runs_tier_idx", + "columns": ["session_id", "tier", "merging_into"], + "isUnique": false + } + }, + "foreignKeys": { + "push_runs_session_id_push_sessions_id_fk": { + "name": "push_runs_session_id_push_sessions_id_fk", + "tableFrom": "push_runs", + "tableTo": "push_sessions", + "columnsFrom": ["session_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "push_runs_session_id_seq_pk": { + "columns": ["session_id", "seq"], + "name": "push_runs_session_id_seq_pk" + } + }, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "push_sessions": { + "name": "push_sessions", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "collection_id": { + "name": "collection_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "base_version_id": { + "name": "base_version_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "base_semver": { + "name": "base_semver", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "message": { + "name": "message", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "app_id": { + "name": "app_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "actor_id": { + "name": "actor_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "strip_unknown_fields": { + "name": "strip_unknown_fields", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "records_received": { + "name": "records_received", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "runs": { + "name": "runs", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'open'" + }, + "result": { + "name": "result", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "finalize_started_at": { + "name": "finalize_started_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "commit_started": { + "name": "commit_started", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "in_key_order": { + "name": "in_key_order", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "overlapping_uploads": { + "name": "overlapping_uploads", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "cleaned_at": { + "name": "cleaned_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "commit_phase": { + "name": "commit_phase", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "progress_at": { + "name": "progress_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "stalls": { + "name": "stalls", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "commit_step": { + "name": "commit_step", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "commit_step_at": { + "name": "commit_step_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "commit_last_error": { + "name": "commit_last_error", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "commit_plan": { + "name": "commit_plan", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "assembly_lease": { + "name": "assembly_lease", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(unixepoch('subsec') * 1000)" + }, + "expires_at": { + "name": "expires_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "push_sessions_collection_idx": { + "name": "push_sessions_collection_idx", + "columns": ["collection_id"], + "isUnique": false + }, + "push_sessions_expires_idx": { + "name": "push_sessions_expires_idx", + "columns": ["status", "expires_at"], + "isUnique": false + }, + "push_sessions_user_idx": { + "name": "push_sessions_user_idx", + "columns": ["user_id", "status"], + "isUnique": false + } + }, + "foreignKeys": { + "push_sessions_collection_id_collections_id_fk": { + "name": "push_sessions_collection_id_collections_id_fk", + "tableFrom": "push_sessions", + "tableTo": "collections", + "columnsFrom": ["collection_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "ref_compaction_parts": { + "name": "ref_compaction_parts", + "columns": { + "compaction_id": { + "name": "compaction_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "part": { + "name": "part", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": { + "ref_compaction_parts_compaction_id_part_pk": { + "columns": ["compaction_id", "part"], + "name": "ref_compaction_parts_compaction_id_part_pk" + } + }, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "ref_compactions": { + "name": "ref_compactions", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "tier": { + "name": "tier", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "input_runs": { + "name": "input_runs", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "output_run": { + "name": "output_run", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "parts": { + "name": "parts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "prefix_length": { + "name": "prefix_length", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'running'" + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(unixepoch('subsec') * 1000)" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "ref_index_units": { + "name": "ref_index_units", + "columns": { + "version_id": { + "name": "version_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "unit": { + "name": "unit", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "events": { + "name": "events", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "bytes": { + "name": "bytes", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": { + "ref_index_units_version_id_unit_pk": { + "columns": ["version_id", "unit"], + "name": "ref_index_units_version_id_unit_pk" + } + }, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "ref_segments": { + "name": "ref_segments", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "run_id": { + "name": "run_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "tier": { + "name": "tier", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "first_hash": { + "name": "first_hash", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "last_hash": { + "name": "last_hash", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "count": { + "name": "count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "bytes": { + "name": "bytes", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "state": { + "name": "state", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'live'" + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(unixepoch('subsec') * 1000)" + } + }, + "indexes": { + "ref_segments_range_idx": { + "name": "ref_segments_range_idx", + "columns": ["state", "first_hash", "last_hash"], + "isUnique": false + }, + "ref_segments_run_idx": { + "name": "ref_segments_run_idx", + "columns": ["run_id"], + "isUnique": false + }, + "ref_segments_tier_idx": { + "name": "ref_segments_tier_idx", + "columns": ["tier"], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "schema_labels": { + "name": "schema_labels", + "columns": { + "schema_hash": { + "name": "schema_hash", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "label": { + "name": "label", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(unixepoch('subsec') * 1000)" + } + }, + "indexes": { + "schema_labels_label_idx": { + "name": "schema_labels_label_idx", + "columns": ["label"], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": { + "schema_labels_schema_hash_label_pk": { + "columns": ["schema_hash", "label"], + "name": "schema_labels_schema_hash_label_pk" + } + }, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "schema_usage": { + "name": "schema_usage", + "columns": { + "schema_hash": { + "name": "schema_hash", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "collection_id": { + "name": "collection_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "type_slug": { + "name": "type_slug", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "set": { + "name": "set", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "from_seq": { + "name": "from_seq", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "to_seq": { + "name": "to_seq", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "schema_usage_hash_idx": { + "name": "schema_usage_hash_idx", + "columns": ["schema_hash"], + "isUnique": false + } + }, + "foreignKeys": { + "schema_usage_collection_id_collections_id_fk": { + "name": "schema_usage_collection_id_collections_id_fk", + "tableFrom": "schema_usage", + "tableTo": "collections", + "columnsFrom": ["collection_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "schema_usage_collection_id_type_slug_set_from_seq_pk": { + "columns": ["collection_id", "type_slug", "set", "from_seq"], + "name": "schema_usage_collection_id_type_slug_set_from_seq_pk" + } + }, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "schemas": { + "name": "schemas", + "columns": { + "hash": { + "name": "hash", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(unixepoch('subsec') * 1000)" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "session": { + "name": "session", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "expires_at": { + "name": "expires_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "token": { + "name": "token", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(unixepoch('subsec') * 1000)" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "ip_address": { + "name": "ip_address", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "user_agent": { + "name": "user_agent", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "active_organization_id": { + "name": "active_organization_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "session_token_unique": { + "name": "session_token_unique", + "columns": ["token"], + "isUnique": true + }, + "session_user_id_idx": { + "name": "session_user_id_idx", + "columns": ["user_id"], + "isUnique": false + } + }, + "foreignKeys": { + "session_user_id_user_id_fk": { + "name": "session_user_id_user_id_fk", + "tableFrom": "session", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "storage_fence": { + "name": "storage_fence", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "epoch": { + "name": "epoch", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "window_until": { + "name": "window_until", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "window_run_id": { + "name": "window_run_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "storage_locations": { + "name": "storage_locations", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "endpoint": { + "name": "endpoint", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "region": { + "name": "region", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "bucket": { + "name": "bucket", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "prefix": { + "name": "prefix", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "''" + }, + "credentials": { + "name": "credentials", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'unverified'" + }, + "last_error": { + "name": "last_error", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "verified_at": { + "name": "verified_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "checked_at": { + "name": "checked_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(unixepoch('subsec') * 1000)" + } + }, + "indexes": {}, + "foreignKeys": { + "storage_locations_organization_id_organization_id_fk": { + "name": "storage_locations_organization_id_organization_id_fk", + "tableFrom": "storage_locations", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "usage_rollups": { + "name": "usage_rollups", + "columns": { + "day": { + "name": "day", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "account_id": { + "name": "account_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "collection_id": { + "name": "collection_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "metric": { + "name": "metric", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "amount": { + "name": "amount", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "usage_rollups_account_idx": { + "name": "usage_rollups_account_idx", + "columns": ["account_id", "day"], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": { + "usage_rollups_day_account_id_collection_id_metric_pk": { + "columns": ["day", "account_id", "collection_id", "metric"], + "name": "usage_rollups_day_account_id_collection_id_metric_pk" + } + }, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "use_collections": { + "name": "use_collections", + "columns": { + "use_id": { + "name": "use_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "collection_id": { + "name": "collection_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "major": { + "name": "major", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "minor": { + "name": "minor", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "patch": { + "name": "patch", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(unixepoch('subsec') * 1000)" + } + }, + "indexes": { + "use_collections_collection_idx": { + "name": "use_collections_collection_idx", + "columns": ["collection_id"], + "isUnique": false + } + }, + "foreignKeys": { + "use_collections_use_id_uses_id_fk": { + "name": "use_collections_use_id_uses_id_fk", + "tableFrom": "use_collections", + "tableTo": "uses", + "columnsFrom": ["use_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "use_collections_collection_id_collections_id_fk": { + "name": "use_collections_collection_id_collections_id_fk", + "tableFrom": "use_collections", + "tableTo": "collections", + "columnsFrom": ["collection_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "use_collections_use_id_collection_id_pk": { + "columns": ["use_id", "collection_id"], + "name": "use_collections_use_id_collection_id_pk" + } + }, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "user": { + "name": "user", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "email": { + "name": "email", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "email_verified": { + "name": "email_verified", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "image": { + "name": "image", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(unixepoch('subsec') * 1000)" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "user_email_unique": { + "name": "user_email_unique", + "columns": ["email"], + "isUnique": true + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "uses": { + "name": "uses", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "made_by": { + "name": "made_by", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "managed_by": { + "name": "managed_by", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "link": { + "name": "link", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "image_url": { + "name": "image_url", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "image_source": { + "name": "image_source", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "social_image_checked_at": { + "name": "social_image_checked_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "public": { + "name": "public", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": true + }, + "declared_in": { + "name": "declared_in", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'form'" + }, + "taken_over_at": { + "name": "taken_over_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(unixepoch('subsec') * 1000)" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "uses_made_by_idx": { + "name": "uses_made_by_idx", + "columns": ["made_by"], + "isUnique": false + }, + "uses_managed_by_idx": { + "name": "uses_managed_by_idx", + "columns": ["managed_by"], + "isUnique": false + }, + "uses_org_idx": { + "name": "uses_org_idx", + "columns": ["organization_id"], + "isUnique": false + } + }, + "foreignKeys": { + "uses_organization_id_organization_id_fk": { + "name": "uses_organization_id_organization_id_fk", + "tableFrom": "uses", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "v3_conversions": { + "name": "v3_conversions", + "columns": { + "collection_id": { + "name": "collection_id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'queued'" + }, + "flip": { + "name": "flip", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "allow_private": { + "name": "allow_private", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "from_layout": { + "name": "from_layout", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "from_public": { + "name": "from_public", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "from_history_bytes": { + "name": "from_history_bytes", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "private": { + "name": "private", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "versions": { + "name": "versions", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'[]'" + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(unixepoch('subsec') * 1000)" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": { + "v3_conversions_collection_id_collections_id_fk": { + "name": "v3_conversions_collection_id_collections_id_fk", + "tableFrom": "v3_conversions", + "tableTo": "collections", + "columnsFrom": ["collection_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "v3_uploads": { + "name": "v3_uploads", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "collection_id": { + "name": "collection_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'open'" + }, + "message": { + "name": "message", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "base": { + "name": "base", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "app_id": { + "name": "app_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "files": { + "name": "files", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "change": { + "name": "change", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "authored": { + "name": "authored", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "expect_head": { + "name": "expect_head", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "schemas": { + "name": "schemas", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "verified": { + "name": "verified", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "scan_units": { + "name": "scan_units", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "scan_done": { + "name": "scan_done", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "attempts": { + "name": "attempts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "result": { + "name": "result", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(unixepoch('subsec') * 1000)" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "expires_at": { + "name": "expires_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "v3_uploads_collection_idx": { + "name": "v3_uploads_collection_idx", + "columns": ["collection_id"], + "isUnique": false + }, + "v3_uploads_user_status_idx": { + "name": "v3_uploads_user_status_idx", + "columns": ["user_id", "status"], + "isUnique": false + } + }, + "foreignKeys": { + "v3_uploads_collection_id_collections_id_fk": { + "name": "v3_uploads_collection_id_collections_id_fk", + "tableFrom": "v3_uploads", + "tableTo": "collections", + "columnsFrom": ["collection_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "verification": { + "name": "verification", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "identifier": { + "name": "identifier", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "value": { + "name": "value", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "expires_at": { + "name": "expires_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(unixepoch('subsec') * 1000)" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "verification_identifier_idx": { + "name": "verification_identifier_idx", + "columns": ["identifier"], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "versions": { + "name": "versions", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "collection_id": { + "name": "collection_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "seq": { + "name": "seq", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "semver": { + "name": "semver", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "major": { + "name": "major", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "minor": { + "name": "minor", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "patch": { + "name": "patch", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "hash": { + "name": "hash", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "base_semver": { + "name": "base_semver", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "message": { + "name": "message", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "pushed_by": { + "name": "pushed_by", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "app_id": { + "name": "app_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "actor_id": { + "name": "actor_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "signature": { + "name": "signature", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "record_count": { + "name": "record_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "public_record_count": { + "name": "public_record_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "file_count": { + "name": "file_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "total_bytes": { + "name": "total_bytes", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "public_file_count": { + "name": "public_file_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "public_total_bytes": { + "name": "public_total_bytes", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "type_counts": { + "name": "type_counts", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "public_type_counts": { + "name": "public_type_counts", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "has_private": { + "name": "has_private", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "public_refs_root": { + "name": "public_refs_root", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "private_refs_root": { + "name": "private_refs_root", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "refs_indexed": { + "name": "refs_indexed", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "ref_events": { + "name": "ref_events", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "ref_bytes": { + "name": "ref_bytes", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "reconciled_at": { + "name": "reconciled_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "reconcile_report": { + "name": "reconcile_report", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "changes": { + "name": "changes", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(unixepoch('subsec') * 1000)" + }, + "published_at": { + "name": "published_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "push_session_id": { + "name": "push_session_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "asset_bytes": { + "name": "asset_bytes", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "v2_hash": { + "name": "v2_hash", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "former_hash": { + "name": "former_hash", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "versions_collection_seq_uq": { + "name": "versions_collection_seq_uq", + "columns": ["collection_id", "seq"], + "isUnique": true + }, + "versions_v2_hash_idx": { + "name": "versions_v2_hash_idx", + "columns": ["v2_hash"], + "isUnique": false + }, + "versions_former_hash_idx": { + "name": "versions_former_hash_idx", + "columns": ["former_hash"], + "isUnique": false + }, + "versions_collection_semver_uq": { + "name": "versions_collection_semver_uq", + "columns": ["collection_id", "semver"], + "isUnique": true + }, + "versions_hash_idx": { + "name": "versions_hash_idx", + "columns": ["hash"], + "isUnique": false + }, + "versions_published_idx": { + "name": "versions_published_idx", + "columns": ["published_at"], + "isUnique": false + }, + "versions_push_session_idx": { + "name": "versions_push_session_idx", + "columns": ["push_session_id"], + "isUnique": false + } + }, + "foreignKeys": { + "versions_collection_id_collections_id_fk": { + "name": "versions_collection_id_collections_id_fk", + "tableFrom": "versions", + "tableTo": "collections", + "columnsFrom": ["collection_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "webhook_deliveries": { + "name": "webhook_deliveries", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "webhook_id": { + "name": "webhook_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "collection_id": { + "name": "collection_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "version_id": { + "name": "version_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "semver": { + "name": "semver", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "bump_type": { + "name": "bump_type", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "event": { + "name": "event", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'version.created'" + }, + "payload": { + "name": "payload", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'pending'" + }, + "attempts": { + "name": "attempts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "response_code": { + "name": "response_code", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "duration_ms": { + "name": "duration_ms", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "next_attempt_at": { + "name": "next_attempt_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(unixepoch('subsec') * 1000)" + }, + "delivered_at": { + "name": "delivered_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "webhook_deliveries_webhook_idx": { + "name": "webhook_deliveries_webhook_idx", + "columns": ["webhook_id", "created_at"], + "isUnique": false + }, + "webhook_deliveries_pending_idx": { + "name": "webhook_deliveries_pending_idx", + "columns": ["status", "next_attempt_at"], + "isUnique": false + } + }, + "foreignKeys": { + "webhook_deliveries_webhook_id_collection_webhooks_id_fk": { + "name": "webhook_deliveries_webhook_id_collection_webhooks_id_fk", + "tableFrom": "webhook_deliveries", + "tableTo": "collection_webhooks", + "columnsFrom": ["webhook_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + } + }, + "views": {}, + "enums": {}, + "_meta": { + "schemas": {}, + "tables": {}, + "columns": {} + }, + "internal": { + "indexes": {} + } +} diff --git a/packages/server/drizzle/meta/_journal.json b/packages/server/drizzle/meta/_journal.json index 7d6ace45..fc6eae8f 100644 --- a/packages/server/drizzle/meta/_journal.json +++ b/packages/server/drizzle/meta/_journal.json @@ -288,6 +288,13 @@ "when": 1795490147250, "tag": "0040_version_former_hash", "breakpoints": true + }, + { + "idx": 41, + "version": "6", + "when": 1796097833935, + "tag": "0041_uses", + "breakpoints": true } ] } diff --git a/packages/server/src/api/avatars.ts b/packages/server/src/api/avatars.ts index 8f1e08d7..89af88d4 100644 --- a/packages/server/src/api/avatars.ts +++ b/packages/server/src/api/avatars.ts @@ -67,7 +67,46 @@ async function ownedOrg(c: Context, noun: string): Promise): PublicAssets | Response { +/** + * Read one image file from a multipart body and store it in the public bucket under + * `prefix` + its SHA-256 + its extension. The URL, or the error response. + */ +export async function storeUploadedImage( + c: Context, + assets: PublicAssets, + prefix: string, + maxBytes: number, +): Promise { + const tooLarge = `Image must be ${maxBytes / 1024 / 1024} MiB or smaller` + const contentType = c.req.header('content-type') ?? '' + if (!contentType.startsWith('multipart/form-data')) + return jsonError(c, 400, 'Send the image as multipart/form-data') + let form: FormData + try { + const body = await readBytes(c, maxBytes + MULTIPART_OVERHEAD) + form = await new Response(body, { headers: { 'content-type': contentType } }).formData() + } catch (err) { + if (err instanceof BodyTooLarge) return jsonError(c, 413, tooLarge) + return jsonError(c, 400, 'Malformed multipart body') + } + const file = [...form.values()].find((v): v is File => typeof v !== 'string') + if (!file) return jsonError(c, 400, 'No file uploaded') + if (file.size > maxBytes) return jsonError(c, 413, tooLarge) + + // The declared type is the browser's guess from the file name; the bytes decide. + const bytes = new Uint8Array(await file.arrayBuffer()) + const raster = sniffRaster(bytes) + if (!ALLOWED_TYPES.includes(file.type) || !raster) + return jsonError(c, 422, 'Only JPEG, PNG, GIF, and WebP images are allowed') + + const digest = new Uint8Array(await crypto.subtle.digest('SHA-256', bytes)) + const hash = [...digest].map((v) => v.toString(16).padStart(2, '0')).join('') + const key = `${prefix}${hash}.${raster.ext}` + await assets.store.put(key, bytes, { contentType: raster.type, cacheControl: CACHE_CONTROL }) + return `${assets.baseUrl}/${key}` +} + +export function assetsOr503(c: Context): PublicAssets | Response { return ( c.var.ports.publicAssets ?? jsonError(c, 503, 'Avatar uploads are not configured on this deployment') @@ -78,41 +117,19 @@ export function avatarRoutes() { const app = new Hono() for (const kind of KINDS) { - const tooLarge = `Image must be ${kind.maxBytes / 1024 / 1024} MiB or smaller` - app.post(`/api/accounts/:owner/${kind.path}`, async (c) => { const org = await ownedOrg(c, kind.noun) if (org instanceof Response) return org const assets = assetsOr503(c) if (assets instanceof Response) return assets - const contentType = c.req.header('content-type') ?? '' - if (!contentType.startsWith('multipart/form-data')) - return jsonError(c, 400, 'Send the image as multipart/form-data') - let form: FormData - try { - const body = await readBytes(c, kind.maxBytes + MULTIPART_OVERHEAD) - form = await new Response(body, { headers: { 'content-type': contentType } }).formData() - } catch (err) { - if (err instanceof BodyTooLarge) return jsonError(c, 413, tooLarge) - return jsonError(c, 400, 'Malformed multipart body') - } - const file = [...form.values()].find((v): v is File => typeof v !== 'string') - if (!file) return jsonError(c, 400, 'No file uploaded') - if (file.size > kind.maxBytes) return jsonError(c, 413, tooLarge) - - // The declared type is the browser's guess from the file name; the bytes decide. - const bytes = new Uint8Array(await file.arrayBuffer()) - const raster = sniffRaster(bytes) - if (!ALLOWED_TYPES.includes(file.type) || !raster) - return jsonError(c, 422, 'Only JPEG, PNG, GIF, and WebP images are allowed') - - const digest = new Uint8Array(await crypto.subtle.digest('SHA-256', bytes)) - const hash = [...digest].map((v) => v.toString(16).padStart(2, '0')).join('') - const key = `${avatarFolder(org.id)}${kind.prefix}${hash}.${raster.ext}` - await assets.store.put(key, bytes, { contentType: raster.type, cacheControl: CACHE_CONTROL }) - - const url = `${assets.baseUrl}/${key}` + const url = await storeUploadedImage( + c, + assets, + `${avatarFolder(org.id)}${kind.prefix}`, + kind.maxBytes, + ) + if (url instanceof Response) return url await c.var.ports.db .update(schema.organization) .set({ [kind.column]: url }) diff --git a/packages/server/src/api/collections.ts b/packages/server/src/api/collections.ts index 70729734..047c7ac0 100644 --- a/packages/server/src/api/collections.ts +++ b/packages/server/src/api/collections.ts @@ -18,6 +18,7 @@ import type { AppEnv } from '../app.js' import { chunks } from '../db/chunks.js' import * as schema from '../db/schema.js' import type { Db } from '../ports.js' +import { collectionUsedByCount, viewerOf } from '../uses/uses.js' import { metadataOf } from '../v3/catalog.js' import { readStore, readView } from '../v3/read-cache.js' import { jsonError, type Principal, reachesOrg, requireCollection } from './access.js' @@ -368,6 +369,8 @@ export function collectionRoutes() { ownerSlug: access.owner.slug, ownerName: access.owner.name, latestVersion, + // How many uses its Used by tab lists for this caller. + usedBy: await collectionUsedByCount(db, await viewerOf(db, c.var.principal), col), }) }) diff --git a/packages/server/src/api/uses.ts b/packages/server/src/api/uses.ts new file mode 100644 index 00000000..5b909510 --- /dev/null +++ b/packages/server/src/api/uses.ts @@ -0,0 +1,410 @@ +/** + * Uses: what people built using collections, listed under the collections' Used by + * (planning: used-by.md; who sees and manages what is in uses/uses.ts). + * + * GET /api/uses My uses: the caller's (made or managed) + * POST /api/uses declare one (below) + * GET /api/uses/:id + * PATCH /api/uses/:id the same fields, each optional + * DELETE /api/uses/:id + * POST /api/uses/:id/image multipart/form-data, one image file + * DELETE /api/uses/:id/image back to the link's social image, if any + * GET /api/collections/:owner/:slug/used-by a collection's Used by + * GET /api/accounts/:slug/used-by an org's Used by, and its pins + * GET /api/accounts/:slug/uses Our uses: those made for the org (members) + * PUT /api/accounts/:slug/pinned-uses {pinned: [use id]} (owners and admins) + * + * The body of a declaration: + * + * {name, description?, link?, public?, org?: slug | null, + * collections: [{collection: "owner/slug", major?, minor?, patch?}]} + * + * Declaring and managing take a session or an unscoped personal key (requireUser): a use + * is made by a person. Each collection named must be one the caller can read, so a + * declaration can't probe for private collections; listing one grants nothing. + */ +import { and, eq, isNull } from 'drizzle-orm' +import { type Context, Hono } from 'hono' + +import type { AppEnv } from '../app.js' +import * as schema from '../db/schema.js' +import { deleteOrgAvatars, deleteOwnedAvatar } from '../lib/avatars.js' +import { useImageFolder, useImageOwner } from '../uses/social-image.js' +import { + BUMPS, + canManageUse, + canReadCollection, + canSeeUse, + collectionUsedBy, + MAX_PINNED_USES, + MAX_USE_COLLECTIONS, + MAX_USE_DESCRIPTION, + MAX_USE_LINK, + MAX_USE_NAME, + orgUsedBy, + pinnedAmong, + type Use, + usesOfOrg, + usesOfPerson, + useViews, + type Viewer, + viewerOf, +} from '../uses/uses.js' +import { isAdmin, jsonError, requireCollection } from './access.js' +import { orgBySlug, requireUser } from './accounts.js' +import { assetsOr503, AVATAR_MAX_BYTES, storeUploadedImage } from './avatars.js' + +/** A use's uploaded image shows as a card's 1.91:1 picture: a 1200px-wide JPEG fits. */ +export const USE_IMAGE_MAX_BYTES = 2 * AVATAR_MAX_BYTES + +type Flags = { major: boolean; minor: boolean; patch: boolean } +type Body = Record + +const viewer = (c: Context) => viewerOf(c.var.ports.db, c.var.principal) + +/** The use, when the caller may see it; otherwise a 404. */ +async function loadUse(c: Context, v: Viewer): Promise { + const [u] = await c.var.ports.db + .select() + .from(schema.uses) + .where(eq(schema.uses.id, c.req.param('id') ?? '')) + .limit(1) + if (!u || !canSeeUse(v, u)) return jsonError(c, 404, 'Use not found') + return u +} + +/** A clean text field: trimmed, empty is none, capped. undefined when absent. */ +function text( + body: Body, + key: string, + max: number, +): { ok: true; value: string | null | undefined } | { ok: false; error: string } { + const v = body[key] + if (v === undefined) return { ok: true, value: undefined } + if (v !== null && typeof v !== 'string') return { ok: false, error: `${key} must be a string` } + const t = (v ?? '').trim() + if (t.length > max) return { ok: false, error: `${key} must be at most ${max} characters` } + // oxlint-disable-next-line no-control-regex + if (/[\u0000-\u0008\u000b-\u001f\u007f]/.test(t)) + return { ok: false, error: `${key} must not contain control characters` } + return { ok: true, value: t || null } +} + +/** A link a page may point at: http or https only (never `javascript:`). */ +function linkProblem(link: string): string | null { + try { + const u = new URL(link) + if (u.protocol !== 'https:' && u.protocol !== 'http:') + return 'link must start with http:// or https://' + return null + } catch { + return 'link must be a web address, like https://example.org' + } +} + +/** + * The collections a body names, resolved and checked: each one the caller can read, no + * repeats. A map of collection id to its notify flags, or the error response. + */ +async function resolveCollections( + c: Context, + v: Viewer, + raw: unknown, +): Promise | Response> { + if (!Array.isArray(raw) || raw.length === 0) + return jsonError(c, 422, 'collections must list at least one collection') + if (raw.length > MAX_USE_COLLECTIONS) + return jsonError(c, 422, `A use may list at most ${MAX_USE_COLLECTIONS} collections`) + const out = new Map() + for (const item of raw) { + const entry = (typeof item === 'string' ? { collection: item } : item) as Body | null + const name = entry?.collection + if (typeof name !== 'string' || !/^[^/\s]+\/[^/\s]+$/.test(name)) + return jsonError(c, 422, 'Each collection is named "owner/slug"') + const [owner, slug] = name.split('/') as [string, string] + const [row] = await c.var.ports.db + .select({ c: schema.collections }) + .from(schema.collections) + .innerJoin(schema.organization, eq(schema.organization.id, schema.collections.organizationId)) + .where( + and( + eq(schema.organization.slug, owner), + eq(schema.collections.slug, slug), + isNull(schema.collections.deletedAt), + ), + ) + .limit(1) + // Unknown and unreadable read the same, so private collections don't leak. + if (!row || !canReadCollection(v.roles, row.c)) + return jsonError(c, 422, `No collection ${name} that you can read`) + for (const b of BUMPS) { + if (entry![b] !== undefined && typeof entry![b] !== 'boolean') + return jsonError(c, 422, `${b} must be true or false`) + } + out.set(row.c.id, { + major: entry!.major === true, + minor: entry!.minor === true, + patch: entry!.patch === true, + }) + } + return out +} + +/** The org a use may be made for: one the caller owns or administers. */ +async function resolveOrg( + c: Context, + v: Viewer, + raw: unknown, +): Promise { + if (raw === null || raw === '') return null + if (typeof raw !== 'string') return jsonError(c, 422, 'org must be an organization slug') + const org = await orgBySlug(c, raw) + if (!org || !isAdmin(v.roles.get(org.id) ?? null)) + return jsonError(c, 403, 'You can declare uses only for organizations you manage') + return org.id +} + +/** Replace a use's collections with `want`. */ +async function setCollections(c: Context, useId: string, want: Map) { + const { db } = c.var.ports + await db.delete(schema.useCollections).where(eq(schema.useCollections.useId, useId)) + // Six values a row; D1 binds at most 100 a statement. + const rows = [...want].map(([collectionId, f]) => ({ useId, collectionId, ...f })) + for (let i = 0; i < rows.length; i += 12) + await db.insert(schema.useCollections).values(rows.slice(i, i + 12)) +} + +async function viewOne(c: Context, v: Viewer, id: string) { + const [u] = await c.var.ports.db.select().from(schema.uses).where(eq(schema.uses.id, id)).limit(1) + return (await useViews(c.var.ports.db, v, u ? [u] : []))[0] ?? null +} + +export function useRoutes() { + const app = new Hono() + + app.get('/api/uses', async (c) => { + const userId = requireUser(c, false) + if (userId instanceof Response) return userId + const v = await viewer(c) + const rows = await usesOfPerson(c.var.ports.db, userId) + return c.json({ uses: await useViews(c.var.ports.db, v, rows) }) + }) + + app.post('/api/uses', async (c) => { + const userId = requireUser(c, true) + if (userId instanceof Response) return userId + const v = await viewer(c) + const body = ((await c.req.json().catch(() => null)) ?? {}) as Body + const name = text(body, 'name', MAX_USE_NAME) + if (!name.ok) return jsonError(c, 422, name.error) + if (!name.value) return jsonError(c, 422, 'name is required') + const description = text(body, 'description', MAX_USE_DESCRIPTION) + if (!description.ok) return jsonError(c, 422, description.error) + const link = text(body, 'link', MAX_USE_LINK) + if (!link.ok) return jsonError(c, 422, link.error) + if (link.value) { + const bad = linkProblem(link.value) + if (bad) return jsonError(c, 422, bad) + } + if (body.public !== undefined && typeof body.public !== 'boolean') + return jsonError(c, 422, 'public must be true or false') + const orgId = await resolveOrg(c, v, body.org ?? null) + if (orgId instanceof Response) return orgId + const cols = await resolveCollections(c, v, body.collections) + if (cols instanceof Response) return cols + + const [u] = await c.var.ports.db + .insert(schema.uses) + .values({ + madeBy: userId, + managedBy: userId, + organizationId: orgId, + name: name.value, + description: description.value ?? null, + link: link.value ?? null, + public: body.public !== false, + declaredIn: 'form', + }) + .returning() + await setCollections(c, u!.id, cols) + if (u!.link) await c.var.ports.jobs.enqueue({ type: 'uses.socialImage', useId: u!.id }) + return c.json(await viewOne(c, v, u!.id), 201) + }) + + app.get('/api/uses/:id', async (c) => { + const v = await viewer(c) + const u = await loadUse(c, v) + if (u instanceof Response) return u + return c.json(await viewOne(c, v, u.id)) + }) + + app.patch('/api/uses/:id', async (c) => { + const userId = requireUser(c, true) + if (userId instanceof Response) return userId + const v = await viewer(c) + const u = await loadUse(c, v) + if (u instanceof Response) return u + if (!canManageUse(v, u)) return jsonError(c, 403, 'You cannot change this use') + const body = ((await c.req.json().catch(() => null)) ?? {}) as Body + const set: Partial = {} + const name = text(body, 'name', MAX_USE_NAME) + if (!name.ok) return jsonError(c, 422, name.error) + if (name.value === null) return jsonError(c, 422, 'name must not be empty') + if (name.value !== undefined) set.name = name.value + const description = text(body, 'description', MAX_USE_DESCRIPTION) + if (!description.ok) return jsonError(c, 422, description.error) + if (description.value !== undefined) set.description = description.value + const link = text(body, 'link', MAX_USE_LINK) + if (!link.ok) return jsonError(c, 422, link.error) + if (link.value) { + const bad = linkProblem(link.value) + if (bad) return jsonError(c, 422, bad) + } + if (link.value !== undefined && link.value !== u.link) { + set.link = link.value + set.socialImageCheckedAt = null + // A social image belongs to the old link; an upload stays. + if (u.imageSource === 'link') Object.assign(set, { imageUrl: null, imageSource: null }) + } + if (body.public !== undefined) { + if (typeof body.public !== 'boolean') return jsonError(c, 422, 'public must be true or false') + set.public = body.public + } + if (body.org !== undefined) { + const orgId = await resolveOrg(c, v, body.org) + if (orgId instanceof Response) return orgId + // Only its maker may make it theirs alone again; an org's admins may not take it. + if (orgId === null && u.organizationId && userId !== u.madeBy) + return jsonError(c, 403, "Only the use's maker can take it out of the organization") + if (orgId !== u.organizationId) set.organizationId = orgId + } + let cols: Map | null = null + if (body.collections !== undefined) { + const r = await resolveCollections(c, v, body.collections) + if (r instanceof Response) return r + cols = r + } + if (Object.keys(set).length) + await c.var.ports.db + .update(schema.uses) + .set({ ...set, updatedAt: new Date() }) + .where(eq(schema.uses.id, u.id)) + if (cols) await setCollections(c, u.id, cols) + if (set.link) await c.var.ports.jobs.enqueue({ type: 'uses.socialImage', useId: u.id }) + if (set.imageUrl === null && u.imageUrl && c.var.ports.publicAssets) + await deleteOwnedAvatar(c.var.ports.publicAssets, useImageOwner(u.id), u.imageUrl) + return c.json(await viewOne(c, v, u.id)) + }) + + app.delete('/api/uses/:id', async (c) => { + const userId = requireUser(c, true) + if (userId instanceof Response) return userId + const v = await viewer(c) + const u = await loadUse(c, v) + if (u instanceof Response) return u + if (!canManageUse(v, u)) return jsonError(c, 403, 'You cannot delete this use') + await c.var.ports.db.delete(schema.uses).where(eq(schema.uses.id, u.id)) + await deleteOrgAvatars(c.var.ports.publicAssets, useImageOwner(u.id)) + return c.json({ ok: true }) + }) + + app.post('/api/uses/:id/image', async (c) => { + const userId = requireUser(c, true) + if (userId instanceof Response) return userId + const v = await viewer(c) + const u = await loadUse(c, v) + if (u instanceof Response) return u + if (!canManageUse(v, u)) return jsonError(c, 403, 'You cannot change this use') + const assets = assetsOr503(c) + if (assets instanceof Response) return assets + const url = await storeUploadedImage(c, assets, useImageFolder(u.id), USE_IMAGE_MAX_BYTES) + if (url instanceof Response) return url + await c.var.ports.db + .update(schema.uses) + .set({ imageUrl: url, imageSource: 'upload', updatedAt: new Date() }) + .where(eq(schema.uses.id, u.id)) + if (u.imageUrl && u.imageUrl !== url) + await deleteOwnedAvatar(assets, useImageOwner(u.id), u.imageUrl) + return c.json({ ok: true, imageUrl: url }) + }) + + app.delete('/api/uses/:id/image', async (c) => { + const userId = requireUser(c, true) + if (userId instanceof Response) return userId + const v = await viewer(c) + const u = await loadUse(c, v) + if (u instanceof Response) return u + if (!canManageUse(v, u)) return jsonError(c, 403, 'You cannot change this use') + await c.var.ports.db + .update(schema.uses) + .set({ imageUrl: null, imageSource: null, updatedAt: new Date() }) + .where(eq(schema.uses.id, u.id)) + if (u.imageUrl && c.var.ports.publicAssets) + await deleteOwnedAvatar(c.var.ports.publicAssets, useImageOwner(u.id), u.imageUrl) + // Without an upload, the link's social image again, if it has one. + if (u.link) await c.var.ports.jobs.enqueue({ type: 'uses.socialImage', useId: u.id }) + return c.json({ ok: true }) + }) + + app.get('/api/collections/:owner/:slug/used-by', async (c) => { + const access = await requireCollection(c, 'read') + if (access instanceof Response) return access + const v = await viewer(c) + return c.json({ uses: await collectionUsedBy(c.var.ports.db, v, access.collection) }) + }) + + app.get('/api/accounts/:slug/used-by', async (c) => { + const org = await orgBySlug(c, c.req.param('slug')) + if (!org) return jsonError(c, 404, 'Organization not found') + const v = await viewer(c) + const list = await orgUsedBy(c.var.ports.db, v, org.id) + const views = await useViews(c.var.ports.db, v, list) + return c.json({ + uses: views, + pinned: pinnedAmong(org.pinnedUses, list).map((u) => u.id), + }) + }) + + app.get('/api/accounts/:slug/uses', async (c) => { + const org = await orgBySlug(c, c.req.param('slug')) + if (!org) return jsonError(c, 404, 'Organization not found') + const v = await viewer(c) + if (!v.roles.has(org.id)) return jsonError(c, 404, 'Organization not found') + const rows = await usesOfOrg(c.var.ports.db, org.id) + return c.json({ uses: await useViews(c.var.ports.db, v, rows) }) + }) + + app.put('/api/accounts/:slug/pinned-uses', async (c) => { + const userId = requireUser(c, true) + if (userId instanceof Response) return userId + const org = await orgBySlug(c, c.req.param('slug')) + if (!org) return jsonError(c, 404, 'Organization not found') + const v = await viewer(c) + if (!isAdmin(v.roles.get(org.id) ?? null)) + return jsonError(c, 403, "Must be an owner or admin to change the organization's page") + const body = ((await c.req.json().catch(() => null)) ?? {}) as Body + const pinned = body.pinned + if ( + !Array.isArray(pinned) || + pinned.length > MAX_PINNED_USES || + pinned.some((id) => typeof id !== 'string') || + new Set(pinned).size !== pinned.length + ) + return jsonError(c, 422, `pinned must be up to ${MAX_PINNED_USES} use ids`) + // Any use the org's page lists, as its members see it: other people's too. + const listed = new Set((await orgUsedBy(c.var.ports.db, v, org.id)).map((u) => u.id)) + if (pinned.some((id) => !listed.has(id as string))) + return jsonError( + c, + 422, + "pinned may name only uses built using this organization's collections", + ) + await c.var.ports.db + .update(schema.organization) + .set({ pinnedUses: pinned as string[] }) + .where(eq(schema.organization.id, org.id)) + return c.json({ ok: true, pinned }) + }) + + return app +} diff --git a/packages/server/src/app.ts b/packages/server/src/app.ts index 76e0fc0d..2e44b48a 100644 --- a/packages/server/src/app.ts +++ b/packages/server/src/app.ts @@ -28,6 +28,7 @@ import { schemaRoutes } from './api/schemas.js' import { statsRoutes } from './api/stats.js' import { syncRoutes } from './api/sync.js' import { uploadRoutes } from './api/uploads.js' +import { useRoutes } from './api/uses.js' import { versionRoutes } from './api/versions.js' import { webhookRoutes } from './api/webhooks.js' import type { Kf } from './auth/kf.js' @@ -366,6 +367,7 @@ export function createApp(setup: Setup) { app.route('/', schemaRoutes()) app.route('/', manageRoutes()) app.route('/', avatarRoutes()) + app.route('/', useRoutes()) app.route('/', locationRoutes()) // Before collectionRoutes: /api/accounts/me would match /api/accounts/:slug. app.route('/', accountRoutes()) diff --git a/packages/server/src/db/schema.ts b/packages/server/src/db/schema.ts index 49c699b1..1c52800d 100644 --- a/packages/server/src/db/schema.ts +++ b/packages/server/src/db/schema.ts @@ -161,6 +161,8 @@ export const organization = sqliteTable('organization', { provenanceNote: text('provenance_note'), /** Collection ids shown as large cards on the org's page, in order. */ pinned: json('pinned'), + /** Use ids shown under Used by in the page's sidebar, in order (org settings, Page). */ + pinnedUses: json('pinned_uses'), /** The org's own NAAN: its ARKs are minted under it, and its owners turn them on. */ arkNaan: text('ark_naan'), /** Set by a KF steward: the org's ARKs use KF's NAAN (`ARK_NAAN`). Without it or @@ -1145,6 +1147,77 @@ export const webhookDeliveries = sqliteTable( ], ) +// --- Uses ------------------------------------------------------------------------------ + +/** + * A use: something built using Underlay collections (a site, a tool, a book, a script), + * declared by a person and listed under the collections' Used by (used-by.md). Owned like an + * API key: made by a person, optionally for an org, and acting with the access of its + * manager, who is its maker until an org admin takes it over. No namespace, no storage. + */ +export const uses = sqliteTable( + 'uses', + { + id: id(), + /** Who declared it. Never changes. */ + madeBy: text('made_by').notNull(), + /** + * Whose access it follows: what it may list and which webhooks it gets. Its maker, until + * the maker leaves the org it's for and an admin takes it over. + */ + managedBy: text('managed_by').notNull(), + /** The org it's made for, if any; its admins manage it and its members see it. */ + organizationId: text('organization_id').references(() => organization.id, { + onDelete: 'cascade', + }), + name: text('name').notNull(), + description: text('description'), + link: text('link'), + /** The image shown: an upload, or the link's social image copied into the bucket. */ + imageUrl: text('image_url'), + imageSource: text('image_source', { enum: ['upload', 'link'] }), + /** When the link's social image was last looked for, found or not. */ + socialImageCheckedAt: ts('social_image_checked_at'), + public: bool('public').notNull().default(true), + /** Where it was declared: the form, a CLI script's header, or a site's meta tags. */ + declaredIn: text('declared_in', { enum: ['form', 'cli', 'meta'] }) + .notNull() + .default('form'), + /** Set when an admin took it over from a maker who left the org. */ + takenOverAt: ts('taken_over_at'), + createdAt: createdAt(), + updatedAt: ts('updated_at') + .notNull() + .$defaultFn(() => new Date()), + }, + (t) => [ + index('uses_made_by_idx').on(t.madeBy), + index('uses_managed_by_idx').on(t.managedBy), + index('uses_org_idx').on(t.organizationId), + ], +) + +/** The collections a use uses, and which kinds of their versions it wants webhooks for. */ +export const useCollections = sqliteTable( + 'use_collections', + { + useId: text('use_id') + .notNull() + .references(() => uses.id, { onDelete: 'cascade' }), + collectionId: text('collection_id') + .notNull() + .references(() => collections.id, { onDelete: 'cascade' }), + major: bool('major').notNull().default(false), + minor: bool('minor').notNull().default(false), + patch: bool('patch').notNull().default(false), + createdAt: createdAt(), + }, + (t) => [ + primaryKey({ columns: [t.useId, t.collectionId] }), + index('use_collections_collection_idx').on(t.collectionId), + ], +) + // --- ARKs, settings ------------------------------------------------------------------------ export const arkShoulders = sqliteTable('ark_shoulders', { diff --git a/packages/server/src/handlers.ts b/packages/server/src/handlers.ts index 410f5dc5..c098fa13 100644 --- a/packages/server/src/handlers.ts +++ b/packages/server/src/handlers.ts @@ -34,6 +34,7 @@ import * as schema from './db/schema.js' import './push/compact.js' import './push/parallel.js' import './refs/log.js' +import './uses/social-image.js' import { registerJob } from './jobs.js' import { recheckLocations } from './locations/locations.js' import { laggingPlacements, queueMirrors } from './locations/mirror.js' diff --git a/packages/server/src/lib/slug.ts b/packages/server/src/lib/slug.ts index b02889ef..c8eb1693 100644 --- a/packages/server/src/lib/slug.ts +++ b/packages/server/src/lib/slug.ts @@ -27,6 +27,7 @@ export const RESERVED_ORG_SLUGS = new Set([ 'settings', 'signup', 'superadmin', + 'uses', // Server routes and redirects. 'agent', 'api', diff --git a/packages/server/src/uses/social-image.ts b/packages/server/src/uses/social-image.ts new file mode 100644 index 00000000..e4837cb5 --- /dev/null +++ b/packages/server/src/uses/social-image.ts @@ -0,0 +1,211 @@ +/** + * A use's image from its link: the page's social image (`og:image`, else `twitter:image`), + * copied into the public assets bucket the way org logos are (lib/avatars.ts), so pages + * never load it from the use's site. + * + * This fetches an arbitrary URL from the server, so each hop is checked like a webhook URL + * (http or https, no local or private hosts; webhooks.ts validateWebhookUrl), redirects are + * followed by hand (at most 3, each checked), and the page and the image are capped in + * time and size. On Workers there is no private network to reach; on Node the deployment's + * outbound fetch refuses private addresses (Ports.outboundFetch). + * + * Runs as a job (`uses.socialImage`) after a use is declared or its link changes, so the + * form doesn't wait on someone else's site. + */ +import { and, eq, isNull, ne, or } from 'drizzle-orm' + +import * as schema from '../db/schema.js' +import { registerJob } from '../jobs.js' +import { deleteOwnedAvatar, sniffRaster } from '../lib/avatars.js' +import type { Ports } from '../ports.js' +import { validateWebhookUrl } from '../webhooks/webhooks.js' + +const TIMEOUT_MS = 5_000 +const MAX_HOPS = 3 +/** The head of a page is near its start; meta tags past this are ignored. */ +const MAX_HTML_BYTES = 512 * 1024 +export const MAX_SOCIAL_IMAGE_BYTES = 3 * 1024 * 1024 +const CACHE_CONTROL = 'public, max-age=31536000, immutable' +const USER_AGENT = 'Underlay-Link-Preview/1.0 (+https://www.underlay.org)' + +/** The bucket folder for a use's images: under `avatars/` so /img sizes them (api/images.ts). */ +export const useImageFolder = (useId: string) => `avatars/use-${useId}/` +/** The folder id deleteOwnedAvatar and /img take for a use. */ +export const useImageOwner = (useId: string) => `use-${useId}` + +class Refused extends Error {} + +/** + * Fetch a public http(s) URL, following up to MAX_HOPS redirects, each checked. Plain http + * is allowed: unlike a webhook, nothing secret is sent. + */ +async function fetchChecked( + ports: Ports, + raw: string, + accept: string, +): Promise<{ res: Response; url: string }> { + let url = raw + for (let hop = 0; hop <= MAX_HOPS; hop++) { + const check = validateWebhookUrl(url, true) + if (!check.ok) throw new Refused(check.reason.replace('Webhook URL', 'Link')) + const target = check.url + const res = await ports.outboundFetch(target, { + method: 'GET', + headers: { accept, 'user-agent': USER_AGENT }, + signal: AbortSignal.timeout(TIMEOUT_MS), + redirect: 'manual', + }) + if (res.status >= 300 && res.status < 400) { + const next = res.headers.get('location') + void res.body?.cancel().catch(() => {}) + if (!next) throw new Refused(`HTTP ${res.status} without a location`) + url = new URL(next, target).toString() + continue + } + if (!res.ok) { + void res.body?.cancel().catch(() => {}) + throw new Refused(`HTTP ${res.status}`) + } + return { res, url: target } + } + throw new Refused('Too many redirects') +} + +/** Up to `max` bytes of a body; more is cut off (`cut`) or refused (`refuse`). */ +async function readCapped( + res: Response, + max: number, + over: 'cut' | 'refuse', +): Promise> { + const reader = res.body?.getReader() + if (!reader) return new Uint8Array() + const parts: Uint8Array[] = [] + let size = 0 + for (;;) { + const { done, value } = await reader.read() + if (done) break + size += value.byteLength + if (size > max) { + void reader.cancel().catch(() => {}) + if (over === 'refuse') throw new Refused('Image too large') + parts.push(value.subarray(0, value.byteLength - (size - max))) + size = max + break + } + parts.push(value) + } + const out = new Uint8Array(size) + let at = 0 + for (const p of parts) { + out.set(p, at) + at += p.byteLength + } + return out +} + +const decodeEntities = (s: string) => + s + .replace(/&/g, '&') + .replace(/"/g, '"') + .replace(/'|'/g, "'") + .replace(/</g, '<') + .replace(/>/g, '>') + .replace(///gi, '/') + +/** + * The social image a page names in its meta tags, absolute, or null. A plain scan of + * `` tags, attribute order free; `og:image:secure_url` and `og:image` win over + * `twitter:image`. + */ +export function socialImageOf(html: string, pageUrl: string): string | null { + const found = new Map() + for (const tag of html.match(/]{0,2000}>/gi) ?? []) { + const attrs = new Map() + for (const m of tag.matchAll(/([a-zA-Z:-]+)\s*=\s*("([^"]*)"|'([^']*)'|([^\s"'>]+))/g)) { + attrs.set(m[1]!.toLowerCase(), decodeEntities(m[3] ?? m[4] ?? m[5] ?? '')) + } + const key = (attrs.get('property') ?? attrs.get('name') ?? '').toLowerCase() + const content = attrs.get('content')?.trim() + if (content && !found.has(key)) found.set(key, content) + } + for (const key of ['og:image:secure_url', 'og:image', 'og:image:url', 'twitter:image']) { + const v = found.get(key) + if (!v) continue + try { + const u = new URL(v, pageUrl) + if (u.protocol === 'https:' || u.protocol === 'http:') return u.toString() + } catch { + // Not a URL: try the next tag. + } + } + return null +} + +/** Fetch the link's social image and store it; null when there is none or it can't be had. */ +async function fetchSocialImage(ports: Ports, useId: string, link: string): Promise { + const assets = ports.publicAssets + if (!assets) return null + const { res: page, url: pageUrl } = await fetchChecked( + ports, + link, + 'text/html,application/xhtml+xml', + ) + const type = page.headers.get('content-type') ?? '' + if (!/html/i.test(type)) { + void page.body?.cancel().catch(() => {}) + return null + } + const html = new TextDecoder().decode(await readCapped(page, MAX_HTML_BYTES, 'cut')) + const imageUrl = socialImageOf(html, pageUrl) + if (!imageUrl) return null + const { res: img } = await fetchChecked(ports, imageUrl, 'image/*') + const bytes = await readCapped(img, MAX_SOCIAL_IMAGE_BYTES, 'refuse') + const raster = sniffRaster(bytes) + if (!raster) return null + const digest = new Uint8Array(await crypto.subtle.digest('SHA-256', bytes)) + const hash = [...digest].map((v) => v.toString(16).padStart(2, '0')).join('') + const key = `${useImageFolder(useId)}link-${hash}.${raster.ext}` + await assets.store.put(key, bytes, { contentType: raster.type, cacheControl: CACHE_CONTROL }) + return `${assets.baseUrl}/${key}` +} + +/** + * Look for the use's link's social image and keep it, unless someone uploaded one since. + * Records when it looked, found or not. + */ +export async function refreshSocialImage(ports: Ports, useId: string): Promise { + const { db } = ports + const [u] = await db.select().from(schema.uses).where(eq(schema.uses.id, useId)).limit(1) + if (!u || !u.link) return + let url: string | null = null + try { + url = await fetchSocialImage(ports, u.id, u.link) + } catch (err) { + if (!(err instanceof Refused) && !(err instanceof Error && /abort|timeout/i.test(err.name))) + console.error(`[uses] Social image for ${useId} failed:`, err) + } + // Only if the link is still the one fetched and nobody uploaded an image meanwhile. + const changed = await db + .update(schema.uses) + .set({ + socialImageCheckedAt: new Date(), + ...(url ? { imageUrl: url, imageSource: 'link' as const } : {}), + }) + .where( + and( + eq(schema.uses.id, u.id), + eq(schema.uses.link, u.link), + or(isNull(schema.uses.imageSource), ne(schema.uses.imageSource, 'upload')), + ), + ) + .returning({ id: schema.uses.id }) + const assets = ports.publicAssets + if (!assets || !url) return + if (changed.length === 0) { + await deleteOwnedAvatar(assets, useImageOwner(u.id), url) + } else if (u.imageUrl && u.imageUrl !== url) { + await deleteOwnedAvatar(assets, useImageOwner(u.id), u.imageUrl) + } +} + +registerJob('uses.socialImage', async (job, ports) => refreshSocialImage(ports, String(job.useId))) diff --git a/packages/server/src/uses/uses.ts b/packages/server/src/uses/uses.ts new file mode 100644 index 00000000..c746f75f --- /dev/null +++ b/packages/server/src/uses/uses.ts @@ -0,0 +1,348 @@ +/** + * Uses (planning: used-by.md): what a person declared they built using collections, and + * who may see and manage it. Owned like an API key: + * + * - Made by a person, always (`madeBy`), and optionally for an org (`organizationId`). + * - It follows its manager's access (`managedBy`: its maker, until an org admin takes it + * over). A use is listed under a collection only while its manager can read that + * collection, and its webhooks for a private collection stop when that access ends. + * Listing a collection grants nothing. + * - A private use shows only to its maker, or, made for an org, to that org's members. + * - A collection a use lists shows only to those who can read it; to anyone else it is + * "a private collection". + * + * Everything here is per viewer, so nothing is cached. + */ +import { and, eq, inArray, isNull, or } from 'drizzle-orm' + +import type { Principal } from '../api/access.js' +import { capRole, reachesOrg } from '../api/access.js' +import { chunks } from '../db/chunks.js' +import * as schema from '../db/schema.js' +import type { Db } from '../ports.js' + +export type Use = typeof schema.uses.$inferSelect +type Collection = typeof schema.collections.$inferSelect +type Org = typeof schema.organization.$inferSelect + +/** A use's name, description and link, in characters. */ +export const MAX_USE_NAME = 100 +export const MAX_USE_DESCRIPTION = 500 +export const MAX_USE_LINK = 500 +/** Collections one use may list. */ +export const MAX_USE_COLLECTIONS = 50 +/** Uses an org may pin under Used by on its page. */ +export const MAX_PINNED_USES = 8 + +export const BUMPS = ['major', 'minor', 'patch'] as const +export type Bump = (typeof BUMPS)[number] + +/** Who is looking: a person and their org roles, or nobody. */ +export interface Viewer { + userId: string | null + /** org id → role, for the orgs this caller acts in. */ + roles: Map +} + +export const anonymous: Viewer = { userId: null, roles: new Map() } + +/** + * The caller as a viewer of uses. A key confined to some collections sees what the public + * sees; a key made for one org acts in that org only, with its holder's role capped by + * its scope, as everywhere else. + */ +export async function viewerOf(db: Db, p: Principal | null): Promise { + if (!p) return anonymous + if (p.collectionIds) return { userId: null, roles: new Map() } + if (p.orgId) return { userId: null, roles: new Map([[p.orgId, capRole(p, 'owner')!]]) } + const rows = await db + .select({ org: schema.member.organizationId, role: schema.member.role }) + .from(schema.member) + .where(eq(schema.member.userId, p.userId)) + const roles = new Map() + for (const r of rows) if (reachesOrg(p, r.org)) roles.set(r.org, capRole(p, r.role)!) + return { userId: p.userId, roles } +} + +/** The roles of several people at once, for checking what each use's manager can read. */ +export async function rolesOf( + db: Db, + userIds: string[], +): Promise>> { + const out = new Map>() + for (const id of userIds) out.set(id, new Map()) + for (const part of chunks([...new Set(userIds)])) { + const rows = await db + .select({ + user: schema.member.userId, + org: schema.member.organizationId, + role: schema.member.role, + }) + .from(schema.member) + .where(inArray(schema.member.userId, part)) + for (const r of rows) out.get(r.user)?.set(r.org, r.role) + } + return out +} + +const isAdminRole = (role: string | undefined) => role === 'owner' || role === 'admin' + +/** Whether someone with these roles can read the collection. */ +export const canReadCollection = (roles: Map, c: Collection) => + !c.deletedAt && (c.public || roles.has(c.organizationId)) + +/** Whether the viewer sees the use at all. */ +export function canSeeUse(v: Viewer, u: Use): boolean { + if (u.public) return true + if (u.organizationId) return v.roles.has(u.organizationId) + return v.userId !== null && v.userId === u.madeBy +} + +/** + * Whether the viewer may edit or delete the use: its manager, and, for a use made for an + * org, that org's owners and admins. A manager who has left the org it's for no longer + * manages it: an admin takes it over (takeover.ts). + */ +export function canManageUse(v: Viewer, u: Use): boolean { + if (u.organizationId) { + const role = v.roles.get(u.organizationId) + if (isAdminRole(role)) return true + return v.userId === u.managedBy && role !== undefined + } + return v.userId !== null && v.userId === u.managedBy +} + +/** Whether a use made for an org has lost its manager (they left), so an admin should claim it. */ +export const needsClaim = (u: Use, managerRoles: Map | undefined) => + !!u.organizationId && !managerRoles?.has(u.organizationId) + +// --- The shape pages and the API show ---------------------------------------------------- + +export interface UseCollectionView { + /** null when the viewer can't read it: "a private collection". */ + owner: string | null + slug: string | null + name: string | null + public: boolean + major?: boolean + minor?: boolean + patch?: boolean +} + +export interface UseView { + id: string + name: string + description: string | null + link: string | null + imageUrl: string | null + imageSource: 'upload' | 'link' | null + public: boolean + declaredIn: 'form' | 'cli' | 'meta' + /** The org it's made for, if any. */ + org: { + slug: string + name: string + avatarUrl: string | null + coverColor: string | null + } | null + /** The person who declared it. */ + madeBy: { name: string } + collections: UseCollectionView[] + createdAt: Date + updatedAt: Date + /** The viewer may edit, delete and take it over. */ + canManage: boolean + /** Its maker left the org it's for: an admin should take it over (managers only). */ + needsClaim?: boolean + /** Who manages it now, when that isn't its maker (managers only). */ + managedBy?: { name: string } | null + takenOverAt?: Date | null + /** Per collection notify flags show only to managers. */ +} + +/** + * Uses as a viewer sees them: only those they may see, each with the collections it lists + * (those the viewer can't read as "a private collection") and, for managers, the notify + * flags and takeover state. Order follows `rows`. + */ +export async function useViews(db: Db, viewer: Viewer, rows: Use[]): Promise { + const seen = rows.filter((u) => canSeeUse(viewer, u)) + if (seen.length === 0) return [] + const ids = seen.map((u) => u.id) + + const links: { + useId: string + c: Collection + o: Org + major: boolean + minor: boolean + patch: boolean + }[] = [] + for (const part of chunks(ids)) { + links.push( + ...(await db + .select({ + useId: schema.useCollections.useId, + c: schema.collections, + o: schema.organization, + major: schema.useCollections.major, + minor: schema.useCollections.minor, + patch: schema.useCollections.patch, + }) + .from(schema.useCollections) + .innerJoin( + schema.collections, + eq(schema.collections.id, schema.useCollections.collectionId), + ) + .innerJoin( + schema.organization, + eq(schema.organization.id, schema.collections.organizationId), + ) + .where(inArray(schema.useCollections.useId, part))), + ) + } + const orgIds = [...new Set(seen.map((u) => u.organizationId).filter((x): x is string => !!x))] + const orgs = new Map() + for (const part of chunks(orgIds)) { + for (const o of await db + .select() + .from(schema.organization) + .where(inArray(schema.organization.id, part))) + orgs.set(o.id, o) + } + const people = [...new Set(seen.flatMap((u) => [u.madeBy, u.managedBy]))] + const names = new Map() + for (const part of chunks(people)) { + for (const p of await db + .select({ id: schema.user.id, name: schema.user.name }) + .from(schema.user) + .where(inArray(schema.user.id, part))) + names.set(p.id, p.name) + } + const managed = seen.filter((u) => canManageUse(viewer, u)) + const managerRoles = managed.length + ? await rolesOf( + db, + managed.map((u) => u.managedBy), + ) + : new Map>() + + return seen.map((u) => { + const manage = canManageUse(viewer, u) + const collections = links + .filter((l) => l.useId === u.id && !l.c.deletedAt) + .sort((a, b) => a.c.slug.localeCompare(b.c.slug)) + .map((l): UseCollectionView => { + const flags = manage ? { major: l.major, minor: l.minor, patch: l.patch } : {} + return canReadCollection(viewer.roles, l.c) + ? { owner: l.o.slug, slug: l.c.slug, name: l.c.name, public: l.c.public, ...flags } + : { owner: null, slug: null, name: null, public: false } + }) + const org = u.organizationId ? orgs.get(u.organizationId) : undefined + return { + id: u.id, + name: u.name, + description: u.description, + link: u.link, + imageUrl: u.imageUrl, + imageSource: u.imageSource, + public: u.public, + declaredIn: u.declaredIn, + org: org + ? { slug: org.slug, name: org.name, avatarUrl: org.avatarUrl, coverColor: org.coverColor } + : null, + madeBy: { name: names.get(u.madeBy) ?? 'Someone' }, + collections, + createdAt: u.createdAt, + updatedAt: u.updatedAt, + canManage: manage, + ...(manage + ? { + needsClaim: needsClaim(u, managerRoles.get(u.managedBy)), + managedBy: + u.managedBy === u.madeBy ? null : { name: names.get(u.managedBy) ?? 'Someone' }, + takenOverAt: u.takenOverAt, + } + : {}), + } + }) +} + +// --- Used by ------------------------------------------------------------------------------- + +/** + * The uses listed under some collections, as the viewer may see them: each use the viewer + * can see, that lists at least one of `collections` that both the viewer and the use's + * manager can read. Newest first. + */ +async function usedByAmong(db: Db, viewer: Viewer, collections: Collection[]): Promise { + const readable = collections.filter((c) => canReadCollection(viewer.roles, c)) + if (readable.length === 0) return [] + const byId = new Map(readable.map((c) => [c.id, c])) + const pairs: { u: Use; collectionId: string }[] = [] + for (const part of chunks(readable.map((c) => c.id))) { + pairs.push( + ...(await db + .select({ u: schema.uses, collectionId: schema.useCollections.collectionId }) + .from(schema.useCollections) + .innerJoin(schema.uses, eq(schema.uses.id, schema.useCollections.useId)) + .where(inArray(schema.useCollections.collectionId, part))), + ) + } + const visible = pairs.filter((p) => canSeeUse(viewer, p.u)) + if (visible.length === 0) return [] + const managers = await rolesOf( + db, + visible.map((p) => p.u.managedBy), + ) + const out = new Map() + for (const p of visible) { + const c = byId.get(p.collectionId)! + if (canReadCollection(managers.get(p.u.managedBy) ?? new Map(), c)) out.set(p.u.id, p.u) + } + return [...out.values()].sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime()) +} + +/** Uses listed under one collection (its Used by tab). */ +export async function collectionUsedBy(db: Db, viewer: Viewer, c: Collection): Promise { + return useViews(db, viewer, await usedByAmong(db, viewer, [c])) +} + +/** How many uses its Used by tab lists, for the tab's count. */ +export async function collectionUsedByCount(db: Db, viewer: Viewer, c: Collection) { + return (await usedByAmong(db, viewer, [c])).length +} + +/** + * Everything built using an org's collections, as the viewer may see it: the org's own + * uses, other people's, and private ones for members. A use made for the org that lists + * only other orgs' collections isn't here (it's in Our uses). + */ +export async function orgUsedBy(db: Db, viewer: Viewer, orgId: string): Promise { + const cs = await db + .select() + .from(schema.collections) + .where(and(eq(schema.collections.organizationId, orgId), isNull(schema.collections.deletedAt))) + return usedByAmong(db, viewer, cs) +} + +/** The org's pins, in its order, that this viewer sees in its Used by list. */ +export function pinnedAmong(pins: string[] | null, list: Use[]): Use[] { + const byId = new Map(list.map((u) => [u.id, u])) + return (pins ?? []).map((id) => byId.get(id)).filter((u): u is Use => !!u) +} + +/** Uses a person made or manages (My uses), newest first. */ +export async function usesOfPerson(db: Db, userId: string): Promise { + const rows = await db + .select() + .from(schema.uses) + .where(or(eq(schema.uses.madeBy, userId), eq(schema.uses.managedBy, userId))) + return rows.sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime()) +} + +/** Uses made for an org (Our uses), newest first. */ +export async function usesOfOrg(db: Db, orgId: string): Promise { + const rows = await db.select().from(schema.uses).where(eq(schema.uses.organizationId, orgId)) + return rows.sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime()) +} diff --git a/packages/server/test/uses.test.ts b/packages/server/test/uses.test.ts new file mode 100644 index 00000000..a36bf1b2 --- /dev/null +++ b/packages/server/test/uses.test.ts @@ -0,0 +1,353 @@ +import { memoryStore } from '@underlay/protocol' +import { eq } from 'drizzle-orm' +import { afterAll, describe, expect, it } from 'vitest' + +import * as schema from '../src/db/schema.js' +import { socialImageOf } from '../src/uses/social-image.js' +import { cleanup, harness, outboundCalls, respondOutbound } from './harness.js' + +afterAll(cleanup) + +async function json(res: Response) { + return (await res.json()) as any +} + +/** + * Org `org` (u1 its owner) with a public collection `pub` and a private one `priv`; org + * `other` (u2 its owner, u3 a member) with a public collection `theirs`; u4 in no org. + */ +async function world() { + const h = await harness() + const { db } = h.ports + await h.member('u1') + const pub = await h.collection('pub') + const priv = await h.collection('priv') + await db.update(schema.collections).set({ public: true }).where(eq(schema.collections.id, pub.id)) + await db.insert(schema.user).values([ + { id: 'u2', name: 'Ana Ruiz', email: 'u2@example.org' }, + { id: 'u3', name: 'Sam Okafor', email: 'u3@example.org' }, + { id: 'u4', name: 'Kim Lee', email: 'u4@example.org' }, + ]) + await db.insert(schema.organization).values({ id: 'org2', name: 'Other Lab', slug: 'other' }) + await db.insert(schema.member).values([ + { organizationId: 'org2', userId: 'u2', role: 'owner' }, + { organizationId: 'org2', userId: 'u3', role: 'member' }, + ]) + const [theirs] = await db + .insert(schema.collections) + .values({ + organizationId: 'org2', + slug: 'theirs', + name: 'Theirs', + public: true, + privateSalt: '00', + }) + .returning() + const declare = async (user: string, body: Record) => + h.request('/api/uses', { method: 'POST', user, json: body }) + return { h, db, pub, priv, theirs: theirs!, declare } +} + +describe('uses', () => { + it('declares a use and lists it under the collections it uses', async () => { + const { h, declare } = await world() + let res = await declare('u4', { + name: 'Tidal Field Guide', + description: 'A field guide', + link: 'https://books.example.org/guide', + collections: [{ collection: 'org/pub', major: true }, 'other/theirs'], + }) + expect(res.status).toBe(201) + const use = await json(res) + expect(use).toMatchObject({ + name: 'Tidal Field Guide', + public: true, + org: null, + madeBy: { name: 'Kim Lee' }, + canManage: true, + }) + expect(use.collections).toEqual([ + { + owner: 'org', + slug: 'pub', + name: 'pub', + public: true, + major: true, + minor: false, + patch: false, + }, + { + owner: 'other', + slug: 'theirs', + name: 'Theirs', + public: true, + major: false, + minor: false, + patch: false, + }, + ]) + + // Anyone sees it on each collection's Used by and the orgs' pages, without the flags. + const listed = await json(await h.request('/api/collections/org/pub/used-by')) + expect(listed.uses.map((u: any) => u.name)).toEqual(['Tidal Field Guide']) + expect(listed.uses[0].canManage).toBe(false) + expect(listed.uses[0].collections[0]).not.toHaveProperty('major') + expect((await json(await h.request('/api/accounts/other/used-by'))).uses).toHaveLength(1) + expect((await json(await h.request('/api/collections/org/pub'))).usedBy).toBe(1) + + // Its page, and My uses. + expect((await json(await h.request(`/api/uses/${use.id}`))).name).toBe('Tidal Field Guide') + expect((await json(await h.request('/api/uses', { user: 'u4' }))).uses).toHaveLength(1) + expect((await h.request('/api/uses')).status).toBe(401) + }) + + it('lists only collections the maker can read, and hides private ones from others', async () => { + const { h, declare } = await world() + // Unknown and private read the same to someone outside the org. + for (const name of ['org/priv', 'org/nope']) { + const res = await declare('u4', { name: 'X', collections: [name] }) + expect(res.status).toBe(422) + expect((await json(res)).error).toBe(`No collection ${name} that you can read`) + } + expect((await declare('u4', { name: 'X', collections: [] })).status).toBe(422) + expect((await declare('u4', { name: '', collections: ['org/pub'] })).status).toBe(422) + expect( + (await declare('u4', { name: 'X', link: 'javascript:alert(1)', collections: ['org/pub'] })) + .status, + ).toBe(422) + + // A member may list the private one; a public use shows it to outsiders as private. + const res = await declare('u1', { + name: 'Public filter', + collections: ['org/priv', 'org/pub'], + }) + expect(res.status).toBe(201) + const anon = await json(await h.request('/api/accounts/org/used-by')) + expect(anon.uses).toHaveLength(1) + expect(anon.uses[0].collections).toEqual([ + { owner: null, slug: null, name: null, public: false }, + { owner: 'org', slug: 'pub', name: 'pub', public: true }, + ]) + const member = await json(await h.request('/api/accounts/org/used-by', { user: 'u1' })) + expect(member.uses[0].collections.map((c: any) => c.slug)).toEqual(['priv', 'pub']) + + // One that lists only the private collection isn't on the org's page for outsiders. + await declare('u1', { name: 'Internal only', collections: ['org/priv'] }) + expect((await json(await h.request('/api/accounts/org/used-by'))).uses).toHaveLength(1) + expect( + (await json(await h.request('/api/accounts/org/used-by', { user: 'u1' }))).uses, + ).toHaveLength(2) + }) + + it('shows private uses only to their maker or the org they are for', async () => { + const { h, declare } = await world() + const mine = await json( + await declare('u4', { name: 'Notebook', public: false, collections: ['org/pub'] }), + ) + const ours = await json( + await declare('u2', { + name: 'Review tool', + public: false, + org: 'other', + collections: ['org/pub', 'other/theirs'], + }), + ) + expect(ours.org).toMatchObject({ slug: 'other', name: 'Other Lab' }) + const names = async (user?: string) => + ( + await json(await h.request('/api/collections/org/pub/used-by', user ? { user } : {})) + ).uses.map((u: any) => u.name) + expect(await names()).toEqual([]) + expect(await names('u4')).toEqual(['Notebook']) + expect(await names('u3')).toEqual(['Review tool']) + expect((await h.request(`/api/uses/${mine.id}`, { user: 'u1' })).status).toBe(404) + expect((await h.request(`/api/uses/${ours.id}`, { user: 'u3' })).status).toBe(200) + + // Our uses: the org's members see the org's. + expect( + (await json(await h.request('/api/accounts/other/uses', { user: 'u3' }))).uses, + ).toHaveLength(1) + expect((await h.request('/api/accounts/other/uses', { user: 'u4' })).status).toBe(404) + // Only the org's admins (and the maker) may make one for it. + expect( + (await declare('u3', { name: 'Y', org: 'other', collections: ['org/pub'] })).status, + ).toBe(403) + }) + + it('lets the manager and the org admins edit it, and nobody else', async () => { + const { h, db, declare } = await world() + // u2 makes one for their org; u3 is a member there, not an admin. + await db.update(schema.member).set({ role: 'admin' }).where(eq(schema.member.userId, 'u3')) + const ours = await json( + await declare('u3', { name: 'Atlas', org: 'other', collections: ['other/theirs'] }), + ) + await db.update(schema.member).set({ role: 'member' }).where(eq(schema.member.userId, 'u3')) + const patch = (user: string, body: Record) => + h.request(`/api/uses/${ours.id}`, { method: 'PATCH', user, json: body }) + // Its maker, a member still, manages it; the org's owner does too; others can't. + expect((await patch('u3', { name: 'Shoreline Atlas' })).status).toBe(200) + expect((await patch('u2', { description: 'A map' })).status).toBe(200) + expect((await patch('u4', { name: 'Mine now' })).status).toBe(403) + expect((await patch('u1', { name: 'Mine now' })).status).toBe(403) + // Only its maker may take it out of the org. + expect((await patch('u2', { org: null })).status).toBe(403) + const got = await json(await h.request(`/api/uses/${ours.id}`)) + expect(got).toMatchObject({ name: 'Shoreline Atlas', description: 'A map' }) + + // Collections and flags are replaced as given. + const res = await patch('u2', { collections: [{ collection: 'org/pub', minor: true }] }) + expect((await json(res)).collections).toEqual([ + { + owner: 'org', + slug: 'pub', + name: 'pub', + public: true, + major: false, + minor: true, + patch: false, + }, + ]) + expect((await json(await h.request('/api/accounts/other/used-by'))).uses).toHaveLength(0) + + expect((await h.request(`/api/uses/${ours.id}`, { method: 'DELETE', user: 'u4' })).status).toBe( + 403, + ) + expect((await h.request(`/api/uses/${ours.id}`, { method: 'DELETE', user: 'u2' })).status).toBe( + 200, + ) + expect((await h.request(`/api/uses/${ours.id}`)).status).toBe(404) + }) + + it("drops a use from a private collection's Used by when its manager loses access", async () => { + const { h, db, declare } = await world() + await db.insert(schema.member).values({ organizationId: 'org1', userId: 'u4', role: 'member' }) + await declare('u4', { name: 'Script', collections: ['org/priv', 'org/pub'] }) + const names = async (path: string) => + (await json(await h.request(path, { user: 'u1' }))).uses.map((u: any) => u.name) + expect(await names('/api/collections/org/priv/used-by')).toEqual(['Script']) + await db.delete(schema.member).where(eq(schema.member.userId, 'u4')) + expect(await names('/api/collections/org/priv/used-by')).toEqual([]) + // Still listed where it uses a public collection. + expect(await names('/api/collections/org/pub/used-by')).toEqual(['Script']) + }) + + it("pins uses on the org's page, in order", async () => { + const { h, declare } = await world() + const a = await json(await declare('u4', { name: 'A', collections: ['org/pub'] })) + const b = await json(await declare('u1', { name: 'B', org: 'org', collections: ['org/pub'] })) + const elsewhere = await json(await declare('u2', { name: 'C', collections: ['other/theirs'] })) + const pin = (user: string, pinned: unknown) => + h.request('/api/accounts/org/pinned-uses', { method: 'PUT', user, json: { pinned } }) + expect((await pin('u4', [a.id])).status).toBe(403) + expect((await pin('u1', [elsewhere.id])).status).toBe(422) + expect((await pin('u1', [a.id, a.id])).status).toBe(422) + expect((await pin('u1', [b.id, a.id])).status).toBe(200) + expect((await json(await h.request('/api/accounts/org/used-by'))).pinned).toEqual([b.id, a.id]) + // A deleted one drops out. + await h.request(`/api/uses/${a.id}`, { method: 'DELETE', user: 'u4' }) + expect((await json(await h.request('/api/accounts/org/used-by'))).pinned).toEqual([b.id]) + }) +}) + +describe("a use's image", () => { + it('reads og:image and twitter:image, relative or absolute', () => { + expect( + socialImageOf( + ``, + 'https://site.example.org/a/b', + ), + ).toBe('https://site.example.org/card.png') + expect( + socialImageOf( + ``, + 'https://s.org', + ), + ).toBe('https://x.org/t.png?a=1&b=2') + expect( + socialImageOf(``, 'https://s.org'), + ).toBe(null) + expect(socialImageOf('none', 'https://s.org')).toBe(null) + }) + + it("copies the link's social image into the bucket, and an upload replaces it", async () => { + const { h, declare } = await world() + const assets = { store: memoryStore(), baseUrl: 'https://assets.test' } + h.ports.publicAssets = assets + const png = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 1, 2, 3]) + outboundCalls.length = 0 + respondOutbound((url) => { + if (url === 'https://atlas.example.org/') + return new Response(null, { status: 301, headers: { location: '/home' } }) + if (url === 'https://atlas.example.org/home') + return new Response('', { + headers: { 'content-type': 'text/html; charset=utf-8' }, + }) + if (url === 'https://atlas.example.org/card.png') + return new Response(png, { headers: { 'content-type': 'image/png' } }) + return new Response('no', { status: 404 }) + }) + const use = await json( + await declare('u4', { + name: 'Atlas', + link: 'https://atlas.example.org/', + collections: ['org/pub'], + }), + ) + await h.drain() + let got = await json(await h.request(`/api/uses/${use.id}`)) + expect(got.imageSource).toBe('link') + expect(got.imageUrl).toMatch( + new RegExp(`^https://assets\\.test/avatars/use-${use.id}/link-[0-9a-f]{64}\\.png$`), + ) + + // An upload wins, and the copied image is deleted. + const form = new FormData() + form.append('file', new File([png], 'x.png', { type: 'image/png' })) + const res = await h.request(`/api/uses/${use.id}/image`, { + method: 'POST', + user: 'u4', + body: form, + }) + expect(res.status).toBe(200) + got = await json(await h.request(`/api/uses/${use.id}`)) + expect(got.imageSource).toBe('upload') + const keys: string[] = [] + for await (const k of (await import('@underlay/protocol')).listAll(assets.store, 'avatars/')) + keys.push(k) + expect(keys).toHaveLength(1) + expect(keys[0]).not.toContain('/link-') + + // Deleting the use deletes its images. + await h.request(`/api/uses/${use.id}`, { method: 'DELETE', user: 'u4' }) + const left: string[] = [] + for await (const k of (await import('@underlay/protocol')).listAll(assets.store, 'avatars/')) + left.push(k) + expect(left).toEqual([]) + }) + + it('never fetches a local or private address', async () => { + const { h, db, declare } = await world() + h.ports.publicAssets = { store: memoryStore(), baseUrl: 'https://assets.test' } + outboundCalls.length = 0 + respondOutbound( + () => new Response(null, { status: 302, headers: { location: 'http://169.254.169.254/' } }), + ) + const a = await json( + await declare('u4', { name: 'A', link: 'https://10.0.0.8/', collections: ['org/pub'] }), + ) + const b = await json( + await declare('u4', { + name: 'B', + link: 'https://redirects.example.org/', + collections: ['org/pub'], + }), + ) + await h.drain() + expect(outboundCalls.map((c) => c.url)).toEqual(['https://redirects.example.org/']) + for (const id of [a.id, b.id]) { + const [row] = await db.select().from(schema.uses).where(eq(schema.uses.id, id)) + expect(row!.imageUrl).toBe(null) + expect(row!.socialImageCheckedAt).not.toBe(null) + } + }) +}) From 467b7ec5c8a20399c8a97cb341885e272fd15e1d Mon Sep 17 00:00:00 2001 From: Travis Rich Date: Mon, 30 Nov 2026 23:15:14 -0500 Subject: [PATCH 2/4] Add Used by pages, use form, My uses, and Our uses --- packages/server/src/api/uses.ts | 15 + packages/server/test/uses.test.ts | 34 ++ packages/web/scripts/ssr-smoke.ts | 104 +++++ packages/web/src/components/CreateMenu.tsx | 7 + .../web/src/components/SettingsLayout.tsx | 16 + packages/web/src/components/UseForm.tsx | 404 ++++++++++++++++++ .../web/src/components/UsePinsSettings.tsx | 180 ++++++++ packages/web/src/components/UserMenu.tsx | 7 + .../web/src/components/UsesSettingsList.tsx | 103 +++++ .../web/src/components/collection-nav.tsx | 18 +- packages/web/src/components/org-page.tsx | 62 ++- packages/web/src/components/uses.tsx | 372 ++++++++++++++++ .../routes/[owner]/[collection]/assets.tsx | 1 + .../src/routes/[owner]/[collection]/index.tsx | 1 + .../routes/[owner]/[collection]/records.tsx | 1 + .../routes/[owner]/[collection]/schemas.tsx | 1 + .../[owner]/[collection]/used-by.data.ts | 19 + .../routes/[owner]/[collection]/used-by.tsx | 45 ++ .../[owner]/[collection]/v/[n]/assets.tsx | 1 + .../[owner]/[collection]/v/[n]/index.tsx | 1 + .../[owner]/[collection]/v/[n]/records.tsx | 1 + .../v/[n]/records/[type]/[id].tsx | 1 + .../[owner]/[collection]/v/[n]/schemas.tsx | 1 + .../routes/[owner]/[collection]/versions.tsx | 1 + .../[owner]/[collection]/versions/compare.tsx | 1 + packages/web/src/routes/[owner]/index.data.ts | 8 +- packages/web/src/routes/[owner]/index.tsx | 34 +- .../src/routes/[owner]/settings/page.data.ts | 5 +- .../web/src/routes/[owner]/settings/page.tsx | 8 +- .../src/routes/[owner]/settings/uses.data.ts | 18 + .../web/src/routes/[owner]/settings/uses.tsx | 45 ++ packages/web/src/routes/settings/uses.data.ts | 13 + packages/web/src/routes/settings/uses.tsx | 19 + packages/web/src/routes/uses/[id].data.ts | 18 + packages/web/src/routes/uses/[id].tsx | 160 +++++++ .../web/src/routes/uses/[id]/edit.data.ts | 20 + packages/web/src/routes/uses/[id]/edit.tsx | 34 ++ packages/web/src/routes/uses/new.data.ts | 34 ++ packages/web/src/routes/uses/new.tsx | 23 + 39 files changed, 1828 insertions(+), 8 deletions(-) create mode 100644 packages/web/src/components/UseForm.tsx create mode 100644 packages/web/src/components/UsePinsSettings.tsx create mode 100644 packages/web/src/components/UsesSettingsList.tsx create mode 100644 packages/web/src/components/uses.tsx create mode 100644 packages/web/src/routes/[owner]/[collection]/used-by.data.ts create mode 100644 packages/web/src/routes/[owner]/[collection]/used-by.tsx create mode 100644 packages/web/src/routes/[owner]/settings/uses.data.ts create mode 100644 packages/web/src/routes/[owner]/settings/uses.tsx create mode 100644 packages/web/src/routes/settings/uses.data.ts create mode 100644 packages/web/src/routes/settings/uses.tsx create mode 100644 packages/web/src/routes/uses/[id].data.ts create mode 100644 packages/web/src/routes/uses/[id].tsx create mode 100644 packages/web/src/routes/uses/[id]/edit.data.ts create mode 100644 packages/web/src/routes/uses/[id]/edit.tsx create mode 100644 packages/web/src/routes/uses/new.data.ts create mode 100644 packages/web/src/routes/uses/new.tsx diff --git a/packages/server/src/api/uses.ts b/packages/server/src/api/uses.ts index 5b909510..303d357f 100644 --- a/packages/server/src/api/uses.ts +++ b/packages/server/src/api/uses.ts @@ -283,6 +283,21 @@ export function useRoutes() { const r = await resolveCollections(c, v, body.collections) if (r instanceof Response) return r cols = r + // Collections the editor can't read stay as they were: an org admin editing a use + // can't see, and so mustn't drop, a private collection elsewhere that its maker listed. + const kept = await c.var.ports.db + .select({ l: schema.useCollections, c: schema.collections }) + .from(schema.useCollections) + .innerJoin( + schema.collections, + eq(schema.collections.id, schema.useCollections.collectionId), + ) + .where(eq(schema.useCollections.useId, u.id)) + for (const k of kept) + if (!canReadCollection(v.roles, k.c) && !r.has(k.c.id)) + r.set(k.c.id, { major: k.l.major, minor: k.l.minor, patch: k.l.patch }) + if (r.size > MAX_USE_COLLECTIONS) + return jsonError(c, 422, `A use may list at most ${MAX_USE_COLLECTIONS} collections`) } if (Object.keys(set).length) await c.var.ports.db diff --git a/packages/server/test/uses.test.ts b/packages/server/test/uses.test.ts index a36bf1b2..4948ea70 100644 --- a/packages/server/test/uses.test.ts +++ b/packages/server/test/uses.test.ts @@ -231,6 +231,40 @@ describe('uses', () => { expect(await names('/api/collections/org/pub/used-by')).toEqual(['Script']) }) + it("keeps collections an editor can't read when they change the list", async () => { + const { h, db, declare } = await world() + // A use for `other`, made by u1 (in both orgs), listing org's private collection; u4, + // an admin of `other` only, edits it. + await db.insert(schema.member).values({ organizationId: 'org2', userId: 'u1', role: 'member' }) + const use = await json( + await declare('u2', { + name: 'Bridge', + org: 'other', + collections: ['other/theirs', { collection: 'org/pub', major: true }], + }), + ) + await db.insert(schema.member).values({ organizationId: 'org2', userId: 'u4', role: 'admin' }) + await db + .update(schema.uses) + .set({ managedBy: 'u1', madeBy: 'u1' }) + .where(eq(schema.uses.id, use.id)) + let res = await h.request(`/api/uses/${use.id}`, { + method: 'PATCH', + user: 'u1', + json: { collections: ['org/priv', 'other/theirs', { collection: 'org/pub', major: true }] }, + }) + expect(res.status).toBe(200) + // u4 (an admin of other, not of org) sees org/priv as private, and edits the list. + res = await h.request(`/api/uses/${use.id}`, { + method: 'PATCH', + user: 'u4', + json: { collections: ['other/theirs'] }, + }) + expect(res.status).toBe(200) + const after = await json(await h.request(`/api/uses/${use.id}`, { user: 'u1' })) + expect(after.collections.map((c: any) => c.slug)).toEqual(['priv', 'theirs']) + }) + it("pins uses on the org's page, in order", async () => { const { h, declare } = await world() const a = await json(await declare('u4', { name: 'A', collections: ['org/pub'] })) diff --git a/packages/web/scripts/ssr-smoke.ts b/packages/web/scripts/ssr-smoke.ts index 134b7377..db68115f 100644 --- a/packages/web/scripts/ssr-smoke.ts +++ b/packages/web/scripts/ssr-smoke.ts @@ -200,6 +200,45 @@ try { const { avatarUrl } = (await res.json()) as { avatarUrl: string } console.log(`uploaded a logo: ${avatarUrl}\n`) + // --- Two uses: a public one listing org/authors and the private collection, and a + // private one made for the org. + const declare = async (user: string, body: Record) => { + const r = await call( + '/api/uses', + { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify(body), + }, + user, + ) + if (r.status !== 201) throw new Error(`declare use: ${r.status} ${await r.text()}`) + return ((await r.json()) as { id: string }).id + } + const atlasId = await declare('u1', { + name: 'Authors Atlas', + description: 'Every author on a map.', + link: 'https://atlas.example.org/', + collections: ['org/authors', 'org/secret'], + }) + const toolId = await declare('u1', { + name: 'Review Tool', + public: false, + org: 'org', + collections: ['org/secret'], + }) + res = await call( + '/api/accounts/org/pinned-uses', + { + method: 'PUT', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ pinned: [toolId, atlasId] }), + }, + 'u1', + ) + if (res.status !== 200) throw new Error(`pin uses: ${res.status} ${await res.text()}`) + console.log('declared two uses\n') + // --- Pages. // A record hash and a schema id, for the provenance and schema pages. const page = (await (await call(`${base}/versions/latest/records?type=Author`)).json()) as { @@ -309,6 +348,71 @@ try { location: '/org/authors/v/1.0.0/assets', }, { path: '/org', status: 200, has: ['Smoke Org', 'authors'], lacks: ['secret'] }, + // Uses: the org's sidebar, its Used by tab, the collection's, a use's page, the form. + { + path: '/org', + status: 200, + has: ['Used by', 'Authors Atlas', 'All 1', 'Declare new use'], + lacks: ['Review Tool', 'Edit pins'], + }, + { + path: '/org', + status: 200, + has: ['Review Tool', 'Authors Atlas', 'All 2', 'Edit pins'], + user: 'u1', + }, + { + path: '/org?tab=used-by', + status: 200, + has: [ + 'Smoke Org's collections', + 'Authors Atlas', + 'atlas.example.org', + 'a private collection', + ], + lacks: ['Review Tool', 'org/secret'], + }, + { + path: '/org/authors/used-by', + status: 200, + has: [ + 'Used by — org/authors', + 'Built using this collection', + 'Authors Atlas', + 'Use this collection', + ], + }, + { + path: `/uses/${atlasId}`, + status: 200, + has: ['Authors Atlas', 'Every author on a map.', 'Ada', 'org/authors'], + lacks: ['>Edit<'], + }, + { path: `/uses/${atlasId}`, status: 200, has: ['>Edit<', 'org/secret'], user: 'u1' }, + { path: `/uses/${toolId}`, status: 404 }, + { path: `/uses/${toolId}`, status: 200, has: ['Review Tool', 'Private'], user: 'u2' }, + { + path: '/uses/new?collection=org/authors', + status: 200, + has: ['Declare new use', 'org/authors'], + user: 'u1', + }, + { path: '/uses/new', status: 302, location: '/login' }, + { path: `/uses/${atlasId}/edit`, status: 200, has: ['Edit use', 'Authors Atlas'], user: 'u1' }, + { path: `/uses/${atlasId}/edit`, status: 404, user: 'u2' }, + { + path: '/settings/uses', + status: 200, + has: ['My uses', 'Authors Atlas', 'Review Tool'], + user: 'u1', + }, + { path: '/org/settings/uses', status: 200, has: ['Our uses', 'Review Tool'], user: 'u1' }, + { + path: '/org/settings/page', + status: 200, + has: ['Pinned under Used by', 'Review Tool'], + user: 'u1', + }, { path: `/records/${adaHash}`, status: 200, has: ['Ada Lovelace', 'org/authors'] }, { path: '/records/abc123', status: 404 }, { path: `/schemas/${schemaId}`, status: 200, has: ['born', 'org/authors'] }, diff --git a/packages/web/src/components/CreateMenu.tsx b/packages/web/src/components/CreateMenu.tsx index ce926712..a7b557fc 100644 --- a/packages/web/src/components/CreateMenu.tsx +++ b/packages/web/src/components/CreateMenu.tsx @@ -40,6 +40,13 @@ export default function CreateMenu() { > New organization + setOpen(false)} + className="text-ink hover:bg-parchment-dark block px-3 py-2 text-sm transition-colors" + > + Declare new use + )} diff --git a/packages/web/src/components/SettingsLayout.tsx b/packages/web/src/components/SettingsLayout.tsx index 9fa91d3c..66b5b981 100644 --- a/packages/web/src/components/SettingsLayout.tsx +++ b/packages/web/src/components/SettingsLayout.tsx @@ -2,6 +2,7 @@ import { useEffect, useState } from 'react' import { Link, useLocation } from 'react-router' import BaseLayout from '~/components/BaseLayout' +import { useAppContext } from '~/lib/app-context' /** * Shared shell for every settings surface (user, org, collection): a sticky @@ -18,6 +19,8 @@ export interface SettingsRailItem { danger?: boolean /** Also active on paths below `to`. */ prefix?: boolean + /** Shown only to this org's owners and admins (and KF stewards). */ + adminOf?: string } export interface SettingsRailGroup { @@ -40,6 +43,7 @@ export const userSettingsRail: SettingsRailGroup[] = [ { label: 'Profile', to: '/settings' }, { label: 'API keys', to: '/settings/keys' }, { label: 'Sessions', to: '/settings/sessions' }, + { label: 'My uses', to: '/settings/uses' }, ], }, ] @@ -53,6 +57,7 @@ export function orgSettingsRail(owner: string): SettingsRailGroup[] { { label: 'Page', to: `/${owner}/settings/page` }, { label: 'Members', to: `/${owner}/settings/members` }, { label: 'Storage', to: `/${owner}/settings/storage` }, + { label: 'Our uses', to: `/${owner}/settings/uses`, adminOf: owner }, ], }, { @@ -130,6 +135,17 @@ export default function SettingsLayout({ children: React.ReactNode }) { const location = useLocation() + const { currentUser } = useAppContext() + const adminOf = (slug: string) => + currentUser?.kfRole === 'admin' || + !!currentUser?.orgs?.some( + (o: { slug: string; role: string }) => + o.slug === slug && (o.role === 'owner' || o.role === 'admin'), + ) + groups = groups.map((g) => ({ + ...g, + items: g.items.filter((i) => !i.adminOf || adminOf(i.adminOf)), + })) const anchorIds = groups.flatMap((g) => g.items.filter((i) => i.to.startsWith('#')).map((i) => i.to.slice(1)), ) diff --git a/packages/web/src/components/UseForm.tsx b/packages/web/src/components/UseForm.tsx new file mode 100644 index 00000000..8cf8186f --- /dev/null +++ b/packages/web/src/components/UseForm.tsx @@ -0,0 +1,404 @@ +/** + * Declare new use, and edit one: name, link, description, image, public or private, who + * it's for, and the collections it uses (planning: used-by.md). + */ +import { useEffect, useMemo, useState } from 'react' +import { useNavigate } from 'react-router' + +import { Alert, Button, Field, Input, Textarea } from '~/components/ui' +import { PrivatePill, UseImage, type UseView } from '~/components/uses' +import { useAppContext } from '~/lib/app-context' +import { shrinkImage } from '~/lib/images' + +export interface PickedCollection { + /** owner/slug */ + key: string + name: string | null + public: boolean + major: boolean + minor: boolean + patch: boolean +} + +const BUMPS = ['major', 'minor', 'patch'] as const + +/** Look a collection up by "owner/slug", as the caller can read it. */ +async function lookUp(key: string): Promise { + const [owner, slug] = key.split('/') + if (!owner || !slug) return null + const res = await fetch( + `/api/collections/${encodeURIComponent(owner)}/${encodeURIComponent(slug)}`, + { + credentials: 'include', + }, + ) + if (!res.ok) return null + const c = (await res.json()) as { ownerSlug: string; slug: string; name: string; public: boolean } + return { + key: `${c.ownerSlug}/${c.slug}`, + name: c.name, + public: c.public, + major: false, + minor: false, + patch: false, + } +} + +export default function UseForm({ + use, + initialCollections, + initialFor, + webhookSection, +}: { + /** The use being edited; absent to declare a new one. */ + use?: UseView + initialCollections: PickedCollection[] + /** The org slug the For field starts on. */ + initialFor?: string | null + /** Step 2's webhook fields, rendered under the collections. */ + webhookSection?: ( + collections: PickedCollection[], + setCollections: (c: PickedCollection[]) => void, + ) => React.ReactNode +}) { + const navigate = useNavigate() + const { currentUser } = useAppContext() + const manageable = useMemo( + () => + ((currentUser?.orgs ?? []) as { slug: string; displayName: string; role: string }[]) + .filter((o) => o.role === 'owner' || o.role === 'admin') + .sort((a, b) => a.displayName.localeCompare(b.displayName)), + [currentUser], + ) + + const [name, setName] = useState(use?.name ?? '') + const [link, setLink] = useState(use?.link ?? '') + const [description, setDescription] = useState(use?.description ?? '') + const [isPublic, setIsPublic] = useState(use?.public ?? true) + const [forOrg, setForOrg] = useState( + use + ? (use.org?.slug ?? '') + : initialFor && manageable.some((o) => o.slug === initialFor) + ? initialFor + : '', + ) + const [collections, setCollections] = useState(initialCollections) + const [adding, setAdding] = useState('') + const [addError, setAddError] = useState(null) + const [image, setImage] = useState(null) + const [preview, setPreview] = useState(null) + const [saving, setSaving] = useState(false) + const [error, setError] = useState(null) + + // Collections in the person's orgs, offered as they type. + const [suggestions, setSuggestions] = useState([]) + useEffect(() => { + const orgs = ((currentUser?.orgs ?? []) as { slug: string }[]).slice(0, 10) + void Promise.all( + orgs.map((o) => + fetch(`/api/accounts/${o.slug}/collections`, { credentials: 'include' }) + .then((r) => (r.ok ? r.json() : [])) + .then((cs: { slug: string }[]) => cs.map((c) => `${o.slug}/${c.slug}`)) + .catch(() => [] as string[]), + ), + ).then((lists) => setSuggestions(lists.flat())) + }, [currentUser]) + + useEffect(() => { + if (!image) return setPreview(null) + const url = URL.createObjectURL(image) + setPreview(url) + return () => URL.revokeObjectURL(url) + }, [image]) + + async function add() { + const key = adding.trim().replace(/^\/+|\/+$/g, '') + setAddError(null) + if (!key) return + if (collections.some((c) => c.key === key)) { + setAdding('') + return + } + const found = await lookUp(key) + if (!found) { + setAddError(`No collection ${key} that you can read. Name it as owner/slug.`) + return + } + setCollections((cs) => [...cs, found]) + setAdding('') + } + + async function submit(e: React.FormEvent) { + e.preventDefault() + setError(null) + if (!collections.length) return setError('Add at least one collection it uses.') + setSaving(true) + try { + const body = { + name, + link: link.trim() || null, + description: description.trim() || null, + public: isPublic, + ...(use && !use.canManage ? {} : { org: forOrg || null }), + collections: collections.map((c) => ({ + collection: c.key, + major: c.major, + minor: c.minor, + patch: c.patch, + })), + } + if (use && (use.org?.slug ?? '') === forOrg) delete (body as { org?: unknown }).org + const res = await fetch(use ? `/api/uses/${use.id}` : '/api/uses', { + method: use ? 'PATCH' : 'POST', + credentials: 'include', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify(body), + }) + const saved = await res.json().catch(() => ({})) + if (!res.ok) throw new Error(saved.error ?? 'Could not save') + if (image) { + const form = new FormData() + form.append('image', await shrinkImage(image, 1280)) + const up = await fetch(`/api/uses/${saved.id}/image`, { + method: 'POST', + credentials: 'include', + body: form, + }) + if (!up.ok) { + const b = await up.json().catch(() => ({})) + throw new Error(`Saved, but the image wasn't: ${b.error ?? 'upload failed'}`) + } + } + void navigate(`/uses/${saved.id}`) + } catch (err) { + setError(err instanceof Error ? err.message : String(err)) + setSaving(false) + } + } + + const flagsVisible = !!webhookSection + + return ( +
+ + setName(e.target.value)} + placeholder="Shoreline Atlas" + /> + + + + setLink(e.target.value)} + placeholder="https://" + /> + + + +