create-cellsweb-rpc-api 1.0.24 → 1.0.26
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -3
- package/bin/create.js +50 -17
- package/bin/crpc.js +4 -0
- package/package.json +10 -6
- package/template/scripts/create-function.ts +26 -15
- package/template/scripts/create-middleware.ts +1 -1
- package/template/scripts/tsconfig.json +3 -2
- package/template/src/functions/public/hello/run.ts +1 -1
- package/template/src/middlewares/auth/constants.ts +3 -0
- package/template/src/middlewares/auth/run.ts +11 -9
- package/template/src/middlewares/rateLimit/run.ts +7 -4
- package/template/src/test/setup.ts +7 -63
- package/template/src/utils/storage.ts +4 -4
package/README.md
CHANGED
|
@@ -57,10 +57,11 @@ npx create-cellsweb-rpc-api@latest my-app --framework ultimate-express
|
|
|
57
57
|
## Features
|
|
58
58
|
|
|
59
59
|
- **Multi-Framework Flexibility**: Choose between Vanilla Node.js, Express, Fastify, or Ultimate-Express while keeping RPC function and middleware code 100% identical.
|
|
60
|
-
- **
|
|
61
|
-
- **
|
|
60
|
+
- **Unified Framework CLI (`crpc`)**: Integrated single-binary developer CLI for dev with hot-reload (`crpc dev`), production build (`crpc build`), serving (`crpc start`), and test suites (`crpc test`).
|
|
61
|
+
- **Pre-wired `@cellsweb/rpc-core`**: High performance $O(1)$ dispatching engine with sub-microsecond JIT schema validation.
|
|
62
|
+
- **Interactive & AI Batch Generators**: Built-in CLI scripts for adding new functions (`crpc create:function`) and middlewares (`crpc create:middleware`) supporting non-interactive flags, JSON batch scaffolding (`--batch '<JSON>'`), and file specs (`--file spec.json`).
|
|
63
|
+
- **Security & Integration Audit Testing**: Built-in in-process security audit test harness with HTML/JSON report generation (`crpc test:audit`).
|
|
62
64
|
- **Pre-scaffolded Common Middlewares**: Includes `auth` (JWT verification stub) and `rateLimit` (in-memory rate limiting).
|
|
63
|
-
- **Security & Integration Audit Testing**: Built-in in-process security audit test harness with HTML/JSON report generation (`pnpm run test:audit`).
|
|
64
65
|
- **Pluggable Extensions**: Modular application-level `env.ts` (TypeBox), `telemetry.ts` (Sentry), and `storage.ts` (Local/S3 uploads).
|
|
65
66
|
|
|
66
67
|
---
|
package/bin/create.js
CHANGED
|
@@ -87,6 +87,34 @@ async function main() {
|
|
|
87
87
|
}
|
|
88
88
|
}
|
|
89
89
|
|
|
90
|
+
// Parse non-interactive, package name, and package manager flags
|
|
91
|
+
const hasYesFlag =
|
|
92
|
+
args.includes("-y") ||
|
|
93
|
+
args.includes("--yes") ||
|
|
94
|
+
args.includes("--non-interactive");
|
|
95
|
+
|
|
96
|
+
let explicitName = null;
|
|
97
|
+
const nameFlagIdx = args.findIndex((arg) => arg === "--name" || arg === "-n");
|
|
98
|
+
if (nameFlagIdx !== -1 && args[nameFlagIdx + 1]) {
|
|
99
|
+
explicitName = args[nameFlagIdx + 1].trim();
|
|
100
|
+
} else {
|
|
101
|
+
const inlineName = args.find((arg) => arg.startsWith("--name="));
|
|
102
|
+
if (inlineName) {
|
|
103
|
+
explicitName = inlineName.split("=")[1]?.trim();
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
let explicitPm = null;
|
|
108
|
+
const pmFlagIdx = args.findIndex((arg) => arg === "--pm");
|
|
109
|
+
if (pmFlagIdx !== -1 && args[pmFlagIdx + 1]) {
|
|
110
|
+
explicitPm = args[pmFlagIdx + 1].trim();
|
|
111
|
+
} else {
|
|
112
|
+
const inlinePm = args.find((arg) => arg.startsWith("--pm="));
|
|
113
|
+
if (inlinePm) {
|
|
114
|
+
explicitPm = inlinePm.split("=")[1]?.trim();
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
|
|
90
118
|
function normalizeFramework(input) {
|
|
91
119
|
if (!input) return "node";
|
|
92
120
|
const str = String(input).toLowerCase().trim();
|
|
@@ -104,7 +132,7 @@ async function main() {
|
|
|
104
132
|
|
|
105
133
|
if (rawArg) {
|
|
106
134
|
targetDir = path.resolve(process.cwd(), rawArg);
|
|
107
|
-
} else if (!isTTY) {
|
|
135
|
+
} else if (!isTTY || hasYesFlag) {
|
|
108
136
|
targetDir = path.resolve(process.cwd(), "./api");
|
|
109
137
|
} else {
|
|
110
138
|
const answer = await ask("Target directory", "./api");
|
|
@@ -116,14 +144,17 @@ async function main() {
|
|
|
116
144
|
? "my-rpc-api"
|
|
117
145
|
: path.basename(targetDir);
|
|
118
146
|
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
147
|
+
const shouldPrompt = isTTY && !hasYesFlag;
|
|
148
|
+
|
|
149
|
+
if (!shouldPrompt) {
|
|
150
|
+
projectName = explicitName || defaultName;
|
|
151
|
+
pm = explicitPm || "pnpm";
|
|
122
152
|
framework = normalizeFramework(explicitFramework);
|
|
123
153
|
rl.close();
|
|
124
154
|
} else {
|
|
125
|
-
projectName = await ask("Package name", defaultName);
|
|
126
|
-
const pmAnswer =
|
|
155
|
+
projectName = explicitName || (await ask("Package name", defaultName));
|
|
156
|
+
const pmAnswer =
|
|
157
|
+
explicitPm || (await ask("Package manager [npm / pnpm / yarn]", "pnpm"));
|
|
127
158
|
pm = ["npm", "pnpm", "yarn"].includes(pmAnswer) ? pmAnswer : "pnpm";
|
|
128
159
|
|
|
129
160
|
if (explicitFramework) {
|
|
@@ -179,8 +210,8 @@ async function main() {
|
|
|
179
210
|
node: ">=20.0.0",
|
|
180
211
|
},
|
|
181
212
|
dependencies: {
|
|
182
|
-
"@cellsweb/rpc-core": "^1.0.
|
|
183
|
-
"create-cellsweb-rpc-api": "^1.0.
|
|
213
|
+
"@cellsweb/rpc-core": "^1.0.30",
|
|
214
|
+
"create-cellsweb-rpc-api": "^1.0.26",
|
|
184
215
|
"@aws-sdk/client-s3": "^3.700.0",
|
|
185
216
|
"@paralleldrive/cuid2": "^2.2.2",
|
|
186
217
|
"@sentry/node": "^8.40.0",
|
|
@@ -201,7 +232,6 @@ async function main() {
|
|
|
201
232
|
"@types/node": "^22.15.18",
|
|
202
233
|
"@vitest/coverage-v8": "^3.2.4",
|
|
203
234
|
"@vitest/ui": "^3.2.4",
|
|
204
|
-
"mongodb-memory-server": "^10.1.4",
|
|
205
235
|
"pino-pretty": "^13.0.0",
|
|
206
236
|
"tsc-alias": "^1.8.17",
|
|
207
237
|
"tsx": "^4.22.0",
|
|
@@ -209,7 +239,7 @@ async function main() {
|
|
|
209
239
|
"vitest": "^3.2.4",
|
|
210
240
|
},
|
|
211
241
|
pnpm: {
|
|
212
|
-
onlyBuiltDependencies: ["esbuild"
|
|
242
|
+
onlyBuiltDependencies: ["esbuild"],
|
|
213
243
|
},
|
|
214
244
|
};
|
|
215
245
|
|
|
@@ -252,10 +282,11 @@ async function main() {
|
|
|
252
282
|
// ── 6. Write scripts/tsconfig.json ────────────────────────────────────────
|
|
253
283
|
const scriptsTsconfig = {
|
|
254
284
|
compilerOptions: {
|
|
255
|
-
target: "
|
|
256
|
-
module: "
|
|
257
|
-
moduleResolution: "
|
|
258
|
-
lib: ["
|
|
285
|
+
target: "ES2023",
|
|
286
|
+
module: "nodenext",
|
|
287
|
+
moduleResolution: "nodenext",
|
|
288
|
+
lib: ["ES2023"],
|
|
289
|
+
types: ["node"],
|
|
259
290
|
strict: true,
|
|
260
291
|
esModuleInterop: true,
|
|
261
292
|
skipLibCheck: true,
|
|
@@ -275,7 +306,7 @@ async function main() {
|
|
|
275
306
|
const giPath = path.join(targetDir, ".gitignore");
|
|
276
307
|
if (!fs.existsSync(giPath)) fs.writeFileSync(giPath, gitignore);
|
|
277
308
|
|
|
278
|
-
const npmrc = "onlyBuiltDependencies=esbuild
|
|
309
|
+
const npmrc = "onlyBuiltDependencies=esbuild\n";
|
|
279
310
|
const npmrcPath = path.join(targetDir, ".npmrc");
|
|
280
311
|
if (!fs.existsSync(npmrcPath)) fs.writeFileSync(npmrcPath, npmrc);
|
|
281
312
|
|
|
@@ -290,7 +321,9 @@ async function main() {
|
|
|
290
321
|
console.log(` ${dim("Installing dependencies with")} ${bold(pm)} ...\n`);
|
|
291
322
|
try {
|
|
292
323
|
const installCmd =
|
|
293
|
-
pm === "pnpm"
|
|
324
|
+
pm === "pnpm"
|
|
325
|
+
? "pnpm install || (pnpm approve-builds esbuild && pnpm install)"
|
|
326
|
+
: `${pm} install`;
|
|
294
327
|
execSync(installCmd, { cwd: targetDir, stdio: "inherit" });
|
|
295
328
|
} catch {
|
|
296
329
|
console.log(` ${yellow("⚠")} Install failed — run ${bold(`${pm} install`)} manually.\n`);
|
|
@@ -320,7 +353,7 @@ async function main() {
|
|
|
320
353
|
${dim("Add your JWT logic in:")}
|
|
321
354
|
${cyan("src/middlewares/auth/run.ts")} ${dim("→ verifyToken()")}
|
|
322
355
|
|
|
323
|
-
${dim("API endpoint:")} POST ${cyan("http://localhost:4000/
|
|
356
|
+
${dim("API endpoint:")} POST ${cyan("http://localhost:4000/rpc")}
|
|
324
357
|
${dim("Docs:")} GET ${cyan("http://localhost:4000/docs")}
|
|
325
358
|
`);
|
|
326
359
|
}
|
package/bin/crpc.js
CHANGED
|
@@ -192,6 +192,10 @@ async function main() {
|
|
|
192
192
|
|
|
193
193
|
case "test:audit": {
|
|
194
194
|
console.log("🛡️ Generating Client Security & Verification Audit Report...");
|
|
195
|
+
const auditDir = path.resolve(rootDir, "audit-reports");
|
|
196
|
+
if (!fs.existsSync(auditDir)) {
|
|
197
|
+
fs.mkdirSync(auditDir, { recursive: true });
|
|
198
|
+
}
|
|
195
199
|
const code = await runChild("npx", [
|
|
196
200
|
"vitest",
|
|
197
201
|
"run",
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "create-cellsweb-rpc-api",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.26",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"publishConfig": {
|
|
6
6
|
"access": "public"
|
|
@@ -16,9 +16,6 @@
|
|
|
16
16
|
"template",
|
|
17
17
|
"templates"
|
|
18
18
|
],
|
|
19
|
-
"scripts": {
|
|
20
|
-
"test": "echo \"CLI scaffolder test suite\""
|
|
21
|
-
},
|
|
22
19
|
"keywords": [
|
|
23
20
|
"rpc",
|
|
24
21
|
"create-app",
|
|
@@ -33,6 +30,13 @@
|
|
|
33
30
|
"url": "git+https://github.com/MinhazurSarker/cellsweb-rpc.git"
|
|
34
31
|
},
|
|
35
32
|
"dependencies": {
|
|
36
|
-
"@clack/prompts": "^1.7.0"
|
|
33
|
+
"@clack/prompts": "^1.7.0",
|
|
34
|
+
"tinyglobby": "^0.2.17"
|
|
35
|
+
},
|
|
36
|
+
"devDependencies": {
|
|
37
|
+
"@types/node": "^26.6.6"
|
|
38
|
+
},
|
|
39
|
+
"scripts": {
|
|
40
|
+
"test": "echo \"CLI scaffolder test suite\""
|
|
37
41
|
}
|
|
38
|
-
}
|
|
42
|
+
}
|
|
@@ -160,7 +160,7 @@ function tplRun(ns: string, fn: string, isMultipart: boolean, mws: string[]): st
|
|
|
160
160
|
let importContextStr = 'import type { MiddlewareContext } from "@cellsweb/rpc-core";';
|
|
161
161
|
|
|
162
162
|
if (mws.length > 0) {
|
|
163
|
-
importContextStr = 'import type { InferContext } from "@cellsweb/rpc-core";\nimport { middlewares } from "./middlewares";';
|
|
163
|
+
importContextStr = 'import type { InferContext } from "@cellsweb/rpc-core";\nimport type { middlewares } from "./middlewares";';
|
|
164
164
|
contextTypeStr = "InferContext<typeof middlewares>";
|
|
165
165
|
}
|
|
166
166
|
|
|
@@ -182,7 +182,7 @@ function tplRun(ns: string, fn: string, isMultipart: boolean, mws: string[]): st
|
|
|
182
182
|
|
|
183
183
|
import type { Static } from "@sinclair/typebox";
|
|
184
184
|
${importContextStr}
|
|
185
|
-
import { inputSchema, outputSchema } from "./constants";
|
|
185
|
+
import type { inputSchema, outputSchema } from "./constants";
|
|
186
186
|
|
|
187
187
|
type Input = Static<typeof inputSchema>;
|
|
188
188
|
type Output = Static<typeof outputSchema>;
|
|
@@ -221,7 +221,7 @@ export const run = async (
|
|
|
221
221
|
|
|
222
222
|
import type { Static } from "@sinclair/typebox";
|
|
223
223
|
${importContextStr}
|
|
224
|
-
import { inputSchema, outputSchema } from "./constants";
|
|
224
|
+
import type { inputSchema, outputSchema } from "./constants";
|
|
225
225
|
|
|
226
226
|
type Input = Static<typeof inputSchema>;
|
|
227
227
|
type Output = Static<typeof outputSchema>;
|
|
@@ -335,17 +335,24 @@ describe("RPC Security & Execution Audit: ${ns}.${fn}", () => {
|
|
|
335
335
|
describe("3. User Flow & Access Control", () => {
|
|
336
336
|
it("executes successfully with authorized user credentials", async () => {
|
|
337
337
|
const actor = await createTestActor({ role: "admin", userId: "usr_authorized" });
|
|
338
|
+
const mockFile = createUploadedFile({
|
|
339
|
+
path: "/tmp/mock.png",
|
|
340
|
+
filename: "test.png",
|
|
341
|
+
mimeType: "image/png",
|
|
342
|
+
byteLength: 1024,
|
|
343
|
+
});
|
|
338
344
|
const raw = await actor.callRaw("${ns}.${fn}", {
|
|
339
345
|
title: "Actor Upload",
|
|
346
|
+
file: mockFile,
|
|
340
347
|
});
|
|
341
|
-
expect(raw.status).
|
|
348
|
+
expect(raw.status).toBe("ok");
|
|
342
349
|
});
|
|
343
350
|
|
|
344
351
|
it("enforces security guards and blocks unprivileged access", async () => {
|
|
345
352
|
if (!metadata.isPublic) {
|
|
346
353
|
const guestActor = await createTestActor({ role: "unprivileged_guest" });
|
|
347
354
|
const res = await guestActor.callRaw("${ns}.${fn}", { title: "Unauthorized Attempt" });
|
|
348
|
-
expect(res.status).
|
|
355
|
+
expect(res.status).toBe("error");
|
|
349
356
|
}
|
|
350
357
|
});
|
|
351
358
|
});
|
|
@@ -353,9 +360,15 @@ describe("RPC Security & Execution Audit: ${ns}.${fn}", () => {
|
|
|
353
360
|
// ── 4. Server Business Logic & Boundary Integrity ──
|
|
354
361
|
describe("4. Server Business Logic & Boundary Integrity", () => {
|
|
355
362
|
it("evaluates server logic cleanly without unhandled crashes", async () => {
|
|
356
|
-
const actor = await createTestActor({ role: "
|
|
357
|
-
const
|
|
358
|
-
|
|
363
|
+
const actor = await createTestActor({ role: "admin", userId: "usr_actor_1" });
|
|
364
|
+
const mockFile = createUploadedFile({
|
|
365
|
+
path: "/tmp/mock.png",
|
|
366
|
+
filename: "test.png",
|
|
367
|
+
mimeType: "image/png",
|
|
368
|
+
byteLength: 1024,
|
|
369
|
+
});
|
|
370
|
+
const res = await actor.callRaw("${ns}.${fn}", { title: "Valid Submission", file: mockFile });
|
|
371
|
+
expect(res.status).toBe("ok");
|
|
359
372
|
});
|
|
360
373
|
});
|
|
361
374
|
});
|
|
@@ -412,11 +425,9 @@ describe("RPC Security & Execution Audit: ${ns}.${fn}", () => {
|
|
|
412
425
|
it("executes successfully with authorized user credentials", async () => {
|
|
413
426
|
const actor = await createTestActor({ role: "admin", userId: "usr_admin_1" });
|
|
414
427
|
const res = await actor.callRaw("${ns}.${fn}", { example: "Actor test payload" });
|
|
415
|
-
|
|
428
|
+
expect(res.status).toBe("ok");
|
|
416
429
|
if (res.status === "ok") {
|
|
417
|
-
expect(res.data).
|
|
418
|
-
} else {
|
|
419
|
-
expect(res.status).toBe("error");
|
|
430
|
+
expect(res.data).toEqual({ result: "Actor test payload" });
|
|
420
431
|
}
|
|
421
432
|
});
|
|
422
433
|
|
|
@@ -424,7 +435,7 @@ describe("RPC Security & Execution Audit: ${ns}.${fn}", () => {
|
|
|
424
435
|
if (!metadata.isPublic) {
|
|
425
436
|
const guestActor = await createTestActor({ role: "unprivileged_guest" });
|
|
426
437
|
const res = await guestActor.callRaw("${ns}.${fn}", { example: "Unauthorized attempt" });
|
|
427
|
-
expect(res.status).
|
|
438
|
+
expect(res.status).toBe("error");
|
|
428
439
|
}
|
|
429
440
|
});
|
|
430
441
|
});
|
|
@@ -432,9 +443,9 @@ describe("RPC Security & Execution Audit: ${ns}.${fn}", () => {
|
|
|
432
443
|
// ── 4. Server Business Logic & Boundary Integrity ──
|
|
433
444
|
describe("4. Server Business Logic & Boundary Integrity", () => {
|
|
434
445
|
it("processes user flow and returns proper status feedback", async () => {
|
|
435
|
-
const actor = await createTestActor({ role: "
|
|
446
|
+
const actor = await createTestActor({ role: "admin", userId: "usr_regular_1" });
|
|
436
447
|
const res = await actor.callRaw("${ns}.${fn}", { example: "Flow test" });
|
|
437
|
-
expect(res.status).
|
|
448
|
+
expect(res.status).toBe("ok");
|
|
438
449
|
});
|
|
439
450
|
});
|
|
440
451
|
});
|
|
@@ -82,7 +82,7 @@ function tplRun(name: string): string {
|
|
|
82
82
|
|
|
83
83
|
import type { MiddlewareFn } from "@cellsweb/rpc-core";
|
|
84
84
|
import type { Static } from "@sinclair/typebox";
|
|
85
|
-
import { optionsSchema } from "./constants";
|
|
85
|
+
import type { optionsSchema } from "./constants";
|
|
86
86
|
|
|
87
87
|
type Options = Static<typeof optionsSchema>;
|
|
88
88
|
|
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
{
|
|
2
2
|
"compilerOptions": {
|
|
3
3
|
"target": "ES2023",
|
|
4
|
-
"module": "
|
|
5
|
-
"moduleResolution": "
|
|
4
|
+
"module": "nodenext",
|
|
5
|
+
"moduleResolution": "nodenext",
|
|
6
6
|
"lib": ["ES2023"],
|
|
7
|
+
"types": ["node"],
|
|
7
8
|
"strict": true,
|
|
8
9
|
"esModuleInterop": true,
|
|
9
10
|
"skipLibCheck": true,
|
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
|
|
7
7
|
import type { Static } from "@sinclair/typebox";
|
|
8
8
|
import type { MiddlewareContext } from "@cellsweb/rpc-core";
|
|
9
|
-
import { inputSchema, outputSchema } from "./constants";
|
|
9
|
+
import type { inputSchema, outputSchema } from "./constants";
|
|
10
10
|
|
|
11
11
|
type Input = Static<typeof inputSchema>;
|
|
12
12
|
type Output = Static<typeof outputSchema>;
|
|
@@ -25,6 +25,9 @@ export const optionsSchema = Type.Object({
|
|
|
25
25
|
{ description: "Allowed user roles for this endpoint" },
|
|
26
26
|
),
|
|
27
27
|
),
|
|
28
|
+
optional: Type.Optional(
|
|
29
|
+
Type.Boolean({ description: "Allow unauthenticated access if token is missing" }),
|
|
30
|
+
),
|
|
28
31
|
});
|
|
29
32
|
|
|
30
33
|
export const outputSchema = Type.Object({
|
|
@@ -13,7 +13,7 @@
|
|
|
13
13
|
|
|
14
14
|
import type { Static } from "@sinclair/typebox";
|
|
15
15
|
import { AppError, ErrorCode, type MiddlewareFn } from "@cellsweb/rpc-core";
|
|
16
|
-
import { optionsSchema, outputSchema,
|
|
16
|
+
import type { optionsSchema, outputSchema, UserRole } from "./constants";
|
|
17
17
|
|
|
18
18
|
export type AuthOptions = Static<typeof optionsSchema>;
|
|
19
19
|
export type AuthContext = Static<typeof outputSchema>;
|
|
@@ -38,8 +38,8 @@ export const run: MiddlewareFn<AuthOptions, { auth?: AuthContext }> = async (
|
|
|
38
38
|
(Array.isArray(headers["token"]) ? headers["token"][0] : headers["token"]);
|
|
39
39
|
|
|
40
40
|
const token = (typeof authHeader === "string" ? authHeader : "")?.replace(/^Bearer\s+/i, "") ?? undefined;
|
|
41
|
-
const roles = options.roles
|
|
42
|
-
const
|
|
41
|
+
const roles = options.roles;
|
|
42
|
+
const isOptional = options.optional === true || (Array.isArray(roles) && roles.length === 0);
|
|
43
43
|
|
|
44
44
|
let user: IUser | null = null;
|
|
45
45
|
try {
|
|
@@ -49,13 +49,15 @@ export const run: MiddlewareFn<AuthOptions, { auth?: AuthContext }> = async (
|
|
|
49
49
|
throw new AppError(ErrorCode.UNAUTHORIZED, "Invalid or expired token");
|
|
50
50
|
}
|
|
51
51
|
|
|
52
|
-
if (!
|
|
53
|
-
if (
|
|
54
|
-
|
|
55
|
-
}
|
|
56
|
-
if (!roles.includes(user.role)) {
|
|
57
|
-
throw new AppError(ErrorCode.FORBIDDEN, "Insufficient permissions");
|
|
52
|
+
if (!user) {
|
|
53
|
+
if (isOptional) {
|
|
54
|
+
return context;
|
|
58
55
|
}
|
|
56
|
+
throw new AppError(ErrorCode.UNAUTHORIZED, "Authentication required");
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
if (roles && roles.length > 0 && !roles.includes(user.role)) {
|
|
60
|
+
throw new AppError(ErrorCode.FORBIDDEN, "Insufficient permissions");
|
|
59
61
|
}
|
|
60
62
|
|
|
61
63
|
if (user) {
|
|
@@ -14,19 +14,22 @@
|
|
|
14
14
|
import type { Static } from "@sinclair/typebox";
|
|
15
15
|
import { AppError, ErrorCode, type MiddlewareFn } from "@cellsweb/rpc-core";
|
|
16
16
|
import { LRUCache } from "lru-cache";
|
|
17
|
-
import
|
|
18
|
-
import { optionsSchema } from "./constants";
|
|
17
|
+
import rateLimiterPkg from "rate-limiter-flexible";
|
|
18
|
+
import type { optionsSchema } from "./constants";
|
|
19
|
+
|
|
20
|
+
const { RateLimiterMemory } = rateLimiterPkg;
|
|
21
|
+
type RateLimiterInstance = InstanceType<typeof RateLimiterMemory>;
|
|
19
22
|
|
|
20
23
|
type Options = Static<typeof optionsSchema>;
|
|
21
24
|
|
|
22
|
-
const limiterCache = new LRUCache<string,
|
|
25
|
+
const limiterCache = new LRUCache<string, RateLimiterInstance>({
|
|
23
26
|
max: 256,
|
|
24
27
|
});
|
|
25
28
|
|
|
26
29
|
function getOrCreateLimiter(
|
|
27
30
|
windowSeconds: number,
|
|
28
31
|
maxRequests: number,
|
|
29
|
-
):
|
|
32
|
+
): RateLimiterInstance {
|
|
30
33
|
const key = `${windowSeconds}:${maxRequests}`;
|
|
31
34
|
let limiter = limiterCache.get(key);
|
|
32
35
|
|
|
@@ -1,79 +1,23 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* src/test/setup.ts
|
|
3
3
|
* ─────────────────────────────────────────────────────────────────────────────
|
|
4
|
-
* GLOBAL TEST LIFECYCLE
|
|
4
|
+
* GLOBAL TEST LIFECYCLE
|
|
5
5
|
*
|
|
6
|
-
* Configures the test environment before any tests run.
|
|
7
|
-
*
|
|
8
|
-
* - "memory": Spins up an isolated in-RAM MongoDB (mongodb-memory-server).
|
|
9
|
-
* - "real": Connects to a real test/staging database via TEST_MONGODB_URI.
|
|
10
|
-
*
|
|
11
|
-
* Automatically wipes collections between tests to guarantee absolute test isolation.
|
|
6
|
+
* Configures the test environment before any integration or unit tests run.
|
|
7
|
+
* Add global test setup, mocks, or database connections here if needed.
|
|
12
8
|
*/
|
|
13
9
|
|
|
14
10
|
import { beforeAll, afterAll, afterEach } from "vitest";
|
|
15
11
|
|
|
16
|
-
let mongodInstance: any = null;
|
|
17
|
-
let mongooseInstance: any = null;
|
|
18
|
-
|
|
19
12
|
beforeAll(async () => {
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
try {
|
|
23
|
-
// Attempt dynamic import of mongoose if available in user project
|
|
24
|
-
// @ts-ignore
|
|
25
|
-
const mongooseMod = await import("mongoose").catch(() => null);
|
|
26
|
-
if (mongooseMod?.default) {
|
|
27
|
-
mongooseInstance = mongooseMod.default;
|
|
28
|
-
} else if (mongooseMod) {
|
|
29
|
-
mongooseInstance = mongooseMod;
|
|
30
|
-
}
|
|
31
|
-
|
|
32
|
-
if (mongooseInstance) {
|
|
33
|
-
if (dbType === "memory") {
|
|
34
|
-
// Attempt dynamic import of mongodb-memory-server
|
|
35
|
-
// @ts-ignore
|
|
36
|
-
const { MongoMemoryServer } = await import("mongodb-memory-server").catch(() => ({ MongoMemoryServer: null }));
|
|
37
|
-
if (MongoMemoryServer) {
|
|
38
|
-
mongodInstance = await MongoMemoryServer.create();
|
|
39
|
-
const uri = mongodInstance.getUri();
|
|
40
|
-
await mongooseInstance.connect(uri);
|
|
41
|
-
}
|
|
42
|
-
} else {
|
|
43
|
-
const uri =
|
|
44
|
-
process.env.TEST_MONGODB_URI ||
|
|
45
|
-
process.env.MONGODB_URI ||
|
|
46
|
-
"mongodb://127.0.0.1:27017/cellsweb_test";
|
|
47
|
-
await mongooseInstance.connect(uri);
|
|
48
|
-
}
|
|
49
|
-
}
|
|
50
|
-
} catch (err) {
|
|
51
|
-
// If mongoose or mongodb-memory-server are not installed, proceed gracefully
|
|
52
|
-
console.warn("Test DB setup note:", (err as Error).message);
|
|
53
|
-
}
|
|
13
|
+
process.env.NODE_ENV = "test";
|
|
14
|
+
process.env.VITEST = "true";
|
|
54
15
|
});
|
|
55
16
|
|
|
56
17
|
afterEach(async () => {
|
|
57
|
-
//
|
|
58
|
-
if (mongooseInstance && mongooseInstance.connection?.readyState === 1) {
|
|
59
|
-
try {
|
|
60
|
-
const collections = mongooseInstance.connection.collections;
|
|
61
|
-
for (const key in collections) {
|
|
62
|
-
await collections[key].deleteMany({});
|
|
63
|
-
}
|
|
64
|
-
} catch {}
|
|
65
|
-
}
|
|
18
|
+
// Reset per-test state here if needed
|
|
66
19
|
});
|
|
67
20
|
|
|
68
21
|
afterAll(async () => {
|
|
69
|
-
|
|
70
|
-
try {
|
|
71
|
-
await mongooseInstance.disconnect();
|
|
72
|
-
} catch {}
|
|
73
|
-
}
|
|
74
|
-
if (mongodInstance) {
|
|
75
|
-
try {
|
|
76
|
-
await mongodInstance.stop();
|
|
77
|
-
} catch {}
|
|
78
|
-
}
|
|
22
|
+
// Clean up global connections or resources here if needed
|
|
79
23
|
});
|
|
@@ -163,10 +163,10 @@ async function localDelete(relativePath: string): Promise<boolean> {
|
|
|
163
163
|
const clean = cleanStoragePath(relativePath);
|
|
164
164
|
const fullPath = path.join(uploadRoot, clean);
|
|
165
165
|
const resolved = path.resolve(fullPath);
|
|
166
|
-
const root = path.resolve(uploadRoot);
|
|
166
|
+
const root = path.resolve(uploadRoot) + path.sep;
|
|
167
167
|
|
|
168
168
|
// Security: prevent directory traversal
|
|
169
|
-
if (!resolved.startsWith(root)) {
|
|
169
|
+
if (!resolved.startsWith(root) && resolved !== path.resolve(uploadRoot)) {
|
|
170
170
|
return false;
|
|
171
171
|
}
|
|
172
172
|
|
|
@@ -189,8 +189,8 @@ async function localServe(relativePath: string): Promise<{ buffer: Buffer; mimeT
|
|
|
189
189
|
const fullPath = path.join(uploadRoot, clean);
|
|
190
190
|
|
|
191
191
|
const resolved = path.resolve(fullPath);
|
|
192
|
-
const root = path.resolve(uploadRoot);
|
|
193
|
-
if (!resolved.startsWith(root)) return null;
|
|
192
|
+
const root = path.resolve(uploadRoot) + path.sep;
|
|
193
|
+
if (!resolved.startsWith(root) && resolved !== path.resolve(uploadRoot)) return null;
|
|
194
194
|
if (!existsSync(fullPath)) return null;
|
|
195
195
|
|
|
196
196
|
const buffer = await fs.readFile(fullPath);
|