diff --git a/CHANGELOG.md b/CHANGELOG.md index 448564c..01e5ea7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -135,8 +135,23 @@ npm treats versions as semver and semver forbids leading zeros. `return` sees `204` instead; return a value to keep a `200`. A route with its own `@Transformer` is not affected. +- **`serveDeno()` and `serveBun()` reject an app created with `tls`.** Only Node's `listen()` ever + read `tls`; Deno and Bun serve through their runtime's own listener, so the same app came up as + plain HTTP there, without a word, for someone who had asked for HTTPS. Both adapters now reject + before they boot or bind. Migrate by dropping `tls` from `createApp` and configuring TLS on the + runtime's server, or terminating it at a proxy. An app without `tls` is unaffected. + ### Added +- **Every type a public signature uses can now be imported.** These were already in the + declarations, but nothing exported them, so code could call the API and could not name what it + passed or got back. From the root: `ModuleOptions`, `Ctor`, `BusLike`, `ArgSource`, + `GraphNodeView`, `GraphRouteView`, `StandardIssue`, `StandardResult`, and, for the experimental + mesh, `Link`, `ReconnectOptions`, `ManifestPolicy`, `SocketCtor`, `EventfulSocket`, `RouteEntry`, + `RemoteScopeNode`, `RemoteRoute`, `MeshControlDeps` and `ResponseShape`. From `/deno`: + `DenoServeOptions` and `DenoHttpServer`. From `/bun`: `BunServeOptions` and `BunServer`. From + `/edge`: `EdgeCtx`. All of them are additions, and nothing was renamed. + - **Health probes: `createApp({ health: true })`** (#115). Off by default. `GET`/`HEAD /__live__` answers `200 {"status":"ok"}` whenever the process answers. `/__ready__` answers `503 {"status":"booting"}` until `boot()` resolves, then `200 {"status":"ok"}` or diff --git a/README.md b/README.md index f04aaa1..fdec6dd 100644 --- a/README.md +++ b/README.md @@ -307,13 +307,13 @@ green-tea is **beta**, on the road to a release candidate. Express and Fastify h **What is not here:** no metrics registry, and **no OpenTelemetry exporter in core** — that is a separate package, because core has one runtime dependency and intends to keep it. A `traceparent` header is carried through untouched for an exporter to interpret; core implements no propagation spec. If your definition of production-ready includes shipping traces on day one, you are writing the exporter, and the stream it needs is the part that now exists. -**Runtimes differ in what they can offer.** Node ≥ 22, Deno, and Bun run everything. On the edge (Cloudflare Workers) there is no `app.listen()`, no filesystem — so `@Html` file/template modes and `static` serving are unavailable — and mesh does not run there at all (the teapot's secret comparison needs `node:crypto`'s `timingSafeEqual`, which `nodejs_compat` doesn't provide). Workers also require the `nodejs_compat` flag. With `compression`, core never encodes on the edge (Cloudflare does), and on Deno it runs zlib on the main thread, where Deno's own `automaticCompression` is the faster gzip. +**Runtimes differ in what they can offer.** Node ≥ 22, Deno, and Bun run everything. On the edge (Cloudflare Workers) there is no `app.listen()`, no filesystem — so `@Html` file/template modes and `static` serving are unavailable — and mesh does not run there at all (the teapot's secret comparison needs `node:crypto`'s `timingSafeEqual`, which `nodejs_compat` doesn't provide). Workers also require the `nodejs_compat` flag. Native TLS (`createApp({ tls })`) is Node's `listen()` only: `serveDeno()` and `serveBun()` reject an app that sets it rather than serve it as plain HTTP, so configure TLS on that runtime's server or at a proxy, as you would on the edge. With `compression`, core never encodes on the edge (Cloudflare does), and on Deno it runs zlib on the main thread, where Deno's own `automaticCompression` is the faster gzip. **mesh is alpha.** Distributed DI works, but discovery, load-balancing, and failover are not built, and its API and wire protocol may change between releases. It is gated behind an explicit opt-in — `createApp({ mesh, experimental: true })` — and `createApp` throws if you configure `mesh` without it. Don't ship mesh to production yet. **What a teapot exports: steps and routes, and nothing else.** A `@Provider` marked `export: true` fails the boot with an error that says why — a provider's value *is* the object it builds, a pool or a client or a `db`, and the mesh moves data, not objects. Export a `@Step` instead: it runs on the teapot, per request, and its result is what comes back. That is also what lets a teacup boot without its teapot: a remote step holds nothing between requests, so a teacup whose teapot never answers still starts once the `bootTimeoutMs` grace runs out — it warns and carries on. Be precise about what that means, because it is narrower than it sounds. A teapot that never connected sent no manifest, so nothing of it reached the graph: its routes **404** rather than `503`, since nothing was registered to match, and a local step that `@needs` one of its tokens **still fails the boot**, naming the teapot that did not connect. That failure is deliberate — it is the check that catches a typo in a token name, which no amount of waiting will fix. `503` is what you get from a teapot that connected and *later* died, where the link and its exports do exist. So what the change buys is the teacup that does *not* depend on that teapot starting anyway, rather than refusing over a dependency it never had. Keeping a *needed* token serving while its teapot is legitimately away is a known gap, not an oversight: the intended answer is a per-teapot `expects` list that declares what a teapot would export, which is planned and not built. -**What is settled, and what is still moving.** Present state, not a roadmap and not the API freeze — this is spare-time work by one person, and a schedule it cannot keep would cost more than it earns. The **graph is the settled part**: `needs`/`provides`, the order derived from them, and the boot-time failure when nothing provides a key have not changed since the beta hardening on 7 July, and `@Provider`, `@Step`, `@Route` and handler shapes still mean what they meant then — the decorator *set* has grown (`@Head`, `@Options`, `@Html`), which only ever adds. **Still moving:** the plugin API, which became `{ name, mount }` and gained `onShutdown`; the runtime entry points, where `serveDeno()` and `serveBun()` became async so they boot before they bind; `createApp`'s options, which gain fields most months; and the pipeline context, which in July became one object mutated in place rather than copied per step — so a step that captured it now sees later steps' writes. **Alpha:** mesh, above. Legacy decorators are a standing *external* risk rather than a green-tea one — see [Why legacy decorators](#why-legacy-decorators). The [matcha](https://github.com/Expressive-Tea/matcha) CLI ships from its own repository on its own version line, so nothing here speaks for it. +**What is settled, and what is frozen.** From RC.1 the public surface of the four entry points (`@green-tea/core`, `/deno`, `/bun`, `/edge`) is frozen. Until the stable release it only gains things, and nothing published in `26.9.0-beta.2` is removed. That covers the graph (`needs`/`provides`, the order derived from them, and the boot-time failure when nothing provides a key), the decorators and handler shapes, the plugin API (`{ name, mount }` with `onShutdown`), the runtime entry points (`serveDeno()` and `serveBun()` are async so they boot before they bind), `createApp`'s options, and the pipeline context, which is one object mutated in place, so a step sees what earlier steps wrote. **Outside the freeze:** mesh, marked `@experimental` and described above. Legacy decorators are a standing *external* risk rather than a green-tea one — see [Why legacy decorators](#why-legacy-decorators). The [matcha](https://github.com/Expressive-Tea/matcha) CLI ships from its own repository on its own version line, so nothing here speaks for it. ## Docs & development @@ -356,7 +356,8 @@ consumer would have received. - ✅ **HTML** — `@Html` (string / file / template), a built-in template engine with a bring-your-own `viewEngine` hook, and `static` serving. - ✅ **router completeness for beta** — safe constrained params, deterministic precedence, explicit/automatic HEAD and OPTIONS, strict path validation, and ambiguity checks across local and mesh routes. - ✅ **observability** — a correlated lifecycle event stream (request id, trace id, route pattern, per-step timings) and an injectable `Logger`. Exporters live outside core. -- **next** — API freeze + first stable release, mesh sub-specs (discovery, load-balancing, failover), official plugins, and a radix-tree matcher for very large route tables. +- ✅ **radix-tree matcher** — route lookup by index rather than a walk past every candidate, so a 200-route table costs about what a 10-route one does. +- **next** — first stable release, mesh sub-specs (discovery, load-balancing, failover), and official plugins. ## Versioning diff --git a/src/app/index.ts b/src/app/index.ts index 92ef455..e101189 100644 --- a/src/app/index.ts +++ b/src/app/index.ts @@ -45,7 +45,7 @@ import { getArgs, getHandlerNeeds, resolveArgs } from '../params'; import { buildOpenApi, type OpenApiInfo } from '../openapi'; import { connectLink, isPermanentRefusal, type Link } from '../mesh/link'; import { Rooms } from '../rooms'; -import type { TlsOptions, SecurityOptions, CorsOptions } from '../security'; +import { TLS_REQUESTED, type TlsOptions, type SecurityOptions, type CorsOptions } from '../security'; import { buildRemote, type RemoteRoute as TeacupRemoteRoute } from '../mesh/teacup'; import { buildManifest, @@ -533,6 +533,9 @@ export function createApp(opts: AppOptions): App { // `edgeHandler` calls this: on the edge core never encodes, whatever detection concluded. [MARK_EDGE]: edgeMarker(compression), + + // `serveDeno` and `serveBun` refuse an app that asked for TLS only Node's listener can give. + [TLS_REQUESTED]: Boolean(opts.tls), }); } diff --git a/src/bun.ts b/src/bun.ts index 905b666..b2d71d6 100644 --- a/src/bun.ts +++ b/src/bun.ts @@ -1,6 +1,7 @@ import { channel } from './channel'; import type { Channel } from './channel'; import type { App } from './app/types'; +import { refuseTls } from './security'; import { WS_MAX_MESSAGE_BYTES, DEFAULT_MAX_WS_MESSAGE_BYTES, @@ -32,7 +33,8 @@ interface BunWebSocketHandler { drain?(ws: BunServerWebSocket): void; error?(ws: BunServerWebSocket, error?: unknown): void; } -interface BunServer { +/** The part of the server `Bun.serve` returns that {@link BunServeResult} builds on. */ +export interface BunServer { port: number; // Returns a promise, verified on Bun 1.3 — the previous `void` here was simply wrong, and it // hid the fact that this is awaitable at all. @@ -53,14 +55,18 @@ export interface BunServeResult extends BunServer { */ close(options?: { timeoutMs?: number }): Promise; } -interface BunServeOptions { +interface BunNativeServeOptions { port?: number; hostname?: string; fetch(request: Request, server: BunServer): Response | Promise | undefined; websocket?: BunWebSocketHandler; } -type BunServeShortOptions = { port?: number; hostname?: string }; -declare const Bun: { serve(options: BunServeOptions): BunServer }; +/** Options for {@link serveBun}; passed through to `Bun.serve`. */ +export interface BunServeOptions { + port?: number; + hostname?: string; +} +declare const Bun: { serve(options: BunNativeServeOptions): BunServer }; /** Per-connection state stashed on ws.data between fetch (upgrade) and the open/message/close callbacks. */ interface BunConnData { @@ -104,7 +110,7 @@ function bunSocket(ws: BunServerWebSocket): WsSocket { * * **Boots before it binds**, which is why it is async — see the `await app.boot()` below. */ -export async function serveBun(app: App, options?: BunServeShortOptions): Promise { +export async function serveBun(app: App, options?: BunServeOptions): Promise { // The same gate `listen()` runs before it binds a socket, and for the same reason: resolve the // graph and run the provider factories here, so a missing key or an unreachable pool is a startup // failure rather than a 500 on every request. @@ -113,6 +119,7 @@ export async function serveBun(app: App, options?: BunServeShortOptions): Promis // the first request would fix the failure in place and the runtime would answer from it forever, // without ever reaching `onError`. This was documented as something the caller should remember to // do, which made the correct use of a core helper depend on reading a README. + refuseTls(app, 'serveBun'); await app.boot(); const server = Bun.serve({ diff --git a/src/channel.ts b/src/channel.ts index 302270d..435856e 100644 --- a/src/channel.ts +++ b/src/channel.ts @@ -118,13 +118,15 @@ function newSub(onReturn: () => void): Sub { * Creates a fan-out {@link Channel}. Values pushed are delivered to every active subscriber. * @param opts.buffer Per-subscriber queue cap; drops oldest when exceeded (default: unbounded). */ -export function channel(opts: { buffer?: number } = {}): TappableChannel { +export function channel(opts: { buffer?: number } = {}): Channel { const cap = opts.buffer ?? Infinity; const subs = new Set, 'iterator'>>(); let done = false; let closedFlag = false; - return { + // Public type stays `Channel` (as in beta.2): the tap is internal plumbing, found by `ws-core` + // through the symbol rather than through this signature. + const ch: TappableChannel = { get closed() { return closedFlag; }, @@ -161,4 +163,5 @@ export function channel(opts: { buffer?: number } = {}): TappableChannel { return () => subs.delete(sink); }, }; + return ch; } diff --git a/src/deno.ts b/src/deno.ts index 4abcc9f..4ee4bdf 100644 --- a/src/deno.ts +++ b/src/deno.ts @@ -1,4 +1,5 @@ import type { App } from './app/types'; +import { refuseTls } from './security'; import { beginDrain } from './http/health'; import { eventSocket, toWsRequest, upgradeSafely, type EventfulSocket } from './http/ws-adapter'; import { closeWithDeadline } from './http/shutdown'; @@ -12,7 +13,8 @@ interface WebSocket extends EventfulSocket { // Minimal ambient for the Deno globals we use — avoids a @types/deno devDep. // Mirrors the real Deno.serve / Deno.upgradeWebSocket signatures we call. -interface DenoServeOptions { +/** Options for {@link serveDeno}; passed through to `Deno.serve`. */ +export interface DenoServeOptions { port?: number; hostname?: string; signal?: AbortSignal; @@ -21,7 +23,8 @@ interface DenoServeOptions { interface DenoServeHandlerInfo { remoteAddr: { hostname: string; port: number; transport: string }; } -interface DenoHttpServer { +/** The part of the server `Deno.serve` returns that {@link DenoServer} builds on. */ +export interface DenoHttpServer { finished: Promise; shutdown(): Promise; } @@ -65,6 +68,7 @@ export async function serveDeno(app: App, options?: DenoServeOptions): Promise): void; } declare const WebSocketPair: { new (): { 0: EdgeWebSocket; 1: EdgeWebSocket } }; diff --git a/src/index.ts b/src/index.ts index d215580..774dea6 100644 --- a/src/index.ts +++ b/src/index.ts @@ -22,7 +22,7 @@ export type { App, AppOptions, InspectLine, Explain, ExplainNode, MeshConfig } f // Graph visualization export { toMermaid, toDOT } from './graph-viz'; -export type { GraphView } from './graph-viz'; +export type { GraphView, GraphNodeView, GraphRouteView } from './graph-viz'; export { buildOpenApi } from './openapi'; export type { OpenApiDoc, OpenApiInfo, OpenApiRoute } from './openapi'; @@ -48,7 +48,7 @@ export { Options, Html, } from './metadata'; -export type { Transport, HttpMethod, RouteDecorator, TransformerFn } from './metadata'; +export type { Transport, HttpMethod, RouteDecorator, TransformerFn, ModuleOptions, Ctor } from './metadata'; export type { Plugin, PluginApi, ScopeApi, ScopeNode } from './plugin'; export type { Hooks } from './app'; export type { TeardownFn } from './lifecycle'; @@ -79,7 +79,7 @@ export type { StepFn, CompiledFlow } from './flow'; // Parameter decorators export { needs, ctx, param, query, body, headers, header, cookies, cookie, inbound, abort } from './params'; -export type { Query, RequestHeaders, Headers, Context, ArgSpec, ArgDecorator } from './params'; +export type { Query, RequestHeaders, Headers, Context, ArgSpec, ArgSource, ArgDecorator } from './params'; // Cookies export { setCookie, parseCookies } from './cookies'; @@ -87,7 +87,7 @@ export type { CookieOptions } from './cookies'; // Observability export { createDefaultLogger, logRequests, withConsoleFallback } from './logger'; -export type { Logger, LogLevel, LogFields } from './logger'; +export type { Logger, LogLevel, LogFields, BusLike } from './logger'; // Streaming export { channel, isAsyncIterable } from './channel'; @@ -103,10 +103,15 @@ export type { CompressionOptions } from './http/compression'; export { UNMATCHED_ROUTE } from './http/core'; export type { TlsOptions, CorsOptions, SecurityOptions } from './security'; export type { UploadedFile, MultipartBody } from './multipart'; -export type { StandardSchemaV1 } from './standard-schema'; +export type { StandardSchemaV1, StandardIssue, StandardResult } from './standard-schema'; // Mesh — experimental (`createApp({ experimental: true })`): outside the API freeze, may change in a minor. export { connectLink } from './mesh/link'; export { buildRemote, envelopeFrom } from './mesh/teacup'; export { buildManifest, createMeshControl, MESH_CONTROL_PATH } from './mesh/teapot'; -export type { Manifest, RequestEnvelope, Frame } from './mesh/protocol'; +export type { Manifest, RequestEnvelope, Frame, RouteEntry } from './mesh/protocol'; +export type { Link, ManifestPolicy, ReconnectOptions } from './mesh/link'; +export type { SocketCtor, EventfulSocket } from './http/ws-adapter'; +export type { RemoteScopeNode, RemoteRoute } from './mesh/teacup'; +export type { MeshControlDeps } from './mesh/teapot'; +export type { ResponseShape } from './pipeline'; diff --git a/src/logger.ts b/src/logger.ts index 81e2344..1bea8d1 100644 --- a/src/logger.ts +++ b/src/logger.ts @@ -129,7 +129,8 @@ export function logRequests(bus: BusLike, logger: Logger): () => void { } /** The slice of {@link Bus} request logging needs — `on` only, matching what a plugin is handed. */ -interface BusLike { +/** The part of a {@link Bus} that {@link logRequests} subscribes to. */ +export interface BusLike { on(event: 'request:end' | 'request:failed', listener: (payload: EventPayload) => void): () => void; } diff --git a/src/params.ts b/src/params.ts index 3bfa2e7..887b4e9 100644 --- a/src/params.ts +++ b/src/params.ts @@ -16,7 +16,7 @@ export type Headers = RequestHeaders; /** Per-request bag that accumulates values produced by steps and providers. */ export type Context = Record; -type ArgSource = 'ctx' | 'needs' | 'params' | 'query' | 'body' | 'headers' | 'cookies' | 'inbound' | 'abort'; +export type ArgSource = 'ctx' | 'needs' | 'params' | 'query' | 'body' | 'headers' | 'cookies' | 'inbound' | 'abort'; /** Describes how a single handler parameter is sourced and (optionally) validated. */ export interface ArgSpec { index: number; diff --git a/src/security.ts b/src/security.ts index f36e809..45d866e 100644 --- a/src/security.ts +++ b/src/security.ts @@ -10,6 +10,23 @@ export interface TlsOptions { passphrase?: string; } +/** + * Set on an app created with `tls`, so the adapters that serve through their runtime's own listener + * (`serveDeno`, `serveBun`) can refuse it. Only Node's `listen()` reads `tls`; anywhere else it would + * serve plain HTTP to someone who asked for HTTPS. Symbol-keyed because it is adapter plumbing. + */ +export const TLS_REQUESTED: unique symbol = Symbol.for('green-tea.tls-requested'); + +/** Throws when `app` was created with `tls`, which `adapter` cannot honour. */ +export function refuseTls(app: object, adapter: string): void { + if ((app as { [TLS_REQUESTED]?: boolean })[TLS_REQUESTED]) { + throw new Error( + `${adapter} does not support createApp({ tls }); it would serve plain HTTP. ` + + `Configure TLS on the runtime's own server or terminate it at a proxy, and drop \`tls\`.`, + ); + } +} + /** CORS policy. `origins` may be a literal, list, `'*'`, or a predicate. */ export interface CorsOptions { origins: string | string[] | '*' | ((origin: string) => boolean); diff --git a/test/adapter-tls.test.ts b/test/adapter-tls.test.ts new file mode 100644 index 0000000..c3e288e --- /dev/null +++ b/test/adapter-tls.test.ts @@ -0,0 +1,30 @@ +import { afterEach, expect, it, vi } from 'vitest'; +import { createApp } from '../src'; +import { serveDeno } from '../src/deno'; +import { serveBun } from '../src/bun'; + +afterEach(() => { + vi.unstubAllGlobals(); +}); + +// Only Node's `listen()` reads `tls`. Deno and Bun serve through their own listener, so an app +// created with `tls` would come up as plain HTTP there — refused before anything binds. +it.each([ + ['serveDeno', 'Deno', serveDeno], + ['serveBun', 'Bun', serveBun], +] as const)('%s refuses an app created with tls', async (name, global, serve) => { + const listen = vi.fn(); + vi.stubGlobal(global, { serve: listen }); + const app = createApp({ modules: [], tls: { key: 'k', cert: 'c' } }); + + await expect(serve(app)).rejects.toThrow(`${name} does not support createApp({ tls })`); + expect(listen).not.toHaveBeenCalled(); +}); + +it('an app without tls is not refused', async () => { + const listen = vi.fn(() => ({ port: 0, stop: vi.fn() })); + vi.stubGlobal('Bun', { serve: listen }); + + await serveBun(createApp({ modules: [] })); + expect(listen).toHaveBeenCalledOnce(); +});