@terreno/api 57.21.0 → 58.0.0-beta.2
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 +89 -0
- package/README.md +1 -1
- package/dist/api.d.ts +0 -13
- package/dist/api.js +0 -9
- package/dist/auth.d.ts +3 -2
- package/dist/auth.js +95 -5
- package/dist/authRecovery.d.ts +2 -1
- package/dist/authRecovery.js +35 -17
- package/dist/collectionRegistry.d.ts +3 -4
- package/dist/collectionRegistry.js +0 -1
- package/dist/consentApp.d.ts +1 -1
- package/dist/consentApp.js +58 -2
- package/dist/index.d.ts +4 -5
- package/dist/index.js +8 -20
- package/dist/mcp/adminTracking.js +1 -1
- package/dist/mcp/serviceTokens.d.ts +21 -1
- package/dist/mcp/serviceTokens.js +159 -183
- package/dist/migrations/builtin/mcpServiceTokenStringIds.d.ts +18 -0
- package/dist/migrations/builtin/mcpServiceTokenStringIds.js +67 -0
- package/dist/models/mcpRequestLog.js +1 -1
- package/dist/models/mcpServiceToken.js +36 -4
- package/dist/openApiBuilder.d.ts +4 -0
- package/dist/openApiBuilder.js +2 -0
- package/dist/rbac/realtimeAccess.d.ts +5 -4
- package/dist/rbac/realtimeAccess.js +17 -64
- package/dist/realtime/changeStreamWatcher.d.ts +8 -63
- package/dist/realtime/changeStreamWatcher.js +32 -391
- package/dist/realtime/realtimeApp.d.ts +14 -27
- package/dist/realtime/realtimeApp.js +14 -220
- package/dist/realtime/types.d.ts +0 -64
- package/dist/sync/entityIds.d.ts +14 -0
- package/dist/sync/entityIds.js +17 -0
- package/dist/sync/executors.js +14 -2
- package/dist/sync/models.d.ts +1 -0
- package/dist/sync/models.js +4 -0
- package/dist/sync/mutationHandler.js +51 -2
- package/dist/sync/routes.js +12 -17
- package/dist/sync/socketHandlers.d.ts +1 -1
- package/dist/sync/socketHandlers.js +1 -1
- package/dist/sync/types.d.ts +8 -0
- package/dist/terrenoApp.d.ts +7 -5
- package/dist/terrenoApp.js +18 -14
- package/dist/tests/openApiResponseSchema.d.ts +39 -0
- package/dist/tests/openApiResponseSchema.js +56 -0
- package/dist/tests.d.ts +1 -0
- package/dist/tests.js +4 -1
- package/dist/types/mcpAdmin.d.ts +1 -1
- package/dist/types/mcpServiceToken.d.ts +7 -4
- package/dist/versionCheckPlugin.d.ts +1 -1
- package/dist/versionCheckPlugin.js +25 -2
- package/package.json +17 -6
- package/src/__snapshots__/openApi.test.ts.snap +4986 -2478
- package/src/__snapshots__/openApiBuilder.test.ts.snap +836 -0
- package/src/__tests__/openApiResponseSchema.test.ts +148 -0
- package/src/__tests__/versionCheckPlugin.test.ts +72 -0
- package/src/api.test.ts +9 -7
- package/src/api.ts +0 -24
- package/src/auth.ts +116 -5
- package/src/authOpenApi.test.ts +316 -0
- package/src/authRecovery.ts +47 -19
- package/src/betterAuthOAuthHandoff.test.ts +13 -5
- package/src/collectionRegistry.ts +3 -5
- package/src/consentApp.test.ts +98 -0
- package/src/consentApp.ts +67 -2
- package/src/index.ts +6 -28
- package/src/mcp/actionTools.test.ts +2 -2
- package/src/mcp/adminTracking.ts +1 -1
- package/src/mcp/auth.test.ts +7 -3
- package/src/mcp/oauth.test.ts +12 -12
- package/src/mcp/serviceTokens.sync.test.ts +230 -0
- package/src/mcp/serviceTokens.test.ts +112 -61
- package/src/mcp/serviceTokens.ts +193 -212
- package/src/migrations/builtin/mcpServiceTokenStringIds.test.ts +194 -0
- package/src/migrations/builtin/mcpServiceTokenStringIds.ts +121 -0
- package/src/models/mcpRequestLog.ts +1 -1
- package/src/models/mcpServiceToken.test.ts +52 -5
- package/src/models/mcpServiceToken.ts +51 -14
- package/src/openApiBuilder.test.ts +34 -1
- package/src/openApiBuilder.ts +5 -0
- package/src/rateLimit/rateLimit.test.ts +25 -10
- package/src/rbac/realtimeAccess.test.ts +20 -172
- package/src/rbac/realtimeAccess.ts +17 -82
- package/src/realtime/changeStreamWatcher.ts +43 -506
- package/src/realtime/realtime.test.ts +205 -2545
- package/src/realtime/realtimeApp.ts +16 -295
- package/src/realtime/types.ts +0 -72
- package/src/sync/entityIds.ts +18 -0
- package/src/sync/executors.test.ts +28 -0
- package/src/sync/executors.ts +23 -2
- package/src/sync/models.ts +6 -0
- package/src/sync/mutationHandler.test.ts +84 -0
- package/src/sync/mutationHandler.ts +57 -2
- package/src/sync/routes.ts +12 -17
- package/src/sync/socketHandlers.ts +1 -1
- package/src/sync/syncRoutes.test.ts +8 -4
- package/src/sync/syncSocket.test.ts +77 -113
- package/src/sync/types.ts +9 -0
- package/src/terrenoApp.mcpServiceTokens.test.ts +14 -6
- package/src/terrenoApp.ts +24 -18
- package/src/tests/openApiResponseSchema.ts +104 -0
- package/src/tests.ts +7 -0
- package/src/types/mcpAdmin.ts +1 -1
- package/src/types/mcpServiceToken.ts +7 -4
- package/src/versionCheckPlugin.ts +41 -2
- package/biome.jsonc +0 -22
- package/bunfig.toml +0 -10
- package/bunfig.unit.toml +0 -3
- package/dist/realtime/deprecation.d.ts +0 -13
- package/dist/realtime/deprecation.js +0 -31
- package/dist/realtime/queryStore.d.ts +0 -37
- package/dist/realtime/queryStore.js +0 -103
- package/dist/realtime/registry.d.ts +0 -15
- package/dist/realtime/registry.js +0 -52
- package/e2e/smoke.ts +0 -193
- package/src/realtime/deprecation.test.ts +0 -60
- package/src/realtime/deprecation.ts +0 -33
- package/src/realtime/queryStore.ts +0 -122
- package/src/realtime/registry.ts +0 -84
- package/tsconfig.json +0 -19
- package/tsconfig.typecheck.json +0 -14
- package/tsconfig.typedoc.json +0 -13
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Built-in data migration for Terreno 58: McpServiceToken became a synced collection with
|
|
3
|
+
* String `_id`s. Rows minted before 58 have ObjectId `_id`s; this migration re-inserts each
|
|
4
|
+
* one with `_id = oldId.toHexString()` and deletes the original, so existing tokens keep
|
|
5
|
+
* the same id string clients already saw.
|
|
6
|
+
*
|
|
7
|
+
* Apps run it through their own `migrations/` directory (see `run-mongodb-migrations.md`):
|
|
8
|
+
*
|
|
9
|
+
* ```typescript
|
|
10
|
+
* // migrations/20261022120000-mcp-service-token-string-ids.ts
|
|
11
|
+
* import {mcpServiceTokenStringIdsMigration} from "@terreno/api";
|
|
12
|
+
*
|
|
13
|
+
* export const id = "20261022120000-mcp-service-token-string-ids";
|
|
14
|
+
* export const up = mcpServiceTokenStringIdsMigration.up;
|
|
15
|
+
* ```
|
|
16
|
+
*
|
|
17
|
+
* Idempotent: only ObjectId-keyed rows are selected, and a run interrupted mid-row resumes
|
|
18
|
+
* cleanly. It works on standalone servers (no transaction): the original row's unique
|
|
19
|
+
* `tokenHash` is parked behind a marker prefix before the copy is inserted, so a crash never
|
|
20
|
+
* loses a row. That token fails MCP auth only for the instant between park and copy.
|
|
21
|
+
*/
|
|
22
|
+
import type mongoose from "mongoose";
|
|
23
|
+
|
|
24
|
+
import type {MigrationContext} from "../types";
|
|
25
|
+
|
|
26
|
+
export const MCP_SERVICE_TOKEN_STRING_IDS_SLUG = "mcp-service-token-string-ids";
|
|
27
|
+
|
|
28
|
+
const COLLECTION_NAME = "mcpservicetokens";
|
|
29
|
+
const BATCH_SIZE = 200;
|
|
30
|
+
const PARKED_HASH_PREFIX = "mcp-service-token-string-ids:";
|
|
31
|
+
const LEGACY_ID_FILTER = {_id: {$type: "objectId" as const}};
|
|
32
|
+
|
|
33
|
+
interface LegacyTokenRow {
|
|
34
|
+
_id: mongoose.Types.ObjectId;
|
|
35
|
+
deleted?: boolean;
|
|
36
|
+
tokenHash: string;
|
|
37
|
+
[key: string]: unknown;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export interface McpServiceTokenStringIdsResult {
|
|
41
|
+
/** Rows re-keyed to a String `_id` in this run. */
|
|
42
|
+
converted: number;
|
|
43
|
+
/** ObjectId-keyed rows still waiting (non-zero only for dry runs). */
|
|
44
|
+
pending: number;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
const unparkedHash = (tokenHash: string): string =>
|
|
48
|
+
tokenHash.startsWith(PARKED_HASH_PREFIX) ? tokenHash.slice(PARKED_HASH_PREFIX.length) : tokenHash;
|
|
49
|
+
|
|
50
|
+
const convertRow = async ({
|
|
51
|
+
collection,
|
|
52
|
+
row,
|
|
53
|
+
}: {
|
|
54
|
+
collection: mongoose.Collection;
|
|
55
|
+
row: LegacyTokenRow;
|
|
56
|
+
}): Promise<void> => {
|
|
57
|
+
const stringId = row._id.toHexString();
|
|
58
|
+
const tokenHash = unparkedHash(row.tokenHash);
|
|
59
|
+
const parkedHash = `${PARKED_HASH_PREFIX}${tokenHash}`;
|
|
60
|
+
// Free the unique tokenHash for the copy while keeping the original row recoverable.
|
|
61
|
+
if (row.tokenHash !== parkedHash) {
|
|
62
|
+
await collection.updateOne({_id: row._id}, {$set: {tokenHash: parkedHash}});
|
|
63
|
+
}
|
|
64
|
+
const existingCopy = await collection.findOne({_id: stringId as never});
|
|
65
|
+
if (!existingCopy) {
|
|
66
|
+
await collection.insertOne({
|
|
67
|
+
...row,
|
|
68
|
+
_id: stringId as never,
|
|
69
|
+
deleted: row.deleted ?? false,
|
|
70
|
+
tokenHash,
|
|
71
|
+
});
|
|
72
|
+
}
|
|
73
|
+
await collection.deleteOne({_id: row._id});
|
|
74
|
+
};
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* Re-key every ObjectId McpServiceToken row to its hex string. Returns how many rows were
|
|
78
|
+
* converted; a dry run converts nothing and reports how many are pending.
|
|
79
|
+
*/
|
|
80
|
+
export const migrateMcpServiceTokenStringIds = async (
|
|
81
|
+
ctx: MigrationContext
|
|
82
|
+
): Promise<McpServiceTokenStringIdsResult> => {
|
|
83
|
+
const collection = ctx.mongoose.connection.collection(COLLECTION_NAME);
|
|
84
|
+
|
|
85
|
+
if (ctx.dryRun) {
|
|
86
|
+
const pending = await collection.countDocuments(LEGACY_ID_FILTER);
|
|
87
|
+
ctx.logger.info(
|
|
88
|
+
`[${MCP_SERVICE_TOKEN_STRING_IDS_SLUG}] dry run: ${pending} ObjectId rows would be re-keyed`
|
|
89
|
+
);
|
|
90
|
+
return {converted: 0, pending};
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
let converted = 0;
|
|
94
|
+
for (;;) {
|
|
95
|
+
await ctx.checkCancellation?.();
|
|
96
|
+
const batch = (await collection
|
|
97
|
+
.find(LEGACY_ID_FILTER)
|
|
98
|
+
.limit(BATCH_SIZE)
|
|
99
|
+
.toArray()) as unknown as LegacyTokenRow[];
|
|
100
|
+
if (batch.length === 0) {
|
|
101
|
+
break;
|
|
102
|
+
}
|
|
103
|
+
for (const row of batch) {
|
|
104
|
+
await convertRow({collection, row});
|
|
105
|
+
converted += 1;
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
const message = `[${MCP_SERVICE_TOKEN_STRING_IDS_SLUG}] re-keyed ${converted} rows to String ids`;
|
|
110
|
+
ctx.logger.info(message);
|
|
111
|
+
await ctx.addLog?.("info", message);
|
|
112
|
+
return {converted, pending: 0};
|
|
113
|
+
};
|
|
114
|
+
|
|
115
|
+
/** Ready-made `up` for an app migration file (irreversible: new rows use UUID ids). */
|
|
116
|
+
export const mcpServiceTokenStringIdsMigration = {
|
|
117
|
+
slug: MCP_SERVICE_TOKEN_STRING_IDS_SLUG,
|
|
118
|
+
up: async (ctx: MigrationContext): Promise<void> => {
|
|
119
|
+
await migrateMcpServiceTokenStringIds(ctx);
|
|
120
|
+
},
|
|
121
|
+
};
|
|
@@ -47,7 +47,7 @@ const mcpRequestLogSchema = new mongoose.Schema<McpRequestLogDocument, McpReques
|
|
|
47
47
|
description: "Service token used for the call, when the credential was a service token",
|
|
48
48
|
index: true,
|
|
49
49
|
ref: "TerrenoMcpServiceToken",
|
|
50
|
-
type:
|
|
50
|
+
type: String,
|
|
51
51
|
},
|
|
52
52
|
toolName: {
|
|
53
53
|
description: "Name of the MCP tool that was called",
|
|
@@ -1,16 +1,20 @@
|
|
|
1
1
|
import {beforeEach, describe, it} from "bun:test";
|
|
2
|
-
import {createHash} from "node:crypto";
|
|
2
|
+
import {createHash, randomUUID} from "node:crypto";
|
|
3
3
|
import {assert} from "chai";
|
|
4
4
|
import {DateTime} from "luxon";
|
|
5
5
|
import mongoose from "mongoose";
|
|
6
6
|
|
|
7
|
+
import {clearSyncRegistry} from "../sync/registry";
|
|
7
8
|
import {McpServiceToken} from "./mcpServiceToken";
|
|
8
9
|
|
|
9
10
|
const hashToken = (token: string): string => createHash("sha256").update(token).digest("hex");
|
|
10
11
|
|
|
11
12
|
describe("McpServiceToken", () => {
|
|
12
13
|
beforeEach(async () => {
|
|
13
|
-
|
|
14
|
+
// Model-level behaviour without the /mcp/service-tokens sync registration.
|
|
15
|
+
clearSyncRegistry();
|
|
16
|
+
// Model.deleteMany is rejected once the collection is sync-registered by another suite.
|
|
17
|
+
await McpServiceToken.collection.deleteMany({});
|
|
14
18
|
await McpServiceToken.syncIndexes();
|
|
15
19
|
});
|
|
16
20
|
|
|
@@ -25,6 +29,51 @@ describe("McpServiceToken", () => {
|
|
|
25
29
|
assert.notInclude(JSON.stringify(issued.mcpServiceToken.toJSON()), issued.token);
|
|
26
30
|
});
|
|
27
31
|
|
|
32
|
+
it("mints UUID string ids", async () => {
|
|
33
|
+
const issued = await McpServiceToken.issueFor(
|
|
34
|
+
{_id: new mongoose.Types.ObjectId()},
|
|
35
|
+
{name: "Uuid"}
|
|
36
|
+
);
|
|
37
|
+
|
|
38
|
+
assert.isString(issued.mcpServiceToken._id);
|
|
39
|
+
assert.match(
|
|
40
|
+
issued.mcpServiceToken._id,
|
|
41
|
+
/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/
|
|
42
|
+
);
|
|
43
|
+
assert.isFalse(issued.mcpServiceToken.deleted);
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
it("turns a soft delete into a revoke so the row stays visible", async () => {
|
|
47
|
+
const issued = await McpServiceToken.issueFor(
|
|
48
|
+
{_id: new mongoose.Types.ObjectId()},
|
|
49
|
+
{name: "Soft delete"}
|
|
50
|
+
);
|
|
51
|
+
|
|
52
|
+
issued.mcpServiceToken.deleted = true;
|
|
53
|
+
await issued.mcpServiceToken.save();
|
|
54
|
+
|
|
55
|
+
const stored = await McpServiceToken.findExactlyOne({_id: issued.mcpServiceToken._id});
|
|
56
|
+
assert.isFalse(stored.deleted);
|
|
57
|
+
assert.instanceOf(stored.revokedAt, Date);
|
|
58
|
+
assert.isNull(await McpServiceToken.verify(issued.token));
|
|
59
|
+
});
|
|
60
|
+
|
|
61
|
+
it("keeps an existing revokedAt when a revoked token is soft deleted", async () => {
|
|
62
|
+
const issued = await McpServiceToken.issueFor(
|
|
63
|
+
{_id: new mongoose.Types.ObjectId()},
|
|
64
|
+
{name: "Already revoked"}
|
|
65
|
+
);
|
|
66
|
+
const revokedAt = DateTime.now().minus({day: 1}).toJSDate();
|
|
67
|
+
issued.mcpServiceToken.revokedAt = revokedAt;
|
|
68
|
+
await issued.mcpServiceToken.save();
|
|
69
|
+
|
|
70
|
+
issued.mcpServiceToken.deleted = true;
|
|
71
|
+
await issued.mcpServiceToken.save();
|
|
72
|
+
|
|
73
|
+
const stored = await McpServiceToken.findExactlyOne({_id: issued.mcpServiceToken._id});
|
|
74
|
+
assert.equal(stored.revokedAt?.getTime(), revokedAt.getTime());
|
|
75
|
+
});
|
|
76
|
+
|
|
28
77
|
it("verifies an active token but not a revoked or expired token", async () => {
|
|
29
78
|
const userId = new mongoose.Types.ObjectId();
|
|
30
79
|
const active = await McpServiceToken.issueFor({_id: userId}, {name: "Active"});
|
|
@@ -63,9 +112,7 @@ describe("McpServiceToken", () => {
|
|
|
63
112
|
assert.instanceOf(revoked?.revokedAt, Date);
|
|
64
113
|
|
|
65
114
|
assert.isNull(await McpServiceToken.revokeForUser({_id: ownerId}, issued.mcpServiceToken._id));
|
|
66
|
-
assert.isNull(
|
|
67
|
-
await McpServiceToken.revokeForUser({_id: ownerId}, new mongoose.Types.ObjectId())
|
|
68
|
-
);
|
|
115
|
+
assert.isNull(await McpServiceToken.revokeForUser({_id: ownerId}, randomUUID()));
|
|
69
116
|
});
|
|
70
117
|
|
|
71
118
|
it("enforces unique token hashes", async () => {
|
|
@@ -1,8 +1,15 @@
|
|
|
1
|
-
import {createHash, randomBytes} from "node:crypto";
|
|
1
|
+
import {createHash, randomBytes, randomUUID} from "node:crypto";
|
|
2
2
|
import {DateTime} from "luxon";
|
|
3
3
|
import mongoose from "mongoose";
|
|
4
4
|
|
|
5
|
-
import {
|
|
5
|
+
import {
|
|
6
|
+
createdUpdatedPlugin,
|
|
7
|
+
findExactlyOne,
|
|
8
|
+
findOneOrNone,
|
|
9
|
+
findOneOrNoneFor,
|
|
10
|
+
isDeletedPlugin,
|
|
11
|
+
} from "../plugins";
|
|
12
|
+
import {syncPlugin} from "../sync/syncSeqPlugin";
|
|
6
13
|
import type {McpServiceTokenDocument, McpServiceTokenModel} from "../types/mcpServiceToken";
|
|
7
14
|
|
|
8
15
|
export type {
|
|
@@ -20,6 +27,13 @@ const hashToken = (token: string): string => createHash("sha256").update(token).
|
|
|
20
27
|
|
|
21
28
|
const mcpServiceTokenSchema = new mongoose.Schema<McpServiceTokenDocument, McpServiceTokenModel>(
|
|
22
29
|
{
|
|
30
|
+
_id: {
|
|
31
|
+
// Synced collections use String ids. New rows get a UUID; rows created before
|
|
32
|
+
// Terreno 58 keep their ObjectId hex after the mcp-service-token-string-ids migration.
|
|
33
|
+
default: (): string => randomUUID(),
|
|
34
|
+
description: "The MCP service token id (String so the synced collection can address it)",
|
|
35
|
+
type: String,
|
|
36
|
+
},
|
|
23
37
|
expiresAt: {
|
|
24
38
|
description: "When this MCP service token expires; unset when it does not expire",
|
|
25
39
|
type: Date,
|
|
@@ -69,9 +83,26 @@ mcpServiceTokenSchema.index({expiresAt: 1}, {expireAfterSeconds: 0});
|
|
|
69
83
|
mcpServiceTokenSchema.index({revokedAt: 1, userId: 1});
|
|
70
84
|
|
|
71
85
|
mcpServiceTokenSchema.plugin(createdUpdatedPlugin);
|
|
86
|
+
mcpServiceTokenSchema.plugin(isDeletedPlugin);
|
|
72
87
|
mcpServiceTokenSchema.plugin(findOneOrNone);
|
|
73
88
|
mcpServiceTokenSchema.plugin(findExactlyOne);
|
|
74
89
|
|
|
90
|
+
// Deleting a token means revoking it: the row stays visible to its owner (and the audit
|
|
91
|
+
// trail) with `revokedAt` set. A soft delete (admin DELETE through modelRouter sets
|
|
92
|
+
// `deleted: true`) is turned into a revoke so it never tombstones the owner's synced row.
|
|
93
|
+
mcpServiceTokenSchema.pre("save", function () {
|
|
94
|
+
if (!this.isModified("deleted") || this.deleted !== true) {
|
|
95
|
+
return;
|
|
96
|
+
}
|
|
97
|
+
this.deleted = false;
|
|
98
|
+
if (!this.revokedAt) {
|
|
99
|
+
this.revokedAt = DateTime.now().toJSDate();
|
|
100
|
+
}
|
|
101
|
+
});
|
|
102
|
+
|
|
103
|
+
// Stamps a per-stream _syncSeq on every write; required by the /mcp/service-tokens sync config.
|
|
104
|
+
mcpServiceTokenSchema.plugin(syncPlugin);
|
|
105
|
+
|
|
75
106
|
const revokeInsteadOfDelete = async (
|
|
76
107
|
doc: McpServiceTokenDocument | null
|
|
77
108
|
): Promise<McpServiceTokenDocument | null> => {
|
|
@@ -93,6 +124,9 @@ mcpServiceTokenSchema.methods = {
|
|
|
93
124
|
},
|
|
94
125
|
};
|
|
95
126
|
|
|
127
|
+
// Query deleteOne revokes instead of removing the row. Registered after syncPlugin so that,
|
|
128
|
+
// once the collection is synced, syncPlugin's hard-delete guard rejects the call before any
|
|
129
|
+
// write happens.
|
|
96
130
|
mcpServiceTokenSchema.pre("deleteOne", {document: false, query: true}, async function () {
|
|
97
131
|
const existing = await findOneOrNoneFor(this.model, this.getFilter());
|
|
98
132
|
await revokeInsteadOfDelete(existing as McpServiceTokenDocument | null);
|
|
@@ -103,7 +137,7 @@ mcpServiceTokenSchema.statics = {
|
|
|
103
137
|
...mcpServiceTokenSchema.statics,
|
|
104
138
|
async countActiveForUser(
|
|
105
139
|
this: McpServiceTokenModel,
|
|
106
|
-
userId: mongoose.Types.ObjectId
|
|
140
|
+
userId: mongoose.Types.ObjectId | string
|
|
107
141
|
): Promise<number> {
|
|
108
142
|
const now = DateTime.now().toJSDate();
|
|
109
143
|
return this.countDocuments({
|
|
@@ -144,11 +178,11 @@ mcpServiceTokenSchema.statics = {
|
|
|
144
178
|
async revokeForUser(
|
|
145
179
|
this: McpServiceTokenModel,
|
|
146
180
|
user: {_id: {toString(): string}},
|
|
147
|
-
tokenId:
|
|
181
|
+
tokenId: string
|
|
148
182
|
): Promise<McpServiceTokenDocument | null> {
|
|
149
183
|
return this.findOneAndUpdate(
|
|
150
184
|
{
|
|
151
|
-
_id: tokenId,
|
|
185
|
+
_id: String(tokenId),
|
|
152
186
|
revokedAt: {$exists: false},
|
|
153
187
|
userId: new mongoose.Types.ObjectId(String(user._id)),
|
|
154
188
|
},
|
|
@@ -165,14 +199,17 @@ mcpServiceTokenSchema.statics = {
|
|
|
165
199
|
user: {_id: {toString(): string}; tokenEpoch?: number}
|
|
166
200
|
): Promise<void> {
|
|
167
201
|
const currentEpoch = user.tokenEpoch ?? 0;
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
)
|
|
202
|
+
const userId = new mongoose.Types.ObjectId(String(user._id));
|
|
203
|
+
const outdated = await this.find({
|
|
204
|
+
revokedAt: {$exists: false},
|
|
205
|
+
tokenEpoch: {$nin: currentEpoch === 0 ? [0, null] : [currentEpoch]},
|
|
206
|
+
userId,
|
|
207
|
+
});
|
|
208
|
+
const revokedAt = DateTime.now().toJSDate();
|
|
209
|
+
for (const token of outdated) {
|
|
210
|
+
token.revokedAt = revokedAt;
|
|
211
|
+
await token.save();
|
|
212
|
+
}
|
|
176
213
|
},
|
|
177
214
|
async verify(this: McpServiceTokenModel, token: string): Promise<McpServiceTokenDocument | null> {
|
|
178
215
|
const now = DateTime.now().toJSDate();
|
|
@@ -185,7 +222,7 @@ mcpServiceTokenSchema.statics = {
|
|
|
185
222
|
};
|
|
186
223
|
|
|
187
224
|
export const McpServiceToken =
|
|
188
|
-
(mongoose.models.TerrenoMcpServiceToken as McpServiceTokenModel | undefined) ??
|
|
225
|
+
(mongoose.models.TerrenoMcpServiceToken as unknown as McpServiceTokenModel | undefined) ??
|
|
189
226
|
mongoose.model<McpServiceTokenDocument, McpServiceTokenModel>(
|
|
190
227
|
"TerrenoMcpServiceToken",
|
|
191
228
|
mcpServiceTokenSchema,
|
|
@@ -4,7 +4,7 @@ import type {Router} from "express";
|
|
|
4
4
|
import supertest from "supertest";
|
|
5
5
|
import type TestAgent from "supertest/lib/agent";
|
|
6
6
|
|
|
7
|
-
import {type ModelRouterOptions, modelRouter} from "./api";
|
|
7
|
+
import {type ModelRouterOptions, modelRouter, type OpenApiMiddleware} from "./api";
|
|
8
8
|
import type {UserModel as AuthUserModel} from "./auth";
|
|
9
9
|
import {createOpenApiBuilder, OpenApiMiddlewareBuilder} from "./openApiBuilder";
|
|
10
10
|
import {Permissions} from "./permissions";
|
|
@@ -438,6 +438,39 @@ describe("OpenApiMiddlewareBuilder configuration", () => {
|
|
|
438
438
|
expect(builder).toBeInstanceOf(OpenApiMiddlewareBuilder);
|
|
439
439
|
});
|
|
440
440
|
|
|
441
|
+
it("lists top-level required response fields only when given", () => {
|
|
442
|
+
const captured: Record<string, unknown>[] = [];
|
|
443
|
+
const openApi = {
|
|
444
|
+
path: (schema: Record<string, unknown> = {}): express.RequestHandler => {
|
|
445
|
+
captured.push(schema);
|
|
446
|
+
return (_req, _res, next) => next();
|
|
447
|
+
},
|
|
448
|
+
} as unknown as OpenApiMiddleware;
|
|
449
|
+
|
|
450
|
+
createOpenApiBuilder({openApi})
|
|
451
|
+
.withResponse(200, {data: {nullable: true, type: "object"}}, {required: ["data"]})
|
|
452
|
+
.withValidation({enabled: false})
|
|
453
|
+
.build();
|
|
454
|
+
createOpenApiBuilder({openApi})
|
|
455
|
+
.withResponse(200, {ok: {type: "boolean"}})
|
|
456
|
+
.withValidation({enabled: false})
|
|
457
|
+
.build();
|
|
458
|
+
|
|
459
|
+
interface CapturedOperation {
|
|
460
|
+
responses: Record<number, {content: Record<string, {schema: Record<string, unknown>}>}>;
|
|
461
|
+
}
|
|
462
|
+
const schemaOf = (index: number): Record<string, unknown> | undefined =>
|
|
463
|
+
(captured[index] as unknown as CapturedOperation | undefined)?.responses[200]?.content[
|
|
464
|
+
"application/json"
|
|
465
|
+
]?.schema;
|
|
466
|
+
expect(schemaOf(0)).toEqual({
|
|
467
|
+
properties: {data: {nullable: true, type: "object"}},
|
|
468
|
+
required: ["data"],
|
|
469
|
+
type: "object",
|
|
470
|
+
});
|
|
471
|
+
expect(schemaOf(1)).toEqual({properties: {ok: {type: "boolean"}}, type: "object"});
|
|
472
|
+
});
|
|
473
|
+
|
|
441
474
|
it("supports optional request body", () => {
|
|
442
475
|
const builder = createOpenApiBuilder({}).withRequestBody(
|
|
443
476
|
{data: {type: "string"}},
|
package/src/openApiBuilder.ts
CHANGED
|
@@ -131,6 +131,8 @@ export interface OpenApiSchemaProperty {
|
|
|
131
131
|
items?: OpenApiSchemaProperty;
|
|
132
132
|
/** Minimum array length when type is "array". */
|
|
133
133
|
minItems?: number;
|
|
134
|
+
/** OpenAPI 3.0 flag: the value may also be `null`. */
|
|
135
|
+
nullable?: boolean;
|
|
134
136
|
/** Nested properties when type is "object" */
|
|
135
137
|
properties?: Record<string, OpenApiSchemaProperty>;
|
|
136
138
|
/** Schema for additional properties or boolean to allow/disallow them */
|
|
@@ -518,6 +520,7 @@ export class OpenApiMiddlewareBuilder {
|
|
|
518
520
|
* @param options - Optional configuration for the response
|
|
519
521
|
* @param options.description - Description of the response (default: "Success")
|
|
520
522
|
* @param options.mediaType - Media type for the response (default: "application/json")
|
|
523
|
+
* @param options.required - Top-level property names that are always present (e.g. `["data"]`)
|
|
521
524
|
* @returns The builder instance for chaining
|
|
522
525
|
*
|
|
523
526
|
* @example
|
|
@@ -541,6 +544,7 @@ export class OpenApiMiddlewareBuilder {
|
|
|
541
544
|
options?: {
|
|
542
545
|
description?: string;
|
|
543
546
|
mediaType?: string;
|
|
547
|
+
required?: string[];
|
|
544
548
|
}
|
|
545
549
|
): this {
|
|
546
550
|
if (typeof schema === "string") {
|
|
@@ -553,6 +557,7 @@ export class OpenApiMiddlewareBuilder {
|
|
|
553
557
|
[options?.mediaType ?? "application/json"]: {
|
|
554
558
|
schema: {
|
|
555
559
|
properties: schema,
|
|
560
|
+
...(options?.required?.length ? {required: options.required} : {}),
|
|
556
561
|
type: "object",
|
|
557
562
|
},
|
|
558
563
|
},
|
|
@@ -28,7 +28,7 @@ const foodRouter = modelRouter("/food", FoodModel, {
|
|
|
28
28
|
},
|
|
29
29
|
});
|
|
30
30
|
|
|
31
|
-
const buildApp = (rateLimit?: RateLimitOptions): Application => {
|
|
31
|
+
const buildApp = (rateLimit?: RateLimitOptions | false): Application => {
|
|
32
32
|
return new TerrenoApp({
|
|
33
33
|
configureApp: (app) => {
|
|
34
34
|
app.get("/health", (_req, res) => {
|
|
@@ -44,13 +44,22 @@ const buildApp = (rateLimit?: RateLimitOptions): Application => {
|
|
|
44
44
|
.start();
|
|
45
45
|
};
|
|
46
46
|
|
|
47
|
+
const loginUpToAuthMax = async (app: Application): Promise<void> => {
|
|
48
|
+
for (let i = 0; i < DEFAULT_AUTH_MAX; i++) {
|
|
49
|
+
const res = await supertest(app)
|
|
50
|
+
.post("/auth/login")
|
|
51
|
+
.send({email: "notAdmin@example.com", password: "password"});
|
|
52
|
+
assert.equal(res.status, 200, `login ${i} should be under the auth cap`);
|
|
53
|
+
}
|
|
54
|
+
};
|
|
55
|
+
|
|
47
56
|
describe("HTTP rate limiting", () => {
|
|
48
57
|
beforeEach(async () => {
|
|
49
58
|
await setupTestData();
|
|
50
59
|
});
|
|
51
60
|
|
|
52
|
-
it("does not 429 burst logins when rateLimit is
|
|
53
|
-
const app = buildApp();
|
|
61
|
+
it("does not 429 burst logins when rateLimit is false", async () => {
|
|
62
|
+
const app = buildApp(false);
|
|
54
63
|
for (let i = 0; i < 25; i++) {
|
|
55
64
|
const res = await supertest(app)
|
|
56
65
|
.post("/auth/login")
|
|
@@ -59,14 +68,20 @@ describe("HTTP rate limiting", () => {
|
|
|
59
68
|
}
|
|
60
69
|
}, 30_000);
|
|
61
70
|
|
|
62
|
-
it("
|
|
71
|
+
it("limits by default: 429 on the 21st POST /auth/login when rateLimit is omitted", async () => {
|
|
72
|
+
const app = buildApp();
|
|
73
|
+
await loginUpToAuthMax(app);
|
|
74
|
+
const limited = await supertest(app)
|
|
75
|
+
.post("/auth/login")
|
|
76
|
+
.send({email: "notAdmin@example.com", password: "password"});
|
|
77
|
+
assert.equal(limited.status, 429);
|
|
78
|
+
assert.equal(limited.body.code, "rate-limit-exceeded");
|
|
79
|
+
assert.include(limited.headers.ratelimit, `limit=${DEFAULT_AUTH_MAX}`);
|
|
80
|
+
}, 30_000);
|
|
81
|
+
|
|
82
|
+
it("returns 429 on the 21st POST /auth/login with rateLimit {}", async () => {
|
|
63
83
|
const app = buildApp({});
|
|
64
|
-
|
|
65
|
-
const res = await supertest(app)
|
|
66
|
-
.post("/auth/login")
|
|
67
|
-
.send({email: "notAdmin@example.com", password: "password"});
|
|
68
|
-
assert.equal(res.status, 200, `login ${i} should be under the auth cap`);
|
|
69
|
-
}
|
|
84
|
+
await loginUpToAuthMax(app);
|
|
70
85
|
const limited = await supertest(app)
|
|
71
86
|
.post("/auth/login")
|
|
72
87
|
.send({email: "notAdmin@example.com", password: "password"});
|