@terreno/api 57.4.0 → 57.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +5 -5
- package/bunfig.toml +1 -1
- package/dist/actions.js +197 -368
- package/dist/adminModelRouter.js +88 -173
- package/dist/api.js +598 -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/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/auth.js
CHANGED
|
@@ -1,125 +1,30 @@
|
|
|
1
1
|
"use strict";
|
|
2
|
-
var __assign = (this && this.__assign) || function () {
|
|
3
|
-
__assign = Object.assign || function(t) {
|
|
4
|
-
for (var s, i = 1, n = arguments.length; i < n; i++) {
|
|
5
|
-
s = arguments[i];
|
|
6
|
-
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
|
|
7
|
-
t[p] = s[p];
|
|
8
|
-
}
|
|
9
|
-
return t;
|
|
10
|
-
};
|
|
11
|
-
return __assign.apply(this, arguments);
|
|
12
|
-
};
|
|
13
|
-
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
|
14
|
-
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
|
15
|
-
return new (P || (P = Promise))(function (resolve, reject) {
|
|
16
|
-
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
|
17
|
-
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
|
18
|
-
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
|
19
|
-
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
20
|
-
});
|
|
21
|
-
};
|
|
22
|
-
var __generator = (this && this.__generator) || function (thisArg, body) {
|
|
23
|
-
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);
|
|
24
|
-
return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
|
|
25
|
-
function verb(n) { return function (v) { return step([n, v]); }; }
|
|
26
|
-
function step(op) {
|
|
27
|
-
if (f) throw new TypeError("Generator is already executing.");
|
|
28
|
-
while (g && (g = 0, op[0] && (_ = 0)), _) try {
|
|
29
|
-
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;
|
|
30
|
-
if (y = 0, t) op = [op[0] & 2, t.value];
|
|
31
|
-
switch (op[0]) {
|
|
32
|
-
case 0: case 1: t = op; break;
|
|
33
|
-
case 4: _.label++; return { value: op[1], done: false };
|
|
34
|
-
case 5: _.label++; y = op[1]; op = [0]; continue;
|
|
35
|
-
case 7: op = _.ops.pop(); _.trys.pop(); continue;
|
|
36
|
-
default:
|
|
37
|
-
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
|
|
38
|
-
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
|
|
39
|
-
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
|
|
40
|
-
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
|
|
41
|
-
if (t[2]) _.ops.pop();
|
|
42
|
-
_.trys.pop(); continue;
|
|
43
|
-
}
|
|
44
|
-
op = body.call(thisArg, _);
|
|
45
|
-
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
|
|
46
|
-
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
|
|
47
|
-
}
|
|
48
|
-
};
|
|
49
|
-
var __rest = (this && this.__rest) || function (s, e) {
|
|
50
|
-
var t = {};
|
|
51
|
-
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
|
|
52
|
-
t[p] = s[p];
|
|
53
|
-
if (s != null && typeof Object.getOwnPropertySymbols === "function")
|
|
54
|
-
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
|
|
55
|
-
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
|
|
56
|
-
t[p[i]] = s[p[i]];
|
|
57
|
-
}
|
|
58
|
-
return t;
|
|
59
|
-
};
|
|
60
|
-
var __values = (this && this.__values) || function(o) {
|
|
61
|
-
var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
|
|
62
|
-
if (m) return m.call(o);
|
|
63
|
-
if (o && typeof o.length === "number") return {
|
|
64
|
-
next: function () {
|
|
65
|
-
if (o && i >= o.length) o = void 0;
|
|
66
|
-
return { value: o && o[i++], done: !o };
|
|
67
|
-
}
|
|
68
|
-
};
|
|
69
|
-
throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
|
|
70
|
-
};
|
|
71
|
-
var __read = (this && this.__read) || function (o, n) {
|
|
72
|
-
var m = typeof Symbol === "function" && o[Symbol.iterator];
|
|
73
|
-
if (!m) return o;
|
|
74
|
-
var i = m.call(o), r, ar = [], e;
|
|
75
|
-
try {
|
|
76
|
-
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
|
|
77
|
-
}
|
|
78
|
-
catch (error) { e = { error: error }; }
|
|
79
|
-
finally {
|
|
80
|
-
try {
|
|
81
|
-
if (r && !r.done && (m = i["return"])) m.call(i);
|
|
82
|
-
}
|
|
83
|
-
finally { if (e) throw e.error; }
|
|
84
|
-
}
|
|
85
|
-
return ar;
|
|
86
|
-
};
|
|
87
|
-
var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
|
|
88
|
-
if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
|
|
89
|
-
if (ar || !(i in from)) {
|
|
90
|
-
if (!ar) ar = Array.prototype.slice.call(from, 0, i);
|
|
91
|
-
ar[i] = from[i];
|
|
92
|
-
}
|
|
93
|
-
}
|
|
94
|
-
return to.concat(ar || Array.prototype.slice.call(from));
|
|
95
|
-
};
|
|
96
2
|
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
97
3
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
98
4
|
};
|
|
99
5
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
100
6
|
exports.addMeRoutes = exports.addAuthRoutes = exports.setupAuth = exports.generateTokens = exports.setPasswordForUser = exports.MAX_PASSWORD_LENGTH = exports.signupUser = exports.omitUserRolesFromWriteBody = exports.stripPrivilegedUserFields = exports.PRIVILEGED_USER_FIELDS = exports.authenticateMiddleware = void 0;
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
var strategies = ["jwt"];
|
|
7
|
+
const node_crypto_1 = require("node:crypto");
|
|
8
|
+
const express_1 = __importDefault(require("express"));
|
|
9
|
+
const jsonwebtoken_1 = __importDefault(require("jsonwebtoken"));
|
|
10
|
+
const luxon_1 = require("luxon");
|
|
11
|
+
const ms_1 = __importDefault(require("ms"));
|
|
12
|
+
const passport_1 = __importDefault(require("passport"));
|
|
13
|
+
const passport_anonymous_1 = require("passport-anonymous");
|
|
14
|
+
const passport_jwt_1 = require("passport-jwt");
|
|
15
|
+
const passport_local_1 = require("passport-local");
|
|
16
|
+
const authRecovery_1 = require("./authRecovery");
|
|
17
|
+
const authTokens_1 = require("./authTokens");
|
|
18
|
+
const errors_1 = require("./errors");
|
|
19
|
+
const logger_1 = require("./logger");
|
|
20
|
+
const policies_1 = require("./rateLimit/policies");
|
|
21
|
+
const requestContext_1 = require("./requestContext");
|
|
22
|
+
const authenticateMiddleware = (anonymous = false) => {
|
|
23
|
+
const strategies = ["jwt"];
|
|
119
24
|
if (anonymous) {
|
|
120
25
|
strategies.push("anonymous");
|
|
121
26
|
}
|
|
122
|
-
return
|
|
27
|
+
return (req, res, next) => {
|
|
123
28
|
if (req.user) {
|
|
124
29
|
return next();
|
|
125
30
|
}
|
|
@@ -131,7 +36,7 @@ var authenticateMiddleware = function (anonymous) {
|
|
|
131
36
|
// matches on, so the response contract is unchanged.
|
|
132
37
|
// (The anonymous strategy calls pass(), which skips this callback and
|
|
133
38
|
// continues the chain with no user — same as before.)
|
|
134
|
-
return passport_1.default.authenticate(strategies, { session: false },
|
|
39
|
+
return passport_1.default.authenticate(strategies, { session: false }, (err, user, info) => {
|
|
135
40
|
if (err) {
|
|
136
41
|
return next(err);
|
|
137
42
|
}
|
|
@@ -141,7 +46,7 @@ var authenticateMiddleware = function (anonymous) {
|
|
|
141
46
|
req.user = user;
|
|
142
47
|
// req.logIn used to populate authInfo; keep that passport-public API
|
|
143
48
|
// intact for downstream consumers.
|
|
144
|
-
req.authInfo = (info
|
|
49
|
+
req.authInfo = (info ?? {});
|
|
145
50
|
return next();
|
|
146
51
|
})(req, res, next);
|
|
147
52
|
};
|
|
@@ -164,64 +69,42 @@ exports.PRIVILEGED_USER_FIELDS = [
|
|
|
164
69
|
* Removes {@link PRIVILEGED_USER_FIELDS} from a self-service body. Fields are dropped rather
|
|
165
70
|
* than rejected so clients that echo a whole user object back still succeed.
|
|
166
71
|
*/
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
if (exports.PRIVILEGED_USER_FIELDS.includes(key)) {
|
|
175
|
-
dropped.push(key);
|
|
176
|
-
continue;
|
|
177
|
-
}
|
|
178
|
-
sanitized[key] = value;
|
|
179
|
-
}
|
|
180
|
-
}
|
|
181
|
-
catch (e_1_1) { e_1 = { error: e_1_1 }; }
|
|
182
|
-
finally {
|
|
183
|
-
try {
|
|
184
|
-
if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
|
|
72
|
+
const stripPrivilegedUserFields = (body, context) => {
|
|
73
|
+
const sanitized = {};
|
|
74
|
+
const dropped = [];
|
|
75
|
+
for (const [key, value] of Object.entries(body)) {
|
|
76
|
+
if (exports.PRIVILEGED_USER_FIELDS.includes(key)) {
|
|
77
|
+
dropped.push(key);
|
|
78
|
+
continue;
|
|
185
79
|
}
|
|
186
|
-
|
|
80
|
+
sanitized[key] = value;
|
|
187
81
|
}
|
|
188
82
|
if (dropped.length > 0) {
|
|
189
|
-
logger_1.logger.warn(
|
|
83
|
+
logger_1.logger.warn(`Ignored privileged user fields on ${context}: ${dropped.join(", ")}`);
|
|
190
84
|
}
|
|
191
85
|
return sanitized;
|
|
192
86
|
};
|
|
193
87
|
exports.stripPrivilegedUserFields = stripPrivilegedUserFields;
|
|
194
|
-
|
|
88
|
+
const isEmailUpdateChangingMailbox = (currentEmail, nextEmail) => {
|
|
195
89
|
if (typeof currentEmail !== "string" || typeof nextEmail !== "string") {
|
|
196
90
|
return false;
|
|
197
91
|
}
|
|
198
92
|
return currentEmail.trim().toLowerCase() !== nextEmail.trim().toLowerCase();
|
|
199
93
|
};
|
|
200
|
-
|
|
201
|
-
var e_2, _a;
|
|
94
|
+
const omitPrivilegedFieldsFromObject = (item, allowAdminWrite) => {
|
|
202
95
|
if (!item || typeof item !== "object" || Array.isArray(item)) {
|
|
203
96
|
return item;
|
|
204
97
|
}
|
|
205
|
-
|
|
206
|
-
|
|
98
|
+
const record = item;
|
|
99
|
+
const fieldsToDrop = exports.PRIVILEGED_USER_FIELDS.filter((field) => field in record && !(field === "admin" && allowAdminWrite));
|
|
207
100
|
if (fieldsToDrop.length === 0) {
|
|
208
101
|
return item;
|
|
209
102
|
}
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
var field = fieldsToDrop_1_1.value;
|
|
214
|
-
Reflect.deleteProperty(next, field);
|
|
215
|
-
}
|
|
103
|
+
const next = { ...record };
|
|
104
|
+
for (const field of fieldsToDrop) {
|
|
105
|
+
Reflect.deleteProperty(next, field);
|
|
216
106
|
}
|
|
217
|
-
|
|
218
|
-
finally {
|
|
219
|
-
try {
|
|
220
|
-
if (fieldsToDrop_1_1 && !fieldsToDrop_1_1.done && (_a = fieldsToDrop_1.return)) _a.call(fieldsToDrop_1);
|
|
221
|
-
}
|
|
222
|
-
finally { if (e_2) throw e_2.error; }
|
|
223
|
-
}
|
|
224
|
-
logger_1.logger.warn("Ignored privileged User fields on a modelRouter write: ".concat(fieldsToDrop.join(", ")));
|
|
107
|
+
logger_1.logger.warn(`Ignored privileged User fields on a modelRouter write: ${fieldsToDrop.join(", ")}`);
|
|
225
108
|
return next;
|
|
226
109
|
};
|
|
227
110
|
/**
|
|
@@ -229,55 +112,41 @@ var omitPrivilegedFieldsFromObject = function (item, allowAdminWrite) {
|
|
|
229
112
|
* writes on `/users`, sync, or MCP. AdminApp captures role assignments before this runs and
|
|
230
113
|
* explicitly marks authorized legacy-admin writes after its additional checks.
|
|
231
114
|
*/
|
|
232
|
-
|
|
233
|
-
if (allowAdminWrite === void 0) { allowAdminWrite = false; }
|
|
115
|
+
const omitUserRolesFromWriteBody = (modelName, accessControl, body, allowAdminWrite = false) => {
|
|
234
116
|
if (modelName !== "User" || !accessControl || body == null) {
|
|
235
117
|
return body;
|
|
236
118
|
}
|
|
237
119
|
if (Array.isArray(body)) {
|
|
238
|
-
return body.map(
|
|
120
|
+
return body.map((item) => omitPrivilegedFieldsFromObject(item, allowAdminWrite));
|
|
239
121
|
}
|
|
240
122
|
return omitPrivilegedFieldsFromObject(body, allowAdminWrite);
|
|
241
123
|
};
|
|
242
124
|
exports.omitUserRolesFromWriteBody = omitUserRolesFromWriteBody;
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
case 3:
|
|
260
|
-
_b.trys.push([3, 5, , 6]);
|
|
261
|
-
return [4 /*yield*/, user.postCreate(bodyRest)];
|
|
262
|
-
case 4:
|
|
263
|
-
_b.sent();
|
|
264
|
-
return [3 /*break*/, 6];
|
|
265
|
-
case 5:
|
|
266
|
-
error_1 = _b.sent();
|
|
267
|
-
logger_1.logger.error("Error in user.postCreate: ".concat(error_1));
|
|
268
|
-
throw error_1;
|
|
269
|
-
case 6: return [4 /*yield*/, user.save()];
|
|
270
|
-
case 7:
|
|
271
|
-
_b.sent();
|
|
272
|
-
return [2 /*return*/, user];
|
|
273
|
-
case 8:
|
|
274
|
-
error_2 = _b.sent();
|
|
275
|
-
message = (0, errors_1.errorMessage)(error_2);
|
|
276
|
-
throw new errors_1.APIError({ title: message });
|
|
277
|
-
case 9: return [2 /*return*/];
|
|
125
|
+
const signupUser = async (userModel, email, password, body) => {
|
|
126
|
+
// Strip email and password from the body. They can cause mongoose to throw an error if strict is
|
|
127
|
+
// set.
|
|
128
|
+
const { email: _email, password: _password, ...rawBody } = body ?? {};
|
|
129
|
+
const bodyRest = (0, exports.stripPrivilegedUserFields)(rawBody, "signup");
|
|
130
|
+
try {
|
|
131
|
+
const registrableModel = userModel;
|
|
132
|
+
const user = await registrableModel.register({ email, ...bodyRest }, password);
|
|
133
|
+
if (user.postCreate) {
|
|
134
|
+
try {
|
|
135
|
+
await user.postCreate(bodyRest);
|
|
136
|
+
}
|
|
137
|
+
catch (error) {
|
|
138
|
+
logger_1.logger.error(`Error in user.postCreate: ${error}`);
|
|
139
|
+
throw error;
|
|
140
|
+
}
|
|
278
141
|
}
|
|
279
|
-
|
|
280
|
-
|
|
142
|
+
await user.save();
|
|
143
|
+
return user;
|
|
144
|
+
}
|
|
145
|
+
catch (error) {
|
|
146
|
+
const message = (0, errors_1.errorMessage)(error);
|
|
147
|
+
throw new errors_1.APIError({ title: message });
|
|
148
|
+
}
|
|
149
|
+
};
|
|
281
150
|
exports.signupUser = signupUser;
|
|
282
151
|
/** Upper bound on password length accepted by {@link setPasswordForUser} (D5). */
|
|
283
152
|
exports.MAX_PASSWORD_LENGTH = 256;
|
|
@@ -293,75 +162,58 @@ exports.MAX_PASSWORD_LENGTH = 256;
|
|
|
293
162
|
* password change), logs a `logger.info` audit line with the admin id, target user id, and
|
|
294
163
|
* timestamp — NEVER the password itself.
|
|
295
164
|
*/
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
165
|
+
const setPasswordForUser = async (user, password, timeoutMs = 15_000, audit) => {
|
|
166
|
+
if (password.length > exports.MAX_PASSWORD_LENGTH) {
|
|
167
|
+
throw new errors_1.APIError({
|
|
168
|
+
status: 400,
|
|
169
|
+
title: `Password must be at most ${exports.MAX_PASSWORD_LENGTH} characters`,
|
|
170
|
+
});
|
|
300
171
|
}
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
title: "Password must be at most ".concat(exports.MAX_PASSWORD_LENGTH, " characters"),
|
|
312
|
-
});
|
|
313
|
-
}
|
|
314
|
-
if ((audit === null || audit === void 0 ? void 0 : audit.adminId) !== undefined) {
|
|
315
|
-
targetUserId = (_b = (_a = user._id) !== null && _a !== void 0 ? _a : user.id) !== null && _b !== void 0 ? _b : "unknown";
|
|
316
|
-
logger_1.logger.info("[auth] Admin ".concat(String(audit.adminId), " set password for user ").concat(String(targetUserId), " ") +
|
|
317
|
-
"at ".concat(luxon_1.DateTime.now().toISO()));
|
|
318
|
-
}
|
|
319
|
-
return [4 /*yield*/, new Promise(function (resolve, reject) {
|
|
320
|
-
var isSettled = false;
|
|
321
|
-
var timeout = setTimeout(function () {
|
|
322
|
-
if (isSettled) {
|
|
323
|
-
return;
|
|
324
|
-
}
|
|
325
|
-
isSettled = true;
|
|
326
|
-
reject(new Error("Timed out while setting password"));
|
|
327
|
-
}, timeoutMs);
|
|
328
|
-
var resolveOnce = function () {
|
|
329
|
-
if (isSettled) {
|
|
330
|
-
return;
|
|
331
|
-
}
|
|
332
|
-
isSettled = true;
|
|
333
|
-
clearTimeout(timeout);
|
|
334
|
-
resolve();
|
|
335
|
-
};
|
|
336
|
-
var rejectOnce = function (error) {
|
|
337
|
-
if (isSettled) {
|
|
338
|
-
return;
|
|
339
|
-
}
|
|
340
|
-
isSettled = true;
|
|
341
|
-
clearTimeout(timeout);
|
|
342
|
-
reject(error);
|
|
343
|
-
};
|
|
344
|
-
try {
|
|
345
|
-
var maybePromise = user.setPassword(password, function (error) {
|
|
346
|
-
if (error) {
|
|
347
|
-
rejectOnce(error);
|
|
348
|
-
return;
|
|
349
|
-
}
|
|
350
|
-
resolveOnce();
|
|
351
|
-
});
|
|
352
|
-
if (maybePromise && typeof maybePromise.then === "function") {
|
|
353
|
-
maybePromise.then(resolveOnce).catch(rejectOnce);
|
|
354
|
-
}
|
|
355
|
-
}
|
|
356
|
-
catch (error) {
|
|
357
|
-
rejectOnce(error);
|
|
358
|
-
}
|
|
359
|
-
})];
|
|
360
|
-
case 1:
|
|
361
|
-
_c.sent();
|
|
362
|
-
return [2 /*return*/];
|
|
172
|
+
if (audit?.adminId !== undefined) {
|
|
173
|
+
const targetUserId = user._id ?? user.id ?? "unknown";
|
|
174
|
+
logger_1.logger.info(`[auth] Admin ${String(audit.adminId)} set password for user ${String(targetUserId)} ` +
|
|
175
|
+
`at ${luxon_1.DateTime.now().toISO()}`);
|
|
176
|
+
}
|
|
177
|
+
await new Promise((resolve, reject) => {
|
|
178
|
+
let isSettled = false;
|
|
179
|
+
const timeout = setTimeout(() => {
|
|
180
|
+
if (isSettled) {
|
|
181
|
+
return;
|
|
363
182
|
}
|
|
364
|
-
|
|
183
|
+
isSettled = true;
|
|
184
|
+
reject(new Error("Timed out while setting password"));
|
|
185
|
+
}, timeoutMs);
|
|
186
|
+
const resolveOnce = () => {
|
|
187
|
+
if (isSettled) {
|
|
188
|
+
return;
|
|
189
|
+
}
|
|
190
|
+
isSettled = true;
|
|
191
|
+
clearTimeout(timeout);
|
|
192
|
+
resolve();
|
|
193
|
+
};
|
|
194
|
+
const rejectOnce = (error) => {
|
|
195
|
+
if (isSettled) {
|
|
196
|
+
return;
|
|
197
|
+
}
|
|
198
|
+
isSettled = true;
|
|
199
|
+
clearTimeout(timeout);
|
|
200
|
+
reject(error);
|
|
201
|
+
};
|
|
202
|
+
try {
|
|
203
|
+
const maybePromise = user.setPassword(password, (error) => {
|
|
204
|
+
if (error) {
|
|
205
|
+
rejectOnce(error);
|
|
206
|
+
return;
|
|
207
|
+
}
|
|
208
|
+
resolveOnce();
|
|
209
|
+
});
|
|
210
|
+
if (maybePromise && typeof maybePromise.then === "function") {
|
|
211
|
+
maybePromise.then(resolveOnce).catch(rejectOnce);
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
catch (error) {
|
|
215
|
+
rejectOnce(error);
|
|
216
|
+
}
|
|
365
217
|
});
|
|
366
218
|
};
|
|
367
219
|
exports.setPasswordForUser = setPasswordForUser;
|
|
@@ -369,9 +221,9 @@ exports.setPasswordForUser = setPasswordForUser;
|
|
|
369
221
|
* Returns the duration when `ms` can parse it, otherwise logs and returns undefined so the caller
|
|
370
222
|
* keeps its default. Signing a token with an unparseable duration throws instead.
|
|
371
223
|
*/
|
|
372
|
-
|
|
224
|
+
const validateDuration = (envName, value) => {
|
|
373
225
|
if ((0, ms_1.default)(value) === undefined) {
|
|
374
|
-
logger_1.logger.error(
|
|
226
|
+
logger_1.logger.error(`${envName} is not a valid duration: "${value}". Using the default instead.`);
|
|
375
227
|
return undefined;
|
|
376
228
|
}
|
|
377
229
|
return value;
|
|
@@ -393,76 +245,66 @@ var validateDuration = function (envName, value) {
|
|
|
393
245
|
* authentication providers) to reuse and customize the same token generation logic.
|
|
394
246
|
* This ensures consistent and secure token issuance across different authentication flows.
|
|
395
247
|
*/
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
248
|
+
const generateTokens = async (user, authOptions, options = {}) => {
|
|
249
|
+
const tokenSecretOrKey = process.env.TOKEN_SECRET;
|
|
250
|
+
if (!tokenSecretOrKey) {
|
|
251
|
+
throw new errors_1.APIError({ status: 500, title: "TOKEN_SECRET must be set in env." });
|
|
400
252
|
}
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
tokenOptions =
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
};
|
|
446
|
-
if (authOptions === null || authOptions === void 0 ? void 0 : authOptions.generateRefreshTokenExpiration) {
|
|
447
|
-
refreshTokenOptions.expiresIn = authOptions.generateRefreshTokenExpiration(authUser);
|
|
448
|
-
}
|
|
449
|
-
else if (process.env.REFRESH_TOKEN_EXPIRES_IN) {
|
|
450
|
-
expiresIn = validateDuration("REFRESH_TOKEN_EXPIRES_IN", process.env.REFRESH_TOKEN_EXPIRES_IN);
|
|
451
|
-
if (expiresIn) {
|
|
452
|
-
refreshTokenOptions.expiresIn = expiresIn;
|
|
453
|
-
}
|
|
454
|
-
}
|
|
455
|
-
refreshToken = jsonwebtoken_1.default.sign(payload, refreshTokenSecretOrKey, refreshTokenOptions);
|
|
456
|
-
}
|
|
457
|
-
else {
|
|
458
|
-
logger_1.logger.info("REFRESH_TOKEN_SECRET not set so refresh tokens will not be issued");
|
|
253
|
+
const tokenUser = user;
|
|
254
|
+
if (!tokenUser?._id) {
|
|
255
|
+
logger_1.logger.warn("No user found for token generation");
|
|
256
|
+
return { refreshToken: null, token: null };
|
|
257
|
+
}
|
|
258
|
+
const sessionId = options.sessionId ?? (0, node_crypto_1.randomUUID)();
|
|
259
|
+
const authUser = user;
|
|
260
|
+
let payload = {
|
|
261
|
+
id: String(tokenUser._id),
|
|
262
|
+
sid: sessionId,
|
|
263
|
+
te: authUser.tokenEpoch ?? 0,
|
|
264
|
+
};
|
|
265
|
+
if (authOptions?.generateJWTPayload) {
|
|
266
|
+
payload = { ...authOptions.generateJWTPayload(authUser), ...payload };
|
|
267
|
+
}
|
|
268
|
+
const tokenOptions = {
|
|
269
|
+
expiresIn: "15m",
|
|
270
|
+
};
|
|
271
|
+
if (authOptions?.generateTokenExpiration) {
|
|
272
|
+
tokenOptions.expiresIn = authOptions.generateTokenExpiration(authUser);
|
|
273
|
+
}
|
|
274
|
+
else if (process.env.TOKEN_EXPIRES_IN) {
|
|
275
|
+
const expiresIn = validateDuration("TOKEN_EXPIRES_IN", process.env.TOKEN_EXPIRES_IN);
|
|
276
|
+
if (expiresIn) {
|
|
277
|
+
tokenOptions.expiresIn = expiresIn;
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
if (process.env.TOKEN_ISSUER) {
|
|
281
|
+
tokenOptions.issuer = process.env.TOKEN_ISSUER;
|
|
282
|
+
}
|
|
283
|
+
const token = jsonwebtoken_1.default.sign(payload, tokenSecretOrKey, tokenOptions);
|
|
284
|
+
const refreshTokenSecretOrKey = process.env.REFRESH_TOKEN_SECRET;
|
|
285
|
+
let refreshToken;
|
|
286
|
+
if (refreshTokenSecretOrKey) {
|
|
287
|
+
const refreshTokenOptions = {
|
|
288
|
+
expiresIn: "30d",
|
|
289
|
+
};
|
|
290
|
+
if (authOptions?.generateRefreshTokenExpiration) {
|
|
291
|
+
refreshTokenOptions.expiresIn = authOptions.generateRefreshTokenExpiration(authUser);
|
|
292
|
+
}
|
|
293
|
+
else if (process.env.REFRESH_TOKEN_EXPIRES_IN) {
|
|
294
|
+
const expiresIn = validateDuration("REFRESH_TOKEN_EXPIRES_IN", process.env.REFRESH_TOKEN_EXPIRES_IN);
|
|
295
|
+
if (expiresIn) {
|
|
296
|
+
refreshTokenOptions.expiresIn = expiresIn;
|
|
459
297
|
}
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
}
|
|
298
|
+
}
|
|
299
|
+
refreshToken = jsonwebtoken_1.default.sign(payload, refreshTokenSecretOrKey, refreshTokenOptions);
|
|
300
|
+
}
|
|
301
|
+
else {
|
|
302
|
+
logger_1.logger.info("REFRESH_TOKEN_SECRET not set so refresh tokens will not be issued");
|
|
303
|
+
}
|
|
304
|
+
return { refreshToken, sessionId, token };
|
|
463
305
|
};
|
|
464
306
|
exports.generateTokens = generateTokens;
|
|
465
|
-
|
|
307
|
+
const setupAuth = (app, userModel) => {
|
|
466
308
|
if (!userModel.createStrategy) {
|
|
467
309
|
throw new errors_1.APIError({ status: 500, title: "setupAuth userModel must have .createStrategy()" });
|
|
468
310
|
}
|
|
@@ -472,33 +314,21 @@ var setupAuth = function (app, userModel) {
|
|
|
472
314
|
passReqToCallback: true,
|
|
473
315
|
passwordField: "password",
|
|
474
316
|
usernameField: "email",
|
|
475
|
-
},
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
return [3 /*break*/, 3];
|
|
487
|
-
case 2:
|
|
488
|
-
error_3 = _c.sent();
|
|
489
|
-
return [2 /*return*/, done(error_3)];
|
|
490
|
-
case 3: return [2 /*return*/];
|
|
491
|
-
}
|
|
492
|
-
});
|
|
493
|
-
}); }));
|
|
494
|
-
var customTokenExtractor = function (req) {
|
|
495
|
-
var _a, _b, _c;
|
|
496
|
-
var token = null;
|
|
497
|
-
if ((_a = req === null || req === void 0 ? void 0 : req.cookies) === null || _a === void 0 ? void 0 : _a.jwt) {
|
|
317
|
+
}, async (req, email, password, done) => {
|
|
318
|
+
try {
|
|
319
|
+
done(undefined, await (0, exports.signupUser)(userModel, email, password, req.body));
|
|
320
|
+
}
|
|
321
|
+
catch (error) {
|
|
322
|
+
return done(error);
|
|
323
|
+
}
|
|
324
|
+
}));
|
|
325
|
+
const customTokenExtractor = (req) => {
|
|
326
|
+
let token = null;
|
|
327
|
+
if (req?.cookies?.jwt) {
|
|
498
328
|
token = req.cookies.jwt;
|
|
499
329
|
}
|
|
500
|
-
else if (
|
|
501
|
-
token =
|
|
330
|
+
else if (req?.headers?.authorization) {
|
|
331
|
+
token = req?.headers?.authorization.split(" ")[1];
|
|
502
332
|
}
|
|
503
333
|
return token;
|
|
504
334
|
};
|
|
@@ -506,243 +336,199 @@ var setupAuth = function (app, userModel) {
|
|
|
506
336
|
if (process.env.NODE_ENV !== "test") {
|
|
507
337
|
logger_1.logger.debug("Setting up JWT Authentication");
|
|
508
338
|
}
|
|
509
|
-
|
|
510
|
-
|
|
339
|
+
const secretOrKey = process.env.TOKEN_SECRET;
|
|
340
|
+
const jwtOpts = {
|
|
511
341
|
issuer: process.env.TOKEN_ISSUER,
|
|
512
342
|
jwtFromRequest: customTokenExtractor,
|
|
513
|
-
secretOrKey
|
|
343
|
+
secretOrKey,
|
|
514
344
|
};
|
|
515
|
-
passport_1.default.use("jwt", new passport_jwt_1.Strategy(jwtOpts,
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
}
|
|
539
|
-
if (!userModel.createAnonymousUser) return [3 /*break*/, 6];
|
|
540
|
-
logger_1.logger.info("[jwt] Creating anonymous user");
|
|
541
|
-
return [4 /*yield*/, userModel.createAnonymousUser()];
|
|
542
|
-
case 5:
|
|
543
|
-
user = _a.sent();
|
|
544
|
-
return [2 /*return*/, done(null, user)];
|
|
545
|
-
case 6:
|
|
546
|
-
logger_1.logger.info("[jwt] No user found from token");
|
|
547
|
-
return [2 /*return*/, done(null, false)];
|
|
548
|
-
}
|
|
549
|
-
});
|
|
550
|
-
}); }));
|
|
345
|
+
passport_1.default.use("jwt", new passport_jwt_1.Strategy(jwtOpts, async (jwtPayload, done) => {
|
|
346
|
+
let user = null;
|
|
347
|
+
if (!jwtPayload) {
|
|
348
|
+
return done(null, false);
|
|
349
|
+
}
|
|
350
|
+
try {
|
|
351
|
+
user = await userModel.findById(jwtPayload.id);
|
|
352
|
+
}
|
|
353
|
+
catch (error) {
|
|
354
|
+
logger_1.logger.warn(`[jwt] Error finding user from id: ${error}`);
|
|
355
|
+
return done(error, false);
|
|
356
|
+
}
|
|
357
|
+
if (user) {
|
|
358
|
+
return done(null, user);
|
|
359
|
+
}
|
|
360
|
+
if (userModel.createAnonymousUser) {
|
|
361
|
+
logger_1.logger.info("[jwt] Creating anonymous user");
|
|
362
|
+
user = await userModel.createAnonymousUser();
|
|
363
|
+
return done(null, user);
|
|
364
|
+
}
|
|
365
|
+
logger_1.logger.info("[jwt] No user found from token");
|
|
366
|
+
return done(null, false);
|
|
367
|
+
}));
|
|
551
368
|
}
|
|
552
369
|
// Adds req.user to the request. This may wind up duplicating requests with passport,
|
|
553
370
|
// but passport doesn't give us req.user early enough.
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
// Genuine JWTs that fail verification (malformed/expired) still return 401 so the
|
|
594
|
-
// client's token-refresh flow is preserved.
|
|
595
|
-
if (jsonwebtoken_1.default.decode(token, { complete: true }) === null) {
|
|
596
|
-
return [2 /*return*/, next()];
|
|
597
|
-
}
|
|
598
|
-
userText = ((_c = req.user) === null || _c === void 0 ? void 0 : _c._id) ? " for user ".concat(req.user._id, " ") : "";
|
|
599
|
-
expiredAt = error && typeof error === "object" && "expiredAt" in error
|
|
600
|
-
? error.expiredAt
|
|
601
|
-
: undefined;
|
|
602
|
-
message = (0, errors_1.errorMessage)(error);
|
|
603
|
-
details = "[jwt] Error decoding token".concat(userText, ": ").concat(error, ", expired at ").concat(expiredAt, ", current time: ").concat(luxon_1.DateTime.now().toMillis());
|
|
604
|
-
logger_1.logger.debug(details);
|
|
605
|
-
return [2 /*return*/, res.status(401).json({ details: details, message: message })];
|
|
606
|
-
}
|
|
607
|
-
if (!(decoded === null || decoded === void 0 ? void 0 : decoded.id)) return [3 /*break*/, 4];
|
|
608
|
-
sessionId = (0, requestContext_1.getSessionIdFromJwtPayload)(decoded);
|
|
609
|
-
req.authTokenPayload = decoded;
|
|
610
|
-
if (sessionId) {
|
|
611
|
-
req.sessionId = sessionId;
|
|
612
|
-
(0, requestContext_1.setRequestContext)({ sessionId: sessionId });
|
|
613
|
-
}
|
|
614
|
-
_e.label = 1;
|
|
615
|
-
case 1:
|
|
616
|
-
_e.trys.push([1, 3, , 4]);
|
|
617
|
-
return [4 /*yield*/, userModel.findById(decoded.id)];
|
|
618
|
-
case 2:
|
|
619
|
-
user = _e.sent();
|
|
620
|
-
req.user = user;
|
|
621
|
-
(0, requestContext_1.updateRequestContextFromRequest)(req, res);
|
|
622
|
-
if ((_d = req.user) === null || _d === void 0 ? void 0 : _d.disabled) {
|
|
623
|
-
logger_1.logger.warn("[jwt] User ".concat(req.user.id, " is disabled"));
|
|
624
|
-
return [2 /*return*/, res.status(401).json({ status: 401, title: "User is disabled" })];
|
|
625
|
-
}
|
|
626
|
-
return [3 /*break*/, 4];
|
|
627
|
-
case 3:
|
|
628
|
-
error_5 = _e.sent();
|
|
629
|
-
logger_1.logger.warn("[jwt] Error finding user from id: ".concat(error_5));
|
|
630
|
-
return [3 /*break*/, 4];
|
|
631
|
-
case 4: return [2 /*return*/, next()];
|
|
371
|
+
const decodeJWTMiddleware = async (req, res, next) => {
|
|
372
|
+
if (!process.env.TOKEN_SECRET) {
|
|
373
|
+
return next();
|
|
374
|
+
}
|
|
375
|
+
// Login, signup, and refresh exchange credentials. A stale access JWT in
|
|
376
|
+
// Authorization / the jwt cookie must not 401 before those handlers run.
|
|
377
|
+
if ((0, policies_1.isJwtCredentialExchangePath)(req)) {
|
|
378
|
+
return next();
|
|
379
|
+
}
|
|
380
|
+
// Allow requests with a "Secret" prefix to pass through since this is a string value,
|
|
381
|
+
// not a jwt that needs to be decoded
|
|
382
|
+
if (req?.headers?.authorization?.split(" ")[0] === "Secret") {
|
|
383
|
+
return next();
|
|
384
|
+
}
|
|
385
|
+
const token = customTokenExtractor(req);
|
|
386
|
+
// For some reason, our app will happily put null into the authorization header when logging
|
|
387
|
+
// out then back in.
|
|
388
|
+
if (!token || token === "null" || token === "undefined") {
|
|
389
|
+
return next();
|
|
390
|
+
}
|
|
391
|
+
let decoded;
|
|
392
|
+
try {
|
|
393
|
+
decoded = jsonwebtoken_1.default.verify(token, process.env.TOKEN_SECRET, {
|
|
394
|
+
issuer: process.env.TOKEN_ISSUER,
|
|
395
|
+
});
|
|
396
|
+
}
|
|
397
|
+
catch (error) {
|
|
398
|
+
// A bearer token that is not a JWT at all (e.g. a Better Auth opaque session
|
|
399
|
+
// token) is not ours to reject — fall through so a later auth layer (Better
|
|
400
|
+
// Auth session middleware) or the route's own permissions can handle it.
|
|
401
|
+
// Detect this by decoding the token's header/payload structure (D1) rather
|
|
402
|
+
// than counting dot-delimited segments: an opaque token can coincidentally
|
|
403
|
+
// contain exactly two dots, and a malformed-but-JWT-shaped string can fail
|
|
404
|
+
// this same check for the wrong reason — `jwt.decode` parses the actual
|
|
405
|
+
// base64url JSON structure of each segment, which dot-counting cannot.
|
|
406
|
+
// Genuine JWTs that fail verification (malformed/expired) still return 401 so the
|
|
407
|
+
// client's token-refresh flow is preserved.
|
|
408
|
+
if (jsonwebtoken_1.default.decode(token, { complete: true }) === null) {
|
|
409
|
+
return next();
|
|
632
410
|
}
|
|
633
|
-
|
|
634
|
-
|
|
411
|
+
const userText = req.user?._id ? ` for user ${req.user._id} ` : "";
|
|
412
|
+
const expiredAt = error && typeof error === "object" && "expiredAt" in error
|
|
413
|
+
? error.expiredAt
|
|
414
|
+
: undefined;
|
|
415
|
+
const message = (0, errors_1.errorMessage)(error);
|
|
416
|
+
const details = `[jwt] Error decoding token${userText}: ${error}, expired at ${expiredAt}, current time: ${luxon_1.DateTime.now().toMillis()}`;
|
|
417
|
+
logger_1.logger.debug(details);
|
|
418
|
+
return res.status(401).json({ details, message });
|
|
419
|
+
}
|
|
420
|
+
if (decoded?.id) {
|
|
421
|
+
const sessionId = (0, requestContext_1.getSessionIdFromJwtPayload)(decoded);
|
|
422
|
+
req.authTokenPayload = decoded;
|
|
423
|
+
if (sessionId) {
|
|
424
|
+
req.sessionId = sessionId;
|
|
425
|
+
(0, requestContext_1.setRequestContext)({ sessionId });
|
|
426
|
+
}
|
|
427
|
+
try {
|
|
428
|
+
const user = await userModel.findById(decoded.id);
|
|
429
|
+
req.user = user;
|
|
430
|
+
(0, requestContext_1.updateRequestContextFromRequest)(req, res);
|
|
431
|
+
if (req.user?.disabled) {
|
|
432
|
+
logger_1.logger.warn(`[jwt] User ${req.user.id} is disabled`);
|
|
433
|
+
return res.status(401).json({ status: 401, title: "User is disabled" });
|
|
434
|
+
}
|
|
435
|
+
}
|
|
436
|
+
catch (error) {
|
|
437
|
+
logger_1.logger.warn(`[jwt] Error finding user from id: ${error}`);
|
|
438
|
+
}
|
|
439
|
+
}
|
|
440
|
+
return next();
|
|
441
|
+
};
|
|
635
442
|
app.use(decodeJWTMiddleware);
|
|
636
443
|
// express 5's urlencoded() handler type doesn't match RequestHandler directly
|
|
637
444
|
app.use(express_1.default.urlencoded({ extended: false }));
|
|
638
445
|
};
|
|
639
446
|
exports.setupAuth = setupAuth;
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
router.post("/login",
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
return
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
447
|
+
const addAuthRoutes = (app, userModel, authOptions) => {
|
|
448
|
+
const router = express_1.default.Router();
|
|
449
|
+
router.post("/login", async (req, res, next) => {
|
|
450
|
+
passport_1.default.authenticate("local", { session: false }, async (err, user, info) => {
|
|
451
|
+
if (err) {
|
|
452
|
+
logger_1.logger.error(`Error logging in: ${err}`);
|
|
453
|
+
return next(err);
|
|
454
|
+
}
|
|
455
|
+
if (!user) {
|
|
456
|
+
logger_1.logger.warn(`Invalid login: ${info}`);
|
|
457
|
+
return res.status(401).json({ message: info?.message });
|
|
458
|
+
}
|
|
459
|
+
if (authOptions?.requireEmailVerification && user.emailVerified !== true) {
|
|
460
|
+
return next(new errors_1.APIError({
|
|
461
|
+
code: "email-not-verified",
|
|
462
|
+
status: 403,
|
|
463
|
+
title: "Email is not verified",
|
|
464
|
+
}));
|
|
465
|
+
}
|
|
466
|
+
if (process.env.NODE_ENV !== "test") {
|
|
467
|
+
logger_1.logger.info(`User logged in: ${user._id}, type: ${user.type || "N/A"}`);
|
|
468
|
+
}
|
|
469
|
+
const tokens = await (0, exports.generateTokens)(user, authOptions);
|
|
470
|
+
if (tokens.sessionId) {
|
|
471
|
+
(0, requestContext_1.setRequestContext)({ sessionId: tokens.sessionId, userId: String(user._id) });
|
|
472
|
+
res.setHeader("X-Session-ID", tokens.sessionId);
|
|
473
|
+
}
|
|
474
|
+
return res.json({
|
|
475
|
+
data: { refreshToken: tokens.refreshToken, token: tokens.token, userId: user?._id },
|
|
476
|
+
});
|
|
477
|
+
})(req, res, next);
|
|
478
|
+
});
|
|
479
|
+
router.post("/refresh_token", async (req, res) => {
|
|
480
|
+
if (!req.body.refreshToken) {
|
|
481
|
+
logger_1.logger.error(`No refresh token provided, must provide refreshToken in body, user id: ${req.user?.id}`);
|
|
482
|
+
return res
|
|
483
|
+
.status(401)
|
|
484
|
+
.json({ message: "No refresh token provided, must provide refreshToken in body" });
|
|
485
|
+
}
|
|
486
|
+
if (!process.env.REFRESH_TOKEN_SECRET) {
|
|
487
|
+
logger_1.logger.error(`No REFRESH_TOKEN_SECRET set, cannot refresh token, user id: ${req.user?.id}`);
|
|
488
|
+
return res.status(401).json({ message: "No REFRESH_TOKEN_SECRET set, cannot refresh token" });
|
|
489
|
+
}
|
|
490
|
+
const refreshTokenSecretOrKey = process.env.REFRESH_TOKEN_SECRET;
|
|
491
|
+
let decoded;
|
|
492
|
+
try {
|
|
493
|
+
decoded = jsonwebtoken_1.default.verify(req.body.refreshToken, refreshTokenSecretOrKey);
|
|
494
|
+
}
|
|
495
|
+
catch (error) {
|
|
496
|
+
logger_1.logger.error(`Error refreshing token for user ${req.user?.id}: ${error}`);
|
|
497
|
+
const message = (0, errors_1.errorMessage)(error);
|
|
498
|
+
return res.status(401).json({ message });
|
|
499
|
+
}
|
|
500
|
+
if (decoded?.id) {
|
|
501
|
+
const user = await userModel.findById(decoded.id);
|
|
502
|
+
const tokenEpoch = typeof decoded.te === "number" ? decoded.te : 0;
|
|
503
|
+
const userEpoch = user?.tokenEpoch ?? 0;
|
|
504
|
+
if (!user || tokenEpoch !== userEpoch) {
|
|
505
|
+
logger_1.logger.error(`Invalid refresh token, user id: ${req.user?.id}`);
|
|
506
|
+
return res.status(401).json({ message: "Invalid refresh token" });
|
|
507
|
+
}
|
|
508
|
+
const sessionId = (0, requestContext_1.getSessionIdFromJwtPayload)(decoded);
|
|
509
|
+
const tokens = await (0, exports.generateTokens)(user, authOptions, { sessionId });
|
|
510
|
+
if (tokens.sessionId) {
|
|
511
|
+
(0, requestContext_1.setRequestContext)({
|
|
512
|
+
sessionId: tokens.sessionId,
|
|
513
|
+
userId: user?._id ? String(user._id) : undefined,
|
|
678
514
|
});
|
|
679
|
-
|
|
680
|
-
return [2 /*return*/];
|
|
681
|
-
});
|
|
682
|
-
}); });
|
|
683
|
-
router.post("/refresh_token", function (req, res) { return __awaiter(void 0, void 0, void 0, function () {
|
|
684
|
-
var refreshTokenSecretOrKey, decoded, message, user, tokenEpoch, userEpoch, sessionId, tokens;
|
|
685
|
-
var _a, _b, _c, _d, _e, _f;
|
|
686
|
-
return __generator(this, function (_g) {
|
|
687
|
-
switch (_g.label) {
|
|
688
|
-
case 0:
|
|
689
|
-
if (!req.body.refreshToken) {
|
|
690
|
-
logger_1.logger.error("No refresh token provided, must provide refreshToken in body, user id: ".concat((_a = req.user) === null || _a === void 0 ? void 0 : _a.id));
|
|
691
|
-
return [2 /*return*/, res
|
|
692
|
-
.status(401)
|
|
693
|
-
.json({ message: "No refresh token provided, must provide refreshToken in body" })];
|
|
694
|
-
}
|
|
695
|
-
if (!process.env.REFRESH_TOKEN_SECRET) {
|
|
696
|
-
logger_1.logger.error("No REFRESH_TOKEN_SECRET set, cannot refresh token, user id: ".concat((_b = req.user) === null || _b === void 0 ? void 0 : _b.id));
|
|
697
|
-
return [2 /*return*/, res.status(401).json({ message: "No REFRESH_TOKEN_SECRET set, cannot refresh token" })];
|
|
698
|
-
}
|
|
699
|
-
refreshTokenSecretOrKey = process.env.REFRESH_TOKEN_SECRET;
|
|
700
|
-
try {
|
|
701
|
-
decoded = jsonwebtoken_1.default.verify(req.body.refreshToken, refreshTokenSecretOrKey);
|
|
702
|
-
}
|
|
703
|
-
catch (error) {
|
|
704
|
-
logger_1.logger.error("Error refreshing token for user ".concat((_c = req.user) === null || _c === void 0 ? void 0 : _c.id, ": ").concat(error));
|
|
705
|
-
message = (0, errors_1.errorMessage)(error);
|
|
706
|
-
return [2 /*return*/, res.status(401).json({ message: message })];
|
|
707
|
-
}
|
|
708
|
-
if (!(decoded === null || decoded === void 0 ? void 0 : decoded.id)) return [3 /*break*/, 3];
|
|
709
|
-
return [4 /*yield*/, userModel.findById(decoded.id)];
|
|
710
|
-
case 1:
|
|
711
|
-
user = _g.sent();
|
|
712
|
-
tokenEpoch = typeof decoded.te === "number" ? decoded.te : 0;
|
|
713
|
-
userEpoch = (_d = user === null || user === void 0 ? void 0 : user.tokenEpoch) !== null && _d !== void 0 ? _d : 0;
|
|
714
|
-
if (!user || tokenEpoch !== userEpoch) {
|
|
715
|
-
logger_1.logger.error("Invalid refresh token, user id: ".concat((_e = req.user) === null || _e === void 0 ? void 0 : _e.id));
|
|
716
|
-
return [2 /*return*/, res.status(401).json({ message: "Invalid refresh token" })];
|
|
717
|
-
}
|
|
718
|
-
sessionId = (0, requestContext_1.getSessionIdFromJwtPayload)(decoded);
|
|
719
|
-
return [4 /*yield*/, (0, exports.generateTokens)(user, authOptions, { sessionId: sessionId })];
|
|
720
|
-
case 2:
|
|
721
|
-
tokens = _g.sent();
|
|
722
|
-
if (tokens.sessionId) {
|
|
723
|
-
(0, requestContext_1.setRequestContext)({
|
|
724
|
-
sessionId: tokens.sessionId,
|
|
725
|
-
userId: (user === null || user === void 0 ? void 0 : user._id) ? String(user._id) : undefined,
|
|
726
|
-
});
|
|
727
|
-
res.setHeader("X-Session-ID", tokens.sessionId);
|
|
728
|
-
}
|
|
729
|
-
logger_1.logger.debug("Refreshed token for ".concat(user === null || user === void 0 ? void 0 : user.id));
|
|
730
|
-
return [2 /*return*/, res.json({ data: { refreshToken: tokens.refreshToken, token: tokens.token } })];
|
|
731
|
-
case 3:
|
|
732
|
-
logger_1.logger.error("Invalid refresh token, user id: ".concat((_f = req.user) === null || _f === void 0 ? void 0 : _f.id));
|
|
733
|
-
return [2 /*return*/, res.status(401).json({ message: "Invalid refresh token" })];
|
|
515
|
+
res.setHeader("X-Session-ID", tokens.sessionId);
|
|
734
516
|
}
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
517
|
+
logger_1.logger.debug(`Refreshed token for ${user?.id}`);
|
|
518
|
+
return res.json({ data: { refreshToken: tokens.refreshToken, token: tokens.token } });
|
|
519
|
+
}
|
|
520
|
+
logger_1.logger.error(`Invalid refresh token, user id: ${req.user?.id}`);
|
|
521
|
+
return res.status(401).json({ message: "Invalid refresh token" });
|
|
522
|
+
});
|
|
523
|
+
const signupDisabled = process.env.SIGNUP_DISABLED === "true";
|
|
738
524
|
if (!signupDisabled) {
|
|
739
525
|
router.post("/signup",
|
|
740
526
|
// Custom callback instead of `failWithError` — passport's internal
|
|
741
527
|
// AuthenticationError is unusable in strict-mode bundles (see
|
|
742
528
|
// authenticateMiddleware). Strategy errors (e.g. duplicate email) pass
|
|
743
529
|
// through unchanged; a bare failure (missing credentials) is a 400.
|
|
744
|
-
|
|
745
|
-
passport_1.default.authenticate("signup", { session: false },
|
|
530
|
+
(req, res, next) => {
|
|
531
|
+
passport_1.default.authenticate("signup", { session: false }, (err, user) => {
|
|
746
532
|
if (err) {
|
|
747
533
|
return next(err);
|
|
748
534
|
}
|
|
@@ -752,126 +538,91 @@ var addAuthRoutes = function (app, userModel, authOptions) {
|
|
|
752
538
|
req.user = user;
|
|
753
539
|
return next();
|
|
754
540
|
})(req, res, next);
|
|
755
|
-
},
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
switch (_c.label) {
|
|
760
|
-
case 0:
|
|
761
|
-
if (!req.user) return [3 /*break*/, 4];
|
|
762
|
-
_c.label = 1;
|
|
763
|
-
case 1:
|
|
764
|
-
_c.trys.push([1, 3, , 4]);
|
|
765
|
-
return [4 /*yield*/, (0, authRecovery_1.sendVerificationEmail)(req.user, authOptions)];
|
|
766
|
-
case 2:
|
|
767
|
-
_c.sent();
|
|
768
|
-
return [3 /*break*/, 4];
|
|
769
|
-
case 3:
|
|
770
|
-
error_6 = _c.sent();
|
|
771
|
-
logger_1.logger.error("[auth] Failed to send verification mail after signup", { error: error_6 });
|
|
772
|
-
return [3 /*break*/, 4];
|
|
773
|
-
case 4: return [4 /*yield*/, (0, exports.generateTokens)(req.user, authOptions)];
|
|
774
|
-
case 5:
|
|
775
|
-
tokens = _c.sent();
|
|
776
|
-
if (tokens.sessionId) {
|
|
777
|
-
(0, requestContext_1.setRequestContext)({
|
|
778
|
-
sessionId: tokens.sessionId,
|
|
779
|
-
userId: ((_a = req.user) === null || _a === void 0 ? void 0 : _a._id) ? String(req.user._id) : undefined,
|
|
780
|
-
});
|
|
781
|
-
res.setHeader("X-Session-ID", tokens.sessionId);
|
|
782
|
-
}
|
|
783
|
-
return [2 /*return*/, res.json({
|
|
784
|
-
data: { refreshToken: tokens.refreshToken, token: tokens.token, userId: (_b = req.user) === null || _b === void 0 ? void 0 : _b._id },
|
|
785
|
-
})];
|
|
541
|
+
}, async (req, res) => {
|
|
542
|
+
if (req.user && authOptions?.emailVerification !== false) {
|
|
543
|
+
try {
|
|
544
|
+
await (0, authRecovery_1.sendVerificationEmail)(req.user, authOptions);
|
|
786
545
|
}
|
|
546
|
+
catch (error) {
|
|
547
|
+
logger_1.logger.error("[auth] Failed to send verification mail after signup", { error });
|
|
548
|
+
}
|
|
549
|
+
}
|
|
550
|
+
const tokens = await (0, exports.generateTokens)(req.user, authOptions);
|
|
551
|
+
if (tokens.sessionId) {
|
|
552
|
+
(0, requestContext_1.setRequestContext)({
|
|
553
|
+
sessionId: tokens.sessionId,
|
|
554
|
+
userId: req.user?._id ? String(req.user._id) : undefined,
|
|
555
|
+
});
|
|
556
|
+
res.setHeader("X-Session-ID", tokens.sessionId);
|
|
557
|
+
}
|
|
558
|
+
return res.json({
|
|
559
|
+
data: { refreshToken: tokens.refreshToken, token: tokens.token, userId: req.user?._id },
|
|
787
560
|
});
|
|
788
|
-
});
|
|
561
|
+
});
|
|
789
562
|
}
|
|
790
563
|
app.set("etag", false);
|
|
791
564
|
app.use("/auth", router);
|
|
792
565
|
(0, authRecovery_1.addAuthRecoveryRoutes)(app, userModel, authOptions);
|
|
793
566
|
};
|
|
794
567
|
exports.addAuthRoutes = addAuthRoutes;
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
router.get("/me", (0, exports.authenticateMiddleware)(),
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
|
|
834
|
-
|
|
835
|
-
|
|
836
|
-
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
return [4 /*yield*/, userModel.findById(req.user.id)];
|
|
840
|
-
case 1:
|
|
841
|
-
doc = _c.sent();
|
|
842
|
-
if (!doc) {
|
|
843
|
-
return [2 /*return*/, res.sendStatus(404)];
|
|
844
|
-
}
|
|
845
|
-
_c.label = 2;
|
|
846
|
-
case 2:
|
|
847
|
-
_c.trys.push([2, 7, , 8]);
|
|
848
|
-
update = (0, exports.stripPrivilegedUserFields)((_b = req.body) !== null && _b !== void 0 ? _b : {}, "PATCH /auth/me");
|
|
849
|
-
isMailboxChange = isEmailUpdateChangingMailbox(doc.email, update.email);
|
|
850
|
-
Object.assign(doc, update);
|
|
851
|
-
if (!isMailboxChange) return [3 /*break*/, 5];
|
|
852
|
-
return [4 /*yield*/, authTokens_1.AuthToken.invalidateUnusedFor({ _id: String(doc._id) }, "passwordReset")];
|
|
853
|
-
case 3:
|
|
854
|
-
_c.sent();
|
|
855
|
-
if (!(userModel.schema.path("emailVerified") !== undefined)) return [3 /*break*/, 5];
|
|
568
|
+
const addMeRoutes = (app, userModel, _authOptions, accessControl) => {
|
|
569
|
+
const router = express_1.default.Router();
|
|
570
|
+
router.get("/me", (0, exports.authenticateMiddleware)(), async (req, res) => {
|
|
571
|
+
if (!req.user?.id) {
|
|
572
|
+
logger_1.logger.debug("Not user found for /me");
|
|
573
|
+
return res.sendStatus(401);
|
|
574
|
+
}
|
|
575
|
+
const data = await userModel.findById(req.user.id);
|
|
576
|
+
if (!data) {
|
|
577
|
+
logger_1.logger.debug("Not user data found for /me");
|
|
578
|
+
return res.sendStatus(404);
|
|
579
|
+
}
|
|
580
|
+
const dataObject = data.toObject();
|
|
581
|
+
dataObject.id = data._id;
|
|
582
|
+
if (accessControl) {
|
|
583
|
+
const withRoles = data;
|
|
584
|
+
dataObject.roles = withRoles.roles ?? [];
|
|
585
|
+
dataObject.permissions = await accessControl.getPermissions({
|
|
586
|
+
user: data,
|
|
587
|
+
});
|
|
588
|
+
}
|
|
589
|
+
return res.json({ data: dataObject });
|
|
590
|
+
});
|
|
591
|
+
router.patch("/me", (0, exports.authenticateMiddleware)(), async (req, res) => {
|
|
592
|
+
if (!req.user?.id) {
|
|
593
|
+
return res.sendStatus(401);
|
|
594
|
+
}
|
|
595
|
+
const doc = await userModel.findById(req.user.id);
|
|
596
|
+
if (!doc) {
|
|
597
|
+
return res.sendStatus(404);
|
|
598
|
+
}
|
|
599
|
+
// TODO support limited updates for profile.
|
|
600
|
+
// try {
|
|
601
|
+
// body = transform(req.body, "update", req.user);
|
|
602
|
+
// } catch (e) {
|
|
603
|
+
// return res.status(403).send({message: (e as Error).message});
|
|
604
|
+
// }
|
|
605
|
+
try {
|
|
606
|
+
const update = (0, exports.stripPrivilegedUserFields)(req.body ?? {}, "PATCH /auth/me");
|
|
607
|
+
const isMailboxChange = isEmailUpdateChangingMailbox(doc.email, update.email);
|
|
608
|
+
Object.assign(doc, update);
|
|
609
|
+
if (isMailboxChange) {
|
|
610
|
+
await authTokens_1.AuthToken.invalidateUnusedFor({ _id: String(doc._id) }, "passwordReset");
|
|
611
|
+
if (userModel.schema.path("emailVerified") !== undefined) {
|
|
856
612
|
doc.emailVerified = false;
|
|
857
|
-
|
|
858
|
-
|
|
859
|
-
_c.sent();
|
|
860
|
-
_c.label = 5;
|
|
861
|
-
case 5: return [4 /*yield*/, doc.save()];
|
|
862
|
-
case 6:
|
|
863
|
-
_c.sent();
|
|
864
|
-
dataObject = doc.toObject();
|
|
865
|
-
dataObject.id = doc._id;
|
|
866
|
-
return [2 /*return*/, res.json({ data: dataObject })];
|
|
867
|
-
case 7:
|
|
868
|
-
error_7 = _c.sent();
|
|
869
|
-
message = (0, errors_1.errorMessage)(error_7);
|
|
870
|
-
return [2 /*return*/, res.status(403).send({ message: message })];
|
|
871
|
-
case 8: return [2 /*return*/];
|
|
613
|
+
await authTokens_1.AuthToken.invalidateUnusedFor({ _id: String(doc._id) }, "emailVerification");
|
|
614
|
+
}
|
|
872
615
|
}
|
|
873
|
-
|
|
874
|
-
|
|
616
|
+
await doc.save();
|
|
617
|
+
const dataObject = doc.toObject();
|
|
618
|
+
dataObject.id = doc._id;
|
|
619
|
+
return res.json({ data: dataObject });
|
|
620
|
+
}
|
|
621
|
+
catch (error) {
|
|
622
|
+
const message = (0, errors_1.errorMessage)(error);
|
|
623
|
+
return res.status(403).send({ message });
|
|
624
|
+
}
|
|
625
|
+
});
|
|
875
626
|
app.set("etag", false);
|
|
876
627
|
app.use("/auth", router);
|
|
877
628
|
app.use(errors_1.apiErrorMiddleware);
|