@terreno/api 0.31.0 → 56.0.0-beta.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 +122 -2
- package/LICENSE +202 -21
- package/dist/api.d.ts +12 -3
- package/dist/api.js +110 -361
- package/dist/auth.d.ts +26 -0
- package/dist/auth.js +100 -1
- package/dist/betterAuth.d.ts +5 -0
- package/dist/betterAuthSetup.d.ts +1 -15
- package/dist/betterAuthSetup.js +29 -8
- package/dist/configurationPlugin.js +2 -2
- package/dist/docLoader.js +12 -9
- package/dist/errors.d.ts +13 -0
- package/dist/errors.js +29 -1
- package/dist/expressServer.js +5 -11
- package/dist/githubAuth.js +4 -1
- package/dist/index.d.ts +17 -1
- package/dist/index.js +29 -1
- package/dist/middleware.d.ts +7 -0
- package/dist/middleware.js +16 -1
- package/dist/openApiCompat.d.ts +10 -1
- package/dist/openApiCompat.js +115 -47
- package/dist/permissions.d.ts +27 -0
- package/dist/permissions.js +42 -1
- package/dist/plugins.d.ts +15 -3
- package/dist/plugins.js +36 -6
- package/dist/realtime/changeStreamWatcher.d.ts +100 -3
- package/dist/realtime/changeStreamWatcher.js +542 -137
- package/dist/realtime/realtimeApp.d.ts +3 -1
- package/dist/realtime/realtimeApp.js +75 -27
- package/dist/realtime/sessionRevalidation.d.ts +90 -0
- package/dist/realtime/sessionRevalidation.js +438 -0
- package/dist/realtime/socketAuth.d.ts +97 -0
- package/dist/realtime/socketAuth.js +272 -0
- package/dist/realtime/socketUser.d.ts +54 -0
- package/dist/realtime/socketUser.js +75 -5
- package/dist/realtime/types.d.ts +40 -0
- package/dist/secretProviders.d.ts +23 -0
- package/dist/secretProviders.js +9 -3
- package/dist/sync/executors.d.ts +198 -0
- package/dist/sync/executors.js +670 -0
- package/dist/sync/loadHarness.js +807 -0
- package/dist/sync/models.d.ts +216 -0
- package/dist/sync/models.js +644 -0
- package/dist/sync/mutationHandler.d.ts +97 -0
- package/dist/sync/mutationHandler.js +886 -0
- package/dist/sync/registry.d.ts +73 -0
- package/dist/sync/registry.js +223 -0
- package/dist/sync/routes.d.ts +62 -0
- package/dist/sync/routes.js +936 -0
- package/dist/sync/scripts/compactTombstones.d.ts +47 -0
- package/dist/sync/scripts/compactTombstones.js +270 -0
- package/dist/sync/serialize.d.ts +20 -0
- package/dist/{tests/bunSetup.js → sync/serialize.js} +35 -68
- package/dist/sync/socketHandlers.d.ts +54 -0
- package/dist/sync/socketHandlers.js +470 -0
- package/dist/sync/streams.d.ts +85 -0
- package/dist/sync/streams.js +221 -0
- package/dist/sync/syncApp.d.ts +29 -0
- package/dist/sync/syncApp.js +44 -0
- package/dist/sync/syncBatch.d.ts +71 -0
- package/dist/sync/syncBatch.js +252 -0
- package/dist/sync/syncSeqPlugin.d.ts +8 -0
- package/dist/sync/syncSeqPlugin.js +903 -0
- package/dist/sync/types.d.ts +254 -0
- package/dist/sync/types.js +9 -0
- package/dist/terrenoApp.js +90 -27
- package/dist/tests/models.d.ts +11 -27
- package/dist/tests/models.js +3 -5
- package/dist/tests/testHelper.d.ts +3 -9
- package/dist/vendor/wesleytodd-openapi/index.d.ts +1 -1
- package/dist/vendor/wesleytodd-openapi/lib/ui.d.ts +2 -1
- package/package.json +10 -8
- package/src/__tests__/openApiCompat.test.ts +20 -0
- package/src/actions.test.ts +12 -19
- package/src/actions.ts +2 -2
- package/src/api.coverage.test.ts +9 -7
- package/src/api.errorPaths.test.ts +1 -47
- package/src/api.test.ts +12 -0
- package/src/api.ts +98 -317
- package/src/auth.test.ts +128 -176
- package/src/auth.ts +109 -0
- package/src/betterAuth.ts +6 -0
- package/src/betterAuthSetup.test.ts +34 -0
- package/src/betterAuthSetup.ts +27 -8
- package/src/configurationPlugin.ts +2 -2
- package/src/consentApp.test.ts +12 -12
- package/src/docLoader.ts +3 -1
- package/src/errors.ts +33 -0
- package/src/expressServer.test.ts +7 -1
- package/src/expressServer.ts +5 -11
- package/src/githubAuth.ts +3 -1
- package/src/index.ts +42 -0
- package/src/middleware.test.ts +40 -1
- package/src/middleware.ts +15 -0
- package/src/models/versionConfig.ts +1 -1
- package/src/openApiBuilder.test.ts +9 -24
- package/src/openApiCompat.ts +99 -45
- package/src/openApiValidator.test.ts +0 -41
- package/src/permissions.test.ts +75 -1
- package/src/permissions.ts +49 -0
- package/src/plugins.test.ts +54 -14
- package/src/plugins.ts +47 -9
- package/src/populate.test.ts +16 -25
- package/src/realtime/changeStreamWatcher.ts +552 -114
- package/src/realtime/realtime.test.ts +157 -239
- package/src/realtime/realtimeApp.ts +80 -19
- package/src/realtime/sessionRevalidation.test.ts +423 -0
- package/src/realtime/sessionRevalidation.ts +273 -0
- package/src/realtime/socketAuth.test.ts +355 -0
- package/src/realtime/socketAuth.ts +228 -0
- package/src/realtime/socketUser.ts +69 -0
- package/src/realtime/types.ts +40 -0
- package/src/secretProviders.test.ts +7 -1
- package/src/secretProviders.ts +15 -3
- package/src/sync/ensureSyncIndexes.test.ts +144 -0
- package/src/sync/executors.test.ts +882 -0
- package/src/sync/executors.ts +703 -0
- package/src/sync/integration.test.ts +1160 -0
- package/src/sync/loadHarness.ts +618 -0
- package/src/sync/models.ts +640 -0
- package/src/sync/mutationHandler.test.ts +1252 -0
- package/src/sync/mutationHandler.ts +850 -0
- package/src/sync/registry.ts +232 -0
- package/src/sync/routes.ts +812 -0
- package/src/sync/scripts/compactTombstones.test.ts +249 -0
- package/src/sync/scripts/compactTombstones.ts +145 -0
- package/src/sync/serialize.ts +48 -0
- package/src/sync/sessionRevalidationIntegration.test.ts +281 -0
- package/src/sync/socketHandlers.ts +320 -0
- package/src/sync/streams.ts +188 -0
- package/src/sync/sync.test.ts +582 -0
- package/src/sync/syncApp.ts +44 -0
- package/src/sync/syncBatch.ts +219 -0
- package/src/sync/syncFrontier.test.ts +494 -0
- package/src/sync/syncPhaseC.test.ts +718 -0
- package/src/sync/syncRoutes.test.ts +865 -0
- package/src/sync/syncSeqPlugin.ts +738 -0
- package/src/sync/syncSocket.test.ts +1440 -0
- package/src/sync/types.ts +270 -0
- package/src/terrenoApp.ts +37 -17
- package/src/tests/bunSetup.ts +8 -0
- package/src/tests/models.ts +6 -8
- package/tsconfig.json +4 -4
- package/tsconfig.typedoc.json +7 -1
- package/dist/__tests__/openApiCompat.test.js +0 -317
- package/dist/__tests__/versionCheckPlugin.test.d.ts +0 -1
- package/dist/__tests__/versionCheckPlugin.test.js +0 -597
- package/dist/actions.openApi.test.d.ts +0 -1
- package/dist/actions.openApi.test.js +0 -253
- package/dist/actions.test.d.ts +0 -1
- package/dist/actions.test.js +0 -1087
- package/dist/api.arrayOperations.test.d.ts +0 -1
- package/dist/api.arrayOperations.test.js +0 -878
- package/dist/api.asyncHandler.test.d.ts +0 -1
- package/dist/api.asyncHandler.test.js +0 -236
- package/dist/api.coverage.test.d.ts +0 -1
- package/dist/api.coverage.test.js +0 -192
- package/dist/api.errorPaths.test.d.ts +0 -1
- package/dist/api.errorPaths.test.js +0 -887
- package/dist/api.errors.test.d.ts +0 -1
- package/dist/api.errors.test.js +0 -185
- package/dist/api.hooks.test.d.ts +0 -1
- package/dist/api.hooks.test.js +0 -950
- package/dist/api.query.test.d.ts +0 -1
- package/dist/api.query.test.js +0 -948
- package/dist/api.test.d.ts +0 -1
- package/dist/api.test.js +0 -2820
- package/dist/auth.compile.test.d.ts +0 -1
- package/dist/auth.compile.test.js +0 -201
- package/dist/auth.coverage.test.d.ts +0 -1
- package/dist/auth.coverage.test.js +0 -202
- package/dist/auth.test.d.ts +0 -1
- package/dist/auth.test.js +0 -2286
- package/dist/betterAuth.test.d.ts +0 -1
- package/dist/betterAuth.test.js +0 -181
- package/dist/betterAuthApp.test.d.ts +0 -1
- package/dist/betterAuthApp.test.js +0 -242
- package/dist/betterAuthSetup.test.d.ts +0 -1
- package/dist/betterAuthSetup.test.js +0 -762
- package/dist/config.test.d.ts +0 -1
- package/dist/config.test.js +0 -353
- package/dist/configuration.test.d.ts +0 -1
- package/dist/configuration.test.js +0 -980
- package/dist/configurationPlugin.test.d.ts +0 -1
- package/dist/configurationPlugin.test.js +0 -827
- package/dist/consentApp.test.d.ts +0 -1
- package/dist/consentApp.test.js +0 -1411
- package/dist/docLoader.test.d.ts +0 -1
- package/dist/docLoader.test.js +0 -137
- package/dist/envConfigurationPlugin.test.d.ts +0 -1
- package/dist/envConfigurationPlugin.test.js +0 -369
- package/dist/errors.test.d.ts +0 -1
- package/dist/errors.test.js +0 -607
- package/dist/expressServer.test.d.ts +0 -1
- package/dist/expressServer.test.js +0 -1249
- package/dist/githubAuth.test.d.ts +0 -1
- package/dist/githubAuth.test.js +0 -1142
- package/dist/httpClient.test.d.ts +0 -1
- package/dist/httpClient.test.js +0 -1471
- package/dist/logger.test.d.ts +0 -1
- package/dist/logger.test.js +0 -685
- package/dist/middleware.test.d.ts +0 -1
- package/dist/middleware.test.js +0 -241
- package/dist/notifiers/googleChatNotifier.test.d.ts +0 -1
- package/dist/notifiers/googleChatNotifier.test.js +0 -298
- package/dist/notifiers/slackNotifier.test.d.ts +0 -1
- package/dist/notifiers/slackNotifier.test.js +0 -297
- package/dist/notifiers/zoomNotifier.test.d.ts +0 -1
- package/dist/notifiers/zoomNotifier.test.js +0 -373
- package/dist/openApi.test.d.ts +0 -1
- package/dist/openApi.test.js +0 -620
- package/dist/openApiBuilder.test.d.ts +0 -1
- package/dist/openApiBuilder.test.js +0 -599
- package/dist/openApiEtag.test.d.ts +0 -1
- package/dist/openApiEtag.test.js +0 -86
- package/dist/openApiValidator.test.d.ts +0 -1
- package/dist/openApiValidator.test.js +0 -795
- package/dist/permissions.middleware.test.d.ts +0 -1
- package/dist/permissions.middleware.test.js +0 -308
- package/dist/permissions.test.d.ts +0 -1
- package/dist/permissions.test.js +0 -439
- package/dist/plugins.test.d.ts +0 -1
- package/dist/plugins.test.js +0 -902
- package/dist/populate.test.d.ts +0 -1
- package/dist/populate.test.js +0 -370
- package/dist/realtime/realtime.test.d.ts +0 -10
- package/dist/realtime/realtime.test.js +0 -4213
- package/dist/realtime/realtimeAppSetup.test.d.ts +0 -1
- package/dist/realtime/realtimeAppSetup.test.js +0 -213
- package/dist/requestContext.test.d.ts +0 -1
- package/dist/requestContext.test.js +0 -412
- package/dist/scriptRunner.test.d.ts +0 -1
- package/dist/scriptRunner.test.js +0 -386
- package/dist/secretProviders.test.d.ts +0 -1
- package/dist/secretProviders.test.js +0 -726
- package/dist/syncConsents.test.d.ts +0 -1
- package/dist/syncConsents.test.js +0 -522
- package/dist/terrenoApp.test.d.ts +0 -1
- package/dist/terrenoApp.test.js +0 -489
- package/dist/tests/bunSetup.d.ts +0 -1
- package/dist/tests/fixtures/compileAuthEntry.d.ts +0 -1
- package/dist/tests/fixtures/compileAuthEntry.js +0 -37
- package/dist/tests/testEnv.d.ts +0 -0
- package/dist/tests/testEnv.js +0 -6
- package/dist/transformers.test.d.ts +0 -1
- package/dist/transformers.test.js +0 -423
- package/dist/utils.test.d.ts +0 -1
- package/dist/utils.test.js +0 -242
- package/src/realtime/realtimeAppSetup.test.ts +0 -161
- /package/dist/{__tests__/openApiCompat.test.d.ts → sync/loadHarness.d.ts} +0 -0
package/src/auth.test.ts
CHANGED
|
@@ -1,19 +1,20 @@
|
|
|
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 express from "express";
|
|
4
|
+
import type 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
10
|
import {
|
|
11
|
-
type UserModel as AuthUserModel,
|
|
12
11
|
addAuthRoutes,
|
|
13
12
|
addMeRoutes,
|
|
14
13
|
generateTokens,
|
|
14
|
+
type HasSetPassword,
|
|
15
|
+
MAX_PASSWORD_LENGTH,
|
|
16
|
+
setPasswordForUser,
|
|
15
17
|
setupAuth,
|
|
16
|
-
signupUser,
|
|
17
18
|
} from "./auth";
|
|
18
19
|
import {logger} from "./logger";
|
|
19
20
|
import {Permissions} from "./permissions";
|
|
@@ -1369,6 +1370,40 @@ describe("decodeJWTMiddleware error paths", () => {
|
|
|
1369
1370
|
const res = await agent.get("/food").set("authorization", "Bearer undefined").expect(200);
|
|
1370
1371
|
expect(res.body.data).toBeDefined();
|
|
1371
1372
|
});
|
|
1373
|
+
|
|
1374
|
+
// D1: the JWT-vs-non-JWT fallthrough now decodes the token's header/payload
|
|
1375
|
+
// structure (jwt.decode with complete: true) instead of counting dots, so it is
|
|
1376
|
+
// robust to opaque tokens that coincidentally contain two dots and to malformed
|
|
1377
|
+
// strings that happen to have three dot-delimited segments without real JWT
|
|
1378
|
+
// structure.
|
|
1379
|
+
it("falls through (200, no 401) for an opaque non-JWT bearer token with two dots", async () => {
|
|
1380
|
+
// An opaque token shaped like a Better Auth session id — has exactly two dots
|
|
1381
|
+
// but is not base64url-encoded JSON in any segment.
|
|
1382
|
+
const res = await agent
|
|
1383
|
+
.get("/food")
|
|
1384
|
+
.set("authorization", "Bearer not.a.jwt-at-all")
|
|
1385
|
+
.expect(200);
|
|
1386
|
+
expect(res.body.data).toBeDefined();
|
|
1387
|
+
});
|
|
1388
|
+
|
|
1389
|
+
it("falls through (200, no 401) for a three-dot string with no real JWT header/payload structure", async () => {
|
|
1390
|
+
// Exactly three dot-delimited segments (would have been treated as "a JWT" by
|
|
1391
|
+
// the old dot-counting check) but none are valid base64url JSON.
|
|
1392
|
+
const res = await agent.get("/food").set("authorization", "Bearer abc.def.ghi").expect(200);
|
|
1393
|
+
expect(res.body.data).toBeDefined();
|
|
1394
|
+
});
|
|
1395
|
+
|
|
1396
|
+
it("returns 401 for a genuinely malformed JWT-shaped token (decodable header, bad signature)", async () => {
|
|
1397
|
+
const jwtLib = await import("jsonwebtoken");
|
|
1398
|
+
// A well-formed JWT (decodable header/payload) but signed with the wrong
|
|
1399
|
+
// secret — jwt.verify throws, and jwt.decode succeeds (it is a real JWT), so
|
|
1400
|
+
// this must still 401 rather than fall through.
|
|
1401
|
+
const badToken = jwtLib.sign({id: "someone"}, "wrong-secret", {
|
|
1402
|
+
issuer: process.env.TOKEN_ISSUER,
|
|
1403
|
+
});
|
|
1404
|
+
const res = await agent.get("/food").set("authorization", `Bearer ${badToken}`);
|
|
1405
|
+
expect(res.status).toBe(401);
|
|
1406
|
+
});
|
|
1372
1407
|
});
|
|
1373
1408
|
|
|
1374
1409
|
describe("signup disabled", () => {
|
|
@@ -1400,205 +1435,122 @@ describe("signup disabled", () => {
|
|
|
1400
1435
|
});
|
|
1401
1436
|
});
|
|
1402
1437
|
|
|
1403
|
-
describe("
|
|
1404
|
-
it("
|
|
1405
|
-
let
|
|
1406
|
-
const
|
|
1407
|
-
|
|
1408
|
-
|
|
1409
|
-
|
|
1410
|
-
save: async () => {
|
|
1411
|
-
saveCalled = true;
|
|
1438
|
+
describe("setPasswordForUser", () => {
|
|
1439
|
+
it("resolves when a callback-based setPassword invokes the callback with no error", async () => {
|
|
1440
|
+
let receivedPassword: string | undefined;
|
|
1441
|
+
const user: HasSetPassword = {
|
|
1442
|
+
setPassword: (password, callback) => {
|
|
1443
|
+
receivedPassword = password;
|
|
1444
|
+
callback?.();
|
|
1412
1445
|
},
|
|
1413
1446
|
};
|
|
1414
|
-
const fakeModel = {
|
|
1415
|
-
register: async () => failingUser,
|
|
1416
|
-
} as unknown as Parameters<typeof signupUser>[0];
|
|
1417
1447
|
|
|
1418
|
-
await
|
|
1419
|
-
|
|
1420
|
-
);
|
|
1421
|
-
expect(saveCalled).toBe(false);
|
|
1448
|
+
await setPasswordForUser(user, "new-password");
|
|
1449
|
+
expect(receivedPassword).toBe("new-password");
|
|
1422
1450
|
});
|
|
1423
|
-
});
|
|
1424
1451
|
|
|
1425
|
-
|
|
1426
|
-
|
|
1427
|
-
|
|
1428
|
-
|
|
1452
|
+
it("resolves when setPassword returns a promise", async () => {
|
|
1453
|
+
let receivedPassword: string | undefined;
|
|
1454
|
+
const user: HasSetPassword = {
|
|
1455
|
+
setPassword: async (password) => {
|
|
1456
|
+
receivedPassword = password;
|
|
1457
|
+
},
|
|
1458
|
+
};
|
|
1429
1459
|
|
|
1430
|
-
|
|
1431
|
-
|
|
1432
|
-
const testData = await setupTestData();
|
|
1433
|
-
admin = testData.users.admin;
|
|
1434
|
-
app = new TerrenoApp({
|
|
1435
|
-
configureApp: () => {},
|
|
1436
|
-
skipListen: true,
|
|
1437
|
-
userModel: UserModel as any,
|
|
1438
|
-
}).build();
|
|
1439
|
-
agent = supertest.agent(app);
|
|
1460
|
+
await setPasswordForUser(user, "promise-password");
|
|
1461
|
+
expect(receivedPassword).toBe("promise-password");
|
|
1440
1462
|
});
|
|
1441
1463
|
|
|
1442
|
-
|
|
1443
|
-
|
|
1444
|
-
|
|
1464
|
+
it("rejects when the callback is invoked with an error", async () => {
|
|
1465
|
+
const user: HasSetPassword = {
|
|
1466
|
+
setPassword: (_password, callback) => {
|
|
1467
|
+
callback?.(new Error("boom"));
|
|
1468
|
+
},
|
|
1469
|
+
};
|
|
1445
1470
|
|
|
1446
|
-
|
|
1447
|
-
const jwtLib = (await import("jsonwebtoken")).default;
|
|
1448
|
-
const token = jwtLib.sign({id: admin._id.toString()}, process.env.TOKEN_SECRET as string, {
|
|
1449
|
-
issuer: process.env.TOKEN_ISSUER,
|
|
1450
|
-
});
|
|
1451
|
-
const findSpy = spyOn(UserModel, "findById").mockImplementation(() => {
|
|
1452
|
-
throw new Error("database unavailable");
|
|
1453
|
-
});
|
|
1454
|
-
try {
|
|
1455
|
-
const res = await agent.get("/auth/me").set("authorization", `Bearer ${token}`);
|
|
1456
|
-
expect(res.status).toBeGreaterThanOrEqual(400);
|
|
1457
|
-
} finally {
|
|
1458
|
-
findSpy.mockRestore();
|
|
1459
|
-
}
|
|
1471
|
+
await expect(setPasswordForUser(user, "pw")).rejects.toThrow("boom");
|
|
1460
1472
|
});
|
|
1461
1473
|
|
|
1462
|
-
it("
|
|
1463
|
-
|
|
1464
|
-
|
|
1465
|
-
|
|
1466
|
-
|
|
1467
|
-
|
|
1468
|
-
|
|
1469
|
-
|
|
1470
|
-
"authenticate"
|
|
1471
|
-
).mockReturnValue((_username, _password, done) => {
|
|
1472
|
-
done(new Error("strategy failure"));
|
|
1473
|
-
});
|
|
1474
|
-
try {
|
|
1475
|
-
const errApp = new TerrenoApp({
|
|
1476
|
-
configureApp: () => {},
|
|
1477
|
-
skipListen: true,
|
|
1478
|
-
userModel: UserModel as any,
|
|
1479
|
-
}).build();
|
|
1480
|
-
const errAgent = supertest.agent(errApp);
|
|
1481
|
-
const res = await errAgent
|
|
1482
|
-
.post("/auth/login")
|
|
1483
|
-
.send({email: "notAdmin@example.com", password: "password"});
|
|
1484
|
-
expect(res.status).toBeGreaterThanOrEqual(400);
|
|
1485
|
-
} finally {
|
|
1486
|
-
authSpy.mockRestore();
|
|
1487
|
-
}
|
|
1474
|
+
it("rejects when setPassword throws synchronously", async () => {
|
|
1475
|
+
const user: HasSetPassword = {
|
|
1476
|
+
setPassword: () => {
|
|
1477
|
+
throw new Error("sync failure");
|
|
1478
|
+
},
|
|
1479
|
+
};
|
|
1480
|
+
|
|
1481
|
+
await expect(setPasswordForUser(user, "pw")).rejects.toThrow("sync failure");
|
|
1488
1482
|
});
|
|
1489
|
-
});
|
|
1490
1483
|
|
|
1491
|
-
|
|
1492
|
-
|
|
1493
|
-
|
|
1484
|
+
it("rejects with a timeout when setPassword never settles", async () => {
|
|
1485
|
+
const user: HasSetPassword = {
|
|
1486
|
+
setPassword: () => {
|
|
1487
|
+
// Never invokes the callback and returns nothing (no promise).
|
|
1488
|
+
},
|
|
1489
|
+
};
|
|
1490
|
+
|
|
1491
|
+
await expect(setPasswordForUser(user, "pw", 10)).rejects.toThrow(
|
|
1492
|
+
"Timed out while setting password"
|
|
1493
|
+
);
|
|
1494
1494
|
});
|
|
1495
1495
|
|
|
1496
|
-
it("
|
|
1497
|
-
|
|
1498
|
-
const
|
|
1499
|
-
|
|
1500
|
-
|
|
1501
|
-
|
|
1502
|
-
|
|
1503
|
-
|
|
1504
|
-
|
|
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);
|
|
1496
|
+
it("rejects passwords longer than MAX_PASSWORD_LENGTH without calling setPassword", async () => {
|
|
1497
|
+
let called = false;
|
|
1498
|
+
const user: HasSetPassword = {
|
|
1499
|
+
setPassword: (_password, callback) => {
|
|
1500
|
+
called = true;
|
|
1501
|
+
callback?.();
|
|
1502
|
+
},
|
|
1503
|
+
};
|
|
1504
|
+
const tooLong = "x".repeat(MAX_PASSWORD_LENGTH + 1);
|
|
1511
1505
|
|
|
1512
|
-
|
|
1513
|
-
|
|
1506
|
+
await expect(setPasswordForUser(user, tooLong)).rejects.toThrow(
|
|
1507
|
+
`Password must be at most ${MAX_PASSWORD_LENGTH} characters`
|
|
1508
|
+
);
|
|
1509
|
+
expect(called).toBe(false);
|
|
1514
1510
|
});
|
|
1515
|
-
});
|
|
1516
1511
|
|
|
1517
|
-
|
|
1518
|
-
|
|
1512
|
+
it("accepts a password exactly at MAX_PASSWORD_LENGTH", async () => {
|
|
1513
|
+
let receivedPassword: string | undefined;
|
|
1514
|
+
const user: HasSetPassword = {
|
|
1515
|
+
setPassword: (password, callback) => {
|
|
1516
|
+
receivedPassword = password;
|
|
1517
|
+
callback?.();
|
|
1518
|
+
},
|
|
1519
|
+
};
|
|
1520
|
+
const atLimit = "x".repeat(MAX_PASSWORD_LENGTH);
|
|
1519
1521
|
|
|
1520
|
-
|
|
1521
|
-
|
|
1522
|
-
process.env.NODE_ENV = originalNodeEnv;
|
|
1522
|
+
await setPasswordForUser(user, atLimit);
|
|
1523
|
+
expect(receivedPassword).toBe(atLimit);
|
|
1523
1524
|
});
|
|
1524
1525
|
|
|
1525
|
-
it("logs
|
|
1526
|
-
setSystemTime();
|
|
1527
|
-
await setupTestData();
|
|
1528
|
-
process.env.NODE_ENV = "development";
|
|
1529
|
-
const debugSpy = spyOn(logger, "debug");
|
|
1526
|
+
it("logs an audit line with the admin id and target user id when audit context is provided", async () => {
|
|
1530
1527
|
const infoSpy = spyOn(logger, "info");
|
|
1531
|
-
|
|
1532
|
-
|
|
1533
|
-
|
|
1534
|
-
|
|
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
|
-
});
|
|
1528
|
+
infoSpy.mockClear();
|
|
1529
|
+
const user: HasSetPassword = {
|
|
1530
|
+
_id: "target-user-id",
|
|
1531
|
+
setPassword: (_password, callback) => callback?.(),
|
|
1532
|
+
};
|
|
1556
1533
|
|
|
1557
|
-
|
|
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
|
-
});
|
|
1534
|
+
await setPasswordForUser(user, "new-password", undefined, {adminId: "admin-id-123"});
|
|
1581
1535
|
|
|
1582
|
-
|
|
1583
|
-
|
|
1584
|
-
|
|
1585
|
-
|
|
1586
|
-
|
|
1587
|
-
|
|
1536
|
+
expect(infoSpy).toHaveBeenCalledTimes(1);
|
|
1537
|
+
const [message] = infoSpy.mock.calls[0] as [string];
|
|
1538
|
+
expect(message).toContain("admin-id-123");
|
|
1539
|
+
expect(message).toContain("target-user-id");
|
|
1540
|
+
expect(message).not.toContain("new-password");
|
|
1541
|
+
infoSpy.mockRestore();
|
|
1588
1542
|
});
|
|
1589
1543
|
|
|
1590
|
-
it("
|
|
1591
|
-
|
|
1592
|
-
|
|
1593
|
-
|
|
1594
|
-
|
|
1595
|
-
|
|
1544
|
+
it("does not log an audit line when no audit context is provided", async () => {
|
|
1545
|
+
const infoSpy = spyOn(logger, "info");
|
|
1546
|
+
infoSpy.mockClear();
|
|
1547
|
+
const user: HasSetPassword = {
|
|
1548
|
+
setPassword: (_password, callback) => callback?.(),
|
|
1549
|
+
};
|
|
1596
1550
|
|
|
1597
|
-
|
|
1598
|
-
|
|
1599
|
-
|
|
1600
|
-
|
|
1601
|
-
.send({name: "Updated"})
|
|
1602
|
-
.expect(404);
|
|
1551
|
+
await setPasswordForUser(user, "new-password");
|
|
1552
|
+
|
|
1553
|
+
expect(infoSpy).not.toHaveBeenCalled();
|
|
1554
|
+
infoSpy.mockRestore();
|
|
1603
1555
|
});
|
|
1604
1556
|
});
|
package/src/auth.ts
CHANGED
|
@@ -131,6 +131,102 @@ export const signupUser = async (
|
|
|
131
131
|
}
|
|
132
132
|
};
|
|
133
133
|
|
|
134
|
+
/** A user document exposing passport-local-mongoose's `setPassword`. */
|
|
135
|
+
export interface HasSetPassword {
|
|
136
|
+
_id?: unknown;
|
|
137
|
+
id?: string;
|
|
138
|
+
setPassword: (
|
|
139
|
+
password: string,
|
|
140
|
+
callback?: (error?: unknown) => void
|
|
141
|
+
) => Promise<unknown> | unknown;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/** Upper bound on password length accepted by {@link setPasswordForUser} (D5). */
|
|
145
|
+
export const MAX_PASSWORD_LENGTH = 256;
|
|
146
|
+
|
|
147
|
+
/** Optional audit context for {@link setPasswordForUser} — never includes the password itself. */
|
|
148
|
+
export interface SetPasswordAuditContext {
|
|
149
|
+
/** The admin performing the change, when set via an admin-only route. */
|
|
150
|
+
adminId?: unknown;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/**
|
|
154
|
+
* Sets a password on a passport-local-mongoose user document, returning a Promise regardless of
|
|
155
|
+
* whether the installed version of `setPassword` is callback- or promise-based. Newer versions
|
|
156
|
+
* return a promise while older ones only invoke the callback; this helper normalizes both and
|
|
157
|
+
* rejects after `timeoutMs` (default 15s) if neither settles. Call `user.save()` afterwards to
|
|
158
|
+
* persist the new hash/salt.
|
|
159
|
+
*
|
|
160
|
+
* Rejects synchronously (before touching `setPassword`) when `password` exceeds
|
|
161
|
+
* {@link MAX_PASSWORD_LENGTH} characters. When `audit.adminId` is provided (an admin-initiated
|
|
162
|
+
* password change), logs a `logger.info` audit line with the admin id, target user id, and
|
|
163
|
+
* timestamp — NEVER the password itself.
|
|
164
|
+
*/
|
|
165
|
+
export const setPasswordForUser = async (
|
|
166
|
+
user: HasSetPassword,
|
|
167
|
+
password: string,
|
|
168
|
+
timeoutMs = 15_000,
|
|
169
|
+
audit?: SetPasswordAuditContext
|
|
170
|
+
): Promise<void> => {
|
|
171
|
+
if (password.length > MAX_PASSWORD_LENGTH) {
|
|
172
|
+
throw new APIError({
|
|
173
|
+
status: 400,
|
|
174
|
+
title: `Password must be at most ${MAX_PASSWORD_LENGTH} characters`,
|
|
175
|
+
});
|
|
176
|
+
}
|
|
177
|
+
if (audit?.adminId !== undefined) {
|
|
178
|
+
const targetUserId = user._id ?? user.id ?? "unknown";
|
|
179
|
+
logger.info(
|
|
180
|
+
`[auth] Admin ${String(audit.adminId)} set password for user ${String(targetUserId)} ` +
|
|
181
|
+
`at ${DateTime.now().toISO()}`
|
|
182
|
+
);
|
|
183
|
+
}
|
|
184
|
+
await new Promise<void>((resolve, reject) => {
|
|
185
|
+
let isSettled = false;
|
|
186
|
+
const timeout = setTimeout(() => {
|
|
187
|
+
if (isSettled) {
|
|
188
|
+
return;
|
|
189
|
+
}
|
|
190
|
+
isSettled = true;
|
|
191
|
+
reject(new Error("Timed out while setting password"));
|
|
192
|
+
}, timeoutMs);
|
|
193
|
+
|
|
194
|
+
const resolveOnce = (): void => {
|
|
195
|
+
if (isSettled) {
|
|
196
|
+
return;
|
|
197
|
+
}
|
|
198
|
+
isSettled = true;
|
|
199
|
+
clearTimeout(timeout);
|
|
200
|
+
resolve();
|
|
201
|
+
};
|
|
202
|
+
|
|
203
|
+
const rejectOnce = (error: unknown): void => {
|
|
204
|
+
if (isSettled) {
|
|
205
|
+
return;
|
|
206
|
+
}
|
|
207
|
+
isSettled = true;
|
|
208
|
+
clearTimeout(timeout);
|
|
209
|
+
reject(error);
|
|
210
|
+
};
|
|
211
|
+
|
|
212
|
+
try {
|
|
213
|
+
const maybePromise = user.setPassword(password, (error?: unknown) => {
|
|
214
|
+
if (error) {
|
|
215
|
+
rejectOnce(error);
|
|
216
|
+
return;
|
|
217
|
+
}
|
|
218
|
+
resolveOnce();
|
|
219
|
+
});
|
|
220
|
+
|
|
221
|
+
if (maybePromise && typeof (maybePromise as Promise<unknown>).then === "function") {
|
|
222
|
+
(maybePromise as Promise<unknown>).then(resolveOnce).catch(rejectOnce);
|
|
223
|
+
}
|
|
224
|
+
} catch (error) {
|
|
225
|
+
rejectOnce(error);
|
|
226
|
+
}
|
|
227
|
+
});
|
|
228
|
+
};
|
|
229
|
+
|
|
134
230
|
/**
|
|
135
231
|
* Generates both an access token (JWT) and a refresh token for a given user.
|
|
136
232
|
*
|
|
@@ -322,6 +418,19 @@ export const setupAuth = (app: express.Application, userModel: UserModel): void
|
|
|
322
418
|
issuer: process.env.TOKEN_ISSUER,
|
|
323
419
|
}) as jwt.JwtPayload;
|
|
324
420
|
} catch (error: unknown) {
|
|
421
|
+
// A bearer token that is not a JWT at all (e.g. a Better Auth opaque session
|
|
422
|
+
// token) is not ours to reject — fall through so a later auth layer (Better
|
|
423
|
+
// Auth session middleware) or the route's own permissions can handle it.
|
|
424
|
+
// Detect this by decoding the token's header/payload structure (D1) rather
|
|
425
|
+
// than counting dot-delimited segments: an opaque token can coincidentally
|
|
426
|
+
// contain exactly two dots, and a malformed-but-JWT-shaped string can fail
|
|
427
|
+
// this same check for the wrong reason — `jwt.decode` parses the actual
|
|
428
|
+
// base64url JSON structure of each segment, which dot-counting cannot.
|
|
429
|
+
// Genuine JWTs that fail verification (malformed/expired) still return 401 so the
|
|
430
|
+
// client's token-refresh flow is preserved.
|
|
431
|
+
if (jwt.decode(token, {complete: true}) === null) {
|
|
432
|
+
return next();
|
|
433
|
+
}
|
|
325
434
|
const userText = req.user?._id ? ` for user ${req.user._id} ` : "";
|
|
326
435
|
const expiredAt =
|
|
327
436
|
error && typeof error === "object" && "expiredAt" in error
|
package/src/betterAuth.ts
CHANGED
|
@@ -43,6 +43,12 @@ export interface BetterAuthConfig {
|
|
|
43
43
|
*/
|
|
44
44
|
trustedOrigins?: string[];
|
|
45
45
|
|
|
46
|
+
/**
|
|
47
|
+
* Allow credential cookies when the frontend and API are hosted on different sites.
|
|
48
|
+
* Enables `SameSite=None; Secure` cookie attributes. Keep disabled for local HTTP.
|
|
49
|
+
*/
|
|
50
|
+
crossDomainCookies?: boolean;
|
|
51
|
+
|
|
46
52
|
/**
|
|
47
53
|
* Base path for Better Auth routes.
|
|
48
54
|
* @default "/api/auth"
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
// noExplicitAny: test mock typing
|
|
2
2
|
// biome-ignore-all lint/suspicious/noExplicitAny: test mock typing
|
|
3
3
|
import {afterAll, afterEach, describe, expect, it, mock} from "bun:test";
|
|
4
|
+
import {assert} from "chai";
|
|
4
5
|
import express from "express";
|
|
5
6
|
import {MongoMemoryServer} from "mongodb-memory-server";
|
|
6
7
|
import mongoose, {Schema} from "mongoose";
|
|
@@ -101,6 +102,39 @@ describe("createBetterAuth", () => {
|
|
|
101
102
|
expect(auth.api).toBeDefined();
|
|
102
103
|
});
|
|
103
104
|
|
|
105
|
+
it("sets cross-site session cookies when crossDomainCookies is enabled", async () => {
|
|
106
|
+
await setup;
|
|
107
|
+
const origin = "https://frontend.example.com";
|
|
108
|
+
const config: BetterAuthConfig = {
|
|
109
|
+
baseURL: "https://api.example.com",
|
|
110
|
+
crossDomainCookies: true,
|
|
111
|
+
enabled: true,
|
|
112
|
+
secret: "test-secret-at-least-32-characters-long",
|
|
113
|
+
trustedOrigins: [origin],
|
|
114
|
+
};
|
|
115
|
+
const auth = createBetterAuth({config, mongoClient: getClient()});
|
|
116
|
+
|
|
117
|
+
const response = await auth.handler(
|
|
118
|
+
new Request("https://api.example.com/api/auth/sign-up/email", {
|
|
119
|
+
body: JSON.stringify({
|
|
120
|
+
email: "cross-domain-cookie@example.com",
|
|
121
|
+
name: "Cross Domain",
|
|
122
|
+
password: "testpassword123",
|
|
123
|
+
}),
|
|
124
|
+
headers: {
|
|
125
|
+
"Content-Type": "application/json",
|
|
126
|
+
Origin: origin,
|
|
127
|
+
},
|
|
128
|
+
method: "POST",
|
|
129
|
+
})
|
|
130
|
+
);
|
|
131
|
+
const setCookie = response.headers.get("set-cookie") ?? "";
|
|
132
|
+
|
|
133
|
+
assert.isTrue(response.ok);
|
|
134
|
+
assert.include(setCookie.toLowerCase(), "samesite=none");
|
|
135
|
+
assert.include(setCookie.toLowerCase(), "secure");
|
|
136
|
+
});
|
|
137
|
+
|
|
104
138
|
it("creates instance with social providers", async () => {
|
|
105
139
|
await setup;
|
|
106
140
|
const config: BetterAuthConfig = {
|
package/src/betterAuthSetup.ts
CHANGED
|
@@ -8,6 +8,7 @@
|
|
|
8
8
|
import {betterAuth} from "better-auth";
|
|
9
9
|
import {mongodbAdapter} from "better-auth/adapters/mongodb";
|
|
10
10
|
import {toNodeHandler} from "better-auth/node";
|
|
11
|
+
import {bearer} from "better-auth/plugins";
|
|
11
12
|
import type {Application, NextFunction, Request, Response} from "express";
|
|
12
13
|
import mongoose from "mongoose";
|
|
13
14
|
import type {UserModel} from "./auth";
|
|
@@ -86,12 +87,27 @@ export const createBetterAuth = (options: CreateBetterAuthOptions): BetterAuthIn
|
|
|
86
87
|
}
|
|
87
88
|
|
|
88
89
|
const auth = betterAuth({
|
|
90
|
+
advanced: config.crossDomainCookies
|
|
91
|
+
? {
|
|
92
|
+
defaultCookieAttributes: {
|
|
93
|
+
httpOnly: true,
|
|
94
|
+
sameSite: "none",
|
|
95
|
+
secure: true,
|
|
96
|
+
},
|
|
97
|
+
}
|
|
98
|
+
: undefined,
|
|
89
99
|
basePath,
|
|
90
100
|
baseURL,
|
|
91
101
|
database: mongodbAdapter(mongoClient.db()),
|
|
92
102
|
emailAndPassword: {
|
|
93
103
|
enabled: true,
|
|
94
104
|
},
|
|
105
|
+
// The bearer plugin lets clients authenticate with `Authorization: Bearer <sessionToken>`
|
|
106
|
+
// instead of the signed session cookie. Required for cross-origin/native clients and for
|
|
107
|
+
// websocket handshakes (RealtimeApp's Better Auth socket validator forwards the handshake
|
|
108
|
+
// token as a bearer header) — without it, a raw session token cannot be validated and
|
|
109
|
+
// socket auth silently fails (the sync client shows perpetually "offline").
|
|
110
|
+
plugins: [bearer()],
|
|
95
111
|
secret,
|
|
96
112
|
session: {
|
|
97
113
|
cookieCache: {
|
|
@@ -103,7 +119,10 @@ export const createBetterAuth = (options: CreateBetterAuthOptions): BetterAuthIn
|
|
|
103
119
|
trustedOrigins: config.trustedOrigins ?? [],
|
|
104
120
|
});
|
|
105
121
|
|
|
106
|
-
|
|
122
|
+
// Cast through unknown: enabling the bearer plugin narrows betterAuth()'s inferred
|
|
123
|
+
// return type to a plugin-specific tuple that no longer matches the plugin-agnostic
|
|
124
|
+
// BetterAuthInstance alias, though the runtime instance is a valid better-auth instance.
|
|
125
|
+
return auth as unknown as BetterAuthInstance;
|
|
107
126
|
};
|
|
108
127
|
|
|
109
128
|
/**
|
|
@@ -173,7 +192,6 @@ export const createBetterAuthSessionMiddleware = (
|
|
|
173
192
|
// Loose shape used when mutating Mongoose user documents during Better Auth sync.
|
|
174
193
|
// The fields are added by the consumer's user schema (via baseUserPlugin or similar).
|
|
175
194
|
interface MutableUserDoc {
|
|
176
|
-
admin?: boolean;
|
|
177
195
|
email?: string;
|
|
178
196
|
name?: string;
|
|
179
197
|
betterAuthId?: string;
|
|
@@ -186,7 +204,9 @@ export const syncBetterAuthUser = async (
|
|
|
186
204
|
userModel: UserModel,
|
|
187
205
|
betterAuthUser: BetterAuthUser,
|
|
188
206
|
oauthProvider?: string
|
|
189
|
-
|
|
207
|
+
// noExplicitAny: return is a consumer-defined user document; tests inspect varied fields
|
|
208
|
+
// biome-ignore lint/suspicious/noExplicitAny: return is a consumer-defined user document; tests inspect varied fields
|
|
209
|
+
): Promise<any> => {
|
|
190
210
|
try {
|
|
191
211
|
const existingUser = (await findOneOrNoneFor(userModel, {
|
|
192
212
|
betterAuthId: betterAuthUser.id,
|
|
@@ -218,17 +238,16 @@ export const syncBetterAuthUser = async (
|
|
|
218
238
|
|
|
219
239
|
// Use Better Auth ID as _id when it's a valid ObjectId (MongoDB adapter) so frontend IDs match
|
|
220
240
|
const useAsId = mongoose.isValidObjectId(betterAuthUser.id) ? {_id: betterAuthUser.id} : {};
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
const newUser = new UserDocumentConstructor({
|
|
241
|
+
// noExplicitAny: userModel is generic across consumers — constructor args are runtime-validated
|
|
242
|
+
// biome-ignore lint/suspicious/noExplicitAny: userModel is generic across consumers — constructor args are runtime-validated
|
|
243
|
+
const newUser = new (userModel as any)({
|
|
225
244
|
...useAsId,
|
|
226
245
|
admin: false,
|
|
227
246
|
betterAuthId: betterAuthUser.id,
|
|
228
247
|
email: betterAuthUser.email,
|
|
229
248
|
name: betterAuthUser.name || betterAuthUser.email.split("@")[0],
|
|
230
249
|
oauthProvider: oauthProvider || null,
|
|
231
|
-
});
|
|
250
|
+
}) as MutableUserDoc;
|
|
232
251
|
await newUser.save();
|
|
233
252
|
logger.info(`Created new user from Better Auth: ${newUser.id}`);
|
|
234
253
|
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
|
+
{new: true, 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
|
+
{new: true, runValidators: true}
|
|
360
360
|
).orFail();
|
|
361
361
|
};
|
|
362
362
|
|