webspresso 0.0.107 → 0.0.108
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/.agents/AGENTS.md +4 -1
- package/.agents/CACHE.md +1 -0
- package/.agents/CONTEXT.md +152 -0
- package/.agents/ORM.md +74 -0
- package/.agents/SHUTDOWN.md +8 -1
- package/.agents/skills/webspresso-framework/SKILL.md +2 -1
- package/.agents/skills/webspresso-orm-and-database/SKILL.md +9 -0
- package/.agents/skills/webspresso-routing-and-api/SKILL.md +18 -2
- package/.agents/skills/webspresso-services/SKILL.md +36 -3
- package/AGENTS.md +6 -3
- package/core/app.js +7 -5
- package/core/applySchema.js +3 -72
- package/core/cache/lru.js +10 -0
- package/core/cache/tagged-lru.js +4 -0
- package/core/compileSchema.js +3 -68
- package/core/compression/compressible.js +53 -6
- package/core/compression/negotiate.js +31 -12
- package/core/context/app-context.js +201 -0
- package/core/context/index.js +55 -0
- package/core/context/request.js +241 -0
- package/core/events/dispatcher.js +144 -15
- package/core/events/signal.js +9 -0
- package/core/health/probes.js +12 -2
- package/core/http/index.js +10 -1
- package/core/http/pipeline.js +519 -368
- package/core/index.js +24 -1
- package/core/orm/eager-loader.js +90 -55
- package/core/orm/index.js +3 -39
- package/core/orm/model.js +6 -1
- package/core/orm/schema-helpers.js +59 -0
- package/core/orm/transaction.js +109 -14
- package/core/plugins/index.js +8 -0
- package/core/plugins/plugin-manager.js +1098 -0
- package/core/queue/manager.js +55 -27
- package/core/rate-limit/stores/memory.js +23 -10
- package/core/resilience/circuit-breaker.js +34 -14
- package/core/schema-cache.js +2 -64
- package/core/services/builtins/auth.js +273 -0
- package/core/services/builtins/exchange.js +229 -0
- package/core/services/builtins/file-manager.js +178 -0
- package/core/services/builtins/mail.js +134 -0
- package/core/services/builtins/media.js +196 -0
- package/core/services/builtins/system.js +219 -0
- package/core/services/discovery.js +133 -0
- package/core/services/executor.js +629 -0
- package/core/services/index.js +110 -5
- package/core/services/loader.js +161 -0
- package/core/services/memoize.js +408 -0
- package/core/services/registry.js +731 -0
- package/core/services/validator.js +424 -0
- package/core/shutdown/shutdown-manager.js +146 -85
- package/core/ssr/stream.js +109 -16
- package/core/stream/text-stream.js +45 -4
- package/core/utils/index.js +110 -0
- package/core/utils/timeout.js +4 -0
- package/core/validation/apply.js +74 -0
- package/core/validation/cache.js +66 -0
- package/core/validation/compiler.js +77 -0
- package/core/validation/index.js +22 -1
- package/index.d.ts +77 -4
- package/index.js +64 -20
- package/package.json +1 -1
- package/src/app-context.js +4 -196
- package/src/dev/typegen.js +1 -1
- package/src/plugin-manager.js +5 -1086
- package/src/server.js +4 -1
- package/src/services/builtins/auth.js +2 -273
- package/src/services/builtins/exchange.js +2 -229
- package/src/services/builtins/file-manager.js +2 -178
- package/src/services/builtins/mail.js +2 -134
- package/src/services/builtins/media.js +2 -196
- package/src/services/builtins/system.js +2 -219
- package/src/services/discovery.js +2 -133
- package/src/services/executor.js +2 -575
- package/src/services/index.js +4 -109
- package/src/services/loader.js +1 -119
- package/src/services/memoize.js +2 -408
- package/src/services/registry.js +1 -711
- package/src/services/validator.js +2 -424
- package/core/utils/array.js +0 -12
- package/core/utils/base64url.js +0 -8
- package/core/utils/ensure-leading-slash.js +0 -6
- package/core/utils/escape-html.js +0 -7
- package/core/utils/escape-regexp.js +0 -7
- package/core/utils/get-client-ip.js +0 -6
- package/core/utils/hmac.js +0 -6
- package/core/utils/random.js +0 -9
- package/core/utils/safe-compare.js +0 -3
- package/core/utils/sha256.js +0 -6
- package/core/utils/strip-trailing-slash.js +0 -6
- package/core/utils/walk.js +0 -7
package/core/queue/manager.js
CHANGED
|
@@ -49,6 +49,8 @@ class QueueManager extends EventEmitter {
|
|
|
49
49
|
this.isDraining = false;
|
|
50
50
|
this.isRunning = false;
|
|
51
51
|
this._timer = null;
|
|
52
|
+
/** @type {Set<Promise<any>>} */
|
|
53
|
+
this._activeJobPromises = new Set();
|
|
52
54
|
|
|
53
55
|
// Retention configuration
|
|
54
56
|
const retentionOption = options.retention;
|
|
@@ -258,18 +260,24 @@ class QueueManager extends EventEmitter {
|
|
|
258
260
|
this.scheduler.stop();
|
|
259
261
|
}
|
|
260
262
|
|
|
261
|
-
if (this.runningCount
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
263
|
+
if (this.runningCount > 0 && this._activeJobPromises.size > 0) {
|
|
264
|
+
let timer = null;
|
|
265
|
+
const timeoutPromise = new Promise((resolve) => {
|
|
266
|
+
timer = setTimeout(resolve, timeoutMs);
|
|
267
|
+
if (timer && typeof timer.unref === 'function') {
|
|
268
|
+
timer.unref();
|
|
269
|
+
}
|
|
270
|
+
});
|
|
271
|
+
const allJobsPromise = Promise.allSettled(Array.from(this._activeJobPromises));
|
|
266
272
|
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
273
|
+
try {
|
|
274
|
+
await Promise.race([allJobsPromise, timeoutPromise]);
|
|
275
|
+
} finally {
|
|
276
|
+
if (timer) {
|
|
277
|
+
clearTimeout(timer);
|
|
278
|
+
timer = null;
|
|
279
|
+
}
|
|
271
280
|
}
|
|
272
|
-
await new Promise((res) => setTimeout(res, 50));
|
|
273
281
|
}
|
|
274
282
|
|
|
275
283
|
this.isDraining = false;
|
|
@@ -284,6 +292,10 @@ class QueueManager extends EventEmitter {
|
|
|
284
292
|
async stop() {
|
|
285
293
|
this.pause();
|
|
286
294
|
this.isRunning = false;
|
|
295
|
+
if (this._timer) {
|
|
296
|
+
clearTimeout(this._timer);
|
|
297
|
+
this._timer = null;
|
|
298
|
+
}
|
|
287
299
|
if (this.scheduler) {
|
|
288
300
|
this.scheduler.stop();
|
|
289
301
|
}
|
|
@@ -578,13 +590,18 @@ class QueueManager extends EventEmitter {
|
|
|
578
590
|
this.emit('job:progress', j, percent, msg);
|
|
579
591
|
};
|
|
580
592
|
|
|
581
|
-
this._executeJob(job).finally(() => {
|
|
593
|
+
const jobPromise = this._executeJob(job).finally(() => {
|
|
582
594
|
this.runningCount--;
|
|
583
595
|
this.activeJobs.delete(job.id);
|
|
584
|
-
|
|
596
|
+
this._activeJobPromises.delete(jobPromise);
|
|
597
|
+
if (this.runningCount === 0) {
|
|
598
|
+
this.emit('idle');
|
|
599
|
+
}
|
|
600
|
+
if (this.isRunning && !this.isPaused && !this.isDraining) {
|
|
585
601
|
this._scheduleNextTick(0);
|
|
586
602
|
}
|
|
587
603
|
});
|
|
604
|
+
this._activeJobPromises.add(jobPromise);
|
|
588
605
|
}
|
|
589
606
|
|
|
590
607
|
if (this.runningCount < this.concurrency) {
|
|
@@ -622,29 +639,40 @@ class QueueManager extends EventEmitter {
|
|
|
622
639
|
}
|
|
623
640
|
});
|
|
624
641
|
|
|
642
|
+
const handlerPromise = Promise.resolve().then(() => handler(job, { queue: this }));
|
|
643
|
+
if (typeof handlerPromise.catch === 'function') {
|
|
644
|
+
handlerPromise.catch(() => {});
|
|
645
|
+
}
|
|
646
|
+
|
|
625
647
|
try {
|
|
626
648
|
const result = await Promise.race([
|
|
627
|
-
|
|
649
|
+
handlerPromise,
|
|
628
650
|
timeoutPromise,
|
|
629
651
|
]);
|
|
630
|
-
if (timeoutTimer) {
|
|
631
|
-
clearTimeout(timeoutTimer);
|
|
632
|
-
}
|
|
633
652
|
|
|
634
|
-
|
|
635
|
-
|
|
653
|
+
try {
|
|
654
|
+
const completedJob = await this.adapter.complete(job.id, result);
|
|
655
|
+
this.emit('job:completed', completedJob || job, result);
|
|
656
|
+
} catch (adapterErr) {
|
|
657
|
+
this.emit('error', adapterErr);
|
|
658
|
+
}
|
|
636
659
|
} catch (err) {
|
|
660
|
+
try {
|
|
661
|
+
if (job.attempts < job.maxAttempts) {
|
|
662
|
+
const delayMs = job.getNextRetryDelay();
|
|
663
|
+
const retryingJob = await this.adapter.retry(job.id, delayMs, err);
|
|
664
|
+
this.emit('job:retrying', retryingJob || job, err, delayMs);
|
|
665
|
+
} else {
|
|
666
|
+
const failedJob = await this.adapter.fail(job.id, err);
|
|
667
|
+
this.emit('job:failed', failedJob || job, err);
|
|
668
|
+
}
|
|
669
|
+
} catch (adapterErr) {
|
|
670
|
+
this.emit('error', adapterErr);
|
|
671
|
+
}
|
|
672
|
+
} finally {
|
|
637
673
|
if (timeoutTimer) {
|
|
638
674
|
clearTimeout(timeoutTimer);
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
if (job.attempts < job.maxAttempts) {
|
|
642
|
-
const delayMs = job.getNextRetryDelay();
|
|
643
|
-
const retryingJob = await this.adapter.retry(job.id, delayMs, err);
|
|
644
|
-
this.emit('job:retrying', retryingJob || job, err, delayMs);
|
|
645
|
-
} else {
|
|
646
|
-
const failedJob = await this.adapter.fail(job.id, err);
|
|
647
|
-
this.emit('job:failed', failedJob || job, err);
|
|
675
|
+
timeoutTimer = null;
|
|
648
676
|
}
|
|
649
677
|
}
|
|
650
678
|
}
|
|
@@ -37,18 +37,31 @@ class MemoryRateLimitStore {
|
|
|
37
37
|
const threshold = now - windowMs;
|
|
38
38
|
|
|
39
39
|
let timestamps = this.hits.get(key);
|
|
40
|
-
if (!timestamps) {
|
|
41
|
-
|
|
42
|
-
|
|
40
|
+
if (!timestamps || timestamps.length === 0) {
|
|
41
|
+
this.hits.set(key, [now]);
|
|
42
|
+
return {
|
|
43
|
+
totalHits: 1,
|
|
44
|
+
resetTime: new Date(now + windowMs),
|
|
45
|
+
};
|
|
43
46
|
}
|
|
44
47
|
|
|
45
|
-
// Filter out expired timestamps
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
48
|
+
// Filter out expired timestamps only if the oldest timestamp is expired
|
|
49
|
+
if (timestamps[0] <= threshold) {
|
|
50
|
+
let validIndex = 0;
|
|
51
|
+
const len = timestamps.length;
|
|
52
|
+
while (validIndex < len && timestamps[validIndex] <= threshold) {
|
|
53
|
+
validIndex++;
|
|
54
|
+
}
|
|
55
|
+
if (validIndex >= len) {
|
|
56
|
+
timestamps = [now];
|
|
57
|
+
this.hits.set(key, timestamps);
|
|
58
|
+
return {
|
|
59
|
+
totalHits: 1,
|
|
60
|
+
resetTime: new Date(now + windowMs),
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
timestamps = timestamps.slice(validIndex);
|
|
64
|
+
this.hits.set(key, timestamps);
|
|
52
65
|
}
|
|
53
66
|
|
|
54
67
|
timestamps.push(now);
|
|
@@ -83,6 +83,7 @@ class CircuitBreaker extends EventEmitter {
|
|
|
83
83
|
|
|
84
84
|
/** @type {Array<{ time: number, success: boolean }>} Rolling window samples */
|
|
85
85
|
this._samples = [];
|
|
86
|
+
this._failureCount = 0;
|
|
86
87
|
|
|
87
88
|
this.metrics = {
|
|
88
89
|
totalCalls: 0,
|
|
@@ -163,6 +164,7 @@ class CircuitBreaker extends EventEmitter {
|
|
|
163
164
|
this.lastFailureTime = null;
|
|
164
165
|
this.lastSuccessTime = null;
|
|
165
166
|
this._samples = [];
|
|
167
|
+
this._failureCount = 0;
|
|
166
168
|
|
|
167
169
|
this.metrics.totalCalls = 0;
|
|
168
170
|
this.metrics.successfulCalls = 0;
|
|
@@ -179,9 +181,25 @@ class CircuitBreaker extends EventEmitter {
|
|
|
179
181
|
* @private
|
|
180
182
|
*/
|
|
181
183
|
_pruneSamples() {
|
|
184
|
+
if (this._samples.length === 0) return;
|
|
182
185
|
const cutoff = Date.now() - this.rollingWindowMs;
|
|
183
|
-
|
|
184
|
-
|
|
186
|
+
if (this._samples[0].time >= cutoff) return;
|
|
187
|
+
|
|
188
|
+
let validIndex = 0;
|
|
189
|
+
const len = this._samples.length;
|
|
190
|
+
while (validIndex < len && this._samples[validIndex].time < cutoff) {
|
|
191
|
+
if (!this._samples[validIndex].success) {
|
|
192
|
+
this._failureCount--;
|
|
193
|
+
}
|
|
194
|
+
validIndex++;
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
if (validIndex >= len) {
|
|
198
|
+
this._samples = [];
|
|
199
|
+
this._failureCount = 0;
|
|
200
|
+
} else {
|
|
201
|
+
this._samples = this._samples.slice(validIndex);
|
|
202
|
+
if (this._failureCount < 0) this._failureCount = 0;
|
|
185
203
|
}
|
|
186
204
|
}
|
|
187
205
|
|
|
@@ -191,6 +209,9 @@ class CircuitBreaker extends EventEmitter {
|
|
|
191
209
|
*/
|
|
192
210
|
_recordSample(success) {
|
|
193
211
|
this._samples.push({ time: Date.now(), success });
|
|
212
|
+
if (!success) {
|
|
213
|
+
this._failureCount++;
|
|
214
|
+
}
|
|
194
215
|
this._pruneSamples();
|
|
195
216
|
}
|
|
196
217
|
|
|
@@ -200,13 +221,7 @@ class CircuitBreaker extends EventEmitter {
|
|
|
200
221
|
getFailureRate() {
|
|
201
222
|
this._pruneSamples();
|
|
202
223
|
if (this._samples.length === 0) return 0;
|
|
203
|
-
|
|
204
|
-
let failures = 0;
|
|
205
|
-
for (let i = 0; i < this._samples.length; i++) {
|
|
206
|
-
if (!this._samples[i].success) failures++;
|
|
207
|
-
}
|
|
208
|
-
|
|
209
|
-
return failures / this._samples.length;
|
|
224
|
+
return this._failureCount / this._samples.length;
|
|
210
225
|
}
|
|
211
226
|
|
|
212
227
|
/**
|
|
@@ -308,8 +323,12 @@ class CircuitBreaker extends EventEmitter {
|
|
|
308
323
|
if (typeof timerId?.unref === 'function') timerId.unref();
|
|
309
324
|
});
|
|
310
325
|
|
|
326
|
+
const targetPromise = Promise.resolve().then(() => fn(...args));
|
|
327
|
+
// Attach catch handler to prevent unhandled rejection if fn rejects after timeout
|
|
328
|
+
targetPromise.catch(() => {});
|
|
329
|
+
|
|
311
330
|
execPromise = Promise.race([
|
|
312
|
-
|
|
331
|
+
targetPromise,
|
|
313
332
|
timeoutPromise,
|
|
314
333
|
]);
|
|
315
334
|
} else {
|
|
@@ -317,13 +336,9 @@ class CircuitBreaker extends EventEmitter {
|
|
|
317
336
|
}
|
|
318
337
|
|
|
319
338
|
const result = await execPromise;
|
|
320
|
-
if (timerId) clearTimeout(timerId);
|
|
321
|
-
|
|
322
339
|
this._onSuccess();
|
|
323
340
|
return result;
|
|
324
341
|
} catch (err) {
|
|
325
|
-
if (timerId) clearTimeout(timerId);
|
|
326
|
-
|
|
327
342
|
const isCountedFailure = this.isFailure(err);
|
|
328
343
|
if (isCountedFailure) {
|
|
329
344
|
this._onFailure(err);
|
|
@@ -337,6 +352,11 @@ class CircuitBreaker extends EventEmitter {
|
|
|
337
352
|
}
|
|
338
353
|
|
|
339
354
|
throw err;
|
|
355
|
+
} finally {
|
|
356
|
+
if (timerId) {
|
|
357
|
+
clearTimeout(timerId);
|
|
358
|
+
timerId = null;
|
|
359
|
+
}
|
|
340
360
|
}
|
|
341
361
|
}
|
|
342
362
|
|
package/core/schema-cache.js
CHANGED
|
@@ -1,66 +1,4 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
* Caches compiled Zod schemas per file path using memory-bounded LRU eviction
|
|
6
|
-
* @module core/schema-cache
|
|
7
|
-
*/
|
|
8
|
-
|
|
9
|
-
const { createLruCache } = require('./cache');
|
|
10
|
-
|
|
11
|
-
// 2,000 schemas capacity protects against OOM in dynamic routing/JIT compilation
|
|
12
|
-
const cache = createLruCache({
|
|
13
|
-
maxEntries: 2000,
|
|
14
|
-
});
|
|
15
|
-
|
|
16
|
-
/**
|
|
17
|
-
* Get cached schema for a file path
|
|
18
|
-
* @param {string} filePath - Absolute file path
|
|
19
|
-
* @returns {Object|undefined} Compiled schema or undefined
|
|
20
|
-
*/
|
|
21
|
-
function get(filePath) {
|
|
22
|
-
return cache.get(filePath);
|
|
23
|
-
}
|
|
24
|
-
|
|
25
|
-
/**
|
|
26
|
-
* Set compiled schema for a file path
|
|
27
|
-
* @param {string} filePath - Absolute file path
|
|
28
|
-
* @param {Object} schema - Compiled schema object
|
|
29
|
-
*/
|
|
30
|
-
function set(filePath, schema) {
|
|
31
|
-
cache.set(filePath, schema);
|
|
32
|
-
}
|
|
33
|
-
|
|
34
|
-
/**
|
|
35
|
-
* Check if schema exists in cache
|
|
36
|
-
* @param {string} filePath - Absolute file path
|
|
37
|
-
* @returns {boolean}
|
|
38
|
-
*/
|
|
39
|
-
function has(filePath) {
|
|
40
|
-
return cache.has(filePath);
|
|
41
|
-
}
|
|
42
|
-
|
|
43
|
-
/**
|
|
44
|
-
* Clear all cached schemas
|
|
45
|
-
* Useful for development hot-reload
|
|
46
|
-
*/
|
|
47
|
-
function clear() {
|
|
48
|
-
cache.clear();
|
|
49
|
-
}
|
|
50
|
-
|
|
51
|
-
/**
|
|
52
|
-
* Delete a specific schema from cache
|
|
53
|
-
* @param {string} filePath - Absolute file path
|
|
54
|
-
* @returns {boolean} True if deleted
|
|
55
|
-
*/
|
|
56
|
-
function del(filePath) {
|
|
57
|
-
return cache.delete(filePath);
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
module.exports = {
|
|
61
|
-
get,
|
|
62
|
-
set,
|
|
63
|
-
has,
|
|
64
|
-
clear,
|
|
65
|
-
del,
|
|
66
|
-
};
|
|
3
|
+
// Backward-compatibility shim
|
|
4
|
+
module.exports = require('./validation/cache');
|
|
@@ -0,0 +1,273 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Built-in Auth Services
|
|
3
|
+
* @module src/services/builtins/auth
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
const { z } = require('zod');
|
|
7
|
+
const { hash, verify } = require('../../auth/hash');
|
|
8
|
+
const {
|
|
9
|
+
TOKEN_TYPES,
|
|
10
|
+
createKnexAuthTokensAdapter,
|
|
11
|
+
createAuthToken,
|
|
12
|
+
verifyAuthToken,
|
|
13
|
+
consumeAuthToken,
|
|
14
|
+
} = require('../../auth/tokens');
|
|
15
|
+
const {
|
|
16
|
+
ValidationError,
|
|
17
|
+
UnauthorizedError,
|
|
18
|
+
NotFoundError,
|
|
19
|
+
} = require('../../errors');
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Create built-in auth services map
|
|
23
|
+
* @param {Object} [options]
|
|
24
|
+
* @param {string} [options.userModel='User'] - Name of user model
|
|
25
|
+
* @param {Object} [options.fields] - Field name mappings
|
|
26
|
+
* @returns {Record<string, Object>}
|
|
27
|
+
*/
|
|
28
|
+
function createAuthServices(options = {}) {
|
|
29
|
+
const userModel = options.userModel || 'User';
|
|
30
|
+
const fields = {
|
|
31
|
+
email: 'email',
|
|
32
|
+
password: 'password',
|
|
33
|
+
name: 'name',
|
|
34
|
+
role: 'role',
|
|
35
|
+
active: 'active',
|
|
36
|
+
emailVerifiedAt: 'email_verified_at',
|
|
37
|
+
...(options.fields || {}),
|
|
38
|
+
};
|
|
39
|
+
|
|
40
|
+
return {
|
|
41
|
+
'auth.login': {
|
|
42
|
+
schema: z.object({
|
|
43
|
+
email: z.string().email(),
|
|
44
|
+
password: z.string().min(1),
|
|
45
|
+
remember: z.boolean().optional(),
|
|
46
|
+
}),
|
|
47
|
+
async handler(input, ctx) {
|
|
48
|
+
const { email, password, remember } = input;
|
|
49
|
+
const db = ctx.db;
|
|
50
|
+
if (!db) {
|
|
51
|
+
throw new Error('Database instance is required in context for auth.login');
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
const repo = db.getRepository(userModel);
|
|
55
|
+
const user = await repo.findOne({ [fields.email]: email });
|
|
56
|
+
|
|
57
|
+
if (!user) {
|
|
58
|
+
throw new UnauthorizedError('Invalid email or password');
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
if (user[fields.active] === false || user[fields.active] === 0) {
|
|
62
|
+
throw new UnauthorizedError('Account is deactivated');
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
const isValid = await verify(password, user[fields.password]);
|
|
66
|
+
if (!isValid) {
|
|
67
|
+
throw new UnauthorizedError('Invalid email or password');
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
// Exclude password from returned user object
|
|
71
|
+
const { [fields.password]: _, ...safeUser } = user;
|
|
72
|
+
|
|
73
|
+
// Attach to session if running inside HTTP request context
|
|
74
|
+
if (ctx.req && ctx.req.session) {
|
|
75
|
+
ctx.req.session.user = safeUser;
|
|
76
|
+
if (remember && ctx.req.session.cookie) {
|
|
77
|
+
// Extend session maxAge if remember is checked (30 days)
|
|
78
|
+
ctx.req.session.cookie.maxAge = 30 * 24 * 60 * 60 * 1000;
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
return { user: safeUser };
|
|
83
|
+
},
|
|
84
|
+
},
|
|
85
|
+
|
|
86
|
+
'auth.register': {
|
|
87
|
+
schema: z.object({
|
|
88
|
+
email: z.string().email(),
|
|
89
|
+
password: z.string().min(8, 'Password must be at least 8 characters long'),
|
|
90
|
+
name: z.string().optional(),
|
|
91
|
+
role: z.string().optional(),
|
|
92
|
+
}),
|
|
93
|
+
transaction: true,
|
|
94
|
+
async handler(input, ctx) {
|
|
95
|
+
const { email, password, name, role } = input;
|
|
96
|
+
const db = ctx.db;
|
|
97
|
+
const trx = ctx.trx;
|
|
98
|
+
if (!db) {
|
|
99
|
+
throw new Error('Database instance is required in context for auth.register');
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
const repo = db.getRepository(userModel);
|
|
103
|
+
const existing = await repo.findOne({ [fields.email]: email }, { trx });
|
|
104
|
+
if (existing) {
|
|
105
|
+
throw new ValidationError('Email is already registered', [
|
|
106
|
+
{ field: 'email', message: 'Email is already registered' },
|
|
107
|
+
]);
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
const hashedPassword = await hash(password);
|
|
111
|
+
const userData = {
|
|
112
|
+
[fields.email]: email,
|
|
113
|
+
[fields.password]: hashedPassword,
|
|
114
|
+
};
|
|
115
|
+
|
|
116
|
+
if (name !== undefined) userData[fields.name] = name;
|
|
117
|
+
if (role !== undefined) userData[fields.role] = role;
|
|
118
|
+
|
|
119
|
+
const user = await repo.create(userData, { trx });
|
|
120
|
+
const { [fields.password]: _, ...safeUser } = user;
|
|
121
|
+
|
|
122
|
+
return { user: safeUser };
|
|
123
|
+
},
|
|
124
|
+
},
|
|
125
|
+
|
|
126
|
+
'auth.request-password-reset': {
|
|
127
|
+
schema: z.object({
|
|
128
|
+
email: z.string().email(),
|
|
129
|
+
ttlMs: z.number().positive().default(60 * 60 * 1000), // Default 1 hour
|
|
130
|
+
}),
|
|
131
|
+
async handler(input, ctx) {
|
|
132
|
+
const { email, ttlMs } = input;
|
|
133
|
+
const db = ctx.db;
|
|
134
|
+
if (!db) {
|
|
135
|
+
throw new Error('Database instance is required in context for auth.request-password-reset');
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
const repo = db.getRepository(userModel);
|
|
139
|
+
const user = await repo.findOne({ [fields.email]: email });
|
|
140
|
+
|
|
141
|
+
// Safe timing-attack resistant behavior: do not leak if account exists
|
|
142
|
+
if (!user) {
|
|
143
|
+
return { sent: true, userId: null, rawToken: null };
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
const adapter = createKnexAuthTokensAdapter(db.knex || db);
|
|
147
|
+
const { rawToken, expiresAt } = await createAuthToken(
|
|
148
|
+
adapter,
|
|
149
|
+
TOKEN_TYPES.PASSWORD_RESET,
|
|
150
|
+
user.id,
|
|
151
|
+
ttlMs
|
|
152
|
+
);
|
|
153
|
+
|
|
154
|
+
return {
|
|
155
|
+
sent: true,
|
|
156
|
+
userId: user.id,
|
|
157
|
+
rawToken,
|
|
158
|
+
expiresAt,
|
|
159
|
+
};
|
|
160
|
+
},
|
|
161
|
+
},
|
|
162
|
+
|
|
163
|
+
'auth.reset-password': {
|
|
164
|
+
schema: z.object({
|
|
165
|
+
token: z.string().min(1, 'Reset token is required'),
|
|
166
|
+
password: z.string().min(8, 'Password must be at least 8 characters long'),
|
|
167
|
+
}),
|
|
168
|
+
transaction: true,
|
|
169
|
+
async handler(input, ctx) {
|
|
170
|
+
const { token, password } = input;
|
|
171
|
+
const db = ctx.db;
|
|
172
|
+
const trx = ctx.trx;
|
|
173
|
+
if (!db) {
|
|
174
|
+
throw new Error('Database instance is required in context for auth.reset-password');
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
const adapter = createKnexAuthTokensAdapter(trx || db.knex || db);
|
|
178
|
+
const verified = await verifyAuthToken(adapter, TOKEN_TYPES.PASSWORD_RESET, token);
|
|
179
|
+
|
|
180
|
+
if (!verified) {
|
|
181
|
+
throw new ValidationError('Invalid or expired password reset token', [
|
|
182
|
+
{ field: 'token', message: 'Token is invalid or has expired' },
|
|
183
|
+
]);
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
const hashedPassword = await hash(password);
|
|
187
|
+
const repo = db.getRepository(userModel);
|
|
188
|
+
await repo.update(verified.userId, { [fields.password]: hashedPassword }, { trx });
|
|
189
|
+
|
|
190
|
+
await consumeAuthToken(adapter, verified.tokenHash);
|
|
191
|
+
|
|
192
|
+
return { success: true, userId: verified.userId };
|
|
193
|
+
},
|
|
194
|
+
},
|
|
195
|
+
|
|
196
|
+
'auth.change-password': {
|
|
197
|
+
schema: z.object({
|
|
198
|
+
currentPassword: z.string().min(1, 'Current password is required'),
|
|
199
|
+
newPassword: z.string().min(8, 'New password must be at least 8 characters long'),
|
|
200
|
+
}),
|
|
201
|
+
auth: true, // Requires user in context
|
|
202
|
+
transaction: true,
|
|
203
|
+
async handler(input, ctx) {
|
|
204
|
+
const { currentPassword, newPassword } = input;
|
|
205
|
+
const db = ctx.db;
|
|
206
|
+
const trx = ctx.trx;
|
|
207
|
+
const currentUser = ctx.user || (ctx.auth && ctx.auth.user) || (ctx.req && ctx.req.session && ctx.req.session.user);
|
|
208
|
+
|
|
209
|
+
if (!currentUser || !currentUser.id) {
|
|
210
|
+
throw new UnauthorizedError('User authentication required');
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
const repo = db.getRepository(userModel);
|
|
214
|
+
const user = await repo.findById(currentUser.id, { trx });
|
|
215
|
+
|
|
216
|
+
if (!user) {
|
|
217
|
+
throw new NotFoundError('User not found');
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
const isCurrentValid = await verify(currentPassword, user[fields.password]);
|
|
221
|
+
if (!isCurrentValid) {
|
|
222
|
+
throw new ValidationError('Current password does not match', [
|
|
223
|
+
{ field: 'currentPassword', message: 'Current password does not match' },
|
|
224
|
+
]);
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
const hashedNewPassword = await hash(newPassword);
|
|
228
|
+
await repo.update(currentUser.id, { [fields.password]: hashedNewPassword }, { trx });
|
|
229
|
+
|
|
230
|
+
return { success: true };
|
|
231
|
+
},
|
|
232
|
+
},
|
|
233
|
+
|
|
234
|
+
'auth.verify-email': {
|
|
235
|
+
schema: z.object({
|
|
236
|
+
token: z.string().min(1, 'Verification token is required'),
|
|
237
|
+
}),
|
|
238
|
+
transaction: true,
|
|
239
|
+
async handler(input, ctx) {
|
|
240
|
+
const { token } = input;
|
|
241
|
+
const db = ctx.db;
|
|
242
|
+
const trx = ctx.trx;
|
|
243
|
+
if (!db) {
|
|
244
|
+
throw new Error('Database instance is required in context for auth.verify-email');
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
const adapter = createKnexAuthTokensAdapter(trx || db.knex || db);
|
|
248
|
+
const verified = await verifyAuthToken(adapter, TOKEN_TYPES.EMAIL_VERIFY, token);
|
|
249
|
+
|
|
250
|
+
if (!verified) {
|
|
251
|
+
throw new ValidationError('Invalid or expired verification token', [
|
|
252
|
+
{ field: 'token', message: 'Verification token is invalid or has expired' },
|
|
253
|
+
]);
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
const repo = db.getRepository(userModel);
|
|
257
|
+
await repo.update(
|
|
258
|
+
verified.userId,
|
|
259
|
+
{ [fields.emailVerifiedAt]: new Date() },
|
|
260
|
+
{ trx }
|
|
261
|
+
);
|
|
262
|
+
|
|
263
|
+
await consumeAuthToken(adapter, verified.tokenHash);
|
|
264
|
+
|
|
265
|
+
return { success: true, userId: verified.userId };
|
|
266
|
+
},
|
|
267
|
+
},
|
|
268
|
+
};
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
module.exports = {
|
|
272
|
+
createAuthServices,
|
|
273
|
+
};
|