@terreno/api 57.4.0 → 57.6.1
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 +5 -5
- package/bunfig.toml +1 -1
- package/dist/actions.js +197 -368
- package/dist/adminModelRouter.js +88 -173
- package/dist/api.js +617 -852
- package/dist/audit/auditApp.js +48 -89
- package/dist/audit/auditEventModel.js +15 -16
- package/dist/audit/cloudTasksEnqueue.js +56 -149
- package/dist/audit/diff.js +70 -160
- package/dist/audit/processQueue.js +25 -70
- package/dist/audit/rbacSink.js +25 -66
- package/dist/audit/record.js +129 -251
- package/dist/auth.js +432 -681
- package/dist/authRecovery.js +155 -269
- package/dist/authTokens.js +43 -118
- package/dist/betterAuthApp.js +25 -26
- package/dist/betterAuthSetup.js +258 -413
- package/dist/browserLogsRoute.d.ts +6 -0
- package/dist/browserLogsRoute.js +97 -0
- package/dist/collectionRegistry.js +32 -47
- package/dist/config.js +53 -122
- package/dist/configurationApp.js +180 -361
- package/dist/configurationPlugin.js +130 -302
- package/dist/consentApp.js +276 -421
- package/dist/docLoader.js +78 -126
- package/dist/envConfigurationPlugin.js +25 -147
- package/dist/errors.js +151 -247
- package/dist/example.js +28 -34
- package/dist/expressServer.d.ts +10 -0
- package/dist/expressServer.js +109 -255
- package/dist/frameworkModelNames.d.ts +24 -0
- package/dist/frameworkModelNames.js +31 -0
- package/dist/githubAuth.js +152 -216
- package/dist/httpClient.js +176 -264
- package/dist/index.d.ts +2 -0
- package/dist/index.js +7 -2
- package/dist/logger.js +145 -278
- package/dist/mcp/auth.js +76 -128
- package/dist/mcp/createMCPRequest.js +4 -5
- package/dist/mcp/handlers.js +268 -480
- package/dist/mcp/query.js +56 -150
- package/dist/mcp/registry.js +17 -30
- package/dist/mcp/schemaGenerator.js +95 -181
- package/dist/mcp/server.js +28 -100
- package/dist/mcp/serviceTokens.js +102 -191
- package/dist/mcp/toolGenerator.js +78 -191
- package/dist/middleware.js +15 -27
- package/dist/migrations/fixtures/all-down/20260910120000-one.js +2 -42
- package/dist/migrations/fixtures/all-down/20260910120001-two.js +2 -42
- package/dist/migrations/fixtures/bad-id/20260910120000-mismatch.js +1 -39
- package/dist/migrations/fixtures/bad-name/not-a-migration.js +1 -39
- package/dist/migrations/fixtures/valid/20260910120000-alpha.js +1 -39
- package/dist/migrations/fixtures/valid/20260910120001-beta.js +2 -42
- package/dist/migrations/generate.js +107 -229
- package/dist/migrations/load.js +75 -201
- package/dist/migrations/lock.js +54 -126
- package/dist/migrations/runner.js +192 -446
- package/dist/migrations/schemaCatalog.js +122 -263
- package/dist/models/consentForm.js +6 -6
- package/dist/models/consentResponse.js +5 -5
- package/dist/models/mcpServiceToken.js +66 -156
- package/dist/models/notification.js +6 -6
- package/dist/models/notificationPreference.js +6 -6
- package/dist/models/versionConfig.js +5 -5
- package/dist/notifications/notificationService.js +133 -273
- package/dist/notifications/notificationsApp.js +85 -179
- package/dist/notifications/notificationsBeforeSend.js +19 -64
- package/dist/notifiers/googleChatNotifier.js +36 -117
- package/dist/notifiers/slackNotifier.d.ts +31 -2
- package/dist/notifiers/slackNotifier.js +170 -119
- package/dist/notifiers/zoomNotifier.js +60 -111
- package/dist/openApi.js +107 -122
- package/dist/openApiBuilder.js +117 -159
- package/dist/openApiCompat.js +81 -148
- package/dist/openApiEtag.js +7 -7
- package/dist/openApiValidator.js +177 -286
- package/dist/orgs/orgContext.js +87 -157
- package/dist/orgs/orgPermissions.js +29 -68
- package/dist/orgs/orgPlugin.js +9 -27
- package/dist/orgs/organizationModel.js +65 -166
- package/dist/orgs/organizationSettings.js +29 -36
- package/dist/orgs/orgsApp.js +346 -608
- package/dist/permissions.js +88 -181
- package/dist/plugins.js +125 -218
- package/dist/populate.js +130 -240
- package/dist/rateLimit/applyTrustProxy.js +1 -1
- package/dist/rateLimit/createStore.js +7 -8
- package/dist/rateLimit/memoryStore.js +22 -100
- package/dist/rateLimit/middleware.js +48 -99
- package/dist/rateLimit/mongoStore.js +54 -112
- package/dist/rateLimit/policies.js +41 -75
- package/dist/rateLimit/redisStore.js +39 -133
- package/dist/rbac/access.js +119 -267
- package/dist/rbac/assertAllowed.js +95 -171
- package/dist/rbac/auditModel.js +14 -58
- package/dist/rbac/backfillAdmins.js +24 -130
- package/dist/rbac/fieldViews.js +46 -141
- package/dist/rbac/membershipOrgAdminSource.js +28 -99
- package/dist/rbac/middleware.js +30 -96
- package/dist/rbac/modelRouterAccess.js +130 -307
- package/dist/rbac/permissionUtils.js +40 -179
- package/dist/rbac/realtimeAccess.js +81 -147
- package/dist/rbac/resolve.d.ts +1 -1
- package/dist/rbac/resolve.js +148 -342
- package/dist/rbac/roleManager.js +318 -700
- package/dist/rbac/roleModel.js +44 -171
- package/dist/rbac/routes.js +93 -196
- package/dist/rbac/scopes.js +39 -133
- package/dist/rbac/statements.js +23 -91
- package/dist/rbac/userPlugin.js +3 -29
- package/dist/realtime/changeStreamWatcher.js +489 -800
- package/dist/realtime/deprecation.js +8 -10
- package/dist/realtime/queryMatcher.js +110 -191
- package/dist/realtime/queryStore.js +35 -118
- package/dist/realtime/realtimeApp.js +247 -401
- package/dist/realtime/registry.js +19 -30
- package/dist/realtime/sessionRevalidation.js +132 -358
- package/dist/realtime/socketAuth.js +89 -208
- package/dist/realtime/socketUser.js +10 -56
- package/dist/requestContext.js +93 -139
- package/dist/schemaMetadata.js +179 -274
- package/dist/scriptRunner.js +96 -266
- package/dist/scrubAdminFields.js +36 -108
- package/dist/secretProviders.js +130 -299
- package/dist/seedRunner.js +221 -514
- package/dist/sync/adminBroadcastScope.js +58 -170
- package/dist/sync/adminWindowAccess.js +15 -86
- package/dist/sync/adminWindowMutation.js +110 -181
- package/dist/sync/executors.js +425 -629
- package/dist/sync/loadHarness.js +392 -689
- package/dist/sync/models.js +181 -341
- package/dist/sync/mutationHandler.js +533 -801
- package/dist/sync/registrationSideEffects.js +41 -95
- package/dist/sync/registry.js +29 -49
- package/dist/sync/routes.js +484 -817
- package/dist/sync/scripts/compactTombstones.js +83 -228
- package/dist/sync/serialize.js +18 -58
- package/dist/sync/socketHandlers.js +253 -478
- package/dist/sync/streams.js +49 -117
- package/dist/sync/syncApp.js +12 -15
- package/dist/sync/syncBatch.js +63 -168
- package/dist/sync/syncSeqPlugin.js +430 -702
- package/dist/syncConsents.js +113 -253
- package/dist/terrenoApp.js +166 -276
- package/dist/tests/createTestData.js +146 -256
- package/dist/tests/models.js +14 -54
- package/dist/tests/mongoTestSetup.js +42 -103
- package/dist/tests/testHelper.js +31 -93
- package/dist/tests.js +12 -51
- package/dist/transformers.js +61 -164
- package/dist/utils.js +31 -93
- package/dist/vendor/wesleytodd-openapi/index.js +37 -51
- package/dist/vendor/wesleytodd-openapi/lib/generate-doc.js +32 -40
- package/dist/vendor/wesleytodd-openapi/lib/layer-schema.js +3 -3
- package/dist/vendor/wesleytodd-openapi/lib/ui.js +50 -19
- package/dist/vendor/wesleytodd-openapi/lib/validate.js +19 -47
- package/dist/versionCheckPlugin.js +52 -100
- package/dist/webhooks/headerValue.js +2 -2
- package/dist/webhooks/idempotency/memoryStore.js +16 -59
- package/dist/webhooks/idempotency/mongoStore.js +55 -130
- package/dist/webhooks/idempotency/webhookReceipt.js +9 -9
- package/dist/webhooks/rawBody.js +1 -1
- package/dist/webhooks/timingSafeEqual.js +4 -5
- package/dist/webhooks/verifiers/hmac.js +17 -18
- package/dist/webhooks/verifiers/sendgrid.js +20 -22
- package/dist/webhooks/verifiers/stripe.js +31 -65
- package/dist/webhooks/verifiers/twilio.js +23 -73
- package/dist/webhooks/webhooksApp.js +78 -177
- package/dist/zodOpenApi.js +2 -2
- package/package.json +6 -6
- package/src/__tests__/browserLogsRoute.test.ts +165 -0
- package/src/api.arrayOperations.test.ts +44 -0
- package/src/api.ts +64 -39
- package/src/audit/auditApp.test.ts +5 -5
- package/src/audit/auditEventModel.ts +7 -3
- package/src/audit/auditRouter.test.ts +5 -5
- package/src/audit/rbacSink.test.ts +2 -2
- package/src/audit/record.test.ts +2 -2
- package/src/audit/record.ts +3 -2
- package/src/auth.ts +1 -1
- package/src/authRecovery.test.ts +43 -0
- package/src/authRecovery.ts +16 -10
- package/src/authTokens.ts +6 -2
- package/src/authVerification.test.ts +22 -0
- package/src/browserLogsRoute.ts +110 -0
- package/src/configurationPlugin.test.ts +1 -11
- package/src/expressServer.ts +10 -0
- package/src/frameworkModelNames.test.ts +62 -0
- package/src/frameworkModelNames.ts +33 -0
- package/src/index.ts +7 -0
- package/src/isolated/migrateCliConnect.isolated.ts +51 -0
- package/src/mcp/auth.test.ts +34 -1
- package/src/migrations/cli.test.ts +0 -23
- package/src/models/mcpServiceToken.ts +4 -3
- package/src/models/notification.ts +3 -2
- package/src/models/notificationPreference.ts +1 -1
- package/src/notifications/notificationsApp.test.ts +24 -1
- package/src/notifiers/slackNotifier.test.ts +186 -1
- package/src/notifiers/slackNotifier.ts +167 -8
- package/src/orgs/orgPlugin.ts +1 -1
- package/src/orgs/organizationModel.ts +11 -6
- package/src/plugins.test.ts +5 -0
- package/src/plugins.ts +3 -0
- package/src/realtime/realtimeApp.ts +1 -1
- package/src/sync/integration.test.ts +2 -2
- package/src/terrenoApp.ts +3 -0
- package/src/types.d.ts +1 -0
- package/src/webhooks/idempotency/webhookReceipt.ts +4 -3
- package/tsconfig.json +13 -54
- package/tsconfig.typedoc.json +2 -0
package/dist/betterAuthSetup.js
CHANGED
|
@@ -5,69 +5,22 @@
|
|
|
5
5
|
* This module provides functions to initialize Better Auth with MongoDB,
|
|
6
6
|
* create session middleware, and sync users with the application User model.
|
|
7
7
|
*/
|
|
8
|
-
var __assign = (this && this.__assign) || function () {
|
|
9
|
-
__assign = Object.assign || function(t) {
|
|
10
|
-
for (var s, i = 1, n = arguments.length; i < n; i++) {
|
|
11
|
-
s = arguments[i];
|
|
12
|
-
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
|
|
13
|
-
t[p] = s[p];
|
|
14
|
-
}
|
|
15
|
-
return t;
|
|
16
|
-
};
|
|
17
|
-
return __assign.apply(this, arguments);
|
|
18
|
-
};
|
|
19
|
-
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
|
20
|
-
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
|
21
|
-
return new (P || (P = Promise))(function (resolve, reject) {
|
|
22
|
-
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
|
23
|
-
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
|
24
|
-
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
|
25
|
-
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
26
|
-
});
|
|
27
|
-
};
|
|
28
|
-
var __generator = (this && this.__generator) || function (thisArg, body) {
|
|
29
|
-
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
|
|
30
|
-
return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
|
|
31
|
-
function verb(n) { return function (v) { return step([n, v]); }; }
|
|
32
|
-
function step(op) {
|
|
33
|
-
if (f) throw new TypeError("Generator is already executing.");
|
|
34
|
-
while (g && (g = 0, op[0] && (_ = 0)), _) try {
|
|
35
|
-
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
|
|
36
|
-
if (y = 0, t) op = [op[0] & 2, t.value];
|
|
37
|
-
switch (op[0]) {
|
|
38
|
-
case 0: case 1: t = op; break;
|
|
39
|
-
case 4: _.label++; return { value: op[1], done: false };
|
|
40
|
-
case 5: _.label++; y = op[1]; op = [0]; continue;
|
|
41
|
-
case 7: op = _.ops.pop(); _.trys.pop(); continue;
|
|
42
|
-
default:
|
|
43
|
-
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
|
|
44
|
-
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
|
|
45
|
-
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
|
|
46
|
-
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
|
|
47
|
-
if (t[2]) _.ops.pop();
|
|
48
|
-
_.trys.pop(); continue;
|
|
49
|
-
}
|
|
50
|
-
op = body.call(thisArg, _);
|
|
51
|
-
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
|
|
52
|
-
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
|
|
53
|
-
}
|
|
54
|
-
};
|
|
55
8
|
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
56
9
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
57
10
|
};
|
|
58
11
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
59
12
|
exports.hasBetterAuthSession = exports.getBetterAuthSession = exports.setupBetterAuthUserSync = exports.getMongoClientFromMongoose = exports.mountBetterAuthRoutes = exports.syncBetterAuthUser = exports.createBetterAuthSessionMiddleware = exports.applyBetterAuthPasswordResetToJwt = exports.readPasswordFromBetterAuthResetRequest = exports.applyJwtPasswordResetToBetterAuth = exports.createBetterAuth = exports.createBetterAuthEmailHooks = void 0;
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
13
|
+
const better_auth_1 = require("better-auth");
|
|
14
|
+
const mongodb_1 = require("better-auth/adapters/mongodb");
|
|
15
|
+
const node_1 = require("better-auth/node");
|
|
16
|
+
const plugins_1 = require("better-auth/plugins");
|
|
17
|
+
const mongoose_1 = __importDefault(require("mongoose"));
|
|
18
|
+
const auth_1 = require("./auth");
|
|
19
|
+
const errors_1 = require("./errors");
|
|
20
|
+
const logger_1 = require("./logger");
|
|
21
|
+
const plugins_2 = require("./plugins");
|
|
22
|
+
const requestContext_1 = require("./requestContext");
|
|
23
|
+
const FALLBACK_AUTH_MAIL = {
|
|
71
24
|
resetPassword: {
|
|
72
25
|
html: '<p><a href="{{resetUrl}}">Reset your password</a></p>',
|
|
73
26
|
subject: "Reset your password",
|
|
@@ -79,112 +32,80 @@ var FALLBACK_AUTH_MAIL = {
|
|
|
79
32
|
text: "Verify your email using this link: {{verifyUrl}}",
|
|
80
33
|
},
|
|
81
34
|
};
|
|
82
|
-
|
|
83
|
-
return
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
var template = (_b = templates === null || templates === void 0 ? void 0 : templates[templateId]) !== null && _b !== void 0 ? _b : FALLBACK_AUTH_MAIL[templateId];
|
|
92
|
-
var base = publicAppUrl.replace(/\/$/, "");
|
|
93
|
-
var resetUrl = "".concat(base, "/resetPassword?token=").concat(encodeURIComponent(token));
|
|
94
|
-
var verifyUrl = "".concat(base, "/verifyEmail?token=").concat(encodeURIComponent(token));
|
|
95
|
-
var data = { publicAppUrl: base, resetUrl: resetUrl, token: token, verifyUrl: verifyUrl };
|
|
35
|
+
const interpolateMail = (value, data) => value.replace(/{{\s*([A-Za-z0-9_]+)\s*}}/g, (_match, key) => {
|
|
36
|
+
return data[key] ?? "";
|
|
37
|
+
});
|
|
38
|
+
const fallbackRenderAuthMail = ({ publicAppUrl, templateId, token, templates, }) => {
|
|
39
|
+
const template = templates?.[templateId] ?? FALLBACK_AUTH_MAIL[templateId];
|
|
40
|
+
const base = publicAppUrl.replace(/\/$/, "");
|
|
41
|
+
const resetUrl = `${base}/resetPassword?token=${encodeURIComponent(token)}`;
|
|
42
|
+
const verifyUrl = `${base}/verifyEmail?token=${encodeURIComponent(token)}`;
|
|
43
|
+
const data = { publicAppUrl: base, resetUrl, token, verifyUrl };
|
|
96
44
|
return {
|
|
97
45
|
html: template.html === undefined ? undefined : interpolateMail(template.html, data),
|
|
98
46
|
subject: interpolateMail(template.subject, data),
|
|
99
47
|
text: template.text === undefined ? undefined : interpolateMail(template.text, data),
|
|
100
48
|
};
|
|
101
49
|
};
|
|
102
|
-
|
|
50
|
+
const createBetterAuthEmailHooks = (config) => {
|
|
103
51
|
if (!config.sendMail) {
|
|
104
52
|
return undefined;
|
|
105
53
|
}
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
rendered = ((_b = config.renderAuthMail) !== null && _b !== void 0 ? _b : fallbackRenderAuthMail)({
|
|
122
|
-
publicAppUrl: publicAppUrl,
|
|
123
|
-
templateId: templateId,
|
|
124
|
-
templates: config.authMailTemplates,
|
|
125
|
-
token: token,
|
|
126
|
-
});
|
|
127
|
-
message = {
|
|
128
|
-
html: rendered.html,
|
|
129
|
-
subject: rendered.subject,
|
|
130
|
-
text: (_c = rendered.text) !== null && _c !== void 0 ? _c : "",
|
|
131
|
-
to: user.email,
|
|
132
|
-
};
|
|
133
|
-
return [4 /*yield*/, sendMail(message)];
|
|
134
|
-
case 1:
|
|
135
|
-
_d.sent();
|
|
136
|
-
return [2 /*return*/];
|
|
137
|
-
}
|
|
54
|
+
const sendMail = config.sendMail;
|
|
55
|
+
const deliver = async (templateId, user, token) => {
|
|
56
|
+
const publicAppUrl = config.publicAppUrl ?? "";
|
|
57
|
+
if (!publicAppUrl) {
|
|
58
|
+
logger_1.logger.error("[auth] publicAppUrl is required to send Better Auth recovery mail");
|
|
59
|
+
throw new errors_1.APIError({
|
|
60
|
+
status: 501,
|
|
61
|
+
title: "publicAppUrl is required to send recovery mail",
|
|
62
|
+
});
|
|
63
|
+
}
|
|
64
|
+
const rendered = (config.renderAuthMail ?? fallbackRenderAuthMail)({
|
|
65
|
+
publicAppUrl,
|
|
66
|
+
templateId,
|
|
67
|
+
templates: config.authMailTemplates,
|
|
68
|
+
token,
|
|
138
69
|
});
|
|
139
|
-
|
|
70
|
+
const message = {
|
|
71
|
+
html: rendered.html,
|
|
72
|
+
subject: rendered.subject,
|
|
73
|
+
text: rendered.text ?? "",
|
|
74
|
+
to: user.email,
|
|
75
|
+
};
|
|
76
|
+
await sendMail(message);
|
|
77
|
+
};
|
|
140
78
|
return {
|
|
141
|
-
sendResetPassword:
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
_c.sent();
|
|
148
|
-
return [2 /*return*/];
|
|
149
|
-
}
|
|
150
|
-
});
|
|
151
|
-
}); },
|
|
152
|
-
sendVerificationEmail: function (_a) { return __awaiter(void 0, [_a], void 0, function (_b) {
|
|
153
|
-
var token = _b.token, user = _b.user;
|
|
154
|
-
return __generator(this, function (_c) {
|
|
155
|
-
switch (_c.label) {
|
|
156
|
-
case 0: return [4 /*yield*/, deliver("verifyEmail", user, token)];
|
|
157
|
-
case 1:
|
|
158
|
-
_c.sent();
|
|
159
|
-
return [2 /*return*/];
|
|
160
|
-
}
|
|
161
|
-
});
|
|
162
|
-
}); },
|
|
79
|
+
sendResetPassword: async ({ token, user, }) => {
|
|
80
|
+
await deliver("resetPassword", user, token);
|
|
81
|
+
},
|
|
82
|
+
sendVerificationEmail: async ({ token, user, }) => {
|
|
83
|
+
await deliver("verifyEmail", user, token);
|
|
84
|
+
},
|
|
163
85
|
};
|
|
164
86
|
};
|
|
165
87
|
exports.createBetterAuthEmailHooks = createBetterAuthEmailHooks;
|
|
166
88
|
/**
|
|
167
89
|
* Creates a Better Auth instance with MongoDB adapter.
|
|
168
90
|
*/
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
var secret = config.secret || process.env.BETTER_AUTH_SECRET;
|
|
91
|
+
const createBetterAuth = (options) => {
|
|
92
|
+
const { config, mongoClient } = options;
|
|
93
|
+
const secret = config.secret || process.env.BETTER_AUTH_SECRET;
|
|
173
94
|
if (!secret) {
|
|
174
95
|
throw new errors_1.APIError({
|
|
175
96
|
status: 500,
|
|
176
97
|
title: "BETTER_AUTH_SECRET must be set in env or config.secret must be provided.",
|
|
177
98
|
});
|
|
178
99
|
}
|
|
179
|
-
|
|
100
|
+
const baseURL = config.baseURL || process.env.BETTER_AUTH_URL;
|
|
180
101
|
if (!baseURL) {
|
|
181
102
|
throw new errors_1.APIError({
|
|
182
103
|
status: 500,
|
|
183
104
|
title: "BETTER_AUTH_URL must be set in env or config.baseURL must be provided.",
|
|
184
105
|
});
|
|
185
106
|
}
|
|
186
|
-
|
|
187
|
-
|
|
107
|
+
const basePath = config.basePath ?? "/api/auth";
|
|
108
|
+
const socialProviders = {};
|
|
188
109
|
if (config.googleOAuth) {
|
|
189
110
|
socialProviders.google = {
|
|
190
111
|
clientId: config.googleOAuth.clientId,
|
|
@@ -203,9 +124,10 @@ var createBetterAuth = function (options) {
|
|
|
203
124
|
clientSecret: config.githubOAuth.clientSecret,
|
|
204
125
|
};
|
|
205
126
|
}
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
127
|
+
const emailHooks = (0, exports.createBetterAuthEmailHooks)(config);
|
|
128
|
+
const userModel = options.userModel;
|
|
129
|
+
const auth = (0, better_auth_1.betterAuth)({
|
|
130
|
+
advanced: config.crossDomainCookies
|
|
209
131
|
? {
|
|
210
132
|
defaultCookieAttributes: {
|
|
211
133
|
httpOnly: true,
|
|
@@ -213,39 +135,47 @@ var createBetterAuth = function (options) {
|
|
|
213
135
|
secure: true,
|
|
214
136
|
},
|
|
215
137
|
}
|
|
216
|
-
: undefined,
|
|
138
|
+
: undefined,
|
|
139
|
+
basePath,
|
|
140
|
+
baseURL,
|
|
141
|
+
database: (0, mongodb_1.mongodbAdapter)(mongoClient.db()),
|
|
142
|
+
emailAndPassword: {
|
|
143
|
+
enabled: true,
|
|
144
|
+
revokeSessionsOnPasswordReset: true,
|
|
145
|
+
...(emailHooks ? { sendResetPassword: emailHooks.sendResetPassword } : {}),
|
|
146
|
+
...(userModel
|
|
147
|
+
? {
|
|
148
|
+
onPasswordReset: async ({ user }, request) => {
|
|
149
|
+
await (0, exports.applyBetterAuthPasswordResetToJwt)(userModel, user, request);
|
|
150
|
+
},
|
|
151
|
+
}
|
|
152
|
+
: {}),
|
|
153
|
+
},
|
|
154
|
+
...(emailHooks
|
|
217
155
|
? {
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
case 0: return [4 /*yield*/, (0, exports.applyBetterAuthPasswordResetToJwt)(userModel, user, request)];
|
|
223
|
-
case 1:
|
|
224
|
-
_c.sent();
|
|
225
|
-
return [2 /*return*/];
|
|
226
|
-
}
|
|
227
|
-
});
|
|
228
|
-
}); },
|
|
156
|
+
emailVerification: {
|
|
157
|
+
sendOnSignUp: true,
|
|
158
|
+
sendVerificationEmail: emailHooks.sendVerificationEmail,
|
|
159
|
+
},
|
|
229
160
|
}
|
|
230
|
-
: {})
|
|
231
|
-
? {
|
|
232
|
-
emailVerification: {
|
|
233
|
-
sendOnSignUp: true,
|
|
234
|
-
sendVerificationEmail: emailHooks.sendVerificationEmail,
|
|
235
|
-
},
|
|
236
|
-
}
|
|
237
|
-
: {})), {
|
|
161
|
+
: {}),
|
|
238
162
|
// The bearer plugin lets clients authenticate with `Authorization: Bearer <sessionToken>`
|
|
239
163
|
// instead of the signed session cookie. Required for cross-origin/native clients and for
|
|
240
164
|
// websocket handshakes (RealtimeApp's Better Auth socket validator forwards the handshake
|
|
241
165
|
// token as a bearer header) — without it, a raw session token cannot be validated and
|
|
242
166
|
// socket auth silently fails (the sync client shows perpetually "offline").
|
|
243
|
-
plugins: [(0, plugins_1.bearer)()],
|
|
167
|
+
plugins: [(0, plugins_1.bearer)()],
|
|
168
|
+
rateLimit: config.disableRateLimit ? { enabled: false } : undefined,
|
|
169
|
+
secret,
|
|
170
|
+
session: {
|
|
244
171
|
cookieCache: {
|
|
245
172
|
enabled: true,
|
|
246
173
|
maxAge: 5 * 60, // 5 minutes
|
|
247
174
|
},
|
|
248
|
-
},
|
|
175
|
+
},
|
|
176
|
+
socialProviders: Object.keys(socialProviders).length > 0 ? socialProviders : undefined,
|
|
177
|
+
trustedOrigins: config.trustedOrigins ?? [],
|
|
178
|
+
});
|
|
249
179
|
// Cast through unknown: enabling the bearer plugin narrows betterAuth()'s inferred
|
|
250
180
|
// return type to a plugin-specific tuple that no longer matches the plugin-agnostic
|
|
251
181
|
// BetterAuthInstance alias, though the runtime instance is a valid better-auth instance.
|
|
@@ -257,202 +187,129 @@ exports.createBetterAuth = createBetterAuth;
|
|
|
257
187
|
* (when that user exists) and delete Better Auth sessions so a dual-enrolled
|
|
258
188
|
* account cannot keep the old password or stolen sessions.
|
|
259
189
|
*/
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
}
|
|
293
|
-
return [4 /*yield*/, ctx.password.hash(password)];
|
|
294
|
-
case 8:
|
|
295
|
-
hashedPassword = _e.sent();
|
|
296
|
-
return [4 /*yield*/, ctx.internalAdapter.findAccounts(betterAuthUserId)];
|
|
297
|
-
case 9:
|
|
298
|
-
accounts = _e.sent();
|
|
299
|
-
hasCredential = accounts.some(function (account) { return account.providerId === "credential"; });
|
|
300
|
-
if (!hasCredential) return [3 /*break*/, 11];
|
|
301
|
-
return [4 /*yield*/, ctx.internalAdapter.updatePassword(betterAuthUserId, hashedPassword)];
|
|
302
|
-
case 10:
|
|
303
|
-
_e.sent();
|
|
304
|
-
return [3 /*break*/, 13];
|
|
305
|
-
case 11: return [4 /*yield*/, ctx.internalAdapter.createAccount({
|
|
306
|
-
accountId: betterAuthUserId,
|
|
307
|
-
password: hashedPassword,
|
|
308
|
-
providerId: "credential",
|
|
309
|
-
userId: betterAuthUserId,
|
|
310
|
-
})];
|
|
311
|
-
case 12:
|
|
312
|
-
_e.sent();
|
|
313
|
-
_e.label = 13;
|
|
314
|
-
case 13: return [4 /*yield*/, ctx.internalAdapter.deleteUserSessions(betterAuthUserId)];
|
|
315
|
-
case 14:
|
|
316
|
-
_e.sent();
|
|
317
|
-
return [2 /*return*/];
|
|
318
|
-
}
|
|
319
|
-
});
|
|
320
|
-
}); };
|
|
190
|
+
const applyJwtPasswordResetToBetterAuth = async (auth, user, password) => {
|
|
191
|
+
const ctx = (await auth.$context);
|
|
192
|
+
let betterAuthUserId = typeof user.betterAuthId === "string" ? user.betterAuthId : "";
|
|
193
|
+
if (!betterAuthUserId && typeof user.email === "string" && user.email.length > 0) {
|
|
194
|
+
const found = await ctx.internalAdapter.findUserByEmail(user.email);
|
|
195
|
+
betterAuthUserId = found?.user?.id ?? "";
|
|
196
|
+
}
|
|
197
|
+
if (!betterAuthUserId) {
|
|
198
|
+
const byId = user.betterAuthId
|
|
199
|
+
? await ctx.internalAdapter.findUserById(user.betterAuthId)
|
|
200
|
+
: null;
|
|
201
|
+
betterAuthUserId = byId?.id ?? "";
|
|
202
|
+
}
|
|
203
|
+
if (!betterAuthUserId) {
|
|
204
|
+
return;
|
|
205
|
+
}
|
|
206
|
+
const hashedPassword = await ctx.password.hash(password);
|
|
207
|
+
const accounts = await ctx.internalAdapter.findAccounts(betterAuthUserId);
|
|
208
|
+
const hasCredential = accounts.some((account) => account.providerId === "credential");
|
|
209
|
+
if (hasCredential) {
|
|
210
|
+
await ctx.internalAdapter.updatePassword(betterAuthUserId, hashedPassword);
|
|
211
|
+
}
|
|
212
|
+
else {
|
|
213
|
+
await ctx.internalAdapter.createAccount({
|
|
214
|
+
accountId: betterAuthUserId,
|
|
215
|
+
password: hashedPassword,
|
|
216
|
+
providerId: "credential",
|
|
217
|
+
userId: betterAuthUserId,
|
|
218
|
+
});
|
|
219
|
+
}
|
|
220
|
+
await ctx.internalAdapter.deleteUserSessions(betterAuthUserId);
|
|
221
|
+
};
|
|
321
222
|
exports.applyJwtPasswordResetToBetterAuth = applyJwtPasswordResetToBetterAuth;
|
|
322
|
-
|
|
323
|
-
var _a;
|
|
223
|
+
const passwordFromUnknown = (value) => {
|
|
324
224
|
if (!value || typeof value !== "object") {
|
|
325
225
|
return "";
|
|
326
226
|
}
|
|
327
|
-
|
|
328
|
-
|
|
227
|
+
const record = value;
|
|
228
|
+
const candidate = record.newPassword ?? record.password;
|
|
329
229
|
if (typeof candidate !== "string") {
|
|
330
230
|
return "";
|
|
331
231
|
}
|
|
332
232
|
return candidate;
|
|
333
233
|
};
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
_a = passwordFromUnknown;
|
|
353
|
-
return [4 /*yield*/, request.clone().json()];
|
|
354
|
-
case 2: return [2 /*return*/, _a.apply(void 0, [_c.sent()])];
|
|
355
|
-
case 3:
|
|
356
|
-
_b = _c.sent();
|
|
357
|
-
return [2 /*return*/, ""];
|
|
358
|
-
case 4: return [2 /*return*/];
|
|
359
|
-
}
|
|
360
|
-
});
|
|
361
|
-
}); };
|
|
234
|
+
const readPasswordFromBetterAuthResetRequest = async (request) => {
|
|
235
|
+
if (!request) {
|
|
236
|
+
return "";
|
|
237
|
+
}
|
|
238
|
+
const attached = passwordFromUnknown(request.body);
|
|
239
|
+
if (attached.length > 0) {
|
|
240
|
+
return attached;
|
|
241
|
+
}
|
|
242
|
+
if (typeof request.clone !== "function") {
|
|
243
|
+
return "";
|
|
244
|
+
}
|
|
245
|
+
try {
|
|
246
|
+
return passwordFromUnknown(await request.clone().json());
|
|
247
|
+
}
|
|
248
|
+
catch {
|
|
249
|
+
return "";
|
|
250
|
+
}
|
|
251
|
+
};
|
|
362
252
|
exports.readPasswordFromBetterAuthResetRequest = readPasswordFromBetterAuthResetRequest;
|
|
363
253
|
/**
|
|
364
254
|
* After Better Auth password reset, update the JWT/passport hash and bump
|
|
365
255
|
* `tokenEpoch` so a dual-enrolled account cannot keep the old password or
|
|
366
256
|
* outstanding refresh tokens.
|
|
367
257
|
*/
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
_c.label = 5;
|
|
391
|
-
case 5:
|
|
392
|
-
if (!appUser) {
|
|
393
|
-
return [2 /*return*/];
|
|
394
|
-
}
|
|
395
|
-
return [4 /*yield*/, (0, exports.readPasswordFromBetterAuthResetRequest)(request)];
|
|
396
|
-
case 6:
|
|
397
|
-
password = _c.sent();
|
|
398
|
-
if (!password) {
|
|
399
|
-
logger_1.logger.error("[auth] Better Auth password reset did not include a password to sync to JWT");
|
|
400
|
-
throw new errors_1.APIError({
|
|
401
|
-
status: 500,
|
|
402
|
-
title: "Password reset could not sync to JWT credentials",
|
|
403
|
-
});
|
|
404
|
-
}
|
|
405
|
-
return [4 /*yield*/, (0, auth_1.setPasswordForUser)(appUser, password)];
|
|
406
|
-
case 7:
|
|
407
|
-
_c.sent();
|
|
408
|
-
appUser.tokenEpoch = ((_b = appUser.tokenEpoch) !== null && _b !== void 0 ? _b : 0) + 1;
|
|
409
|
-
return [4 /*yield*/, appUser.save()];
|
|
410
|
-
case 8:
|
|
411
|
-
_c.sent();
|
|
412
|
-
return [2 /*return*/];
|
|
413
|
-
}
|
|
414
|
-
});
|
|
415
|
-
}); };
|
|
258
|
+
const applyBetterAuthPasswordResetToJwt = async (userModel, betterAuthUser, request) => {
|
|
259
|
+
const betterAuthId = typeof betterAuthUser.id === "string" ? betterAuthUser.id : "";
|
|
260
|
+
const email = typeof betterAuthUser.email === "string" ? betterAuthUser.email : "";
|
|
261
|
+
let appUser = betterAuthId ? await (0, plugins_2.findOneOrNoneFor)(userModel, { betterAuthId }) : null;
|
|
262
|
+
if (!appUser && email.length > 0) {
|
|
263
|
+
appUser = await (0, plugins_2.findOneOrNoneFor)(userModel, { email });
|
|
264
|
+
}
|
|
265
|
+
if (!appUser) {
|
|
266
|
+
return;
|
|
267
|
+
}
|
|
268
|
+
const password = await (0, exports.readPasswordFromBetterAuthResetRequest)(request);
|
|
269
|
+
if (!password) {
|
|
270
|
+
logger_1.logger.error("[auth] Better Auth password reset did not include a password to sync to JWT");
|
|
271
|
+
throw new errors_1.APIError({
|
|
272
|
+
status: 500,
|
|
273
|
+
title: "Password reset could not sync to JWT credentials",
|
|
274
|
+
});
|
|
275
|
+
}
|
|
276
|
+
await (0, auth_1.setPasswordForUser)(appUser, password);
|
|
277
|
+
appUser.tokenEpoch = (appUser.tokenEpoch ?? 0) + 1;
|
|
278
|
+
await appUser.save();
|
|
279
|
+
};
|
|
416
280
|
exports.applyBetterAuthPasswordResetToJwt = applyBetterAuthPasswordResetToJwt;
|
|
417
281
|
/**
|
|
418
282
|
* Creates Express middleware that extracts the Better Auth session
|
|
419
283
|
* and populates req.user with the application User model.
|
|
420
284
|
*/
|
|
421
|
-
|
|
422
|
-
return
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
newUser = _a.sent();
|
|
450
|
-
reqWithSession.user = newUser;
|
|
451
|
-
reqWithSession.betterAuthSession = session;
|
|
452
|
-
(0, requestContext_1.updateRequestContextFromRequest)(req);
|
|
453
|
-
_a.label = 5;
|
|
454
|
-
case 5: return [3 /*break*/, 7];
|
|
455
|
-
case 6:
|
|
285
|
+
const createBetterAuthSessionMiddleware = (auth, userModel) => {
|
|
286
|
+
return async (req, _res, next) => {
|
|
287
|
+
try {
|
|
288
|
+
const session = await auth.api.getSession({
|
|
289
|
+
headers: req.headers,
|
|
290
|
+
});
|
|
291
|
+
if (session?.user && session?.session) {
|
|
292
|
+
const betterAuthUser = session.user;
|
|
293
|
+
const reqWithSession = req;
|
|
294
|
+
if (userModel) {
|
|
295
|
+
// Look up the application user by betterAuthId
|
|
296
|
+
const appUser = await (0, plugins_2.findOneOrNoneFor)(userModel, {
|
|
297
|
+
betterAuthId: betterAuthUser.id,
|
|
298
|
+
});
|
|
299
|
+
if (appUser) {
|
|
300
|
+
reqWithSession.user = appUser;
|
|
301
|
+
reqWithSession.betterAuthSession = session;
|
|
302
|
+
(0, requestContext_1.updateRequestContextFromRequest)(req);
|
|
303
|
+
}
|
|
304
|
+
else {
|
|
305
|
+
// User exists in Better Auth but not synced yet - create them
|
|
306
|
+
const newUser = await (0, exports.syncBetterAuthUser)(userModel, betterAuthUser);
|
|
307
|
+
reqWithSession.user = newUser;
|
|
308
|
+
reqWithSession.betterAuthSession = session;
|
|
309
|
+
(0, requestContext_1.updateRequestContextFromRequest)(req);
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
else {
|
|
456
313
|
// No user model - just attach the Better Auth user directly
|
|
457
314
|
reqWithSession.user = {
|
|
458
315
|
_id: betterAuthUser.id,
|
|
@@ -464,94 +321,83 @@ var createBetterAuthSessionMiddleware = function (auth, userModel) {
|
|
|
464
321
|
};
|
|
465
322
|
reqWithSession.betterAuthSession = session;
|
|
466
323
|
(0, requestContext_1.updateRequestContextFromRequest)(req);
|
|
467
|
-
|
|
468
|
-
case 7:
|
|
469
|
-
next();
|
|
470
|
-
return [3 /*break*/, 9];
|
|
471
|
-
case 8:
|
|
472
|
-
error_1 = _a.sent();
|
|
473
|
-
logger_1.logger.debug("Better Auth session extraction error: ".concat(error_1));
|
|
474
|
-
next();
|
|
475
|
-
return [3 /*break*/, 9];
|
|
476
|
-
case 9: return [2 /*return*/];
|
|
324
|
+
}
|
|
477
325
|
}
|
|
478
|
-
|
|
479
|
-
|
|
326
|
+
next();
|
|
327
|
+
}
|
|
328
|
+
catch (error) {
|
|
329
|
+
logger_1.logger.debug(`Better Auth session extraction error: ${error}`);
|
|
330
|
+
next();
|
|
331
|
+
}
|
|
332
|
+
};
|
|
480
333
|
};
|
|
481
334
|
exports.createBetterAuthSessionMiddleware = createBetterAuthSessionMiddleware;
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
existingUser.email = betterAuthUser.email;
|
|
496
|
-
if (betterAuthUser.name) {
|
|
497
|
-
existingUser.name = betterAuthUser.name;
|
|
498
|
-
}
|
|
499
|
-
return [4 /*yield*/, existingUser.save()];
|
|
500
|
-
case 2:
|
|
501
|
-
_a.sent();
|
|
502
|
-
return [2 /*return*/, existingUser];
|
|
503
|
-
case 3: return [4 /*yield*/, (0, plugins_2.findOneOrNoneFor)(userModel, {
|
|
504
|
-
email: betterAuthUser.email,
|
|
505
|
-
})];
|
|
506
|
-
case 4:
|
|
507
|
-
userByEmail = (_a.sent());
|
|
508
|
-
if (!userByEmail) return [3 /*break*/, 6];
|
|
509
|
-
// Link existing user to Better Auth
|
|
510
|
-
userByEmail.betterAuthId = betterAuthUser.id;
|
|
511
|
-
if (oauthProvider) {
|
|
512
|
-
userByEmail.oauthProvider = oauthProvider;
|
|
513
|
-
}
|
|
514
|
-
return [4 /*yield*/, userByEmail.save()];
|
|
515
|
-
case 5:
|
|
516
|
-
_a.sent();
|
|
517
|
-
return [2 /*return*/, userByEmail];
|
|
518
|
-
case 6:
|
|
519
|
-
useAsId = mongoose_1.default.isValidObjectId(betterAuthUser.id) ? { _id: betterAuthUser.id } : {};
|
|
520
|
-
UserDocumentConstructor = userModel;
|
|
521
|
-
newUser = new UserDocumentConstructor(__assign(__assign(__assign({}, useAsId), { admin: false, betterAuthId: betterAuthUser.id, email: betterAuthUser.email, name: betterAuthUser.name || betterAuthUser.email.split("@")[0] }), (oauthProvider ? { oauthProvider: oauthProvider } : {})));
|
|
522
|
-
return [4 /*yield*/, newUser.save()];
|
|
523
|
-
case 7:
|
|
524
|
-
_a.sent();
|
|
525
|
-
logger_1.logger.info("Created new user from Better Auth: ".concat(newUser.id));
|
|
526
|
-
return [2 /*return*/, newUser];
|
|
527
|
-
case 8:
|
|
528
|
-
error_2 = _a.sent();
|
|
529
|
-
logger_1.logger.error("Error syncing Better Auth user: ".concat(error_2));
|
|
530
|
-
throw error_2;
|
|
531
|
-
case 9: return [2 /*return*/];
|
|
335
|
+
const syncBetterAuthUser = async (userModel, betterAuthUser, oauthProvider) => {
|
|
336
|
+
try {
|
|
337
|
+
const existingUser = (await (0, plugins_2.findOneOrNoneFor)(userModel, {
|
|
338
|
+
betterAuthId: betterAuthUser.id,
|
|
339
|
+
}));
|
|
340
|
+
if (existingUser) {
|
|
341
|
+
// Update existing user if needed
|
|
342
|
+
existingUser.email = betterAuthUser.email;
|
|
343
|
+
if (betterAuthUser.name) {
|
|
344
|
+
existingUser.name = betterAuthUser.name;
|
|
345
|
+
}
|
|
346
|
+
await existingUser.save();
|
|
347
|
+
return existingUser;
|
|
532
348
|
}
|
|
533
|
-
|
|
534
|
-
|
|
349
|
+
// Check if user exists by email (migration case)
|
|
350
|
+
const userByEmail = (await (0, plugins_2.findOneOrNoneFor)(userModel, {
|
|
351
|
+
email: betterAuthUser.email,
|
|
352
|
+
}));
|
|
353
|
+
if (userByEmail) {
|
|
354
|
+
// Link existing user to Better Auth
|
|
355
|
+
userByEmail.betterAuthId = betterAuthUser.id;
|
|
356
|
+
if (oauthProvider) {
|
|
357
|
+
userByEmail.oauthProvider = oauthProvider;
|
|
358
|
+
}
|
|
359
|
+
await userByEmail.save();
|
|
360
|
+
return userByEmail;
|
|
361
|
+
}
|
|
362
|
+
// Use Better Auth ID as _id when it's a valid ObjectId (MongoDB adapter) so frontend IDs match
|
|
363
|
+
const useAsId = mongoose_1.default.isValidObjectId(betterAuthUser.id) ? { _id: betterAuthUser.id } : {};
|
|
364
|
+
const UserDocumentConstructor = userModel;
|
|
365
|
+
const newUser = new UserDocumentConstructor({
|
|
366
|
+
...useAsId,
|
|
367
|
+
admin: false,
|
|
368
|
+
betterAuthId: betterAuthUser.id,
|
|
369
|
+
email: betterAuthUser.email,
|
|
370
|
+
name: betterAuthUser.name || betterAuthUser.email.split("@")[0],
|
|
371
|
+
...(oauthProvider ? { oauthProvider } : {}),
|
|
372
|
+
});
|
|
373
|
+
await newUser.save();
|
|
374
|
+
logger_1.logger.info(`Created new user from Better Auth: ${newUser.id}`);
|
|
375
|
+
return newUser;
|
|
376
|
+
}
|
|
377
|
+
catch (error) {
|
|
378
|
+
logger_1.logger.error(`Error syncing Better Auth user: ${error}`);
|
|
379
|
+
throw error;
|
|
380
|
+
}
|
|
381
|
+
};
|
|
535
382
|
exports.syncBetterAuthUser = syncBetterAuthUser;
|
|
536
383
|
/**
|
|
537
384
|
* Mounts Better Auth routes on the Express app.
|
|
538
385
|
*/
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
var handler = (0, node_1.toNodeHandler)(auth);
|
|
386
|
+
const mountBetterAuthRoutes = (app, auth, basePath = "/api/auth") => {
|
|
387
|
+
const handler = (0, node_1.toNodeHandler)(auth);
|
|
542
388
|
// Mount at the base path with wildcard
|
|
543
|
-
app.all(
|
|
389
|
+
app.all(`${basePath}/*path`, (req, res) => {
|
|
544
390
|
return handler(req, res);
|
|
545
391
|
});
|
|
546
|
-
logger_1.logger.info(
|
|
392
|
+
logger_1.logger.info(`Better Auth routes mounted at ${basePath}/*`);
|
|
547
393
|
};
|
|
548
394
|
exports.mountBetterAuthRoutes = mountBetterAuthRoutes;
|
|
549
395
|
/**
|
|
550
396
|
* Gets the MongoDB client from the mongoose connection.
|
|
551
397
|
*/
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
398
|
+
const getMongoClientFromMongoose = () => {
|
|
399
|
+
const connection = mongoose_1.default.connection;
|
|
400
|
+
const client = connection.client;
|
|
555
401
|
if (!client) {
|
|
556
402
|
throw new errors_1.APIError({
|
|
557
403
|
status: 500,
|
|
@@ -568,7 +414,7 @@ exports.getMongoClientFromMongoose = getMongoClientFromMongoose;
|
|
|
568
414
|
* Note: Better Auth doesn't have built-in event hooks, so we rely on the session middleware
|
|
569
415
|
* to create users on first session access.
|
|
570
416
|
*/
|
|
571
|
-
|
|
417
|
+
const setupBetterAuthUserSync = (_auth, _userModel) => {
|
|
572
418
|
// Better Auth v1.x doesn't expose event hooks for user creation.
|
|
573
419
|
// User sync is handled in createBetterAuthSessionMiddleware when a session is accessed.
|
|
574
420
|
// This function is a placeholder for future versions that may support hooks.
|
|
@@ -578,15 +424,14 @@ exports.setupBetterAuthUserSync = setupBetterAuthUserSync;
|
|
|
578
424
|
/**
|
|
579
425
|
* Extracts Better Auth session data from the request.
|
|
580
426
|
*/
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
return (_a = req.betterAuthSession) !== null && _a !== void 0 ? _a : null;
|
|
427
|
+
const getBetterAuthSession = (req) => {
|
|
428
|
+
return req.betterAuthSession ?? null;
|
|
584
429
|
};
|
|
585
430
|
exports.getBetterAuthSession = getBetterAuthSession;
|
|
586
431
|
/**
|
|
587
432
|
* Checks if the request has a valid Better Auth session.
|
|
588
433
|
*/
|
|
589
|
-
|
|
434
|
+
const hasBetterAuthSession = (req) => {
|
|
590
435
|
return Boolean(req.betterAuthSession);
|
|
591
436
|
};
|
|
592
437
|
exports.hasBetterAuthSession = hasBetterAuthSession;
|