@graphile/depth-limit

中文文档
0.4.0发布于 2026/10/13MITTypeScriptCommonJS零依赖近 30 天下载 14.9万

用于GraphQL操作的验证规则,以避免过深的询问.

中文使用文档
文档目录17 节
  1. 财务问题
  2. 我能相信这个模块吗?
  3. 这个模块是图形化的吗?
  4. 我需要这个模块吗?
  5. 如果我使用信任文件,我是否需要这个?
  6. 使用量
  7. 图表ql-http
  8. 覆盖
  9. 瑜伽语
  10. 原始图QL.js
  11. 选项
  12. 如何为您选择正确的选项
  13. 社区资助的开放源码软件
  14. countOperationDepths
  15. countDepth
  16. 洞穴
  17. 另见

@ graphile/ 深度限制

高度能限制深度 图QL.js 帮助的验证规则 保护您的服务器免遭恶意操作.

  • 在操作中限制字段选择深度
  • 列表在操作中可能嵌入的次数限制
  • 同一字段坐标的限定次数可能是(直接或 间接地)筑巢
  • 对内部查询和常规操作有单独的限制
  • 可以添加特定字段的限制,以表示它们可能筑巢的次数 (例如允许"朋友的朋友"但否认"朋友的朋友"通过 {'User.friends': 2}(中文(简体) )
  • 可以配置到每个片段引用也会增加深度 (不建议)

财务问题

我能相信这个模块吗?

你检查对了! 本单元由下列人员维护: 本杰·吉拉姆成员 图QL 技术指导委员会。 。 。 .

该模块没有依赖性(尽管它确实有“同”依赖性,即: graphql当然,所以审计应该是直截了当的.

这个模块是麻省理工学院的许可,所以正如它在许可证中所说的:THE SOFTWARE IS 提供 " 资产是 " ,不带任何种类的恐惧、驱逐或监禁,包括 但不限制于雇佣军,特别是 目的与不动。 连警察或警察都没有 B. 任何索赔、索赔或其他赔偿责任的赔偿责任 产生于、来自或涉及 软件或软件的使用或其他交易.

这个模块是图形化的吗?

没有! 此规则应用于允许自定义 GraphQL.js 的任何服务器 审定规则。 格蕾丝后期并不具体快点、 格拉夫斯尔或任何 其他图形软件.

我需要这个模块吗?

GraphQL是一个非常强大的技术,但必须小心处理 - 这是 比较容易让坏角色写出一个小的 GraphQL 查询,从而导致 服务器来完成大量工作。 因此,这是 强烈建议你只接受 信任的文档 给您的 GraphQL 服务器 - 像 Facebook 内部一样 .

如果您的 GraphQL API 被不可信( 或不完全) 消耗 (信任的)第三方,那么你就不能依赖安全利益 信任的文件模式,因此你需要保护自己免受恶意伤害 查询。 这条规则很容易使用(虽然你 应该注意,单靠它是不够的, 你仍然应该使用所有的 保护您的 API 的常见模式: 速率限制, 断路器, 执行超时,执行页码限制,体积限制等).

如果我使用信任文件,我是否需要这个?

即使你正在使用这个 信任文档 (经修正) 查询、存储的操作等)模式(如果您的 API 是 仅打算被您自己的网站、 移动应用程序和其他 这仍然是一条有用的验证规则.

虽然信任的文件意味着恶意行动的关切是没有意义的 (每个文件都可信,所以没有人是恶意的),这个规则 仍然有助于防止工程师写出过于复杂的询问 而且对你的服务器来说可能太贵了 合理,当使用 信任文件,以便根据需要增加限制.

使用量

安装模块(和 graphql与您的包管理器选择 :

yarn add graphql @graphile/depth-limit

然后如何使用它取决于您使用的服务器软件.

图表ql-http

添加 depthLimit() 页:1 validationRules 列表传递到 createHandler 电话 以下是一个以“与..... http" 使用实例 在图表ql-http文档中数字 :

import http from "http";
import { createHandler } from "graphql-http/lib/use/http";
import { depthLimit } from "@graphile/depth-limit";
import { schema } from "./schema.js";

// Create the GraphQL over HTTP handler
export const handler = createHandler({
  schema,
  validationRules: [
    depthLimit({
      // Options here
    }),
  ],
});

覆盖

如果你用的是绝佳的 内嵌插件系统 您的图形QL 用我们的手 useDepthLimit 导出以构建一个内嵌插件来添加 验证规则 :

import * as GraphQLJS from "graphql";
import { envelop, useEngine } from "@envelop/core";
import { useDepthLimit } from "@graphile/depth-limit";

const getEnveloped = envelop({
  plugins: [
    useEngine(GraphQLJS),
    useDepthLimit({
      // Options here
    }),
  ],
});

瑜伽语

用图QL 瑜伽,你会跟上面的Envelop一样遵循类似的设置 文献 瑜伽插件。 。 。 .

import { createYoga } from "graphql-yoga";
import { useDepthLimit } from "@graphile/depth-limit";

const yoga = createYoga({
  plugins: [
    useDepthLimit({
      // Options here
    }),
  ],
});

原始图QL.js

如果你正在使用这个 graphql 从 npm 直接导入模块 depthLimit 工厂的功能及其与 specifiedRules (规则) 在验证 GraphQL 操作时:

import { depthLimit } from "@graphile/depth-limit";
import { validate, specifiedRules, parse, execute } from "graphql";

const allValidationRules = [
  // ❗ Don't forget to use the built in GraphQL validation rules!
  ...specifiedRules,

  //👇👇👇👇
  depthLimit({
    // Options here
  }),
  //👆👆👆👆
];

// This is just an example (and assumes the schema has already been validated).
// The `validate()` call is the part that would differ from what you would
// normally have; in particular the optional third argument is specified.
export function executeGraphQLRequest(
  schema: GraphQLSchema,
  source: string,
  variableValues?: Record<string, any>,
) {
  let document;
  try {
    document = parse(source);
  } catch (syntaxError) {
    return {
      errors: [syntaxError],
    };
  }

  //                                        👇👇👇👇👇👇👇👇👇
  const errors = validate(schema, document, allValidationRules);
  //                                        👆👆👆👆👆👆👆👆👆

  if (errors.length > 0) {
    return { errors };
  }

  return execute({ schema, document, variableValues });
}

选项

无论您如何加载此验证规则, 它都接受相同的选项 :

export type Options = {
  /**
   * How many selection sets deep may the user query?
   *
   * @defaultValue `12`
   */
  maxDepth?: number;

  /**
   * How many nested lists deep may the user query?
   *
   * @defaultValue `4`
   */
  maxListDepth?: number;

  /**
   * How many times may a field reference itself recursively by default. This
   * is to try and block the most common forms of attack automatically, if you
   * have legitimate cases where a field should be referenced recursively then
   * you may specifically override those via `maxDepthByFieldCoordinates`.
   *
   * @defaultValue `2`
   */
  maxSelfReferentialDepth?: number;

  /**
   * How many selection sets deep may the user query in introspection?
   *
   * @defaultValue `12`
   */
  maxIntrospectionDepth?: number;

  /**
   * How many nested lists deep may the user query in introspection?
   *
   * @defaultValue `3`
   */
  maxIntrospectionListDepth?: number;

  /**
   * How many times may an introspection field reference itself recursively by
   * default. This is to try and block the most common forms of attack
   * automatically, if you have legitimate cases where a field should be
   * referenced recursively then you may specifically override those via
   * `maxDepthByFieldCoordinates`.
   *
   * @defaultValue `2`
   */
  maxIntrospectionSelfReferentialDepth?: number;

  /**
   * Set `true` if you want fragment spreads to add to the depth. Not
   * recommended; fragments are essential to using GraphQL correctly so using
   * them should not have a penalty.
   *
   * Whether this setting is true or false, the fields referenced by the
   * fragment will still of course weigh into the depth calculations.
   *
   * @defaultValue `false`
   */
  fragmentsAddToDepth?: boolean;

  /**
   * Limits the number of times a particular field coordinate can be nested
   * inside itself; for example:
   *
   * ```
   * maxDepthByFieldCoordinates: {
   *   'User.friends': 2,
   * }
   * ```
   *
   * Would allow you to load a users friends, or their friends of friends, but
   * not their friends of friends of friends.
   */
  maxDepthByFieldCoordinates?: Record<string, number>;

  /**
   * If true, informs the user what the issues are. Setting this to true could
   * have security ramifications as it will make it easier for an attacker to
   * determine your limits (however, this could be derived with minimal effort
   * also, so is potentially not a big deal).
   *
   * @defaultValue `false`
   */
  revealDetails?: boolean;
};

如何为您选择正确的选项

首先,我们设定了内向默认 允许最常见的 内向查询通过验证,所以不需要自定义 除非你在做一些花样.

您应该看看自定义的主要选项是 maxListDepth, (中文(简体) ), maxDepth 财务报告和审定财务报表 maxSelfReferentialDepth (按此顺序排列).

如果你从头开始,你应该 设置低,并工作你的 随你怎么说 如果您拥有一个已有的服务器, 那么它可能有意义 跟踪您暂时的查询, 并找出所使用的平移值( 请参看 countOperationDepths 并设定限制,以防止 更复杂的询问.

归根结底,调整这些参数 更多的是一种艺术而不是科学, 而这个 这也是为什么这个验证规则不是 所构建的特征 graphql 模块,或者事实上,规格.

最大长度

maxListDepth 您应该设置到您能够容忍的最低值; 某物 像2,3或4个。 您的用户不太可能成功进入 通过收藏 比这个更深。 说明: maxListDepth 只计数 列表中的选择集,所以缩略图列表被忽略,而不添加到 伯爵,这是设计.

最大深度

maxDepth 也该设定为适当低值,虽然它远比 允许生长这个。 一个常见的内向查询需要 深度为12(主要是由于 ofType { ofType { ofType { ... } } } 页:1 确定字段或参数的类型),因此这是我们偶数使用的默认值 用于非回顾性查询; 更低会更好, 但如果 你需要这个 注意, 如果您的策略使用了中继光标连接模式 可能最终需要更深的限度 比你可能意识到.

最大自定义深度

maxSelfReferentialDepth 默认仅为 2 并阻止攻击者 利用图表中的循环(例如:. { friends { friends { friends { ... } } } }) (中文(简体) ). 我们建议你留着这个 限制低,然后通过 maxDepthByFieldCoordinates 如果一个 特定田地一般以筑巢方式使用.

最大深度字段坐标

如果你在计划中有一个特定的周期(例如你可能拥有) User.friends 返回时 [User],因此您可以将其查询为 { currentUser { friends { friends { friends { friends { ... } } } } } }和 你希望防止人们筑巢过多(或者,或者, 愿意让它们筑巢超过 maxSelfReferentialDepth 时间) 然后可以设定特定字段可能次数的具体限制 编号限制 计划坐标, (中文(简体) ), 例如:

import { depthLimit } from "@graphile/depth-limit";

export const rule = depthLimit({
  maxSelfReferentialDepth: 2,
  maxDepthByFieldCoordinates: {
    // Allow `{ currentUser { friends { friends { friends { name }  } } } }`
    // But forbid `{ currentUser { friends { friends { friends { friends { name } } } } } }`
    "User.friends": 3,
  },
});

社区资助的开放源码软件

我喜欢GraphQL(故名:Graphile!),我坚信 开源软件的好处,但我没时间写 像这样的软件 财务报告和审定财务报表 出去挣一天的工资 如果你用这个 验证规则,请考虑 赞助我{\fn方正粗倩简体\fs12\an8\1cHFFFF00\b0}这样我才能保持 并建造这种关键软件, 也许我甚至有机会 工作在我的山上 GraphQL spect PRs。 。 。 . 谢谢你赞助我 这个计划不可能存在 没有赞助商的支持.

* 联合国 还有其他的赞助方法,如果你有兴趣的话 在GitHub handle上的电子邮件.

countOperationDepths

此函数返回给定文档中看到的深度, 帮助您计算 显示您选择的好值。 多数选项在这里被忽略, 影响结果的主(只有?) depths 实值 fragmentsAddToDepth。 。 。 .

您可以在此同时提供 schema SDL( 或 schema 对象) 和文档 源代码文本 。 如果您已经解析过文档, 请使用 countDepths 反而更能表现.

import { countOperationDepths } from "@graphile/depth-limit";

const schema = /* GraphQL */ `
  type Query {
    currentUser: User
  }
  type User {
    name: String
    friends: [User!]!
  }
  type Mutation {
    addFriend(id: ID!): AddFriendPayload
  }
  type AddFriendPayload {
    query: Query
  }
`;

const source = /* GraphQL */ `
  query FriendsOfFriends {
    ...FoF
  }
  mutation AddFriend($id: ID!) {
    addFriend(id: $id) {
      query {
        ...FoF
      }
    }
  }
  fragment FoF on Query {
    currentUser {
      name
      friends {
        name
        friends {
          name
        }
      }
    }
  }
`;

const depthsByOperationName = countOperationDepths(schema, source);

import assert from "assert";
assert.deepEqual(depthsByOperationName, {
  FriendsOfFriends: {
    $$depth: 3,
    $$listDepth: 2,
    "Query.currentUser": 1,
    "User.name": 1,
    "User.friends": 2,
  },
  AddFriend: {
    $$depth: 5,
    $$listDepth: 2,
    "Mutation.addFriend": 1,
    "AddFriendPayload.query": 1,
    "Query.currentUser": 1,
    "User.name": 1,
    "User.friends": 2,
  },
});

countDepth

此函数返回给定操作中看到的深度, 帮助您计算 显示您选择的好值。 多数选项在这里被忽略, 影响结果的主(只有?) depths 实值 fragmentsAddToDepth。 。 。 .

import assert from "assert";
import { countDepth } from "@graphile/depth-limit";
import { parse, Kind, getOperationAST } from "graphql";
import { schema } from "./schema.js";

const query = /* GraphQL */ `
  query FriendsOfFriends {
    currentUser {
      name
      friends {
        name
        friends {
          name
        }
      }
    }
  }
`;

const document = parse(query);
const operationName = undefined;
const fragments = document.definitions.filter(
  /** @type {(d: any) => d is import('graphql').FragmentDefinitionNode} */
  (d) => d.kind === Kind.FRAGMENT_DEFINITION,
);
const operation = getOperationAST(document, operationName);
const { depths, resolvedOptions } = countDepth(schema, operation, fragments, {
  // Options here
});
assert.deepEqual(depths, {
  $$depth: 3,
  $$listDepth: 2,
  "Query.currentUser": 1,
  "User.name": 1,
  "User.friends": 2,
});

洞穴

我们在翻转文档时计算出当前命名的字段类型 类型可以是对象、界面或联盟类型。 因此,一个领域 在一个界面上存在的,根据 如果用户直接通过界面或其中之一访问 执行.

另见

这不是唯一限制验证的深度规则, 其他的检查是:

版本与发布记录

@graphile/depth-limit 共发布 5 个版本,首次发布于 2024/04/16;过去 12 个月发布了 1 个版本。

版本发布日期距今
0.4.0latest2026/10/131 个月前
0.3.12024/06/172 年前
0.3.02024/04/162 年前
0.2.02024/04/162 年前
0.1.02024/04/162 年前

关于 @graphile/depth-limit 的常见问题

@graphile/depth-limit 是什么?

用于GraphQL操作的验证规则,以避免过深的询问.

如何安装 @graphile/depth-limit?

在项目目录运行 npm install @graphile/depth-limit,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:graphql(>=15 <18)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@graphile/depth-limit 支持 TypeScript 吗?

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

@graphile/depth-limit 支持 ESM 还是 CommonJS?

以 CommonJS 形式发布,可以直接 require();在 ES Module 项目中也可以用 import 引入(Node.js 会把 module.exports 作为默认导出)。

@graphile/depth-limit 可以商用吗?

@graphile/depth-limit 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@graphile/depth-limit 的下载量有多少?

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

@graphile/depth-limit 还在维护吗?

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