@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.
- package/LICENSE +202 -0
- package/dist/app.d.ts +72 -0
- package/dist/app.js +273 -0
- package/dist/app.js.map +1 -0
- package/dist/boot.d.ts +37 -0
- package/dist/boot.js +53 -0
- package/dist/boot.js.map +1 -0
- package/dist/composition/extension.d.ts +50 -0
- package/dist/composition/extension.js +16 -0
- package/dist/composition/extension.js.map +1 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.js +10 -0
- package/dist/index.js.map +1 -0
- package/dist/links.d.ts +17 -0
- package/dist/links.js +46 -0
- package/dist/links.js.map +1 -0
- package/dist/mailer.d.ts +58 -0
- package/dist/mailer.js +187 -0
- package/dist/mailer.js.map +1 -0
- package/dist/mcp/errors.d.ts +14 -0
- package/dist/mcp/errors.js +175 -0
- package/dist/mcp/errors.js.map +1 -0
- package/dist/mcp/prompts.d.ts +29 -0
- package/dist/mcp/prompts.js +180 -0
- package/dist/mcp/prompts.js.map +1 -0
- package/dist/mcp/server.d.ts +14 -0
- package/dist/mcp/server.js +34 -0
- package/dist/mcp/server.js.map +1 -0
- package/dist/mcp/tools-admin.d.ts +8 -0
- package/dist/mcp/tools-admin.js +260 -0
- package/dist/mcp/tools-admin.js.map +1 -0
- package/dist/mcp/tools-orient.d.ts +6 -0
- package/dist/mcp/tools-orient.js +110 -0
- package/dist/mcp/tools-orient.js.map +1 -0
- package/dist/mcp/tools.d.ts +88 -0
- package/dist/mcp/tools.js +375 -0
- package/dist/mcp/tools.js.map +1 -0
- package/dist/middleware/api-key.d.ts +13 -0
- package/dist/middleware/api-key.js +83 -0
- package/dist/middleware/api-key.js.map +1 -0
- package/dist/middleware/api-or-session.d.ts +9 -0
- package/dist/middleware/api-or-session.js +22 -0
- package/dist/middleware/api-or-session.js.map +1 -0
- package/dist/middleware/authenticate.d.ts +21 -0
- package/dist/middleware/authenticate.js +51 -0
- package/dist/middleware/authenticate.js.map +1 -0
- package/dist/middleware/index.d.ts +1 -0
- package/dist/middleware/index.js +9 -0
- package/dist/middleware/index.js.map +1 -0
- package/dist/middleware/oauth-bearer.d.ts +8 -0
- package/dist/middleware/oauth-bearer.js +117 -0
- package/dist/middleware/oauth-bearer.js.map +1 -0
- package/dist/middleware/rate-limit.d.ts +58 -0
- package/dist/middleware/rate-limit.js +139 -0
- package/dist/middleware/rate-limit.js.map +1 -0
- package/dist/middleware/request-context.d.ts +7 -0
- package/dist/middleware/request-context.js +14 -0
- package/dist/middleware/request-context.js.map +1 -0
- package/dist/output-validation.d.ts +18 -0
- package/dist/output-validation.js +30 -0
- package/dist/output-validation.js.map +1 -0
- package/dist/redis.d.ts +9 -0
- package/dist/redis.js +37 -0
- package/dist/redis.js.map +1 -0
- package/dist/rest/cursor.d.ts +14 -0
- package/dist/rest/cursor.js +38 -0
- package/dist/rest/cursor.js.map +1 -0
- package/dist/rest/errors.d.ts +14 -0
- package/dist/rest/errors.js +119 -0
- package/dist/rest/errors.js.map +1 -0
- package/dist/rest/router.d.ts +33 -0
- package/dist/rest/router.js +846 -0
- package/dist/rest/router.js.map +1 -0
- package/dist/rest/scope.d.ts +14 -0
- package/dist/rest/scope.js +45 -0
- package/dist/rest/scope.js.map +1 -0
- package/dist/routes/api-keys.d.ts +2 -0
- package/dist/routes/api-keys.js +77 -0
- package/dist/routes/api-keys.js.map +1 -0
- package/dist/routes/auth.d.ts +20 -0
- package/dist/routes/auth.js +325 -0
- package/dist/routes/auth.js.map +1 -0
- package/dist/routes/capabilities.d.ts +10 -0
- package/dist/routes/capabilities.js +17 -0
- package/dist/routes/capabilities.js.map +1 -0
- package/dist/routes/health.d.ts +7 -0
- package/dist/routes/health.js +12 -0
- package/dist/routes/health.js.map +1 -0
- package/dist/routes/mcp.d.ts +27 -0
- package/dist/routes/mcp.js +81 -0
- package/dist/routes/mcp.js.map +1 -0
- package/dist/routes/oauth-authorize.d.ts +8 -0
- package/dist/routes/oauth-authorize.js +245 -0
- package/dist/routes/oauth-authorize.js.map +1 -0
- package/dist/routes/oauth-clients.d.ts +2 -0
- package/dist/routes/oauth-clients.js +59 -0
- package/dist/routes/oauth-clients.js.map +1 -0
- package/dist/routes/oauth-register.d.ts +8 -0
- package/dist/routes/oauth-register.js +59 -0
- package/dist/routes/oauth-register.js.map +1 -0
- package/dist/routes/oauth-token.d.ts +30 -0
- package/dist/routes/oauth-token.js +451 -0
- package/dist/routes/oauth-token.js.map +1 -0
- package/dist/routes/onboarding.d.ts +2 -0
- package/dist/routes/onboarding.js +47 -0
- package/dist/routes/onboarding.js.map +1 -0
- package/dist/routes/profile.d.ts +2 -0
- package/dist/routes/profile.js +35 -0
- package/dist/routes/profile.js.map +1 -0
- package/dist/routes/well-known.d.ts +2 -0
- package/dist/routes/well-known.js +77 -0
- package/dist/routes/well-known.js.map +1 -0
- package/dist/version.d.ts +1 -0
- package/dist/version.js +17 -0
- package/dist/version.js.map +1 -0
- package/package.json +67 -0
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
// API-key authentication (auth C3). Reads `X-API-Key: 3ng_<prefix>_<secret>`,
|
|
3
|
+
// resolves it through the core api-key service, and binds the identity for the
|
|
4
|
+
// rest of the request — the SAME req.userId + log-context shape the Bearer
|
|
5
|
+
// `authenticate` middleware uses, so the two coexist transparently downstream.
|
|
6
|
+
//
|
|
7
|
+
// STATUS CONTRACT (ADR-0009 §C3, for the capture-hook verify path):
|
|
8
|
+
// 200 valid key -> identity bound, next() runs the route
|
|
9
|
+
// 401 missing / malformed / unknown / revoked key (UNIFORM, no enumeration)
|
|
10
|
+
// 503 resolver-or-DB failure
|
|
11
|
+
// The middleware MUST catch resolver/DB errors LOCALLY and emit 503 itself: the
|
|
12
|
+
// app.ts generic handler maps any uncaught error to 500, which would silently
|
|
13
|
+
// break this contract. So errors are handled here, not forwarded to next().
|
|
14
|
+
//
|
|
15
|
+
// The raw user id is attached to req.userId; only its HASH enters the log
|
|
16
|
+
// context (hard rule 6). The key, its hash, and the secret are never logged.
|
|
17
|
+
import { bindContext, hashUserId, log } from '@3ngram/config';
|
|
18
|
+
import { authenticateApiKey, touchApiKeyLastUsed } from '@3ngram/core/auth';
|
|
19
|
+
const API_KEY_HEADER = 'x-api-key';
|
|
20
|
+
/**
|
|
21
|
+
* Parse the prefix segment from a `3ng_<prefix>_<secret>` key string, or
|
|
22
|
+
* return undefined when the format does not match (fewer than 3 underscore-
|
|
23
|
+
* delimited segments). The raw key and secret are never logged; only the
|
|
24
|
+
* parse failure event is recorded (hard rule 6).
|
|
25
|
+
*/
|
|
26
|
+
function parseApiKeyPrefix(key) {
|
|
27
|
+
const segments = key.split('_');
|
|
28
|
+
// Expected: ['3ng', '<prefix>', '<secret...>'] — at least 3 segments.
|
|
29
|
+
if (segments.length < 3)
|
|
30
|
+
return undefined;
|
|
31
|
+
return segments[1];
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* Authenticate the request via X-API-Key. On success binds req.userId + the
|
|
35
|
+
* hashed id into the log context, fires a best-effort last_used_at stamp (never
|
|
36
|
+
* blocking), and continues. A missing/garbage/unknown/revoked key is a uniform
|
|
37
|
+
* 401; any resolver/DB failure is a 503 emitted here (never a leaked 500).
|
|
38
|
+
*
|
|
39
|
+
* Also sets req.apiKeyId to the key prefix segment (`3ng_<PREFIX>_<secret>`)
|
|
40
|
+
* for use by the per-key rate-limiter bucket on /api/*. A malformed key
|
|
41
|
+
* format is logged (redacted — no key material) but does NOT block the request;
|
|
42
|
+
* req.userId is already bound and the route continues without a rate-limit key.
|
|
43
|
+
*/
|
|
44
|
+
export function apiKeyAuth(req, res, next) {
|
|
45
|
+
const key = req.header(API_KEY_HEADER)?.trim();
|
|
46
|
+
if (key === undefined || key.length === 0) {
|
|
47
|
+
res.status(401).json({ error: 'unauthorized' });
|
|
48
|
+
return;
|
|
49
|
+
}
|
|
50
|
+
authenticateApiKey(key)
|
|
51
|
+
.then((userId) => {
|
|
52
|
+
if (userId === undefined) {
|
|
53
|
+
res.status(401).json({ error: 'unauthorized' });
|
|
54
|
+
return;
|
|
55
|
+
}
|
|
56
|
+
req.userId = userId;
|
|
57
|
+
bindContext({ userIdHash: hashUserId(userId) });
|
|
58
|
+
// Bind the key prefix for the per-key rate-limiter bucket. A
|
|
59
|
+
// malformed format is logged (no key material) and skipped;
|
|
60
|
+
// userId is already bound so the route continues without a limiter key.
|
|
61
|
+
const prefix = parseApiKeyPrefix(key);
|
|
62
|
+
if (prefix !== undefined) {
|
|
63
|
+
req.apiKeyId = prefix;
|
|
64
|
+
}
|
|
65
|
+
else {
|
|
66
|
+
log().warn({ keyHeader: API_KEY_HEADER }, 'api-key: malformed key format, no prefix bound');
|
|
67
|
+
}
|
|
68
|
+
// Fire-and-forget: the last_used_at write must not block the request, and
|
|
69
|
+
// its failure must not surface to the client. Log a redacted warning only
|
|
70
|
+
// (no key material — hard rule 6).
|
|
71
|
+
touchApiKeyLastUsed(userId, key).catch((err) => {
|
|
72
|
+
log().warn({ err: err instanceof Error ? err.name : 'unknown' }, 'api-key: last_used update failed');
|
|
73
|
+
});
|
|
74
|
+
next();
|
|
75
|
+
})
|
|
76
|
+
.catch((err) => {
|
|
77
|
+
// Resolver or DB failure: emit the 503 contract HERE. Forwarding to next()
|
|
78
|
+
// would hit the generic 500 handler and break the capture-hook contract.
|
|
79
|
+
log().error({ err: err instanceof Error ? err.name : 'unknown' }, 'api-key: resolver unavailable');
|
|
80
|
+
res.status(503).json({ error: 'service_unavailable' });
|
|
81
|
+
});
|
|
82
|
+
}
|
|
83
|
+
//# sourceMappingURL=api-key.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"api-key.js","sourceRoot":"","sources":["../../src/middleware/api-key.ts"],"names":[],"mappings":"AAAA,sCAAsC;AACtC,8EAA8E;AAC9E,+EAA+E;AAC/E,2EAA2E;AAC3E,+EAA+E;AAC/E,EAAE;AACF,oEAAoE;AACpE,6D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Bearer token. A
|
|
4
|
+
* present X-API-Key routes to the api-key gate (its 401/503 contract is
|
|
5
|
+
* authoritative — a bad key never falls through to the Bearer path). Absent an
|
|
6
|
+
* X-API-Key, an Authorization header routes to the session-Bearer gate. With
|
|
7
|
+
* neither, it is a uniform 401. Both gates bind req.userId identically.
|
|
8
|
+
*/
|
|
9
|
+
export declare function apiOrSessionAuth(req: Request, res: Response, next: NextFunction): void;
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { apiKeyAuth } from './api-key.js';
|
|
2
|
+
import { authenticate } from './authenticate.js';
|
|
3
|
+
const API_KEY_HEADER = 'x-api-key';
|
|
4
|
+
/**
|
|
5
|
+
* Authenticate an /api/v1 request via X-API-Key OR a session Bearer token. A
|
|
6
|
+
* present X-API-Key routes to the api-key gate (its 401/503 contract is
|
|
7
|
+
* authoritative — a bad key never falls through to the Bearer path). Absent an
|
|
8
|
+
* X-API-Key, an Authorization header routes to the session-Bearer gate. With
|
|
9
|
+
* neither, it is a uniform 401. Both gates bind req.userId identically.
|
|
10
|
+
*/
|
|
11
|
+
export function apiOrSessionAuth(req, res, next) {
|
|
12
|
+
const apiKey = req.header(API_KEY_HEADER)?.trim();
|
|
13
|
+
if (apiKey !== undefined && apiKey.length > 0) {
|
|
14
|
+
apiKeyAuth(req, res, next);
|
|
15
|
+
return;
|
|
16
|
+
}
|
|
17
|
+
// No X-API-Key: fall back to the C2 session Bearer path. authenticate() emits
|
|
18
|
+
// the uniform 401 itself when the Authorization header is missing/garbage, so
|
|
19
|
+
// the no-credential case is handled there (no separate branch needed).
|
|
20
|
+
authenticate(req, res, next);
|
|
21
|
+
}
|
|
22
|
+
//# sourceMappingURL=api-or-session.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"api-or-session.js","sourceRoot":"","sources":["../../src/middleware/api-or-session.ts"],"names":[],"mappings":"AA0BA,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAA;AACzC,OAAO,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAA;AAEhD,MAAM,cAAc,GAAG,WAAW,CAAA;AAElC;;;;;;GAMG;AACH,MAAM,UAAU,gBAAgB,CAAC,GAAY,EAAE,GAAa,EAAE,IAAkB;IAC9E,MAAM,MAAM,GAAG,GAAG,CAAC,MAAM,CAAC,cAAc,CAAC,EAAE,IAAI,EAAE,CAAA;IACjD,IAAI,MAAM,KAAK,SAAS,IAAI,MAAM,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;QAC9C,UAAU,CAAC,GAAG,EAAE,GAAG,EAAE,IAAI,CAAC,CAAA;QAC1B,OAAM;IACR,CAAC;IACD,8EAA8E;IAC9E,8EAA8E;IAC9E,uEAAuE;IACvE,YAAY,CAAC,GAAG,EAAE,GAAG,EAAE,IAAI,CAAC,CAAA;AAC9B,CAAC"}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import type { NextFunction, Request, Response } from 'express';
|
|
2
|
+
declare module 'express' {
|
|
3
|
+
interface Request {
|
|
4
|
+
userId?: string;
|
|
5
|
+
oauthScopes?: readonly string[];
|
|
6
|
+
apiKeyId?: string;
|
|
7
|
+
}
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* Extract the token from a well-formed Authorization header, else undefined.
|
|
11
|
+
* The auth-scheme is matched case-insensitively (RFC 7235 §2.1: scheme names
|
|
12
|
+
* are case-insensitive), but the token bytes after the prefix are taken
|
|
13
|
+
* unchanged.
|
|
14
|
+
*/
|
|
15
|
+
export declare function readBearerToken(header: string | undefined): string | undefined;
|
|
16
|
+
/**
|
|
17
|
+
* Authenticate the request. On success binds req.userId and the hashed id into
|
|
18
|
+
* the log context, then continues; otherwise responds 401 and stops. Errors
|
|
19
|
+
* from the resolver bubble to the app error handler (500), not a silent pass.
|
|
20
|
+
*/
|
|
21
|
+
export declare function authenticate(req: Request, res: Response, next: NextFunction): void;
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
// Bearer-token authentication (auth C2). Reads `Authorization: Bearer <token>`,
|
|
3
|
+
// resolves it through the core session service, and binds the identity for the
|
|
4
|
+
// rest of the request. A missing/garbage/expired token is a uniform 401 — the
|
|
5
|
+
// route never sees an unauthenticated request.
|
|
6
|
+
//
|
|
7
|
+
// The raw user id is attached to req.userId (route handlers feed it to
|
|
8
|
+
// withTenant); only its HASH enters the log context (hard rule 6). The token
|
|
9
|
+
// itself is never logged.
|
|
10
|
+
import { bindContext, hashUserId } from '@3ngram/config';
|
|
11
|
+
import { authenticateToken } from '@3ngram/core/auth';
|
|
12
|
+
const BEARER_PREFIX = 'Bearer ';
|
|
13
|
+
/**
|
|
14
|
+
* Extract the token from a well-formed Authorization header, else undefined.
|
|
15
|
+
* The auth-scheme is matched case-insensitively (RFC 7235 §2.1: scheme names
|
|
16
|
+
* are case-insensitive), but the token bytes after the prefix are taken
|
|
17
|
+
* unchanged.
|
|
18
|
+
*/
|
|
19
|
+
export function readBearerToken(header) {
|
|
20
|
+
if (header === undefined)
|
|
21
|
+
return undefined;
|
|
22
|
+
if (header.slice(0, BEARER_PREFIX.length).toLowerCase() !== BEARER_PREFIX.toLowerCase()) {
|
|
23
|
+
return undefined;
|
|
24
|
+
}
|
|
25
|
+
const token = header.slice(BEARER_PREFIX.length).trim();
|
|
26
|
+
return token.length > 0 ? token : undefined;
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* Authenticate the request. On success binds req.userId and the hashed id into
|
|
30
|
+
* the log context, then continues; otherwise responds 401 and stops. Errors
|
|
31
|
+
* from the resolver bubble to the app error handler (500), not a silent pass.
|
|
32
|
+
*/
|
|
33
|
+
export function authenticate(req, res, next) {
|
|
34
|
+
const token = readBearerToken(req.header('authorization'));
|
|
35
|
+
if (token === undefined) {
|
|
36
|
+
res.status(401).json({ error: 'unauthorized' });
|
|
37
|
+
return;
|
|
38
|
+
}
|
|
39
|
+
authenticateToken(token)
|
|
40
|
+
.then((userId) => {
|
|
41
|
+
if (userId === undefined) {
|
|
42
|
+
res.status(401).json({ error: 'unauthorized' });
|
|
43
|
+
return;
|
|
44
|
+
}
|
|
45
|
+
req.userId = userId;
|
|
46
|
+
bindContext({ userIdHash: hashUserId(userId) });
|
|
47
|
+
next();
|
|
48
|
+
})
|
|
49
|
+
.catch(next);
|
|
50
|
+
}
|
|
51
|
+
//# sourceMappingURL=authenticate.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"authenticate.js","sourceRoot":"","sources":["../../src/middleware/authenticate.ts"],"names":[],"mappings":"AAAA,sCAAsC;AACtC,gFAAgF;AAChF,+EAA+E;AAC/E,8EAA8E;AAC9E,+CAA+C;AAC/C,EAAE;AACF,uEAAuE;AACvE,6EAA6E;AAC7E,0BAA0B;AAC1B,OAAO,EAAE,WAAW,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAA;AACxD,OAAO,EAAE,iBAAiB,EAAE,MAAM,mBAAmB,CAAA;AAqBrD,MAAM,aAAa,GAAG,SAAS,CAAA;AAE/B;;;;;GAKG;AACH,MAAM,UAAU,eAAe,CAAC,MAA0B;IACxD,IAAI,MAAM,KAAK,SAAS;QAAE,OAAO,SAAS,CAAA;IAC1C,IAAI,MAAM,CAAC,KAAK,CAAC,CAAC,EAAE,aAAa,CAAC,MAAM,CAAC,CAAC,WAAW,EAAE,KAAK,aAAa,CAAC,WAAW,EAAE,EAAE,CAAC;QACxF,OAAO,SAAS,CAAA;IAClB,CAAC;IACD,MAAM,KAAK,GAAG,MAAM,CAAC,KAAK,CAAC,aAAa,CAAC,MAAM,CAAC,CAAC,IAAI,EAAE,CAAA;IACvD,OAAO,KAAK,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,SAAS,CAAA;AAC7C,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,YAAY,CAAC,GAAY,EAAE,GAAa,EAAE,IAAkB;IAC1E,MAAM,KAAK,GAAG,eAAe,CAAC,GAAG,CAAC,MAAM,CAAC,eAAe,CAAC,CAAC,CAAA;IAC1D,IAAI,KAAK,KAAK,SAAS,EAAE,CAAC;QACxB,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,EAAE,KAAK,EAAE,cAAc,EAAE,CAAC,CAAA;QAC/C,OAAM;IACR,CAAC;IACD,iBAAiB,CAAC,KAAK,CAAC;SACrB,IAAI,CAAC,CAAC,MAAM,EAAE,EAAE;QACf,IAAI,MAAM,KAAK,SAAS,EAAE,CAAC;YACzB,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,EAAE,KAAK,EAAE,cAAc,EAAE,CAAC,CAAA;YAC/C,OAAM;QACR,CAAC;QACD,GAAG,CAAC,MAAM,GAAG,MAAM,CAAA;QACnB,WAAW,CAAC,EAAE,UAAU,EAAE,UAAU,CAAC,MAAM,CAAC,EAAE,CAAC,CAAA;QAC/C,IAAI,EAAE,CAAA;IACR,CAAC,CAAC;SACD,KAAK,CAAC,IAAI,CAAC,CAAA;AAChB,CAAC"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { apiOrSessionAuth } from './api-or-session.js';
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
// Public middleware barrel. Exposes the combined /api/v1
|
|
3
|
+
// authentication gate so the private repo can mount hosted-only authenticated
|
|
4
|
+
// routes behind the SAME credential handling the Apache transports use — binding
|
|
5
|
+
// the SAME `req.userId` (X-API-Key OR session Bearer) without re-implementing auth
|
|
6
|
+
// (hard rule 5). This is an Apache→private export (the private repo imports it);
|
|
7
|
+
// the reverse is what CI bans.
|
|
8
|
+
export { apiOrSessionAuth } from './api-or-session.js';
|
|
9
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/middleware/index.ts"],"names":[],"mappings":"AAAA,sCAAsC;AACtC,yDAAyD;AACzD,8EAA8E;AAC9E,iFAAiF;AACjF,mFAAmF;AACnF,iFAAiF;AACjF,+BAA+B;AAC/B,OAAO,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAA"}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import type { NextFunction, Request, Response } from 'express';
|
|
2
|
+
/**
|
|
3
|
+
* Authenticate the request via a Bearer JWT. On success binds req.userId + the
|
|
4
|
+
* hashed id into the log context and continues. A missing token is a bare 401
|
|
5
|
+
* challenge; an invalid token is a 401 with error="invalid_token"; any
|
|
6
|
+
* verifier/DB failure is a 503 emitted here (never a leaked 500).
|
|
7
|
+
*/
|
|
8
|
+
export declare function oauthBearerAuth(req: Request, res: Response, next: NextFunction): void;
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
// OAuth Bearer-JWT authentication (auth C4b). Reads `Authorization: Bearer <jwt>`,
|
|
3
|
+
// verifies it as an RS256 access token against the local JWKS + revocation check
|
|
4
|
+
// (core verifyAccessToken), and binds the identity for the rest of the request —
|
|
5
|
+
// the SAME req.userId + log-context shape the C2 `authenticate` and C3
|
|
6
|
+
// `apiKeyAuth` middlewares use, so all three coexist transparently downstream.
|
|
7
|
+
//
|
|
8
|
+
// STATUS CONTRACT (RFC 6750 + RFC 9728 §5.1 + ADR-0009 §RS):
|
|
9
|
+
// 200 valid token -> identity bound, next() runs the route
|
|
10
|
+
// 401 missing / malformed / invalid / wrong-aud / wrong-iss / expired /
|
|
11
|
+
// unknown-kid / revoked token, with a `WWW-Authenticate: Bearer` header.
|
|
12
|
+
// A missing header omits error params (RFC 6750 §3: a bare challenge); a
|
|
13
|
+
// present-but-invalid token carries error="invalid_token". EVERY
|
|
14
|
+
// challenge carries `resource_metadata="<RFC 9728 well-known URL>"` —
|
|
15
|
+
// the MCP authorization spec (2025-06-18 revision) REQUIRES the 401 to
|
|
16
|
+
// point clients at the protected-resource metadata; without it the
|
|
17
|
+
// Claude Code client cannot locate the AS to run the refresh_token
|
|
18
|
+
// grant and falls back to interactive re-auth at every access expiry.
|
|
19
|
+
// 503 verifier/DB failure (JWKS unreachable, resolver down) — caught LOCALLY,
|
|
20
|
+
// never forwarded to next() (which would become a generic 500 and break
|
|
21
|
+
// this contract, C3 precedent).
|
|
22
|
+
//
|
|
23
|
+
// The raw user id is attached to req.userId; only its HASH enters the log
|
|
24
|
+
// context (hard rule 6). The token and its claims are never logged.
|
|
25
|
+
import { bindContext, hashUserId, loadOAuthConfig, log } from '@3ngram/config';
|
|
26
|
+
import { parseScopes, verifyAccessToken } from '@3ngram/core/auth';
|
|
27
|
+
const BEARER_PREFIX = 'Bearer ';
|
|
28
|
+
/** The OAuth scopes that protected resources advertise on a challenge. */
|
|
29
|
+
const RESOURCE_REALM = 'mcp';
|
|
30
|
+
/**
|
|
31
|
+
* Extract the token from a well-formed Authorization header, else undefined.
|
|
32
|
+
* Scheme matched case-insensitively (RFC 7235 §2.1); token
|
|
33
|
+
* bytes after the prefix are taken unchanged.
|
|
34
|
+
*/
|
|
35
|
+
function readBearerToken(header) {
|
|
36
|
+
if (header === undefined)
|
|
37
|
+
return undefined;
|
|
38
|
+
if (header.slice(0, BEARER_PREFIX.length).toLowerCase() !== BEARER_PREFIX.toLowerCase()) {
|
|
39
|
+
return undefined;
|
|
40
|
+
}
|
|
41
|
+
const token = header.slice(BEARER_PREFIX.length).trim();
|
|
42
|
+
return token.length > 0 ? token : undefined;
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* RFC 9728 §3.1: the protected-resource metadata URL inserts the well-known
|
|
46
|
+
* segment between the resource's origin and its path, so the `/mcp` resource
|
|
47
|
+
* is discovered at `/.well-known/oauth-protected-resource/mcp` (the document
|
|
48
|
+
* routes/well-known.ts serves). Pure derivation — no business logic. Returns
|
|
49
|
+
* undefined when the OAuth config is unavailable: a 401 challenge must stay a
|
|
50
|
+
* 401 even with a half-configured server (the verify path surfaces the config
|
|
51
|
+
* failure as its own 503); in production loadOAuthConfig always resolves.
|
|
52
|
+
*/
|
|
53
|
+
function resourceMetadataUrl() {
|
|
54
|
+
try {
|
|
55
|
+
const url = new URL(loadOAuthConfig().resource);
|
|
56
|
+
const path = url.pathname === '/' ? '' : url.pathname;
|
|
57
|
+
return `${url.origin}/.well-known/oauth-protected-resource${path}`;
|
|
58
|
+
}
|
|
59
|
+
catch {
|
|
60
|
+
return undefined;
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* Emit an RFC 6750 401. A bare challenge (no token presented) carries no error
|
|
65
|
+
* params; a rejected token carries error="invalid_token" + a human
|
|
66
|
+
* description. Every challenge carries the RFC 9728 §5.1 `resource_metadata`
|
|
67
|
+
* pointer (MCP authorization spec, 2025-06-18 revision) so a client holding a
|
|
68
|
+
* refresh token can rediscover the AS and refresh non-interactively.
|
|
69
|
+
* No token material or claim values enter the header (hard rule 6).
|
|
70
|
+
*/
|
|
71
|
+
function challenge(res, error) {
|
|
72
|
+
const params = [`realm="${RESOURCE_REALM}"`];
|
|
73
|
+
if (error !== undefined) {
|
|
74
|
+
params.push(`error="${error}"`, 'error_description="The access token is invalid"');
|
|
75
|
+
}
|
|
76
|
+
const metadataUrl = resourceMetadataUrl();
|
|
77
|
+
if (metadataUrl !== undefined)
|
|
78
|
+
params.push(`resource_metadata="${metadataUrl}"`);
|
|
79
|
+
res.setHeader('WWW-Authenticate', `Bearer ${params.join(', ')}`);
|
|
80
|
+
res.status(401).json({ error: error ?? 'unauthorized' });
|
|
81
|
+
}
|
|
82
|
+
/**
|
|
83
|
+
* Authenticate the request via a Bearer JWT. On success binds req.userId + the
|
|
84
|
+
* hashed id into the log context and continues. A missing token is a bare 401
|
|
85
|
+
* challenge; an invalid token is a 401 with error="invalid_token"; any
|
|
86
|
+
* verifier/DB failure is a 503 emitted here (never a leaked 500).
|
|
87
|
+
*/
|
|
88
|
+
export function oauthBearerAuth(req, res, next) {
|
|
89
|
+
const token = readBearerToken(req.header('authorization'));
|
|
90
|
+
if (token === undefined) {
|
|
91
|
+
challenge(res);
|
|
92
|
+
return;
|
|
93
|
+
}
|
|
94
|
+
verifyAccessToken(token, loadOAuthConfig())
|
|
95
|
+
.then((result) => {
|
|
96
|
+
if (!result.ok) {
|
|
97
|
+
challenge(res, 'invalid_token');
|
|
98
|
+
return;
|
|
99
|
+
}
|
|
100
|
+
req.userId = result.token.userId;
|
|
101
|
+
// Bind the verified token's granted scopes (RFC 6749 space-delimited
|
|
102
|
+
// `scope`) for per-tool enforcement downstream (ADR-0009 §RS). FAIL-CLOSED:
|
|
103
|
+
// a token with no/empty scope claim yields an empty set, so a later
|
|
104
|
+
// memory:write check fails. Scope VALUES are not content, but they are not
|
|
105
|
+
// logged either (only the user-id hash enters the log context).
|
|
106
|
+
req.oauthScopes = [...parseScopes(result.token.scope)];
|
|
107
|
+
bindContext({ userIdHash: hashUserId(result.token.userId) });
|
|
108
|
+
next();
|
|
109
|
+
})
|
|
110
|
+
.catch((err) => {
|
|
111
|
+
// Verifier or DB failure: emit the 503 contract HERE. Forwarding to next()
|
|
112
|
+
// would hit the generic 500 handler and break the status contract.
|
|
113
|
+
log().error({ err: err instanceof Error ? err.name : 'unknown' }, 'oauth-bearer: verifier unavailable');
|
|
114
|
+
res.status(503).json({ error: 'service_unavailable' });
|
|
115
|
+
});
|
|
116
|
+
}
|
|
117
|
+
//# sourceMappingURL=oauth-bearer.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"oauth-bearer.js","sourceRoot":"","sources":["../../src/middleware/oauth-bearer.ts"],"names":[],"mappings":"AAAA,sCAAsC;AACtC,mFAAmF;AACnF,iFAAiF;AACjF,iFAAiF;AACjF,uEAAuE;AACvE,+EAA+E;AAC/E,EAAE;AACF,6DAA6D;AAC7D,8DAA8D;AAC9D,2EAA2E;AAC3E,gFAAgF;AAChF,gFAAgF;AAChF,wEAAwE;AACxE,6EAA6E;AAC7E,8EA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A2E;QAC3E,gEAAgE;QAChE,GAAG,CAAC,WAAW,GAAG,CAAC,GAAG,WAAW,CAAC,MAAM,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,CAAA;QACtD,WAAW,CAAC,EAAE,UAAU,EAAE,UAAU,CAAC,MAAM,CAAC,KAAK,CAAC,MAAM,CAAC,EAAE,CAAC,CAAA;QAC5D,IAAI,EAAE,CAAA;IACR,CAAC,CAAC;SACD,KAAK,CAAC,CAAC,GAAY,EAAE,EAAE;QACtB,2EAA2E;QAC3E,mEAAmE;QACnE,GAAG,EAAE,CAAC,KAAK,CACT,EAAE,GAAG,EAAE,GAAG,YAAY,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC,SAAS,EAAE,EACpD,oCAAoC,CACrC,CAAA;QACD,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,EAAE,KAAK,EAAE,qBAAqB,EAAE,CAAC,CAAA;IACxD,CAAC,CAAC,CAAA;AACN,CAAC"}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import type { NextFunction, Request, Response } from 'express';
|
|
2
|
+
import type { Redis } from 'ioredis';
|
|
3
|
+
/** Resolve the bucket key for a request, or undefined to SKIP limiting it. */
|
|
4
|
+
export type KeyResolver = (req: Request) => string | undefined;
|
|
5
|
+
/** The Express middleware shape the factory returns; the wiring seam injects it. */
|
|
6
|
+
export type RateLimiterMiddleware = (req: Request, res: Response, next: NextFunction) => void;
|
|
7
|
+
/** Per-IP key: req.ip is the real client address because app.ts sets trust proxy. */
|
|
8
|
+
export declare const ipKey: KeyResolver;
|
|
9
|
+
/** Per-user key: the authenticated principal bound by the auth middleware. */
|
|
10
|
+
export declare const userIdKey: KeyResolver;
|
|
11
|
+
/**
|
|
12
|
+
* Composite IP+prefix key for the /api/v1 pre-auth rate-limit bucket.
|
|
13
|
+
* Reads the prefix segment of the `3ng_<prefix>_<secret>` header value so the
|
|
14
|
+
* limiter fires BEFORE apiKeyAuth runs. Keying on IP+prefix (not prefix alone)
|
|
15
|
+
* prevents a targeted-DoS: an attacker who knows the non-secret prefix cannot
|
|
16
|
+
* exhaust the victim's bucket from a different IP — only their own IP:prefix
|
|
17
|
+
* composite bucket is consumed. Returns undefined for Bearer/session paths (no
|
|
18
|
+
* X-API-Key) or malformed keys (< 3 segments) so those requests skip the limiter.
|
|
19
|
+
*
|
|
20
|
+
* TRADE-OFF: a legitimate user that distributes requests across many IPs gets
|
|
21
|
+
* separate buckets per IP (each up to the full limit); the protection is
|
|
22
|
+
* per-source rather than global-per-key. This is the accepted design.
|
|
23
|
+
*/
|
|
24
|
+
export declare const apiKeyIdKey: KeyResolver;
|
|
25
|
+
export interface RateLimiterOptions {
|
|
26
|
+
/** Allowed requests per `duration` window. */
|
|
27
|
+
points: number;
|
|
28
|
+
/** Window length in seconds. */
|
|
29
|
+
duration: number;
|
|
30
|
+
/**
|
|
31
|
+
* Namespace for the Redis keys (e.g. 'mcp:user', 'oauth:ip'). Composes with the
|
|
32
|
+
* resolved key as `<keyPrefix>:<key>` so independent buckets never collide.
|
|
33
|
+
*/
|
|
34
|
+
keyPrefix: string;
|
|
35
|
+
/**
|
|
36
|
+
* How to derive the bucket key from a request. Defaults to per-user (req.userId).
|
|
37
|
+
* Use `ipKey` for unauthenticated endpoints. When it returns undefined the
|
|
38
|
+
* request is NOT limited (e.g. an endpoint reached before identity is bound).
|
|
39
|
+
*/
|
|
40
|
+
keyResolver?: KeyResolver;
|
|
41
|
+
/**
|
|
42
|
+
* Redis client for a cross-instance store. When omitted the limiter uses an
|
|
43
|
+
* in-process RateLimiterMemory (local dev + CI; tests inject nothing).
|
|
44
|
+
*/
|
|
45
|
+
redis?: Redis | undefined;
|
|
46
|
+
/**
|
|
47
|
+
* On a STORE failure (Redis unreachable), allow the request through (true,
|
|
48
|
+
* default) or reject it 503-style via next(err) (false). Default fail-open:
|
|
49
|
+
* availability over protection for a protective control.
|
|
50
|
+
*/
|
|
51
|
+
failOpen?: boolean;
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* Create rate-limiting Express middleware. Consumes one point per request for the
|
|
55
|
+
* resolved key; over-limit yields 429 + Retry-After, a store failure fails open
|
|
56
|
+
* (or closed when `failOpen: false`). Stateless and reusable across endpoints.
|
|
57
|
+
*/
|
|
58
|
+
export declare function createRateLimiter(options: RateLimiterOptions): RateLimiterMiddleware;
|
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
// Redis-backed rate limiting (ADR-0009 §6 per-IP on the OAuth/login endpoints).
|
|
3
|
+
//
|
|
4
|
+
// REUSABLE FACTORY: createRateLimiter({ points, duration, keyPrefix, ... })
|
|
5
|
+
// returns Express middleware backed by rate-limiter-flexible — RateLimiterRedis
|
|
6
|
+
// when an ioredis client is injected (cross-instance: Railway runs N replicas,
|
|
7
|
+
// so the bucket MUST live in Redis, not per-process), else RateLimiterMemory
|
|
8
|
+
// (local/CI parity, and the test seam — NO real Redis in CI).
|
|
9
|
+
//
|
|
10
|
+
// KEYING DIMENSIONS (mcp-design.md "per-user + per-key"):
|
|
11
|
+
// - /mcp -> per-AUTHENTICATED-USER (req.userId, bound by oauthBearerAuth).
|
|
12
|
+
// - /auth/login + future /oauth/* -> per-IP (req.ip — correct because app.ts
|
|
13
|
+
// sets `trust proxy`, so this is the client address, not the Railway proxy).
|
|
14
|
+
// - per-KEY (API-key id): the factory ACCEPTS an optional keyResolver so a
|
|
15
|
+
// caller can compose a second bucket, but D4 wires NO per-key limiter:
|
|
16
|
+
// /mcp is Bearer-ONLY (API keys never reach it) and apiKeyAuth sets only
|
|
17
|
+
// req.userId (no req.apiKeyId reaches a limited route this slice). Per-key
|
|
18
|
+
// limiting lands when A2's /api/* is limited (the documented follow-up that
|
|
19
|
+
// also plumbs req.apiKeyId through api-key.ts). Building the seam now keeps
|
|
20
|
+
// that follow-up additive.
|
|
21
|
+
//
|
|
22
|
+
// FAIL-OPEN on Redis-down (DECISION): rate limiting is protective, not
|
|
23
|
+
// correctness — a Redis outage must NOT take down the API. On a store error
|
|
24
|
+
// (distinct from a real over-limit rejection, which carries msBeforeNext) we log
|
|
25
|
+
// a REDACTED warning (never REDIS_URL, never a key) and call next(). The tradeoff
|
|
26
|
+
// is documented in the changeset; flip `failOpen: false` per-limiter if a future
|
|
27
|
+
// endpoint needs fail-closed.
|
|
28
|
+
//
|
|
29
|
+
// On limit exceeded: 429 with Retry-After (seconds) + a structured body
|
|
30
|
+
// { error: 'rate_limited' } and no further content (hard rule 5: thin transport).
|
|
31
|
+
import { log, rateLimitStoreFailure } from '@3ngram/config';
|
|
32
|
+
import { RateLimiterMemory, RateLimiterRedis, } from 'rate-limiter-flexible';
|
|
33
|
+
/** Per-IP key: req.ip is the real client address because app.ts sets trust proxy. */
|
|
34
|
+
export const ipKey = (req) => req.ip;
|
|
35
|
+
/** Per-user key: the authenticated principal bound by the auth middleware. */
|
|
36
|
+
export const userIdKey = (req) => req.userId;
|
|
37
|
+
/**
|
|
38
|
+
* Composite IP+prefix key for the /api/v1 pre-auth rate-limit bucket.
|
|
39
|
+
* Reads the prefix segment of the `3ng_<prefix>_<secret>` header value so the
|
|
40
|
+
* limiter fires BEFORE apiKeyAuth runs. Keying on IP+prefix (not prefix alone)
|
|
41
|
+
* prevents a targeted-DoS: an attacker who knows the non-secret prefix cannot
|
|
42
|
+
* exhaust the victim's bucket from a different IP — only their own IP:prefix
|
|
43
|
+
* composite bucket is consumed. Returns undefined for Bearer/session paths (no
|
|
44
|
+
* X-API-Key) or malformed keys (< 3 segments) so those requests skip the limiter.
|
|
45
|
+
*
|
|
46
|
+
* TRADE-OFF: a legitimate user that distributes requests across many IPs gets
|
|
47
|
+
* separate buckets per IP (each up to the full limit); the protection is
|
|
48
|
+
* per-source rather than global-per-key. This is the accepted design.
|
|
49
|
+
*/
|
|
50
|
+
export const apiKeyIdKey = (req) => {
|
|
51
|
+
// Prefer req.apiKeyId when already bound (post-auth paths); fall back to
|
|
52
|
+
// parsing the raw header so the limiter also works before auth runs.
|
|
53
|
+
const prefix = req.apiKeyId !== undefined
|
|
54
|
+
? req.apiKeyId
|
|
55
|
+
: (() => {
|
|
56
|
+
const raw = req.header('x-api-key')?.trim();
|
|
57
|
+
if (raw === undefined || raw.length === 0)
|
|
58
|
+
return undefined;
|
|
59
|
+
const segments = raw.split('_');
|
|
60
|
+
return segments.length >= 3 ? segments[1] : undefined;
|
|
61
|
+
})();
|
|
62
|
+
if (prefix === undefined)
|
|
63
|
+
return undefined;
|
|
64
|
+
// Composite key: IP is the real client address because app.ts sets trust proxy.
|
|
65
|
+
return req.ip !== undefined ? `${req.ip}:${prefix}` : prefix;
|
|
66
|
+
};
|
|
67
|
+
/**
|
|
68
|
+
* A real over-limit rejection carries `msBeforeNext`; a store/infra failure does
|
|
69
|
+
* not look like that. rate-limiter-flexible rejects with a RateLimiterRes on
|
|
70
|
+
* over-limit and with the underlying Error on a store failure — discriminate so
|
|
71
|
+
* we only fail-open on the latter.
|
|
72
|
+
*/
|
|
73
|
+
function isOverLimit(rejection) {
|
|
74
|
+
return (typeof rejection === 'object' &&
|
|
75
|
+
rejection !== null &&
|
|
76
|
+
'msBeforeNext' in rejection &&
|
|
77
|
+
typeof rejection.msBeforeNext === 'number');
|
|
78
|
+
}
|
|
79
|
+
/** Build the underlying limiter: Redis-backed when a client is present, else memory. */
|
|
80
|
+
function buildLimiter(options) {
|
|
81
|
+
const base = {
|
|
82
|
+
points: options.points,
|
|
83
|
+
duration: options.duration,
|
|
84
|
+
keyPrefix: options.keyPrefix,
|
|
85
|
+
};
|
|
86
|
+
if (options.redis !== undefined) {
|
|
87
|
+
return new RateLimiterRedis({ ...base, storeClient: options.redis });
|
|
88
|
+
}
|
|
89
|
+
return new RateLimiterMemory(base);
|
|
90
|
+
}
|
|
91
|
+
/**
|
|
92
|
+
* Create rate-limiting Express middleware. Consumes one point per request for the
|
|
93
|
+
* resolved key; over-limit yields 429 + Retry-After, a store failure fails open
|
|
94
|
+
* (or closed when `failOpen: false`). Stateless and reusable across endpoints.
|
|
95
|
+
*/
|
|
96
|
+
export function createRateLimiter(options) {
|
|
97
|
+
const limiter = buildLimiter(options);
|
|
98
|
+
const resolveKey = options.keyResolver ?? userIdKey;
|
|
99
|
+
const failOpen = options.failOpen ?? true;
|
|
100
|
+
return (req, res, next) => {
|
|
101
|
+
const key = resolveKey(req);
|
|
102
|
+
if (key === undefined) {
|
|
103
|
+
// No principal/IP to key on — do not limit (e.g. identity not yet bound).
|
|
104
|
+
next();
|
|
105
|
+
return;
|
|
106
|
+
}
|
|
107
|
+
limiter
|
|
108
|
+
.consume(key)
|
|
109
|
+
.then(() => next())
|
|
110
|
+
.catch((rejection) => {
|
|
111
|
+
if (isOverLimit(rejection)) {
|
|
112
|
+
const retryAfterSeconds = Math.ceil(rejection.msBeforeNext / 1000);
|
|
113
|
+
res.setHeader('Retry-After', String(retryAfterSeconds));
|
|
114
|
+
res.status(429).json({ error: 'rate_limited' });
|
|
115
|
+
return;
|
|
116
|
+
}
|
|
117
|
+
// Store failure (Redis-down): the key/IP is identifying material and the
|
|
118
|
+
// connection string is a credential — neither enters the log line or the
|
|
119
|
+
// metric. key_prefix (the limiter/route class) is the only label.
|
|
120
|
+
//
|
|
121
|
+
// TRADEOFF (DECISION, see header): fail-open trades protection for
|
|
122
|
+
// availability — a Redis outage with failOpen:true lets EVERY request
|
|
123
|
+
// through, so brute-force throttling on /auth/login (ADR-0009 §6)
|
|
124
|
+
// silently lapses with no over-limit 429s to alert on. The counter below
|
|
125
|
+
// is the alert signal that makes the outage observable: an operator can
|
|
126
|
+
// react (or flip a specific limiter to failOpen:false to fail-closed,
|
|
127
|
+
// which locks out that route during the outage — a conscious availability
|
|
128
|
+
// call left to the operator, NOT defaulted here).
|
|
129
|
+
rateLimitStoreFailure.add(1, { key_prefix: options.keyPrefix, fail_open: failOpen });
|
|
130
|
+
log().warn({ keyPrefix: options.keyPrefix, failOpen }, 'rate-limit: store unavailable');
|
|
131
|
+
if (failOpen) {
|
|
132
|
+
next();
|
|
133
|
+
return;
|
|
134
|
+
}
|
|
135
|
+
res.status(503).json({ error: 'service_unavailable' });
|
|
136
|
+
});
|
|
137
|
+
};
|
|
138
|
+
}
|
|
139
|
+
//# sourceMappingURL=rate-limit.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"rate-limit.js","sourceRoot":"","sources":["../../src/middleware/rate-limit.ts"],"names":[],"mappings":"AAAA,sCAAsC;AACtC,gFAAgF;AAChF,EAAE;AACF,4EAA4E;AAC5E,gFAAgF;AAChF,+EAA+E;AAC/E,6EAA6E;AAC7E,8DAA8D;AAC9D,EAAE;AACF,0DAA0D;AAC1D,8EAA8E;AAC9E,+EAA+E;AAC/E,iFAAiF;AACjF,6EAA6E;AAC7E,2EAA2E;AAC3E,6EAA6E;AAC7E,+EAA+E;AAC/E,gFAAgF;AAChF,gFAAgF;AAChF,+BAA+B;AAC/B,EAAE;AACF,uEAAuE;AACvE,4EAA4E;AAC5E,iFAAiF;AACjF,kFAAkF;AAClF,iFAAiF;AACjF,8BAA8B;AAC9B,EAAE;AACF,wEAAwE;AACxE,kFAAkF;AAClF,OAAO,EAAE,GAAG,EAAE,qBAAqB,EAAE,MAAM,gBAAgB,CAAA;AAG3D,OAAO,EAGL,iBAAiB,EACjB,gBAAgB,GAEjB,MAAM,uBAAuB,CAAA;AAQ9B,qFAAqF;AACrF,MAAM,CAAC,MAAM,KAAK,GAAgB,CAAC,GAAG,EAAE,EAAE,CAAC,GAAG,CAAC,EAAE,CAAA;AAEjD,8EAA8E;AAC9E,MAAM,CAAC,MAAM,SAAS,GAAgB,CAAC,GAAG,EAAE,EAAE,CAAC,GAAG,CAAC,MAAM,CAAA;AAEzD;;;;;;;;;;;;GAYG;AACH,MAAM,CAAC,MAAM,WAAW,GAAgB,CAAC,GAAG,EAAE,EAAE;IAC9C,yEAAyE;IACzE,qEAAqE;IACrE,MAAM,MAAM,GACV,GA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AkD;YAClD,qBAAqB,CAAC,GAAG,CAAC,CAAC,EAAE,EAAE,UAAU,EAAE,OAAO,CAAC,SAAS,EAAE,SAAS,EAAE,QAAQ,EAAE,CAAC,CAAA;YACpF,GAAG,EAAE,CAAC,IAAI,CAAC,EAAE,SAAS,EAAE,OAAO,CAAC,SAAS,EAAE,QAAQ,EAAE,EAAE,+BAA+B,CAAC,CAAA;YACvF,IAAI,QAAQ,EAAE,CAAC;gBACb,IAAI,EAAE,CAAA;gBACN,OAAM;YACR,CAAC;YACD,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,EAAE,KAAK,EAAE,qBAAqB,EAAE,CAAC,CAAA;QACxD,CAAC,CAAC,CAAA;IACN,CAAC,CAAA;AACH,CAAC"}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type { NextFunction, Request, Response } from 'express';
|
|
2
|
+
/**
|
|
3
|
+
* Enter the AsyncLocalStorage request scope at the transport boundary
|
|
4
|
+
* (observability.md §1): every log line downstream carries request_id and
|
|
5
|
+
* surface via log(). The id is echoed as x-request-id for client correlation.
|
|
6
|
+
*/
|
|
7
|
+
export declare function requestContext(_req: Request, res: Response, next: NextFunction): void;
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
import { randomUUID } from 'node:crypto';
|
|
3
|
+
import { runWithContext } from '@3ngram/config';
|
|
4
|
+
/**
|
|
5
|
+
* Enter the AsyncLocalStorage request scope at the transport boundary
|
|
6
|
+
* (observability.md §1): every log line downstream carries request_id and
|
|
7
|
+
* surface via log(). The id is echoed as x-request-id for client correlation.
|
|
8
|
+
*/
|
|
9
|
+
export function requestContext(_req, res, next) {
|
|
10
|
+
const requestId = randomUUID();
|
|
11
|
+
res.setHeader('x-request-id', requestId);
|
|
12
|
+
runWithContext({ requestId, surface: 'rest' }, next);
|
|
13
|
+
}
|
|
14
|
+
//# sourceMappingURL=request-context.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"request-context.js","sourceRoot":"","sources":["../../src/middleware/request-context.ts"],"names":[],"mappings":"AAAA,sCAAsC;AACtC,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAA;AACxC,OAAO,EAAE,cAAc,EAAE,MAAM,gBAAgB,CAAA;AAG/C;;;;GAIG;AACH,MAAM,UAAU,cAAc,CAAC,IAAa,EAAE,GAAa,EAAE,IAAkB;IAC7E,MAAM,SAAS,GAAG,UAAU,EAAE,CAAA;IAC9B,GAAG,CAAC,SAAS,CAAC,cAAc,EAAE,SAAS,CAAC,CAAA;IACxC,cAAc,CAAC,EAAE,SAAS,EAAE,OAAO,EAAE,MAAM,EAAE,EAAE,IAAI,CAAC,CAAA;AACtD,CAAC"}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import type { ZodError, ZodType, z } from 'zod';
|
|
2
|
+
/** A tool/route RESULT failed its output schema — a server fault, not bad input. */
|
|
3
|
+
export declare class OutputValidationError extends Error {
|
|
4
|
+
/** The tool/route whose result failed validation. */
|
|
5
|
+
readonly surface: string;
|
|
6
|
+
/** Number of schema issues (bounded metadata only). */
|
|
7
|
+
readonly issueCount: number;
|
|
8
|
+
/** Issue paths — schema field names and array indices, never values. */
|
|
9
|
+
readonly issuePaths: string[];
|
|
10
|
+
constructor(surface: string, zodError: ZodError);
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* Parse a handler's RESULT against its output schema, rethrowing a ZodError as
|
|
14
|
+
* {@link OutputValidationError} so the transport error ladder can distinguish a
|
|
15
|
+
* server-side result-shape fault from malformed caller input. Input `.parse()`
|
|
16
|
+
* calls stay bare — only OUTPUT parses go through here.
|
|
17
|
+
*/
|
|
18
|
+
export declare function parseOutput<S extends ZodType>(surface: string, schema: S, value: unknown): z.infer<S>;
|