Repository navigation
Add ExtensionInstance.middleware: wrap semantics alongside authorize's gate - #129
Merged
Merged
Conversation
…s gate Adds a third, additive ExtensionInstance capability (src/extensions.ts): middleware(config, request, next). It attaches the same way authorize does (policies.extensions.<name> on a route, config the same validated per-route value authorize's requirement receives) but wraps the rest of the pipeline via next() instead of only gating before it, so an extension can run code both before and after the route's real handler and inspect/mutate its HandlerResult, or short-circuit by never calling next(). - src/extensions.ts: ExtensionInstance.middleware, documented with its next()-once, chain and non-interference-with-authorize contract. prepareExtensions now accepts an extension implementing authorize, middleware, or both for any route naming it via policies.extensions (previously authorize was required unconditionally). - src/runtime.ts: refactors "the rest of the pipeline for a route" (method contract, native reply, the native middleware: chain and handler, dispatched through the sandboxed/trusted engines exactly as today) into an explicit runPipeline() callable. Extensions naming middleware() on the route (route.extensionPolicyNames, the same order authorize already iterates) wrap it in declaration order, first-declared outermost, each next() reaching the next one and the innermost next() reaching runPipeline(). A short-circuit result (next() never called) gets exactly the one finishPolicies/extensionResponse pass authorize's own denial already gets; a result that flowed through next() has already had that applied at the bottom of the chain, so it is not reprocessed. next() is guarded to fire at most once per middleware() call, throwing otherwise. The pre-existing authorize() closure is fixed to skip an extension that does not implement authorize (previously assumed unconditionally, which broke as soon as a route could name a middleware-only extension) and now iterates route.extensionPolicyNames instead of recomputing the policy map. authorize's own call site and gate behavior are otherwise unchanged: it still runs first, before any middleware() wrapping begins. - Native `middleware:` YAML array, its schema and its sandboxed/trusted dispatch are completely untouched; this hook is purely additive at the policies.extensions layer, parallel to authorize, never nested inside it. - schemas/urlcode.schema.json: no change. policies.extensions.<name> already accepts a general-purpose object config, reused unchanged by middleware(). Docs: docs/EXTENSIONS.md adds "Wrapping a route: extension middleware" describing wrap vs. gate semantics precisely and how authorize/middleware compose; docs/SPIKE-CORE-LAYERING.md records that the middleware extraction's prior gap (no way to wrap-and-mutate a response) is now resolved, without rewriting the rest of that doc. llms-full.txt regenerated (npm run docs:llms). Tests: test/extensions.test.ts adds a synthetic middleware-capable extension fixture and five tests covering (a) a header added after next(), end-to-end against a real route; (b) a short-circuit that never calls next(), verified the wrapped function handler never runs; (c) two extensions both declaring middleware on one route, verified they nest in declaration order (headers and a call-order log); (d) one extension implementing both authorize and middleware, verified authorize's gate runs first and middleware's next() wraps everything after; (e) a route naming an extension may declare only middleware, only authorize, or neither (which now fails activation with an updated message). No existing authorize() test was weakened or removed. Verification: npm run typecheck, npm run lint, npm run check, full npm test (486 tests, 484 pass/2 pre-existing skips, 0 fail), npm run build and npm run test:package all green. Adversarial review (per task instructions): - Could a route end up with a middleware() hook running when the project didn't declare that extension? No: the chain is built only from route.extensionPolicyNames, which is derived from effectiveExtensionPolicies(document, route) — the project's own policies.extensions declarations (with profile/route merging and `false` removal already applied) — filtered to names prepareExtensions already validated have a declaration and a registered, activated instance. An extension never named by the route's own (possibly profile-merged) policy can never appear in that list. - Could next() be called more than once, or with different semantics than a single well-defined invocation? No: each middleware() call gets its own next closure with a local `called` flag; a second invocation throws before doing anything, matching the existing next()-once guard trusted-functions.ts already enforces for native middleware. Semantics are fixed and single: it always resolves to "the rest of the pipeline for this route" as of the moment that middleware() instance was reached in the chain — never re-runs, never a different pipeline on a second (rejected) call. Co-Authored-By: Claude Sonnet 5 <[email protected]> Claude-Session: https://claude.ai/code/session_018neC2tYKPxMPbzZf1wNctr
jimhoyd
added a commit
that referenced
this pull request
Sep 19, 2026
…cwd() (#130) urlcode-middleware needs to resolve project-relative middleware source files (the same way core's own functionFile()/router.ts resolves native function/middleware `source` entries) the same way core does, but ExtensionActivation ({origin, target, projectSha256, mounts}) had no project directory to resolve against. process.cwd() is not a substitute: --project/--host-file are independent, arbitrary paths, a server can be started from a different working directory than the project, and the JS API can load a project programmatically with no relationship to cwd() at all (confirmed by reading src/cli.ts/src/config.ts: loadDocument() takes an explicit `project` path and resolves it via realpath(), independent of cwd()). - src/extensions.ts: adds `root: string` to ExtensionActivation, documented as the project's resolved absolute directory, the same value functionFile() resolves native sources against, and explicitly not process.cwd(). - src/runtime.ts: passes loaded.root (already computed there, already used for compilePolicies and functionFile()) through to prepareExtensions' context, so it reaches every RuntimeExtension's activate(). - test/extensions.test.ts: asserts activate() receives the resolved project root, and adds a dedicated regression test that changes process.cwd() to an unrelated directory before activation and confirms the observed root is still the project's own resolved directory, not cwd(). - docs/SPIKE-CORE-LAYERING.md: records this as a second gap the middleware extraction surfaced (alongside the wrap-semantics gap #129 already closed), now resolved the same way. Verification: npm run typecheck, npm run lint, npm run check, full npm run verify (487 tests, 485 pass / 2 pre-existing skips, 0 fail). Claude-Session: https://claude.ai/code/session_018neC2tYKPxMPbzZf1wNctr Co-authored-by: Claude <[email protected]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Problem and change
docs/SPIKE-CORE-LAYERING.mdidentified a real gap blocking themiddlewareextraction: today's
RuntimeExtension/ExtensionInstancecontract(
src/extensions.ts) has mount ownership (handle) and a pre-handler gate(
authorize), but nothing that can wrap a route's handler the way nativemiddleware:does — run code before and after it, vianext(), inspectingor mutating the response. This adds that as a third, additive capability:
authorize(policies.extensions.<name>on a route,no
extension:mount required), reusing the same validated per-routeconfig/requirementvalue and the existingeffectiveExtensionPoliciesplumbing — no duplicated validation logic.
next()invokes the rest of the pipeline for that route: any otherextension
middleware()declared on the same route (chained inpolicies.extensionsdeclaration order, first-declared outermost), thenthe route's own native
middleware:chain and handler, dispatched throughthe existing sandboxed/trusted engines exactly as today. Skipping
next()short-circuits the rest of the pipeline, the same capability
authorizealready has.
authorizeis completely untouched: same call site, same gate-then-proceedbehavior, always runs first.
middleware()wraps everything after thatpoint, including the rest of the authorize-gated pipeline, when both are
declared (same or different extensions).
middleware:YAML, its schema and its sandboxed/trusted dispatch areunchanged; this is purely additive at the
policies.extensionslayer.src/runtime.ts: refactored "the rest of the pipeline for a route" (methodcontract, native reply, native
middleware:chain, handler dispatch) intoan explicit
runPipeline()callable that extensionmiddleware()hookswrap. A short-circuit result gets exactly the one
finishPolicies/extensionResponsepassauthorize's own denial already gets; a resultthat flowed through
next()already had that applied at the bottom of thechain, so it isn't reprocessed.
src/extensions.ts: a route naming an extension viapolicies.extensionsnow only requires that extension to implement
authorize,middleware, orboth (previously
authorizewas required unconditionally for any routenaming the extension in policies).
authorizedispatch closure in
src/runtime.tscalledentry.instance.authorize!(...)unconditionally for every extension a route names, which threw once a route
could legally name a middleware-only extension. It now skips extensions
that don't implement
authorize, and iterates the already-computedroute.extensionPolicyNamesinstead of recomputing the policy map.schemas/urlcode.schema.json: no change — confirmedpolicies.extensions.<name>already accepts a general-purpose objectconfig, reused unchanged by
middleware().docs/EXTENSIONS.mdadds "Wrapping a route: extension middleware"(wrap vs. gate semantics, chaining, composition with
authorize);docs/SPIKE-CORE-LAYERING.mdrecords the gap as resolved without rewritingthe rest of the doc.
docs/FRAMEWORK.mddoesn't enumerate extensioncapabilities, so it needed no change (checked).
llms-full.txtregenerated.Verification
npm run typecheck— greennpm run lint— greennpm run check— green (afternpm run docs:llmsto refreshllms-full.txt)npm test— 486 tests: 484 pass, 2 pre-existing skips (TLS, unrelated), 0 failnpm run build— greennpm run test:package— greenNew tests in
test/extensions.test.ts(synthetic middleware-capable extensionfixture): (a) a header added after
next(), end-to-end against a real route;(b) a short-circuit that never calls
next(), verified the wrappedfunctionhandler never actually runs (module-level counter unchanged); (c) two
extensions both declaring
middlewareon one route, verified they nest indeclaration order (call-order log + header order); (d) one extension
implementing both
authorizeandmiddleware, verifiedauthorizegatesfirst and
middleware'snext()wraps everything after; (e) a route namingan extension that implements neither now fails activation with an updated,
still-descriptive message. No existing
authorize()test was weakened orremoved.
Compatibility and security
Additive contract change to
src/extensions.ts, which is documented as"Trusted operator code only" — same trust boundary as
authorize/handletoday, nothing new is exposed to application/guest code, and native
function/middleware:guest execution (sandboxed or trusted-by-default) isuntouched.
Adversarial review (per task instructions):
Could a route end up with a
middleware()hook running when the projectdidn't declare that extension? No. The chain is built only from
route.extensionPolicyNames, itselfeffectiveExtensionPolicies(document, route)'s keys — the project's ownpolicies.extensionsdeclarations, withprofile/route-layer merging and
falseremoval already applied — furtherfiltered in
prepareExtensionsto names with an actual declaration and aregistered, activated instance. An extension the route's own (possibly
profile-merged) policy never names can never appear in that list, so it can
never be invoked.
Could
next()be called more than once, or with different semantics thana single well-defined invocation? No. Each
middleware()call gets itsown
nextclosure with a localcalledflag; a second invocation throws(
assert) before doing anything, matching the existing next()-once guardsrc/trusted-functions.tsalready enforces for native middleware. Itssemantics are fixed and single: it always resolves to "the rest of the
pipeline for this route" as of the moment that
middleware()instance wasreached in the chain — it never re-runs and is never a different pipeline
on a rejected second call.
Changes match the documented portable contract; docs/examples are updated where needed.
Relevant tests and package checks pass, or limitations are explained above.
No credentials, customer data or private project material are included.
Runtime/starter changes remain aligned where applicable (no starter changes needed; contract is operator-extension-only).
🤖 Generated with Claude Code
https://claude.ai/code/session_018neC2tYKPxMPbzZf1wNctr
Generated by Claude Code