diff --git a/deno.json b/deno.json index e0621d3..2a1b9db 100644 --- a/deno.json +++ b/deno.json @@ -1,5 +1,5 @@ { - "workspace": [], + "workspace": ["./packages/jwt"], "nodeModulesDir": "manual", "compilerOptions": { "experimentalDecorators": true, diff --git a/package-lock.json b/package-lock.json index a19c484..57a4435 100644 --- a/package-lock.json +++ b/package-lock.json @@ -610,6 +610,35 @@ "node": "^18.18.0 || ^20.9.0 || >=21.1.0" } }, + "node_modules/@green-tea/core": { + "version": "26.9.0-beta.2", + "resolved": "https://npm.svc.zoit.services/@green-tea/core/-/core-26.9.0-beta.2.tgz", + "integrity": "sha512-7np7bK5bG1M+bYPDA8YH4jlO3z2EHpuR0Ou8uFi4ywTFFCqHgtb6fmp4gBNHxPFTtFlxBvRHwj8DAHl7Y3b/Xg==", + "dev": true, + "license": "MIT", + "dependencies": { + "reflect-metadata": "0.2.2" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "busboy": "^1.6.0", + "ws": "^8.18.0" + }, + "peerDependenciesMeta": { + "busboy": { + "optional": true + }, + "ws": { + "optional": true + } + } + }, + "node_modules/@green-tea/jwt": { + "resolved": "packages/jwt", + "link": true + }, "node_modules/@humanfs/core": { "version": "0.19.2", "resolved": "https://registry.npmjs.org/@humanfs/core/-/core-0.19.2.tgz", @@ -1985,6 +2014,15 @@ "@pkgjs/parseargs": "^0.11.0" } }, + "node_modules/jose": { + "version": "6.2.12", + "resolved": "https://registry.npmjs.org/jose/-/jose-6.2.12.tgz", + "integrity": "sha512-9NiFmJEex0sy2Dk58j2UGBSHgUs2ypF9eZSu4L6vjOX3Dp96Sw1F3uL+H+D1sx02jZZdzUT0HgvCy59CuvXcWw==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/panva" + } + }, "node_modules/js-beautify": { "version": "1.15.4", "resolved": "https://registry.npmjs.org/js-beautify/-/js-beautify-1.15.4.tgz", @@ -2372,6 +2410,13 @@ "node": ">=6" } }, + "node_modules/reflect-metadata": { + "version": "0.2.2", + "resolved": "https://registry.npmjs.org/reflect-metadata/-/reflect-metadata-0.2.2.tgz", + "integrity": "sha512-urBwgfrvVP/eAyXx4hluJivBKzuEbSQs9rKWCrCkbSxNv8mxPcUZKeuoF3Uy4mJl3Lwprp6yy5/39VWigZ4K6Q==", + "dev": true, + "license": "Apache-2.0" + }, "node_modules/resolve-from": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-4.0.0.tgz", @@ -2875,6 +2920,22 @@ "funding": { "url": "https://github.com/sponsors/sindresorhus" } + }, + "packages/jwt": { + "name": "@green-tea/jwt", + "version": "26.9.0-beta.0", + "license": "MIT", + "dependencies": { + "jose": "^6.2.12" + }, + "devDependencies": { + "@green-tea/core": "26.9.0-beta.2" + }, + "engines": { + "bun": ">=1.3", + "deno": ">=2", + "node": ">=22" + } } } } diff --git a/packages/jwt/CHANGELOG.md b/packages/jwt/CHANGELOG.md new file mode 100644 index 0000000..760dc67 --- /dev/null +++ b/packages/jwt/CHANGELOG.md @@ -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. diff --git a/packages/jwt/README.md b/packages/jwt/README.md new file mode 100644 index 0000000..7993fe3 --- /dev/null +++ b/packages/jwt/README.md @@ -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. diff --git a/packages/jwt/deno.json b/packages/jwt/deno.json new file mode 100644 index 0000000..10f5cb3 --- /dev/null +++ b/packages/jwt/deno.json @@ -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"] + } +} diff --git a/packages/jwt/package.json b/packages/jwt/package.json new file mode 100644 index 0000000..520b986 --- /dev/null +++ b/packages/jwt/package.json @@ -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 ", + "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" + } +} diff --git a/test/workspace.test.ts b/test/workspace.test.ts new file mode 100644 index 0000000..5070eee --- /dev/null +++ b/test/workspace.test.ts @@ -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 = { Node: 'node', Deno: 'deno', Bun: 'bun', 'workerd (edge)': 'workerd' }; + +interface PackageJson { + name: string; + version: string; + engines?: Record; + dependencies?: Record; + devDependencies?: Record; + peerDependencies?: Record; + repository?: { type?: string; url?: string; directory?: string }; +} + +interface DenoJson { + name?: string; + version?: string; + imports?: Record; + workspace?: string[]; +} + +const readJson = (...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('packages', dir, 'package.json'); + const deno = readJson('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('deno.json').workspace?.includes(`./packages/${dir}`)); + }); +}