@octabits-io/storage
Namespaced blob storage as one contract with interchangeable adapters. Put,
get, head, list, delete and prefix-delete an object under an optional
namespace; errors come back as Result values; and the HTTP handlers that
serve stored bytes — ETag, If-None-Match, Last-Modified, a safe
Cache-Control default, nosniff — are plain functions, not middleware for
one framework.
Three adapters ship, and one conformance suite runs against all three:
Postgres (a self-owned table over a structural SQL executor — pg, PGlite,
postgres.js), any S3-compatible store, and the local filesystem,
content-addressed. Moving a deployment from S3 to Postgres, or from the
filesystem to either, is a change of factory call. Over any of them, the
encrypting store seals every object under a key per scope before it leaves
the process, so an S3 provider holds only ciphertext.
npm i @octabits-io/storage # the contract, the serve handlers, the fs adapter
npm i @octabits-io/storage aws4fetch # + the S3 adapter (a 2.5 kB SigV4 signer, no AWS SDK)
npm i @octabits-io/storage pg # + the Postgres adapter's Pool convenience
import type { ObjectStorageService } from '@octabits-io/storage';
import { createPostgresObjectStorageService } from '@octabits-io/storage/postgres';
const storage: ObjectStorageService = createPostgresObjectStorageService({
db: pool, // a pg Pool, PGlite, or any SqlExecutor
createPublicUrl: (namespace, key) => `/api/files/${key}`,
});
await storage.uploadObject({ key: 'docs/f.pdf', metadata: { 'content-type': 'application/pdf' }, body: bytes });
const obj = await storage.getObjectData({ key: 'docs/f.pdf' });
if (!obj.ok) return obj; // errors are values
console.log(obj.value.contentType, obj.value.size); // obj.value.data is a Uint8Array
| Subpath | Deps | Contents |
|---|---|---|
. |
@octabits-io/result |
the ObjectStorageService / ObjectStorageUrlProvider / ObjectFileServer contracts, the StorageObject / ObjectData / ListObjectsResponse types, ObjectStorageError, the StorageLogger seam, the encrypting store — createEncryptingObjectStorage, the ObjectKeyring seam, createInMemoryObjectKeyring, objectKeyringFromScopedKeys — and the serve handlers — createWebResponse, createGenericHandler, getObjectData, parseStoragePath / isValidObjectKey / sanitizeObjectKey, DEFAULT_CACHE_CONTROL |
./postgres |
none at runtime (pg an optional peer, for its type) |
createPostgresObjectStorageService, createPostgresObjectStorageUrlProvider, objectStorageDdl(), the SqlExecutor seam and its poolExecutor / toExecutor wrappers |
./drizzle |
drizzle-orm (optional peer) |
objectStorageColumns — the object_storage table as a spreadable Drizzle column set, for a host whose migrations drizzle-kit owns; columns only, the store stays ./postgres |
./s3 |
aws4fetch (optional peer) |
createAWSObjectStorageService, createAWSObjectStorageUrlProvider, NamespacePrefixFn, ObjectCannedACL |
./fs |
none (node:*) |
createFsObjectStorageService, createFsObjectStorageUrlProvider |
A boundary lint keeps the contract, the serve handlers and the Postgres adapter
importing nothing but @octabits-io/result, drizzle-orm confined to
./drizzle, aws4fetch confined to ./s3, and node:* confined to ./fs; everything but ./fs type-checks with no Node
typings (tsconfig.portable.json), so the contract and its two portable
adapters run on a Worker or an edge runtime as well as on Node.
The contract
interface ObjectStorageService {
readonly type?: string;
getPublicUrl(p: { namespace?: string; key: string }): string;
listObjects<T extends boolean>(p: { namespace?: string; prefix?: string; includeHead: T; continuationToken?: string; maxKeys?: number }): Promise<Result<ListObjectsResponse<T>, ObjectStorageError>>;
uploadObject(p: { namespace?: string; key: string; metadata?: Record<string, string>; body: Uint8Array | ReadableStream<Uint8Array>; visibility?: 'public' | 'private' }): Promise<Result<void, ObjectStorageError>>;
deleteObject(p: { namespace?: string; key: string }): Promise<Result<void, ObjectStorageError>>;
deleteObjectsByPrefix(p: { namespace?: string; prefix?: string }): Promise<Result<{ deleted: number }, ObjectStorageError>>;
getObjectData(p: { namespace?: string; key: string }): Promise<Result<ObjectData, ObjectStorageError>>;
}
namespaceis optional, everywhere. It is a logical partition — a tenant id, an environment name, or nothing at all — and how it is realized is the adapter’s business: a key prefix on S3, a column on Postgres, a directory of key records on the filesystem. Omit it and you address the root namespace, so a single-tenant consumer never has to invent a value.''andundefinedare the same namespace.- Keys come back as they went in. Whatever an adapter does with the
namespace underneath,
listObjectsreturns the keys you uploaded. - Content type travels in
metadata.metadata['content-type'](orcontentType) becomes the stored content type, falling back toapplication/octet-stream. There is no separate parameter. ObjectData.datais aUint8Array, not aBuffer: the contract names no runtime. A Node adapter may still hand back aBuffer— it is aUint8Array— but do not rely onBuffermethods; decode with aTextDecoder, or wrap explicitly.deleteObjectsByPrefixrequires a non-emptyprefix. A missing prefix would wipe the namespace (or, on S3 with no namespace, the bucket), so every adapter returnsinvalid_prefixinstead. Delete by listing if a full wipe is genuinely intended.- Delete is idempotent — deleting an absent object succeeds — and a read of
an absent object is
not_found. - Unsafe keys are refused before the backend is touched, on every adapter:
empty, leading
/, or any..path segment yieldsinvalid_key. Keys are concatenated onto prefixes and normalized by CDNs, browsers and filesystems, sons-a/../ns-b/secretnever gets the chance to becomens-b/secret. - Unsafe namespaces are refused the same way:
.,.., or a namespace holding/,\or a control character yieldsinvalid_namespaceon every adapter. On S3 the namespace is the first segment of the request path —..would reach another bucket, anda+ keyb/xis the same object asa/b+ keyx. A tenant id or an environment name passes. - A prefix is literal.
%and_are characters on every adapter, never wildcards:deleteObjectsByPrefix({ prefix: '%' })deletes nothing. ObjectStorageErroris anOctErrorWithKey<'network_error' | 'not_found' | 'not_found_bucket' | 'access_denied' | 'invalid_key' | 'invalid_namespace' | 'invalid_prefix' | 'object_lock_unavailable' | 'internal_error'>.listObjectspages throughcontinuationToken: S3 pages at up to 1000 objects; the Postgres and filesystem adapters return everything in one page and ignore the token.
Each adapter also ships a lighter URL-only factory
(create*ObjectStorageUrlProvider) exposing getPublicUrl plus the read side —
for a process that serves blobs but never writes them.
The adapters
Postgres — ./postgres
Blobs in a self-owned object_storage table, over plain parameterized SQL
through a structural executor. That seam is the whole database dependency:
interface SqlExecutor {
query<R>(sql: string, params?: unknown[]): Promise<{ rows: R[]; rowCount: number | null }>;
transaction<T>(fn: (tx: Pick<SqlExecutor, 'query'>) => Promise<T>): Promise<T>;
}
A pg Pool is the convenience form (poolExecutor wraps it, and passing the
pool directly works — toExecutor discriminates on the missing transaction
method); an embedded PGlite, a postgres.js wrapper or an RLS-scoped connection
implements the seam directly. The adapter never opens a connection of its own,
so the host decides how queries run.
import { Pool } from 'pg';
import { createPostgresObjectStorageService, objectStorageDdl } from '@octabits-io/storage/postgres';
const storage = createPostgresObjectStorageService({
db: new Pool({ connectionString: process.env.DATABASE_URL }),
createPublicUrl: (namespace, key) => `https://app.example.com/api/storage/${namespace ?? '_'}/${key}`,
});
The table appears on first use (CREATE TABLE IF NOT EXISTS, advisory-locked,
in one transaction), and a legacy tenant_id column is renamed to namespace
automatically. With that default every operation — a plain read included —
may trigger DDL on first use, so the connected role needs DDL privileges. Own
the schema in migrations instead by applying objectStorageDdl() and passing
autoCreateTable: false; advisoryLockId changes the bootstrap’s
pg_advisory_xact_lock id (default 123456789) if it collides with one of
yours.
objectStorageDdl() emits the table, both indexes and the
object_storage_namespace_key_unique constraint on (namespace, key). That
constraint is required: uploadObject is one INSERT … ON CONFLICT (namespace, key) DO UPDATE upsert, and a table without it fails uploads with a
pointed internal_error.
Declaring the table (drizzle-kit) — ./drizzle
A host that keeps every table in its own schema and lets drizzle-kit write the
migrations declares object_storage from objectStorageColumns instead of
running objectStorageDdl() — one mechanism per repository, never both. The
store is unchanged: the same plain SQL over the same executor, pointed at the
table the host declared, with autoCreateTable: false.
npm i @octabits-io/storage drizzle-orm
// schema.ts
import { index, pgTable, unique } from 'drizzle-orm/pg-core';
import { objectStorageColumns } from '@octabits-io/storage/drizzle';
export const objectStorage = pgTable('object_storage', { ...objectStorageColumns }, (t) => [
// Required: uploadObject is INSERT … ON CONFLICT (namespace, key).
unique('object_storage_namespace_key_unique').on(t.namespace, t.key),
index('object_storage_namespace_key_idx').on(t.namespace, t.key),
index('object_storage_namespace_idx').on(t.namespace),
]);
// the store, over the table drizzle-kit created
const storage = createPostgresObjectStorageService({
db: pool, // or any SqlExecutor
autoCreateTable: false, // the migrations own the schema
createPublicUrl: (namespace, key) => `/api/files/${key}`,
});
- The table is named
object_storage. The store’s SQL names it and takes no option to rename it. - The unique constraint is not optional. A column set cannot carry a
constraint or an index, so the
pgTablecall does — and withoutobject_storage_namespace_key_uniqueevery upload fails. The index and constraint names are the DDL’s, so a database built either way is the same. namespaceis the scope seam. A multi-scope host passes its scope id as thenamespaceon every call; the root namespace is stored as''. The store never writes a scope column of its own; a host under row-level security adds one with a default the policy reads (DEFAULT current_setting('app.org_id', true), asapps/starterdoes) and keepsnamespaceequal to it, so the policy and the store’s(namespace, key)upsert agree.- Modes.
idandsizeread asnumber(an identity counter and a byte countbyteacaps at 1 GB),created_atandupdated_atasDate,dataas aUint8Arraythrough a localbyteacustom type, andmetadataasRecord<string, string>.
A test holds objectStorageColumns and objectStorageDdl() equal column for
column — name, type, NOT NULL, default, identity — and round-trips a row on
PGlite: written by the SQL store, read through Drizzle, and the other way round.
S3-compatible — ./s3
Not AWS-bound despite the symbol names: every call is a signed fetch against
an explicit endpoint, path-style, so it talks to any S3-compatible store
(production: Hetzner Object Storage, EU).
There is no AWS SDK here. The six calls the contract needs — HEAD, GET, PUT,
DELETE, ListObjectsV2 and Multi-Object Delete — are the REST API written out,
and the only dependency is aws4fetch: a
2.5 kB (gzipped) SigV4 signer over fetch and SubtleCrypto, an optional peer.
What the SDK brought, this package already had — retries with backoff, error
classification — and what it added was 3.3 MB of AWS service bindings across
eleven transitive packages, plus a default-checksum policy that several
S3-compatible stores reject. Requests now carry exactly what the adapter
writes, and the payload hash is computed rather than sent as
UNSIGNED-PAYLOAD, so the signature covers the body even over a plain-HTTP
endpoint.
import { createAWSObjectStorageService } from '@octabits-io/storage/s3';
const storage = createAWSObjectStorageService({
bucket: 'app-blobs',
publicEndpoint: 'https://cdn.example.com',
region: 'eu-central',
endpoint: 'https://<project>.your-objectstorage.com',
accessKeyId,
secretAccessKey,
logger, // the two-method StorageLogger seam
// sessionToken, // for temporary (STS) credentials
// fetch: myFetch, // the fetch that carries the signed requests
});
fetch is a seam, not a setting: a consumer behind a proxy or on a custom
dispatcher hands its own in and the signing is untouched. For the S3 calls this
contract does not model — creating a bucket, a lifecycle rule, a multipart
upload — storage.signedFetch(path, init) is a SigV4-signed fetch against the
configured endpoint (signedFetch('/my-bucket', { method: 'PUT' })).
A body of known length goes out sized whatever the host did to the global fetch.
Next.js patches it and rebuilds any Request it is given, which turns the body
into a stream; a stream leaves as transfer-encoding: chunked, and S3 stores
refuse that on a PUT (RustFS: missing header: content-length). So the default
path calls fetch(url, init) with the bytes, leaving nothing to rebuild, and the
runtime derives the length. A fetch of your own gets the signed Request: send
it as it is, because one rebuilt from request.body goes out chunked. A stream
passed to signedFetch goes out chunked too, unless you set content-length.
Keys are namespace-prefixed (<namespace>/<key>, unprefixed when the namespace
is omitted) and the prefix is stripped from listed keys; namespacePrefix
customizes the layout ((ns) => \tenant/${ns}/`reproduces a pre-namespace one). Transient failures — 5xx, throttling, timeouts — are retried with exponential backoff and jitter.visibility: ‘private’ | ‘public’overrides the configureddefaultACL` per object, which matters because an object ACL grants
access independently of any bucket policy.
Two shapes are worth knowing. uploadObject is a single PUT, so a stream
body is drained first (as it is on the other two adapters) and objects past a
few hundred megabytes want a multipart upload through signedFetch. And
deleteObjectsByPrefix batches up to 1000 keys per Multi-Object Delete, which
the API requires a Content-MD5 over — SubtleCrypto has no MD5, so the
package computes one itself (src/internal/md5.ts, held to the RFC 1321
vectors). It is a wire checksum, never a security primitive. Per-key failures
in that response are surfaced as an error rather than counted as deletes.
WORM: Object Lock
For what must not change after it is written — a ledger anchor, an evidence export, an archived document — the adapter writes under S3 Object Lock:
const archive = createAWSObjectStorageService({
...s3,
bucket: 'ledger-anchors', // created with Object Lock on
objectLock: { mode: 'COMPLIANCE', retainDays: 3650 },
});
const lock = await archive.checkObjectLock(); // at boot: object_lock_unavailable when the bucket has none
await archive.uploadObject({ key: `anchors/${scope}/${at}.json`, body });
- Every upload is locked. It carries the mode, a retain-until date
retainDaysahead and the SHA-256 checksum a locked write needs.COMPLIANCE: nobody, the root account included, deletes the version or shortens its date.GOVERNANCE: a principal with the bypass permission can. - Never silently unlocked. A bucket created without Object Lock refuses the
write, and the adapter returns
object_lock_unavailable— it does not store the object without a lock in its place. - A delete is a marker. Object Lock needs a versioned bucket, where a plain
deleteObjectonly puts a delete marker on top; the locked version stays.listObjectVersions({ prefix })lists versions and markers alike, newest first per key, andgetObjectVersionData({ key, versionId })reads a version a marker hides. A reader that has to trust what it finds — a ledger check against its anchors — reads through these, not throughlistObjects. - What is locked, and until when.
getObjectRetention({ key, versionId? })returns the mode, the retain-until date and the version id. - A date per object.
retainDaysis the lock every upload gets; an object that must be kept until a date of its own — a document kept until the end of its legal retention, counted from its date, not from the upload — is uploaded under the shortest lock (retainDays: 1) and then given its date withsetObjectRetention({ key, versionId?, retainUntil })(S3’s PutObjectRetention, in the configured mode), which answers the retention as the store reads it back. The same call extends a lock later — an open tax assessment keeps a document longer. UnderCOMPLIANCEa date earlier than the one set is refused by the store (access_denied): the adapter does not pre-check, and nothing shortens a lock. If the second call fails, the object stays under its short lock; treat the write as failed and write it again.
Works on any S3-compatible store with Object Lock — AWS S3, MinIO, Ceph RGW, NetApp StorageGRID, RustFS (the integration test runs on it). The bucket and its versioning are created once by whoever runs the store; the adapter never creates buckets.
Filesystem — ./fs
The local disk, content-addressed: an object’s bytes live at a path derived
from the SHA-256 of the content — two hex characters as a directory, then the
full digest — and a small JSON record per (namespace, key) points at that
digest and carries the size, content type, metadata and last-write time.
import { createFsObjectStorageService } from '@octabits-io/storage/fs';
const storage = createFsObjectStorageService({
root: '/var/lib/app/blobs', // created on first write
createPublicUrl: (namespace, key) => `/api/files/${key}`,
});
<root>/blobs/ab/abcd… the bytes, one file per distinct content
<root>/keys/_root/<base64url>.json a key record in the root namespace
<root>/keys/ns_<base64url>/… a key record in a named namespace
Deduplication is not a feature bolted on — identical bytes are one file, in
any namespace — and deleting the last reference to a digest removes it (so does
overwriting the last key that pointed at it). A key is never used as a path:
its record is named by the base64url of the whole key, which is why a key
containing / is one file and a hostile key cannot escape the store even before
the shared key guard rejects it.
Node only, and it says so in the subpath: node:fs/promises, node:path and
node:crypto are the implementation, which is why ./fs is the one part of the
package outside the portability gate. Writes are atomic per file (write a temp
file, rename), and within one process every write and every last-reference
sweep runs in turn, so a put and a delete of identical bytes cannot unlink each
other’s blob; but the store takes no cross-process lock and the sweep scans the
key records — it is meant for development, single-node deployments and tests,
not for a fleet sharing one volume. A key record is a file named by the
base64url of the key, so a key longer than about 180 bytes fails with
internal_error on most filesystems; S3 allows 1024.
The encrypting store
createEncryptingObjectStorage wraps any adapter and seals each object before
the adapter sees it: the body and every metadata value but the content type,
under a key per scope (the namespace; '' for the root). The adapter
underneath — a bucket above all — holds ciphertext only, and destroying the
scope’s key makes every copy of its objects unreadable: the bucket, its
versions, its backups.
import { createEncryptingObjectStorage, objectKeyringFromScopedKeys, createWebResponse } from '@octabits-io/storage';
import { createScopedKeyService } from '@octabits-io/pii';
import { createPostgresScopedKeyStore } from '@octabits-io/pii/postgres';
const storage = createEncryptingObjectStorage({
storage: s3, // any ObjectStorageService: S3, Postgres, the disk
keyring: objectKeyringFromScopedKeys((scope) => { // pii's per-scope keys, one store for fields and files
const keyScope = { column: 'org_id', value: scope };
return createScopedKeyService({ store: createPostgresScopedKeyStore({ db, scope: keyScope }), scope: keyScope, masterKeyProvider, cache });
}),
plainMetadata: ['kind'], // values the backend may read; the content type always is
});
await storage.uploadObject({ namespace: orgId, key: `receipts/${id}`, metadata: { 'content-type': 'application/pdf', name: fileName }, body });
return createWebResponse(storage, { namespace: orgId, key: `receipts/${id}` }, request.headers); // plaintext, the usual headers
It is held to the conformance suite over all three adapters, like an adapter.
- The format.
'OCTE'· version · key id · salt · IV · AES-256-GCM ciphertext · tag; 53 bytes of overhead (ENCRYPTED_OBJECT_OVERHEAD). The AES key is derived per object (HKDF-SHA-256 over the scope’s key and the salt), and the additional data binds the header, the namespace, the key and the purpose: changed bytes, an object copied onto another key or into another namespace, and a metadata value moved to another name all read asdecryption_failed, as does an object written in the clear behind the wrapper. Web Crypto only; it is under the portability gate. - Object Lock and versions keep working. An upload is one write of a newly
sealed object, never a rewrite, and everything needed to open it travels
inside it. On a locked bucket a second upload is a second version; a version a
delete marker hides is read with the S3 adapter’s
getObjectVersionDataand opened withstorage.openObject({ namespace, key, object }). Lock, retention (getObjectRetention,setObjectRetention) and version listings are the S3 adapter’s own methods, called on it (their sizes are the ciphertext’s). - Keys.
ObjectKeyringis two methods:current(scope)for writing,byId(scope, id)for reading. A key is 32 bytes; its id (32 bits) is written into every object, so a rotated scope still opens its older objects while the keyring holds their key. Rotation never re-encrypts — under a lock nothing can be rewritten.objectKeyringFromScopedKeysderives the store’s key from@octabits-io/pii’s scoped age identity (structurally — this package imports nothing from pii); the id is pii’skeyVersion, and pii keeps one version per scope.createInMemoryObjectKeyring()(withrotateanddestroy) is for tests and development: a restart loses its keys. - Shredding. A destroyed scope key reads as
object_key_destroyed, and the serve handlers answer 410 Gone; an upload for the scope is refused. Other processes keep their cached keys for pii’scacheTtlMs(five minutes by default) unless the host wires pii’sonKeysDestroyedbroadcast. In a shredded scope,listObjects({ includeHead: true })fails — its metadata does not open — so a cleanup lists without heads. - What it does not do.
getPublicUrlis the backend’s and serves ciphertext; serve throughcreateWebResponseover the wrapper. The body is held in memory whole while it is sealed or opened. Listings report plaintext sizes; a bare listing computes them from the fixed overhead. Metadata names and the content type stay readable to the backend.
Errors: object_key_destroyed, object_key_unavailable (the keyring failed,
or does not hold the key an object names) and decryption_failed join
ObjectStorageError. The design and its open questions:
docs/specs/storage-encryption.md.
Serving objects over HTTP
The root ships framework-agnostic handlers over ObjectFileServer, the
one-method read side of the contract — so they serve any adapter:
import { createWebResponse } from '@octabits-io/storage';
// inside any web-standard route handler (Hono, Next.js, Bun.serve, a Worker):
return createWebResponse(storage, { key }, request.headers); // served as an attachment
On Node’s http — Express, Connect, NestJS, http.createServer — wrap it with
@octabits-io/server/node, which bridges the request
and streams the response back:
import { toNodeHandler } from '@octabits-io/server/node';
app.use('/storage', toNodeHandler((request) => {
const { key } = parseStoragePath(new URL(request.url).pathname);
return key ? createWebResponse(storage, { key }, request.headers) : new Response('Not found', { status: 404 });
}));
A Nuxt/Nitro handler returns the Response as it is, which h3 accepts since 1.8:
export default defineEventHandler((event) =>
createWebResponse(storage, { key: getRouterParam(event, 'key') ?? '' }, event.headers),
);
createGenericHandler returns { statusCode, headers, body } for plumbing that
has no Response. Both handlers:
- validates the request key before touching storage — traversal segments (plain or percent-encoded), leading slashes and empty keys are rejected with 400;
- emits
ETag,Last-Modified,Content-Length,Cache-Control,Content-DispositionandX-Content-Type-Options: nosniff; - answers 304 to an
If-None-Matchthat names the object’s ETag —*, a comma-separated list, a weakW/tag — with theETag,Last-ModifiedandCache-Controlthe 200 would carry. The ETag is the first 128 bits of the bytes’ SHA-256, so an object overwritten with as many bytes within a second (S3’sLast-Modifiedhas seconds) gets a new one; - keeps internals out of 5xx bodies (a fixed
Internal error; the real error is yours to log) and passes 4xx bodies through, since they describe the caller’s own request.
Two ServeHandlerOptions are worth a decision rather than a default:
contentDisposition— defaults toattachment: a browser that navigates to an object downloads it, while an<img>,<video>orfetchignores the header and shows it. Pass'inline'only for content you trust, or behind a sandboxing CSP or on a separate origin: untrusted SVG or HTML rendered inline on your app’s origin is stored XSS, its scripts running with your origin’s privileges.'attachment; filename="report.pdf"'names the download.cacheControl— defaults toprivate, no-store, because a namespaced blob store normally sits behind an authenticated route. Opt in to'public, max-age=31536000, immutable'only for content-addressed public assets: on an authenticated route,publiclets a CDN store one caller’s object and re-serve it to another.
The conformance suite
src/conformance.ts is the behaviour of ObjectStorageService as one scenario,
and every adapter runs it: the Postgres adapter against an embedded PGlite
through the executor seam, the filesystem adapter in a temp directory
(src/conformance.test.ts, no Docker), and the S3 adapter against a real S3 server, RustFS
(src/integration.test.ts, Docker required — test:unit is the Docker-free half). The encrypting store runs it
over each of the three. Interchangeable adapters are a
claim; the suite is the proof. A fourth adapter passes it or it is not an
adapter.
License
MIT
From @octabits-io/storage@0.14.1 in the platform repository.