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

This commit was merged in pull request #1.
This commit is contained in:
chrnx committed 2026-09-18 04:20:47 +00:00
commit d8ffb09ddc
22 files changed
+3853

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
+88
View File
@@ -0,0 +1,88 @@
name: CI
# Gitea only, for now. Every package builds against @green-tea/core@26.9.0-beta.2, which exists on
# Verdaccio alone, and a GitHub runner cannot reach Verdaccio. Plan B3 moves the packages to a core on
# npm, removes these guards and adds the GitHub mirror; until then GitHub has no copy to run against.
on:
push:
branches: [develop, main]
pull_request:
branches: [develop, main]
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' && github.server_url != 'https://github.com'
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:
if: github.server_url != 'https://github.com'
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: '22'
- name: Authenticate to Verdaccio
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_AUTH }}
run: npm config set //npm.svc.zoit.services/:_authToken "$NODE_AUTH_TOKEN"
- run: npm ci
- run: npm run lint
- run: npm run format:check
- run: npm run complexity:check
- run: npm run typecheck
- run: npm test
# 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:
if: github.server_url != 'https://github.com'
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'
- name: Authenticate to Verdaccio
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_AUTH }}
run: npm config set //npm.svc.zoit.services/:_authToken "$NODE_AUTH_TOKEN"
- 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
+4
View File
@@ -0,0 +1,4 @@
# The @green-tea scope resolves from Verdaccio while core 26.9.0-beta.2 exists only there. The token is
# not here: it comes from ~/.npmrc locally and from the NPM_AUTH secret in CI. Plan B3 removes this line
# when the packages move to a core published on npm.
@green-tea:registry=https://npm.svc.zoit.services/
+8
View File
@@ -0,0 +1,8 @@
{
"printWidth": 120,
"tabWidth": 2,
"singleQuote": true,
"semi": true,
"trailingComma": "all",
"arrowParens": "always"
}
+9
View File
@@ -0,0 +1,9 @@
{
"workspace": ["./packages/jwt"],
"nodeModulesDir": "manual",
"compilerOptions": {
"experimentalDecorators": true,
"emitDecoratorMetadata": true
},
"lint": { "exclude": ["node_modules"] }
}
+43
View File
@@ -0,0 +1,43 @@
import js from '@eslint/js';
import tseslint from 'typescript-eslint';
import stylistic from '@stylistic/eslint-plugin';
export default tseslint.config(
{ 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',
},
},
);
+2941
View File
File diff suppressed because it is too large. Load diff
+33
View File
@@ -0,0 +1,33 @@
{
"name": "green-tea-plugins",
"private": true,
"license": "MIT",
"type": "module",
"workspaces": ["packages/*"],
"engines": {
"node": ">=22"
},
"scripts": {
"lint": "eslint --no-error-on-unmatched-pattern packages test",
"format": "prettier --write \"packages/*/{src,test}/**/*.ts\" \"test/**/*.ts\"",
"format:check": "prettier --check \"packages/*/{src,test}/**/*.ts\" \"test/**/*.ts\"",
"complexity:check": "node scripts/check-complexity.mjs",
"typecheck": "tsc --noEmit -p tsconfig.json",
"test": "node --import tsx --test test/*.test.ts packages/*/test/*.test.ts",
"test:deno": "node scripts/run-runtime.mjs deno",
"test:bun": "node scripts/run-runtime.mjs bun",
"test:edge": "node scripts/run-runtime.mjs workerd",
"prepare": "git config core.hooksPath .githooks || true"
},
"devDependencies": {
"@eslint/js": "^9.39.5",
"@stylistic/eslint-plugin": "^5.10.0",
"@types/node": "^22.0.0",
"cognitive-complexity-ts": "^0.8.2",
"eslint": "^9.39.5",
"prettier": "^3.9.6",
"tsx": "^4.23.5",
"typescript": "^5.5.0",
"typescript-eslint": "^8.70.0"
}
}
+9
View File
@@ -0,0 +1,9 @@
# Changelog
## [Unreleased]
### Added
- `jwt({ keys, provides? })`: loads each JWK file while providers boot and publishes a `JwtRegistry`
under `provides` (default `jwt`). `Signer` signs with `iat` and a random `jti`, and verifies issuer
and audience. `JwtRegistry.publicJwk(name)` returns a key's public half for a JWKS endpoint.
+46
View File
@@ -0,0 +1,46 @@
# @green-tea/jwt
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. |
## 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' } },
},
}),
],
});
```
```ts
@Post('/signin')
async signIn(@needs('jwt') jwt: JwtRegistry) {
return { token: await jwt.get('access').sign({ sub: user.id }) };
}
```
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"]
}
}
+28
View File
@@ -0,0 +1,28 @@
{
"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"
},
"exports": {
".": "./src/index.ts"
},
"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');
});
}
+53
View File
@@ -0,0 +1,53 @@
#!/usr/bin/env node
// Cognitive-complexity gate over every package's src. Fails (exit 1) if any named function exceeds the
// threshold. Same gate as core's, walked per package because ccts-json takes one directory.
import { execSync } from 'node:child_process';
import { existsSync, readdirSync } from 'node:fs';
const THRESHOLD = 25;
function scores(dir) {
try {
return execSync(`npx ccts-json ${dir}`, { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] });
} catch (error) {
return error.stdout?.toString() ?? '';
}
}
const offenders = [];
function walk(node, dir) {
if (!node || typeof node !== 'object') return;
if (node.kind === 'function' && node.name && node.score > THRESHOLD) {
offenders.push({ score: node.score, name: `${dir}: ${node.name}` });
}
for (const [key, value] of Object.entries(node)) {
if (key === 'inner' && Array.isArray(value)) value.forEach((child) => walk(child, dir));
else if (value && typeof value === 'object') walk(value, dir);
}
}
const dirs = readdirSync('packages')
.map((name) => `packages/${name}/src`)
.filter((dir) => existsSync(dir));
for (const dir of dirs) {
const raw = scores(dir);
if (!raw.trim()) {
console.error(`check-complexity: no output from ccts-json for ${dir}`);
process.exit(2);
}
walk(JSON.parse(raw), dir);
}
if (offenders.length) {
offenders.sort((a, b) => b.score - a.score);
console.error(`\n✖ cognitive complexity: ${offenders.length} function(s) over ${THRESHOLD}\n`);
for (const o of offenders) console.error(` ${String(o.score).padStart(4)} ${o.name}`);
console.error('\nExtract helpers to bring them under the threshold. The threshold is not raised.\n');
process.exit(1);
}
console.log(`✓ cognitive complexity: every function ≤ ${THRESHOLD} (${dirs.length} package(s))`);
+41
View File
@@ -0,0 +1,41 @@
#!/usr/bin/env node
// Runs the contract tests of every package whose `engines` declares <runtime>, on that runtime.
// `engines` is the one declaration (convention rule 9): a package that does not claim a runtime is not
// tested on it, and a package that claims one cannot skip it.
//
// Usage: node scripts/run-runtime.mjs <deno|bun|workerd>
import { spawnSync } from 'node:child_process';
import { readdirSync, readFileSync } from 'node:fs';
const COMMANDS = {
deno: (dirs) => ['deno', ['test', '--allow-all', '--no-check', ...dirs.map((dir) => `packages/${dir}/test/`)]],
bun: (dirs) => ['bun', ['test', ...dirs.map((dir) => `./packages/${dir}/test/`)]],
};
const runtime = process.argv[2];
if (!(runtime in COMMANDS) && runtime !== 'workerd') {
console.error('usage: run-runtime.mjs <deno|bun|workerd>');
process.exit(2);
}
const declares = (dir) => {
const { engines = {} } = JSON.parse(readFileSync(`packages/${dir}/package.json`, 'utf8'));
return runtime in engines;
};
const dirs = readdirSync('packages').filter(declares);
if (dirs.length === 0) {
console.log(`no package declares ${runtime}; nothing to run`);
process.exit(0);
}
// There is no workerd harness for plugins yet (spec, section 4). A package that declares workerd must
// not pass CI by having nothing run against it — copy core's test/edge harness first.
if (runtime === 'workerd') {
console.error(`${dirs.join(', ')} declare workerd, and there is no workerd harness yet.`);
process.exit(1);
}
const [command, args] = COMMANDS[runtime](dirs);
const { status } = spawnSync(command, args, { stdio: 'inherit' });
process.exit(status ?? 1);
+24
View File
@@ -0,0 +1,24 @@
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;
}
+100
View File
@@ -0,0 +1,100 @@
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;
engines?: Record<string, string>;
dependencies?: Record<string, string>;
devDependencies?: Record<string, string>;
peerDependencies?: Record<string, string>;
repository?: { type?: string; url?: string; directory?: string };
}
interface DenoJson {
name?: string;
version?: string;
imports?: Record<string, string>;
workspace?: 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}`));
});
}
+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"]
}