@terreno/admin-backend 57.19.2 → 57.21.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude/CLAUDE.local.md +1 -1
- package/.cursor/rules/00-root.mdc +1 -1
- package/.github/copilot-instructions.md +1 -1
- package/AGENTS.md +1 -1
- package/CHANGELOG.md +443 -0
- package/biome.jsonc +1 -0
- package/dist/adminApp.d.ts +2 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.js +7 -1
- package/dist/mcpAdmin.d.ts +42 -0
- package/dist/mcpAdmin.js +212 -0
- package/e2e/smoke.ts +246 -0
- package/package.json +10 -7
- package/src/adminApp.migrations.test.ts +3 -2
- package/src/adminApp.models.test.ts +6 -3
- package/src/adminApp.test.ts +2 -2
- package/src/adminApp.ts +2 -0
- package/src/adminScriptJob.test.ts +10 -3
- package/src/adminSyncMutationAuthMismatch.test.ts +3 -2
- package/src/aggregateAdmin.test.ts +9 -5
- package/src/enrichAdminListFilters.test.ts +1 -1
- package/src/index.ts +8 -0
- package/src/mcpAdmin.test.ts +176 -0
- package/src/mcpAdmin.ts +236 -0
- package/tsconfig.typecheck.json +18 -0
package/dist/index.js
CHANGED
|
@@ -14,7 +14,7 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
|
|
|
14
14
|
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
|
|
15
15
|
};
|
|
16
16
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
17
|
-
exports.runScriptCli = exports.normalizeAdminRoutePath = exports.resolvedModelFromAdminConfig = exports.resetLegacyDeprecationWarningsForTests = exports.convertLegacyModelConfig = exports.parseAdminListFilters = exports.DocumentStorageApp = exports.collectRegisteredAdminModels = exports.collectPluginAdminContributions = exports.aggregateFromTerrenoApp = exports.aggregateAdminContributions = exports.defineAdminScriptJob = exports.ADMIN_SCRIPT_JOB_NAME = exports.adminOwnedBy = exports.AdminApp = void 0;
|
|
17
|
+
exports.runScriptCli = exports.normalizeAdminRoutePath = exports.resolvedModelFromAdminConfig = exports.mcpSignOutEverywhere = exports.mcpAdminStatements = exports.mcpAdminScripts = exports.mcpAdminModels = exports.MCP_ADMIN_GROUP = exports.resetLegacyDeprecationWarningsForTests = exports.convertLegacyModelConfig = exports.parseAdminListFilters = exports.DocumentStorageApp = exports.collectRegisteredAdminModels = exports.collectPluginAdminContributions = exports.aggregateFromTerrenoApp = exports.aggregateAdminContributions = exports.defineAdminScriptJob = exports.ADMIN_SCRIPT_JOB_NAME = exports.adminOwnedBy = exports.AdminApp = void 0;
|
|
18
18
|
var adminApp_1 = require("./adminApp");
|
|
19
19
|
Object.defineProperty(exports, "AdminApp", { enumerable: true, get: function () { return adminApp_1.AdminApp; } });
|
|
20
20
|
Object.defineProperty(exports, "adminOwnedBy", { enumerable: true, get: function () { return adminApp_1.adminOwnedBy; } });
|
|
@@ -34,6 +34,12 @@ Object.defineProperty(exports, "parseAdminListFilters", { enumerable: true, get:
|
|
|
34
34
|
var legacy_1 = require("./legacy");
|
|
35
35
|
Object.defineProperty(exports, "convertLegacyModelConfig", { enumerable: true, get: function () { return legacy_1.convertLegacyModelConfig; } });
|
|
36
36
|
Object.defineProperty(exports, "resetLegacyDeprecationWarningsForTests", { enumerable: true, get: function () { return legacy_1.resetLegacyDeprecationWarningsForTests; } });
|
|
37
|
+
var mcpAdmin_1 = require("./mcpAdmin");
|
|
38
|
+
Object.defineProperty(exports, "MCP_ADMIN_GROUP", { enumerable: true, get: function () { return mcpAdmin_1.MCP_ADMIN_GROUP; } });
|
|
39
|
+
Object.defineProperty(exports, "mcpAdminModels", { enumerable: true, get: function () { return mcpAdmin_1.mcpAdminModels; } });
|
|
40
|
+
Object.defineProperty(exports, "mcpAdminScripts", { enumerable: true, get: function () { return mcpAdmin_1.mcpAdminScripts; } });
|
|
41
|
+
Object.defineProperty(exports, "mcpAdminStatements", { enumerable: true, get: function () { return mcpAdmin_1.mcpAdminStatements; } });
|
|
42
|
+
Object.defineProperty(exports, "mcpSignOutEverywhere", { enumerable: true, get: function () { return mcpAdmin_1.mcpSignOutEverywhere; } });
|
|
37
43
|
var resolvedAdminModel_1 = require("./resolvedAdminModel");
|
|
38
44
|
Object.defineProperty(exports, "resolvedModelFromAdminConfig", { enumerable: true, get: function () { return resolvedAdminModel_1.resolvedModelFromAdminConfig; } });
|
|
39
45
|
var routePath_1 = require("./routePath");
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { type ScriptRunner } from "@terreno/api";
|
|
2
|
+
import type { AdminModelConfig, AdminScriptConfig } from "./adminApp";
|
|
3
|
+
/**
|
|
4
|
+
* RBAC statements for the MCP admin screens. Spread into `createAccess({statements})` when
|
|
5
|
+
* `AdminApp` has `accessControl`; without it the screens use `IsAdmin`.
|
|
6
|
+
*/
|
|
7
|
+
export declare const mcpAdminStatements: {
|
|
8
|
+
readonly adminMcpOAuthClient: readonly ["read", "write", "writeOwned"];
|
|
9
|
+
readonly adminMcpOAuthConnection: readonly ["read", "write", "writeOwned"];
|
|
10
|
+
readonly adminMcpRequestLog: readonly ["read", "write", "writeOwned"];
|
|
11
|
+
readonly adminMcpServiceToken: readonly ["read", "write", "writeOwned"];
|
|
12
|
+
readonly adminMcpTool: readonly ["read", "write", "writeOwned"];
|
|
13
|
+
};
|
|
14
|
+
/** Sidebar group the MCP screens share. */
|
|
15
|
+
export declare const MCP_ADMIN_GROUP = "MCP";
|
|
16
|
+
export interface McpAdminModelsOptions {
|
|
17
|
+
/** Sidebar group. Default `"MCP"`. */
|
|
18
|
+
group?: string;
|
|
19
|
+
/**
|
|
20
|
+
* Include the request log screen. Match `TerrenoApp`'s `mcpRequestLog`: the screen is empty
|
|
21
|
+
* without it. Default false, like the server option.
|
|
22
|
+
*/
|
|
23
|
+
requestLog?: boolean;
|
|
24
|
+
/**
|
|
25
|
+
* Include the tool registry screen. Match `TerrenoApp`'s `mcpToolSettings`: without it the
|
|
26
|
+
* server ignores the switches. Default false, like the server option.
|
|
27
|
+
*/
|
|
28
|
+
toolSettings?: boolean;
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* Admin screens for a Terreno MCP server: service tokens, OAuth clients, OAuth connections
|
|
32
|
+
* (token families), the request log, and the tool registry. Secret hashes are never listed, and
|
|
33
|
+
* "delete" on a token or connection revokes it instead of removing the row.
|
|
34
|
+
*/
|
|
35
|
+
export declare const mcpAdminModels: (options?: McpAdminModelsOptions) => AdminModelConfig[];
|
|
36
|
+
/**
|
|
37
|
+
* Revoke every MCP credential a user holds: OAuth connections and service tokens. Dry run counts
|
|
38
|
+
* what would be revoked.
|
|
39
|
+
*/
|
|
40
|
+
export declare const mcpSignOutEverywhere: ScriptRunner;
|
|
41
|
+
/** Admin scripts for MCP operators. Pass to `AdminApp({scripts})`. */
|
|
42
|
+
export declare const mcpAdminScripts: () => AdminScriptConfig[];
|
package/dist/mcpAdmin.js
ADDED
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.mcpAdminScripts = exports.mcpSignOutEverywhere = exports.mcpAdminModels = exports.MCP_ADMIN_GROUP = exports.mcpAdminStatements = void 0;
|
|
7
|
+
const api_1 = require("@terreno/api");
|
|
8
|
+
const mongoose_1 = __importDefault(require("mongoose"));
|
|
9
|
+
/**
|
|
10
|
+
* RBAC statements for the MCP admin screens. Spread into `createAccess({statements})` when
|
|
11
|
+
* `AdminApp` has `accessControl`; without it the screens use `IsAdmin`.
|
|
12
|
+
*/
|
|
13
|
+
exports.mcpAdminStatements = {
|
|
14
|
+
adminMcpOAuthClient: api_1.ADMIN_MODEL_ACCESS,
|
|
15
|
+
adminMcpOAuthConnection: api_1.ADMIN_MODEL_ACCESS,
|
|
16
|
+
adminMcpRequestLog: api_1.ADMIN_MODEL_ACCESS,
|
|
17
|
+
adminMcpServiceToken: api_1.ADMIN_MODEL_ACCESS,
|
|
18
|
+
adminMcpTool: api_1.ADMIN_MODEL_ACCESS,
|
|
19
|
+
};
|
|
20
|
+
/** Sidebar group the MCP screens share. */
|
|
21
|
+
exports.MCP_ADMIN_GROUP = "MCP";
|
|
22
|
+
/**
|
|
23
|
+
* Admin screens for a Terreno MCP server: service tokens, OAuth clients, OAuth connections
|
|
24
|
+
* (token families), the request log, and the tool registry. Secret hashes are never listed, and
|
|
25
|
+
* "delete" on a token or connection revokes it instead of removing the row.
|
|
26
|
+
*/
|
|
27
|
+
const mcpAdminModels = (options = {}) => {
|
|
28
|
+
const group = options.group ?? exports.MCP_ADMIN_GROUP;
|
|
29
|
+
const models = [
|
|
30
|
+
{
|
|
31
|
+
adminAccess: { resource: "adminMcpServiceToken" },
|
|
32
|
+
displayName: "MCP service tokens",
|
|
33
|
+
group,
|
|
34
|
+
hiddenFields: ["tokenHash"],
|
|
35
|
+
listFields: [
|
|
36
|
+
"name",
|
|
37
|
+
"tokenPrefix",
|
|
38
|
+
"userId",
|
|
39
|
+
"lastUsedAt",
|
|
40
|
+
"expiresAt",
|
|
41
|
+
"revokedAt",
|
|
42
|
+
"created",
|
|
43
|
+
],
|
|
44
|
+
model: api_1.McpServiceToken,
|
|
45
|
+
permissions: { create: false, delete: true, update: false },
|
|
46
|
+
routePath: "/mcp-service-tokens",
|
|
47
|
+
searchFields: ["name", "tokenPrefix"],
|
|
48
|
+
sortableFields: ["name", "created", "lastUsedAt", "expiresAt", "revokedAt"],
|
|
49
|
+
},
|
|
50
|
+
{
|
|
51
|
+
adminAccess: { resource: "adminMcpOAuthClient" },
|
|
52
|
+
displayName: "MCP OAuth clients",
|
|
53
|
+
group,
|
|
54
|
+
hiddenFields: ["clientSecretHash"],
|
|
55
|
+
listFields: [
|
|
56
|
+
"clientName",
|
|
57
|
+
"clientId",
|
|
58
|
+
"redirectUris",
|
|
59
|
+
"grantTypes",
|
|
60
|
+
"tokenEndpointAuthMethod",
|
|
61
|
+
"userId",
|
|
62
|
+
"revokedAt",
|
|
63
|
+
"created",
|
|
64
|
+
],
|
|
65
|
+
model: api_1.McpOAuthClient,
|
|
66
|
+
// Deleting a client removes its registration and revokes every token issued to it.
|
|
67
|
+
permissions: { create: false, delete: true, update: false },
|
|
68
|
+
routePath: "/mcp-oauth-clients",
|
|
69
|
+
searchFields: ["clientName", "clientId"],
|
|
70
|
+
sortableFields: ["clientName", "created", "revokedAt"],
|
|
71
|
+
},
|
|
72
|
+
{
|
|
73
|
+
adminAccess: { resource: "adminMcpOAuthConnection" },
|
|
74
|
+
displayName: "MCP OAuth connections",
|
|
75
|
+
group,
|
|
76
|
+
hiddenFields: ["accessTokenHash", "refreshTokenHash"],
|
|
77
|
+
listFields: [
|
|
78
|
+
"userId",
|
|
79
|
+
"clientId",
|
|
80
|
+
"familyId",
|
|
81
|
+
"scope",
|
|
82
|
+
"accessExpiresAt",
|
|
83
|
+
"refreshExpiresAt",
|
|
84
|
+
"rotatedAt",
|
|
85
|
+
"revokedAt",
|
|
86
|
+
"created",
|
|
87
|
+
],
|
|
88
|
+
model: api_1.McpOAuthToken,
|
|
89
|
+
// Each row is one access/refresh pair. Deleting any row revokes its whole connection.
|
|
90
|
+
permissions: { create: false, delete: true, update: false },
|
|
91
|
+
routePath: "/mcp-oauth-connections",
|
|
92
|
+
searchFields: ["clientId", "familyId"],
|
|
93
|
+
sortableFields: ["created", "accessExpiresAt", "refreshExpiresAt", "revokedAt"],
|
|
94
|
+
},
|
|
95
|
+
];
|
|
96
|
+
if (options.requestLog === true) {
|
|
97
|
+
models.push({
|
|
98
|
+
adminAccess: { resource: "adminMcpRequestLog" },
|
|
99
|
+
defaultSort: "-created",
|
|
100
|
+
displayName: "MCP request log",
|
|
101
|
+
group,
|
|
102
|
+
listFields: [
|
|
103
|
+
"created",
|
|
104
|
+
"toolName",
|
|
105
|
+
"outcome",
|
|
106
|
+
"durationMs",
|
|
107
|
+
"userId",
|
|
108
|
+
"credential",
|
|
109
|
+
"oauthClientId",
|
|
110
|
+
"serviceTokenId",
|
|
111
|
+
"errorName",
|
|
112
|
+
],
|
|
113
|
+
model: api_1.McpRequestLog,
|
|
114
|
+
permissions: { create: false, delete: false, update: false },
|
|
115
|
+
routePath: "/mcp-request-log",
|
|
116
|
+
searchFields: ["toolName", "oauthClientId", "errorName"],
|
|
117
|
+
sortableFields: ["created", "toolName", "durationMs", "outcome"],
|
|
118
|
+
});
|
|
119
|
+
}
|
|
120
|
+
if (options.toolSettings === true) {
|
|
121
|
+
models.push({
|
|
122
|
+
adminAccess: { resource: "adminMcpTool" },
|
|
123
|
+
defaultSort: "name",
|
|
124
|
+
displayName: "MCP tools",
|
|
125
|
+
group,
|
|
126
|
+
listFields: ["name", "enabled", "source", "registered", "lastRegisteredAt"],
|
|
127
|
+
model: api_1.McpToolSetting,
|
|
128
|
+
permissions: { create: false, delete: false, update: true },
|
|
129
|
+
readonlyFields: ["name", "source", "registered", "description", "lastRegisteredAt"],
|
|
130
|
+
routePath: "/mcp-tools",
|
|
131
|
+
searchFields: ["name", "description"],
|
|
132
|
+
sortableFields: ["name", "enabled", "source", "lastRegisteredAt"],
|
|
133
|
+
});
|
|
134
|
+
}
|
|
135
|
+
return models;
|
|
136
|
+
};
|
|
137
|
+
exports.mcpAdminModels = mcpAdminModels;
|
|
138
|
+
const SIGN_OUT_SCRIPT_NAME = "mcp-sign-out-everywhere";
|
|
139
|
+
const OBJECT_ID_HEX = /^[0-9a-f]{24}$/i;
|
|
140
|
+
/** Resolve the `user` argument (an id or an email) to a user id. */
|
|
141
|
+
const resolveUserId = async (value) => {
|
|
142
|
+
// Only a 24-hex-character string is an id. isValidObjectId also accepts any 12-character
|
|
143
|
+
// string, which would read a short email like "ab@gmail.com" as an id.
|
|
144
|
+
if (OBJECT_ID_HEX.test(value)) {
|
|
145
|
+
return new mongoose_1.default.Types.ObjectId(value);
|
|
146
|
+
}
|
|
147
|
+
const userModel = mongoose_1.default.models.User;
|
|
148
|
+
if (!userModel) {
|
|
149
|
+
return undefined;
|
|
150
|
+
}
|
|
151
|
+
const email = value.trim();
|
|
152
|
+
const users = await userModel
|
|
153
|
+
.find({ email: { $in: [...new Set([email, email.toLowerCase()])] } })
|
|
154
|
+
.limit(2)
|
|
155
|
+
.select({ _id: 1 })
|
|
156
|
+
.lean();
|
|
157
|
+
return users.length === 1 ? users[0]._id : undefined;
|
|
158
|
+
};
|
|
159
|
+
/**
|
|
160
|
+
* Revoke every MCP credential a user holds: OAuth connections and service tokens. Dry run counts
|
|
161
|
+
* what would be revoked.
|
|
162
|
+
*/
|
|
163
|
+
const mcpSignOutEverywhere = async (wetRun, ctx) => {
|
|
164
|
+
const value = ctx?.args.getString("user");
|
|
165
|
+
if (typeof value !== "string" || value.trim().length === 0) {
|
|
166
|
+
return { results: ["Pass --user <user id or email>."], success: false };
|
|
167
|
+
}
|
|
168
|
+
const userId = await resolveUserId(value);
|
|
169
|
+
if (!userId) {
|
|
170
|
+
return { results: [`No single user matches "${value}".`], success: false };
|
|
171
|
+
}
|
|
172
|
+
if (!wetRun) {
|
|
173
|
+
const families = await api_1.McpOAuthToken.distinct("familyId", {
|
|
174
|
+
revokedAt: { $exists: false },
|
|
175
|
+
userId,
|
|
176
|
+
});
|
|
177
|
+
const tokens = await api_1.McpServiceToken.countDocuments({ revokedAt: { $exists: false }, userId });
|
|
178
|
+
return {
|
|
179
|
+
results: [
|
|
180
|
+
`Would revoke ${families.length} OAuth connection(s) and ${tokens} service token(s) for user ${String(userId)}.`,
|
|
181
|
+
],
|
|
182
|
+
success: true,
|
|
183
|
+
};
|
|
184
|
+
}
|
|
185
|
+
const families = await api_1.McpOAuthToken.revokeAllForUser(userId);
|
|
186
|
+
const tokens = await api_1.McpServiceToken.revokeAllForUser(userId);
|
|
187
|
+
await ctx?.addLog("info", `Revoked MCP credentials for user ${String(userId)}`);
|
|
188
|
+
return {
|
|
189
|
+
results: [
|
|
190
|
+
`Revoked ${families} OAuth connection(s) and ${tokens} service token(s) for user ${String(userId)}.`,
|
|
191
|
+
],
|
|
192
|
+
success: true,
|
|
193
|
+
};
|
|
194
|
+
};
|
|
195
|
+
exports.mcpSignOutEverywhere = mcpSignOutEverywhere;
|
|
196
|
+
/** Admin scripts for MCP operators. Pass to `AdminApp({scripts})`. */
|
|
197
|
+
const mcpAdminScripts = () => [
|
|
198
|
+
{
|
|
199
|
+
args: [
|
|
200
|
+
{
|
|
201
|
+
description: "User id or email whose MCP credentials to revoke",
|
|
202
|
+
example: "someone@example.com",
|
|
203
|
+
name: "user",
|
|
204
|
+
required: true,
|
|
205
|
+
},
|
|
206
|
+
],
|
|
207
|
+
description: "Revoke every MCP OAuth connection and service token a user holds. Clients must reconnect.",
|
|
208
|
+
name: SIGN_OUT_SCRIPT_NAME,
|
|
209
|
+
runner: exports.mcpSignOutEverywhere,
|
|
210
|
+
},
|
|
211
|
+
];
|
|
212
|
+
exports.mcpAdminScripts = mcpAdminScripts;
|
package/e2e/smoke.ts
ADDED
|
@@ -0,0 +1,246 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Real-process smoke for @terreno/admin-backend. Run `bun e2e/smoke.ts` after `bun run compile`.
|
|
3
|
+
*
|
|
4
|
+
* The smoke re-runs this file with `serve` as a child process: a minimal TerrenoApp from the
|
|
5
|
+
* compiled `@terreno/api` with one `modelRouter` model that declares `admin:`, and the compiled
|
|
6
|
+
* `AdminApp`, on a free port, against `smokeMongoUri()`. The child seeds one admin user, because
|
|
7
|
+
* signup never grants admin. The parent then checks over real HTTP that the admin reads the admin
|
|
8
|
+
* config and lists the model's documents, and that a signed-up non-admin is denied both. Exits
|
|
9
|
+
* non-zero on the first failed check.
|
|
10
|
+
*/
|
|
11
|
+
import {
|
|
12
|
+
freePort,
|
|
13
|
+
type SpawnedProcess,
|
|
14
|
+
smokeMongoUri,
|
|
15
|
+
spawnUntilReady,
|
|
16
|
+
stopSmokeMongo,
|
|
17
|
+
} from "@terreno/test";
|
|
18
|
+
import type express from "express";
|
|
19
|
+
import {DateTime} from "luxon";
|
|
20
|
+
import type {Schema} from "mongoose";
|
|
21
|
+
|
|
22
|
+
const SERVE_ARG = "serve";
|
|
23
|
+
const PASSWORD = "admin-backend-smoke-password-1";
|
|
24
|
+
const WIDGET_DISPLAY_NAME = "Smoke widgets";
|
|
25
|
+
/** AdminApp mounts a model at `basePath` + its modelRouter path; the app also serves `/widgets`. */
|
|
26
|
+
const ADMIN_WIDGETS_PATH = "/admin/widgets";
|
|
27
|
+
|
|
28
|
+
interface AdminConfigModel {
|
|
29
|
+
displayName: string;
|
|
30
|
+
name: string;
|
|
31
|
+
routePath: string;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
interface SmokeWidget {
|
|
35
|
+
_id: string;
|
|
36
|
+
name: string;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Child: the compiled API with auth, one admin-enabled model, the compiled AdminApp, and a health
|
|
41
|
+
* plugin. Both packages are imported here, not at the top, so the parent process never loads
|
|
42
|
+
* them.
|
|
43
|
+
*/
|
|
44
|
+
const serve = async (): Promise<void> => {
|
|
45
|
+
const {createdUpdatedPlugin, logger, modelRouter, Permissions, TerrenoApp} = await import(
|
|
46
|
+
"@terreno/api"
|
|
47
|
+
);
|
|
48
|
+
const {AdminApp} = await import("@terreno/admin-backend");
|
|
49
|
+
const {default: mongoose} = await import("mongoose");
|
|
50
|
+
const {default: passportLocalMongoose} = await import("passport-local-mongoose");
|
|
51
|
+
|
|
52
|
+
const userSchema = new mongoose.Schema({
|
|
53
|
+
admin: {default: false, description: "Whether the user is an admin", type: Boolean},
|
|
54
|
+
email: {description: "Sign-in email", type: String},
|
|
55
|
+
name: {description: "Display name", type: String},
|
|
56
|
+
});
|
|
57
|
+
userSchema.plugin(passportLocalMongoose as unknown as (schema: Schema, options: object) => void, {
|
|
58
|
+
usernameCaseInsensitive: true,
|
|
59
|
+
usernameField: "email",
|
|
60
|
+
});
|
|
61
|
+
userSchema.plugin(createdUpdatedPlugin);
|
|
62
|
+
const User = mongoose.model("User", userSchema);
|
|
63
|
+
|
|
64
|
+
const widgetSchema = new mongoose.Schema({
|
|
65
|
+
name: {description: "Widget name", required: true, type: String},
|
|
66
|
+
});
|
|
67
|
+
widgetSchema.plugin(createdUpdatedPlugin);
|
|
68
|
+
const Widget = mongoose.model("Widget", widgetSchema);
|
|
69
|
+
|
|
70
|
+
const widgetRouter = modelRouter("/widgets", Widget, {
|
|
71
|
+
admin: {displayName: WIDGET_DISPLAY_NAME, listFields: ["name", "created"]},
|
|
72
|
+
permissions: {
|
|
73
|
+
create: [Permissions.IsAdmin],
|
|
74
|
+
delete: [Permissions.IsAdmin],
|
|
75
|
+
list: [Permissions.IsAdmin],
|
|
76
|
+
read: [Permissions.IsAdmin],
|
|
77
|
+
update: [Permissions.IsAdmin],
|
|
78
|
+
},
|
|
79
|
+
});
|
|
80
|
+
|
|
81
|
+
const healthPlugin = {
|
|
82
|
+
register: (app: express.Application): void => {
|
|
83
|
+
app.get("/health", (_req, res) => {
|
|
84
|
+
res.json({healthy: mongoose.connection.readyState === 1});
|
|
85
|
+
});
|
|
86
|
+
},
|
|
87
|
+
};
|
|
88
|
+
|
|
89
|
+
await mongoose.connect(process.env.MONGO_URI as string);
|
|
90
|
+
await (
|
|
91
|
+
User as unknown as {register: (user: object, password: string) => Promise<unknown>}
|
|
92
|
+
).register(
|
|
93
|
+
{admin: true, email: process.env.SMOKE_ADMIN_EMAIL, name: "Smoke admin"},
|
|
94
|
+
process.env.SMOKE_ADMIN_PASSWORD as string
|
|
95
|
+
);
|
|
96
|
+
await Widget.create({name: process.env.SMOKE_WIDGET_NAME});
|
|
97
|
+
|
|
98
|
+
const app = new TerrenoApp({
|
|
99
|
+
loggingOptions: {logRequests: false},
|
|
100
|
+
userModel: User as unknown as ConstructorParameters<typeof TerrenoApp>[0]["userModel"],
|
|
101
|
+
})
|
|
102
|
+
.register(widgetRouter)
|
|
103
|
+
.register(new AdminApp({}))
|
|
104
|
+
.register(healthPlugin);
|
|
105
|
+
app.start();
|
|
106
|
+
await app.whenReady();
|
|
107
|
+
logger.info(`[adminBackendSmoke] serving on port ${process.env.PORT}`);
|
|
108
|
+
};
|
|
109
|
+
|
|
110
|
+
const expectStatus = async (res: Response, status: number, step: string): Promise<unknown> => {
|
|
111
|
+
const body = await res.text();
|
|
112
|
+
if (res.status !== status) {
|
|
113
|
+
throw new Error(`${step}: expected ${status}, got ${res.status}: ${body}`);
|
|
114
|
+
}
|
|
115
|
+
return body ? JSON.parse(body) : undefined;
|
|
116
|
+
};
|
|
117
|
+
|
|
118
|
+
const bearer = (token: string): Record<string, string> => ({
|
|
119
|
+
Authorization: `Bearer ${token}`,
|
|
120
|
+
"Content-Type": "application/json",
|
|
121
|
+
});
|
|
122
|
+
|
|
123
|
+
const signIn = async (
|
|
124
|
+
baseUrl: string,
|
|
125
|
+
route: "login" | "signup",
|
|
126
|
+
email: string
|
|
127
|
+
): Promise<string> => {
|
|
128
|
+
const res = (await expectStatus(
|
|
129
|
+
await fetch(`${baseUrl}/auth/${route}`, {
|
|
130
|
+
body: JSON.stringify({email, password: PASSWORD}),
|
|
131
|
+
headers: {"Content-Type": "application/json"},
|
|
132
|
+
method: "POST",
|
|
133
|
+
}),
|
|
134
|
+
200,
|
|
135
|
+
`POST /auth/${route}`
|
|
136
|
+
)) as {data: {token: string}};
|
|
137
|
+
return res.data.token;
|
|
138
|
+
};
|
|
139
|
+
|
|
140
|
+
/** Parent: boots the child and walks the admin read path and the non-admin denial over HTTP. */
|
|
141
|
+
const run = async (): Promise<void> => {
|
|
142
|
+
const startedAt = DateTime.now();
|
|
143
|
+
const runId = startedAt.toMillis();
|
|
144
|
+
const adminEmail = `admin-backend-smoke-admin-${runId}@example.com`;
|
|
145
|
+
const widgetName = `Smoke widget ${runId}`;
|
|
146
|
+
const port = await freePort();
|
|
147
|
+
const baseUrl = `http://127.0.0.1:${port}`;
|
|
148
|
+
let server: SpawnedProcess | undefined;
|
|
149
|
+
|
|
150
|
+
try {
|
|
151
|
+
server = await spawnUntilReady({
|
|
152
|
+
cmd: [process.execPath, __filename, SERVE_ARG],
|
|
153
|
+
env: {
|
|
154
|
+
MONGO_URI: await smokeMongoUri({databaseName: "adminBackendSmoke"}),
|
|
155
|
+
PORT: String(port),
|
|
156
|
+
REFRESH_TOKEN_SECRET: "admin-backend-smoke-refresh-secret",
|
|
157
|
+
SESSION_SECRET: "admin-backend-smoke-session-secret",
|
|
158
|
+
SMOKE_ADMIN_EMAIL: adminEmail,
|
|
159
|
+
SMOKE_ADMIN_PASSWORD: PASSWORD,
|
|
160
|
+
SMOKE_WIDGET_NAME: widgetName,
|
|
161
|
+
TOKEN_ISSUER: "admin-backend-smoke",
|
|
162
|
+
TOKEN_SECRET: "admin-backend-smoke-token-secret",
|
|
163
|
+
},
|
|
164
|
+
timeoutMs: 30000,
|
|
165
|
+
url: `${baseUrl}/health`,
|
|
166
|
+
});
|
|
167
|
+
|
|
168
|
+
const adminToken = await signIn(baseUrl, "login", adminEmail);
|
|
169
|
+
console.info("✅ POST /auth/login signs in the seeded admin");
|
|
170
|
+
|
|
171
|
+
const config = (await expectStatus(
|
|
172
|
+
await fetch(`${baseUrl}/admin/config`, {headers: bearer(adminToken)}),
|
|
173
|
+
200,
|
|
174
|
+
"GET /admin/config as admin"
|
|
175
|
+
)) as {models: AdminConfigModel[]};
|
|
176
|
+
const widgetModel = config.models.find((model) => model.displayName === WIDGET_DISPLAY_NAME);
|
|
177
|
+
if (!widgetModel) {
|
|
178
|
+
throw new Error(
|
|
179
|
+
`GET /admin/config: the "${WIDGET_DISPLAY_NAME}" model is missing: ${JSON.stringify(config.models)}`
|
|
180
|
+
);
|
|
181
|
+
}
|
|
182
|
+
if (widgetModel.routePath !== ADMIN_WIDGETS_PATH) {
|
|
183
|
+
throw new Error(
|
|
184
|
+
`GET /admin/config: expected routePath ${ADMIN_WIDGETS_PATH}, got ${widgetModel.routePath}`
|
|
185
|
+
);
|
|
186
|
+
}
|
|
187
|
+
console.info(`✅ GET /admin/config lists the ${widgetModel.name} model`);
|
|
188
|
+
|
|
189
|
+
const list = (await expectStatus(
|
|
190
|
+
await fetch(`${baseUrl}${ADMIN_WIDGETS_PATH}`, {headers: bearer(adminToken)}),
|
|
191
|
+
200,
|
|
192
|
+
`GET ${ADMIN_WIDGETS_PATH} as admin`
|
|
193
|
+
)) as {data: SmokeWidget[]};
|
|
194
|
+
if (!list.data.some((widget) => widget.name === widgetName)) {
|
|
195
|
+
throw new Error(
|
|
196
|
+
`GET ${ADMIN_WIDGETS_PATH}: the seeded widget is missing: ${JSON.stringify(list.data)}`
|
|
197
|
+
);
|
|
198
|
+
}
|
|
199
|
+
console.info(`✅ GET ${ADMIN_WIDGETS_PATH} lists the seeded widget`);
|
|
200
|
+
|
|
201
|
+
const userToken = await signIn(
|
|
202
|
+
baseUrl,
|
|
203
|
+
"signup",
|
|
204
|
+
`admin-backend-smoke-user-${runId}@example.com`
|
|
205
|
+
);
|
|
206
|
+
console.info("✅ POST /auth/signup signs in a non-admin user");
|
|
207
|
+
|
|
208
|
+
await expectStatus(
|
|
209
|
+
await fetch(`${baseUrl}/admin/config`, {headers: bearer(userToken)}),
|
|
210
|
+
403,
|
|
211
|
+
"GET /admin/config as non-admin"
|
|
212
|
+
);
|
|
213
|
+
console.info("✅ GET /admin/config returns 403 for the non-admin");
|
|
214
|
+
|
|
215
|
+
// modelRouter answers a permission denial on a CRUD route with 405, not 403.
|
|
216
|
+
await expectStatus(
|
|
217
|
+
await fetch(`${baseUrl}${ADMIN_WIDGETS_PATH}`, {headers: bearer(userToken)}),
|
|
218
|
+
405,
|
|
219
|
+
`GET ${ADMIN_WIDGETS_PATH} as non-admin`
|
|
220
|
+
);
|
|
221
|
+
console.info(`✅ GET ${ADMIN_WIDGETS_PATH} returns 405 for the non-admin`);
|
|
222
|
+
} catch (error: unknown) {
|
|
223
|
+
if (server) {
|
|
224
|
+
console.error(`--- server output ---\n${server.output()}`);
|
|
225
|
+
}
|
|
226
|
+
throw error;
|
|
227
|
+
} finally {
|
|
228
|
+
await server?.stop();
|
|
229
|
+
await stopSmokeMongo();
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
console.info(`admin-backend smoke passed in ${DateTime.now().diff(startedAt).toMillis()} ms`);
|
|
233
|
+
};
|
|
234
|
+
|
|
235
|
+
const main = process.argv[2] === SERVE_ARG ? serve : run;
|
|
236
|
+
main().then(
|
|
237
|
+
() => {
|
|
238
|
+
if (main === run) {
|
|
239
|
+
process.exit(0);
|
|
240
|
+
}
|
|
241
|
+
},
|
|
242
|
+
(error: unknown) => {
|
|
243
|
+
console.error(`❌ ${error instanceof Error ? error.message : String(error)}`);
|
|
244
|
+
process.exit(1);
|
|
245
|
+
}
|
|
246
|
+
);
|
package/package.json
CHANGED
|
@@ -5,8 +5,8 @@
|
|
|
5
5
|
},
|
|
6
6
|
"dependencies": {
|
|
7
7
|
"@google-cloud/storage": "^7.15.0",
|
|
8
|
-
"@terreno/api": "57.
|
|
9
|
-
"@terreno/jobs": "57.
|
|
8
|
+
"@terreno/api": "57.21.0",
|
|
9
|
+
"@terreno/jobs": "57.21.0",
|
|
10
10
|
"express": "^5.2.1",
|
|
11
11
|
"luxon": "^3.7.2",
|
|
12
12
|
"multer": "2.2.0"
|
|
@@ -14,12 +14,13 @@
|
|
|
14
14
|
"description": "Admin panel backend plugin for @terreno/api — part of Terreno, the batteries-included TypeScript framework for universal apps.",
|
|
15
15
|
"devDependencies": {
|
|
16
16
|
"@biomejs/biome": "^2.3.6",
|
|
17
|
-
"@terreno/test": "57.
|
|
17
|
+
"@terreno/test": "57.21.0",
|
|
18
18
|
"@types/bun": "^1.4.0",
|
|
19
19
|
"@types/express": "^5.0.6",
|
|
20
20
|
"@types/luxon": "^3.7.1",
|
|
21
21
|
"@types/multer": "^1.4.12",
|
|
22
22
|
"@types/supertest": "^7.2.0",
|
|
23
|
+
"passport-local-mongoose": "^9.0.1",
|
|
23
24
|
"supertest": "^7.2.2",
|
|
24
25
|
"typescript": "~6.0.3"
|
|
25
26
|
},
|
|
@@ -47,13 +48,15 @@
|
|
|
47
48
|
"compile": "node ../.github/scripts/compile-workspace-deps.js && bun tsc",
|
|
48
49
|
"compile:watch": "bun tsc -w",
|
|
49
50
|
"dev": "bun tsc -w",
|
|
50
|
-
"lint": "biome check ./src",
|
|
51
|
-
"lint:fix": "biome check --write ./src",
|
|
51
|
+
"lint": "biome check ./src ./e2e",
|
|
52
|
+
"lint:fix": "biome check --write ./src ./e2e",
|
|
53
|
+
"smoke": "bun e2e/smoke.ts",
|
|
52
54
|
"test": "bun test --timeout=120000",
|
|
53
55
|
"test:agent": "AGENT=1 bun test --only-failures --timeout=120000",
|
|
54
56
|
"test:ci": "bun test --timeout=120000",
|
|
55
|
-
"test:coverage": "bun run ../scripts/check-coverage.ts"
|
|
57
|
+
"test:coverage": "bun run ../scripts/check-coverage.ts",
|
|
58
|
+
"typecheck": "tsc -p tsconfig.typecheck.json"
|
|
56
59
|
},
|
|
57
60
|
"types": "dist/index.d.ts",
|
|
58
|
-
"version": "57.
|
|
61
|
+
"version": "57.21.0"
|
|
59
62
|
}
|
|
@@ -11,6 +11,7 @@ import {
|
|
|
11
11
|
createAccess,
|
|
12
12
|
MIGRATION_LOCK_ID,
|
|
13
13
|
MIGRATIONS_COLLECTION,
|
|
14
|
+
type MigrationStoreDoc,
|
|
14
15
|
setupAuth,
|
|
15
16
|
terrenoStatements,
|
|
16
17
|
type UserModel as UserModelType,
|
|
@@ -22,7 +23,7 @@ import type TestAgent from "supertest/lib/agent";
|
|
|
22
23
|
|
|
23
24
|
import {AdminApp} from "./adminApp";
|
|
24
25
|
|
|
25
|
-
const fixturesDir = join(
|
|
26
|
+
const fixturesDir = join(__dirname, "../../api/src/migrations/fixtures/valid");
|
|
26
27
|
|
|
27
28
|
const buildApp = ({
|
|
28
29
|
accessControl,
|
|
@@ -52,7 +53,7 @@ const waitForTask = (): Promise<void> => {
|
|
|
52
53
|
|
|
53
54
|
const appliedIds = async (): Promise<string[]> => {
|
|
54
55
|
const docs = await mongoose.connection
|
|
55
|
-
.collection(MIGRATIONS_COLLECTION)
|
|
56
|
+
.collection<MigrationStoreDoc>(MIGRATIONS_COLLECTION)
|
|
56
57
|
.find({_id: {$ne: MIGRATION_LOCK_ID}})
|
|
57
58
|
.project({id: 1})
|
|
58
59
|
.toArray();
|
|
@@ -34,13 +34,16 @@ import {
|
|
|
34
34
|
} from "@terreno/api/testing";
|
|
35
35
|
import {assert} from "chai";
|
|
36
36
|
import type express from "express";
|
|
37
|
-
import mongoose from "mongoose";
|
|
37
|
+
import mongoose, {type Model} from "mongoose";
|
|
38
38
|
import supertest from "supertest";
|
|
39
39
|
import type TestAgent from "supertest/lib/agent";
|
|
40
40
|
|
|
41
41
|
import type {AdminAuditEvent, AdminModelConfig, AdminOptions} from "./adminApp";
|
|
42
42
|
import {AdminApp, getArrayEmbeddedSchemaType} from "./adminApp";
|
|
43
43
|
|
|
44
|
+
/** Plugin contributions take `Model<unknown>`; the shared Food fixture keys `_id` as a string. */
|
|
45
|
+
const contributedFoodModel = FoodModel as unknown as Model<unknown>;
|
|
46
|
+
|
|
44
47
|
const buildApp = (
|
|
45
48
|
models: AdminModelConfig[] = [],
|
|
46
49
|
adminOverrides?: Partial<AdminOptions>
|
|
@@ -175,7 +178,7 @@ describe("AdminApp /admin/config", () => {
|
|
|
175
178
|
models: [
|
|
176
179
|
{
|
|
177
180
|
admin: {displayName: "Flags", listFields: ["key"]},
|
|
178
|
-
model:
|
|
181
|
+
model: contributedFoodModel,
|
|
179
182
|
routePath: "/feature-flags",
|
|
180
183
|
},
|
|
181
184
|
],
|
|
@@ -2219,7 +2222,7 @@ describe("AdminApp adminPermissions methods", () => {
|
|
|
2219
2222
|
listFields: ["name", "calories"],
|
|
2220
2223
|
searchFields: ["name"],
|
|
2221
2224
|
},
|
|
2222
|
-
model:
|
|
2225
|
+
model: contributedFoodModel,
|
|
2223
2226
|
routePath: "/locked-foods",
|
|
2224
2227
|
},
|
|
2225
2228
|
],
|
package/src/adminApp.test.ts
CHANGED
|
@@ -18,7 +18,7 @@ import mongoose from "mongoose";
|
|
|
18
18
|
import supertest from "supertest";
|
|
19
19
|
import type TestAgent from "supertest/lib/agent";
|
|
20
20
|
|
|
21
|
-
import {AdminApp} from "./adminApp";
|
|
21
|
+
import {AdminApp, type AdminScriptConfig} from "./adminApp";
|
|
22
22
|
|
|
23
23
|
const createTestScript = (overrides?: {
|
|
24
24
|
runner?: ScriptRunner;
|
|
@@ -53,7 +53,7 @@ const createFailingScript = () => ({
|
|
|
53
53
|
});
|
|
54
54
|
|
|
55
55
|
const buildApp = (
|
|
56
|
-
scripts = [createTestScript()],
|
|
56
|
+
scripts: AdminScriptConfig[] = [createTestScript()],
|
|
57
57
|
accessControl?: AnyTerrenoAccess
|
|
58
58
|
): express.Application => {
|
|
59
59
|
const app = getBaseServer();
|
package/src/adminApp.ts
CHANGED
|
@@ -123,6 +123,8 @@ export interface AdminModelConfig {
|
|
|
123
123
|
fieldOrder?: string[];
|
|
124
124
|
/** Fields to hide from admin forms/responses (e.g., password hash fields). */
|
|
125
125
|
hiddenFields?: string[];
|
|
126
|
+
/** Fields stripped from admin create and update bodies. */
|
|
127
|
+
excludeFields?: string[];
|
|
126
128
|
/** Optional sidebar / nav grouping label for schema v2 shells */
|
|
127
129
|
group?: string;
|
|
128
130
|
/** Changelist columns (defaults to listFields) */
|