Skip to content

Add ExtensionInstance.middleware: wrap semantics alongside authorize's gate - #129

Merged
jimhoyd merged 1 commit into
mainfrom
claude/extension-middleware-hook
Sep 19, 2026
Merged

jimhoyd merged 1 commit into
mainfrom
claude/extension-middleware-hook

Conversation

@jimhoyd

@jimhoyd jimhoyd commented Sep 19, 2026

Copy link
Copy Markdown
Collaborator

Problem and change

docs/SPIKE-CORE-LAYERING.md identified a real gap blocking the middleware
extraction: today's RuntimeExtension/ExtensionInstance contract
(src/extensions.ts) has mount ownership (handle) and a pre-handler gate
(authorize), but nothing that can wrap a route's handler the way native
middleware: does — run code before and after it, via next(), inspecting
or mutating the response. This adds that as a third, additive capability:

middleware?(config: Readonly<Record<string, unknown>>, request: ExtensionRequest,
  next: () => Promise<HandlerResult>): HandlerResult | Promise<HandlerResult>;
  • Attached exactly like authorize (policies.extensions.<name> on a route,
    no extension: mount required), reusing the same validated per-route
    config/requirement value and the existing effectiveExtensionPolicies
    plumbing — no duplicated validation logic.
  • next() invokes the rest of the pipeline for that route: any other
    extension middleware() declared on the same route (chained in
    policies.extensions declaration order, first-declared outermost), then
    the route's own native middleware: chain and handler, dispatched through
    the existing sandboxed/trusted engines exactly as today. Skipping next()
    short-circuits the rest of the pipeline, the same capability authorize
    already has.
  • authorize is completely untouched: same call site, same gate-then-proceed
    behavior, always runs first. middleware() wraps everything after that
    point, including the rest of the authorize-gated pipeline, when both are
    declared (same or different extensions).
  • Native middleware: YAML, its schema and its sandboxed/trusted dispatch are
    unchanged; this is purely additive at the policies.extensions layer.
  • src/runtime.ts: refactored "the rest of the pipeline for a route" (method
    contract, native reply, native middleware: chain, handler dispatch) into
    an explicit runPipeline() callable that extension middleware() hooks
    wrap. A short-circuit result gets exactly the one finishPolicies/
    extensionResponse pass authorize's own denial already gets; a result
    that flowed through next() already had that applied at the bottom of the
    chain, so it isn't reprocessed.
  • src/extensions.ts: a route naming an extension via policies.extensions
    now only requires that extension to implement authorize, middleware, or
    both (previously authorize was required unconditionally for any route
    naming the extension in policies).
  • Fixed a latent bug the new capability exposed: the pre-existing authorize
    dispatch closure in src/runtime.ts called entry.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-computed
    route.extensionPolicyNames instead of recomputing the policy map.
  • schemas/urlcode.schema.json: no change — confirmed
    policies.extensions.<name> already accepts a general-purpose object
    config, reused unchanged by middleware().
  • Docs: docs/EXTENSIONS.md adds "Wrapping a route: extension middleware"
    (wrap vs. gate semantics, chaining, composition with authorize);
    docs/SPIKE-CORE-LAYERING.md records the gap as resolved without rewriting
    the rest of the doc. docs/FRAMEWORK.md doesn't enumerate extension
    capabilities, so it needed no change (checked). llms-full.txt regenerated.

Verification

  • npm run typecheck — green
  • npm run lint — green
  • npm run check — green (after npm run docs:llms to refresh llms-full.txt)
  • npm test — 486 tests: 484 pass, 2 pre-existing skips (TLS, unrelated), 0 fail
  • npm run build — green
  • npm run test:package — green

New tests in test/extensions.test.ts (synthetic middleware-capable extension
fixture): (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 actually runs (module-level counter unchanged); (c) two
extensions both declaring middleware on one route, verified they nest in
declaration order (call-order log + header order); (d) one extension
implementing both authorize and middleware, verified authorize gates
first and middleware's next() wraps everything after; (e) a route naming
an extension that implements neither now fails activation with an updated,
still-descriptive message. No existing authorize() test was weakened or
removed.

Compatibility and security

Additive contract change to src/extensions.ts, which is documented as
"Trusted operator code only" — same trust boundary as authorize/handle
today, nothing new is exposed to application/guest code, and native
function/middleware: guest execution (sandboxed or trusted-by-default) is
untouched.

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, itself effectiveExtensionPolicies(document, route)'s keys — the project's own policies.extensions declarations, with
    profile/route-layer merging and false removal already applied — further
    filtered in prepareExtensions to names with an actual declaration and a
    registered, 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 than
    a single well-defined invocation?
    No. Each middleware() call gets its
    own next closure with a local called flag; a second invocation throws
    (assert) before doing anything, matching the existing next()-once guard
    src/trusted-functions.ts already enforces for native middleware. Its
    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 — 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

…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
jimhoyd merged commit d8a1c2b into main Sep 19, 2026
10 checks passed
@jimhoyd
jimhoyd deleted the claude/extension-middleware-hook branch September 19, 2026 02:45
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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants