
core
dev.filelayer/core
User files for a SaaS, under one person's authority: list, share with an expiry, revoke.
Documentation
Filelayer
Per-file permissions, links you can take back, and an audit trail of every allowed and denied access, for the files your users upload. A Node library on your own Postgres and your own S3 or R2 bucket.
A first file in an organization, and a refusal, in fourteen lines:
npm install @filelayer/core
npm install --save-dev "@electric-sql/pglite@^0.3.11"
The command pins PGlite's 0.3 line; 0.5 and 0.6 work too, and the
await fl.close() at the end of the block lets the process exit at once with
any of them.
import { Filelayer } from '@filelayer/core';
const fl = await Filelayer.quickstart({ baseUrl: 'http://localhost:3000' });
await fl.orgs.create('acme', { owner: 'alice' }); // a tenant and its owner
await fl.orgs.setRole('acme', 'bob', 'member', { as: 'alice' }); // a member of it
await fl.orgs.create('globex', { owner: 'eve' }); // another tenant
const { id } = await fl.files.put(new TextEncoder().encode('Q3 plan'), {
org: 'acme', owner: 'alice', visibility: 'org', name: 'q3.txt',
});
const { body } = await fl.files.get(id, { as: 'bob' }); // a member of acme: allowed
console.log(new TextDecoder().decode(body)); // 'Q3 plan'
await fl.files.get(id, { as: 'eve' }).catch((e) => console.log(e.status, e.code)); // 404 not_found
const [refusal] = await fl.orgs.audit('acme', { as: 'alice', decision: 'deny' }); // oldest first
console.log(refusal.summary); // '<time> eve file.read deny:no_membership q3.txt @acme'
await fl.close(); // lets the process exit at once
To run it: in an empty directory, npm init -y, the two installs above, save
the block as first.mjs, then node first.mjs. No account, no credential and
no dashboard: quickstart() runs Postgres in process. The refusal is a 404, so a stranger cannot tell the file exists, and
the reason is in the audit trail, not in the response.
Or try it with nothing to install: a demo in the browser uploads a file, is refused from another organization, revokes a share link and shows the audit trail that recorded both refusals.
The file layer for SaaS applications. A customer's security review asks who opened a file and who was refused. A link you sent has to stop working now. Someone asks to be erased from your logs. Filelayer answers all three for the files your users upload: per-file permissions, links you can take back, and an audit trail of every allowed and denied access, on your own Postgres. → filelayer.dev
One file feature, built five ways and attacked the same way. The same document workspace was built with Filelayer, Supabase Storage with row-level security, raw S3 presigned URLs, Convex and Vercel Blob, and every version that runs was attacked by one shared suite:
- About 3.1 times as many kinds of security-sensitive decision in the two alternatives that ran, places where a wrong choice leaks data and nothing reports it: 25 for Supabase and 24 for raw S3, against Filelayer's 8, and about 4.0 times as many places to get them right.
- 21 of 21 for Filelayer on the 21 attacks every executed version can express, after the executed alternatives were revised against the suite (raw S3 in one round, Supabase in two rounds), with every diff published. Raw S3 also defends 21 of 21; Supabase defends 21 of 21. The hand-written versions can be made safe; the difference is how much code that takes.
- About 2.9 times as many lines in the two alternatives that ran, wired as in production: 569 lines of application and infrastructure code for Supabase and 794 for raw S3, against Filelayer's 233, with its pool, bucket and policies. Against our example as it ships, 157 lines, it is about 4.1 times as many. Convex and Vercel Blob were neither executed nor compiled, so they are left out of every figure.
The results, the method and where each alternative is better:
filelayer.dev/one-feature-five-ways.
Everything reruns from a clone with node benchmark/run.mjs.
You tell Filelayer who the caller is. Filelayer decides what they may do with a
file, serves the bytes with the right headers, and writes the audit event. For
file access that goes through Filelayer, that decision is made in one place,
packages/core/src/authz.ts, so you write no ownership checks in route
handlers, no presigned-URL expiry logic, and no per-route access rules of your
own.
Built to be adopted without us. The quickstart, the guides, the examples and
llms.txtare written so that you, or your coding agent, can integrate it alone. Where it breaks, open an issue. Free and open source, with no usage limits. You pay for support and reviews, see pricing. The core library is and will remain Apache-2.0. Alpha, and the numbers behind that word are all on one page: should you depend on this? · what it does not do · roadmap to 1.0
// Public avatar
const { url } = await fl.files.put(bytes, { public: true });
// Private, user-owned
const { id } = await fl.files.put(bytes, { owner: 'user_123' });
const file = await fl.files.get(id, { as: 'user_123' });
// Multi-tenant, role-controlled: create the org once, then upload into it
await fl.orgs.create('acme', { owner: 'user_123' });
await fl.files.put(bytes, { org: 'acme', owner: 'user_123' });
// Shared with an expiry, a password and a download cap, and revocable
const share = await fl.shares.create(id, {
as: 'user_123', expiresIn: 3600, maxDownloads: 3, password: 'hunter2',
});
await fl.shares.revoke(share.grantId, { as: 'user_123' }); // this link, now
// Shared with a named user, and taken back. `unshare` is the one you want for
// a person: `create()` is not idempotent, so revoking a single grant id you
// happen to be holding can leave an earlier one live.
await fl.shares.create(id, { as: 'user_123', withUser: 'user_456' });
await fl.shares.unshare(id, { as: 'user_123', user: 'user_456' }); // all of it
Start at whichever line matches your problem. Complexity is incremental:
each tier adds one concept, and no tier makes you pay for a concept you are not
using. → docs/QUICKSTART.md
The three layers
your application fl.files.put / get / list, fl.shares, fl.orgs
you pass YOUR user id; nothing here knows a uuid
───────────────────────────────────────────────────────────────────────
Filelayer ONE authorization function answers every request
grants, roles, expiry, download caps, revocation
the audit event, written in the decision's own
transaction so the log cannot disagree with it
───────────────────────────────────────────────────────────────────────
your Postgres 13 tables: 9 for tenants, files, permissions,
your bucket shares, the audit chain and job runs, and 4 for
the schema version and the usage report.
Filelayer owns the schema, you own the database.
Bytes go to S3, R2, B2 or a directory behind one
adapter; storage is replaceable
Filelayer sits between the two things you already run. It brings no database and no storage of its own, and zero runtime dependencies.
It is authorization middleware, not row-level security. It decides for calls
made through it, in your process. The schema additionally refuses cross-tenant
grants, cross-project identities and delegation that amplifies authority from
every writer that connects as an ordinary role, a psql session included;
those are constraints and triggers. A superuser, or a role granted SET on
session_replication_role, can switch triggers and foreign-key checks off for its own session, and
the table's owner can disable a trigger with ALTER TABLE.
In the documented install, which applies schema.sql with the application's own
DATABASE_URL, the application's role is that owner.
But there is no RLS policy in schema.sql, and a direct SELECT against these
tables is filtered by nothing. Filelayer composes with database-level
enforcement; it does not replace it.
What it is for, and what it is not for
Worth the overhead when: files are private, belong to specific people or tenants, and their permissions change over time. Documents, contracts, attachments, exports, anything with a share link you might later want back.
Not worth the overhead when:
| You need | Use instead | Why |
|---|---|---|
| Public images at CDN volume | a CDN-backed bucket | Default delivery proxies every byte. Redirect delivery (below) removes the proxy but is opt-in and narrow. |
| Video or audio at scale | a CDN / media service | Seeking works: the shipped routes answer Range with 206. But default delivery proxies every byte through your server, and there is no CDN on that path. |
| Browser → storage upload with your server out of the data path, in development | a real bucket | FsStorage mints the credential so the client code is identical, but it receives the bytes itself and says so: via: 'server'. Only S3 and R2 keep your process out of the path. |
| Resumable or multipart direct upload | presigned S3 directly / tus | One signed PUT, one object. There is no resume. |
| Thumbnails, transforms, format negotiation | Cloudinary / imgix | We have none. |
Against the two things you would otherwise do
| Hand-rolled presigned URLs | Supabase Storage | Filelayer | |
|---|---|---|---|
| Revoke a link somebody already holds | No. A signature is valid until its clock runs out; your options are a short TTL or proxying the bytes yourself | No. Signed URLs are signed with an internal key and cannot be revoked | Yes, on the next request, transitively through the delegation chain |
| "Everyone in this org may read" | your own join, recomputed on every join and leave | expressible as an RLS policy | one grant row; membership resolves at request time |
| Who accessed this, including refusals | whatever you wrote | not a product feature; Postgres logging is not an access log | hash-chained per tenant, written in the decision's transaction |
| Download cap | your own counter, and the race in it | none | atomic, reserved before the bytes move |
| CDN on the private path | yes, and that is why you cannot revoke | yes, same trade | no: the two facts are the same fact |
| Public images at volume | yes | yes | no. Use a bucket behind a CDN |
| Lines for a public avatar | ~10 | 10 | 16 |
The last two rows are losses and they are not close. We publish the full
comparison, including every case we lose, in
ARCHITECTURE-PROGRESSIVE.md
§5. Short version: for a public avatar, Supabase is 10 lines and Filelayer is
16. If avatars are your whole problem, use Supabase.
The five security properties
These are the product. Each is enforced in the schema or the authorization engine, not by convention, and each has tests named after it.
| Property | What it means in practice | |
|---|---|---|
| P1 | Deny by default | There is no public boolean anywhere in the schema. Public delivery is an explicit, revocable, auditable grant row; there is no flag to leave on by accident. This is a property of the schema, not of your object store: Filelayer cannot make your bucket private, and a public bucket bypasses everything on this page. That is the one configuration step it cannot do for you: QUICKSTART §7. |
| P2 | No ambient authority | Knowing an object key, a URL or a file id grants nothing. Storage location is never an input to a decision. |
| P3 | Cross-tenant grants are structurally impossible to write | A grant's org_id must equal its file's org_id, enforced by the composite foreign key FOREIGN KEY (file_id, org_id) REFERENCES file (id, org_id). No writer that connects as an ordinary role, including a migration or a psql session, can create a grant pointing at another tenant's file; a superuser, or a role granted SET on session_replication_role, can switch foreign-key checks off for its own session, since PostgreSQL implements them as triggers. This is a write-side integrity constraint, not a read filter: it makes the row unrepresentable. Reads are scoped by the engine, not by the database. |
| P4 | A URL never outlives its permission | Every signed URL embeds a grant id and is re-validated on every request, transitively through the whole delegation chain. Revocation beats a live URL. |
| P5 | Every decision is audited, including denials | Hash-chained per tenant. Probes that cannot be attributed to a tenant go to a system chain rather than being dropped. The log answers in your identifiers (marco, contract.pdf, acme) alongside the internal ones, so "who accessed this?" needs no SQL of yours. |
Three more properties are enforced in the schema and documented in
packages/core/SEMANTICS.md: atomic download
counters (P6), deletion as a liveness predicate rather than a cascade
(P7), and per-project identifier namespaces (P8).
Two consequences worth knowing before you adopt:
- Revocation actually works.
fl.files.unpublish(id)makes a URL that has been printed, indexed and pasted into a support ticket stop working on the next request. No deletion, no key rotation, no cache purge. Supabase'sgetPublicUrl()is offline string concatenation, so it has no request at which to make that decision; deleting the object is the only withdrawal. - This costs you a byte path. P4 is why the default is to serve bytes rather
than hand out a presigned URL, and it is why the default path has no CDN in
front of it. The two facts are the same fact. Redirect delivery trades a
bounded revocation window for that CDN and is opt-in; see
packages/core/SEMANTICS.md.
What backs that up
Said once, here, because every number in it is checked by a gate that fails the build when a public surface and the run disagree:
| The suite | 781 tests across 169 suites, every commit. Most run on PGlite (PostgreSQL 17 compiled to WebAssembly); the concurrency, audit retention and MCP server suites run against a real PostgreSQL 17 |
| Concurrency | 8 tests on a real PostgreSQL with two backends: races staged, not reasoned about. Three carry a control that removes the protection and asserts the bad outcome does happen |
| Adversarial | 26 attacks, 0 breaches. Also run against filelayer-prerebuild, the example application before its delivery and authorization were rebuilt, known to be vulnerable, which scores 3. A suite that only ever passes proves nothing about itself |
| Live object storage | 12 tests against live Cloudflare R2 and 12 against live AWS S3, every commit, plus a thirteenth each on the nightly run: an 11 MB multipart upload reassembled byte-exactly. R2 is S3-compatible, not S3, which is why both run |
| Schema migrations | every migration file applied to the previous release's schema.sql and the result compared against the next one, on real PostgreSQL |
| The published artifact | the tarball installed into an empty directory and driven through the whole lifecycle; the starter booted over HTTP and driven through 25 checks; every relative path inside the tarball resolved from inside the tarball |
What none of that measures is load, or anyone's production. The complete table, including the rows that are zero, is on the trust page.
The five that make people decline
The complete list is LIMITATIONS.md -- seventeen
entries, each with its reasoning, shipped in the npm tarball so an install has
it on disk. These five are the ones that should make you close the tab if they
apply to you:
-
No CDN on the private delivery path. Bytes proxy through your application, and authenticated responses carry
Cache-Control: no-store. That is not an oversight, it is P4: a URL that can be revoked is a URL that has to be asked about. An opt-in redirect mode trades a bounded revocation window of up to 300 seconds for cacheability. If your workload is public images at volume, use a bucket behind a CDN and come back when you need to take a URL back. -
A grant id is not a person's access, and
shares.create()still inserts a row per call by default. Two calls with anexpiresInare two legitimately different windows, so the engine cannot dedupe on its own. Pass anidempotencyKeyand a retry returns the grant that already exists; without one, a double-clicked share button gives one reader two grants.revoke()now answerssubjectCanStillRead, so revoking one grant and not removing somebody's access is visible in the reply rather than in an audit later. Useshares.unshare(fileId, { as, user })to remove a named person, and note there is still no bound on how many live grants one subject may hold.The cost of that is no longer the problem it was. Until
0.17.0the read paid one recursive chain walk per grant held: 4.3 ms at five, 5 911 ms at a hundred thousand. The short-circuit moved into SQL and the cliff went with it: 30.4 ms at two hundred thousand concentrated grants, 1.13x the owner read on the same file, measured inbenchmark/load/RESULTS.mdH4b. What remains is a correctness trap, not a performance cliff. -
No resumable or multipart upload. One signed PUT, one object. A large upload that fails starts over, and
fl.files.put()holds the whole body in memory -- only the corefl.upload()takes a stream, and neither imposes a size ceiling, so that is yours to enforce. -
Org admins and owners can read
privatefiles. Deliberate: retention and legal hold are useless if the people accountable for them cannot see what they are holding. But it is a policy decision, and if you need to exclude the operator you need envelope encryption, which we do not have. -
Alpha, and the schema has changed thirteen times. Any
0.x→0.(x+1)may break the API, the schema or both. Every break has a numbered entry inMIGRATIONS.mdand a runnable file undermigrations/that CI applies to the previous release's schema and checks produces the next one -- but there is no LTS branch, no backporting, and no independent security review.
Install
npm install @filelayer/core
Requires Node ≥ 22. The package ships compiled JavaScript and type
declarations in dist/; the TypeScript source and the full test suite are in
the tarball as well, so every claim on this page is inspectable from what you
installed.
That install has zero runtime dependencies. Filelayer talks to your
Postgres and your bucket, so it ships neither. The throwaway instance below is
the one exception: quickstart() runs on an embedded WebAssembly Postgres,
which you install yourself so that it never lands in a production
node_modules. Add it if you want the throwaway instance, and skip it
otherwise. createTestDb() will tell you, by name, if you need it:
npm install --save-dev "@electric-sql/pglite@^0.3.11"
Filelayer supports PGlite ^0.3.11, ^0.5.8 and ^0.6.0, and CI runs the whole suite on
the 0.3 line and on the newest release inside the range. The command pins the 0.3 line: 0.5.x and 0.6.x work too; with them, a script that uses quickstart() ends with await fl.close(), or it waits about 10 s on exit (electric-sql/pglite#1232). PGlite is not a peer dependency, so installing it never
fails the tree. With a version outside the range, quickstart() and
createTestDb() stop with the error pglite_unsupported_version, which gives
the command above.
import { Filelayer } from '@filelayer/core';
const fl2 = await Filelayer.quickstart(); // PGlite + in-memory bytes
const { url: avatarUrl } = await fl2.files.put(bytes, { public: true });
quickstart() is ephemeral: everything is lost when the process exits.
Serving the bytes
Authorizing a read is not the same as answering the request. Two handlers do the second, and which one you want is decided by your runtime, not by preference:
deliveryHandler(fl, opts?) | Returns (req: IncomingMessage, res: ServerResponse) => Promise<void>. Node's own HTTP server, and Express, Fastify and Koa, which hand you those objects. |
deliveryFetch(fl, opts?) | Returns (req: Request) => Promise<Response | null>. Next.js App Router, and other frameworks on Node such as Hono, which hand you a Request and want a Response back. |
They are the same two routes with the same behaviour. deliveryFetch returns
null for a request it does not own, so a catch-all route can fall through to
the rest of your application instead of swallowing it.
Cloudflare Workers is not supported yet (the library does not bundle for workerd), and Deno and Bun are not run in CI, so neither is claimed; both are tracked in ROADMAP.
Mounting the wrong one is the easiest integration mistake to make. A
node:http handler in an App Router route exports a function with the wrong
shape. In a Next 16 project with TypeScript, next build reports it as a type
error in the route file; without type checking, the symptom is a request that
never answers. In an App Router route, mount deliveryFetch.
import { deliveryFetch } from '@filelayer/core';
const serve = deliveryFetch(fl, {
principal: async () => ({ as: await currentUserId() }),
});
export async function GET(req: Request) {
return (await serve(req)) ?? new Response('Not found', { status: 404 });
}
Both parse Range, which matters more than it sounds: a <video> element will
not let the user scrub until a range request is answered, and a PDF reader asks
for the end of the file first. An invalid range is answered 200 with the
whole representation, which RFC 9110 allows (a server may ignore Range), and
a range that parsed cleanly and cannot be satisfied gets 416 with
Content-Range: bytes */<size>.
Accept-Ranges: bytes goes on the plain 200 as well, because that is how a
client learns it may seek at all.
Two defaults to know before you mount either one. disposition defaults to
attachment, which downloads rather than plays, so a media route needs
disposition: 'inline'. And redirecting to a presigned URL instead of proxying
is opt-in, because it moves revocation out of your process for the life of the
URL; it requires a storage adapter that can sign, and it refuses with
redirect_not_acknowledged until the configuration says so out loud.
docs/guides/serving-private-files.md
is the measured comparison of the two.
Everything else, one page per thing
That is the whole integration for most applications: install, quickstart() to
see it work, then a real database and one of these handlers. The rest is a page
each, and every one of them ships inside the npm tarball, so an install has them
on disk.
| Which storage adapter, and making the bucket private | QUICKSTART §7 |
Checking a deployment from a terminal (filelayer doctor) | docs/CLI.md |
The Agent Skill, if an agent is doing the integration: copy it from node_modules, or npx skills add filelayer/filelayer | docs/AGENT-SKILL.md |
| Browser → bucket upload, with your server out of the path | docs/DIRECT-UPLOAD.md |
| An MCP server, so an agent can operate files | docs/MCP.md |
The 29 error codes, and FilelayerError | QUICKSTART §9 · ERRORS.md |
Proving your routes hold, not ours (auditIntegration()) | QUICKSTART §8 |
| Reading the audit trail, with a time window and no storage adapter | QUICKSTART §4 |
| Running the suite yourself, from a clone | CONTRIBUTING · from an install |
The guides are also rendered at filelayer.dev/guides, which is the same markdown and is easier to read than a repository file.
Versioning
Pre-1.0. The version is 0.MINOR.PATCH and the promise is deliberately narrow:
0.x→0.(x+1)may break the API, the schema, or both. Every break is inpackages/core/CHANGELOG.md, and every schema break has a migration inpackages/core/MIGRATIONS.md.0.x.y→0.x.(y+1)is additive or a fix. No schema change that requires action, no signature change.- There is no long-term support branch and no backporting before 1.0.
The schema has changed thirteen times. MIGRATIONS.md has sixteen numbered
entries, eleven of which carry forward SQL; the other two schema changes predate
the oldest tag in the repository and cannot be verified against an earlier
schema. Budget an upgrade against that file rather than against this paragraph.
Every figure in this paragraph is derived from migrations/manifest.json by
check:versions, which fails the build if any of them drifts.
Which version a database is at is readable off the database.
schemaStatus(db) reports where a database is, what this build expects, and
which files under migrations/ are outstanding. It issues no DDL: your
application owns the migration runner, which is the position
MIGRATIONS.md
§2 takes and is keeping.
Layout
| Path | What it is |
|---|---|
packages/core/schema.sql | The data model. Every security property is commented at the constraint that enforces it. Read this first if you are reviewing us. |
packages/core/src/authz.ts | The authorization engine. Two functions, one decision core. |
packages/core/src/simple.ts | The tiered API (files, orgs, shares). No authorization logic: a facade. |
packages/core/src/delivery.ts | Byte delivery. Owns the response headers so you cannot get them wrong. |
packages/core/test/ | The property suite. Ships in the tarball. |
packages/core/dev/ | Diagnostic scripts. Not published. |
examples/tier1-avatar … tier3-org-roles | One runnable example per tier |
examples/vault | A full B2B document workspace over HTTP |
examples/starter | A deployable server: your Postgres, FsStorage, route helpers mounted |
examples/nextjs | App Router: deliveryFetch at a catch-all route, upload, share, revoke |
examples/mcp | A launchable MCP server, driven over real stdio by its own verify.mjs |
Documents
docs/QUICKSTART.md: install → first file → the advanced capabilitiesLIMITATIONS.md: the complete list of what this does not do, seventeen entries with their reasoningROADMAP.md: the nine things an outside evaluator said would change its answer, eight of them done, and what is deliberately not comingdocs/guides/: nine answers to questions people actually ask, useful whether or not you use this library; the code in them is executed in CIpackages/core/SEMANTICS.md: the exact behaviour of every edge: liveness, delegation, deletion, the audit chainpackages/core/MIGRATIONS.md: how schema changes are delivered and what the pre-1.0 compatibility promise ispackages/core/CHANGELOG.md: the real history, including the security defects we found in ourselvesARCHITECTURE-PROGRESSIVE.md: the tier model, lines of code versus the alternatives, and where we losearchitecture/TIER5-DESIGN-NOTE.md: large files, streaming, range requests, CDNllms.txt: the same map, written for an agent implementing an integrationopenapi.yaml: the two HTTP routes the library serves, as OpenAPI 3.1
Every link above points at GitHub, and an installed consumer may have no network
and no browser. The npm package therefore carries the same files on disk under
node_modules/@filelayer/core/, and three resolve as subpath imports
(@filelayer/core/llms.txt, @filelayer/core/openapi.json and
@filelayer/core/schema.sql) so a reader does not have to guess at the layout
of node_modules.
License
Apache-2.0, with
an express patent grant and a patent-retaliation termination clause. No copyleft
obligation on your own code; preserve the notices and state significant changes.
LICENSE and NOTICE
both ship in the tarball, so the grant travels with the artifact.
SPDX-License-Identifier: Apache-2.0
Copyright 2026 Technology Pro Bono S.L.
Dependencies. No runtime dependencies, and a job in CI fails the build
if one appears. The third-party packages are all devDependencies:
@electric-sql/pglite (Apache-2.0),
also an optional peer dependency and what quickstart() runs on, plus pg and
embedded-postgres for the contention tests that need two real backends. A
production install contains none of them, and no third-party code is copied or
embedded anywhere in this repository.
Contributing, security and conduct
CONTRIBUTING.md: how to set up, whatnpm run verifycovers, and what a pull request needs.SECURITY.md: report vulnerabilities privately, never as a public issue. Includes our disclosure timetable and what is in and out of scope.CODE_OF_CONDUCT.md: Contributor Covenant 2.1.
Bugs, questions and "this document is wrong" reports go to GitHub Issues. A report that the product does not do what this README says is the most valuable thing you can send us.
@filelayer/corenpm install @filelayer/core