关于 security-convex
面向 Convex 开发者的安全审计技能,检查身份验证、授权、输入验证及常见漏洞,并提供审计模式和查找风险函数的命令。
主要功能
- 01身份验证与授权检查
- 02输入验证审查
- 03所有权与成员资格核验
- 04HTTP Action 和 Webhook 检查
- 05审计命令与加固清单
适用场景
- 01审计公开的 query 和 mutation
- 02检查文档所有权保护
- 03审查 HTTP 端点的签名验证
- 04查找缺少验证器的函数
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ igorwarzocha/ opencode-workflows --skill security-convex安装后在 Claude Code 中输入/security-convex确认已加载。
附带文件scripts/scan.sh
详细介绍
涵盖 Convex 应用中身份验证、授权、输入验证和 Convex 特有漏洞的安全审计模式。
Vibecoding 最常见的错误:未经过身份验证的函数
Convex 函数默认公开。除非添加身份验证检查,否则任何客户端都可以调用每个查询和变更。
// ❌ CRITICAL: Anyone can read all users
export const listUsers = query({
handler: async (ctx) => {
return await ctx.db.query("users").collect();
},
});
// ❌ CRITICAL: Anyone can delete any document
export const deleteNote = mutation({
args: { noteId: v.id("notes") },
handler: async (ctx, args) => {
await ctx.db.delete(args.noteId);
},
});
// ✓ SECURE: Check auth first
export const listUsers = query({
handler: async (ctx) => {
const userId = await getAuthUserId(ctx);
if (!userId) throw new Error("Unauthenticated");
// Now safe to return data
return await ctx.db.query("users").collect();
},
});
身份验证检查
使用 Convex Auth
import { getAuthUserId } from "@convex-dev/auth/server";
// ❌ No auth check
export const getMyProfile = query({
handler: async (ctx) => {
// Who is "my"? Anyone can call this!
return await ctx.db.query("users").first();
},
});
// ✓ Get authenticated user
export const getMyProfile = query({
handler: async (ctx) => {
const userId = await getAuthUserId(ctx);
if (!userId) throw new Error("Unauthenticated");
return await ctx.db.get(userId);
},
});
使用第三方身份验证(Clerk、Auth0)
// ❌ Just checking ctx.auth exists (wrong!)
export const sensitiveData = query({
handler: async (ctx) => {
const identity = await ctx.auth.getUserIdentity();
// identity could be null!
return await ctx.db.query("secrets").collect();
},
});
// ✓ Properly validate identity
export const sensitiveData = query({
handler: async (ctx) => {
const identity = await ctx.auth.getUserIdentity();
if (!identity) throw new Error("Unauthenticated");
// Now identity.tokenIdentifier is available
return await ctx.db.query("secrets")
.filter(q => q.eq(q.field("userId"), identity.subject))
.collect();
},
});
授权:IDOR 问题
身份验证(你是谁)≠ 授权(你可以访问什么)。
// ❌ HIGH: IDOR - Any logged-in user can read any note
export const getNote = query({
args: { noteId: v.id("notes") },
handler: async (ctx, args) => {
const userId = await getAuthUserId(ctx);
if (!userId) throw new Error("Unauthenticated");
// Authenticated but no ownership check!
return await ctx.db.get(args.noteId);
},
});
// ✓ Check ownership
export const getNote = query({
args: { noteId: v.id("notes") },
handler: async (ctx, args) => {
const userId = await getAuthUserId(ctx);
if (!userId) throw new Error("Unauthenticated");
const note = await ctx.db.get(args.noteId);
if (!note || note.userId !== userId) {
throw new Error("Not found"); // Don't reveal existence
}
return note;
},
});
团队/组织成员身份检查
// ❌ Trusts client-provided teamId
export const getTeamData = query({
args: { teamId: v.id("teams") },
handler: async (ctx, args) => {
const userId = await getAuthUserId(ctx);
if (!userId) throw new Error("Unauthenticated");
// User says they're on this team - but are they?
return await ctx.db.query("projects")
.filter(q => q.eq(q.field("teamId"), args.teamId))
.collect();
},
});
// ✓ Verify membership
export const getTeamData = query({
args: { teamId: v.id("teams") },
handler: async (ctx, args) => {
const userId = await getAuthUserId(ctx);
if (!userId) throw new Error("Unauthenticated");
const membership = await ctx.db.query("teamMembers")
.withIndex("by_team_user", q =>
q.eq("teamId", args.teamId).eq("userId", userId)
).first();
if (!membership) throw new Error("Not a team member");
return await ctx.db.query("projects")
.filter(q => q.eq(q.field("teamId"), args.teamId))
.collect();
},
});
自定义函数模式(推荐)
使用 convex-helpers 默认强制执行身份验证:
// convex/functions.ts
import { customQuery, customMutation } from "convex-helpers/server/customFunctions";
import { getAuthUserId } from "@convex-dev/auth/server";
// All userQuery functions require authentication
export const userQuery = customQuery(query, {
args: {},
input: async (ctx) => {
const userId = await getAuthUserId(ctx);
if (!userId) throw new Error("Unauthenticated");
const user = await ctx.db.get(userId);
if (!user) throw new Error("User not found");
return { ctx: { user }, args: {} };
},
});
// Usage - ctx.user is guaranteed to exist
export const getMyNotes = userQuery({
handler: async (ctx) => {
return await ctx.db.query("notes")
.filter(q => q.eq(q.field("userId"), ctx.user._id))
.collect();
},
});
审计: 检查是否一致地使用了自定义函数。搜索原始的 query( 和 mutation( 用法。
输入验证
缺少验证器
// ❌ No validation - args is 'any'
export const createNote = mutation({
handler: async (ctx, args) => {
await ctx.db.insert("notes", args); // Could insert anything!
},
});
// ✓ Strict validators
export const createNote = mutation({
args: {
title: v.string(),
content: v.string(),
isPublic: v.optional(v.boolean()),
},
handler: async (ctx, args) => {
const userId = await getAuthUserId(ctx);
if (!userId) throw new Error("Unauthenticated");
await ctx.db.insert("notes", {
...args,
userId, // Server sets this, not client
});
},
});
信任客户端提供的所有权 ID
// ❌ Client provides userId - can impersonate anyone
export const createNote = mutation({
args: {
title: v.string(),
userId: v.id("users"), // Client-controlled!
},
handler: async (ctx, args) => {
await ctx.db.insert("notes", args);
},
});
// ✓ Server determines userId
export const createNote = mutation({
args: { title: v.string() },
handler: async (ctx, args) => {
const userId = await getAuthUserId(ctx);
if (!userId) throw new Error("Unauthenticated");
await ctx.db.insert("notes", {
title: args.title,
userId, // From auth, not args
});
},
});
内部函数
// ❌ Sensitive logic in public mutation
export const processPayment = mutation({
args: { amount: v.number() },
handler: async (ctx, args) => {
// Anyone can call this!
await chargeCard(args.amount);
},
});
// ✓ Use internalMutation for sensitive operations
export const processPayment = internalMutation({
args: { userId: v.id("users"), amount: v.number() },
handler: async (ctx, args) => {
// Only callable from other server functions
await chargeCard(args.amount);
},
});
// Public function validates then calls internal
export const purchaseItem = mutation({
args: { itemId: v.id("items") },
handler: async (ctx, args) => {
const userId = await getAuthUserId(ctx);
if (!userId) throw new Error("Unauthenticated");
const item = await ctx.db.get(args.itemId);
// Validate, then call internal
await ctx.runMutation(internal.payments.processPayment, {
userId,
amount: item.price,
});
},
});
HTTP Actions
// ❌ No auth on HTTP endpoint
export const webhook = httpAction(async (ctx, request) => {
const body = await request.json();
await ctx.runMutation(api.data.processWebhook, body);
return new Response("OK");
});
// ✓ Verify webhook signature
export const webhook = httpAction(async (ctx, request) => {
const signature = request.headers.get("x-webhook-signature");
const body = await request.text();
if (!verifySignature(body, signature, process.env.WEBHOOK_SECRET)) {
return new Response("Unauthorized", { status: 401 });
}
await ctx.runMutation(api.data.processWebhook, JSON.parse(body));
return new Response("OK");
});
实时订阅数据泄露
// ❌ Subscription returns all messages (data leak)
export const allMessages = query({
handler: async (ctx) => {
return await ctx.db.query("messages").collect();
},
});
// ✓ Filter by user's access
export const myMessages = query({
handler: async (ctx) => {
const userId = await getAuthUserId(ctx);
if (!userId) return []; // Or throw
// Only messages user has access to
const myChannels = await ctx.db.query("channelMembers")
.filter(q => q.eq(q.field("userId"), userId))
.collect();
const channelIds = myChannels.map(m => m.channelId);
return await ctx.db.query("messages")
.filter(q => q.or(...channelIds.map(id =>
q.eq(q.field("channelId"), id)
)))
.collect();
},
});
环境变量
// ❌ Accessing env vars that don't exist (undefined behavior)
const apiKey = process.env.STRIPE_SECRET_KEY;
// ✓ Use Convex environment variables properly
// Set via: npx convex env set STRIPE_SECRET_KEY sk_live_...
// Access in actions only (not queries/mutations for determinism)
export const callStripe = action({
handler: async (ctx) => {
const apiKey = process.env.STRIPE_SECRET_KEY;
if (!apiKey) throw new Error("STRIPE_SECRET_KEY not configured");
// ...
},
});
注意: 环境变量仅在 actions 中可用,不能在 queries/mutations 中使用。
<severity_table>
常见漏洞摘要
| 问题 | 检查位置 | 严重性 |
|---|---|---|
| query/mutation 中没有身份验证检查 | 所有 query({ 和 mutation({ | 严重 |
| IDOR(没有所有权检查) | 参数中包含文档 ID 的函数 | 高 |
| 客户端提供的 userId | 包含 v.id("users") 的参数 | 高 |
| 缺少验证器 | 没有 args: {} 的函数 | 高 |
| 将公开函数用于内部逻辑 | 敏感业务逻辑 | 高 |
| HTTP action 未经过身份验证 | httpAction( | 高 |
| 订阅数据泄露 | 返回集合的查询 | 中 |
| 原始 query/mutation(未使用自定义函数) | 未使用 userQuery/userMutation | 中 |
</severity_table>
快速审计命令
# Find all public queries and mutations
rg "export const .* = query\(" convex/
rg "export const .* = mutation\(" convex/
# Find functions without auth checks
rg -l "export const .* = (query|mutation)\(" convex/ | \
xargs rg -L "(getAuthUserId|getUserIdentity)"
# Find client-provided userId (potential IDOR)
rg 'userId: v\.id\("users"\)' convex/
# Find functions without validators
rg "handler: async \(ctx\)" convex/ -g "*.ts"
# Find HTTP actions
rg "httpAction" convex/
# Find internal vs public function usage
rg "internalMutation|internalQuery|internalAction" convex/
加固检查清单
- 所有 queries/mutations 都有身份验证检查(或使用自定义函数)
- 文档访问包含所有权/成员身份验证
- userId 来自身份验证上下文,而非客户端参数
- 所有函数都有适当的验证器
- 敏感操作使用 internalMutation/internalAction
- HTTP actions 验证签名/令牌
- 实时订阅按用户访问权限进行筛选
- 一致地使用自定义函数(userQuery/userMutation)
- ESLint 规则禁止导入原始 query/mutation
评论
支持 Markdown