Dateispeicher für S3-kompatible Buckets (R2, S3, MinIO) und lokale Platte, mit signierten Direkt-Uploads
Installieren
genpm add @core/storageWas du bekommst
- Quellcode in src/lib/storage/, 11 Dateien. (22,7 kB)
- KI-Regeln in src/lib/storage/AGENTS.md, dazu Regeldateien für die IDE.
- Umgebungsvariablen in .env.example ergänzt: STORAGE_DRIVER, STORAGE_BUCKET, STORAGE_ENDPOINT, STORAGE_ACCESS_KEY_ID, STORAGE_SECRET_ACCESS_KEY, STORAGE_PUBLIC_URL, STORAGE_SECRET, STORAGE_LOCAL_DIR.
README
@core/storage
File storage for S3-compatible buckets (R2, S3, MinIO) and local disk, with signed direct uploads
A GenPM module: source code + AI rules + MCP config, injected into your project instead of hidden in node_modules. The code lands in src/lib/storage, pinned to a verified commit, and you own it.
Install
genpm add @core/storageNo genpm yet? curl -fsSL https://genpm.net/install.sh | sh (macOS/Linux), irm https://genpm.net/install.ps1 | iex (Windows), or one-off with npx @genpm-net/cli add @core/storage.
Or let your AI agent do it: run genpm mcp setup once, then ask "add @core/storage with genpm" in Claude Code, Cursor, VS Code, Windsurf, Codex or Gemini CLI. It shows you a dry-run plan before writing anything.
What it does
One StorageProvider interface to store and serve files: S3-compatible buckets (Cloudflare R2, AWS S3, MinIO, B2)
signed with SigV4 (aws4fetch, works on Node and Workers), plus local (disk) and memory drivers for development
and tests. Signed direct uploads from the browser with the exact size and content type signed. No media library,
no image processing (that is @core/media). No tables.
Setup
After genpm add, follow these steps (your AI agent finds the same steps in src/lib/storage/AGENTS.md and can do them for you):
- Env for S3/R2 (default driver):
STORAGE_ENDPOINT(R2:https://<account>.r2.cloudflarestorage.com),STORAGE_BUCKET,STORAGE_ACCESS_KEY_ID,STORAGE_SECRET_ACCESS_KEY, optionalSTORAGE_REGION(defaultauto) andSTORAGE_PUBLIC_URL(CDN/custom domain serving thepublic/prefix). Local dev:STORAGE_DRIVER=local,STORAGE_SECRET(≥ 32 chars),STORAGE_PUBLIC_URL=http://localhost:3000(files go toSTORAGE_LOCAL_DIR, default.storage/: add it to.gitignore), and mount the route: Honoapp.route('/api/storage', localStorageRoutes()); Next.jsapp/api/storage/[[...key]]/route.tswithexport { localStoragePut as PUT, localStorageGet as GET } from '@/lib/storage/adapters/next'. - Bucket CORS (S3/R2): allow
PUTfrom your origin with headercontent-type. - Direct upload: server creates
const key = generateKey('public/media', file.name)andawait getStorage().presignUpload(key, { contentType, size, maxBytes: 10_000_000 }); the browser doesfetch(url, { method: 'PUT', headers, body: file }). - Verify: upload a small file, then
getStorage().head(key)returns its size.
What's inside
Paths are relative to src/lib/storage.
index.ts— public API:getStorage(),setStorage(),generateKey(),assertSafeKey(),s3Storage(), types.s3.ts— S3 driver.memory.ts— local/memory drivers and signed tokens.local-routes.ts— handlers for them.adapters/hono.ts,adapters/next.ts— upload/download route, only needed withlocal/memory.
At a glance
- npm dependencies (proposed, never installed without asking):
aws4fetch - Environment variables (added to
.env.example):STORAGE_DRIVER,STORAGE_BUCKET,STORAGE_ENDPOINT,STORAGE_ACCESS_KEY_ID,STORAGE_SECRET_ACCESS_KEY,STORAGE_PUBLIC_URL,STORAGE_SECRET,STORAGE_LOCAL_DIR - AI rules:
AGENTS.md, loaded by your agent only when it works insrc/lib/storage
Security
GenPM installs a 40-character commit SHA (never a branch), verifies an Ed25519-signed manifest, never runs install scripts and scans AI rules for prompt injection. Details: genpm.net/docs/security.
License
Genau das liest deine KI, wenn sie in src/lib/storage arbeitet. Sonst wird ihrem Kontext nichts hinzugefügt.
@core/storage — rules for AI agents
Purpose
One StorageProvider interface to store and serve files: S3-compatible buckets (Cloudflare R2, AWS S3, MinIO, B2)
signed with SigV4 (aws4fetch, works on Node and Workers), plus local (disk) and memory drivers for development
and tests. Signed direct uploads from the browser with the exact size and content type signed. No media library,
no image processing (that is @core/media). No tables.
Map
index.ts— public API:getStorage(),setStorage(),generateKey(),assertSafeKey(),s3Storage(), types.s3.ts— S3 driver.memory.ts— local/memory drivers and signed tokens.local-routes.ts— handlers for them.adapters/hono.ts,adapters/next.ts— upload/download route, only needed withlocal/memory.
Integration
- Env for S3/R2 (default driver):
STORAGE_ENDPOINT(R2:https://<account>.r2.cloudflarestorage.com),STORAGE_BUCKET,STORAGE_ACCESS_KEY_ID,STORAGE_SECRET_ACCESS_KEY, optionalSTORAGE_REGION(defaultauto) andSTORAGE_PUBLIC_URL(CDN/custom domain serving thepublic/prefix). Local dev:STORAGE_DRIVER=local,STORAGE_SECRET(≥ 32 chars),STORAGE_PUBLIC_URL=http://localhost:3000(files go toSTORAGE_LOCAL_DIR, default.storage/: add it to.gitignore), and mount the route: Honoapp.route('/api/storage', localStorageRoutes()); Next.jsapp/api/storage/[[...key]]/route.tswithexport { localStoragePut as PUT, localStorageGet as GET } from '@/lib/storage/adapters/next'. - Bucket CORS (S3/R2): allow
PUTfrom your origin with headercontent-type. - Direct upload: server creates
const key = generateKey('public/media', file.name)andawait getStorage().presignUpload(key, { contentType, size, maxBytes: 10_000_000 }); the browser doesfetch(url, { method: 'PUT', headers, body: file }). - Verify: upload a small file, then
getStorage().head(key)returns its size.
Conventions
- Keys are generated by the server (
generateKey); never use the user's filename or path as the key. - Everything is private unless its key starts with
public/; serve private files withpresignDownloadafter an authorization check. - Store the key in your table, not the URL (URLs change with the CDN or driver).
- A presigned upload URL can be reused until it expires. If the server validates or transforms the file after upload,
presign a private key (e.g.
uploads/pending/…) and have the server copy the validated bytes to the finalpublic/key.
Don't
- Don't make the whole bucket public or proxy private files without checking permissions.
- Don't trust the client's content type for security decisions; @core/media sniffs the real type after upload.
- Don't log storage credentials or presigned URLs.
# @core/storage — rules for AI agents
## Purpose
One `StorageProvider` interface to store and serve files: S3-compatible buckets (Cloudflare R2, AWS S3, MinIO, B2)
signed with SigV4 (`aws4fetch`, works on Node and Workers), plus `local` (disk) and `memory` drivers for development
and tests. Signed direct uploads from the browser with the exact size and content type signed. No media library,
no image processing (that is @core/media). No tables.
## Map
- `index.ts` — public API: `getStorage()`, `setStorage()`, `generateKey()`, `assertSafeKey()`, `s3Storage()`, types.
- `s3.ts` — S3 driver. `memory.ts` — local/memory drivers and signed tokens. `local-routes.ts` — handlers for them.
- `adapters/hono.ts`, `adapters/next.ts` — upload/download route, only needed with `local`/`memory`.
## Integration
1. Env for S3/R2 (default driver): `STORAGE_ENDPOINT` (R2: `https://<account>.r2.cloudflarestorage.com`),
`STORAGE_BUCKET`, `STORAGE_ACCESS_KEY_ID`, `STORAGE_SECRET_ACCESS_KEY`, optional `STORAGE_REGION` (default `auto`)
and `STORAGE_PUBLIC_URL` (CDN/custom domain serving the `public/` prefix).
Local dev: `STORAGE_DRIVER=local`, `STORAGE_SECRET` (≥ 32 chars), `STORAGE_PUBLIC_URL=http://localhost:3000`
(files go to `STORAGE_LOCAL_DIR`, default `.storage/`: add it to `.gitignore`), and
mount the route: Hono `app.route('/api/storage', localStorageRoutes())`; Next.js
`app/api/storage/[[...key]]/route.ts` with `export { localStoragePut as PUT, localStorageGet as GET } from '@/lib/storage/adapters/next'`.
2. Bucket CORS (S3/R2): allow `PUT` from your origin with header `content-type`.
3. Direct upload: server creates `const key = generateKey('public/media', file.name)` and
`await getStorage().presignUpload(key, { contentType, size, maxBytes: 10_000_000 })`; the browser does
`fetch(url, { method: 'PUT', headers, body: file })`.
4. Verify: upload a small file, then `getStorage().head(key)` returns its size.
## Conventions
- Keys are generated by the server (`generateKey`); never use the user's filename or path as the key.
- Everything is private unless its key starts with `public/`; serve private files with `presignDownload` after an authorization check.
- Store the key in your table, not the URL (URLs change with the CDN or driver).
- A presigned upload URL can be reused until it expires. If the server validates or transforms the file after upload,
presign a private key (e.g. `uploads/pending/…`) and have the server copy the validated bytes to the final `public/` key.
## Don't
- Don't make the whole bucket public or proxy private files without checking permissions.
- Don't trust the client's content type for security decisions; @core/media sniffs the real type after upload.
- Don't log storage credentials or presigned URLs.
Der genaue Baum, der nach .genpmignore eingebunden wird. Gepinnt an
// Driver en memoria y driver local (disco) para desarrollo y tests. Las subidas firmadas apuntan a una ruta de la
// propia app (`uploadPath`) que valida un token HMAC y escribe con `handleLocalUpload`.
import { assertSafeKey, isPublicKey, StorageError } from './keys.ts';
import { checkSize } from './s3.ts';
import { type ObjectInfo, type PutBody, type PutOptions, type StorageProvider, streamOf, toBytes } from './provider.ts';
export type Backend = {
write(key: string, bytes: Uint8Array, contentType: string): Promise<void>;
read(key: string): Promise<{ bytes: Uint8Array; contentType: string } | null>;
remove(key: string): Promise<void>;
};
export type LocalConfig = {
/** Secreto para firmar subidas y descargas locales (≥ 32 caracteres). */
secret: string;
/** Origen de la app, p. ej. `http://localhost:3000`. */
baseUrl: string;
/** Ruta que monta `handleLocalUpload` / `handleLocalDownload`. */
routePath?: string;
};
const enc = new TextEncoder();
// base64url sin Buffer (funciona también en Workers y navegador).
const b64url = (bytes: Uint8Array) => btoa(String.fromCharCode(...bytes)).replaceAll('+', '-').replaceAll('/', '_').replace(/=+$/, '');
const fromB64url = (s: string) => Uint8Array.from(atob(s.replaceAll('-', '+').replaceAll('_', '/')), (c) => c.charCodeAt(0));
async function hmac(secret: string, data: string): Promise<string> {
const k = await crypto.subtle.importKey('raw', enc.encode(secret), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']);
return b64url(new Uint8Array(await crypto.subtle.sign('HMAC', k, enc.encode(data))));
}
function timingSafeEqual(a: string, b: string): boolean {
if (a.length !== b.length) return false;
let d = 0;
for (let i = 0; i < a.length; i++) d |= a.charCodeAt(i) ^ b.charCodeAt(i);
return d === 0;
}
type Grant = { op: 'put' | 'get'; key: string; exp: number; size?: number; type?: string };
export async function signGrant(secret: string, g: Grant): Promise<string> {
const body = b64url(enc.encode(JSON.stringify(g)));
return `${body}.${await hmac(secret, body)}`;
}
export async function verifyGrant(secret: string, token: string | null): Promise<Grant> {
const [body, sig] = (token ?? '').split('.');
if (!body || !sig || !timingSafeEqual(sig, await hmac(secret, body))) throw new StorageError('invalid_token');
const g = JSON.parse(new TextDecoder().decode(fromB64url(body))) as Grant;
if (g.exp < Date.now()) throw new StorageError('invalid_token', 'expired');
return g;
}
export function backendStorage(driver: 'local' | 'memory', backend: Backend, cfg: LocalConfig): StorageProvider {
if (cfg.secret.length < 32) throw new Error('STORAGE_SECRET must be >= 32 chars');
const route = `${cfg.baseUrl.replace(/\/+$/, '')}${cfg.routePath ?? '/api/storage'}`;
return {
driver,
async put(key: string, body: PutBody, opts: PutOptions): Promise<ObjectInfo> {
const bytes = await toBytes(body);
await backend.write(assertSafeKey(key), bytes, opts.contentType);
return { key, size: bytes.byteLength, contentType: opts.contentType };
},
async get(key) {
const o = await backend.read(assertSafeKey(key));
return o ? { key, size: o.bytes.byteLength, contentType: o.contentType, body: streamOf(o.bytes) } : null;
},
async head(key) {
const o = await backend.read(assertSafeKey(key));
return o ? { key, size: o.bytes.byteLength, contentType: o.contentType } : null;
},
delete: (key) => backend.remove(assertSafeKey(key)),
async presignUpload(key, opts) {
assertSafeKey(key);
checkSize(opts);
const exp = Date.now() + (opts.expiresIn ?? 600) * 1000;
const token = await signGrant(cfg.secret, { op: 'put', key, exp, size: opts.size, type: opts.contentType });
return { url: `${route}?token=${token}`, method: 'PUT', headers: { 'content-type': opts.contentType }, expiresAt: new Date(exp) };
},
async presignDownload(key, expiresIn = 300) {
assertSafeKey(key);
return `${route}?token=${await signGrant(cfg.secret, { op: 'get', key, exp: Date.now() + expiresIn * 1000 })}`;
},
publicUrl(key) {
assertSafeKey(key);
if (!isPublicKey(key)) throw new StorageError('not_public', `not a public key: ${key}`);
return `${route}/${key}`;
},
};
}
export function memoryBackend(): Backend & { files: Map<string, { bytes: Uint8Array; contentType: string }> } {
const files = new Map<string, { bytes: Uint8Array; contentType: string }>();
return {
files,
write: async (key, bytes, contentType) => void files.set(key, { bytes, contentType }),
read: async (key) => files.get(key) ?? null,
remove: async (key) => void files.delete(key),
};
}
/** Disco local (solo desarrollo): `dir/<clave>` y `dir/<clave>.type` con el content-type. */
export function diskBackend(dir: string): Backend {
const path = async () => import('node:path');
const fs = async () => import('node:fs/promises');
const file = async (key: string) => (await path()).join(dir, ...key.split('/'));
return {
async write(key, bytes, contentType) {
const f = await file(key);
const p = await fs();
await p.mkdir((await path()).dirname(f), { recursive: true });
await p.writeFile(f, bytes);
await p.writeFile(`${f}.type`, contentType);
},
async read(key) {
const f = await file(key);
const p = await fs();
try {
return { bytes: new Uint8Array(await p.readFile(f)), contentType: await p.readFile(`${f}.type`, 'utf8') };
} catch {
return null;
}
},
async remove(key) {
const f = await file(key);
const p = await fs();
await p.rm(f, { force: true });
await p.rm(`${f}.type`, { force: true });
},
};
}
Dieses Paket deklariert keine MCP-Server.
- genpm
- keine
- vorgeschlagen
- GenPM schlägt den npm-Befehl vor und führt ihn nur aus, wenn du zustimmst.
- Verwendet von (1)
- @core/media ^1.0.0
- Prüfung
- Prüfung bestanden · 0 Befunde
- Commit
- v1.0.2 → 4d50ba54c3604f7a5fc0c973183ccee4493e8d76 · nach dem Abruf verifiziert
- Skripte
- Keine. GenPM führt niemals Paketcode aus.
- Lizenz
- MIT
- Qualität
- 100/100
- Anerkannte Lizenzerfüllt
- AGENTS.md erklärt den Zweckerfüllt
- AGENTS.md enthält Integrationsschritteerfüllt
- AGENTS.md nennt Konventionen oder Verboteerfüllt
- Enthält Testserfüllt
- Sicherheitsscan bestandenerfüllt
- In den letzten 6 Monaten veröffentlichterfüllt
- Verifizierter Herausgebererfüllt
- Zusammenfassung und Schlagwörtererfüllt
- Meldung
- Stimmt etwas nicht?