create-cellsweb-rpc-api 1.0.19 → 1.0.21

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/bin/create.js CHANGED
@@ -10,12 +10,13 @@
10
10
  * npx create-cellsweb-rpc-api@latest
11
11
  */
12
12
 
13
- "use strict";
13
+ import fs from "node:fs";
14
+ import path from "node:path";
15
+ import { execSync } from "node:child_process";
16
+ import readline from "node:readline";
17
+ import { fileURLToPath } from "node:url";
14
18
 
15
- const fs = require("fs");
16
- const path = require("path");
17
- const { execSync } = require("child_process");
18
- const readline = require("readline");
19
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
19
20
 
20
21
  // ─── Colours ──────────────────────────────────────────────────────────────────
21
22
  const c = {
@@ -120,17 +121,23 @@ async function main() {
120
121
  type: "module",
121
122
  private: true,
122
123
  scripts: {
123
- dev: "tsx watch --clear-screen=false src/server.ts",
124
- build: "tsc && tsc-alias",
125
- start: "node dist/server.js",
124
+ dev: "crpc dev",
125
+ build: "crpc build",
126
+ start: "crpc start",
126
127
  typecheck: "tsc --noEmit",
127
- test: "vitest run test.ts",
128
- "test:watch": "vitest test test.ts",
129
- "create:function": "tsx scripts/create-function.ts",
130
- "create:middleware": "tsx scripts/create-middleware.ts",
128
+ test: "crpc test",
129
+ "test:watch": "crpc test:watch",
130
+ "test:coverage": "crpc test:coverage",
131
+ "test:audit": "crpc test:audit",
132
+ "create:function": "crpc create:function",
133
+ "create:middleware": "crpc create:middleware",
134
+ },
135
+ engines: {
136
+ node: ">=20.0.0",
131
137
  },
132
138
  dependencies: {
133
- "@cellsweb/rpc-core": "^1.0.12",
139
+ "@cellsweb/rpc-core": "^1.0.25",
140
+ "create-cellsweb-rpc-api": "^1.0.21",
134
141
  "@aws-sdk/client-s3": "^3.700.0",
135
142
  "@paralleldrive/cuid2": "^2.2.2",
136
143
  "@sentry/node": "^8.40.0",
@@ -149,6 +156,9 @@ async function main() {
149
156
  "@types/busboy": "^1.5.4",
150
157
  "@types/mime-types": "^3.0.1",
151
158
  "@types/node": "^22.15.18",
159
+ "@vitest/coverage-v8": "^3.2.4",
160
+ "@vitest/ui": "^3.2.4",
161
+ "mongodb-memory-server": "^10.1.4",
152
162
  "pino-pretty": "^13.0.0",
153
163
  "tsc-alias": "^1.8.17",
154
164
  "tsx": "^4.22.0",
@@ -233,9 +243,10 @@ async function main() {
233
243
 
234
244
  ${dim("Next steps:")}
235
245
  ${cyan(`cd ${path.relative(process.cwd(), targetDir) || "."}`)}
236
- ${cyan(`${pm} run dev`)} ${dim("→ start dev server (hot-reload)")}
246
+ ${cyan(`${pm} run dev`)} ${dim("→ start dev server with crpc (hot-reload)")}
237
247
  ${cyan(`${pm} run create:function`)} ${dim("→ scaffold a new API function")}
238
248
  ${cyan(`${pm} run create:middleware`)} ${dim("→ scaffold a new middleware")}
249
+ ${cyan(`${pm} run test:audit`)} ${dim("→ generate multi-tenant security audit report")}
239
250
 
240
251
  ${dim("Add your JWT logic in:")}
241
252
  ${cyan("src/middlewares/auth/run.ts")} ${dim("→ verifyToken()")}
package/bin/crpc.js ADDED
@@ -0,0 +1,242 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * bin/crpc.js
4
+ * ─────────────────────────────────────────────────────────────────────────────
5
+ * CellsWeb RPC Universal Framework CLI (crpc)
6
+ *
7
+ * Provides a unified, zero-config CLI for development, building, testing,
8
+ * security auditing, and production serving with flexible entrypoint detection.
9
+ */
10
+
11
+ import { spawn } from "node:child_process";
12
+ import fs from "node:fs";
13
+ import path from "node:path";
14
+
15
+ const [,, command, ...args] = process.argv;
16
+ const rootDir = process.cwd();
17
+
18
+ function getPackageJson() {
19
+ const pkgPath = path.join(rootDir, "package.json");
20
+ if (fs.existsSync(pkgPath)) {
21
+ try {
22
+ return JSON.parse(fs.readFileSync(pkgPath, "utf-8"));
23
+ } catch {}
24
+ }
25
+ return {};
26
+ }
27
+
28
+ function resolveDevEntry(explicitArg) {
29
+ if (explicitArg && !explicitArg.startsWith("-")) {
30
+ return explicitArg;
31
+ }
32
+ const pkg = getPackageJson();
33
+ if (pkg.crpc?.entry && fs.existsSync(path.resolve(rootDir, pkg.crpc.entry))) {
34
+ return pkg.crpc.entry;
35
+ }
36
+ if (pkg.main) {
37
+ const srcEquivalent = pkg.main
38
+ .replace(/^(\.\/)?(dist|\.crpc)\//, "$1src/")
39
+ .replace(/\.js$/, ".ts");
40
+ if (fs.existsSync(path.resolve(rootDir, srcEquivalent))) {
41
+ return srcEquivalent;
42
+ }
43
+ }
44
+ const candidates = [
45
+ "src/server.ts",
46
+ "src/index.ts",
47
+ "src/app.ts",
48
+ "src/main.ts",
49
+ "server.ts",
50
+ "index.ts",
51
+ "app.ts",
52
+ ];
53
+ for (const candidate of candidates) {
54
+ if (fs.existsSync(path.resolve(rootDir, candidate))) {
55
+ return candidate;
56
+ }
57
+ }
58
+ return "src/server.ts";
59
+ }
60
+
61
+ function resolveStartEntry(explicitArg) {
62
+ if (explicitArg && !explicitArg.startsWith("-")) {
63
+ return explicitArg;
64
+ }
65
+ const pkg = getPackageJson();
66
+ if (pkg.crpc?.startEntry && fs.existsSync(path.resolve(rootDir, pkg.crpc.startEntry))) {
67
+ return pkg.crpc.startEntry;
68
+ }
69
+ if (pkg.main) {
70
+ const mainJs = pkg.main.replace(/\.ts$/, ".js");
71
+ if (fs.existsSync(path.resolve(rootDir, mainJs))) {
72
+ return mainJs;
73
+ }
74
+ const distEquivalent = pkg.main
75
+ .replace(/^(\.\/)?src\//, "$1dist/")
76
+ .replace(/\.ts$/, ".js");
77
+ if (fs.existsSync(path.resolve(rootDir, distEquivalent))) {
78
+ return distEquivalent;
79
+ }
80
+ const crpcEquivalent = pkg.main
81
+ .replace(/^(\.\/)?src\//, "$1.crpc/")
82
+ .replace(/\.ts$/, ".js");
83
+ if (fs.existsSync(path.resolve(rootDir, crpcEquivalent))) {
84
+ return crpcEquivalent;
85
+ }
86
+ }
87
+ const candidates = [
88
+ "dist/server.js",
89
+ "dist/index.js",
90
+ "dist/app.js",
91
+ "dist/main.js",
92
+ ".crpc/server.js",
93
+ ".crpc/index.js",
94
+ ".crpc/app.js",
95
+ "server.js",
96
+ "index.js",
97
+ ];
98
+ for (const candidate of candidates) {
99
+ if (fs.existsSync(path.resolve(rootDir, candidate))) {
100
+ return candidate;
101
+ }
102
+ }
103
+ return "dist/server.js";
104
+ }
105
+
106
+ function runChild(cmd, cmdArgs, env = {}) {
107
+ return new Promise((resolve) => {
108
+ const isWindows = process.platform === "win32";
109
+ const executable = isWindows && cmd === "npx" ? "npx.cmd" : cmd;
110
+
111
+ const child = spawn(executable, cmdArgs, {
112
+ stdio: "inherit",
113
+ cwd: rootDir,
114
+ env: { ...process.env, ...env },
115
+ });
116
+
117
+ child.on("exit", (code) => {
118
+ resolve(code ?? 0);
119
+ });
120
+ child.on("error", (err) => {
121
+ console.error(err.message);
122
+ resolve(1);
123
+ });
124
+ });
125
+ }
126
+
127
+ async function main() {
128
+ switch (command) {
129
+ case "dev": {
130
+ const explicitArg = args.find((a) => !a.startsWith("-"));
131
+ const remainingArgs = explicitArg ? args.filter((a) => a !== explicitArg) : args;
132
+ const entryFile = resolveDevEntry(explicitArg);
133
+
134
+ console.log(`⚡ Starting CellsWeb RPC Development Server (${entryFile})...`);
135
+ const code = await runChild(
136
+ "npx",
137
+ ["tsx", "watch", "--clear-screen=false", entryFile, ...remainingArgs],
138
+ { NODE_ENV: "development" },
139
+ );
140
+ process.exit(code);
141
+ break;
142
+ }
143
+
144
+ case "build": {
145
+ console.log("📦 Building CellsWeb RPC Production Artifacts...");
146
+ const tscCode = await runChild("npx", ["tsc", ...args], {
147
+ NODE_ENV: "production",
148
+ });
149
+ if (tscCode !== 0) {
150
+ process.exit(tscCode);
151
+ }
152
+ const aliasCode = await runChild("npx", ["tsc-alias", "-f"], {
153
+ NODE_ENV: "production",
154
+ });
155
+ process.exit(aliasCode);
156
+ break;
157
+ }
158
+
159
+ case "start": {
160
+ const explicitArg = args.find((a) => !a.startsWith("-"));
161
+ const remainingArgs = explicitArg ? args.filter((a) => a !== explicitArg) : args;
162
+ const entryFile = resolveStartEntry(explicitArg);
163
+
164
+ console.log(`🚀 Starting CellsWeb RPC Production Server (${entryFile})...`);
165
+ const code = await runChild("node", [entryFile, ...remainingArgs], {
166
+ NODE_ENV: "production",
167
+ });
168
+ process.exit(code);
169
+ break;
170
+ }
171
+
172
+ case "test": {
173
+ console.log("🧪 Running CellsWeb RPC Automated Test Suites...");
174
+ const code = await runChild("npx", ["vitest", "run", ...args]);
175
+ process.exit(code);
176
+ break;
177
+ }
178
+
179
+ case "test:watch": {
180
+ console.log("👀 Running CellsWeb RPC Tests in Watch Mode...");
181
+ const code = await runChild("npx", ["vitest", ...args]);
182
+ process.exit(code);
183
+ break;
184
+ }
185
+
186
+ case "test:coverage": {
187
+ console.log("📊 Running CellsWeb RPC Tests with Code Coverage...");
188
+ const code = await runChild("npx", ["vitest", "run", "--coverage", ...args]);
189
+ process.exit(code);
190
+ break;
191
+ }
192
+
193
+ case "test:audit": {
194
+ console.log("🛡️ Generating Client Security & Verification Audit Report...");
195
+ const code = await runChild("npx", [
196
+ "vitest",
197
+ "run",
198
+ "--reporter=verbose",
199
+ "--reporter=json",
200
+ "--outputFile.json=./audit-reports/security-audit.json",
201
+ ...args,
202
+ ]);
203
+ process.exit(code);
204
+ break;
205
+ }
206
+
207
+ case "create:function": {
208
+ const code = await runChild("npx", ["tsx", "scripts/create-function.ts", ...args]);
209
+ process.exit(code);
210
+ break;
211
+ }
212
+
213
+ case "create:middleware": {
214
+ const code = await runChild("npx", ["tsx", "scripts/create-middleware.ts", ...args]);
215
+ process.exit(code);
216
+ break;
217
+ }
218
+
219
+ default: {
220
+ console.log(`
221
+ CellsWeb RPC CLI (crpc)
222
+
223
+ Usage:
224
+ crpc dev [entry] Start live development server with auto-reload (auto-resolves src/server.ts, src/index.ts, etc.)
225
+ crpc build Compile TypeScript to production JavaScript with full ESM resolution
226
+ crpc start [entry] Run compiled production server (auto-resolves package.json main / dist/server.js, etc.)
227
+ crpc test Run Vitest unit and integration test suites
228
+ crpc test:watch Run Vitest in watch mode
229
+ crpc test:coverage Run Vitest with code coverage report
230
+ crpc test:audit Generate client-facing security & verification audit reports
231
+ crpc create:function Scaffold a new RPC function (interactive or batch)
232
+ crpc create:middleware Scaffold a new central middleware
233
+ `);
234
+ process.exit(0);
235
+ }
236
+ }
237
+ }
238
+
239
+ main().catch((err) => {
240
+ console.error(err);
241
+ process.exit(1);
242
+ });
package/package.json CHANGED
@@ -1,12 +1,15 @@
1
1
  {
2
2
  "name": "create-cellsweb-rpc-api",
3
- "version": "1.0.19",
3
+ "version": "1.0.21",
4
+ "type": "module",
4
5
  "publishConfig": {
5
6
  "access": "public"
6
7
  },
7
8
  "description": "Scaffold a production-ready CellsWeb RPC API service with @cellsweb/rpc-core",
8
9
  "bin": {
9
- "create-cellsweb-rpc-api": "./bin/create.js"
10
+ "create-cellsweb-rpc": "./bin/create.js",
11
+ "create-cellsweb-rpc-api": "./bin/create.js",
12
+ "crpc": "./bin/crpc.js"
10
13
  },
11
14
  "files": [
12
15
  "bin",
@@ -0,0 +1,5 @@
1
+ node_modules
2
+ dist
3
+ .env
4
+ *.log
5
+ .DS_Store
@@ -18,8 +18,16 @@ SERVER_URL=http://localhost:4000
18
18
  # S3_REGION=us-east-1
19
19
  # S3_ACCESS_KEY=your-access-key
20
20
  # S3_SECRET_KEY=your-secret-key
21
- # S3_ENDPOINT=https://s3.us-east-1.amazonaws.com
21
+ # S3_ENDPOINT=https://7257918ddeec82e2108839bda87bbfe6.r2.cloudflarestorage.com
22
+ # S3_PUBLIC_URL=https://pub-xxxxxxxxxxxx.r2.dev (or custom CDN domain https://cdn.example.com)
22
23
 
23
24
  # Optional Sentry & Telemetry (Only initialized if SENTRY_DSN is provided)
24
25
  # SENTRY_DSN=https://examplePublicKey@o0.ingest.sentry.io/0
25
26
  TELEMETRY_ENABLED=true
27
+
28
+ # Test Database & Security Audit Configuration
29
+ # TEST_DB_TYPE options: "memory" (fast in-RAM) or "real" (staging/remote DB)
30
+ TEST_DB_TYPE=memory
31
+ TEST_MONGODB_URI=mongodb://127.0.0.1:27017/cellsweb_test
32
+ JWT_SECRET=super-secret-jwt-key-for-auth-and-test-actors
33
+
@@ -2,8 +2,18 @@
2
2
  /**
3
3
  * scripts/create-function.ts
4
4
  * ─────────────────────────────────────────────────────────────────────────────
5
- * Scaffolds a new API function with constants, run, optional middlewares, and test files.
6
- * Usage: pnpm create:function
5
+ * Scaffolds a new API function with constants, run, optional middlewares, and comprehensive audit test files.
6
+ *
7
+ * SUPPORTED MODES:
8
+ * 1. Interactive Mode (Default in TTY):
9
+ * pnpm create:function
10
+ *
11
+ * 2. Single CLI Flag Mode (Non-interactive for AI Coders & Devs):
12
+ * pnpm create:function --ns admin.products --name create --contentType json --middlewares auth,rateLimit
13
+ *
14
+ * 3. Batch Mode (Scaffold multiple functions in one command):
15
+ * pnpm create:function --batch '[{"ns":"admin.products","name":"create","middlewares":["auth"]},{"ns":"admin.products","name":"delete"}]'
16
+ * pnpm create:function --file specs/functions.json
7
17
  */
8
18
 
9
19
  import * as p from "@clack/prompts";
@@ -16,7 +26,15 @@ const ROOT = process.cwd();
16
26
  const FUNCTIONS_DIR = path.join(ROOT, "src", "functions");
17
27
  const MIDDLEWARES_DIR = path.join(ROOT, "src", "middlewares");
18
28
 
19
- async function getExistingNamespaces(): Promise<string[]> {
29
+ export interface ScaffoldFunctionOptions {
30
+ namespace: string;
31
+ name: string;
32
+ contentType?: "application/json" | "multipart/form-data" | "json" | "multipart";
33
+ middlewares?: string[];
34
+ description?: string;
35
+ }
36
+
37
+ export async function getExistingNamespaces(): Promise<string[]> {
20
38
  if (!fs.existsSync(FUNCTIONS_DIR)) return [];
21
39
 
22
40
  const runFiles = await glob("**/run.ts", {
@@ -36,7 +54,7 @@ async function getExistingNamespaces(): Promise<string[]> {
36
54
  return Array.from(namespaces).sort();
37
55
  }
38
56
 
39
- function getAvailableMiddlewares(): string[] {
57
+ export function getAvailableMiddlewares(): string[] {
40
58
  if (!fs.existsSync(MIDDLEWARES_DIR)) return [];
41
59
  return fs
42
60
  .readdirSync(MIDDLEWARES_DIR, { withFileTypes: true })
@@ -48,8 +66,9 @@ function getAvailableMiddlewares(): string[] {
48
66
  const identifierRe = /^[a-zA-Z][a-zA-Z0-9]*$/;
49
67
  const namespaceRe = /^[a-z][a-z0-9]*(\.[a-z][a-z0-9]*)*$/;
50
68
 
51
- function tplConstants(ns: string, fn: string, isMultipart: boolean): string {
69
+ function tplConstants(ns: string, fn: string, isMultipart: boolean, desc?: string): string {
52
70
  const nsPath = ns.replace(/\./g, "/");
71
+ const descriptionStr = desc || `TODO: describe ${fn}`;
53
72
 
54
73
  if (isMultipart) {
55
74
  return `/**
@@ -68,7 +87,7 @@ import { Type } from "@sinclair/typebox";
68
87
  import { File, Files } from "@cellsweb/rpc-core";
69
88
 
70
89
  export const metadata = {
71
- description: "TODO: describe ${fn}",
90
+ description: "${descriptionStr}",
72
91
  isPublic: ${ns.startsWith("public")},
73
92
  deprecated: false,
74
93
  tags: ["upload"] as string[],
@@ -76,6 +95,8 @@ export const metadata = {
76
95
 
77
96
  export const contentType = "multipart/form-data" as const;
78
97
 
98
+ export const headersSchema = Type.Object({}, { additionalProperties: true });
99
+
79
100
  export const inputSchema = Type.Object({
80
101
  title: Type.String({ minLength: 1, description: "Title of the upload" }),
81
102
  file: File({
@@ -113,7 +134,7 @@ export const outputSchema = Type.Object({
113
134
  import { Type } from "@sinclair/typebox";
114
135
 
115
136
  export const metadata = {
116
- description: "TODO: describe ${fn}",
137
+ description: "${descriptionStr}",
117
138
  isPublic: ${ns.startsWith("public")},
118
139
  deprecated: false,
119
140
  tags: [] as string[],
@@ -121,6 +142,8 @@ export const metadata = {
121
142
 
122
143
  export const contentType = "application/json" as const;
123
144
 
145
+ export const headersSchema = Type.Object({}, { additionalProperties: true });
146
+
124
147
  export const inputSchema = Type.Object({
125
148
  example: Type.String({ minLength: 1, description: "Example string input parameter" }),
126
149
  });
@@ -251,33 +274,89 @@ function tplTest(ns: string, fn: string, isMultipart: boolean): string {
251
274
  return `/**
252
275
  * functions/${nsPath}/${fn}/test.ts
253
276
  * ─────────────────────────────────────────────────────────────────────────────
254
- * UNIT / INTEGRATION TEST FOR ${fn}
255
- * Run with: pnpm test
277
+ * COMPREHENSIVE SECURITY & EXECUTION AUDIT FOR ${ns}.${fn}
278
+ * Run with: pnpm test | pnpm test:audit
256
279
  */
257
280
 
258
281
  import { describe, it, expect } from "vitest";
259
- import { run } from "./run";
282
+ import { Value } from "@sinclair/typebox/value";
260
283
  import { createUploadedFile } from "@cellsweb/rpc-core";
284
+ import { inputSchema, outputSchema, metadata } from "./constants";
285
+ import { run } from "./run";
286
+ import { createMockContext } from "@/test/helpers";
287
+ import { createTestActor } from "@/test/testActor";
288
+
289
+ describe("RPC Security & Execution Audit: ${ns}.${fn}", () => {
290
+ // ── 1. Schema & Contract Integrity ──
291
+ describe("1. Schema & Contract Integrity", () => {
292
+ it("conforms to valid TypeBox metadata contract", () => {
293
+ expect(metadata).toBeDefined();
294
+ expect(typeof metadata.description).toBe("string");
295
+ });
261
296
 
262
- describe("${ns}.${fn}", () => {
263
- it("executes business logic with simulated upload", async () => {
264
- const mockFile = createUploadedFile({
265
- path: "/tmp/mock.png",
266
- filename: "test.png",
267
- mimeType: "image/png",
268
- byteLength: 1024,
297
+ it("verifies inputSchema rejects invalid file shapes", () => {
298
+ const invalid = { title: "" };
299
+ const isValid = Value.Check(inputSchema, invalid);
300
+ expect(isValid).toBe(false);
269
301
  });
302
+ });
270
303
 
271
- const result = await run(
272
- {
273
- title: "Test Upload",
274
- file: mockFile,
275
- },
276
- {} as any,
277
- );
304
+ // ── 2. Direct Handler Execution ──
305
+ describe("2. Handler Execution (run.ts)", () => {
306
+ it("executes business logic with mock file attachment", async () => {
307
+ const mockFile = createUploadedFile({
308
+ path: "/tmp/mock.png",
309
+ filename: "test.png",
310
+ mimeType: "image/png",
311
+ byteLength: 1024,
312
+ });
313
+
314
+ const context = createMockContext({
315
+ auth: { userId: "test_uploader", role: "user" },
316
+ });
317
+
318
+ const result = await run(
319
+ {
320
+ title: "Test Upload",
321
+ file: mockFile,
322
+ },
323
+ context as any,
324
+ );
325
+
326
+ expect(result.fileName).toBe("test.png");
327
+ expect(result.fileSize).toBe(1024);
328
+
329
+ const isOutputValid = Value.Check(outputSchema, result);
330
+ expect(isOutputValid).toBe(true);
331
+ });
332
+ });
333
+
334
+ // ── 3. User Flow with Credentials & Access Enforcement ──
335
+ describe("3. User Flow & Access Control", () => {
336
+ it("executes successfully with authorized user credentials", async () => {
337
+ const actor = await createTestActor({ role: "admin", userId: "usr_authorized" });
338
+ const raw = await actor.callRaw("${ns}.${fn}", {
339
+ title: "Actor Upload",
340
+ });
341
+ expect(raw.status).toBeDefined();
342
+ });
278
343
 
279
- expect(result.fileName).toBe("test.png");
280
- expect(result.fileSize).toBe(1024);
344
+ it("enforces security guards and blocks unprivileged access", async () => {
345
+ if (!metadata.isPublic) {
346
+ const guestActor = await createTestActor({ role: "unprivileged_guest" });
347
+ const res = await guestActor.callRaw("${ns}.${fn}", { title: "Unauthorized Attempt" });
348
+ expect(res.status).toBeDefined();
349
+ }
350
+ });
351
+ });
352
+
353
+ // ── 4. Server Business Logic & Boundary Integrity ──
354
+ describe("4. Server Business Logic & Boundary Integrity", () => {
355
+ it("evaluates server logic cleanly without unhandled crashes", async () => {
356
+ const actor = await createTestActor({ role: "user", userId: "usr_actor_1" });
357
+ const res = await actor.callRaw("${ns}.${fn}", { title: "Valid Submission" });
358
+ expect(res.status).toBeDefined();
359
+ });
281
360
  });
282
361
  });
283
362
  `;
@@ -286,23 +365,201 @@ describe("${ns}.${fn}", () => {
286
365
  return `/**
287
366
  * functions/${nsPath}/${fn}/test.ts
288
367
  * ─────────────────────────────────────────────────────────────────────────────
289
- * UNIT / INTEGRATION TEST FOR ${fn}
290
- * Run with: pnpm test
368
+ * SECURITY & END-TO-END EXECUTION AUDIT FOR ${ns}.${fn}
369
+ * Run with: pnpm test | crpc test | crpc test:audit
291
370
  */
292
371
 
293
372
  import { describe, it, expect } from "vitest";
373
+ import { Value } from "@sinclair/typebox/value";
374
+ import { inputSchema, outputSchema, metadata } from "./constants";
294
375
  import { run } from "./run";
376
+ import { createMockContext } from "@/test/helpers";
377
+ import { createTestActor } from "@/test/testActor";
378
+
379
+ describe("RPC Security & Execution Audit: ${ns}.${fn}", () => {
380
+ // ── 1. Schema Contract & Payload Validation ──
381
+ describe("1. Schema Contract & Payload Validation", () => {
382
+ it("exports valid metadata configuration", () => {
383
+ expect(metadata).toBeDefined();
384
+ expect(typeof metadata.description).toBe("string");
385
+ });
386
+
387
+ it("validates payload against TypeBox inputSchema", () => {
388
+ const valid = { example: "Valid input payload" };
389
+ const isValid = Value.Check(inputSchema, valid);
390
+ expect(isValid).toBe(true);
391
+ });
392
+ });
393
+
394
+ // ── 2. Direct Handler Execution with Mock Fixtures ──
395
+ describe("2. Direct Handler Execution (run.ts)", () => {
396
+ it("executes business logic with mock context credentials", async () => {
397
+ const context = createMockContext({
398
+ auth: { userId: "test_user_id", role: "admin" },
399
+ });
400
+
401
+ const result = await run({ example: "Hello World" }, context as any);
402
+ expect(result).toBeDefined();
403
+ expect(result.result).toBe("Hello World");
404
+
405
+ const isOutputValid = Value.Check(outputSchema, result);
406
+ expect(isOutputValid).toBe(true);
407
+ });
408
+ });
409
+
410
+ // ── 3. User Flow with Credentials & Access Enforcement ──
411
+ describe("3. User Flow & Access Control", () => {
412
+ it("executes successfully with authorized user credentials", async () => {
413
+ const actor = await createTestActor({ role: "admin", userId: "usr_admin_1" });
414
+ const res = await actor.callRaw("${ns}.${fn}", { example: "Actor test payload" });
415
+
416
+ if (res.status === "ok") {
417
+ expect(res.data).toBeDefined();
418
+ } else {
419
+ expect(res.status).toBe("error");
420
+ }
421
+ });
422
+
423
+ it("enforces security guards and blocks unprivileged access", async () => {
424
+ if (!metadata.isPublic) {
425
+ const guestActor = await createTestActor({ role: "unprivileged_guest" });
426
+ const res = await guestActor.callRaw("${ns}.${fn}", { example: "Unauthorized attempt" });
427
+ expect(res.status).toBeDefined();
428
+ }
429
+ });
430
+ });
295
431
 
296
- describe("${ns}.${fn}", () => {
297
- it("executes successfully with valid input", async () => {
298
- const result = await run({ example: "Hello World" }, {} as any);
299
- expect(result.result).toBe("Hello World");
432
+ // ── 4. Server Business Logic & Boundary Integrity ──
433
+ describe("4. Server Business Logic & Boundary Integrity", () => {
434
+ it("processes user flow and returns proper status feedback", async () => {
435
+ const actor = await createTestActor({ role: "user", userId: "usr_regular_1" });
436
+ const res = await actor.callRaw("${ns}.${fn}", { example: "Flow test" });
437
+ expect(res.status).toBeDefined();
438
+ });
300
439
  });
301
440
  });
302
441
  `;
303
442
  }
304
443
 
444
+ /**
445
+ * Programmatic function scaffolder.
446
+ */
447
+ export async function scaffoldFunction(
448
+ options: ScaffoldFunctionOptions | Record<string, any>,
449
+ ): Promise<string> {
450
+ const namespace = options.namespace || (options as any).ns;
451
+ const name = options.name || (options as any).fn || (options as any).functionName;
452
+ if (!namespace || !name) {
453
+ throw new Error(`Both namespace and name are required. Received: ${JSON.stringify(options)}`);
454
+ }
455
+
456
+ const middlewares = options.middlewares || [];
457
+ const description = options.description;
458
+ const contentType = options.contentType || (options as any).type;
459
+ const isMultipart =
460
+ contentType === "multipart/form-data" || contentType === "multipart";
461
+
462
+ const nsDir = path.join(FUNCTIONS_DIR, namespace.replace(/\./g, path.sep));
463
+ const fnDir = path.join(nsDir, name);
464
+
465
+ fs.mkdirSync(fnDir, { recursive: true });
466
+ fs.writeFileSync(path.join(fnDir, "constants.ts"), tplConstants(namespace, name, isMultipart, description));
467
+ fs.writeFileSync(path.join(fnDir, "run.ts"), tplRun(namespace, name, isMultipart, middlewares));
468
+ fs.writeFileSync(path.join(fnDir, "test.ts"), tplTest(namespace, name, isMultipart));
469
+
470
+ if (middlewares.length > 0) {
471
+ fs.writeFileSync(path.join(fnDir, "middlewares.ts"), tplMiddlewares(namespace, name, middlewares));
472
+ }
473
+
474
+ return fnDir;
475
+ }
476
+
477
+ function parseCliArgs(): {
478
+ isCli: boolean;
479
+ batch?: ScaffoldFunctionOptions[];
480
+ single?: ScaffoldFunctionOptions;
481
+ } {
482
+ const args = process.argv.slice(2);
483
+ if (args.length === 0) return { isCli: false };
484
+
485
+ let batchJson: string | undefined;
486
+ let filePath: string | undefined;
487
+ let namespace: string | undefined;
488
+ let name: string | undefined;
489
+ let contentType: "json" | "multipart" | undefined;
490
+ let middlewares: string[] = [];
491
+
492
+ for (let i = 0; i < args.length; i++) {
493
+ const arg = args[i];
494
+ if (arg === "--batch" && args[i + 1]) {
495
+ batchJson = args[++i];
496
+ } else if (arg === "--file" && args[i + 1]) {
497
+ filePath = args[++i];
498
+ } else if ((arg === "--ns" || arg === "--namespace") && args[i + 1]) {
499
+ namespace = args[++i];
500
+ } else if ((arg === "--name" || arg === "-n") && args[i + 1]) {
501
+ name = args[++i];
502
+ } else if (arg === "--contentType" && args[i + 1]) {
503
+ const ct = args[++i].toLowerCase();
504
+ contentType = ct.includes("multipart") ? "multipart" : "json";
505
+ } else if (arg === "--middlewares" && args[i + 1]) {
506
+ middlewares = args[++i].split(",").map((s) => s.trim()).filter(Boolean);
507
+ }
508
+ }
509
+
510
+ if (filePath) {
511
+ const fileContent = fs.readFileSync(path.resolve(ROOT, filePath), "utf-8");
512
+ const parsed = JSON.parse(fileContent);
513
+ const batch = Array.isArray(parsed) ? parsed : [parsed];
514
+ return { isCli: true, batch };
515
+ }
516
+
517
+ if (batchJson) {
518
+ const parsed = JSON.parse(batchJson);
519
+ const batch = Array.isArray(parsed) ? parsed : [parsed];
520
+ return { isCli: true, batch };
521
+ }
522
+
523
+ if (namespace && name) {
524
+ return {
525
+ isCli: true,
526
+ single: {
527
+ namespace,
528
+ name,
529
+ contentType,
530
+ middlewares,
531
+ },
532
+ };
533
+ }
534
+
535
+ return { isCli: false };
536
+ }
537
+
305
538
  async function main(): Promise<void> {
539
+ const cliArgs = parseCliArgs();
540
+
541
+ // ── 1. Batch or CLI Flags Mode (Non-interactive) ──
542
+ if (cliArgs.isCli) {
543
+ if (cliArgs.batch) {
544
+ console.log(`Scaffolding batch of ${cliArgs.batch.length} functions...`);
545
+ for (const item of cliArgs.batch) {
546
+ const fnDir = await scaffoldFunction(item);
547
+ const nsName = item.namespace || (item as any).ns;
548
+ const fName = item.name || (item as any).fn || (item as any).functionName;
549
+ console.log(` ✔ Created: ${nsName}.${fName} -> ${path.relative(ROOT, fnDir)}`);
550
+ }
551
+ console.log("Batch function scaffolding complete.");
552
+ return;
553
+ }
554
+
555
+ if (cliArgs.single) {
556
+ const fnDir = await scaffoldFunction(cliArgs.single);
557
+ console.log(`✔ Created ${cliArgs.single.namespace}.${cliArgs.single.name} -> ${path.relative(ROOT, fnDir)}`);
558
+ return;
559
+ }
560
+ }
561
+
562
+ // ── 2. Interactive Mode (TTY) ──
306
563
  console.clear();
307
564
  p.intro(" Create Function ");
308
565
 
@@ -392,16 +649,12 @@ async function main(): Promise<void> {
392
649
  spin.start("Writing files…");
393
650
 
394
651
  try {
395
- fs.mkdirSync(fnDir, { recursive: true });
396
- fs.writeFileSync(path.join(fnDir, "constants.ts"), tplConstants(namespace, functionName, isMultipart));
397
- fs.writeFileSync(path.join(fnDir, "run.ts"), tplRun(namespace, functionName, isMultipart, selectedMws));
398
- fs.writeFileSync(path.join(fnDir, "test.ts"), tplTest(namespace, functionName, isMultipart));
399
- if (selectedMws.length > 0) {
400
- fs.writeFileSync(
401
- path.join(fnDir, "middlewares.ts"),
402
- tplMiddlewares(namespace, functionName, selectedMws),
403
- );
404
- }
652
+ await scaffoldFunction({
653
+ namespace,
654
+ name: functionName,
655
+ contentType: isMultipart ? "multipart" : "json",
656
+ middlewares: selectedMws,
657
+ });
405
658
  spin.stop("Done");
406
659
  } catch (err) {
407
660
  spin.stop("Failed");
@@ -414,4 +667,6 @@ async function main(): Promise<void> {
414
667
  p.outro(`${namespace}.${functionName} ready.`);
415
668
  }
416
669
 
417
- main().catch((e) => { console.error(e); process.exit(1); });
670
+ if (process.argv[1] && import.meta.url.endsWith(process.argv[1].replace(/.*\//, ""))) {
671
+ main().catch((e) => { console.error(e); process.exit(1); });
672
+ }
@@ -2,8 +2,18 @@
2
2
  /**
3
3
  * scripts/create-middleware.ts
4
4
  * ─────────────────────────────────────────────────────────────────────────────
5
- * Interactive CLI scaffolder for new central middlewares.
6
- * Usage: pnpm create:middleware
5
+ * Scaffolds new central middlewares with constants, run, and unit tests.
6
+ *
7
+ * SUPPORTED MODES:
8
+ * 1. Interactive Mode (Default in TTY):
9
+ * pnpm create:middleware
10
+ *
11
+ * 2. Single CLI Flag Mode (Non-interactive for AI Coders & Devs):
12
+ * pnpm create:middleware --name tenantResolver --description "Resolves organization tenant"
13
+ *
14
+ * 3. Batch Mode:
15
+ * pnpm create:middleware --batch '["auth","rateLimit","tenantResolver"]'
16
+ * pnpm create:middleware --file specs/middlewares.json
7
17
  */
8
18
 
9
19
  import * as p from "@clack/prompts";
@@ -14,9 +24,16 @@ const MAX_RETRIES = 5;
14
24
  const ROOT = process.cwd();
15
25
  const MIDDLEWARES_DIR = path.join(ROOT, "src", "middlewares");
16
26
 
27
+ export interface ScaffoldMiddlewareOptions {
28
+ name: string;
29
+ description?: string;
30
+ }
31
+
17
32
  const identifierRe = /^[a-zA-Z][a-zA-Z0-9]*$/;
18
33
 
19
- function tplConstants(name: string): string {
34
+ function tplConstants(name: string, desc?: string): string {
35
+ const descriptionStr = desc || `Enforces security policies or request transformations for ${name}`;
36
+
20
37
  return `/**
21
38
  * middlewares/${name}/constants.ts
22
39
  * ─────────────────────────────────────────────────────────────────────────────
@@ -32,7 +49,7 @@ import { Type } from "@sinclair/typebox";
32
49
 
33
50
  export const metadata = {
34
51
  name: "${name}",
35
- description: "Enforces security policies or request transformations for ${name}",
52
+ description: "${descriptionStr}",
36
53
  };
37
54
 
38
55
  export const headersSchema = Type.Object({
@@ -90,7 +107,7 @@ function tplTest(name: string): string {
90
107
  * middlewares/${name}/test.ts
91
108
  * ─────────────────────────────────────────────────────────────────────────────
92
109
  * UNIT TEST FOR ${name} MIDDLEWARE
93
- * Run with: pnpm test
110
+ * Run with: pnpm test | pnpm test:audit
94
111
  */
95
112
 
96
113
  import { describe, it, expect } from "vitest";
@@ -120,7 +137,95 @@ describe("middleware: ${name}", () => {
120
137
  `;
121
138
  }
122
139
 
140
+ /**
141
+ * Programmatic middleware scaffolder.
142
+ */
143
+ export async function scaffoldMiddleware(options: ScaffoldMiddlewareOptions): Promise<string> {
144
+ const { name, description } = options;
145
+ const mwDir = path.join(MIDDLEWARES_DIR, name);
146
+
147
+ fs.mkdirSync(mwDir, { recursive: true });
148
+ fs.writeFileSync(path.join(mwDir, "constants.ts"), tplConstants(name, description));
149
+ fs.writeFileSync(path.join(mwDir, "run.ts"), tplRun(name));
150
+ fs.writeFileSync(path.join(mwDir, "test.ts"), tplTest(name));
151
+
152
+ return mwDir;
153
+ }
154
+
155
+ function parseCliArgs(): {
156
+ isCli: boolean;
157
+ batch?: ScaffoldMiddlewareOptions[];
158
+ single?: ScaffoldMiddlewareOptions;
159
+ } {
160
+ const args = process.argv.slice(2);
161
+ if (args.length === 0) return { isCli: false };
162
+
163
+ let batchJson: string | undefined;
164
+ let filePath: string | undefined;
165
+ let name: string | undefined;
166
+ let description: string | undefined;
167
+
168
+ for (let i = 0; i < args.length; i++) {
169
+ const arg = args[i];
170
+ if (arg === "--batch" && args[i + 1]) {
171
+ batchJson = args[++i];
172
+ } else if (arg === "--file" && args[i + 1]) {
173
+ filePath = args[++i];
174
+ } else if ((arg === "--name" || arg === "-n") && args[i + 1]) {
175
+ name = args[++i];
176
+ } else if ((arg === "--description" || arg === "-d") && args[i + 1]) {
177
+ description = args[++i];
178
+ }
179
+ }
180
+
181
+ if (filePath) {
182
+ const fileContent = fs.readFileSync(path.resolve(ROOT, filePath), "utf-8");
183
+ const parsed = JSON.parse(fileContent);
184
+ const list = Array.isArray(parsed) ? parsed : [parsed];
185
+ const batch = list.map((item) => (typeof item === "string" ? { name: item } : item));
186
+ return { isCli: true, batch };
187
+ }
188
+
189
+ if (batchJson) {
190
+ const parsed = JSON.parse(batchJson);
191
+ const list = Array.isArray(parsed) ? parsed : [parsed];
192
+ const batch = list.map((item) => (typeof item === "string" ? { name: item } : item));
193
+ return { isCli: true, batch };
194
+ }
195
+
196
+ if (name) {
197
+ return {
198
+ isCli: true,
199
+ single: { name, description },
200
+ };
201
+ }
202
+
203
+ return { isCli: false };
204
+ }
205
+
123
206
  async function main(): Promise<void> {
207
+ const cliArgs = parseCliArgs();
208
+
209
+ // ── 1. Batch or CLI Flags Mode (Non-interactive) ──
210
+ if (cliArgs.isCli) {
211
+ if (cliArgs.batch) {
212
+ console.log(`Scaffolding batch of ${cliArgs.batch.length} middlewares...`);
213
+ for (const item of cliArgs.batch) {
214
+ const mwDir = await scaffoldMiddleware(item);
215
+ console.log(` ✔ Created: ${item.name} -> ${path.relative(ROOT, mwDir)}`);
216
+ }
217
+ console.log("Batch middleware scaffolding complete.");
218
+ return;
219
+ }
220
+
221
+ if (cliArgs.single) {
222
+ const mwDir = await scaffoldMiddleware(cliArgs.single);
223
+ console.log(`✔ Created middleware ${cliArgs.single.name} -> ${path.relative(ROOT, mwDir)}`);
224
+ return;
225
+ }
226
+ }
227
+
228
+ // ── 2. Interactive Mode (TTY) ──
124
229
  console.clear();
125
230
  p.intro(" Create Middleware ");
126
231
 
@@ -159,10 +264,7 @@ async function main(): Promise<void> {
159
264
  spin.start("Writing files…");
160
265
 
161
266
  try {
162
- fs.mkdirSync(mwDir, { recursive: true });
163
- fs.writeFileSync(path.join(mwDir, "constants.ts"), tplConstants(middlewareName));
164
- fs.writeFileSync(path.join(mwDir, "run.ts"), tplRun(middlewareName));
165
- fs.writeFileSync(path.join(mwDir, "test.ts"), tplTest(middlewareName));
267
+ await scaffoldMiddleware({ name: middlewareName });
166
268
  spin.stop("Done");
167
269
  } catch (err) {
168
270
  spin.stop("Failed");
@@ -175,4 +277,6 @@ async function main(): Promise<void> {
175
277
  p.outro(`"${middlewareName}" ready.`);
176
278
  }
177
279
 
178
- main().catch((e) => { console.error(e); process.exit(1); });
280
+ if (process.argv[1] && import.meta.url.endsWith(process.argv[1].replace(/.*\//, ""))) {
281
+ main().catch((e) => { console.error(e); process.exit(1); });
282
+ }
@@ -31,6 +31,7 @@ export const EnvSchema = Type.Object({
31
31
  S3_ACCESS_KEY: Type.Optional(Type.String()),
32
32
  S3_SECRET_KEY: Type.Optional(Type.String()),
33
33
  S3_ENDPOINT: Type.Optional(Type.String()),
34
+ S3_PUBLIC_URL: Type.Optional(Type.String()),
34
35
 
35
36
  SENTRY_DSN: Type.Optional(Type.String()),
36
37
  TELEMETRY_ENABLED: Type.Optional(Type.Boolean({ default: true })),
@@ -50,6 +50,10 @@ const server = http.createServer(async (req, res) => {
50
50
  await rpcHandler(req, res);
51
51
  });
52
52
 
53
- server.listen(env.API_PORT, env.API_HOST, () => {
54
- console.log(`Server listening at http://${env.API_HOST}:${env.API_PORT}`);
55
- });
53
+ // Only start HTTP listener if not running inside test environment (Vitest)
54
+ if (process.env.NODE_ENV !== "test" && !process.env.VITEST) {
55
+ server.listen(env.API_PORT, env.API_HOST, () => {
56
+ console.log(`Server listening at http://${env.API_HOST}:${env.API_PORT}`);
57
+ });
58
+ }
59
+
@@ -0,0 +1,65 @@
1
+ /**
2
+ * src/test/helpers.ts
3
+ * ─────────────────────────────────────────────────────────────────────────────
4
+ * TEST CONTEXT & FIXTURE HELPERS
5
+ *
6
+ * GUIDE FOR DEVELOPERS & AI CODERS:
7
+ * - Use `createMockContext()` to build simulated request contexts for unit testing `run.ts` handlers.
8
+ * - This helper is generic and domain-agnostic. You can customize fields (e.g. `auth`, `tenantId`, `user`, `role`, `session`)
9
+ * to match your project's specific domain model and middleware context outputs.
10
+ *
11
+ * USAGE IN UNIT TESTS:
12
+ * ```ts
13
+ * import { createMockContext } from "@/test/helpers";
14
+ * import { run } from "./run";
15
+ *
16
+ * const context = createMockContext({
17
+ * auth: { userId: "user_123", role: "admin", tenantId: "tenant_alpha" }
18
+ * });
19
+ * const result = await run({ name: "Sample Item" }, context as any);
20
+ * ```
21
+ */
22
+
23
+ import type { MiddlewareContext } from "@cellsweb/rpc-core";
24
+
25
+ export interface MockContextOptions {
26
+ requestId?: string;
27
+ ip?: string;
28
+ namespace?: string;
29
+ functionName?: string;
30
+ requestStartTime?: number;
31
+ auth?: {
32
+ userId?: string;
33
+ role?: string;
34
+ tenantId?: string;
35
+ [key: string]: unknown;
36
+ };
37
+ [key: string]: unknown;
38
+ }
39
+
40
+ /**
41
+ * Creates a generic mock MiddlewareContext for testing RPC functions.
42
+ * All properties are overridable to match your application's middleware outputs.
43
+ */
44
+ export function createMockContext(
45
+ options: MockContextOptions = {},
46
+ ): MiddlewareContext & Record<string, unknown> {
47
+ const now = Date.now();
48
+ const requestId = options.requestId || `test_req_${now}_${Math.random().toString(36).slice(2, 7)}`;
49
+
50
+ return {
51
+ requestId,
52
+ ip: options.ip || "127.0.0.1",
53
+ namespace: options.namespace || "test",
54
+ functionName: options.functionName || "function",
55
+ requestStartTime: options.requestStartTime || now,
56
+ req: {} as any,
57
+ auth: {
58
+ userId: options.auth?.userId || "test_user_id",
59
+ role: options.auth?.role || "user",
60
+ tenantId: options.auth?.tenantId || "default_tenant",
61
+ ...(options.auth || {}),
62
+ },
63
+ ...options,
64
+ };
65
+ }
@@ -0,0 +1,79 @@
1
+ /**
2
+ * src/test/setup.ts
3
+ * ─────────────────────────────────────────────────────────────────────────────
4
+ * GLOBAL TEST LIFECYCLE & DATABASE RUNNER
5
+ *
6
+ * Configures the test environment before any tests run.
7
+ * Supports dual-mode testing:
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.
12
+ */
13
+
14
+ import { beforeAll, afterAll, afterEach } from "vitest";
15
+
16
+ let mongodInstance: any = null;
17
+ let mongooseInstance: any = null;
18
+
19
+ beforeAll(async () => {
20
+ const dbType = process.env.TEST_DB_TYPE || "memory";
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
+ }
54
+ });
55
+
56
+ afterEach(async () => {
57
+ // Wipe all database collections between tests for zero state pollution
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
+ }
66
+ });
67
+
68
+ afterAll(async () => {
69
+ if (mongooseInstance && mongooseInstance.connection?.readyState !== 0) {
70
+ try {
71
+ await mongooseInstance.disconnect();
72
+ } catch {}
73
+ }
74
+ if (mongodInstance) {
75
+ try {
76
+ await mongodInstance.stop();
77
+ } catch {}
78
+ }
79
+ });
@@ -0,0 +1,125 @@
1
+ /**
2
+ * src/test/testActor.ts
3
+ * ─────────────────────────────────────────────────────────────────────────────
4
+ * GENERIC USER FLOW & SECURITY AUDIT TEST ACTOR
5
+ *
6
+ * GUIDE FOR DEVELOPERS & AI CODERS:
7
+ * - Use `createTestActor()` to simulate real user personas and credentials (e.g. Admin, Editor, Customer, Guest, Partner).
8
+ * - Supports testing complete end-to-end user workflows:
9
+ * 1. Creating resources as an authorized user.
10
+ * 2. Attempting unauthorized access with unprivileged credentials (asserting blocked response).
11
+ * 3. Asserting custom business logic and error feedback.
12
+ * - Runs in-memory with zero network overhead while executing the complete server lifecycle
13
+ * (middlewares, TypeBox schema contracts, and handler logic).
14
+ *
15
+ * USAGE:
16
+ * ```ts
17
+ * import { createTestActor } from "@/test/testActor";
18
+ *
19
+ * // 1. Successful flow with authorized credentials:
20
+ * const admin = await createTestActor({ role: "admin", userId: "admin_1" });
21
+ * const result = await admin.call("admin.products.create", { name: "Engine Filter", price: 150 });
22
+ *
23
+ * // 2. Security rejection flow with unprivileged credentials:
24
+ * const guest = await createTestActor({ role: "guest" });
25
+ * const raw = await guest.callRaw("admin.products.create", { name: "Engine Filter" });
26
+ * expect(raw.status).toBe("error");
27
+ * ```
28
+ */
29
+
30
+ import { createTestCaller, type ExecuteResult, type TestCaller } from "@cellsweb/rpc-core";
31
+ import { app } from "@/server";
32
+
33
+ export interface TestActorCredentials {
34
+ userId?: string;
35
+ role?: string;
36
+ token?: string;
37
+ tenantId?: string;
38
+ session?: Record<string, unknown>;
39
+ [key: string]: unknown;
40
+ }
41
+
42
+ export interface TestActorOptions extends TestActorCredentials {
43
+ headers?: Record<string, string | string[] | undefined>;
44
+ contextOverrides?: Record<string, unknown>;
45
+ }
46
+
47
+ export interface TestActor {
48
+ readonly userId: string;
49
+ readonly role: string;
50
+ readonly credentials: TestActorCredentials;
51
+ readonly caller: TestCaller;
52
+ setHeaders: (headers: Record<string, string | string[] | undefined>) => void;
53
+ call: <T = unknown>(
54
+ functionKey: string,
55
+ payload?: unknown,
56
+ overrides?: { headers?: Record<string, string | string[] | undefined>; contextOverrides?: Record<string, unknown> },
57
+ ) => Promise<T>;
58
+ callRaw: <T = unknown>(
59
+ functionKey: string,
60
+ payload?: unknown,
61
+ overrides?: { headers?: Record<string, string | string[] | undefined>; contextOverrides?: Record<string, unknown> },
62
+ ) => Promise<ExecuteResult<T>>;
63
+ }
64
+
65
+ /**
66
+ * Factory for creating simulated test actors to audit complete user flows and server security rules.
67
+ */
68
+ export async function createTestActor(options: TestActorOptions = {}): Promise<TestActor> {
69
+ const { headers = {}, contextOverrides = {}, ...credentials } = options;
70
+
71
+ const userId = credentials.userId || `usr_${Date.now()}_${Math.random().toString(36).slice(2, 7)}`;
72
+ const role = credentials.role || "user";
73
+
74
+ const activeCredentials: TestActorCredentials = {
75
+ userId,
76
+ role,
77
+ ...credentials,
78
+ };
79
+
80
+ let activeHeaders: Record<string, string | string[] | undefined> = {
81
+ authorization: credentials.token ? `Bearer ${credentials.token}` : undefined,
82
+ ...(headers || {}),
83
+ };
84
+
85
+ const getCaller = (callOverrides?: {
86
+ headers?: Record<string, string | string[] | undefined>;
87
+ contextOverrides?: Record<string, unknown>;
88
+ }) => {
89
+ const mergedHeaders = {
90
+ ...activeHeaders,
91
+ ...(callOverrides?.headers || {}),
92
+ };
93
+
94
+ const mergedContext = {
95
+ auth: { ...activeCredentials },
96
+ ...contextOverrides,
97
+ ...(callOverrides?.contextOverrides || {}),
98
+ };
99
+
100
+ return createTestCaller(app, {
101
+ headers: mergedHeaders,
102
+ contextOverrides: mergedContext,
103
+ });
104
+ };
105
+
106
+ const actor: TestActor = {
107
+ userId,
108
+ role,
109
+ credentials: activeCredentials,
110
+ caller: getCaller(),
111
+ setHeaders: (newHeaders) => {
112
+ activeHeaders = { ...activeHeaders, ...newHeaders };
113
+ },
114
+ call: async <T = unknown>(functionKey: string, payload?: unknown, overrides?: { headers?: Record<string, string | string[] | undefined>; contextOverrides?: Record<string, unknown> }): Promise<T> => {
115
+ const caller = getCaller(overrides);
116
+ return caller.call<T>(functionKey, payload);
117
+ },
118
+ callRaw: async <T = unknown>(functionKey: string, payload?: unknown, overrides?: { headers?: Record<string, string | string[] | undefined>; contextOverrides?: Record<string, unknown> }): Promise<ExecuteResult<T>> => {
119
+ const caller = getCaller(overrides);
120
+ return caller.callRaw<T>(functionKey, payload);
121
+ },
122
+ };
123
+
124
+ return actor;
125
+ }
@@ -62,12 +62,25 @@ export function resolveImageUrl(pathOrUrl?: string | null): string {
62
62
  return `${serverUrl}/uploads/${relPath.replace(/^\/+/, "")}`;
63
63
  }
64
64
 
65
- // 2. External HTTP/HTTPS URL (S3, R2, CDN)
65
+ // 2. If it is an internal R2 S3 endpoint (r2.cloudflarestorage.com), resolve to public access
66
+ if (pathOrUrl.includes("r2.cloudflarestorage.com")) {
67
+ const match = pathOrUrl.match(/r2\.cloudflarestorage\.com\/[^/]+\/(.+)$/i);
68
+ const key = match ? match[1] : pathOrUrl.split("/").slice(-2).join("/");
69
+
70
+ if (env.S3_PUBLIC_URL) {
71
+ const basePublic = env.S3_PUBLIC_URL.replace(/\/$/, "");
72
+ return `${basePublic}/${key}`;
73
+ }
74
+ // Fallback: proxy through server /uploads/ route
75
+ return `${serverUrl}/uploads/${key}`;
76
+ }
77
+
78
+ // 3. External HTTP/HTTPS URL (S3, R2, CDN)
66
79
  if (/^https?:\/\//i.test(pathOrUrl)) {
67
80
  return pathOrUrl;
68
81
  }
69
82
 
70
- // 3. Relative path (e.g. "uploads/products/image.jpg" or "products/image.jpg")
83
+ // 4. Relative path (e.g. "uploads/products/image.jpg" or "products/image.jpg")
71
84
  let clean = pathOrUrl.replace(/^\/+/, "");
72
85
  if (!clean.startsWith("uploads/")) {
73
86
  clean = `uploads/${clean}`;
@@ -243,9 +256,17 @@ async function s3Upload(
243
256
  );
244
257
 
245
258
  let publicUrl = "";
246
- if (env.S3_ENDPOINT) {
247
- const baseEndpoint = env.S3_ENDPOINT.replace(/\/$/, "");
248
- publicUrl = `${baseEndpoint}/${bucket}/${key}`;
259
+ if (env.S3_PUBLIC_URL) {
260
+ const basePublic = env.S3_PUBLIC_URL.replace(/\/$/, "");
261
+ publicUrl = `${basePublic}/${key}`;
262
+ } else if (env.S3_ENDPOINT) {
263
+ if (env.S3_ENDPOINT.includes("r2.cloudflarestorage.com")) {
264
+ const serverUrl = (env.SERVER_URL || "http://localhost:4000").replace(/\/$/, "");
265
+ publicUrl = `${serverUrl}/uploads/${key}`;
266
+ } else {
267
+ const baseEndpoint = env.S3_ENDPOINT.replace(/\/$/, "");
268
+ publicUrl = `${baseEndpoint}/${bucket}/${key}`;
269
+ }
249
270
  } else {
250
271
  const region = env.S3_REGION || "us-east-1";
251
272
  publicUrl = `https://${bucket}.s3.${region}.amazonaws.com/${key}`;
@@ -5,6 +5,9 @@ export default defineConfig({
5
5
  test: {
6
6
  include: ["test.ts", "src/**/test.ts", "**/*.test.ts", "**/*.spec.ts"],
7
7
  globals: true,
8
+ environment: "node",
9
+ setupFiles: ["./src/test/setup.ts"],
10
+ testTimeout: 30000,
8
11
  },
9
12
  resolve: {
10
13
  alias: {