convex-security-check

convex-security-check

熱門

快速安全稽核檢查清單,涵蓋驗證、函式暴露、參數驗證、列層級存取控制與環境變數處理

400星標
31分支
更新於 2026/2/6
SKILL.md
唯讀
名稱
convex-security-check
描述

快速安全稽核檢查清單,涵蓋驗證、函式暴露、參數驗證、列層級存取控制與環境變數處理

版本
1.0.0

Convex 安全檢查

針對 Convex 應用程式的快速安全稽核檢查清單,涵蓋驗證、函式暴露、參數驗證、列層級存取控制與環境變數處理。

文件來源

實作前,請勿假設;請取得最新文件:

指示

安全檢查清單

使用此清單快速稽核您的 Convex 應用程式安全性:

1. 驗證
  • [ ] 已設定驗證提供者(Clerk、Auth0 等)
  • [ ] 所有敏感查詢都檢查 ctx.auth.getUserIdentity()
  • [ ] 明確允許未驗證存取(如預期)
  • [ ] 工作階段權杖已正確驗證
2. 函式暴露
  • [ ] 已審查公開函式(querymutationaction
  • [ ] 內部函式使用 internalQueryinternalMutationinternalAction
  • [ ] 沒有敏感操作暴露為公開函式
  • [ ] HTTP actions 驗證來源/驗證
3. 參數驗證
  • [ ] 所有函式都有明確的 args 驗證器
  • [ ] 所有函式都有明確的 returns 驗證器
  • [ ] 敏感資料不使用 v.any()
  • [ ] ID 驗證器使用正確的資料表名稱
4. 列層級存取控制
  • [ ] 使用者只能存取自己的資料
  • [ ] 管理員函式檢查使用者角色
  • [ ] 共享資源有適當的存取檢查
  • [ ] 刪除函式驗證所有權
5. 環境變數
  • [ ] API 金鑰儲存在環境變數中
  • [ ] 程式碼或 schema 中沒有機密
  • [ ] 開發/生產環境使用不同的金鑰
  • [ ] 環境變數僅在 actions 中存取

驗證檢查

// convex/auth.ts
import { query, mutation } from "./_generated/server";
import { v } from "convex/values";
import { ConvexError } from "convex/values";

// 輔助函式:要求驗證
async function requireAuth(ctx: QueryCtx | MutationCtx) {
  const identity = await ctx.auth.getUserIdentity();
  if (!identity) {
    throw new ConvexError("需要驗證");
  }
  return identity;
}

// 安全查詢模式
export const getMyProfile = query({
  args: {},
  returns: v.union(v.object({
    _id: v.id("users"),
    name: v.string(),
    email: v.string(),
  }), v.null()),
  handler: async (ctx) => {
    const identity = await requireAuth(ctx);
    
    return await ctx.db
      .query("users")
      .withIndex("by_tokenIdentifier", (q) => 
        q.eq("tokenIdentifier", identity.tokenIdentifier)
      )
      .unique();
  },
});

函式暴露檢查

// 公開 - 暴露給用戶端(請仔細審查!)
export const listPublicPosts = query({
  args: {},
  returns: v.array(v.object({ /* ... */ })),
  handler: async (ctx) => {
    // 任何人都可以呼叫此函式 - 刻意公開
    return await ctx.db
      .query("posts")
      .withIndex("by_public", (q) => q.eq("isPublic", true))
      .collect();
  },
});

// 內部 - 僅能從其他 Convex 函式呼叫
export const _updateUserCredits = internalMutation({
  args: { userId: v.id("users"), amount: v.number() },
  returns: v.null(),
  handler: async (ctx, args) => {
    // 此函式無法直接從用戶端呼叫
    await ctx.db.patch(args.userId, {
      credits: args.amount,
    });
    return null;
  },
});

參數驗證檢查

// 良好:嚴格驗證
export const createPost = mutation({
  args: {
    title: v.string(),
    content: v.string(),
    category: v.union(
      v.literal("tech"),
      v.literal("news"),
      v.literal("other")
    ),
  },
  returns: v.id("posts"),
  handler: async (ctx, args) => {
    const identity = await requireAuth(ctx);
    return await ctx.db.insert("posts", {
      ...args,
      authorId: identity.tokenIdentifier,
    });
  },
});

// 不良:弱驗證
export const createPostUnsafe = mutation({
  args: {
    data: v.any(), // 危險:允許任何資料
  },
  returns: v.id("posts"),
  handler: async (ctx, args) => {
    return await ctx.db.insert("posts", args.data);
  },
});

列層級存取控制檢查

// 更新前驗證所有權
export const updateTask = mutation({
  args: {
    taskId: v.id("tasks"),
    title: v.string(),
  },
  returns: v.null(),
  handler: async (ctx, args) => {
    const identity = await requireAuth(ctx);
    
    const task = await ctx.db.get(args.taskId);
    
    // 檢查所有權
    if (!task || task.userId !== identity.tokenIdentifier) {
      throw new ConvexError("無權更新此任務");
    }
    
    await ctx.db.patch(args.taskId, { title: args.title });
    return null;
  },
});

// 刪除前驗證所有權
export const deleteTask = mutation({
  args: { taskId: v.id("tasks") },
  returns: v.null(),
  handler: async (ctx, args) => {
    const identity = await requireAuth(ctx);
    
    const task = await ctx.db.get(args.taskId);
    
    if (!task || task.userId !== identity.tokenIdentifier) {
      throw new ConvexError("無權刪除此任務");
    }
    
    await ctx.db.delete(args.taskId);
    return null;
  },
});

環境變數檢查

// convex/actions.ts
"use node";

import { action } from "./_generated/server";
import { v } from "convex/values";

export const sendEmail = action({
  args: {
    to: v.string(),
    subject: v.string(),
    body: v.string(),
  },
  returns: v.object({ success: v.boolean() }),
  handler: async (ctx, args) => {
    // 從環境變數存取 API 金鑰
    const apiKey = process.env.RESEND_API_KEY;
    
    if (!apiKey) {
      throw new Error("未設定 RESEND_API_KEY");
    }
    
    const response = await fetch("https://api.resend.com/emails", {
      method: "POST",
      headers: {
        "Authorization": `Bearer ${apiKey}`,
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        from: "noreply@example.com",
        to: args.to,
        subject: args.subject,
        html: args.body,
      }),
    });
    
    return { success: response.ok };
  },
});

