Compare commits

Author SHA1 Message Date
chrnx 5e9ca2678b test(rate-limit): give peers on different addresses separate budgets on every runtime
CI / dco (pull_request) Successful in 3s
CI / build (pull_request) Successful in 13s
CI / runtimes (bun) (pull_request) Failing after 10s
CI / runtimes (edge) (pull_request) Successful in 7s
CI / runtimes (deno) (pull_request) Failing after 8s
The default keyOf buckets callers by ctx.ip. serveDeno and serveBun left ctx.ip empty until
core #116 (merged in core #117), so every caller on those runtimes shared the 'unknown' bucket
and the first one to reach max locked out everybody else.

This drives the plugin's default keyOf over a real socket: one dual-stack listener, client A over
127.0.0.1 and client B over ::1, max: 1. A's second request must be 429 and B's first 200, with two
distinct ctx.ip values. Node's listen() path runs the same test as the control and passes on any
core; on Deno and Bun it passes only on a core that carries #116, and fails on 26.9.0-beta.2.
Hosts without an IPv6 loopback fall back to 127.0.0.1 and 127.0.0.2, which only Linux routes.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-10 11:57:43 -05:00
chrnx c87dccedd0 Merge pull request 'fix(ci): install bun in the release workflow' (#11) from fix/release-needs-bun into develop
CI / dco (pull_request) Successful in 5s
CI / runtimes (bun) (pull_request) Successful in 12s
CI / dco (push) Has been skipped
CI / build (pull_request) Successful in 13s
CI / runtimes (edge) (pull_request) Successful in 8s
CI / runtimes (deno) (pull_request) Successful in 12s
CI / runtimes (bun) (push) Successful in 10s
CI / runtimes (deno) (push) Successful in 10s
CI / runtimes (edge) (push) Successful in 9s
CI / build (push) Successful in 15s
Promote → GitHub / push-github (push) Successful in 6s
2026-09-23 17:53:05 +00:00
chrnx fc495fa3cb fix(ci): install bun in the release workflow
CI / dco (pull_request) Successful in 4s
CI / build (pull_request) Successful in 14s
CI / runtimes (deno) (pull_request) Successful in 10s
CI / runtimes (bun) (pull_request) Successful in 10s
CI / runtimes (edge) (pull_request) Successful in 9s
`release.yml` runs `npm run test:bun` but never installed bun. `ci.yml` gets
away with one setup action per matrix entry; the release job runs every suite in
the same job, so it needs both.

Leaving it out does not skip the suite. `scripts/run-runtime.mjs` spawns `bun`,
gets `ENOENT`, and `process.exit(status ?? 1)` turns a missing binary into a
failure — verified: `spawnSync` on a missing command returns `status: null`,
which that expression maps to 1.

Nothing would have been published, since the gates run before the publish. What
it would have cost is a tag sitting on GitHub with no release against it, which
has to be deleted before the same tag can be tried again.

Found during the pre-flight for the first tag, by checking which tools the steps
use against which ones the job installs, rather than by pushing the tag and
reading the failure.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-23 12:52:21 -05:00
chrnx 1f3a42e747 Merge pull request 'ci: publish to JSR from a dated tag, and close the changelogs' (#9) from ci/release-to-jsr into develop
CI / dco (pull_request) Successful in 5s
CI / build (pull_request) Successful in 12s
CI / runtimes (bun) (pull_request) Successful in 13s
CI / runtimes (deno) (pull_request) Successful in 12s
CI / build (push) Successful in 14s
CI / runtimes (edge) (push) Successful in 10s
Promote → GitHub / push-github (push) Successful in 5s
CI / runtimes (edge) (pull_request) Successful in 9s
CI / dco (push) Has been skipped
CI / runtimes (bun) (push) Successful in 10s
CI / runtimes (deno) (push) Successful in 10s
2026-09-23 17:35:33 +00:00
chrnx d5e8c8a827 fix(ci): stop a failed publish from reporting as a successful release
CI / runtimes (edge) (pull_request) Successful in 7s
CI / dco (pull_request) Successful in 4s
CI / build (pull_request) Successful in 14s
CI / runtimes (bun) (pull_request) Successful in 9s
CI / runtimes (deno) (pull_request) Successful in 12s
Two bugs in one line, both silent, both found in review before anything shipped.

**The pipe swallowed the exit status.** `deno publish | tee` reports the status
of the last command in the pipeline, and that is `tee`, which always succeeds.
GitHub's default shell is `bash -e` *without* `pipefail`, so a failed publish
would have been a green step — and the workflow would have gone on to cut a
GitHub release for it. Demonstrated rather than assumed:

    bash -e   -c 'false | tee /dev/null'  -> exit 0
    bash -eo pipefail -c 'false | tee /dev/null'  -> exit 1

Naming `shell: bash` gets `-eo pipefail`.

**And the log was going to be empty anyway.** deno's logger is env_logger,
whose default target is stderr, so the `Successfully published` lines never
reach stdout. Measured against a real `deno publish`: 0 lines on stdout, all of
them on stderr. So `--notes` would have found nothing and announced that nothing
shipped, on every successful release. `2>&1` fixes it.

The second bug is the reason for the third change: `--notes` now refuses a log
carrying neither marker instead of reporting it as "nothing was published". A log
this script cannot read and a release where nothing shipped are indistinguishable
from the text, and guessing wrong is silent in the direction that matters. Now it
fails and says to check the redirect and the pipeline.

Verified all three paths: an empty log exits 1, an all-skipped log renders the
"already on JSR" line and exits 0, and a real publish log renders per-package
sections.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-23 12:34:30 -05:00
chrnx 32baf0c592 ci: publish to JSR from a dated tag, and close the changelogs
CI / build (pull_request) Successful in 15s
CI / runtimes (edge) (pull_request) Successful in 8s
CI / dco (pull_request) Successful in 4s
CI / runtimes (bun) (pull_request) Successful in 10s
CI / runtimes (deno) (pull_request) Successful in 12s
Adds the release workflow and the script it leans on, plus the `[Unreleased]`
sections these three packages have carried since they were written.

**The tag is a date, not a version.** `release-26.9.23` says when; the release
body says what moved. A version-shaped tag would be a lie here — three packages
carry three independent versions, so `plugins-v26.9.0` would match none of them
and invite being read as `@green-tea/jwt@26.9.0`.

**Tag-driven, not push-driven.** JSR's own setup page offers an example that
publishes on every push to `main`. For this repository that means every
promotion publishes, and a JSR version can never be replaced or removed, so one
distracted merge would burn a version number permanently. A tag is a decision; a
merge is not.

**Publishing all three at once is safe, and that is measured rather than
assumed.** `deno publish` queries the registry per package and drops the ones
already there (`filter_out_published_packages` in denoland/deno,
cli/tools/publish/mod.rs); skipping logs a warning, and a workspace with nothing
left to do exits 0 with "All packages are already published". So a tag cut after
changing one package publishes that one and leaves the others alone, with no
per-package logic here.

`scripts/release.mjs --check` runs **before** the publish and refuses when a
version about to ship has no changelog entry. That ordering is the point: core's
equivalent runs after npm and JSR have already published, so a missing heading
fails a release that has already shipped. Worth not inheriting.

`--notes` builds the release body from what `deno publish` actually reported
rather than from a prediction of it — predicting means duplicating Deno's
filtering and being wrong about it silently.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-23 12:30:18 -05:00
chrnx 4a98046da2 Merge pull request 'Prepare the repository to be public: scrub infrastructure, add community files' (#8) from chore/scrub-before-publish into develop
CI / dco (pull_request) Successful in 5s
CI / runtimes (bun) (pull_request) Successful in 11s
CI / runtimes (edge) (pull_request) Successful in 9s
CI / build (pull_request) Successful in 14s
CI / runtimes (deno) (pull_request) Successful in 12s
CI / dco (push) Has been skipped
CI / build (push) Successful in 12s
CI / runtimes (edge) (push) Successful in 9s
CI / runtimes (deno) (push) Successful in 11s
CI / runtimes (bun) (push) Successful in 11s
Promote → GitHub / push-github (push) Successful in 6s
2026-09-23 17:01:05 +00:00
chrnx 57c4707bc5 ci: run on both forges, and watch contrib
CI / dco (pull_request) Successful in 5s
CI / build (pull_request) Successful in 12s
CI / runtimes (bun) (pull_request) Successful in 12s
CI / runtimes (deno) (pull_request) Successful in 11s
CI / runtimes (edge) (pull_request) Successful in 9s
Adding `contrib` to the mirror without adding it here was a hole, not a gap.
A pull request against a branch a workflow does not list triggers **nothing** —
not a reduced set of checks, none — so an external contributor would have seen
no signal at all, and neither would whoever merged their work. The branch and
its CI had to land together; the previous commit shipped only half of that.

So `contrib` joins `develop` and `main` in both trigger lists, and the three
`github.server_url != 'https://github.com'` guards are gone. Their reason went
with Verdaccio: the packages used to build against a core that existed only on
an internal registry a public runner cannot reach, and they resolve
`@green-tea/core` from npmjs.org now. Guarding CI to one forge while inviting
contributions to the other cannot both be true.

The dco job keeps `github.event_name == 'pull_request'`, matching core, so it
reports on pull requests and costs nothing on push.

Verified the way a public runner would: the workflow names no secrets and no
internal hosts, and a fresh clone runs `npm ci`, lint, typecheck, the Node suite
and `deno publish --dry-run` with nothing configured.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-23 11:58:48 -05:00
chrnx e1ea1542c9 docs: add the community files GitHub expects before this goes public
CI / dco (pull_request) Successful in 5s
CI / build (pull_request) Successful in 12s
CI / runtimes (bun) (pull_request) Successful in 11s
CI / runtimes (deno) (pull_request) Successful in 11s
CI / runtimes (edge) (pull_request) Successful in 8s
The repository had a LICENSE and nothing else. Adds CONTRIBUTING, a code of
conduct, a security policy, the DCO, issue templates and a pull request
template — the set GitHub checks for, written for these packages rather than
copied from core.

**This adds a `contrib` branch, reversing a decision made earlier today.** The
promotion originally mirrored `main` alone, on the reasoning that a repository
with no documented contribution flow does not need a branch nobody targets. That
reasoning held right up until we decided to document one. CONTRIBUTING has to
send people somewhere, `main` is the wrong answer — a pull request there puts the
forges out of step and breaks the next promotion — so `develop → contrib` is
back, the same arrangement core runs.

What is adapted rather than inherited:

- Node 22, not core's 18, which is what every package here already requires.
- No build step anywhere. JSR transpiles the source, so `deno publish --dry-run`
  is what stands in for one.
- The four traps an assistant falls into *here*: turning `import type` into a
  value import, adding a build, writing for Node alone, and changing `engines`
  without the README's Runtimes table.
- SECURITY scopes each package separately, and sends vulnerabilities in the
  framework itself to core — same people, but the advisory has to live where the
  fix does.

There is also a plugin proposal template, which exists to ask the question that
is cheaper in a paragraph than in a written pull request: whether a thing belongs
in the official set at all, or is better as the author's own package. The
template says the second outcome is first-class, because it usually is.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-23 11:55:22 -05:00
chrnx a3f57e61d9 chore(ci): stop naming internal infrastructure in files that go public
`main` is about to be mirrored to a public repository for the first time, so
everything in the tree becomes readable by anyone. Two things in here were
written when only the development forge could see them.

`ci.yml` carried the internal registry's hostname in a step that authenticated
to it — twice. That step is also dead: `.npmrc` no longer points the @green-tea
scope anywhere, and core resolves from npmjs.org. So this removes a published
hostname and an instruction that does nothing, in the same edit.

`AGENTS.md` named the origin by its repository path. Core's public copy says
"Development lives on a private Gitea instance" and stops there, which is the
right level: a reader learns the shape of the workflow without learning where it
lives, and a path they cannot reach tells them nothing anyway.

`promote.yml` keeps saying the forge by name, because core's public copy does and
the two should read alike. Naming the product is not the problem; naming the host
was.

Checked the rest while here: no credentials, no keys, no personal paths or
addresses, no issue templates routing anyone to a forge they cannot open.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-23 11:50:52 -05:00
chrnx fd82d10c2b Merge pull request 'ci(plugins): mirror Gitea main to GitHub main' (#6) from ci/promote-to-github into develop
CI / dco (push) Has been skipped
CI / build (push) Successful in 13s
CI / runtimes (bun) (push) Successful in 12s
CI / runtimes (edge) (push) Successful in 9s
CI / runtimes (deno) (push) Successful in 11s
CI / dco (pull_request) Successful in 3s
CI / runtimes (bun) (pull_request) Successful in 10s
CI / build (pull_request) Successful in 14s
CI / runtimes (edge) (pull_request) Successful in 9s
CI / runtimes (deno) (pull_request) Successful in 11s
2026-09-23 16:43:30 +00:00
chrnx 51c54c1cc4 ci(plugins): mirror Gitea main to GitHub main
CI / dco (pull_request) Successful in 5s
CI / build (pull_request) Successful in 13s
CI / runtimes (bun) (pull_request) Successful in 12s
CI / runtimes (deno) (pull_request) Successful in 12s
CI / runtimes (edge) (pull_request) Successful in 9s
The public repository exists but nothing populates it. This is the same
promotion core uses, cut down to what this repository actually has: one branch.

Only `main`, and no `contrib` counterpart. Core mirrors `develop` as `contrib`
because outside contributions land there, and that flow is documented. Here it
is not, so a second mirrored branch would be a branch nobody targets.

Tags stay off the push, `--tags` included. Core's reason was that the same tag
means one thing on each forge; here it is simpler and sharper — these packages
publish to JSR, and a JSR version can never be replaced or removed, so a tag must
never reach the public forge as a side effect of promoting a branch.

The push is not forced, and the step fails early with a readable message when
GH_PROMOTE_TOKEN is missing rather than building a remote URL with an empty
credential and failing on the push with an authentication error instead. The
secret is set on this repository; the guard is for whoever forks or rebuilds it.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-23 11:41:25 -05:00
chrnx ea25331631 Merge pull request 'chore(plugins): publish to JSR alone, and drop the npm build' (#5) from chore/jsr-only-plugins into develop
CI / dco (push) Has been skipped
CI / runtimes (bun) (push) Successful in 10s
CI / build (push) Successful in 14s
CI / runtimes (deno) (push) Successful in 10s
CI / runtimes (edge) (push) Successful in 9s
2026-09-23 16:35:02 +00:00
chrnx 686a4527cf docs(plugins): give each package a header, and stop leaning on a marketplace
CI / dco (pull_request) Successful in 7s
CI / build (pull_request) Successful in 12s
CI / runtimes (bun) (pull_request) Successful in 12s
CI / runtimes (deno) (pull_request) Successful in 11s
CI / runtimes (edge) (pull_request) Successful in 10s
Each README now opens the way core's does — logo, name, one line saying what
the package is for. The package README is the page JSR renders, so it is the
first thing anyone sees, and three of them opened with a bare `# @green-tea/x`.

The logo is an absolute URL rather than a relative path, deliberately. Core's
README points at `./assets/logo.png`, and core's `publish.include` does not ship
`assets/` — so that image 404s on core's JSR page today. Repeating the pattern
three more times would have repeated the bug three more times.

Also drops the claim that npmjs.org discovery does not matter "where the
marketplace is the channel anyway". There is no marketplace yet, and a plugin
should stand on its own rather than on a site that has not shipped. The cost is
now stated plainly instead of argued away.

Corrects "their built code never imports it": with JSR publishing the source,
the build is JSR's, not ours. What holds is that a type import leaves nothing
behind, so the published JavaScript never mentions core.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-23 11:24:09 -05:00
chrnx 16f8329794 docs(plugins): say how to install now that npm is not an option
CI / dco (pull_request) Successful in 5s
CI / build (pull_request) Successful in 15s
CI / runtimes (bun) (pull_request) Successful in 11s
CI / runtimes (edge) (pull_request) Successful in 9s
CI / runtimes (deno) (pull_request) Successful in 11s
The READMEs still described a dual publish, and none of them carried an install
command at all — so the instruction a reader would infer, `npm i
@green-tea/jwt`, is the one command that no longer works. Each package README is
also the page JSR renders, which makes it the first thing anyone sees.

Adds `npx jsr add` to all three, with the deno and bun forms, and says plainly
that there is no npmjs.org package rather than letting someone find out from a
404.

Also corrects a claim in the root README that this branch made false: "installing
one never pulls a second copy of core". Measured while deciding this change — a
plugin names an exact core in `deno.json`, and across a minor boundary npm nests
a second copy instead of deduplicating. The copy is inert, since a plugin's built
code never imports core, and that is worth saying precisely: what is guaranteed
is which core *runs*, not how many are on disk.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-23 10:26:10 -05:00
chrnx 8499aaa760 fix(ci): resolve core from npm, not Verdaccio
CI / dco (pull_request) Successful in 6s
CI / runtimes (deno) (pull_request) Successful in 12s
CI / build (pull_request) Successful in 14s
CI / runtimes (bun) (pull_request) Successful in 11s
CI / runtimes (edge) (pull_request) Successful in 9s
`npm ci` has been failing on `develop` with `EINTEGRITY` for `@green-tea/core`,
independently of any branch — verified by running it on a clean clone of
`develop` before touching anything. Every job that installs was red; only `dco`,
which does not, was green.

Verdaccio proxies npmjs.org. When core 26.9.0-beta.2 was published for real on
2026-09-22, the staged tarball under the same version was superseded by the
upstream one, and the integrity recorded in the lockfile stopped matching what
the registry serves. Nothing in this repository changed; the thing it pinned
did.

`.npmrc` existed only because that version lived on Verdaccio alone, which its
own comment said would end at Plan B3. It ended early: core is on npmjs.org, so
the scope line goes and the lockfile now resolves from
`registry.npmjs.org` with the integrity npm published.

The `if:` guards keeping CI on Gitea stay. Their stated reason is gone — a
GitHub runner can reach npm — but turning CI on over there is its own change,
and the repository has no GitHub mirror yet.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-23 10:21:53 -05:00
chrnx 4caf8809df chore(plugins): publish to JSR alone, and drop the npm build
CI / dco (pull_request) Successful in 4s
CI / build (pull_request) Failing after 8s
CI / runtimes (bun) (pull_request) Failing after 7s
CI / runtimes (deno) (pull_request) Failing after 9s
CI / runtimes (edge) (pull_request) Failing after 7s
The second registry was costing a tsup config per package, a dual `exports`
map and a `dist/` that could go stale between a merge and a release — and it
was not buying a reader anything. `npx jsr add @green-tea/<name>` installs
under npm, yarn, pnpm and bun through `npm.jsr.io`: one line in `.npmrc`, and
the import specifier stays `@green-tea/<name>`. The `@jsr/` name only ever
appears in the lockfile.

Nothing is published yet — all three packages are absent from both registries
— so this costs no consumer anything, and it is the reversible direction:
adding npm later breaks nobody, while removing it after a publish would.

JSR is also the only one of the two that can record *where a plugin runs*, per
package, which is not cosmetic for a framework whose claim is one app on four
runtimes. `jwt` needs `node:fs/promises` and cannot serve workerd; `metrics`
imports nothing and runs everywhere. npm has nowhere to put that.

`private: true` stays and becomes the guard: an accidental `npm publish` now
fails rather than shipping entry points that describe a build nobody runs.
`test/workspace.test.ts` pins that invariant instead of the dual-registry one.

The CI job keeps the name `build` deliberately — renaming it would change a
required status check on the protected branches, which is a separate change.
`deno publish --dry-run` in the `runtimes` job now stands in for the build, and
it is the publish path these packages actually take.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-23 10:13:39 -05:00
chrnx 3e8707034c Merge pull request 'docs: list every package, and show the graph doing the work' (#4) from docs/steps-and-index into develop
CI / dco (push) Has been skipped
CI / runtimes (bun) (push) Successful in 12s
CI / build (push) Successful in 17s
CI / runtimes (edge) (push) Successful in 8s
CI / runtimes (deno) (push) Successful in 13s
2026-09-19 17:34:35 +00:00
chrnx 772f4d11a9 docs: list every package, and show the graph doing the work
CI / dco (pull_request) Successful in 3s
CI / runtimes (bun) (pull_request) Successful in 10s
CI / build (pull_request) Successful in 18s
CI / runtimes (deno) (pull_request) Successful in 11s
CI / runtimes (edge) (pull_request) Successful in 10s
The root README still advertised one package, three releases in.

jwt and rate-limit both demonstrated themselves from inside a handler, which
reads as a middleware chain with extra steps. Signing does belong there — it is
the response to that one request — but verifying is a precondition shared by
every protected route, and its result is what those routes are actually asking
for. Shown as a `@Step` that provides `user`, so the handler asks for `user` and
never for `jwt`.

rate-limit gains the same treatment plus the constraint that makes it work:
the step must provide a token the handler names. `subgraphFor` builds each
route's closure backwards from the handler's `needs`, so a step providing
something nobody asks for is not in the closure and never runs — the limit
would silently not apply, which is the worst way for a rate limiter to fail.
The inline call is kept as the smaller option, with what it costs.

metrics is left alone: rendering a scrape really is a route's job.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-19 12:24:23 -05:00
chrnx dcc9c3d42b Merge pull request 'build: publish a real build to npm, and the source to JSR' (#3) from feature/package-builds into develop
CI / dco (push) Has been skipped
CI / runtimes (bun) (push) Successful in 11s
CI / build (push) Successful in 19s
CI / runtimes (deno) (push) Successful in 11s
CI / runtimes (edge) (push) Successful in 9s
2026-09-19 17:06:43 +00:00
chrnx 3b1eceecb9 build: publish a real build to npm, and the source to JSR
CI / dco (pull_request) Successful in 4s
CI / runtimes (bun) (pull_request) Successful in 10s
CI / build (pull_request) Successful in 18s
CI / runtimes (deno) (pull_request) Successful in 11s
CI / runtimes (edge) (pull_request) Successful in 9s
Every package exported `./src/index.ts` and had no build at all, which made the
npm half of the dual publish unusable. Measured against a staging registry with
`@green-tea/metrics` installed into a clean project: Node threw
ERR_UNSUPPORTED_NODE_MODULES_TYPE_STRIPPING, `--experimental-strip-types` threw
the same error because Node refuses to strip types under `node_modules`
unconditionally, and Deno-via-npm threw it too. Only Bun could import it. The
release pipeline would have published that to both registries at once.

JSR needs no help — it transpiles on publish and hands Node an ESM package with
generated declarations — so `deno.json` keeps exporting `src/`. The build exists
for npm alone, as CJS and ESM: core is `"type": "commonjs"` and publishes both,
so a CJS application has to be able to `require()` a plugin.

Core stays external in the declarations. tsup bundles devDependencies by
default, and convention rule 8 puts core there, so without that line every
plugin would have shipped a frozen private copy of a contract core owns.

Verified by packing all three and consuming them from outside the workspace:
`require()` and `import` both resolve under Node, Bun and Deno, and `tsc`
type-checks clean under `node16` and `bundler` resolution.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-19 11:58:54 -05:00
chrnx a7253196dc Merge pull request 'feat: rate-limit and metrics plugins' (#2) from feature/rate-limit-metrics into develop
CI / dco (push) Has been skipped
CI / build (push) Successful in 13s
CI / runtimes (bun) (push) Successful in 12s
CI / runtimes (edge) (push) Successful in 7s
CI / runtimes (deno) (push) Successful in 13s
2026-09-19 16:58:41 +00:00
chrnx e1773ae1e0 build: record the two new packages in the lockfile
CI / dco (pull_request) Successful in 5s
CI / build (pull_request) Successful in 12s
CI / runtimes (bun) (pull_request) Successful in 11s
CI / runtimes (deno) (pull_request) Successful in 10s
CI / runtimes (edge) (pull_request) Successful in 10s
npm ci verifies the lockfile against every workspace package.json and refuses to
install when they disagree, so adding rate-limit and metrics without refreshing
the lock failed all four CI jobs at their first step.

Nothing caught it locally: the contract tests import through relative paths
(../src/index.ts) rather than by package name, so the new workspaces never
needed to be linked into node_modules for the suite to pass. Verified now by
running npm ci itself rather than npm install.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-18 13:33:39 -05:00
chrnx de0081ddae feat(metrics): publish the collector and a transformer to serve it
CI / dco (pull_request) Successful in 5s
CI / build (pull_request) Failing after 8s
CI / runtimes (bun) (pull_request) Failing after 6s
CI / runtimes (deno) (pull_request) Failing after 7s
CI / runtimes (edge) (pull_request) Failing after 6s
The transformer is exported instead of a route: the path, the auth and whether
the endpoint exists are the application's decisions, and a plugin that mounted
/metrics itself would be taking them.

No onShutdown — a bus subscription is an entry in a set and keeps nothing alive,
which is what rule 7 asks about. Closes green-tea#68.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-18 13:27:08 -05:00
chrnx 5a74cad793 feat(metrics): count request:end, and only request:end
A failed request emits three lifecycle events. request:end is the terminal and
universal one, so it is the request counter; request:failed is additional and
gets its own series. Counting both as requests is the double count issue #64
was filed for.

Labels come from route, which the route table bounds, never from name, which
carries the arriving path and is bounded by nothing — issue #65.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-18 13:26:32 -05:00
chrnx 22e77ee452 feat(metrics): declare the package and what it refuses to label
The README carries the cardinality rule up front: label on route, which the
route table bounds, never on name, which nothing bounds. That is the mistake
issue #65 was filed for and the one a collector makes by default.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-18 13:25:48 -05:00
chrnx f72c391646 test(rate-limit): measure that close() lets the process exit
Rule 7 says nothing a plugin opens outlives close(), and the only portable probe
is a process: a leaked interval keeps all three runtimes alive, a cleared one
lets each exit in well under a second.

Verified the test fails with onShutdown removed — it reports the process still
alive after 2s — because a leak test that passes while leaking is worth nothing.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-18 13:25:17 -05:00
chrnx 8ac46fed61 feat(rate-limit): publish the limiter as a named plugin
Extracted from patitas-peludas onto the object contract. The node now takes the
name it provides — the original registered 'rate-limit' while providing
'rateLimit', so two instances shared a node name and rule 2 could not hold.

onShutdown closes the store this plugin built. One passed in owns its own
lifecycle, and is closed only if it offers a close().

Every test that builds an app closes it, through a helper that says why: the
sweep timer is deliberately not unref'ed, so an app left open keeps the test
runner alive after its assertions have passed. That is the same behaviour the
exit test measures, so these exercise the shutdown path in passing.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-18 13:22:45 -05:00
chrnx 14ed9c38be feat(rate-limit): carry the error brand instead of extending core
The original extended core's HttpError, which is a value import and makes the
published plugin need core at run time. The brand is a registry-wide symbol, so
core renders the 429 without this package depending on it, and it survives two
copies of core in one tree where instanceof would not.

The fields asserted here are exactly the ones HttpErrorLike declares. That core
really renders them is proven end to end in the limiter's own tests, which read
a 429 and its Retry-After back out of app.fetch.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-18 13:18:49 -05:00
chrnx 66afb59103 feat(rate-limit): sweep expired windows instead of walking the map
hit() called evictExpired on every new or expired key, which is a full walk of
the map — O(N^2) over N callers, and a client rotating addresses drives it on
purpose. A timer armed on the first hit does the same work off the hot path.

It is not unref'ed, deliberately: the timer holds the process open so that
failing to release it fails the exit test rather than leaking quietly.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-18 13:18:26 -05:00
chrnx b15ce29315 feat(rate-limit): declare the package and the runtimes it claims
No workerd: the default store counts per isolate, and an edge deployment has
many, so the limit it would enforce is not the one configured. The README says
so rather than leaving someone to find out.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-18 13:17:45 -05:00
chrnx 74f297dafd test: pick the child-process command from the host runtime
The exit test spawns a probe and asserts it dies on its own, and the contract
files run unchanged on three runtimes — so the argv has to be decided at run
time rather than written for Node and skipped elsewhere.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-18 13:17:12 -05:00
chrnx d8ffb09ddc Merge pull request 'feat: plugins workspace with @green-tea/jwt' (#1) from feature/scaffold-jwt into develop
CI / dco (push) Has been skipped
CI / build (push) Successful in 11s
CI / runtimes (bun) (push) Successful in 12s
CI / runtimes (deno) (push) Successful in 11s
CI / runtimes (edge) (push) Successful in 10s
2026-09-18 04:20:47 +00:00
chrnx 7be37f5184 ci: gate every package on Gitea
CI / dco (pull_request) Successful in 3s
CI / build (pull_request) Successful in 11s
CI / runtimes (bun) (pull_request) Successful in 10s
CI / runtimes (deno) (pull_request) Successful in 11s
CI / runtimes (edge) (pull_request) Successful in 8s
Lint, format, complexity, typecheck and the Node suite on the engines floor,
then Deno and Bun for the packages that declare them. Gitea only until core
comes from npm, because the version these packages build against lives on
Verdaccio.

The JSR dry-run is kept rather than deferred: it passes locally on Deno 2.9.6,
because `nodeModulesDir: manual` resolves core from the tree `npm ci` installed,
so JSR's checker never needs that version to exist on npm.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-17 23:18:22 -05:00
chrnx 1c0b6bde91 feat(jwt): load signing keys at boot as a named plugin
Extracted from patitas-peludas onto the object plugin contract. Core is a type
import only, so installing the plugin never drags in a second core or a version
warning; a bad key still fails boot, which the contract tests now pin.

The extraction moves from jose 5 to jose 6, and that is not a version bump: jose
6 refuses a private CryptoKey in jwtVerify, where jose 5 accepted one and derived
the public half itself. The original keeps a single key per signer and verifies
with the key it signed with, which works on 5 and throws
"CryptoKey instances must be of type public" on 6 — for every asymmetric
algorithm, so ES*, RS*, PS* and EdDSA alike. Symmetric keys are unaffected, which
is exactly why one HS256 test would have shipped it.

importJWKKey now imports the key twice for an asymmetric pair: as given, to sign
with, and with the private fields stripped, to verify with. A symmetric key has
no public half, so it keeps one secret for both. The round-trip is covered per
algorithm family rather than once, because one algorithm is not coverage — it is
the gap the defect lived in.

The get() helper in the contract tests is generic in its body: Response.json()
is typed Promise<unknown>, so reaching into the payload did not typecheck.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-17 23:11:55 -05:00
chrnx 42a2f490e8 test: check each package against the plugin convention
Rules 8 and 9 are the two a reviewer cannot see from a diff: where core sits in
package.json, and whether engines, the README table and JSR still agree. A
static test makes a drift fail the build instead of reaching a user.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-17 23:02:12 -05:00
chrnx efffaebb96 build: npm and Deno workspace with core's gates
Same lint, format and complexity gates as core, plus a lint rule that keeps
core a types-only import in plugin sources. Runtime suites are chosen from each
package's engines, so declaring a runtime is what puts a package under its test.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-17 23:00:49 -05:00
55 changed files with 5990 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
+98
View File
@@ -0,0 +1,98 @@
name: Release → JSR
# Publishes the workspace to JSR. Runs on GITHUB ONLY, on a `release-*` tag.
#
# **The tag is a date, not a version.** `release-26.9.23` says when, and the release body says what
# moved. A version-shaped tag would be a lie here: three packages carry three independent versions,
# so `plugins-v26.9.0` would match none of them and invite exactly the confusion of reading it as
# `@green-tea/jwt@26.9.0`.
#
# Tag-driven rather than push-driven, unlike the example JSR's own setup page offers. That example
# publishes on every push to `main`, which for this repository means every promotion publishes — and
# a JSR version can never be replaced or removed, so a distracted merge would burn a version number
# forever. A tag is a decision; a merge is not.
#
# Publishing all three at once is safe, and this is the fact the whole design rests on: `deno publish`
# queries the registry per package and drops the ones already there, logging
# `Warning: Skipping, already published` for each. If every version is already published it prints
# `Success: All packages are already published` and exits 0. So a tag cut after changing one package
# publishes that one and leaves the others alone, with no per-package logic here.
# (denoland/deno, cli/tools/publish/mod.rs — `filter_out_published_packages`.)
on:
push:
tags: ['release-*']
jobs:
publish:
if: ${{ github.server_url == 'https://github.com' }}
runs-on: ubuntu-latest
permissions:
id-token: write # OIDC — this is what publishes, and what earns provenance
contents: write # create the GitHub release for this tag
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: '22'
- uses: denoland/setup-deno@v2
with:
deno-version: v2.x
# Both runtimes, because the gates below run both suites. `ci.yml` installs these one per
# matrix entry; here every suite runs in the same job, so both have to be present. Leaving
# bun out does not skip its suite — `scripts/run-runtime.mjs` spawns `bun`, gets ENOENT, and
# `process.exit(status ?? 1)` turns that into a failure that aborts the release.
- uses: oven-sh/setup-bun@v2
- run: npm ci
# The same gates CI runs. They ran on `main` already, and they run again here because this is
# the last moment they can still change the outcome: after the publish there is no amending a
# version, only publishing another one.
- run: npm run lint
- run: npm run format:check
- run: npm run typecheck
- run: npm run complexity:check
- run: npm test
- run: npm run test:deno
- run: npm run test:bun
- run: npm run test:edge
# Before the publish, on purpose. This reports which versions the tag would ship and refuses
# when one has no CHANGELOG entry — a package whose own changelog says it was never released
# is not something to discover afterwards, because afterwards is permanent.
- name: Every version about to ship has a changelog entry
run: node scripts/release.mjs --check
# JSR checks things no other gate does — slow types, module analysis — and learning about them
# mid-publish leaves a tag half-shipped.
- run: deno publish --dry-run
# No token: OIDC exchanges the workflow's id-token, which is also what attaches provenance.
# `tee` because the release body is built from what this actually did rather than from a guess
# about what it would do.
#
# Two details in this one line, both of which produce a *silently wrong* release when missed:
#
# `shell: bash` — the default shell here is `bash -e`, without `pipefail`, so a pipeline
# reports the exit status of its LAST command. That is `tee`, which always
# succeeds. A failed publish would have been reported as a green step, and
# a GitHub release created for it. Naming the shell gets `-eo pipefail`.
#
# `2>&1` — deno's logger is env_logger, whose default target is stderr, so every
# "Successfully published" line goes there. Measured: a publish writes 0
# lines to stdout and all of them to stderr. Without this the log is empty
# and the release notes say nothing shipped while three packages did.
- name: Publish
shell: bash
run: deno publish 2>&1 | tee /tmp/publish.log
- name: Release notes
run: node scripts/release.mjs --notes /tmp/publish.log "$GITHUB_REF_NAME" > /tmp/notes.md
- name: GitHub release
env:
GH_TOKEN: ${{ github.token }}
run: |
gh release create "$GITHUB_REF_NAME" \
--title "$GITHUB_REF_NAME" \
--notes-file /tmp/notes.md \
--prerelease
+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"
}
}
+11
View File
@@ -0,0 +1,11 @@
# Changelog
## [26.9.0-beta.0] - 2026-09-23
### 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.
[26.9.0-beta.0]: https://jsr.io/@green-tea/jwt@26.9.0-beta.0
+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');
});
}
+12
View File
@@ -0,0 +1,12 @@
# Changelog
## [26.9.0-beta.0] - 2026-09-23
### 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.
[26.9.0-beta.0]: https://jsr.io/@green-tea/metrics@26.9.0-beta.0
+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');
});
+12
View File
@@ -0,0 +1,12 @@
# Changelog
## [26.9.0-beta.0] - 2026-09-23
### 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`.
[26.9.0-beta.0]: https://jsr.io/@green-tea/rate-limit@26.9.0-beta.0
+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();
+123
View File
@@ -0,0 +1,123 @@
// The default `keyOf` buckets callers by `ctx.ip`, so it is only as good as the address the serving
// path hands it. Node's `listen()` has always filled `ctx.ip` from the socket. `serveDeno` and
// `serveBun` left it as `''` until core #116 (merged in core #117), which put every caller in the
// one `'unknown'` bucket: the first client to reach `max` locked out everybody else.
//
// So this runs over a real socket on each runtime, with the plugin's default `keyOf`, rather than
// through `app.fetch` with a hand-written one — `app.fetch` has no peer, and a custom `keyOf` would
// test the test. Two clients reach one dual-stack listener, one over IPv4 and one over IPv6, which is
// the cheapest way to get two distinct peer addresses on one host.
//
// Against a core without #116 the Deno and Bun runs fail here, on purpose. Node is the control: its
// path never had the bug and must stay green.
import { strict as assert } from 'node:assert';
import { createServer } from 'node:net';
import type { AddressInfo } from 'node:net';
import { test } from 'node:test';
import { createApp, ctx, Get, Module, needs, Route } from '@green-tea/core';
import type { App } 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, @ctx() context: { ip?: string }) {
await limit('signin');
return { ip: context.ip };
}
}
@Module({ mountpoint: '/', controllers: [Probe] })
class ProbeModule {}
/** A running server, whichever helper started it. */
interface Served {
port: number;
close(): Promise<void>;
}
interface RuntimeGlobals {
Deno?: unknown;
Bun?: unknown;
}
/**
* Serves `app` on `hostname` through the helper this runtime actually uses in production.
*
* The adapters are imported lazily because each one only works on its own runtime. Node takes no
* hostname: `listen(port)` binds the unspecified address, which is dual-stack wherever IPv6 exists.
*/
async function serve(app: App, hostname: string): Promise<Served> {
const globals = globalThis as RuntimeGlobals;
if (globals.Deno) {
const { serveDeno } = await import('@green-tea/core/deno');
const server = await serveDeno(app, { hostname, port: 0, onListen: () => {} });
const { port } = (server as unknown as { addr: { port: number } }).addr;
return { port, close: () => server.close({ timeoutMs: 1_000 }) };
}
if (globals.Bun) {
const { serveBun } = await import('@green-tea/core/bun');
const server = await serveBun(app, { hostname, port: 0 });
return { port: server.port, close: () => server.close({ timeoutMs: 1_000 }) };
}
const server = await app.listen(0);
return { port: (server.address() as AddressInfo).port, close: () => app.close({ timeoutMs: 1_000 }) };
}
/** Whether this host can bind the IPv6 loopback at all; some CI containers cannot. */
function ipv6Available(): Promise<boolean> {
return new Promise((resolve) => {
const probe = createServer();
probe.once('error', () => resolve(false));
probe.listen(0, '::1', () => probe.close(() => resolve(true)));
});
}
test('two peers on different addresses get separate budgets on the real serving path', async (t) => {
// Without IPv6, the fallback is two IPv4 loopback addresses. Every 127/8 address answers on Linux,
// which is what CI runs; macOS configures only 127.0.0.1, so there the fallback cannot connect.
const ipv6 = await ipv6Available();
const [hostname, a, b] = ipv6 ? ['::', '127.0.0.1', '[::1]'] : ['0.0.0.0', '127.0.0.1', '127.0.0.2'];
if (!ipv6) t.diagnostic('no IPv6 loopback: falling back to 127.0.0.1 and 127.0.0.2 (Linux only)');
const app = createApp({
modules: [ProbeModule],
plugins: [rateLimit({ rules: { signin: { windowMs: 60_000, max: 1, message: 'too many' } } })],
});
const server = await serve(app, hostname);
const hit = (host: string) => fetch(`http://${host}:${server.port}/probe`);
try {
const first = await hit(a);
assert.equal(first.status, 200);
const { ip: ipA } = (await first.json()) as { ip?: string };
assert.equal((await hit(a)).status, 429, 'client A was not limited at max: 1');
const other = await hit(b);
const body = (await other.text()) || '(empty body)';
// Checked before B's status so a regression names its cause: an empty `ctx.ip` is what folds both
// clients into one bucket, and the 429 that follows is only its symptom.
assert.ok(ipA, `ctx.ip was empty for client A on this serving path: ${JSON.stringify(ipA)}`);
assert.equal(other.status, 200, `client B shared client A's bucket (ctx.ip ${JSON.stringify(ipA)}): ${body}`);
const { ip: ipB } = JSON.parse(body) as { ip?: string };
assert.ok(ipB, 'ctx.ip was empty for client B');
assert.notEqual(ipA, ipB, 'both clients reported the same ctx.ip');
} finally {
await server.close();
}
});
+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))`);
+148
View File
@@ -0,0 +1,148 @@
#!/usr/bin/env node
// Two jobs around a `deno publish`, both about the same thing: a JSR version can never be replaced
// or removed, so anything wrong has to be caught *before* the publish rather than reported after it.
//
// --check Which packages this tag would publish, and whether each has a CHANGELOG entry
// to match. Exits non-zero when one does not. Run this BEFORE publishing.
// --notes <log> The GitHub release body, built from what `deno publish` actually did.
//
// The order matters and is the whole point of splitting it in two. core's equivalent script runs
// after npm and JSR have already published, so a missing heading fails a release that has already
// shipped — a wart worth not inheriting.
import { readFileSync, readdirSync } from 'node:fs';
import { join } from 'node:path';
const ROOT = new URL('..', import.meta.url).pathname;
const PACKAGES = join(ROOT, 'packages');
const REPO = 'Expressive-Tea/green-tea-plugins';
/** Every workspace package, with the version its deno.json declares. */
function readPackages() {
return readdirSync(PACKAGES, { withFileTypes: true })
.filter((entry) => entry.isDirectory())
.map((entry) => {
const deno = JSON.parse(readFileSync(join(PACKAGES, entry.dir ?? entry.name, 'deno.json'), 'utf8'));
return { dir: entry.name, name: deno.name, version: deno.version };
});
}
/** Whether JSR already serves this exact version. A 404 for a package with no versions at all is
* not an error — it is what every one of these looks like until its first publish. */
async function isPublished({ name, version }) {
const [scope, pkg] = name.replace(/^@/, '').split('/');
const url = `https://api.jsr.io/scopes/${scope}/packages/${pkg}/versions/${version}`;
const response = await fetch(url, { headers: { accept: 'application/json' } });
if (response.status === 404) return false;
if (!response.ok) throw new Error(`${name}@${version}: ${url} answered ${response.status}`);
return true;
}
/** One version's section of a package CHANGELOG, heading excluded. */
function changelogSection(dir, version) {
const lines = readFileSync(join(PACKAGES, dir, 'CHANGELOG.md'), 'utf8').split('\n');
const start = lines.findIndex((line) => line.startsWith(`## [${version}]`));
if (start === -1) return null;
const rest = lines.slice(start + 1);
const end = rest.findIndex((line) => line.startsWith('## '));
return (end === -1 ? rest : rest.slice(0, end))
// Link reference definitions belong to the file, not to the entry. Nothing separates them from
// the last section, so without this they ride along into the release body as a stray line.
.filter((line) => !/^\[[^\]]+\]:\s/.test(line))
.join('\n')
.trim();
}
async function check() {
const packages = readPackages();
const published = await Promise.all(packages.map(isPublished));
const pending = packages.filter((_, i) => !published[i]);
if (pending.length === 0) {
console.log('Nothing to publish: every package version is already on JSR.');
return 0;
}
let missing = 0;
for (const pkg of pending) {
const section = changelogSection(pkg.dir, pkg.version);
if (section) {
console.log(` ok ${pkg.name}@${pkg.version}`);
} else {
// Deliberately an error rather than a warning. A version heading is a claim that the release
// exists, and publishing without one leaves a package on JSR that its own changelog says was
// never released — permanently, because the version cannot be replaced.
console.error(` MISSING ${pkg.name}@${pkg.version} has no "## [${pkg.version}]" in packages/${pkg.dir}/CHANGELOG.md`);
missing += 1;
}
}
packages
.filter((_, i) => published[i])
.forEach((pkg) => console.log(` skip ${pkg.name}@${pkg.version} (already on JSR)`));
return missing === 0 ? 0 : 1;
}
/** Parse what `deno publish` reported. Its own output is the only honest source for this: predicting
* it means duplicating the filtering Deno already did, and being wrong about it silently. */
function notes(logPath, tag) {
const log = readFileSync(logPath, 'utf8');
// Colour codes survive when a terminal is attached and vanish in CI. Strip either way.
const plain = log.replace(/\u001b\[[0-9;]*m/g, '');
const shipped = [...plain.matchAll(/Successfully published (@[^@\s]+\/[^@\s]+)@(\S+)/g)]
.map(([, name, version]) => ({ name, version }));
// A log carrying neither marker is not "nothing was published" — it is a log this script cannot
// read, and the two are indistinguishable from the text alone. Saying nothing shipped when three
// packages did is the worse failure, and it is silent, so refuse instead of guessing.
//
// This is not hypothetical: the first version of this workflow piped only stdout, while deno logs
// to stderr, so every successful release would have produced an empty log and a release body
// announcing that nothing happened.
if (shipped.length === 0 && !/already published/.test(plain)) {
throw new Error(
`${logPath} contains neither "Successfully published" nor "already published". ` +
'Either the publish did not run, or its output is not being captured — check that the step ' +
'redirects stderr (deno logs there) and that the pipeline uses pipefail.',
);
}
if (shipped.length === 0) {
return `No package versions were published by \`${tag}\` — every version in the workspace was already on JSR.`;
}
const byName = Object.fromEntries(readPackages().map((pkg) => [pkg.name, pkg.dir]));
const body = shipped.map(({ name, version }) => {
const dir = byName[name];
const section = (dir && changelogSection(dir, version)) || '_No changelog entry._';
const link = `https://github.com/${REPO}/blob/${tag}/packages/${dir}/CHANGELOG.md`;
return `## [${name}@${version}](https://jsr.io/${name}@${version})\n\n${section}\n\n[Full changelog](${link})`;
});
const untouched = readPackages().filter((pkg) => !shipped.some((s) => s.name === pkg.name));
const footer = untouched.length
? `\n\n---\n\nUnchanged in this release: ${untouched.map((p) => `\`${p.name}@${p.version}\``).join(', ')}.`
: '';
return `${body.join('\n\n')}${footer}`;
}
const [mode, arg] = process.argv.slice(2);
if (mode === '--check') {
process.exit(await check());
} else if (mode === '--notes') {
if (!arg) {
console.error('usage: release.mjs --notes <publish-log> [tag]');
process.exit(2);
}
console.log(notes(arg, process.argv[4] ?? 'main'));
} else {
console.error('usage: release.mjs --check | --notes <publish-log> [tag]');
process.exit(2);
}
+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"]
}