@haneinfo/mcp-server 3.5.0 → 4.0.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 (84) hide show
  1. package/README.md +177 -12
  2. package/dist/admin-access.d.ts +24 -0
  3. package/dist/admin-access.d.ts.map +1 -0
  4. package/dist/admin-access.js +54 -0
  5. package/dist/admin-access.js.map +1 -0
  6. package/dist/authenticator.d.ts +31 -0
  7. package/dist/authenticator.d.ts.map +1 -0
  8. package/dist/authenticator.js +37 -0
  9. package/dist/authenticator.js.map +1 -0
  10. package/dist/deployment-config.d.ts +67 -0
  11. package/dist/deployment-config.d.ts.map +1 -0
  12. package/dist/deployment-config.js +157 -0
  13. package/dist/deployment-config.js.map +1 -0
  14. package/dist/discovery-push.service.d.ts +11 -9
  15. package/dist/discovery-push.service.d.ts.map +1 -1
  16. package/dist/discovery-push.service.js +27 -11
  17. package/dist/discovery-push.service.js.map +1 -1
  18. package/dist/enabled-resources.d.ts +53 -0
  19. package/dist/enabled-resources.d.ts.map +1 -0
  20. package/dist/enabled-resources.js +243 -0
  21. package/dist/enabled-resources.js.map +1 -0
  22. package/dist/iam-authenticator.d.ts +29 -0
  23. package/dist/iam-authenticator.d.ts.map +1 -0
  24. package/dist/iam-authenticator.js +269 -0
  25. package/dist/iam-authenticator.js.map +1 -0
  26. package/dist/index.d.ts +10 -3
  27. package/dist/index.d.ts.map +1 -1
  28. package/dist/index.js +10 -5
  29. package/dist/index.js.map +1 -1
  30. package/dist/mcp-tool.registry.d.ts +21 -76
  31. package/dist/mcp-tool.registry.d.ts.map +1 -1
  32. package/dist/mcp-tool.registry.js +66 -240
  33. package/dist/mcp-tool.registry.js.map +1 -1
  34. package/dist/mcp.controller.d.ts +21 -5
  35. package/dist/mcp.controller.d.ts.map +1 -1
  36. package/dist/mcp.controller.js +273 -48
  37. package/dist/mcp.controller.js.map +1 -1
  38. package/dist/mcp.module.d.ts +5 -0
  39. package/dist/mcp.module.d.ts.map +1 -1
  40. package/dist/mcp.module.js +71 -8
  41. package/dist/mcp.module.js.map +1 -1
  42. package/dist/mcp.service.d.ts +31 -18
  43. package/dist/mcp.service.d.ts.map +1 -1
  44. package/dist/mcp.service.js +784 -194
  45. package/dist/mcp.service.js.map +1 -1
  46. package/dist/pg-rate-limiter.d.ts +46 -0
  47. package/dist/pg-rate-limiter.d.ts.map +1 -0
  48. package/dist/pg-rate-limiter.js +161 -0
  49. package/dist/pg-rate-limiter.js.map +1 -0
  50. package/dist/plugin.d.ts +41 -4
  51. package/dist/plugin.d.ts.map +1 -1
  52. package/dist/plugin.js +26 -14
  53. package/dist/plugin.js.map +1 -1
  54. package/dist/prm.controller.d.ts +17 -0
  55. package/dist/prm.controller.d.ts.map +1 -0
  56. package/dist/prm.controller.js +77 -0
  57. package/dist/prm.controller.js.map +1 -0
  58. package/dist/protocol-config.d.ts +36 -0
  59. package/dist/protocol-config.d.ts.map +1 -0
  60. package/dist/protocol-config.js +142 -0
  61. package/dist/protocol-config.js.map +1 -0
  62. package/dist/rate-limit-config.d.ts +25 -0
  63. package/dist/rate-limit-config.d.ts.map +1 -0
  64. package/dist/rate-limit-config.js +85 -0
  65. package/dist/rate-limit-config.js.map +1 -0
  66. package/dist/rate-limit-http.d.ts +11 -0
  67. package/dist/rate-limit-http.d.ts.map +1 -0
  68. package/dist/rate-limit-http.js +68 -0
  69. package/dist/rate-limit-http.js.map +1 -0
  70. package/dist/request-state.d.ts +14 -9
  71. package/dist/request-state.d.ts.map +1 -1
  72. package/dist/request-state.js +37 -3
  73. package/dist/request-state.js.map +1 -1
  74. package/dist/types.d.ts +24 -7
  75. package/dist/types.d.ts.map +1 -1
  76. package/dist/types.js +3 -0
  77. package/dist/types.js.map +1 -1
  78. package/dist/write-confirmation.d.ts +82 -0
  79. package/dist/write-confirmation.d.ts.map +1 -0
  80. package/dist/write-confirmation.js +207 -0
  81. package/dist/write-confirmation.js.map +1 -0
  82. package/haneinfo.plugin.json +19 -11
  83. package/package.json +23 -11
  84. package/prisma/mcp-rate-limit.prisma +34 -0
package/README.md CHANGED
@@ -1,17 +1,182 @@
1
1
  # @haneinfo/mcp-server
2
2
 
3
- The MCP server provides authenticated HTTP transport, scope-filtered tools and optional dynamic
4
- tool sources. See [agent-guide.md](agent-guide.md) for client update and session requirements.
3
+ The MCP server provides stateless HTTP transport for employee (`/mcp`) and admin (`/mcp/admin`)
4
+ MCP resources, RFC 9728 Protected Resource Metadata (PRM), and a minimal `/mcp/health` endpoint.
5
+ See [agent-guide.md](agent-guide.md) for client requirements.
5
6
 
6
- ## Tool updates and legacy sessions
7
+ ## Routing and `setGlobalPrefix`
7
8
 
8
- Clients that receive `notifications/tools/list_changed` must retrieve `tools/list` again before
9
- using the updated tools. Until a client refreshes its list and schemas after a change, its calls
10
- are not guaranteed to match the current tool definitions.
9
+ Each enabled resource exposes an OAuth 2.0 Protected Resource Metadata document per RFC 9728 §3.1
10
+ at `/.well-known/oauth-protected-resource<resource-path>` (for example, `https://h/x/mcp` serves
11
+ metadata at `https://h/.well-known/oauth-protected-resource/x/mcp`).
11
12
 
