express-file-cluster 0.9.3 → 0.10.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/dist/auth/index.cjs +6 -7
- package/dist/auth/index.cjs.map +1 -1
- package/dist/auth/index.d.cts +7 -2
- package/dist/auth/index.d.ts +7 -2
- package/dist/auth/index.js +5 -6
- package/dist/{chunk-QL6EWT4B.cjs → chunk-4DOHQU6I.cjs} +9 -7
- package/dist/chunk-4DOHQU6I.cjs.map +1 -0
- package/dist/chunk-73XJUT2S.js +366 -0
- package/dist/chunk-73XJUT2S.js.map +1 -0
- package/dist/{chunk-ATL4GYFU.js → chunk-7KC2H76D.js} +50 -8
- package/dist/chunk-7KC2H76D.js.map +1 -0
- package/dist/{chunk-TYR2GZZE.cjs → chunk-7KO4DJRJ.cjs} +19 -14
- package/dist/chunk-7KO4DJRJ.cjs.map +1 -0
- package/dist/{chunk-UBQYQPBU.js → chunk-ATVD2HGC.js} +4 -4
- package/dist/{chunk-R34R7QPD.cjs → chunk-DCJOWFVD.cjs} +3 -3
- package/dist/{chunk-R34R7QPD.cjs.map → chunk-DCJOWFVD.cjs.map} +1 -1
- package/dist/chunk-DUADUR6R.cjs +366 -0
- package/dist/chunk-DUADUR6R.cjs.map +1 -0
- package/dist/{chunk-BBSZLGZW.js → chunk-EGSSZUVO.js} +8 -6
- package/dist/chunk-EGSSZUVO.js.map +1 -0
- package/dist/{chunk-TI24L4XE.cjs → chunk-GBI77W5T.cjs} +6 -2
- package/dist/chunk-GBI77W5T.cjs.map +1 -0
- package/dist/{chunk-RTF7PHS2.cjs → chunk-HBCY7ILD.cjs} +306 -119
- package/dist/chunk-HBCY7ILD.cjs.map +1 -0
- package/dist/{chunk-ANUSWEAP.cjs → chunk-KFVFP2Q7.cjs} +59 -17
- package/dist/chunk-KFVFP2Q7.cjs.map +1 -0
- package/dist/{chunk-RS4MXCPW.js → chunk-NI2BNGGV.js} +2 -2
- package/dist/{chunk-X2US4RAM.cjs → chunk-NKLOE4AK.cjs} +11 -13
- package/dist/chunk-NKLOE4AK.cjs.map +1 -0
- package/dist/{chunk-RRQ2RK5M.js → chunk-PGJQK36V.js} +195 -8
- package/dist/chunk-PGJQK36V.js.map +1 -0
- package/dist/{chunk-QKQZF573.js → chunk-QDEDOHP7.js} +4 -6
- package/dist/chunk-QDEDOHP7.js.map +1 -0
- package/dist/{chunk-UTM4PEVG.js → chunk-R4XO4SVM.js} +10 -5
- package/dist/chunk-R4XO4SVM.js.map +1 -0
- package/dist/chunk-R52CUEGT.js +74 -0
- package/dist/chunk-R52CUEGT.js.map +1 -0
- package/dist/{chunk-HBYSKULC.js → chunk-RAB44UGX.js} +5 -1
- package/dist/chunk-RAB44UGX.js.map +1 -0
- package/dist/{chunk-7YEX4MQV.cjs → chunk-WBLUGOAG.cjs} +42 -6
- package/dist/chunk-WBLUGOAG.cjs.map +1 -0
- package/dist/{chunk-T4OHFU5T.cjs → chunk-YK4ZM3CA.cjs} +15 -15
- package/dist/{chunk-T4OHFU5T.cjs.map → chunk-YK4ZM3CA.cjs.map} +1 -1
- package/dist/cli/db-runner.cjs +2012 -120
- package/dist/cli/db-runner.cjs.map +1 -1
- package/dist/cli/db-runner.js +1989 -97
- package/dist/cli/db-runner.js.map +1 -1
- package/dist/cli/index.cjs +101 -43
- package/dist/cli/index.cjs.map +1 -1
- package/dist/cli/index.js +80 -22
- package/dist/cli/index.js.map +1 -1
- package/dist/docs/api-reference/auth.md +10 -8
- package/dist/docs/api-reference/collection.md +44 -1
- package/dist/docs/api-reference/ignite.md +22 -3
- package/dist/docs/api-reference/types.md +99 -0
- package/dist/docs/cli/add.md +1 -1
- package/dist/docs/cli/db.md +2 -2
- package/dist/docs/contributing/index.md +1 -1
- package/dist/docs/core-concepts/background-tasks.md +6 -3
- package/dist/docs/getting-started/index.md +3 -2
- package/dist/docs/guides/authentication.md +34 -24
- package/dist/docs/guides/caching.md +32 -1
- package/dist/docs/guides/database.md +14 -0
- package/dist/docs/guides/feature-matrix.md +58 -0
- package/dist/docs/guides/migrations.md +23 -2
- package/dist/docs/guides/oauth.md +15 -1
- package/dist/docs/guides/which-api.md +2 -2
- package/dist/docs/index.md +4 -1
- package/dist/docs/skills/SKILL.md +2 -2
- package/dist/docs/skills/api-surface.md +10 -4
- package/dist/docs/skills/auth-internals.md +3 -3
- package/dist/docs/skills/tasks-internals.md +4 -3
- package/dist/docs/skills/what-not-to-invent.md +4 -3
- package/dist/docs/versioning.md +42 -0
- package/dist/index.cjs +144 -51
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +204 -3
- package/dist/index.d.ts +204 -3
- package/dist/index.js +107 -14
- package/dist/index.js.map +1 -1
- package/dist/pgboss-backend-FW42SBSM.js +14 -0
- package/dist/pgboss-backend-RVHUBJTU.cjs +14 -0
- package/dist/{pgboss-backend-TCHI7CHM.cjs.map → pgboss-backend-RVHUBJTU.cjs.map} +1 -1
- package/dist/registry/index.json +34 -3
- package/dist/registry/js-mongo/account-security.json +1 -1
- package/dist/registry/js-mongo/admin-users.json +1 -1
- package/dist/registry/js-mongo/auth.json +1 -1
- package/dist/registry/js-mongo/auth@apple.json +1 -1
- package/dist/registry/js-mongo/auth@google.json +1 -1
- package/dist/registry/js-mongo/email-verification.json +1 -1
- package/dist/registry/js-mongo/forgot-password.json +1 -1
- package/dist/registry/js-mongo/user-profile.json +1 -1
- package/dist/registry/js-mongo-collection/_base.json +1 -0
- package/dist/registry/js-mongo-collection/account-security.json +1 -0
- package/dist/registry/js-mongo-collection/account-settings.json +1 -0
- package/dist/registry/js-mongo-collection/admin-admins.json +1 -0
- package/dist/registry/js-mongo-collection/admin-analytics.json +1 -0
- package/dist/registry/js-mongo-collection/admin-billing.json +1 -0
- package/dist/registry/js-mongo-collection/admin-content.json +1 -0
- package/dist/registry/js-mongo-collection/admin-logs.json +1 -0
- package/dist/registry/js-mongo-collection/admin-support.json +1 -0
- package/dist/registry/js-mongo-collection/admin-system.json +1 -0
- package/dist/registry/js-mongo-collection/admin-users.json +1 -0
- package/dist/registry/js-mongo-collection/admin.json +1 -0
- package/dist/registry/js-mongo-collection/auth.json +1 -0
- package/dist/registry/js-mongo-collection/auth@apple.json +1 -0
- package/dist/registry/js-mongo-collection/auth@google.json +1 -0
- package/dist/registry/js-mongo-collection/billing.json +1 -0
- package/dist/registry/js-mongo-collection/email-client.json +1 -0
- package/dist/registry/js-mongo-collection/email-verification.json +1 -0
- package/dist/registry/js-mongo-collection/files.json +1 -0
- package/dist/registry/js-mongo-collection/forgot-password.json +1 -0
- package/dist/registry/js-mongo-collection/notifications.json +1 -0
- package/dist/registry/js-mongo-collection/support.json +1 -0
- package/dist/registry/js-mongo-collection/user-profile.json +1 -0
- package/dist/registry/js-pg-model/account-security.json +1 -1
- package/dist/registry/js-pg-model/admin-users.json +1 -1
- package/dist/registry/js-pg-model/auth.json +1 -1
- package/dist/registry/js-pg-model/auth@apple.json +1 -1
- package/dist/registry/js-pg-model/auth@google.json +1 -1
- package/dist/registry/js-pg-model/email-verification.json +1 -1
- package/dist/registry/js-pg-model/forgot-password.json +1 -1
- package/dist/registry/js-pg-model/user-profile.json +1 -1
- package/dist/registry/js-pg-table/account-security.json +1 -1
- package/dist/registry/js-pg-table/admin-users.json +1 -1
- package/dist/registry/js-pg-table/auth.json +1 -1
- package/dist/registry/js-pg-table/auth@apple.json +1 -1
- package/dist/registry/js-pg-table/auth@google.json +1 -1
- package/dist/registry/js-pg-table/email-verification.json +1 -1
- package/dist/registry/js-pg-table/forgot-password.json +1 -1
- package/dist/registry/js-pg-table/user-profile.json +1 -1
- package/dist/registry/ts-mongo/account-security.json +1 -1
- package/dist/registry/ts-mongo/admin-users.json +1 -1
- package/dist/registry/ts-mongo/auth.json +1 -1
- package/dist/registry/ts-mongo/auth@apple.json +1 -1
- package/dist/registry/ts-mongo/auth@google.json +1 -1
- package/dist/registry/ts-mongo/email-verification.json +1 -1
- package/dist/registry/ts-mongo/forgot-password.json +1 -1
- package/dist/registry/ts-mongo/user-profile.json +1 -1
- package/dist/registry/ts-mongo-collection/_base.json +1 -0
- package/dist/registry/ts-mongo-collection/account-security.json +1 -0
- package/dist/registry/ts-mongo-collection/account-settings.json +1 -0
- package/dist/registry/ts-mongo-collection/admin-admins.json +1 -0
- package/dist/registry/ts-mongo-collection/admin-analytics.json +1 -0
- package/dist/registry/ts-mongo-collection/admin-billing.json +1 -0
- package/dist/registry/ts-mongo-collection/admin-content.json +1 -0
- package/dist/registry/ts-mongo-collection/admin-logs.json +1 -0
- package/dist/registry/ts-mongo-collection/admin-support.json +1 -0
- package/dist/registry/ts-mongo-collection/admin-system.json +1 -0
- package/dist/registry/ts-mongo-collection/admin-users.json +1 -0
- package/dist/registry/ts-mongo-collection/admin.json +1 -0
- package/dist/registry/ts-mongo-collection/auth.json +1 -0
- package/dist/registry/ts-mongo-collection/auth@apple.json +1 -0
- package/dist/registry/ts-mongo-collection/auth@google.json +1 -0
- package/dist/registry/ts-mongo-collection/billing.json +1 -0
- package/dist/registry/ts-mongo-collection/email-client.json +1 -0
- package/dist/registry/ts-mongo-collection/email-verification.json +1 -0
- package/dist/registry/ts-mongo-collection/files.json +1 -0
- package/dist/registry/ts-mongo-collection/forgot-password.json +1 -0
- package/dist/registry/ts-mongo-collection/notifications.json +1 -0
- package/dist/registry/ts-mongo-collection/support.json +1 -0
- package/dist/registry/ts-mongo-collection/user-profile.json +1 -0
- package/dist/registry/ts-pg-model/account-security.json +1 -1
- package/dist/registry/ts-pg-model/admin-users.json +1 -1
- package/dist/registry/ts-pg-model/auth.json +1 -1
- package/dist/registry/ts-pg-model/auth@apple.json +1 -1
- package/dist/registry/ts-pg-model/auth@google.json +1 -1
- package/dist/registry/ts-pg-model/email-verification.json +1 -1
- package/dist/registry/ts-pg-model/forgot-password.json +1 -1
- package/dist/registry/ts-pg-model/user-profile.json +1 -1
- package/dist/registry/ts-pg-table/account-security.json +1 -1
- package/dist/registry/ts-pg-table/admin-users.json +1 -1
- package/dist/registry/ts-pg-table/auth.json +1 -1
- package/dist/registry/ts-pg-table/auth@apple.json +1 -1
- package/dist/registry/ts-pg-table/auth@google.json +1 -1
- package/dist/registry/ts-pg-table/email-verification.json +1 -1
- package/dist/registry/ts-pg-table/forgot-password.json +1 -1
- package/dist/registry/ts-pg-table/user-profile.json +1 -1
- package/dist/tasks/index.cjs +4 -2
- package/dist/tasks/index.cjs.map +1 -1
- package/dist/tasks/index.d.cts +4 -2
- package/dist/tasks/index.d.ts +4 -2
- package/dist/tasks/index.js +3 -1
- package/dist/thread-runner.cjs +8 -0
- package/dist/thread-runner.cjs.map +1 -0
- package/dist/thread-runner.d.cts +3 -0
- package/dist/thread-runner.d.ts +3 -0
- package/dist/thread-runner.js +8 -0
- package/dist/thread-runner.js.map +1 -0
- package/dist/{types-BY-ObnZH.d.ts → types-Bnxvj3l0.d.cts} +14 -2
- package/dist/{types-BY-ObnZH.d.cts → types-Bnxvj3l0.d.ts} +14 -2
- package/package.json +1 -1
- package/dist/chunk-277BSYVH.js +0 -127
- package/dist/chunk-277BSYVH.js.map +0 -1
- package/dist/chunk-7YEX4MQV.cjs.map +0 -1
- package/dist/chunk-ANUSWEAP.cjs.map +0 -1
- package/dist/chunk-ATL4GYFU.js.map +0 -1
- package/dist/chunk-BBSZLGZW.js.map +0 -1
- package/dist/chunk-HBYSKULC.js.map +0 -1
- package/dist/chunk-HXV543HZ.js +0 -177
- package/dist/chunk-HXV543HZ.js.map +0 -1
- package/dist/chunk-LJNSJFOL.js +0 -38
- package/dist/chunk-LJNSJFOL.js.map +0 -1
- package/dist/chunk-QKQZF573.js.map +0 -1
- package/dist/chunk-QL6EWT4B.cjs.map +0 -1
- package/dist/chunk-RRQ2RK5M.js.map +0 -1
- package/dist/chunk-RTF7PHS2.cjs.map +0 -1
- package/dist/chunk-TI24L4XE.cjs.map +0 -1
- package/dist/chunk-TYR2GZZE.cjs.map +0 -1
- package/dist/chunk-UTM4PEVG.js.map +0 -1
- package/dist/chunk-VQSWSYK6.cjs +0 -177
- package/dist/chunk-VQSWSYK6.cjs.map +0 -1
- package/dist/chunk-X2US4RAM.cjs.map +0 -1
- package/dist/chunk-YL37D6KM.cjs +0 -127
- package/dist/chunk-YL37D6KM.cjs.map +0 -1
- package/dist/pgboss-backend-QKBXVJ6B.js +0 -14
- package/dist/pgboss-backend-TCHI7CHM.cjs +0 -14
- /package/dist/{chunk-UBQYQPBU.js.map → chunk-ATVD2HGC.js.map} +0 -0
- /package/dist/{chunk-RS4MXCPW.js.map → chunk-NI2BNGGV.js.map} +0 -0
- /package/dist/{pgboss-backend-QKBXVJ6B.js.map → pgboss-backend-FW42SBSM.js.map} +0 -0
|
@@ -1,13 +1,11 @@
|
|
|
1
1
|
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } async function _asyncNullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return await rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
|
|
2
2
|
|
|
3
|
-
var
|
|
3
|
+
var _chunkYK4ZM3CAcjs = require('./chunk-YK4ZM3CA.cjs');
|
|
4
4
|
|
|
5
5
|
|
|
6
|
-
var _chunkVQSWSYK6cjs = require('./chunk-VQSWSYK6.cjs');
|
|
7
6
|
|
|
8
7
|
|
|
9
|
-
|
|
10
|
-
var _chunkYL37D6KMcjs = require('./chunk-YL37D6KM.cjs');
|
|
8
|
+
var _chunkDUADUR6Rcjs = require('./chunk-DUADUR6R.cjs');
|
|
11
9
|
|
|
12
10
|
// src/auth/index.ts
|
|
13
11
|
var _crypto = require('crypto');
|
|
@@ -43,6 +41,8 @@ function servePrimaryCache(maxEntries) {
|
|
|
43
41
|
return store.del(req.args[0]);
|
|
44
42
|
case "clear":
|
|
45
43
|
return store.clear(req.args[0]);
|
|
44
|
+
case "incr":
|
|
45
|
+
return store.incr(req.args[0], req.args[1]);
|
|
46
46
|
}
|
|
47
47
|
};
|
|
48
48
|
run().then(
|
|
@@ -79,7 +79,7 @@ async function connectPrimaryCache() {
|
|
|
79
79
|
await call("ping");
|
|
80
80
|
} catch (e) {
|
|
81
81
|
process.off("message", onMessage);
|
|
82
|
-
|
|
82
|
+
_chunkDUADUR6Rcjs.getLogger.call(void 0, ).warn(
|
|
83
83
|
'cache backend "memory": no EFC cluster primary answered \u2014 using a per-worker store (entries and revoked sessions are not shared)'
|
|
84
84
|
);
|
|
85
85
|
return null;
|
|
@@ -91,6 +91,7 @@ async function connectPrimaryCache() {
|
|
|
91
91
|
},
|
|
92
92
|
del: async (keys) => await call("del", keys),
|
|
93
93
|
clear: async (prefix2) => await call("clear", prefix2),
|
|
94
|
+
incr: async (key, ttl) => await call("incr", key, ttl),
|
|
94
95
|
close: async () => {
|
|
95
96
|
process.off("message", onMessage);
|
|
96
97
|
for (const p of pending2.values()) clearTimeout(p.timer);
|
|
@@ -134,6 +135,21 @@ function memoryBackend(maxEntries) {
|
|
|
134
135
|
for (const k of [...store.keys()]) if (k.startsWith(prefix2) && store.delete(k)) n++;
|
|
135
136
|
return n;
|
|
136
137
|
},
|
|
138
|
+
// One event-loop turn, no awaits: atomic within this process. Under clustering this
|
|
139
|
+
// store lives in the primary, so it's atomic across workers too.
|
|
140
|
+
async incr(key, ttl) {
|
|
141
|
+
const hit = live(key);
|
|
142
|
+
const current = hit ? Number(hit.value) : 0;
|
|
143
|
+
if (!Number.isInteger(current)) throw new Error(`cache incr: "${key}" is not an integer`);
|
|
144
|
+
const expires = hit ? hit.expires : ttl ? Date.now() + ttl * 1e3 : 0;
|
|
145
|
+
store.delete(key);
|
|
146
|
+
store.set(key, { value: String(current + 1), expires });
|
|
147
|
+
while (store.size > maxEntries) store.delete(store.keys().next().value);
|
|
148
|
+
return {
|
|
149
|
+
value: current + 1,
|
|
150
|
+
ttlMs: expires === 0 ? null : Math.max(0, expires - Date.now())
|
|
151
|
+
};
|
|
152
|
+
},
|
|
137
153
|
async close() {
|
|
138
154
|
store.clear();
|
|
139
155
|
}
|
|
@@ -145,10 +161,10 @@ async function redisBackend(url, timeout) {
|
|
|
145
161
|
const mod = await Promise.resolve().then(() => _interopRequireWildcard(require("ioredis")));
|
|
146
162
|
Redis = _nullishCoalesce(mod.Redis, () => ( mod.default));
|
|
147
163
|
} catch (err) {
|
|
148
|
-
throw
|
|
164
|
+
throw _chunkDUADUR6Rcjs.notInstalled.call(void 0, err, "ioredis", "npm install ioredis");
|
|
149
165
|
}
|
|
150
166
|
const client = new Redis({
|
|
151
|
-
...
|
|
167
|
+
..._chunkYK4ZM3CAcjs.parseRedisUrl.call(void 0, url),
|
|
152
168
|
// Fail fast instead of queueing commands while disconnected; callers treat
|
|
153
169
|
// a rejected command as a miss.
|
|
154
170
|
enableOfflineQueue: false,
|
|
@@ -159,7 +175,7 @@ async function redisBackend(url, timeout) {
|
|
|
159
175
|
client.on("error", (err) => {
|
|
160
176
|
if (Date.now() - lastWarn > 3e4) {
|
|
161
177
|
lastWarn = Date.now();
|
|
162
|
-
|
|
178
|
+
_chunkDUADUR6Rcjs.getLogger.call(void 0, ).warn(`Cache Redis unavailable: ${err.message} (serving cache misses)`);
|
|
163
179
|
}
|
|
164
180
|
});
|
|
165
181
|
await new Promise((resolve) => {
|
|
@@ -176,6 +192,19 @@ async function redisBackend(url, timeout) {
|
|
|
176
192
|
else await client.set(key, value);
|
|
177
193
|
},
|
|
178
194
|
del: (keys) => keys.length ? client.del(...keys) : Promise.resolve(0),
|
|
195
|
+
// INCR and the first EXPIRE in one script: a crash in between can't leave a counter
|
|
196
|
+
// that never expires.
|
|
197
|
+
async incr(key, ttl) {
|
|
198
|
+
const [value, pttl] = await client.eval(
|
|
199
|
+
`local n = redis.call('INCR', KEYS[1])
|
|
200
|
+
if n == 1 and tonumber(ARGV[1]) > 0 then redis.call('PEXPIRE', KEYS[1], ARGV[1]) end
|
|
201
|
+
return {n, redis.call('PTTL', KEYS[1])}`,
|
|
202
|
+
1,
|
|
203
|
+
key,
|
|
204
|
+
ttl ? Math.max(1, Math.ceil(ttl * 1e3)) : 0
|
|
205
|
+
);
|
|
206
|
+
return { value, ttlMs: pttl < 0 ? null : pttl };
|
|
207
|
+
},
|
|
179
208
|
async clear(prefix2) {
|
|
180
209
|
let n = 0;
|
|
181
210
|
let cursor = "0";
|
|
@@ -229,7 +258,7 @@ async function safely(op, fn, fallback) {
|
|
|
229
258
|
try {
|
|
230
259
|
return await fn(b);
|
|
231
260
|
} catch (err) {
|
|
232
|
-
|
|
261
|
+
_chunkDUADUR6Rcjs.getLogger.call(void 0, ).debug({ err }, `cache ${op} failed`);
|
|
233
262
|
return fallback;
|
|
234
263
|
}
|
|
235
264
|
}
|
|
@@ -267,8 +296,15 @@ var cache = {
|
|
|
267
296
|
},
|
|
268
297
|
async clear(keyPrefix = "") {
|
|
269
298
|
return safely("clear", (b) => b.clear(prefix + keyPrefix), 0);
|
|
299
|
+
},
|
|
300
|
+
async incr(key, options) {
|
|
301
|
+
const r = await safely("incr", (b) => b.incr(prefix + key, _optionalChain([options, 'optionalAccess', _4 => _4.ttl])), void 0);
|
|
302
|
+
return _optionalChain([r, 'optionalAccess', _5 => _5.value]);
|
|
270
303
|
}
|
|
271
304
|
};
|
|
305
|
+
async function rawIncr(key, ttlSeconds) {
|
|
306
|
+
return requireBackend().incr(prefix + key, ttlSeconds);
|
|
307
|
+
}
|
|
272
308
|
async function rawGet(key) {
|
|
273
309
|
return requireBackend().get(prefix + key);
|
|
274
310
|
}
|
|
@@ -306,7 +342,7 @@ async function hashPassword(password) {
|
|
|
306
342
|
async function verifyPassword(password, hash) {
|
|
307
343
|
if (typeof password !== "string" || typeof hash !== "string") return false;
|
|
308
344
|
if (/^\$2[aby]\$/.test(hash)) {
|
|
309
|
-
|
|
345
|
+
_chunkDUADUR6Rcjs.getLogger.call(void 0, ).warn(
|
|
310
346
|
"[EFC] verifyPassword: bcrypt hash found \u2014 not supported since 0.9.2. This account must reset its password (the reset stores a hashPassword() hash)."
|
|
311
347
|
);
|
|
312
348
|
return false;
|
|
@@ -340,14 +376,16 @@ async function sign(payload) {
|
|
|
340
376
|
return new (0, _jose.SignJWT)({ ...payload, efc_iat: Date.now() }).setProtectedHeader({ alg: "HS256" }).setJti(_crypto.randomUUID.call(void 0, )).setIssuedAt().setExpirationTime(expiresIn).sign(new TextEncoder().encode(secret));
|
|
341
377
|
}
|
|
342
378
|
async function issueToken(res, payload) {
|
|
343
|
-
const { cookieDomain } = getConfig();
|
|
379
|
+
const { cookieDomain, strategy } = getConfig();
|
|
344
380
|
const token = await sign(payload);
|
|
381
|
+
if (strategy !== "http-only") return token;
|
|
345
382
|
res.cookie("efc_token", token, {
|
|
346
383
|
httpOnly: true,
|
|
347
384
|
secure: process.env["NODE_ENV"] === "production",
|
|
348
385
|
sameSite: "strict",
|
|
349
386
|
...cookieDomain !== void 0 && { domain: cookieDomain }
|
|
350
387
|
});
|
|
388
|
+
return void 0;
|
|
351
389
|
}
|
|
352
390
|
function revokeToken(res) {
|
|
353
391
|
res.clearCookie("efc_token");
|
|
@@ -357,13 +395,15 @@ async function signToken(payload) {
|
|
|
357
395
|
}
|
|
358
396
|
function tokenFrom(req) {
|
|
359
397
|
if (getConfig().strategy === "http-only") {
|
|
360
|
-
return _optionalChain([req, 'access',
|
|
398
|
+
return _optionalChain([req, 'access', _6 => _6.cookies, 'optionalAccess', _7 => _7["efc_token"]]);
|
|
361
399
|
}
|
|
362
400
|
const auth = req.headers["authorization"];
|
|
363
401
|
return typeof auth === "string" && auth.startsWith("Bearer ") ? auth.slice(7) : void 0;
|
|
364
402
|
}
|
|
365
403
|
async function verify(token) {
|
|
366
|
-
const { payload } = await _jose.jwtVerify.call(void 0, token, new TextEncoder().encode(getConfig().secret)
|
|
404
|
+
const { payload } = await _jose.jwtVerify.call(void 0, token, new TextEncoder().encode(getConfig().secret), {
|
|
405
|
+
algorithms: ["HS256"]
|
|
406
|
+
});
|
|
367
407
|
return payload;
|
|
368
408
|
}
|
|
369
409
|
var userIdOf = (payload) => {
|
|
@@ -432,7 +472,7 @@ async function authenticate(req, res, next, roles) {
|
|
|
432
472
|
const reject = revocationFailureMode() === "reject";
|
|
433
473
|
if (Date.now() - lastRevocationError > 3e4) {
|
|
434
474
|
lastRevocationError = Date.now();
|
|
435
|
-
|
|
475
|
+
_chunkDUADUR6Rcjs.getLogger.call(void 0, ).error(
|
|
436
476
|
{ err },
|
|
437
477
|
`Session revocation check failed \u2014 ${reject ? "rejecting with 503" : "allowing"} authenticated requests`
|
|
438
478
|
);
|
|
@@ -455,7 +495,7 @@ async function authenticate(req, res, next, roles) {
|
|
|
455
495
|
}
|
|
456
496
|
}
|
|
457
497
|
req.user = payload;
|
|
458
|
-
|
|
498
|
+
_chunkDUADUR6Rcjs.setCurrentUser.call(void 0, payload);
|
|
459
499
|
next();
|
|
460
500
|
} catch (e3) {
|
|
461
501
|
res.status(401).json({ error: "Unauthorized" });
|
|
@@ -487,5 +527,7 @@ var requireAuth = ((...args) => {
|
|
|
487
527
|
|
|
488
528
|
|
|
489
529
|
|
|
490
|
-
|
|
491
|
-
|
|
530
|
+
|
|
531
|
+
|
|
532
|
+
exports.servePrimaryCache = servePrimaryCache; exports.configureCache = configureCache; exports.isCacheConfigured = isCacheConfigured; exports.closeCache = closeCache; exports.cache = cache; exports.rawIncr = rawIncr; exports.hashPassword = hashPassword; exports.verifyPassword = verifyPassword; exports.passwordNeedsRehash = passwordNeedsRehash; exports.configureAuth = configureAuth; exports.issueToken = issueToken; exports.revokeToken = revokeToken; exports.signToken = signToken; exports.revokeSession = revokeSession; exports.revokeAllSessions = revokeAllSessions; exports.requireAuth = requireAuth;
|
|
533
|
+
//# sourceMappingURL=chunk-KFVFP2Q7.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["/home/runner/work/express-file-cluster/express-file-cluster/packages/core/dist/chunk-KFVFP2Q7.cjs","../src/auth/index.ts","../src/cache/index.ts","../src/cache/ipc.ts","../src/auth/password.ts"],"names":["pending","prefix","cluster"],"mappings":"AAAA;AACE;AACF,wDAA6B;AAC7B;AACE;AACA;AACA;AACF,wDAA6B;AAC7B;AACA;ACTA,gCAA2B;AAE3B,4BAAoD;ADUpD;AACA;AEbA,oFAAoB;AFepB;AACA;AGhBA;AACA;AAUA,IAAM,IAAA,EAAM,YAAA;AACZ,IAAM,WAAA,EAAa,GAAA;AAiBnB,IAAM,SAAA,EAAW,CAAC,GAAA,EAAA,GAChB,IAAA,IAAQ,KAAA,GAAQ,OAAO,IAAA,IAAQ,SAAA,GAAa,GAAA,CAAgC,GAAG,EAAA,IAAM,IAAA;AAGhF,SAAS,iBAAA,CAAkB,UAAA,EAA0B;AAC1D,EAAA,MAAM,MAAA,EAAQ,aAAA,CAAc,UAAU,CAAA;AACtC,EAAA,iBAAA,CAAQ,EAAA,CAAG,SAAA,EAAW,CAAC,MAAA,EAAgB,GAAA,EAAA,GAAiB;AACtD,IAAA,GAAA,CAAI,CAAC,QAAA,CAAS,GAAG,CAAA,EAAG,MAAA;AACpB,IAAA,MAAM,IAAA,EAAM,GAAA;AACZ,IAAA,MAAM,IAAA,EAAM,MAAA,CAAA,EAAA,GAA8B;AACxC,MAAA,OAAA,CAAQ,GAAA,CAAI,EAAA,EAAI;AAAA,QACd,KAAK,MAAA;AACH,UAAA,OAAO,MAAA;AAAA,QACT,KAAK,K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,EAAA;AACR,EAAA;AACA,EAAA;AAC0B,IAAA;AACtB,EAAA;AACN,IAAA;AACF,EAAA;AACkB,EAAA;AACsD,EAAA;AACX,EAAA;AAC/D;AAMgF;AACvD,EAAA;AACyC,EAAA;AAClE;AAOiB;AACX,EAAA;AACyB,IAAA;AAEf,IAAA;AACoC,MAAA;AAC9C,MAAA;AACF,IAAA;AAEkC,IAAA;AAET,IAAA;AACT,MAAA;AACV,MAAA;AAC+B,QAAA;AACrB,MAAA;AAC+B,QAAA;AACI,QAAA;AACd,UAAA;AACnB,UAAA;AACJ,YAAA;AACwC,YAAA;AAChD,UAAA;AACF,QAAA;AAGY,QAAA;AAC4D,UAAA;AACtE,UAAA;AACF,QAAA;AACF,MAAA;AACa,MAAA;AACmC,QAAA;AAC9C,QAAA;AACF,MAAA;AACF,IAAA;AAEsB,IAAA;AACoC,MAAA;AACD,MAAA;AACV,QAAA;AAC3C,QAAA;AACF,MAAA;AACF,IAAA;AAE+C,IAAA;AACE,IAAA;AAC5C,IAAA;AACC,EAAA;AACwC,IAAA;AAChD,EAAA;AACF;AAYiE;AACX,EAAA;AACpC,IAAA;AAC8C,IAAA;AACnB,MAAA;AACzC,IAAA;AACF,EAAA;AACyB,EAAA;AACW,EAAA;AACtC;ADmRoF;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"/home/runner/work/express-file-cluster/express-file-cluster/packages/core/dist/chunk-KFVFP2Q7.cjs","sourcesContent":[null,"import { randomUUID } from 'node:crypto';\nimport type { NextFunction, Request, RequestHandler, Response } from 'express';\nimport { SignJWT, jwtVerify, type JWTPayload } from 'jose';\nimport type { AuthStrategy } from '../types.js';\nimport { setCurrentUser } from '../context.js';\nimport { isCacheConfigured, rawGet, rawSet, revocationFailureMode } from '../cache/index.js';\nimport { getLogger } from '../logger.js';\n\ninterface AuthConfig {\n secret: string;\n strategy: AuthStrategy;\n expiresIn: string;\n cookieDomain?: string | undefined;\n}\n\nlet _config: AuthConfig | null = null;\n\nexport function configureAuth(config: AuthConfig): void {\n _config = config;\n}\n\nfunction getConfig(): AuthConfig {\n if (!_config) throw new Error('[EFC] Auth not configured — pass jwtSecret to ignite()');\n return _config;\n}\n\n// Every token carries a unique `jti` (so one session can be revoked) and its issue\n// time in milliseconds, `efc_iat` (so \"revoke all sessions issued before now\" doesn't\n// also catch a token minted in the same second as the revocation).\nasync function sign(payload: Record<string, unknown>): Promise<string> {\n const { secret, expiresIn } = getConfig();\n return new SignJWT({ ...payload, efc_iat: Date.now() })\n .setProtectedHeader({ alg: 'HS256' })\n .setJti(randomUUID())\n .setIssuedAt()\n .setExpirationTime(expiresIn)\n .sign(new TextEncoder().encode(secret));\n}\n\n/**\n * Signs a JWT for `payload` and hands it to the client the configured way: `'http-only'`\n * sets the `efc_token` cookie and resolves `undefined`; `'bearer'` resolves the token for\n * the response body (no cookie). `res.json({ ...(token ? { token } : {}) })` works for both.\n */\nexport async function issueToken(\n res: Response,\n payload: Record<string, unknown>,\n): Promise<string | undefined> {\n const { cookieDomain, strategy } = getConfig();\n const token = await sign(payload);\n if (strategy !== 'http-only') return token;\n\n res.cookie('efc_token', token, {\n httpOnly: true,\n secure: process.env['NODE_ENV'] === 'production',\n sameSite: 'strict',\n ...(cookieDomain !== undefined && { domain: cookieDomain }),\n });\n return undefined;\n}\n\nexport function revokeToken(res: Response): void {\n res.clearCookie('efc_token');\n}\n\nexport async function signToken(payload: Record<string, unknown>): Promise<string> {\n return sign(payload);\n}\n\nfunction tokenFrom(req: Request): string | undefined {\n if (getConfig().strategy === 'http-only') {\n return (req as typeof req & { cookies?: Record<string, string> }).cookies?.['efc_token'];\n }\n const auth = req.headers['authorization'];\n return typeof auth === 'string' && auth.startsWith('Bearer ') ? auth.slice(7) : undefined;\n}\n\nasync function verify(token: string): Promise<JWTPayload> {\n // Only the algorithm EFC signs with — never whatever the token's header claims.\n const { payload } = await jwtVerify(token, new TextEncoder().encode(getConfig().secret), {\n algorithms: ['HS256'],\n });\n return payload;\n}\n\nconst userIdOf = (payload: JWTPayload): string | undefined => {\n const id = payload.sub ?? (payload as Record<string, unknown>)['id'];\n return id === undefined || id === null ? undefined : String(id);\n};\n\n// ── Session revocation (needs `cache` in ignite()) ───────────────────────────\n// Stateless JWTs can't be \"un-issued\", so revocation is a denylist in the cache:\n// one key per revoked token (`sess:jti:<jti>`, kept until that token would expire)\n// and one per user for \"everything issued before T\" (`sess:user:<id>`).\n\n/** Lifetime of a token signed now, in seconds — `jwtExpiresIn` like '15m', '7d'. */\nfunction tokenLifetimeSeconds(): number {\n const m =\n /^(\\d+(?:\\.\\d+)?)\\s*(s|sec|secs|seconds?|m|min|mins|minutes?|h|hr|hrs|hours?|d|days?|w|weeks?|y|yrs?|years?)?$/i.exec(\n getConfig().expiresIn.trim(),\n );\n if (!m) return 30 * 86_400;\n const n = Number(m[1]);\n const unit = (m[2] ?? 's')[0]!.toLowerCase();\n const factor = { s: 1, m: 60, h: 3600, d: 86_400, w: 604_800, y: 31_557_600 }[unit] ?? 1;\n return Math.ceil(n * factor);\n}\n\nlet lastRevocationError = 0;\n\nasync function isRevoked(payload: JWTPayload): Promise<boolean> {\n if (payload.jti && (await rawGet(`sess:jti:${payload.jti}`)) !== null) return true;\n const userId = userIdOf(payload);\n if (userId === undefined) return false;\n const cutoff = await rawGet(`sess:user:${userId}`);\n if (cutoff === null) return false;\n const issuedMs =\n typeof (payload as Record<string, unknown>)['efc_iat'] === 'number'\n ? ((payload as Record<string, unknown>)['efc_iat'] as number)\n : (payload.iat ?? 0) * 1000; // tokens minted before efc_iat existed\n return issuedMs < Number(cutoff);\n}\n\nfunction requireRevocationStore(): void {\n if (!isCacheConfigured()) {\n throw new Error(\n '[EFC] Session revocation needs a cache — pass cache: { backend: \"redis\" } to ignite()',\n );\n }\n}\n\n/**\n * Revokes the token the current request was authenticated with: `requireAuth` rejects\n * it from now until it would have expired anyway. Pass `res` to also clear the cookie\n * (http-only strategy). Throws if the cache is unreachable, so a failed logout is visible.\n */\nexport async function revokeSession(req: Request, res?: Response): Promise<void> {\n requireRevocationStore();\n const token = tokenFrom(req);\n if (res && getConfig().strategy === 'http-only') res.clearCookie('efc_token');\n if (!token) return;\n let payload: JWTPayload;\n try {\n payload = await verify(token);\n } catch {\n return; // already invalid or expired — nothing to revoke\n }\n if (!payload.jti) return;\n const ttl = payload.exp ? payload.exp - Math.floor(Date.now() / 1000) : tokenLifetimeSeconds();\n if (ttl > 0) await rawSet(`sess:jti:${payload.jti}`, '1', ttl);\n}\n\n/**\n * Revokes every token issued to `userId` (the JWT's `sub` or `id` claim) before now —\n * \"log out of all devices\", or after a password change. Tokens issued afterwards work.\n */\nexport async function revokeAllSessions(userId: string | number): Promise<void> {\n requireRevocationStore();\n await rawSet(`sess:user:${String(userId)}`, String(Date.now()), tokenLifetimeSeconds());\n}\n\nasync function authenticate(\n req: Request,\n res: Response,\n next: NextFunction,\n roles: string[],\n): Promise<void> {\n try {\n const token = tokenFrom(req);\n\n if (!token) {\n res.status(401).json({ error: 'Unauthorized' });\n return;\n }\n\n const payload = await verify(token);\n\n if (isCacheConfigured()) {\n let revoked = false;\n try {\n revoked = await isRevoked(payload);\n } catch (err) {\n const reject = revocationFailureMode() === 'reject';\n if (Date.now() - lastRevocationError > 30_000) {\n lastRevocationError = Date.now();\n getLogger().error(\n { err },\n `Session revocation check failed — ${reject ? 'rejecting with 503' : 'allowing'} authenticated requests`,\n );\n }\n // 503, not 401: the session isn't invalid, the check is unavailable — clients\n // shouldn't discard the token and force a re-login over a cache blip.\n if (reject) {\n res.status(503).json({ error: 'Service Unavailable', statusCode: 503 });\n return;\n }\n }\n if (revoked) {\n res.status(401).json({ error: 'Unauthorized' });\n return;\n }\n }\n\n if (roles.length > 0) {\n const role = (payload as Record<string, unknown>)['role'];\n if (typeof role !== 'string' || !roles.includes(role)) {\n res.status(403).json({ error: 'Forbidden' });\n return;\n }\n }\n\n (req as typeof req & { user: unknown }).user = payload;\n setCurrentUser(payload as Record<string, unknown>);\n next();\n } catch {\n res.status(401).json({ error: 'Unauthorized' });\n }\n}\n\n/**\n * Used bare (`middlewares = [requireAuth]`) it just verifies the JWT.\n * Called with role names (`middlewares = [requireAuth('admin')]`) it\n * returns a middleware that also enforces `payload.role` is one of them.\n */\nexport interface RequireAuth {\n (req: Request, res: Response, next: NextFunction): void;\n (...roles: string[]): RequestHandler;\n}\n\nexport const requireAuth: RequireAuth = ((...args: unknown[]) => {\n if (args.length > 0 && typeof args[0] === 'string') {\n const roles = args as string[];\n return (req: Request, res: Response, next: NextFunction) => {\n void authenticate(req, res, next, roles);\n };\n }\n const [req, res, next] = args as [Request, Response, NextFunction];\n void authenticate(req, res, next, []);\n}) as RequireAuth;\n\n// Reads the JWT payload requireAuth attached for the in-flight request, from\n// anywhere — not just where `req` is in scope. Returns undefined outside a\n// request, or on a request that never ran through requireAuth.\nexport { getCurrentUser } from '../context.js';\nexport { hashPassword, verifyPassword, passwordNeedsRehash } from './password.js';\n","import cluster from 'node:cluster';\nimport type { Redis as RedisClient, RedisOptions } from 'ioredis';\nimport type { CacheConfig } from '../types.js';\nimport { getLogger } from '../logger.js';\nimport { notInstalled } from '../db/postgres.js';\nimport { parseRedisUrl } from '../tasks/bullmq-backend.js';\nimport { connectPrimaryCache } from './ipc.js';\n\n// A small key/value cache with two backends:\n// - redis: shared by every worker and instance — what production wants.\n// - memory: in-process; under clustering the primary holds it and workers reach it\n// over IPC, so it's shared by all workers on the machine (not across machines).\n// Values are JSON-serialised. A Redis outage degrades to cache misses instead of\n// failing the request — a cache must never be the thing that takes the API down.\n\nexport interface Backend {\n get(key: string): Promise<string | null>;\n set(key: string, value: string, ttlSeconds: number | undefined): Promise<void>;\n del(keys: string[]): Promise<number>;\n clear(prefix: string): Promise<number>;\n /**\n * Atomically adds 1 to an integer value (a missing key counts as 0). The TTL is set only\n * when the key is created, so it describes a fixed window. `ttlMs` is what's left of it\n * (null: no expiry).\n */\n incr(\n key: string,\n ttlSeconds: number | undefined,\n ): Promise<{ value: number; ttlMs: number | null }>;\n close(): Promise<void>;\n}\n\nexport function memoryBackend(maxEntries: number): Backend {\n const store = new Map<string, { value: string; expires: number }>();\n const live = (key: string) => {\n const hit = store.get(key);\n if (!hit) return undefined;\n if (hit.expires !== 0 && hit.expires <= Date.now()) {\n store.delete(key);\n return undefined;\n }\n return hit;\n };\n return {\n async get(key) {\n const hit = live(key);\n if (!hit) return null;\n // Re-insert so Map order tracks recency (LRU eviction drops the oldest).\n store.delete(key);\n store.set(key, hit);\n return hit.value;\n },\n async set(key, value, ttl) {\n store.delete(key);\n store.set(key, { value, expires: ttl ? Date.now() + ttl * 1000 : 0 });\n while (store.size > maxEntries) store.delete(store.keys().next().value!);\n },\n async del(keys) {\n let n = 0;\n for (const k of keys) if (live(k) && store.delete(k)) n++;\n return n;\n },\n async clear(prefix) {\n let n = 0;\n for (const k of [...store.keys()]) if (k.startsWith(prefix) && store.delete(k)) n++;\n return n;\n },\n // One event-loop turn, no awaits: atomic within this process. Under clustering this\n // store lives in the primary, so it's atomic across workers too.\n async incr(key, ttl) {\n const hit = live(key);\n const current = hit ? Number(hit.value) : 0;\n if (!Number.isInteger(current)) throw new Error(`cache incr: \"${key}\" is not an integer`);\n const expires = hit ? hit.expires : ttl ? Date.now() + ttl * 1000 : 0;\n store.delete(key);\n store.set(key, { value: String(current + 1), expires });\n while (store.size > maxEntries) store.delete(store.keys().next().value!);\n return {\n value: current + 1,\n ttlMs: expires === 0 ? null : Math.max(0, expires - Date.now()),\n };\n },\n async close() {\n store.clear();\n },\n };\n}\n\nasync function redisBackend(url: string, timeout: number): Promise<Backend> {\n let Redis: new (opts: RedisOptions) => RedisClient;\n try {\n const mod = (await import('ioredis')) as unknown as {\n Redis?: typeof Redis;\n default?: typeof Redis;\n };\n Redis = (mod.Redis ?? mod.default)!;\n } catch (err) {\n throw notInstalled(err, 'ioredis', 'npm install ioredis');\n }\n const client = new Redis({\n ...parseRedisUrl(url),\n // Fail fast instead of queueing commands while disconnected; callers treat\n // a rejected command as a miss.\n enableOfflineQueue: false,\n maxRetriesPerRequest: 1,\n commandTimeout: timeout,\n });\n let lastWarn = 0;\n client.on('error', (err: Error) => {\n // Reconnect attempts emit an error each time — log at most every 30 s.\n if (Date.now() - lastWarn > 30_000) {\n lastWarn = Date.now();\n getLogger().warn(`Cache Redis unavailable: ${err.message} (serving cache misses)`);\n }\n });\n\n // Wait for the first connection so writes made right after boot aren't dropped (the\n // offline queue is off), but never longer than a few timeouts: an unreachable Redis\n // must not block startup — the cache just serves misses until it comes back.\n await new Promise<void>((resolve) => {\n const timer = setTimeout(resolve, Math.max(2000, timeout * 2));\n client.once('ready', () => {\n clearTimeout(timer);\n resolve();\n });\n });\n return {\n get: (key) => client.get(key),\n async set(key, value, ttl) {\n if (ttl) await client.set(key, value, 'EX', Math.max(1, Math.ceil(ttl)));\n else await client.set(key, value);\n },\n del: (keys) => (keys.length ? client.del(...keys) : Promise.resolve(0)),\n // INCR and the first EXPIRE in one script: a crash in between can't leave a counter\n // that never expires.\n async incr(key, ttl) {\n const [value, pttl] = (await client.eval(\n `local n = redis.call('INCR', KEYS[1])\n if n == 1 and tonumber(ARGV[1]) > 0 then redis.call('PEXPIRE', KEYS[1], ARGV[1]) end\n return {n, redis.call('PTTL', KEYS[1])}`,\n 1,\n key,\n ttl ? Math.max(1, Math.ceil(ttl * 1000)) : 0,\n )) as [number, number];\n return { value, ttlMs: pttl < 0 ? null : pttl };\n },\n async clear(prefix) {\n let n = 0;\n let cursor = '0';\n const match = prefix.replace(/[*?[\\]\\\\]/g, '\\\\$&') + '*';\n do {\n const [next, keys] = await client.scan(cursor, 'MATCH', match, 'COUNT', 500);\n cursor = next;\n if (keys.length) n += await client.unlink(...keys);\n } while (cursor !== '0');\n return n;\n },\n async close() {\n await client.quit().catch(() => client.disconnect());\n },\n };\n}\n\nlet backend: Backend | null = null;\nlet prefix = 'efc:';\nlet revocationFailure: 'reject' | 'allow' = 'reject';\n\n/** How requireAuth should treat a failed revocation check — see CacheConfig. */\nexport function revocationFailureMode(): 'reject' | 'allow' {\n return revocationFailure;\n}\nconst pending = new Map<string, Promise<unknown>>();\n\nexport async function configureCache(config: CacheConfig): Promise<void> {\n await closeCache();\n prefix = config.prefix ?? 'efc:';\n revocationFailure = config.onRevocationCheckError ?? 'reject';\n if (config.backend === 'redis') {\n backend = await redisBackend(config.url ?? 'redis://localhost:6379', config.timeout ?? 1000);\n } else if (cluster.isWorker) {\n // Cluster workers share the primary's store over IPC (see cache/ipc.ts).\n backend = (await connectPrimaryCache()) ?? memoryBackend(config.maxEntries ?? 10_000);\n } else {\n backend = memoryBackend(config.maxEntries ?? 10_000);\n }\n}\n\nexport function isCacheConfigured(): boolean {\n return backend !== null;\n}\n\nexport async function closeCache(): Promise<void> {\n const b = backend;\n backend = null;\n pending.clear();\n await b?.close();\n}\n\nfunction requireBackend(): Backend {\n if (!backend) throw new Error('[EFC] Cache not configured — pass cache: { backend } to ignite()');\n return backend;\n}\n\n// Backend errors (Redis down/slow) degrade to \"no cache\" rather than failing the caller.\nasync function safely<T>(op: string, fn: (b: Backend) => Promise<T>, fallback: T): Promise<T> {\n const b = requireBackend();\n try {\n return await fn(b);\n } catch (err) {\n getLogger().debug({ err }, `cache ${op} failed`);\n return fallback;\n }\n}\n\nexport interface CacheSetOptions {\n /** Seconds until the entry expires. Omit for no expiry. */\n ttl?: number;\n}\n\nexport interface Cache {\n /** The cached value, or `undefined` on a miss (or when the backend is unreachable). */\n get<T = unknown>(key: string): Promise<T | undefined>;\n set(key: string, value: unknown, options?: CacheSetOptions): Promise<void>;\n has(key: string): Promise<boolean>;\n /** Deletes keys; returns how many existed. */\n del(...keys: string[]): Promise<number>;\n /**\n * Returns the cached value, or runs `fn`, caches its result and returns it.\n * Concurrent calls for the same key in one process share a single `fn` run.\n * `undefined` results are not cached.\n */\n wrap<T>(key: string, options: CacheSetOptions | number, fn: () => Promise<T>): Promise<T>;\n /** Deletes every key starting with `keyPrefix` (all of this app's keys when omitted). */\n clear(keyPrefix?: string): Promise<number>;\n /**\n * Atomically adds 1 and returns the new count — across workers and instances (Redis) or\n * this machine's workers (memory). `ttl` applies when the key is created (a fixed\n * window). Resolves `undefined` when the backend is unreachable: a count can't be made up.\n */\n incr(key: string, options?: CacheSetOptions): Promise<number | undefined>;\n}\n\nexport const cache: Cache = {\n async get<T>(key: string) {\n const raw = await safely('get', (b) => b.get(prefix + key), null);\n return raw === null ? undefined : (JSON.parse(raw) as T);\n },\n async set(key, value, options) {\n if (value === undefined) return;\n await safely('set', (b) => b.set(prefix + key, JSON.stringify(value), options?.ttl), undefined);\n },\n async has(key) {\n return (await safely('get', (b) => b.get(prefix + key), null)) !== null;\n },\n async del(...keys) {\n return safely('del', (b) => b.del(keys.map((k) => prefix + k)), 0);\n },\n async wrap<T>(key: string, options: CacheSetOptions | number, fn: () => Promise<T>) {\n const hit = await cache.get<T>(key);\n if (hit !== undefined) return hit;\n const inflight = pending.get(key) as Promise<T> | undefined;\n if (inflight) return inflight;\n const run = (async () => {\n try {\n const value = await fn();\n await cache.set(key, value, typeof options === 'number' ? { ttl: options } : options);\n return value;\n } finally {\n pending.delete(key);\n }\n })();\n pending.set(key, run);\n return run;\n },\n async clear(keyPrefix = '') {\n return safely('clear', (b) => b.clear(prefix + keyPrefix), 0);\n },\n async incr(key, options) {\n const r = await safely('incr', (b) => b.incr(prefix + key, options?.ttl), undefined);\n return r?.value;\n },\n};\n\n/** For rateLimit: the count and the window's remaining time; throws when the backend is down. */\nexport async function rawIncr(\n key: string,\n ttlSeconds: number,\n): Promise<{ value: number; ttlMs: number | null }> {\n return requireBackend().incr(prefix + key, ttlSeconds);\n}\n\n/** For auth's revocation checks, which must distinguish \"absent\" from \"backend down\". */\nexport async function rawGet(key: string): Promise<string | null> {\n return requireBackend().get(prefix + key);\n}\n\nexport async function rawSet(key: string, value: string, ttlSeconds: number): Promise<void> {\n await requireBackend().set(prefix + key, value, ttlSeconds);\n}\n","import cluster, { type Worker } from 'node:cluster';\nimport { randomUUID } from 'node:crypto';\nimport type { Backend } from './index.js';\nimport { memoryBackend } from './index.js';\nimport { getLogger } from '../logger.js';\n\n// The memory cache under clustering: the primary owns the only store and answers\n// workers' requests over the cluster IPC channel, so every worker sees the same\n// entries and the same revoked sessions. Message shape is tagged to avoid clashing\n// with application IPC.\n\nconst TAG = '__efcCache';\nconst TIMEOUT_MS = 2000;\n\ntype Op = 'ping' | 'get' | 'set' | 'del' | 'clear' | 'incr';\ninterface Request {\n [TAG]: true;\n id: string;\n op: Op;\n args: unknown[];\n}\ninterface Response {\n [TAG]: true;\n id: string;\n ok: boolean;\n result?: unknown;\n error?: string;\n}\n\nconst isTagged = (msg: unknown): msg is Record<string, unknown> =>\n msg !== null && typeof msg === 'object' && (msg as Record<string, unknown>)[TAG] === true;\n\n/** Primary side: hold the store and serve every worker. Called before workers fork. */\nexport function servePrimaryCache(maxEntries: number): void {\n const store = memoryBackend(maxEntries);\n cluster.on('message', (worker: Worker, msg: unknown) => {\n if (!isTagged(msg)) return;\n const req = msg as unknown as Request;\n const run = async (): Promise<unknown> => {\n switch (req.op) {\n case 'ping':\n return 'pong';\n case 'get':\n return store.get(req.args[0] as string);\n case 'set':\n return store.set(\n req.args[0] as string,\n req.args[1] as string,\n req.args[2] as number | undefined,\n );\n case 'del':\n return store.del(req.args[0] as string[]);\n case 'clear':\n return store.clear(req.args[0] as string);\n case 'incr':\n return store.incr(req.args[0] as string, req.args[1] as number | undefined);\n }\n };\n run().then(\n (result) =>\n worker.isConnected() &&\n worker.send({ [TAG]: true, id: req.id, ok: true, result } satisfies Response),\n (err: unknown) =>\n worker.isConnected() &&\n worker.send({ [TAG]: true, id: req.id, ok: false, error: String(err) } satisfies Response),\n );\n });\n}\n\n/**\n * Worker side: a Backend that forwards to the primary. Resolves to null — so the caller\n * can fall back to a local store — when no EFC primary answers (e.g. the app runs its\n * own cluster primary instead of ignite()'s).\n */\nexport async function connectPrimaryCache(): Promise<Backend | null> {\n if (!process.send) return null;\n const pending = new Map<\n string,\n { resolve: (v: unknown) => void; reject: (e: Error) => void; timer: NodeJS.Timeout }\n >();\n const onMessage = (msg: unknown) => {\n if (!isTagged(msg)) return;\n const res = msg as unknown as Response;\n const p = pending.get(res.id);\n if (!p) return;\n pending.delete(res.id);\n clearTimeout(p.timer);\n if (res.ok) p.resolve(res.result);\n else p.reject(new Error(res.error));\n };\n process.on('message', onMessage);\n\n const call = (op: Op, ...args: unknown[]) =>\n new Promise<unknown>((resolve, reject) => {\n const id = randomUUID();\n const timer = setTimeout(() => {\n pending.delete(id);\n reject(new Error(`[EFC] cache IPC \"${op}\" timed out`));\n }, TIMEOUT_MS);\n timer.unref();\n pending.set(id, { resolve, reject, timer });\n process.send!({ [TAG]: true, id, op, args } satisfies Request);\n });\n\n try {\n await call('ping');\n } catch {\n process.off('message', onMessage);\n getLogger().warn(\n 'cache backend \"memory\": no EFC cluster primary answered — using a per-worker store (entries and revoked sessions are not shared)',\n );\n return null;\n }\n\n return {\n get: async (key) => (await call('get', key)) as string | null,\n set: async (key, value, ttl) => {\n await call('set', key, value, ttl);\n },\n del: async (keys) => (await call('del', keys)) as number,\n clear: async (prefix) => (await call('clear', prefix)) as number,\n incr: async (key, ttl) =>\n (await call('incr', key, ttl)) as { value: number; ttlMs: number | null },\n close: async () => {\n process.off('message', onMessage);\n for (const p of pending.values()) clearTimeout(p.timer);\n pending.clear();\n },\n };\n}\n","import { randomBytes, scrypt, timingSafeEqual, type ScryptOptions } from 'node:crypto';\nimport { getLogger } from '../logger.js';\n\n// Password hashing on node:crypto's scrypt — no native addon, no extra dependency.\n// Stored format: `scrypt$<N>$<r>$<p>$<salt b64>$<key b64>`. The cost parameters travel\n// with each hash, so raising them later doesn't invalidate passwords already stored.\n// N=2^15, r=8, p=1: 32 MiB and ~100–250 ms per hash — above bcrypt cost 10 (what EFC used before)\n// without making each login hold a libuv thread for most of a second.\nconst N = 2 ** 15;\nconst R = 8;\nconst P = 1;\nconst KEY_LEN = 64;\nconst SALT_LEN = 16;\n\nfunction derive(\n password: string,\n salt: Buffer,\n n: number,\n r: number,\n p: number,\n keyLen: number,\n): Promise<Buffer> {\n // scrypt needs 128 * N * r bytes; Node's default maxmem (32 MiB) is exactly that at our defaults.\n const options: ScryptOptions = { N: n, r, p, maxmem: 256 * n * r };\n return new Promise((resolve, reject) => {\n scrypt(password.normalize('NFKC'), salt, keyLen, options, (err, key) =>\n err ? reject(err) : resolve(key),\n );\n });\n}\n\n/** Hashes a password with scrypt and a random salt. Store the returned string as-is. */\nexport async function hashPassword(password: string): Promise<string> {\n if (typeof password !== 'string' || password.length === 0) {\n throw new TypeError('[EFC] hashPassword: password must be a non-empty string');\n }\n const salt = randomBytes(SALT_LEN);\n const key = await derive(password, salt, N, R, P, KEY_LEN);\n return `scrypt$${N}$${R}$${P}$${salt.toString('base64')}$${key.toString('base64')}`;\n}\n\n/**\n * Checks a password against a hash from `hashPassword`. Returns false for a wrong password or any\n * other format — including bcrypt hashes (`$2a$`/`$2b$`/`$2y$`) from apps scaffolded before 0.9.2,\n * which EFC deliberately can't verify: those accounts reset their password.\n */\nexport async function verifyPassword(password: string, hash: string): Promise<boolean> {\n if (typeof password !== 'string' || typeof hash !== 'string') return false;\n if (/^\\$2[aby]\\$/.test(hash)) {\n getLogger().warn(\n '[EFC] verifyPassword: bcrypt hash found — not supported since 0.9.2. ' +\n 'This account must reset its password (the reset stores a hashPassword() hash).',\n );\n return false;\n }\n\n const parts = hash.split('$');\n if (parts.length !== 6 || parts[0] !== 'scrypt') return false;\n const [n, r, p] = parts.slice(1, 4).map(Number) as [number, number, number];\n if (![n, r, p].every((v) => Number.isInteger(v) && v > 0) || (n & (n - 1)) !== 0) return false;\n // Refuse cost parameters far above ours — a planted hash shouldn't be able to pin a worker.\n if (n > 2 ** 20 || r > 32 || p > 16) return false;\n const salt = Buffer.from(parts[4]!, 'base64');\n const expected = Buffer.from(parts[5]!, 'base64');\n if (salt.length === 0 || expected.length === 0) return false;\n\n const actual = await derive(password, salt, n, r, p, expected.length);\n return timingSafeEqual(actual, expected);\n}\n\n/** True when a stored hash should be replaced with `hashPassword()` (e.g. after a successful login). */\nexport function passwordNeedsRehash(hash: string): boolean {\n return !hash.startsWith(`scrypt$${N}$${R}$${P}$`);\n}\n"]}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import {
|
|
2
2
|
getLogger
|
|
3
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-73XJUT2S.js";
|
|
4
4
|
|
|
5
5
|
// src/router/scan.ts
|
|
6
6
|
import fs from "fs";
|
|
@@ -113,4 +113,4 @@ function scanDir(dir, base = dir, maxDepth = DEFAULT_MAX_DEPTH, _depth = 0) {
|
|
|
113
113
|
export {
|
|
114
114
|
scanDir
|
|
115
115
|
};
|
|
116
|
-
//# sourceMappingURL=chunk-
|
|
116
|
+
//# sourceMappingURL=chunk-NI2BNGGV.js.map
|
|
@@ -1,11 +1,9 @@
|
|
|
1
1
|
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
|
|
2
2
|
|
|
3
3
|
|
|
4
|
-
var _chunkVQSWSYK6cjs = require('./chunk-VQSWSYK6.cjs');
|
|
5
4
|
|
|
6
5
|
|
|
7
|
-
|
|
8
|
-
var _chunkYL37D6KMcjs = require('./chunk-YL37D6KM.cjs');
|
|
6
|
+
var _chunkDUADUR6Rcjs = require('./chunk-DUADUR6R.cjs');
|
|
9
7
|
|
|
10
8
|
// src/errors.ts
|
|
11
9
|
var HttpError = class _HttpError extends Error {
|
|
@@ -212,10 +210,10 @@ function isDefaultOperator(value) {
|
|
|
212
210
|
function resolveDefault(value, objectId) {
|
|
213
211
|
if (!isDefaultOperator(value)) return value;
|
|
214
212
|
if (value === "$objectId") return objectId;
|
|
215
|
-
if (value === "$currentUser") return () =>
|
|
213
|
+
if (value === "$currentUser") return () => _chunkDUADUR6Rcjs.getCurrentUser.call(void 0, );
|
|
216
214
|
if (isCurrentUserOperator(value)) {
|
|
217
215
|
const key = value.slice("$currentUser.".length);
|
|
218
|
-
return () => _optionalChain([
|
|
216
|
+
return () => _optionalChain([_chunkDUADUR6Rcjs.getCurrentUser.call(void 0, ), 'optionalAccess', _ => _[key]]);
|
|
219
217
|
}
|
|
220
218
|
return STATIC_DEFAULT_OPERATORS[value];
|
|
221
219
|
}
|
|
@@ -688,7 +686,7 @@ function pgTable(name, tree, options, config) {
|
|
|
688
686
|
synced ??= reconcile(false).then(
|
|
689
687
|
(changes) => {
|
|
690
688
|
if (changes.length)
|
|
691
|
-
|
|
689
|
+
_chunkDUADUR6Rcjs.getLogger.call(void 0, ).info({ table, changes: changes.length }, `Synced table ${table}`);
|
|
692
690
|
},
|
|
693
691
|
(err) => {
|
|
694
692
|
synced = void 0;
|
|
@@ -701,7 +699,7 @@ function pgTable(name, tree, options, config) {
|
|
|
701
699
|
};
|
|
702
700
|
const client = () => {
|
|
703
701
|
const tx = currentTx();
|
|
704
|
-
return _optionalChain([tx, 'optionalAccess', _10 => _10.engine]) === "postgresql" ? tx.tx :
|
|
702
|
+
return _optionalChain([tx, 'optionalAccess', _10 => _10.engine]) === "postgresql" ? tx.tx : _chunkDUADUR6Rcjs.getOrm.call(void 0, );
|
|
705
703
|
};
|
|
706
704
|
const columnFor = (t, field) => {
|
|
707
705
|
if (!columns.has(field))
|
|
@@ -968,7 +966,7 @@ function pgTable(name, tree, options, config) {
|
|
|
968
966
|
}
|
|
969
967
|
return out;
|
|
970
968
|
}
|
|
971
|
-
const tableExists = async (t) => (await
|
|
969
|
+
const tableExists = async (t) => (await _chunkDUADUR6Rcjs.getPool.call(void 0, ).query(
|
|
972
970
|
`SELECT 1 FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace
|
|
973
971
|
WHERE c.relname = $1 AND n.nspname = current_schema() AND c.relkind IN ('r', 'p')`,
|
|
974
972
|
[t]
|
|
@@ -988,7 +986,7 @@ function pgTable(name, tree, options, config) {
|
|
|
988
986
|
for (const fk of fks) deferred.add(fk.name);
|
|
989
987
|
tx.afterCommit.push(() => {
|
|
990
988
|
reconcile(false).catch(
|
|
991
|
-
(err) =>
|
|
989
|
+
(err) => _chunkDUADUR6Rcjs.getLogger.call(void 0, ).error({ err }, `${name}: adding foreign keys to "${table}" failed`)
|
|
992
990
|
);
|
|
993
991
|
});
|
|
994
992
|
}
|
|
@@ -999,7 +997,7 @@ function pgTable(name, tree, options, config) {
|
|
|
999
997
|
if (running) {
|
|
1000
998
|
deferred.add(fk.name);
|
|
1001
999
|
void running.then(() => reconcile(false)).catch(
|
|
1002
|
-
(err) =>
|
|
1000
|
+
(err) => _chunkDUADUR6Rcjs.getLogger.call(void 0, ).error({ err }, `${name}: adding foreign keys to "${table}" failed`)
|
|
1003
1001
|
);
|
|
1004
1002
|
} else {
|
|
1005
1003
|
await getRegisteredModel(fk.target).sync();
|
|
@@ -1021,7 +1019,7 @@ function pgTable(name, tree, options, config) {
|
|
|
1021
1019
|
async function reconcileTable(mode, fks, deferred) {
|
|
1022
1020
|
const { dryRun } = mode;
|
|
1023
1021
|
const generating = mode.plan !== void 0;
|
|
1024
|
-
const pool =
|
|
1022
|
+
const pool = _chunkDUADUR6Rcjs.getPool.call(void 0, );
|
|
1025
1023
|
const conn = await pool.connect();
|
|
1026
1024
|
try {
|
|
1027
1025
|
await conn.query("BEGIN");
|
|
@@ -1332,7 +1330,7 @@ function pgTable(name, tree, options, config) {
|
|
|
1332
1330
|
await conn.query(validations[i]);
|
|
1333
1331
|
} catch (e3) {
|
|
1334
1332
|
const n = await conn.query(orphans(fk)).then((r) => _nullishCoalesce(_optionalChain([r, 'access', _68 => _68.rows, 'access', _69 => _69[0], 'optionalAccess', _70 => _70.n]), () => ( "?"))).catch(() => "?");
|
|
1335
|
-
|
|
1333
|
+
_chunkDUADUR6Rcjs.getLogger.call(void 0, ).warn(
|
|
1336
1334
|
{ table, constraint: fk.name, orphans: Number(n) },
|
|
1337
1335
|
`${name}.${fk.field}: ${n} row(s) reference a missing ${fk.target} \u2014 the foreign key applies to new writes; fix those rows, then run efc db sync to validate it`
|
|
1338
1336
|
);
|
|
@@ -1405,4 +1403,4 @@ function pgTable(name, tree, options, config) {
|
|
|
1405
1403
|
|
|
1406
1404
|
|
|
1407
1405
|
exports.HttpError = HttpError; exports.isHttpError = isHttpError; exports.normalizeSchema = normalizeSchema; exports.timestampFields = timestampFields; exports.resolveDefault = resolveDefault; exports.ModelValidationError = ModelValidationError; exports.sequenceFields = sequenceFields; exports.nodeAt = nodeAt; exports.validateAtPath = validateAtPath; exports.setDbEngine = setDbEngine; exports.getDbEngine = getDbEngine; exports.setAutoSync = setAutoSync; exports.isAutoSync = isAutoSync; exports.setSyncSuppressed = setSyncSuppressed; exports.isSyncSuppressed = isSyncSuppressed; exports.registerModel = registerModel; exports.getRegisteredModel = getRegisteredModel; exports.registeredModels = registeredModels; exports.currentTx = currentTx; exports.runInTx = runInTx; exports.tableNameFor = tableNameFor; exports.snakeCase = snakeCase; exports.q = q; exports.pgTable = pgTable;
|
|
1408
|
-
//# sourceMappingURL=chunk-
|
|
1406
|
+
//# sourceMappingURL=chunk-NKLOE4AK.cjs.map
|