@terreno/api 0.31.0 → 56.0.0-beta.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/api.d.ts +10 -0
- package/dist/api.js +110 -361
- package/dist/auth.d.ts +26 -0
- package/dist/auth.js +121 -26
- package/dist/betterAuth.d.ts +5 -0
- package/dist/betterAuthSetup.js +23 -4
- package/dist/docLoader.js +12 -9
- package/dist/errors.d.ts +13 -0
- package/dist/errors.js +29 -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 +13 -0
- package/dist/plugins.js +47 -1
- package/dist/realtime/changeStreamWatcher.d.ts +100 -3
- package/dist/realtime/changeStreamWatcher.js +542 -137
- package/dist/realtime/realtimeApp.d.ts +2 -0
- package/dist/realtime/realtimeApp.js +83 -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 +54 -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 +899 -0
- package/dist/sync/types.d.ts +254 -0
- package/dist/sync/types.js +9 -0
- package/dist/terrenoApp.js +90 -27
- package/dist/vendor/wesleytodd-openapi/index.d.ts +1 -1
- package/dist/vendor/wesleytodd-openapi/lib/ui.d.ts +2 -1
- package/package.json +7 -6
- package/src/__tests__/openApiCompat.test.ts +20 -0
- package/src/api.errors.test.ts +32 -23
- package/src/api.test.ts +12 -0
- package/src/api.ts +87 -296
- package/src/auth.test.ts +202 -0
- package/src/auth.ts +134 -23
- package/src/betterAuth.ts +6 -0
- package/src/betterAuthSetup.test.ts +34 -0
- package/src/betterAuthSetup.ts +20 -1
- package/src/configuration.test.ts +59 -38
- package/src/configurationPlugin.test.ts +72 -42
- package/src/docLoader.ts +3 -1
- package/src/errors.ts +33 -0
- package/src/expressServer.test.ts +7 -1
- package/src/index.ts +42 -0
- package/src/middleware.test.ts +56 -1
- package/src/middleware.ts +15 -0
- package/src/openApiCompat.ts +99 -45
- package/src/permissions.test.ts +101 -17
- package/src/permissions.ts +49 -0
- package/src/plugins.test.ts +64 -0
- package/src/plugins.ts +56 -0
- package/src/realtime/changeStreamWatcher.ts +552 -114
- package/src/realtime/realtime.test.ts +157 -0
- package/src/realtime/realtimeApp.ts +82 -14
- package/src/realtime/realtimeAppSetup.test.ts +25 -27
- 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 +54 -0
- package/src/secretProviders.test.ts +7 -1
- package/src/secretProviders.ts +15 -3
- package/src/secretProvidersGcpClient.test.ts +66 -0
- package/src/sync/ensureSyncIndexes.test.ts +144 -0
- package/src/sync/executors.test.ts +882 -0
- package/src/sync/executors.ts +705 -0
- package/src/sync/integration.test.ts +1160 -0
- package/src/sync/loadHarness.ts +618 -0
- package/src/sync/models.ts +641 -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 +730 -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/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/dist/{__tests__/openApiCompat.test.d.ts → sync/loadHarness.d.ts} +0 -0
package/src/auth.test.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
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 {assert} from "chai";
|
|
4
5
|
import express from "express";
|
|
5
6
|
import type jwt from "jsonwebtoken";
|
|
6
7
|
import supertest from "supertest";
|
|
@@ -12,6 +13,9 @@ import {
|
|
|
12
13
|
addAuthRoutes,
|
|
13
14
|
addMeRoutes,
|
|
14
15
|
generateTokens,
|
|
16
|
+
type HasSetPassword,
|
|
17
|
+
MAX_PASSWORD_LENGTH,
|
|
18
|
+
setPasswordForUser,
|
|
15
19
|
setupAuth,
|
|
16
20
|
signupUser,
|
|
17
21
|
} from "./auth";
|
|
@@ -810,6 +814,38 @@ describe("generateTokens edge cases", () => {
|
|
|
810
814
|
expect(result.token).toBeDefined();
|
|
811
815
|
expect(result.refreshToken).toBeUndefined();
|
|
812
816
|
});
|
|
817
|
+
|
|
818
|
+
it("falls back to the default expiration when TOKEN_EXPIRES_IN is invalid", async () => {
|
|
819
|
+
process.env.TOKEN_EXPIRES_IN = "not-a-duration";
|
|
820
|
+
const errorSpy = spyOn(logger, "error").mockImplementation(() => logger);
|
|
821
|
+
try {
|
|
822
|
+
const result = await generateTokens({_id: "user-123"});
|
|
823
|
+
const decoded = decodeTokenPayload<{exp: number}>(result.token as string);
|
|
824
|
+
// Falls back to the 15 minute default rather than failing token generation.
|
|
825
|
+
const expectedExp = Math.floor(Date.now() / 1000) + 15 * 60;
|
|
826
|
+
assert.isAbove(decoded.exp, expectedExp - 10);
|
|
827
|
+
assert.isBelow(decoded.exp, expectedExp + 10);
|
|
828
|
+
assert.include(String(errorSpy.mock.calls[0]?.[0]), "TOKEN_EXPIRES_IN");
|
|
829
|
+
} finally {
|
|
830
|
+
errorSpy.mockRestore();
|
|
831
|
+
}
|
|
832
|
+
});
|
|
833
|
+
|
|
834
|
+
it("falls back to the default expiration when REFRESH_TOKEN_EXPIRES_IN is invalid", async () => {
|
|
835
|
+
process.env.REFRESH_TOKEN_EXPIRES_IN = "not-a-duration";
|
|
836
|
+
const errorSpy = spyOn(logger, "error").mockImplementation(() => logger);
|
|
837
|
+
try {
|
|
838
|
+
const result = await generateTokens({_id: "user-123"});
|
|
839
|
+
const decoded = decodeTokenPayload<{exp: number}>(result.refreshToken as string);
|
|
840
|
+
// Falls back to the 30 day default rather than failing token generation.
|
|
841
|
+
const expectedExp = Math.floor(Date.now() / 1000) + 30 * 24 * 3600;
|
|
842
|
+
assert.isAbove(decoded.exp, expectedExp - 10);
|
|
843
|
+
assert.isBelow(decoded.exp, expectedExp + 10);
|
|
844
|
+
assert.include(String(errorSpy.mock.calls[0]?.[0]), "REFRESH_TOKEN_EXPIRES_IN");
|
|
845
|
+
} finally {
|
|
846
|
+
errorSpy.mockRestore();
|
|
847
|
+
}
|
|
848
|
+
});
|
|
813
849
|
});
|
|
814
850
|
|
|
815
851
|
describe("addAuthRoutes /refresh_token error paths", () => {
|
|
@@ -1369,6 +1405,40 @@ describe("decodeJWTMiddleware error paths", () => {
|
|
|
1369
1405
|
const res = await agent.get("/food").set("authorization", "Bearer undefined").expect(200);
|
|
1370
1406
|
expect(res.body.data).toBeDefined();
|
|
1371
1407
|
});
|
|
1408
|
+
|
|
1409
|
+
// D1: the JWT-vs-non-JWT fallthrough now decodes the token's header/payload
|
|
1410
|
+
// structure (jwt.decode with complete: true) instead of counting dots, so it is
|
|
1411
|
+
// robust to opaque tokens that coincidentally contain two dots and to malformed
|
|
1412
|
+
// strings that happen to have three dot-delimited segments without real JWT
|
|
1413
|
+
// structure.
|
|
1414
|
+
it("falls through (200, no 401) for an opaque non-JWT bearer token with two dots", async () => {
|
|
1415
|
+
// An opaque token shaped like a Better Auth session id — has exactly two dots
|
|
1416
|
+
// but is not base64url-encoded JSON in any segment.
|
|
1417
|
+
const res = await agent
|
|
1418
|
+
.get("/food")
|
|
1419
|
+
.set("authorization", "Bearer not.a.jwt-at-all")
|
|
1420
|
+
.expect(200);
|
|
1421
|
+
expect(res.body.data).toBeDefined();
|
|
1422
|
+
});
|
|
1423
|
+
|
|
1424
|
+
it("falls through (200, no 401) for a three-dot string with no real JWT header/payload structure", async () => {
|
|
1425
|
+
// Exactly three dot-delimited segments (would have been treated as "a JWT" by
|
|
1426
|
+
// the old dot-counting check) but none are valid base64url JSON.
|
|
1427
|
+
const res = await agent.get("/food").set("authorization", "Bearer abc.def.ghi").expect(200);
|
|
1428
|
+
expect(res.body.data).toBeDefined();
|
|
1429
|
+
});
|
|
1430
|
+
|
|
1431
|
+
it("returns 401 for a genuinely malformed JWT-shaped token (decodable header, bad signature)", async () => {
|
|
1432
|
+
const jwtLib = await import("jsonwebtoken");
|
|
1433
|
+
// A well-formed JWT (decodable header/payload) but signed with the wrong
|
|
1434
|
+
// secret — jwt.verify throws, and jwt.decode succeeds (it is a real JWT), so
|
|
1435
|
+
// this must still 401 rather than fall through.
|
|
1436
|
+
const badToken = jwtLib.sign({id: "someone"}, "wrong-secret", {
|
|
1437
|
+
issuer: process.env.TOKEN_ISSUER,
|
|
1438
|
+
});
|
|
1439
|
+
const res = await agent.get("/food").set("authorization", `Bearer ${badToken}`);
|
|
1440
|
+
expect(res.status).toBe(401);
|
|
1441
|
+
});
|
|
1372
1442
|
});
|
|
1373
1443
|
|
|
1374
1444
|
describe("signup disabled", () => {
|
|
@@ -1400,6 +1470,126 @@ describe("signup disabled", () => {
|
|
|
1400
1470
|
});
|
|
1401
1471
|
});
|
|
1402
1472
|
|
|
1473
|
+
describe("setPasswordForUser", () => {
|
|
1474
|
+
it("resolves when a callback-based setPassword invokes the callback with no error", async () => {
|
|
1475
|
+
let receivedPassword: string | undefined;
|
|
1476
|
+
const user: HasSetPassword = {
|
|
1477
|
+
setPassword: (password, callback) => {
|
|
1478
|
+
receivedPassword = password;
|
|
1479
|
+
callback?.();
|
|
1480
|
+
},
|
|
1481
|
+
};
|
|
1482
|
+
|
|
1483
|
+
await setPasswordForUser(user, "new-password");
|
|
1484
|
+
expect(receivedPassword).toBe("new-password");
|
|
1485
|
+
});
|
|
1486
|
+
|
|
1487
|
+
it("resolves when setPassword returns a promise", async () => {
|
|
1488
|
+
let receivedPassword: string | undefined;
|
|
1489
|
+
const user: HasSetPassword = {
|
|
1490
|
+
setPassword: async (password) => {
|
|
1491
|
+
receivedPassword = password;
|
|
1492
|
+
},
|
|
1493
|
+
};
|
|
1494
|
+
|
|
1495
|
+
await setPasswordForUser(user, "promise-password");
|
|
1496
|
+
expect(receivedPassword).toBe("promise-password");
|
|
1497
|
+
});
|
|
1498
|
+
|
|
1499
|
+
it("rejects when the callback is invoked with an error", async () => {
|
|
1500
|
+
const user: HasSetPassword = {
|
|
1501
|
+
setPassword: (_password, callback) => {
|
|
1502
|
+
callback?.(new Error("boom"));
|
|
1503
|
+
},
|
|
1504
|
+
};
|
|
1505
|
+
|
|
1506
|
+
await expect(setPasswordForUser(user, "pw")).rejects.toThrow("boom");
|
|
1507
|
+
});
|
|
1508
|
+
|
|
1509
|
+
it("rejects when setPassword throws synchronously", async () => {
|
|
1510
|
+
const user: HasSetPassword = {
|
|
1511
|
+
setPassword: () => {
|
|
1512
|
+
throw new Error("sync failure");
|
|
1513
|
+
},
|
|
1514
|
+
};
|
|
1515
|
+
|
|
1516
|
+
await expect(setPasswordForUser(user, "pw")).rejects.toThrow("sync failure");
|
|
1517
|
+
});
|
|
1518
|
+
|
|
1519
|
+
it("rejects with a timeout when setPassword never settles", async () => {
|
|
1520
|
+
const user: HasSetPassword = {
|
|
1521
|
+
setPassword: () => {
|
|
1522
|
+
// Never invokes the callback and returns nothing (no promise).
|
|
1523
|
+
},
|
|
1524
|
+
};
|
|
1525
|
+
|
|
1526
|
+
await expect(setPasswordForUser(user, "pw", 10)).rejects.toThrow(
|
|
1527
|
+
"Timed out while setting password"
|
|
1528
|
+
);
|
|
1529
|
+
});
|
|
1530
|
+
|
|
1531
|
+
it("rejects passwords longer than MAX_PASSWORD_LENGTH without calling setPassword", async () => {
|
|
1532
|
+
let called = false;
|
|
1533
|
+
const user: HasSetPassword = {
|
|
1534
|
+
setPassword: (_password, callback) => {
|
|
1535
|
+
called = true;
|
|
1536
|
+
callback?.();
|
|
1537
|
+
},
|
|
1538
|
+
};
|
|
1539
|
+
const tooLong = "x".repeat(MAX_PASSWORD_LENGTH + 1);
|
|
1540
|
+
|
|
1541
|
+
await expect(setPasswordForUser(user, tooLong)).rejects.toThrow(
|
|
1542
|
+
`Password must be at most ${MAX_PASSWORD_LENGTH} characters`
|
|
1543
|
+
);
|
|
1544
|
+
expect(called).toBe(false);
|
|
1545
|
+
});
|
|
1546
|
+
|
|
1547
|
+
it("accepts a password exactly at MAX_PASSWORD_LENGTH", async () => {
|
|
1548
|
+
let receivedPassword: string | undefined;
|
|
1549
|
+
const user: HasSetPassword = {
|
|
1550
|
+
setPassword: (password, callback) => {
|
|
1551
|
+
receivedPassword = password;
|
|
1552
|
+
callback?.();
|
|
1553
|
+
},
|
|
1554
|
+
};
|
|
1555
|
+
const atLimit = "x".repeat(MAX_PASSWORD_LENGTH);
|
|
1556
|
+
|
|
1557
|
+
await setPasswordForUser(user, atLimit);
|
|
1558
|
+
expect(receivedPassword).toBe(atLimit);
|
|
1559
|
+
});
|
|
1560
|
+
|
|
1561
|
+
it("logs an audit line with the admin id and target user id when audit context is provided", async () => {
|
|
1562
|
+
const infoSpy = spyOn(logger, "info");
|
|
1563
|
+
infoSpy.mockClear();
|
|
1564
|
+
const user: HasSetPassword = {
|
|
1565
|
+
_id: "target-user-id",
|
|
1566
|
+
setPassword: (_password, callback) => callback?.(),
|
|
1567
|
+
};
|
|
1568
|
+
|
|
1569
|
+
await setPasswordForUser(user, "new-password", undefined, {adminId: "admin-id-123"});
|
|
1570
|
+
|
|
1571
|
+
expect(infoSpy).toHaveBeenCalledTimes(1);
|
|
1572
|
+
const [message] = infoSpy.mock.calls[0] as [string];
|
|
1573
|
+
expect(message).toContain("admin-id-123");
|
|
1574
|
+
expect(message).toContain("target-user-id");
|
|
1575
|
+
expect(message).not.toContain("new-password");
|
|
1576
|
+
infoSpy.mockRestore();
|
|
1577
|
+
});
|
|
1578
|
+
|
|
1579
|
+
it("does not log an audit line when no audit context is provided", async () => {
|
|
1580
|
+
const infoSpy = spyOn(logger, "info");
|
|
1581
|
+
infoSpy.mockClear();
|
|
1582
|
+
const user: HasSetPassword = {
|
|
1583
|
+
setPassword: (_password, callback) => callback?.(),
|
|
1584
|
+
};
|
|
1585
|
+
|
|
1586
|
+
await setPasswordForUser(user, "new-password");
|
|
1587
|
+
|
|
1588
|
+
expect(infoSpy).not.toHaveBeenCalled();
|
|
1589
|
+
infoSpy.mockRestore();
|
|
1590
|
+
});
|
|
1591
|
+
});
|
|
1592
|
+
|
|
1403
1593
|
describe("signupUser postCreate failures", () => {
|
|
1404
1594
|
it("wraps and rethrows errors thrown by user.postCreate", async () => {
|
|
1405
1595
|
let saveCalled = false;
|
|
@@ -1554,6 +1744,18 @@ describe("auth logging outside of the test environment", () => {
|
|
|
1554
1744
|
});
|
|
1555
1745
|
});
|
|
1556
1746
|
|
|
1747
|
+
describe("setupAuth validation", () => {
|
|
1748
|
+
it("throws when the user model has no createStrategy", () => {
|
|
1749
|
+
const app = getBaseServer();
|
|
1750
|
+
const modelWithoutStrategy = {} as unknown as AuthUserModel;
|
|
1751
|
+
|
|
1752
|
+
assert.throws(
|
|
1753
|
+
() => setupAuth(app, modelWithoutStrategy),
|
|
1754
|
+
"setupAuth userModel must have .createStrategy()"
|
|
1755
|
+
);
|
|
1756
|
+
});
|
|
1757
|
+
});
|
|
1758
|
+
|
|
1557
1759
|
describe("/me routes with an already populated req.user", () => {
|
|
1558
1760
|
const buildApp = (
|
|
1559
1761
|
user: {_id?: string; id?: string} | undefined,
|
package/src/auth.ts
CHANGED
|
@@ -131,6 +131,114 @@ 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
|
+
|
|
230
|
+
/**
|
|
231
|
+
* Returns the duration when `ms` can parse it, otherwise logs and returns undefined so the caller
|
|
232
|
+
* keeps its default. Signing a token with an unparseable duration throws instead.
|
|
233
|
+
*/
|
|
234
|
+
const validateDuration = (envName: string, value: string): StringValue | undefined => {
|
|
235
|
+
if (ms(value as StringValue) === undefined) {
|
|
236
|
+
logger.error(`${envName} is not a valid duration: "${value}". Using the default instead.`);
|
|
237
|
+
return undefined;
|
|
238
|
+
}
|
|
239
|
+
return value as StringValue;
|
|
240
|
+
};
|
|
241
|
+
|
|
134
242
|
/**
|
|
135
243
|
* Generates both an access token (JWT) and a refresh token for a given user.
|
|
136
244
|
*
|
|
@@ -173,14 +281,9 @@ export const generateTokens = async (
|
|
|
173
281
|
if (authOptions?.generateTokenExpiration) {
|
|
174
282
|
tokenOptions.expiresIn = authOptions.generateTokenExpiration(user);
|
|
175
283
|
} else if (process.env.TOKEN_EXPIRES_IN) {
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
ms(process.env.TOKEN_EXPIRES_IN as StringValue);
|
|
180
|
-
tokenOptions.expiresIn = process.env.TOKEN_EXPIRES_IN as StringValue;
|
|
181
|
-
} catch (error) {
|
|
182
|
-
// This error will result in using the default value above of 15m.
|
|
183
|
-
logger.error(error as string);
|
|
284
|
+
const expiresIn = validateDuration("TOKEN_EXPIRES_IN", process.env.TOKEN_EXPIRES_IN);
|
|
285
|
+
if (expiresIn) {
|
|
286
|
+
tokenOptions.expiresIn = expiresIn;
|
|
184
287
|
}
|
|
185
288
|
}
|
|
186
289
|
if (process.env.TOKEN_ISSUER) {
|
|
@@ -197,14 +300,12 @@ export const generateTokens = async (
|
|
|
197
300
|
if (authOptions?.generateRefreshTokenExpiration) {
|
|
198
301
|
refreshTokenOptions.expiresIn = authOptions.generateRefreshTokenExpiration(user);
|
|
199
302
|
} else if (process.env.REFRESH_TOKEN_EXPIRES_IN) {
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
// This error will result in using the default value above of 30d.
|
|
207
|
-
logger.error(error as string);
|
|
303
|
+
const expiresIn = validateDuration(
|
|
304
|
+
"REFRESH_TOKEN_EXPIRES_IN",
|
|
305
|
+
process.env.REFRESH_TOKEN_EXPIRES_IN
|
|
306
|
+
);
|
|
307
|
+
if (expiresIn) {
|
|
308
|
+
refreshTokenOptions.expiresIn = expiresIn;
|
|
208
309
|
}
|
|
209
310
|
}
|
|
210
311
|
refreshToken = jwt.sign(payload, refreshTokenSecretOrKey, refreshTokenOptions);
|
|
@@ -215,6 +316,10 @@ export const generateTokens = async (
|
|
|
215
316
|
};
|
|
216
317
|
|
|
217
318
|
export const setupAuth = (app: express.Application, userModel: UserModel): void => {
|
|
319
|
+
if (!userModel.createStrategy) {
|
|
320
|
+
throw new APIError({status: 500, title: "setupAuth userModel must have .createStrategy()"});
|
|
321
|
+
}
|
|
322
|
+
|
|
218
323
|
passport.use(new AnonymousStrategy());
|
|
219
324
|
passport.use(userModel.createStrategy());
|
|
220
325
|
passport.use(
|
|
@@ -235,10 +340,6 @@ export const setupAuth = (app: express.Application, userModel: UserModel): void
|
|
|
235
340
|
) as passport.Strategy
|
|
236
341
|
);
|
|
237
342
|
|
|
238
|
-
if (!userModel.createStrategy) {
|
|
239
|
-
throw new APIError({status: 500, title: "setupAuth userModel must have .createStrategy()"});
|
|
240
|
-
}
|
|
241
|
-
|
|
242
343
|
const customTokenExtractor: JwtFromRequestFunction = (req) => {
|
|
243
344
|
let token: string | null = null;
|
|
244
345
|
if (req?.cookies?.jwt) {
|
|
@@ -255,9 +356,6 @@ export const setupAuth = (app: express.Application, userModel: UserModel): void
|
|
|
255
356
|
}
|
|
256
357
|
|
|
257
358
|
const secretOrKey = process.env.TOKEN_SECRET;
|
|
258
|
-
if (!secretOrKey) {
|
|
259
|
-
throw new APIError({status: 500, title: "TOKEN_SECRET must be set in env."});
|
|
260
|
-
}
|
|
261
359
|
const jwtOpts: StrategyOptions = {
|
|
262
360
|
issuer: process.env.TOKEN_ISSUER,
|
|
263
361
|
jwtFromRequest: customTokenExtractor,
|
|
@@ -322,6 +420,19 @@ export const setupAuth = (app: express.Application, userModel: UserModel): void
|
|
|
322
420
|
issuer: process.env.TOKEN_ISSUER,
|
|
323
421
|
}) as jwt.JwtPayload;
|
|
324
422
|
} catch (error: unknown) {
|
|
423
|
+
// A bearer token that is not a JWT at all (e.g. a Better Auth opaque session
|
|
424
|
+
// token) is not ours to reject — fall through so a later auth layer (Better
|
|
425
|
+
// Auth session middleware) or the route's own permissions can handle it.
|
|
426
|
+
// Detect this by decoding the token's header/payload structure (D1) rather
|
|
427
|
+
// than counting dot-delimited segments: an opaque token can coincidentally
|
|
428
|
+
// contain exactly two dots, and a malformed-but-JWT-shaped string can fail
|
|
429
|
+
// this same check for the wrong reason — `jwt.decode` parses the actual
|
|
430
|
+
// base64url JSON structure of each segment, which dot-counting cannot.
|
|
431
|
+
// Genuine JWTs that fail verification (malformed/expired) still return 401 so the
|
|
432
|
+
// client's token-refresh flow is preserved.
|
|
433
|
+
if (jwt.decode(token, {complete: true}) === null) {
|
|
434
|
+
return next();
|
|
435
|
+
}
|
|
325
436
|
const userText = req.user?._id ? ` for user ${req.user._id} ` : "";
|
|
326
437
|
const expiredAt =
|
|
327
438
|
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
|
/**
|