gdp-ts

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

gdp-ts

gdp-ts

A sensitive function (one that reads or changes something only some callers may touch) takes a proof about its exact arguments, so calling it without the check, or with a check about a different value, does not compile.
  1. Name values.
    name(viewer.id, projectId, async (user, project) => ...)
    gives each value a compile-time-only name, valid inside the callback.
  2. Prove facts about names. A small trusted module in
    proofs/
    runs the check and returns a proof such as
    UserIsProjectAdmin<U, P>
    , or
    null
    . Only that module can mint it.
  3. Demand proofs. The sensitive function takes
    project: Named<P, ProjectId>
    and
    _proof: UserIsProjectAdmin<U, P>
    . The wrong proof, a proof about another value, a raw id or no proof is a compile error.
This is not a theorem prover. Prove the facts whose absence would be an incident, and stop there (where to stop).
敏感函数(读取或修改某些调用方才有权操作的对象的函数)会接收一份针对其精确参数的 proof,因此,如果不进行该检查,或者使用针对其他值的检查来调用它,代码将无法通过编译。
  1. 为值命名。
    name(viewer.id, projectId, async (user, project) => ...)
    为每个值赋予一个仅在编译期存在的名称,该名称在回调内有效。
  2. 证明关于名称的事实。
    proofs/
    中的小型可信模块执行检查,并返回诸如
    UserIsProjectAdmin<U, P>
    或
    null
    的 proof。只有该模块可以签发此类 proof。
  3. 要求提供 proof。 敏感函数接收
    project: Named<P, ProjectId>
    和
    _proof: UserIsProjectAdmin<U, P>
    。错误的 proof、针对另一个值的 proof、原始 id 或缺少 proof,都会导致编译错误。
这不是定理证明器。只应证明那些一旦缺失就会引发事故的事实,并就此止步(何时停止)。

Workflow

工作流

When adding or changing authorization in a codebase that uses this pattern:
  1. Is the id branded? If not, brand it first.
  2. Is there a proof for the fact you need in
    proofs/
    ? If yes, reuse it. If no, add one file: private
    defineProof
    , exported
    interface X<...> extends Proof<"X", [...]> {}
    , exported
    async function x(...named): Promise<X<...> | null>
    . Nothing else.
  3. Does the sensitive function take proofs about its named arguments? If it takes raw ids, change the signature; let the compiler list the call sites to fix.
  4. Does the request carry other values the operation trusts (a token in a cookie, an id in the body)? Check them in a trusted module against the resource they claim to unlock (
    TokenUnlocksUrl<H>
    ). This is where cross-resource and cross-tenant bugs live.
  5. Are there non-user preconditions (plan, scope, state)? Make them proofs too (
    PlanIncludesPasswordProtection<P>
    ).
  6. In the handler body (not middleware):
    name(...)
    , call the policy function, turn
    null
    into the right HTTP response, do all sensitive work inside the callback. If that block will likely be called from many places, consider moving it into a shared function (recipe step 5).
  7. Never write
    as
    to satisfy a proof or
    Named
    type. If you feel the need, the signature is wrong or you are outside
    proofs/
    . If the codebase has no gdp-ts lint preset yet, add it (recipe step 6); if it does, fix lint errors rather than disabling them.
  8. Never export a prover, never call
    defineProof
    outside
    proofs/
    , never return a
    Named
    , or a proof that mentions that callback's names, from a
    name()
    callback.
  9. Add the new mistake you almost made to
    mistakes.ts
    (a type-checked file that never runs) as one line under
    // @ts-expect-error
    . It is the cheapest regression test you will write (details).
  10. Test the proof function you added. It is the only thing that can be wrong at runtime.
The recipe shows each step in full.
在使用此模式的代码库中新增或修改授权时:
  1. 该 id 是否已品牌化?如果没有,先为其添加品牌类型。
  2. proofs/
    中是否已有证明所需事实的 proof?如果有,复用。如果没有,只新增一个文件:模块私有的
    defineProof
    、导出的
    interface X<...> extends Proof<"X", [...]> {}
    、导出的
    async function x(...named): Promise<X<...> | null>
    。不要做其他事情。
  3. 敏感函数是否接收关于其具名参数的 proof?如果仍接收原始 id,则修改函数签名;让编译器列出需要修复的调用位置。
  4. 请求是否携带操作所信任的其他值(cookie 中的 token、请求体中的 id)?应在可信模块中,将这些值与其声称要解锁的资源进行核对(
    TokenUnlocksUrl<H>
    )。跨资源和跨租户漏洞往往出现在这里。
  5. 是否存在与用户无关的前置条件(套餐、scope、状态)?也应将其定义为 proof(
    PlanIncludesPasswordProtection<P>
    )。
  6. 在 handler 主体中(而非 middleware 中):调用
    name(...)
    ,调用 policy 函数,将
    null
    转为正确的 HTTP 响应,并在回调内完成所有敏感操作。如果该代码块很可能从许多位置调用,可考虑将其移入共享函数(配方第 5 步)。
  7. 绝不要编写
    as
    来强行满足 proof 或
    Named
    类型。如果你觉得有必要这样做,说明函数签名有误,或者当前代码不在
    proofs/
    中。如果代码库尚无 gdp-ts lint preset,请添加它(配方第 6 步);如果已有,则应修复 lint 错误,而不是禁用它们。
  8. 绝不要导出 prover,绝不要在
    proofs/
    之外调用
    defineProof
    ,也绝不要从
    name()
    回调中返回
    Named
    ,或返回提及该回调名称的 proof。
  9. 将你差点犯下的新错误添加到
    mistakes.ts
    (一个经过类型检查但永不运行的文件)中,作为
    // @ts-expect-error
    下的一行。这是你能写出的成本最低的回归测试(详情)。
  10. 测试新增的 proof 函数。它是唯一可能在运行时出错的部分。
