@terreno/api 0.29.0 → 0.31.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/CHANGELOG.md +2 -43
- package/LICENSE +21 -202
- package/dist/actions.js +17 -8
- package/dist/actions.openApi.test.js +1 -3
- package/dist/actions.test.js +8 -5
- package/dist/api.arrayOperations.test.js +16 -8
- package/dist/api.coverage.test.js +2 -3
- package/dist/api.d.ts +3 -2
- package/dist/api.errorPaths.test.js +608 -1
- package/dist/api.errors.test.js +9 -0
- package/dist/api.js +137 -170
- package/dist/api.query.test.js +20 -8
- package/dist/api.test.js +12 -6
- package/dist/auth.coverage.test.d.ts +1 -0
- package/dist/auth.coverage.test.js +202 -0
- package/dist/auth.test.js +159 -0
- package/dist/betterAuthSetup.d.ts +15 -1
- package/dist/betterAuthSetup.js +4 -6
- package/dist/configurationPlugin.js +2 -2
- package/dist/consentApp.test.js +1 -5
- package/dist/docLoader.js +5 -1
- package/dist/envConfigurationPlugin.d.ts +1 -1
- package/dist/envConfigurationPlugin.js +0 -2
- package/dist/errors.d.ts +14 -0
- package/dist/errors.js +24 -2
- package/dist/errors.test.js +137 -0
- package/dist/expressServer.js +11 -5
- package/dist/githubAuth.js +1 -4
- package/dist/httpClient.js +5 -1
- package/dist/openApiBuilder.test.js +0 -2
- package/dist/openApiValidator.test.js +34 -0
- package/dist/plugins.d.ts +6 -5
- package/dist/plugins.js +56 -10
- package/dist/plugins.test.js +73 -17
- package/dist/populate.test.js +9 -12
- package/dist/realtime/realtime.test.js +231 -0
- package/dist/realtime/realtimeApp.d.ts +1 -1
- package/dist/realtime/realtimeApp.js +6 -2
- package/dist/realtime/realtimeAppSetup.test.d.ts +1 -0
- package/dist/realtime/realtimeAppSetup.test.js +213 -0
- package/dist/realtime/registry.d.ts +3 -2
- 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 +4 -5
- package/src/actions.openApi.test.ts +7 -10
- package/src/actions.test.ts +27 -15
- package/src/actions.ts +21 -12
- package/src/api.arrayOperations.test.ts +16 -8
- package/src/api.coverage.test.ts +9 -10
- package/src/api.errorPaths.test.ts +360 -4
- package/src/api.errors.test.ts +12 -0
- package/src/api.query.test.ts +20 -8
- package/src/api.test.ts +12 -6
- package/src/api.ts +162 -171
- package/src/auth.coverage.test.ts +101 -0
- package/src/auth.test.ts +125 -2
- package/src/betterAuthSetup.ts +7 -7
- package/src/configurationPlugin.ts +2 -2
- package/src/consentApp.test.ts +12 -12
- package/src/docLoader.ts +6 -2
- package/src/envConfigurationPlugin.ts +2 -6
- package/src/errors.test.ts +106 -1
- package/src/errors.ts +25 -1
- package/src/expressServer.ts +11 -5
- package/src/githubAuth.ts +1 -3
- package/src/httpClient.ts +6 -2
- package/src/models/versionConfig.ts +1 -1
- package/src/openApiBuilder.test.ts +24 -9
- package/src/openApiValidator.test.ts +41 -0
- package/src/plugins.test.ts +59 -9
- package/src/plugins.ts +81 -39
- package/src/populate.test.ts +25 -16
- package/src/realtime/changeStreamWatcher.ts +8 -1
- package/src/realtime/realtime.test.ts +239 -0
- package/src/realtime/realtimeApp.ts +8 -5
- package/src/realtime/realtimeAppSetup.test.ts +161 -0
- package/src/realtime/registry.ts +3 -4
- package/src/tests/models.ts +8 -6
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
import {beforeEach, describe, expect, it, setSystemTime} from "bun:test";
|
|
2
|
+
import type express from "express";
|
|
3
|
+
import jwt from "jsonwebtoken";
|
|
4
|
+
import supertest from "supertest";
|
|
5
|
+
|
|
6
|
+
import {addAuthRoutes, addMeRoutes, setupAuth, type User, type UserModel} from "./auth";
|
|
7
|
+
import {getBaseServer, setupTestData, UserModel as TestUserModel} from "./tests";
|
|
8
|
+
|
|
9
|
+
const testUserModel = TestUserModel as unknown as UserModel;
|
|
10
|
+
|
|
11
|
+
const signTokenForId = (id: string): string =>
|
|
12
|
+
jwt.sign({id}, process.env.TOKEN_SECRET as string, {issuer: process.env.TOKEN_ISSUER});
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Builds a stand-in UserModel that reuses the real passport strategy but lets each test
|
|
16
|
+
* control what `findById` resolves to.
|
|
17
|
+
*/
|
|
18
|
+
const createStubUserModel = (overrides: Partial<UserModel>): UserModel => {
|
|
19
|
+
return {
|
|
20
|
+
createStrategy: () => testUserModel.createStrategy(),
|
|
21
|
+
findById: async () => null,
|
|
22
|
+
...overrides,
|
|
23
|
+
} as unknown as UserModel;
|
|
24
|
+
};
|
|
25
|
+
|
|
26
|
+
describe("setupAuth token extraction", () => {
|
|
27
|
+
beforeEach(async () => {
|
|
28
|
+
setSystemTime();
|
|
29
|
+
await setupTestData();
|
|
30
|
+
});
|
|
31
|
+
|
|
32
|
+
it("reads the token from the jwt cookie when no authorization header is present", async () => {
|
|
33
|
+
const app = getBaseServer();
|
|
34
|
+
const admin = await TestUserModel.findOne({email: "admin@example.com"});
|
|
35
|
+
const token = signTokenForId(String(admin?._id));
|
|
36
|
+
// Emulate cookie-parser, which consumers mount before setupAuth.
|
|
37
|
+
app.use((req: express.Request, _res: express.Response, next: express.NextFunction) => {
|
|
38
|
+
req.cookies = {jwt: token};
|
|
39
|
+
next();
|
|
40
|
+
});
|
|
41
|
+
setupAuth(app, testUserModel);
|
|
42
|
+
addMeRoutes(app, testUserModel);
|
|
43
|
+
|
|
44
|
+
const res = await supertest.agent(app).get("/auth/me").expect(200);
|
|
45
|
+
expect(res.body.data.email).toBe("admin@example.com");
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
it("logs the JWT setup message when not running in test mode", async () => {
|
|
49
|
+
const app = getBaseServer();
|
|
50
|
+
process.env.NODE_ENV = "development";
|
|
51
|
+
try {
|
|
52
|
+
setupAuth(app, testUserModel);
|
|
53
|
+
addAuthRoutes(app, testUserModel);
|
|
54
|
+
addMeRoutes(app, testUserModel);
|
|
55
|
+
const res = await supertest
|
|
56
|
+
.agent(app)
|
|
57
|
+
.post("/auth/login")
|
|
58
|
+
.send({email: "admin@example.com", password: "securePassword"})
|
|
59
|
+
.expect(200);
|
|
60
|
+
expect(res.body.data.token).toBeDefined();
|
|
61
|
+
} finally {
|
|
62
|
+
process.env.NODE_ENV = "test";
|
|
63
|
+
}
|
|
64
|
+
});
|
|
65
|
+
});
|
|
66
|
+
|
|
67
|
+
describe("addMeRoutes without a resolvable user", () => {
|
|
68
|
+
beforeEach(async () => {
|
|
69
|
+
setSystemTime();
|
|
70
|
+
await setupTestData();
|
|
71
|
+
});
|
|
72
|
+
|
|
73
|
+
it("returns 401 when the authenticated user has no id", async () => {
|
|
74
|
+
const app = getBaseServer();
|
|
75
|
+
// The anonymous user has no id, so the /me handlers cannot look it up.
|
|
76
|
+
const anonymousModel = createStubUserModel({
|
|
77
|
+
createAnonymousUser: async () => ({}) as User,
|
|
78
|
+
});
|
|
79
|
+
setupAuth(app, anonymousModel);
|
|
80
|
+
addMeRoutes(app, anonymousModel);
|
|
81
|
+
const agent = supertest
|
|
82
|
+
.agent(app)
|
|
83
|
+
.set("authorization", `Bearer ${signTokenForId("507f1f77bcf86cd799439011")}`);
|
|
84
|
+
|
|
85
|
+
await agent.get("/auth/me").expect(401);
|
|
86
|
+
await agent.patch("/auth/me").send({name: "New Name"}).expect(401);
|
|
87
|
+
});
|
|
88
|
+
|
|
89
|
+
it("returns 404 when the user cannot be found for the me routes", async () => {
|
|
90
|
+
const app = getBaseServer();
|
|
91
|
+
const admin = await TestUserModel.findOne({email: "admin@example.com"});
|
|
92
|
+
setupAuth(app, testUserModel);
|
|
93
|
+
addMeRoutes(app, createStubUserModel({}));
|
|
94
|
+
const agent = supertest
|
|
95
|
+
.agent(app)
|
|
96
|
+
.set("authorization", `Bearer ${signTokenForId(String(admin?._id))}`);
|
|
97
|
+
|
|
98
|
+
await agent.get("/auth/me").expect(404);
|
|
99
|
+
await agent.patch("/auth/me").send({name: "New Name"}).expect(404);
|
|
100
|
+
});
|
|
101
|
+
});
|
package/src/auth.test.ts
CHANGED
|
@@ -1,13 +1,21 @@
|
|
|
1
1
|
// noExplicitAny: test mock typing
|
|
2
2
|
// biome-ignore-all lint/suspicious/noExplicitAny: test mock typing
|
|
3
3
|
import {afterEach, beforeEach, describe, expect, it, setSystemTime, spyOn} from "bun:test";
|
|
4
|
-
import
|
|
4
|
+
import express from "express";
|
|
5
5
|
import type jwt from "jsonwebtoken";
|
|
6
6
|
import supertest from "supertest";
|
|
7
7
|
import type TestAgent from "supertest/lib/agent";
|
|
8
8
|
|
|
9
9
|
import {modelRouter} from "./api";
|
|
10
|
-
import {
|
|
10
|
+
import {
|
|
11
|
+
type UserModel as AuthUserModel,
|
|
12
|
+
addAuthRoutes,
|
|
13
|
+
addMeRoutes,
|
|
14
|
+
generateTokens,
|
|
15
|
+
setupAuth,
|
|
16
|
+
signupUser,
|
|
17
|
+
} from "./auth";
|
|
18
|
+
import {logger} from "./logger";
|
|
11
19
|
import {Permissions} from "./permissions";
|
|
12
20
|
import {getCurrentRequestContext} from "./requestContext";
|
|
13
21
|
import {TerrenoApp} from "./terrenoApp";
|
|
@@ -1479,3 +1487,118 @@ describe("auth error paths when the user lookup fails", () => {
|
|
|
1479
1487
|
}
|
|
1480
1488
|
});
|
|
1481
1489
|
});
|
|
1490
|
+
|
|
1491
|
+
describe("cookie based JWT extraction", () => {
|
|
1492
|
+
afterEach(() => {
|
|
1493
|
+
setSystemTime();
|
|
1494
|
+
});
|
|
1495
|
+
|
|
1496
|
+
it("authenticates /auth/me from a jwt cookie", async () => {
|
|
1497
|
+
setSystemTime();
|
|
1498
|
+
const {users} = await setupTestData();
|
|
1499
|
+
const jwtLib = (await import("jsonwebtoken")).default;
|
|
1500
|
+
const token = jwtLib.sign({id: String(users.admin._id)}, process.env.TOKEN_SECRET as string, {
|
|
1501
|
+
issuer: process.env.TOKEN_ISSUER,
|
|
1502
|
+
});
|
|
1503
|
+
const app = getBaseServer();
|
|
1504
|
+
// Stand in for cookie-parser: the extractor prefers req.cookies.jwt over the auth header.
|
|
1505
|
+
app.use((req: express.Request, _res: express.Response, next: express.NextFunction) => {
|
|
1506
|
+
req.cookies = {jwt: token};
|
|
1507
|
+
next();
|
|
1508
|
+
});
|
|
1509
|
+
setupAuth(app, UserModel as unknown as AuthUserModel);
|
|
1510
|
+
addMeRoutes(app, UserModel as unknown as AuthUserModel);
|
|
1511
|
+
|
|
1512
|
+
const res = await supertest.agent(app).get("/auth/me").expect(200);
|
|
1513
|
+
expect(res.body.data.email).toBe("admin@example.com");
|
|
1514
|
+
});
|
|
1515
|
+
});
|
|
1516
|
+
|
|
1517
|
+
describe("auth logging outside of the test environment", () => {
|
|
1518
|
+
const originalNodeEnv = process.env.NODE_ENV;
|
|
1519
|
+
|
|
1520
|
+
afterEach(() => {
|
|
1521
|
+
setSystemTime();
|
|
1522
|
+
process.env.NODE_ENV = originalNodeEnv;
|
|
1523
|
+
});
|
|
1524
|
+
|
|
1525
|
+
it("logs JWT setup and successful logins when NODE_ENV is not test", async () => {
|
|
1526
|
+
setSystemTime();
|
|
1527
|
+
await setupTestData();
|
|
1528
|
+
process.env.NODE_ENV = "development";
|
|
1529
|
+
const debugSpy = spyOn(logger, "debug");
|
|
1530
|
+
const infoSpy = spyOn(logger, "info");
|
|
1531
|
+
try {
|
|
1532
|
+
const app = getBaseServer();
|
|
1533
|
+
setupAuth(app, UserModel as unknown as AuthUserModel);
|
|
1534
|
+
addAuthRoutes(app, UserModel as unknown as AuthUserModel);
|
|
1535
|
+
|
|
1536
|
+
const res = await supertest
|
|
1537
|
+
.agent(app)
|
|
1538
|
+
.post("/auth/login")
|
|
1539
|
+
.send({email: "notAdmin@example.com", password: "password"})
|
|
1540
|
+
.expect(200);
|
|
1541
|
+
expect(res.body.data.token).toBeDefined();
|
|
1542
|
+
expect(
|
|
1543
|
+
debugSpy.mock.calls.some(([message]) =>
|
|
1544
|
+
String(message).includes("Setting up JWT Authentication")
|
|
1545
|
+
)
|
|
1546
|
+
).toBe(true);
|
|
1547
|
+
expect(
|
|
1548
|
+
infoSpy.mock.calls.some(([message]) => String(message).includes("User logged in"))
|
|
1549
|
+
).toBe(true);
|
|
1550
|
+
} finally {
|
|
1551
|
+
debugSpy.mockRestore();
|
|
1552
|
+
infoSpy.mockRestore();
|
|
1553
|
+
}
|
|
1554
|
+
});
|
|
1555
|
+
});
|
|
1556
|
+
|
|
1557
|
+
describe("/me routes with an already populated req.user", () => {
|
|
1558
|
+
const buildApp = (
|
|
1559
|
+
user: {_id?: string; id?: string} | undefined,
|
|
1560
|
+
foundUser: unknown
|
|
1561
|
+
): express.Application => {
|
|
1562
|
+
const app = express();
|
|
1563
|
+
app.use(express.json());
|
|
1564
|
+
app.use((req: express.Request, _res: express.Response, next: express.NextFunction) => {
|
|
1565
|
+
req.user = user as unknown as express.Request["user"];
|
|
1566
|
+
next();
|
|
1567
|
+
});
|
|
1568
|
+
const stubUserModel = {
|
|
1569
|
+
findById: async () => foundUser,
|
|
1570
|
+
} as unknown as AuthUserModel;
|
|
1571
|
+
addMeRoutes(app, stubUserModel);
|
|
1572
|
+
return app;
|
|
1573
|
+
};
|
|
1574
|
+
|
|
1575
|
+
it("returns 401 from GET /auth/me when the request user has no id", async () => {
|
|
1576
|
+
await supertest
|
|
1577
|
+
.agent(buildApp({_id: "abc"}, null))
|
|
1578
|
+
.get("/auth/me")
|
|
1579
|
+
.expect(401);
|
|
1580
|
+
});
|
|
1581
|
+
|
|
1582
|
+
it("returns 401 from PATCH /auth/me when the request user has no id", async () => {
|
|
1583
|
+
await supertest
|
|
1584
|
+
.agent(buildApp({_id: "abc"}, null))
|
|
1585
|
+
.patch("/auth/me")
|
|
1586
|
+
.send({name: "Updated"})
|
|
1587
|
+
.expect(401);
|
|
1588
|
+
});
|
|
1589
|
+
|
|
1590
|
+
it("returns 404 from GET /auth/me when the user record no longer exists", async () => {
|
|
1591
|
+
await supertest
|
|
1592
|
+
.agent(buildApp({id: "abc"}, null))
|
|
1593
|
+
.get("/auth/me")
|
|
1594
|
+
.expect(404);
|
|
1595
|
+
});
|
|
1596
|
+
|
|
1597
|
+
it("returns 404 from PATCH /auth/me when the user record no longer exists", async () => {
|
|
1598
|
+
await supertest
|
|
1599
|
+
.agent(buildApp({id: "abc"}, null))
|
|
1600
|
+
.patch("/auth/me")
|
|
1601
|
+
.send({name: "Updated"})
|
|
1602
|
+
.expect(404);
|
|
1603
|
+
});
|
|
1604
|
+
});
|
package/src/betterAuthSetup.ts
CHANGED
|
@@ -173,6 +173,7 @@ export const createBetterAuthSessionMiddleware = (
|
|
|
173
173
|
// Loose shape used when mutating Mongoose user documents during Better Auth sync.
|
|
174
174
|
// The fields are added by the consumer's user schema (via baseUserPlugin or similar).
|
|
175
175
|
interface MutableUserDoc {
|
|
176
|
+
admin?: boolean;
|
|
176
177
|
email?: string;
|
|
177
178
|
name?: string;
|
|
178
179
|
betterAuthId?: string;
|
|
@@ -185,9 +186,7 @@ export const syncBetterAuthUser = async (
|
|
|
185
186
|
userModel: UserModel,
|
|
186
187
|
betterAuthUser: BetterAuthUser,
|
|
187
188
|
oauthProvider?: string
|
|
188
|
-
|
|
189
|
-
// biome-ignore lint/suspicious/noExplicitAny: return is a consumer-defined user document; tests inspect varied fields
|
|
190
|
-
): Promise<any> => {
|
|
189
|
+
): Promise<MutableUserDoc> => {
|
|
191
190
|
try {
|
|
192
191
|
const existingUser = (await findOneOrNoneFor(userModel, {
|
|
193
192
|
betterAuthId: betterAuthUser.id,
|
|
@@ -219,16 +218,17 @@ export const syncBetterAuthUser = async (
|
|
|
219
218
|
|
|
220
219
|
// Use Better Auth ID as _id when it's a valid ObjectId (MongoDB adapter) so frontend IDs match
|
|
221
220
|
const useAsId = mongoose.isValidObjectId(betterAuthUser.id) ? {_id: betterAuthUser.id} : {};
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
221
|
+
const UserDocumentConstructor = userModel as unknown as new (
|
|
222
|
+
doc: Record<string, unknown>
|
|
223
|
+
) => MutableUserDoc;
|
|
224
|
+
const newUser = new UserDocumentConstructor({
|
|
225
225
|
...useAsId,
|
|
226
226
|
admin: false,
|
|
227
227
|
betterAuthId: betterAuthUser.id,
|
|
228
228
|
email: betterAuthUser.email,
|
|
229
229
|
name: betterAuthUser.name || betterAuthUser.email.split("@")[0],
|
|
230
230
|
oauthProvider: oauthProvider || null,
|
|
231
|
-
})
|
|
231
|
+
});
|
|
232
232
|
await newUser.save();
|
|
233
233
|
logger.info(`Created new user from Better Auth: ${newUser.id}`);
|
|
234
234
|
return newUser;
|
|
@@ -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/docLoader.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import mongoose, {type Model} from "mongoose";
|
|
2
2
|
|
|
3
3
|
import {addPopulateToQuery} from "./api";
|
|
4
|
-
import {APIError, isAPIError, NotFoundError} from "./errors";
|
|
4
|
+
import {APIError, errorDetail, isAPIError, NotFoundError} from "./errors";
|
|
5
5
|
import type {PopulatePath} from "./populate";
|
|
6
6
|
|
|
7
7
|
/**
|
|
@@ -28,7 +28,8 @@ export const loadDocOr404 = async <T>(
|
|
|
28
28
|
throw new APIError({
|
|
29
29
|
cause: error,
|
|
30
30
|
code: "get-error",
|
|
31
|
-
detail: `GET failed on ${id}`,
|
|
31
|
+
detail: `GET failed on ${id}: ${errorDetail(error)}`,
|
|
32
|
+
meta: {model: model.modelName},
|
|
32
33
|
status: 500,
|
|
33
34
|
title: "GET error",
|
|
34
35
|
});
|
|
@@ -42,6 +43,7 @@ export const loadDocOr404 = async <T>(
|
|
|
42
43
|
|
|
43
44
|
if (!hiddenDoc) {
|
|
44
45
|
throw new NotFoundError({
|
|
46
|
+
code: "document-not-found",
|
|
45
47
|
detail: notFoundDetail,
|
|
46
48
|
title: "Document not found",
|
|
47
49
|
});
|
|
@@ -58,11 +60,13 @@ export const loadDocOr404 = async <T>(
|
|
|
58
60
|
|
|
59
61
|
if (!reason) {
|
|
60
62
|
throw new NotFoundError({
|
|
63
|
+
code: "document-not-found",
|
|
61
64
|
detail: notFoundDetail,
|
|
62
65
|
title: "Document not found",
|
|
63
66
|
});
|
|
64
67
|
}
|
|
65
68
|
throw new NotFoundError({
|
|
69
|
+
code: "document-not-found",
|
|
66
70
|
detail: notFoundDetail,
|
|
67
71
|
disableExternalErrorTracking: true,
|
|
68
72
|
meta: reason,
|
|
@@ -60,9 +60,7 @@ const mapToObject = (
|
|
|
60
60
|
|
|
61
61
|
const refreshFromDoc = async (Model: Model<unknown>): Promise<void> => {
|
|
62
62
|
try {
|
|
63
|
-
|
|
64
|
-
// biome-ignore lint/suspicious/noExplicitAny: doc shape determined by consumer schema
|
|
65
|
-
const doc = (await findOneOrNoneFor(Model as Model<any>, {})) as
|
|
63
|
+
const doc = (await findOneOrNoneFor(Model, {})) as
|
|
66
64
|
| (Document & {env?: Map<string, string> | Record<string, string>})
|
|
67
65
|
| null;
|
|
68
66
|
Config.setCachedEnv(mapToObject(doc?.env));
|
|
@@ -73,9 +71,7 @@ const refreshFromDoc = async (Model: Model<unknown>): Promise<void> => {
|
|
|
73
71
|
}
|
|
74
72
|
};
|
|
75
73
|
|
|
76
|
-
|
|
77
|
-
// biome-ignore lint/suspicious/noExplicitAny: Schema generics must be loose to accept arbitrary consumer schemas
|
|
78
|
-
export const envConfigurationPlugin = (schema: Schema<any, any, any, any>): void => {
|
|
74
|
+
export const envConfigurationPlugin = (schema: Schema): void => {
|
|
79
75
|
schema.add({
|
|
80
76
|
env: {
|
|
81
77
|
default: () => new Map<string, string>(),
|
package/src/errors.test.ts
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import {beforeEach, describe, expect, it, mock, spyOn} from "bun:test";
|
|
2
2
|
import * as Sentry from "@sentry/bun";
|
|
3
|
-
import type
|
|
3
|
+
import express, {type NextFunction, type Request, type Response} from "express";
|
|
4
4
|
import mongoose, {Schema} from "mongoose";
|
|
5
|
+
import supertest from "supertest";
|
|
5
6
|
|
|
6
7
|
import {
|
|
7
8
|
APIError,
|
|
@@ -9,6 +10,7 @@ import {
|
|
|
9
10
|
apiUnauthorizedMiddleware,
|
|
10
11
|
BadRequestError,
|
|
11
12
|
ConflictError,
|
|
13
|
+
errorDetail,
|
|
12
14
|
errorMessage,
|
|
13
15
|
errorStack,
|
|
14
16
|
errorsPlugin,
|
|
@@ -422,6 +424,109 @@ describe("apiUnauthorizedMiddleware", () => {
|
|
|
422
424
|
expect(next).toHaveBeenCalledWith(err);
|
|
423
425
|
expect(res.status).not.toHaveBeenCalled();
|
|
424
426
|
});
|
|
427
|
+
|
|
428
|
+
it("forwards an APIError titled Unauthorized so it keeps its own status", () => {
|
|
429
|
+
const err = new ForbiddenError({
|
|
430
|
+
code: "org-membership-required",
|
|
431
|
+
detail: "You are not a member of this organization",
|
|
432
|
+
title: "Unauthorized",
|
|
433
|
+
});
|
|
434
|
+
apiUnauthorizedMiddleware(
|
|
435
|
+
err,
|
|
436
|
+
req,
|
|
437
|
+
res as unknown as Response,
|
|
438
|
+
next as unknown as NextFunction
|
|
439
|
+
);
|
|
440
|
+
expect(next).toHaveBeenCalledWith(err);
|
|
441
|
+
expect(res.status).not.toHaveBeenCalled();
|
|
442
|
+
});
|
|
443
|
+
|
|
444
|
+
it("forwards a plain APIError titled Unauthorized rather than rewriting it to a 401", () => {
|
|
445
|
+
const err = new APIError({status: 403, title: "Unauthorized"});
|
|
446
|
+
apiUnauthorizedMiddleware(
|
|
447
|
+
err,
|
|
448
|
+
req,
|
|
449
|
+
res as unknown as Response,
|
|
450
|
+
next as unknown as NextFunction
|
|
451
|
+
);
|
|
452
|
+
expect(next).toHaveBeenCalledWith(err);
|
|
453
|
+
expect(res.status).not.toHaveBeenCalled();
|
|
454
|
+
});
|
|
455
|
+
|
|
456
|
+
it("forwards an Error subclass whose message is Unauthorized", () => {
|
|
457
|
+
class DomainUnauthorizedError extends Error {}
|
|
458
|
+
const err = new DomainUnauthorizedError("Unauthorized");
|
|
459
|
+
apiUnauthorizedMiddleware(
|
|
460
|
+
err,
|
|
461
|
+
req,
|
|
462
|
+
res as unknown as Response,
|
|
463
|
+
next as unknown as NextFunction
|
|
464
|
+
);
|
|
465
|
+
expect(next).toHaveBeenCalledWith(err);
|
|
466
|
+
expect(res.status).not.toHaveBeenCalled();
|
|
467
|
+
});
|
|
468
|
+
});
|
|
469
|
+
|
|
470
|
+
describe("apiUnauthorizedMiddleware in the terrenoApp middleware order", () => {
|
|
471
|
+
const buildApp = (): express.Express => {
|
|
472
|
+
const app = express();
|
|
473
|
+
app.get("/forbidden", (_req, _res, next) => {
|
|
474
|
+
next(
|
|
475
|
+
new ForbiddenError({
|
|
476
|
+
code: "org-membership-required",
|
|
477
|
+
detail: "You are not a member of this organization",
|
|
478
|
+
title: "Unauthorized",
|
|
479
|
+
})
|
|
480
|
+
);
|
|
481
|
+
});
|
|
482
|
+
app.get("/passport", (_req, _res, next) => {
|
|
483
|
+
next(new Error("Unauthorized"));
|
|
484
|
+
});
|
|
485
|
+
app.use(apiUnauthorizedMiddleware);
|
|
486
|
+
app.use(apiErrorMiddleware);
|
|
487
|
+
return app;
|
|
488
|
+
};
|
|
489
|
+
|
|
490
|
+
it("keeps a 403 titled Unauthorized a 403", async () => {
|
|
491
|
+
const res = await supertest(buildApp()).get("/forbidden").expect(403);
|
|
492
|
+
expect(res.body).toEqual({
|
|
493
|
+
code: "org-membership-required",
|
|
494
|
+
detail: "You are not a member of this organization",
|
|
495
|
+
status: 403,
|
|
496
|
+
title: "Unauthorized",
|
|
497
|
+
});
|
|
498
|
+
});
|
|
499
|
+
|
|
500
|
+
it("still converts a plain Passport Unauthorized error to a 401", async () => {
|
|
501
|
+
const res = await supertest(buildApp()).get("/passport").expect(401);
|
|
502
|
+
expect(res.body).toEqual({status: 401, title: "Unauthorized"});
|
|
503
|
+
});
|
|
504
|
+
});
|
|
505
|
+
|
|
506
|
+
describe("errorDetail", () => {
|
|
507
|
+
it("combines an APIError's title and detail", () => {
|
|
508
|
+
const error = new ConflictError({
|
|
509
|
+
code: "schedule-item-staff-conflict",
|
|
510
|
+
detail: "Conflict detected for Dr. Ada on 2026-07-31",
|
|
511
|
+
title: "Conflict detected",
|
|
512
|
+
});
|
|
513
|
+
expect(errorDetail(error)).toBe(
|
|
514
|
+
"Conflict detected: Conflict detected for Dr. Ada on 2026-07-31"
|
|
515
|
+
);
|
|
516
|
+
});
|
|
517
|
+
|
|
518
|
+
it("falls back to the title when an APIError has no detail", () => {
|
|
519
|
+
expect(errorDetail(new APIError({title: "Conflict detected"}))).toBe("Conflict detected");
|
|
520
|
+
});
|
|
521
|
+
|
|
522
|
+
it("returns the message for a plain Error", () => {
|
|
523
|
+
expect(errorDetail(new Error("boom"))).toBe("boom");
|
|
524
|
+
});
|
|
525
|
+
|
|
526
|
+
it("stringifies non-Error values", () => {
|
|
527
|
+
expect(errorDetail("boom")).toBe("boom");
|
|
528
|
+
expect(errorDetail(42)).toBe("42");
|
|
529
|
+
});
|
|
425
530
|
});
|
|
426
531
|
|
|
427
532
|
describe("apiErrorMiddleware", () => {
|
package/src/errors.ts
CHANGED
|
@@ -339,6 +339,18 @@ export const errorMessage = (error: unknown): string => {
|
|
|
339
339
|
return String(error);
|
|
340
340
|
};
|
|
341
341
|
|
|
342
|
+
/**
|
|
343
|
+
* Extract the fullest human-readable text from an unknown error, for use as the `detail` of a
|
|
344
|
+
* wrapper error. An `APIError`'s `message` is exactly its `title`, so `errorMessage` alone would
|
|
345
|
+
* drop the per-occurrence text the caller put in `detail`.
|
|
346
|
+
*/
|
|
347
|
+
export const errorDetail = (error: unknown): string => {
|
|
348
|
+
if (isAPIError(error) && error.detail) {
|
|
349
|
+
return `${error.title}: ${error.detail}`;
|
|
350
|
+
}
|
|
351
|
+
return errorMessage(error);
|
|
352
|
+
};
|
|
353
|
+
|
|
342
354
|
/** Extract a stack trace string from an unknown error. */
|
|
343
355
|
export const errorStack = (error: unknown): string => {
|
|
344
356
|
if (error instanceof Error && error.stack) {
|
|
@@ -406,13 +418,25 @@ export const getAPIErrorBody = (error: APIError): Record<string, unknown> => {
|
|
|
406
418
|
return serializeAPIError(error) as unknown as Record<string, unknown>;
|
|
407
419
|
};
|
|
408
420
|
|
|
421
|
+
/**
|
|
422
|
+
* Converts the bare `Error("Unauthorized")` that Passport throws into a quiet 401.
|
|
423
|
+
*
|
|
424
|
+
* Only the plain `Error` prototype is matched. An `APIError` carries its own status, code,
|
|
425
|
+
* detail, and meta, so one whose title happens to be "Unauthorized" falls through to
|
|
426
|
+
* `apiErrorMiddleware`. A domain-specific `Error` subclass with the same message also falls
|
|
427
|
+
* through so its own handler can respond.
|
|
428
|
+
*/
|
|
409
429
|
export const apiUnauthorizedMiddleware = (
|
|
410
430
|
err: Error,
|
|
411
431
|
_req: Request,
|
|
412
432
|
res: Response,
|
|
413
433
|
next: NextFunction
|
|
414
434
|
) => {
|
|
415
|
-
if (
|
|
435
|
+
if (
|
|
436
|
+
!isAPIError(err) &&
|
|
437
|
+
err.message === "Unauthorized" &&
|
|
438
|
+
Object.getPrototypeOf(err) === Error.prototype
|
|
439
|
+
) {
|
|
416
440
|
// not using the actual APIError class here because we don't want to log it as an error.
|
|
417
441
|
res.status(401).json({status: 401, title: "Unauthorized"}).send();
|
|
418
442
|
} else {
|
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,
|
package/src/httpClient.ts
CHANGED
|
@@ -4,7 +4,7 @@ import axios, {
|
|
|
4
4
|
type InternalAxiosRequestConfig,
|
|
5
5
|
} from "axios";
|
|
6
6
|
|
|
7
|
-
import {APIError} from "./errors";
|
|
7
|
+
import {APIError, InternalServerError} from "./errors";
|
|
8
8
|
import {logger as defaultLogger} from "./logger";
|
|
9
9
|
|
|
10
10
|
// Internal per-request state tracked on the axios config across interceptor retries.
|
|
@@ -344,7 +344,11 @@ export const createAuthenticatedClient = (
|
|
|
344
344
|
);
|
|
345
345
|
const accessToken = response.data?.access_token;
|
|
346
346
|
if (typeof accessToken !== "string" || accessToken.length === 0) {
|
|
347
|
-
throw new
|
|
347
|
+
throw new InternalServerError({
|
|
348
|
+
code: "http-client-error",
|
|
349
|
+
detail: `${apiName} token response has no access_token`,
|
|
350
|
+
title: "[httpClient] token response has no access_token",
|
|
351
|
+
});
|
|
348
352
|
}
|
|
349
353
|
return accessToken;
|
|
350
354
|
};
|