@gilhrpenner/convex-files-control

中文文档
0.6.0发布于 2026/11/09Apache-2.0TypeScriptES Module构建来源已验证近 30 天下载 5.4万

A convex files control component for Convex.

原始使用文档
文档目录21 节
  1. Features
  2. Development and demo
  3. Install
  4. Quick start
  5. 1) Add the component
  6. 2) Create wrapper functions in your app
  7. 3) Optional HTTP routes
  8. Uploading files
  9. Presigned URL flow
  10. React hook
  11. Downloading files
  12. Create a grant + build a URL
  13. Shareable links
  14. Password-protected grants
  15. Access control & queries
  16. Cleanup
  17. Server-side helper (FilesControl)
  18. R2 configuration
  19. Transfer between providers
  20. Testing helper
  21. Example app

Convex Files Control

A Convex component for secure file uploads, access control, download grants, and lifecycle cleanup. Works with Convex storage and Cloudflare R2, and ships with an optional HTTP upload/download router plus a React upload hook.

Live Demo →

Features

  • Two-step uploads (presigned URL) with access keys and optional expiration.
  • Optional HTTP upload/download routes with auth hooks.
  • Download grants with max uses, expiration, optional password, and shareable links.
  • Access-key based authorization (user IDs, tenant IDs, etc.).
  • Built-in cleanup for expired uploads, grants, and files.
  • Transfer files between Convex and R2.
  • React hook for presigned or HTTP uploads.

Development and demo

See CONTRIBUTING.md for reproducible checks, example/README.md for local setup, and example/DEPLOY.md for deployment. The live demo is a shared sandbox with demo-user impersonation; upload disposable test data only.

Install

Requires Convex 1.46+ and Node 22.12+ (Node 24 recommended). React 18 and 19 remain supported.

npm install @gilhrpenner/convex-files-control

Quick start

1) Add the component

// convex.config.ts
import { defineApp } from "convex/server";
import convexFilesControl from "@gilhrpenner/convex-files-control/convex.config";

const app = defineApp();
app.use(convexFilesControl);

export default app;

2) Create wrapper functions in your app

The component stores access control and download grants. Your app should store its own file metadata (name, owner, etc.) and enforce auth. The wrappers below mirror the example app in example/convex/files.ts.

// convex/files.ts
import { ConvexError, v } from "convex/values";
import { mutation } from "./_generated/server";
import { components } from "./_generated/api";

export const generateUploadUrl = mutation({
  args: {
    provider: v.union(v.literal("convex"), v.literal("r2")),
  },
  handler: async (ctx, args) => {
    const identity = await ctx.auth.getUserIdentity();
    if (!identity) throw new ConvexError("Unauthorized");

    return await ctx.runMutation(
      components.convexFilesControl.upload.generateUploadUrl,
      {
        provider: args.provider,
        // r2Config: { accountId, accessKeyId, secretAccessKey, bucketName },
      },
    );
  },
});

export const finalizeUpload = mutation({
  args: {
    uploadToken: v.string(),
    storageId: v.string(),
    fileName: v.string(),
    expiresAt: v.optional(v.union(v.null(), v.number())),
    metadata: v.optional(
      v.object({
        size: v.number(),
        sha256: v.string(),
        contentType: v.union(v.string(), v.null()),
      }),
    ),
  },
  handler: async (ctx, args) => {
    const identity = await ctx.auth.getUserIdentity();
    if (!identity) throw new ConvexError("Unauthorized");

    const { fileName, ...componentArgs } = args;
    const result = await ctx.runMutation(
      components.convexFilesControl.upload.finalizeUpload,
      {
        ...componentArgs,
        accessKeys: [identity.subject],
      },
    );

    // Store your own file record (name, owner, etc.) here.
    // await ctx.db.insert("files", { ... });

    return result;
  },
});

3) Optional HTTP routes

If you want /files/upload and /files/download, register the router in convex/http.ts. Access keys are provided by your hook (not via the form).

// convex/http.ts
import { httpRouter } from "convex/server";
import { registerRoutes } from "@gilhrpenner/convex-files-control";
import { components } from "./_generated/api";

const http = httpRouter();

registerRoutes(http, components.convexFilesControl, {
  pathPrefix: "files",
  enableUploadRoute: true,

  // Required when enableUploadRoute is true
  checkUploadRequest: async (ctx) => {
    const identity = await ctx.auth.getUserIdentity();
    if (!identity) {
      return new Response(JSON.stringify({ error: "Unauthorized" }), {
        status: 401,
        headers: { "Content-Type": "application/json" },
      });
    }

    return { accessKeys: [identity.subject] };
  },

  // Optional: persist file metadata after a successful HTTP upload
  onUploadComplete: async (ctx, { result, file, formData }) => {
    const fileNameFromForm = formData.get("fileName");
    const fileName =
      typeof fileNameFromForm === "string"
        ? fileNameFromForm
        : ((file as File).name ?? "untitled");
    // await ctx.runMutation(api.files.recordUpload, { ...result, fileName });
  },

  // Optional: provide accessKey for downloads
  checkDownloadRequest: async (ctx) => {
    const identity = await ctx.auth.getUserIdentity();
    if (identity) return { accessKey: identity.subject };
  },
});

export default http;

HTTP upload requires multipart/form-data with fields:

  • file (required)
  • provider (optional, "convex" | "r2")
  • expiresAt (optional, timestamp or null)

Access keys are not accepted via the form; they must come from checkUploadRequest. Additional form fields are available on onUploadComplete via formData.