配方完整展示了每个步骤。

References

参考

Read the one you need:
FileRead it when
references/recipe.md
Adding a proof, a policy or a sensitive function, or adopting the pattern. Six steps: brand ids, trusted modules, policies as unions, sensitive functions, naming in the handler, lint rules.
references/patterns.md
Reusing proofs, weaker-from-stronger proofs, proofs that carry evidence, preconditions that are not about users.
references/errors.md
A type error mentions
Named<...>
, a proof type, or "two different types with this name".
references/limits.md
Judging what the types do and do not guarantee (forging, stale proofs, older TypeScript).
references/where-to-stop.md
Deciding how much to prove.
按需阅读以下文档:
文件阅读时机
references/recipe.md
添加 proof、policy 或敏感函数,或引入该模式时。包含六个步骤:品牌化 id、可信模块、将策略建模为联合类型、敏感函数、在 handler 中命名、lint 规则。
references/patterns.md
复用 proof、从更强 proof 推导更弱 proof、携带证据的 proof、与用户无关的前置条件。
references/errors.md
类型错误提及
Named<...>
、proof 类型,或“两种同名但不同的类型”时。
references/limits.md
判断类型能够和不能保证什么(伪造、过期 proof、较旧 TypeScript)。
references/where-to-stop.md
确定需要证明多少内容。

API

API

Everything is exported from
@gdp-ts/core
.
ExportWhat it is
Named<N, A>
A value of type
A
with compile-time name
N
. Read it with
.value
.
N
is invariant.
name(a, k)
/
name(a, b, k)
/
name(a, b, c, k)
Gives one to three values fresh names, scoped to
k
. Returns what
k
returns (Promises included).
Proof<Kind, About>
Evidence that fact
Kind
holds about the tuple of names
About
. Has a runtime
kind: Kind
. Both parameters are invariant.
defineProof(kind)
Returns a
Prover
:
{ kind, prove(...named) }
.
prove
infers
About
from its arguments. Keep it private to the module that performs the check.
NameOf<T>
The
N
of a
Named<N, A>
. Rarely needed.
NamesOf<S>
The names of a tuple of
Named
values. Used in
prove
's signature.
Lint presets, for the gaps the type system cannot close (recipe step 6):
ImportWhat it is
@gdp-ts/core/lint/eslint
gdp(options?)
: ESLint flat-config entries. Spread after your typescript-eslint config.
@gdp-ts/core/lint/oxlint
gdp(options?)
: an Oxlint config (works on TypeScript 7).
@gdp-ts/core/lint/plugin
The rules themselves (
gdp-ts/no-define-proof
,
no-exported-prover
,
no-proof-assertion
,
no-type-assertion
,
no-any
), for custom setups.
Options:
proofs
(trusted-module globs, default
**/proofs/**
),
strict
(also ban every
as
and
any
outside them, default
false
),
allowAssertions
(strict-mode exceptions, default
**/lib/ids.ts
),
proofImports
and
files
.
The only place the library asserts a proof type is inside
prove
, so code using it never needs to. The runtime footprint is one frozen
{ kind }
object per
defineProof
call;
prove
returns that same object every time, and
name
wraps each value in a frozen
{ value }
.
所有内容均从
@gdp-ts/core
导出。
导出项用途
Named<N, A>
类型为
A
、具有编译时名称
N
的值。通过
.value
读取。
N
具有不变性。
name(a, k)
/
name(a, b, k)
/
name(a, b, c, k)
为一个至三个值赋予全新名称,名称作用域限定为
k
。返回
k
的返回值(包括 Promise)。
Proof<Kind, About>
表明事实
Kind
关于名称元组
About
成立的证据。运行时具有
kind: Kind
。两个参数均具有不变性。
defineProof(kind)
返回
Prover
:
{ kind, prove(...named) }
。
prove
根据参数推断
About
。应保持其对执行检查的模块私有。
NameOf<T>
Named<N, A>
中的
N
。很少需要使用。
NamesOf<S>
Named
值元组中的名称。用于
prove
的函数签名。
Lint preset 用于弥补类型系统无法封闭的缺口(配方第 6 步):
导入项用途
@gdp-ts/core/lint/eslint
gdp(options?)
:ESLint flat-config 配置项。展开在 typescript-eslint 配置之后。
@gdp-ts/core/lint/oxlint
gdp(options?)
:Oxlint 配置(适用于 TypeScript 7)。
@gdp-ts/core/lint/plugin
规则本身(
gdp-ts/no-define-proof
、
no-exported-prover
、
no-proof-assertion
、
no-type-assertion
、
no-any
),用于自定义配置。
选项包括:
proofs
(可信模块的 glob 模式,默认值为
**/proofs/**
)、
strict
(同时禁止在这些模块之外使用所有
as
和
any
,默认值为
false
)、
allowAssertions
(strict 模式下的例外,默认值为
**/lib/ids.ts
)、
proofImports
和
files
。
该库唯一断言 proof 类型的地方是在
prove
内部,因此使用该库的代码永远不需要进行此类断言。运行时开销仅为每次
defineProof
调用生成一个冻结的
{ kind }
对象;
prove
每次都返回同一个对象,而
name
会将每个值包装在冻结的
{ value }
中。