diff --git a/apps/hub/package.json b/apps/hub/package.json index 71104b09f8..32e3732f4d 100644 --- a/apps/hub/package.json +++ b/apps/hub/package.json @@ -16,8 +16,8 @@ "@corbits/agent-directory": "workspace:*", "@corbits/agent-runtime": "workspace:*", "@corbits/approvals": "workspace:*", - "@corbits/artifacts": "github:corbitsdev/corbits-artifacts#dc435ba749b4378f19e5de772159c2a57e932938", - "@corbits/artifacts-hub": "workspace:*", + "@corbits/artifact-ui": "workspace:*", + "@corbits/artifacts": "github:corbitsdev/corbits-artifacts#5309a15d4aa504f132c54b4da08bb672b4903873", "@corbits/attio-task-agent-workflow": "workspace:*", "@corbits/chat": "workspace:*", "@corbits/code-review-workflow": "workspace:*", diff --git a/apps/hub/src/index.ts b/apps/hub/src/index.ts index e2ad04f682..e6ad03a07d 100644 --- a/apps/hub/src/index.ts +++ b/apps/hub/src/index.ts @@ -164,7 +164,17 @@ import { readProcessProvisionerConfig, type ProcessProvisionerRole, } from "@corbits/process-provisioner"; -import { createWorkflowRunAuthenticator } from "@corbits/artifacts-hub"; +import { + InlineContentStore, + mountArtifacts, + mountWorkflowArtifacts, + runArtifactMigrations, + type WorkflowArtifactEnv, +} from "@corbits/artifacts"; +import { + artifactMatchesLibraryKindSegment, + LIBRARY_KIND_SEGMENTS, +} from "@corbits/artifact-ui/kind-filter"; import { createConnectionRoutes, isInferenceProvider, @@ -223,7 +233,10 @@ import { createInFlightRequestTracker, withInFlightRequestTracking, } from "./in-flight-requests"; -import { withWorkflowRunTenantAuth } from "./workflow-run-tenant-auth"; +import { + createWorkflowRunAuthenticator, + withWorkflowRunTenantAuth, +} from "./workflow-run-tenant-auth"; // Host policy constants, not configuration. const MAX_TARBALL_BYTES = 10 * 1024 * 1024; @@ -674,6 +687,10 @@ export async function createHub(config: HubConfig) { }, ) => void; } = {}; + // Package-owned artifacts tables (CL-8188): idempotent, advisory-locked, + // safe on every boot of every replica — see @corbits/artifacts' README. + await runArtifactMigrations(db); + const artifactContentStore = InlineContentStore; const baseEventCollectors = createEventCollectorRegistry({ db: withTurnPartWriteDefaults(db), // CL-7418: deliberately no terminal-status settle here. The folded @@ -1468,18 +1485,53 @@ export async function createHub(config: HubConfig) { `${TENANT_PREFIX}/inbox`, createInboxRoutes({ db: mailboxDb, bus: mailboxBus }), ); - // CL-8160: the Workbench-composed workflow detail route - // (`@corbits/workflows`'s former `./detail/detail-route.ts`, mounted - // here at this same `/workflows/definitions` prefix as the vendored - // `createWorkflowDefinitionRoutes`) and the scheduled-workflow routes - // (`./schedule/scheduled-route.ts`: list/run-now/available-catalog) are - // both deleted per the owner ruling that workflow detail and schedule - // state derive from stock `@intx/hub-api` reads, not a hub-composed - // route. Stock's `GET /workflows/definitions` (mounted below by - // `createWorkflowDefinitionRoutes`) does not yet expose enough to - // reconstruct what these routes gave (no manifest/package metadata, no - // wire projection, no grant snapshot) — see the PR for CL-8160 for the - // upstream ask. + // Library/artifacts plane (CL-8188): `@corbits/artifacts` mounted directly + // rather than through the retired `@corbits/artifacts-hub` wrapper — the + // library now owns counts, preview, and every other Library HTTP surface + // this app previously reimplemented. `countSegments` keeps the segment + // taxonomy (what makes an artifact a "document" or a "routine") host-owned, + // per the library's README; the predicates themselves live in + // `@corbits/artifact-ui` so the web Files nav and this count walk share one + // mapping. + { + const artifactsApi = new Hono(); + mountArtifacts(artifactsApi, { + db, + contentStore: artifactContentStore, + requireGrant: createRequireGrant({ + grantStore: chatGrantStore, + conditionRegistry: grantConditionRegistry, + }), + countSegments: Object.fromEntries( + LIBRARY_KIND_SEGMENTS.map((segment) => [ + segment, + (row: { kind: string; title: string }) => + artifactMatchesLibraryKindSegment(row, segment), + ]), + ), + }); + app.route(TENANT_PREFIX, artifactsApi); + } + // Myra's own artifact tools (`@corbits/artifact-tools`, CL-6000) and every + // Routine's own `finalize-tool`/`artifact-client` duplicate: the + // workflow-run-authenticated counterpart to the tenant-session mount just + // above, at the same `/api/workflow-artifacts` prefix the sidecar's + // `hubArtifactsUrl` already points at. Every route lives under this + // mount's own `/artifacts` prefix per `@corbits/artifacts`' fixed shape + // (`POST /artifacts`, `GET /artifacts/recent`, `GET /artifacts/:id`, + // `POST /artifacts/binary`) — callers reach it at + // `/api/workflow-artifacts/artifacts...`. + { + const workflowArtifactsApi = new Hono(); + const workflowRunAuthenticator = createWorkflowRunAuthenticator({ db }); + mountWorkflowArtifacts(workflowArtifactsApi, { + db, + contentStore: artifactContentStore, + resolveRunScope: (token, runAddress) => + workflowRunAuthenticator.resolve(token, runAddress), + }); + app.route("/api/workflow-artifacts", workflowArtifactsApi); + } { const mailboxApp = new Hono(); mountMailbox(mailboxApp, { diff --git a/apps/hub/src/workflow-run-tenant-auth.ts b/apps/hub/src/workflow-run-tenant-auth.ts index bb6a8c9ff1..e9fd82bc63 100644 --- a/apps/hub/src/workflow-run-tenant-auth.ts +++ b/apps/hub/src/workflow-run-tenant-auth.ts @@ -21,8 +21,11 @@ // before. The `:tenantId` path segment is never trusted: the middleware sets // the tenant from the authenticated run's own scope, so a run cannot widen // its reach by naming another tenant in the URL. +import { eq } from "drizzle-orm"; import { Hono } from "hono"; +import { sha256 } from "@intx/crypto"; import type { DB } from "@intx/db"; +import { sidecar, workflowRun } from "@intx/db/schema"; import { createWorkflowRunDeployAuth, type AppEnv, @@ -34,6 +37,59 @@ export type WorkflowRunTenantAuthDeps = { authenticator: WorkflowRunAuthenticator; }; +/** + * The tenant + principal + run a presented sidecar token and run address + * resolve to. This is the one concrete implementation of the + * `WorkflowRunAuthenticator` shape every workflow-run-authenticated surface + * in this app takes structurally (agent-directory, chat, connections, + * memory-hub, `@corbits/artifacts`' `mountWorkflowArtifacts`, and the + * `withWorkflowRunTenantAuth` wrap below) — a single sidecar-token + + * run-address check, reused everywhere rather than re-verified per surface. + */ +export type ResolvedWorkflowRunScope = { + readonly tenantId: string; + readonly principalId: string; + readonly runId: string; +}; + +export type CreateWorkflowRunAuthenticatorDeps = { + db: DB["db"]; +}; + +export type ConcreteWorkflowRunAuthenticator = { + resolve( + token: string, + runAddress: string, + ): Promise; +}; + +export function createWorkflowRunAuthenticator( + deps: CreateWorkflowRunAuthenticatorDeps, +): ConcreteWorkflowRunAuthenticator { + return { + async resolve(token, runAddress) { + if (token === "" || runAddress === "") return null; + + const tokenHash = await sha256(token); + const sidecarRow = await deps.db.query.sidecar.findFirst({ + where: eq(sidecar.tokenHashSha256, tokenHash), + }); + if (sidecarRow === undefined) return null; + + const run = await deps.db.query.workflowRun.findFirst({ + where: eq(workflowRun.address, runAddress), + }); + if (run === undefined || run.principalId === null) return null; + + return { + tenantId: run.tenantId, + principalId: run.principalId, + runId: run.id, + }; + }, + }; +} + export function withWorkflowRunTenantAuth( nativeApp: Hono, deps: WorkflowRunTenantAuthDeps, diff --git a/apps/web/src/api.ts b/apps/web/src/api.ts index effff10a6e..98d208203c 100644 --- a/apps/web/src/api.ts +++ b/apps/web/src/api.ts @@ -49,16 +49,21 @@ export const ArtifactListItemSchema = type({ updatedAt: "string", }); export const ArtifactListPageSchema = type({ - data: ArtifactListItemSchema.array(), + artifacts: ArtifactListItemSchema.array(), nextCursor: "string | null", }); -export const ArtifactDetailSchema = ArtifactListItemSchema.merge( +export const ArtifactRowSchema = ArtifactListItemSchema.merge( type({ content: "string", }), ); +// GET /api/tenants/:id/artifacts/:artifactId wraps the row in an `artifact` +// envelope key (`@corbits/artifacts`' `mountArtifacts`, CL-8188). +export const ArtifactDetailSchema = type({ + artifact: ArtifactRowSchema, +}); export const ArtifactUploadResponseSchema = type({ - data: ArtifactDetailSchema.array(), + artifacts: ArtifactRowSchema.array(), }); // GET /api/tenants/:id/artifacts/counts — honest per-kind-segment counts @@ -79,7 +84,7 @@ export type Approval = typeof ApprovalResponse.infer; export type AssetRow = typeof AssetWithOriginResponse.infer; export type ArtifactListItem = typeof ArtifactListItemSchema.infer; export type ArtifactListPage = typeof ArtifactListPageSchema.infer; -export type ArtifactDetail = typeof ArtifactDetailSchema.infer; +export type ArtifactDetail = typeof ArtifactRowSchema.infer; export type ArtifactCounts = typeof ArtifactCountsSchema.infer; /** * The envelope paginatedSchema validates, stated structurally: the generic @@ -247,5 +252,5 @@ export async function fetchArtifactDetail( `Unexpected artifact response shape: ${parsed.summary}`, ); } - return parsed; + return parsed.artifact; } diff --git a/apps/web/src/command-palette-provider.tsx b/apps/web/src/command-palette-provider.tsx index 93cf2544df..d82e26f594 100644 --- a/apps/web/src/command-palette-provider.tsx +++ b/apps/web/src/command-palette-provider.tsx @@ -427,7 +427,7 @@ export function CommandPaletteProvider({ const libraryItems = useMemo( () => artifactsQuery.kind === "ready" - ? artifactsQuery.data.data.map((artifact) => ({ + ? artifactsQuery.data.artifacts.map((artifact) => ({ id: `entity:library:${artifact.id}`, title: artifact.title, subtitle: artifactKindLabel(artifact.kind), diff --git a/apps/web/src/pages/library-page.tsx b/apps/web/src/pages/library-page.tsx index 405ea64ad0..478d9097e8 100644 --- a/apps/web/src/pages/library-page.tsx +++ b/apps/web/src/pages/library-page.tsx @@ -733,7 +733,7 @@ export function LibraryRoute({ path }: { readonly path: string }) { // Drop selection when the filtered list no longer contains the id. useEffect(() => { if (selectedId === null || page.kind !== "ready") return; - const stillThere = mapArtifactListToSummaries(page.data.data) + const stillThere = mapArtifactListToSummaries(page.data.artifacts) .filter((row) => artifactMatchesLibraryKindSegment(row, kindSegment)) .some((row) => row.id === selectedId); if (!stillThere) setSelectedId(null); @@ -796,8 +796,8 @@ export function LibraryRoute({ path }: { readonly path: string }) { return ( {(rows) => { - const artifacts = mapArtifactListToSummaries(rows.data).filter((row) => - artifactMatchesLibraryKindSegment(row, kindSegment), + const artifacts = mapArtifactListToSummaries(rows.artifacts).filter( + (row) => artifactMatchesLibraryKindSegment(row, kindSegment), ); return ( { } if (url.includes("/artifacts/art_1")) { return Promise.resolve( - jsonResponse({ ...listedArtifact, content: "# Q3\nGrowth is up." }), + jsonResponse({ + artifact: { ...listedArtifact, content: "# Q3\nGrowth is up." }, + }), ); } if (url.includes("/artifacts")) { return Promise.resolve( - jsonResponse({ data: [listedArtifact], nextCursor: null }), + jsonResponse({ artifacts: [listedArtifact], nextCursor: null }), ); } return Promise.reject(new Error(`unrouted fetch in library test: ${url}`)); diff --git a/apps/web/test/library-upload-confirmation.test.tsx b/apps/web/test/library-upload-confirmation.test.tsx index d8ab16265b..488f054a4c 100644 --- a/apps/web/test/library-upload-confirmation.test.tsx +++ b/apps/web/test/library-upload-confirmation.test.tsx @@ -105,7 +105,7 @@ describe("Files upload confirmation", () => { if (url.includes("/artifacts/upload") && init?.method === "POST") { return Promise.resolve( jsonResponse({ - data: [ + artifacts: [ { id: "art_new", kind: "document", @@ -126,7 +126,9 @@ describe("Files upload confirmation", () => { ); } if (url.includes("/artifacts")) { - return Promise.resolve(jsonResponse({ data: [], nextCursor: null })); + return Promise.resolve( + jsonResponse({ artifacts: [], nextCursor: null }), + ); } return Promise.reject(new Error(`unrouted fetch: ${url}`)); }) as typeof fetch; @@ -153,7 +155,9 @@ describe("Files upload confirmation", () => { return Promise.resolve(jsonResponse({ error: "boom" }, 500)); } if (url.includes("/artifacts")) { - return Promise.resolve(jsonResponse({ data: [], nextCursor: null })); + return Promise.resolve( + jsonResponse({ artifacts: [], nextCursor: null }), + ); } return Promise.reject(new Error(`unrouted fetch: ${url}`)); }) as typeof fetch; diff --git a/bun.lock b/bun.lock index 7f2a1ac9ae..ad0ea787cf 100644 --- a/bun.lock +++ b/bun.lock @@ -8,8 +8,7 @@ "arktype": "catalog:", }, "devDependencies": { - "@corbits/artifacts": "github:corbitsdev/corbits-artifacts#dc435ba749b4378f19e5de772159c2a57e932938", - "@corbits/artifacts-hub": "workspace:*", + "@corbits/artifacts": "github:corbitsdev/corbits-artifacts#5309a15d4aa504f132c54b4da08bb672b4903873", "@corbits/codex-provider": "workspace:*", "@corbits/connections": "workspace:*", "@corbits/evals": "workspace:*", @@ -40,8 +39,8 @@ "@corbits/agent-directory": "workspace:*", "@corbits/agent-runtime": "workspace:*", "@corbits/approvals": "workspace:*", - "@corbits/artifacts": "github:corbitsdev/corbits-artifacts#dc435ba749b4378f19e5de772159c2a57e932938", - "@corbits/artifacts-hub": "workspace:*", + "@corbits/artifact-ui": "workspace:*", + "@corbits/artifacts": "github:corbitsdev/corbits-artifacts#5309a15d4aa504f132c54b4da08bb672b4903873", "@corbits/attio-task-agent-workflow": "workspace:*", "@corbits/chat": "workspace:*", "@corbits/code-review-workflow": "workspace:*", @@ -345,27 +344,6 @@ "typescript": "catalog:", }, }, - "packages/artifacts-hub": { - "name": "@corbits/artifacts-hub", - "version": "0.0.1", - "dependencies": { - "@corbits/artifact-ui": "workspace:*", - "@corbits/artifacts": "github:corbitsdev/corbits-artifacts#dc435ba749b4378f19e5de772159c2a57e932938", - "@corbits/collections": "workspace:*", - "@corbits/error-sink": "workspace:*", - "@intx/crypto": "0.3.0", - "@intx/db": "workspace:*", - "@intx/hub-api": "workspace:*", - "@intx/types": "workspace:*", - "arktype": "catalog:", - "drizzle-orm": "catalog:", - "hono": "catalog:", - }, - "devDependencies": { - "@types/bun": "catalog:", - "typescript": "catalog:", - }, - }, "packages/bench-ui": { "name": "@corbits/bench-ui", "version": "0.0.1", @@ -1090,7 +1068,7 @@ }, "packages/scout-agent": { "name": "@corbits/scout-agent", - "version": "0.0.3", + "version": "0.0.4", "dependencies": { "@intx/agent": "workspace:*", "@intx/types": "workspace:*", @@ -1984,9 +1962,7 @@ "@corbits/artifact-ui": ["@corbits/artifact-ui@workspace:packages/artifact-ui"], - "@corbits/artifacts": ["@corbits/artifacts@github:corbitsdev/corbits-artifacts#dc435ba", { "dependencies": { "@hono/standard-validator": "^0.2.3" }, "peerDependencies": { "@intx/hub-api": "^0.2.2", "@intx/types": "^0.2.2", "arktype": "^2.1.29", "drizzle-orm": "^0.45.2", "hono": "^4.12.32", "hono-openapi": "^1.2.0", "postgres": "^3.4.9" } }, "corbitsdev-corbits-artifacts-dc435ba", "sha512-VksIyrrJY9nRke0QyjgqGdW3gLD73Bi3+CzpJWG+l8vRJKdUxVi7ms2Mp95NmJXr4TpVX6i1z4odufX/QBxnSw=="], - - "@corbits/artifacts-hub": ["@corbits/artifacts-hub@workspace:packages/artifacts-hub"], + "@corbits/artifacts": ["@corbits/artifacts@github:corbitsdev/corbits-artifacts#5309a15", { "dependencies": { "@hono/standard-validator": "^0.2.3" }, "peerDependencies": { "@intx/hub-api": "^0.3.0", "@intx/types": "^0.3.0", "arktype": "^2.1.29", "drizzle-orm": "^0.45.2", "hono": "^4.12.32", "hono-openapi": "^1.2.0", "postgres": "^3.4.9" } }, "corbitsdev-corbits-artifacts-5309a15", "sha512-zGHkq++juclUrOd0O8/Z5ziTldmJZ6gqyH/c9cs5S10UPU4gqn8CHwq174SiJXY0ujJ3cNpJXnrr+0fcqlfQ1w=="], "@corbits/assistant-workflow": ["@corbits/assistant-workflow@workspace:workflows/assistant"], @@ -3378,12 +3354,14 @@ "@corbits/artifact-ui/@corbits/react-ui": ["@corbits/react-ui@github:corbitsdev/react-ui#3b12281", { "dependencies": { "class-variance-authority": "^0.7.1", "clsx": "^2.1.1", "tailwind-merge": "^3.3.1" }, "peerDependencies": { "@radix-ui/react-dialog": "^1.1.15", "@radix-ui/react-dropdown-menu": "^2.1.16", "@radix-ui/react-slot": "^1.2.3", "@radix-ui/react-tooltip": "^1.2.8", "@tanstack/react-query": "^5.90.2", "lucide-react": "^0.545.0 || ^1.0.0", "react": "^18.2.0 || ^19.0.0", "react-dom": "^18.2.0 || ^19.0.0", "sonner": "^2.0.7" }, "optionalPeers": ["@tanstack/react-query"] }, "corbitsdev-react-ui-3b12281", "sha512-Abvm/DO0Gqg0ITHGT9355ZxyKRPMVJLSSQSjpd3a8qt4JPrSMOLIOS4sX8ZMNNaArIbnY9F+VKrOWkUJUyO4Nw=="], - "@corbits/artifacts-hub/@corbits/artifacts": ["@corbits/artifacts@github:corbitsdev/corbits-artifacts#dc435ba", { "dependencies": { "@hono/standard-validator": "^0.2.3" }, "peerDependencies": { "@intx/hub-api": "^0.2.2", "@intx/types": "^0.2.2", "arktype": "^2.1.29", "drizzle-orm": "^0.45.2", "hono": "^4.12.32", "hono-openapi": "^1.2.0", "postgres": "^3.4.9" } }, "corbitsdev-corbits-artifacts-dc435ba", "sha512-VksIyrrJY9nRke0QyjgqGdW3gLD73Bi3+CzpJWG+l8vRJKdUxVi7ms2Mp95NmJXr4TpVX6i1z4odufX/QBxnSw=="], + "@corbits/assistant-workflow/@corbits/memory": ["@corbits/memory@github:corbitsdev/corbits-memory#9e6f213", { "dependencies": { "@intx/agent": "0.2.2", "@intx/authz": "0.2.2", "@intx/hub-api": "0.2.2", "@intx/log": "0.2.2", "@intx/workflow": "0.2.2", "arktype": "^2.1.29", "drizzle-orm": "^0.45.1", "hono": "^4.9.0", "hono-openapi": "^1.3.1", "postgres": "^3.4.7" } }, "corbitsdev-corbits-memory-9e6f213", "sha512-utnM4ZT2zmslcPXYWAAqxlDNLcpGsXFiTOtj8h7+OXnhCP0Eaw8yl25+yCTyHpvt3jcdeG4h5uFsSj7ou0BZCA=="], "@corbits/chat-ui/@corbits/mailbox": ["@corbits/mailbox@github:corbitsdev/corbits-mailbox#bc96404", { "dependencies": { "@hono/standard-validator": "0.2.3", "@standard-community/standard-json": "0.3.5", "@standard-community/standard-openapi": "0.2.9", "arktype": "2.1.29", "hono-openapi": "1.3.1" }, "peerDependencies": { "@intx/log": "^0.2.2", "@intx/mime": "^0.2.2", "@intx/types": "^0.2.2", "drizzle-orm": "^0.45.2", "hono": "^4.12.0", "postgres": "^3.4.0" } }, "corbitsdev-corbits-mailbox-bc96404", "sha512-NEeNP2XsjIKOUbRr5szrCDWAYPQSmMNSu33ODyLUCiXdnq12HYWYG/C+0DcAMELlY+9Ktqf543Kg/Qb22NtjWQ=="], "@corbits/mailbox/hono-openapi": ["hono-openapi@1.3.1", "", { "peerDependencies": { "@hono/standard-validator": "^0.2.0", "@standard-community/standard-json": "^0.3.5", "@standard-community/standard-openapi": "^0.2.9", "@types/json-schema": "^7.0.15", "hono": "^4.11.2", "openapi-types": "^12.1.3" }, "optionalPeers": ["@hono/standard-validator", "hono"] }, "sha512-NLVeVkhKZ3drmQNEIPac8HX8Y54uf1hJAgIM/7MfDsaeVVmB+QILWQxx5x3R3NvRHgedcbEbOCGY2uR7WQYyMw=="], + "@corbits/scout-agent/@corbits/memory": ["@corbits/memory@github:corbitsdev/corbits-memory#9e6f213", { "dependencies": { "@intx/agent": "0.2.2", "@intx/authz": "0.2.2", "@intx/hub-api": "0.2.2", "@intx/log": "0.2.2", "@intx/workflow": "0.2.2", "arktype": "^2.1.29", "drizzle-orm": "^0.45.1", "hono": "^4.9.0", "hono-openapi": "^1.3.1", "postgres": "^3.4.7" } }, "corbitsdev-corbits-memory-9e6f213", "sha512-utnM4ZT2zmslcPXYWAAqxlDNLcpGsXFiTOtj8h7+OXnhCP0Eaw8yl25+yCTyHpvt3jcdeG4h5uFsSj7ou0BZCA=="], + "@esbuild-kit/core-utils/esbuild": ["esbuild@0.18.20", "", { "optionalDependencies": { "@esbuild/android-arm": "0.18.20", "@esbuild/android-arm64": "0.18.20", "@esbuild/android-x64": "0.18.20", "@esbuild/darwin-arm64": "0.18.20", "@esbuild/darwin-x64": "0.18.20", "@esbuild/freebsd-arm64": "0.18.20", "@esbuild/freebsd-x64": "0.18.20", "@esbuild/linux-arm": "0.18.20", "@esbuild/linux-arm64": "0.18.20", "@esbuild/linux-ia32": "0.18.20", "@esbuild/linux-loong64": "0.18.20", "@esbuild/linux-mips64el": "0.18.20", "@esbuild/linux-ppc64": "0.18.20", "@esbuild/linux-riscv64": "0.18.20", "@esbuild/linux-s390x": "0.18.20", "@esbuild/linux-x64": "0.18.20", "@esbuild/netbsd-x64": "0.18.20", "@esbuild/openbsd-x64": "0.18.20", "@esbuild/sunos-x64": "0.18.20", "@esbuild/win32-arm64": "0.18.20", "@esbuild/win32-ia32": "0.18.20", "@esbuild/win32-x64": "0.18.20" }, "bin": { "esbuild": "bin/esbuild" } }, "sha512-ceqxoedUrcayh7Y7ZX6NdbbDzGROiyVBgC4PriJThBKSVPWnnFHZAkfI1lJT8QFkOwH4qOS2SJkS4wvpGl8BpA=="], "@eslint-community/eslint-utils/eslint-visitor-keys": ["eslint-visitor-keys@3.4.3", "", {}, "sha512-wpc+LXeiyiisxPlEkUzU6svyS1frIO3Mgxj1fdy7Pm8Ygzguax2N3Fa/D/ag1WqbOprdI+uY6wMUl8/a2G+iag=="], @@ -3404,8 +3382,6 @@ "@typescript-eslint/eslint-plugin/ignore": ["ignore@7.0.9", "", {}, "sha512-brTTsvFRt5C1gGHtPst/281UjPD5t9fBqbgoMPlVWy11ZLTPfu7HxK4ZYqO9H7o/yC9rSTCI85EaQ4OoY12qYw=="], - "@workbench/hub/@corbits/artifacts": ["@corbits/artifacts@github:corbitsdev/corbits-artifacts#dc435ba", { "dependencies": { "@hono/standard-validator": "^0.2.3" }, "peerDependencies": { "@intx/hub-api": "^0.2.2", "@intx/types": "^0.2.2", "arktype": "^2.1.29", "drizzle-orm": "^0.45.2", "hono": "^4.12.32", "hono-openapi": "^1.2.0", "postgres": "^3.4.9" } }, "corbitsdev-corbits-artifacts-dc435ba", "sha512-VksIyrrJY9nRke0QyjgqGdW3gLD73Bi3+CzpJWG+l8vRJKdUxVi7ms2Mp95NmJXr4TpVX6i1z4odufX/QBxnSw=="], - "@workbench/sidecar/@corbits/oauth-core": ["@corbits/oauth-core@github:corbitsdev/corbits-oauth-core#e1e69e6", { "dependencies": { "arktype": "2.2.3" } }, "corbitsdev-corbits-oauth-core-e1e69e6", "sha512-wUrD73iVyk/Dtb4yRn3hCh6N8syfsEvAkRz4XYqT0FIB3sYDSMYEWHcDMJx9nq64my/HBOeN1J6PHIOtpjhtPg=="], "ajv-formats/ajv": ["ajv@8.20.0", "", { "dependencies": { "fast-deep-equal": "^3.1.3", "fast-uri": "^3.0.1", "json-schema-traverse": "^1.0.0", "require-from-string": "^2.0.2" } }, "sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA=="], diff --git a/package.json b/package.json index 81dbd48dc5..728d2262e1 100644 --- a/package.json +++ b/package.json @@ -30,8 +30,7 @@ "eval": "bun run scripts/evals-run.ts" }, "devDependencies": { - "@corbits/artifacts": "github:corbitsdev/corbits-artifacts#dc435ba749b4378f19e5de772159c2a57e932938", - "@corbits/artifacts-hub": "workspace:*", + "@corbits/artifacts": "github:corbitsdev/corbits-artifacts#5309a15d4aa504f132c54b4da08bb672b4903873", "@corbits/codex-provider": "workspace:*", "@corbits/evals": "workspace:*", "@corbits/ollama-adapter": "workspace:*", diff --git a/packages/artifacts-hub/LICENSE b/packages/artifacts-hub/LICENSE deleted file mode 100644 index c6487f4fdf..0000000000 --- a/packages/artifacts-hub/LICENSE +++ /dev/null @@ -1,176 +0,0 @@ -GNU LESSER GENERAL PUBLIC LICENSE - -Version 2.1, February 1999 - -Copyright (C) 1991, 1999 Free Software Foundation, Inc. -51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - -Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. - -[This is the first released version of the Lesser GPL. It also counts as the successor of the GNU Library Public License, version 2, hence the version number 2.1.] - -Preamble - -The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public Licenses are intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. - -This license, the Lesser General Public License, applies to some specially designated software packages--typically libraries--of the Free Software Foundation and other authors who decide to use it. You can use it too, but we suggest you first think carefully about whether this license or the ordinary General Public License is the better strategy to use in any particular case, based on the explanations below. - -When we speak of free software, we are referring to freedom of use, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish); that you receive source code or can get it if you want it; that you can change the software and use pieces of it in new free programs; and that you are informed that you can do these things. - -To protect your rights, we need to make restrictions that forbid distributors to deny you these rights or to ask you to surrender these rights. These restrictions translate to certain responsibilities for you if you distribute copies of the library or if you modify it. - -For example, if you distribute copies of the library, whether gratis or for a fee, you must give the recipients all the rights that we gave you. You must make sure that they, too, receive or can get the source code. If you link other code with the library, you must provide complete object files to the recipients, so that they can relink them with the library after making changes to the library and recompiling it. And you must show them these terms so they know their rights. - -We protect your rights with a two-step method: (1) we copyright the library, and (2) we offer you this license, which gives you legal permission to copy, distribute and/or modify the library. - -To protect each distributor, we want to make it very clear that there is no warranty for the free library. Also, if the library is modified by someone else and passed on, the recipients should know that what they have is not the original version, so that the original author's reputation will not be affected by problems that might be introduced by others. - -Finally, software patents pose a constant threat to the existence of any free program. We wish to make sure that a company cannot effectively restrict the users of a free program by obtaining a restrictive license from a patent holder. Therefore, we insist that any patent license obtained for a version of the library must be consistent with the full freedom of use specified in this license. - -Most GNU software, including some libraries, is covered by the ordinary GNU General Public License. This license, the GNU Lesser General Public License, applies to certain designated libraries, and is quite different from the ordinary General Public License. We use this license for certain libraries in order to permit linking those libraries into non-free programs. - -When a program is linked with a library, whether statically or using a shared library, the combination of the two is legally speaking a combined work, a derivative of the original library. The ordinary General Public License therefore permits such linking only if the entire combination fits its criteria of freedom. The Lesser General Public License permits more lax criteria for linking other code with the library. - -We call this license the "Lesser" General Public License because it does Less to protect the user's freedom than the ordinary General Public License. It also provides other free software developers Less of an advantage over competing non-free programs. These disadvantages are the reason we use the ordinary General Public License for many libraries. However, the Lesser license provides advantages in certain special circumstances. - -For example, on rare occasions, there may be a special need to encourage the widest possible use of a certain library, so that it becomes a de-facto standard. To achieve this, non-free programs must be allowed to use the library. A more frequent case is that a free library does the same job as widely used non-free libraries. In this case, there is little to gain by limiting the free library to free software only, so we use the Lesser General Public License. - -In other cases, permission to use a particular library in non-free programs enables a greater number of people to use a large body of free software. For example, permission to use the GNU C Library in non-free programs enables many more people to use the whole GNU operating system, as well as its variant, the GNU/Linux operating system. - -Although the Lesser General Public License is Less protective of the users' freedom, it does ensure that the user of a program that is linked with the Library has the freedom and the wherewithal to run that program using a modified version of the Library. - -The precise terms and conditions for copying, distribution and modification follow. Pay close attention to the difference between a "work based on the library" and a "work that uses the library". The former contains code derived from the library, whereas the latter must be combined with the library in order to run. - -GNU LESSER GENERAL PUBLIC LICENSE -TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION - -0. This License Agreement applies to any software library or other program which contains a notice placed by the copyright holder or other authorized party saying it may be distributed under the terms of this Lesser General Public License (also called "this License"). Each licensee is addressed as "you". - -A "library" means a collection of software functions and/or data prepared so as to be conveniently linked with application programs (which use some of those functions and data) to form executables. - -The "Library", below, refers to any such software library or work which has been distributed under these terms. A "work based on the Library" means either the Library or any derivative work under copyright law: that is to say, a work containing the Library or a portion of it, either verbatim or with modifications and/or translated straightforwardly into another language. (Hereinafter, translation is included without limitation in the term "modification".) - -"Source code" for a work means the preferred form of the work for making modifications to it. For a library, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the library. - -Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running a program using the Library is not restricted, and output from such a program is covered only if its contents constitute a work based on the Library (independent of the use of the Library in a tool for writing it). Whether that is true depends on what the Library does and what the program that uses the Library does. - -1. You may copy and distribute verbatim copies of the Library's complete source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and distribute a copy of this License along with the Library. - -You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. - -2. You may modify your copy or copies of the Library or any portion of it, thus forming a work based on the Library, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: - - a) The modified work must itself be a software library. - - b) You must cause the files modified to carry prominent notices stating that you changed the files and the date of any change. - - c) You must cause the whole of the work to be licensed at no charge to all third parties under the terms of this License. - - d) If a facility in the modified Library refers to a function or a table of data to be supplied by an application program that uses the facility, other than as an argument passed when the facility is invoked, then you must make a good faith effort to ensure that, in the event an application does not supply such function or table, the facility still operates, and performs whatever part of its purpose remains meaningful. - -(For example, a function in a library to compute square roots has a purpose that is entirely well-defined independent of the application. Therefore, Subsection 2d requires that any application-supplied function or table used by this function must be optional: if the application does not supply it, the square root function must still compute square roots.) - -These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Library, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Library, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. - -Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Library. - -In addition, mere aggregation of another work not based on the Library with the Library (or with a work based on the Library) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. - -3. You may opt to apply the terms of the ordinary GNU General Public License instead of this License to a given copy of the Library. To do this, you must alter all the notices that refer to this License, so that they refer to the ordinary GNU General Public License, version 2, instead of to this License. (If a newer version than version 2 of the ordinary GNU General Public License has appeared, then you can specify that version instead if you wish.) Do not make any other change in these notices. - -Once this change is made in a given copy, it is irreversible for that copy, so the ordinary GNU General Public License applies to all subsequent copies and derivative works made from that copy. - -This option is useful when you wish to copy part of the code of the Library into a program that is not a library. - -4. You may copy and distribute the Library (or a portion or derivative of it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange. - -If distribution of object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place satisfies the requirement to distribute the source code, even though third parties are not compelled to copy the source along with the object code. - -5. A program that contains no derivative of any portion of the Library, but is designed to work with the Library by being compiled or linked with it, is called a "work that uses the Library". Such a work, in isolation, is not a derivative work of the Library, and therefore falls outside the scope of this License. - -However, linking a "work that uses the Library" with the Library creates an executable that is a derivative of the Library (because it contains portions of the Library), rather than a "work that uses the library". The executable is therefore covered by this License. Section 6 states terms for distribution of such executables. - -When a "work that uses the Library" uses material from a header file that is part of the Library, the object code for the work may be a derivative work of the Library even though the source code is not. Whether this is true is especially significant if the work can be linked without the Library, or if the work is itself a library. The threshold for this to be true is not precisely defined by law. - -If such an object file uses only numerical parameters, data structure layouts and accessors, and small macros and small inline functions (ten lines or less in length), then the use of the object file is unrestricted, regardless of whether it is legally a derivative work. (Executables containing this object code plus portions of the Library will still fall under Section 6.) - -Otherwise, if the work is a derivative of the Library, you may distribute the object code for the work under the terms of Section 6. Any executables containing that work also fall under Section 6, whether or not they are linked directly with the Library itself. - -6. As an exception to the Sections above, you may also combine or link a "work that uses the Library" with the Library to produce a work containing portions of the Library, and distribute that work under terms of your choice, provided that the terms permit modification of the work for the customer's own use and reverse engineering for debugging such modifications. - -You must give prominent notice with each copy of the work that the Library is used in it and that the Library and its use are covered by this License. You must supply a copy of this License. If the work during execution displays copyright notices, you must include the copyright notice for the Library among them, as well as a reference directing the user to the copy of this License. Also, you must do one of these things: - - a) Accompany the work with the complete corresponding machine-readable source code for the Library including whatever changes were used in the work (which must be distributed under Sections 1 and 2 above); and, if the work is an executable linked with the Library, with the complete machine-readable "work that uses the Library", as object code and/or source code, so that the user can modify the Library and then relink to produce a modified executable containing the modified Library. (It is understood that the user who changes the contents of definitions files in the Library will not necessarily be able to recompile the application to use the modified definitions.) - - b) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (1) uses at run time a copy of the library already present on the user's computer system, rather than copying library functions into the executable, and (2) will operate properly with a modified version of the library, if the user installs one, as long as the modified version is interface-compatible with the version that the work was made with. - - c) Accompany the work with a written offer, valid for at least three years, to give the same user the materials specified in Subsection 6a, above, for a charge no more than the cost of performing this distribution. - - d) If distribution of the work is made by offering access to copy from a designated place, offer equivalent access to copy the above specified materials from the same place. - - e) Verify that the user has already received a copy of these materials or that you have already sent this user a copy. - -For an executable, the required form of the "work that uses the Library" must include any data and utility programs needed for reproducing the executable from it. However, as a special exception, the materials to be distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. - -It may happen that this requirement contradicts the license restrictions of other proprietary libraries that do not normally accompany the operating system. Such a contradiction means you cannot use both them and the Library together in an executable that you distribute. - -7. You may place library facilities that are a work based on the Library side-by-side in a single library together with other library facilities not covered by this License, and distribute such a combined library, provided that the separate distribution of the work based on the Library and of the other library facilities is otherwise permitted, and provided that you do these two things: - - a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities. This must be distributed under the terms of the Sections above. - - b) Give prominent notice with the combined library of the fact that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. - -8. You may not copy, modify, sublicense, link with, or distribute the Library except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, link with, or distribute the Library is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. - -9. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Library or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Library (or any work based on the Library), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Library or works based on it. - -10. Each time you redistribute the Library (or any work based on the Library), the recipient automatically receives a license from the original licensor to copy, distribute, link with or modify the Library subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties with this License. - -11. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Library at all. For example, if a patent license would not permit royalty-free redistribution of the Library by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Library. - -If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply, and the section as a whole is intended to apply in other circumstances. - -It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. - -This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. - -12. If the distribution and/or use of the Library is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Library under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. - -13. The Free Software Foundation may publish revised and/or new versions of the Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. - -Each version is given a distinguishing version number. If the Library specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Library does not specify a license version number, you may choose any version ever published by the Free Software Foundation. - -14. If you wish to incorporate parts of the Library into other free programs whose distribution conditions are incompatible with these, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. - -NO WARRANTY - -15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - -16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. - -END OF TERMS AND CONDITIONS - -How to Apply These Terms to Your New Libraries - -If you develop a new library, and you want it to be of the greatest possible use to the public, we recommend making it free software that everyone can redistribute and change. You can do so by permitting redistribution under these terms (or, alternatively, under the terms of the ordinary General Public License). - -To apply these terms, attach the following notices to the library. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. - - one line to give the library's name and an idea of what it does. - Copyright (C) year name of author - - This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Also add information on how to contact you by electronic and paper mail. - -You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the library, if necessary. Here is a sample; alter the names: - -Yoyodyne, Inc., hereby disclaims all copyright interest in -the library `Frob' (a library for tweaking knobs) written -by James Random Hacker. - -signature of Ty Coon, 1 April 1990 -Ty Coon, President of Vice -That's all there is to it! diff --git a/packages/artifacts-hub/README.md b/packages/artifacts-hub/README.md deleted file mode 100644 index a5808b2602..0000000000 --- a/packages/artifacts-hub/README.md +++ /dev/null @@ -1,56 +0,0 @@ -# @corbits/artifacts-hub - -Tenant-scoped Library HTTP surface over the mounted `@corbits/artifacts` -engine: list (newest-first, paginated, optional text search), get-by-id, -multipart upload, and per-kind-segment counts for the Library nav. Also -exposes a second, narrower surface — the sanctioned workflow-artifacts -path (CL-6000) — so a workflow-process child can persist and read Library -artifacts without a database handle or a browser session. - -## Composition - -- `createArtifactRoutes` mounts under the tenant-session prefix and uses - `RequireGrant`/`TenantEnv` from `@intx/hub-api`, reusing the existing - `asset` resource family so Library grants keep working without a - parallel vocabulary. -- `createWorkflowArtifactRoutes` mounts outside the tenant-session prefix. - Every request authenticates via `WorkflowRunAuthenticator` - (`workflow-auth.ts`) instead of `resolveTenant` + `requireGrant`: the - sidecar's bearer token (hashed and checked against the `sidecar` table - via `@intx/crypto` + `@intx/db`) plus the run's own address (resolved - through `@intx/db`'s `workflowRun` address lookup) together - scope the call to one run's tenant + principal. -- Both surfaces wrap the same `@corbits/artifacts` engine db handle; the - store is injected (`ArtifactRoutesStore` / `WorkflowArtifactRoutesStore`) - so tests exercise happy/empty/cross-tenant paths without a live - Postgres. -- `@corbits/artifact-tools`' `artifact_list_recent` and - `@corbits/memory-hub` (workflow-memory's sibling surface) both follow - the same authenticator pattern this package established. - -## Key modules - -- `routes.ts` — `createArtifactRoutes`: list/get/upload/counts under - tenant-session auth; `createArtifactDbStore` wraps the engine db. -- `workflow-auth.ts` — `createWorkflowRunAuthenticator`: resolves a - sidecar bearer token + run address pair to a tenant/principal/run scope. -- `workflow-routes.ts` — `createWorkflowArtifactRoutes`: `POST /` (create, - rate-limited to 30/run/minute, 64k-char content cap), `GET /recent`, - `GET /:id` (read back one artifact's content — the render step of a - research/due-diligence run reading the Markdown brief it just saved), - and `POST /binary` (rate-limited alongside `POST /`, base64 body, - 10 MiB decoded cap — same `MAX_UPLOAD_BYTES` ceiling and `ContentStore` - the tenant Library's own upload path uses, so a run can persist a - rendered PDF). All four are scoped to the authenticated run's own - tenant + principal. -- `createUnavailableArtifactRoutes` / `createUnavailableWorkflowArtifactRoutes` - — honest 503 surfaces when the artifacts plane isn't mounted, so the - Library UI can distinguish "not configured" from "empty bench". - -## Tests - -``` -cd packages/artifacts-hub && bun test -``` - -No DATABASE_URL needed — stores are injected fakes. diff --git a/packages/artifacts-hub/package.json b/packages/artifacts-hub/package.json deleted file mode 100644 index e636836a13..0000000000 --- a/packages/artifacts-hub/package.json +++ /dev/null @@ -1,32 +0,0 @@ -{ - "name": "@corbits/artifacts-hub", - "private": true, - "description": "Tenant-scoped Library HTTP surface over the mounted @corbits/artifacts engine: list, get-by-id, multipart upload, and per-kind-segment counts for the Library nav", - "version": "0.0.1", - "license": "LGPL-2.1-or-later", - "type": "module", - "exports": { - ".": "./src/index.ts" - }, - "scripts": { - "typecheck": "tsc --noEmit", - "test": "bun test" - }, - "dependencies": { - "@corbits/artifact-ui": "workspace:*", - "@corbits/artifacts": "github:corbitsdev/corbits-artifacts#dc435ba749b4378f19e5de772159c2a57e932938", - "@corbits/collections": "workspace:*", - "@corbits/error-sink": "workspace:*", - "@intx/crypto": "0.3.0", - "@intx/db": "workspace:*", - "@intx/hub-api": "workspace:*", - "@intx/types": "workspace:*", - "arktype": "catalog:", - "drizzle-orm": "catalog:", - "hono": "catalog:" - }, - "devDependencies": { - "@types/bun": "catalog:", - "typescript": "catalog:" - } -} diff --git a/packages/artifacts-hub/src/index.ts b/packages/artifacts-hub/src/index.ts deleted file mode 100644 index b6bc1678dc..0000000000 --- a/packages/artifacts-hub/src/index.ts +++ /dev/null @@ -1,28 +0,0 @@ -export { - ArtifactCountsIncompleteError, - createArtifactDbStore, - createArtifactRoutes, - createUnavailableArtifactRoutes, - type ArtifactCounts, - type ArtifactListPage, - type ArtifactRoutesStore, - type ArtifactUploadInput, - type CreateArtifactRoutesDeps, -} from "./routes"; -export { - createWorkflowRunAuthenticator, - type ResolvedWorkflowRunScope, - type WorkflowRunAuthenticator, -} from "./workflow-auth"; -export { - createUnavailableWorkflowArtifactRoutes, - createWorkflowArtifactDbStore, - createWorkflowArtifactRoutes, - MAX_WORKFLOW_BINARY_BYTES, - type CreateWorkflowArtifactInput, - type CreateWorkflowArtifactRoutesDeps, - type CreateWorkflowBinaryArtifactInput, - type CreatedWorkflowArtifact, - type WorkflowArtifactEnv, - type WorkflowArtifactRoutesStore, -} from "./workflow-routes"; diff --git a/packages/artifacts-hub/src/routes.test.ts b/packages/artifacts-hub/src/routes.test.ts deleted file mode 100644 index 7f9f1e68cc..0000000000 --- a/packages/artifacts-hub/src/routes.test.ts +++ /dev/null @@ -1,609 +0,0 @@ -import { beforeEach, describe, expect, test } from "bun:test"; -import type { RequireGrant } from "@intx/hub-api"; -import type { ArtifactDb, ArtifactRow, ContentStore } from "@corbits/artifacts"; -import { Hono } from "hono"; - -import { - createArtifactRoutes, - createUnavailableArtifactRoutes, - resolvePreviewableContent, - type ArtifactPreviewResult, - type ArtifactRoutesStore, - type ArtifactUploadInput, -} from "./routes"; - -type Tenant = { id: string }; -type Principal = { id: string }; - -type TestEnv = { - Variables: { - tenant: Tenant; - principal: Principal; - }; -}; - -const TENANT = { id: "tenant_a" }; -const OTHER = { id: "tenant_b" }; -const PRINCIPAL = { id: "prin_1" }; - -const allowAll: RequireGrant = () => async (_c, next) => { - await next(); -}; - -type Row = { - id: string; - kind: string; - title: string; - source: { origin: string }; - version: number; - ownerPrincipalId: string; - ownerName: string | null; - archivedAt: string | null; - createdAt: string; - updatedAt: string; - content: string; - mimeType: string; - _tenantId: string; -}; - -function sampleRow(id: string, tenantId: string, content = ""): Row { - return { - id, - kind: "file", - title: `doc-${id}.txt`, - source: { origin: "library-upload" }, - version: 1, - ownerPrincipalId: PRINCIPAL.id, - ownerName: null, - archivedAt: null, - createdAt: "2026-01-01T00:00:00.000Z", - updatedAt: "2026-01-01T00:00:00.000Z", - content, - mimeType: "text/plain", - _tenantId: tenantId, - }; -} - -function stripTenant(row: Row) { - const { _tenantId: _t, ...rest } = row; - return rest; -} - -function memoryStore(): ArtifactRoutesStore & { rows: Row[] } { - const rows: Row[] = []; - return { - rows, - async list(tenantId, opts) { - let data = rows - .filter((r) => r._tenantId === tenantId) - .map((r) => { - const { content: _c, ...item } = stripTenant(r); - return item; - }); - if (opts.query !== null) { - const q = opts.query.toLowerCase(); - data = data.filter((r) => r.title.toLowerCase().includes(q)); - } - return { - data: data.slice(0, opts.limit), - nextCursor: null, - }; - }, - async get(tenantId, artifactId) { - const row = rows.find( - (r) => r.id === artifactId && r._tenantId === tenantId, - ); - if (row === undefined) return null; - return stripTenant(row); - }, - async upload( - tenantId: string, - principalId: string, - files: readonly ArtifactUploadInput[], - ) { - return files.map((file, index) => { - const item = sampleRow(`up_${rows.length + index}`, tenantId); - item.title = file.filename; - item.ownerPrincipalId = principalId; - item.content = new TextDecoder().decode(file.bytes); - item.mimeType = file.mimeType; - rows.push(item); - return stripTenant(item); - }); - }, - async preview(tenantId, artifactId): Promise { - const row = rows.find( - (r) => r.id === artifactId && r._tenantId === tenantId, - ); - if (row === undefined) return { status: "not_found" }; - if (row.mimeType !== "text/html") return { status: "unsupported" }; - return { status: "ok", html: row.content }; - }, - async update(tenantId, _principalId, artifactId, content) { - const row = rows.find( - (r) => r.id === artifactId && r._tenantId === tenantId, - ); - if (row === undefined) return null; - row.content = content; - row.version += 1; - return stripTenant(row); - }, - }; -} - -function mount(store: ArtifactRoutesStore) { - const app = new Hono(); - app.use("*", async (c, next) => { - c.set("tenant", TENANT); - c.set("principal", PRINCIPAL); - await next(); - }); - app.route( - "/artifacts", - createArtifactRoutes({ store, requireGrant: allowAll }), - ); - return app; -} - -describe("artifact routes", () => { - let store: ReturnType; - let app: ReturnType; - - beforeEach(() => { - store = memoryStore(); - app = mount(store); - }); - - test("GET / lists empty data for a tenant with no artifacts", async () => { - const res = await app.request("/artifacts"); - expect(res.status).toBe(200); - expect(await res.json()).toEqual({ data: [], nextCursor: null }); - }); - - test("GET / returns only the calling tenant's rows", async () => { - store.rows.push(sampleRow("a1", TENANT.id, "mine")); - store.rows.push(sampleRow("b1", OTHER.id, "theirs")); - const res = await app.request("/artifacts"); - expect(res.status).toBe(200); - const body = (await res.json()) as { data: { id: string }[] }; - expect(body.data.map((r) => r.id)).toEqual(["a1"]); - }); - - test("GET /?q= filters by title", async () => { - store.rows.push({ - ...sampleRow("a1", TENANT.id, "x"), - title: "Quarterly report.pdf", - }); - store.rows.push({ - ...sampleRow("a2", TENANT.id, "y"), - title: "notes.txt", - }); - const res = await app.request("/artifacts?q=report"); - expect(res.status).toBe(200); - const body = (await res.json()) as { data: { id: string }[] }; - expect(body.data.map((r) => r.id)).toEqual(["a1"]); - }); - - test("GET /:id returns 404 for a foreign tenant row", async () => { - store.rows.push(sampleRow("b1", OTHER.id, "secret")); - const res = await app.request("/artifacts/b1"); - expect(res.status).toBe(404); - }); - - test("GET /:id returns the row for the calling tenant", async () => { - store.rows.push(sampleRow("a1", TENANT.id, "hello")); - const res = await app.request("/artifacts/a1"); - expect(res.status).toBe(200); - const body = (await res.json()) as { id: string; content: string }; - expect(body.id).toBe("a1"); - expect(body.content).toBe("hello"); - }); - - test("PUT /:id saves a new version and returns the updated row", async () => { - store.rows.push(sampleRow("a1", TENANT.id, "hello")); - const res = await app.request("/artifacts/a1", { - method: "PUT", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ content: "edited" }), - }); - expect(res.status).toBe(200); - const body = (await res.json()) as { content: string; version: number }; - expect(body.content).toBe("edited"); - expect(body.version).toBe(2); - }); - - test("PUT /:id returns 404 for a foreign tenant row", async () => { - store.rows.push(sampleRow("b1", OTHER.id, "secret")); - const res = await app.request("/artifacts/b1", { - method: "PUT", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ content: "edited" }), - }); - expect(res.status).toBe(404); - }); - - test("PUT /:id returns 400 without a string content field", async () => { - store.rows.push(sampleRow("a1", TENANT.id, "hello")); - const res = await app.request("/artifacts/a1", { - method: "PUT", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify({}), - }); - expect(res.status).toBe(400); - }); - - test("GET /:id/preview serves HTML with a strict sandbox CSP", async () => { - const row = sampleRow("html1", TENANT.id, "hi"); - row.mimeType = "text/html"; - store.rows.push(row); - const res = await app.request("/artifacts/html1/preview"); - expect(res.status).toBe(200); - expect(res.headers.get("Content-Type")).toBe("text/html; charset=utf-8"); - expect(res.headers.get("Content-Security-Policy")).toBe( - "sandbox allow-scripts; default-src 'none'; style-src 'unsafe-inline'; img-src data:; script-src 'unsafe-inline'", - ); - expect(res.headers.get("X-Frame-Options")).toBeNull(); - expect(await res.text()).toBe("hi"); - }); - - test("GET /:id/preview answers 415 for a non-HTML artifact", async () => { - store.rows.push(sampleRow("txt1", TENANT.id, "plain text")); - const res = await app.request("/artifacts/txt1/preview"); - expect(res.status).toBe(415); - const body = (await res.json()) as { error: { code: string } }; - expect(body.error.code).toBe("unsupported_media_type"); - }); - - test("GET /:id/preview answers 404 for a foreign tenant row", async () => { - const row = sampleRow("html2", OTHER.id, ""); - row.mimeType = "text/html"; - store.rows.push(row); - const res = await app.request("/artifacts/html2/preview"); - expect(res.status).toBe(404); - }); - - test("POST /upload creates artifacts from multipart files", async () => { - const form = new FormData(); - form.append( - "file", - new File(["hello library"], "hello.txt", { type: "text/plain" }), - ); - const res = await app.request("/artifacts/upload", { - method: "POST", - body: form, - }); - expect(res.status).toBe(201); - const body = (await res.json()) as { - data: { title: string; content: string }[]; - }; - expect(body.data).toHaveLength(1); - expect(body.data[0]?.title).toBe("hello.txt"); - expect(body.data[0]?.content).toBe("hello library"); - expect(store.rows).toHaveLength(1); - }); - - test("POST /upload rejects an empty multipart body", async () => { - const form = new FormData(); - form.append("note", "not a file"); - const res = await app.request("/artifacts/upload", { - method: "POST", - body: form, - }); - expect(res.status).toBe(400); - }); - - test("POST /upload rejects a file over the per-file byte limit instead of storing it empty", async () => { - const oversized = new Uint8Array(10 * 1024 * 1024 + 1); - const form = new FormData(); - form.append( - "file", - new File([oversized], "huge.txt", { type: "text/plain" }), - ); - const res = await app.request("/artifacts/upload", { - method: "POST", - body: form, - }); - expect(res.status).toBe(413); - const body = (await res.json()) as { error: { code: string } }; - expect(body.error.code).toBe("payload_too_large"); - // The whole point: an oversized file never reaches the store at all, so - // there is no empty/partial artifact row left behind to look uploaded. - expect(store.rows).toHaveLength(0); - }); - - test("GET /counts is all zero for a tenant with no artifacts", async () => { - const res = await app.request("/artifacts/counts"); - expect(res.status).toBe(200); - expect(await res.json()).toEqual({ - all: 0, - document: 0, - sheet: 0, - pdf: 0, - routine: 0, - }); - }); - - test("GET /counts buckets by kind segment and ignores other tenants", async () => { - store.rows.push({ - ...sampleRow("doc1", TENANT.id), - kind: "document", - title: "brief", - }); - store.rows.push({ - ...sampleRow("sheet1", TENANT.id), - kind: "file", - title: "budget.csv", - }); - store.rows.push({ - ...sampleRow("pdf1", TENANT.id), - kind: "pdf", - title: "contract.pdf", - }); - store.rows.push({ - ...sampleRow("routine1", TENANT.id), - kind: "routine", - title: "weekly digest", - }); - store.rows.push({ - ...sampleRow("other-tenant", OTHER.id), - kind: "document", - title: "not mine", - }); - const res = await app.request("/artifacts/counts"); - expect(res.status).toBe(200); - expect(await res.json()).toEqual({ - all: 4, - document: 1, - sheet: 1, - pdf: 1, - routine: 1, - }); - }); -}); - -describe("GET /counts pagination", () => { - function paginatedStore(rows: Row[], pageLimit: number): ArtifactRoutesStore { - return { - async list(tenantId, opts) { - const tenantRows = rows - .filter((r) => r._tenantId === tenantId) - .map((r) => { - const { content: _c, ...item } = stripTenant(r); - return item; - }); - const offset = - opts.cursor === null ? 0 : Number.parseInt(opts.cursor, 10); - const limit = Math.min(opts.limit, pageLimit); - const page = tenantRows.slice(offset, offset + limit); - const nextOffset = offset + page.length; - return { - data: page, - nextCursor: - nextOffset < tenantRows.length ? String(nextOffset) : null, - }; - }, - async get() { - return null; - }, - async upload() { - return []; - }, - async preview() { - return { status: "not_found" }; - }, - async update() { - return null; - }, - }; - } - - test("walks every cursor page without double-counting or dropping a row at the boundary", async () => { - const rows: Row[] = []; - const expected = { all: 0, document: 0, sheet: 0, pdf: 0, routine: 0 }; - function rowKindAndTitle(i: number): { kind: string; title: string } { - switch (i % 4) { - case 0: - return { kind: "document", title: `brief-${i}` }; - case 1: - return { kind: "pdf", title: `contract-${i}.pdf` }; - case 2: - return { kind: "routine", title: `digest-${i}` }; - default: - return { kind: "file", title: `budget-${i}.csv` }; // sheet, by extension - } - } - for (let i = 0; i < 250; i++) { - const { kind, title } = rowKindAndTitle(i); - rows.push({ ...sampleRow(`r${i}`, TENANT.id), kind, title }); - expected.all += 1; - if (kind === "document") expected.document += 1; - if (kind === "pdf") expected.pdf += 1; - if (kind === "routine") expected.routine += 1; - if (kind === "file") expected.sheet += 1; - } - // Store's own page size (25) is smaller than the route's per-page walk - // limit (100, capped by MAX_LIMIT) so a real multi-page walk exercises - // several boundaries, not just the one the route itself requests. - const app = mount(paginatedStore(rows, 25)); - - const res = await app.request("/artifacts/counts"); - expect(res.status).toBe(200); - expect(await res.json()).toEqual(expected); - }); - - test("answers 503 instead of a partial count when the tenant list exceeds the page cap", async () => { - const neverEndingStore: ArtifactRoutesStore = { - async list(_tenantId, opts) { - const next = - opts.cursor === null - ? "1" - : String(Number.parseInt(opts.cursor, 10) + 1); - return { data: [], nextCursor: next }; - }, - async get() { - return null; - }, - async upload() { - return []; - }, - async preview() { - return { status: "not_found" }; - }, - async update() { - return null; - }, - }; - const app = mount(neverEndingStore); - - const res = await app.request("/artifacts/counts"); - expect(res.status).toBe(503); - const body = (await res.json()) as { error: { code: string } }; - expect(body.error.code).toBe("counts_unavailable"); - }); - - test("answers 503 instead of hanging when the store's cursor stops advancing", async () => { - const stuckCursorStore: ArtifactRoutesStore = { - async list(_tenantId, opts) { - const next = opts.cursor === null ? "A" : opts.cursor; - return { data: [], nextCursor: next }; - }, - async get() { - return null; - }, - async upload() { - return []; - }, - async preview() { - return { status: "not_found" }; - }, - async update() { - return null; - }, - }; - const app = mount(stuckCursorStore); - - const res = await app.request("/artifacts/counts"); - expect(res.status).toBe(503); - const body = (await res.json()) as { error: { code: string } }; - expect(body.error.code).toBe("counts_unavailable"); - }); -}); - -describe("unavailable artifact routes", () => { - test("every surface answers 503", async () => { - const app = new Hono(); - app.use("*", async (c, next) => { - c.set("tenant", TENANT); - c.set("principal", PRINCIPAL); - await next(); - }); - app.route("/artifacts", createUnavailableArtifactRoutes(allowAll)); - - for (const path of [ - "/artifacts", - "/artifacts/upload", - "/artifacts/counts", - "/artifacts/x", - "/artifacts/x/preview", - ]) { - const method = path.endsWith("/upload") ? "POST" : "GET"; - const res = await app.request(path, { method }); - expect(res.status).toBe(503); - const body = (await res.json()) as { error: { code: string } }; - expect(body.error.code).toBe("unavailable"); - } - }); -}); - -describe("resolvePreviewableContent", () => { - const NOT_CALLED: ArtifactDb = undefined as unknown as ArtifactDb; - - function blobBackedRow(overrides: Partial = {}): ArtifactRow { - return { - id: "a1", - tenantId: "tenant_a", - principalId: "prin_1", - ownerPrincipalId: "prin_1", - kind: "file", - title: "SKILL.md", - content: "", - source: { origin: "library-upload", upload: { id: "up_1" } }, - version: 1, - archivedAt: null, - createdAt: new Date("2026-01-01T00:00:00.000Z"), - updatedAt: new Date("2026-01-01T00:00:00.000Z"), - ...overrides, - } as ArtifactRow; - } - - function contentStoreReturning( - blob: { filename: string; mimeType: string; bytes: Uint8Array } | null, - ): ContentStore { - return { - put: () => { - throw new Error( - "put should not be called by resolvePreviewableContent", - ); - }, - get: async () => blob, - }; - } - - test("inlines the out-of-band blob when it decodes as text", async () => { - const bytes = new TextEncoder().encode("---\nname: SKILL\n---\nbody"); - const store = contentStoreReturning({ - filename: "SKILL.md", - mimeType: "text/markdown", - bytes, - }); - const content = await resolvePreviewableContent( - NOT_CALLED, - store, - blobBackedRow(), - ); - expect(content).toBe("---\nname: SKILL\n---\nbody"); - }); - - test("leaves content empty for a non-text-decodable blob instead of decoding garbage", async () => { - const store = contentStoreReturning({ - filename: "photo.png", - mimeType: "image/png", - bytes: new Uint8Array([0x89, 0x50, 0x4e, 0x47]), - }); - const content = await resolvePreviewableContent( - NOT_CALLED, - store, - blobBackedRow({ title: "photo.png" }), - ); - expect(content).toBe(""); - }); - - test("never touches the content store when the row already carries inline content", async () => { - const store: ContentStore = { - put: () => { - throw new Error("put should not be called"); - }, - get: () => { - throw new Error( - "get should not be called when content is already inline", - ); - }, - }; - const content = await resolvePreviewableContent( - NOT_CALLED, - store, - blobBackedRow({ content: "already inline", source: {} }), - ); - expect(content).toBe("already inline"); - }); - - test("leaves content empty when the referenced blob cannot be found", async () => { - const store = contentStoreReturning(null); - const content = await resolvePreviewableContent( - NOT_CALLED, - store, - blobBackedRow(), - ); - expect(content).toBe(""); - }); -}); diff --git a/packages/artifacts-hub/src/routes.ts b/packages/artifacts-hub/src/routes.ts deleted file mode 100644 index e3161bea30..0000000000 --- a/packages/artifacts-hub/src/routes.ts +++ /dev/null @@ -1,572 +0,0 @@ -/** - * Tenant-scoped Library HTTP surface over the mounted `@corbits/artifacts` - * engine: list (newest-first, paginated, optional text search), get-by-id, - * multipart upload, and per-kind-segment counts for the Library nav. - * - * Authz uses the existing `asset` resource family so Library grants keep - * working without inventing a parallel vocabulary. - * - * The store is injected so tests can exercise happy/empty/cross-tenant - * without a live Postgres. - */ -import { - ARTIFACT_UPLOAD_POLICY, - createFileArtifact, - getArtifact, - listArtifacts, - resolveDownload, - serializeArtifact, - serializeArtifactListItem, - UnsupportedUploadTypeError, - writeArtifactVersion, - type ArtifactDb, - type ArtifactRow, - type ContentStore, - type SerializedArtifact, - type SerializedArtifactListItem, -} from "@corbits/artifacts"; -import { - LIBRARY_KIND_SEGMENTS, - artifactMatchesLibraryKindSegment, - type LibraryKindSegment, -} from "@corbits/artifact-ui/kind-filter"; -import { isTextDecodableMediaType } from "@corbits/artifact-ui/renderer-kind"; -import type { RequireGrant, TenantEnv } from "@intx/hub-api"; -import { Hono } from "hono"; -import { makeErrorEnvelope } from "@corbits/error-sink"; - -const DEFAULT_LIMIT = 50; -const MAX_LIMIT = 100; -const MAX_UPLOAD_BYTES = 10 * 1024 * 1024; -const MAX_UPLOAD_FILE_COUNT = 50; -const MAX_UPLOAD_TOTAL_BYTES = 100 * 1024 * 1024; -// Safety cap on the counts walk: 200 pages of MAX_LIMIT rows each is 20,000 -// artifacts, far past any real tenant today. A tenant that legitimately -// exceeds it — or a store whose cursor stops advancing — gets an honest -// "can't count that" instead of a route that hangs or lies with a partial -// total. -const MAX_COUNT_PAGES = 200; - -/** Thrown when the counts walk cannot finish honestly — capped out or the - * store's cursor stopped advancing — rather than ever returning a partial - * count as if it were the whole tenant. */ -export class ArtifactCountsIncompleteError extends Error {} - -export type ArtifactListPage = { - readonly data: readonly SerializedArtifactListItem[]; - readonly nextCursor: string | null; -}; - -/** Per-kind-segment counts for the Library nav, plus the tenant total. */ -export type ArtifactCounts = { - readonly all: number; -} & { readonly [K in (typeof LIBRARY_KIND_SEGMENTS)[number]]: number }; - -export type ArtifactUploadInput = { - readonly filename: string; - readonly mimeType: string; - readonly bytes: Uint8Array; -}; - -/** Outcome of resolving an artifact's sandboxed HTML preview. */ -export type ArtifactPreviewResult = - | { readonly status: "ok"; readonly html: string } - | { readonly status: "not_found" } - | { readonly status: "unsupported" }; - -/** Minimal port the routes need — production wraps the engine db. */ -export type ArtifactRoutesStore = { - list( - tenantId: string, - opts: { limit: number; cursor: string | null; query: string | null }, - ): Promise; - get(tenantId: string, artifactId: string): Promise; - upload( - tenantId: string, - principalId: string, - files: readonly ArtifactUploadInput[], - ): Promise; - preview(tenantId: string, artifactId: string): Promise; - /** - * Writes a new version of a document-kind artifact's content (CL-8189): - * the artifact editor's one save path now that co-edit presence is gone. - * Returns `null` for an artifact the tenant can't see, so the route can - * answer 404 the same way `get` does. - */ - update( - tenantId: string, - principalId: string, - artifactId: string, - content: string, - ): Promise; -}; - -/** Bare MIME type, stripped of any `; charset=...` parameter. */ -function baseMimeType(mimeType: string): string { - return mimeType.split(";")[0]?.trim().toLowerCase() ?? ""; -} - -/** - * `createFileArtifact` (the ONE path a browser upload goes through) always - * leaves the artifact row's own `content` column empty — the bytes it just - * accepted live out-of-band, in `ContentStore`, referenced by - * `source.upload.id`. That is correct for the store, but a naive detail read - * of `content` alone reads back as "no content" even when the upload was a - * plain-text file (Markdown, CSV, JSON, ...) whose bytes are intact. - * - * This resolves the out-of-band blob and inlines it into `content` whenever - * it decodes as text — the same thing `/preview` already does for HTML, - * generalized to every text-decodable MIME type. A non-text blob (an image, - * a real PDF, a legacy `.docx`) is left as `""`: its bytes are still safe in - * the content store, this route only ever projects them into `content` when - * doing so is an honest text rendering. - */ -export async function resolvePreviewableContent( - db: ArtifactDb, - contentStore: ContentStore, - row: ArtifactRow, -): Promise { - if (row.content !== "") return row.content; - const download = await resolveDownload(db, contentStore, row, false); - if ("status" in download || !isTextDecodableMediaType(download.mimeType)) { - return row.content; - } - return typeof download.body === "string" - ? download.body - : new TextDecoder().decode(download.body); -} - -export type CreateArtifactRoutesDeps = { - store: ArtifactRoutesStore; - requireGrant: RequireGrant; -}; - -function parseLimit(raw: string | undefined): number { - if (raw === undefined || raw === "") return DEFAULT_LIMIT; - const n = Number.parseInt(raw, 10); - if (!Number.isFinite(n) || n < 1) return DEFAULT_LIMIT; - return Math.min(n, MAX_LIMIT); -} - -function parseCursor( - raw: string | undefined, -): { at: string; id: string } | undefined { - if (raw === undefined || raw === "") return undefined; - const sep = raw.lastIndexOf("__"); - if (sep <= 0 || sep === raw.length - 2) return undefined; - const at = raw.slice(0, sep); - const id = raw.slice(sep + 2); - if (!at || !id) return undefined; - return { at, id }; -} - -function parseQuery(raw: string | undefined): string | null { - if (raw === undefined) return null; - const trimmed = raw.trim(); - if (trimmed === "") return null; - return trimmed.slice(0, 200); -} - -/** - * Walks every page of a tenant's artifacts (unfiltered, so the same row - * never gets double-counted or missed at a page boundary) and buckets each - * row by the Library kind nav's segment predicate. Real counts over the - * full tenant list, not an estimate from one page. - */ -async function countArtifactsByKindSegment( - store: Pick, - tenantId: string, -): Promise { - let all = 0; - const bySegment: Record = { - document: 0, - sheet: 0, - pdf: 0, - routine: 0, - }; - - let cursor: string | null = null; - let pages = 0; - for (;;) { - const page = await store.list(tenantId, { - limit: MAX_LIMIT, - cursor, - query: null, - }); - pages += 1; - for (const row of page.data) { - all += 1; - for (const segment of LIBRARY_KIND_SEGMENTS) { - if (artifactMatchesLibraryKindSegment(row, segment)) { - bySegment[segment] += 1; - } - } - } - if (page.nextCursor === null) break; - if (page.nextCursor === cursor) { - throw new ArtifactCountsIncompleteError( - `Artifact list cursor for tenant ${tenantId} did not advance past page ${pages}`, - ); - } - if (pages >= MAX_COUNT_PAGES) { - throw new ArtifactCountsIncompleteError( - `Artifact list for tenant ${tenantId} exceeds ${MAX_COUNT_PAGES} pages — counts would be incomplete`, - ); - } - cursor = page.nextCursor; - } - - return { - all, - document: bySegment.document, - sheet: bySegment.sheet, - pdf: bySegment.pdf, - routine: bySegment.routine, - }; -} - -/** Prefer the browser-declared type when the upload policy accepts it. */ -function resolveUploadMime(file: { name: string; type: string }): string { - if (file.type !== "" && ARTIFACT_UPLOAD_POLICY.accepts(file.type)) { - return file.type; - } - return file.type === "" ? "application/octet-stream" : file.type; -} - -/** Production store over an artifacts engine db handle + content store. */ -export function createArtifactDbStore( - db: ArtifactDb, - contentStore: ContentStore, -): ArtifactRoutesStore { - return { - async list(tenantId, opts) { - const cursor = parseCursor(opts.cursor ?? undefined); - const withCursor = - cursor !== undefined - ? { limit: opts.limit, cursor } - : { limit: opts.limit }; - const filters = - opts.query !== null ? { ...withCursor, query: opts.query } : withCursor; - const result = await listArtifacts(db, tenantId, filters); - return { - data: result.rows.map(serializeArtifactListItem), - nextCursor: result.nextCursor, - }; - }, - async get(tenantId, artifactId) { - const row = await getArtifact(db, artifactId); - if (row === null || row.tenantId !== tenantId) return null; - const content = await resolvePreviewableContent(db, contentStore, row); - return { ...serializeArtifact(row), content }; - }, - async upload(tenantId, principalId, files) { - const scope = { tenantId, principalId }; - const rows = await db.transaction(async (tx) => { - const created = []; - for (const file of files) { - created.push( - await createFileArtifact(tx, contentStore, { - scope, - ownerPrincipalId: principalId, - filename: file.filename, - mimeType: file.mimeType, - policy: ARTIFACT_UPLOAD_POLICY, - bytes: file.bytes, - origin: "library-upload", - }), - ); - } - return created; - }); - return rows.map(serializeArtifact); - }, - async preview(tenantId, artifactId) { - const row = await getArtifact(db, artifactId); - if (row === null || row.tenantId !== tenantId) - return { status: "not_found" }; - const download = await resolveDownload(db, contentStore, row, false); - if ("status" in download) { - return { - status: download.status === 404 ? "not_found" : "unsupported", - }; - } - if (baseMimeType(download.mimeType) !== "text/html") { - return { status: "unsupported" }; - } - const html = - typeof download.body === "string" - ? download.body - : new TextDecoder().decode(download.body); - return { status: "ok", html }; - }, - async update(tenantId, principalId, artifactId, content) { - const row = await getArtifact(db, artifactId); - if (row === null || row.tenantId !== tenantId) return null; - await writeArtifactVersion(db, { - scope: { tenantId, principalId }, - artifactId, - content, - }); - const written = await getArtifact(db, artifactId); - if (written === null) return null; - return { ...serializeArtifact(written), content: written.content }; - }, - }; -} - -export function createArtifactRoutes( - deps: CreateArtifactRoutesDeps, -): Hono { - const app = new Hono(); - - app.get("/", deps.requireGrant("asset:*", "read"), async (c) => { - const tenant = c.get("tenant"); - const limit = parseLimit(c.req.query("limit")); - const cursor = c.req.query("cursor") ?? null; - const query = parseQuery(c.req.query("q") ?? undefined); - const page = await deps.store.list(tenant.id, { limit, cursor, query }); - return c.json(page); - }); - - app.post("/upload", deps.requireGrant("asset:*", "write"), async (c) => { - const tenant = c.get("tenant"); - const principal = c.get("principal"); - - let parsed: Record; - try { - parsed = (await c.req.parseBody({ all: true })) as Record< - string, - unknown - >; - } catch { - return c.json( - makeErrorEnvelope({ - code: "bad_request", - userMessage: "Invalid multipart body", - }), - 400, - ); - } - - const files: File[] = []; - for (const value of Object.values(parsed)) { - for (const entry of Array.isArray(value) ? value : [value]) { - if (entry instanceof File) files.push(entry); - } - } - - if (files.length === 0) { - return c.json( - makeErrorEnvelope({ - code: "bad_request", - userMessage: "Expected at least one file field", - }), - 400, - ); - } - if (files.length > MAX_UPLOAD_FILE_COUNT) { - return c.json( - makeErrorEnvelope({ - code: "payload_too_large", - userMessage: `Too many files: ${files.length} exceeds the ${MAX_UPLOAD_FILE_COUNT} file limit`, - }), - 413, - ); - } - - let totalBytes = 0; - const inputs: ArtifactUploadInput[] = []; - for (const file of files) { - if (file.size > MAX_UPLOAD_BYTES) { - return c.json( - makeErrorEnvelope({ - code: "payload_too_large", - userMessage: `File "${file.name}" exceeds the ${MAX_UPLOAD_BYTES} byte limit`, - }), - 413, - ); - } - totalBytes += file.size; - if (totalBytes > MAX_UPLOAD_TOTAL_BYTES) { - return c.json( - makeErrorEnvelope({ - code: "payload_too_large", - userMessage: `Upload exceeds the ${MAX_UPLOAD_TOTAL_BYTES} byte aggregate limit`, - }), - 413, - ); - } - inputs.push({ - filename: file.name, - mimeType: resolveUploadMime(file), - bytes: new Uint8Array(await file.arrayBuffer()), - }); - } - - try { - const data = await deps.store.upload(tenant.id, principal.id, inputs); - return c.json({ data }, 201); - } catch (err) { - if (err instanceof UnsupportedUploadTypeError) { - return c.json( - makeErrorEnvelope({ - code: "unsupported_media_type", - userMessage: err.message, - }), - 415, - ); - } - throw err; - } - }); - - app.get("/counts", deps.requireGrant("asset:*", "read"), async (c) => { - const tenant = c.get("tenant"); - try { - const counts = await countArtifactsByKindSegment(deps.store, tenant.id); - return c.json(counts); - } catch (err) { - if (err instanceof ArtifactCountsIncompleteError) { - return c.json( - makeErrorEnvelope({ - code: "counts_unavailable", - userMessage: err.message, - }), - 503, - ); - } - throw err; - } - }); - - // Sandboxed HTML preview: served with a locked-down CSP so a self-contained - // page renders visually but can reach nothing on the hub's own origin. - // - `sandbox allow-scripts` (the header, mirrored by the iframe's own - // `sandbox` attribute): scripts may run, but the document sits in an - // opaque unique origin — no cookies, no storage, no same-origin fetches, - // no top-level navigation, no popups. - // - `default-src 'none'`: nothing loads unless a more specific directive - // below allows it — no network reach to the hub API or anywhere else. - // - `style-src 'unsafe-inline'`: inline `