Управляет правами доступа пользователей к файлам, позволяет настраивать временный доступ по ссылкам и вести аудит для SaaS-приложений, используя вашу собственную базу данных Postgres.
Также известен как filelayer/filelayer, core, @filelayer/core
- Звёзды
- 0
- Инструменты
- —
- Загрузки, 30 дней
- 3 529
- Последняя версия
- 0.35.4
- Последний коммит
- 13 нояб. 2026 г.
- Лицензия
- Apache-2.0
Что такое Filelayer MCP?
Filelayer — это MCP server. Управляет правами доступа пользователей к файлам, позволяет настраивать временный доступ по ссылкам и вести аудит для SaaS-приложений, используя вашу собственную базу данных Postgres.
Сводка сгенерирована из README проекта
О Filelayer MCP server
Filelayer предоставляет специализированный слой авторизации для SaaS-приложений, позволяющий управлять правами доступа пользователей к файлам, совместным доступом и журналами аудита. Вместо того чтобы полагаться на row-level security или вручную прописывать логику presigned URL, Filelayer работает как middleware между вашим приложением и существующей базой данных Postgres. Он использует вашу базу для хранения девяти таблиц, управляющих разрешениями, ролями и сроками действия, в то время как сами байты файлов хранятся в любом удобном вам хранилище, например S3, R2 или B2.
Разработчики интегрируют решение, устанавливая пакет @filelayer/core и используя класс Filelayer для выполнения операций с файлами. Вы передаете собственные идентификаторы пользователей, а движок принимает решения о доступе на основе заданных вами разрешений, таких как членство в организации или конкретные права пользователя. Такая архитектура позволяет реализовать продвинутые функции: ссылки с возможностью отзыва доступа, лимиты на скачивание и защиту паролем. Поскольку решение работает внутри вашего процесса, оно исключает уязвимости, часто встречающиеся в стандартных конфигурациях объектных хранилищ, гарантируя, что каждый запрос на доступ проверяется через журнал аудита в реальном времени.
Что вы можете с ним делать
- 1Отзыв доступа по общей ссылкеРазработчик может мгновенно аннулировать ранее созданную ссылку, чтобы прекратить доступ к файлу.
- 2Внедрение лимитов на скачиваниеВы можете ограничить количество раз, которое пользователь может скачать конкретный файл.
- 3Формирование журналов аудитаAI-клиент может запрашивать систему, чтобы точно узнать, кому был предоставлен или запрещен доступ к конкретному документу.
- 4Управление правами в мультиарендной средеНастройка правил доступа к файлам строго в рамках конкретных организаций для предотвращения утечек данных между клиентами.
Взято из README проекта. Каждый вариант использования проверен на соответствие цитате из него.
Как установить Filelayer MCP
Форматы проверены 10 ноя 2026Добавить в CursorДобавить в GooseУстановка Filelayer MCP в Claude Code
$ claude mcp add --env 'DATABASE_URL=<YOUR_DATABASE_URL>' --env 'FILELAYER_AS=<FILELAYER_AS>' --env 'FILELAYER_ORG=<FILELAYER_ORG>' --env 'S3_ACCESS_KEY_ID=<YOUR_S3_ACCESS_KEY_ID>' --env 'S3_SECRET_ACCESS_KEY=<YOUR_S3_SECRET_ACCESS_KEY>' core -- npx -y @filelayer/coreУстановка Filelayer MCP в Cursor
~/.cursor/mcp.json
{
"mcpServers": {
"core": {
"command": "npx",
"args": [
"-y",
"@filelayer/core"
],
"env": {
"DATABASE_URL": "<YOUR_DATABASE_URL>",
"FILELAYER_AS": "<FILELAYER_AS>",
"FILELAYER_ORG": "<FILELAYER_ORG>",
"S3_ACCESS_KEY_ID": "<YOUR_S3_ACCESS_KEY_ID>",
"S3_SECRET_ACCESS_KEY": "<YOUR_S3_SECRET_ACCESS_KEY>"
}
}
}
}Установка Filelayer MCP в VS Code
.vscode/mcp.json
{
"servers": {
"core": {
"type": "stdio",
"command": "npx",
"args": [
"-y",
"@filelayer/core"
],
"env": {
"DATABASE_URL": "<YOUR_DATABASE_URL>",
"FILELAYER_AS": "<FILELAYER_AS>",
"FILELAYER_ORG": "<FILELAYER_ORG>",
"S3_ACCESS_KEY_ID": "<YOUR_S3_ACCESS_KEY_ID>",
"S3_SECRET_ACCESS_KEY": "<YOUR_S3_SECRET_ACCESS_KEY>"
}
}
}
}Установка Filelayer MCP в VS Code CLI
$ code --add-mcp '{"name":"core","type":"stdio","command":"npx","args":["-y","@filelayer/core"],"env":{"DATABASE_URL":"<YOUR_DATABASE_URL>","FILELAYER_AS":"<FILELAYER_AS>","FILELAYER_ORG":"<FILELAYER_ORG>","S3_ACCESS_KEY_ID":"<YOUR_S3_ACCESS_KEY_ID>","S3_SECRET_ACCESS_KEY":"<YOUR_S3_SECRET_ACCESS_KEY>"}}'Установка Filelayer MCP в Claude Desktop
claude_desktop_config.json
{
"mcpServers": {
"core": {
"command": "npx",
"args": [
"-y",
"@filelayer/core"
],
"env": {
"DATABASE_URL": "<YOUR_DATABASE_URL>",
"FILELAYER_AS": "<FILELAYER_AS>",
"FILELAYER_ORG": "<FILELAYER_ORG>",
"S3_ACCESS_KEY_ID": "<YOUR_S3_ACCESS_KEY_ID>",
"S3_SECRET_ACCESS_KEY": "<YOUR_S3_SECRET_ACCESS_KEY>"
}
}
}
}Установка Filelayer MCP в Codex
$ codex mcp add core --env 'DATABASE_URL=<YOUR_DATABASE_URL>' --env 'FILELAYER_AS=<FILELAYER_AS>' --env 'FILELAYER_ORG=<FILELAYER_ORG>' --env 'S3_ACCESS_KEY_ID=<YOUR_S3_ACCESS_KEY_ID>' --env 'S3_SECRET_ACCESS_KEY=<YOUR_S3_SECRET_ACCESS_KEY>' -- npx -y @filelayer/coreУстановка Filelayer MCP в Codex config.toml
~/.codex/config.toml
[mcp_servers.core] command = "npx" args = ["-y", "@filelayer/core"] [mcp_servers.core.env] DATABASE_URL = "<YOUR_DATABASE_URL>" FILELAYER_AS = "<FILELAYER_AS>" FILELAYER_ORG = "<FILELAYER_ORG>" S3_ACCESS_KEY_ID = "<YOUR_S3_ACCESS_KEY_ID>" S3_SECRET_ACCESS_KEY = "<YOUR_S3_SECRET_ACCESS_KEY>"
Установка Filelayer MCP в Gemini CLI
$ gemini mcp add -s user -e 'DATABASE_URL=<YOUR_DATABASE_URL>' -e 'FILELAYER_AS=<FILELAYER_AS>' -e 'FILELAYER_ORG=<FILELAYER_ORG>' -e 'S3_ACCESS_KEY_ID=<YOUR_S3_ACCESS_KEY_ID>' -e 'S3_SECRET_ACCESS_KEY=<YOUR_S3_SECRET_ACCESS_KEY>' core npx -- -y @filelayer/coreУстановка Filelayer MCP в Gemini settings.json
~/.gemini/settings.json
{
"mcpServers": {
"core": {
"command": "npx",
"args": [
"-y",
"@filelayer/core"
],
"env": {
"DATABASE_URL": "<YOUR_DATABASE_URL>",
"FILELAYER_AS": "<FILELAYER_AS>",
"FILELAYER_ORG": "<FILELAYER_ORG>",
"S3_ACCESS_KEY_ID": "<YOUR_S3_ACCESS_KEY_ID>",
"S3_SECRET_ACCESS_KEY": "<YOUR_S3_SECRET_ACCESS_KEY>"
}
}
}
}Конфигурация
DATABASE_URLОбязательноСекретYour own PostgreSQL, where this library keeps file ownership, grants and the audit chain. Apply node_modules/@filelayer/core/schema.sql once before starting.
FILELAYER_ASОбязательноThe ONE subject this server speaks for, in your own id space. Fixed for the life of the process: no tool reads it as an argument and no tool can change it, which is the only reason exposing these tools to an agent is safe. Write it yourself or have your provisioning write it, never derive it from a conversation. Serving several people means starting several servers.
FILELAYER_ORGОбязательноThe organisation this server is scoped to, in your own id space.
S3_ACCESS_KEY_IDСекретAccess key id for the bucket.
S3_SECRET_ACCESS_KEYСекретSecret access key for the bucket.
FILELAYER_BASE_URLThe base of the share URLs this instance mints. Without it, share links come back without a URL.
FILELAYER_DATA_DIRA local directory for the bytes. Needs no bucket and no IAM user. Set this OR the S3_* block: with neither, the server refuses to start rather than falling back to memory, which would work in a demo and lose the first real file.
FILELAYER_MCP_AGENT_LABELHow this agent names itself in the audit trail, recorded on every event these tools produce. It is what lets the chain separate "the partner opened this document" from "the partner's assistant opened this document".
FILELAYER_MCP_ALLOW_DESTRUCTIVESet to exactly `true` to register delete_file. Off by default because deleting is not recoverable and an agent that misreads a sentence deletes the wrong thing silently.
FILELAYER_MCP_EXPOSE_AUDITSet to exactly `true` to register file_audit. Off by default because the trail is an organisation's whole history and a tool that returns it copies every file name, actor and denial into the model's context. Reading it is itself audited since 0.27.0, which was the previous reason; the default did not move.
FILELAYER_MCP_RETURN_BYTESSet to exactly `true` to register read_file. Off by default because a document returned by a tool is a document copied into a model's context; file_info plus a share link is usually what was actually needed.
S3_BUCKETThe bucket. It must be private: this library decides who may be GIVEN a URL and has no say in who the object store will answer. `npx -p @filelayer/core filelayer doctor` reports whether yours serves unauthenticated reads.
S3_ENDPOINTAn S3-compatible endpoint, for example https://<account>.r2.cloudflarestorage.com. Setting it makes S3_BUCKET, S3_ACCESS_KEY_ID and S3_SECRET_ACCESS_KEY required.
S3_REGIONRegion, or `auto` for Cloudflare R2.
| Название | Описание | Тип |
|---|---|---|
| DATABASE_URL | Your own PostgreSQL, where this library keeps file ownership, grants and the audit chain. Apply node_modules/@filelayer/core/schema.sql once before starting. | ОбязательноСекрет |
| FILELAYER_AS | The ONE subject this server speaks for, in your own id space. Fixed for the life of the process: no tool reads it as an argument and no tool can change it, which is the only reason exposing these tools to an agent is safe. Write it yourself or have your provisioning write it, never derive it from a conversation. Serving several people means starting several servers. | Обязательно |
| FILELAYER_ORG | The organisation this server is scoped to, in your own id space. | Обязательно |
| S3_ACCESS_KEY_ID | Access key id for the bucket. | Секрет |
| S3_SECRET_ACCESS_KEY | Secret access key for the bucket. | Секрет |
| FILELAYER_BASE_URL | The base of the share URLs this instance mints. Without it, share links come back without a URL. | |
| FILELAYER_DATA_DIR | A local directory for the bytes. Needs no bucket and no IAM user. Set this OR the S3_* block: with neither, the server refuses to start rather than falling back to memory, which would work in a demo and lose the first real file. | |
| FILELAYER_MCP_AGENT_LABEL | How this agent names itself in the audit trail, recorded on every event these tools produce. It is what lets the chain separate "the partner opened this document" from "the partner's assistant opened this document". | |
| FILELAYER_MCP_ALLOW_DESTRUCTIVE | Set to exactly `true` to register delete_file. Off by default because deleting is not recoverable and an agent that misreads a sentence deletes the wrong thing silently. | |
| FILELAYER_MCP_EXPOSE_AUDIT | Set to exactly `true` to register file_audit. Off by default because the trail is an organisation's whole history and a tool that returns it copies every file name, actor and denial into the model's context. Reading it is itself audited since 0.27.0, which was the previous reason; the default did not move. | |
| FILELAYER_MCP_RETURN_BYTES | Set to exactly `true` to register read_file. Off by default because a document returned by a tool is a document copied into a model's context; file_info plus a share link is usually what was actually needed. | |
| S3_BUCKET | The bucket. It must be private: this library decides who may be GIVEN a URL and has no say in who the object store will answer. `npx -p @filelayer/core filelayer doctor` reports whether yours serves unauthenticated reads. | |
| S3_ENDPOINT | An S3-compatible endpoint, for example https://<account>.r2.cloudflarestorage.com. Setting it makes S3_BUCKET, S3_ACCESS_KEY_ID and S3_SECRET_ACCESS_KEY required. | |
| S3_REGION | Region, or `auto` for Cloudflare R2. |
Автоматические проверки
Запущено 14 нояб. 2026 г.Полный отчёт →Прошло наши автоматизированные проверки. Это не аудит безопасности: изучите код и предоставьте серверу минимально необходимый доступ. Как работают проверки
- Связанный и доступный исходный репозиторийfilelayer/filelayer is public and reachablegithub.com/filelayer/filelayer ↗Пройдено
- Пакет указывает этот репозиторий как источник@filelayer/core names filelayer/filelayer as sourcenpmjs.com/package/@filelayer/core ↗Пройдено
- Происхождение сборки (аттестация Sigstore)Sigstore attestation for @filelayer/corenpmjs.com/package/@filelayer/core/v/0.35.3#provenance ↗Пройдено
- Open source лицензия (OSI)Apache-2.0spdx.org/licenses/Apache-2.0.html ↗Пройдено
- Коммит или релиз за последний годLast commit or release 2026-11-13github.com/filelayer/filelayer ↗Пройдено
- OpenSSF ScorecardНе проверялось
- Имя пакета не похоже на популярный пакетNo popular package one edit away from @filelayer/coreПройдено
- Нет критических предупреждений в пакете или его зависимостяхthe package checked; no critical advisoryosv.dev ↗Пройдено
- Нет скрытых инструкций для модели0 tool descriptions and the README read; no override phrases, credential paths or hidden charactersПройдено
- Деструктивные инструменты помеченыНе проверялось
- Удалённая конечная точка отвечает на рукопожатие MCPНе проверялось
README
Открыть на GitHubFilelayer
A first file in an organization, and a refusal, in twelve lines:
npm install @filelayer/core
npm install --save-dev "@electric-sql/pglite@^0.3.11"
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',
});
await fl.files.get(id, { as: 'bob' }); // a member of acme: allowed
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' });
console.log(refusal.summary); // '<time> eve file.read deny:no_membership q3.txt @acme'
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.
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:
- 18 of 18 for Filelayer on the 18 attacks every executed version can express. The executed alternatives had no breaches on them either: Supabase and raw S3 each had one audit gap, a refused read that left no event in the application's audit trail, and Supabase had two partials.
- 133 lines of application code, against a median of 632 for the two alternatives that ran: 4.8x. Convex and Vercel Blob were neither executed nor compiled, so they are left out of the median.
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,
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; paid plans add support and priority, see pricing. 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
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 9 tables. Filelayer owns the schema, you own the
your bucket 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, including a psql session; those are constraints and triggers.
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, including a migration or a psql session, can create a grant pointing at another tenant's file. 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
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
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 | 749 tests, every commit, all of them against a real PostgreSQL |
| 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 an earlier revision of this library 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 -- fourteen
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.18. 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,
declared as an optional peer dependency 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"
Install PGlite with that version constraint. Filelayer supports the
0.3.x line, which is what peerDependencies declares and what the suite runs
against. 0.5.x is not supported: we ran the full suite against 0.5.8 and it
does not pass, so the range has not been widened. PGlite's latest on npm is a
0.5.x release, so omitting the constraint can install a version outside the
supported range, and npm then refuses the whole tree with ERESOLVE. The quotes
are for your shell, not for npm: ^ is a glob operator under zsh with
extendedglob and an escape character in cmd.exe.
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, Hono, Cloudflare Workers, Deno and Bun, 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.
Mounting the wrong one is the most common integration failure we see. 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, as RFC 9110 requires, and only 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.
Вопросы о Filelayer MCP
Как добавить Filelayer MCP в Claude Code?
Выполните claude mcp add --env 'DATABASE_URL=<YOUR_DATABASE_URL>' --env 'FILELAYER_AS=<FILELAYER_AS>' --env 'FILELAYER_ORG=<FILELAYER_ORG>' --env 'S3_ACCESS_KEY_ID=<YOUR_S3_ACCESS_KEY_ID>' --env 'S3_SECRET_ACCESS_KEY=<YOUR_S3_SECRET_ACCESS_KEY>' core -- npx -y @filelayer/core в терминале. Добавьте --scope user, чтобы сервер был доступен во всех проектах.
Как добавить Filelayer MCP в Cursor?
Откройте ~/.cursor/mcp.json и добавьте сервер в mcpServers, используя конфигурацию Cursor из раздела установки выше.
Как Filelayer работает с журналами аудита?
Каждое решение о предоставлении доступа, включая отказы, записывается в цепочку хешированных логов аудита, которая создается в рамках той же транзакции, что и само решение.