@4da/mcp-server 4.6.6 → 5.0.1
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/README.md +19 -1
- package/dist/auth-context.d.ts +49 -0
- package/dist/auth-context.js +72 -0
- package/dist/auth.d.ts +42 -15
- package/dist/auth.js +160 -49
- package/dist/db.d.ts +1 -1
- package/dist/db.js +72 -37
- package/dist/http-transport.d.ts +72 -10
- package/dist/http-transport.js +175 -99
- package/dist/index.d.ts +7 -24
- package/dist/index.js +178 -135
- package/dist/setup.js +0 -0
- package/dist/tool-dispatch.d.ts +6 -6
- package/dist/tool-dispatch.js +6 -0
- package/dist/tools/get-actionable-signals.js +5 -1
- package/dist/tools/get-relevant-content.js +4 -1
- package/package.json +31 -14
package/README.md
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
[](https://www.npmjs.com/package/@4da/mcp-server)
|
|
4
4
|
[](LICENSE)
|
|
5
|
-
[](https://nodejs.org/)
|
|
6
6
|
[](https://smithery.ai/server/@4da/mcp-server)
|
|
7
7
|
|
|
8
8
|
**Dependency intelligence for AI coding agents.** Live CVE scanning, dependency health checks, upgrade planning, ecosystem news, and persistent decision memory. Zero config, privacy-first.
|
|
@@ -188,6 +188,21 @@ npx @4da/mcp-server
|
|
|
188
188
|
npx @4da/mcp-server --http --port 4840
|
|
189
189
|
```
|
|
190
190
|
|
|
191
|
+
The HTTP transport binds to `127.0.0.1` by default and applies a `Host`-header
|
|
192
|
+
DNS rebinding guard to every request. Exposing it beyond this machine requires
|
|
193
|
+
a shared secret:
|
|
194
|
+
|
|
195
|
+
```bash
|
|
196
|
+
MCP_AUTH_SECRET=<same value as the relay's JWT_SECRET> \
|
|
197
|
+
MCP_ALLOWED_HOSTS=mcp.internal \
|
|
198
|
+
npx @4da/mcp-server --http --host 0.0.0.0
|
|
199
|
+
```
|
|
200
|
+
|
|
201
|
+
Without `MCP_AUTH_SECRET` a non-loopback bind is refused at startup. With it,
|
|
202
|
+
every request must carry a Bearer token whose HMAC-SHA256 signature verifies
|
|
203
|
+
against that secret, and the token's role is enforced per tool (`viewer` is
|
|
204
|
+
read-only; `member` and `admin` may write). Put TLS in front of it.
|
|
205
|
+
|
|
191
206
|
## CLI Reference
|
|
192
207
|
|
|
193
208
|
```
|
|
@@ -204,6 +219,9 @@ npx @4da/mcp-server --version # Print version
|
|
|
204
219
|
|----------|-------------|---------|
|
|
205
220
|
| `FOURDA_DB_PATH` | Path to 4DA's SQLite database | Auto-detected |
|
|
206
221
|
| `FOURDA_OFFLINE` | Disable all network calls | `false` |
|
|
222
|
+
| `MCP_AUTH_SECRET` | Shared secret for verifying Bearer tokens on `--http` (HMAC-SHA256). Falls back to `JWT_SECRET`. Unset means no token is accepted. | Unset |
|
|
223
|
+
| `MCP_AUTH_REQUIRED` | Require auth on a **loopback** `--http` bind. Always required on a non-loopback bind. | `false` |
|
|
224
|
+
| `MCP_ALLOWED_HOSTS` | Extra comma-separated hostnames accepted in `Host`/`Origin` (needed when binding to `0.0.0.0`). | localhost only |
|
|
207
225
|
|
|
208
226
|
## FAQ
|
|
209
227
|
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Per-request authorization context.
|
|
3
|
+
*
|
|
4
|
+
* The MCP v2 serving entries build a fresh `Server` per request from a
|
|
5
|
+
* zero-argument factory, so verified claims cannot be threaded through as a
|
|
6
|
+
* constructor argument. `AsyncLocalStorage` carries them from the HTTP
|
|
7
|
+
* transport (where the token is verified) to the tool-dispatch path (where the
|
|
8
|
+
* role is enforced) without touching every handler signature.
|
|
9
|
+
*
|
|
10
|
+
* Trust model:
|
|
11
|
+
* - stdio → no context at all. The host launched this process; it
|
|
12
|
+
* already has local process rights. Nothing to enforce.
|
|
13
|
+
* - HTTP, no auth→ context with `claims: null, enforced: false`. Only
|
|
14
|
+
* reachable when bound to loopback with auth disabled, i.e.
|
|
15
|
+
* the same trust boundary as stdio.
|
|
16
|
+
* - HTTP, auth → context with verified claims. Roles are enforced.
|
|
17
|
+
*/
|
|
18
|
+
import { type TeamClaims } from "./auth.js";
|
|
19
|
+
export interface RequestAuthContext {
|
|
20
|
+
/** Claims verified by `extractAuthClaims`, or null when auth was not required. */
|
|
21
|
+
claims: TeamClaims | null;
|
|
22
|
+
/** True when the transport required authentication for this request. */
|
|
23
|
+
enforced: boolean;
|
|
24
|
+
}
|
|
25
|
+
/** Run `fn` (and everything it awaits) with the given auth context attached. */
|
|
26
|
+
export declare function runWithAuthContext<T>(ctx: RequestAuthContext, fn: () => T): T;
|
|
27
|
+
/** The current request's auth context, or undefined on the stdio path. */
|
|
28
|
+
export declare function getAuthContext(): RequestAuthContext | undefined;
|
|
29
|
+
/** Thrown when an authenticated caller's role does not permit a tool call. */
|
|
30
|
+
export declare class AuthorizationError extends Error {
|
|
31
|
+
constructor(message: string);
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* The operation a tool performs, derived from the registry annotation that
|
|
35
|
+
* already declares it. `readOnlyHint: true` means the tool cannot mutate
|
|
36
|
+
* state; everything else is treated as a write.
|
|
37
|
+
*
|
|
38
|
+
* Deliberately coarse: `decision_memory` and `agent_memory` have read-shaped
|
|
39
|
+
* actions too, but they are dispatched through a tool that CAN write, so a
|
|
40
|
+
* viewer is denied the whole tool rather than trusting an `action` argument to
|
|
41
|
+
* decide. Unknown tools fail closed as writes.
|
|
42
|
+
*/
|
|
43
|
+
export declare function requiredOperation(toolName: string): "read" | "write";
|
|
44
|
+
/**
|
|
45
|
+
* Enforce the caller's role against the tool being invoked.
|
|
46
|
+
* Throws `AuthorizationError` when the role is insufficient.
|
|
47
|
+
*/
|
|
48
|
+
export declare function assertToolPermission(toolName: string): void;
|
|
49
|
+
//# sourceMappingURL=auth-context.d.ts.map
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
/**
|
|
3
|
+
* Per-request authorization context.
|
|
4
|
+
*
|
|
5
|
+
* The MCP v2 serving entries build a fresh `Server` per request from a
|
|
6
|
+
* zero-argument factory, so verified claims cannot be threaded through as a
|
|
7
|
+
* constructor argument. `AsyncLocalStorage` carries them from the HTTP
|
|
8
|
+
* transport (where the token is verified) to the tool-dispatch path (where the
|
|
9
|
+
* role is enforced) without touching every handler signature.
|
|
10
|
+
*
|
|
11
|
+
* Trust model:
|
|
12
|
+
* - stdio → no context at all. The host launched this process; it
|
|
13
|
+
* already has local process rights. Nothing to enforce.
|
|
14
|
+
* - HTTP, no auth→ context with `claims: null, enforced: false`. Only
|
|
15
|
+
* reachable when bound to loopback with auth disabled, i.e.
|
|
16
|
+
* the same trust boundary as stdio.
|
|
17
|
+
* - HTTP, auth → context with verified claims. Roles are enforced.
|
|
18
|
+
*/
|
|
19
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
20
|
+
import { hasPermission } from "./auth.js";
|
|
21
|
+
import { TOOL_REGISTRY } from "./schema-registry.js";
|
|
22
|
+
const storage = new AsyncLocalStorage();
|
|
23
|
+
/** Run `fn` (and everything it awaits) with the given auth context attached. */
|
|
24
|
+
export function runWithAuthContext(ctx, fn) {
|
|
25
|
+
return storage.run(ctx, fn);
|
|
26
|
+
}
|
|
27
|
+
/** The current request's auth context, or undefined on the stdio path. */
|
|
28
|
+
export function getAuthContext() {
|
|
29
|
+
return storage.getStore();
|
|
30
|
+
}
|
|
31
|
+
/** Thrown when an authenticated caller's role does not permit a tool call. */
|
|
32
|
+
export class AuthorizationError extends Error {
|
|
33
|
+
constructor(message) {
|
|
34
|
+
super(message);
|
|
35
|
+
this.name = "AuthorizationError";
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* The operation a tool performs, derived from the registry annotation that
|
|
40
|
+
* already declares it. `readOnlyHint: true` means the tool cannot mutate
|
|
41
|
+
* state; everything else is treated as a write.
|
|
42
|
+
*
|
|
43
|
+
* Deliberately coarse: `decision_memory` and `agent_memory` have read-shaped
|
|
44
|
+
* actions too, but they are dispatched through a tool that CAN write, so a
|
|
45
|
+
* viewer is denied the whole tool rather than trusting an `action` argument to
|
|
46
|
+
* decide. Unknown tools fail closed as writes.
|
|
47
|
+
*/
|
|
48
|
+
export function requiredOperation(toolName) {
|
|
49
|
+
return TOOL_REGISTRY[toolName]?.annotations.readOnlyHint ? "read" : "write";
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* Enforce the caller's role against the tool being invoked.
|
|
53
|
+
* Throws `AuthorizationError` when the role is insufficient.
|
|
54
|
+
*/
|
|
55
|
+
export function assertToolPermission(toolName) {
|
|
56
|
+
const ctx = storage.getStore();
|
|
57
|
+
if (!ctx)
|
|
58
|
+
return; // stdio — local process, no network identity to enforce
|
|
59
|
+
const operation = requiredOperation(toolName);
|
|
60
|
+
if (!ctx.claims) {
|
|
61
|
+
if (ctx.enforced) {
|
|
62
|
+
// Defensive: the transport rejects unauthenticated requests with 401
|
|
63
|
+
// before dispatch, so reaching here means the gate was bypassed.
|
|
64
|
+
throw new AuthorizationError(`Authentication required for '${toolName}' but no verified claims are present`);
|
|
65
|
+
}
|
|
66
|
+
return; // loopback HTTP with auth disabled — same trust boundary as stdio
|
|
67
|
+
}
|
|
68
|
+
if (!hasPermission(ctx.claims.role, operation)) {
|
|
69
|
+
throw new AuthorizationError(`Role '${ctx.claims.role}' is not permitted to perform '${operation}' operations (tool: ${toolName})`);
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
//# sourceMappingURL=auth-context.js.map
|
package/dist/auth.d.ts
CHANGED
|
@@ -1,36 +1,63 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* MCP Authentication
|
|
2
|
+
* MCP Authentication — Bearer token verification for the HTTP transport.
|
|
3
3
|
*
|
|
4
|
-
*
|
|
5
|
-
*
|
|
6
|
-
* HTTP transport
|
|
4
|
+
* Stdio transport (one server process per host, launched by the host itself)
|
|
5
|
+
* is unauthenticated by design: the caller already has local process rights.
|
|
6
|
+
* The HTTP transport verifies every token cryptographically before a single
|
|
7
|
+
* claim is trusted.
|
|
8
|
+
*
|
|
9
|
+
* Verification is HMAC-SHA256 over `base64url(header) + "." + base64url(payload)`
|
|
10
|
+
* compared in constant time against the shared relay secret, followed by
|
|
11
|
+
* expiry, not-before, and role checks. Tokens are issued by the 4DA Team Relay
|
|
12
|
+
* (`relay/src/auth.rs`: `jsonwebtoken` v9, `Header::default()` = HS256,
|
|
13
|
+
* `Validation::default()` = HS256 + mandatory `exp` + 60s leeway) — the
|
|
14
|
+
* parameters below mirror that issuer exactly.
|
|
15
|
+
*
|
|
16
|
+
* FAIL CLOSED: when no shared secret is configured, every token is rejected.
|
|
17
|
+
* A server that cannot verify a signature must never accept the claims inside
|
|
18
|
+
* it — the payload of an unverified JWT is attacker-controlled plaintext.
|
|
7
19
|
*/
|
|
8
20
|
import { IncomingMessage } from "node:http";
|
|
21
|
+
/** Roles the relay issues. Anything else is rejected. */
|
|
22
|
+
export declare const KNOWN_ROLES: readonly ["admin", "member", "viewer"];
|
|
23
|
+
export type TeamRole = (typeof KNOWN_ROLES)[number];
|
|
9
24
|
export interface TeamClaims {
|
|
10
25
|
team_id: string;
|
|
11
26
|
client_id: string;
|
|
12
|
-
role:
|
|
27
|
+
role: TeamRole;
|
|
13
28
|
exp: number;
|
|
14
29
|
}
|
|
15
30
|
/**
|
|
16
|
-
*
|
|
31
|
+
* The shared secret used to verify relay-issued tokens.
|
|
17
32
|
*
|
|
18
|
-
*
|
|
19
|
-
*
|
|
33
|
+
* `MCP_AUTH_SECRET` is the name to use when the MCP server is deployed on its
|
|
34
|
+
* own; `JWT_SECRET` is accepted as a fallback so a server co-deployed with the
|
|
35
|
+
* relay (which reads `JWT_SECRET`) inherits the same value without duplicating
|
|
36
|
+
* the config. Whitespace-only values count as unset.
|
|
37
|
+
*/
|
|
38
|
+
export declare function getAuthSecret(): string | undefined;
|
|
39
|
+
/**
|
|
40
|
+
* Verify a JWT's signature and claims. Returns the claims only when the
|
|
41
|
+
* signature checks out against the configured secret AND the claims are valid.
|
|
20
42
|
*
|
|
21
|
-
*
|
|
22
|
-
*
|
|
23
|
-
* For launch, we validate structure + expiry. Post-launch, add signature verification.
|
|
43
|
+
* @param token The raw JWT (no "Bearer " prefix).
|
|
44
|
+
* @param nowMs Current time in epoch milliseconds (injectable for tests).
|
|
24
45
|
*/
|
|
25
|
-
export declare function
|
|
46
|
+
export declare function verifyToken(token: string, nowMs?: number): TeamClaims | null;
|
|
26
47
|
/**
|
|
27
|
-
*
|
|
28
|
-
*
|
|
48
|
+
* Extract and verify the Bearer token on an HTTP request.
|
|
49
|
+
*
|
|
50
|
+
* Returns the verified claims, or null when the request carries no token, a
|
|
51
|
+
* malformed token, a forged/tampered token, or an expired one.
|
|
29
52
|
*/
|
|
30
|
-
export declare function
|
|
53
|
+
export declare function extractAuthClaims(req: IncomingMessage): TeamClaims | null;
|
|
31
54
|
/**
|
|
32
55
|
* Check if a role has permission for a specific operation.
|
|
33
56
|
* Viewers can read, members can read+write, admins can do everything.
|
|
57
|
+
*
|
|
58
|
+
* Enforced on the tool-dispatch path — see `assertToolPermission` in
|
|
59
|
+
* `auth-context.ts`, which maps each tool to an operation via its
|
|
60
|
+
* `readOnlyHint` annotation.
|
|
34
61
|
*/
|
|
35
62
|
export declare function hasPermission(role: string, operation: "read" | "write" | "admin"): boolean;
|
|
36
63
|
//# sourceMappingURL=auth.d.ts.map
|
package/dist/auth.js
CHANGED
|
@@ -1,76 +1,187 @@
|
|
|
1
1
|
// SPDX-License-Identifier: Apache-2.0
|
|
2
2
|
/**
|
|
3
|
-
* MCP Authentication
|
|
3
|
+
* MCP Authentication — Bearer token verification for the HTTP transport.
|
|
4
4
|
*
|
|
5
|
-
*
|
|
6
|
-
*
|
|
7
|
-
* HTTP transport
|
|
5
|
+
* Stdio transport (one server process per host, launched by the host itself)
|
|
6
|
+
* is unauthenticated by design: the caller already has local process rights.
|
|
7
|
+
* The HTTP transport verifies every token cryptographically before a single
|
|
8
|
+
* claim is trusted.
|
|
9
|
+
*
|
|
10
|
+
* Verification is HMAC-SHA256 over `base64url(header) + "." + base64url(payload)`
|
|
11
|
+
* compared in constant time against the shared relay secret, followed by
|
|
12
|
+
* expiry, not-before, and role checks. Tokens are issued by the 4DA Team Relay
|
|
13
|
+
* (`relay/src/auth.rs`: `jsonwebtoken` v9, `Header::default()` = HS256,
|
|
14
|
+
* `Validation::default()` = HS256 + mandatory `exp` + 60s leeway) — the
|
|
15
|
+
* parameters below mirror that issuer exactly.
|
|
16
|
+
*
|
|
17
|
+
* FAIL CLOSED: when no shared secret is configured, every token is rejected.
|
|
18
|
+
* A server that cannot verify a signature must never accept the claims inside
|
|
19
|
+
* it — the payload of an unverified JWT is attacker-controlled plaintext.
|
|
20
|
+
*/
|
|
21
|
+
import { createHmac, timingSafeEqual } from "node:crypto";
|
|
22
|
+
/** Roles the relay issues. Anything else is rejected. */
|
|
23
|
+
export const KNOWN_ROLES = ["admin", "member", "viewer"];
|
|
24
|
+
/**
|
|
25
|
+
* The only accepted signing algorithm. Pinning a single algorithm is what
|
|
26
|
+
* closes algorithm-confusion attacks: `alg: none` (no signature at all) and
|
|
27
|
+
* asymmetric algorithms (where a public key can be replayed as the HMAC key)
|
|
28
|
+
* are rejected before any HMAC is computed.
|
|
8
29
|
*/
|
|
30
|
+
const ACCEPTED_ALG = "HS256";
|
|
31
|
+
/** Clock skew tolerance, matching `jsonwebtoken`'s default `leeway` on the issuer. */
|
|
32
|
+
const CLOCK_SKEW_SECONDS = 60;
|
|
9
33
|
/**
|
|
10
|
-
*
|
|
34
|
+
* The shared secret used to verify relay-issued tokens.
|
|
11
35
|
*
|
|
12
|
-
*
|
|
13
|
-
*
|
|
36
|
+
* `MCP_AUTH_SECRET` is the name to use when the MCP server is deployed on its
|
|
37
|
+
* own; `JWT_SECRET` is accepted as a fallback so a server co-deployed with the
|
|
38
|
+
* relay (which reads `JWT_SECRET`) inherits the same value without duplicating
|
|
39
|
+
* the config. Whitespace-only values count as unset.
|
|
40
|
+
*/
|
|
41
|
+
export function getAuthSecret() {
|
|
42
|
+
const secret = process.env.MCP_AUTH_SECRET?.trim() || process.env.JWT_SECRET?.trim();
|
|
43
|
+
return secret ? secret : undefined;
|
|
44
|
+
}
|
|
45
|
+
/** Constant-time buffer comparison that tolerates length mismatch. */
|
|
46
|
+
function constantTimeEquals(a, b) {
|
|
47
|
+
// timingSafeEqual throws on differing lengths. A wrong-length signature is
|
|
48
|
+
// unconditionally invalid, so returning early leaks nothing an attacker
|
|
49
|
+
// cannot already compute (HS256 signatures are always 32 bytes).
|
|
50
|
+
if (a.length !== b.length)
|
|
51
|
+
return false;
|
|
52
|
+
return timingSafeEqual(a, b);
|
|
53
|
+
}
|
|
54
|
+
function decodeSegment(segment) {
|
|
55
|
+
const json = Buffer.from(segment, "base64url").toString("utf-8");
|
|
56
|
+
return JSON.parse(json);
|
|
57
|
+
}
|
|
58
|
+
function isPlainObject(value) {
|
|
59
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
60
|
+
}
|
|
61
|
+
function isNonEmptyString(value) {
|
|
62
|
+
return typeof value === "string" && value.length > 0;
|
|
63
|
+
}
|
|
64
|
+
/** Reject anything that is not a finite number (NaN, Infinity, strings, null). */
|
|
65
|
+
function isFiniteNumber(value) {
|
|
66
|
+
return typeof value === "number" && Number.isFinite(value);
|
|
67
|
+
}
|
|
68
|
+
function reject(reason) {
|
|
69
|
+
// console.warn writes to stderr, which is the only stream an MCP stdio
|
|
70
|
+
// server may write diagnostics to. Never log the token itself.
|
|
71
|
+
console.warn(`[4DA MCP Auth] Token rejected: ${reason}`);
|
|
72
|
+
return null;
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* Verify a JWT's signature and claims. Returns the claims only when the
|
|
76
|
+
* signature checks out against the configured secret AND the claims are valid.
|
|
14
77
|
*
|
|
15
|
-
*
|
|
16
|
-
*
|
|
17
|
-
* For launch, we validate structure + expiry. Post-launch, add signature verification.
|
|
78
|
+
* @param token The raw JWT (no "Bearer " prefix).
|
|
79
|
+
* @param nowMs Current time in epoch milliseconds (injectable for tests).
|
|
18
80
|
*/
|
|
19
|
-
export function
|
|
20
|
-
const
|
|
21
|
-
if (!
|
|
22
|
-
|
|
81
|
+
export function verifyToken(token, nowMs = Date.now()) {
|
|
82
|
+
const secret = getAuthSecret();
|
|
83
|
+
if (!secret) {
|
|
84
|
+
// Fail closed. Without a secret there is nothing to verify against, so no
|
|
85
|
+
// token can be trusted — including one that is perfectly well-formed.
|
|
86
|
+
return reject("no shared secret configured (set MCP_AUTH_SECRET). Refusing to trust unverifiable tokens");
|
|
23
87
|
}
|
|
24
|
-
const
|
|
25
|
-
if (
|
|
26
|
-
return
|
|
88
|
+
const parts = token.split(".");
|
|
89
|
+
if (parts.length !== 3 || parts.some((p) => p.length === 0)) {
|
|
90
|
+
return reject("malformed token (expected three non-empty segments)");
|
|
91
|
+
}
|
|
92
|
+
const [encodedHeader, encodedPayload, encodedSignature] = parts;
|
|
93
|
+
// --- 1. Header: pin the algorithm BEFORE doing any crypto ---------------
|
|
94
|
+
let header;
|
|
27
95
|
try {
|
|
28
|
-
|
|
29
|
-
const parts = token.split(".");
|
|
30
|
-
if (parts.length !== 3)
|
|
31
|
-
return null;
|
|
32
|
-
// Decode payload (middle part)
|
|
33
|
-
const payload = JSON.parse(Buffer.from(parts[1], "base64url").toString("utf-8"));
|
|
34
|
-
// Validate required fields
|
|
35
|
-
if (!payload.team_id || !payload.client_id || !payload.role) {
|
|
36
|
-
return null;
|
|
37
|
-
}
|
|
38
|
-
// Check expiry
|
|
39
|
-
if (payload.exp && payload.exp < Math.floor(Date.now() / 1000)) {
|
|
40
|
-
console.warn(`[4DA MCP Auth] Token expired for team ${payload.team_id}`);
|
|
41
|
-
return null;
|
|
42
|
-
}
|
|
43
|
-
// Validate role is known
|
|
44
|
-
if (!["admin", "member", "viewer"].includes(payload.role)) {
|
|
45
|
-
return null;
|
|
46
|
-
}
|
|
47
|
-
return {
|
|
48
|
-
team_id: payload.team_id,
|
|
49
|
-
client_id: payload.client_id,
|
|
50
|
-
role: payload.role,
|
|
51
|
-
exp: payload.exp || 0,
|
|
52
|
-
};
|
|
96
|
+
header = decodeSegment(encodedHeader);
|
|
53
97
|
}
|
|
54
98
|
catch {
|
|
55
|
-
|
|
56
|
-
return null;
|
|
99
|
+
return reject("undecodable header segment");
|
|
57
100
|
}
|
|
101
|
+
if (!isPlainObject(header))
|
|
102
|
+
return reject("header is not a JSON object");
|
|
103
|
+
if (header.alg !== ACCEPTED_ALG) {
|
|
104
|
+
return reject(`unsupported alg '${String(header.alg)}' (only ${ACCEPTED_ALG} is accepted)`);
|
|
105
|
+
}
|
|
106
|
+
if (header.typ !== undefined && header.typ !== "JWT") {
|
|
107
|
+
return reject(`unsupported typ '${String(header.typ)}'`);
|
|
108
|
+
}
|
|
109
|
+
if (header.crit !== undefined) {
|
|
110
|
+
// `crit` marks header params a verifier MUST understand. We understand
|
|
111
|
+
// none of them, so the only spec-correct response is to refuse.
|
|
112
|
+
return reject("token declares critical header params this verifier does not implement");
|
|
113
|
+
}
|
|
114
|
+
// --- 2. Signature: constant-time HMAC-SHA256 over header.payload -------
|
|
115
|
+
const signingInput = `${encodedHeader}.${encodedPayload}`;
|
|
116
|
+
const expected = createHmac("sha256", secret).update(signingInput).digest();
|
|
117
|
+
const provided = Buffer.from(encodedSignature, "base64url");
|
|
118
|
+
if (!constantTimeEquals(expected, provided)) {
|
|
119
|
+
return reject("signature verification failed");
|
|
120
|
+
}
|
|
121
|
+
// --- 3. Claims: only now is the payload trustworthy --------------------
|
|
122
|
+
let payload;
|
|
123
|
+
try {
|
|
124
|
+
payload = decodeSegment(encodedPayload);
|
|
125
|
+
}
|
|
126
|
+
catch {
|
|
127
|
+
return reject("undecodable payload segment");
|
|
128
|
+
}
|
|
129
|
+
if (!isPlainObject(payload))
|
|
130
|
+
return reject("payload is not a JSON object");
|
|
131
|
+
const { team_id, client_id, role, exp, nbf } = payload;
|
|
132
|
+
if (!isNonEmptyString(team_id))
|
|
133
|
+
return reject("missing or invalid team_id");
|
|
134
|
+
if (!isNonEmptyString(client_id))
|
|
135
|
+
return reject("missing or invalid client_id");
|
|
136
|
+
if (!isNonEmptyString(role))
|
|
137
|
+
return reject("missing or invalid role");
|
|
138
|
+
if (!KNOWN_ROLES.includes(role)) {
|
|
139
|
+
return reject(`unknown role '${role}'`);
|
|
140
|
+
}
|
|
141
|
+
// `exp` is mandatory: a signed token with no expiry is a permanent
|
|
142
|
+
// credential, and the issuer always sets one.
|
|
143
|
+
if (!isFiniteNumber(exp))
|
|
144
|
+
return reject("missing or invalid exp claim");
|
|
145
|
+
const nowSeconds = Math.floor(nowMs / 1000);
|
|
146
|
+
if (exp + CLOCK_SKEW_SECONDS < nowSeconds) {
|
|
147
|
+
return reject(`token expired for team ${team_id}`);
|
|
148
|
+
}
|
|
149
|
+
if (nbf !== undefined) {
|
|
150
|
+
if (!isFiniteNumber(nbf))
|
|
151
|
+
return reject("invalid nbf claim");
|
|
152
|
+
if (nbf - CLOCK_SKEW_SECONDS > nowSeconds)
|
|
153
|
+
return reject("token not yet valid (nbf)");
|
|
154
|
+
}
|
|
155
|
+
return { team_id, client_id, role: role, exp };
|
|
58
156
|
}
|
|
59
157
|
/**
|
|
60
|
-
*
|
|
61
|
-
*
|
|
158
|
+
* Extract and verify the Bearer token on an HTTP request.
|
|
159
|
+
*
|
|
160
|
+
* Returns the verified claims, or null when the request carries no token, a
|
|
161
|
+
* malformed token, a forged/tampered token, or an expired one.
|
|
62
162
|
*/
|
|
63
|
-
export function
|
|
64
|
-
|
|
163
|
+
export function extractAuthClaims(req) {
|
|
164
|
+
const auth = req.headers["authorization"];
|
|
165
|
+
if (typeof auth !== "string" || !auth.startsWith("Bearer ")) {
|
|
166
|
+
return null;
|
|
167
|
+
}
|
|
168
|
+
const token = auth.slice(7).trim();
|
|
169
|
+
if (!token)
|
|
170
|
+
return null;
|
|
171
|
+
return verifyToken(token);
|
|
65
172
|
}
|
|
66
173
|
/**
|
|
67
174
|
* Check if a role has permission for a specific operation.
|
|
68
175
|
* Viewers can read, members can read+write, admins can do everything.
|
|
176
|
+
*
|
|
177
|
+
* Enforced on the tool-dispatch path — see `assertToolPermission` in
|
|
178
|
+
* `auth-context.ts`, which maps each tool to an operation via its
|
|
179
|
+
* `readOnlyHint` annotation.
|
|
69
180
|
*/
|
|
70
181
|
export function hasPermission(role, operation) {
|
|
71
182
|
switch (operation) {
|
|
72
183
|
case "read":
|
|
73
|
-
return
|
|
184
|
+
return KNOWN_ROLES.includes(role);
|
|
74
185
|
case "write":
|
|
75
186
|
return role === "member" || role === "admin";
|
|
76
187
|
case "admin":
|
package/dist/db.d.ts
CHANGED
|
@@ -107,7 +107,7 @@ export declare class FourDADatabase {
|
|
|
107
107
|
* Get relevant content items scored by the Rust pipeline (preferred) or
|
|
108
108
|
* TypeScript fallback scoring when Rust scores are unavailable.
|
|
109
109
|
*/
|
|
110
|
-
getRelevantContent(minScore?: number, sourceType?: string, limit?: number, sinceHours?: number): RelevantItem[];
|
|
110
|
+
getRelevantContent(minScore?: number, sourceType?: string, limit?: number, sinceHours?: number, requireCurrentVersion?: boolean): RelevantItem[];
|
|
111
111
|
/**
|
|
112
112
|
* Read the live freshness state of the feed database. Answered from ground truth, not from any
|
|
113
113
|
* claim that a refresh ran — so DB-backed tools can tell the caller whether the curated feed is
|