Token导航 LogoToken导航TokenDH.com
研究检索需要联网github未标认证来源可访问clear审计异常

graphql-securityGraphQL 安全

Agent Skill

用于辅助 API 设计、接口文档、请求响应结构和服务集成说明。它适合让 Agent 梳理 endpoint、生成 OpenAPI 草稿、检查字段命名、整理错误码或辅助前后端联调。使用时需要确认真实业务语义、鉴权方式、分页和错误处理规则;涉及生成接口文档时,应避免凭空补字段,最好从现有代码、schema 或接口样例中提取事实。

总安装

212

周安装

9

GitHub Stars

1

下载量

74
CodexClaudeCursorGemini CLI

安装说明

本站只整理中文说明和来源信息,不托管安装包,也不代用户安装。

GitHub

来源数

3

许可证

MIT

最后核验

2026-05-01

来源状态

来源可访问

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:graphql-security(GraphQL 安全)
来源仓库:https://github.com/pluginagentmarketplace/custom-plugin-graphql
仓库路径:skills/graphql-security
安装命令:
npx skills add https://github.com/pluginagentmarketplace/custom-plugin-graphql --skill graphql-security
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。不同来源提供的安装方式可能略有差异;本站展示可直接复制的安装命令,安装前请核对来源页面。

skills.shnpx skills
npx skills add https://github.com/pluginagentmarketplace/custom-plugin-graphql --skill graphql-security

简介

用于识别 GraphQL API 中的安全风险与防护措施。

  • 适合检查未授权访问、过度数据暴露与注入漏洞。graphql-security 属于研究检索类 Skill,可作为该场景下的辅助能力补充。
  • 使用时需提供 schema 片段或查询示例进行分析。
  • 可建议字段级权限控制、查询复杂度限制与审计日志。
  • 安装前请核实是否需读取生产环境配置或访问用户数据。

SKILL.md

GraphQL Security Skill

Protect your GraphQL APIs from attacks

Overview

Learn essential security patterns for GraphQL: JWT authentication, role-based authorization, rate limiting, query complexity limits, and input validation.


Security Checklist

CheckPriorityImplementation
AuthenticationCriticalJWT with refresh tokens
AuthorizationCriticalField-level with graphql-shield
Rate LimitingCriticalPer-user/IP with Redis
Query DepthHighgraphql-depth-limit
Query ComplexityHighgraphql-query-complexity
IntrospectionHighDisable in production
Input ValidationHighValidate all inputs
Error MaskingMediumHide internal errors

Core Patterns

1. JWT Authentication

import jwt from 'jsonwebtoken';

// Token creation
function createTokens(user) {
  const accessToken = jwt.sign(
    { userId: user.id, roles: user.roles },
    process.env.JWT_SECRET,
    { expiresIn: '15m' }
  );

  const refreshToken = jwt.sign(
    { userId: user.id },
    process.env.JWT_REFRESH_SECRET,
    { expiresIn: '7d' }
  );

  return { accessToken, refreshToken };
}

// Context setup
const context = async ({ req }) => {
  const token = req.headers.authorization?.replace('Bearer ', '');

  let user = null;
  if (token) {
    try {
      const payload = jwt.verify(token, process.env.JWT_SECRET);
      user = await db.users.findById(payload.userId);
    } catch (e) {
      // Token invalid or expired
    }
  }

  return { user };
};

// Login resolver
const resolvers = {
  Mutation: {
    login: async (_, { email, password }) => {
      const user = await db.users.findByEmail(email);

      if (!user || !await bcrypt.compare(password, user.passwordHash)) {
        throw new GraphQLError('Invalid credentials', {
          extensions: { code: 'UNAUTHORIZED' }
        });
      }

      return { ...createTokens(user), user };
    },
  },
};

2. Authorization with graphql-shield

import { rule, shield, and, or } from 'graphql-shield';

// Rules
const isAuthenticated = rule()((_, __, { user }) => user !== null);

const isAdmin = rule()((_, __, { user }) =>
  user?.roles?.includes('ADMIN')
);

const isOwner = rule()(async (_, { id }, { user, dataSources }) => {
  const resource = await dataSources.findById(id);
  return resource?.userId === user?.id;
});

// Permissions
const permissions = shield({
  Query: {
    me: isAuthenticated,
    users: and(isAuthenticated, isAdmin),
    user: and(isAuthenticated, or(isOwner, isAdmin)),
  },
  Mutation: {
    updateUser: and(isAuthenticated, or(isOwner, isAdmin)),
    deleteUser: and(isAuthenticated, isAdmin),
  },
  User: {
    email: or(isOwner, isAdmin),
    privateField: isOwner,
  },
}, {
  fallbackError: new GraphQLError('Not authorized'),
});

// Apply
import { applyMiddleware } from 'graphql-middleware';
const protectedSchema = applyMiddleware(schema, permissions);

3. Rate Limiting

