@terreno/api 58.0.1 → 58.0.3

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/CHANGELOG.md CHANGED
@@ -20,6 +20,37 @@ Upgrade notes for consumer action live in [`mcp-server/src/docs/upgrades/`](mcp-
20
20
 
21
21
  Unreleased changes live in [`changelog/unreleased/`](changelog/unreleased/). Add one Markdown file per feature (see that directory's README) instead of editing this section.
22
22
 
23
+ ## [58.0.3] - 2026-11-11
24
+
25
+ Upgrade note: [`mcp-server/src/docs/upgrades/58.0.3.md`](mcp-server/src/docs/upgrades/58.0.3.md).
26
+
27
+ ### Added
28
+
29
+ - `fix-code-scanning-alerts` skill: clears every open CodeQL alert on one PR. Fixes close on the master rescan; reviewed false positives go in `.github/code-scanning/dismissals.json` and a workflow dismisses them after merge. CodeQL now also scans pull requests and ignores test files. See `docs/how-to/fix-code-scanning-alerts.md`.
30
+ - **@terreno/syncdb:** `registerTerrenoDevClientDispatch`, `registerTerrenoDevStorage`, and `registerTerrenoDevCommand` for `terreno-mcp-local` dev tooling.
31
+ - **@terreno/mcp-server:** `read_logs` sources `network` and `native`; `dispatch_client_action`, storage read/write, and dev command list/invoke; CDP network capture with header redaction.
32
+
33
+ ### Changed
34
+
35
+ - Package tests run as concurrent `bun test --shard` processes through `scripts/test-shards.ts` (half the cores by default, `TERRENO_TEST_SHARDS` to override), and `test:coverage` merges the shards' LCOV. CircleCI now pins Bun 1.4.4, the same version as the local toolchain.
36
+
37
+ ### Fixed
38
+
39
+ - `Avatar` no longer freezes release builds when its image fails to load. The image error handler passed the native error event to `console.warn`, and with Sentry enabled the app hung while turning that event into a breadcrumb. It now logs only the error message.
40
+ - Mongo filters built from request values reject non-string input with 400 instead of running it as a query operator: AI request explorer `model`, observability review `status`, review batch `promptName`, experiment `datasetId`, trace list filters, push-token `platform`, and `loadDocOr404` ids (404). Sync conflict reloads and tombstone lookups match `_id` with `$eq`.
41
+ - Nested-path helpers in `populate`, RBAC field views, and MCP `excludeFields` skip `__proto__`, `constructor`, and `prototype`, so a crafted path can no longer touch `Object.prototype`.
42
+ - Removed polynomial-time regexes from bearer-header parsing, trailing-slash trimming (syncdb, ui `ListDetailLayout`, jobs Cloud Tasks runner, admin route paths), prompt references, judge score ranges, AI JSON fence stripping, and the MCP import parser.
43
+ - Dataset schema validation stops at the first error (`allErrors` off) to bound work on untrusted input.
44
+ - `isTestUser` in `@terreno/ui` matches `nang.io` and `example.com` as the email domain or a subdomain, not as a substring, and always returns a boolean.
45
+ - MCP OAuth metadata responses set an explicit JSON content type.
46
+ - The example app's AI session id comes from `expo-crypto` `randomUUID` instead of `Math.random`.
47
+
48
+ ## [58.0.2] - 2026-11-09
49
+
50
+ ### Fixed
51
+
52
+ - Patch the remaining critical and high security advisories in Terreno's dependency tree. `@terreno/ui` now asks for `@react-navigation/native` `^7.5.1`, whose `@react-navigation/core` no longer pulls in the vulnerable `decode-uri-component` (#1693). The docs site moves to tinypool 2.2.0 (critical) and serialize-javascript 7.1.4 (#1690, #1691), Metro's stale nested copy no longer brings in image-size 1.x (#1694), and rulesync 43.8.0 drops its pinned zod 4.6.5 (#1695). Dependabot now opens one security PR per advisory instead of one grouped PR per package block (#1689). Expo tooling still carries zod 3.25.76, which has no fixed 3.x release.
53
+
23
54
  ## [58.0.1] - 2026-11-09
24
55
 
25
56
  ### Added
@@ -95,6 +95,11 @@ export declare const applyBetterAuthPasswordResetToJwt: (userModel: UserModel, b
95
95
  email?: string;
96
96
  id?: string;
97
97
  }, request: PasswordResetRequestLike | undefined, capturedPassword?: string) => Promise<void>;
98
+ /**
99
+ * The credential from an `Authorization: Bearer <token>` header, or undefined. Parsed with string
100
+ * operations rather than a regex so a long run of whitespace cannot cause polynomial backtracking.
101
+ */
102
+ export declare const extractBearerToken: (header: string | undefined) => string | undefined;
98
103
  /**
99
104
  * Creates Express middleware that extracts the Better Auth session
100
105
  * and populates req.user with the application User model.
@@ -9,7 +9,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
9
9
  return (mod && mod.__esModule) ? mod : { "default": mod };
10
10
  };
11
11
  Object.defineProperty(exports, "__esModule", { value: true });
12
- exports.hasBetterAuthSession = exports.getBetterAuthSession = exports.setupBetterAuthUserSync = exports.getMongoClientFromMongoose = exports.mountBetterAuthRoutes = exports.resolveBetterAuthAppUser = exports.createAppUserSyncPlugin = exports.syncBetterAuthUser = exports.VERIFY_EMAIL_TO_USE_ACCOUNT = exports.createBetterAuthSessionMiddleware = exports.applyBetterAuthPasswordResetToJwt = exports.readPasswordFromBetterAuthResetRequest = exports.currentBetterAuthEndpointBody = exports.verifyBetterAuthCredentialPassword = exports.applyJwtPasswordResetToBetterAuth = exports.createBetterAuth = exports.createBetterAuthEmailHooks = exports.betterAuthResetPasswordUrl = void 0;
12
+ exports.hasBetterAuthSession = exports.getBetterAuthSession = exports.setupBetterAuthUserSync = exports.getMongoClientFromMongoose = exports.mountBetterAuthRoutes = exports.resolveBetterAuthAppUser = exports.createAppUserSyncPlugin = exports.syncBetterAuthUser = exports.VERIFY_EMAIL_TO_USE_ACCOUNT = exports.createBetterAuthSessionMiddleware = exports.extractBearerToken = exports.applyBetterAuthPasswordResetToJwt = exports.readPasswordFromBetterAuthResetRequest = exports.currentBetterAuthEndpointBody = exports.verifyBetterAuthCredentialPassword = exports.applyJwtPasswordResetToBetterAuth = exports.createBetterAuth = exports.createBetterAuthEmailHooks = exports.betterAuthResetPasswordUrl = void 0;
13
13
  const better_auth_1 = require("better-auth");
14
14
  const mongodb_1 = require("better-auth/adapters/mongodb");
15
15
  const api_1 = require("better-auth/api");
@@ -501,12 +501,31 @@ const originOfReferer = (referer) => {
501
501
  // True when the request's own `Authorization: Bearer` token is the session Better Auth resolved,
502
502
  // rather than a cookie sent beside some other header. The bearer plugin accepts the raw token or
503
503
  // the signed `token.signature` form.
504
+ const BEARER_SCHEME = "bearer";
505
+ /**
506
+ * The credential from an `Authorization: Bearer <token>` header, or undefined. Parsed with string
507
+ * operations rather than a regex so a long run of whitespace cannot cause polynomial backtracking.
508
+ */
509
+ const extractBearerToken = (header) => {
510
+ if (!header || header.length <= BEARER_SCHEME.length) {
511
+ return undefined;
512
+ }
513
+ if (header.slice(0, BEARER_SCHEME.length).toLowerCase() !== BEARER_SCHEME) {
514
+ return undefined;
515
+ }
516
+ if (header.charAt(BEARER_SCHEME.length).trim() !== "") {
517
+ return undefined;
518
+ }
519
+ const token = header.slice(BEARER_SCHEME.length + 1).trim();
520
+ return token || undefined;
521
+ };
522
+ exports.extractBearerToken = extractBearerToken;
504
523
  const isBearerSession = (req, sessionToken) => {
505
- const match = /^Bearer\s+(.+)$/i.exec(headerValue(req.headers.authorization) ?? "");
506
- if (!match || !sessionToken) {
524
+ const token = (0, exports.extractBearerToken)(headerValue(req.headers.authorization));
525
+ if (!token || !sessionToken) {
507
526
  return false;
508
527
  }
509
- let bearer = match[1].trim();
528
+ let bearer = token;
510
529
  try {
511
530
  bearer = decodeURIComponent(bearer);
512
531
  }
package/dist/docLoader.js CHANGED
@@ -33,6 +33,10 @@ const documentNotFound = (modelName, id) => {
33
33
  * Matches permission middleware behavior including soft-delete metadata.
34
34
  */
35
35
  const loadDocOr404 = async (model, id, populatePaths) => {
36
+ // A non-string id (e.g. `{$ne: null}` from a JSON body) would become a query operator.
37
+ if (typeof id !== "string") {
38
+ throw documentNotFound(model.modelName, String(id));
39
+ }
36
40
  const builtQuery = model.findById(id);
37
41
  const populatedQuery = (0, api_1.addPopulateToQuery)(builtQuery, populatePaths);
38
42
  let data;
@@ -228,7 +228,10 @@ const setupGitHubAuth = (_app, userModel, githubOptions) => {
228
228
  // The link target comes only from state issued by /auth/github/link, never from an
229
229
  // ambient session or token on the callback request.
230
230
  const linkUserId = verifiedLinkTargets.get(req);
231
- const linkUser = linkUserId ? await userModel.findById(linkUserId) : null;
231
+ // Only a string id reaches the query, so a crafted state value cannot become an operator.
232
+ const linkUser = typeof linkUserId === "string" && linkUserId
233
+ ? await userModel.findById(linkUserId)
234
+ : null;
232
235
  if (linkUserId && !linkUser) {
233
236
  return done(new errors_1.APIError({ status: 404, title: "User not found" }));
234
237
  }
@@ -54,6 +54,10 @@ const deleteAtPath = (obj, segments) => {
54
54
  return;
55
55
  }
56
56
  const [head, ...rest] = segments;
57
+ // Never walk into or delete from a prototype through a configured path.
58
+ if (head === "__proto__" || head === "constructor" || head === "prototype") {
59
+ return;
60
+ }
57
61
  if (rest.length === 0) {
58
62
  delete obj[head];
59
63
  return;
@@ -91,7 +91,9 @@ exports.resolveMcpOAuthOption = resolveMcpOAuthOption;
91
91
  * get exactly the RFC-defined members.
92
92
  */
93
93
  const sendProtocolJson = (res, status, body) => {
94
- res.status(status).type("application/json").send(JSON.stringify(body));
94
+ // An explicit JSON content type keeps reflected request values from rendering as HTML.
95
+ res.setHeader("Content-Type", "application/json; charset=utf-8");
96
+ res.status(status).send(JSON.stringify(body));
95
97
  };
96
98
  exports.sendProtocolJson = sendProtocolJson;
97
99
  /** RFC 9728 protected-resource metadata. */
package/dist/populate.js CHANGED
@@ -217,6 +217,10 @@ const unpopulate = (doc, path) => {
217
217
  // Recursive because we need to support nested paths.
218
218
  const recursiveUnpopulate = (current, parts) => {
219
219
  const part = parts[0];
220
+ // Never read from or assign to a prototype through a configured path.
221
+ if (part === "__proto__" || part === "constructor" || part === "prototype") {
222
+ return asRecord(doc);
223
+ }
220
224
  const value = current[part];
221
225
  // If the path doesn't exist, return the original doc
222
226
  if (!value) {
@@ -13,6 +13,9 @@ const getNestedValue = (doc, path) => {
13
13
  if (!isPlainObject(current)) {
14
14
  return undefined;
15
15
  }
16
+ if (part === "__proto__" || part === "constructor" || part === "prototype") {
17
+ return undefined;
18
+ }
16
19
  current = current[part];
17
20
  }
18
21
  return current;
@@ -22,13 +25,21 @@ const setNestedValue = (doc, path, value) => {
22
25
  let current = doc;
23
26
  for (let index = 0; index < parts.length - 1; index++) {
24
27
  const part = parts[index];
28
+ // A mask path must never reach a prototype.
29
+ if (part === "__proto__" || part === "constructor" || part === "prototype") {
30
+ return;
31
+ }
25
32
  const next = current[part];
26
33
  if (!isPlainObject(next)) {
27
34
  current[part] = {};
28
35
  }
29
36
  current = current[part];
30
37
  }
31
- current[parts[parts.length - 1]] = value;
38
+ const lastPart = parts[parts.length - 1];
39
+ if (lastPart === "__proto__" || lastPart === "constructor" || lastPart === "prototype") {
40
+ return;
41
+ }
42
+ current[lastPart] = value;
32
43
  };
33
44
  const pickPaths = (doc, paths) => {
34
45
  const result = {};
@@ -42,13 +53,17 @@ const pickPaths = (doc, paths) => {
42
53
  };
43
54
  const omitPath = (doc, omitPathName) => {
44
55
  const parts = omitPathName.split(".");
56
+ const lastPart = parts[parts.length - 1];
57
+ if (lastPart === "__proto__" || lastPart === "constructor" || lastPart === "prototype") {
58
+ return;
59
+ }
45
60
  if (parts.length === 1) {
46
- delete doc[parts[0]];
61
+ delete doc[lastPart];
47
62
  return;
48
63
  }
49
64
  const parent = getNestedValue(doc, parts.slice(0, -1).join("."));
50
65
  if (isPlainObject(parent)) {
51
- delete parent[parts[parts.length - 1]];
66
+ delete parent[lastPart];
52
67
  }
53
68
  };
54
69
  const applyReadMask = (value, mask) => {
@@ -87,7 +87,10 @@ exports.isVersionError = isVersionError;
87
87
  */
88
88
  const reloadDocForConflict = async (model, id) => {
89
89
  try {
90
- const found = await model.find({ _id: id, deleted: { $in: [true, false] } }).limit(1);
90
+ // $eq pins the id to an equality match so a client-supplied object cannot add operators.
91
+ const found = await model
92
+ .find({ _id: { $eq: id }, deleted: { $in: [true, false] } })
93
+ .limit(1);
91
94
  return found[0];
92
95
  }
93
96
  catch {
@@ -567,7 +570,9 @@ const executeDelete = async ({ model, options, user, id, existingDoc, req, skipP
567
570
  error.meta?.deleted === "true";
568
571
  if (alreadyDeleted) {
569
572
  // Hydrate the tombstone bypassing the isDeletedPlugin find filter.
570
- const tombstone = await model.find({ _id: id, deleted: { $in: [true, false] } }).limit(1);
573
+ const tombstone = await model
574
+ .find({ _id: { $eq: id }, deleted: { $in: [true, false] } })
575
+ .limit(1);
571
576
  const resolved = tombstone[0];
572
577
  if (!resolved) {
573
578
  throw error;
package/package.json CHANGED
@@ -13,7 +13,7 @@
13
13
  "@modelcontextprotocol/node": "^2.1.2",
14
14
  "@modelcontextprotocol/server": "^2.0.0",
15
15
  "@sentry/bun": "^11.0.0",
16
- "@terreno/test": "58.0.1",
16
+ "@terreno/test": "58.0.3",
17
17
  "@thream/socketio-jwt": "^3.1.4",
18
18
  "@types/qs": "^6.14.0",
19
19
  "ajv": "8.20.0",
@@ -51,7 +51,7 @@
51
51
  "devDependencies": {
52
52
  "@biomejs/biome": "2.5.13",
53
53
  "@modelcontextprotocol/client": "^2.0.0",
54
- "@terreno/syncdb": "58.0.1",
54
+ "@terreno/syncdb": "58.0.3",
55
55
  "@types/bun": "^1.4.0",
56
56
  "@types/cors": "^2.8.17",
57
57
  "@types/express": "^5.0.6",
@@ -141,16 +141,16 @@
141
141
  "lint:unsafefix": "biome check --fix --unsafe ./src",
142
142
  "load": "bun src/sync/loadHarness.ts",
143
143
  "smoke": "bun e2e/smoke.ts",
144
- "test": "bun test --update-snapshots",
145
- "test:agent": "AGENT=1 bun test --only-failures",
144
+ "test": "bun ../scripts/test-shards.ts -- --update-snapshots",
145
+ "test:agent": "AGENT=1 bun ../scripts/test-shards.ts -- --only-failures",
146
146
  "test:cache:clean": "bun ./src/tests/mongoTestSetup.ts clean",
147
147
  "test:cache:setup": "bun ./src/tests/mongoTestSetup.ts setup",
148
148
  "test:cache:status": "bun ./src/tests/mongoTestSetup.ts status",
149
- "test:ci": "bun test",
149
+ "test:ci": "bun ../scripts/test-shards.ts",
150
150
  "test:coverage": "bun run ../scripts/check-coverage.ts",
151
151
  "typecheck": "tsc -p tsconfig.typecheck.json",
152
152
  "updateSnapshot": "bun test --update-snapshots"
153
153
  },
154
154
  "types": "dist/index.d.ts",
155
- "version": "58.0.1"
155
+ "version": "58.0.3"
156
156
  }
@@ -12,6 +12,7 @@ import {apiErrorMiddleware} from "../errors";
12
12
  import {type AuthenticatableSocket, createBetterAuthValidator} from "../realtime/socketAuth";
13
13
  import {type RequestCredential, runWithRequestContext} from "../requestContext";
14
14
  import {
15
+ ACCOUNT_SECURITY_HOOK_TIMEOUT_MS,
15
16
  access,
16
17
  betterAuthCollection,
17
18
  betterAuthIdFor,
@@ -126,11 +127,11 @@ const tokenFromUrl = (url: string): string => new URL(url).searchParams.get("tok
126
127
  describe("access recovery actions", () => {
127
128
  beforeAll(async () => {
128
129
  await access.roles.seedDefaults();
129
- });
130
+ }, ACCOUNT_SECURITY_HOOK_TIMEOUT_MS);
130
131
 
131
132
  beforeEach(async () => {
132
133
  await resetAccountSecurityState();
133
- });
134
+ }, ACCOUNT_SECURITY_HOOK_TIMEOUT_MS);
134
135
 
135
136
  afterEach(() => {
136
137
  resetAuditRecorderForTests();
@@ -8,6 +8,7 @@ import {resetAuditRecorderForTests} from "../audit/record";
8
8
  import type {BetterAuthApp} from "../betterAuthApp";
9
9
  import {logger} from "../logger";
10
10
  import {
11
+ ACCOUNT_SECURITY_HOOK_TIMEOUT_MS,
11
12
  access,
12
13
  betterAuthCollection,
13
14
  betterAuthIdFor,
@@ -189,11 +190,11 @@ const interleaveNextDelete = async (
189
190
  describe("credential recovery actions", () => {
190
191
  beforeAll(async () => {
191
192
  await access.roles.seedDefaults();
192
- });
193
+ }, ACCOUNT_SECURITY_HOOK_TIMEOUT_MS);
193
194
 
194
195
  beforeEach(async () => {
195
196
  await resetAccountSecurityState();
196
- });
197
+ }, ACCOUNT_SECURITY_HOOK_TIMEOUT_MS);
197
198
 
198
199
  afterEach(() => {
199
200
  resetAuditRecorderForTests();
@@ -8,6 +8,7 @@ import type {BetterAuthConfig} from "../betterAuth";
8
8
  import type {BetterAuthApp} from "../betterAuthApp";
9
9
  import {logger} from "../logger";
10
10
  import {
11
+ ACCOUNT_SECURITY_HOOK_TIMEOUT_MS,
11
12
  access,
12
13
  betterAuthCollection,
13
14
  betterAuthIdFor,
@@ -193,11 +194,11 @@ const registerPasskey = async (app: express.Application, token: string): Promise
193
194
  describe("security notification emails", () => {
194
195
  beforeAll(async () => {
195
196
  await access.roles.seedDefaults();
196
- });
197
+ }, ACCOUNT_SECURITY_HOOK_TIMEOUT_MS);
197
198
 
198
199
  beforeEach(async () => {
199
200
  await resetAccountSecurityState();
200
- });
201
+ }, ACCOUNT_SECURITY_HOOK_TIMEOUT_MS);
201
202
 
202
203
  afterEach(async () => {
203
204
  await flushSecurityNotificationsForTests();
@@ -16,6 +16,7 @@ import {
16
16
  createBetterAuth,
17
17
  createBetterAuthEmailHooks,
18
18
  createBetterAuthSessionMiddleware,
19
+ extractBearerToken,
19
20
  getBetterAuthSession,
20
21
  getMongoClientFromMongoose,
21
22
  hasBetterAuthSession,
@@ -1588,3 +1589,29 @@ describe("setupBetterAuthUserSync", () => {
1588
1589
  expect(() => setupBetterAuthUserSync(auth, asUserModel(TestUser))).not.toThrow();
1589
1590
  });
1590
1591
  });
1592
+
1593
+ describe("extractBearerToken", () => {
1594
+ it("reads the token after the case-insensitive Bearer scheme", () => {
1595
+ expect(extractBearerToken("Bearer abc.def")).toBe("abc.def");
1596
+ expect(extractBearerToken("bearer abc")).toBe("abc");
1597
+ expect(extractBearerToken("BEARER\tabc")).toBe("abc");
1598
+ expect(extractBearerToken("Bearer abc ")).toBe("abc");
1599
+ });
1600
+
1601
+ it("returns undefined for missing, empty, or non-Bearer headers", () => {
1602
+ expect(extractBearerToken(undefined)).toBeUndefined();
1603
+ expect(extractBearerToken("")).toBeUndefined();
1604
+ expect(extractBearerToken("Bearer")).toBeUndefined();
1605
+ expect(extractBearerToken("Bearer ")).toBeUndefined();
1606
+ expect(extractBearerToken("Bearerabc")).toBeUndefined();
1607
+ expect(extractBearerToken("Basic abc")).toBeUndefined();
1608
+ });
1609
+
1610
+ it("parses a long run of whitespace in linear time", () => {
1611
+ const header = `bearer ${" ".repeat(200_000)}x`;
1612
+ const start = performance.now();
1613
+ expect(extractBearerToken(header)).toBe("x");
1614
+ expect(extractBearerToken(`bearer ${" ".repeat(200_000)}`)).toBeUndefined();
1615
+ expect(performance.now() - start).toBeLessThan(500);
1616
+ });
1617
+ });
@@ -688,12 +688,32 @@ const originOfReferer = (referer: string | undefined): string | undefined => {
688
688
  // True when the request's own `Authorization: Bearer` token is the session Better Auth resolved,
689
689
  // rather than a cookie sent beside some other header. The bearer plugin accepts the raw token or
690
690
  // the signed `token.signature` form.
691
+ const BEARER_SCHEME = "bearer";
692
+
693
+ /**
694
+ * The credential from an `Authorization: Bearer <token>` header, or undefined. Parsed with string
695
+ * operations rather than a regex so a long run of whitespace cannot cause polynomial backtracking.
696
+ */
697
+ export const extractBearerToken = (header: string | undefined): string | undefined => {
698
+ if (!header || header.length <= BEARER_SCHEME.length) {
699
+ return undefined;
700
+ }
701
+ if (header.slice(0, BEARER_SCHEME.length).toLowerCase() !== BEARER_SCHEME) {
702
+ return undefined;
703
+ }
704
+ if (header.charAt(BEARER_SCHEME.length).trim() !== "") {
705
+ return undefined;
706
+ }
707
+ const token = header.slice(BEARER_SCHEME.length + 1).trim();
708
+ return token || undefined;
709
+ };
710
+
691
711
  const isBearerSession = (req: Request, sessionToken: string): boolean => {
692
- const match = /^Bearer\s+(.+)$/i.exec(headerValue(req.headers.authorization) ?? "");
693
- if (!match || !sessionToken) {
712
+ const token = extractBearerToken(headerValue(req.headers.authorization));
713
+ if (!token || !sessionToken) {
694
714
  return false;
695
715
  }
696
- let bearer = match[1].trim();
716
+ let bearer = token;
697
717
  try {
698
718
  bearer = decodeURIComponent(bearer);
699
719
  } catch {
@@ -100,4 +100,17 @@ describe("loadDocOr404", () => {
100
100
  expect(apiError.meta).toEqual({});
101
101
  }
102
102
  });
103
+
104
+ it("rejects a non-string id before it can reach the query as an operator", async () => {
105
+ const findById = mock(() => ({exec: mock(async () => ({_id: "leaked"}))}));
106
+ const model = {
107
+ collection: {findOne: mock(async () => null)},
108
+ findById,
109
+ modelName: "MockModel",
110
+ } as unknown as Model<unknown>;
111
+
112
+ const injected = {$ne: null} as unknown as string;
113
+ await expect(loadDocOr404(model, injected)).rejects.toMatchObject({status: 404});
114
+ expect(findById).not.toHaveBeenCalled();
115
+ });
103
116
  });
package/src/docLoader.ts CHANGED
@@ -37,6 +37,10 @@ export const loadDocOr404 = async <T>(
37
37
  id: string,
38
38
  populatePaths?: PopulatePath[]
39
39
  ): Promise<T> => {
40
+ // A non-string id (e.g. `{$ne: null}` from a JSON body) would become a query operator.
41
+ if (typeof id !== "string") {
42
+ throw documentNotFound(model.modelName, String(id));
43
+ }
40
44
  const builtQuery = model.findById(id);
41
45
  const populatedQuery = addPopulateToQuery(
42
46
  builtQuery as unknown as Parameters<typeof addPopulateToQuery>[0],
@@ -1,4 +1,5 @@
1
1
  import {afterEach, beforeEach, describe, expect, it, setSystemTime} from "bun:test";
2
+ import {createHmac} from "node:crypto";
2
3
  import type express from "express";
3
4
  import mongoose, {type Model, model, Schema} from "mongoose";
4
5
  import passport from "passport";
@@ -1137,6 +1138,44 @@ describe("GitHub OAuth state binding", () => {
1137
1138
  expect(res.headers.location).toContain("/auth/github/failure");
1138
1139
  });
1139
1140
 
1141
+ describe("signed state link targets", () => {
1142
+ const signedStateCookie = (state: string | null, linkUserId: unknown): string => {
1143
+ const payload = Buffer.from(
1144
+ JSON.stringify({expiresAt: Date.now() + 60_000, linkUserId, nonce: state})
1145
+ ).toString("base64url");
1146
+ const signature = createHmac("sha256", process.env.SESSION_SECRET ?? "")
1147
+ .update(payload)
1148
+ .digest("base64url");
1149
+ return `terreno_github_oauth_state=${payload}.${signature}`;
1150
+ };
1151
+
1152
+ it("a correctly signed string link target links that user", async () => {
1153
+ const user = await GitHubTestUserModel.create({email: "signed-link@example.test"});
1154
+ const start = await supertest(app).get("/auth/github").expect(302);
1155
+ const state = stateFromLocation(start.headers.location);
1156
+
1157
+ const res = await supertest(app)
1158
+ .get(`/auth/github/callback?code=gh-signed-1&state=${state}`)
1159
+ .set("cookie", signedStateCookie(state, String(user._id)))
1160
+ .expect(200);
1161
+ expect(String(res.body.data.userId)).toBe(String(user._id));
1162
+ });
1163
+
1164
+ it("a signed state whose link target is not a string is rejected", async () => {
1165
+ const victim = await GitHubTestUserModel.create({email: "victim6@example.test"});
1166
+ const start = await supertest(app).get("/auth/github").expect(302);
1167
+ const state = stateFromLocation(start.headers.location);
1168
+
1169
+ const res = await supertest(app)
1170
+ .get(`/auth/github/callback?code=gh-operator-1&state=${state}`)
1171
+ .set("cookie", signedStateCookie(state, {$ne: null}))
1172
+ .expect(302);
1173
+ expect(res.headers.location).toContain("/auth/github/failure");
1174
+ const victimRow = await GitHubTestUserModel.findById(victim._id);
1175
+ expect(victimRow?.githubId).toBeUndefined();
1176
+ });
1177
+ });
1178
+
1140
1179
  it("a tampered state cookie is rejected", async () => {
1141
1180
  const victim = await GitHubTestUserModel.create({email: "victim5@example.test"});
1142
1181
  const browser = supertest.agent(app);
package/src/githubAuth.ts CHANGED
@@ -322,7 +322,11 @@ export const setupGitHubAuth = (
322
322
  // The link target comes only from state issued by /auth/github/link, never from an
323
323
  // ambient session or token on the callback request.
324
324
  const linkUserId = verifiedLinkTargets.get(req);
325
- const linkUser = linkUserId ? await userModel.findById(linkUserId) : null;
325
+ // Only a string id reaches the query, so a crafted state value cannot become an operator.
326
+ const linkUser =
327
+ typeof linkUserId === "string" && linkUserId
328
+ ? await userModel.findById(linkUserId)
329
+ : null;
326
330
  if (linkUserId && !linkUser) {
327
331
  return done(new APIError({status: 404, title: "User not found"}));
328
332
  }
@@ -1,4 +1,4 @@
1
- import {beforeEach, describe, it, spyOn} from "bun:test";
1
+ import {afterEach, beforeEach, describe, it, spyOn} from "bun:test";
2
2
  import {assert} from "chai";
3
3
  import mongoose, {Schema} from "mongoose";
4
4
 
@@ -146,6 +146,29 @@ describe("MCP handlers", () => {
146
146
  });
147
147
  });
148
148
 
149
+ describe("excludeFields prototype safety", () => {
150
+ afterEach(() => {
151
+ delete (Object.prototype as Record<string, unknown>).__terrenoProbe;
152
+ });
153
+
154
+ it("does not delete from Object.prototype through a __proto__ exclude path", async () => {
155
+ Object.defineProperty(Object.prototype, "__terrenoProbe", {
156
+ configurable: true,
157
+ enumerable: false,
158
+ value: "kept",
159
+ writable: true,
160
+ });
161
+ const doc = await NoteModel.create({ownerId: owner._id, title: "Mine"});
162
+ const redacted: MCPRegistryEntry = {
163
+ ...entry,
164
+ config: {...entry.config, excludeFields: ["__proto__.__terrenoProbe"]},
165
+ };
166
+ const result = await handleRead(redacted, {id: doc._id.toString()}, asUser(owner));
167
+ assert.notEqual(result.isError, true);
168
+ assert.equal(({} as Record<string, unknown>).__terrenoProbe, "kept");
169
+ });
170
+ });
171
+
149
172
  describe("populate resolution", () => {
150
173
  it("treats a populate string of only separators as no populate request", async () => {
151
174
  await NoteModel.create({ownerId: owner._id, title: "One"});
@@ -60,6 +60,10 @@ const deleteAtPath = (obj: unknown, segments: string[]): void => {
60
60
  return;
61
61
  }
62
62
  const [head, ...rest] = segments;
63
+ // Never walk into or delete from a prototype through a configured path.
64
+ if (head === "__proto__" || head === "constructor" || head === "prototype") {
65
+ return;
66
+ }
63
67
  if (rest.length === 0) {
64
68
  delete obj[head];
65
69
  return;
@@ -0,0 +1,19 @@
1
+ import {describe, expect, it} from "bun:test";
2
+ import express from "express";
3
+ import supertest from "supertest";
4
+
5
+ import {sendProtocolJson} from "./oauthMetadata";
6
+
7
+ describe("sendProtocolJson", () => {
8
+ it("serializes reflected input as JSON with a JSON content type", async () => {
9
+ const app = express();
10
+ app.get("/echo", (req, res) => {
11
+ sendProtocolJson(res, 400, {error: "invalid_request", error_description: req.query.value});
12
+ });
13
+
14
+ const payload = "<script>alert(1)</script>";
15
+ const res = await supertest(app).get("/echo").query({value: payload}).expect(400);
16
+ expect(res.headers["content-type"]).toBe("application/json; charset=utf-8");
17
+ expect(res.text).toBe(JSON.stringify({error: "invalid_request", error_description: payload}));
18
+ });
19
+ });
@@ -181,7 +181,9 @@ export const resolveMcpOAuthOption = (
181
181
  * get exactly the RFC-defined members.
182
182
  */
183
183
  export const sendProtocolJson = (res: Response, status: number, body: unknown): void => {
184
- res.status(status).type("application/json").send(JSON.stringify(body));
184
+ // An explicit JSON content type keeps reflected request values from rendering as HTML.
185
+ res.setHeader("Content-Type", "application/json; charset=utf-8");
186
+ res.status(status).send(JSON.stringify(body));
185
187
  };
186
188
 
187
189
  /** RFC 9728 protected-resource metadata. */
@@ -1,4 +1,4 @@
1
- import {beforeEach, describe, expect, it} from "bun:test";
1
+ import {afterEach, beforeEach, describe, expect, it} from "bun:test";
2
2
  import {assert} from "chai";
3
3
  import mongoose, {type Document, type HydratedDocument, Schema} from "mongoose";
4
4
 
@@ -63,6 +63,25 @@ describe("populate functions", () => {
63
63
  expect(populated.likesIds[1].userId.toString()).toBe(notAdmin.id);
64
64
  expect(populated.likesIds[1].userId.name).toBeUndefined();
65
65
  });
66
+
67
+ describe("unpopulate prototype safety", () => {
68
+ afterEach(() => {
69
+ delete (Object.prototype as Record<string, unknown>).__terrenoProbe;
70
+ });
71
+
72
+ it("does not assign onto Object.prototype through a __proto__ path", () => {
73
+ Object.defineProperty(Object.prototype, "__terrenoProbe", {
74
+ configurable: true,
75
+ enumerable: false,
76
+ value: {_id: "probe-id"},
77
+ writable: true,
78
+ });
79
+ const doc = {name: "plain"} as unknown as Document<unknown>;
80
+ expect(unpopulate(doc, "__proto__.__terrenoProbe")).toBe(doc);
81
+ expect(unpopulate(doc, "constructor.prototype.__terrenoProbe")).toBe(doc);
82
+ expect(({} as Record<string, unknown>).__terrenoProbe).toEqual({_id: "probe-id"});
83
+ });
84
+ });
66
85
  });
67
86
 
68
87
  describe("unpopulate edge cases", () => {
package/src/populate.ts CHANGED
@@ -278,6 +278,10 @@ export const unpopulate = <T>(doc: Document<T>, path: string): Document<T> => {
278
278
  // Recursive because we need to support nested paths.
279
279
  const recursiveUnpopulate = (current: NestedRecord, parts: string[]): NestedRecord => {
280
280
  const part = parts[0];
281
+ // Never read from or assign to a prototype through a configured path.
282
+ if (part === "__proto__" || part === "constructor" || part === "prototype") {
283
+ return asRecord(doc);
284
+ }
281
285
  const value = current[part];
282
286
 
283
287
  // If the path doesn't exist, return the original doc
@@ -1,4 +1,4 @@
1
- import {describe, expect, it} from "bun:test";
1
+ import {afterEach, describe, expect, it} from "bun:test";
2
2
  import {assert} from "chai";
3
3
 
4
4
  import {applyReadMask, getDisallowedWriteKeys} from "./fieldViews";
@@ -125,4 +125,33 @@ describe("fieldViews", () => {
125
125
  it("getDisallowedWriteKeys returns nothing for an empty body", () => {
126
126
  assert.deepEqual(getDisallowedWriteKeys({}, {omit: [], read: "*", write: ["name"]}), []);
127
127
  });
128
+
129
+ describe("prototype pollution", () => {
130
+ afterEach(() => {
131
+ delete (Object.prototype as Record<string, unknown>).polluted;
132
+ delete (Object.prototype as Record<string, unknown>).__terrenoProbe;
133
+ });
134
+
135
+ it("applyReadMask does not copy a __proto__ read path onto Object.prototype", () => {
136
+ const doc = JSON.parse('{"__proto__": {"polluted": "yes"}, "name": "Todo"}');
137
+ const masked = applyReadMask(doc, {
138
+ omit: [],
139
+ read: ["name", "__proto__.polluted", "constructor.prototype.polluted"],
140
+ write: [],
141
+ });
142
+ expect(masked).toEqual({name: "Todo"});
143
+ expect(({} as Record<string, unknown>).polluted).toBeUndefined();
144
+ });
145
+
146
+ it("applyReadMask does not delete from Object.prototype through an omit path", () => {
147
+ Object.defineProperty(Object.prototype, "__terrenoProbe", {
148
+ configurable: true,
149
+ enumerable: false,
150
+ value: "kept",
151
+ writable: true,
152
+ });
153
+ applyReadMask({name: "Todo"}, {omit: ["__proto__.__terrenoProbe"], read: "*", write: []});
154
+ expect(({} as Record<string, unknown>).__terrenoProbe).toBe("kept");
155
+ });
156
+ });
128
157
  });
@@ -12,6 +12,9 @@ const getNestedValue = (doc: Record<string, unknown>, path: string): unknown =>
12
12
  if (!isPlainObject(current)) {
13
13
  return undefined;
14
14
  }
15
+ if (part === "__proto__" || part === "constructor" || part === "prototype") {
16
+ return undefined;
17
+ }
15
18
  current = current[part];
16
19
  }
17
20
  return current;
@@ -22,13 +25,21 @@ const setNestedValue = (doc: Record<string, unknown>, path: string, value: unkno
22
25
  let current: Record<string, unknown> = doc;
23
26
  for (let index = 0; index < parts.length - 1; index++) {
24
27
  const part = parts[index];
28
+ // A mask path must never reach a prototype.
29
+ if (part === "__proto__" || part === "constructor" || part === "prototype") {
30
+ return;
31
+ }
25
32
  const next = current[part];
26
33
  if (!isPlainObject(next)) {
27
34
  current[part] = {};
28
35
  }
29
36
  current = current[part] as Record<string, unknown>;
30
37
  }
31
- current[parts[parts.length - 1]] = value;
38
+ const lastPart = parts[parts.length - 1];
39
+ if (lastPart === "__proto__" || lastPart === "constructor" || lastPart === "prototype") {
40
+ return;
41
+ }
42
+ current[lastPart] = value;
32
43
  };
33
44
 
34
45
  const pickPaths = (doc: Record<string, unknown>, paths: string[]): Record<string, unknown> => {
@@ -44,13 +55,17 @@ const pickPaths = (doc: Record<string, unknown>, paths: string[]): Record<string
44
55
 
45
56
  const omitPath = (doc: Record<string, unknown>, omitPathName: string): void => {
46
57
  const parts = omitPathName.split(".");
58
+ const lastPart = parts[parts.length - 1];
59
+ if (lastPart === "__proto__" || lastPart === "constructor" || lastPart === "prototype") {
60
+ return;
61
+ }
47
62
  if (parts.length === 1) {
48
- delete doc[parts[0]];
63
+ delete doc[lastPart];
49
64
  return;
50
65
  }
51
66
  const parent = getNestedValue(doc, parts.slice(0, -1).join("."));
52
67
  if (isPlainObject(parent)) {
53
- delete parent[parts[parts.length - 1]];
68
+ delete parent[lastPart];
54
69
  }
55
70
  };
56
71
 
@@ -837,6 +837,20 @@ describe("executeDelete", () => {
837
837
  assert.isTrue(doc.deleted);
838
838
  });
839
839
 
840
+ it("rejects an operator object as an id without deleting anything", async () => {
841
+ await createDoc();
842
+ const error = await caught(
843
+ executeDelete<ExecStuff>({
844
+ id: {$ne: null} as unknown as string,
845
+ model: ExecStuffModel,
846
+ options: baseOptions(),
847
+ user: owner,
848
+ })
849
+ );
850
+ assert.equal(error.status, 404);
851
+ expect(await ExecStuffModel.countDocuments({deleted: true})).toBe(0);
852
+ });
853
+
840
854
  it("checks object permissions before returning an idempotent tombstone", async () => {
841
855
  const id = "foreign-offline-id";
842
856
  await ExecStringIdStuffModel.create({
@@ -188,7 +188,10 @@ const reloadDocForConflict = async <T>(
188
188
  id: string
189
189
  ): Promise<ExecutorDoc<T> | undefined> => {
190
190
  try {
191
- const found = await model.find({_id: id, deleted: {$in: [true, false]}} as never).limit(1);
191
+ // $eq pins the id to an equality match so a client-supplied object cannot add operators.
192
+ const found = await model
193
+ .find({_id: {$eq: id}, deleted: {$in: [true, false]}} as never)
194
+ .limit(1);
192
195
  return found[0] as ExecutorDoc<T> | undefined;
193
196
  } catch {
194
197
  return undefined;
@@ -854,7 +857,9 @@ export const executeDelete = async <T>({
854
857
  (error.meta as {deleted?: string} | undefined)?.deleted === "true";
855
858
  if (alreadyDeleted) {
856
859
  // Hydrate the tombstone bypassing the isDeletedPlugin find filter.
857
- const tombstone = await model.find({_id: id, deleted: {$in: [true, false]}}).limit(1);
860
+ const tombstone = await model
861
+ .find({_id: {$eq: id}, deleted: {$in: [true, false]}} as never)
862
+ .limit(1);
858
863
  const resolved = tombstone[0] as ExecutorDoc<T> & {deleted?: boolean};
859
864
  if (!resolved) {
860
865
  throw error;
@@ -1,6 +1,7 @@
1
- import {beforeAll, beforeEach, describe, expect, it} from "bun:test";
1
+ import {beforeAll, beforeEach, describe, expect, it, setSystemTime} from "bun:test";
2
2
  import {assert} from "chai";
3
3
  import type express from "express";
4
+ import {DateTime} from "luxon";
4
5
  import {type Model, model, Schema, Types} from "mongoose";
5
6
  import supertest from "supertest";
6
7
  import type TestAgent from "supertest/lib/agent";
@@ -891,6 +892,9 @@ describe("sync routes", () => {
891
892
  // cannot spread across the 1-second rolling window under machine load
892
893
  // (a sequential loop's wall-clock time is unbounded and would let the
893
894
  // window reset mid-flood, making the final request wrongly succeed).
895
+ // Freeze the clock as well: on a loaded machine even the concurrent flood can take
896
+ // longer than the window. The package preload restores real time after each test.
897
+ setSystemTime(DateTime.now().toJSDate());
894
898
  const body = (mutationId: string) => ({
895
899
  collection: "routeStuff",
896
900
  data: {name: "flood", ownerId: notAdminId},
@@ -17,6 +17,7 @@ import {
17
17
  clearSecurityActionListenersForTests,
18
18
  SECURITY_ACTIONS,
19
19
  } from "../accountSecurity/securityEvents";
20
+ import {flushSecurityNotificationsForTests} from "../accountSecurity/securityNotifications";
20
21
  import {AuditApp} from "../audit/auditApp";
21
22
  import {createAuditEventModel} from "../audit/auditEventModel";
22
23
  import {flushAuditRecorderForTests, resetAuditRecorderForTests} from "../audit/record";
@@ -67,6 +68,9 @@ export const SecurityUser = getSecurityUserModel();
67
68
  export const securityUserModel = SecurityUser as unknown as UserModel;
68
69
  export const AuditEvent = createAuditEventModel(mongoose.connection);
69
70
 
71
+ /** Account-security suites reset Mongo and Better Auth collections each test; allow headroom on CI. */
72
+ export const ACCOUNT_SECURITY_HOOK_TIMEOUT_MS = 30_000;
73
+
70
74
  export const access = createAccess({
71
75
  connection: mongoose.connection,
72
76
  organizations: true,
@@ -278,6 +282,7 @@ export const betterAuthIdFor = async (userId: string): Promise<string> => {
278
282
 
279
283
  /** Clears every collection the security suites write, plus in-process recorder state. */
280
284
  export const resetAccountSecurityState = async (): Promise<void> => {
285
+ await flushSecurityNotificationsForTests();
281
286
  clearMCPRegistry();
282
287
  clearSecurityActionListenersForTests();
283
288
  resetAuditRecorderForTests();