@spfn/core 0.2.0-beta.8 → 0.3.0-beta.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +1 -1
- package/README.md +444 -305
- package/dist/authz/index.d.ts +34 -0
- package/dist/authz/index.js +810 -0
- package/dist/authz/index.js.map +1 -0
- package/dist/{boss-DI1r4kTS.d.ts → boss-D16fO2oG.d.ts} +41 -1
- package/dist/cache/index.js +42 -30
- package/dist/cache/index.js.map +1 -1
- package/dist/codegen/index.d.ts +121 -13
- package/dist/codegen/index.js +212 -15
- package/dist/codegen/index.js.map +1 -1
- package/dist/config/index.d.ts +615 -6
- package/dist/config/index.js +124 -5
- package/dist/config/index.js.map +1 -1
- package/dist/contract/index.d.ts +220 -0
- package/dist/contract/index.js +558 -0
- package/dist/contract/index.js.map +1 -0
- package/dist/db/index.d.ts +528 -85
- package/dist/db/index.js +831 -122
- package/dist/db/index.js.map +1 -1
- package/dist/define-middleware-DfDP39Nq.d.ts +167 -0
- package/dist/env/index.d.ts +26 -2
- package/dist/env/index.js +15 -5
- package/dist/env/index.js.map +1 -1
- package/dist/env/loader.d.ts +26 -19
- package/dist/env/loader.js +32 -25
- package/dist/env/loader.js.map +1 -1
- package/dist/errors/index.d.ts +10 -0
- package/dist/errors/index.js +418 -5
- package/dist/errors/index.js.map +1 -1
- package/dist/event/index.d.ts +33 -3
- package/dist/event/index.js +24 -3
- package/dist/event/index.js.map +1 -1
- package/dist/event/sse/client.d.ts +42 -3
- package/dist/event/sse/client.js +128 -45
- package/dist/event/sse/client.js.map +1 -1
- package/dist/event/sse/index.d.ts +12 -5
- package/dist/event/sse/index.js +280 -32
- package/dist/event/sse/index.js.map +1 -1
- package/dist/event/ws/client.d.ts +59 -0
- package/dist/event/ws/client.js +273 -0
- package/dist/event/ws/client.js.map +1 -0
- package/dist/event/ws/index.d.ts +94 -0
- package/dist/event/ws/index.js +272 -0
- package/dist/event/ws/index.js.map +1 -0
- package/dist/job/index.d.ts +2 -2
- package/dist/job/index.js +155 -42
- package/dist/job/index.js.map +1 -1
- package/dist/logger/index.d.ts +5 -0
- package/dist/logger/index.js +14 -0
- package/dist/logger/index.js.map +1 -1
- package/dist/middleware/index.d.ts +347 -9
- package/dist/middleware/index.js +1462 -15
- package/dist/middleware/index.js.map +1 -1
- package/dist/nextjs/index.d.ts +2 -2
- package/dist/nextjs/index.js +42 -28
- package/dist/nextjs/index.js.map +1 -1
- package/dist/nextjs/server.d.ts +35 -51
- package/dist/nextjs/server.js +126 -60
- package/dist/nextjs/server.js.map +1 -1
- package/dist/ops/index.d.ts +107 -0
- package/dist/ops/index.js +476 -0
- package/dist/ops/index.js.map +1 -0
- package/dist/route/index.d.ts +8 -694
- package/dist/route/index.js +111 -22
- package/dist/route/index.js.map +1 -1
- package/dist/router-ukNdAZcN.d.ts +676 -0
- package/dist/security/index.d.ts +83 -0
- package/dist/security/index.js +173 -0
- package/dist/security/index.js.map +1 -0
- package/dist/server/index.d.ts +491 -22
- package/dist/server/index.js +1887 -308
- package/dist/server/index.js.map +1 -1
- package/dist/token-manager-BT5EnUAR.d.ts +278 -0
- package/dist/types-2AbaW4Ie.d.ts +205 -0
- package/dist/{types-BOPTApC2.d.ts → types-9oszaJqp.d.ts} +7 -2
- package/dist/types-Bvvig_tT.d.ts +115 -0
- package/dist/types-ZQODsBft.d.ts +282 -0
- package/package.json +244 -208
- package/dist/router-Di7ENoah.d.ts +0 -151
- package/dist/types-B-e_f2dQ.d.ts +0 -121
- package/docs/cache.md +0 -133
- package/docs/codegen.md +0 -74
- package/docs/database.md +0 -346
- package/docs/entity.md +0 -539
- package/docs/env.md +0 -477
- package/docs/errors.md +0 -319
- package/docs/event.md +0 -116
- package/docs/job.md +0 -131
- package/docs/logger.md +0 -108
- package/docs/middleware.md +0 -337
- package/docs/nextjs.md +0 -241
- package/docs/repository.md +0 -496
- package/docs/route.md +0 -497
- package/docs/server.md +0 -307
package/dist/middleware/index.js
CHANGED
|
@@ -1,10 +1,90 @@
|
|
|
1
|
+
import { randomBytes, createHmac, createHash, timingSafeEqual } from 'crypto';
|
|
1
2
|
import { SerializableError } from '@spfn/core/errors';
|
|
2
3
|
import { logger } from '@spfn/core/logger';
|
|
3
4
|
import { env } from '@spfn/core/config';
|
|
4
|
-
import {
|
|
5
|
+
import { format } from 'util';
|
|
5
6
|
|
|
6
7
|
// src/middleware/error-handler.ts
|
|
7
8
|
var errorLogger = logger.child("@spfn/core:error-handler");
|
|
9
|
+
function withEnvelope(body, c) {
|
|
10
|
+
return {
|
|
11
|
+
...body,
|
|
12
|
+
error: {
|
|
13
|
+
code: body.__type,
|
|
14
|
+
message: body.message,
|
|
15
|
+
requestId: resolveRequestId(c)
|
|
16
|
+
}
|
|
17
|
+
};
|
|
18
|
+
}
|
|
19
|
+
function resolveRequestId(c) {
|
|
20
|
+
const existing = c.get("requestId");
|
|
21
|
+
return existing ?? randomBytes(16).toString("hex");
|
|
22
|
+
}
|
|
23
|
+
function extractCauseMessage(err) {
|
|
24
|
+
const cause = err.cause;
|
|
25
|
+
if (!cause) {
|
|
26
|
+
return void 0;
|
|
27
|
+
}
|
|
28
|
+
if (cause instanceof Error) {
|
|
29
|
+
return cause.message;
|
|
30
|
+
}
|
|
31
|
+
if (typeof cause === "string") {
|
|
32
|
+
return cause;
|
|
33
|
+
}
|
|
34
|
+
return String(cause);
|
|
35
|
+
}
|
|
36
|
+
var SENSITIVE_HEADERS = /* @__PURE__ */ new Set(["authorization", "cookie", "x-api-key", "x-auth-token"]);
|
|
37
|
+
function extractHeaders(c) {
|
|
38
|
+
const headers = {};
|
|
39
|
+
c.req.raw.headers.forEach((value, key) => {
|
|
40
|
+
headers[key] = SENSITIVE_HEADERS.has(key.toLowerCase()) ? "***" : value;
|
|
41
|
+
});
|
|
42
|
+
return headers;
|
|
43
|
+
}
|
|
44
|
+
var SENSITIVE_QUERY_PARAMS = /* @__PURE__ */ new Set([
|
|
45
|
+
"token",
|
|
46
|
+
"access_token",
|
|
47
|
+
"refresh_token",
|
|
48
|
+
"id_token",
|
|
49
|
+
"code",
|
|
50
|
+
"secret",
|
|
51
|
+
"client_secret",
|
|
52
|
+
"password",
|
|
53
|
+
"passwd",
|
|
54
|
+
"pwd",
|
|
55
|
+
"api_key",
|
|
56
|
+
"apikey",
|
|
57
|
+
"key",
|
|
58
|
+
"signature",
|
|
59
|
+
"sig",
|
|
60
|
+
"session",
|
|
61
|
+
"sessionid",
|
|
62
|
+
"auth",
|
|
63
|
+
"authorization"
|
|
64
|
+
]);
|
|
65
|
+
function extractQuery(c) {
|
|
66
|
+
const query = c.req.query();
|
|
67
|
+
const masked = {};
|
|
68
|
+
for (const [key, value] of Object.entries(query)) {
|
|
69
|
+
masked[key] = SENSITIVE_QUERY_PARAMS.has(key.toLowerCase()) ? "***" : value;
|
|
70
|
+
}
|
|
71
|
+
return masked;
|
|
72
|
+
}
|
|
73
|
+
function buildOnErrorContext(c, statusCode) {
|
|
74
|
+
const auth = c.get("auth");
|
|
75
|
+
return {
|
|
76
|
+
statusCode,
|
|
77
|
+
path: c.req.path,
|
|
78
|
+
method: c.req.method,
|
|
79
|
+
requestId: c.get("requestId"),
|
|
80
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
|
|
81
|
+
userId: auth?.userId,
|
|
82
|
+
request: {
|
|
83
|
+
headers: extractHeaders(c),
|
|
84
|
+
query: extractQuery(c)
|
|
85
|
+
}
|
|
86
|
+
};
|
|
87
|
+
}
|
|
8
88
|
function logError(err, logData, includeStack) {
|
|
9
89
|
const logLevel = logData.statusCode >= 500 ? "error" : "warn";
|
|
10
90
|
if (includeStack) {
|
|
@@ -19,25 +99,48 @@ function isSerializableError(err) {
|
|
|
19
99
|
function ErrorHandler(options = {}) {
|
|
20
100
|
const {
|
|
21
101
|
includeStack = env.NODE_ENV !== "production",
|
|
22
|
-
enableLogging = true
|
|
102
|
+
enableLogging = true,
|
|
103
|
+
errorEnvelope = true,
|
|
104
|
+
onError
|
|
23
105
|
} = options;
|
|
106
|
+
const respond = (c, body, statusCode) => {
|
|
107
|
+
return c.json(
|
|
108
|
+
errorEnvelope ? withEnvelope(body, c) : body,
|
|
109
|
+
statusCode
|
|
110
|
+
);
|
|
111
|
+
};
|
|
24
112
|
return (err, c) => {
|
|
113
|
+
const path = c.req.path;
|
|
114
|
+
const method = c.req.method;
|
|
115
|
+
const causeMessage = extractCauseMessage(err);
|
|
25
116
|
if (isSerializableError(err)) {
|
|
26
117
|
const { statusCode: statusCode2 } = err;
|
|
27
118
|
if (enableLogging) {
|
|
28
119
|
logError(err, {
|
|
29
120
|
type: err.constructor.name,
|
|
30
121
|
message: err.message,
|
|
122
|
+
cause: causeMessage,
|
|
31
123
|
statusCode: statusCode2,
|
|
32
|
-
path
|
|
33
|
-
method
|
|
124
|
+
path,
|
|
125
|
+
method
|
|
34
126
|
}, includeStack);
|
|
35
127
|
}
|
|
128
|
+
if (onError) {
|
|
129
|
+
const ctx = buildOnErrorContext(c, statusCode2);
|
|
130
|
+
Promise.resolve(onError(err, ctx)).catch((e) => errorLogger.warn("onError callback failed", e));
|
|
131
|
+
}
|
|
132
|
+
if (err.internal === true && !includeStack) {
|
|
133
|
+
return respond(
|
|
134
|
+
c,
|
|
135
|
+
{ __type: err.constructor.name, message: "Internal server error" },
|
|
136
|
+
statusCode2
|
|
137
|
+
);
|
|
138
|
+
}
|
|
36
139
|
const serialized = err.toJSON();
|
|
37
140
|
if (includeStack && err.stack) {
|
|
38
141
|
serialized.stack = err.stack;
|
|
39
142
|
}
|
|
40
|
-
return c
|
|
143
|
+
return respond(c, serialized, statusCode2);
|
|
41
144
|
}
|
|
42
145
|
const errorWithCode = err;
|
|
43
146
|
const statusCode = errorWithCode.statusCode || 500;
|
|
@@ -45,21 +148,1183 @@ function ErrorHandler(options = {}) {
|
|
|
45
148
|
logError(err, {
|
|
46
149
|
type: err.name || "Error",
|
|
47
150
|
message: err.message,
|
|
151
|
+
cause: causeMessage,
|
|
48
152
|
statusCode,
|
|
49
|
-
path
|
|
50
|
-
method
|
|
153
|
+
path,
|
|
154
|
+
method
|
|
51
155
|
}, includeStack);
|
|
52
156
|
}
|
|
157
|
+
if (onError) {
|
|
158
|
+
const ctx = buildOnErrorContext(c, statusCode);
|
|
159
|
+
Promise.resolve(onError(err, ctx)).catch((e) => errorLogger.warn("onError callback failed", e));
|
|
160
|
+
}
|
|
53
161
|
const response = {
|
|
54
162
|
__type: "Error",
|
|
55
|
-
message: err.message || "Internal Server Error"
|
|
163
|
+
message: includeStack ? err.message || "Internal Server Error" : "Internal Server Error"
|
|
56
164
|
};
|
|
165
|
+
if (causeMessage && includeStack) {
|
|
166
|
+
response.cause = causeMessage;
|
|
167
|
+
}
|
|
57
168
|
if (includeStack && err.stack) {
|
|
58
169
|
response.stack = err.stack;
|
|
59
170
|
}
|
|
60
|
-
return c
|
|
171
|
+
return respond(c, response, statusCode);
|
|
172
|
+
};
|
|
173
|
+
}
|
|
174
|
+
var PROXY_SIGNATURE_HEADER = "x-spfn-proxy-signature";
|
|
175
|
+
var PROXY_TIMESTAMP_HEADER = "x-spfn-proxy-timestamp";
|
|
176
|
+
var PROXY_NONCE_HEADER = "x-spfn-proxy-nonce";
|
|
177
|
+
var PROXY_KEY_ID_HEADER = "x-spfn-proxy-key-id";
|
|
178
|
+
var PROXY_CLIENT_IP_HEADER = "x-spfn-proxy-client-ip";
|
|
179
|
+
var DEFAULT_KEY_ID = "default";
|
|
180
|
+
function parseProxyKey(raw) {
|
|
181
|
+
const idx = raw.indexOf(":");
|
|
182
|
+
if (idx === -1) {
|
|
183
|
+
return { keyId: DEFAULT_KEY_ID, secret: raw };
|
|
184
|
+
}
|
|
185
|
+
return { keyId: raw.slice(0, idx) || DEFAULT_KEY_ID, secret: raw.slice(idx + 1) };
|
|
186
|
+
}
|
|
187
|
+
function parseProxyKeySet(raws) {
|
|
188
|
+
const keys = [];
|
|
189
|
+
const seen = /* @__PURE__ */ new Set();
|
|
190
|
+
for (const raw of raws) {
|
|
191
|
+
if (!raw) {
|
|
192
|
+
continue;
|
|
193
|
+
}
|
|
194
|
+
for (const part of raw.split(",")) {
|
|
195
|
+
const trimmed = part.trim();
|
|
196
|
+
if (!trimmed) {
|
|
197
|
+
continue;
|
|
198
|
+
}
|
|
199
|
+
const key = parseProxyKey(trimmed);
|
|
200
|
+
if (!key.secret || seen.has(key.keyId)) {
|
|
201
|
+
continue;
|
|
202
|
+
}
|
|
203
|
+
seen.add(key.keyId);
|
|
204
|
+
keys.push(key);
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
return keys;
|
|
208
|
+
}
|
|
209
|
+
function buildCanonicalString(parts) {
|
|
210
|
+
return [parts.method.toUpperCase(), parts.path, parts.query, parts.timestamp, parts.nonce, parts.bodyHash].join("\n");
|
|
211
|
+
}
|
|
212
|
+
function hashBody(body) {
|
|
213
|
+
if (!body || body.length === 0) {
|
|
214
|
+
return "";
|
|
215
|
+
}
|
|
216
|
+
return typeof body === "string" ? createHash("sha256").update(body, "utf8").digest("hex") : createHash("sha256").update(body).digest("hex");
|
|
217
|
+
}
|
|
218
|
+
function computeSignature(secret, parts) {
|
|
219
|
+
return createHmac("sha256", secret).update(buildCanonicalString(parts)).digest("hex");
|
|
220
|
+
}
|
|
221
|
+
function safeEqualHex(a, b) {
|
|
222
|
+
const bufA = Buffer.from(a, "hex");
|
|
223
|
+
const bufB = Buffer.from(b, "hex");
|
|
224
|
+
if (bufA.length === 0 || bufA.length !== bufB.length) {
|
|
225
|
+
return false;
|
|
226
|
+
}
|
|
227
|
+
return timingSafeEqual(bufA, bufB);
|
|
228
|
+
}
|
|
229
|
+
function verifyProxyRequest(input) {
|
|
230
|
+
const { signature, timestamp, nonce, keyId } = input;
|
|
231
|
+
if (!signature || !timestamp || !nonce || !keyId) {
|
|
232
|
+
return { valid: false, reason: "missing-headers" };
|
|
233
|
+
}
|
|
234
|
+
const ts = Number(timestamp);
|
|
235
|
+
if (!Number.isFinite(ts)) {
|
|
236
|
+
return { valid: false, reason: "bad-timestamp" };
|
|
237
|
+
}
|
|
238
|
+
const now = input.now ?? Date.now();
|
|
239
|
+
const windowMs = input.windowMs ?? 3e4;
|
|
240
|
+
if (Math.abs(now - ts) > windowMs) {
|
|
241
|
+
return { valid: false, reason: "stale-timestamp" };
|
|
242
|
+
}
|
|
243
|
+
const key = input.keys.find((k) => k.keyId === keyId);
|
|
244
|
+
if (!key) {
|
|
245
|
+
return { valid: false, reason: "unknown-key" };
|
|
246
|
+
}
|
|
247
|
+
const expected = computeSignature(key.secret, {
|
|
248
|
+
method: input.method,
|
|
249
|
+
path: input.path,
|
|
250
|
+
query: input.query ?? "",
|
|
251
|
+
timestamp,
|
|
252
|
+
nonce,
|
|
253
|
+
bodyHash: hashBody(input.body)
|
|
254
|
+
});
|
|
255
|
+
if (!safeEqualHex(signature, expected)) {
|
|
256
|
+
return { valid: false, reason: "signature-mismatch" };
|
|
257
|
+
}
|
|
258
|
+
return { valid: true, nonce, keyId };
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
// src/route/define-middleware.ts
|
|
262
|
+
function defineMiddleware(name, handlerOrFactory, options) {
|
|
263
|
+
const skips = options?.skips;
|
|
264
|
+
if (typeof handlerOrFactory === "function") {
|
|
265
|
+
const paramCount = handlerOrFactory.length;
|
|
266
|
+
if (paramCount === 2) {
|
|
267
|
+
return {
|
|
268
|
+
name,
|
|
269
|
+
handler: handlerOrFactory,
|
|
270
|
+
_name: name,
|
|
271
|
+
...skips
|
|
272
|
+
};
|
|
273
|
+
} else {
|
|
274
|
+
const factory = handlerOrFactory;
|
|
275
|
+
const wrapper = (...args) => factory(...args);
|
|
276
|
+
Object.defineProperty(wrapper, "name", {
|
|
277
|
+
value: name,
|
|
278
|
+
writable: false,
|
|
279
|
+
enumerable: false,
|
|
280
|
+
configurable: true
|
|
281
|
+
});
|
|
282
|
+
Object.defineProperty(wrapper, "_name", {
|
|
283
|
+
value: name,
|
|
284
|
+
writable: false,
|
|
285
|
+
enumerable: false,
|
|
286
|
+
configurable: true
|
|
287
|
+
});
|
|
288
|
+
return wrapper;
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
return {
|
|
292
|
+
name,
|
|
293
|
+
handler: handlerOrFactory,
|
|
294
|
+
_name: name,
|
|
295
|
+
...skips
|
|
296
|
+
};
|
|
297
|
+
}
|
|
298
|
+
function defineMiddlewareFactory(name, factory) {
|
|
299
|
+
const wrapper = (...args) => factory(...args);
|
|
300
|
+
Object.defineProperty(wrapper, "name", {
|
|
301
|
+
value: name,
|
|
302
|
+
writable: false,
|
|
303
|
+
enumerable: false,
|
|
304
|
+
configurable: true
|
|
305
|
+
});
|
|
306
|
+
Object.defineProperty(wrapper, "_name", {
|
|
307
|
+
value: name,
|
|
308
|
+
writable: false,
|
|
309
|
+
enumerable: false,
|
|
310
|
+
configurable: true
|
|
311
|
+
});
|
|
312
|
+
return wrapper;
|
|
313
|
+
}
|
|
314
|
+
logger.child("@spfn/core:cache");
|
|
315
|
+
logger.child("@spfn/core:cache");
|
|
316
|
+
var CACHE_KEY = Symbol.for("@spfn/core:cache");
|
|
317
|
+
var state = globalThis[CACHE_KEY] ??= {
|
|
318
|
+
write: void 0,
|
|
319
|
+
read: void 0,
|
|
320
|
+
disabled: false
|
|
321
|
+
};
|
|
322
|
+
function getCache() {
|
|
323
|
+
return state.write;
|
|
324
|
+
}
|
|
325
|
+
function isCacheDisabled() {
|
|
326
|
+
return state.disabled;
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
// src/errors/error-registry.ts
|
|
330
|
+
var ErrorRegistry = class _ErrorRegistry {
|
|
331
|
+
errors = /* @__PURE__ */ new Map();
|
|
332
|
+
constructor(initialErrors) {
|
|
333
|
+
if (initialErrors) {
|
|
334
|
+
for (const input of initialErrors) {
|
|
335
|
+
if (input instanceof _ErrorRegistry) {
|
|
336
|
+
this.concat(input);
|
|
337
|
+
} else if (Array.isArray(input)) {
|
|
338
|
+
this.append(input);
|
|
339
|
+
} else {
|
|
340
|
+
this.append(input);
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
/**
|
|
346
|
+
* Append error class(es) to the registry
|
|
347
|
+
*
|
|
348
|
+
* @param input - Error constructor or array of constructors
|
|
349
|
+
* @returns This registry for chaining
|
|
350
|
+
*/
|
|
351
|
+
append(input) {
|
|
352
|
+
if (Array.isArray(input)) {
|
|
353
|
+
for (const ErrorClass of input) {
|
|
354
|
+
this.errors.set(ErrorClass.name, ErrorClass);
|
|
355
|
+
}
|
|
356
|
+
} else {
|
|
357
|
+
this.errors.set(input.name, input);
|
|
358
|
+
}
|
|
359
|
+
return this;
|
|
360
|
+
}
|
|
361
|
+
/**
|
|
362
|
+
* Concatenate another ErrorRegistry into this one
|
|
363
|
+
*
|
|
364
|
+
* @param registry - Another ErrorRegistry to merge
|
|
365
|
+
* @returns This registry for chaining
|
|
366
|
+
*/
|
|
367
|
+
concat(registry) {
|
|
368
|
+
for (const [name, ErrorClass] of registry.errors) {
|
|
369
|
+
this.errors.set(name, ErrorClass);
|
|
370
|
+
}
|
|
371
|
+
return this;
|
|
372
|
+
}
|
|
373
|
+
/**
|
|
374
|
+
* Check if error type is registered
|
|
375
|
+
*
|
|
376
|
+
* @param name - Error class name
|
|
377
|
+
*/
|
|
378
|
+
has(name) {
|
|
379
|
+
return this.errors.has(name);
|
|
380
|
+
}
|
|
381
|
+
/**
|
|
382
|
+
* Deserialize error from JSON data
|
|
383
|
+
*
|
|
384
|
+
* @param data - Serialized error data with __type field
|
|
385
|
+
* @returns Deserialized error instance
|
|
386
|
+
* @throws Error if error type is not registered
|
|
387
|
+
*/
|
|
388
|
+
deserialize(data) {
|
|
389
|
+
const ErrorClass = this.errors.get(data.__type);
|
|
390
|
+
if (!ErrorClass) {
|
|
391
|
+
throw new Error(`Unknown error type: ${data.__type}`);
|
|
392
|
+
}
|
|
393
|
+
const { __type: _type, error: _envelope, ...fields } = data;
|
|
394
|
+
return new ErrorClass(fields);
|
|
395
|
+
}
|
|
396
|
+
/**
|
|
397
|
+
* Try to deserialize error, return null if type unknown
|
|
398
|
+
*
|
|
399
|
+
* @param data - Serialized error data
|
|
400
|
+
* @returns Deserialized error or null
|
|
401
|
+
*/
|
|
402
|
+
tryDeserialize(data) {
|
|
403
|
+
if (!data.__type || !this.has(data.__type)) {
|
|
404
|
+
return null;
|
|
405
|
+
}
|
|
406
|
+
try {
|
|
407
|
+
return this.deserialize(data);
|
|
408
|
+
} catch {
|
|
409
|
+
return null;
|
|
410
|
+
}
|
|
411
|
+
}
|
|
412
|
+
/**
|
|
413
|
+
* Get all registered error types
|
|
414
|
+
*/
|
|
415
|
+
getRegisteredTypes() {
|
|
416
|
+
return Array.from(this.errors.keys());
|
|
417
|
+
}
|
|
418
|
+
};
|
|
419
|
+
|
|
420
|
+
// src/logger/types.ts
|
|
421
|
+
var LOG_LEVEL_PRIORITY = {
|
|
422
|
+
debug: 0,
|
|
423
|
+
info: 1,
|
|
424
|
+
warn: 2,
|
|
425
|
+
error: 3,
|
|
426
|
+
fatal: 4
|
|
427
|
+
};
|
|
428
|
+
|
|
429
|
+
// src/logger/formatters.ts
|
|
430
|
+
var SENSITIVE_KEYS = [
|
|
431
|
+
"password",
|
|
432
|
+
"passwd",
|
|
433
|
+
"pwd",
|
|
434
|
+
"secret",
|
|
435
|
+
"token",
|
|
436
|
+
"apikey",
|
|
437
|
+
"api_key",
|
|
438
|
+
"accesstoken",
|
|
439
|
+
"access_token",
|
|
440
|
+
"refreshtoken",
|
|
441
|
+
"refresh_token",
|
|
442
|
+
"authorization",
|
|
443
|
+
"auth",
|
|
444
|
+
"cookie",
|
|
445
|
+
"session",
|
|
446
|
+
"sessionid",
|
|
447
|
+
"session_id",
|
|
448
|
+
"privatekey",
|
|
449
|
+
"private_key",
|
|
450
|
+
"creditcard",
|
|
451
|
+
"credit_card",
|
|
452
|
+
"cardnumber",
|
|
453
|
+
"card_number",
|
|
454
|
+
"cvv",
|
|
455
|
+
"ssn",
|
|
456
|
+
"pin"
|
|
457
|
+
];
|
|
458
|
+
var MASKED_VALUE = "***MASKED***";
|
|
459
|
+
function isSensitiveKey(key) {
|
|
460
|
+
const lowerKey = key.toLowerCase();
|
|
461
|
+
return SENSITIVE_KEYS.some((sensitive) => lowerKey.includes(sensitive));
|
|
462
|
+
}
|
|
463
|
+
function maskSensitiveData(data, seen = /* @__PURE__ */ new WeakSet()) {
|
|
464
|
+
if (data === null || data === void 0) {
|
|
465
|
+
return data;
|
|
466
|
+
}
|
|
467
|
+
if (typeof data !== "object") {
|
|
468
|
+
return data;
|
|
469
|
+
}
|
|
470
|
+
if (seen.has(data)) {
|
|
471
|
+
return "[Circular]";
|
|
472
|
+
}
|
|
473
|
+
seen.add(data);
|
|
474
|
+
if (Array.isArray(data)) {
|
|
475
|
+
return data.map((item) => maskSensitiveData(item, seen));
|
|
476
|
+
}
|
|
477
|
+
const masked = {};
|
|
478
|
+
for (const [key, value] of Object.entries(data)) {
|
|
479
|
+
if (isSensitiveKey(key)) {
|
|
480
|
+
masked[key] = MASKED_VALUE;
|
|
481
|
+
} else if (typeof value === "object" && value !== null) {
|
|
482
|
+
masked[key] = maskSensitiveData(value, seen);
|
|
483
|
+
} else {
|
|
484
|
+
masked[key] = value;
|
|
485
|
+
}
|
|
486
|
+
}
|
|
487
|
+
return masked;
|
|
488
|
+
}
|
|
489
|
+
var COLORS = {
|
|
490
|
+
reset: "\x1B[0m",
|
|
491
|
+
bright: "\x1B[1m",
|
|
492
|
+
dim: "\x1B[2m",
|
|
493
|
+
// 로그 레벨 컬러
|
|
494
|
+
debug: "\x1B[36m",
|
|
495
|
+
// cyan
|
|
496
|
+
info: "\x1B[32m",
|
|
497
|
+
// green
|
|
498
|
+
warn: "\x1B[33m",
|
|
499
|
+
// yellow
|
|
500
|
+
error: "\x1B[31m",
|
|
501
|
+
// red
|
|
502
|
+
fatal: "\x1B[35m",
|
|
503
|
+
// magenta
|
|
504
|
+
// 추가 컬러
|
|
505
|
+
gray: "\x1B[90m"
|
|
506
|
+
};
|
|
507
|
+
function formatTimestampHuman(date) {
|
|
508
|
+
const year = date.getFullYear();
|
|
509
|
+
const month = String(date.getMonth() + 1).padStart(2, "0");
|
|
510
|
+
const day = String(date.getDate()).padStart(2, "0");
|
|
511
|
+
const hours = String(date.getHours()).padStart(2, "0");
|
|
512
|
+
const minutes = String(date.getMinutes()).padStart(2, "0");
|
|
513
|
+
const seconds = String(date.getSeconds()).padStart(2, "0");
|
|
514
|
+
const ms = String(date.getMilliseconds()).padStart(3, "0");
|
|
515
|
+
return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}.${ms}`;
|
|
516
|
+
}
|
|
517
|
+
function formatError(error) {
|
|
518
|
+
const lines = [];
|
|
519
|
+
lines.push(`${error.name}: ${error.message}`);
|
|
520
|
+
if (error.stack) {
|
|
521
|
+
const stackLines = error.stack.split("\n").slice(1);
|
|
522
|
+
lines.push(...stackLines);
|
|
523
|
+
}
|
|
524
|
+
if (error.cause instanceof Error) {
|
|
525
|
+
lines.push(`Caused by: ${formatError(error.cause)}`);
|
|
526
|
+
} else if (error.cause !== void 0) {
|
|
527
|
+
lines.push(`Caused by: ${String(error.cause)}`);
|
|
528
|
+
}
|
|
529
|
+
return lines.join("\n");
|
|
530
|
+
}
|
|
531
|
+
function formatConsole(metadata, colorize = true) {
|
|
532
|
+
const parts = [];
|
|
533
|
+
const timestamp = formatTimestampHuman(metadata.timestamp);
|
|
534
|
+
if (colorize) {
|
|
535
|
+
parts.push(`${COLORS.gray}[${timestamp}]${COLORS.reset}`);
|
|
536
|
+
} else {
|
|
537
|
+
parts.push(`[${timestamp}]`);
|
|
538
|
+
}
|
|
539
|
+
const pid = process.pid;
|
|
540
|
+
if (colorize) {
|
|
541
|
+
parts.push(`${COLORS.dim}[pid=${pid}]${COLORS.reset}`);
|
|
542
|
+
} else {
|
|
543
|
+
parts.push(`[pid=${pid}]`);
|
|
544
|
+
}
|
|
545
|
+
if (metadata.module) {
|
|
546
|
+
if (colorize) {
|
|
547
|
+
parts.push(`${COLORS.dim}[module=${metadata.module}]${COLORS.reset}`);
|
|
548
|
+
} else {
|
|
549
|
+
parts.push(`[module=${metadata.module}]`);
|
|
550
|
+
}
|
|
551
|
+
}
|
|
552
|
+
if (metadata.context && Object.keys(metadata.context).length > 0) {
|
|
553
|
+
Object.entries(metadata.context).forEach(([key, value]) => {
|
|
554
|
+
let valueStr;
|
|
555
|
+
if (typeof value === "string") {
|
|
556
|
+
valueStr = value;
|
|
557
|
+
} else if (typeof value === "object" && value !== null) {
|
|
558
|
+
try {
|
|
559
|
+
valueStr = JSON.stringify(value);
|
|
560
|
+
} catch (error) {
|
|
561
|
+
valueStr = "[circular]";
|
|
562
|
+
}
|
|
563
|
+
} else {
|
|
564
|
+
valueStr = String(value);
|
|
565
|
+
}
|
|
566
|
+
if (colorize) {
|
|
567
|
+
parts.push(`${COLORS.dim}[${key}=${valueStr}]${COLORS.reset}`);
|
|
568
|
+
} else {
|
|
569
|
+
parts.push(`[${key}=${valueStr}]`);
|
|
570
|
+
}
|
|
571
|
+
});
|
|
572
|
+
}
|
|
573
|
+
const levelStr = metadata.level.toUpperCase();
|
|
574
|
+
if (colorize) {
|
|
575
|
+
const color = COLORS[metadata.level];
|
|
576
|
+
parts.push(`${color}(${levelStr})${COLORS.reset}:`);
|
|
577
|
+
} else {
|
|
578
|
+
parts.push(`(${levelStr}):`);
|
|
579
|
+
}
|
|
580
|
+
if (colorize) {
|
|
581
|
+
parts.push(`${COLORS.bright}${metadata.message}${COLORS.reset}`);
|
|
582
|
+
} else {
|
|
583
|
+
parts.push(metadata.message);
|
|
584
|
+
}
|
|
585
|
+
let output = parts.join(" ");
|
|
586
|
+
if (metadata.error) {
|
|
587
|
+
output += "\n" + formatError(metadata.error);
|
|
588
|
+
}
|
|
589
|
+
return output;
|
|
590
|
+
}
|
|
591
|
+
|
|
592
|
+
// src/logger/logger.ts
|
|
593
|
+
var FORMAT_PATTERN = /%[sdifjoOc%]/;
|
|
594
|
+
var Logger = class _Logger {
|
|
595
|
+
config;
|
|
596
|
+
module;
|
|
597
|
+
constructor(config) {
|
|
598
|
+
this.config = config;
|
|
599
|
+
this.module = config.module;
|
|
600
|
+
}
|
|
601
|
+
/**
|
|
602
|
+
* Convert unknown error to Error object
|
|
603
|
+
*/
|
|
604
|
+
toError(error) {
|
|
605
|
+
if (error instanceof Error) return error;
|
|
606
|
+
if (typeof error === "string") return new Error(error);
|
|
607
|
+
if (typeof error === "object" && error !== null) {
|
|
608
|
+
return new Error(JSON.stringify(error));
|
|
609
|
+
}
|
|
610
|
+
return new Error(String(error));
|
|
611
|
+
}
|
|
612
|
+
/**
|
|
613
|
+
* Check if value is a context object (not an error)
|
|
614
|
+
*/
|
|
615
|
+
isContext(value) {
|
|
616
|
+
if (typeof value !== "object" || value === null) return false;
|
|
617
|
+
if (value instanceof Error) return false;
|
|
618
|
+
const hasStack = "stack" in value && typeof value.stack === "string";
|
|
619
|
+
if (hasStack) {
|
|
620
|
+
return false;
|
|
621
|
+
}
|
|
622
|
+
return true;
|
|
623
|
+
}
|
|
624
|
+
/**
|
|
625
|
+
* Get current log level
|
|
626
|
+
*/
|
|
627
|
+
get level() {
|
|
628
|
+
return this.config.level;
|
|
629
|
+
}
|
|
630
|
+
/**
|
|
631
|
+
* Create child logger (per module)
|
|
632
|
+
*/
|
|
633
|
+
child(module) {
|
|
634
|
+
return new _Logger({
|
|
635
|
+
...this.config,
|
|
636
|
+
module
|
|
637
|
+
});
|
|
638
|
+
}
|
|
639
|
+
/**
|
|
640
|
+
* Common log method with error/context detection
|
|
641
|
+
*/
|
|
642
|
+
logWithLevel(level, message, errorOrContext, context) {
|
|
643
|
+
if (errorOrContext !== void 0 && FORMAT_PATTERN.test(message)) {
|
|
644
|
+
this.log(level, format(message, errorOrContext), void 0, context);
|
|
645
|
+
return;
|
|
646
|
+
}
|
|
647
|
+
if (errorOrContext instanceof Error) {
|
|
648
|
+
this.log(level, message, errorOrContext, context);
|
|
649
|
+
} else if (errorOrContext !== void 0 && typeof errorOrContext === "object" && !this.isContext(errorOrContext)) {
|
|
650
|
+
this.log(level, message, this.toError(errorOrContext), context);
|
|
651
|
+
} else if (typeof errorOrContext === "string" || typeof errorOrContext === "number" || typeof errorOrContext === "boolean") {
|
|
652
|
+
this.log(level, message, this.toError(errorOrContext), context);
|
|
653
|
+
} else {
|
|
654
|
+
this.log(level, message, void 0, errorOrContext);
|
|
655
|
+
}
|
|
656
|
+
}
|
|
657
|
+
debug(message, errorOrContext, context) {
|
|
658
|
+
this.logWithLevel("debug", message, errorOrContext, context);
|
|
659
|
+
}
|
|
660
|
+
info(message, errorOrContext, context) {
|
|
661
|
+
this.logWithLevel("info", message, errorOrContext, context);
|
|
662
|
+
}
|
|
663
|
+
warn(message, errorOrContext, context) {
|
|
664
|
+
this.logWithLevel("warn", message, errorOrContext, context);
|
|
665
|
+
}
|
|
666
|
+
error(message, errorOrContext, context) {
|
|
667
|
+
this.logWithLevel("error", message, errorOrContext, context);
|
|
668
|
+
}
|
|
669
|
+
fatal(message, errorOrContext, context) {
|
|
670
|
+
this.logWithLevel("fatal", message, errorOrContext, context);
|
|
671
|
+
}
|
|
672
|
+
/**
|
|
673
|
+
* Log processing (internal)
|
|
674
|
+
*/
|
|
675
|
+
log(level, message, error, context) {
|
|
676
|
+
if (LOG_LEVEL_PRIORITY[level] < LOG_LEVEL_PRIORITY[this.config.level]) {
|
|
677
|
+
return;
|
|
678
|
+
}
|
|
679
|
+
const metadata = {
|
|
680
|
+
timestamp: /* @__PURE__ */ new Date(),
|
|
681
|
+
level,
|
|
682
|
+
message,
|
|
683
|
+
module: this.module,
|
|
684
|
+
error,
|
|
685
|
+
// Mask sensitive information in context to prevent credential leaks
|
|
686
|
+
context: context ? maskSensitiveData(context) : void 0
|
|
687
|
+
};
|
|
688
|
+
this.processTransports(metadata);
|
|
689
|
+
}
|
|
690
|
+
/**
|
|
691
|
+
* Process Transports
|
|
692
|
+
*/
|
|
693
|
+
processTransports(metadata) {
|
|
694
|
+
const promises = this.config.transports.filter((transport) => transport.enabled).map((transport) => this.safeTransportLog(transport, metadata));
|
|
695
|
+
Promise.all(promises).catch((error) => {
|
|
696
|
+
const errorMessage = error instanceof Error ? error.message : String(error);
|
|
697
|
+
process.stderr.write(`[Logger] Transport error: ${errorMessage}
|
|
698
|
+
`);
|
|
699
|
+
});
|
|
700
|
+
}
|
|
701
|
+
/**
|
|
702
|
+
* Transport log (error-safe)
|
|
703
|
+
*/
|
|
704
|
+
async safeTransportLog(transport, metadata) {
|
|
705
|
+
try {
|
|
706
|
+
await transport.log(metadata);
|
|
707
|
+
} catch (error) {
|
|
708
|
+
const errorMessage = error instanceof Error ? error.message : String(error);
|
|
709
|
+
process.stderr.write(`[Logger] Transport "${transport.name}" failed: ${errorMessage}
|
|
710
|
+
`);
|
|
711
|
+
}
|
|
712
|
+
}
|
|
713
|
+
/**
|
|
714
|
+
* Close all Transports
|
|
715
|
+
*/
|
|
716
|
+
async close() {
|
|
717
|
+
const closePromises = this.config.transports.filter((transport) => transport.close).map((transport) => transport.close());
|
|
718
|
+
await Promise.all(closePromises);
|
|
719
|
+
}
|
|
720
|
+
};
|
|
721
|
+
|
|
722
|
+
// src/logger/transports/console.ts
|
|
723
|
+
var ConsoleTransport = class {
|
|
724
|
+
name = "console";
|
|
725
|
+
level;
|
|
726
|
+
enabled;
|
|
727
|
+
colorize;
|
|
728
|
+
constructor(config) {
|
|
729
|
+
this.level = config.level;
|
|
730
|
+
this.enabled = config.enabled;
|
|
731
|
+
this.colorize = config.colorize ?? true;
|
|
732
|
+
}
|
|
733
|
+
async log(metadata) {
|
|
734
|
+
if (!this.enabled) {
|
|
735
|
+
return;
|
|
736
|
+
}
|
|
737
|
+
if (LOG_LEVEL_PRIORITY[metadata.level] < LOG_LEVEL_PRIORITY[this.level]) {
|
|
738
|
+
return;
|
|
739
|
+
}
|
|
740
|
+
const message = formatConsole(metadata, this.colorize);
|
|
741
|
+
if (metadata.level === "warn" || metadata.level === "error" || metadata.level === "fatal") {
|
|
742
|
+
console.error(message);
|
|
743
|
+
} else {
|
|
744
|
+
console.log(message);
|
|
745
|
+
}
|
|
746
|
+
}
|
|
747
|
+
};
|
|
748
|
+
|
|
749
|
+
// src/logger/config.ts
|
|
750
|
+
function getConsoleConfig() {
|
|
751
|
+
const isProduction = process.env.NODE_ENV === "production";
|
|
752
|
+
return {
|
|
753
|
+
level: "debug",
|
|
754
|
+
enabled: true,
|
|
755
|
+
colorize: !isProduction
|
|
756
|
+
// Dev: colored output, Production: plain text
|
|
757
|
+
};
|
|
758
|
+
}
|
|
759
|
+
function validateEnvironment() {
|
|
760
|
+
const nodeEnv = process.env.NODE_ENV;
|
|
761
|
+
if (!nodeEnv) {
|
|
762
|
+
process.stderr.write(
|
|
763
|
+
"[Logger] Warning: NODE_ENV is not set. Defaulting to test environment.\n"
|
|
764
|
+
);
|
|
765
|
+
}
|
|
766
|
+
}
|
|
767
|
+
function validateConfig() {
|
|
768
|
+
validateEnvironment();
|
|
769
|
+
}
|
|
770
|
+
|
|
771
|
+
// src/logger/factory.ts
|
|
772
|
+
function initializeTransports() {
|
|
773
|
+
const transports = [];
|
|
774
|
+
const consoleConfig = getConsoleConfig();
|
|
775
|
+
transports.push(new ConsoleTransport(consoleConfig));
|
|
776
|
+
return transports;
|
|
777
|
+
}
|
|
778
|
+
function getLogLevel() {
|
|
779
|
+
const envLevel = process.env.SPFN_LOG_LEVEL || process.env.NEXT_PUBLIC_SPFN_LOG_LEVEL || "info";
|
|
780
|
+
if (envLevel in LOG_LEVEL_PRIORITY) {
|
|
781
|
+
return envLevel;
|
|
782
|
+
}
|
|
783
|
+
process.stderr.write(
|
|
784
|
+
`[Logger] Invalid log level "${envLevel}", defaulting to "info"
|
|
785
|
+
`
|
|
786
|
+
);
|
|
787
|
+
return "info";
|
|
788
|
+
}
|
|
789
|
+
function initializeLogger() {
|
|
790
|
+
validateConfig();
|
|
791
|
+
return new Logger({
|
|
792
|
+
level: getLogLevel(),
|
|
793
|
+
transports: initializeTransports()
|
|
794
|
+
});
|
|
795
|
+
}
|
|
796
|
+
var logger4 = initializeLogger();
|
|
797
|
+
|
|
798
|
+
// src/errors/serializable-error.ts
|
|
799
|
+
var RESERVED_RESPONSE_KEYS = /* @__PURE__ */ new Set(["__type", "message", "error"]);
|
|
800
|
+
var AUTHORING_ENVIRONMENTS = /* @__PURE__ */ new Set(["local", "development", "test"]);
|
|
801
|
+
function refuseReservedKey(className, key) {
|
|
802
|
+
const detail = `${className} declares the reserved field "${key}". Reserved response keys: ${[...RESERVED_RESPONSE_KEYS].join(", ")}. Rename the field.`;
|
|
803
|
+
if (AUTHORING_ENVIRONMENTS.has(process.env.NODE_ENV ?? "local")) {
|
|
804
|
+
throw new Error(detail);
|
|
805
|
+
}
|
|
806
|
+
logger4.error(`[SerializableError] ${detail} The field is omitted from the response.`);
|
|
807
|
+
}
|
|
808
|
+
var SerializableError2 = class extends Error {
|
|
809
|
+
/**
|
|
810
|
+
* Serialize error to JSON-compatible object
|
|
811
|
+
*
|
|
812
|
+
* Automatically includes:
|
|
813
|
+
* - __type: Constructor name for deserialization
|
|
814
|
+
* - message: Error message
|
|
815
|
+
* - All public instance properties (except name, stack)
|
|
816
|
+
*/
|
|
817
|
+
toJSON() {
|
|
818
|
+
const json = {
|
|
819
|
+
__type: this.constructor.name,
|
|
820
|
+
message: this.message
|
|
821
|
+
};
|
|
822
|
+
for (const key of Object.keys(this)) {
|
|
823
|
+
if (key === "name" || key === "stack" || key === "statusCode") {
|
|
824
|
+
continue;
|
|
825
|
+
}
|
|
826
|
+
if (RESERVED_RESPONSE_KEYS.has(key)) {
|
|
827
|
+
refuseReservedKey(this.constructor.name, key);
|
|
828
|
+
continue;
|
|
829
|
+
}
|
|
830
|
+
json[key] = this[key];
|
|
831
|
+
}
|
|
832
|
+
return json;
|
|
833
|
+
}
|
|
834
|
+
};
|
|
835
|
+
|
|
836
|
+
// src/errors/http-errors.ts
|
|
837
|
+
var HttpError = class extends SerializableError2 {
|
|
838
|
+
statusCode;
|
|
839
|
+
details;
|
|
840
|
+
constructor(data) {
|
|
841
|
+
super(data.message);
|
|
842
|
+
this.name = "HttpError";
|
|
843
|
+
this.statusCode = data.statusCode;
|
|
844
|
+
if (data.details) {
|
|
845
|
+
this.details = data.details;
|
|
846
|
+
}
|
|
847
|
+
Error.captureStackTrace(this, this.constructor);
|
|
848
|
+
}
|
|
849
|
+
};
|
|
850
|
+
var BadRequestError = class extends HttpError {
|
|
851
|
+
constructor(data = {}) {
|
|
852
|
+
super({
|
|
853
|
+
message: data.message || "Bad request",
|
|
854
|
+
statusCode: 400,
|
|
855
|
+
details: data.details
|
|
856
|
+
});
|
|
857
|
+
this.name = "BadRequestError";
|
|
858
|
+
}
|
|
859
|
+
};
|
|
860
|
+
var ValidationError = class extends HttpError {
|
|
861
|
+
fields;
|
|
862
|
+
constructor(data) {
|
|
863
|
+
super({
|
|
864
|
+
message: data.message,
|
|
865
|
+
statusCode: 400,
|
|
866
|
+
details: data.details
|
|
867
|
+
});
|
|
868
|
+
this.name = "ValidationError";
|
|
869
|
+
if (data.fields) {
|
|
870
|
+
this.fields = data.fields;
|
|
871
|
+
}
|
|
872
|
+
}
|
|
873
|
+
};
|
|
874
|
+
var UnauthorizedError = class extends HttpError {
|
|
875
|
+
constructor(data = {}) {
|
|
876
|
+
super({
|
|
877
|
+
message: data.message || "Authentication required",
|
|
878
|
+
statusCode: 401,
|
|
879
|
+
details: data.details
|
|
880
|
+
});
|
|
881
|
+
this.name = "UnauthorizedError";
|
|
882
|
+
}
|
|
883
|
+
};
|
|
884
|
+
var ForbiddenError = class extends HttpError {
|
|
885
|
+
constructor(data = {}) {
|
|
886
|
+
super({
|
|
887
|
+
message: data.message || "Access forbidden",
|
|
888
|
+
statusCode: 403,
|
|
889
|
+
details: data.details
|
|
890
|
+
});
|
|
891
|
+
this.name = "ForbiddenError";
|
|
892
|
+
}
|
|
893
|
+
};
|
|
894
|
+
var NotFoundError = class extends HttpError {
|
|
895
|
+
resource;
|
|
896
|
+
constructor(data = {}) {
|
|
897
|
+
super({
|
|
898
|
+
message: data.message || "Resource not found",
|
|
899
|
+
statusCode: 404,
|
|
900
|
+
details: data.details
|
|
901
|
+
});
|
|
902
|
+
this.name = "NotFoundError";
|
|
903
|
+
if (data.resource) {
|
|
904
|
+
this.resource = data.resource;
|
|
905
|
+
}
|
|
906
|
+
}
|
|
907
|
+
};
|
|
908
|
+
var ConflictError = class extends HttpError {
|
|
909
|
+
constructor(data = {}) {
|
|
910
|
+
super({
|
|
911
|
+
message: data.message || "Resource conflict",
|
|
912
|
+
statusCode: 409,
|
|
913
|
+
details: data.details
|
|
914
|
+
});
|
|
915
|
+
this.name = "ConflictError";
|
|
916
|
+
}
|
|
917
|
+
};
|
|
918
|
+
var GoneError = class extends HttpError {
|
|
919
|
+
resource;
|
|
920
|
+
constructor(data = {}) {
|
|
921
|
+
super({
|
|
922
|
+
message: data.message || "Resource permanently deleted",
|
|
923
|
+
statusCode: 410,
|
|
924
|
+
details: data.details
|
|
925
|
+
});
|
|
926
|
+
this.name = "GoneError";
|
|
927
|
+
if (data.resource) {
|
|
928
|
+
this.resource = data.resource;
|
|
929
|
+
}
|
|
930
|
+
}
|
|
931
|
+
};
|
|
932
|
+
var TooManyRequestsError = class extends HttpError {
|
|
933
|
+
retryAfter;
|
|
934
|
+
constructor(data = {}) {
|
|
935
|
+
super({
|
|
936
|
+
message: data.message || "Too many requests",
|
|
937
|
+
statusCode: 429,
|
|
938
|
+
details: data.details
|
|
939
|
+
});
|
|
940
|
+
this.name = "TooManyRequestsError";
|
|
941
|
+
if (data.retryAfter) {
|
|
942
|
+
this.retryAfter = data.retryAfter;
|
|
943
|
+
}
|
|
944
|
+
}
|
|
945
|
+
};
|
|
946
|
+
var InternalServerError = class extends HttpError {
|
|
947
|
+
constructor(data = {}) {
|
|
948
|
+
super({
|
|
949
|
+
message: data.message || "Internal server error",
|
|
950
|
+
statusCode: 500,
|
|
951
|
+
details: data.details
|
|
952
|
+
});
|
|
953
|
+
this.name = "InternalServerError";
|
|
954
|
+
}
|
|
955
|
+
};
|
|
956
|
+
var UnsupportedMediaTypeError = class extends HttpError {
|
|
957
|
+
mediaType;
|
|
958
|
+
supportedTypes;
|
|
959
|
+
constructor(data = {}) {
|
|
960
|
+
super({
|
|
961
|
+
message: data.message || "Unsupported media type",
|
|
962
|
+
statusCode: 415,
|
|
963
|
+
details: data.details
|
|
964
|
+
});
|
|
965
|
+
this.name = "UnsupportedMediaTypeError";
|
|
966
|
+
if (data.mediaType) {
|
|
967
|
+
this.mediaType = data.mediaType;
|
|
968
|
+
}
|
|
969
|
+
if (data.supportedTypes) {
|
|
970
|
+
this.supportedTypes = data.supportedTypes;
|
|
971
|
+
}
|
|
972
|
+
}
|
|
973
|
+
};
|
|
974
|
+
var UnprocessableEntityError = class extends HttpError {
|
|
975
|
+
constructor(data = {}) {
|
|
976
|
+
super({
|
|
977
|
+
message: data.message || "Unprocessable entity",
|
|
978
|
+
statusCode: 422,
|
|
979
|
+
details: data.details
|
|
980
|
+
});
|
|
981
|
+
this.name = "UnprocessableEntityError";
|
|
982
|
+
}
|
|
983
|
+
};
|
|
984
|
+
var ServiceUnavailableError = class extends HttpError {
|
|
985
|
+
retryAfter;
|
|
986
|
+
constructor(data = {}) {
|
|
987
|
+
super({
|
|
988
|
+
message: data.message || "Service unavailable",
|
|
989
|
+
statusCode: 503,
|
|
990
|
+
details: data.details
|
|
991
|
+
});
|
|
992
|
+
this.name = "ServiceUnavailableError";
|
|
993
|
+
if (data.retryAfter) {
|
|
994
|
+
this.retryAfter = data.retryAfter;
|
|
995
|
+
}
|
|
996
|
+
}
|
|
997
|
+
};
|
|
998
|
+
|
|
999
|
+
// src/errors/database-errors.ts
|
|
1000
|
+
var DatabaseError = class extends SerializableError2 {
|
|
1001
|
+
statusCode;
|
|
1002
|
+
details;
|
|
1003
|
+
constructor(data) {
|
|
1004
|
+
super(data.message);
|
|
1005
|
+
this.name = "DatabaseError";
|
|
1006
|
+
this.statusCode = data.statusCode ?? 500;
|
|
1007
|
+
this.details = data.details;
|
|
1008
|
+
Error.captureStackTrace(this, this.constructor);
|
|
1009
|
+
}
|
|
1010
|
+
/**
|
|
1011
|
+
* Whether this error's message/details are derived from the raw database
|
|
1012
|
+
* driver (SQL text, table/column/constraint names, parameter values) and
|
|
1013
|
+
* therefore must NOT be exposed to clients in production. Defined as a
|
|
1014
|
+
* prototype getter so it is never serialized into the response by toJSON().
|
|
1015
|
+
* Subclasses with a safe, constructed message override this to `false`.
|
|
1016
|
+
*/
|
|
1017
|
+
get internal() {
|
|
1018
|
+
return true;
|
|
1019
|
+
}
|
|
1020
|
+
};
|
|
1021
|
+
var ConnectionError = class extends DatabaseError {
|
|
1022
|
+
constructor(data) {
|
|
1023
|
+
super({ message: data.message, statusCode: 503, details: data.details });
|
|
1024
|
+
this.name = "ConnectionError";
|
|
1025
|
+
}
|
|
1026
|
+
};
|
|
1027
|
+
var QueryError = class extends DatabaseError {
|
|
1028
|
+
constructor(data) {
|
|
1029
|
+
super({
|
|
1030
|
+
message: data.message,
|
|
1031
|
+
statusCode: data.statusCode ?? 500,
|
|
1032
|
+
details: data.details
|
|
1033
|
+
});
|
|
1034
|
+
this.name = "QueryError";
|
|
1035
|
+
}
|
|
1036
|
+
};
|
|
1037
|
+
var EntityNotFoundError = class extends QueryError {
|
|
1038
|
+
resource;
|
|
1039
|
+
id;
|
|
1040
|
+
constructor(data) {
|
|
1041
|
+
super({
|
|
1042
|
+
message: `${data.resource} with id ${data.id} not found`,
|
|
1043
|
+
statusCode: 404,
|
|
1044
|
+
details: { resource: data.resource, id: data.id }
|
|
1045
|
+
});
|
|
1046
|
+
this.name = "EntityNotFoundError";
|
|
1047
|
+
this.resource = data.resource;
|
|
1048
|
+
this.id = data.id;
|
|
1049
|
+
}
|
|
1050
|
+
// Message/details are constructed from the resource + id, not driver text
|
|
1051
|
+
get internal() {
|
|
1052
|
+
return false;
|
|
1053
|
+
}
|
|
1054
|
+
};
|
|
1055
|
+
var ConstraintViolationError = class extends QueryError {
|
|
1056
|
+
constructor(data) {
|
|
1057
|
+
super({ message: data.message, statusCode: 400, details: data.details });
|
|
1058
|
+
this.name = "ConstraintViolationError";
|
|
1059
|
+
}
|
|
1060
|
+
};
|
|
1061
|
+
var TransactionError = class extends DatabaseError {
|
|
1062
|
+
constructor(data) {
|
|
1063
|
+
super({
|
|
1064
|
+
message: data.message,
|
|
1065
|
+
statusCode: data.statusCode ?? 500,
|
|
1066
|
+
details: data.details
|
|
1067
|
+
});
|
|
1068
|
+
this.name = "TransactionError";
|
|
1069
|
+
}
|
|
1070
|
+
};
|
|
1071
|
+
var DeadlockError = class extends TransactionError {
|
|
1072
|
+
constructor(data) {
|
|
1073
|
+
super({ message: data.message, statusCode: 409, details: data.details });
|
|
1074
|
+
this.name = "DeadlockError";
|
|
1075
|
+
}
|
|
1076
|
+
};
|
|
1077
|
+
var DuplicateEntryError = class extends QueryError {
|
|
1078
|
+
field;
|
|
1079
|
+
value;
|
|
1080
|
+
constructor(data) {
|
|
1081
|
+
super({
|
|
1082
|
+
message: `${data.field} already exists`,
|
|
1083
|
+
statusCode: 409,
|
|
1084
|
+
details: { field: data.field }
|
|
1085
|
+
});
|
|
1086
|
+
this.name = "DuplicateEntryError";
|
|
1087
|
+
this.field = data.field;
|
|
1088
|
+
this.value = data.value;
|
|
1089
|
+
}
|
|
1090
|
+
// Field-only message/details — safe to surface to the client (not internal)
|
|
1091
|
+
get internal() {
|
|
1092
|
+
return false;
|
|
1093
|
+
}
|
|
1094
|
+
};
|
|
1095
|
+
|
|
1096
|
+
// src/errors/index.ts
|
|
1097
|
+
var errorRegistry = new ErrorRegistry();
|
|
1098
|
+
errorRegistry.append([
|
|
1099
|
+
HttpError,
|
|
1100
|
+
BadRequestError,
|
|
1101
|
+
ValidationError,
|
|
1102
|
+
UnauthorizedError,
|
|
1103
|
+
ForbiddenError,
|
|
1104
|
+
NotFoundError,
|
|
1105
|
+
ConflictError,
|
|
1106
|
+
GoneError,
|
|
1107
|
+
TooManyRequestsError,
|
|
1108
|
+
UnsupportedMediaTypeError,
|
|
1109
|
+
UnprocessableEntityError,
|
|
1110
|
+
InternalServerError,
|
|
1111
|
+
ServiceUnavailableError
|
|
1112
|
+
]);
|
|
1113
|
+
errorRegistry.append([
|
|
1114
|
+
DatabaseError,
|
|
1115
|
+
ConnectionError,
|
|
1116
|
+
QueryError,
|
|
1117
|
+
EntityNotFoundError,
|
|
1118
|
+
ConstraintViolationError,
|
|
1119
|
+
TransactionError,
|
|
1120
|
+
DeadlockError,
|
|
1121
|
+
DuplicateEntryError
|
|
1122
|
+
]);
|
|
1123
|
+
|
|
1124
|
+
// src/middleware/rate-limit-store.ts
|
|
1125
|
+
var FIXED_WINDOW_LUA = `
|
|
1126
|
+
local count = redis.call('INCR', KEYS[1])
|
|
1127
|
+
if count == 1 then
|
|
1128
|
+
redis.call('PEXPIRE', KEYS[1], ARGV[1])
|
|
1129
|
+
end
|
|
1130
|
+
return { count, redis.call('PTTL', KEYS[1]) }
|
|
1131
|
+
`;
|
|
1132
|
+
var CacheRateLimitStore = class {
|
|
1133
|
+
constructor(cache) {
|
|
1134
|
+
this.cache = cache;
|
|
1135
|
+
}
|
|
1136
|
+
async hit(key, windowMs) {
|
|
1137
|
+
const [count, pttl] = await this.cache.eval(
|
|
1138
|
+
FIXED_WINDOW_LUA,
|
|
1139
|
+
1,
|
|
1140
|
+
key,
|
|
1141
|
+
String(windowMs)
|
|
1142
|
+
);
|
|
1143
|
+
return { count, pttl };
|
|
1144
|
+
}
|
|
1145
|
+
};
|
|
1146
|
+
var MemoryRateLimitStore = class {
|
|
1147
|
+
constructor(maxKeys = 1e4) {
|
|
1148
|
+
this.maxKeys = maxKeys;
|
|
1149
|
+
}
|
|
1150
|
+
windows = /* @__PURE__ */ new Map();
|
|
1151
|
+
/** How many live windows were dropped to stay under `maxKeys`. */
|
|
1152
|
+
evicted = 0;
|
|
1153
|
+
async hit(key, windowMs) {
|
|
1154
|
+
const now = Date.now();
|
|
1155
|
+
const existing = this.windows.get(key);
|
|
1156
|
+
if (existing !== void 0 && existing.expiresAt > now) {
|
|
1157
|
+
existing.count += 1;
|
|
1158
|
+
return { count: existing.count, pttl: existing.expiresAt - now };
|
|
1159
|
+
}
|
|
1160
|
+
if (this.windows.size >= this.maxKeys) {
|
|
1161
|
+
this.makeRoom(now);
|
|
1162
|
+
}
|
|
1163
|
+
this.windows.set(key, { count: 1, expiresAt: now + windowMs });
|
|
1164
|
+
return { count: 1, pttl: windowMs };
|
|
1165
|
+
}
|
|
1166
|
+
/** Drops every window that has already reset. */
|
|
1167
|
+
prune(nowMillis) {
|
|
1168
|
+
for (const [key, window] of this.windows) {
|
|
1169
|
+
if (window.expiresAt <= nowMillis) {
|
|
1170
|
+
this.windows.delete(key);
|
|
1171
|
+
}
|
|
1172
|
+
}
|
|
1173
|
+
}
|
|
1174
|
+
/**
|
|
1175
|
+
* Frees a slot for a new key.
|
|
1176
|
+
*
|
|
1177
|
+
* Expired windows go first. If every window is still live the oldest one is
|
|
1178
|
+
* dropped, because a hard bound is the only thing standing between a
|
|
1179
|
+
* per-IP limiter and unbounded memory. A dropped window loses its count,
|
|
1180
|
+
* so a caller who can mint `maxKeys` distinct identities can push another
|
|
1181
|
+
* one out — which is why `evictionCount` is worth watching: it says this
|
|
1182
|
+
* process is past what an in-memory limiter should be asked to hold, and
|
|
1183
|
+
* the deployment wants a real cache.
|
|
1184
|
+
*/
|
|
1185
|
+
makeRoom(nowMillis) {
|
|
1186
|
+
this.prune(nowMillis);
|
|
1187
|
+
if (this.windows.size < this.maxKeys) {
|
|
1188
|
+
return;
|
|
1189
|
+
}
|
|
1190
|
+
const oldest = this.windows.keys().next();
|
|
1191
|
+
if (!oldest.done) {
|
|
1192
|
+
this.windows.delete(oldest.value);
|
|
1193
|
+
this.evicted += 1;
|
|
1194
|
+
}
|
|
1195
|
+
}
|
|
1196
|
+
get size() {
|
|
1197
|
+
return this.windows.size;
|
|
1198
|
+
}
|
|
1199
|
+
/** Live windows dropped for capacity — nonzero means the bound is binding. */
|
|
1200
|
+
get evictionCount() {
|
|
1201
|
+
return this.evicted;
|
|
1202
|
+
}
|
|
1203
|
+
clear() {
|
|
1204
|
+
this.windows.clear();
|
|
1205
|
+
this.evicted = 0;
|
|
1206
|
+
}
|
|
1207
|
+
};
|
|
1208
|
+
|
|
1209
|
+
// src/middleware/rate-limit.ts
|
|
1210
|
+
var rateLimitLogger = logger4.child("@spfn/core:rate-limit");
|
|
1211
|
+
var memoryStore = new MemoryRateLimitStore();
|
|
1212
|
+
function resetMemoryRateLimitStore() {
|
|
1213
|
+
memoryStore.clear();
|
|
1214
|
+
}
|
|
1215
|
+
function getClientIp(c) {
|
|
1216
|
+
const clientType = c.get("clientType");
|
|
1217
|
+
if (clientType && clientType !== "untrusted") {
|
|
1218
|
+
const forwarded = c.req.header(PROXY_CLIENT_IP_HEADER);
|
|
1219
|
+
if (forwarded) {
|
|
1220
|
+
return forwarded;
|
|
1221
|
+
}
|
|
1222
|
+
}
|
|
1223
|
+
const forwardedFor = c.req.header("x-forwarded-for");
|
|
1224
|
+
return forwardedFor?.split(",")[0]?.trim() || c.req.header("x-real-ip") || socketRemoteAddress(c) || "unknown";
|
|
1225
|
+
}
|
|
1226
|
+
function socketRemoteAddress(c) {
|
|
1227
|
+
const env4 = c.env;
|
|
1228
|
+
const bindings = env4?.server ?? env4;
|
|
1229
|
+
return bindings?.incoming?.socket?.remoteAddress;
|
|
1230
|
+
}
|
|
1231
|
+
function selectStore(failClosed, message, path) {
|
|
1232
|
+
const cache = getCache();
|
|
1233
|
+
if (cache && !isCacheDisabled()) {
|
|
1234
|
+
return new CacheRateLimitStore(cache);
|
|
1235
|
+
}
|
|
1236
|
+
if (failClosed) {
|
|
1237
|
+
throw new TooManyRequestsError({ message: message || "Rate limiter unavailable" });
|
|
1238
|
+
}
|
|
1239
|
+
rateLimitLogger.debug("No cache \u2014 counting rate limits in this process", { path });
|
|
1240
|
+
return memoryStore;
|
|
1241
|
+
}
|
|
1242
|
+
async function hitWithFallback(store, key, windowMs, failClosed, message, path) {
|
|
1243
|
+
try {
|
|
1244
|
+
return await store.hit(key, windowMs);
|
|
1245
|
+
} catch (error) {
|
|
1246
|
+
if (failClosed) {
|
|
1247
|
+
throw new TooManyRequestsError({ message: message || "Rate limiter unavailable" });
|
|
1248
|
+
}
|
|
1249
|
+
rateLimitLogger.warn("Cache failed \u2014 counting this rate limit in the process instead", {
|
|
1250
|
+
path,
|
|
1251
|
+
error: error instanceof Error ? error.message : String(error)
|
|
1252
|
+
});
|
|
1253
|
+
return memoryStore.hit(key, windowMs);
|
|
1254
|
+
}
|
|
1255
|
+
}
|
|
1256
|
+
var rateLimit = defineMiddlewareFactory(
|
|
1257
|
+
"rateLimit",
|
|
1258
|
+
(options) => {
|
|
1259
|
+
const { limit, windowMs, scope, by, failClosed = false, message } = options;
|
|
1260
|
+
return async (c, next) => {
|
|
1261
|
+
const store = selectStore(failClosed, message, c.req.path);
|
|
1262
|
+
const dimensions = (by ? await by(c) : [getClientIp(c)]).filter((d) => Boolean(d));
|
|
1263
|
+
const ns = scope || `${c.req.method} ${c.req.routePath || c.req.path}`;
|
|
1264
|
+
for (const dimension of dimensions) {
|
|
1265
|
+
const key = typeof dimension === "string" ? dimension : dimension.key;
|
|
1266
|
+
if (!key) {
|
|
1267
|
+
continue;
|
|
1268
|
+
}
|
|
1269
|
+
const dimLimit = typeof dimension === "string" ? limit : dimension.limit ?? limit;
|
|
1270
|
+
const { count, pttl } = await hitWithFallback(
|
|
1271
|
+
store,
|
|
1272
|
+
`ratelimit:${ns}:${key}`,
|
|
1273
|
+
windowMs,
|
|
1274
|
+
failClosed,
|
|
1275
|
+
message,
|
|
1276
|
+
c.req.path
|
|
1277
|
+
);
|
|
1278
|
+
if (count > dimLimit) {
|
|
1279
|
+
const retryAfter = Math.max(1, Math.ceil((pttl > 0 ? pttl : windowMs) / 1e3));
|
|
1280
|
+
c.header("Retry-After", String(retryAfter));
|
|
1281
|
+
throw new TooManyRequestsError({
|
|
1282
|
+
message: message || "Too many requests, please try again later",
|
|
1283
|
+
retryAfter
|
|
1284
|
+
});
|
|
1285
|
+
}
|
|
1286
|
+
}
|
|
1287
|
+
return next();
|
|
1288
|
+
};
|
|
1289
|
+
}
|
|
1290
|
+
);
|
|
1291
|
+
var policyRegistry = /* @__PURE__ */ new Map();
|
|
1292
|
+
var policyFailClosedDefault = false;
|
|
1293
|
+
function setRateLimitFailClosedDefault(failClosed) {
|
|
1294
|
+
policyFailClosedDefault = failClosed;
|
|
1295
|
+
}
|
|
1296
|
+
function setRateLimitPolicies(policies) {
|
|
1297
|
+
policyRegistry.clear();
|
|
1298
|
+
if (!policies) {
|
|
1299
|
+
return;
|
|
1300
|
+
}
|
|
1301
|
+
for (const [name, options] of Object.entries(policies)) {
|
|
1302
|
+
policyRegistry.set(name, options);
|
|
1303
|
+
}
|
|
1304
|
+
}
|
|
1305
|
+
function getRateLimitPolicy(name) {
|
|
1306
|
+
return policyRegistry.get(name);
|
|
1307
|
+
}
|
|
1308
|
+
function rateLimitPolicy(name, fallback) {
|
|
1309
|
+
let resolved;
|
|
1310
|
+
const handler = (c, next) => {
|
|
1311
|
+
if (!resolved) {
|
|
1312
|
+
const configured = getRateLimitPolicy(name);
|
|
1313
|
+
const merged = configured ? { ...fallback, ...configured } : { ...fallback };
|
|
1314
|
+
if (merged.scope === void 0) {
|
|
1315
|
+
merged.scope = name;
|
|
1316
|
+
}
|
|
1317
|
+
if (merged.failClosed === void 0) {
|
|
1318
|
+
merged.failClosed = policyFailClosedDefault;
|
|
1319
|
+
}
|
|
1320
|
+
resolved = rateLimit(merged);
|
|
1321
|
+
}
|
|
1322
|
+
return resolved(c, next);
|
|
61
1323
|
};
|
|
1324
|
+
return defineMiddleware(`rateLimit:${name}`, handler);
|
|
62
1325
|
}
|
|
1326
|
+
|
|
1327
|
+
// src/middleware/request-logger.ts
|
|
63
1328
|
var DEFAULT_CONFIG = {
|
|
64
1329
|
excludePaths: ["/health", "/ping", "/favicon.ico"],
|
|
65
1330
|
sensitiveFields: ["password", "token", "apiKey", "secret", "authorization"],
|
|
@@ -70,7 +1335,7 @@ function generateRequestId() {
|
|
|
70
1335
|
const randomPart = randomBytes(6).toString("hex");
|
|
71
1336
|
return `req_${timestamp}_${randomPart}`;
|
|
72
1337
|
}
|
|
73
|
-
function
|
|
1338
|
+
function maskSensitiveData2(obj, sensitiveFields, seen = /* @__PURE__ */ new WeakSet()) {
|
|
74
1339
|
if (!obj || typeof obj !== "object") return obj;
|
|
75
1340
|
if (seen.has(obj)) return "[Circular]";
|
|
76
1341
|
seen.add(obj);
|
|
@@ -81,7 +1346,7 @@ function maskSensitiveData(obj, sensitiveFields, seen = /* @__PURE__ */ new Weak
|
|
|
81
1346
|
if (lowerFields.some((field) => lowerKey.includes(field))) {
|
|
82
1347
|
masked[key] = "***MASKED***";
|
|
83
1348
|
} else if (typeof masked[key] === "object" && masked[key] !== null) {
|
|
84
|
-
masked[key] =
|
|
1349
|
+
masked[key] = maskSensitiveData2(masked[key], sensitiveFields, seen);
|
|
85
1350
|
}
|
|
86
1351
|
}
|
|
87
1352
|
return masked;
|
|
@@ -101,8 +1366,7 @@ function RequestLogger(options) {
|
|
|
101
1366
|
c.set("requestId", requestId);
|
|
102
1367
|
const method = c.req.method;
|
|
103
1368
|
const userAgent = c.req.header("user-agent");
|
|
104
|
-
const
|
|
105
|
-
const ip = forwardedFor?.split(",")[0]?.trim() || c.req.header("x-real-ip") || "unknown";
|
|
1369
|
+
const ip = getClientIp(c);
|
|
106
1370
|
const startTime = Date.now();
|
|
107
1371
|
apiLogger.info("Request received", {
|
|
108
1372
|
requestId,
|
|
@@ -134,7 +1398,7 @@ function RequestLogger(options) {
|
|
|
134
1398
|
if (["POST", "PUT", "PATCH"].includes(method)) {
|
|
135
1399
|
try {
|
|
136
1400
|
const requestBody = await c.req.json();
|
|
137
|
-
logData.request =
|
|
1401
|
+
logData.request = maskSensitiveData2(requestBody, cfg.sensitiveFields);
|
|
138
1402
|
} catch {
|
|
139
1403
|
}
|
|
140
1404
|
}
|
|
@@ -153,7 +1417,190 @@ function RequestLogger(options) {
|
|
|
153
1417
|
}
|
|
154
1418
|
};
|
|
155
1419
|
}
|
|
1420
|
+
var guardLogger = logger.child("@spfn/core:proxy-guard");
|
|
1421
|
+
var BODY_OVERSIZE = Symbol("proxy-guard:body-oversize");
|
|
1422
|
+
var BODY_READ_ERROR = Symbol("proxy-guard:body-read-error");
|
|
1423
|
+
async function readRawBody(c, maxBytes) {
|
|
1424
|
+
const method = c.req.method;
|
|
1425
|
+
if (method === "GET" || method === "HEAD") {
|
|
1426
|
+
return void 0;
|
|
1427
|
+
}
|
|
1428
|
+
const contentType = c.req.header("content-type") || "";
|
|
1429
|
+
if (contentType.includes("multipart/form-data")) {
|
|
1430
|
+
return void 0;
|
|
1431
|
+
}
|
|
1432
|
+
const stream = c.req.raw.clone().body;
|
|
1433
|
+
if (!stream) {
|
|
1434
|
+
return void 0;
|
|
1435
|
+
}
|
|
1436
|
+
const reader = stream.getReader();
|
|
1437
|
+
const chunks = [];
|
|
1438
|
+
let total = 0;
|
|
1439
|
+
try {
|
|
1440
|
+
for (; ; ) {
|
|
1441
|
+
const { done, value } = await reader.read();
|
|
1442
|
+
if (done) {
|
|
1443
|
+
break;
|
|
1444
|
+
}
|
|
1445
|
+
total += value.byteLength;
|
|
1446
|
+
if (maxBytes !== void 0 && total > maxBytes) {
|
|
1447
|
+
void reader.cancel().catch(() => void 0);
|
|
1448
|
+
return BODY_OVERSIZE;
|
|
1449
|
+
}
|
|
1450
|
+
chunks.push(value);
|
|
1451
|
+
}
|
|
1452
|
+
} catch {
|
|
1453
|
+
guardLogger.debug("Request body read failed (client abort?)");
|
|
1454
|
+
return BODY_READ_ERROR;
|
|
1455
|
+
}
|
|
1456
|
+
return Buffer.concat(chunks);
|
|
1457
|
+
}
|
|
1458
|
+
function isOriginAllowed(c, allowedOrigins) {
|
|
1459
|
+
if (!allowedOrigins || allowedOrigins.length === 0) {
|
|
1460
|
+
return true;
|
|
1461
|
+
}
|
|
1462
|
+
const origin = c.req.header("origin");
|
|
1463
|
+
if (!origin) {
|
|
1464
|
+
return true;
|
|
1465
|
+
}
|
|
1466
|
+
return allowedOrigins.includes(origin);
|
|
1467
|
+
}
|
|
1468
|
+
function createProxyGuard(config = {}) {
|
|
1469
|
+
const mode = config.mode ?? "off";
|
|
1470
|
+
const windowMs = config.windowMs ?? 3e4;
|
|
1471
|
+
const allowedOrigins = config.allowedOrigins;
|
|
1472
|
+
const nonceStore = config.nonceStore;
|
|
1473
|
+
const nonceFailClosed = config.nonceFailClosed ?? false;
|
|
1474
|
+
const skipPaths = new Set(config.skipPaths ?? []);
|
|
1475
|
+
const maxBodyBytes = config.maxBodyBytes;
|
|
1476
|
+
const activeRaw = config.secret ?? env.SPFN_PROXY_SECRET;
|
|
1477
|
+
const previousRaw = config.previousSecrets ?? env.SPFN_PROXY_SECRET_PREVIOUS;
|
|
1478
|
+
const keys = parseProxyKeySet([activeRaw, previousRaw]);
|
|
1479
|
+
if (mode === "strict" && keys.length === 0) {
|
|
1480
|
+
throw new Error(
|
|
1481
|
+
'[proxy-guard] mode "strict" requires a proxy key but none is configured (SPFN_PROXY_SECRET is empty/unset). Refusing to start with the guard open \u2014 set the secret, or use mode "tag" / "off".'
|
|
1482
|
+
);
|
|
1483
|
+
}
|
|
1484
|
+
if (activeRaw && previousRaw) {
|
|
1485
|
+
const activeId = parseProxyKey(activeRaw).keyId;
|
|
1486
|
+
const collides = previousRaw.split(",").some((p) => p.trim() && parseProxyKey(p.trim()).keyId === activeId);
|
|
1487
|
+
if (collides) {
|
|
1488
|
+
guardLogger.warn(
|
|
1489
|
+
'Previous proxy key shares keyId with the active key (likely bare secrets without a "keyId:" prefix) \u2014 grace key ignored, rotation will drop in-flight requests. Use "<keyId>:<secret>" on both keys.',
|
|
1490
|
+
{ keyId: activeId }
|
|
1491
|
+
);
|
|
1492
|
+
}
|
|
1493
|
+
}
|
|
1494
|
+
return async (c, next) => {
|
|
1495
|
+
if (mode === "off" || skipPaths.has(c.req.path)) {
|
|
1496
|
+
return next();
|
|
1497
|
+
}
|
|
1498
|
+
if (c.req.method === "OPTIONS" && c.req.header("access-control-request-method")) {
|
|
1499
|
+
c.set("clientType", "untrusted");
|
|
1500
|
+
return next();
|
|
1501
|
+
}
|
|
1502
|
+
if (!isOriginAllowed(c, allowedOrigins)) {
|
|
1503
|
+
return reject(c, mode, next, "origin-not-allowed");
|
|
1504
|
+
}
|
|
1505
|
+
if (keys.length === 0) {
|
|
1506
|
+
c.set("clientType", "untrusted");
|
|
1507
|
+
return next();
|
|
1508
|
+
}
|
|
1509
|
+
const signature = c.req.header(PROXY_SIGNATURE_HEADER);
|
|
1510
|
+
const timestamp = c.req.header(PROXY_TIMESTAMP_HEADER);
|
|
1511
|
+
const nonce = c.req.header(PROXY_NONCE_HEADER);
|
|
1512
|
+
const keyId = c.req.header(PROXY_KEY_ID_HEADER);
|
|
1513
|
+
if (!signature || !timestamp || !nonce || !keyId) {
|
|
1514
|
+
return reject(c, mode, next, "missing-headers");
|
|
1515
|
+
}
|
|
1516
|
+
const body = await readRawBody(c, maxBodyBytes);
|
|
1517
|
+
if (body === BODY_OVERSIZE) {
|
|
1518
|
+
if (mode === "strict") {
|
|
1519
|
+
return c.json({ error: "Payload Too Large" }, 413);
|
|
1520
|
+
}
|
|
1521
|
+
c.set("clientType", "untrusted");
|
|
1522
|
+
return next();
|
|
1523
|
+
}
|
|
1524
|
+
if (body === BODY_READ_ERROR) {
|
|
1525
|
+
return reject(c, mode, next, "body-read-error");
|
|
1526
|
+
}
|
|
1527
|
+
const url = new URL(c.req.url);
|
|
1528
|
+
const result = verifyProxyRequest({
|
|
1529
|
+
keys,
|
|
1530
|
+
method: c.req.method,
|
|
1531
|
+
path: url.pathname,
|
|
1532
|
+
query: url.search,
|
|
1533
|
+
body,
|
|
1534
|
+
signature,
|
|
1535
|
+
timestamp,
|
|
1536
|
+
nonce,
|
|
1537
|
+
keyId,
|
|
1538
|
+
windowMs
|
|
1539
|
+
});
|
|
1540
|
+
if (!result.valid) {
|
|
1541
|
+
return reject(c, mode, next, result.reason);
|
|
1542
|
+
}
|
|
1543
|
+
if (nonceStore && result.nonce) {
|
|
1544
|
+
try {
|
|
1545
|
+
const fresh = await nonceStore.checkAndSet(result.nonce, windowMs * 2);
|
|
1546
|
+
if (!fresh) {
|
|
1547
|
+
return reject(c, mode, next, "nonce-replay");
|
|
1548
|
+
}
|
|
1549
|
+
} catch (err) {
|
|
1550
|
+
if (nonceFailClosed) {
|
|
1551
|
+
guardLogger.warn("Nonce store unavailable \u2014 rejecting (fail-closed)", {
|
|
1552
|
+
error: err.message
|
|
1553
|
+
});
|
|
1554
|
+
return reject(c, mode, next, "nonce-store-unavailable");
|
|
1555
|
+
}
|
|
1556
|
+
guardLogger.warn("Nonce store unavailable \u2014 falling back to timestamp window", {
|
|
1557
|
+
error: err.message
|
|
1558
|
+
});
|
|
1559
|
+
}
|
|
1560
|
+
}
|
|
1561
|
+
c.set("clientType", "web");
|
|
1562
|
+
return next();
|
|
1563
|
+
};
|
|
1564
|
+
}
|
|
1565
|
+
function createCacheNonceStore(cache, prefix = "spfn:proxy-nonce:") {
|
|
1566
|
+
return {
|
|
1567
|
+
async checkAndSet(nonce, ttlMs) {
|
|
1568
|
+
const res = await cache.set(`${prefix}${nonce}`, "1", "PX", Math.ceil(ttlMs), "NX");
|
|
1569
|
+
return res === "OK";
|
|
1570
|
+
}
|
|
1571
|
+
};
|
|
1572
|
+
}
|
|
1573
|
+
function createInMemoryNonceStore() {
|
|
1574
|
+
const seen = /* @__PURE__ */ new Map();
|
|
1575
|
+
let lastSweep = 0;
|
|
1576
|
+
return {
|
|
1577
|
+
async checkAndSet(nonce, ttlMs) {
|
|
1578
|
+
const now = Date.now();
|
|
1579
|
+
if (now - lastSweep > 6e4) {
|
|
1580
|
+
for (const [n, exp] of seen) {
|
|
1581
|
+
if (exp <= now) seen.delete(n);
|
|
1582
|
+
}
|
|
1583
|
+
lastSweep = now;
|
|
1584
|
+
}
|
|
1585
|
+
const existing = seen.get(nonce);
|
|
1586
|
+
if (existing !== void 0 && existing > now) {
|
|
1587
|
+
return false;
|
|
1588
|
+
}
|
|
1589
|
+
seen.set(nonce, now + ttlMs);
|
|
1590
|
+
return true;
|
|
1591
|
+
}
|
|
1592
|
+
};
|
|
1593
|
+
}
|
|
1594
|
+
function reject(c, mode, next, reason) {
|
|
1595
|
+
if (mode === "strict") {
|
|
1596
|
+
guardLogger.warn("Rejected unverified request", { reason, path: c.req.path, method: c.req.method });
|
|
1597
|
+
return c.json({ error: "Forbidden", message: "Request origin could not be verified" }, 403);
|
|
1598
|
+
}
|
|
1599
|
+
guardLogger.debug("Unverified request (would reject in strict mode)", { reason, path: c.req.path });
|
|
1600
|
+
c.set("clientType", "untrusted");
|
|
1601
|
+
return next();
|
|
1602
|
+
}
|
|
156
1603
|
|
|
157
|
-
export { ErrorHandler, RequestLogger, maskSensitiveData };
|
|
1604
|
+
export { CacheRateLimitStore, ErrorHandler, MemoryRateLimitStore, RequestLogger, createCacheNonceStore, createInMemoryNonceStore, createProxyGuard, getClientIp, getRateLimitPolicy, maskSensitiveData2 as maskSensitiveData, rateLimit, rateLimitPolicy, resetMemoryRateLimitStore, setRateLimitFailClosedDefault, setRateLimitPolicies };
|
|
158
1605
|
//# sourceMappingURL=index.js.map
|
|
159
1606
|
//# sourceMappingURL=index.js.map
|