@terreno/api 0.23.1 → 0.25.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/README.md +1 -0
- package/dist/__tests__/versionCheckPlugin.test.js +47 -2
- package/dist/api.query.test.js +99 -0
- package/dist/auth.compile.test.d.ts +1 -0
- package/dist/auth.compile.test.js +201 -0
- package/dist/auth.js +38 -7
- package/dist/auth.test.js +249 -0
- package/dist/betterAuthSetup.test.js +76 -0
- package/dist/docLoader.test.js +0 -1
- package/dist/expressServer.d.ts +25 -1
- package/dist/expressServer.js +1 -3
- package/dist/expressServer.test.js +15 -8
- package/dist/githubAuth.d.ts +1 -1
- package/dist/httpClient.d.ts +119 -0
- package/dist/httpClient.js +412 -0
- package/dist/httpClient.test.d.ts +1 -0
- package/dist/httpClient.test.js +1470 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -0
- package/dist/notifiers/googleChatNotifier.test.js +0 -1
- package/dist/populate.test.js +30 -0
- package/dist/realtime/queryStore.d.ts +3 -3
- package/dist/realtime/queryStore.js +0 -1
- package/dist/realtime/realtime.test.js +22 -0
- package/dist/tests/fixtures/compileAuthEntry.d.ts +1 -0
- package/dist/tests/fixtures/compileAuthEntry.js +37 -0
- package/dist/transformers.test.js +0 -1
- package/package.json +2 -2
- package/src/__tests__/versionCheckPlugin.test.ts +37 -2
- package/src/api.query.test.ts +59 -0
- package/src/auth.compile.test.ts +106 -0
- package/src/auth.test.ts +177 -0
- package/src/auth.ts +49 -7
- package/src/betterAuthSetup.test.ts +65 -0
- package/src/docLoader.test.ts +4 -4
- package/src/expressServer.test.ts +17 -8
- package/src/expressServer.ts +30 -6
- package/src/githubAuth.ts +2 -4
- package/src/httpClient.test.ts +979 -0
- package/src/httpClient.ts +464 -0
- package/src/index.ts +1 -0
- package/src/notifiers/googleChatNotifier.test.ts +5 -4
- package/src/populate.test.ts +32 -0
- package/src/realtime/queryStore.ts +6 -7
- package/src/realtime/realtime.test.ts +28 -2
- package/src/realtime/realtimeApp.ts +3 -3
- package/src/tests/fixtures/compileAuthEntry.ts +43 -0
- package/src/transformers.test.ts +15 -8
package/src/auth.ts
CHANGED
|
@@ -60,16 +60,39 @@ export const authenticateMiddleware = (anonymous = false) => {
|
|
|
60
60
|
if (anonymous) {
|
|
61
61
|
strategies.push("anonymous");
|
|
62
62
|
}
|
|
63
|
-
const passportAuth = passport.authenticate(strategies, {
|
|
64
|
-
failureMessage: false, // this is just avoiding storing the message in the session
|
|
65
|
-
failWithError: true,
|
|
66
|
-
session: false,
|
|
67
|
-
});
|
|
68
63
|
return (req: express.Request, res: express.Response, next: express.NextFunction) => {
|
|
69
64
|
if (req.user) {
|
|
70
65
|
return next();
|
|
71
66
|
}
|
|
72
|
-
|
|
67
|
+
// Failures use a custom callback rather than passport's `failWithError`:
|
|
68
|
+
// passport's internal AuthenticationError touches `arguments.callee`,
|
|
69
|
+
// which throws a TypeError in strict-mode contexts — inside
|
|
70
|
+
// `bun build --compile` binaries that turned every 401 into a 500. The
|
|
71
|
+
// plain Error("Unauthorized") below is what apiUnauthorizedMiddleware
|
|
72
|
+
// matches on, so the response contract is unchanged.
|
|
73
|
+
// (The anonymous strategy calls pass(), which skips this callback and
|
|
74
|
+
// continues the chain with no user — same as before.)
|
|
75
|
+
return passport.authenticate(
|
|
76
|
+
strategies,
|
|
77
|
+
{session: false},
|
|
78
|
+
(
|
|
79
|
+
err: Error | null,
|
|
80
|
+
user: NonNullable<express.Request["user"]> | false | null,
|
|
81
|
+
info: unknown
|
|
82
|
+
) => {
|
|
83
|
+
if (err) {
|
|
84
|
+
return next(err);
|
|
85
|
+
}
|
|
86
|
+
if (!user) {
|
|
87
|
+
return next(new Error("Unauthorized"));
|
|
88
|
+
}
|
|
89
|
+
req.user = user;
|
|
90
|
+
// req.logIn used to populate authInfo; keep that passport-public API
|
|
91
|
+
// intact for downstream consumers.
|
|
92
|
+
req.authInfo = (info ?? {}) as Express.AuthInfo;
|
|
93
|
+
return next();
|
|
94
|
+
}
|
|
95
|
+
)(req, res, next);
|
|
73
96
|
};
|
|
74
97
|
};
|
|
75
98
|
|
|
@@ -412,7 +435,26 @@ export const addAuthRoutes = (
|
|
|
412
435
|
if (!signupDisabled) {
|
|
413
436
|
router.post(
|
|
414
437
|
"/signup",
|
|
415
|
-
|
|
438
|
+
// Custom callback instead of `failWithError` — passport's internal
|
|
439
|
+
// AuthenticationError is unusable in strict-mode bundles (see
|
|
440
|
+
// authenticateMiddleware). Strategy errors (e.g. duplicate email) pass
|
|
441
|
+
// through unchanged; a bare failure (missing credentials) is a 400.
|
|
442
|
+
(req: express.Request, res: express.Response, next: express.NextFunction) => {
|
|
443
|
+
passport.authenticate(
|
|
444
|
+
"signup",
|
|
445
|
+
{session: false},
|
|
446
|
+
(err: Error | null, user: NonNullable<express.Request["user"]> | false | null) => {
|
|
447
|
+
if (err) {
|
|
448
|
+
return next(err);
|
|
449
|
+
}
|
|
450
|
+
if (!user) {
|
|
451
|
+
return next(new APIError({status: 400, title: "Missing credentials"}));
|
|
452
|
+
}
|
|
453
|
+
req.user = user;
|
|
454
|
+
return next();
|
|
455
|
+
}
|
|
456
|
+
)(req, res, next);
|
|
457
|
+
},
|
|
416
458
|
async (req: express.Request, res: express.Response) => {
|
|
417
459
|
const tokens = await generateTokens(req.user, authOptions);
|
|
418
460
|
if (tokens.sessionId) {
|
|
@@ -238,6 +238,19 @@ describe("syncBetterAuthUser", () => {
|
|
|
238
238
|
|
|
239
239
|
expect(result.name).toBe("Keep This Name");
|
|
240
240
|
});
|
|
241
|
+
|
|
242
|
+
it("logs and rethrows when the lookup fails", async () => {
|
|
243
|
+
await setup;
|
|
244
|
+
const failure = new Error("lookup exploded");
|
|
245
|
+
const throwingModel = {
|
|
246
|
+
findOneOrNone: () => {
|
|
247
|
+
throw failure;
|
|
248
|
+
},
|
|
249
|
+
} as unknown as UserModel;
|
|
250
|
+
|
|
251
|
+
const baUser = makeBetterAuthUser();
|
|
252
|
+
await expect(syncBetterAuthUser(throwingModel, baUser)).rejects.toThrow("lookup exploded");
|
|
253
|
+
});
|
|
241
254
|
});
|
|
242
255
|
|
|
243
256
|
describe("createBetterAuthSessionMiddleware", () => {
|
|
@@ -435,6 +448,47 @@ describe("mountBetterAuthRoutes", () => {
|
|
|
435
448
|
|
|
436
449
|
expect(() => mountBetterAuthRoutes(app, auth, "/custom/auth")).not.toThrow();
|
|
437
450
|
});
|
|
451
|
+
|
|
452
|
+
it("delegates matched requests to the Better Auth node handler", async () => {
|
|
453
|
+
await setup;
|
|
454
|
+
const config: BetterAuthConfig = {
|
|
455
|
+
baseURL: "http://localhost:3000",
|
|
456
|
+
enabled: true,
|
|
457
|
+
secret: "test-secret-at-least-32-characters-long",
|
|
458
|
+
};
|
|
459
|
+
|
|
460
|
+
const auth = createBetterAuth({config, mongoClient: getClient()});
|
|
461
|
+
|
|
462
|
+
type RouteHandler = (req: unknown, res: unknown) => unknown;
|
|
463
|
+
let registered: RouteHandler | undefined;
|
|
464
|
+
let registeredPath: string | undefined;
|
|
465
|
+
const fakeApp = {
|
|
466
|
+
all: (path: string, handler: RouteHandler) => {
|
|
467
|
+
registeredPath = path;
|
|
468
|
+
registered = handler;
|
|
469
|
+
},
|
|
470
|
+
} as unknown as express.Application;
|
|
471
|
+
|
|
472
|
+
mountBetterAuthRoutes(fakeApp, auth, "/api/auth");
|
|
473
|
+
expect(registeredPath).toBe("/api/auth/*path");
|
|
474
|
+
expect(registered).toBeDefined();
|
|
475
|
+
|
|
476
|
+
// Invoke the registered handler so the wildcard delegation runs.
|
|
477
|
+
const req = {headers: {}, method: "GET", on: () => {}, url: "/api/auth/session"};
|
|
478
|
+
const res = {
|
|
479
|
+
end: mock(() => {}),
|
|
480
|
+
getHeader: () => undefined,
|
|
481
|
+
setHeader: mock(() => {}),
|
|
482
|
+
write: mock(() => {}),
|
|
483
|
+
writeHead: mock(() => {}),
|
|
484
|
+
};
|
|
485
|
+
try {
|
|
486
|
+
await registered?.(req, res);
|
|
487
|
+
} catch {
|
|
488
|
+
// The bare req/res may not satisfy the underlying handler; we only need
|
|
489
|
+
// the delegating arrow itself to execute.
|
|
490
|
+
}
|
|
491
|
+
});
|
|
438
492
|
});
|
|
439
493
|
|
|
440
494
|
describe("getMongoClientFromMongoose", () => {
|
|
@@ -443,6 +497,17 @@ describe("getMongoClientFromMongoose", () => {
|
|
|
443
497
|
const client = getMongoClientFromMongoose();
|
|
444
498
|
expect(client).toBeDefined();
|
|
445
499
|
});
|
|
500
|
+
|
|
501
|
+
it("throws when the mongoose connection has no client", () => {
|
|
502
|
+
const connection = mongoose.connection as unknown as {client?: unknown};
|
|
503
|
+
const originalClient = connection.client;
|
|
504
|
+
connection.client = undefined;
|
|
505
|
+
try {
|
|
506
|
+
expect(() => getMongoClientFromMongoose()).toThrow("Mongoose is not connected");
|
|
507
|
+
} finally {
|
|
508
|
+
connection.client = originalClient;
|
|
509
|
+
}
|
|
510
|
+
});
|
|
446
511
|
});
|
|
447
512
|
|
|
448
513
|
describe("getBetterAuthSession", () => {
|
package/src/docLoader.test.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
// biome-ignore-all lint/suspicious/noExplicitAny: test mock typing
|
|
2
1
|
import {describe, expect, it, mock} from "bun:test";
|
|
2
|
+
import type {Model} from "mongoose";
|
|
3
3
|
import {loadDocOr404} from "./docLoader";
|
|
4
4
|
import {APIError} from "./errors";
|
|
5
5
|
|
|
@@ -9,7 +9,7 @@ describe("loadDocOr404", () => {
|
|
|
9
9
|
collection: {findOne: mock(async () => ({deleted: true}))},
|
|
10
10
|
findById: mock(() => ({exec: mock(async () => null)})),
|
|
11
11
|
modelName: "MockModel",
|
|
12
|
-
} as
|
|
12
|
+
} as unknown as Model<unknown>;
|
|
13
13
|
|
|
14
14
|
try {
|
|
15
15
|
await loadDocOr404(model, "507f1f77bcf86cd799439011");
|
|
@@ -33,7 +33,7 @@ describe("loadDocOr404", () => {
|
|
|
33
33
|
}),
|
|
34
34
|
})),
|
|
35
35
|
modelName: "MockModel",
|
|
36
|
-
} as
|
|
36
|
+
} as unknown as Model<unknown>;
|
|
37
37
|
|
|
38
38
|
await expect(loadDocOr404(model, "507f1f77bcf86cd799439011")).rejects.toBe(original);
|
|
39
39
|
});
|
|
@@ -43,7 +43,7 @@ describe("loadDocOr404", () => {
|
|
|
43
43
|
collection: {findOne: mock(async () => null)},
|
|
44
44
|
findById: mock(() => ({exec: mock(async () => null)})),
|
|
45
45
|
modelName: "MockModel",
|
|
46
|
-
} as
|
|
46
|
+
} as unknown as Model<unknown>;
|
|
47
47
|
|
|
48
48
|
try {
|
|
49
49
|
await loadDocOr404(model, "507f1f77bcf86cd799439011");
|
|
@@ -5,6 +5,7 @@ import express from "express";
|
|
|
5
5
|
import supertest from "supertest";
|
|
6
6
|
import winston from "winston";
|
|
7
7
|
|
|
8
|
+
import type {UserModel as UserModelType} from "./auth";
|
|
8
9
|
import {
|
|
9
10
|
createRouter,
|
|
10
11
|
createRouterWithAuth,
|
|
@@ -17,6 +18,8 @@ import {logger, winstonLogger} from "./logger";
|
|
|
17
18
|
import {TerrenoApp} from "./terrenoApp";
|
|
18
19
|
import {UserModel} from "./tests";
|
|
19
20
|
|
|
21
|
+
const typedUserModel = UserModel as unknown as UserModelType;
|
|
22
|
+
|
|
20
23
|
describe("expressServer", () => {
|
|
21
24
|
describe("setupEnvironment", () => {
|
|
22
25
|
const originalEnv = process.env;
|
|
@@ -821,7 +824,7 @@ describe("expressServer", () => {
|
|
|
821
824
|
const app = new TerrenoApp({
|
|
822
825
|
configureApp,
|
|
823
826
|
skipListen: false,
|
|
824
|
-
userModel:
|
|
827
|
+
userModel: typedUserModel,
|
|
825
828
|
}).start();
|
|
826
829
|
expect(app).toBeDefined();
|
|
827
830
|
} finally {
|
|
@@ -829,21 +832,27 @@ describe("expressServer", () => {
|
|
|
829
832
|
}
|
|
830
833
|
});
|
|
831
834
|
|
|
832
|
-
it("handles listen
|
|
833
|
-
process.env.PORT = "-1";
|
|
835
|
+
it("handles listen errors", () => {
|
|
834
836
|
const configureApp = (): void => {};
|
|
837
|
+
const http = require("node:http") as typeof import("node:http");
|
|
838
|
+
const originalListen = http.Server.prototype.listen;
|
|
835
839
|
const originalExit = process.exit;
|
|
836
|
-
|
|
840
|
+
const exit = mock(() => undefined);
|
|
841
|
+
process.exit = exit as unknown as typeof process.exit;
|
|
842
|
+
http.Server.prototype.listen = mock(() => {
|
|
843
|
+
throw new Error("listen failed");
|
|
844
|
+
}) as unknown as typeof originalListen;
|
|
837
845
|
try {
|
|
838
846
|
new TerrenoApp({
|
|
839
847
|
configureApp,
|
|
840
848
|
skipListen: false,
|
|
841
|
-
userModel:
|
|
849
|
+
userModel: typedUserModel,
|
|
842
850
|
}).start();
|
|
843
|
-
|
|
844
|
-
|
|
851
|
+
expect(exit).toHaveBeenCalledWith(1);
|
|
852
|
+
} finally {
|
|
853
|
+
http.Server.prototype.listen = originalListen;
|
|
854
|
+
process.exit = originalExit;
|
|
845
855
|
}
|
|
846
|
-
process.exit = originalExit;
|
|
847
856
|
});
|
|
848
857
|
});
|
|
849
858
|
|
package/src/expressServer.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type {OutgoingMessage} from "node:http";
|
|
1
2
|
import * as Sentry from "@sentry/bun";
|
|
2
3
|
import cron from "cron";
|
|
3
4
|
import express, {type Router} from "express";
|
|
@@ -36,8 +37,27 @@ export const setupEnvironment = (): void => {
|
|
|
36
37
|
|
|
37
38
|
export type AddRoutes = (router: Router, options?: Partial<ModelRouterOptions<unknown>>) => void;
|
|
38
39
|
|
|
39
|
-
|
|
40
|
-
|
|
40
|
+
interface LoggableRequest {
|
|
41
|
+
body?: Record<string, unknown>;
|
|
42
|
+
method: string;
|
|
43
|
+
originalUrl?: string;
|
|
44
|
+
route?: {path: string};
|
|
45
|
+
routeMount?: string | string[];
|
|
46
|
+
url?: string;
|
|
47
|
+
user?: {
|
|
48
|
+
admin?: boolean;
|
|
49
|
+
id?: string;
|
|
50
|
+
testUser?: boolean;
|
|
51
|
+
type?: string;
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
interface LoggableResponse {
|
|
56
|
+
locals?: {loggingOptions?: LoggingOptions};
|
|
57
|
+
statusCode?: number;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
const logRequestsFinished = (req: LoggableRequest, res: LoggableResponse, startTime: bigint) => {
|
|
41
61
|
const options = (res.locals?.loggingOptions ?? {}) as LoggingOptions;
|
|
42
62
|
|
|
43
63
|
const slowReadMs = options.logSlowRequestsReadMs ?? SLOW_READ_MAX;
|
|
@@ -50,7 +70,7 @@ const logRequestsFinished = (req: any, res: any, startTime: bigint) => {
|
|
|
50
70
|
pathName = `${req.routeMount}${req.route.path}`;
|
|
51
71
|
} else if (req.route) {
|
|
52
72
|
pathName = req.route.path;
|
|
53
|
-
} else if (res.statusCode < 400) {
|
|
73
|
+
} else if (res.statusCode != null && res.statusCode < 400) {
|
|
54
74
|
logger.warn(`Request without route: ${req.originalUrl}`);
|
|
55
75
|
}
|
|
56
76
|
if (process.env.DISABLE_LOG_ALL_REQUESTS !== "true") {
|
|
@@ -77,8 +97,11 @@ const logRequestsFinished = (req: any, res: any, startTime: bigint) => {
|
|
|
77
97
|
}
|
|
78
98
|
};
|
|
79
99
|
|
|
80
|
-
|
|
81
|
-
|
|
100
|
+
export const logRequests = (
|
|
101
|
+
req: LoggableRequest,
|
|
102
|
+
res: LoggableResponse,
|
|
103
|
+
next: express.NextFunction
|
|
104
|
+
): void => {
|
|
82
105
|
const startTime = process.hrtime.bigint();
|
|
83
106
|
|
|
84
107
|
let userString = "";
|
|
@@ -106,7 +129,7 @@ export const logRequests = (req: any, res: any, next: express.NextFunction): voi
|
|
|
106
129
|
if (process.env.DISABLE_LOG_ALL_REQUESTS !== "true") {
|
|
107
130
|
logger.debug(`${req.method} <- ${req.url}${userString}${body}`);
|
|
108
131
|
}
|
|
109
|
-
onFinished(res, () => logRequestsFinished(req, res, startTime));
|
|
132
|
+
onFinished(res as unknown as OutgoingMessage, () => logRequestsFinished(req, res, startTime));
|
|
110
133
|
next();
|
|
111
134
|
};
|
|
112
135
|
|
|
@@ -145,6 +168,7 @@ export const createRouterWithAuth = (
|
|
|
145
168
|
};
|
|
146
169
|
|
|
147
170
|
export interface AuthOptions {
|
|
171
|
+
// noExplicitAny: user shape is provided by the consumer's User model — any preserves the loose-binding contract
|
|
148
172
|
// biome-ignore lint/suspicious/noExplicitAny: user shape is provided by the consumer's User model — any preserves the loose-binding contract
|
|
149
173
|
generateJWTPayload?: (user: any) => Record<string, unknown>;
|
|
150
174
|
// biome-ignore lint/suspicious/noExplicitAny: see above
|
package/src/githubAuth.ts
CHANGED
|
@@ -33,10 +33,8 @@ export interface GitHubAuthOptions {
|
|
|
33
33
|
profile: Profile,
|
|
34
34
|
accessToken: string,
|
|
35
35
|
refreshToken: string,
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
// biome-ignore lint/suspicious/noExplicitAny: passport user value remains untyped
|
|
39
|
-
) => Promise<any>;
|
|
36
|
+
existingUser?: Record<string, unknown>
|
|
37
|
+
) => Promise<unknown>;
|
|
40
38
|
}
|
|
41
39
|
|
|
42
40
|
/** Fields added to user documents for GitHub authentication */
|