@terreno/api 56.0.0-beta.0 → 56.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 +2 -122
- package/LICENSE +21 -202
- package/dist/api.d.ts +3 -2
- package/dist/auth.js +21 -25
- package/dist/betterAuthSetup.d.ts +15 -1
- package/dist/betterAuthSetup.js +4 -6
- package/dist/configurationPlugin.js +2 -2
- package/dist/expressServer.js +11 -5
- package/dist/githubAuth.js +1 -4
- package/dist/plugins.d.ts +7 -6
- package/dist/plugins.js +24 -8
- package/dist/realtime/realtimeApp.d.ts +1 -1
- package/dist/realtime/realtimeApp.js +16 -8
- package/dist/realtime/types.d.ts +14 -0
- package/dist/sync/executors.js +14 -14
- package/dist/sync/models.js +1 -1
- package/dist/sync/registry.js +1 -1
- package/dist/sync/syncSeqPlugin.js +25 -29
- package/dist/tests/models.d.ts +27 -11
- package/dist/tests/models.js +5 -3
- package/dist/tests/testHelper.d.ts +9 -3
- package/package.json +5 -6
- package/src/actions.test.ts +19 -12
- package/src/actions.ts +2 -2
- package/src/api.coverage.test.ts +7 -9
- package/src/api.errorPaths.test.ts +47 -1
- package/src/api.errors.test.ts +32 -23
- package/src/api.ts +22 -12
- package/src/auth.test.ts +251 -1
- package/src/auth.ts +25 -23
- package/src/betterAuthSetup.ts +7 -7
- package/src/configuration.test.ts +59 -38
- package/src/configurationPlugin.test.ts +72 -42
- package/src/configurationPlugin.ts +2 -2
- package/src/consentApp.test.ts +12 -12
- package/src/expressServer.ts +11 -5
- package/src/githubAuth.ts +1 -3
- package/src/middleware.test.ts +16 -0
- package/src/models/versionConfig.ts +1 -1
- package/src/openApiBuilder.test.ts +24 -9
- package/src/openApiValidator.test.ts +41 -0
- package/src/permissions.test.ts +35 -25
- package/src/plugins.test.ts +24 -0
- package/src/plugins.ts +29 -11
- package/src/populate.test.ts +25 -16
- package/src/realtime/realtime.test.ts +239 -0
- package/src/realtime/realtimeApp.ts +15 -8
- package/src/realtime/realtimeAppSetup.test.ts +159 -0
- package/src/realtime/types.ts +14 -0
- package/src/secretProvidersGcpClient.test.ts +66 -0
- package/src/sync/executors.ts +16 -14
- package/src/sync/models.ts +2 -1
- package/src/sync/registry.ts +1 -1
- package/src/sync/syncFrontier.test.ts +2 -2
- package/src/sync/syncSeqPlugin.ts +43 -51
- package/src/tests/models.ts +8 -6
package/src/betterAuthSetup.ts
CHANGED
|
@@ -192,6 +192,7 @@ export const createBetterAuthSessionMiddleware = (
|
|
|
192
192
|
// Loose shape used when mutating Mongoose user documents during Better Auth sync.
|
|
193
193
|
// The fields are added by the consumer's user schema (via baseUserPlugin or similar).
|
|
194
194
|
interface MutableUserDoc {
|
|
195
|
+
admin?: boolean;
|
|
195
196
|
email?: string;
|
|
196
197
|
name?: string;
|
|
197
198
|
betterAuthId?: string;
|
|
@@ -204,9 +205,7 @@ export const syncBetterAuthUser = async (
|
|
|
204
205
|
userModel: UserModel,
|
|
205
206
|
betterAuthUser: BetterAuthUser,
|
|
206
207
|
oauthProvider?: string
|
|
207
|
-
|
|
208
|
-
// biome-ignore lint/suspicious/noExplicitAny: return is a consumer-defined user document; tests inspect varied fields
|
|
209
|
-
): Promise<any> => {
|
|
208
|
+
): Promise<MutableUserDoc> => {
|
|
210
209
|
try {
|
|
211
210
|
const existingUser = (await findOneOrNoneFor(userModel, {
|
|
212
211
|
betterAuthId: betterAuthUser.id,
|
|
@@ -238,16 +237,17 @@ export const syncBetterAuthUser = async (
|
|
|
238
237
|
|
|
239
238
|
// Use Better Auth ID as _id when it's a valid ObjectId (MongoDB adapter) so frontend IDs match
|
|
240
239
|
const useAsId = mongoose.isValidObjectId(betterAuthUser.id) ? {_id: betterAuthUser.id} : {};
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
240
|
+
const UserDocumentConstructor = userModel as unknown as new (
|
|
241
|
+
doc: Record<string, unknown>
|
|
242
|
+
) => MutableUserDoc;
|
|
243
|
+
const newUser = new UserDocumentConstructor({
|
|
244
244
|
...useAsId,
|
|
245
245
|
admin: false,
|
|
246
246
|
betterAuthId: betterAuthUser.id,
|
|
247
247
|
email: betterAuthUser.email,
|
|
248
248
|
name: betterAuthUser.name || betterAuthUser.email.split("@")[0],
|
|
249
249
|
oauthProvider: oauthProvider || null,
|
|
250
|
-
})
|
|
250
|
+
});
|
|
251
251
|
await newUser.save();
|
|
252
252
|
logger.info(`Created new user from Better Auth: ${newUser.id}`);
|
|
253
253
|
return newUser;
|
|
@@ -1,15 +1,18 @@
|
|
|
1
|
-
// noExplicitAny: test mock typing
|
|
2
|
-
// biome-ignore-all lint/suspicious/noExplicitAny: test mock typing
|
|
3
1
|
import {beforeEach, describe, expect, it} from "bun:test";
|
|
4
2
|
import type express from "express";
|
|
5
3
|
import mongoose, {Schema} from "mongoose";
|
|
6
4
|
import supertest from "supertest";
|
|
7
5
|
import type TestAgent from "supertest/lib/agent";
|
|
8
6
|
|
|
9
|
-
import {addAuthRoutes, setupAuth} from "./auth";
|
|
10
|
-
import {
|
|
7
|
+
import {type UserModel as AuthUserModel, addAuthRoutes, setupAuth} from "./auth";
|
|
8
|
+
import {
|
|
9
|
+
ConfigurationApp,
|
|
10
|
+
type ConfigurationAppOptions,
|
|
11
|
+
type ConfigurationMetaResponse,
|
|
12
|
+
} from "./configurationApp";
|
|
11
13
|
import {type ConfigurationModel, configurationPlugin} from "./configurationPlugin";
|
|
12
14
|
import {apiErrorMiddleware, apiUnauthorizedMiddleware} from "./errors";
|
|
15
|
+
import type {PermissionMethod} from "./permissions";
|
|
13
16
|
import {createdUpdatedPlugin} from "./plugins";
|
|
14
17
|
import {authAsUser, getBaseServer, setupDb, UserModel} from "./tests";
|
|
15
18
|
|
|
@@ -92,13 +95,31 @@ const ScalarConfig = (mongoose.models.ScalarConfig ||
|
|
|
92
95
|
|
|
93
96
|
// -- Helpers --
|
|
94
97
|
|
|
98
|
+
/** APIError exposes `title`; plain errors only `message`. */
|
|
99
|
+
const errorText = (error: unknown): string => {
|
|
100
|
+
if (error && typeof error === "object" && "title" in error && typeof error.title === "string") {
|
|
101
|
+
return error.title;
|
|
102
|
+
}
|
|
103
|
+
return error instanceof Error ? error.message : String(error);
|
|
104
|
+
};
|
|
105
|
+
|
|
106
|
+
const findSection = (
|
|
107
|
+
body: ConfigurationMetaResponse,
|
|
108
|
+
name: string
|
|
109
|
+
): ConfigurationMetaResponse["sections"][number] | undefined =>
|
|
110
|
+
body.sections.find((s) => s.name === name);
|
|
111
|
+
|
|
112
|
+
/** Hook payloads are untyped bags of section values. */
|
|
113
|
+
const section = (payload: Record<string, unknown>, name: string): Record<string, unknown> =>
|
|
114
|
+
payload[name] as Record<string, unknown>;
|
|
115
|
+
|
|
95
116
|
const buildApp = (
|
|
96
|
-
configModel:
|
|
97
|
-
options?: Partial<Omit<
|
|
117
|
+
configModel: ConfigurationAppOptions["model"],
|
|
118
|
+
options?: Partial<Omit<ConfigurationAppOptions, "model">>
|
|
98
119
|
): express.Application => {
|
|
99
120
|
const app = getBaseServer();
|
|
100
|
-
setupAuth(app, UserModel as
|
|
101
|
-
addAuthRoutes(app, UserModel as
|
|
121
|
+
setupAuth(app, UserModel as unknown as AuthUserModel);
|
|
122
|
+
addAuthRoutes(app, UserModel as unknown as AuthUserModel);
|
|
102
123
|
|
|
103
124
|
const configApp = new ConfigurationApp({
|
|
104
125
|
model: configModel,
|
|
@@ -201,8 +222,8 @@ describe("configurationPlugin", () => {
|
|
|
201
222
|
try {
|
|
202
223
|
await TestConfig.create({});
|
|
203
224
|
throw new Error("Should have thrown");
|
|
204
|
-
} catch (error
|
|
205
|
-
expect(error
|
|
225
|
+
} catch (error) {
|
|
226
|
+
expect(errorText(error)).toInclude("Only one configuration document");
|
|
206
227
|
}
|
|
207
228
|
});
|
|
208
229
|
});
|
|
@@ -213,8 +234,8 @@ describe("configurationPlugin", () => {
|
|
|
213
234
|
try {
|
|
214
235
|
await TestConfig.deleteOne({});
|
|
215
236
|
throw new Error("Should have thrown");
|
|
216
|
-
} catch (error
|
|
217
|
-
expect(error
|
|
237
|
+
} catch (error) {
|
|
238
|
+
expect(errorText(error)).toInclude("Cannot hard-delete");
|
|
218
239
|
}
|
|
219
240
|
});
|
|
220
241
|
|
|
@@ -223,8 +244,8 @@ describe("configurationPlugin", () => {
|
|
|
223
244
|
try {
|
|
224
245
|
await TestConfig.deleteMany({});
|
|
225
246
|
throw new Error("Should have thrown");
|
|
226
|
-
} catch (error
|
|
227
|
-
expect(error
|
|
247
|
+
} catch (error) {
|
|
248
|
+
expect(errorText(error)).toInclude("Cannot hard-delete");
|
|
228
249
|
}
|
|
229
250
|
});
|
|
230
251
|
|
|
@@ -233,8 +254,8 @@ describe("configurationPlugin", () => {
|
|
|
233
254
|
try {
|
|
234
255
|
await TestConfig.findOneAndDelete({});
|
|
235
256
|
throw new Error("Should have thrown");
|
|
236
|
-
} catch (error
|
|
237
|
-
expect(error
|
|
257
|
+
} catch (error) {
|
|
258
|
+
expect(errorText(error)).toInclude("Cannot hard-delete");
|
|
238
259
|
}
|
|
239
260
|
});
|
|
240
261
|
});
|
|
@@ -295,17 +316,17 @@ describe("ConfigurationApp routes", () => {
|
|
|
295
316
|
expect(res.body.sections).toBeDefined();
|
|
296
317
|
expect(res.body.sections.length).toBeGreaterThan(0);
|
|
297
318
|
|
|
298
|
-
const generalSection = res.body
|
|
319
|
+
const generalSection = findSection(res.body, "general");
|
|
299
320
|
expect(generalSection).toBeDefined();
|
|
300
|
-
expect(generalSection
|
|
301
|
-
expect(generalSection
|
|
321
|
+
expect(generalSection?.fields.appName).toBeDefined();
|
|
322
|
+
expect(generalSection?.fields.appName.type).toBe("string");
|
|
302
323
|
});
|
|
303
324
|
|
|
304
325
|
it("marks secret fields in metadata", async () => {
|
|
305
326
|
const res = await adminAgent.get("/configuration/meta").expect(200);
|
|
306
|
-
const intSection = res.body
|
|
307
|
-
expect(intSection
|
|
308
|
-
expect(intSection
|
|
327
|
+
const intSection = findSection(res.body, "integrations");
|
|
328
|
+
expect(intSection?.fields.apiKey.secret).toBe(true);
|
|
329
|
+
expect(intSection?.fields.webhookUrl.secret).toBeFalsy();
|
|
309
330
|
});
|
|
310
331
|
|
|
311
332
|
it("returns 403 for non-admin", async () => {
|
|
@@ -326,7 +347,7 @@ describe("ConfigurationApp routes", () => {
|
|
|
326
347
|
|
|
327
348
|
it("redacts secret fields", async () => {
|
|
328
349
|
// Set a secret value first
|
|
329
|
-
await
|
|
350
|
+
await TestConfig.updateConfig({integrations: {apiKey: "super-secret-key"}});
|
|
330
351
|
const res = await adminAgent.get("/configuration").expect(200);
|
|
331
352
|
expect(res.body.data.integrations.apiKey).toBe("********");
|
|
332
353
|
expect(res.body.data.integrations.webhookUrl).toBe("https://example.com/hook");
|
|
@@ -362,7 +383,7 @@ describe("ConfigurationApp routes", () => {
|
|
|
362
383
|
expect(res.body.data.integrations.webhookUrl).toBe("https://changed.example.com");
|
|
363
384
|
|
|
364
385
|
// Confirm the raw stored document holds no secret value.
|
|
365
|
-
const stored = await
|
|
386
|
+
const stored = await TestConfig.getConfig();
|
|
366
387
|
expect(stored.integrations.apiKey).toBe("");
|
|
367
388
|
});
|
|
368
389
|
|
|
@@ -387,9 +408,9 @@ describe("ConfigurationApp routes", () => {
|
|
|
387
408
|
});
|
|
388
409
|
|
|
389
410
|
it("does not mutate the stored config document's secret fields", async () => {
|
|
390
|
-
await
|
|
411
|
+
await TestConfig.getConfig();
|
|
391
412
|
await adminAgent.post("/configuration/list-secrets").expect(200);
|
|
392
|
-
const stored = await
|
|
413
|
+
const stored = await TestConfig.getConfig();
|
|
393
414
|
// list-secrets must never write resolved values into the document.
|
|
394
415
|
expect(stored.integrations.apiKey).toBe("");
|
|
395
416
|
});
|
|
@@ -419,11 +440,11 @@ describe("ConfigurationApp with scalar fields", () => {
|
|
|
419
440
|
|
|
420
441
|
it("puts scalar fields into __root__ section", async () => {
|
|
421
442
|
const res = await adminAgent.get("/configuration/meta").expect(200);
|
|
422
|
-
const rootSection = res.body
|
|
443
|
+
const rootSection = findSection(res.body, "__root__");
|
|
423
444
|
expect(rootSection).toBeDefined();
|
|
424
|
-
expect(rootSection
|
|
425
|
-
expect(rootSection
|
|
426
|
-
expect(rootSection
|
|
445
|
+
expect(rootSection?.displayName).toBe("General");
|
|
446
|
+
expect(rootSection?.fields.siteName).toBeDefined();
|
|
447
|
+
expect(rootSection?.fields.debugMode).toBeDefined();
|
|
427
448
|
});
|
|
428
449
|
});
|
|
429
450
|
|
|
@@ -442,8 +463,8 @@ describe("ConfigurationApp with field overrides", () => {
|
|
|
442
463
|
|
|
443
464
|
it("applies widget overrides to metadata", async () => {
|
|
444
465
|
const res = await adminAgent.get("/configuration/meta").expect(200);
|
|
445
|
-
const intSection = res.body
|
|
446
|
-
expect(intSection
|
|
466
|
+
const intSection = findSection(res.body, "integrations");
|
|
467
|
+
expect(intSection?.fields.webhookUrl.widget).toBe("url");
|
|
447
468
|
});
|
|
448
469
|
});
|
|
449
470
|
|
|
@@ -453,7 +474,7 @@ describe("ConfigurationApp with custom permissions", () => {
|
|
|
453
474
|
let notAdminAgent: TestAgent;
|
|
454
475
|
|
|
455
476
|
// Terreno-style permission: any authenticated user (not just admins).
|
|
456
|
-
const isAuthenticated = (_method
|
|
477
|
+
const isAuthenticated: PermissionMethod<unknown> = (_method, user) => Boolean(user?.id);
|
|
457
478
|
|
|
458
479
|
beforeEach(async () => {
|
|
459
480
|
await setupDb();
|
|
@@ -541,13 +562,13 @@ describe("ConfigurationApp with update hooks", () => {
|
|
|
541
562
|
expect(res.body.data.general.appName).toBe("Safe");
|
|
542
563
|
expect(res.body.data.integrations.apiKey).toBe("");
|
|
543
564
|
|
|
544
|
-
const stored = await
|
|
565
|
+
const stored = await TestConfig.getConfig();
|
|
545
566
|
expect(stored.integrations.apiKey).toBe("");
|
|
546
567
|
});
|
|
547
568
|
|
|
548
569
|
it("runs postUpdate with redacted config and previous value", async () => {
|
|
549
570
|
// Seed a secret so we can confirm it is redacted in hook payloads.
|
|
550
|
-
await
|
|
571
|
+
await TestConfig.updateConfig({integrations: {apiKey: "should-not-leak"}});
|
|
551
572
|
await adminAgent
|
|
552
573
|
.patch("/configuration")
|
|
553
574
|
.send({general: {appName: "Audited"}})
|
|
@@ -555,10 +576,10 @@ describe("ConfigurationApp with update hooks", () => {
|
|
|
555
576
|
|
|
556
577
|
expect(postUpdateCalls).toHaveLength(1);
|
|
557
578
|
const {config, prev} = postUpdateCalls[0];
|
|
558
|
-
expect((config
|
|
579
|
+
expect(section(config, "general").appName).toBe("Audited");
|
|
559
580
|
// Secret values must be redacted in both payloads.
|
|
560
|
-
expect((config
|
|
561
|
-
expect((prev
|
|
581
|
+
expect(section(config, "integrations").apiKey).toBe("********");
|
|
582
|
+
expect(section(prev, "integrations").apiKey).toBe("********");
|
|
562
583
|
expect(JSON.stringify(postUpdateCalls)).not.toContain("should-not-leak");
|
|
563
584
|
});
|
|
564
585
|
});
|
|
@@ -1,10 +1,12 @@
|
|
|
1
|
-
// noExplicitAny: test mock typing
|
|
2
|
-
// biome-ignore-all lint/suspicious/noExplicitAny: test mock typing
|
|
3
1
|
import {afterAll, beforeAll, beforeEach, describe, expect, it, spyOn} from "bun:test";
|
|
4
2
|
import mongoose, {model, Schema} from "mongoose";
|
|
5
|
-
import type {SecretProvider} from "./configurationPlugin";
|
|
3
|
+
import type {ConfigurationModel, Paths, SecretProvider} from "./configurationPlugin";
|
|
6
4
|
import {configurationPlugin, flattenToDotPaths} from "./configurationPlugin";
|
|
7
|
-
import {
|
|
5
|
+
import type {APIError} from "./errors";
|
|
6
|
+
import {type FindOneOrNonePlugin, type IsDeleted, isDeletedPlugin} from "./plugins";
|
|
7
|
+
|
|
8
|
+
/** A configuration model as created by the plugin, including the findOneOrNone static it adds. */
|
|
9
|
+
type ConfigModel<T extends object> = ConfigurationModel<T> & FindOneOrNonePlugin<T>;
|
|
8
10
|
|
|
9
11
|
// --- Test schema with secret fields ---
|
|
10
12
|
|
|
@@ -57,36 +59,58 @@ const testConfigSchema = new Schema<TestConfig>({
|
|
|
57
59
|
|
|
58
60
|
testConfigSchema.plugin(configurationPlugin);
|
|
59
61
|
|
|
60
|
-
const TestConfigModel = model
|
|
62
|
+
const TestConfigModel = model<TestConfig, ConfigModel<TestConfig>>(
|
|
63
|
+
"TestConfiguration",
|
|
64
|
+
testConfigSchema
|
|
65
|
+
);
|
|
61
66
|
|
|
62
67
|
// --- Simple schema for singleton tests ---
|
|
63
68
|
|
|
64
|
-
|
|
69
|
+
interface SimpleConfig {
|
|
70
|
+
value: string;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
const simpleSchema = new Schema<SimpleConfig>({
|
|
65
74
|
value: {default: "default", description: "A value", type: String},
|
|
66
75
|
});
|
|
67
76
|
simpleSchema.plugin(configurationPlugin);
|
|
68
|
-
const SimpleConfigModel = model
|
|
77
|
+
const SimpleConfigModel = model<SimpleConfig, ConfigModel<SimpleConfig>>(
|
|
78
|
+
"SimpleConfiguration",
|
|
79
|
+
simpleSchema
|
|
80
|
+
);
|
|
69
81
|
|
|
70
82
|
// --- Schema opting into the _singleton unique index ---
|
|
71
83
|
|
|
72
|
-
const indexedSchema = new Schema({
|
|
84
|
+
const indexedSchema = new Schema<SimpleConfig>({
|
|
73
85
|
value: {default: "default", description: "A value", type: String},
|
|
74
86
|
});
|
|
75
87
|
indexedSchema.plugin(configurationPlugin, {enforceSingletonIndex: true});
|
|
76
|
-
const IndexedConfigModel = model
|
|
88
|
+
const IndexedConfigModel = model<SimpleConfig, ConfigModel<SimpleConfig>>(
|
|
89
|
+
"IndexedConfiguration",
|
|
90
|
+
indexedSchema
|
|
91
|
+
);
|
|
77
92
|
|
|
78
93
|
// --- Soft-delete-aware schema ---
|
|
79
94
|
|
|
80
|
-
|
|
95
|
+
interface SoftDeleteConfig extends SimpleConfig, IsDeleted {}
|
|
96
|
+
|
|
97
|
+
const softDeleteSchema = new Schema<SoftDeleteConfig>({
|
|
81
98
|
value: {default: "default", description: "A value", type: String},
|
|
82
99
|
});
|
|
83
100
|
softDeleteSchema.plugin(configurationPlugin);
|
|
84
101
|
softDeleteSchema.plugin(isDeletedPlugin);
|
|
85
|
-
const SoftDeleteConfigModel = model
|
|
102
|
+
const SoftDeleteConfigModel = model<SoftDeleteConfig, ConfigModel<SoftDeleteConfig>>(
|
|
103
|
+
"SoftDeleteConfiguration",
|
|
104
|
+
softDeleteSchema
|
|
105
|
+
);
|
|
86
106
|
|
|
87
107
|
// --- Schema with a validated field (enum) for runValidators coverage ---
|
|
88
108
|
|
|
89
|
-
|
|
109
|
+
interface ValidatedConfig {
|
|
110
|
+
level: string;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
const validatedSchema = new Schema<ValidatedConfig>({
|
|
90
114
|
level: {
|
|
91
115
|
default: "low",
|
|
92
116
|
description: "Severity level",
|
|
@@ -95,26 +119,25 @@ const validatedSchema = new Schema({
|
|
|
95
119
|
},
|
|
96
120
|
});
|
|
97
121
|
validatedSchema.plugin(configurationPlugin);
|
|
98
|
-
const ValidatedConfigModel = model
|
|
122
|
+
const ValidatedConfigModel = model<ValidatedConfig, ConfigModel<ValidatedConfig>>(
|
|
123
|
+
"ValidatedConfiguration",
|
|
124
|
+
validatedSchema
|
|
125
|
+
);
|
|
99
126
|
|
|
100
127
|
describe("configurationPlugin", () => {
|
|
101
128
|
describe("schema setup", () => {
|
|
102
129
|
it("does not add a _singleton index by default", () => {
|
|
103
130
|
const indexes = SimpleConfigModel.schema.indexes();
|
|
104
|
-
const singletonIndex = indexes.find(
|
|
105
|
-
([fields]: [Record<string, any>]) => fields._singleton !== undefined
|
|
106
|
-
);
|
|
131
|
+
const singletonIndex = indexes.find(([fields]) => fields._singleton !== undefined);
|
|
107
132
|
expect(singletonIndex).toBeUndefined();
|
|
108
133
|
expect(SimpleConfigModel.schema.path("_singleton")).toBeUndefined();
|
|
109
134
|
});
|
|
110
135
|
|
|
111
136
|
it("adds a _singleton field with unique index when enforceSingletonIndex is true", () => {
|
|
112
137
|
const indexes = IndexedConfigModel.schema.indexes();
|
|
113
|
-
const singletonIndex = indexes.find(
|
|
114
|
-
([fields]: [Record<string, any>]) => fields._singleton !== undefined
|
|
115
|
-
);
|
|
138
|
+
const singletonIndex = indexes.find(([fields]) => fields._singleton !== undefined);
|
|
116
139
|
expect(singletonIndex).toBeDefined();
|
|
117
|
-
expect(singletonIndex[1]
|
|
140
|
+
expect(singletonIndex?.[1]?.unique).toBe(true);
|
|
118
141
|
});
|
|
119
142
|
|
|
120
143
|
it("adds getConfig static", () => {
|
|
@@ -137,22 +160,22 @@ describe("configurationPlugin", () => {
|
|
|
137
160
|
describe("getSecretFields", () => {
|
|
138
161
|
it("discovers top-level secret fields", () => {
|
|
139
162
|
const secrets = TestConfigModel.getSecretFields();
|
|
140
|
-
const apiKeySecret = secrets.find((s
|
|
163
|
+
const apiKeySecret = secrets.find((s) => s.path === "apiKey");
|
|
141
164
|
expect(apiKeySecret).toBeDefined();
|
|
142
|
-
expect(apiKeySecret
|
|
165
|
+
expect(apiKeySecret?.secretName).toBe("ext-api-key");
|
|
143
166
|
});
|
|
144
167
|
|
|
145
168
|
it("discovers nested secret fields", () => {
|
|
146
169
|
const secrets = TestConfigModel.getSecretFields();
|
|
147
|
-
const nestedSecret = secrets.find((s
|
|
170
|
+
const nestedSecret = secrets.find((s) => s.path === "nested.secretToken");
|
|
148
171
|
expect(nestedSecret).toBeDefined();
|
|
149
|
-
expect(nestedSecret
|
|
150
|
-
expect(nestedSecret
|
|
172
|
+
expect(nestedSecret?.secretName).toBe("nested-token");
|
|
173
|
+
expect(nestedSecret?.secretProvider).toBe("vault");
|
|
151
174
|
});
|
|
152
175
|
|
|
153
176
|
it("does not include non-secret fields", () => {
|
|
154
177
|
const secrets = TestConfigModel.getSecretFields();
|
|
155
|
-
const nonSecret = secrets.find((s
|
|
178
|
+
const nonSecret = secrets.find((s) => s.path === "appName");
|
|
156
179
|
expect(nonSecret).toBeUndefined();
|
|
157
180
|
});
|
|
158
181
|
|
|
@@ -211,7 +234,7 @@ describe("configurationPlugin", () => {
|
|
|
211
234
|
});
|
|
212
235
|
|
|
213
236
|
it("passes the discovered secret version to the provider", async () => {
|
|
214
|
-
const versionedSchema = new Schema({
|
|
237
|
+
const versionedSchema = new Schema<{token: string}>({
|
|
215
238
|
token: {
|
|
216
239
|
default: "",
|
|
217
240
|
description: "Pinned secret",
|
|
@@ -222,7 +245,10 @@ describe("configurationPlugin", () => {
|
|
|
222
245
|
},
|
|
223
246
|
});
|
|
224
247
|
versionedSchema.plugin(configurationPlugin);
|
|
225
|
-
const VersionedModel = model
|
|
248
|
+
const VersionedModel = model<{token: string}, ConfigModel<{token: string}>>(
|
|
249
|
+
"VersionedConfiguration",
|
|
250
|
+
versionedSchema
|
|
251
|
+
);
|
|
226
252
|
|
|
227
253
|
const received: Array<{name: string; version?: string}> = [];
|
|
228
254
|
const provider: SecretProvider = {
|
|
@@ -311,7 +337,7 @@ describe("configurationPlugin", () => {
|
|
|
311
337
|
}
|
|
312
338
|
const first = await SimpleConfigModel.getConfig();
|
|
313
339
|
const second = await SimpleConfigModel.getConfig();
|
|
314
|
-
expect(first._id
|
|
340
|
+
expect(String(first._id)).toBe(String(second._id));
|
|
315
341
|
});
|
|
316
342
|
|
|
317
343
|
it("prevents creating a second document via save", async () => {
|
|
@@ -327,14 +353,14 @@ describe("configurationPlugin", () => {
|
|
|
327
353
|
if (!dbConnected) {
|
|
328
354
|
return;
|
|
329
355
|
}
|
|
330
|
-
const existing =
|
|
356
|
+
const existing = await SimpleConfigModel.getConfig();
|
|
331
357
|
// Simulate a race: the initial lookup misses, so getConfig attempts a create
|
|
332
358
|
// that the pre-save singleton guard rejects with a 409. getConfig should then
|
|
333
359
|
// re-fetch and return the document created by the "other process".
|
|
334
360
|
const spy = spyOn(SimpleConfigModel, "findOneOrNone").mockResolvedValueOnce(null);
|
|
335
361
|
try {
|
|
336
|
-
const config =
|
|
337
|
-
expect(config._id
|
|
362
|
+
const config = await SimpleConfigModel.getConfig();
|
|
363
|
+
expect(String(config._id)).toBe(String(existing._id));
|
|
338
364
|
} finally {
|
|
339
365
|
spy.mockRestore();
|
|
340
366
|
}
|
|
@@ -362,9 +388,13 @@ describe("configurationPlugin", () => {
|
|
|
362
388
|
}
|
|
363
389
|
await SimpleConfigModel.getConfig();
|
|
364
390
|
// `value` is a string, so descending into `value.missing` bails out.
|
|
365
|
-
expect(
|
|
391
|
+
expect(
|
|
392
|
+
await SimpleConfigModel.getConfig("value.missing" as Paths<SimpleConfig>)
|
|
393
|
+
).toBeUndefined();
|
|
366
394
|
// A missing top-level segment also resolves to undefined.
|
|
367
|
-
expect(
|
|
395
|
+
expect(
|
|
396
|
+
await SimpleConfigModel.getConfig("nope.deeper" as Paths<SimpleConfig>)
|
|
397
|
+
).toBeUndefined();
|
|
368
398
|
});
|
|
369
399
|
|
|
370
400
|
it("updates an existing document via updateConfig", async () => {
|
|
@@ -411,8 +441,8 @@ describe("configurationPlugin", () => {
|
|
|
411
441
|
try {
|
|
412
442
|
await SimpleConfigModel.deleteOne({}).exec();
|
|
413
443
|
expect.unreachable("Should have thrown");
|
|
414
|
-
} catch (err
|
|
415
|
-
expect(err.title).toMatch(/Cannot hard-delete the configuration document/);
|
|
444
|
+
} catch (err) {
|
|
445
|
+
expect((err as APIError).title).toMatch(/Cannot hard-delete the configuration document/);
|
|
416
446
|
}
|
|
417
447
|
});
|
|
418
448
|
|
|
@@ -424,8 +454,8 @@ describe("configurationPlugin", () => {
|
|
|
424
454
|
try {
|
|
425
455
|
await SimpleConfigModel.findOneAndDelete({}).exec();
|
|
426
456
|
expect.unreachable("Should have thrown");
|
|
427
|
-
} catch (err
|
|
428
|
-
expect(err.title).toMatch(/Cannot hard-delete the configuration document/);
|
|
457
|
+
} catch (err) {
|
|
458
|
+
expect((err as APIError).title).toMatch(/Cannot hard-delete the configuration document/);
|
|
429
459
|
}
|
|
430
460
|
});
|
|
431
461
|
|
|
@@ -437,8 +467,8 @@ describe("configurationPlugin", () => {
|
|
|
437
467
|
try {
|
|
438
468
|
await SimpleConfigModel.deleteMany({}).exec();
|
|
439
469
|
expect.unreachable("Should have thrown");
|
|
440
|
-
} catch (err
|
|
441
|
-
expect(err.title).toMatch(/Cannot hard-delete the configuration document/);
|
|
470
|
+
} catch (err) {
|
|
471
|
+
expect((err as APIError).title).toMatch(/Cannot hard-delete the configuration document/);
|
|
442
472
|
}
|
|
443
473
|
});
|
|
444
474
|
});
|
|
@@ -496,7 +526,7 @@ describe("configurationPlugin", () => {
|
|
|
496
526
|
// A new non-deleted singleton can now be created
|
|
497
527
|
const second = await SoftDeleteConfigModel.getConfig();
|
|
498
528
|
expect(second.deleted).toBe(false);
|
|
499
|
-
expect(second._id
|
|
529
|
+
expect(String(second._id)).not.toBe(String(first._id));
|
|
500
530
|
});
|
|
501
531
|
|
|
502
532
|
it("does not let updateConfig touch a soft-deleted document", async () => {
|
|
@@ -511,7 +541,7 @@ describe("configurationPlugin", () => {
|
|
|
511
541
|
const updated = await SoftDeleteConfigModel.updateConfig({value: "fresh"});
|
|
512
542
|
expect(updated.deleted).toBe(false);
|
|
513
543
|
expect(updated.value).toBe("fresh");
|
|
514
|
-
expect(updated._id
|
|
544
|
+
expect(String(updated._id)).not.toBe(String(first._id));
|
|
515
545
|
});
|
|
516
546
|
});
|
|
517
547
|
});
|
|
@@ -344,7 +344,7 @@ export const configurationPlugin = (schema: Schema, options?: ConfigurationPlugi
|
|
|
344
344
|
const updated = await this.findOneAndUpdate(
|
|
345
345
|
singletonFilter,
|
|
346
346
|
{$set: setFields},
|
|
347
|
-
{
|
|
347
|
+
{returnDocument: "after", runValidators: true}
|
|
348
348
|
);
|
|
349
349
|
if (updated) {
|
|
350
350
|
return updated;
|
|
@@ -356,7 +356,7 @@ export const configurationPlugin = (schema: Schema, options?: ConfigurationPlugi
|
|
|
356
356
|
return this.findOneAndUpdate(
|
|
357
357
|
singletonFilter,
|
|
358
358
|
{$set: setFields},
|
|
359
|
-
{
|
|
359
|
+
{returnDocument: "after", runValidators: true}
|
|
360
360
|
).orFail();
|
|
361
361
|
};
|
|
362
362
|
|
package/src/consentApp.test.ts
CHANGED
|
@@ -1,26 +1,27 @@
|
|
|
1
|
-
// noExplicitAny: test mock typing
|
|
2
|
-
// biome-ignore-all lint/suspicious/noExplicitAny: test mock typing
|
|
3
1
|
import {afterEach, beforeEach, describe, expect, it} from "bun:test";
|
|
4
2
|
import type express from "express";
|
|
3
|
+
import type {HydratedDocument} from "mongoose";
|
|
5
4
|
import supertest from "supertest";
|
|
6
5
|
import type TestAgent from "supertest/lib/agent";
|
|
7
|
-
import {
|
|
6
|
+
import type {UserModel as UserMongooseModel} from "./auth";
|
|
7
|
+
import {ConsentApp, type ConsentAppOptions} from "./consentApp";
|
|
8
8
|
import {ConsentForm} from "./models/consentForm";
|
|
9
9
|
import {ConsentResponse} from "./models/consentResponse";
|
|
10
10
|
import {TerrenoApp} from "./terrenoApp";
|
|
11
|
-
import {authAsUser, setupDb, UserModel} from "./tests";
|
|
11
|
+
import {authAsUser, setupDb, type User, UserModel} from "./tests";
|
|
12
|
+
import type {ConsentFormDocument} from "./types/consentForm";
|
|
12
13
|
|
|
13
|
-
const buildApp = (consentAppOptions = {}): express.Application =>
|
|
14
|
+
const buildApp = (consentAppOptions: ConsentAppOptions = {}): express.Application =>
|
|
14
15
|
new TerrenoApp({
|
|
15
16
|
skipListen: true,
|
|
16
|
-
userModel: UserModel as
|
|
17
|
+
userModel: UserModel as unknown as UserMongooseModel,
|
|
17
18
|
})
|
|
18
19
|
.register(new ConsentApp(consentAppOptions))
|
|
19
20
|
.build();
|
|
20
21
|
|
|
21
22
|
describe("ConsentApp", () => {
|
|
22
|
-
let admin:
|
|
23
|
-
let notAdmin:
|
|
23
|
+
let admin: HydratedDocument<User>;
|
|
24
|
+
let notAdmin: HydratedDocument<User>;
|
|
24
25
|
let adminAgent: TestAgent;
|
|
25
26
|
let userAgent: TestAgent;
|
|
26
27
|
|
|
@@ -344,8 +345,7 @@ describe("ConsentApp", () => {
|
|
|
344
345
|
|
|
345
346
|
// Build app with resolver that only returns privacy forms
|
|
346
347
|
const filteredApp = buildApp({
|
|
347
|
-
resolveConsentForms: (_user
|
|
348
|
-
forms.filter((f) => f.type === "privacy"),
|
|
348
|
+
resolveConsentForms: (_user, forms) => forms.filter((f) => f.type === "privacy"),
|
|
349
349
|
});
|
|
350
350
|
const filteredAgent = await authAsUser(filteredApp, "notAdmin");
|
|
351
351
|
|
|
@@ -367,7 +367,7 @@ describe("ConsentApp", () => {
|
|
|
367
367
|
|
|
368
368
|
// Build app with resolver that skips admin users
|
|
369
369
|
const filteredApp = buildApp({
|
|
370
|
-
resolveConsentForms: (user
|
|
370
|
+
resolveConsentForms: (user, forms) => (user.admin ? [] : forms),
|
|
371
371
|
});
|
|
372
372
|
const filteredAdmin = await authAsUser(filteredApp, "admin");
|
|
373
373
|
const filteredUser = await authAsUser(filteredApp, "notAdmin");
|
|
@@ -388,7 +388,7 @@ describe("ConsentApp", () => {
|
|
|
388
388
|
});
|
|
389
389
|
|
|
390
390
|
describe("POST /consents/respond", () => {
|
|
391
|
-
let form:
|
|
391
|
+
let form: ConsentFormDocument;
|
|
392
392
|
|
|
393
393
|
beforeEach(async () => {
|
|
394
394
|
form = await ConsentForm.create({
|
package/src/expressServer.ts
CHANGED
|
@@ -7,6 +7,7 @@ import cloneDeep from "lodash/cloneDeep";
|
|
|
7
7
|
import onFinished from "on-finished";
|
|
8
8
|
import passport from "passport";
|
|
9
9
|
import type {ModelRouterOptions} from "./api";
|
|
10
|
+
import {APIError} from "./errors";
|
|
10
11
|
import {type LoggingOptions, logger} from "./logger";
|
|
11
12
|
import {sendToSlack} from "./notifiers/slackNotifier";
|
|
12
13
|
|
|
@@ -16,16 +17,16 @@ const IS_JEST = process.env.JEST_WORKER_ID !== undefined;
|
|
|
16
17
|
|
|
17
18
|
export const setupEnvironment = (): void => {
|
|
18
19
|
if (!process.env.TOKEN_ISSUER) {
|
|
19
|
-
throw new
|
|
20
|
+
throw new APIError({status: 500, title: "TOKEN_ISSUER must be set in env."});
|
|
20
21
|
}
|
|
21
22
|
if (!process.env.TOKEN_SECRET) {
|
|
22
|
-
throw new
|
|
23
|
+
throw new APIError({status: 500, title: "TOKEN_SECRET must be set."});
|
|
23
24
|
}
|
|
24
25
|
if (!process.env.REFRESH_TOKEN_SECRET) {
|
|
25
|
-
throw new
|
|
26
|
+
throw new APIError({status: 500, title: "REFRESH_TOKEN_SECRET must be set."});
|
|
26
27
|
}
|
|
27
28
|
if (!process.env.SESSION_SECRET) {
|
|
28
|
-
throw new
|
|
29
|
+
throw new APIError({status: 500, title: "SESSION_SECRET must be set."});
|
|
29
30
|
}
|
|
30
31
|
if (!process.env.TOKEN_EXPIRES_IN && !IS_JEST) {
|
|
31
32
|
logger.warn("TOKEN_EXPIRES_IN is not set so using default.");
|
|
@@ -190,7 +191,12 @@ export const cronjob = (
|
|
|
190
191
|
try {
|
|
191
192
|
new cron.CronJob(cronSchedule, callback, null, true, "America/Chicago");
|
|
192
193
|
} catch (error) {
|
|
193
|
-
throw new
|
|
194
|
+
throw new APIError({
|
|
195
|
+
cause: error,
|
|
196
|
+
detail: `Failed to create cronjob ${name} with schedule ${cronSchedule}: ${error}`,
|
|
197
|
+
status: 500,
|
|
198
|
+
title: "Failed to create cronjob",
|
|
199
|
+
});
|
|
194
200
|
}
|
|
195
201
|
};
|
|
196
202
|
|
package/src/githubAuth.ts
CHANGED
|
@@ -90,9 +90,7 @@ export const setupGitHubAuth = (
|
|
|
90
90
|
|
|
91
91
|
passport.use(
|
|
92
92
|
"github",
|
|
93
|
-
|
|
94
|
-
// biome-ignore lint/suspicious/noExplicitAny: passport-github2's typed constructor overloads don't match passReqToCallback variant
|
|
95
|
-
new (GitHubStrategy as any)(
|
|
93
|
+
new GitHubStrategy(
|
|
96
94
|
{
|
|
97
95
|
callbackURL: githubOptions.callbackURL,
|
|
98
96
|
clientID: githubOptions.clientId,
|