@hexagen-monaco/sync 0.5.2 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (104) hide show
  1. package/dist/cli.js +1191 -389
  2. package/dist/cli.js.map +1 -1
  3. package/dist/config.d.ts +7 -0
  4. package/dist/config.d.ts.map +1 -1
  5. package/dist/fs-utils.d.ts +13 -0
  6. package/dist/fs-utils.d.ts.map +1 -1
  7. package/dist/generators/apps-framework-templates.d.ts +2 -1
  8. package/dist/generators/apps-framework-templates.d.ts.map +1 -1
  9. package/dist/generators/apps.d.ts.map +1 -1
  10. package/dist/generators/architecture-files.d.ts.map +1 -1
  11. package/dist/generators/barrels/recursive.d.ts.map +1 -1
  12. package/dist/generators/cross-context.d.ts +5 -0
  13. package/dist/generators/cross-context.d.ts.map +1 -0
  14. package/dist/generators/eslint.d.ts +3 -1
  15. package/dist/generators/eslint.d.ts.map +1 -1
  16. package/dist/generators/layer-folders.d.ts.map +1 -1
  17. package/dist/generators/port-analyzer.d.ts +38 -4
  18. package/dist/generators/port-analyzer.d.ts.map +1 -1
  19. package/dist/generators/root-file-templates.d.ts +3 -3
  20. package/dist/generators/root-file-templates.d.ts.map +1 -1
  21. package/dist/generators/shared-kernel.d.ts +23 -0
  22. package/dist/generators/shared-kernel.d.ts.map +1 -0
  23. package/dist/generators/stubs.d.ts +13 -0
  24. package/dist/generators/stubs.d.ts.map +1 -1
  25. package/dist/index.js +950 -172
  26. package/dist/index.js.map +1 -1
  27. package/dist/scope-filter.d.ts +35 -0
  28. package/dist/scope-filter.d.ts.map +1 -0
  29. package/dist/sync-engine.d.ts.map +1 -1
  30. package/dist/templates/adobe-creative-production/manifest.json +2 -0
  31. package/dist/templates/adobe-express/manifest.json +2 -0
  32. package/dist/templates/adobe-firefly-composite/manifest.json +2 -0
  33. package/dist/templates/adobe-firefly-content-tagging/manifest.json +2 -0
  34. package/dist/templates/adobe-firefly-core/manifest.json +2 -0
  35. package/dist/templates/adobe-firefly-custom-models/manifest.json +2 -0
  36. package/dist/templates/adobe-firefly-generate/manifest.json +2 -0
  37. package/dist/templates/adobe-firefly-media/manifest.json +2 -0
  38. package/dist/templates/adobe-firefly-storage-azure/manifest.json +2 -0
  39. package/dist/templates/adobe-firefly-storage-gcs/manifest.json +2 -0
  40. package/dist/templates/adobe-firefly-storage-s3/manifest.json +2 -0
  41. package/dist/templates/adobe-firefly-upscale/manifest.json +2 -0
  42. package/dist/templates/adobe-illustrator/manifest.json +2 -0
  43. package/dist/templates/adobe-ims-spa/manifest.json +2 -0
  44. package/dist/templates/adobe-indesign/manifest.json +2 -0
  45. package/dist/templates/adobe-lightroom/manifest.json +2 -0
  46. package/dist/templates/adobe-photoshop/manifest.json +2 -0
  47. package/dist/templates/adobe-substance-3d/manifest.json +2 -0
  48. package/dist/templates/auth-mock/manifest.json +2 -0
  49. package/dist/templates/bedrock-agentcore-runtime/manifest.json +10 -2
  50. package/dist/templates/bedrock-agentcore-services/manifest.json +38 -9
  51. package/dist/templates/better-auth/manifest.json +2 -0
  52. package/dist/templates/bullmq/manifest.json +2 -0
  53. package/dist/templates/ci-github-actions/README.md +7 -0
  54. package/dist/templates/ci-github-actions/files/.github/dependabot.yml +16 -4
  55. package/dist/templates/ci-github-actions/files/.github/workflows/ci.yml +7 -3
  56. package/dist/templates/ci-github-actions/files/.github/workflows/preview.yml +20 -2
  57. package/dist/templates/ci-github-actions/manifest.json +26 -6
  58. package/dist/templates/clerk/manifest.json +2 -0
  59. package/dist/templates/design-system/manifest.json +14 -3
  60. package/dist/templates/docker/manifest.json +2 -0
  61. package/dist/templates/error-handling/manifest.json +2 -0
  62. package/dist/templates/eslint-no-console/manifest.json +2 -0
  63. package/dist/templates/github-oauth/manifest.json +2 -0
  64. package/dist/templates/google-oauth/manifest.json +2 -0
  65. package/dist/templates/langgraph/manifest.json +62 -15
  66. package/dist/templates/llm-adapter/manifest.json +2 -0
  67. package/dist/templates/magic-link/manifest.json +2 -0
  68. package/dist/templates/mcp-server/README.md +49 -0
  69. package/dist/templates/mcp-server/files/.env.mcp.example +6 -0
  70. package/dist/templates/mcp-server/files/.mcp.json.example +8 -0
  71. package/dist/templates/mcp-server/files/bin/cli.ts +15 -0
  72. package/dist/templates/mcp-server/files/src/infrastructure/mcp/prompts/example.prompt.ts +32 -0
  73. package/dist/templates/mcp-server/files/src/infrastructure/mcp/registry/register-all.ts +11 -0
  74. package/dist/templates/mcp-server/files/src/infrastructure/mcp/registry/tool-registry.test.ts +67 -0
  75. package/dist/templates/mcp-server/files/src/infrastructure/mcp/registry/tool-registry.ts +45 -0
  76. package/dist/templates/mcp-server/files/src/infrastructure/mcp/resources/example.resource.ts +28 -0
  77. package/dist/templates/mcp-server/files/src/infrastructure/mcp/sdk.ts +41 -0
  78. package/dist/templates/mcp-server/files/src/infrastructure/mcp/server.ts +52 -0
  79. package/dist/templates/mcp-server/files/src/infrastructure/mcp/tools/example.tool.test.ts +31 -0
  80. package/dist/templates/mcp-server/files/src/infrastructure/mcp/tools/example.tool.ts +74 -0
  81. package/dist/templates/mcp-server/files/src/infrastructure/mcp/transport/register-transports.ts +15 -0
  82. package/dist/templates/mcp-server/files/src/infrastructure/mcp/transport/stdio.ts +14 -0
  83. package/dist/templates/mcp-server/manifest.json +68 -0
  84. package/dist/templates/mcp-server-http/README.md +98 -0
  85. package/dist/templates/mcp-server-http/files/.env.mcp-http.example +22 -0
  86. package/dist/templates/mcp-server-http/files/src/infrastructure/mcp/auth/bearer.test.ts +54 -0
  87. package/dist/templates/mcp-server-http/files/src/infrastructure/mcp/auth/bearer.ts +49 -0
  88. package/dist/templates/mcp-server-http/files/src/infrastructure/mcp/auth/oauth.test.ts +50 -0
  89. package/dist/templates/mcp-server-http/files/src/infrastructure/mcp/auth/oauth.ts +53 -0
  90. package/dist/templates/mcp-server-http/files/src/infrastructure/mcp/guard.test.ts +75 -0
  91. package/dist/templates/mcp-server-http/files/src/infrastructure/mcp/guard.ts +26 -0
  92. package/dist/templates/mcp-server-http/files/src/infrastructure/mcp/transport/http.ts +94 -0
  93. package/dist/templates/mcp-server-http/files/src/infrastructure/mcp/transport/register-transports.ts +15 -0
  94. package/dist/templates/mcp-server-http/manifest.json +56 -0
  95. package/dist/templates/microsoft-entra/manifest.json +2 -0
  96. package/dist/templates/nextauth/manifest.json +2 -0
  97. package/dist/templates/observability/manifest.json +10 -2
  98. package/dist/templates/rate-limiting/manifest.json +2 -0
  99. package/dist/templates/shared-types/manifest.json +2 -0
  100. package/dist/templates/supabase/manifest.json +2 -0
  101. package/dist/templates/supabase-auth/manifest.json +2 -0
  102. package/dist/types/manifest/apps.d.ts +12 -1
  103. package/dist/types/manifest/apps.d.ts.map +1 -1
  104. package/package.json +1 -1