// Express-level (basic)
import rateLimit from 'express-rate-limit';

app.use('/graphql', rateLimit({
  windowMs: 15 * 60 * 1000, // 15 minutes
  max: 100,
  keyGenerator: (req) => req.user?.id || req.ip,
}));

// GraphQL-level (granular)
const typeDefs = gql`
  directive @rateLimit(max: Int!, window: String!) on FIELD_DEFINITION

  type Mutation {
    login(email: String!, password: String!): AuthPayload!
      @rateLimit(max: 5, window: "15m")

    sendEmail(input: SendEmailInput!): Boolean!
      @rateLimit(max: 10, window: "1h")
  }
`;

4. Query Limits

import depthLimit from 'graphql-depth-limit';
import { createComplexityLimitRule } from 'graphql-validation-complexity';

const server = new ApolloServer({
  typeDefs,
  resolvers,
  validationRules: [
    // Max depth of 10
    depthLimit(10),

    // Max complexity of 1000
    createComplexityLimitRule(1000, {
      scalarCost: 1,
      objectCost: 2,
      listFactor: 10,
    }),
  ],

  // Disable introspection in production
  introspection: process.env.NODE_ENV !== 'production',
});

5. Input Validation

import validator from 'validator';
import xss from 'xss';

const validate = {
  email: (v) => {
    if (!validator.isEmail(v)) throw new Error('Invalid email');
    return validator.normalizeEmail(v);
  },

  password: (v) => {
    if (v.length < 8) throw new Error('Password too short');
    if (!/[A-Z]/.test(v)) throw new Error('Need uppercase');
    if (!/[0-9]/.test(v)) throw new Error('Need number');
    return v;
  },

  html: (v) => xss(v),
};

const resolvers = {
  Mutation: {
    createUser: async (_, { input }) => {
      const clean = {
        email: validate.email(input.email),
        password: validate.password(input.password),
        bio: input.bio ? validate.html(input.bio) : null,
      };
      return db.users.create(clean);
    },
  },
};

6. Error Masking

const server = new ApolloServer({
  formatError: (error) => {
    // Log full error
    console.error(error);

    // In production, hide internal errors
    if (process.env.NODE_ENV === 'production') {
      if (error.extensions?.code === 'INTERNAL_SERVER_ERROR') {
        return { message: 'Internal error', extensions: { code: 'INTERNAL_ERROR' } };
      }
    }

    return error;
  },
});

Security Headers

import helmet from 'helmet';
import cors from 'cors';

app.use(helmet());
app.use(cors({
  origin: process.env.ALLOWED_ORIGINS?.split(','),
  credentials: true,
}));
app.use(express.json({ limit: '100kb' }));

Troubleshooting

IssueCauseSolution
Token always invalidClock skewAdd grace period
Rate limit bypassWrong keyUse user ID when authenticated
Auth not workingContext asyncAwait context setup
Introspection exposedWrong env checkVerify NODE_ENV

Security Testing

# Test introspection (should fail in prod)
curl -X POST $API \
  -H "Content-Type: application/json" \
  -d '{"query":"{ __schema { types { name } } }"}'

# Test rate limit
for i in {1..20}; do
  curl -X POST $API \
    -d '{"query":"mutation { login(email:\"x\",password:\"y\") { token } }"}'
done

# Test depth limit (should fail)
curl -X POST $API \
  -d '{"query":"{ user { posts { author { posts { author { id } } } } } }"}'

Usage

Skill("graphql-security")

Related Skills

  • graphql-apollo-server - Server configuration
  • graphql-resolvers - Auth in resolvers
  • graphql-schema-design - Auth-aware schema

Related Agent

  • 06-graphql-security - For detailed guidance

适合场景

01

用户想查找某类 Agent Skill 时

02

需要根据任务场景推荐可安装能力包时

03

需要对比不同来源的安装命令和来源信息时

04

需要参考平台分布和安装热度时

能力概览

能力 1

按任务关键词查找相关 Skills

能力 2

展示可复制的安装命令

能力 3

保留来源站点、仓库和原始说明,方便继续核验

能力 4

补充不同宿主或平台的使用分布数据

能力 5

展示第三方安全扫描或审计结果

安装后应在对应宿主中按原始 README 的触发条件使用;具体调用方式请以来源页面和 README 为准。

平台分布

Claude Code

28.42%
按下载量换算21

windsurf

21.06%
按下载量换算16

trae

16.28%
按下载量换算12

OpenCode

12.13%
按下载量换算9

Cursor

7.43%
按下载量换算5

Codex

3.51%
按下载量换算3

安全审计

Gen Agent Trust Hub

未通过

Socket

通过

Snyk

通过

权限和风险

需要联网

该 Skill 可能需要联网访问来源站点、仓库或外部 API;具体网络访问范围需要结合源码和 README 复核。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。来源安全扫描存在 warning/failed 结果,不能写成本站确认安全。

来源信息

继续浏览同类 Skills