Useful route options:

  • pathPrefix (default: /files)
  • defaultUploadProvider (\"convex\" or \"r2\")
  • enableDownloadRoute (default: true)
  • requireAccessKey (force checkDownloadRequest to return an access key)
  • passwordHeader / passwordQueryParam (override or disable password inputs)
  • cors (exact browser origins and allowed headers; other browser origins receive 403)
registerRoutes(http, components.convexFilesControl, {
  cors: {
    allowedOrigins: ["https://app.example.com"],
    allowedHeaders: ["Authorization", "Content-Type"],
    allowCredentials: false,
  },
});

Requests without an Origin header continue to work. If cors is omitted, the existing permissive CORS behavior remains unchanged.

Uploading files

Presigned URL flow

// Client-side
const { uploadUrl, uploadToken } = await generateUploadUrl({
  provider: "convex",
});

const uploadResponse = await fetch(uploadUrl, {
  method: "POST",
  body: file,
  headers: { "Content-Type": file.type || "application/octet-stream" },
});

const { storageId } = await uploadResponse.json();

const result = await finalizeUpload({
  uploadToken,
  storageId,
  fileName: file.name,
  expiresAt: Date.now() + 60 * 60 * 1000,
});

React hook

import { useUploadFile } from "@gilhrpenner/convex-files-control/react";
import { api } from "../convex/_generated/api";

const convexSiteUrl = import.meta.env.VITE_CONVEX_URL.replace(
  ".cloud",
  ".site",
);

const { uploadFile } = useUploadFile(api.files, {
  method: "presigned",
  http: { baseUrl: convexSiteUrl },
});

// Presigned
await uploadFile({ file, provider: "convex" });

// HTTP route
await uploadFile({
  file,
  method: "http",
  provider: "convex",
  http: {
    baseUrl: convexSiteUrl,
    // authToken: useAuthToken() from @convex-dev/auth/react
  },
});

uploadFile accepts:

  • file (required)
  • provider ("convex" | "r2")
  • expiresAt (timestamp or null)
  • method ("presigned" | "http")

Downloading files

Create a grant + build a URL

import { buildDownloadUrl } from "@gilhrpenner/convex-files-control";

const grant = await ctx.runMutation(
  components.convexFilesControl.download.createDownloadGrant,
  {
    storageId,
    maxUses: 1,
    expiresAt: Date.now() + 10 * 60 * 1000,
    shareableLink: false,
  },
);

const url = buildDownloadUrl({
  baseUrl: "https://<your-convex-site>",
  downloadToken: grant.downloadToken,
  filename: "report.pdf",
  // pathPrefix: "/files", // Optional if you changed the HTTP route prefix
});

Access keys are not placed in the URL. For private grants, supply them via checkDownloadRequest (HTTP route) or pass accessKey when calling consumeDownloadGrantForUrl.

Set shareableLink: true to allow unauthenticated downloads (no access key required). This is how the example app generates public links. If you enable requireAccessKey on the HTTP route, shareable links will still require checkDownloadRequest to return an access key.

Password-protected grants

const grant = await ctx.runMutation(
  components.convexFilesControl.download.createDownloadGrant,
  { storageId, password: "secret-passphrase" },
);

To consume a password-protected grant, pass password to consumeDownloadGrantForUrl, or send it to the HTTP route via the x-download-password header (preferred) or the password query param. Query params can leak into logs, so headers or POST flows are safer.

Access control & queries

Access keys are normalized (trimmed) and must contain at least one non-empty value.

  • accessControl.addAccessKey(storageId, accessKey)
  • accessControl.removeAccessKey(storageId, accessKey)
  • accessControl.updateFileExpiration(storageId, expiresAt)
  • queries.hasAccessKey(storageId, accessKey)
  • queries.listAccessKeysPage(storageId, paginationOpts)
  • queries.listFilesPage(paginationOpts)
  • queries.listFilesByAccessKeyPage(accessKey, paginationOpts)
  • queries.listDownloadGrantsPage(paginationOpts)
  • queries.getFile({ storageId })

Pagination uses { numItems: number, cursor: string | null }.

Cleanup

Use cleanUp.cleanupExpired to delete expired uploads, grants, and files. The example app wraps this in a mutation and runs it in a cron job.

// convex/crons.ts
import { cronJobs } from "convex/server";
import { internal } from "./_generated/api";

const crons = cronJobs();
crons.hourly(
  "cleanup-expired-files",
  { minuteUTC: 0 },
  internal.files.cleanupExpiredFiles,
  {},
);
export default crons;

Server-side helper (FilesControl)

If you prefer a class wrapper around component calls, use FilesControl:

import { FilesControl } from "@gilhrpenner/convex-files-control";
import { components } from "./_generated/api";

const files = new FilesControl(components.convexFilesControl, {
  // r2: { accountId, accessKeyId, secretAccessKey, bucketName, jurisdiction },
});

await files.generateUploadUrl(ctx, { provider: "convex" });

FilesControl.clientApi() also returns a ready-to-export API surface with optional hooks if you want the component to generate your Convex mutations and queries for you.

R2 configuration

Provide R2 credentials when you use R2 for uploads, downloads, deletes, or transfers. You can pass r2Config to the component calls or supply env vars for the HTTP routes:

  • R2_ACCOUNT_ID
  • R2_ACCESS_KEY_ID
  • R2_SECRET_ACCESS_KEY
  • R2_BUCKET_NAME
  • R2_JURISDICTION (optional, for example eu or fedramp)

Set R2_JURISDICTION only when your bucket was created with a Cloudflare R2 jurisdiction. See Cloudflare's data location docs for the supported jurisdiction values and S3 endpoint format.

Transfer between providers

const result = await ctx.runAction(
  components.convexFilesControl.transfer.transferFile,
  { storageId, targetProvider: "r2", r2Config },
);

The transfer preserves access keys and download grants, updates the file record, and deletes the original storage object.

Testing helper

import { convexTest } from "convex-test";
import { register } from "@gilhrpenner/convex-files-control/test";

const t = convexTest(schema, modules);
register(t, "convexFilesControl");

Example app

Live Demo →

A full Convex + React + Convex Auth implementation lives in example/. It demonstrates:

  • presigned and HTTP uploads
  • authenticated downloads and shareable links
  • access key management
  • transfer between Convex and R2
  • scheduled cleanup

版本与发布记录

@gilhrpenner/convex-files-control 共发布 16 个版本,首次发布于 2025/12/29;过去 12 个月发布了 16 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
0.6.0latest2026/11/097 天前
0.5.92026/09/241 个月前
0.5.82026/08/262 个月前
0.5.72026/08/033 个月前
0.5.62026/06/125 个月前
0.5.52026/06/035 个月前

关于 @gilhrpenner/convex-files-control 的常见问题

@gilhrpenner/convex-files-control 是什么?

A convex files control component for Convex.

如何安装 @gilhrpenner/convex-files-control?

在项目目录运行 npm install @gilhrpenner/convex-files-control,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:react(^18.3.1 || ^19.0.0)、convex(^1.46.0)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@gilhrpenner/convex-files-control 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@gilhrpenner/convex-files-control 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@gilhrpenner/convex-files-control 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=22.12.0。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@gilhrpenner/convex-files-control 可以商用吗?

@gilhrpenner/convex-files-control 使用 Apache-2.0 许可。宽松许可:允许商业使用、修改和再分发,并附带明确的专利授权;分发时需保留许可与 NOTICE 文件,修改过的文件要注明改动。以上为概括,不构成法律意见,请以许可原文为准。

@gilhrpenner/convex-files-control 的下载量有多少?

根据 npm 官方下载统计,@gilhrpenner/convex-files-control 在 2026/10/17 – 2026/11/15 这 30 天内被下载 54,049 次,日均约 1,802 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@gilhrpenner/convex-files-control 还在维护吗?

最新版本 0.6.0 发布于 2026/11/09(7 天前);至今共发布 16 个版本,其中过去 12 个月发布了 16 个;首次发布于 2025/12/29。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。