@@ -0,0 +1,14 @@
1
+ // @hexagen-server-only
2
+ import type { TransportFactory } from "../server.js";
3
+
4
+ /**
5
+ * stdio transport factory — the secure local default: the server runs as a
6
+ * subprocess of a trusted client (Claude Desktop/Code, an IDE), with no network
7
+ * surface. The SDK transport is dynamically imported (ADR-0010).
8
+ */
9
+ export const createStdioTransport: TransportFactory = async () => {
10
+ const { StdioServerTransport } = await import(
11
+ "@modelcontextprotocol/sdk/server/stdio.js"
12
+ );
13
+ return new StdioServerTransport();
14
+ };
@@ -0,0 +1,68 @@
1
+ {
2
+ "id": "mcp-server",
3
+ "name": "MCP Server (stdio)",
4
+ "description": "Expose the project's application use-cases as MCP tools over stdio — an inbound adapter with a static tool registry, a transport-factory seam, and a dynamic SDK import (ADR-0010).",
5
+ "provides": "platform.mcp",
6
+ "scope": "project",
7
+ "version": "1.0.0",
8
+ "requires": ["env-setup"],
9
+ "conflicts": [],
10
+ "branch": "feature/generator-template-mcp-server",
11
+ "questions": [
12
+ {
13
+ "id": "server_name",
14
+ "type": "text",
15
+ "prompt": "MCP server name advertised to clients?",
16
+ "default": "{projectName}"
17
+ },
18
+ {
19
+ "id": "resources",
20
+ "type": "boolean",
21
+ "prompt": "Scaffold MCP resources (read-only)?",
22
+ "default": false
23
+ },
24
+ {
25
+ "id": "prompts",
26
+ "type": "boolean",
27
+ "prompt": "Scaffold reusable MCP prompts?",
28
+ "default": false
29
+ }
30
+ ],
31
+ "envVars": ["MCP_SERVER_NAME", "MCP_TRANSPORT"],
32
+ "outputs": [
33
+ "src/infrastructure/mcp/sdk.ts",
34
+ "src/infrastructure/mcp/server.ts",
35
+ "src/infrastructure/mcp/transport/stdio.ts",
36
+ "src/infrastructure/mcp/transport/register-transports.ts",
37
+ "src/infrastructure/mcp/registry/tool-registry.ts",
38
+ "src/infrastructure/mcp/registry/register-all.ts",
39
+ "src/infrastructure/mcp/tools/example.tool.ts",
40
+ "src/infrastructure/mcp/tools/example.tool.test.ts",
41
+ "src/infrastructure/mcp/registry/tool-registry.test.ts",
42
+ "bin/cli.ts",
43
+ ".mcp.json.example",
44
+ ".env.mcp.example",
45
+ {
46
+ "path": "src/infrastructure/mcp/resources/example.resource.ts",
47
+ "when": {
48
+ "answer": "resources",
49
+ "equals": true
50
+ }
51
+ },
52
+ {
53
+ "path": "src/infrastructure/mcp/prompts/example.prompt.ts",
54
+ "when": {
55
+ "answer": "prompts",
56
+ "equals": true
57
+ }
58
+ }
59
+ ],
60
+ "checklist": [
61
+ "Install the SDK (there is no manifest deps field — this is the only channel): npm install @modelcontextprotocol/sdk",
62
+ "Set MCP_SERVER_NAME in .env (defaults to the project name).",
63
+ "Add a tool: copy src/infrastructure/mcp/tools/example.tool.ts, wrap your use-case, then add one import + registerTool(...) line in registry/register-all.ts.",
64
+ "Point your MCP client at the server using .mcp.json.example — it runs: npx tsx bin/cli.ts (.ts isn't executable by node directly; use tsx, or build and run node dist/bin/cli.js).",
65
+ "Verify with the inspector: npx @modelcontextprotocol/inspector npx tsx bin/cli.ts",
66
+ "For remote/HTTP access, install the mcp-server-http addon (always authenticated)."
67
+ ]
68
+ }
@@ -0,0 +1,98 @@
1
+ # Template: `mcp-server-http` (author / agent guide)
2
+
3
+ > Not emitted. This documents how the template is built so a future agent can
4
+ > extend it without re-deriving the design. The user-facing install steps live
5
+ > in `manifest.json`'s `checklist`.
6
+
7
+ HTTP-transport + auth addon for [`mcp-server`](../mcp-server/README.md). Splitting
8
+ HTTP out of the base does two things: it keeps the auth/transport prompt noise
9
+ out of stdio installs, and it makes the network transport **always
10
+ authenticated** — the unsafe `auth=none` combination is structurally excluded
11
+ (no such option) rather than rejected at prompt time.
12
+
13
+ ## Why this is a factory addon, not a `server.ts` rewrite
14
+
15
+ `docs/planning/generator-templates/18-mcp-server.md` (Template 2) predates the
16
+ base and describes re-emitting `server.ts` with an HTTP branch. **It is stale.**
17
+ The base shipped with the `registerTransport(factory)` seam its own Risk #4
18
+ asked for, so this addon uses the seam:
19
+
20
+ - **`server.ts` is untouched.** `startServer()` already dispatches on
21
+ `MCP_TRANSPORT` via the transport-factory registry.
22
+ - **`transport/register-transports.ts` is re-emitted** with both `stdio` and
23
+ `streamable-http` registrations — the seam's documented extension point. It is
24
+ a 3-line declarative file, so the overwrite's blast radius is minimal; a
25
+ user-edited copy is preserved as `.hexagen-update`.
26
+ - **The startup guard runs inside `createHttpTransport()`** (lazy), not in the
27
+ composition root — so stdio deployments pay nothing and importing the module
28
+ in a test never trips it.
29
+
30
+ ## Auth wiring (the `{auth}` interpolation)
31
+
32
+ `auth` is a select (`bearer` | `oauth`, no `none`). Only the chosen
33
+ implementation is emitted (gated outputs), and `http.ts` imports it via the
34
+ reserved-var seam: the source line
35
+
36
+ ```ts
37
+ import { authenticate } from "../auth/{auth}.js";
38
+ ```
39
+
40
+ interpolates to `../auth/bearer.js` or `../auth/oauth.js`. This is
41
+ install-time-fixed by design: only the selected strategy ships, so the unused
42
+ one is never a bundle/attack surface. `MCP_AUTH_MODE` does not switch the auth
43
+ _implementation_ (that is fixed at install via the gated file) — but it IS read
44
+ at startup by `guard.ts` (unset/`none` over HTTP → refuse to start). Changing the
45
+ actual mechanism means re-installing; if a runtime switch is ever required,
46
+ promote to a runtime auth registry mirroring the transport seam (the gated-file
47
+ structure does not block that).
48
+
49
+ Both `bearer.ts` and `oauth.ts` export `authenticate(req): Promise<boolean>`.
50
+ `bearer` does a constant-time token compare against `MCP_BEARER_TOKEN`. `oauth`
51
+ is a **fail-closed scaffold**: it denies all requests until you wire JWKS
52
+ verification (the `jose` snippet is in the file). A scaffold that returned `true`
53
+ would be dangerously misleading, so the default is deny.
54
+
55
+ Each module also exports **`assertConfigured()`**, called once at startup from the
56
+ HTTP factory (`http.ts`), which throws if the chosen mode's secret
57
+ (`MCP_BEARER_TOKEN` / `MCP_OAUTH_ISSUER_URL`) is unset — turning a silent
58
+ deny-all into a loud startup error. (The manifest's `envVars` intentionally lists
59
+ only the always-required `MCP_TRANSPORT`/`MCP_HTTP_PORT`/`MCP_AUTH_MODE`; the
60
+ secrets are conditional on `auth`, so listing both would make
61
+ `validate-templates` flag the unused mode's secret. A schema for conditional env
62
+ vars would be the proper static fix — an engine follow-up, not this addon.)
63
+
64
+ ## Deliberate deviations from the planning doc
65
+
66
+ - **`server.ts` is not re-emitted** (seam, above).
67
+ - **`MCP_ALLOWED_TOOLS` is documented but NOT enforced.** Tool-level
68
+ allowlisting filters tool dispatch, which lives in the base tool registry and
69
+ applies to every transport — it does not belong in a transport addon. The env
70
+ var is reserved with a loud "not yet enforced" note; enforcing it is a base
71
+ follow-up.
72
+
73
+ ## Files
74
+
75
+ | Output | Notes |
76
+ | ---------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------- |
77
+ | `transport/http.ts` | StreamableHTTP factory (`StreamableHTTPServerTransport`, dynamic import, stateless); guards, then authenticates each request before `handleRequest` |
78
+ | `transport/register-transports.ts` | **re-emit** — registers stdio + streamable-http |
79
+ | `guard.ts` | `assertSafeTransport` — refuses streamable-http without an auth mode |
80
+ | `auth/bearer.ts` / `auth/oauth.ts` | gated on `auth`; `http.ts` imports the chosen one via `{auth}` |
81
+ | `*.test.ts` (guard, bearer, oauth) | `node:test`; pattern-gated behind `--with-tests` (`99-gap-analysis.md`) |
82
+ | `.env.mcp-http.example` | `MCP_HTTP_PORT`/`MCP_AUTH_MODE` seeded from the answers |
83
+
84
+ ## SDK
85
+
86
+ `@modelcontextprotocol/sdk` **v1** — `server/streamableHttp.js` →
87
+ `StreamableHTTPServerTransport` (verified against the installed `1.29.0`, not
88
+ external docs; the repo's own server is stdio-only so there was no in-repo
89
+ ground truth for the HTTP subpath). Dynamically imported per ADR-0010.
90
+
91
+ ## Verify
92
+
93
+ ```bash
94
+ # emit shape (this repo)
95
+ yarn --cwd packages/template-engine test
96
+ # runtime (a generated project, SDK installed)
97
+ MCP_TRANSPORT=streamable-http MCP_AUTH_MODE=bearer MCP_BEARER_TOKEN=dev npx tsx bin/cli.ts
98
+ ```
@@ -0,0 +1,22 @@
1
+ # ─────────────────────────────────────────────────────────────────────────────
2
+ # MCP server — HTTP transport (added by mcp-server-http)
3
+ # Overrides the stdio defaults in .env.mcp.example. The server REFUSES TO START
4
+ # with streamable-http unless MCP_AUTH_MODE is bearer|oauth (see guard.ts).
5
+ # ─────────────────────────────────────────────────────────────────────────────
6
+ MCP_TRANSPORT=streamable-http
7
+ MCP_HTTP_PORT={http_port}
8
+
9
+ # Auth mode (chosen at install): bearer | oauth — there is no "none", HTTP is
10
+ # always authenticated.
11
+ MCP_AUTH_MODE={auth}
12
+
13
+ # bearer: the shared secret clients send as `Authorization: Bearer <token>`.
14
+ MCP_BEARER_TOKEN=
15
+
16
+ # oauth: your OAuth issuer base URL; wire token verification in auth/oauth.ts.
17
+ MCP_OAUTH_ISSUER_URL=
18
+
19
+ # Reserved — NOT YET ENFORCED. A comma-separated tool allowlist. Tool-level
20
+ # allowlisting is a cross-transport concern slated for the base tool registry;
21
+ # do not rely on this for access control in this version.
22
+ MCP_ALLOWED_TOOLS=
@@ -0,0 +1,54 @@
1
+ import { describe, it, afterEach } from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import type { IncomingMessage } from "node:http";
4
+ import { authenticate, assertConfigured } from "./bearer.js";
5
+
6
+ function reqWith(authorization?: string): IncomingMessage {
7
+ return {
8
+ headers: authorization ? { authorization } : {},
9
+ } as IncomingMessage;
10
+ }
11
+
12
+ describe("bearer authenticate", () => {
13
+ const original = process.env.MCP_BEARER_TOKEN;
14
+ afterEach(() => {
15
+ if (original === undefined) delete process.env.MCP_BEARER_TOKEN;
16
+ else process.env.MCP_BEARER_TOKEN = original;
17
+ });
18
+
19
+ it("denies when MCP_BEARER_TOKEN is unset (fail closed)", async () => {
20
+ delete process.env.MCP_BEARER_TOKEN;
21
+ assert.equal(await authenticate(reqWith("Bearer anything")), false);
22
+ });
23
+
24
+ it("denies a missing, prefix-less, or wrong token", async () => {
25
+ process.env.MCP_BEARER_TOKEN = "s3cret";
26
+ assert.equal(await authenticate(reqWith(undefined)), false);
27
+ assert.equal(await authenticate(reqWith("s3cret")), false); // no "Bearer " prefix
28
+ assert.equal(await authenticate(reqWith("Bearer wrong")), false);
29
+ });
30
+
31
+ it("allows the correct token (scheme is case-insensitive, RFC 7235)", async () => {
32
+ process.env.MCP_BEARER_TOKEN = "s3cret";
33
+ assert.equal(await authenticate(reqWith("Bearer s3cret")), true);
34
+ assert.equal(await authenticate(reqWith("bearer s3cret")), true);
35
+ });
36
+ });
37
+
38
+ describe("bearer assertConfigured", () => {
39
+ const original = process.env.MCP_BEARER_TOKEN;
40
+ afterEach(() => {
41
+ if (original === undefined) delete process.env.MCP_BEARER_TOKEN;
42
+ else process.env.MCP_BEARER_TOKEN = original;
43
+ });
44
+
45
+ it("throws at startup when MCP_BEARER_TOKEN is unset", () => {
46
+ delete process.env.MCP_BEARER_TOKEN;
47
+ assert.throws(() => assertConfigured(), /MCP_BEARER_TOKEN/);
48
+ });
49
+
50
+ it("passes when MCP_BEARER_TOKEN is set", () => {
51
+ process.env.MCP_BEARER_TOKEN = "s3cret";
52
+ assert.doesNotThrow(() => assertConfigured());
53
+ });
54
+ });
@@ -0,0 +1,49 @@
1
+ // @hexagen-server-only
2
+ import { timingSafeEqual } from "node:crypto";
3
+ import type { IncomingMessage } from "node:http";
4
+
5
+ /**
6
+ * Bearer-token authentication for the HTTP transport. Compares the
7
+ * `Authorization: Bearer <token>` header against `MCP_BEARER_TOKEN` with a
8
+ * constant-time comparison. Fail-closed: denies when the env token is unset, so
9
+ * a misconfigured deployment rejects every request rather than allowing them.
10
+ */
11
+ export async function authenticate(req: IncomingMessage): Promise<boolean> {
12
+ const expected = process.env.MCP_BEARER_TOKEN;
13
+ if (!expected) return false; // fail closed — no token configured = deny all
14
+
15
+ const header = req.headers.authorization;
16
+ const value = Array.isArray(header) ? header[0] : header;
17
+ // RFC 7235 §2.1: the auth-scheme name is case-insensitive ("Bearer"/"bearer"/…).
18
+ if (!value || !/^Bearer /i.test(value)) return false;
19
+
20
+ const provided = value.slice(7).trim(); // "Bearer ".length === 7
21
+ return constantTimeEqual(provided, expected);
22
+ }
23
+
24
+ /**
25
+ * Startup configuration check (called once from the HTTP transport factory): the
26
+ * bearer transport is unusable without a token — an unset token fail-closes and
27
+ * silently denies every request. Throw at startup so a missing secret is a loud,
28
+ * immediate error rather than a confusing wall of 401s.
29
+ */
30
+ export function assertConfigured(): void {
31
+ if (!process.env.MCP_BEARER_TOKEN) {
32
+ throw new Error(
33
+ "Refusing to start: MCP_AUTH_MODE=bearer requires MCP_BEARER_TOKEN to be set " +
34
+ "(an unset token denies every request).",
35
+ );
36
+ }
37
+ }
38
+
39
+ /**
40
+ * Length-checked constant-time string compare. `timingSafeEqual` throws on a
41
+ * length mismatch, so the length guard runs first (token length is not
42
+ * meaningfully secret); equal-length tokens are then compared without an
43
+ * early-exit timing side channel.
44
+ */
45
+ function constantTimeEqual(a: string, b: string): boolean {
46
+ const aBuf = Buffer.from(a, "utf8");
47
+ const bBuf = Buffer.from(b, "utf8");
48
+ return aBuf.length === bBuf.length && timingSafeEqual(aBuf, bBuf);
49
+ }
@@ -0,0 +1,50 @@
1
+ import { describe, it, afterEach } from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import type { IncomingMessage } from "node:http";
4
+ import { authenticate, assertConfigured } from "./oauth.js";
5
+
6
+ function reqWith(authorization?: string): IncomingMessage {
7
+ return {
8
+ headers: authorization ? { authorization } : {},
9
+ } as IncomingMessage;
10
+ }
11
+
12
+ describe("oauth authenticate (scaffold — fail closed)", () => {
13
+ const original = process.env.MCP_OAUTH_ISSUER_URL;
14
+ afterEach(() => {
15
+ if (original === undefined) delete process.env.MCP_OAUTH_ISSUER_URL;
16
+ else process.env.MCP_OAUTH_ISSUER_URL = original;
17
+ });
18
+
19
+ it("denies when the issuer URL is unset", async () => {
20
+ delete process.env.MCP_OAUTH_ISSUER_URL;
21
+ assert.equal(await authenticate(reqWith("Bearer token")), false);
22
+ });
23
+
24
+ it("denies until real verification is wired (fail-closed default)", async () => {
25
+ // The scaffold returns false even for a well-formed bearer until you
26
+ // implement issuer verification — see auth/oauth.ts. This test documents
27
+ // that contract; replace it once verification lands.
28
+ process.env.MCP_OAUTH_ISSUER_URL = "https://issuer.example.com";
29
+ assert.equal(await authenticate(reqWith("Bearer token")), false);
30
+ assert.equal(await authenticate(reqWith(undefined)), false);
31
+ });
32
+ });
33
+
34
+ describe("oauth assertConfigured", () => {
35
+ const original = process.env.MCP_OAUTH_ISSUER_URL;
36
+ afterEach(() => {
37
+ if (original === undefined) delete process.env.MCP_OAUTH_ISSUER_URL;
38
+ else process.env.MCP_OAUTH_ISSUER_URL = original;
39
+ });
40
+
41
+ it("throws at startup when MCP_OAUTH_ISSUER_URL is unset", () => {
42
+ delete process.env.MCP_OAUTH_ISSUER_URL;
43
+ assert.throws(() => assertConfigured(), /MCP_OAUTH_ISSUER_URL/);
44
+ });
45
+
46
+ it("passes when MCP_OAUTH_ISSUER_URL is set", () => {
47
+ process.env.MCP_OAUTH_ISSUER_URL = "https://issuer.example.com";
48
+ assert.doesNotThrow(() => assertConfigured());
49
+ });
50
+ });
@@ -0,0 +1,53 @@
1
+ // @hexagen-server-only
2
+ import type { IncomingMessage } from "node:http";
3
+
4
+ /**
5
+ * OAuth resource-server authentication for the HTTP transport (SCAFFOLD).
6
+ *
7
+ * Validate the incoming bearer token as an access token issued by your OAuth
8
+ * provider (`MCP_OAUTH_ISSUER_URL`): verify the JWT signature against the
9
+ * issuer's JWKS, then check the audience and any required scopes. This is left
10
+ * as a deliberate scaffold because the issuer, audience, and scope policy are
11
+ * project-specific.
12
+ *
13
+ * Fail-closed: returns false until you wire real verification — an unconfigured
14
+ * OAuth deployment denies every request rather than allowing them.
15
+ *
16
+ * Recommended verifier — `jose` (`npm i jose`):
17
+ *
18
+ * import { createRemoteJWKSet, jwtVerify } from "jose";
19
+ * const JWKS = createRemoteJWKSet(new URL(`${issuer}/.well-known/jwks.json`));
20
+ * const { payload } = await jwtVerify(token, JWKS, {
21
+ * issuer,
22
+ * audience: "<your-mcp-server-audience>",
23
+ * });
24
+ * return hasRequiredScopes(payload.scope);
25
+ */
26
+ export async function authenticate(req: IncomingMessage): Promise<boolean> {
27
+ const issuer = process.env.MCP_OAUTH_ISSUER_URL;
28
+ if (!issuer) return false; // fail closed — issuer unset = deny all
29
+
30
+ const header = req.headers.authorization;
31
+ const value = Array.isArray(header) ? header[0] : header;
32
+ // RFC 7235 §2.1: the auth-scheme name is case-insensitive.
33
+ if (!value || !/^Bearer /i.test(value)) return false;
34
+
35
+ // const token = value.slice(7).trim(); // "Bearer ".length === 7
36
+ // TODO: verify `token` against the issuer JWKS (see the jose snippet above)
37
+ // and return true only for a valid token carrying the required scopes.
38
+ return false; // <- replace with real verification; fail-closed until then
39
+ }
40
+
41
+ /**
42
+ * Startup configuration check (called once from the HTTP transport factory):
43
+ * OAuth verification needs the issuer URL. Throw at startup so a missing issuer
44
+ * is a loud error rather than a silent deny-all. (Even when configured, this
45
+ * scaffold denies until you implement verification above.)
46
+ */
47
+ export function assertConfigured(): void {
48
+ if (!process.env.MCP_OAUTH_ISSUER_URL) {
49
+ throw new Error(
50
+ "Refusing to start: MCP_AUTH_MODE=oauth requires MCP_OAUTH_ISSUER_URL to be set.",
51
+ );
52
+ }
53
+ }
@@ -0,0 +1,75 @@
1
+ import { describe, it } from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import { assertSafeTransport } from "./guard.js";
4
+
5
+ describe("assertSafeTransport", () => {
6
+ it("throws when streamable-http has no auth mode set", () => {
7
+ assert.throws(
8
+ () => assertSafeTransport({ MCP_TRANSPORT: "streamable-http" }),
9
+ /requires MCP_AUTH_MODE/,
10
+ );
11
+ });
12
+
13
+ it("throws when streamable-http has MCP_AUTH_MODE=none", () => {
14
+ assert.throws(
15
+ () =>
16
+ assertSafeTransport({
17
+ MCP_TRANSPORT: "streamable-http",
18
+ MCP_AUTH_MODE: "none",
19
+ }),
20
+ /requires MCP_AUTH_MODE/,
21
+ );
22
+ });
23
+
24
+ it("allows streamable-http with bearer auth", () => {
25
+ assert.doesNotThrow(() =>
26
+ assertSafeTransport({
27
+ MCP_TRANSPORT: "streamable-http",
28
+ MCP_AUTH_MODE: "bearer",
29
+ }),
30
+ );
31
+ });
32
+
33
+ it("allows streamable-http with oauth auth", () => {
34
+ assert.doesNotThrow(() =>
35
+ assertSafeTransport({
36
+ MCP_TRANSPORT: "streamable-http",
37
+ MCP_AUTH_MODE: "oauth",
38
+ }),
39
+ );
40
+ });
41
+
42
+ it("ignores non-http transports — stdio needs no auth", () => {
43
+ assert.doesNotThrow(() => assertSafeTransport({ MCP_TRANSPORT: "stdio" }));
44
+ assert.doesNotThrow(() => assertSafeTransport({}));
45
+ });
46
+
47
+ it("throws for empty, whitespace, or otherwise invalid auth modes", () => {
48
+ for (const MCP_AUTH_MODE of ["", " ", "disabled", "basic"]) {
49
+ assert.throws(
50
+ () =>
51
+ assertSafeTransport({
52
+ MCP_TRANSPORT: "streamable-http",
53
+ MCP_AUTH_MODE,
54
+ }),
55
+ /requires MCP_AUTH_MODE/,
56
+ `MCP_AUTH_MODE=${JSON.stringify(MCP_AUTH_MODE)} must be rejected`,
57
+ );
58
+ }
59
+ });
60
+
61
+ it("accepts bearer/oauth case-insensitively and trims whitespace", () => {
62
+ assert.doesNotThrow(() =>
63
+ assertSafeTransport({
64
+ MCP_TRANSPORT: "streamable-http",
65
+ MCP_AUTH_MODE: " Bearer ",
66
+ }),
67
+ );
68
+ assert.doesNotThrow(() =>
69
+ assertSafeTransport({
70
+ MCP_TRANSPORT: "streamable-http",
71
+ MCP_AUTH_MODE: "OAUTH",
72
+ }),
73
+ );
74
+ });
75
+ });
@@ -0,0 +1,26 @@
1
+ // @hexagen-server-only
2
+ /**
3
+ * Defense-in-depth startup guard: refuse to start a network-exposed transport
4
+ * without authentication. The structural protection is the template split — the
5
+ * `mcp-server-http` addon's `auth` question has no `none` option — but `.env` is
6
+ * hand-edited after generation, so this guard fails fast at startup unless
7
+ * `MCP_TRANSPORT=streamable-http` is paired with a valid `MCP_AUTH_MODE`
8
+ * (`bearer` | `oauth`). It enforces an **allowlist**, so an empty string,
9
+ * `none`, or any other invalid value is rejected — not just an unset variable.
10
+ *
11
+ * Called first inside `createHttpTransport()`, i.e. only on the HTTP path: stdio
12
+ * deployments pay nothing, and importing the transport module in a unit test
13
+ * never trips it. `MCP_AUTH_MODE` is read only here — the auth implementation
14
+ * itself is fixed at install.
15
+ */
16
+ export function assertSafeTransport(env: NodeJS.ProcessEnv): void {
17
+ if (env.MCP_TRANSPORT !== "streamable-http") return;
18
+
19
+ const mode = (env.MCP_AUTH_MODE ?? "").trim().toLowerCase();
20
+ if (mode !== "bearer" && mode !== "oauth") {
21
+ throw new Error(
22
+ "Refusing to start: MCP_TRANSPORT=streamable-http requires MCP_AUTH_MODE=bearer|oauth. " +
23
+ "Set MCP_AUTH_MODE and the matching secret, or use the stdio transport.",
24
+ );
25
+ }
26
+ }
@@ -0,0 +1,94 @@
1
+ // @hexagen-server-only — network-exposed transport; holds no logic and gates
2
+ // every request through auth before the MCP layer sees it (ADR-0037).
3
+ import {
4
+ createServer,
5
+ type IncomingMessage,
6
+ type ServerResponse,
7
+ } from "node:http";
8
+ import type { TransportFactory } from "../server.js";
9
+ import { assertSafeTransport } from "../guard.js";
10
+ import { authenticate, assertConfigured } from "../auth/{auth}.js";
11
+
12
+ /**
13
+ * Streamable-HTTP transport factory. Unlike stdio (a one-shot subprocess pipe),
14
+ * the HTTP transport is request-driven: it needs a Node http server to feed it
15
+ * requests via `transport.handleRequest(req, res)`. This factory builds a
16
+ * stateless transport plus a Node http listener (authenticating every request
17
+ * first), then ties the listener into the transport's own lifecycle:
18
+ *
19
+ * - The port opens in `transport.start()`, which `server.connect()` invokes
20
+ * only AFTER it has wired `onmessage`/`onclose`/`onerror` — so no request can
21
+ * reach `handleRequest` before the transport is connected to the McpServer.
22
+ * - `transport.close()` shuts the listener down, so stopping the MCP server
23
+ * frees the port and lets the process exit (no dangling listener, no
24
+ * EADDRINUSE on restart).
25
+ * - A bind failure (e.g. EADDRINUSE) rejects `start()` with a clear error
26
+ * rather than crashing the process with an unhandled `'error'` event.
27
+ *
28
+ * The SDK is dynamically imported (ADR-0010). For stateful multi-client
29
+ * deployments, pass a `sessionIdGenerator` instead of `undefined` (see SDK docs).
30
+ */
31
+ export const createHttpTransport: TransportFactory = async () => {
32
+ // Defense-in-depth: refuse to expose the server over the network without auth
33
+ // (even if MCP_AUTH_MODE was cleared in a hand-edited .env), and fail fast when
34
+ // the chosen auth's secret is unset — otherwise the server would start and
35
+ // silently deny every request.
36
+ assertSafeTransport(process.env);
37
+ assertConfigured();
38
+
39
+ const { StreamableHTTPServerTransport } = await import(
40
+ "@modelcontextprotocol/sdk/server/streamableHttp.js"
41
+ );
42
+ const transport = new StreamableHTTPServerTransport({
43
+ sessionIdGenerator: undefined, // stateless: one transport, no session tracking
44
+ });
45
+
46
+ const port = Number(process.env.MCP_HTTP_PORT) || 3333;
47
+ const httpServer = createServer(
48
+ async (req: IncomingMessage, res: ServerResponse) => {
49
+ try {
50
+ if (!(await authenticate(req))) {
51
+ res.writeHead(401, { "content-type": "application/json" });
52
+ res.end(JSON.stringify({ error: "unauthorized" }));
53
+ return;
54
+ }
55
+ await transport.handleRequest(req, res);
56
+ } catch (error: unknown) {
57
+ console.error("[mcp-http] request failed:", error);
58
+ if (!res.headersSent) {
59
+ res.writeHead(500, { "content-type": "application/json" });
60
+ res.end(JSON.stringify({ error: "internal_error" }));
61
+ }
62
+ }
63
+ },
64
+ );
65
+
66
+ // Open the port in start() (run by server.connect() after the message handlers
67
+ // are wired) and surface a bind error there instead of as an unhandled event.
68
+ const baseStart = transport.start.bind(transport);
69
+ transport.start = async () => {
70
+ await baseStart();
71
+ await new Promise<void>((resolve, reject) => {
72
+ const onBindError = (err: Error) => reject(err);
73
+ httpServer.once("error", onBindError);
74
+ httpServer.listen(port, () => {
75
+ httpServer.removeListener("error", onBindError);
76
+ httpServer.on("error", (err) =>
77
+ console.error("[mcp-http] server error:", err),
78
+ );
79
+ console.error(`[mcp-http] listening on :${port}`);
80
+ resolve();
81
+ });
82
+ });
83
+ };
84
+
85
+ // Free the listener when the MCP server shuts down, so the port is released
86
+ // and the event loop can exit.
87
+ const baseClose = transport.close.bind(transport);
88
+ transport.close = async () => {
89
+ await new Promise<void>((resolve) => httpServer.close(() => resolve()));
90
+ await baseClose();
91
+ };
92
+
93
+ return transport;
94
+ };
@@ -0,0 +1,15 @@
1
+ // @hexagen-server-only
2
+ /**
3
+ * Static transport registrations. The base registers `stdio`; the
4
+ * `mcp-server-http` addon re-emits this file to add `streamable-http` — the
5
+ * seam's intended extension point (see the base file's note). Re-emitting this
6
+ * tiny declarative file is the minimal-blast-radius way to extend the registry
7
+ * without touching the composition root (`server.ts`). If you had hand-edited
8
+ * it, your version is preserved as a `.hexagen-update` conflict copy.
9
+ */
10
+ import { registerTransport } from "../server.js";
11
+ import { createStdioTransport } from "./stdio.js";
12
+ import { createHttpTransport } from "./http.js";
13
+
14
+ registerTransport("stdio", createStdioTransport);
15
+ registerTransport("streamable-http", createHttpTransport);