範例

完整安全模式

// convex/secure.ts
import { query, mutation, internalMutation } from "./_generated/server";
import { v } from "convex/values";
import { ConvexError } from "convex/values";

// 驗證輔助函式
async function getAuthenticatedUser(ctx: QueryCtx | MutationCtx) {
  const identity = await ctx.auth.getUserIdentity();
  if (!identity) {
    throw new ConvexError({
      code: "UNAUTHENTICATED",
      message: "您必須登入",
    });
  }
  
  const user = await ctx.db
    .query("users")
    .withIndex("by_tokenIdentifier", (q) => 
      q.eq("tokenIdentifier", identity.tokenIdentifier)
    )
    .unique();
    
  if (!user) {
    throw new ConvexError({
      code: "USER_NOT_FOUND",
      message: "找不到使用者設定檔",
    });
  }
  
  return user;
}

// 檢查管理員角色
async function requireAdmin(ctx: QueryCtx | MutationCtx) {
  const user = await getAuthenticatedUser(ctx);
  
  if (user.role !== "admin") {
    throw new ConvexError({
      code: "FORBIDDEN",
      message: "需要管理員權限",
    });
  }
  
  return user;
}

// 公開:列出自己的任務
export const listMyTasks = query({
  args: {},
  returns: v.array(v.object({
    _id: v.id("tasks"),
    title: v.string(),
    completed: v.boolean(),
  })),
  handler: async (ctx) => {
    const user = await getAuthenticatedUser(ctx);
    
    return await ctx.db
      .query("tasks")
      .withIndex("by_user", (q) => q.eq("userId", user._id))
      .collect();
  },
});

// 僅管理員:列出所有使用者
export const listAllUsers = query({
  args: {},
  returns: v.array(v.object({
    _id: v.id("users"),
    name: v.string(),
    role: v.string(),
  })),
  handler: async (ctx) => {
    await requireAdmin(ctx);
    
    return await ctx.db.query("users").collect();
  },
});

// 內部:更新使用者角色(永不暴露)
export const _setUserRole = internalMutation({
  args: {
    userId: v.id("users"),
    role: v.union(v.literal("user"), v.literal("admin")),
  },
  returns: v.null(),
  handler: async (ctx, args) => {
    await ctx.db.patch(args.userId, { role: args.role });
    return null;
  },
});

最佳實務

  • 除非明確指示,否則絕不執行 npx convex deploy
  • 除非明確指示,否則絕不執行任何 git 指令
  • 回傳敏感資料前,務必驗證使用者身分
  • 使用內部函式處理敏感操作
  • 使用嚴格的驗證器驗證所有參數
  • 更新/刪除操作前檢查所有權
  • 將 API 金鑰儲存在環境變數中
  • 審查所有公開函式的安全影響

常見陷阱

  1. 缺少驗證檢查 - 務必驗證身分
  2. 暴露內部操作 - 使用 internalMutation/Query
  3. 信任用戶端提供的 ID - 驗證所有權
  4. 對參數使用 v.any() - 使用特定的驗證器
  5. 硬編碼機密 - 使用環境變數

參考資料