Promote develop to main — JSR-only plugins, and the GitHub mirror #7

Merged
chrnx merged 31 commits from develop into main 2026-09-23 17:03:17 +00:00
52 changed files with 5615 additions and 8 deletions

No files matched your search

+14
View File
@@ -0,0 +1,14 @@
#!/bin/sh
# Pre-commit gate. Auto-fixes formatting and lint on staged TypeScript, re-stages it, then enforces lint
# and the complexity gate. Enabled by the `prepare` script (`git config core.hooksPath .githooks`).
set -e
staged=$(git diff --cached --name-only --diff-filter=ACM -- 'packages/*.ts' 'test/*.ts')
if [ -n "$staged" ]; then
echo "$staged" | xargs npx prettier --write
echo "$staged" | xargs npx eslint --fix
echo "$staged" | xargs git add
fi
npm run lint
npm run complexity:check
+37
View File
@@ -0,0 +1,37 @@
---
name: Bug report
about: A plugin behaves differently from what its README or its types promise
labels: bug
---
## Which plugin
<!-- @green-tea/jwt, @green-tea/metrics or @green-tea/rate-limit -->
## What happened
## What you expected
## Minimal reproduction
The smallest app that shows it — the `createApp` call, the plugin options, and the route:
```ts
```
## Environment
- Plugin version:
- `@green-tea/core` version:
- Runtime and version: <!-- Node 22.11 / Deno 2.1 / Bun 1.3 / Cloudflare Workers -->
- OS:
<!--
If it works on one runtime and not another, say which. That difference is usually
the bug rather than a detail of it.
Each README has a Runtimes table. If the behaviour you hit is a runtime the table
already rules out, that is a documentation problem rather than a bug — still worth
filing, just say so.
-->
+14
View File
@@ -0,0 +1,14 @@
# Design questions and "should this live here?" threads do not fit a form, and they are
# worth having. Keep the blank option available.
blank_issues_enabled: true
contact_links:
- name: Security vulnerability
url: https://github.com/Expressive-Tea/green-tea-plugins/security/advisories/new
about: Report it privately instead. Never in a public issue — see SECURITY.md.
- name: A bug in green-tea itself
url: https://github.com/Expressive-Tea/green-tea/issues/new
about: The framework lives in its own repository. Plugins are types-only against it.
- name: Documentation
url: https://green-tea.expressive-tea.io/docs/
about: How to wire a route, a module, a plugin or a runtime adapter.
+35
View File
@@ -0,0 +1,35 @@
---
name: Plugin proposal
about: Suggest something for the official set — before writing it
labels: enhancement
---
## What it does
<!-- One paragraph. What a user gets that they do not have today. -->
## Why it belongs in the official set
<!--
The honest question is not whether the code would be good. It is whether this
belongs here rather than as your own package.
A plugin that depends on a service, a vendor or a protocol we cannot test is
usually better as `@you/green-tea-whatever`, published to JSR or npm. That is a
first-class outcome, not a consolation — say so if you already plan it that way
and only want a sanity check.
-->
## Runtimes it could support
<!--
Node, Deno, Bun, workerd — and which it cannot, with the reason. A plugin that
needs a filesystem cannot serve workerd, for instance, and knowing that early
changes the design rather than the documentation.
-->
## Shape
```ts
// The call as a user would write it.
```
+26
View File
@@ -0,0 +1,26 @@
> **Base branch:** on GitHub this must target `contrib`, not `main`. You can change it above before you submit — and [here is why](https://github.com/Expressive-Tea/green-tea-plugins/blob/main/CONTRIBUTING.md#where-to-send-your-changes). Delete this line once the base is right.
## What this changes
<!-- A sentence or two, on the why rather than the what. -->
Closes #
## Which runtimes you ran
<!-- Not all four are expected for a typo. Say which you ran rather than leaving it to be guessed. -->
- [ ] `npm test` (Node)
- [ ] `npm run test:deno`
- [ ] `npm run test:bun`
- [ ] `npm run test:edge`
## Checklist
- [ ] The base branch above is `contrib`
- [ ] Commits are signed off (`git commit -s`)
- [ ] `lint`, `format:check`, `typecheck`, `complexity:check` and `deno publish --dry-run` pass locally
- [ ] New behaviour has a test
- [ ] Core is still imported as `import type` only — never a value import
- [ ] If `engines` changed, the package README's Runtimes table changed with it
- [ ] A breaking change is under `### Breaking`, first in that package's CHANGELOG
+89
View File
@@ -0,0 +1,89 @@
name: CI
# Runs on BOTH forges. It used to be guarded to the development forge, because the packages built
# against a core that existed only on an internal registry a public runner cannot reach. They now
# resolve `@green-tea/core` from npmjs.org, so that reason is gone and the guards are too.
#
# `contrib` is in both lists because external pull requests target it (CONTRIBUTING.md). Leaving it
# out is not a smaller version of running CI — it is none: a pull request against a branch that is
# not listed triggers nothing at all, so a contributor gets no signal and neither does whoever
# merges it.
#
# GitHub does not run workflows on pull requests from forks until a maintainer approves them, so a
# contributor's first push may sit with no checks for a while. That is not a rejection.
on:
push:
branches: [develop, main, contrib]
pull_request:
branches: [develop, main, contrib]
jobs:
# Its own job so a missing sign-off reports on its own and costs nothing on push. Checks that the
# trailer is present, not that it matches the author.
dco:
if: github.event_name == 'pull_request'
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Every commit needs a Signed-off-by
env:
RANGE: ${{ github.event.pull_request.base.sha }}..${{ github.event.pull_request.head.sha }}
run: |
missing=0
for sha in $(git rev-list --no-merges "$RANGE"); do
if ! git show -s --format='%(trailers:key=Signed-off-by,valueonly)' "$sha" | grep -q '[^[:space:]]'; then
echo "::error::no Signed-off-by: $(git show -s --format='%h %s' "$sha")"
missing=1
fi
done
if [ "$missing" = 1 ]; then
echo "Fix the whole branch with: git rebase --signoff ${{ github.event.pull_request.base.sha }}"
exit 1
fi
echo "All commits signed off."
# Node 22 is the lowest `engines.node` any package declares (spec 2.5: build on the floor).
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: '22'
- run: npm ci
- run: npm run lint
- run: npm run format:check
- run: npm run complexity:check
- run: npm run typecheck
- run: npm test
# No build step: JSR publishes `src/` and transpiles it. `deno publish --dry-run`, in the
# `runtimes` job below, is what stands in for it — that is the publish path these packages
# actually take.
# A fixed matrix, not `fromJSON`: Gitea Actions support for a dynamic matrix was not verified. Each
# entry runs only the packages whose engines name that runtime (scripts/run-runtime.mjs).
runtimes:
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
runtime: [deno, bun, edge]
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: '22'
- run: npm ci
- if: matrix.runtime == 'deno'
uses: denoland/setup-deno@v2
with:
deno-version: v2.x
- if: matrix.runtime == 'bun'
uses: oven-sh/setup-bun@v2
- run: npm run test:${{ matrix.runtime }}
# Kept because it passed locally on Deno 2.9.6: `nodeModulesDir: manual` resolves core from the
# tree `npm ci` installed, so JSR's checker never needs the version to exist on npm.
- if: matrix.runtime == 'deno'
run: deno publish --dry-run
+51
View File
@@ -0,0 +1,51 @@
name: Promote → GitHub
# Promotion. Runs on GITEA ONLY. Mirrors two branches to the public GitHub repo and nothing else:
#
# main → GitHub main what has been promoted
# develop → GitHub contrib what outside contributors fork from and target
#
# Feature branches stay private, which is why this is a workflow rather than a push-mirror — that
# would expose every branch.
#
# `contrib` exists because CONTRIBUTING.md sends people there. A pull request against `main` would
# put the two forges out of step, so contributors need a branch that tracks current development,
# and this is it. Same arrangement as core.
#
# Neither push is forced. For `contrib` that is the guard rather than a limitation: the push is
# refused exactly when `contrib` holds external merges nobody has carried into `develop` yet. Carry
# them, and the next develop push fast-forwards.
#
# Tags are deliberately NOT mirrored, and `--tags` is left off the push for the same reason. These
# packages publish to JSR, where a version can never be replaced or removed — so promoting a tag
# has to stay a decision someone takes deliberately, never a side effect of promoting a branch.
on:
push:
branches: [main, develop]
jobs:
push-github:
if: ${{ github.server_url != 'https://github.com' }}
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0 # full history for a clean push
- name: Push to GitHub
env:
GH_TOKEN: ${{ secrets.GH_PROMOTE_TOKEN }}
run: |
case "$GITHUB_REF_NAME" in
main) target=main ;;
develop) target=contrib ;;
*) echo "::error::promote runs for main and develop only, got '$GITHUB_REF_NAME'"; exit 1 ;;
esac
if [ -z "$GH_TOKEN" ]; then
echo "::error::GH_PROMOTE_TOKEN is not set on this repository. Add it in Settings → Actions → Secrets."
exit 1
fi
git remote add github "https://x-access-token:${GH_TOKEN}@github.com/Expressive-Tea/green-tea-plugins.git"
if ! git push github "HEAD:refs/heads/${target}"; then
echo "::error::GitHub ${target} has commits that ${GITHUB_REF_NAME} does not. For contrib that means external merges not yet carried into develop — carry them (CONTRIBUTING.md); never force this push."
exit 1
fi
+8
View File
@@ -0,0 +1,8 @@
{
"printWidth": 120,
"tabWidth": 2,
"singleQuote": true,
"semi": true,
"trailingComma": "all",
"arrowParens": "always"
}
+65 -3
View File
@@ -24,9 +24,49 @@ Run all of them before proposing anything as finished. CI runs each one and each
## Two forges
Gitea `Green-Tea/plugins` is the origin. `develop` and `main` are protected; everything lands through
a pull request. Until core is consumed from npm (Plan B3), CI runs on Gitea only, because
`@green-tea/core` comes from Verdaccio, which a GitHub runner cannot reach.
Development lives on a private Gitea instance. GitHub is a downstream mirror that receives `main`,
and `develop` under the name `contrib`. On the development forge `develop` and `main` are
protected; everything lands through a pull request.
```
feature/* → develop → main → [promote.yml] → GitHub main
│ │
└─[promote.yml]┴──→ GitHub contrib ← external pull requests
```
`promote.yml` runs on the development forge only. Feature branches stay private, which is why this
is a workflow rather than a push-mirror — that would expose every branch. Neither push is forced.
`contrib` exists because `CONTRIBUTING.md` sends people there: a pull request against `main` would
put the two forges out of step, so contributors need a branch that tracks current development. For
`contrib` the unforced push is the guard rather than a limitation — it is refused exactly when
`contrib` holds external merges nobody has carried into `develop` yet. Carry them and the next
develop push fast-forwards. Never force it.
**External contributions** arrive on `contrib`. Merge the pull request there, fetch `contrib` into
a branch on the development forge, then open a pull request from it into `develop` and merge that.
The next develop push mirrors back and fast-forwards, because `develop` now contains everything
`contrib` had. Merge rather than rebase: rewriting a contributor's SHAs gains nothing and leaves
`contrib` holding commits `develop` does not have, which is exactly the state that makes the
mirror push refuse.
**Tags are not mirrored.** These packages publish to JSR, where a version can never be replaced or
removed, so promoting a tag has to stay a deliberate act rather than a side effect of promoting a
branch.
**CI runs on both forges, and `contrib` is one of the branches it watches.** It used to be guarded
to the development forge, because the packages built against a core that existed only on an
internal registry a public runner cannot reach; they resolve `@green-tea/core` from npmjs.org now,
so the guards are gone.
Adding `contrib` to the mirror without adding it to `ci.yml` would have been worse than not having
the branch. A pull request against a branch a workflow does not list triggers **nothing** — not a
reduced set of checks, none — so a contributor would see no signal and neither would whoever merged
it. The two changes belong together.
GitHub does not run workflows on pull requests from forks until a maintainer approves them, so a
contributor's first push may sit with no checks for a while. That is not a rejection, and it is
worth saying so rather than letting silence read as one.
## The plugin convention
@@ -48,6 +88,28 @@ a pull request. Until core is consumed from npm (Plan B3), CI runs on Gitea only
beside every one that is not supported. Nobody should have to open an issue to learn where a
plugin runs.
10. A breaking change goes under `### Breaking`, first in the package's CHANGELOG.
11. **Plugins publish to JSR alone.** `deno.json` exports `./src/index.ts` and there is no build:
JSR transpiles the TypeScript itself and hands consumers a typed ESM package with generated
declarations. Every `package.json` here stays `private`, so an accidental `npm publish` fails
rather than shipping entry points that describe a `dist/` nobody produces. `test/workspace.test.ts`
pins that.
The second registry was dropped because it was not buying a reader anything. `npx jsr add
@green-tea/<name>` installs under npm, yarn, pnpm and bun via `npm.jsr.io` — one line in
`.npmrc`, and the import specifier stays `@green-tea/<name>`; the `@jsr/` name appears only in
the lockfile. What it cost was a tsup config per package, a dual `exports` map, and a `dist/`
that could go stale between a merge and a release.
JSR is also the only one of the two that can say **where a plugin runs**. Its `runtimeCompat` is
per package, which matters for a framework whose claim is one app on four runtimes: `jwt` needs
`node:fs/promises` and cannot serve workerd, while `metrics` imports nothing and runs everywhere.
npm has nowhere to record that difference, so rule 9's `engines`/README pair was the only place
it lived. It is declared in the JSR package settings, not in `deno.json` — the config schema
accepts `name`, `version`, `license`, `exports` and `publish`, and nothing else.
What this gives up, stated plainly rather than argued away: nobody searching npmjs.org will find
these, and a site behind a registry proxy that mirrors npmjs.org and refuses to add a second one
cannot install them at all. Core still can — it publishes to both.
## Conventions
+89
View File
@@ -0,0 +1,89 @@
# Contributor Covenant Code of Conduct
## Our Pledge
We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, caste, color, religion, or sexual identity and orientation.
We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.
## Our Standards
Examples of behavior that contributes to a positive environment for our community include:
* Demonstrating empathy and kindness toward other people
* Being respectful of differing opinions, viewpoints, and experiences
* Giving and gracefully accepting constructive feedback
* Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience
* Focusing on what is best not just for us as individuals, but for the overall community
Examples of unacceptable behavior include:
* The use of sexualized language or imagery, and sexual attention or advances of any kind
* Trolling, insulting or derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or email address, without their explicit permission
* Other conduct which could reasonably be considered inappropriate in a professional setting
## Enforcement Responsibilities
Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.
Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate.
## Scope
This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at **compliance@expressive-tea.io**. All complaints will be reviewed and investigated promptly and fairly.
All community leaders are obligated to respect the privacy and security of the reporter of any incident.
If you would rather write to a named person than to an address, the project lead reads
diego.resendez@expressive-tea.io. Reports about a maintainer, including the project lead,
should go to compliance@expressive-tea.io, which is not maintained by the project team.
## Enforcement Guidelines
Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:
### 1. Correction
**Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.
**Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested.
### 2. Warning
**Community Impact**: A violation through a single incident or series of actions.
**Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban.
### 3. Temporary Ban
**Community Impact**: A serious violation of community standards, including sustained inappropriate behavior.
**Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban.
### 4. Permanent Ban
**Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals.
**Consequence**: A permanent ban from any sort of public interaction within the community.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.1, available at [https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1].
Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder][Mozilla CoC].
For answers to common questions about this code of conduct, see the FAQ at [https://www.contributor-covenant.org/faq][FAQ]. Translations are available at [https://www.contributor-covenant.org/translations][translations].
[homepage]: https://www.contributor-covenant.org
[v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html
[Mozilla CoC]: https://github.com/mozilla/diversity
[FAQ]: https://www.contributor-covenant.org/faq
[translations]: https://www.contributor-covenant.org/translations
+136
View File
@@ -0,0 +1,136 @@
# Contributing to green-tea plugins
Thanks for your interest. These are the official plugins for [green-tea](https://github.com/Expressive-Tea/green-tea), and they are open source — but nobody pushes directly. Everything lands through a reviewed pull request with a **DCO sign-off**.
## Where to send your changes
Development happens on a private Gitea instance. The GitHub repository is a downstream mirror: it receives `main`, and `develop` under the name `contrib`.
**Open your pull request against `contrib`. Not `main`.** `main` is a mirror of what has been promoted, and merging into it puts the two forges out of step and breaks the next promotion. A maintainer reviews on `contrib` and carries your commits upstream with your authorship and your sign-off intact. Because `contrib` follows `develop`, you are working against current code rather than the last promotion.
### Worked example
```bash
# fork Expressive-Tea/green-tea-plugins on GitHub, then
git clone git@github.com:<you>/green-tea-plugins.git
cd green-tea-plugins
git remote add upstream https://github.com/Expressive-Tea/green-tea-plugins.git
git fetch upstream
# branch from contrib, not from main
git checkout -b fix/sweep-interval upstream/contrib
# ... make the change, add a test ...
git commit -s -m "fix(rate-limit): clear the sweep timer on close"
git push origin fix/sweep-interval
```
`contrib` moves whenever development does. If your branch has been open a while, rebase onto the current `contrib` before pushing again.
## Developer Certificate of Origin (DCO)
We use the [Developer Certificate of Origin](./DCO) instead of a CLA. It is a per-commit affirmation that you have the right to submit your work under this project's license. No copyright assignment, no paperwork.
**Every commit must be signed off:**
```bash
git commit -s -m "feat(metrics): count upgrades separately"
```
That appends `Signed-off-by: Your Name <your.email@example.com>`, and the name and email must match your real `git config`. Commits without it are rejected by CI.
Forgot on a range you already wrote?
```bash
git rebase --signoff <base>
```
Or on the commit you just made: `git commit --amend -s`, then `git push --force-with-lease`.
## Local setup
Node 22 or newer, which is what every package's `engines` requires and what CI runs.
```bash
npm install
```
That points `core.hooksPath` at `.githooks/`, which installs a pre-commit gate: it formats and lint-fixes your staged sources, then refuses the commit if `lint` or `complexity:check` fails. It exists so CI tells you nothing you could not have heard locally. Confirm it took:
```bash
git config core.hooksPath # should print .githooks
```
If it prints nothing, run `git config core.hooksPath .githooks` yourself.
**There is no build step.** These packages publish to JSR, which transpiles the TypeScript and generates the declarations, so what you edit in `src/` is what ships. `deno publish --dry-run` is the closest thing to a build, and CI runs it.
## Before you open a pull request
Run what CI runs:
```bash
npm run lint
npm run format:check
npm run typecheck
npm run complexity:check
npm test # Node: every package's contract tests plus the workspace checks
npm run test:deno # packages whose engines declare deno
npm run test:bun # packages whose engines declare bun
npm run test:edge # packages whose engines declare workerd
deno publish --dry-run # the actual publish path, including the slow-types check
```
You are not expected to install every runtime to fix a typo. You are expected to run the one your change touches, and to say in the pull request which ones you ran.
## What a plugin has to do
The full list is in [`AGENTS.md`](./AGENTS.md), and `test/workspace.test.ts` enforces most of it so you will hear about a miss before a reviewer has to mention it. The parts that catch people out:
- **A plugin imports core as types only.** `import type { Plugin } from '@green-tea/core'` — never a value import. A type import leaves nothing behind when it compiles, which is what keeps a plugin from dragging a second copy of the framework into someone's application.
- **Runtimes are declared twice and the two must agree:** as `engines` keys, and as the Runtimes table in the package README, which lists all four with a reason beside every one that is not supported. Nobody should have to open an issue to find out where a plugin runs.
- **Errors carry the `Symbol.for('green-tea.http-error')` brand** rather than extending `HttpError`. A lint rule and the workspace test enforce it.
- **A breaking change goes under `### Breaking`**, first in that package's CHANGELOG.
- **Relative imports carry the `.ts` extension.** Deno and JSR require it.
## Commits
Follow [Conventional Commits](https://www.conventionalcommits.org/), scoped to the package where that helps: `fix(jwt):`, `feat(metrics):`, `docs:`. Focus the message on the *why*. Do not add AI co-authoring attribution.
## Working with AI assistance
Use one if it helps. There is no permission to ask for and nothing to declare.
What we do ask is that you read what it hands you before it becomes a pull request. Every line that lands here is reviewed by a person, by hand, and usually that person is one person. A diff its own author has not read moves that work onto them, and turns review into proofreading — which is the thing review is worst at.
So go through the diff the way you would go through a stranger's, because that is what it is. If you cannot say why a line is there, it is not ready to send.
**What assistants tend to get wrong in this repository in particular:**
- They turn `import type` into a value import, which is the one thing a plugin must never do to core.
- They add a build. There isn't one, and `package.json` deliberately carries no `main`, `exports` or `files`.
- They write for Node and assume the rest follows. `npm test` does not cover Deno, Bun or workerd.
- They update `engines` without the README table, or the table without `engines`.
**Where you are unsure, say so** — not as a disclosure, as a pointer. "I am not confident about the Deno path here" tells a reviewer where to spend their attention, and that is worth more than a pull request that merely looks clean.
None of this changes the sign-off. `Signed-off-by` says you have the right to submit the work under this project's license, and that stays true however the text was produced.
If your assistant reads repository instructions, [`AGENTS.md`](./AGENTS.md) has the conventions.
## Proposing a new plugin
Open an issue before writing it. The useful question is not whether the code is good — it is whether the thing belongs in the official set at all, and that is cheaper to answer in a paragraph than in a pull request you have already written.
A plugin that depends on a service, a vendor or a protocol we cannot test is usually better as your own package. Nothing stops you publishing `@you/green-tea-whatever` to JSR or npm, and that is a first-class outcome rather than a consolation.
## Reporting issues
Open an issue with a minimal reproduction: which plugin and version, the runtime and version, and the smallest app that shows the problem.
**Except for security.** If what you found is exploitable, do not open an issue — an issue is world-readable the moment you press the button. See [`SECURITY.md`](./SECURITY.md).
## Code of conduct
By taking part here you agree to the [Code of Conduct](./CODE_OF_CONDUCT.md), which is the Contributor Covenant 2.1. Reports go to compliance@expressive-tea.io.
+37
View File
@@ -0,0 +1,37 @@
Developer Certificate of Origin
Version 1.1
Copyright (C) 2004, 2006 The Linux Foundation and its contributors.
1 Letterman Drive
Suite D4700
San Francisco, CA, 94129
Everyone is permitted to copy and distribute verbatim copies of this
license document, but changing it is not allowed.
Developer's Certificate of Origin 1.1
By making a contribution to this project, I certify that:
(a) The contribution was created in whole or in part by me and I
have the right to submit it under the open source license
indicated in the file; or
(b) The contribution is based upon previous work that, to the best
of my knowledge, is covered under an appropriate open source
license and I have the right under that license to submit that
work with modifications, whether created in whole or in part
by me, under the same open source license (unless I am
permitted to submit under a different license), as indicated
in the file; or
(c) The contribution was provided directly to me by some other
person who certified (a), (b) or (c) and I have not modified
it.
(d) I understand and agree that this project and the contribution
are public and that a record of the contribution (including all
personal information I submit with it, including my sign-off) is
maintained indefinitely and may be redistributed consistent with
this project or the open source license(s) involved.
+38 -5
View File
@@ -1,12 +1,45 @@
# green-tea plugins
<p align="center">
<img src="https://raw.githubusercontent.com/Expressive-Tea/green-tea/main/assets/logo.png" width="96" alt="Green Tea" />
</p>
<h1 align="center">green&nbsp;tea plugins.</h1>
<p align="center"><b>Each one is a node in the graph, not a link in a chain.</b></p>
<p align="center">
A plugin declares what it provides; your route declares what it needs.<br />
Nothing runs for a route that never asked for it.
</p>
---
Official plugins for [green-tea](https://github.com/Expressive-Tea/green-tea). Each one is its own
package under `packages/`, published to npm and JSR, and each README says which runtimes it supports
and why not the others.
package under `packages/`, published to JSR, and each README says which runtimes it supports and why
not the others.
```bash
npx jsr add @green-tea/jwt # npm, and the same command for yarn and pnpm
deno add jsr:@green-tea/jwt
bunx jsr add @green-tea/jwt
```
That works under every package manager: `jsr add` writes one line to `.npmrc` and installs through
`npm.jsr.io`, so the import stays `@green-tea/jwt` and nothing in your code mentions JSR. A plain
`npm i @green-tea/jwt` will **not** work — these packages are not on npmjs.org.
| Package | What it does |
|---|---|
| [`@green-tea/jwt`](packages/jwt) | Loads signing keys at boot and publishes a sign/verify registry |
| [`@green-tea/rate-limit`](packages/rate-limit) | A per-request limiter with a branded `429` and a swept in-memory store |
| [`@green-tea/metrics`](packages/metrics) | Counts the lifecycle stream and renders the Prometheus text format |
Plugins import core as types only, so installing one never pulls a second copy of core — and never
warns about a version range, which under CalVer no range can express.
Plugins import core as types only, and a type import leaves nothing behind when it compiles — the
JavaScript JSR publishes never mentions core. So the core that runs is always your application's,
whatever version a plugin was written against, and nothing warns about a version range, which under
CalVer no range can express.
That is about *loading*, not about disk. A plugin names an exact core in its `deno.json`, and when
your version differs by more than the patch, npm places a second copy under the plugin rather than
deduplicating. Measured, on purpose: it is inert, because nothing ever imports it. What it can do
is make `tsc` resolve a plugin's `Plugin` type against that copy instead of yours, which fails
loudly at compile time rather than quietly at runtime.
+47
View File
@@ -0,0 +1,47 @@
# Security Policy
## Reporting a vulnerability
Email **security@expressive-tea.io**. Please do not open a public issue for something exploitable — an issue is world-readable from the moment you press the button, and that is the one thing a security report cannot be.
Include whatever you have: which plugin, the version, the runtime, and the smallest app that shows it. A route and a request is usually enough. If you have a working exploit, send it; if you only have a suspicion, send that instead of sitting on it.
You can also report privately through GitHub's [security advisory form](https://github.com/Expressive-Tea/green-tea-plugins/security/advisories/new), which reaches the same people.
## What happens next
Acknowledgement within **5 working days**. A verdict on whether we agree it is a vulnerability within **15**. If we agree, you get the fix timeline and a heads-up before the advisory goes public. If we don't, you get the reasoning rather than silence.
Those numbers are deliberately slower than the 24 to 48 hours you will see quoted elsewhere. That figure describes vendors and coordinators — organizations with someone on rotation. This project is one person. A number that only holds in a good week is worse than an honest one.
Which is why there is an escape hatch, and you should use it. **If you have no acknowledgement after 10 working days**, write directly to diego.resendez@expressive-tea.io. If that is also met with silence, consider yourself released from any embargo and disclose as you see fit. You will not have done anything wrong: a project that goes quiet on a security report has spent whatever claim it had on your patience.
## Disclosure window
We ask for **90 days** from your report before public disclosure, or until the fix ships, whichever comes first. If the fix is out in a week, so is the advisory.
If a vulnerability is being actively exploited, the window is however long it takes us to ship, and we will say so rather than hold you to 90 days while users are being attacked.
We publish a GitHub advisory for anything that affects a released version, and credit you by the name you ask for. Say so if you would rather not be named.
There is no bug bounty and no money, which we would rather state here than leave you to find out after the work.
## Supported versions
Nothing has been released yet. When the first versions ship, only the most recent of each package receives fixes, and this section gets the real table.
## Scope
Each package is its own scope, and a report should name which one.
**In scope** — anything in a package's `src/` that ships:
- `@green-tea/jwt` — key loading, signature verification, claim validation, and anything that could make a bad token verify or a good one fail open.
- `@green-tea/rate-limit` — anything that lets a caller exceed a configured limit, or that lets one caller's traffic count against another's.
- `@green-tea/metrics` — anything that puts request data into the metrics output that should not be there, since that endpoint is often less protected than the app around it.
**Out of scope:** the test suites, dev-only tooling, and anything that requires an attacker to already control your application code. A misconfiguration is not a vulnerability — a plugin that does what you told it to, where what you told it was unsafe, belongs in an issue or the documentation rather than here. If you are unsure which one you have, send it and let us decide.
**Vulnerabilities in green-tea itself** go to the [core repository](https://github.com/Expressive-Tea/green-tea/security/advisories/new) instead. Same address, same people, but the advisory needs to live where the fix does.
Advisories in a dependency — `jose`, for instance — are worth telling us about, and we handle them as ordinary dependency updates rather than as vulnerabilities in these packages. If the advisory is exploitable *through* the way a plugin uses that dependency, that is a real report and we want it.
+9
View File
@@ -0,0 +1,9 @@
{
"workspace": ["./packages/jwt", "./packages/metrics", "./packages/rate-limit"],
"nodeModulesDir": "manual",
"compilerOptions": {
"experimentalDecorators": true,
"emitDecoratorMetadata": true
},
"lint": { "exclude": ["node_modules"] }
}
+45
View File
@@ -0,0 +1,45 @@
import js from '@eslint/js';
import tseslint from 'typescript-eslint';
import stylistic from '@stylistic/eslint-plugin';
export default tseslint.config(
// Flat-config ignores are literal paths unless globbed, and the build output now lives one level
// down in every package — a bare 'dist' would only have covered a root directory that does not exist.
{ ignores: ['**/dist', '**/node_modules', '**/coverage'] },
js.configs.recommended,
...tseslint.configs.recommended,
{
plugins: { '@stylistic': stylistic },
rules: {
'@typescript-eslint/no-explicit-any': 'warn',
'@typescript-eslint/no-unused-vars': ['error', { argsIgnorePattern: '^_', varsIgnorePattern: '^_' }],
'@stylistic/padding-line-between-statements': [
'error',
{ blankLine: 'always', prev: 'multiline-block-like', next: '*' },
{ blankLine: 'always', prev: '*', next: 'multiline-block-like' },
],
},
},
{
// Rule 8 of the convention. A value import of core makes the published plugin need core at
// runtime, and no semver range accepts next month's CalVer beta — not even `*` — so every
// install would warn. Tests are exempt: they drive the real createApp on purpose.
files: ['packages/*/src/**/*.ts'],
rules: {
'no-restricted-imports': 'off',
'@typescript-eslint/no-restricted-imports': [
'error',
{
paths: [
{
name: '@green-tea/core',
message: 'Plugins import core as types only: `import type { … } from "@green-tea/core"`.',
allowTypeImports: true,
},
],
},
],
'no-console': 'error',
},
},
);
+2975
View File
File diff suppressed because it is too large. Load diff
+35
View File
@@ -0,0 +1,35 @@
{
"name": "green-tea-plugins",
"private": true,
"license": "MIT",
"type": "module",
"workspaces": [
"packages/*"
],
"engines": {
"node": ">=22"
},
"scripts": {
"lint": "eslint --no-error-on-unmatched-pattern packages test",
"format": "prettier --write \"packages/*/{src,test}/**/*.ts\" \"test/**/*.ts\"",
"format:check": "prettier --check \"packages/*/{src,test}/**/*.ts\" \"test/**/*.ts\"",
"complexity:check": "node scripts/check-complexity.mjs",
"typecheck": "tsc --noEmit -p tsconfig.json",
"test": "node --import tsx --test test/*.test.ts packages/*/test/*.test.ts",
"test:deno": "node scripts/run-runtime.mjs deno",
"test:bun": "node scripts/run-runtime.mjs bun",
"test:edge": "node scripts/run-runtime.mjs workerd",
"prepare": "git config core.hooksPath .githooks || true"
},
"devDependencies": {
"@eslint/js": "^9.39.5",
"@stylistic/eslint-plugin": "^5.10.0",
"@types/node": "^22.0.0",
"cognitive-complexity-ts": "^0.8.2",
"eslint": "^9.39.5",
"prettier": "^3.9.6",
"tsx": "^4.23.5",
"typescript": "^5.5.0",
"typescript-eslint": "^8.70.0"
}
}
+9
View File
@@ -0,0 +1,9 @@
# Changelog
## [Unreleased]
### Added
- `jwt({ keys, provides? })`: loads each JWK file while providers boot and publishes a `JwtRegistry`
under `provides` (default `jwt`). `Signer` signs with `iat` and a random `jti`, and verifies issuer
and audience. `JwtRegistry.publicJwk(name)` returns a key's public half for a JWKS endpoint.
+96
View File
@@ -0,0 +1,96 @@
<p align="center">
<img src="https://raw.githubusercontent.com/Expressive-Tea/green-tea/main/assets/logo.png" width="96" alt="Green Tea" />
</p>
<h1 align="center">@green-tea/jwt</h1>
<p align="center"><b>Sign and verify, as one node in the graph.</b></p>
<p align="center">
Keys load once, while providers boot — a bad key fails the deploy,<br />
not the first sign-in of the day.
</p>
---
Loads JWT signing keys at boot and publishes them into the graph as one registry. A handler asks for
it with `@needs('jwt')` and signs or verifies by key name.
## Runtimes
| Runtime | Supported | Why not |
|---|---|---|
| Node | ✅ | |
| Deno | ✅ | |
| Bun | ✅ | |
| workerd (edge) | ❌ | Reads the signing key from a file path, and workerd has no filesystem. |
## Install
```bash
npx jsr add @green-tea/jwt
```
Or `deno add jsr:@green-tea/jwt`, or `bunx jsr add @green-tea/jwt`. Under npm, yarn and pnpm
`jsr add` installs through `npm.jsr.io`, so the import below stays `@green-tea/jwt`.
There is no npmjs.org package — `npm i @green-tea/jwt` will not find one.
## Usage
```ts
import { createApp } from '@green-tea/core';
import { jwt } from '@green-tea/jwt';
const app = createApp({
modules: [AuthModule],
plugins: [
jwt({
keys: {
access: { path: '/etc/keys/access.json', settings: { issuer: 'api', maxAge: '15m' } },
refresh: { path: '/etc/keys/refresh.json', settings: { maxAge: '7d' } },
},
}),
],
});
```
Signing belongs in the handler — it is the response to that one request:
```ts
@Post('/signin')
async signIn(@needs('jwt') jwt: JwtRegistry) {
return { token: await jwt.get('access').sign({ sub: user.id }) };
}
```
Verifying does not. It is a precondition shared by every protected route, and its result is what
those routes are actually asking for, so it belongs in a `@Step`:
```ts
@Step({ provides: 'user', needs: ['jwt', 'req'] })
class Authenticate {
async run(ctx) {
const header = ctx.req.headers.authorization ?? '';
if (!header.startsWith('Bearer ')) throw new Unauthorized('missing bearer token');
// verify() throws on a bad signature, a wrong issuer or an expired token, which cuts the
// request before the handler — the handler only ever sees a token that was good.
return { user: await ctx.jwt.get('access').verify(header.slice(7)) };
}
}
@Get('/me')
me(@needs('user') user: Claims) {
return user;
}
```
The handler asks for `user`, never for `jwt`, and green-tea runs `Authenticate` only for the routes
that do — the route table says which ones, rather than a matcher on a middleware chain.
Keys are read once, while providers boot. A missing or malformed key therefore fails `app.listen()` —
or `await app.boot()` on Deno and Bun — instead of the first sign-in of the day. Call `app.boot()`
before `Deno.serve` or `Bun.serve`; without it, the failure surfaces on every request instead.
Two instances need two graph names: `jwt({ provides: 'serviceJwt', keys })` publishes under
`serviceJwt`, and the plugin takes that name too.
+13
View File
@@ -0,0 +1,13 @@
{
"name": "@green-tea/jwt",
"version": "26.9.0-beta.0",
"license": "MIT",
"exports": "./src/index.ts",
"imports": {
"@green-tea/core": "npm:@green-tea/core@26.9.0-beta.2",
"jose": "npm:jose@^6.2.12"
},
"publish": {
"include": ["src", "README.md", "CHANGELOG.md", "deno.json"]
}
}
+25
View File
@@ -0,0 +1,25 @@
{
"name": "@green-tea/jwt",
"version": "26.9.0-beta.0",
"private": true,
"description": "Loads JWT signing keys at boot and publishes a sign/verify registry into the green-tea graph.",
"license": "MIT",
"author": "green-tea contributors <projects@expressive-tea.io>",
"type": "module",
"repository": {
"type": "git",
"url": "git+https://github.com/Expressive-Tea/green-tea-plugins.git",
"directory": "packages/jwt"
},
"engines": {
"node": ">=22",
"deno": ">=2",
"bun": ">=1.3"
},
"dependencies": {
"jose": "^6.2.12"
},
"devDependencies": {
"@green-tea/core": "26.9.0-beta.2"
}
}
+87
View File
@@ -0,0 +1,87 @@
import type { Plugin } from '@green-tea/core';
import type { JWK } from 'jose';
import { importJWKKey, readPublicJWK } from './keys.ts';
import { Signer } from './signer.ts';
import type { JwtKeyConfig, JwtOptions } from './types.ts';
export { Signer } from './signer.ts';
export { importJWKKey, readPublicJWK } from './keys.ts';
export type { ImportedJWK, JwtKeyConfig, JwtOptions, JwtSettings, KeyMaterial } from './types.ts';
/** The value published into the graph: every configured signer, by name. */
export class JwtRegistry<Name extends string = string> {
constructor(
private readonly signers: Map<Name, Signer>,
private readonly paths: Map<Name, string>,
) {}
get(name: Name): Signer {
const signer = this.signers.get(name);
// Reachable only through a typo in a key name — the configured set is fixed at boot.
if (!signer) throw new Error(`Unknown JWT signer "${name}". Configured: ${[...this.signers.keys()].join(', ')}`);
return signer;
}
names(): Name[] {
return [...this.signers.keys()];
}
/** The public half of a key, for serving at a JWKS endpoint. */
async publicJwk(name: Name): Promise<JWK> {
const path = this.paths.get(name);
if (!path) throw new Error(`Unknown JWT signer "${name}"`);
return await readPublicJWK(path);
}
}
async function loadRegistry<Name extends string>(entries: Array<[Name, JwtKeyConfig]>): Promise<JwtRegistry<Name>> {
const signers = new Map<Name, Signer>();
const paths = new Map<Name, string>();
for (const [name, config] of entries) {
signers.set(name, new Signer(await importJWKKey(config.path), config.settings));
paths.set(name, config.path);
}
return new JwtRegistry(signers, paths);
}
/**
* Loads signing keys while providers boot and publishes them as one graph node.
*
* Keys are read once, in the provider's `run`, so a missing or malformed key fails `app.listen()` or
* `app.boot()` instead of turning the first sign-in of the day into a 500. Nothing loads lazily and
* nothing is cached in the module registry. A key read once holds nothing open, so there is no
* `onShutdown` (convention rule 7).
*
* @example
* const app = createApp({
* modules: [AuthModule],
* plugins: [jwt({ keys: { access: { path: '/etc/keys/access.json', settings: { maxAge: '15m' } } } })],
* });
*
* @example <caption>In a handler.</caption>
* ⁣@Post('/signin')
* async signIn(@needs('jwt') jwt: JwtRegistry) {
* return { token: await jwt.get('access').sign({ sub: user.id }) };
* }
*/
export function jwt<Name extends string>(options: JwtOptions<Name>): Plugin {
const provides = options.provides ?? 'jwt';
const entries = Object.entries(options.keys) as Array<[Name, JwtKeyConfig]>;
return {
// Rule 2: plugin name, node name and provided token are one string.
name: provides,
mount({ scope }) {
scope.add({
kind: 'provider',
name: provides,
needs: [],
provides: [provides],
run: async () => ({ [provides]: await loadRegistry(entries) }),
});
},
};
}
+59
View File
@@ -0,0 +1,59 @@
import { readFile } from 'node:fs/promises';
import { importJWK, type JWK } from 'jose';
import type { ImportedJWK, KeyMaterial } from './types.ts';
/**
* Reads a JWK from disk.
*
* `readFile` + `JSON.parse` rather than `await import(path)`: a dynamic import of a JSON file is cached
* by the module registry for the life of the process, resolves differently under CommonJS and ESM, and
* puts private key material into a module cache anything in the process can read.
*/
async function readJWK(filePath: string): Promise<JWK> {
return JSON.parse(await readFile(filePath, 'utf8')) as JWK;
}
const PRIVATE_FIELDS = new Set(['d', 'p', 'q', 'dp', 'dq', 'qi', 'oth', 'key_ops']);
/** Whether the key is symmetric, in which case one secret both signs and verifies. */
function isSymmetric(jwk: JWK): boolean {
return jwk.kty === 'oct' || 'k' in jwk;
}
/** The same JWK with every private field removed. */
function publicHalf(jwk: JWK): JWK {
return Object.fromEntries(Object.entries(jwk).filter(([field]) => !PRIVATE_FIELDS.has(field))) as JWK;
}
/**
* Reads and imports a JWK file, keeping the algorithm and key id it declares.
*
* Imports the key **twice** for an asymmetric pair: once as given, to sign with, and once with the
* private fields stripped, to verify with. That is not redundancy — jose 6 rejects a private
* `CryptoKey` in `jwtVerify` with `CryptoKey instances must be of type "public"`, where jose 5
* accepted one and derived the public half itself. A signer that kept a single key therefore signed
* fine and threw on every verification, for every asymmetric algorithm, which is all of ES*, RS*,
* PS* and EdDSA.
*
* A symmetric key has no public half to derive, so it verifies with the same secret it signs with.
*/
export async function importJWKKey(filePath: string): Promise<ImportedJWK> {
const jwk = await readJWK(filePath);
const key: KeyMaterial = await importJWK(jwk, jwk.alg);
const verifyKey: KeyMaterial = isSymmetric(jwk) ? key : await importJWK(publicHalf(jwk), jwk.alg);
return { key, verifyKey, alg: jwk.alg, kid: jwk.kid };
}
/** Strips every private field, so the result is safe to serve at a JWKS endpoint. */
export async function readPublicJWK(filePath: string): Promise<JWK> {
const jwk = await readJWK(filePath);
if (isSymmetric(jwk)) {
throw new Error('A JWKS endpoint requires an asymmetric key; a symmetric JWK has no public half to publish.');
}
return { ...publicHalf(jwk), use: 'sig', key_ops: ['verify'] };
}
+66
View File
@@ -0,0 +1,66 @@
import { SignJWT, errors, jwtVerify, type JWTPayload } from 'jose';
import type { ImportedJWK, JwtSettings, KeyMaterial } from './types.ts';
/** Signs and verifies with one key. */
export class Signer {
private readonly key: KeyMaterial;
/** Separate from `key`: jose 6 will not verify with a private one. See `importJWKKey`. */
private readonly verifyKey: KeyMaterial;
private readonly algorithm: string;
private readonly kid?: string;
constructor(
jwk: ImportedJWK,
private readonly settings: JwtSettings = {},
) {
this.key = jwk.key;
this.verifyKey = jwk.verifyKey;
this.algorithm = jwk.alg ?? '';
this.kid = jwk.kid;
}
/**
* Issues a token, stamping `iat` and a random `jti`.
*
* The `jti` is what makes a token revocable — without it the only way to retire a token early is to
* rotate the key and invalidate everyone's. `crypto.randomUUID` is the Web Crypto global, present on
* every runtime this package declares, so nothing is imported from `node:crypto`.
*/
async sign<T = JWTPayload>(payload: T & JWTPayload, overrides: JwtSettings = {}): Promise<string> {
const { audience, issuer, maxAge } = { ...this.settings, ...overrides };
const jwt = new SignJWT(payload).setProtectedHeader({ alg: this.algorithm, kid: this.kid });
if (audience) jwt.setAudience(audience);
if (issuer) jwt.setIssuer(issuer);
jwt.setIssuedAt();
jwt.setJti(crypto.randomUUID());
if (maxAge) jwt.setExpirationTime(maxAge);
return await jwt.sign(this.key);
}
/**
* Verifies signature, issuer and audience.
*
* @param ignoreExpiration returns the payload of an expired token instead of throwing. Only for refresh
* flows that need the claims of a token they already know has expired — never for authenticating a
* request.
*/
async verify<T = JWTPayload>(token: string, ignoreExpiration = false): Promise<T> {
const { issuer, audience } = this.settings;
try {
const { payload } = await jwtVerify(token, this.verifyKey, { issuer, audience });
return payload as T;
} catch (error) {
if (ignoreExpiration && error instanceof errors.JWTExpired) return error.payload as T;
throw error;
}
}
/** Signs with no managed claims — no audience, issuer, expiry or jti. */
async signUnmanaged<T = JWTPayload>(payload: T & JWTPayload): Promise<string> {
return await new SignJWT(payload).setProtectedHeader({ alg: this.algorithm, kid: this.kid }).sign(this.key);
}
}
+41
View File
@@ -0,0 +1,41 @@
import type { CryptoKey, JWK } from 'jose';
/** What jose signs and verifies with: an imported asymmetric key, or the bytes of a symmetric one. */
export type KeyMaterial = CryptoKey | Uint8Array;
/** A JWK imported from disk, with the algorithm and key id it declares. */
export interface ImportedJWK {
/** Signs. The private half of an asymmetric pair, or the secret of a symmetric key. */
key: KeyMaterial;
/**
* Verifies. The public half for an asymmetric key, and the same secret again for a symmetric one.
*
* Kept separate because jose 6 refuses a private `CryptoKey` in `jwtVerify` — see `importJWKKey`.
*/
verifyKey: KeyMaterial;
alg?: string;
kid?: string;
}
/** Claim defaults applied to every token a signer issues. */
export interface JwtSettings {
audience?: string;
issuer?: string;
/** Anything jose's `setExpirationTime` accepts — `'15m'`, `'1h'`, a timestamp. */
maxAge?: string;
}
export interface JwtKeyConfig {
/** Path to a JWK file. Resolved as given, so pass an absolute path if unsure. */
path: string;
settings?: JwtSettings;
}
export interface JwtOptions<Name extends string = string> {
/** One entry per signing key. The names become the keys of the published registry. */
keys: Record<Name, JwtKeyConfig>;
/** Graph name the registry is published under, and the plugin's name. Defaults to `jwt`. */
provides?: string;
}
export type { JWK };
+128
View File
@@ -0,0 +1,128 @@
import { strict as assert } from 'node:assert';
import { mkdtemp, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { test } from 'node:test';
import { createApp } from '@green-tea/core';
import { exportJWK, generateKeyPair, generateSecret } from 'jose';
import { probeModule } from '../../../test/helpers.ts';
import { importJWKKey, jwt, Signer, type JwtRegistry } from '../src/index.ts';
// One key file for the whole file, written once. A promise rather than a `before` hook: only flat
// `test()` is relied on, because this file runs unchanged under Node, Deno and Bun.
const keyFile = (async () => {
const { privateKey } = await generateKeyPair('ES256', { extractable: true });
const path = join(await mkdtemp(join(tmpdir(), 'green-tea-jwt-')), 'access.json');
await writeFile(path, JSON.stringify({ ...(await exportJWK(privateKey)), alg: 'ES256', kid: 'test' }));
return path;
})();
// Generic in the body: `Response.json()` is typed `Promise<unknown>`, so a caller that reaches into
// the payload has to say what it expects. The default keeps the deepEqual callers untouched.
const get = async <T = unknown>(
app: { fetch(request: Request): Promise<Response> },
path: string,
): Promise<{ status: number; body: T }> => {
const response = await app.fetch(new Request(`http://plugin.test${path}`));
return { status: response.status, body: (await response.json()) as T };
};
test('a handler signs and verifies through the published registry', async () => {
const app = createApp({
modules: [
probeModule('jwt', async (registry: JwtRegistry) => {
const signer = registry.get('access');
return (await signer.verify<{ sub: string }>(await signer.sign({ sub: '42' }))).sub;
}),
],
plugins: [jwt({ keys: { access: { path: await keyFile } } })],
});
assert.deepEqual(await get(app, '/jwt/probe'), { status: 200, body: { value: '42' } });
});
test('publicJwk serves the public half only', async () => {
const app = createApp({
modules: [probeModule('jwt', (registry: JwtRegistry) => registry.publicJwk('access'))],
plugins: [jwt({ keys: { access: { path: await keyFile } } })],
});
const { body } = await get<{ value: Record<string, unknown> }>(app, '/jwt/probe');
assert.equal('d' in body.value, false);
assert.equal(body.value.use, 'sig');
assert.deepEqual(body.value.key_ops, ['verify']);
});
// Convention rule 4: the promise the plugin makes is that a bad key is a startup failure.
test('a key file that does not exist fails app.boot(), naming the provider', async () => {
const app = createApp({
modules: [probeModule('jwt', () => null)],
plugins: [jwt({ keys: { access: { path: join(tmpdir(), 'green-tea-jwt-missing', 'nope.json') } } })],
});
await assert.rejects(app.boot(), /provider 'jwt' failed/);
});
test('a key file that is not a JWK fails app.boot() too', async () => {
const path = join(await mkdtemp(join(tmpdir(), 'green-tea-jwt-')), 'broken.json');
await writeFile(path, 'not json');
const app = createApp({ modules: [probeModule('jwt', () => null)], plugins: [jwt({ keys: { access: { path } } })] });
await assert.rejects(app.boot(), /provider 'jwt' failed/);
});
// Convention rule 2, checked where it bites: two instances in one app.
test('two instances with different provides both answer, without colliding', async () => {
const path = await keyFile;
const app = createApp({
modules: [
probeModule('userJwt', (registry: JwtRegistry) => registry.names()),
probeModule('serviceJwt', (registry: JwtRegistry) => registry.names()),
],
plugins: [
jwt({ provides: 'userJwt', keys: { user: { path } } }),
jwt({ provides: 'serviceJwt', keys: { service: { path } } }),
],
});
assert.deepEqual(await get(app, '/userJwt/probe'), { status: 200, body: { value: ['user'] } });
assert.deepEqual(await get(app, '/serviceJwt/probe'), { status: 200, body: { value: ['service'] } });
});
test('the plugin is named after what it provides', () => {
assert.equal(jwt({ keys: {} }).name, 'jwt');
assert.equal(jwt({ provides: 'serviceJwt', keys: {} }).name, 'serviceJwt');
});
// One algorithm is not coverage. A signer that verified with the key it signed with passed every
// symmetric test and threw `CryptoKey instances must be of type "public"` on every asymmetric one —
// which is all of ES*, RS*, PS* and EdDSA, and in practice every key anyone signs a session with.
// jose 5 accepted a private key here and derived the public half itself; jose 6 does not, so the
// defect only appears on the upgrade. Each family is listed so the next one to break says which.
for (const [alg, kind] of [
['EdDSA', 'asymmetric'],
['ES256', 'asymmetric'],
['RS256', 'asymmetric'],
['HS256', 'symmetric'],
] as const) {
test(`round-trips a token signed with ${alg} (${kind})`, async () => {
const path = join(await mkdtemp(join(tmpdir(), 'green-tea-jwt-alg-')), `${alg}.json`);
if (kind === 'symmetric') {
await writeFile(
path,
JSON.stringify({ ...(await exportJWK(await generateSecret(alg, { extractable: true }))), alg }),
);
} else {
const { privateKey } = await generateKeyPair(alg, { extractable: true });
await writeFile(path, JSON.stringify({ ...(await exportJWK(privateKey)), alg, kid: alg }));
}
const signer = new Signer(await importJWKKey(path));
assert.equal((await signer.verify<{ sub: string }>(await signer.sign({ sub: 'u1' }))).sub, 'u1');
});
}
+10
View File
@@ -0,0 +1,10 @@
# Changelog
## [Unreleased]
### Added
- `metrics({ provides? })`: subscribes to the lifecycle stream and publishes a `Metrics` with
`render()`. Counts `request:end` as requests and `request:failed` separately, labelled on the
bounded `route` rather than on the caller-controlled `name`. `prometheus` is a `TransformerFn` for
serving `render()` from a route the application owns. Closes green-tea#68.
+73
View File
@@ -0,0 +1,73 @@
<p align="center">
<img src="https://raw.githubusercontent.com/Expressive-Tea/green-tea/main/assets/logo.png" width="96" alt="Green Tea" />
</p>
<h1 align="center">@green-tea/metrics</h1>
<p align="center"><b>Count the lifecycle. Render Prometheus.</b></p>
<p align="center">
Reads the event stream green-tea already emits, so nothing in your<br />
handlers has to know it is being measured.
</p>
---
Subscribes to green-tea's lifecycle stream and counts what happened. You expose it on a route you
own, with the transformer this package ships.
## Runtimes
| Runtime | Supported | Why not |
|---|---|---|
| Node | ✅ | |
| Deno | ✅ | |
| Bun | ✅ | |
| workerd (edge) | ❌ | Counters live in one isolate, and an edge deployment has many, so a scrape reports whichever isolate answered it. Supported once the counters can be shared. |
## Install
```bash
npx jsr add @green-tea/metrics
```
Or `deno add jsr:@green-tea/metrics`, or `bunx jsr add @green-tea/metrics`. Under npm, yarn and pnpm
`jsr add` installs through `npm.jsr.io`, so the import below stays `@green-tea/metrics`.
There is no npmjs.org package — `npm i @green-tea/metrics` will not find one.
## Usage
```ts
import { createApp } from '@green-tea/core';
import { metrics } from '@green-tea/metrics';
const app = createApp({ modules: [ApiModule], plugins: [metrics()] });
```
```ts
import { prometheus, type Metrics } from '@green-tea/metrics';
@Get('/metrics')
@Transformer(prometheus)
scrape(@needs('metrics') metrics: Metrics) {
return metrics.render();
}
```
The route is yours, so its path, its auth and whether it is exposed at all stay your decisions.
## What it counts, and what it refuses to
One failed request emits **three** lifecycle events, and a collector that counts them as three
outcomes reports one request as several. The division this package follows:
| Series | From | Meaning |
|---|---|---|
| `green_tea_requests_total` | `request:end` | Every dispatched request. Terminal and universal — this is *the* request counter |
| `green_tea_request_errors_total` | `request:failed` | Handler code threw. **Additional** to the request above, never a second request |
| `green_tea_request_duration_seconds` | `request:end` | Sum and count, so an average is available without buckets |
Labels are `route`, `method` and `status` — never the event's `name`. `route` is the matched
*pattern* and is bounded by your route table (`<unmatched>` when nothing matched); `name` carries the
path that arrived, which is bounded by nothing, so a scanner walking `/aaa`, `/aab`, `/aac` would
mint a label per URL. That is a memory leak with a metrics backend attached.
+12
View File
@@ -0,0 +1,12 @@
{
"name": "@green-tea/metrics",
"version": "26.9.0-beta.0",
"license": "MIT",
"exports": "./src/index.ts",
"imports": {
"@green-tea/core": "npm:@green-tea/core@26.9.0-beta.2"
},
"publish": {
"include": ["src", "README.md", "CHANGELOG.md", "deno.json"]
}
}
+22
View File
@@ -0,0 +1,22 @@
{
"name": "@green-tea/metrics",
"version": "26.9.0-beta.0",
"private": true,
"description": "Counts green-tea's lifecycle events and renders them in the Prometheus text format.",
"license": "MIT",
"author": "green-tea contributors <projects@expressive-tea.io>",
"type": "module",
"repository": {
"type": "git",
"url": "git+https://github.com/Expressive-Tea/green-tea-plugins.git",
"directory": "packages/metrics"
},
"engines": {
"node": ">=22",
"deno": ">=2",
"bun": ">=1.3"
},
"devDependencies": {
"@green-tea/core": "26.9.0-beta.2"
}
}
Binary file not shown.
+49
View File
@@ -0,0 +1,49 @@
import type { Plugin } from '@green-tea/core';
import { Metrics } from './collector.ts';
import type { MetricsOptions } from './types.ts';
export { Metrics } from './collector.ts';
export { prometheus } from './prometheus.ts';
export type { MetricsOptions, MetricsSnapshot, Series } from './types.ts';
/**
* Subscribes to the lifecycle stream and publishes the counters into the graph.
*
* There is no `onShutdown` (convention rule 7): a bus subscription is an entry in a set, and holds
* no timer, socket or handle that could keep a process alive. Nothing to release.
*
* The collector is built at mount time rather than in the provider's `run`, because the subscription
* has to exist before the first request — a provider runs on boot, which is late enough to miss it.
*
* @example
* const app = createApp({ modules: [ApiModule], plugins: [metrics()] });
*
* @example <caption>Exposed on a route the application owns.</caption>
* ⁣@Get('/metrics')
* ⁣@Transformer(prometheus)
* scrape(@needs('metrics') collector: Metrics) {
* return collector.render();
* }
*/
export function metrics(options: MetricsOptions = {}): Plugin {
const provides = options.provides ?? 'metrics';
const collector = new Metrics();
return {
// Rule 2: plugin name, node name and provided token are one string.
name: provides,
mount({ bus, scope }) {
bus.on('request:end', (payload) => collector.observeEnd(payload));
bus.on('request:failed', (payload) => collector.observeFailure(payload));
scope.add({
kind: 'provider',
name: provides,
needs: [],
provides: [provides],
run: () => ({ [provides]: collector }),
});
},
};
}
+22
View File
@@ -0,0 +1,22 @@
import type { TransformerFn } from '@green-tea/core';
/**
* Serves a rendered scrape as the Prometheus text exposition format.
*
* A `TransformerFn` rather than a route: the path, the auth and whether the endpoint exists at all
* are the application's decisions, and a plugin that mounted `/metrics` itself would be taking them.
* The version is part of the content type — Prometheus reads it, and omitting it makes a scrape fall
* back to a guess.
*
* @example
* ⁣@Get('/metrics')
* ⁣@Transformer(prometheus)
* scrape(@needs('metrics') collector: Metrics) {
* return collector.render();
* }
*/
export const prometheus: TransformerFn = (value) => ({
status: 200,
headers: { 'content-type': 'text/plain; version=0.0.4; charset=utf-8' },
body: String(value),
});
+19
View File
@@ -0,0 +1,19 @@
/** One labelled series and its accumulated value. */
export interface Series {
route: string;
method: string;
status?: number;
value: number;
}
/** What the collector holds, for a consumer that wants numbers rather than text. */
export interface MetricsSnapshot {
requests: Series[];
errors: Series[];
duration: Array<{ route: string; method: string; sum: number; count: number }>;
}
export interface MetricsOptions {
/** Graph name the collector is published under, and the plugin's name. Defaults to `metrics`. */
provides?: string;
}
+130
View File
@@ -0,0 +1,130 @@
import { strict as assert } from 'node:assert';
import { test } from 'node:test';
import { createApp, Get, Module, Route, Transformer, needs } from '@green-tea/core';
import { Metrics } from '../src/collector.ts';
import { metrics, prometheus } from '../src/index.ts';
const end = (route: string, method: string, status: number, durationMs = 5) =>
({ name: route, route, method, status, durationMs }) as never;
test('counts one request per request:end, keyed by route, method and status', () => {
const collector = new Metrics();
collector.observeEnd(end('/users/:id', 'GET', 200));
collector.observeEnd(end('/users/:id', 'GET', 200));
collector.observeEnd(end('/users/:id', 'GET', 404));
const { requests } = collector.snapshot();
assert.equal(requests.find((s) => s.status === 200)?.value, 2);
assert.equal(requests.find((s) => s.status === 404)?.value, 1);
});
// The defect issue #64 was filed for: a failed request emits request:start, request:failed and
// request:end. Counting the failure as a request reports one request as two.
test('a failure counts once as a request and once as an error, not twice as a request', () => {
const collector = new Metrics();
collector.observeFailure({ name: '/boom', route: '/boom', method: 'GET' } as never);
collector.observeEnd(end('/boom', 'GET', 500));
const { requests, errors } = collector.snapshot();
assert.equal(
requests.reduce((total, s) => total + s.value, 0),
1,
);
assert.equal(
errors.reduce((total, s) => total + s.value, 0),
1,
);
});
// Issue #65: `name` is the path that arrived and is bounded by nothing. `route` is the matched
// pattern, and is '<unmatched>' when nothing matched.
test('labels on the bounded route, so a scanner cannot mint a series per URL', () => {
const collector = new Metrics();
for (const probe of ['/aaa', '/aab', '/aac']) {
collector.observeEnd({
name: `GET ${probe}`,
route: '<unmatched>',
method: 'GET',
status: 404,
durationMs: 1,
} as never);
}
const { requests } = collector.snapshot();
assert.equal(requests.length, 1);
assert.equal(requests[0].route, '<unmatched>');
assert.equal(requests[0].value, 3);
});
test('accumulates duration as a sum and a count, in seconds', () => {
const collector = new Metrics();
collector.observeEnd(end('/x', 'GET', 200, 1500));
collector.observeEnd(end('/x', 'GET', 200, 500));
const [duration] = collector.snapshot().duration;
assert.equal(duration.count, 2);
assert.equal(duration.sum, 2);
});
test('an event with no route is attributed rather than dropped or left blank', () => {
const collector = new Metrics();
collector.observeEnd({ name: 'GET /x', method: 'GET', status: 200, durationMs: 1 } as never);
assert.equal(collector.snapshot().requests[0].route, '<unknown>');
});
test('the transformer serves the text format with the content type Prometheus expects', () => {
const rendered = prometheus('green_tea_requests_total{route="/x",method="GET",status="200"} 1\n');
assert.equal(rendered.status, 200);
assert.match(rendered.headers!['content-type'], /text\/plain/);
assert.match(rendered.body, /green_tea_requests_total/);
});
test('an application serves its own /metrics route from the published collector', async () => {
@Route('/')
class Ops {
@Get('/metrics')
@Transformer(prometheus)
scrape(@needs('metrics') collector: Metrics) {
return collector.render();
}
@Get('/hello')
hello() {
return { ok: true };
}
}
@Module({ mountpoint: '/', controllers: [Ops] })
class OpsModule {}
const app = createApp({ modules: [OpsModule], plugins: [metrics()] });
try {
await app.fetch(new Request('http://plugin.test/hello'));
const scrape = await app.fetch(new Request('http://plugin.test/metrics'));
const body = await scrape.text();
assert.equal(scrape.status, 200);
assert.match(body, /green_tea_requests_total\{route="\/hello",method="GET",status="200"\} 1/);
} finally {
await app.close();
}
});
test('the plugin is named after what it provides', () => {
assert.equal(metrics().name, 'metrics');
assert.equal(metrics({ provides: 'opsMetrics' }).name, 'opsMetrics');
});
+10
View File
@@ -0,0 +1,10 @@
# Changelog
## [Unreleased]
### Added
- `rateLimit({ rules, store?, keyOf?, provides? })`: publishes a `RateLimiter` under `provides`
(default `rateLimit`). Exceeding a rule throws `TooManyRequests`, a branded 429 carrying
`Retry-After`. The default `MemoryStore` sweeps expired windows on an interval and is released by
the plugin's `onShutdown`.
+108
View File
@@ -0,0 +1,108 @@
<p align="center">
<img src="https://raw.githubusercontent.com/Expressive-Tea/green-tea/main/assets/logo.png" width="96" alt="Green Tea" />
</p>
<h1 align="center">@green-tea/rate-limit</h1>
<p align="center"><b>A limit your handler's signature admits to.</b></p>
<p align="center">
The route asks for the limiter by name, so it runs where it is wanted<br />
and nowhere else — and you can see which routes those are.
</p>
---
Publishes a per-request rate limiter into the graph. A handler opts in by asking for it and naming a
rule, so the limit is visible in the handler's signature rather than hidden in a middleware chain —
and green-tea runs the step only for the routes that depend on it.
## Runtimes
| Runtime | Supported | Why not |
|---|---|---|
| Node | ✅ | |
| Deno | ✅ | |
| Bun | ✅ | |
| workerd (edge) | ❌ | The default store counts per isolate, and an edge deployment has many, so a shared limit is not one. Supported once a store that shares state ships. |
## Install
```bash
npx jsr add @green-tea/rate-limit
```
Or `deno add jsr:@green-tea/rate-limit`, or `bunx jsr add @green-tea/rate-limit`. Under npm, yarn and pnpm
`jsr add` installs through `npm.jsr.io`, so the import below stays `@green-tea/rate-limit`.
There is no npmjs.org package — `npm i @green-tea/rate-limit` will not find one.
## Usage
```ts
import { createApp } from '@green-tea/core';
import { rateLimit } from '@green-tea/rate-limit';
const app = createApp({
modules: [AuthModule],
plugins: [
rateLimit({
rules: {
signin: { windowMs: 15 * 60 * 1000, max: 5, message: 'Too many attempts, try again later.' },
},
}),
],
});
```
Then spend the limit in a `@Step`, so the handler stays the thing it is about and the limit is a
dependency rather than a first line of code someone can forget to write:
```ts
@Step({ provides: 'signinAllowed', needs: ['rateLimit', 'req'] })
class ThrottleSignin {
async run(ctx) {
await ctx.rateLimit('signin'); // throws 429, so the handler never runs
return { signinAllowed: true };
}
}
@Post('/signin')
async signIn(@needs('signinAllowed') _allowed: true, @body() credentials: Credentials) {
// ...
}
```
**The step has to provide something the handler asks for.** green-tea slices the graph per route and
runs only what the handler transitively needs, so a step providing a token nobody names is not in the
closure and never runs — the limit would silently not apply. That is why there is a
`signinAllowed` at all.
Better still, fold it into a step that already provides something real. A protected route usually
has one:
```ts
@Step({ provides: 'user', needs: ['jwt', 'rateLimit', 'req'] })
class Authenticate {
async run(ctx) {
await ctx.rateLimit('api'); // spend it before the expensive part
return { user: await verifyBearer(ctx) };
}
}
```
Calling `@needs('rateLimit')` straight from the handler and awaiting it there works too, and for a
single route it is less machinery. It just puts the limit somewhere a reader of the signature cannot
see it.
Exceeding a rule throws a `429` carrying `Retry-After`. The error is recognised by green-tea through
a registered symbol rather than by extending its `HttpError`, so this package never imports core at
runtime.
## The store
The default `MemoryStore` keeps fixed windows in this process and sweeps expired ones on an interval.
**One process, one set of counters:** two replicas each enforce the limit separately, so the real
ceiling is `max × replicas`. Implement `RateLimitStore` against Redis when you scale past one.
The sweep timer keeps the process alive on purpose, and the plugin's `onShutdown` clears it. A custom
store owns its own lifecycle; `close()` is called on it if it has one.
+12
View File
@@ -0,0 +1,12 @@
{
"name": "@green-tea/rate-limit",
"version": "26.9.0-beta.0",
"license": "MIT",
"exports": "./src/index.ts",
"imports": {
"@green-tea/core": "npm:@green-tea/core@26.9.0-beta.2"
},
"publish": {
"include": ["src", "README.md", "CHANGELOG.md", "deno.json"]
}
}
+22
View File
@@ -0,0 +1,22 @@
{
"name": "@green-tea/rate-limit",
"version": "26.9.0-beta.0",
"private": true,
"description": "A per-request rate limiter published into the green-tea graph, with a branded 429 and a swept in-memory store.",
"license": "MIT",
"author": "green-tea contributors <projects@expressive-tea.io>",
"type": "module",
"repository": {
"type": "git",
"url": "git+https://github.com/Expressive-Tea/green-tea-plugins.git",
"directory": "packages/rate-limit"
},
"engines": {
"node": ">=22",
"deno": ">=2",
"bun": ">=1.3"
},
"devDependencies": {
"@green-tea/core": "26.9.0-beta.2"
}
}
+33
View File
@@ -0,0 +1,33 @@
/**
* Core's error brand, as the public protocol rather than as an import.
*
* `Symbol.for` is registry-wide, so this resolves to the same symbol core registered, in this copy
* of the process and in any other. That is what lets a plugin throw something core renders without
* depending on core at runtime — and it survives two copies of core in one tree, which `instanceof`
* does not, since each copy has its own class identity.
*
* The string is the contract (design spec 1.2). `unique symbol` is what TypeScript needs for a
* computed class field, and a `const` annotated with it satisfies that.
*/
const HTTP_ERROR: unique symbol = Symbol.for('green-tea.http-error');
/**
* Thrown when a caller exceeds a rule. Carries `Retry-After` so a client can back off rather than
* retry immediately and spend the next window too.
*
* Extends `Error`, not core's `HttpError`: core reads `status`, `message`, `body` and `headers` off
* whatever carries the brand, and never uses `instanceof`.
*/
export class TooManyRequests extends Error {
readonly [HTTP_ERROR] = true;
readonly status = 429;
readonly body: { message: string; status: number };
readonly headers: Record<string, string>;
constructor(message: string, retryAfterSeconds: number) {
super(message);
this.name = 'TooManyRequests';
this.body = { message, status: 429 };
this.headers = { 'retry-after': String(retryAfterSeconds) };
}
}
+96
View File
@@ -0,0 +1,96 @@
import type { Plugin } from '@green-tea/core';
import { TooManyRequests } from './errors.ts';
import { MemoryStore } from './memory-store.ts';
import type { RateLimitContext, RateLimiter, RateLimitOptions, RateLimitRule } from './types.ts';
export { MemoryStore } from './memory-store.ts';
export { TooManyRequests } from './errors.ts';
export type {
RateLimitContext,
RateLimiter,
RateLimitHit,
RateLimitOptions,
RateLimitRule,
RateLimitStore,
} from './types.ts';
function defaultKeyOf(ctx: RateLimitContext): string {
return ctx.ip !== undefined && ctx.ip !== '' ? ctx.ip : 'unknown';
}
/**
* The sweep period for a store this plugin builds: the shortest window any rule configures.
*
* Sweeping less often than the shortest window would let a generation of expired counters sit in the
* map for longer than they can possibly be useful, which is the growth the sweep exists to bound.
*/
function sweepPeriod(rules: Record<string, RateLimitRule>): number | undefined {
const windows = Object.values(rules).map((rule) => rule.windowMs);
return windows.length ? Math.min(...windows) : undefined;
}
/**
* Publishes a per-request rate limiter into the graph.
*
* Rules live in one place; a handler opts in by asking for the limiter and naming a rule. Nothing is
* enforced on routes that do not ask — green-tea runs a step only for the routes that depend on it —
* so the limit is visible in the handler's signature rather than hidden in a middleware chain.
*
* The default store holds a sweep timer, which this releases in `onShutdown` (convention rule 7). A
* store passed in owns its own lifecycle, and is closed only if it offers a `close()`.
*
* @example
* const app = createApp({
* modules: [AuthModule],
* plugins: [rateLimit({ rules: { signin: { windowMs: 900_000, max: 5, message: 'too many' } } })],
* });
*
* @example <caption>In a handler.</caption>
* ⁣@Post('/signin')
* async signIn(@needs('rateLimit') limit: RateLimiter) {
* await limit('signin');
* }
*/
export function rateLimit(options: RateLimitOptions): Plugin {
const provides = options.provides ?? 'rateLimit';
const store = options.store ?? new MemoryStore({ sweepMs: sweepPeriod(options.rules) });
const keyOf = options.keyOf ?? defaultKeyOf;
const limiterFor = (ctx: RateLimitContext): RateLimiter => {
return async (name, override) => {
const configured = options.rules[name];
if (!configured) throw new Error(`Unknown rate limit rule: "${name}"`);
const rule: RateLimitRule = { ...configured, ...override };
const bucket = keyOf(ctx);
if (bucket === null) return;
const { count, resetAt } = await store.hit(`${bucket}:${name}`, rule.windowMs);
if (count > rule.max) {
throw new TooManyRequests(rule.message, Math.max(1, Math.ceil((resetAt - Date.now()) / 1000)));
}
};
};
return {
// Rule 2: plugin name, node name and provided token are one string. The original registered the
// node as 'rate-limit' while providing 'rateLimit', so two instances shared a node name.
name: provides,
mount({ scope, onShutdown }) {
scope.add({
kind: 'step',
name: provides,
// `ip` and `headers` ride on the seed context rather than being graph nodes, so `req` is the
// only declarable dependency here.
needs: ['req'],
provides: [provides],
run: (ctx: RateLimitContext) => ({ [provides]: limiterFor(ctx) }),
});
onShutdown(() => store.close?.());
},
};
}
+80
View File
@@ -0,0 +1,80 @@
import type { RateLimitHit, RateLimitStore } from './types.ts';
/** Fallback sweep period, for a store built without rules to derive one from. */
const DEFAULT_SWEEP_MS = 60_000;
/**
* Fixed-window counters held in this process.
*
* **One process, one set of counters.** Two replicas each enforce the limit separately, so the
* effective ceiling is `max × replicas`. Implement `RateLimitStore` against Redis to share them.
*
* Expired windows are dropped by a timer rather than on the hot path. The version this replaces
* walked the entire map from inside `hit()` whenever a key was new or expired — O(N²) over N
* distinct callers, and a client rotating addresses drove it deliberately.
*/
export class MemoryStore implements RateLimitStore {
private readonly windows = new Map<string, RateLimitHit>();
private readonly sweepMs: number;
private timer: ReturnType<typeof setInterval> | undefined;
constructor(options: { sweepMs?: number } = {}) {
this.sweepMs = options.sweepMs ?? DEFAULT_SWEEP_MS;
}
/** How many windows are held. Lets a test assert the sweep without reaching inside. */
get size(): number {
return this.windows.size;
}
hit(key: string, windowMs: number): RateLimitHit {
this.start();
const now = Date.now();
const current = this.windows.get(key);
if (!current || current.resetAt <= now) {
const fresh: RateLimitHit = { count: 1, resetAt: now + windowMs };
this.windows.set(key, fresh);
return fresh;
}
current.count += 1;
return current;
}
reset(): void {
this.windows.clear();
}
/** Stops the sweep. Safe to call twice — `close()` is reached more than once in real apps. */
close(): void {
if (!this.timer) return;
clearInterval(this.timer);
this.timer = undefined;
}
/**
* Arms the sweep on the first hit, not in the constructor.
*
* A store built and never used holds nothing, and starting a timer for it would keep a process
* alive over an empty map. Deliberately **not** `unref`ed: the timer is meant to hold the process
* open, so that failing to release it is a visible bug rather than a silent leak, and so that all
* three runtimes behave the same.
*/
private start(): void {
if (this.timer) return;
this.timer = setInterval(() => this.sweep(), this.sweepMs);
}
private sweep(): void {
const now = Date.now();
for (const [key, window] of this.windows) {
if (window.resetAt <= now) this.windows.delete(key);
}
}
}
+59
View File
@@ -0,0 +1,59 @@
/** A single named limit: how many hits are allowed inside a window. */
export interface RateLimitRule {
/** Window length in milliseconds. */
windowMs: number;
/** Maximum hits allowed per key inside the window. */
max: number;
/** Message returned in the 429 body. */
message: string;
}
/** What a store reports back for one hit. */
export interface RateLimitHit {
/** Hits recorded for this key inside the current window, including this one. */
count: number;
/** Epoch milliseconds at which the current window expires. */
resetAt: number;
}
/**
* Pluggable counter backend. The default is in-process memory; swap in Redis or Postgres by
* implementing this and passing it to `rateLimit({ store })`.
*/
export interface RateLimitStore {
/** Record one hit against `key` and return the resulting window state. */
hit(key: string, windowMs: number): Promise<RateLimitHit> | RateLimitHit;
/** Drop every counter. Used by tests and by operators clearing a lockout. */
reset(): Promise<void> | void;
/**
* Release whatever the store holds open. Optional: a store that holds nothing needs none, and the
* plugin's `onShutdown` calls it only if it exists.
*/
close?(): Promise<void> | void;
}
/** The function a handler receives from `@needs('rateLimit')`. */
export type RateLimiter = (rule: string, override?: Partial<RateLimitRule>) => Promise<void>;
/** The slice of the green-tea request context this plugin reads. */
export interface RateLimitContext {
ip?: string;
headers?: Record<string, string | string[] | undefined>;
}
export interface RateLimitOptions {
/** Named rules, addressed by handlers as `limit('signin')`. */
rules: Record<string, RateLimitRule>;
/** Counter backend. Defaults to an in-process `MemoryStore`. */
store?: RateLimitStore;
/**
* Derives the per-caller bucket from the request context. Defaults to `ctx.ip`.
*
* Returning `null` skips the limit for that request — use it to exempt health checks. Note that
* `ctx.ip` is empty when the app is driven through `app.fetch()` rather than a socket, so the
* default folds those into a single `unknown` bucket.
*/
keyOf?: (ctx: RateLimitContext) => string | null;
/** Graph name the limiter is published under, and the plugin's name. Defaults to `rateLimit`. */
provides?: string;
}
+35
View File
@@ -0,0 +1,35 @@
// Not a test — the child the exit test spawns. Named with a leading underscore so no runner picks it
// up: `node --test`, `deno test` and `bun test` all discover by filename, and this matches none.
//
// It boots an app that has taken a hit (so the sweep timer is armed), closes it, and prints one line.
// Nothing here calls process.exit: whether the process ends is the measurement.
import { createApp, Get, Module, Route, needs } from '@green-tea/core';
import { rateLimit } from '../src/index.ts';
import type { RateLimiter } from '../src/index.ts';
@Route('/')
class Probe {
@Get('/probe')
async probe(@needs('rateLimit') limit: RateLimiter) {
await limit('signin');
return { ok: true };
}
}
@Module({ mountpoint: '/', controllers: [Probe] })
class ProbeModule {}
async function main(): Promise<void> {
const app = createApp({
modules: [ProbeModule],
plugins: [rateLimit({ rules: { signin: { windowMs: 60_000, max: 10, message: 'too many' } } })],
});
await app.fetch(new Request('http://probe.test/probe'));
await app.close();
console.log('closed');
}
void main();
+242
View File
@@ -0,0 +1,242 @@
import { strict as assert } from 'node:assert';
import { spawn } from 'node:child_process';
import { test } from 'node:test';
import { createApp } from '@green-tea/core';
import type { App } from '@green-tea/core';
import { probeModule, runtimeCommand } from '../../../test/helpers.ts';
import { TooManyRequests } from '../src/errors.ts';
import { rateLimit } from '../src/index.ts';
import type { RateLimiter } from '../src/index.ts';
import { MemoryStore } from '../src/memory-store.ts';
const sleep = (ms: number): Promise<void> => new Promise((resolve) => setTimeout(resolve, ms));
test('counts hits inside a window and starts a new one after it expires', async () => {
const store = new MemoryStore();
try {
assert.equal(store.hit('a', 40).count, 1);
assert.equal(store.hit('a', 40).count, 2);
await sleep(60);
assert.equal(store.hit('a', 40).count, 1);
} finally {
store.close();
}
});
test('keeps separate counters per key', () => {
const store = new MemoryStore();
try {
store.hit('a', 1000);
assert.equal(store.hit('b', 1000).count, 1);
assert.equal(store.hit('a', 1000).count, 2);
} finally {
store.close();
}
});
// The defect this store replaces: `hit()` walked the whole map whenever a key was new or expired,
// so N distinct callers cost N², and a client rotating addresses triggered it on purpose. The sweep
// is what keeps the map bounded now, so it has to actually drop things.
test('sweeps expired windows without being asked on the hot path', async () => {
const store = new MemoryStore({ sweepMs: 20 });
try {
for (let i = 0; i < 50; i++) store.hit(`caller-${i}`, 10);
assert.equal(store.size, 50);
await sleep(80);
assert.equal(store.size, 0, 'expired windows were never swept');
} finally {
store.close();
}
});
test('reset drops every counter', () => {
const store = new MemoryStore();
try {
store.hit('a', 1000);
store.reset();
assert.equal(store.size, 0);
} finally {
store.close();
}
});
test('close is idempotent, because close() is called more than once in real apps', () => {
const store = new MemoryStore();
store.hit('a', 1000);
store.close();
assert.doesNotThrow(() => store.close());
});
// Convention rule 8, checked where it bites. The class never extends core's HttpError — it carries a
// registry-wide symbol, which is what lets a plugin throw a 429 that core renders without importing
// core, and what keeps working when two copies of core are in one tree (`instanceof` does not).
test('carries the brand core recognises, and the fields core reads off it', () => {
const error = new TooManyRequests('slow down', 30);
assert.equal((error as unknown as Record<symbol, unknown>)[Symbol.for('green-tea.http-error')], true);
assert.equal(error.status, 429);
assert.equal(error.message, 'slow down');
assert.equal(error.headers['retry-after'], '30');
assert.deepEqual(error.body, { message: 'slow down', status: 429 });
// Still an Error: a throw that is not one loses the stack, and core rethrows before rendering.
assert.ok(error instanceof Error);
});
const RULES = { signin: { windowMs: 60_000, max: 2, message: 'too many' } };
/**
* Runs `body` against `app` and always closes it.
*
* Closing is not housekeeping here. The default store's sweep timer is deliberately not `unref`ed —
* that is what makes the exit test in this file mean something — so an app left open keeps the test
* runner alive long after its assertions passed. `close()` runs the plugin's `onShutdown`, which is
* the same path the exit test measures, so every test here exercises it in passing.
*/
async function withApp(app: App, body: () => Promise<void>): Promise<void> {
try {
await body();
} finally {
await app.close();
}
}
test('allows up to the limit and then answers 429 with retry-after', async () => {
const app = createApp({
modules: [
probeModule('rateLimit', async (limit: RateLimiter) => {
await limit('signin');
return 'ok';
}),
],
plugins: [rateLimit({ rules: RULES, keyOf: () => 'one-caller' })],
});
await withApp(app, async () => {
const hit = () => app.fetch(new Request('http://plugin.test/rateLimit/probe'));
assert.equal((await hit()).status, 200);
assert.equal((await hit()).status, 200);
const refused = await hit();
assert.equal(refused.status, 429);
assert.ok(Number(refused.headers.get('retry-after')) >= 1);
});
});
test('keeps separate budgets per caller', async () => {
let caller = 'a';
const app = createApp({
modules: [
probeModule('rateLimit', async (limit: RateLimiter) => {
await limit('signin');
return 'ok';
}),
],
plugins: [rateLimit({ rules: RULES, keyOf: () => caller })],
});
await withApp(app, async () => {
const hit = () => app.fetch(new Request('http://plugin.test/rateLimit/probe'));
await hit();
await hit();
assert.equal((await hit()).status, 429);
caller = 'b';
assert.equal((await hit()).status, 200);
});
});
test('a keyOf returning null exempts the request entirely', async () => {
const app = createApp({
modules: [
probeModule('rateLimit', async (limit: RateLimiter) => {
await limit('signin');
return 'ok';
}),
],
plugins: [rateLimit({ rules: RULES, keyOf: () => null })],
});
await withApp(app, async () => {
for (let i = 0; i < 5; i++) {
assert.equal((await app.fetch(new Request('http://plugin.test/rateLimit/probe'))).status, 200);
}
});
});
test('names an unknown rule rather than silently allowing it', async () => {
const app = createApp({
modules: [
probeModule('rateLimit', async (limit: RateLimiter) => {
await limit('nope');
return 'ok';
}),
],
plugins: [rateLimit({ rules: RULES })],
});
await withApp(app, async () => {
assert.equal((await app.fetch(new Request('http://plugin.test/rateLimit/probe'))).status, 500);
});
});
// Convention rule 2: the plugin's name, the node's name and the provided token are one string, so
// two instances collide on none of the three.
test('two instances with different provides both answer, without colliding', async () => {
const app = createApp({
modules: [probeModule('userLimit', () => 'user'), probeModule('adminLimit', () => 'admin')],
plugins: [rateLimit({ rules: RULES, provides: 'userLimit' }), rateLimit({ rules: RULES, provides: 'adminLimit' })],
});
await withApp(app, async () => {
assert.equal((await app.fetch(new Request('http://plugin.test/userLimit/probe'))).status, 200);
assert.equal((await app.fetch(new Request('http://plugin.test/adminLimit/probe'))).status, 200);
});
});
test('the plugin is named after what it provides', () => {
assert.equal(rateLimit({ rules: RULES }).name, 'rateLimit');
assert.equal(rateLimit({ rules: RULES, provides: 'adminLimit' }).name, 'adminLimit');
});
/** Runs the probe and reports how it ended. `timeoutMs` elapsing means it never exited. */
function runProbe(timeoutMs: number): Promise<{ exited: boolean; output: string }> {
const { command, args } = runtimeCommand('packages/rate-limit/test/_exit-probe.ts');
return new Promise((resolve) => {
const child = spawn(command, args, { stdio: ['ignore', 'pipe', 'inherit'] });
let output = '';
child.stdout.on('data', (chunk: Buffer) => (output += chunk.toString()));
const timer = setTimeout(() => {
child.kill('SIGKILL');
resolve({ exited: false, output });
}, timeoutMs);
child.on('exit', () => {
clearTimeout(timer);
resolve({ exited: true, output });
});
});
}
// Convention rule 7, and the only test in the repository that measures it rather than asserting it.
// A leaked setInterval keeps Node, Deno and Bun alive indefinitely; a cleared one lets each exit in
// well under a second. The process is the probe, which is what makes this portable.
test('the app exits on its own after close(), because onShutdown cleared the sweep', async () => {
const { exited, output } = await runProbe(2_000);
assert.ok(output.includes('closed'), `the probe never reached close(): ${output}`);
assert.ok(exited, 'the process was still alive 2s after close() — a timer outlived onShutdown');
});
+53
View File
@@ -0,0 +1,53 @@
#!/usr/bin/env node
// Cognitive-complexity gate over every package's src. Fails (exit 1) if any named function exceeds the
// threshold. Same gate as core's, walked per package because ccts-json takes one directory.
import { execSync } from 'node:child_process';
import { existsSync, readdirSync } from 'node:fs';
const THRESHOLD = 25;
function scores(dir) {
try {
return execSync(`npx ccts-json ${dir}`, { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] });
} catch (error) {
return error.stdout?.toString() ?? '';
}
}
const offenders = [];
function walk(node, dir) {
if (!node || typeof node !== 'object') return;
if (node.kind === 'function' && node.name && node.score > THRESHOLD) {
offenders.push({ score: node.score, name: `${dir}: ${node.name}` });
}
for (const [key, value] of Object.entries(node)) {
if (key === 'inner' && Array.isArray(value)) value.forEach((child) => walk(child, dir));
else if (value && typeof value === 'object') walk(value, dir);
}
}
const dirs = readdirSync('packages')
.map((name) => `packages/${name}/src`)
.filter((dir) => existsSync(dir));
for (const dir of dirs) {
const raw = scores(dir);
if (!raw.trim()) {
console.error(`check-complexity: no output from ccts-json for ${dir}`);
process.exit(2);
}
walk(JSON.parse(raw), dir);
}
if (offenders.length) {
offenders.sort((a, b) => b.score - a.score);
console.error(`\n✖ cognitive complexity: ${offenders.length} function(s) over ${THRESHOLD}\n`);
for (const o of offenders) console.error(` ${String(o.score).padStart(4)} ${o.name}`);
console.error('\nExtract helpers to bring them under the threshold. The threshold is not raised.\n');
process.exit(1);
}
console.log(`✓ cognitive complexity: every function ≤ ${THRESHOLD} (${dirs.length} package(s))`);
+41
View File
@@ -0,0 +1,41 @@
#!/usr/bin/env node
// Runs the contract tests of every package whose `engines` declares <runtime>, on that runtime.
// `engines` is the one declaration (convention rule 9): a package that does not claim a runtime is not
// tested on it, and a package that claims one cannot skip it.
//
// Usage: node scripts/run-runtime.mjs <deno|bun|workerd>
import { spawnSync } from 'node:child_process';
import { readdirSync, readFileSync } from 'node:fs';
const COMMANDS = {
deno: (dirs) => ['deno', ['test', '--allow-all', '--no-check', ...dirs.map((dir) => `packages/${dir}/test/`)]],
bun: (dirs) => ['bun', ['test', ...dirs.map((dir) => `./packages/${dir}/test/`)]],
};
const runtime = process.argv[2];
if (!(runtime in COMMANDS) && runtime !== 'workerd') {
console.error('usage: run-runtime.mjs <deno|bun|workerd>');
process.exit(2);
}
const declares = (dir) => {
const { engines = {} } = JSON.parse(readFileSync(`packages/${dir}/package.json`, 'utf8'));
return runtime in engines;
};
const dirs = readdirSync('packages').filter(declares);
if (dirs.length === 0) {
console.log(`no package declares ${runtime}; nothing to run`);
process.exit(0);
}
// There is no workerd harness for plugins yet (spec, section 4). A package that declares workerd must
// not pass CI by having nothing run against it — copy core's test/edge harness first.
if (runtime === 'workerd') {
console.error(`${dirs.join(', ')} declare workerd, and there is no workerd harness yet.`);
process.exit(1);
}
const [command, args] = COMMANDS[runtime](dirs);
const { status } = spawnSync(command, args, { stdio: 'inherit' });
process.exit(status ?? 1);
+11
View File
@@ -0,0 +1,11 @@
import { strict as assert } from 'node:assert';
import { test } from 'node:test';
import { runtimeCommand } from './helpers.ts';
test('runtimeCommand names an executable and passes the script last', () => {
const { command, args } = runtimeCommand('some/probe.ts');
assert.ok(command.length > 0, 'no command');
assert.equal(args.at(-1), 'some/probe.ts');
});
+49
View File
@@ -0,0 +1,49 @@
import { Get, Module, Route, needs } from '@green-tea/core';
/**
* A module with one route, `GET /<token>/probe`, whose handler receives `@needs(token)` and answers
* `{ value: await read(value) }`.
*
* It gives a plugin's node a consumer, which is how an application reaches it too — so a contract test
* exercises the plugin through `createApp` and `app.fetch` rather than by calling `mount` by hand.
* The token doubles as the mountpoint, so two probes for two instances of one plugin cannot collide.
*/
export function probeModule(token: string, read: (value: any) => unknown) {
@Route('/')
class Probe {
@Get('/probe')
async probe(@needs(token) value: unknown) {
return { value: await read(value) };
}
}
@Module({ mountpoint: `/${token}`, controllers: [Probe] })
class ProbeModule {}
return ProbeModule;
}
/** The globals each runtime defines, for picking the argv that re-runs a script under it. */
interface RuntimeGlobals {
Deno?: { execPath(): string };
Bun?: unknown;
process?: { execPath: string };
}
/**
* The command that runs `script` on whichever runtime is hosting this test.
*
* A contract file runs unchanged on three runtimes, so a test that spawns a child cannot hardcode
* one. Deno needs its permission flag, Bun runs TypeScript directly, and Node needs tsx to load it.
*/
export function runtimeCommand(script: string): { command: string; args: string[] } {
const globals = globalThis as RuntimeGlobals;
// `--no-check` for the same reason `npm run test:deno` passes it: Deno type-checks the whole
// reachable graph, which here reaches core's Node-only modules and their ambient `Buffer`. The
// child is a runtime probe, and `npm run typecheck` already covers the types.
if (globals.Deno) return { command: globals.Deno.execPath(), args: ['run', '--allow-all', '--no-check', script] };
if (globals.Bun) return { command: 'bun', args: ['run', script] };
return { command: globals.process!.execPath, args: ['--import', 'tsx', script] };
}
+135
View File
@@ -0,0 +1,135 @@
import { strict as assert } from 'node:assert';
import { existsSync, readdirSync, readFileSync } from 'node:fs';
import { join } from 'node:path';
import { test } from 'node:test';
// Static checks for convention rules 8 and 9 and for npm provenance. They read files only, so they run
// under Node alone; the contract tests are what run on every runtime.
const ROOT = join(import.meta.dirname, '..');
const RUNTIMES = new Set(['node', 'deno', 'bun', 'workerd']);
// The README names runtimes for people; `engines` names them for tools. This is the whole mapping.
const README_RUNTIMES: Record<string, string> = { Node: 'node', Deno: 'deno', Bun: 'bun', 'workerd (edge)': 'workerd' };
interface PackageJson {
name: string;
version: string;
private?: boolean;
engines?: Record<string, string>;
dependencies?: Record<string, string>;
devDependencies?: Record<string, string>;
peerDependencies?: Record<string, string>;
repository?: { type?: string; url?: string; directory?: string };
main?: string;
module?: string;
types?: string;
files?: string[];
exports?: unknown;
scripts?: Record<string, string>;
}
interface DenoJson {
name?: string;
version?: string;
imports?: Record<string, string>;
workspace?: string[];
exports?: string;
}
const readJson = <T>(...path: string[]): T => JSON.parse(readFileSync(join(ROOT, ...path), 'utf8')) as T;
const packages = existsSync(join(ROOT, 'packages'))
? readdirSync(join(ROOT, 'packages'), { withFileTypes: true })
.filter((entry) => entry.isDirectory())
.map((entry) => entry.name)
: [];
/** Rows of the README's `## Runtimes` table, as `[runtime, supported]`. */
function runtimeRows(readme: string): Array<[string, boolean]> {
const section = readme.split(/^## /m).find((part) => part.startsWith('Runtimes'));
assert.ok(section, 'README has no "## Runtimes" section');
return section
.split('\n')
.map((line) => line.split('|').map((cell) => cell.trim()))
.filter((cells) => cells[1] in README_RUNTIMES)
.map((cells) => [README_RUNTIMES[cells[1]], cells[2] === '✅']);
}
test('the workspace has at least one package', () => {
assert.ok(packages.length > 0, 'no directories under packages/');
});
for (const dir of packages) {
const pkg = readJson<PackageJson>('packages', dir, 'package.json');
const deno = readJson<DenoJson>('packages', dir, 'deno.json');
test(`${dir}: npm and JSR publish the same package at the same version`, () => {
assert.equal(pkg.name, `@green-tea/${dir}`);
assert.equal(deno.name, pkg.name);
assert.equal(deno.version, pkg.version);
});
test(`${dir}: core is a dev dependency only`, () => {
assert.ok(pkg.devDependencies?.['@green-tea/core'], 'core missing from devDependencies');
assert.equal(pkg.dependencies?.['@green-tea/core'], undefined, 'core in dependencies');
assert.equal(pkg.peerDependencies?.['@green-tea/core'], undefined, 'core in peerDependencies');
});
test(`${dir}: JSR maps the core version npm installs`, () => {
assert.equal(deno.imports?.['@green-tea/core'], `npm:@green-tea/core@${pkg.devDependencies?.['@green-tea/core']}`);
});
test(`${dir}: engines declares runtimes, and only known ones`, () => {
const keys = Object.keys(pkg.engines ?? {});
assert.ok(keys.length > 0, 'engines is empty');
for (const key of keys) assert.ok(RUNTIMES.has(key), `unknown engines key "${key}"`);
});
test(`${dir}: the README lists all four runtimes, and ✅ exactly the engines keys`, () => {
const rows = runtimeRows(readFileSync(join(ROOT, 'packages', dir, 'README.md'), 'utf8'));
assert.deepEqual(rows.map(([runtime]) => runtime).sort(), [...RUNTIMES].sort());
const supported = rows.filter(([, ok]) => ok).map(([runtime]) => runtime);
assert.deepEqual(supported.sort(), Object.keys(pkg.engines ?? {}).sort());
});
test(`${dir}: npm provenance points at the public repository and this directory`, () => {
assert.deepEqual(pkg.repository, {
type: 'git',
url: 'git+https://github.com/Expressive-Tea/green-tea-plugins.git',
directory: `packages/${dir}`,
});
});
test(`${dir}: the Deno workspace includes it`, () => {
assert.ok(readJson<DenoJson>('deno.json').workspace?.includes(`./packages/${dir}`));
});
test(`${dir}: JSR is served the source`, () => {
// JSR transpiles TypeScript itself and hands consumers a typed ESM package, so it gets `src/`
// and the packages carry no build of their own.
assert.equal(deno.exports, './src/index.ts', 'JSR should publish the TypeScript source');
});
test(`${dir}: nothing here is publishable to npm`, () => {
// Plugins publish to JSR alone. `npx jsr add` installs them under npm, yarn, pnpm and bun
// through `npm.jsr.io`, which leaves the import specifier intact, so the second registry bought
// a per-package tsup build and a dual `exports` map without buying a reader anything.
//
// JSR is also the only one of the two that can say *where a plugin runs*, per package. That is
// not cosmetic for a framework whose claim is one app on four runtimes: `jwt` needs
// `node:fs/promises` and `metrics` imports nothing at all, and npm has nowhere to record the
// difference.
//
// `private` is the guard, not a leftover: it is what makes an accidental `npm publish` fail
// instead of shipping a package whose entry points describe a `dist/` nobody builds.
assert.equal(pkg.private, true, 'a plugin must not be publishable to npm');
for (const field of ['main', 'module', 'types', 'exports', 'files'] as const) {
assert.equal(pkg[field], undefined, `${field} describes an npm tarball that is never built`);
}
assert.equal(pkg.scripts?.build, undefined, 'there is no build to run');
});
}
+18
View File
@@ -0,0 +1,18 @@
{
"compilerOptions": {
"target": "es2022",
"module": "preserve",
"moduleResolution": "bundler",
"lib": ["es2022"],
"types": ["node"],
"strict": true,
"noEmit": true,
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"skipLibCheck": true,
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"forceConsistentCasingInFileNames": true
},
"include": ["packages/*/src", "packages/*/test", "test"]
}