@softure-ai/files
v0.6.1
Published
SOFTURE AI files module: an app's stored files (content hash, size, type, owner, kind, expiry, a per-owner quota, opt-in dedupe) on a storage driver (local disk with atomic writes, S3-compatible with SigV4 and multipart uploads, in memory for tests), stre
Readme
@softure-ai/files
Stored files for a Next.js app that takes uploads or produces media (rendered videos, exports, reports), and public links that hand one of them to a third party: a social media scheduler that fetches media from a URL, a mail with a large download, a webhook consumer. The module keeps one table, puts the bytes on a storage driver (a folder on a volume, or an S3-compatible bucket), and serves links that work without the app's session, serve byte ranges for video and stop working after their time. A client that cannot hand the server a stream (an assistant in its own sandbox, a phone behind a proxy with a body limit) uploads through a signed URL in resumable chunks.
1. What it provides
- A table of files (
files.files): owner, SHA-256, size, content type, sanitised original name, kind (the app's own category, e.g.input,output), expiry, soft delete. saveFile(ctx, { ownerId, body | path, name, contentType?, kind?, expiresAt? | ttlSeconds? }): the body is hashed and counted while it streams into storage, one chunk in memory at a time;maxFileBytesstops it at the first chunk over, a per-owner quota (quotaBytesPerOwner) is checked before and again under a per-owner lock after, and withdedupean owner's second copy of the same content answers the first file. A refused or failed save leaves no bytes and no row.saveFileFromUrl(ctx, { ownerId, url, name?, contentType?, contentTypes?, kind?, expiresAt? | ttlSeconds?, timeoutMs? }): a file at anhttps:URL (a document someone links to), downloaded through@softure-ai/security's guarded download (every redirect checked against private and loopback addresses,https:only, one time limit for the whole download) and streamed intosaveFile, so its cap, quota and dedupe apply. See "Saving a file from a URL" below.findFile,openFile(a byte range or the whole file),listFiles,deleteFile,getOwnerUsage: live files only (neither deleted nor expired); anownerIdfilter makes another owner's file read as missing.setFileExpiry(ctx, fileId, { ownerId?, expiresAt }): changes a live file's expiry after it was saved;nullkeeps it until it is deleted (an app that keeps the files a rule of its own chooses), a date after the file was saved letspruneFilestake it then. A deleted or expired file answersfiles.not_found.- Storage drivers behind one interface (
put,getwith a range,head,delete, an optionalcheck):createLocalStorage({ dir })(partial file renamed into place, keys fanned out by file id) andcreateS3Storage({ endpoint, bucket, ... })for Cloudflare R2, MinIO, Garage or AWS S3 (SigV4 withnode:crypto, singlePUTor a multipart upload that holds one part in memory). Write your own for anything else. - Public links:
createFileLink(ctx, fileId, { ttlSeconds, downloadName? })answershttps://<app>/f/<id>/<expiry>/<generation>.<mac>/<name>, an HMAC-SHA256 over every part. The route (serveFileLinkRoute) checks the MAC and the expiry before any database read, answersGETandHEADwithContent-Length,Accept-Ranges,206for a range,416past the end,Content-Disposition, andCache-Control: private, no-store(no CDN keeps a copy), and the same404for an expired, revoked, deleted or forged link.revokeFileLinks(ctx, fileId)stops every link made so far. - The owner's own view:
serveStoredFile(ctx, fileId, request, { ownerId })and the Next routecreateStoredFileRoute({ getOwnerId })give the signed-in owner the same answer (ranges, headers, one404) for a player or an image in the app's own page, with no public link. See §4.4. - Resumable uploads (
files.uploads):createUpload(ctx, { ownerId, name, contentType?, size, sha256?, kind?, ttlSeconds? })opens a session and answers{ uploadId, uploadUrl, chunkSize, chunkCount, expiresAt }. The client sends the file touploadUrlin chunks under the edge's body limit (64 MiB by default), resumes after a dropped connection, andfinalizeUpload(ctx, uploadId)checks every byte and the optional SHA-256 and saves the file likesaveFile(quota, dedupe). See §4.1. - A browser client (
@softure-ai/files/client):sendUpload(file, { uploadUrl, signal?, onProgress? })sends aFileto a session, only the chunks it lacks, andcreateUploadQueue({ open, finalize })keeps an upload list for an upload screen (theme-notion'sUploadItemtakes its items as they are). See §4.3. - MCP upload tools (
@softure-ai/files/mcp):registerFileUploadTools(server, { identity, getContext })addscreate_upload(a signed URL, a readycurlloop and the browser page) andfinalize_upload, so an assistant hands over a video without its bytes going through a tool call. See §4.2. - Retention:
pruneFiles(ctx)removes expired and deleted files from storage and the table, and expired upload sessions with their chunks; thefiles.prunejob (@softure-ai/files/jobs) runs it hourly. Every run logs one linefiles.prune finished removed=<n> freedBytes=<b> failedFiles deletedUploads failedUploads, with the removed ids asfileIdswhen at most 10 went;createFilesJobHandlers({ logger: createLogger("files") })sends it through@softure-ai/observabilityinstead of the console. - A privacy contributor (the export lists the owner's files, the deletion removes them) and a health check
(the table answers, storage takes a write, free space above
health.minFreeBytes). /testing: an in-memory driver, a fixed link keyring,fetchFileLink(status, headers and bytes of a link, with a range orHEAD) andreadFileLinkExpiry.
2. Installation
npm install @softure-ai/files@softure-ai/jobs is an optional peer, needed only for the prune schedule; @modelcontextprotocol/server is an
optional peer, needed only for @softure-ai/files/mcp.
3. Configuration
// softure.config.ts
import { files } from "@softure-ai/files";
import { createLocalStorage } from "@softure-ai/files/server";
files({
storage: createLocalStorage({ dir: "/data/files" }),
maxFileBytes: 500 * 1024 ** 2,
quotaBytesPerOwner: 5 * 1024 ** 3,
dedupe: true,
});| Option | Default | Meaning |
| --- | --- | --- |
| storage | (required) | the driver: createLocalStorage, createS3Storage, createMemoryStorage (tests) or your own FileStorage |
| maxFileBytes | 100 MiB | the largest file saveFile accepts (files.too_large above it) |
| quotaBytesPerOwner | null (none) | the bytes one owner may keep in live files (files.quota_exceeded) |
| dedupe | false | an owner's save of content they already have (same SHA-256) answers the existing file |
| defaultTtlSeconds | null (kept) | the lifetime of a file saved without expiresAt or ttlSeconds |
| links.maxTtlSeconds | 7 days | the longest lifetime createFileLink grants |
| links.disposition | attachment | attachment (a download) or inline (shown by the browser) |
| health.minFreeBytes | 1 GiB | the health check fails below this many free bytes (local disk only) |
| uploads.chunkBytes | 64 MiB | the bytes of one upload request; keep it under the edge's body limit (Cloudflare: 100 MB on Free and Pro, 200 MB on Business) |
| uploads.ttlSeconds | 1 day | how long an upload session and its URL work (at most 7 days); createUpload may ask for less |
| uploads.maxOpenPerOwner | 20 | sessions one owner may have open at once, enough for a batch from a phone (files.too_many_uploads) |
| uploads.contentTypes | null (any) | the media types an upload may declare, video/mp4 or video/* (files.content_type_not_allowed) |
| routes.links | /f | the link route's prefix; mount the route under the same folder |
| routes.uploads | /u | the upload route's prefix; mount the route under the same folder |
Building a driver touches neither the disk nor the network, so next build runs without the folder or the bucket's
keys.
An S3-compatible bucket instead of the disk:
import { createS3Storage } from "@softure-ai/files/server";
files({
storage: createS3Storage({
endpoint: "https://<account>.r2.cloudflarestorage.com", // http://localhost:9000 for MinIO in development
bucket: "app-files",
region: "auto", // R2; the bucket's region elsewhere (MinIO and Garage default to us-east-1)
prefix: "files/", // optional folder in the bucket
// accessKeyIdEnv / secretAccessKeyEnv rename the two variables of §6.
}),
});A multipart upload left behind by a crashed process is aborted by the driver when it can; give the bucket a lifecycle rule that aborts incomplete multipart uploads after a day for the rest.
4. Mounting
One route handler, the public links:
// app/f/[...link]/route.ts
export { serveFileLinkRoute as GET, serveFileLinkRoute as HEAD } from "@softure-ai/files/next";The route has no session and must stay reachable without one. A link is protected by its signature, so:
- keep
/fout of the app's own sign-in guard (createAuthGuard(config, { protect: [...] })of@softure-ai/authguards only the prefixes it lists; do not list/for/); - behind an edge sign-in such as Cloudflare Access on every path, add a bypass for the prefix: with
@softure-ai/host,apps[].access.bypassPaths: [/f]creates the Access application<slug> bypass /f; by hand, a second Access application for<host>/fwith a Bypass policy for everyone; - never cache it at the edge: the answer says
private, no-store, and a cache rule that overrides origin headers must exclude/f.
Server code calls the functions with a context: getFilesContext() from /next in a route or action, or any
{ db, clock, config } in a worker.
import { getFilesContext } from "@softure-ai/files/next";
import { createFileLink, saveFile } from "@softure-ai/files/server";
const ctx = await getFilesContext();
const saved = await saveFile(ctx, { ownerId: user.id, path: renderedPath, name: "promo.mp4", contentType: "video/mp4", kind: "output", ttlSeconds: 7 * 86_400 });
if (!saved.ok) return saved; // files.too_large, files.quota_exceeded, files.invalid_input
const link = await createFileLink(ctx, saved.value.id, { ttlSeconds: 86_400 });
// link.value.url goes to the scheduler; link.value.expiresAt says until when it works.A request body streams in directly: saveFile(ctx, { ownerId, body: request.body, name, contentType }) (a web
ReadableStream is an async iterable in Node 22).
Saving a file from a URL works the same way, with the download's own refusals:
const saved = await saveFileFromUrl(ctx, {
ownerId: user.id,
url: confirmationUrl, // https only
contentTypes: ["application/pdf", "image/*"], // checked against the answer before a byte is stored
kind: "document",
});
// Refusals: files.url_not_allowed (not https, another port), files.url_blocked (a private or loopback address, the
// SSRF guard), files.download_failed (a status other than 2xx, a reset), files.download_timeout (60 s by default),
// files.content_type_not_allowed, files.too_large, files.quota_exceeded, files.invalid_input.The name defaults to the last part of the final URL's path (download when it has none), the media type to the
answer's (application/octet-stream when it sends none); a given contentType must itself pass contentTypes.
4.1 Uploads from clients
A second route handler takes uploads:
// app/u/[...upload]/route.ts
export { serveUploadRoute as GET, serveUploadRoute as HEAD, serveUploadRoute as PUT } from "@softure-ai/files/next";Like /f, the route has no session: the URL carries an HMAC signature (under SOFTURE_FILES_LINK_KEYS, with its
own context, so an upload URL never passes as a link) and stops working once the session expires or is finalized. Keep
/u out of the app's sign-in guard, add an edge bypass for it as for /f (apps[].access.bypassPaths: [/f, /u] with
@softure-ai/host), and never cache it. Raise the edge's body limit only if you raise uploads.chunkBytes.
The app opens a session for a signed-in user and hands the URL to the client; the client sends the bytes; the app finalizes:
import { createUpload, finalizeUpload } from "@softure-ai/files/server";
const created = await createUpload(ctx, { ownerId: user.id, name: "promo.mp4", contentType: "video/mp4", size, kind: "input" });
if (!created.ok) return created; // files.too_large, files.quota_exceeded, files.content_type_not_allowed, files.too_many_uploads, files.invalid_input
// ...the client uploads to created.value.uploadUrl...
const saved = await finalizeUpload(ctx, created.value.uploadId, { ownerId: user.id });
// saved.value is the StoredFile; files.upload_incomplete, files.checksum_mismatch, files.quota_exceeded otherwiseThe wire protocol on uploadUrl:
| Request | Answer |
| --- | --- |
| PUT with Content-Range: bytes <start>-<end>/<size> | stores one chunk: start a multiple of chunkSize, end the chunk's last byte (the last chunk is shorter). 200 with the JSON status; a chunk that already arrived is answered without being rewritten, so a resend is safe. 416 for a range that is not one chunk, 400 for a body of another length, 404 once finalized or expired. |
| PUT without Content-Range | the whole file, when it fits one chunk |
| HEAD | upload-state (open, complete, finalized), upload-size, upload-chunk-size, upload-received (byte ranges, 0-67108863,134217728-201326591), upload-expires |
| GET | the JSON status (received, receivedBytes, missingChunks, state, ...); a browser (Accept: text/html) gets the upload page instead |
The upload page is a small phone-friendly page on the same URL: the person picks the file and it is sent in chunks
with fetch, from the missing ones, so pressing Upload again resumes. Its loop is sendUpload of the browser client
(§4.3), inlined. Its copy is filesMessages.en.uploadPage; it
loads nothing external and runs one inline script under a per-response CSP nonce.
Rate limit: when the app enables @softure-ai/security, every request to the upload route counts in the
files-upload bucket, keyed by the session; spread FILES_RATE_LIMIT_BUCKETS (from @softure-ai/files) into
security({ buckets }), or the route throws a setup error naming it. Without the security module the route relies on
the signature alone.
Every chunk is its own object in storage (uploads/<id>/<index>); finalizeUpload streams them in order into
saveFile, which writes the one final object (a multipart upload on S3) and the parts are removed. Storage briefly
holds the file twice while a finalize runs. Two parallel finalizes keep one file; a second call answers the same file.
4.3 The browser client
@softure-ai/files/client runs in the browser (no Node built-ins, no server code). An app with its own upload screen
opens the session on the server and sends the file from the client:
"use client";
import { sendUpload } from "@softure-ai/files/client";
const opened = await openUpload({ name: file.name, size: file.size }); // a server action around createUpload
if (!opened.ok) return opened;
const sent = await sendUpload(file, {
uploadUrl: opened.value.uploadUrl,
signal: controller.signal,
onProgress: ({ sentBytes, totalBytes }) => setProgress(sentBytes / totalBytes),
});
if (sent.ok) await finishUpload(opened.value.uploadId); // a server action around finalizeUploadsendUpload reads the session's HEAD, takes the chunk size from it and sends only the missing chunks, in order;
calling it again resumes. It reports { sentBytes, totalBytes } once with what already arrived and after every chunk,
and answers a Result: files.upload_expired (404: expired, finalized for a write, or forged),
files.upload_rejected (another 4xx, or a file whose size is not the session's), files.network (a failed request,
429, 5xx) or files.upload_aborted (the signal). It never throws for these.
For a list of files, createUploadQueue does the bookkeeping:
"use client";
import { createUploadQueue } from "@softure-ai/files/client";
import { UploadField, UploadItem } from "@softure-ai/theme-notion";
import { useState, useSyncExternalStore } from "react";
const [queue] = useState(() => createUploadQueue({ open: openUpload, finalize: (session) => finishUpload(session.uploadId) }));
const items = useSyncExternalStore(queue.subscribe, queue.getItems, queue.getItems);
<UploadField label={copy.files} onFilesSelected={(files) => queue.add(files)} />
{items.map((item) => (
<UploadItem key={item.id} item={item} onRetry={() => queue.retry(item.id)} onPause={() => queue.pause(item.id)}
onResume={() => queue.resume(item.id)} onRemove={() => queue.remove(item.id)} />
))}- Items are
{ id, name, size, state, progress, error?, errorCode? }:queued,uploading,paused,done,failed;progress0–100, 100 only once finalized;getItemsanswers the same array until something changes. open(file)andfinalize(session, file)are the app's (usually server actions) and answer aResult; their error codes land inerrorCodewith the copy ofdescribeError(code)(the built-infilesmessages by default, so an app passes(code) => getFilesErrorMessage(myMessages, code)or its own wording).concurrency(1 by default) uploads run at once.pauseaborts the running send and keeps the session;resumeandretrysend only what is missing in the same session, and a session that expired is opened again on the nextretry.removestops the upload and drops it; the unfinished session expires andfiles.pruneremoves it.
4.2 MCP upload tools
An MCP tool cannot take a video as an argument. With @softure-ai/mcp-access, register the two upload tools in the
app's server factory and list them in the catalog:
import { getFilesContext } from "@softure-ai/files/next";
import { FILE_UPLOAD_MCP_TOOLS, registerFileUploadTools } from "@softure-ai/files/mcp";
mcpAccess({ serverName: "acme", tools: [...appTools, ...FILE_UPLOAD_MCP_TOOLS] });
export const createServer = createMcpServerFactory({
name: "acme",
strictToolInput: true,
registerTools: (server, identity) => {
registerAppTools(server, identity);
registerFileUploadTools(server, { identity, getContext: () => getFilesContext(), kind: "input" });
},
});create_upload({ name, size, content_type?, sha256? })answersupload_id,upload_url,chunk_size,chunk_count,expires_at,curl(a bash loop withddandcurlthat sends every chunk;CHUNKS="3 4"resends only those) andbrowser_page. The assistant runs the loop in its own sandbox; the bytes never pass through the tool call.finalize_upload({ upload_id })answersfile_id,name,size,content_type,sha256, or the error's sentence with its code.- Both are write tools: registered only when
identity.canWrite(mcp-access's write switch). The uploads belong to the token's user (getOwnerIdchanges that). The app's tools then take thefile_id.
An app that turns the uploaded file into its own record in the same call, or that words its tool texts its own way, passes three more options:
registerFileUploadTools(server, {
identity,
getContext: () => getFilesContext(),
// After every successful finalize, a repeated one for the same file included: keep it idempotent.
onFinalized: async (file) => {
const asset = await upsertAssetForFile(file.id); // the app's own step, e.g. a row plus a background job
return asset.ok ? { asset_id: asset.value.id } : asset; // fields join the answer; err(code) answers a failure
},
descriptions: { finalize_upload: `Acme: ${FILE_UPLOAD_TOOL_DESCRIPTIONS.finalize_upload}` },
hints: { "assets.quota_exceeded": "The plan holds no more assets." },
});onFinalized(file, ctx): its returned fields are merged into thefinalize_uploadanswer (the file's own fields win a name clash); a returnederr(code)answers that code as a failure; a thrown error answers the generic failure and is logged.descriptions: the served text ofcreate_uploadandfinalize_upload; the defaults are exported asFILE_UPLOAD_TOOL_DESCRIPTIONS. The catalog entries inFILE_UPLOAD_MCP_TOOLSstay as they are.hints: the text answered for an error code, followed by the code: the hook's codes and the package'sfiles.*codes alike. Without a hint afiles.*code answers its sentence and any other code answers the code alone.
4.4 Showing a file to its signed-in owner
A link is for someone outside the app (a scheduler, a recipient). To play a stored video or show an image to the signed-in owner inside the app's own page, serve it by id through the owner route instead: no link is minted (no write), and the file stays unreachable without a session.
// app/media/[id]/route.ts
import { getCurrentUser } from "@softure-ai/auth/next";
import { createStoredFileRoute } from "@softure-ai/files/next";
export const { GET, HEAD } = createStoredFileRoute({
getOwnerId: async () => (await getCurrentUser())?.id ?? null,
});<video src={`/media/${file.id}`} controls />The route answers like a link (GET and HEAD, single byte ranges for seeking, 206, 416,
Cache-Control: private, no-store, nosniff, the sandboxing CSP) under the file's stored name, inline by default
(disposition: "attachment" for a download). Without a session, and for a file that is missing, expired, deleted or
another owner's, it answers the same 404, so it never tells whether a file exists. files does not depend on auth:
the session lookup is the app's getOwnerId.
Unlike /f and /u, this route sits behind the app's sign-in guard: list its prefix in
createAuthGuard(config, { protect: [...] }) and add no edge bypass for it.
A route of the app's own (another path shape, an extra permission check) calls the server function with the owner it has checked:
import { getFilesContext } from "@softure-ai/files/next";
import { serveStoredFile } from "@softure-ai/files/server";
return serveStoredFile(await getFilesContext(), fileId, request, { ownerId: user.id });5. Migrations and tables
Schema files, migration 0001_create_files.sql, table files:
| Column | Meaning |
| --- | --- |
| id | uuid, made by saveFile (the storage key is derived from it: ab/cd/<uuid>) |
| owner_id | the owner's account id, 1 to 200 characters, no foreign key |
| sha256, size | lowercase hex SHA-256 and byte count of the content |
| content_type | a media type with optional parameters, type and subtype lowercased |
| original_name | the sanitised name: last path part, no control characters, at most 255 characters |
| kind | the app's category, ^[a-z][a-z0-9_-]{0,31}$, file by default |
| storage_key | where the bytes are, unique |
| link_generation | bumped by revokeFileLinks; a link carries the generation it was made for |
| expires_at, deleted_at, created_at | a file is live while deleted_at is null and expires_at is null or ahead |
A deleted or expired file keeps its row until pruneFiles has removed its bytes. Rollback: drop the table and its
softure.migrations row (the migration's header has the statements); the objects in storage stay.
Migration 0002_create_uploads.sql, table uploads: one row per upload session (owner, sanitised name, content type,
kind, declared size and optional SHA-256, chunk size, received_chunks (the indices that arrived), file_id once
finalized, expires_at). The state is derived from those columns. A finalized session keeps its row until it expires,
so a repeated finalize answers the same file; pruneFiles then removes it. Rollback: drop files.uploads and the
version 2 row; chunk objects under uploads/ stay in storage.
6. Environment variables
| Variable | Required | Meaning |
| --- | --- | --- |
| SOFTURE_FILES_LINK_KEYS | for links and uploads | the signing keyring, <id>:<base64 of 32 bytes>[,<id>:<key>…]: the first key signs, every key verifies. generateFilesLinkKey() (from /server) prints a new entry. Rotate by putting a new key first and dropping the old one after links.maxTtlSeconds. Without it, createFileLink answers files.link_key_missing and the route answers 404 (and logs the code). |
| SOFTURE_FILES_S3_ACCESS_KEY_ID, SOFTURE_FILES_S3_SECRET_ACCESS_KEY | with createS3Storage | the bucket's access keys, read on each request (renamed with accessKeyIdEnv / secretAccessKeyEnv) |
7. Switches
None.
8. Appearance
The upload page (§4.1) is plain HTML with a minimal inline style, so it works before any theme loads; an app that
wants its own look builds a page on createUpload and the browser client (§4.3). A file browser is out of scope.
9. Copy
filesMessages.en.errors.files.* has a sentence per error code (too_large, quota_exceeded, not_found, ...);
getFilesErrorMessage(messages, code) picks one, falling back to the generic failure. The link route's 404 body
is a fixed Not found for machines, not copy. uploadPage.* is the upload page's copy ({name}, {size}, {done}
and {total} are filled in). The browser client's codes (upload_expired, upload_rejected, network,
upload_aborted) have their sentences in the same group.
10. Hooks
None. A driver is the extension point: any object with kind, put(body, key), get(key, range?), head(key),
delete(key) and optionally check() (FileStorage) works.
11. GDPR
exportUserData lists the user's live files (id, name, kind, content type, size, SHA-256, created and expiry
times), never the bytes or the storage key; an app that wants the bytes in the export adds links itself.
deleteUserData marks every file of the user deleted (nothing of theirs is served from that moment), removes the
bytes from storage and then the rows; a file whose storage delete fails keeps its marked row until pruneFiles
removes it. Upload sessions too: the export lists the open ones (name, size, what arrived), the deletion removes all
of the user's sessions with their chunks.
12. Limitations
- Uploads from clients go through upload sessions (§4.1): chunks must align to the session's chunk size, and a finalize briefly needs twice the file's size in storage. No image transforms, no virus scanning, no file browser UI.
- A link serves one range per request; a request for several ranges gets the whole file (
200), as RFC 9110 allows. NoIf-RangeorETag. - Links are
attachmentwithnosniffand a sandboxingContent-Security-Policyby default, so an uploaded HTML or SVG never runs on the app's origin;inlinekeeps those headers. - The quota counts live files of one owner; it is not a global storage limit. Dedupe works per owner and only when enabled; two owners' copies of one file are two objects.
- The local driver needs one filesystem for the folder (the rename is atomic only there); the free-space check reads that filesystem. The S3 driver reports no free space.
- A storage key comes from the file id, not the hash: the hash is known only after the write, and S3 has no rename.
Testing an app with it
import { createMemoryStorage, createTestLinkKeys, fetchFileLink, readFileLinkExpiry } from "@softure-ai/files/testing";
const storage = createMemoryStorage(); // files({ storage }); storage.objects(), setFailing(), setCheck()
const ctx = { db, clock, config, env: createTestLinkKeys() };
const answer = await fetchFileLink(ctx, link.url, { range: "bytes=0-99" }); // { status: 206, headers, body }
expect(readFileLinkExpiry(link.url)).toEqual(expectedExpiry);fetchFileLink runs the same code as the route, at the context's clock, so advancing a test clock past the expiry
gives the 404.
An app that reads or writes an S3-compatible bucket itself (a user's own bucket, an off-site copy) tests against
createFakeS3, a bucket in memory that checks every request's SigV4 signature against one key pair:
import { createS3Storage } from "@softure-ai/files/server";
import { createFakeS3 } from "@softure-ai/files/testing";
const s3 = createFakeS3({ bucket: "notes", accessKeyId, secretAccessKey, basePath: "/s3", isWritable: true });
s3.put("vault/a.md", "# A"); // seed objects; s3.remove(key)
const storage = createS3Storage({
endpoint: "http://127.0.0.1:9000/s3", bucket: "notes", region: "auto", fetch: s3.fetch,
accessKeyIdEnv: "S3_KEY_ID", secretAccessKeyEnv: "S3_SECRET", env: { S3_KEY_ID: accessKeyId, S3_SECRET: secretAccessKey },
});
s3.fail("get", 503); // every GetObject answers 503 until s3.fail("get", null)
expect(s3.calls).toMatchObject({ list: 0, get: 1 });It answers path-style ListObjectsV2 (prefix, max-keys, continuation tokens) and GetObject (If-Match, a byte
range); with isWritable also a single-part PutObject (body checked against x-amz-content-sha256), HeadObject and
DeleteObject. A wrong signature is 403, an unknown bucket 404. s3.handle(request) answers one Request, for a
local HTTP server that end-to-end tests point an app at.
Build
npm run build -w modules/files runs tsc -p tsconfig.build.json: ESM and .d.ts per source file in dist/.
Releasing: scripts/release/README.md.
