@3ngram/server 0.7.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 (116) hide show
  1. package/LICENSE +202 -0
  2. package/dist/app.d.ts +72 -0
  3. package/dist/app.js +273 -0
  4. package/dist/app.js.map +1 -0
  5. package/dist/boot.d.ts +37 -0
  6. package/dist/boot.js +53 -0
  7. package/dist/boot.js.map +1 -0
  8. package/dist/composition/extension.d.ts +50 -0
  9. package/dist/composition/extension.js +16 -0
  10. package/dist/composition/extension.js.map +1 -0
  11. package/dist/index.d.ts +1 -0
  12. package/dist/index.js +10 -0
  13. package/dist/index.js.map +1 -0
  14. package/dist/links.d.ts +17 -0
  15. package/dist/links.js +46 -0
  16. package/dist/links.js.map +1 -0
  17. package/dist/mailer.d.ts +58 -0
  18. package/dist/mailer.js +187 -0
  19. package/dist/mailer.js.map +1 -0
  20. package/dist/mcp/errors.d.ts +14 -0
  21. package/dist/mcp/errors.js +175 -0
  22. package/dist/mcp/errors.js.map +1 -0
  23. package/dist/mcp/prompts.d.ts +29 -0
  24. package/dist/mcp/prompts.js +180 -0
  25. package/dist/mcp/prompts.js.map +1 -0
  26. package/dist/mcp/server.d.ts +14 -0
  27. package/dist/mcp/server.js +34 -0
  28. package/dist/mcp/server.js.map +1 -0
  29. package/dist/mcp/tools-admin.d.ts +8 -0
  30. package/dist/mcp/tools-admin.js +260 -0
  31. package/dist/mcp/tools-admin.js.map +1 -0
  32. package/dist/mcp/tools-orient.d.ts +6 -0
  33. package/dist/mcp/tools-orient.js +110 -0
  34. package/dist/mcp/tools-orient.js.map +1 -0
  35. package/dist/mcp/tools.d.ts +88 -0
  36. package/dist/mcp/tools.js +375 -0
  37. package/dist/mcp/tools.js.map +1 -0
  38. package/dist/middleware/api-key.d.ts +13 -0
  39. package/dist/middleware/api-key.js +83 -0
  40. package/dist/middleware/api-key.js.map +1 -0
  41. package/dist/middleware/api-or-session.d.ts +9 -0
  42. package/dist/middleware/api-or-session.js +22 -0
  43. package/dist/middleware/api-or-session.js.map +1 -0
  44. package/dist/middleware/authenticate.d.ts +21 -0
  45. package/dist/middleware/authenticate.js +51 -0
  46. package/dist/middleware/authenticate.js.map +1 -0
  47. package/dist/middleware/index.d.ts +1 -0
  48. package/dist/middleware/index.js +9 -0
  49. package/dist/middleware/index.js.map +1 -0
  50. package/dist/middleware/oauth-bearer.d.ts +8 -0
  51. package/dist/middleware/oauth-bearer.js +117 -0
  52. package/dist/middleware/oauth-bearer.js.map +1 -0
  53. package/dist/middleware/rate-limit.d.ts +58 -0
  54. package/dist/middleware/rate-limit.js +139 -0
  55. package/dist/middleware/rate-limit.js.map +1 -0
  56. package/dist/middleware/request-context.d.ts +7 -0
  57. package/dist/middleware/request-context.js +14 -0
  58. package/dist/middleware/request-context.js.map +1 -0
  59. package/dist/output-validation.d.ts +18 -0
  60. package/dist/output-validation.js +30 -0
  61. package/dist/output-validation.js.map +1 -0
  62. package/dist/redis.d.ts +9 -0
  63. package/dist/redis.js +37 -0
  64. package/dist/redis.js.map +1 -0
  65. package/dist/rest/cursor.d.ts +14 -0
  66. package/dist/rest/cursor.js +38 -0
  67. package/dist/rest/cursor.js.map +1 -0
  68. package/dist/rest/errors.d.ts +14 -0
  69. package/dist/rest/errors.js +119 -0
  70. package/dist/rest/errors.js.map +1 -0
  71. package/dist/rest/router.d.ts +33 -0
  72. package/dist/rest/router.js +846 -0
  73. package/dist/rest/router.js.map +1 -0
  74. package/dist/rest/scope.d.ts +14 -0
  75. package/dist/rest/scope.js +45 -0
  76. package/dist/rest/scope.js.map +1 -0
  77. package/dist/routes/api-keys.d.ts +2 -0
  78. package/dist/routes/api-keys.js +77 -0
  79. package/dist/routes/api-keys.js.map +1 -0
  80. package/dist/routes/auth.d.ts +20 -0
  81. package/dist/routes/auth.js +325 -0
  82. package/dist/routes/auth.js.map +1 -0
  83. package/dist/routes/capabilities.d.ts +10 -0
  84. package/dist/routes/capabilities.js +17 -0
  85. package/dist/routes/capabilities.js.map +1 -0
  86. package/dist/routes/health.d.ts +7 -0
  87. package/dist/routes/health.js +12 -0
  88. package/dist/routes/health.js.map +1 -0
  89. package/dist/routes/mcp.d.ts +27 -0
  90. package/dist/routes/mcp.js +81 -0
  91. package/dist/routes/mcp.js.map +1 -0
  92. package/dist/routes/oauth-authorize.d.ts +8 -0
  93. package/dist/routes/oauth-authorize.js +245 -0
  94. package/dist/routes/oauth-authorize.js.map +1 -0
  95. package/dist/routes/oauth-clients.d.ts +2 -0
  96. package/dist/routes/oauth-clients.js +59 -0
  97. package/dist/routes/oauth-clients.js.map +1 -0
  98. package/dist/routes/oauth-register.d.ts +8 -0
  99. package/dist/routes/oauth-register.js +59 -0
  100. package/dist/routes/oauth-register.js.map +1 -0
  101. package/dist/routes/oauth-token.d.ts +30 -0
  102. package/dist/routes/oauth-token.js +451 -0
  103. package/dist/routes/oauth-token.js.map +1 -0
  104. package/dist/routes/onboarding.d.ts +2 -0
  105. package/dist/routes/onboarding.js +47 -0
  106. package/dist/routes/onboarding.js.map +1 -0
  107. package/dist/routes/profile.d.ts +2 -0
  108. package/dist/routes/profile.js +35 -0
  109. package/dist/routes/profile.js.map +1 -0
  110. package/dist/routes/well-known.d.ts +2 -0
  111. package/dist/routes/well-known.js +77 -0
  112. package/dist/routes/well-known.js.map +1 -0
  113. package/dist/version.d.ts +1 -0
  114. package/dist/version.js +17 -0
  115. package/dist/version.js.map +1 -0
  116. package/package.json +67 -0
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
202
+
package/dist/app.d.ts ADDED
@@ -0,0 +1,72 @@
1
+ import { type Gateway } from '@3ngram/llm';
2
+ import { type Express } from 'express';
3
+ import type { Redis } from 'ioredis';
4
+ import { type Extension } from './composition/extension.js';
5
+ import { type RateLimiterMiddleware } from './middleware/rate-limit.js';
6
+ export type { Extension } from './composition/extension.js';
7
+ /** App-factory options. The gateway seam lets tests inject a fake; boot derives it from env. */
8
+ export interface AppOptions {
9
+ /**
10
+ * Embedding gateway for the MCP tools. When omitted, it is derived from env
11
+ * (ADR-0007, env-gated): a real OpenAI-compatible client iff LLM_GATEWAY_URL +
12
+ * LLM_GATEWAY_API_KEY are set, else undefined (search returns a typed
13
+ * "not configured" error and remember runs with embedding off).
14
+ */
15
+ gateway?: Gateway;
16
+ /**
17
+ * Rate-limiter seam. When omitted, boot builds Redis-backed limiters
18
+ * iff REDIS_URL is set (else in-memory). Tests inject limiters directly so NO
19
+ * real Redis is required in CI:
20
+ * - `mcpLimiter` — per-user bucket on /mcp (req.userId, set by oauthBearerAuth).
21
+ * - `authLimiter` — per-IP bucket on /auth/login (ADR-0009 §6; req.ip is the
22
+ * real client because trust proxy is set).
23
+ * Provide `redis` instead to let boot construct the default limiters over an
24
+ * explicit client (or omit both for the env-derived client).
25
+ */
26
+ mcpLimiter?: RateLimiterMiddleware;
27
+ authLimiter?: RateLimiterMiddleware;
28
+ /**
29
+ * Per-IP buckets for the five public self-serve auth endpoints. Each
30
+ * carries its own threshold (signup 5/min, resend-verification 3/min,
31
+ * verify-email 10/min, forgot-password 3/min, reset-password 5/min) keyed on
32
+ * req.ip; the shared `authLimiter` still guards /auth/login + change-password.
33
+ * Tests inject these directly (no Redis); when omitted boot builds the defaults.
34
+ */
35
+ signupLimiter?: RateLimiterMiddleware;
36
+ resendVerificationLimiter?: RateLimiterMiddleware;
37
+ verifyEmailLimiter?: RateLimiterMiddleware;
38
+ forgotPasswordLimiter?: RateLimiterMiddleware;
39
+ resetPasswordLimiter?: RateLimiterMiddleware;
40
+ /**
41
+ * Per-IP limiter for POST /oauth/register (ADR-0009 §6). Defaults to a
42
+ * conservative per-IP bucket built like the two above — /oauth/register is
43
+ * unauthenticated, so it must never ship unlimited. Tuning it is an
44
+ * injection-only change.
45
+ */
46
+ registerLimiter?: RateLimiterMiddleware;
47
+ /**
48
+ * Per-IP limiter shared by GET/POST /oauth/authorize and POST /oauth/token
49
+ * (ADR-0009 §6 — both are unauthenticated surfaces, so a real conservative
50
+ * bucket is the default, mirroring registerLimiter). Tuning it is an
51
+ * injection-only change (incl. failed-exchange progressive delay).
52
+ */
53
+ oauthLimiter?: RateLimiterMiddleware;
54
+ /**
55
+ * Per-API-key limiter on /api/v1. Keyed on req.apiKeyId (the prefix
56
+ * segment set by apiKeyAuth after a successful key lookup). Mounted before
57
+ * apiOrSessionAuth so the cheap bucket runs as the first gate; requests that
58
+ * carry no X-API-Key (and thus have no req.apiKeyId) skip the limiter.
59
+ * Default: 300 req / 60s per key.
60
+ */
61
+ apiKeyLimiter?: RateLimiterMiddleware;
62
+ redis?: Redis | undefined;
63
+ /**
64
+ * Composition seam. When omitted, resolves to `noOpExtension` — the self-host
65
+ * default: zero hosted-only capabilities, no extra routes. The real extension is
66
+ * injected ONLY from the private repo's entrypoint; no Apache package imports it.
67
+ * The boundary is package absence, never a flag.
68
+ */
69
+ extension?: Extension;
70
+ }
71
+ /** App factory — tests drive it in-process; index.ts is the only listener. */
72
+ export declare function createApp(options?: AppOptions): Express;
package/dist/app.js ADDED
@@ -0,0 +1,273 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ import { budgetGateLookupFailure, loadBudgetConfig, loadLlmGatewayConfig, log, } from '@3ngram/config';
3
+ import { crashSafeError } from '@3ngram/config/otel';
4
+ import { allowAllAccess, SELFHOST_LIMITS } from '@3ngram/core';
5
+ import { createOpenAIGateway } from '@3ngram/llm';
6
+ import express, {} from 'express';
7
+ import { baseCapabilities, noOpExtension } from './composition/extension.js';
8
+ import { apiKeyIdKey, createRateLimiter, ipKey, userIdKey, } from './middleware/rate-limit.js';
9
+ import { requestContext } from './middleware/request-context.js';
10
+ import { resolveRedis } from './redis.js';
11
+ import { restRouter } from './rest/router.js';
12
+ import { apiKeysRouter } from './routes/api-keys.js';
13
+ import { authRouter } from './routes/auth.js';
14
+ import { capabilitiesRouter } from './routes/capabilities.js';
15
+ import { healthRouter } from './routes/health.js';
16
+ import { mcpRouter } from './routes/mcp.js';
17
+ import { oauthAuthorizeRouter } from './routes/oauth-authorize.js';
18
+ import { oauthClientsRouter } from './routes/oauth-clients.js';
19
+ import { oauthRegisterRouter } from './routes/oauth-register.js';
20
+ import { oauthTokenRouter } from './routes/oauth-token.js';
21
+ import { onboardingRouter } from './routes/onboarding.js';
22
+ import { profileRouter } from './routes/profile.js';
23
+ import { wellKnownRouter } from './routes/well-known.js';
24
+ /**
25
+ * Per-user bucket on /mcp: 120 requests / 60s. Per-IP on /auth/login: 10 / 60s.
26
+ * Per-IP on /oauth/register: 10 / 60s — registration is a rare, one-time-per-
27
+ * client operation, so a tight bucket bounds the unauthenticated insert path
28
+ * (~33KB/request worst case) without blocking legitimate DCR retries.
29
+ * Per-API-key on /api/v1: 300 req / 60s — a generous ceiling for normal programmatic
30
+ * use while bounding runaway agents or credential-stuffing.
31
+ */
32
+ const MCP_USER_POINTS = 120;
33
+ const AUTH_IP_POINTS = 10;
34
+ // Per-endpoint thresholds (per source IP, per RATE_WINDOW_SECONDS). The
35
+ // public self-serve surface is more abuse-prone than login, so each endpoint
36
+ // gets its own tight bucket instead of the shared 10/min login bucket.
37
+ const SIGNUP_IP_POINTS = 5;
38
+ const RESEND_VERIFICATION_IP_POINTS = 3;
39
+ const VERIFY_EMAIL_IP_POINTS = 10;
40
+ const FORGOT_PASSWORD_IP_POINTS = 3;
41
+ const RESET_PASSWORD_IP_POINTS = 5;
42
+ const REGISTER_IP_POINTS = 10;
43
+ // /oauth/authorize + /oauth/token share one per-IP bucket: a full code flow is
44
+ // ~3 requests (form GET, consent POST, exchange) plus periodic refreshes, so
45
+ // 30/60s bounds abuse without throttling a legitimate multi-client login burst.
46
+ const OAUTH_IP_POINTS = 30;
47
+ const API_KEY_POINTS = 300;
48
+ const RATE_WINDOW_SECONDS = 60;
49
+ /** Resolve the embedding gateway: an explicit override, else the env-gated client. */
50
+ function resolveGateway(override) {
51
+ if (override !== undefined)
52
+ return override;
53
+ const config = loadLlmGatewayConfig();
54
+ return config === undefined ? undefined : createOpenAIGateway(config);
55
+ }
56
+ /**
57
+ * Resolve the rate limiters: explicit overrides win (the test seam), else build
58
+ * the defaults over the injected/env Redis client. Mirrors resolveGateway: a
59
+ * missing Redis client makes createRateLimiter fall back to RateLimiterMemory.
60
+ */
61
+ function resolveLimiters(options, redis) {
62
+ return {
63
+ mcpLimiter: options.mcpLimiter ??
64
+ createRateLimiter({
65
+ points: MCP_USER_POINTS,
66
+ duration: RATE_WINDOW_SECONDS,
67
+ keyPrefix: 'mcp:user',
68
+ keyResolver: userIdKey,
69
+ redis,
70
+ }),
71
+ authLimiter: options.authLimiter ??
72
+ createRateLimiter({
73
+ points: AUTH_IP_POINTS,
74
+ duration: RATE_WINDOW_SECONDS,
75
+ keyPrefix: 'auth:ip',
76
+ keyResolver: ipKey,
77
+ redis,
78
+ }),
79
+ signupLimiter: options.signupLimiter ??
80
+ createRateLimiter({
81
+ points: SIGNUP_IP_POINTS,
82
+ duration: RATE_WINDOW_SECONDS,
83
+ keyPrefix: 'auth:signup:ip',
84
+ keyResolver: ipKey,
85
+ redis,
86
+ }),
87
+ resendVerificationLimiter: options.resendVerificationLimiter ??
88
+ createRateLimiter({
89
+ points: RESEND_VERIFICATION_IP_POINTS,
90
+ duration: RATE_WINDOW_SECONDS,
91
+ keyPrefix: 'auth:resend-verification:ip',
92
+ keyResolver: ipKey,
93
+ redis,
94
+ }),
95
+ verifyEmailLimiter: options.verifyEmailLimiter ??
96
+ createRateLimiter({
97
+ points: VERIFY_EMAIL_IP_POINTS,
98
+ duration: RATE_WINDOW_SECONDS,
99
+ keyPrefix: 'auth:verify-email:ip',
100
+ keyResolver: ipKey,
101
+ redis,
102
+ }),
103
+ forgotPasswordLimiter: options.forgotPasswordLimiter ??
104
+ createRateLimiter({
105
+ points: FORGOT_PASSWORD_IP_POINTS,
106
+ duration: RATE_WINDOW_SECONDS,
107
+ keyPrefix: 'auth:forgot-password:ip',
108
+ keyResolver: ipKey,
109
+ redis,
110
+ }),
111
+ resetPasswordLimiter: options.resetPasswordLimiter ??
112
+ createRateLimiter({
113
+ points: RESET_PASSWORD_IP_POINTS,
114
+ duration: RATE_WINDOW_SECONDS,
115
+ keyPrefix: 'auth:reset-password:ip',
116
+ keyResolver: ipKey,
117
+ redis,
118
+ }),
119
+ registerLimiter: options.registerLimiter ??
120
+ createRateLimiter({
121
+ points: REGISTER_IP_POINTS,
122
+ duration: RATE_WINDOW_SECONDS,
123
+ keyPrefix: 'oauth:register:ip',
124
+ keyResolver: ipKey,
125
+ redis,
126
+ }),
127
+ oauthLimiter: options.oauthLimiter ??
128
+ createRateLimiter({
129
+ points: OAUTH_IP_POINTS,
130
+ duration: RATE_WINDOW_SECONDS,
131
+ keyPrefix: 'oauth:as:ip',
132
+ keyResolver: ipKey,
133
+ redis,
134
+ }),
135
+ apiKeyLimiter: options.apiKeyLimiter ??
136
+ createRateLimiter({
137
+ points: API_KEY_POINTS,
138
+ duration: RATE_WINDOW_SECONDS,
139
+ keyPrefix: 'api:key',
140
+ keyResolver: apiKeyIdKey,
141
+ redis,
142
+ }),
143
+ };
144
+ }
145
+ /** A body-parser parse failure (malformed JSON body) — a 400, not a 500. */
146
+ function isBodyParseError(err) {
147
+ return (err instanceof SyntaxError &&
148
+ 'type' in err &&
149
+ err.type === 'entity.parse.failed');
150
+ }
151
+ /** App factory — tests drive it in-process; index.ts is the only listener. */
152
+ export function createApp(options = {}) {
153
+ const app = express();
154
+ const gateway = resolveGateway(options.gateway);
155
+ // Composition seam: resolve the injected extension or the Apache no-op default.
156
+ // Package absence ⇒ no-op ⇒ self-host runs with the public primitives only (access
157
+ // port, budget caps). The capability document advertises base Apache surfaces ∪
158
+ // the extension's hosted-only capabilities; extension.register attaches its routes
159
+ // below.
160
+ const extension = options.extension ?? noOpExtension;
161
+ // Budget enforcement, constructed ONCE and threaded into BOTH
162
+ // metered transports (REST + MCP) — the two enforcement points.
163
+ // The private repo injects a real limits resolver via the extension seam;
164
+ // self-host (no extension) resolves empty limits, so the budget falls through to
165
+ // the config default cap. The OTel fail-open alert is wired via onLookupFailure
166
+ // so core stays config-free. Self-host runs exactly this wiring and still gets
167
+ // cost caps.
168
+ const budget = {
169
+ resolveLimits: extension.resolveLimits ?? (async () => SELFHOST_LIMITS),
170
+ config: loadBudgetConfig(),
171
+ onLookupFailure: (operation) => budgetGateLookupFailure.add(1, { operation }),
172
+ logger: { warn: (obj, msg) => log().warn(obj, msg) },
173
+ };
174
+ // Access gate, threaded into BOTH metered transports alongside the budget. The
175
+ // private repo injects a real access policy; self-host keeps allowAllAccess.
176
+ const access = extension.access ?? allowAllAccess;
177
+ // Resolve the shared ioredis client ONCE: the rate limiters and the
178
+ // progressive-delay failure tracker both ride it, so dialing twice
179
+ // would open a redundant connection. An explicit override wins (the test
180
+ // seam); else the env-derived client (undefined ⇒ in-memory fallbacks).
181
+ const redis = options.redis ?? resolveRedis();
182
+ const { mcpLimiter, authLimiter, signupLimiter, resendVerificationLimiter, verifyEmailLimiter, forgotPasswordLimiter, resetPasswordLimiter, registerLimiter, oauthLimiter, apiKeyLimiter, } = resolveLimiters(options, redis);
183
+ // Railway terminates TLS at a proxy; without this, req.ip (and the SDK auth
184
+ // router's rate limiter) see the proxy address.
185
+ app.set('trust proxy', 1);
186
+ app.disable('x-powered-by');
187
+ app.use(requestContext);
188
+ // Capture the exact raw bytes alongside JSON parsing so a private webhook
189
+ // (mounted by the extension below) can verify the signature over the
190
+ // unmodified payload — re-serializing a parsed body would change the bytes and
191
+ // break verification. Self-host attaches no webhook, so the
192
+ // captured buffer is simply unused there.
193
+ app.use(express.json({
194
+ verify: (req, _res, buf) => {
195
+ ;
196
+ req.rawBody = buf;
197
+ },
198
+ }));
199
+ app.use(healthRouter);
200
+ app.use(wellKnownRouter);
201
+ // Capability discovery: base Apache surfaces ∪ injected hosted-only
202
+ // capabilities. On self-host (no-op extension) only base capabilities appear.
203
+ app.use(capabilitiesRouter([...baseCapabilities, ...extension.capabilities]));
204
+ app.use(authRouter({
205
+ limiter: authLimiter,
206
+ signupLimiter,
207
+ resendVerificationLimiter,
208
+ verifyEmailLimiter,
209
+ forgotPasswordLimiter,
210
+ resetPasswordLimiter,
211
+ }));
212
+ app.use(apiKeysRouter);
213
+ app.use(oauthClientsRouter);
214
+ // Onboarding connection-status read (GET /auth/onboarding) —
215
+ // session-authed like the api-keys / oauth-clients management surfaces; the
216
+ // dashboard polls it to flip the connect step to "Connected ✓".
217
+ app.use(onboardingRouter);
218
+ app.use(profileRouter);
219
+ app.use(mcpRouter({ gateway, limiter: mcpLimiter, budget, access }));
220
+ // REST /api/v1 mirror (ADR-0011) — behind the
221
+ // apiKeyAuth chain the router applies itself, so it mounts independent of the
222
+ // MCP Bearer mount. APPEND-ONLY after the existing routers, before the error
223
+ // handler. The same env-gated gateway threaded into mcpRouter is threaded here.
224
+ // The per-key limiter is mounted before apiOrSessionAuth in the router.
225
+ app.use(restRouter({
226
+ gateway,
227
+ rateLimiter: apiKeyLimiter,
228
+ budget,
229
+ access,
230
+ // Account-deletion hook: the private repo injects platform-specific cleanup;
231
+ // self-host (no-op extension) runs no extra work.
232
+ onAccountDeletion: extension.onAccountDeletion,
233
+ // GDPR-export enricher: the private repo adds extra user-owned rows to the
234
+ // archive; self-host omits them.
235
+ exportEnricher: extension.exportEnricher,
236
+ }));
237
+ // RFC 7591 dynamic client registration —
238
+ // APPEND-ONLY after the existing routers, before the error handler. Gated by
239
+ // the injected per-IP limiter seam (real bucket by default).
240
+ app.use(oauthRegisterRouter({ limiter: registerLimiter }));
241
+ // OAuth authorize/consent + token endpoints —
242
+ // APPEND-ONLY after the existing routers, before the error handler. Both are
243
+ // unauthenticated and sit behind the shared injected per-IP limiter seam
244
+ // (real bucket by default).
245
+ app.use(oauthAuthorizeRouter({ limiter: oauthLimiter }));
246
+ // The same shared ioredis client backs the progressive-delay failure counter
247
+ // so the budget is shared across Railway replicas; a missing client
248
+ // makes the tracker fall back to a per-process Map.
249
+ app.use(oauthTokenRouter({ limiter: oauthLimiter, redis }));
250
+ // Composition seam: the injected extension attaches its hosted-only
251
+ // routes/handlers here, at the composition root, AFTER every Apache router and
252
+ // BEFORE the error handler. On self-host this is the no-op default (attaches
253
+ // nothing). No Apache package imports the extension — it arrives only via
254
+ // options.extension from the private repo.
255
+ extension.register(app);
256
+ // The 4-arg signature is how express recognizes an error handler. Errors are
257
+ // logged via the crash-safe projection: an Error message built from memory
258
+ // content must not reach stdout raw.
259
+ app.use((err, _req, res, _next) => {
260
+ // A malformed JSON body is a client error: express.json() throws a
261
+ // body-parser SyntaxError (status 400, type 'entity.parse.failed') before
262
+ // any route runs. Surface it as the documented 400 invalid_request contract
263
+ // (ADR-0009) rather than the generic 500.
264
+ if (isBodyParseError(err)) {
265
+ res.status(400).json({ error: 'invalid_request' });
266
+ return;
267
+ }
268
+ log().error(crashSafeError(err), 'server: unhandled error');
269
+ res.status(500).json({ error: 'internal_error' });
270
+ });
271
+ return app;
272
+ }
273
+ //# sourceMappingURL=app.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"app.js","sourceRoot":"","sources":["../src/app.ts"],"names":[],"mappings":"AAAA,sCAAsC;AACtC,OAAO,EACL,uBAAuB,EACvB,gBAAgB,EAChB,oBAAoB,EACpB,GAAG,GACJ,MAAM,gBAAgB,CAAA;AACvB,OAAO,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAA;AACpD,OAAO,EAAE,cAAc,EAA0B,eAAe,EAAE,MAAM,cAAc,CAAA;AACtF,OAAO,EAAE,mBAAmB,EAAgB,MAAM,aAAa,CAAA;AAC/D,OAAO,OAAO,EAAE,EAAgE,MAAM,SAAS,CAAA;AAE/F,OAAO,EAAE,gBAAgB,EAAkB,aAAa,EAAE,MAAM,4BAA4B,CAAA;AAC5F,OAAO,EACL,WAAW,EACX,iBAAiB,EACjB,KAAK,EAEL,SAAS,GACV,MAAM,4BAA4B,CAAA;AACnC,OAAO,EAAE,cAAc,EAAE,MAAM,iCAAiC,CAAA;AAChE,O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AC,CAAA;YAClD,OAAM;QACR,CAAC;QACD,GAAG,EAAE,CAAC,KAAK,CAAC,cAAc,CAAC,GAAG,CAAC,EAAE,yBAAyB,CAAC,CAAA;QAC3D,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,EAAE,KAAK,EAAE,gBAAgB,EAAE,CAAC,CAAA;IACnD,CAAC,CAAC,CAAA;IACF,OAAO,GAAG,CAAA;AACZ,CAAC"}
package/dist/boot.d.ts ADDED
@@ -0,0 +1,37 @@
1
+ import type { Server } from 'node:http';
2
+ import type { Extension } from './composition/extension.js';
3
+ /**
4
+ * The private repo supplies its Extension as a LAZY factory, not a value, so the
5
+ * express/pg module graph it pulls in (its router → @3ngram/db) loads INSIDE
6
+ * bootstrap() — after initObservability() — honoring the OTel load-order contract
7
+ * (a value would force the import eagerly at the call site, before instrumentation,
8
+ * dropping HTTP/pg spans under SENTRY_DSN). A plain value is still accepted for
9
+ * backward compatibility.
10
+ */
11
+ export type ExtensionFactory = () => Extension | Promise<Extension>;
12
+ export interface BootstrapOptions {
13
+ /**
14
+ * Composition seam. The private repo passes its real Extension (as a factory —
15
+ * see {@link ExtensionFactory}); the Apache entry passes nothing (no-op default).
16
+ * createApp derives every other option (gateway, limiters, redis) from env, so
17
+ * the boot path only threads the extension.
18
+ */
19
+ extension?: Extension | ExtensionFactory;
20
+ }
21
+ /**
22
+ * Run the fail-closed boot sequence and start the server:
23
+ * 1. initObservability() FIRST (before express loads — load-order contract).
24
+ * 2. loadEnv() — refuse-by-construction: a misconfigured process dies at boot.
25
+ * 3. assertMeteredOperationsRegistered() — every metered LLM op has a maxCost
26
+ * (ADR-0007); a missing entry is a loud startup failure, not a runtime
27
+ * surprise.
28
+ * 4. OAuth key validation (when configured) — config validates JWK SHAPE,
29
+ * assertSigningKeysUsable validates KEY MATERIAL as RS256 (ADR-0009; an
30
+ * unusable key kills the process before the first request). Dynamic import
31
+ * keeps core's graph behind initObservability, like the app graph below.
32
+ * 5. Dynamic-import createApp (express graph) and listen; wire signal handlers.
33
+ *
34
+ * Reused verbatim by both entrypoints so hosted cloud gets the SAME fail-closed
35
+ * env/key checks and OTel/request instrumentation as the Apache server.
36
+ */
37
+ export declare function bootstrap(options?: BootstrapOptions): Promise<Server>;
package/dist/boot.js ADDED
@@ -0,0 +1,53 @@
1
+ import { loadEnv, loadOAuthConfig, log } from '@3ngram/config';
2
+ import { initObservability } from '@3ngram/config/otel';
3
+ // Zero-dep, fetch-based package — safe to static-import (no express/OTel graph,
4
+ // so it does not violate the load-order contract above).
5
+ import { assertMeteredOperationsRegistered } from '@3ngram/llm';
6
+ /** Resolve the extension seam: invoke a factory (after initObservability) or pass a value through. */
7
+ async function resolveExtension(extension) {
8
+ if (typeof extension === 'function')
9
+ return extension();
10
+ return extension;
11
+ }
12
+ /**
13
+ * Run the fail-closed boot sequence and start the server:
14
+ * 1. initObservability() FIRST (before express loads — load-order contract).
15
+ * 2. loadEnv() — refuse-by-construction: a misconfigured process dies at boot.
16
+ * 3. assertMeteredOperationsRegistered() — every metered LLM op has a maxCost
17
+ * (ADR-0007); a missing entry is a loud startup failure, not a runtime
18
+ * surprise.
19
+ * 4. OAuth key validation (when configured) — config validates JWK SHAPE,
20
+ * assertSigningKeysUsable validates KEY MATERIAL as RS256 (ADR-0009; an
21
+ * unusable key kills the process before the first request). Dynamic import
22
+ * keeps core's graph behind initObservability, like the app graph below.
23
+ * 5. Dynamic-import createApp (express graph) and listen; wire signal handlers.
24
+ *
25
+ * Reused verbatim by both entrypoints so hosted cloud gets the SAME fail-closed
26
+ * env/key checks and OTel/request instrumentation as the Apache server.
27
+ */
28
+ export async function bootstrap(options = {}) {
29
+ initObservability();
30
+ const env = loadEnv();
31
+ assertMeteredOperationsRegistered();
32
+ if (env.BASE_URL !== undefined && env.OAUTH_JWKS !== undefined) {
33
+ const { assertSigningKeysUsable } = await import('@3ngram/core/auth');
34
+ await assertSigningKeysUsable(loadOAuthConfig().keys);
35
+ }
36
+ // Resolve the extension AFTER initObservability(): a factory pulls its
37
+ // express/pg graph in here, behind the OTel load-order contract.
38
+ const extension = await resolveExtension(options.extension);
39
+ const { createApp } = await import('./app.js');
40
+ // Pass `extension` only when present (exactOptionalPropertyTypes): an explicit
41
+ // `undefined` is not assignable to the optional AppOptions.extension.
42
+ const server = createApp(extension === undefined ? {} : { extension }).listen(env.PORT, () => {
43
+ log().info({ port: env.PORT }, 'server: listening');
44
+ });
45
+ for (const signal of ['SIGINT', 'SIGTERM']) {
46
+ process.on(signal, () => {
47
+ log().info({ signal }, 'server: shutting down');
48
+ server.close(() => process.exit(0));
49
+ });
50
+ }
51
+ return server;
52
+ }
53
+ //# sourceMappingURL=boot.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"boot.js","sourceRoot":"","sources":["../src/boot.ts"],"names":[],"mappings":"AAaA,OAAO,EAAE,OAAO,EAAE,eAAe,EAAE,GAAG,EAAE,MAAM,gBAAgB,CAAA;AAC9D,OAAO,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAA;AACvD,gFAAgF;AAChF,yDAAyD;AACzD,OAAO,EAAE,iCAAiC,EAAE,MAAM,aAAa,CAAA;AAuB/D,sGAAsG;AACtG,KAAK,UAAU,gBAAgB,CAC7B,SAAmD;IAEnD,IAAI,OAAO,SAAS,KAAK,UAAU;QAAE,OAAO,SAAS,EAAE,CAAA;IACvD,OAAO,SAAS,CAAA;AAClB,CAAC;AAED;;;;;;;;;;;;;;;GAeG;AACH,MAAM,CAAC,KAAK,UAAU,SAAS,CAAC,UAA4B,EAAE;IAC5D,iBAAiB,EAAE,CAAA;IACnB,MAAM,GAAG,GAAG,OAAO,EAAE,CAAA;IACrB,iCAAiC,EAAE,CAAA;IACnC,IAAI,GAAG,CAAC,QAAQ,KAAK,SAAS,IAAI,GAAG,CAAC,UAAU,KAAK,SAAS,EAAE,CAAC;QAC/D,MAAM,EAAE,uBAAuB,EAAE,GAAG,MAAM,MAAM,CAAC,mBAAmB,CAAC,CAAA;Q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