@terreno/api 0.26.0 → 0.27.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/dist/__tests__/openApiCompat.test.js +8 -2
- package/dist/actions.openApi.test.js +1 -0
- package/dist/actions.test.js +1 -0
- package/dist/api.arrayOperations.test.js +1 -0
- package/dist/api.coverage.test.d.ts +1 -0
- package/dist/api.coverage.test.js +191 -0
- package/dist/api.errorPaths.test.d.ts +1 -0
- package/dist/api.errorPaths.test.js +278 -0
- package/dist/api.errors.test.js +1 -0
- package/dist/api.hooks.test.js +1 -0
- package/dist/api.js +160 -167
- package/dist/api.query.test.js +1 -0
- package/dist/api.test.js +1 -0
- package/dist/auth.js +1 -0
- package/dist/auth.test.js +122 -0
- package/dist/betterAuthSetup.js +1 -0
- package/dist/betterAuthSetup.test.js +1 -0
- package/dist/configuration.test.js +1 -0
- package/dist/configurationApp.js +1 -0
- package/dist/configurationPlugin.test.js +80 -0
- package/dist/consentApp.test.js +1 -0
- package/dist/docLoader.js +1 -3
- package/dist/envConfigurationPlugin.js +1 -0
- package/dist/example.js +3 -2
- package/dist/expressServer.test.js +1 -0
- package/dist/githubAuth.js +2 -0
- package/dist/githubAuth.test.js +1 -0
- package/dist/logger.test.js +107 -0
- package/dist/openApi.test.js +1 -0
- package/dist/openApiBuilder.js +2 -1
- package/dist/openApiBuilder.test.js +3 -2
- package/dist/openApiValidator.js +1 -0
- package/dist/openApiValidator.test.js +41 -0
- package/dist/permissions.middleware.test.js +1 -0
- package/dist/permissions.test.js +1 -0
- package/dist/plugins.js +8 -0
- package/dist/plugins.test.js +1 -0
- package/dist/populate.js +4 -2
- package/dist/populate.test.js +1 -0
- package/dist/realtime/realtime.test.js +13 -3
- package/dist/realtime/types.d.ts +1 -1
- package/dist/requestContext.test.js +28 -0
- package/dist/terrenoApp.js +1 -0
- package/dist/tests/createTestData.js +11 -6
- package/dist/tests/models.js +1 -0
- package/dist/vendor/wesleytodd-openapi/lib/generate-doc.js +3 -1
- package/package.json +7 -7
- package/src/__tests__/openApiCompat.test.ts +8 -2
- package/src/actions.openApi.test.ts +1 -0
- package/src/actions.test.ts +1 -0
- package/src/api.arrayOperations.test.ts +1 -0
- package/src/api.coverage.test.ts +121 -0
- package/src/api.errorPaths.test.ts +171 -0
- package/src/api.errors.test.ts +1 -0
- package/src/api.hooks.test.ts +1 -0
- package/src/api.query.test.ts +1 -0
- package/src/api.test.ts +1 -0
- package/src/api.ts +13 -9
- package/src/auth.test.ts +91 -2
- package/src/auth.ts +6 -0
- package/src/betterAuthSetup.test.ts +1 -0
- package/src/betterAuthSetup.ts +3 -0
- package/src/configuration.test.ts +1 -0
- package/src/configurationApp.ts +2 -0
- package/src/configurationPlugin.test.ts +46 -1
- package/src/consentApp.test.ts +1 -0
- package/src/docLoader.ts +1 -2
- package/src/envConfigurationPlugin.ts +2 -0
- package/src/example.ts +3 -2
- package/src/expressServer.test.ts +1 -0
- package/src/expressServer.ts +4 -2
- package/src/githubAuth.test.ts +1 -0
- package/src/githubAuth.ts +2 -0
- package/src/logger.test.ts +78 -0
- package/src/openApi.test.ts +1 -0
- package/src/openApiBuilder.test.ts +7 -6
- package/src/openApiBuilder.ts +2 -1
- package/src/openApiValidator.test.ts +64 -0
- package/src/openApiValidator.ts +1 -0
- package/src/permissions.middleware.test.ts +1 -0
- package/src/permissions.test.ts +1 -0
- package/src/plugins.test.ts +1 -0
- package/src/plugins.ts +9 -0
- package/src/populate.test.ts +1 -0
- package/src/populate.ts +4 -2
- package/src/realtime/realtime.test.ts +13 -3
- package/src/realtime/realtimeApp.ts +1 -0
- package/src/realtime/registry.ts +1 -0
- package/src/realtime/types.ts +1 -2
- package/src/requestContext.test.ts +32 -0
- package/src/terrenoApp.ts +1 -0
- package/src/tests/createTestData.ts +11 -6
- package/src/tests/models.ts +1 -0
- package/src/vendor/wesleytodd-openapi/lib/generate-doc.js +4 -1
- package/tsconfig.json +3 -3
- /package/{types.d.ts → src/types.d.ts} +0 -0
package/src/auth.test.ts
CHANGED
|
@@ -1,12 +1,13 @@
|
|
|
1
|
+
// noExplicitAny: test mock typing
|
|
1
2
|
// biome-ignore-all lint/suspicious/noExplicitAny: test mock typing
|
|
2
|
-
import {afterEach, beforeEach, describe, expect, it, setSystemTime} from "bun:test";
|
|
3
|
+
import {afterEach, beforeEach, describe, expect, it, setSystemTime, spyOn} from "bun:test";
|
|
3
4
|
import type express from "express";
|
|
4
5
|
import type jwt from "jsonwebtoken";
|
|
5
6
|
import supertest from "supertest";
|
|
6
7
|
import type TestAgent from "supertest/lib/agent";
|
|
7
8
|
|
|
8
9
|
import {modelRouter} from "./api";
|
|
9
|
-
import {addAuthRoutes, addMeRoutes, generateTokens, setupAuth} from "./auth";
|
|
10
|
+
import {addAuthRoutes, addMeRoutes, generateTokens, setupAuth, signupUser} from "./auth";
|
|
10
11
|
import {Permissions} from "./permissions";
|
|
11
12
|
import {getCurrentRequestContext} from "./requestContext";
|
|
12
13
|
import {TerrenoApp} from "./terrenoApp";
|
|
@@ -1390,3 +1391,91 @@ describe("signup disabled", () => {
|
|
|
1390
1391
|
expect(res.status).toBe(404);
|
|
1391
1392
|
});
|
|
1392
1393
|
});
|
|
1394
|
+
|
|
1395
|
+
describe("signupUser postCreate failures", () => {
|
|
1396
|
+
it("wraps and rethrows errors thrown by user.postCreate", async () => {
|
|
1397
|
+
let saveCalled = false;
|
|
1398
|
+
const failingUser = {
|
|
1399
|
+
postCreate: async () => {
|
|
1400
|
+
throw new Error("postCreate failed");
|
|
1401
|
+
},
|
|
1402
|
+
save: async () => {
|
|
1403
|
+
saveCalled = true;
|
|
1404
|
+
},
|
|
1405
|
+
};
|
|
1406
|
+
const fakeModel = {
|
|
1407
|
+
register: async () => failingUser,
|
|
1408
|
+
} as unknown as Parameters<typeof signupUser>[0];
|
|
1409
|
+
|
|
1410
|
+
await expect(signupUser(fakeModel, "new@example.com", "password123")).rejects.toThrow(
|
|
1411
|
+
"postCreate failed"
|
|
1412
|
+
);
|
|
1413
|
+
expect(saveCalled).toBe(false);
|
|
1414
|
+
});
|
|
1415
|
+
});
|
|
1416
|
+
|
|
1417
|
+
describe("auth error paths when the user lookup fails", () => {
|
|
1418
|
+
let app: express.Application;
|
|
1419
|
+
let agent: TestAgent;
|
|
1420
|
+
let admin: {_id: {toString: () => string}};
|
|
1421
|
+
|
|
1422
|
+
beforeEach(async () => {
|
|
1423
|
+
setSystemTime();
|
|
1424
|
+
const testData = await setupTestData();
|
|
1425
|
+
admin = testData.users.admin;
|
|
1426
|
+
app = new TerrenoApp({
|
|
1427
|
+
configureApp: () => {},
|
|
1428
|
+
skipListen: true,
|
|
1429
|
+
userModel: UserModel as any,
|
|
1430
|
+
}).build();
|
|
1431
|
+
agent = supertest.agent(app);
|
|
1432
|
+
});
|
|
1433
|
+
|
|
1434
|
+
afterEach(() => {
|
|
1435
|
+
setSystemTime();
|
|
1436
|
+
});
|
|
1437
|
+
|
|
1438
|
+
it("responds with an error when userModel.findById throws during authentication", async () => {
|
|
1439
|
+
const jwtLib = (await import("jsonwebtoken")).default;
|
|
1440
|
+
const token = jwtLib.sign({id: admin._id.toString()}, process.env.TOKEN_SECRET as string, {
|
|
1441
|
+
issuer: process.env.TOKEN_ISSUER,
|
|
1442
|
+
});
|
|
1443
|
+
const findSpy = spyOn(UserModel, "findById").mockImplementation(() => {
|
|
1444
|
+
throw new Error("database unavailable");
|
|
1445
|
+
});
|
|
1446
|
+
try {
|
|
1447
|
+
const res = await agent.get("/auth/me").set("authorization", `Bearer ${token}`);
|
|
1448
|
+
expect(res.status).toBeGreaterThanOrEqual(400);
|
|
1449
|
+
} finally {
|
|
1450
|
+
findSpy.mockRestore();
|
|
1451
|
+
}
|
|
1452
|
+
});
|
|
1453
|
+
|
|
1454
|
+
it("calls next(err) when the local login strategy errors", async () => {
|
|
1455
|
+
type Authenticator = (
|
|
1456
|
+
username: string,
|
|
1457
|
+
password: string,
|
|
1458
|
+
done: (err: Error | null) => void
|
|
1459
|
+
) => void;
|
|
1460
|
+
const authSpy = spyOn(
|
|
1461
|
+
UserModel as unknown as {authenticate: () => Authenticator},
|
|
1462
|
+
"authenticate"
|
|
1463
|
+
).mockReturnValue((_username, _password, done) => {
|
|
1464
|
+
done(new Error("strategy failure"));
|
|
1465
|
+
});
|
|
1466
|
+
try {
|
|
1467
|
+
const errApp = new TerrenoApp({
|
|
1468
|
+
configureApp: () => {},
|
|
1469
|
+
skipListen: true,
|
|
1470
|
+
userModel: UserModel as any,
|
|
1471
|
+
}).build();
|
|
1472
|
+
const errAgent = supertest.agent(errApp);
|
|
1473
|
+
const res = await errAgent
|
|
1474
|
+
.post("/auth/login")
|
|
1475
|
+
.send({email: "notAdmin@example.com", password: "password"});
|
|
1476
|
+
expect(res.status).toBeGreaterThanOrEqual(400);
|
|
1477
|
+
} finally {
|
|
1478
|
+
authSpy.mockRestore();
|
|
1479
|
+
}
|
|
1480
|
+
});
|
|
1481
|
+
});
|
package/src/auth.ts
CHANGED
|
@@ -41,12 +41,16 @@ export interface UserModel extends Model<User> {
|
|
|
41
41
|
// Allows additional setup during signup. This will be passed the rest of req.body from the signup
|
|
42
42
|
postCreate?: (body: Record<string, unknown>) => Promise<void>;
|
|
43
43
|
|
|
44
|
+
// noExplicitAny: passport-local-mongoose return types are untyped
|
|
44
45
|
// biome-ignore lint/suspicious/noExplicitAny: passport-local-mongoose return types are untyped
|
|
45
46
|
createStrategy(): any;
|
|
47
|
+
// noExplicitAny: passport-local-mongoose return types are untyped
|
|
46
48
|
// biome-ignore lint/suspicious/noExplicitAny: passport-local-mongoose return types are untyped
|
|
47
49
|
serializeUser(): any;
|
|
50
|
+
// noExplicitAny: passport-local-mongoose return types are untyped
|
|
48
51
|
// biome-ignore lint/suspicious/noExplicitAny: passport-local-mongoose return types are untyped
|
|
49
52
|
deserializeUser(): any;
|
|
53
|
+
// noExplicitAny: passport-local-mongoose return types are untyped
|
|
50
54
|
// biome-ignore lint/suspicious/noExplicitAny: passport-local-mongoose return types are untyped
|
|
51
55
|
findByUsername(username: string, findOpts: any): any;
|
|
52
56
|
}
|
|
@@ -107,6 +111,7 @@ export const signupUser = async (
|
|
|
107
111
|
const {email: _email, password: _password, ...bodyRest} = body ?? {};
|
|
108
112
|
|
|
109
113
|
try {
|
|
114
|
+
// noExplicitAny: passport-local-mongoose's register() is untyped
|
|
110
115
|
// biome-ignore lint/suspicious/noExplicitAny: passport-local-mongoose's register() is untyped
|
|
111
116
|
const user = await (userModel as any).register({email, ...bodyRest}, password);
|
|
112
117
|
|
|
@@ -349,6 +354,7 @@ export const setupAuth = (app: express.Application, userModel: UserModel): void
|
|
|
349
354
|
return next();
|
|
350
355
|
};
|
|
351
356
|
app.use(decodeJWTMiddleware);
|
|
357
|
+
// noExplicitAny: express 5 type for urlencoded doesn't match RequestHandler
|
|
352
358
|
// biome-ignore lint/suspicious/noExplicitAny: express 5 type for urlencoded doesn't match RequestHandler
|
|
353
359
|
app.use(express.urlencoded({extended: false}) as any);
|
|
354
360
|
};
|
package/src/betterAuthSetup.ts
CHANGED
|
@@ -27,6 +27,7 @@ export type BetterAuthInstance = ReturnType<typeof betterAuth>;
|
|
|
27
27
|
*/
|
|
28
28
|
// Minimal shape we use from the MongoDB native client returned by mongoose connection
|
|
29
29
|
export interface MongoClientLike {
|
|
30
|
+
// noExplicitAny: the MongoDB driver Db type is opaque to this layer; it is passed straight to better-auth's adapter
|
|
30
31
|
// biome-ignore lint/suspicious/noExplicitAny: the MongoDB driver Db type is opaque to this layer; it is passed straight to better-auth's adapter
|
|
31
32
|
db: () => any;
|
|
32
33
|
}
|
|
@@ -184,6 +185,7 @@ export const syncBetterAuthUser = async (
|
|
|
184
185
|
userModel: UserModel,
|
|
185
186
|
betterAuthUser: BetterAuthUser,
|
|
186
187
|
oauthProvider?: string
|
|
188
|
+
// noExplicitAny: return is a consumer-defined user document; tests inspect varied fields
|
|
187
189
|
// biome-ignore lint/suspicious/noExplicitAny: return is a consumer-defined user document; tests inspect varied fields
|
|
188
190
|
): Promise<any> => {
|
|
189
191
|
try {
|
|
@@ -217,6 +219,7 @@ export const syncBetterAuthUser = async (
|
|
|
217
219
|
|
|
218
220
|
// Use Better Auth ID as _id when it's a valid ObjectId (MongoDB adapter) so frontend IDs match
|
|
219
221
|
const useAsId = mongoose.isValidObjectId(betterAuthUser.id) ? {_id: betterAuthUser.id} : {};
|
|
222
|
+
// noExplicitAny: userModel is generic across consumers — constructor args are runtime-validated
|
|
220
223
|
// biome-ignore lint/suspicious/noExplicitAny: userModel is generic across consumers — constructor args are runtime-validated
|
|
221
224
|
const newUser = new (userModel as any)({
|
|
222
225
|
...useAsId,
|
package/src/configurationApp.ts
CHANGED
|
@@ -132,6 +132,7 @@ export type ConfigurationPostUpdateHook = (
|
|
|
132
132
|
*/
|
|
133
133
|
export interface ConfigurationAppOptions {
|
|
134
134
|
/** The Mongoose model with configurationPlugin applied. */
|
|
135
|
+
// noExplicitAny: Model<any> required for invariance — consumers pass arbitrary configuration models
|
|
135
136
|
// biome-ignore lint/suspicious/noExplicitAny: Model<any> required for invariance — consumers pass arbitrary configuration models
|
|
136
137
|
model: Model<any>;
|
|
137
138
|
/** Base path for configuration routes. Defaults to "/configuration". */
|
|
@@ -478,6 +479,7 @@ export class ConfigurationApp implements TerrenoPlugin {
|
|
|
478
479
|
* Top-level fields with subschemas become sections.
|
|
479
480
|
* Top-level scalar fields go into a "General" section.
|
|
480
481
|
*/
|
|
482
|
+
// noExplicitAny: Model<any> required for invariance with consumer-supplied configuration models
|
|
481
483
|
// biome-ignore lint/suspicious/noExplicitAny: Model<any> required for invariance with consumer-supplied configuration models
|
|
482
484
|
private buildMetadata(_model: Model<any>, schema: Schema): ConfigurationMetaResponse {
|
|
483
485
|
const sections: ConfigSectionMeta[] = [];
|
|
@@ -1,5 +1,6 @@
|
|
|
1
|
+
// noExplicitAny: test mock typing
|
|
1
2
|
// biome-ignore-all lint/suspicious/noExplicitAny: test mock typing
|
|
2
|
-
import {afterAll, beforeAll, beforeEach, describe, expect, it} from "bun:test";
|
|
3
|
+
import {afterAll, beforeAll, beforeEach, describe, expect, it, spyOn} from "bun:test";
|
|
3
4
|
import mongoose, {model, Schema} from "mongoose";
|
|
4
5
|
import type {SecretProvider} from "./configurationPlugin";
|
|
5
6
|
import {configurationPlugin, flattenToDotPaths} from "./configurationPlugin";
|
|
@@ -322,6 +323,50 @@ describe("configurationPlugin", () => {
|
|
|
322
323
|
await expect(duplicate.save()).rejects.toThrow();
|
|
323
324
|
});
|
|
324
325
|
|
|
326
|
+
it("re-fetches the existing singleton when a concurrent create hits a 409", async () => {
|
|
327
|
+
if (!dbConnected) {
|
|
328
|
+
return;
|
|
329
|
+
}
|
|
330
|
+
const existing = (await SimpleConfigModel.getConfig()) as {_id: {toString(): string}};
|
|
331
|
+
// Simulate a race: the initial lookup misses, so getConfig attempts a create
|
|
332
|
+
// that the pre-save singleton guard rejects with a 409. getConfig should then
|
|
333
|
+
// re-fetch and return the document created by the "other process".
|
|
334
|
+
const spy = spyOn(SimpleConfigModel, "findOneOrNone").mockResolvedValueOnce(null);
|
|
335
|
+
try {
|
|
336
|
+
const config = (await SimpleConfigModel.getConfig()) as {_id: {toString(): string}};
|
|
337
|
+
expect(config._id.toString()).toBe(existing._id.toString());
|
|
338
|
+
} finally {
|
|
339
|
+
spy.mockRestore();
|
|
340
|
+
}
|
|
341
|
+
});
|
|
342
|
+
|
|
343
|
+
it("rethrows non-409 errors raised while creating the singleton", async () => {
|
|
344
|
+
if (!dbConnected) {
|
|
345
|
+
return;
|
|
346
|
+
}
|
|
347
|
+
const findSpy = spyOn(SimpleConfigModel, "findOneOrNone").mockResolvedValueOnce(null);
|
|
348
|
+
const saveSpy = spyOn(SimpleConfigModel.prototype, "save").mockRejectedValueOnce(
|
|
349
|
+
new Error("unexpected save failure")
|
|
350
|
+
);
|
|
351
|
+
try {
|
|
352
|
+
await expect(SimpleConfigModel.getConfig()).rejects.toThrow("unexpected save failure");
|
|
353
|
+
} finally {
|
|
354
|
+
findSpy.mockRestore();
|
|
355
|
+
saveSpy.mockRestore();
|
|
356
|
+
}
|
|
357
|
+
});
|
|
358
|
+
|
|
359
|
+
it("returns undefined for a dotted key that traverses a non-object value", async () => {
|
|
360
|
+
if (!dbConnected) {
|
|
361
|
+
return;
|
|
362
|
+
}
|
|
363
|
+
await SimpleConfigModel.getConfig();
|
|
364
|
+
// `value` is a string, so descending into `value.missing` bails out.
|
|
365
|
+
expect(await SimpleConfigModel.getConfig("value.missing")).toBeUndefined();
|
|
366
|
+
// A missing top-level segment also resolves to undefined.
|
|
367
|
+
expect(await SimpleConfigModel.getConfig("nope.deeper")).toBeUndefined();
|
|
368
|
+
});
|
|
369
|
+
|
|
325
370
|
it("updates an existing document via updateConfig", async () => {
|
|
326
371
|
if (!dbConnected) {
|
|
327
372
|
return;
|
package/src/consentApp.test.ts
CHANGED
package/src/docLoader.ts
CHANGED
|
@@ -16,8 +16,7 @@ export const loadDocOr404 = async <T>(
|
|
|
16
16
|
): Promise<T> => {
|
|
17
17
|
const builtQuery = model.findById(id);
|
|
18
18
|
const populatedQuery = addPopulateToQuery(
|
|
19
|
-
|
|
20
|
-
builtQuery as any,
|
|
19
|
+
builtQuery as unknown as Parameters<typeof addPopulateToQuery>[0],
|
|
21
20
|
populatePaths
|
|
22
21
|
);
|
|
23
22
|
let data: T | null;
|
|
@@ -60,6 +60,7 @@ const mapToObject = (
|
|
|
60
60
|
|
|
61
61
|
const refreshFromDoc = async (Model: Model<unknown>): Promise<void> => {
|
|
62
62
|
try {
|
|
63
|
+
// noExplicitAny: doc shape determined by consumer schema
|
|
63
64
|
// biome-ignore lint/suspicious/noExplicitAny: doc shape determined by consumer schema
|
|
64
65
|
const doc = (await findOneOrNoneFor(Model as Model<any>, {})) as
|
|
65
66
|
| (Document & {env?: Map<string, string> | Record<string, string>})
|
|
@@ -72,6 +73,7 @@ const refreshFromDoc = async (Model: Model<unknown>): Promise<void> => {
|
|
|
72
73
|
}
|
|
73
74
|
};
|
|
74
75
|
|
|
76
|
+
// noExplicitAny: Schema generics must be loose to accept arbitrary consumer schemas
|
|
75
77
|
// biome-ignore lint/suspicious/noExplicitAny: Schema generics must be loose to accept arbitrary consumer schemas
|
|
76
78
|
export const envConfigurationPlugin = (schema: Schema<any, any, any, any>): void => {
|
|
77
79
|
schema.add({
|
package/src/example.ts
CHANGED
|
@@ -45,8 +45,9 @@ const userSchema = new Schema<User>(
|
|
|
45
45
|
{strict: "throw", toJSON: {virtuals: true}, toObject: {virtuals: true}}
|
|
46
46
|
);
|
|
47
47
|
|
|
48
|
-
|
|
49
|
-
|
|
48
|
+
userSchema.plugin(passportLocalMongoose as unknown as Parameters<typeof userSchema.plugin>[0], {
|
|
49
|
+
usernameField: "email",
|
|
50
|
+
});
|
|
50
51
|
userSchema.plugin(createdUpdatedPlugin);
|
|
51
52
|
userSchema.plugin(isDeletedPlugin);
|
|
52
53
|
userSchema.plugin(findOneOrNone);
|
package/src/expressServer.ts
CHANGED
|
@@ -171,9 +171,11 @@ export interface AuthOptions {
|
|
|
171
171
|
// noExplicitAny: user shape is provided by the consumer's User model — any preserves the loose-binding contract
|
|
172
172
|
// biome-ignore lint/suspicious/noExplicitAny: user shape is provided by the consumer's User model — any preserves the loose-binding contract
|
|
173
173
|
generateJWTPayload?: (user: any) => Record<string, unknown>;
|
|
174
|
-
//
|
|
174
|
+
// noExplicitAny: user shape is provided by the consumer's User model — any preserves the loose-binding contract
|
|
175
|
+
// biome-ignore lint/suspicious/noExplicitAny: user shape is provided by the consumer's User model — any preserves the loose-binding contract
|
|
175
176
|
generateTokenExpiration?: (user: any) => number | jwt.SignOptions["expiresIn"];
|
|
176
|
-
//
|
|
177
|
+
// noExplicitAny: user shape is provided by the consumer's User model — any preserves the loose-binding contract
|
|
178
|
+
// biome-ignore lint/suspicious/noExplicitAny: user shape is provided by the consumer's User model — any preserves the loose-binding contract
|
|
177
179
|
generateRefreshTokenExpiration?: (user: any) => number | jwt.SignOptions["expiresIn"];
|
|
178
180
|
}
|
|
179
181
|
|
package/src/githubAuth.test.ts
CHANGED
package/src/githubAuth.ts
CHANGED
|
@@ -60,6 +60,7 @@ export interface GitHubUserFields {
|
|
|
60
60
|
* userSchema.plugin(githubUserPlugin);
|
|
61
61
|
* ```
|
|
62
62
|
*/
|
|
63
|
+
// noExplicitAny: Schema generics must be loose to accept arbitrary consumer schemas
|
|
63
64
|
// biome-ignore lint/suspicious/noExplicitAny: Schema generics must be loose to accept arbitrary consumer schemas
|
|
64
65
|
export const githubUserPlugin = (schema: Schema<any, any, any, any>): void => {
|
|
65
66
|
schema.add({
|
|
@@ -89,6 +90,7 @@ export const setupGitHubAuth = (
|
|
|
89
90
|
|
|
90
91
|
passport.use(
|
|
91
92
|
"github",
|
|
93
|
+
// noExplicitAny: passport-github2's typed constructor overloads don't match passReqToCallback variant
|
|
92
94
|
// biome-ignore lint/suspicious/noExplicitAny: passport-github2's typed constructor overloads don't match passReqToCallback variant
|
|
93
95
|
new (GitHubStrategy as any)(
|
|
94
96
|
{
|
package/src/logger.test.ts
CHANGED
|
@@ -3,6 +3,7 @@ import fs from "node:fs";
|
|
|
3
3
|
import os from "node:os";
|
|
4
4
|
import path from "node:path";
|
|
5
5
|
import {Writable} from "node:stream";
|
|
6
|
+
import * as Sentry from "@sentry/bun";
|
|
6
7
|
import winston from "winston";
|
|
7
8
|
|
|
8
9
|
import {
|
|
@@ -57,6 +58,59 @@ describe("logger", () => {
|
|
|
57
58
|
});
|
|
58
59
|
});
|
|
59
60
|
|
|
61
|
+
describe("logger Sentry structured logging", () => {
|
|
62
|
+
afterEach(() => {
|
|
63
|
+
Reflect.deleteProperty(process.env, "USE_SENTRY_LOGGING");
|
|
64
|
+
});
|
|
65
|
+
|
|
66
|
+
it("forwards every level to Sentry.logger when USE_SENTRY_LOGGING is true", () => {
|
|
67
|
+
process.env.USE_SENTRY_LOGGING = "true";
|
|
68
|
+
logger.debug("sentry-debug-message");
|
|
69
|
+
logger.info("sentry-info-message");
|
|
70
|
+
logger.warn("sentry-warn-message");
|
|
71
|
+
logger.error("sentry-error-message");
|
|
72
|
+
expect(Sentry.logger?.debug).toHaveBeenCalledWith("sentry-debug-message", expect.anything());
|
|
73
|
+
expect(Sentry.logger?.info).toHaveBeenCalledWith("sentry-info-message", expect.anything());
|
|
74
|
+
expect(Sentry.logger?.warn).toHaveBeenCalledWith("sentry-warn-message", expect.anything());
|
|
75
|
+
expect(Sentry.logger?.error).toHaveBeenCalledWith("sentry-error-message", expect.anything());
|
|
76
|
+
});
|
|
77
|
+
|
|
78
|
+
it("does not forward to Sentry.logger when USE_SENTRY_LOGGING is unset", () => {
|
|
79
|
+
Reflect.deleteProperty(process.env, "USE_SENTRY_LOGGING");
|
|
80
|
+
expect(() => logger.info("no-sentry-message")).not.toThrow();
|
|
81
|
+
expect(Sentry.logger?.info).not.toHaveBeenCalledWith("no-sentry-message", expect.anything());
|
|
82
|
+
});
|
|
83
|
+
|
|
84
|
+
it("attaches terrenoRequestLog to Sentry attributes inside a request scope", () => {
|
|
85
|
+
process.env.USE_SENTRY_LOGGING = "true";
|
|
86
|
+
runWithRequestContext({requestId: "sentry-req-1", userId: "sentry-user-1"}, () => {
|
|
87
|
+
logger.info("sentry-request-scoped-message");
|
|
88
|
+
});
|
|
89
|
+
expect(Sentry.logger?.info).toHaveBeenCalledWith(
|
|
90
|
+
"sentry-request-scoped-message",
|
|
91
|
+
expect.objectContaining({
|
|
92
|
+
terrenoRequestLog: expect.objectContaining({
|
|
93
|
+
requestId: "sentry-req-1",
|
|
94
|
+
userId: "sentry-user-1",
|
|
95
|
+
}),
|
|
96
|
+
})
|
|
97
|
+
);
|
|
98
|
+
});
|
|
99
|
+
|
|
100
|
+
it("logs a caught non-Error value via Sentry.logger.error when enabled", () => {
|
|
101
|
+
process.env.USE_SENTRY_LOGGING = "true";
|
|
102
|
+
expect(() => logger.catch("plain-string-failure")).not.toThrow();
|
|
103
|
+
expect(Sentry.logger?.error).toHaveBeenCalled();
|
|
104
|
+
});
|
|
105
|
+
|
|
106
|
+
it("scoped logger catch logs a non-Error value via Sentry.logger.error when enabled", () => {
|
|
107
|
+
process.env.USE_SENTRY_LOGGING = "true";
|
|
108
|
+
const scoped = createScopedLogger({labels: {jobId: "j1"}, prefix: "[SentryScoped]"});
|
|
109
|
+
expect(() => scoped.catch("scoped-plain-failure")).not.toThrow();
|
|
110
|
+
expect(Sentry.logger?.error).toHaveBeenCalled();
|
|
111
|
+
});
|
|
112
|
+
});
|
|
113
|
+
|
|
60
114
|
describe("formatLogContextSuffix", () => {
|
|
61
115
|
it("includes request ids and sorts terrenoLabels for stable output", () => {
|
|
62
116
|
const suffix = formatLogContextSuffix({
|
|
@@ -611,4 +665,28 @@ describe("setupLogging", () => {
|
|
|
611
665
|
})
|
|
612
666
|
).not.toThrow();
|
|
613
667
|
});
|
|
668
|
+
|
|
669
|
+
it("attaches the dev JSONL transport when TERRENO_LOG_FILE forces it on", () => {
|
|
670
|
+
const originalCwd = process.cwd();
|
|
671
|
+
process.env.TERRENO_LOG_FILE = "true";
|
|
672
|
+
try {
|
|
673
|
+
process.chdir(tempDir);
|
|
674
|
+
setupLogging({disableConsoleLogging: true, disableFileLogging: true});
|
|
675
|
+
expect(fs.existsSync(path.join(tempDir, ".terreno", "logs"))).toBe(true);
|
|
676
|
+
} finally {
|
|
677
|
+
process.chdir(originalCwd);
|
|
678
|
+
Reflect.deleteProperty(process.env, "TERRENO_LOG_FILE");
|
|
679
|
+
}
|
|
680
|
+
});
|
|
681
|
+
|
|
682
|
+
it("skips the dev JSONL transport when TERRENO_LOG_FILE forces it off", () => {
|
|
683
|
+
process.env.TERRENO_LOG_FILE = "false";
|
|
684
|
+
try {
|
|
685
|
+
expect(() =>
|
|
686
|
+
setupLogging({disableConsoleLogging: true, disableFileLogging: true})
|
|
687
|
+
).not.toThrow();
|
|
688
|
+
} finally {
|
|
689
|
+
Reflect.deleteProperty(process.env, "TERRENO_LOG_FILE");
|
|
690
|
+
}
|
|
691
|
+
});
|
|
614
692
|
});
|
package/src/openApi.test.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
// noExplicitAny: test mock typing
|
|
1
2
|
// biome-ignore-all lint/suspicious/noExplicitAny: test mock typing
|
|
2
3
|
import {beforeEach, describe, expect, it} from "bun:test";
|
|
3
4
|
import type express from "express";
|
|
@@ -362,24 +363,24 @@ describe("OpenApiMiddlewareBuilder without OpenAPI", () => {
|
|
|
362
363
|
.withTags(["test"])
|
|
363
364
|
.withSummary("Test")
|
|
364
365
|
.withResponse(200, {id: {type: "string"}})
|
|
365
|
-
.build();
|
|
366
|
+
.build() as express.RequestHandler;
|
|
366
367
|
|
|
367
368
|
// Middleware should be a function
|
|
368
369
|
expect(typeof middleware).toBe("function");
|
|
369
370
|
|
|
370
371
|
// Should call next() without error
|
|
371
372
|
let nextCalled = false;
|
|
372
|
-
middleware({}, {}, () => {
|
|
373
|
+
middleware({} as express.Request, {} as express.Response, () => {
|
|
373
374
|
nextCalled = true;
|
|
374
375
|
});
|
|
375
376
|
expect(nextCalled).toBe(true);
|
|
376
377
|
});
|
|
377
378
|
|
|
378
379
|
it("build returns noop middleware when options is empty", () => {
|
|
379
|
-
const middleware = createOpenApiBuilder({}).build();
|
|
380
|
+
const middleware = createOpenApiBuilder({}).build() as express.RequestHandler;
|
|
380
381
|
|
|
381
382
|
let nextCalled = false;
|
|
382
|
-
middleware({}, {}, () => {
|
|
383
|
+
middleware({} as express.Request, {} as express.Response, () => {
|
|
383
384
|
nextCalled = true;
|
|
384
385
|
});
|
|
385
386
|
expect(nextCalled).toBe(true);
|
|
@@ -503,7 +504,7 @@ describe("OpenApiMiddlewareBuilder withValidation / buildWithSchemas", () => {
|
|
|
503
504
|
expect(result.validationEnabled).toBe(false);
|
|
504
505
|
});
|
|
505
506
|
|
|
506
|
-
it("build() returns an array
|
|
507
|
+
it("build() returns an array when validation is enabled with body and query", () => {
|
|
507
508
|
const result = createOpenApiBuilder({})
|
|
508
509
|
.withRequestBody({name: {required: true, type: "string"}})
|
|
509
510
|
.withQueryParameter("page", {type: "number"})
|
|
@@ -511,7 +512,7 @@ describe("OpenApiMiddlewareBuilder withValidation / buildWithSchemas", () => {
|
|
|
511
512
|
.build();
|
|
512
513
|
|
|
513
514
|
expect(Array.isArray(result)).toBe(true);
|
|
514
|
-
expect(result
|
|
515
|
+
expect(result).toHaveLength(3);
|
|
515
516
|
});
|
|
516
517
|
|
|
517
518
|
it("build() returns a single middleware when validation is disabled", () => {
|
package/src/openApiBuilder.ts
CHANGED
|
@@ -759,7 +759,8 @@ export class OpenApiMiddlewareBuilder {
|
|
|
759
759
|
* router.get("/users/:id", middleware, getUserHandler);
|
|
760
760
|
* ```
|
|
761
761
|
*/
|
|
762
|
-
//
|
|
762
|
+
// noExplicitAny: returns either a single RequestHandler or an array depending on validation config — callers spread or invoke
|
|
763
|
+
// biome-ignore lint/suspicious/noExplicitAny: returns either a single RequestHandler or an array depending on validation config
|
|
763
764
|
build(): any {
|
|
764
765
|
const noop: express.RequestHandler = (_a, _b, next) => next();
|
|
765
766
|
|
|
@@ -1,9 +1,12 @@
|
|
|
1
|
+
// noExplicitAny: test mock typing
|
|
1
2
|
// biome-ignore-all lint/suspicious/noExplicitAny: test mock typing
|
|
2
3
|
import {afterEach, beforeEach, describe, expect, it} from "bun:test";
|
|
3
4
|
import type {ErrorObject} from "ajv";
|
|
5
|
+
import type {NextFunction, Request, Response} from "express";
|
|
4
6
|
|
|
5
7
|
import {modelRouter} from "./api";
|
|
6
8
|
import {addAuthRoutes, setupAuth} from "./auth";
|
|
9
|
+
import type {OpenApiSchemaProperty} from "./openApiBuilder";
|
|
7
10
|
import {
|
|
8
11
|
buildQuerySchemaFromFields,
|
|
9
12
|
configureOpenApiValidator,
|
|
@@ -707,4 +710,65 @@ describe("openApiValidator", () => {
|
|
|
707
710
|
expect(getOpenApiValidatorConfig().removeAdditional).toBe(false);
|
|
708
711
|
});
|
|
709
712
|
});
|
|
713
|
+
|
|
714
|
+
describe("schema sanitization and validator caching", () => {
|
|
715
|
+
const runMiddleware = (
|
|
716
|
+
middleware: (req: Request, res: Response, next: NextFunction) => void,
|
|
717
|
+
req: Partial<Request>
|
|
718
|
+
): boolean => {
|
|
719
|
+
let nextCalled = false;
|
|
720
|
+
middleware(req as unknown as Request, {} as unknown as Response, () => {
|
|
721
|
+
nextCalled = true;
|
|
722
|
+
});
|
|
723
|
+
return nextCalled;
|
|
724
|
+
};
|
|
725
|
+
|
|
726
|
+
// An unresolvable $ref makes ajv.compile throw, so getValidator catches the error
|
|
727
|
+
// and returns null. Built via `unknown` to keep the non-standard keyword out of the
|
|
728
|
+
// typed surface (and out of the explicit-any baseline).
|
|
729
|
+
const uncompilableSchema = {
|
|
730
|
+
broken: {$ref: "#/components/schemas/DoesNotExist"},
|
|
731
|
+
} as unknown as Record<string, OpenApiSchemaProperty>;
|
|
732
|
+
|
|
733
|
+
it("maps an unrecognized mongoose type to string so the schema still compiles", () => {
|
|
734
|
+
configureOpenApiValidator();
|
|
735
|
+
|
|
736
|
+
// "buffer" is neither a valid JSON Schema type nor present in MONGOOSE_TYPE_MAP,
|
|
737
|
+
// so sanitizeSchemaForAjv falls through to the `type = "string"` branch.
|
|
738
|
+
const middleware = validateRequestBody({raw: {type: "buffer"}});
|
|
739
|
+
|
|
740
|
+
expect(
|
|
741
|
+
runMiddleware(middleware, {body: {raw: "some-string"}, method: "POST", path: "/t"})
|
|
742
|
+
).toBe(true);
|
|
743
|
+
});
|
|
744
|
+
|
|
745
|
+
it("reuses the cached validator on subsequent requests with the same schema", () => {
|
|
746
|
+
configureOpenApiValidator();
|
|
747
|
+
|
|
748
|
+
const middleware = validateRequestBody({name: {type: "string"}});
|
|
749
|
+
const req: Partial<Request> = {body: {name: "ok"}, method: "POST", path: "/t"};
|
|
750
|
+
|
|
751
|
+
// First request compiles and caches the validator; the second must hit the cache.
|
|
752
|
+
expect(runMiddleware(middleware, req)).toBe(true);
|
|
753
|
+
expect(runMiddleware(middleware, req)).toBe(true);
|
|
754
|
+
});
|
|
755
|
+
|
|
756
|
+
it("skips query validation when the schema cannot be compiled", () => {
|
|
757
|
+
configureOpenApiValidator();
|
|
758
|
+
|
|
759
|
+
const middleware = validateQueryParams(uncompilableSchema);
|
|
760
|
+
|
|
761
|
+
expect(runMiddleware(middleware, {method: "GET", path: "/t", query: {broken: "x"}})).toBe(
|
|
762
|
+
true
|
|
763
|
+
);
|
|
764
|
+
});
|
|
765
|
+
|
|
766
|
+
it("skips response validation when the schema cannot be compiled", () => {
|
|
767
|
+
configureOpenApiValidator({validateResponses: true});
|
|
768
|
+
|
|
769
|
+
const result = validateResponseData({broken: "x"}, uncompilableSchema);
|
|
770
|
+
|
|
771
|
+
expect(result.valid).toBe(true);
|
|
772
|
+
});
|
|
773
|
+
});
|
|
710
774
|
});
|
package/src/openApiValidator.ts
CHANGED
|
@@ -184,6 +184,7 @@ const getAjvInstance = (): Ajv => {
|
|
|
184
184
|
useDefaults: true,
|
|
185
185
|
validateSchema: false,
|
|
186
186
|
});
|
|
187
|
+
// noExplicitAny: ajv-formats has a known type compat issue with AJV instances
|
|
187
188
|
// biome-ignore lint/suspicious/noExplicitAny: ajv-formats has a known type compat issue with AJV instances
|
|
188
189
|
addFormats(instance as any);
|
|
189
190
|
ajvCache.set(key, instance);
|
package/src/permissions.test.ts
CHANGED
package/src/plugins.test.ts
CHANGED