12
- The current dynamic tool source integration does **not** send `tools/list_changed`. When generated
13
- tools change, clients must refresh proactively; 2025-era stateful sessions must reconnect, then
14
- retrieve the list, because their registered tool schemas are fixed at initialization. In an
15
- existing session, a new argument may be rejected by the old schema before it reaches the current
16
- handler, while arguments accepted by the old schema are passed to that current handler. Newly
17
- added tools are unavailable in the old session. See the generated-tools README for refresh timing.
13
+ If your NestJS application calls `app.setGlobalPrefix(...)`, exclude `.well-known/oauth-protected-resource`
14
+ so PRM routes remain mounted at the host root:
15
+
16
+ ```ts
17
+ app.setGlobalPrefix('x', {
18
+ exclude: ['.well-known/oauth-protected-resource/*path'],
19
+ });
20
+ ```
21
+
22
+ ## Health Check (`/mcp/health`)
23
+
24
+ `GET /mcp/health` returns `{"status":"ok"}` with `Cache-Control: no-store` and no server metadata
25
+ or tool counts.
26
+
27
+ An optional `challenge` query parameter is echoed back when it matches `^[A-Za-z0-9._~-]{1,128}$`.
28
+ Any invalid `challenge` value returns HTTP `400`.
29
+
30
+ ## Tool Registration (`@haneinfo/commands` + `McpModule.forRoot`)
31
+
32
+ `@haneinfo/commands` (`CommandRegistry`) is the sole source of MCP tools. Legacy decorator and registry registration APIs (`@McpTool()`, `registerMcpToolsFromInstance()`, `McpToolRegistry.registerTool()`, `registerToolSource()`, `refreshToolSources()`, `MCP_TOOLS`, and `*` wildcard scope matching) have been removed.
33
+
34
+ Pass a sealed `CommandRegistry` and positive integer `lockTimeoutMs` to `McpModule.forRoot(deployment, options)`:
35
+
36
+ ```ts
37
+ import { Module } from '@nestjs/common';
38
+ import { McpModule } from '@haneinfo/mcp-server';
39
+
40
+ @Module({
41
+ imports: [
42
+ McpModule.forRoot(deployment, {
43
+ commands: sealedCommandRegistry,
44
+ lockTimeoutMs: 2000,
45
+ }),
46
+ ],
47
+ })
48
+ export class AppMcpModule {}
49
+ ```
50
+
51
+ - `/mcp` exposes commands with surface `'mcp'`; `/mcp/admin` exposes commands with surface `'mcp-admin'`.
52
+ - `tools/list` filters by resource, surface, App admission, exact OAuth scope match, RBAC (or resource-ACL declaration `permissions: []`), `mcp-server.disabledTools`, and dynamic source visibility.
53
+ - `tools/call` re-runs full authorization **before** validating `inputSchema` and returns byte-for-byte identical JSON-RPC `-32602` (`data.code: 'tool_unavailable'`) for missing, disabled, unauthorized, wrong-surface, or insufficient-scope tools.
54
+ - `access: 'read'` commands run with `PRISMA`; `access: 'write'` commands run inside a `ReadCommitted` transaction with `authorizeWriteInTransaction` (`-32090` `lock_timeout`, `-32091` `authorization_stale`).
55
+ - Write commands requiring confirmation (`confirmation: 'required'`, and **all** writes on `mcp-admin`) use the 2026-07-28 `input_required` elicitation confirmation flow (see below); when the confirmation gate is not met, `tools/call` returns JSON-RPC `-32092` (`data.code: 'confirmation_unavailable'`).
56
+ - Throwing `CommandToolError(payload)` from a command handler returns `{ isError: true, content: [{ type: 'text', text: JSON.stringify(payload) }] }` without `structuredContent`.
57
+
58
+ ## Dynamic tool updates
59
+
60
+ The dynamic tool source integration does **not** send `notifications/tools/list_changed`. When
61
+ generated tools change, clients must refresh `tools/list` proactively.
62
+
63
+ ## Admin Endpoint (`/mcp/admin`) Configuration and Checks
64
+
65
+ When `mcp.admin.enabled` is `true`, `McpIamDeploymentConfig.mcp.admin` requires:
66
+
67
+ - `requiredScope?: string` — Single OAuth scope required for `/mcp/admin`. Required when `enabled` is `true`; must be a non-empty string without whitespace, double quotes, backslashes, or control characters.
68
+ - `adminRoleNames?: readonly string[]` — App RBAC role names granting admin access. Defaults to `['ADMIN']` (`SYSTEM_ADMIN_ROLE`) when omitted; must be a non-empty array if provided.
69
+ - `stepUpAcrValues?: string` — Space-delimited `acr_values` returned in RFC 9470 step-up challenges. Required when `enabled` is `true`; must be a non-empty string without double quotes, backslashes, or control characters.
70
+
71
+ After token verification and local App admission succeed, `/mcp/admin` enforces three checks in order and returns the first failure:
72
+
73
+ 1. **Management scope** (`claims.scopes` includes `requiredScope`):
74
+ - Failure: HTTP `403` `{ "error": "insufficient_scope" }` with `WWW-Authenticate: Bearer error="insufficient_scope", scope="<requiredScope>", resource_metadata="<admin-prm-url>"`.
75
+ 2. **App RBAC admin role** (live `RBAC_POLICY.rolesForUser(userId)` intersects `adminRoleNames`; token role claims are never read):
76
+ - Failure: HTTP `403` `{ "error": "insufficient_role" }` (without `WWW-Authenticate`).
77
+ 3. **MFA & `auth_time` freshness** (`mfa === true`, `authTime` is an integer, `authTime <= nowSeconds`, and `nowSeconds - authTime <= maxAuthAgeSeconds` with no clock tolerance):
78
+ - Failure: HTTP `401` `{ "error": "insufficient_user_authentication" }` with `WWW-Authenticate: Bearer error="insufficient_user_authentication", acr_values="<stepUpAcrValues>", max_age="<maxAuthAgeSeconds>", resource_metadata="<admin-prm-url>"`.
79
+
80
+ ## Cross-Replica Rate Limiting (`MCP_RATE_LIMITER`)
81
+
82
+ `@haneinfo/mcp-server` provides a PostgreSQL-backed fixed-window rate limiter (`PgMcpRateLimiter`) as the default `MCP_RATE_LIMITER` implementation, using `@haneinfo/common`'s `PrismaService`. Applications can override `MCP_RATE_LIMITER` in NestJS DI if they supply a custom `McpRateLimiterPort`.
83
+
84
+ ### Database Table and Migrations
85
+
86
+ The Prisma model `McpRateLimitBucket` (`mcp_rate_limit_buckets`) is shipped as a schema fragment in [`prisma/mcp-rate-limit.prisma`](prisma/mcp-rate-limit.prisma). `@haneinfo/mcp-server` never creates tables or runs migrations at runtime: `haneinfo build` (`@haneinfo/plugin-cli`'s Prisma composer) composes the fragment into the host App's `schema.prisma`, and the host App owns and applies the Prisma migration.
87
+
88
+ Keys are always SHA-256 hashed before storage; raw client IPs and user identifiers are never persisted in `mcp_rate_limit_buckets`.
89
+
90
+ ### Request Flow and Failure Behavior
91
+
92
+ - **RPC endpoints (`/mcp`, `/mcp/admin`)** process requests in this exact order:
93
+ 1. **Resource enabled check**: Disabled or unconfigured resources return HTTP `404` `{"error":"not_found"}`.
94
+ 2. **Host validation** (`MCP_ALLOWED_HOSTNAMES`): Fail closed when unset or unlisted (HTTP `403`).
95
+ 3. **Origin validation** (`MCP_ALLOWED_ORIGINS`): Requests without an `Origin` header are allowed. When present, `Origin` must be a single valid `scheme://host[:port]` URL matching an entry in `MCP_ALLOWED_ORIGINS` (empty string, `null`, multiple values, malformed URLs, or scheme/host/port mismatches return HTTP `403` `{"error":"forbidden_origin"}`).
96
+ 4. **Per-replica concurrency limit** (`MCP_MAX_CONCURRENT_PER_SOURCE`, default `20`): Tracked in memory per replica by `req.ip` + normalized resource path and released when the HTTP exchange ends (response completion or connection close). A slot counts an in-flight HTTP exchange, not tool work: when a client aborts, the SDK ends the exchange and the slot is released while the tool handler may still be running, so abort-and-resend is bounded by the pre-auth and post-auth rate quotas rather than by this limit. Exceeding the limit returns HTTP `429` with `Retry-After: 1` and `{"error":"too_many_concurrent_requests"}`. The effective cluster-wide concurrency limit is `MCP_MAX_CONCURRENT_PER_SOURCE * replicas`.
97
+ 5. **Pre-auth rate limit**: Keyed by `req.ip` + normalized resource path. Quota exceeded returns HTTP `429` with `Retry-After` and `{"error":"rate_limited"}`.
98
+ 6. **HTTP method, request size, JSON object, and batch checks**:
99
+ - Non-`POST` methods (`GET`, `DELETE`, etc.) return HTTP `405` with `Allow: POST` and `{"error":"method_not_allowed"}`.
100
+ - A non-integer or oversized `Content-Length` (`> MCP_MAX_BODY_BYTES`, default `1048576`) returns HTTP `413` `{"error":"payload_too_large"}`. A request without `Content-Length` (HTTP/1.1 chunked, HTTP/2) is allowed; its size is limited only by the host body parser. Host applications using NestJS/Express **must** configure their Express JSON body parser limit to the same `MCP_MAX_BODY_BYTES` value so oversized bodies are rejected before parsing.
101
+ - Non-object JSON bodies return HTTP `400` (`-32600`). JSON-RPC batch arrays return HTTP `400` with JSON-RPC error `-32600` after `pre-auth` quota has been charged.
102
+ 7. **M2M rejection, token verification, local admission, and admin checks**: Unauthenticated callers receive HTTP `401` (with `WWW-Authenticate: Bearer resource_metadata="..."`) or `403` without protocol-layer details (except size and batch rejections in step 6).
103
+ 8. **Post-auth rate limit**: Keyed by `issuer`, `actingUserId`, `clientId`, and `resource`.
104
+ 9. **Protocol routing, version check, and method check**:
105
+ - Modern `2026-07-28` envelope (`params._meta['io.modelcontextprotocol/protocolVersion']`): `subscriptions/listen` returns HTTP `200` `application/json` JSON-RPC `-32601` (never opens SSE); all other requests route to the modern stateless `createMcpHandler` (`legacy: 'reject'`, `responseMode: 'json'`, `inputRequired: { legacyShim: false }`).
106
+ - Non-envelope `initialize`: `params.protocolVersion` must equal `2025-11-25` (older versions return HTTP `400`).
107
+ - Non-envelope non-`initialize`: `MCP-Protocol-Version` header must equal `2025-11-25` (missing or other values return HTTP `400`). Only `initialize`, `notifications/initialized`, `ping`, `tools/list`, and `tools/call` are allowed; any other method (including `subscriptions/listen`) returns HTTP `200` `application/json` JSON-RPC `-32601`.
108
+ 10. **Handler execution**: Never emits `Mcp-Session-Id`. Both `2026-07-28` and `2025-11-25` allow `read` commands and `confirmation: 'exempt'` writes on `/mcp`; confirmation-required writes (and all writes on `/mcp/admin`) are listed in `2026-07-28` `tools/list`, hidden in `2025-11-25` `tools/list`, and require the confirmation gate in `tools/call`.
109
+ - **Public metadata (`/mcp/health`, `/.well-known/oauth-protected-resource/*`)**: Rate-limited under the independent `public-meta` bucket (keyed by client IP) so public metadata probes do not interfere with RPC quotas.
110
+ - **Cost weighting**: `tools/call` consumes `MCP_RATE_LIMIT_TOOLS_CALL_COST` (default `5`), while other methods consume `MCP_RATE_LIMIT_DEFAULT_COST` (default `1`). JSON-RPC batch arrays sum the cost of their items against `pre-auth`.
111
+ - **Quota exceeded**: Returns HTTP `429` with `Retry-After` (integer seconds, at least `1`) and JSON body `{"error":"rate_limited"}`.
112
+ - **Backend unavailable (timeout > 1000 ms or DB failure)**: Returns HTTP `503` with `{"error":"rate_limiter_unavailable"}` on `/mcp` and `/mcp/admin` without entering authentication or handlers. By architectural choice, PRM and `/mcp/health` also return HTTP `503` `{"error":"rate_limiter_unavailable"}` when the rate limiter throws.
113
+ - **IAM backend lookup failure**: If `OIDC_IDENTITY_LOOKUP`, `IDENTITY_STORE`, or `RBAC_POLICY` throws during authentication, the server returns HTTP `503` with `{"error":"service_unavailable"}` without leaking internal error details.
114
+
115
+ ### Express `trust proxy` Requirement
116
+
117
+ Client IP resolution relies strictly on Express `req.ip` and never parses `X-Forwarded-For` directly. Host applications running behind a reverse proxy or load balancer **must** configure Express `trust proxy` accurately (for example, `app.set('trust proxy', 1)` or trusted proxy CIDRs) so `req.ip` reflects the real client address rather than the proxy or a spoofed header.
118
+
119
+ ### Environment Variables and Defaults
120
+
121
+ All limits, windows, costs, and timeouts must be positive integers (`tools/call` cost must be strictly greater than the default cost). Invalid values fail fast at module startup.
122
+
123
+ | Variable | Default | Description |
124
+ | --- | --- | --- |
125
+ | `MCP_RATE_LIMIT_PRE_AUTH_LIMIT` | `120` | Max cost units per window for `pre-auth` (`req.ip` + path). Sized to absorb shared corporate NAT traffic while blocking unauthenticated floods. |
126
+ | `MCP_RATE_LIMIT_PRE_AUTH_WINDOW_SECONDS` | `60` | Fixed window duration in seconds for `pre-auth`. |
127
+ | `MCP_RATE_LIMIT_POST_AUTH_LIMIT` | `120` | Max cost units per window for `post-auth` (`issuer` + `actingUserId` + `clientId` + `resource`). Allows ~24 `tools/call` or 120 metadata calls per minute per client/user/resource. |
128
+ | `MCP_RATE_LIMIT_POST_AUTH_WINDOW_SECONDS` | `60` | Fixed window duration in seconds for `post-auth`. |
129
+ | `MCP_RATE_LIMIT_PUBLIC_META_LIMIT` | `60` | Max requests per window for `public-meta` (PRM and `/mcp/health`, keyed by `req.ip`). |
130
+ | `MCP_RATE_LIMIT_PUBLIC_META_WINDOW_SECONDS` | `60` | Fixed window duration in seconds for `public-meta`. |
131
+ | `MCP_RATE_LIMIT_DEFAULT_COST` | `1` | Cost per non-`tools/call` JSON-RPC request (such as `initialize` or `tools/list`). |
132
+ | `MCP_RATE_LIMIT_TOOLS_CALL_COST` | `5` | Cost per `tools/call` invocation (must be greater than `MCP_RATE_LIMIT_DEFAULT_COST`). |
133
+ | `MCP_RATE_LIMIT_TIMEOUT_MS` | `1000` | Client-side deadline in milliseconds before failing closed with `503`. The query itself is not cancelled by this deadline; set `statement_timeout` on the database role (for example `ALTER ROLE <app_role> SET statement_timeout = '1s'`) as the server-side bound. |
134
+
135
+ ### Protocol, Origin, and Pre-Processing Environment Variables
136
+
137
+ | Variable | Default | Description |
138
+ | --- | --- | --- |
139
+ | `MCP_ALLOWED_HOSTNAMES` | *(unset — fail closed)* | Comma-separated allowed `Host` header hostnames. All RPC requests are rejected when unset or empty. |
140
+ | `MCP_ALLOWED_ORIGINS` | *(unset — fail closed for browser `Origin`)* | Comma-separated exact allowed origins (`scheme://host[:port]`, no path, query, fragment, or wildcard). Requests without `Origin` are allowed. |
141
+ | `MCP_MAX_CONCURRENT_PER_SOURCE` | `20` | Initial value without load measurements (maintainer 2026-11-15); tune it from real traffic. Per-replica in-memory concurrent request limit per `req.ip` + resource path. Effective cluster-wide limit is `MCP_MAX_CONCURRENT_PER_SOURCE * replicas`. |
142
+ | `MCP_MAX_BODY_BYTES` | `1048576` | Maximum allowed `Content-Length` in bytes (`1 MiB`). Set the host Express JSON body parser limit to the same value. |
143
+
144
+ **Removed in 4.0**: `MCP_ALLOWED_ORIGIN_HOSTNAMES` (replaced by `MCP_ALLOWED_ORIGINS`; startup fails if the old variable is set without the new one), `MCP_MAX_LEGACY_SESSIONS`, and `MCP_LEGACY_SESSION_IDLE_TTL_MS`.
145
+
146
+ ### Scheduling Bucket Cleanup
147
+
148
+ Expired rows in `mcp_rate_limit_buckets` are not deleted on the request path. Schedule `purgeExpiredRateLimitBuckets(prisma, olderThan)` from a periodic background job (for example, hourly or daily via `@haneinfo/background-jobs` or a cron worker), passing a cutoff timestamp older than the longest configured rate-limit window (e.g. `new Date(Date.now() - 3600_000)`).
149
+
150
+ ## Write Confirmation (`input_required`, Receipts, `requestState`, and Audit)
151
+
152
+ Write commands with `confirmation: 'required'` (and **all** write commands on `/mcp/admin`, regardless of `confirmation`) require per-invocation user confirmation over MCP `2026-07-28` form elicitation (`input_required`).
153
+
154
+ ### Confirmation Gate & `MCP_REQUEST_STATE_KEY`
155
+
156
+ On **both** the initial `tools/call` and every resume carrying `requestState`, the executor verifies three gate conditions:
157
+
158
+ 1. Protocol revision is `2026-07-28`.
159
+ 2. The current request declares `elicitation.form` in `params._meta['io.modelcontextprotocol/clientCapabilities']`.
160
+ 3. `MCP_REQUEST_STATE_KEY` is configured as a base64-encoded key that decodes to **at least 32 bytes** (shared across all replicas; never committed to source control).
161
+
162
+ If any condition fails, the server returns HTTP `200` with JSON-RPC `error.code: -32092` and `error.data.code: 'confirmation_unavailable'` without creating a receipt or executing any write.
163
+
164
+ `requestState` is signed using `@modelcontextprotocol/server`'s `createRequestStateCodec` (HMAC-SHA256) with a **120-second TTL** (`DEFAULT_REQUEST_STATE_TTL_SECONDS = 120`), bound to `(method, issuer, subject, resource)`. The signed payload contains only `{ toolName, schemaVersion, argsDigest, operationId }` (no raw arguments).
165
+
166
+ ### Receipt Table and Migrations
167
+
168
+ The `McpConfirmationReceipt` (`mcp_confirmation_receipts`) model is shipped in the same Prisma schema fragment [`prisma/mcp-rate-limit.prisma`](prisma/mcp-rate-limit.prisma) alongside `McpRateLimitBucket`. `haneinfo build` (`@haneinfo/plugin-cli`) composes it into the host App's `schema.prisma`, and the host App owns and applies the Prisma migration. Every `DateTime` column in the fragment is `@db.Timestamptz(3)` and `updatedAt` has a database default, because both tables are written with raw SQL; the generated migration must keep those types. Schedule `expirePendingConfirmationReceipts(prisma, { logger })` (for example every minute) so abandoned confirmations reach `expired` and are audited.
169
+
170
+ Receipt reads/writes run inside the App's `ReadCommitted` Prisma `TransactionClient` (`FOR UPDATE` row lock + `WHERE status = 'pending'`):
171
+
172
+ - `pending`: Inserted before returning `input_required`, binding `operationId`, `correlationId`, `issuer`, `subject`, `actingUserId`, `clientId`, `resource`, `toolName`, `schemaVersion`, `argsDigest`, and `expiresAt`.
173
+ - `committed`: Transitions only on `accept` with `confirm === true` after acquiring the receipt lock (`FOR UPDATE`), re-checking `requestState`, token `exp`, admin `auth_time`, and Step 5 RBAC/user locks (`authorizeWriteInTransaction`), and executing `command.handler(actor, input, tx)` in the same transaction.
174
+ - `declined` / `cancelled`: Transitions on valid `decline`, `cancel`, or `confirm === false` without executing the handler.
175
+ - `expired`: Transitions lazily on resume if `expiresAt <= now`, and via `expirePendingConfirmationReceipts(prisma, { now, logger })` scheduled periodically by the host App.
176
+ - **Retry / Replay**: Retrying a `committed` `operationId` first passes live authorization (`authorizer.authorize`) and then returns the stored `resultJson` without re-executing the handler.
177
+
178
+ ### Structured Audit Events
179
+
180
+ `McpService` emits single-line JSON audit events via Nest `Logger` (`ConfirmationAuditEvent`) with a server-generated `correlationId` linking `confirmation_issued`, `confirmation_accepted`, `confirmation_declined`, `confirmation_cancelled`, `confirmation_expired`, `confirmation_replayed`, `confirmation_authz_denied`, `confirmation_write_succeeded`, `confirmation_write_failed`, `confirmation_gate_rejected`, and `confirmation_binding_rejected`.
181
+
182
+ Each event records `event`, `timestamp`, `correlationId`, `operationId`, `resource`, `issuer`, `subject`, `actingUserId`, `clientId`, `toolName`, `resultCode`, and `workflowId` (external correlation only; never proof of identity or confirmation). Bearer tokens, full `requestState` strings, and raw tool arguments are never logged.
@@ -0,0 +1,24 @@
1
+ import { type NormalizedMcpAdminClaims } from '@haneinfo/plugin-api';
2
+ import { type McpIamDeploymentConfig } from './deployment-config';
3
+ export interface CheckAdminAccessInput {
4
+ claims: Pick<NormalizedMcpAdminClaims, 'scopes' | 'mfa' | 'authTime'>;
5
+ roleNames: readonly string[];
6
+ deployment: McpIamDeploymentConfig;
7
+ nowSeconds: number;
8
+ }
9
+ export type AdminAccessResult = {
10
+ ok: true;
11
+ } | {
12
+ ok: false;
13
+ status: 401 | 403;
14
+ error: 'insufficient_scope' | 'insufficient_role' | 'insufficient_user_authentication';
15
+ wwwAuthenticate?: string;
16
+ };
17
+ /**
18
+ * Pure check for `/mcp/admin` authorization layers in the exact order mandated by 1A §3:
19
+ * 1. Management OAuth scope (`mcp.admin.requiredScope`)
20
+ * 2. Live App RBAC admin role (`mcp.admin.adminRoleNames`, defaulting to `[SYSTEM_ADMIN_ROLE]`)
21
+ * 3. MFA evidence (`mfa === true`) and `auth_time` freshness (no clock tolerance)
22
+ */
23
+ export declare function checkAdminAccess(input: CheckAdminAccessInput): AdminAccessResult;
24
+ //# sourceMappingURL=admin-access.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"admin-access.d.ts","sourceRoot":"","sources":["../src/admin-access.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,wBAAwB,EAAqB,MAAM,sBAAsB,CAAC;AACxF,OAAO,EAAgB,KAAK,sBAAsB,EAAE,MAAM,qBAAqB,CAAC;AAEhF,MAAM,WAAW,qBAAqB;IACpC,MAAM,EAAE,IAAI,CAAC,wBAAwB,EAAE,QAAQ,GAAG,KAAK,GAAG,UAAU,CAAC,CAAC;IACtE,SAAS,EAAE,SAAS,MAAM,EAAE,CAAC;IAC7B,UAAU,EAAE,sBAAsB,CAAC;IACnC,UAAU,EAAE,MAAM,CAAC;CACpB;AAED,MAAM,MAAM,iBAAiB,GACzB;IAAE,EAAE,EAAE,IAAI,CAAA;CAAE,GACZ;IACE,EAAE,EAAE,KAAK,CAAC;IACV,MAAM,EAAE,GAAG,GAAG,GAAG,CAAC;IAClB,KAAK,EAAE,oBAAoB,GAAG,mBAAmB,GAAG,kCAAkC,CAAC;IACvF,eAAe,CAAC,EAAE,MAAM,CAAC;CAC1B,CAAC;AAEN;;;;;GAKG;AACH,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,qBAAqB,GAAG,iBAAiB,CA+ChF"}
@@ -0,0 +1,54 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.checkAdminAccess = checkAdminAccess;
4
+ const plugin_api_1 = require("@haneinfo/plugin-api");
5
+ const deployment_config_1 = require("./deployment-config");
6
+ /**
7
+ * Pure check for `/mcp/admin` authorization layers in the exact order mandated by 1A §3:
8
+ * 1. Management OAuth scope (`mcp.admin.requiredScope`)
9
+ * 2. Live App RBAC admin role (`mcp.admin.adminRoleNames`, defaulting to `[SYSTEM_ADMIN_ROLE]`)
10
+ * 3. MFA evidence (`mfa === true`) and `auth_time` freshness (no clock tolerance)
11
+ */
12
+ function checkAdminAccess(input) {
13
+ const { claims, roleNames, deployment, nowSeconds } = input;
14
+ const adminConfig = deployment.mcp.admin;
15
+ const adminPrmUrl = (0, deployment_config_1.derivePrmUrl)(adminConfig.canonicalResourceUrl);
16
+ // Layer 1: Management OAuth scope
17
+ const requiredScope = adminConfig.requiredScope;
18
+ if (!requiredScope || !claims.scopes.includes(requiredScope)) {
19
+ return {
20
+ ok: false,
21
+ status: 403,
22
+ error: 'insufficient_scope',
23
+ wwwAuthenticate: `Bearer error="insufficient_scope", scope="${requiredScope ?? ''}", resource_metadata="${adminPrmUrl}"`,
24
+ };
25
+ }
26
+ // Layer 2: Live App RBAC admin role (never read from token claims)
27
+ const adminRoleNames = adminConfig.adminRoleNames ?? [plugin_api_1.SYSTEM_ADMIN_ROLE];
28
+ const hasAdminRole = roleNames.some((role) => adminRoleNames.includes(role));
29
+ if (!hasAdminRole) {
30
+ return {
31
+ ok: false,
32
+ status: 403,
33
+ error: 'insufficient_role',
34
+ };
35
+ }
36
+ // Layer 3: MFA evidence & auth_time freshness (exact comparison, no clock tolerance)
37
+ const { mfa, authTime } = claims;
38
+ const maxAge = adminConfig.maxAuthAgeSeconds;
39
+ const isFreshAuthTime = typeof authTime === 'number' &&
40
+ Number.isInteger(authTime) &&
41
+ authTime <= nowSeconds &&
42
+ nowSeconds - authTime <= maxAge;
43
+ if (mfa !== true || !isFreshAuthTime) {
44
+ const stepUpAcrValues = adminConfig.stepUpAcrValues ?? '';
45
+ return {
46
+ ok: false,
47
+ status: 401,
48
+ error: 'insufficient_user_authentication',
49
+ wwwAuthenticate: `Bearer error="insufficient_user_authentication", acr_values="${stepUpAcrValues}", max_age="${maxAge}", resource_metadata="${adminPrmUrl}"`,
50
+ };
51
+ }
52
+ return { ok: true };
53
+ }
54
+ //# sourceMappingURL=admin-access.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"admin-access.js","sourceRoot":"","sources":["../src/admin-access.ts"],"names":[],"mappings":";;AAyBA,4CA+CC;AAxED,qDAAwF;AACxF,2DAAgF;AAkBhF;;;;;GAKG;AACH,SAAgB,gBAAgB,CAAC,KAA4B;IAC3D,MAAM,EAAE,MAAM,EAAE,SAAS,EAAE,UAAU,EAAE,UAAU,EAAE,GAAG,KAAK,CAAC;IAC5D,MAAM,WAAW,GAAG,UAAU,CAAC,GAAG,CAAC,KAAK,CAAC;IACzC,MAAM,WAAW,GAAG,IAAA,gCAAY,EAAC,WAAW,CAAC,oBAAoB,CAAC,CAAC;IAEnE,kCAAkC;IAClC,MAAM,aAAa,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AAC;IACJ,CAAC;IAED,OAAO,EAAE,EAAE,EAAE,IAAI,EAAE,CAAC;AACtB,CAAC"}
@@ -0,0 +1,31 @@
1
+ import type { Request } from 'express';
2
+ import type { McpCallContext, McpResourceKind } from './types';
3
+ /**
4
+ * Matches `KEY_PREFIX` in `@haneinfo/m2m-api-key` (`packages/m2m-api-key/src/api-keys.service.ts`)
5
+ * without introducing a package dependency on `m2m-api-key`.
6
+ */
7
+ export declare const M2M_API_KEY_PREFIX = "an_live_";
8
+ export declare const MCP_REQUEST_AUTHENTICATOR: unique symbol;
9
+ export type McpAuthResult = {
10
+ ok: true;
11
+ context: McpCallContext;
12
+ } | {
13
+ ok: false;
14
+ status: 401 | 403 | 503;
15
+ error: string;
16
+ message?: string;
17
+ wwwAuthenticate?: string;
18
+ };
19
+ export declare function extractBearerToken(authorization: unknown): string | undefined;
20
+ /**
21
+ * Internal seam for authenticating incoming MCP HTTP requests.
22
+ * W5-01 provides a fail-closed default that rejects all requests with 401;
23
+ * W5-02 replaces this with full `IAM_PROFILE` JWT verification and local user lookup.
24
+ */
25
+ export interface McpRequestAuthenticator {
26
+ authenticate(request: Request, kind: McpResourceKind): Promise<McpAuthResult> | McpAuthResult;
27
+ }
28
+ export declare class DefaultMcpRequestAuthenticator implements McpRequestAuthenticator {
29
+ authenticate(_request: Request, _kind: McpResourceKind): McpAuthResult;
30
+ }
31
+ //# sourceMappingURL=authenticator.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"authenticator.d.ts","sourceRoot":"","sources":["../src/authenticator.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,SAAS,CAAC;AACvC,OAAO,KAAK,EAAE,cAAc,EAAE,eAAe,EAAE,MAAM,SAAS,CAAC;AAE/D;;;GAGG;AACH,eAAO,MAAM,kBAAkB,aAAa,CAAC;AAE7C,eAAO,MAAM,yBAAyB,eAA0D,CAAC;AAEjG,MAAM,MAAM,aAAa,GACrB;IAAE,EAAE,EAAE,IAAI,CAAC;IAAC,OAAO,EAAE,cAAc,CAAA;CAAE,GACrC;IACE,EAAE,EAAE,KAAK,CAAC;IACV,MAAM,EAAE,GAAG,GAAG,GAAG,GAAG,GAAG,CAAC;IACxB,KAAK,EAAE,MAAM,CAAC;IACd,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,eAAe,CAAC,EAAE,MAAM,CAAC;CAC1B,CAAC;AAEN,wBAAgB,kBAAkB,CAAC,aAAa,EAAE,OAAO,GAAG,MAAM,GAAG,SAAS,CAI7E;AAED;;;;GAIG;AACH,MAAM,WAAW,uBAAuB;IACtC,YAAY,CAAC,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,eAAe,GAAG,OAAO,CAAC,aAAa,CAAC,GAAG,aAAa,CAAC;CAC/F;AAED,qBACa,8BAA+B,YAAW,uBAAuB;IAC5E,YAAY,CAAC,QAAQ,EAAE,OAAO,EAAE,KAAK,EAAE,eAAe,GAAG,aAAa;CAOvE"}
@@ -0,0 +1,37 @@
1
+ "use strict";
2
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
7
+ };
8
+ Object.defineProperty(exports, "__esModule", { value: true });
9
+ exports.DefaultMcpRequestAuthenticator = exports.MCP_REQUEST_AUTHENTICATOR = exports.M2M_API_KEY_PREFIX = void 0;
10
+ exports.extractBearerToken = extractBearerToken;
11
+ const common_1 = require("@nestjs/common");
12
+ /**
13
+ * Matches `KEY_PREFIX` in `@haneinfo/m2m-api-key` (`packages/m2m-api-key/src/api-keys.service.ts`)
14
+ * without introducing a package dependency on `m2m-api-key`.
15
+ */
16
+ exports.M2M_API_KEY_PREFIX = 'an_live_';
17
+ exports.MCP_REQUEST_AUTHENTICATOR = Symbol.for('haneinfo.mcp-server.request-authenticator');
18
+ function extractBearerToken(authorization) {
19
+ if (typeof authorization !== 'string')
20
+ return undefined;
21
+ const match = /^Bearer\s+(\S+)$/i.exec(authorization.trim());
22
+ return match?.[1];
23
+ }
24
+ let DefaultMcpRequestAuthenticator = class DefaultMcpRequestAuthenticator {
25
+ authenticate(_request, _kind) {
26
+ return {
27
+ ok: false,
28
+ status: 401,
29
+ error: 'invalid_token',
30
+ };
31
+ }
32
+ };
33
+ exports.DefaultMcpRequestAuthenticator = DefaultMcpRequestAuthenticator;
34
+ exports.DefaultMcpRequestAuthenticator = DefaultMcpRequestAuthenticator = __decorate([
35
+ (0, common_1.Injectable)()
36
+ ], DefaultMcpRequestAuthenticator);
37
+ //# sourceMappingURL=authenticator.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"authenticator.js","sourceRoot":"","sources":["../src/authenticator.ts"],"names":[],"mappings":";;;;;;;;;AAsBA,gDAIC;AA1BD,2CAA4C;AAI5C;;;GAGG;AACU,QAAA,kBAAkB,GAAG,UAAU,CAAC;AAEhC,QAAA,yBAAyB,GAAG,MAAM,CAAC,GAAG,CAAC,2CAA2C,CAAC,CAAC;AAYjG,SAAgB,kBAAkB,CAAC,aAAsB;IACvD,IAAI,OAAO,aAAa,KAAK,QAAQ;QAAE,OAAO,SAAS,CAAC;IACxD,MAAM,KAAK,GAAG,mBAAmB,CAAC,IAAI,CAAC,aAAa,CAAC,IAAI,EAAE,CAAC,CAAC;IAC7D,OAAO,KAAK,EAAE,CAAC,CAAC,CAAC,CAAC;AACpB,CAAC;AAYM,IAAM,8BAA8B,GAApC,MAAM,8BAA8B;IACzC,YAAY,CAAC,QAAiB,EAAE,KAAsB;QACpD,OAAO;YACL,EAAE,EAAE,KAAK;YACT,MAAM,EAAE,GAAG;YACX,KAAK,EAAE,eAAe;SACvB,CAAC;IACJ,CAAC;CACF,CAAA;AARY,wEAA8B;yCAA9B,8BAA8B;IAD1C,IAAA,mBAAU,GAAE;GACA,8BAA8B,CAQ1C"}
@@ -0,0 +1,67 @@
1
+ import { z } from 'zod';
2
+ export interface McpResourceDeploymentConfig {
3
+ enabled: boolean;
4
+ canonicalResourceUrl: string;
5
+ allowedClientIds: readonly string[];
6
+ }
7
+ export interface McpIamDeploymentConfig {
8
+ issuer: string;
9
+ mcp: {
10
+ employee: McpResourceDeploymentConfig;
11
+ admin: McpResourceDeploymentConfig & {
12
+ maxAuthAgeSeconds: number;
13
+ requiredScope?: string;
14
+ adminRoleNames?: readonly string[];
15
+ stepUpAcrValues?: string;
16
+ };
17
+ };
18
+ }
19
+ export interface PrmDocument {
20
+ resource: string;
21
+ authorization_servers: [string];
22
+ scopes_supported: string[];
23
+ bearer_methods_supported: ['header'];
24
+ }
25
+ export declare const MCP_DEPLOYMENT_CONFIG: unique symbol;
26
+ /**
27
+ * Derives the OAuth 2.0 Protected Resource Metadata (PRM) URL per RFC 9728 §3.1
28
+ * by inserting `/.well-known/oauth-protected-resource` between the host and path
29
+ * of the canonical resource URL.
30
+ */
31
+ export declare function derivePrmUrl(canonicalResourceUrl: string): string;
32
+ /**
33
+ * Derives the HTTP pathname for the PRM route from a canonical resource URL.
34
+ */
35
+ export declare function derivePrmPathname(canonicalResourceUrl: string): string;
36
+ /**
37
+ * Validates MCP deployment configuration (fail-closed at startup).
38
+ * Checks that enabled resources have valid absolute URLs without query/fragment,
39
+ * employee path ends with `/mcp`, admin URL equals employee URL + `/admin`,
40
+ * and admin-specific scope/role/step-up settings are safe and complete when enabled.
41
+ */
42
+ export declare function validateMcpDeploymentConfig(config: McpIamDeploymentConfig): void;
43
+ /**
44
+ * Zod schema for the `iam` configRef fields required by `@haneinfo/mcp-server`.
45
+ * Allows other `IamDeploymentConfig` fields (such as `profileId`, `capabilities`, `web`)
46
+ * without depending on `@haneinfo/iam-keycloak`.
47
+ */
48
+ export declare const mcpIamDeploymentConfigSchema: z.ZodObject<{
49
+ issuer: z.ZodString;
50
+ mcp: z.ZodObject<{
51
+ employee: z.ZodObject<{
52
+ enabled: z.ZodBoolean;
53
+ canonicalResourceUrl: z.ZodString;
54
+ allowedClientIds: z.ZodReadonly<z.ZodArray<z.ZodString>>;
55
+ }, z.core.$strip>;
56
+ admin: z.ZodObject<{
57
+ enabled: z.ZodBoolean;
58
+ canonicalResourceUrl: z.ZodString;
59
+ allowedClientIds: z.ZodReadonly<z.ZodArray<z.ZodString>>;
60
+ maxAuthAgeSeconds: z.ZodNumber;
61
+ requiredScope: z.ZodOptional<z.ZodString>;
62
+ adminRoleNames: z.ZodOptional<z.ZodReadonly<z.ZodArray<z.ZodString>>>;
63
+ stepUpAcrValues: z.ZodOptional<z.ZodString>;
64
+ }, z.core.$strip>;
65
+ }, z.core.$strip>;
66
+ }, z.core.$strip>;
67
+ //# sourceMappingURL=deployment-config.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"deployment-config.d.ts","sourceRoot":"","sources":["../src/deployment-config.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB,MAAM,WAAW,2BAA2B;IAC1C,OAAO,EAAE,OAAO,CAAC;IACjB,oBAAoB,EAAE,MAAM,CAAC;IAC7B,gBAAgB,EAAE,SAAS,MAAM,EAAE,CAAC;CACrC;AAED,MAAM,WAAW,sBAAsB;IACrC,MAAM,EAAE,MAAM,CAAC;IACf,GAAG,EAAE;QACH,QAAQ,EAAE,2BAA2B,CAAC;QACtC,KAAK,EAAE,2BAA2B,GAAG;YACnC,iBAAiB,EAAE,MAAM,CAAC;YAC1B,aAAa,CAAC,EAAE,MAAM,CAAC;YACvB,cAAc,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;YACnC,eAAe,CAAC,EAAE,MAAM,CAAC;SAC1B,CAAC;KACH,CAAC;CACH;AAED,MAAM,WAAW,WAAW;IAC1B,QAAQ,EAAE,MAAM,CAAC;IACjB,qBAAqB,EAAE,CAAC,MAAM,CAAC,CAAC;IAChC,gBAAgB,EAAE,MAAM,EAAE,CAAC;IAC3B,wBAAwB,EAAE,CAAC,QAAQ,CAAC,CAAC;CACtC;AAED,eAAO,MAAM,qBAAqB,eAAsD,CAAC;AAyBzF;;;;GAIG;AACH,wBAAgB,YAAY,CAAC,oBAAoB,EAAE,MAAM,GAAG,MAAM,CAIjE;AAED;;GAEG;AACH,wBAAgB,iBAAiB,CAAC,oBAAoB,EAAE,MAAM,GAAG,MAAM,CAGtE;AAYD;;;;;GAKG;AACH,wBAAgB,2BAA2B,CAAC,MAAM,EAAE,sBAAsB,GAAG,IAAI,CAiFhF;AAeD;;;;GAIG;AACH,eAAO,MAAM,4BAA4B;;;;;;;;;;;;;;;;;;iBAiBrC,CAAC"}
@@ -0,0 +1,157 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.mcpIamDeploymentConfigSchema = exports.MCP_DEPLOYMENT_CONFIG = void 0;
4
+ exports.derivePrmUrl = derivePrmUrl;
5
+ exports.derivePrmPathname = derivePrmPathname;
6
+ exports.validateMcpDeploymentConfig = validateMcpDeploymentConfig;
7
+ const zod_1 = require("zod");
8
+ exports.MCP_DEPLOYMENT_CONFIG = Symbol.for('haneinfo.mcp-server.deployment-config');
9
+ /**
10
+ * Validates that a string is an absolute URL without query or fragment components,
11
+ * and returns the parsed URL.
12
+ */
13
+ function parseCanonicalUrl(raw, label) {
14
+ if (raw.includes('?') || raw.includes('#')) {
15
+ throw new Error(`${label} must not contain query or fragment components`);
16
+ }
17
+ let parsed;
18
+ try {
19
+ parsed = new URL(raw);
20
+ }
21
+ catch {
22
+ throw new Error(`${label} must be a valid absolute URL`);
23
+ }
24
+ if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
25
+ throw new Error(`${label} must use http or https protocol`);
26
+ }
27
+ if (parsed.search.length > 0 || parsed.hash.length > 0) {
28
+ throw new Error(`${label} must not contain query or fragment components`);
29
+ }
30
+ return parsed;
31
+ }
32
+ /**
33
+ * Derives the OAuth 2.0 Protected Resource Metadata (PRM) URL per RFC 9728 §3.1
34
+ * by inserting `/.well-known/oauth-protected-resource` between the host and path
35
+ * of the canonical resource URL.
36
+ */
37
+ function derivePrmUrl(canonicalResourceUrl) {
38
+ const url = parseCanonicalUrl(canonicalResourceUrl, 'canonicalResourceUrl');
39
+ const pathSuffix = url.pathname === '/' ? '' : url.pathname;
40
+ return `${url.origin}/.well-known/oauth-protected-resource${pathSuffix}`;
41
+ }
42
+ /**
43
+ * Derives the HTTP pathname for the PRM route from a canonical resource URL.
44
+ */
45
+ function derivePrmPathname(canonicalResourceUrl) {
46
+ const prmUrl = derivePrmUrl(canonicalResourceUrl);
47
+ return new URL(prmUrl).pathname;
48
+ }
49
+ function hasUnsafeHeaderChars(value) {
50
+ for (let i = 0; i < value.length; i += 1) {
51
+ const code = value.charCodeAt(i);
52
+ if (code <= 0x1f || code === 0x7f || code === 0x22 || code === 0x5c) {
53
+ return true;
54
+ }
55
+ }
56
+ return false;
57
+ }
58
+ /**
59
+ * Validates MCP deployment configuration (fail-closed at startup).
60
+ * Checks that enabled resources have valid absolute URLs without query/fragment,
61
+ * employee path ends with `/mcp`, admin URL equals employee URL + `/admin`,
62
+ * and admin-specific scope/role/step-up settings are safe and complete when enabled.
63
+ */
64
+ function validateMcpDeploymentConfig(config) {
65
+ if (!config.issuer || config.issuer.trim().length === 0) {
66
+ throw new Error('issuer must be a non-empty string');
67
+ }
68
+ const { employee, admin } = config.mcp;
69
+ if (employee.enabled) {
70
+ const employeeUrl = parseCanonicalUrl(employee.canonicalResourceUrl, 'mcp.employee.canonicalResourceUrl');
71
+ if (!employeeUrl.pathname.endsWith('/mcp')) {
72
+ throw new Error('mcp.employee.canonicalResourceUrl path must end with /mcp');
73
+ }
74
+ if (employee.allowedClientIds.length === 0) {
75
+ throw new Error('mcp.employee.allowedClientIds must not be empty when enabled');
76
+ }
77
+ }
78
+ if (admin.adminRoleNames !== undefined) {
79
+ if (!Array.isArray(admin.adminRoleNames) ||
80
+ admin.adminRoleNames.length === 0 ||
81
+ admin.adminRoleNames.some((role) => typeof role !== 'string' || role.trim().length === 0)) {
82
+ throw new Error('mcp.admin.adminRoleNames must be a non-empty array when provided');
83
+ }
84
+ }
85
+ if (admin.requiredScope !== undefined) {
86
+ if (typeof admin.requiredScope !== 'string' ||
87
+ admin.requiredScope.length === 0 ||
88
+ /\s/.test(admin.requiredScope) ||
89
+ hasUnsafeHeaderChars(admin.requiredScope)) {
90
+ throw new Error('mcp.admin.requiredScope must be a non-empty string without whitespace, quotes, backslashes, or control characters');
91
+ }
92
+ }
93
+ if (admin.stepUpAcrValues !== undefined) {
94
+ if (typeof admin.stepUpAcrValues !== 'string' ||
95
+ admin.stepUpAcrValues.trim().length === 0 ||
96
+ hasUnsafeHeaderChars(admin.stepUpAcrValues)) {
97
+ throw new Error('mcp.admin.stepUpAcrValues must be a non-empty string without quotes, backslashes, or control characters');
98
+ }
99
+ }
100
+ if (admin.enabled) {
101
+ const adminUrl = parseCanonicalUrl(admin.canonicalResourceUrl, 'mcp.admin.canonicalResourceUrl');
102
+ if (!adminUrl.pathname.endsWith('/mcp/admin')) {
103
+ throw new Error('mcp.admin.canonicalResourceUrl path must end with /mcp/admin');
104
+ }
105
+ if (admin.canonicalResourceUrl !== `${employee.canonicalResourceUrl}/admin`) {
106
+ throw new Error('mcp.admin.canonicalResourceUrl must equal mcp.employee.canonicalResourceUrl + "/admin"');
107
+ }
108
+ if (admin.allowedClientIds.length === 0) {
109
+ throw new Error('mcp.admin.allowedClientIds must not be empty when enabled');
110
+ }
111
+ if (!Number.isInteger(admin.maxAuthAgeSeconds) || admin.maxAuthAgeSeconds <= 0) {
112
+ throw new Error('mcp.admin.maxAuthAgeSeconds must be a positive integer');
113
+ }
114
+ if (admin.requiredScope === undefined) {
115
+ throw new Error('mcp.admin.requiredScope is required when mcp.admin.enabled is true');
116
+ }
117
+ if (admin.stepUpAcrValues === undefined) {
118
+ throw new Error('mcp.admin.stepUpAcrValues is required when mcp.admin.enabled is true');
119
+ }
120
+ }
121
+ }
122
+ const mcpResourceSchema = zod_1.z.object({
123
+ enabled: zod_1.z.boolean(),
124
+ canonicalResourceUrl: zod_1.z.string().min(1),
125
+ allowedClientIds: zod_1.z.array(zod_1.z.string().min(1)).readonly(),
126
+ });
127
+ const mcpAdminResourceSchema = mcpResourceSchema.extend({
128
+ maxAuthAgeSeconds: zod_1.z.number().int().positive(),
129
+ requiredScope: zod_1.z.string().min(1).optional(),
130
+ adminRoleNames: zod_1.z.array(zod_1.z.string().min(1)).min(1).readonly().optional(),
131
+ stepUpAcrValues: zod_1.z.string().min(1).optional(),
132
+ });
133
+ /**
134
+ * Zod schema for the `iam` configRef fields required by `@haneinfo/mcp-server`.
135
+ * Allows other `IamDeploymentConfig` fields (such as `profileId`, `capabilities`, `web`)
136
+ * without depending on `@haneinfo/iam-keycloak`.
137
+ */
138
+ exports.mcpIamDeploymentConfigSchema = zod_1.z
139
+ .object({
140
+ issuer: zod_1.z.string().min(1),
141
+ mcp: zod_1.z.object({
142
+ employee: mcpResourceSchema,
143
+ admin: mcpAdminResourceSchema,
144
+ }),
145
+ })
146
+ .superRefine((value, ctx) => {
147
+ try {
148
+ validateMcpDeploymentConfig(value);
149
+ }
150
+ catch (err) {
151
+ ctx.addIssue({
152
+ code: 'custom',
153
+ message: err instanceof Error ? err.message : String(err),
154
+ });
155
+ }
156
+ });
157
+ //# sourceMappingURL=deployment-config.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"deployment-config.js","sourceRoot":"","sources":["../src/deployment-config.ts"],"names":[],"mappings":";;;AA0DA,oCAIC;AAKD,8CAGC;AAkBD,kEAiFC;AAzKD,6BAAwB;AA4BX,QAAA,qBAAqB,GAAG,MAAM,CAAC,GAAG,CAAC,uCAAuC,CAAC,CAAC;AAEzF;;;GAGG;AACH,SAAS,iBAAiB,CAAC,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