@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
@@ -0,0 +1,451 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // POST /oauth/token transport. Thin by
3
+ // contract: validate at the one boundary (tokenRequestSchema),
4
+ // authenticate the client, delegate the grant exchange to the core provider,
5
+ // shape the RFC 6749 response.
6
+ //
7
+ // CLIENT AUTH IS CUSTOM (by design): the SDK's authenticateClient
8
+ // middleware compares a PLAINTEXT secret against what the clients store
9
+ // returns — but our store never returns secret material (only the SHA-256 hash
10
+ // is at rest), so the SDK default cannot work. authenticateClientCredentials
11
+ // (core) hashes the presented secret and compares against the stored hash.
12
+ // SDK 1.29 reads client credentials from req.body ONLY, so a Basic-auth
13
+ // shim decodes `Authorization: Basic` into the body first (RFC 6749 §2.3.1) —
14
+ // that is how client_secret_basic (the RFC 7591 default) is honored.
15
+ //
16
+ // ERRORS ARE THE SDK'S TYPED ERRORS ONLY: every failure maps to
17
+ // an OAuthError subclass and its RFC 6749 response object — a generic Error
18
+ // becomes the opaque ServerError 500 and is logged crash-safe. Token, code,
19
+ // and secret material never enter a log line or an error body.
20
+ import { contentDigest, loadOAuthConfig, log } from '@3ngram/config';
21
+ import { crashSafeError } from '@3ngram/config/otel';
22
+ import { authenticateClientCredentials, createOAuthServerProvider, insertAuditLog, OAuthGrantError, touchClientLastUsed, } from '@3ngram/core/auth';
23
+ import { tokenRequestSchema } from '@3ngram/schema';
24
+ import { InvalidClientError, InvalidGrantError, InvalidRequestError, InvalidTargetError, InvalidTokenError, OAuthError, ServerError, UnsupportedGrantTypeError, } from '@modelcontextprotocol/sdk/server/auth/errors.js';
25
+ import { Router, urlencoded } from 'express';
26
+ /** Which channel carried the client credentials — used to enforce the registered method. */
27
+ const PRESENTED_AUTH_METHOD = Symbol('presentedAuthMethod');
28
+ /**
29
+ * Set by the shim when the presented client authentication is itself
30
+ * malformed (an unparseable Basic header, or a Basic identity that conflicts
31
+ * with a posted client_id). The handler turns this into a uniform
32
+ * invalid_client BEFORE any schema/provider work so the failure is no oracle.
33
+ */
34
+ const CLIENT_AUTH_INVALID = Symbol('clientAuthInvalid');
35
+ /** Read the channel the shim attributed the credentials to (undefined = public/none). */
36
+ function presentedAuthMethod(req) {
37
+ return req[PRESENTED_AUTH_METHOD];
38
+ }
39
+ /** True when the shim already determined the presented client auth is invalid. */
40
+ function clientAuthIsInvalid(req) {
41
+ return req[CLIENT_AUTH_INVALID] === true;
42
+ }
43
+ /** Decode an `Authorization: Basic` header into client_id/client_secret, or undefined when malformed. */
44
+ function decodeBasicCredentials(header) {
45
+ let decoded;
46
+ try {
47
+ decoded = Buffer.from(header.slice('basic '.length).trim(), 'base64').toString('utf8');
48
+ }
49
+ catch {
50
+ return undefined;
51
+ }
52
+ const sep = decoded.indexOf(':');
53
+ // RFC 6749 §2.3.1: both fields are present and the separator is a colon, so a
54
+ // non-empty client_id (username) before the first colon is required.
55
+ if (sep <= 0)
56
+ return undefined;
57
+ // RFC 6749 §2.3.1 form-encodes both fields, but a client may present invalid
58
+ // percent-encoding (e.g. a bare `%` or `%ZZ`); decodeURIComponent throws a
59
+ // URIError on those. Treat them as a malformed Basic header (invalid_client),
60
+ // not a generic 500, so the failure stays a uniform OAuth error / no oracle.
61
+ try {
62
+ return {
63
+ clientId: decodeURIComponent(decoded.slice(0, sep)),
64
+ clientSecret: decodeURIComponent(decoded.slice(sep + 1)),
65
+ };
66
+ }
67
+ catch {
68
+ return undefined;
69
+ }
70
+ }
71
+ /**
72
+ * RFC 6749 §2.3.1 / §3.2.1 client-authentication shim (S4). The SDK reads
73
+ * credentials from req.body only, so this normalizes every accepted channel
74
+ * into the body the schema validates AND attributes the presented method so the
75
+ * auth step can enforce the registered token_endpoint_auth_method:
76
+ *
77
+ * - `Authorization: Basic` present → ALWAYS decode it; the username is
78
+ * client_id, the password is client_secret, method = client_secret_basic.
79
+ * RFC 6749 §3.2.1 lets a client ALSO post client_id, so a posted client_id
80
+ * that MATCHES the Basic username is accepted; a CONFLICTING one is rejected
81
+ * (§2.3: a client MUST NOT use more than one authentication method).
82
+ * - No Basic header, body carries client_secret → client_secret_post.
83
+ * - No Basic header, body carries only client_id → the public / client_id-as
84
+ * -parameter path (§3.2.1): no secret presented, method left undefined; the
85
+ * auth step admits this ONLY for clients registered 'none' (PKCE enforced
86
+ * upstream).
87
+ * - A malformed Basic header (not base64 / no colon) → marked invalid_client;
88
+ * it never silently falls through to a different method.
89
+ */
90
+ function shimBasicAuth(req, _res, next) {
91
+ const tagged = req;
92
+ const header = req.header('authorization');
93
+ // An empty POST or an unsupported Content-Type leaves req.body undefined;
94
+ // default to {} so the schema (not a dereference crash) reports the failure
95
+ // as invalid_request (400) rather than a generic ServerError (500).
96
+ const body = (req.body ?? {});
97
+ const hasBasic = header?.toLowerCase().startsWith('basic ') === true;
98
+ if (!hasBasic) {
99
+ // No Authorization: Basic — a body-carried secret is client_secret_post;
100
+ // a body with only client_id is the public / §3.2.1 parameter path.
101
+ if (typeof body.client_secret === 'string')
102
+ tagged[PRESENTED_AUTH_METHOD] = 'client_secret_post';
103
+ next();
104
+ return;
105
+ }
106
+ const credentials = decodeBasicCredentials(header);
107
+ if (credentials === undefined) {
108
+ // Malformed Basic header: do NOT fall through to another method.
109
+ tagged[CLIENT_AUTH_INVALID] = true;
110
+ next();
111
+ return;
112
+ }
113
+ // RFC 6749 §3.2.1 + §2.3: a posted client_id may accompany Basic, but it MUST
114
+ // identify the same client — a conflicting identity is invalid_client.
115
+ if (typeof body.client_id === 'string' && body.client_id !== credentials.clientId) {
116
+ tagged[CLIENT_AUTH_INVALID] = true;
117
+ next();
118
+ return;
119
+ }
120
+ body.client_id = credentials.clientId;
121
+ body.client_secret = credentials.clientSecret;
122
+ tagged[PRESENTED_AUTH_METHOD] = 'client_secret_basic';
123
+ next();
124
+ }
125
+ // ---------------------------------------------------------------------------
126
+ // Progressive delay on repeated failed token exchanges (Redis-backed).
127
+ //
128
+ // The failure counter is keyed `oauth:exchange-failure:{client_id}` and lives in
129
+ // Redis (INCR + EXPIRE) so the budget is SHARED across Railway replicas — the
130
+ // per-process Map gave each replica its own budget, defeatable by
131
+ // rotating exchanges across replicas. When no Redis client is injected
132
+ // (single-instance / CI) the tracker falls back to an in-process Map, mirroring
133
+ // the rate-limiter's RateLimiterMemory fallback.
134
+ //
135
+ // FAIL-OPEN on Redis-down (DECISION, mirrors rate-limit.ts): the progressive
136
+ // delay is a protective control, not correctness — a Redis outage must NOT take
137
+ // down the token endpoint. recordExchangeFailure swallows store errors (the
138
+ // counter simply does not advance) and applyProgressiveDelay treats a store
139
+ // failure as "no recorded failures" (count 0, no delay). The connection string
140
+ // is a credential and client_id is identifying material — neither enters a log
141
+ // line; only the redacted error name is logged.
142
+ //
143
+ // RESET TTL (DECISION): every recordExchangeFailure (re)sets a 900s (15-minute)
144
+ // sliding EXPIRE on the counter. This auto-forgives a client that stops failing
145
+ // for 15 minutes (a legitimate client whose config is fixed recovers without a
146
+ // successful exchange) while keeping the delay ramped across a sustained attack
147
+ // burst. A successful exchange clears the counter immediately. On the Redis
148
+ // path the INCR + EXPIRE run in ONE MULTI/EXEC, so the EXPIRE always lands with
149
+ // the INCR (a crash between them can never leave a TTL-less key) and growth stays
150
+ // bounded: Redis reclaims idle keys on expiry, so attacker-enumerated client_ids
151
+ // cannot accumulate unbounded. The no-Redis Map
152
+ // fallback has no TTL, so it retains the 10k-entry FIFO eviction cap
153
+ // (EXCHANGE_FAILURES_MAX) to keep the same DoS bound on single-instance deploys.
154
+ // ---------------------------------------------------------------------------
155
+ const DELAY_THRESHOLD = 3;
156
+ const MAX_DELAY_MS = 8000;
157
+ // Sliding reset window: a counter with no new failure for this many seconds
158
+ // expires, forgiving the client. Refreshed on every recorded failure.
159
+ const FAILURE_RESET_TTL_SECONDS = 900;
160
+ const EXCHANGE_FAILURE_KEY_PREFIX = 'oauth:exchange-failure:';
161
+ // Hard cap on tracked client_ids in the in-process Map fallback (no-Redis
162
+ // path). The Redis path is bounded by the sliding EXPIRE, but the Map has no
163
+ // TTL, so an attacker enumerating schema-valid client_ids could otherwise drive
164
+ // unbounded heap growth. Evict the oldest insertion at the cap (Map
165
+ // preserves insertion order). The Redis path keeps the EXPIRE-based bound.
166
+ const EXCHANGE_FAILURES_MAX = 10_000;
167
+ /** Redis key for a client_id's failure counter (client_id is never logged). */
168
+ function exchangeFailureKey(clientId) {
169
+ return `${EXCHANGE_FAILURE_KEY_PREFIX}${clientId}`;
170
+ }
171
+ /**
172
+ * The per-process fallback counter used when no Redis client is injected
173
+ * (single-instance / CI). Exported for test inspection of the fallback path
174
+ * only — the Redis path is exercised via an injected ioredis-mock client.
175
+ */
176
+ export const _exchangeFailures = new Map();
177
+ /**
178
+ * The injected failure-tracker Redis client, or undefined for the in-process
179
+ * fallback. Set once by oauthTokenRouter at boot; the tracker functions read it
180
+ * so the wiring stays a single injection seam (testable with ioredis-mock).
181
+ */
182
+ let exchangeFailureRedis;
183
+ /** Wire the failure-tracker Redis client (or clear it for the Map fallback). */
184
+ export function setExchangeFailureRedis(redis) {
185
+ exchangeFailureRedis = redis;
186
+ }
187
+ /** Increment the failure counter for a client_id and refresh its reset TTL. */
188
+ export async function recordExchangeFailure(clientId) {
189
+ if (exchangeFailureRedis === undefined) {
190
+ // Enforce the cap before inserting a NEW key: drop the oldest insertion so
191
+ // attacker-enumerated client_ids cannot grow the Map without bound. An
192
+ // existing key just increments (no size change).
193
+ if (!_exchangeFailures.has(clientId) && _exchangeFailures.size >= EXCHANGE_FAILURES_MAX) {
194
+ const oldest = _exchangeFailures.keys().next().value;
195
+ if (oldest !== undefined)
196
+ _exchangeFailures.delete(oldest);
197
+ }
198
+ _exchangeFailures.set(clientId, (_exchangeFailures.get(clientId) ?? 0) + 1);
199
+ return;
200
+ }
201
+ try {
202
+ const key = exchangeFailureKey(clientId);
203
+ // INCR then EXPIRE in ONE MULTI/EXEC: MULTI queues both commands and EXEC
204
+ // runs them atomically server-side, so the key ALWAYS gets its TTL even if
205
+ // the connection drops mid-sequence. This preserves the bounded-growth
206
+ // guarantee — a crash between INCR and EXPIRE can no longer leave a key with
207
+ // no TTL (otherwise an attacker enumerating client_ids grows the keyspace
208
+ // unbounded). The EXPIRE is re-set on every failure so the window slides.
209
+ const results = await exchangeFailureRedis
210
+ .multi()
211
+ .incr(key)
212
+ .expire(key, FAILURE_RESET_TTL_SECONDS)
213
+ .exec();
214
+ // exec() resolves to null only when the transaction was discarded (e.g. a
215
+ // WATCH conflict — none here), and otherwise an array of [err, reply] tuples.
216
+ // Surface a per-command error so the catch swallows it as a record failure
217
+ // (fail-open) rather than silently advancing without the TTL.
218
+ const commandError = results?.find(([err]) => err !== null)?.[0];
219
+ if (commandError)
220
+ throw commandError;
221
+ }
222
+ catch (err) {
223
+ log().warn({ err: err instanceof Error ? err.name : 'unknown' }, 'oauth: exchange-failure record failed');
224
+ }
225
+ }
226
+ /** Clear the failure counter for a client_id (a successful exchange forgives it). */
227
+ export async function clearExchangeFailures(clientId) {
228
+ if (exchangeFailureRedis === undefined) {
229
+ _exchangeFailures.delete(clientId);
230
+ return;
231
+ }
232
+ try {
233
+ await exchangeFailureRedis.del(exchangeFailureKey(clientId));
234
+ }
235
+ catch (err) {
236
+ log().warn({ err: err instanceof Error ? err.name : 'unknown' }, 'oauth: exchange-failure clear failed');
237
+ }
238
+ }
239
+ /** Read the current failure count for a client_id (0 on store failure — fail-open). */
240
+ async function readExchangeFailureCount(clientId) {
241
+ if (exchangeFailureRedis === undefined) {
242
+ return _exchangeFailures.get(clientId) ?? 0;
243
+ }
244
+ try {
245
+ const raw = await exchangeFailureRedis.get(exchangeFailureKey(clientId));
246
+ if (raw === null)
247
+ return 0;
248
+ const count = Number.parseInt(raw, 10);
249
+ return Number.isNaN(count) ? 0 : count;
250
+ }
251
+ catch (err) {
252
+ log().warn({ err: err instanceof Error ? err.name : 'unknown' }, 'oauth: exchange-failure read failed');
253
+ return 0;
254
+ }
255
+ }
256
+ export async function applyProgressiveDelay(clientId) {
257
+ const count = await readExchangeFailureCount(clientId);
258
+ if (count < DELAY_THRESHOLD)
259
+ return;
260
+ const ms = Math.min(1000 * 2 ** (count - DELAY_THRESHOLD), MAX_DELAY_MS);
261
+ await new Promise((resolve) => setTimeout(resolve, ms));
262
+ }
263
+ // First N chars of a client_id we are willing to log. redaction.ts does NOT
264
+ // cover client_id, so the truncation is the load-bearing secret safeguard: a
265
+ // client_secret_basic credential can carry a long opaque id, and we never want
266
+ // the full value (or any code/secret/refresh_token) in a log line (hard rule 6).
267
+ const CLIENT_ID_PREFIX_LEN = 8;
268
+ /**
269
+ * A non-throwing, content-free preview of the presented client_id for the audit
270
+ * line. Legitimate ids are long (`cl_` + uuid), so the first 8 chars are a safe,
271
+ * human-readable strict prefix. But the value is read raw off req.body on the
272
+ * error path: a SHORT (<= 8 char) client-controlled value would be echoed in
273
+ * full, leaking short secret/token material a malformed request could smuggle
274
+ * in. For those, emit a non-reversible `sha8:` fingerprint (the redaction.ts
275
+ * sha256-8 convention) that can NEVER equal the raw input. '(none)' when absent.
276
+ */
277
+ function clientIdPrefix(clientId) {
278
+ if (typeof clientId !== 'string' || clientId.length === 0)
279
+ return '(none)';
280
+ if (clientId.length <= CLIENT_ID_PREFIX_LEN)
281
+ return `sha8:${contentDigest(clientId)}`;
282
+ return clientId.slice(0, CLIENT_ID_PREFIX_LEN);
283
+ }
284
+ // The only grant_type values RFC 6749 §4.1.3/§6 lets this server log verbatim.
285
+ // On the error path grant_type is raw, client-controlled body data that could
286
+ // carry a code/refresh_token/secret, so anything else collapses to '(invalid)'
287
+ // (or '(none)' when absent) before it reaches a log line (hard rule 6).
288
+ const LOGGABLE_GRANT_TYPES = new Set(['authorization_code', 'refresh_token']);
289
+ /**
290
+ * A non-throwing, whitelisted preview of the presented grant_type for the audit
291
+ * line: a known RFC token verbatim, '(none)' when absent, '(invalid)' for any
292
+ * other client-controlled value. NEVER echoes unbounded body data (hard rule 6).
293
+ */
294
+ function grantTypeLabel(grantType) {
295
+ if (grantType === undefined)
296
+ return '(none)';
297
+ return typeof grantType === 'string' && LOGGABLE_GRANT_TYPES.has(grantType)
298
+ ? grantType
299
+ : '(invalid)';
300
+ }
301
+ /**
302
+ * ONE structured, content-free line per /oauth/token request. grant_type
303
+ * is whitelisted to an RFC token (not secret); client_id is truncated to a
304
+ * prefix here; outcome is 'success' or the RFC error code. No token/code/secret/
305
+ * full client_id ever enters this line (hard rule 6). Rides the request-context
306
+ * bindings via log().
307
+ */
308
+ function logTokenOutcome(grantType, clientId, outcome) {
309
+ log().info({
310
+ grant_type: grantTypeLabel(grantType),
311
+ client_id_prefix: clientIdPrefix(clientId),
312
+ outcome,
313
+ }, 'oauth: token endpoint');
314
+ }
315
+ /** Map a thrown failure to the SDK's typed OAuthError (generic -> ServerError 500). */
316
+ function toOAuthError(err) {
317
+ if (err instanceof OAuthError)
318
+ return err;
319
+ if (err instanceof OAuthGrantError) {
320
+ switch (err.code) {
321
+ case 'invalid_grant':
322
+ return new InvalidGrantError('The provided grant is invalid, expired, or revoked');
323
+ case 'invalid_client':
324
+ return new InvalidClientError('Client authentication failed');
325
+ case 'invalid_target':
326
+ return new InvalidTargetError('The requested resource is not served by this server');
327
+ case 'invalid_token':
328
+ return new InvalidTokenError('The access token is invalid');
329
+ }
330
+ }
331
+ return new ServerError('Internal Server Error');
332
+ }
333
+ /**
334
+ * RFC 6749 §3.2/§4.1.3: the token endpoint accepts ONLY a
335
+ * application/x-www-form-urlencoded body. A global express.json() parses a JSON
336
+ * body before this router runs, so a presented Content-Type other than form
337
+ * (notably application/json) must be rejected here — otherwise the route's own
338
+ * urlencoded() middleware is a no-op and a pre-parsed JSON object would be
339
+ * validated as a token request. An ABSENT Content-Type (an empty POST) is left
340
+ * to the missing-grant_type path so it stays the documented invalid_request.
341
+ */
342
+ function rejectsNonFormContentType(req) {
343
+ const contentType = req.headers['content-type'];
344
+ if (contentType === undefined)
345
+ return false;
346
+ return req.is('application/x-www-form-urlencoded') !== 'application/x-www-form-urlencoded';
347
+ }
348
+ /** Dispatch a validated, client-authenticated grant to the core provider. */
349
+ async function handleTokenRequest(req, res) {
350
+ res.setHeader('Cache-Control', 'no-store');
351
+ // RFC 6749 §5.1 also mandates Pragma: no-cache on token-bearing responses.
352
+ res.setHeader('Pragma', 'no-cache');
353
+ if (rejectsNonFormContentType(req)) {
354
+ throw new InvalidRequestError('The token endpoint requires application/x-www-form-urlencoded');
355
+ }
356
+ // A malformed Basic header or a Basic identity conflicting with a posted
357
+ // client_id is a failed client authentication (RFC 6749 §2.3/§3.2.1) — a
358
+ // uniform invalid_client with no oracle, decided before any schema/provider work.
359
+ if (clientAuthIsInvalid(req))
360
+ throw new InvalidClientError('Client authentication failed');
361
+ const body = (req.body ?? {});
362
+ // RFC 6749 §5.2: a request missing required parameters is invalid_request.
363
+ // An absent grant_type (e.g. an empty body) is a malformed request, distinct
364
+ // from a PRESENT-but-unrecognized grant_type (unsupported_grant_type).
365
+ if (body.grant_type === undefined)
366
+ throw new InvalidRequestError('Malformed token request');
367
+ if (body.grant_type !== 'authorization_code' && body.grant_type !== 'refresh_token') {
368
+ throw new UnsupportedGrantTypeError('The grant type is not supported by this server');
369
+ }
370
+ const parsed = tokenRequestSchema.safeParse(body);
371
+ if (!parsed.success)
372
+ throw new InvalidRequestError('Malformed token request');
373
+ const input = parsed.data;
374
+ // Apply progressive delay before the grant exchange. The delay is keyed on
375
+ // client_id (never logged) and ramps after DELAY_THRESHOLD
376
+ // repeated failures tracked in Redis, so the budget is shared across replicas.
377
+ await applyProgressiveDelay(input.client_id);
378
+ const client = await authenticateClientCredentials(input.client_id, input.client_secret, presentedAuthMethod(req));
379
+ if (client === undefined) {
380
+ await recordExchangeFailure(input.client_id);
381
+ throw new InvalidClientError('Client authentication failed');
382
+ }
383
+ // COMPILE PIN: the core provider must remain assignable to the SDK 1.29
384
+ // OAuthServerProvider (the A2 contract the structural mirror promises).
385
+ const provider = createOAuthServerProvider(loadOAuthConfig());
386
+ const resource = input.resource === undefined ? undefined : new URL(input.resource);
387
+ let tokens;
388
+ try {
389
+ tokens =
390
+ input.grant_type === 'authorization_code'
391
+ ? await provider.exchangeAuthorizationCode(client, input.code, input.code_verifier, input.redirect_uri, resource)
392
+ : await provider.exchangeRefreshToken(client, input.refresh_token, input.scope?.split(' '), resource);
393
+ }
394
+ catch (exchangeErr) {
395
+ await recordExchangeFailure(input.client_id);
396
+ throw exchangeErr;
397
+ }
398
+ await clearExchangeFailures(input.client_id);
399
+ // Fire-and-forget: stamp last_used_at so the client escapes the 30-day idle GC
400
+ // (ADR-0009 §5). Must never block the exchange; its rejection is logged redacted.
401
+ touchClientLastUsed(input.client_id).catch((err) => {
402
+ log().warn({ err: err instanceof Error ? err.name : 'unknown' }, 'oauth: client touch failed');
403
+ });
404
+ // Fire-and-forget: audit the successful token issuance. NEVER include the raw
405
+ // token, code, client_secret, or refresh_token — only the client_id.
406
+ insertAuditLog({
407
+ actorKind: 'system',
408
+ action: 'token.issue',
409
+ resource: input.client_id,
410
+ ...(req.ip !== undefined ? { ip: req.ip } : {}),
411
+ }).catch((err) => {
412
+ log().warn({ err: err instanceof Error ? err.name : 'unknown' }, 'audit: token.issue failed');
413
+ });
414
+ logTokenOutcome(input.grant_type, input.client_id, 'success');
415
+ res.status(200).json(tokens);
416
+ }
417
+ /** Build the /oauth/token router behind the injected per-IP limiter. */
418
+ export function oauthTokenRouter(options) {
419
+ // Wire the failure-tracker store: the shared ioredis client (cross-replica
420
+ // budget) when injected, else the in-process Map fallback.
421
+ setExchangeFailureRedis(options.redis);
422
+ const router = Router();
423
+ router.post('/oauth/token', options.limiter, urlencoded({ extended: false }), shimBasicAuth, (req, res) => {
424
+ handleTokenRequest(req, res).catch((err) => {
425
+ const oauthError = toOAuthError(err);
426
+ const body = (req.body ?? {});
427
+ // outcome IS the mapped RFC error code (invalid_grant|invalid_client|
428
+ // invalid_request|unsupported_grant_type|server_error) — observability.md
429
+ // wants the same vocabulary the client sees in the response body.
430
+ logTokenOutcome(body.grant_type, body.client_id, oauthError.errorCode);
431
+ if (oauthError instanceof ServerError) {
432
+ log().error(crashSafeError(err), 'oauth: token endpoint failure');
433
+ }
434
+ // RFC 6749 §5.2: a failed client authentication is 401, not 400; and
435
+ // when the client authenticated via the Authorization header, the
436
+ // response MUST carry a matching WWW-Authenticate challenge.
437
+ if (oauthError instanceof InvalidClientError) {
438
+ if (req.header('authorization')?.toLowerCase().startsWith('basic ') === true) {
439
+ res.setHeader('WWW-Authenticate', 'Basic realm="oauth"');
440
+ }
441
+ res.status(401).json(oauthError.toResponseObject());
442
+ return;
443
+ }
444
+ res
445
+ .status(oauthError instanceof ServerError ? 500 : 400)
446
+ .json(oauthError.toResponseObject());
447
+ });
448
+ });
449
+ return router;
450
+ }
451
+ //# sourceMappingURL=oauth-token.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"oauth-token.js","sourceRoot":"","sources":["../../src/routes/oauth-token.ts"],"names":[],"mappings":"AAAA,sCAAsC;AACtC,uCAAuC;AACvC,+DAA+D;AAC/D,6EAA6E;AAC7E,+BAA+B;AAC/B,EAAE;AACF,kEAAkE;AAClE,wEAAwE;AACxE,+EAA+E;AAC/E,6EAA6E;AAC7E,2EAA2E;AAC3E,wEAAwE;AACxE,8EAA8E;AAC9E,qEAAqE;AACrE,EAAE;AACF,gEAAgE;AAChE,4EAA4E;AAC5E,4EAA4E;AAC5E,+DAA+D;AAC/D,OAAO,EAAE,aAAa,EAAE,eAAe,EAAE,GAAG,EAAE,MAAM,gBAAgB,CAAA;AACpE,OAAO,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAA;AACpD,OAAO,EACL,6BAA6B,EAC7B,yBAAyB,EACzB,cAAc,EACd,eAAe,EACf,mBAAmB,GACpB,MAAM,mBAAmB,CAAA;AAC1B,OAAO,EAAgC,kBAAkB,EAAE,MAAM,gBAAgB,CAAA;AACjF,OAAO,EACL,kBAAkB,EAClB,iBAAiB,EACjB,mBAAmB,EACnB,kBAAkB,EAClB,iBAAiB,EACjB,UAAU,EACV,WAAW,EACX,yBAAyB,GAC1B,MAAM,iDAAiD,CAAA;AAExD,OAAO,EAAkD,MAAM,EAAE,UAAU,EAAE,MAAM,SAAS,CAAA;AAiB5F,4FAA4F;AAC5F,MAAM,qBAAqB,GAAG,MAAM,CAAC,qBAAqB,CAAC,CAAA;AAE3D;;;;;GAKG;AACH,MAAM,mBAAmB,GAAG,MAAM,CAAC,mBAAmB,CAAC,CAAA;AAOvD,yFAAyF;AACzF,SAAS,mBAAmB,CAAC,GAAY;IACvC,OAAQ,GAAqB,CAAC,qBAAqB,CAAC,CAAA;AACtD,CAAC;AAED,kFAAkF;AAClF,SAAS,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B,CAAC,CAAA;YACnE,CAAC;YACD,qEAAqE;YACrE,kEAAkE;YAClE,6DAA6D;YAC7D,IAAI,UAAU,YAAY,kBAAkB,EAAE,CAAC;gBAC7C,IAAI,GAAG,CAAC,MAAM,CAAC,eAAe,CAAC,EAAE,WAAW,EAAE,CAAC,UAAU,CAAC,QAAQ,CAAC,KAAK,IAAI,EAAE,CAAC;oBAC7E,GAAG,CAAC,SAAS,CAAC,kBAAkB,EAAE,qBAAqB,CAAC,CAAA;gBAC1D,CAAC;gBACD,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,UAAU,CAAC,gBAAgB,EAAE,CAAC,CAAA;gBACnD,OAAM;YACR,CAAC;YACD,GAAG;iBACA,MAAM,CAAC,UAAU,YAAY,WAAW,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,CAAC;iBACrD,IAAI,CAAC,UAAU,CAAC,gBAAgB,EAAE,CAAC,CAAA;QACxC,CAAC,CAAC,CAAA;IACJ,CAAC,CACF,CAAA;IACD,OAAO,MAAM,CAAA;AACf,CAAC"}
@@ -0,0 +1,2 @@
1
+ import { Router } from 'express';
2
+ export declare const onboardingRouter: Router;
@@ -0,0 +1,47 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // Onboarding status transport.
3
+ // Thin by contract: delegate the "has this user connected an
4
+ // agent yet" decision to packages/core (getOnboardingStatus), shape the HTTP
5
+ // response. No business logic here. The route sits behind the `authenticate`
6
+ // middleware, so req.userId is the session-authenticated owner — the dashboard
7
+ // polls it (session bearer) to flip the connect step to "Connected ✓".
8
+ //
9
+ // Status contract:
10
+ // GET /auth/onboarding 200 { connected: boolean } — true once the
11
+ // caller has been issued their first OAuth token
12
+ // (ADR-0009).
13
+ // POST /auth/onboarding/seed 204 — idempotently (re-)provision the caller's
14
+ // default scopes + welcome memory. The
15
+ // first-run dashboard calls this when the seed was
16
+ // deferred/failed at verification, then gates on
17
+ // the welcome memory existing — never a blank first
18
+ // run. Idempotent: a re-run on an already
19
+ // seeded account is a no-op (the core helper
20
+ // swallows the scope/duplicate conflicts).
21
+ import { getOnboardingStatus, provisionVerifiedAccount } from '@3ngram/core/auth';
22
+ import { Router } from 'express';
23
+ import { authenticate } from '../middleware/authenticate.js';
24
+ export const onboardingRouter = Router();
25
+ // authenticate guarantees req.userId is bound before each handler runs; the
26
+ // non-null assertion is safe because an unauthenticated request never reaches
27
+ // here (the middleware 401s first).
28
+ onboardingRouter.get('/auth/onboarding', authenticate, (req, res, next) => {
29
+ getOnboardingStatus(req.userId)
30
+ .then((status) => {
31
+ res.status(200).json({ connected: status.connected });
32
+ })
33
+ .catch(next);
34
+ });
35
+ onboardingRouter.post('/auth/onboarding/seed', authenticate, (req, res, next) => {
36
+ // Idempotent re-seed: provisionVerifiedAccount swallows the scope/duplicate
37
+ // conflicts, so a call against an already-seeded account is a no-op. No
38
+ // embedding gateway is threaded here — the welcome memory is stored with a
39
+ // NULL embedding (still listable / FTS-searchable, backfillable later), which
40
+ // is enough for the non-empty first-run guarantee.
41
+ provisionVerifiedAccount(req.userId)
42
+ .then(() => {
43
+ res.status(204).end();
44
+ })
45
+ .catch(next);
46
+ });
47
+ //# sourceMappingURL=onboarding.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"onboarding.js","sourceRoot":"","sources":["../../src/routes/onboarding.ts"],"names":[],"mappings":"AAAA,sCAAsC;AACtC,+BAA+B;AAC/B,6DAA6D;AAC7D,6EAA6E;AAC7E,6EAA6E;AAC7E,+EAA+E;AAC/E,uEAAuE;AACvE,EAAE;AACF,mBAAmB;AACnB,4EAA4E;AAC5E,gFAAgF;AAChF,6CAA6C;AAC7C,gFAAgF;AAChF,sEAAsE;AACtE,kFAAkF;AAClF,gFAAgF;AAChF,mFAAmF;AACnF,yEAAyE;AACzE,4EAA4E;AAC5E,0EAA0E;AAC1E,OAAO,EAAE,mBAAmB,EAAE,wBAAwB,EAAE,MAAM,mBAAmB,CAAA;AACjF,OAAO,EAAkD,MAAM,EAAE,MAAM,SAAS,CAAA;AAChF,OAAO,EAAE,YAAY,EAAE,MAAM,+BAA+B,CAAA;AAE5D,MAAM,CAAC,MAAM,gBAAgB,GAAW,MAAM,EAAE,CAAA;AAEhD,4EAA4E;AAC5E,8EAA8E;AAC9E,oCAAoC;AACpC,gBAAgB,CAAC,GAAG,CAClB,kBAAkB,EAClB,YAAY,EACZ,CAAC,GAAY,EAAE,GAAa,EAAE,IAAkB,EAAE,EAAE;IAClD,mBAAmB,CAAC,GAAG,CAAC,MAAgB,CAAC;SACtC,IAAI,CAAC,CAAC,MAAM,EAAE,EAAE;QACf,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,EAAE,SAAS,EAAE,MAAM,CAAC,SAAS,EAAE,CAAC,CAAA;IACvD,CAAC,CAAC;SACD,KAAK,CAAC,IAAI,CAAC,CAAA;AAChB,CAAC,CACF,CAAA;AAED,gBAAgB,CAAC,IAAI,CACnB,uBAAuB,EACvB,YAAY,EACZ,CAAC,GAAY,EAAE,GAAa,EAAE,IAAkB,EAAE,EAAE;IAClD,4EAA4E;IAC5E,wEAAwE;IACxE,2EAA2E;IAC3E,8EAA8E;IAC9E,mDAAmD;IACnD,wBAAwB,CAAC,GAAG,CAAC,MAAgB,CAAC;SAC3C,IAAI,CAAC,GAAG,EAAE;QACT,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,CAAA;IACvB,CAAC,CAAC;SACD,KAAK,CAAC,IAAI,CAAC,CAAA;AAChB,CAAC,CACF,CAAA"}
@@ -0,0 +1,2 @@
1
+ import { Router } from 'express';
2
+ export declare const profileRouter: Router;
@@ -0,0 +1,35 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // Onboarding "About you" profiling transport. Thin by
3
+ // contract: validate the body at the boundary, delegate to
4
+ // packages/core, shape the HTTP response. Behind the `authenticate`
5
+ // middleware, so req.userId is the session-authenticated owner.
6
+ //
7
+ // GET /auth/profile 200 {role?,useCase?,aiTools?,referralSource?} — {} if unset
8
+ // PUT /auth/profile 204 — upsert the (all-optional) attributes; 400 on a body
9
+ // that fails userProfileAttributesSchema (single validation
10
+ // boundary, hard rule 2).
11
+ import { getUserProfile, setUserProfile } from '@3ngram/core/auth';
12
+ import { userProfileAttributesSchema } from '@3ngram/schema';
13
+ import { Router } from 'express';
14
+ import { authenticate } from '../middleware/authenticate.js';
15
+ export const profileRouter = Router();
16
+ profileRouter.get('/auth/profile', authenticate, (req, res, next) => {
17
+ getUserProfile(req.userId)
18
+ .then((attrs) => {
19
+ res.status(200).json(attrs ?? {});
20
+ })
21
+ .catch(next);
22
+ });
23
+ profileRouter.put('/auth/profile', authenticate, (req, res, next) => {
24
+ const parsed = userProfileAttributesSchema.safeParse(req.body);
25
+ if (!parsed.success) {
26
+ res.status(400).json({ error: 'invalid_profile' });
27
+ return;
28
+ }
29
+ setUserProfile(req.userId, parsed.data)
30
+ .then(() => {
31
+ res.status(204).end();
32
+ })
33
+ .catch(next);
34
+ });
35
+ //# sourceMappingURL=profile.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"profile.js","sourceRoot":"","sources":["../../src/routes/profile.ts"],"names":[],"mappings":"AAAA,sCAAsC;AACtC,sDAAsD;AACtD,2DAA2D;AAC3D,oEAAoE;AACpE,gEAAgE;AAChE,EAAE;AACF,oFAAoF;AACpF,kFAAkF;AAClF,kFAAkF;AAClF,gDAAgD;AAChD,OAAO,EAAE,cAAc,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAA;AAClE,OAAO,EAAE,2BAA2B,EAAE,MAAM,gBAAgB,CAAA;AAC5D,OAAO,EAAkD,MAAM,EAAE,MAAM,SAAS,CAAA;AAChF,OAAO,EAAE,YAAY,EAAE,MAAM,+BAA+B,CAAA;AAE5D,MAAM,CAAC,MAAM,aAAa,GAAW,MAAM,EAAE,CAAA;AAE7C,aAAa,CAAC,GAAG,CACf,eAAe,EACf,YAAY,EACZ,CAAC,GAAY,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