@caprogramacion/mongo-call 0.0.0-stage → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,3 +1,195 @@
1
- # Temporary Holding Version
1
+ # @caprogramacion/mongo-call
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Firebase `onCall`-style RPC wrapper for MongoDB, replicating the `firebase-functions`
4
+ developer experience (`onCall` / `httpsCallable`) over Express + MongoDB with
5
+ production-grade security enabled by default.
6
+
7
+ - **Encapsulated dependencies**: `mongodb`, `express`, `ajv`, `jose`, `helmet`,
8
+ `express-rate-limit`, `swagger-ui-express`, `cookie-parser`.
9
+ - **DB-backed authentication**: JWT sessions verified against the `users` collection
10
+ (active flag + `tokenVersion` revocation), roles resolved from `users` + `_roles`.
11
+ - **Role-based `onCall`**: each function can require authentication and/or a list of
12
+ allowed roles; no role configured means the function is public.
13
+ - **Hardened by default**: NoSQL-injection sanitizer, prototype-pollution protection,
14
+ JWT entropy/algorithm validation, CSRF double-submit for cookie sessions, rate
15
+ limiting, Helmet, CORS allowlists, Swagger hidden in production.
16
+
17
+ > Node.js **>= 22** required. The server entry is **ESM-only** (uses `jose` 6); the
18
+ > `./client` entry ships both ESM and CJS.
19
+
20
+ ## Install
21
+
22
+ ```bash
23
+ pnpm add @caprogramacion/mongo-call
24
+ # optional: argon2 for Argon2id hashing (falls back to node:crypto scrypt)
25
+ pnpm add argon2
26
+ ```
27
+
28
+ ## Environment (.env)
29
+
30
+ Copy `.env.example` to `.env`. Only `MONGO_URI` and `JWT_SECRET` (>= 32 chars) are
31
+ required when auth is enabled.
32
+
33
+ ```env
34
+ MONGO_URI=mongodb://localhost:27017
35
+ MONGO_DB_NAME=app
36
+ USERS_COLLECTION=users
37
+ ROLES_COLLECTION=_roles
38
+
39
+ JWT_SECRET=replace_with_at_least_32_random_characters_secret
40
+ JWT_TTL_SECONDS=28800
41
+ JWT_ISSUER=api.example.com
42
+ JWT_AUDIENCE=web-app
43
+
44
+ AUTH_ENABLED=true
45
+ AUTH_COOKIES_ENABLED=true
46
+ COOKIE_SECURE=false
47
+
48
+ CORS_ORIGINS=https://app.example.com,https://admin.example.com
49
+ PORT=4000
50
+ TRUST_PROXY=1
51
+ ```
52
+
53
+ ## Server
54
+
55
+ ```ts
56
+ import {
57
+ onCall,
58
+ startCallServer,
59
+ CallError,
60
+ toObjectId,
61
+ SignJWT
62
+ } from '@caprogramacion/mongo-call'
63
+
64
+ const signIn = onCall<{ email: string; password: string }>(
65
+ {
66
+ tags: ['Authentication'],
67
+ summary: 'Sign in and issue a JWT',
68
+ rateLimit: { windowMs: 60_000, max: 5 },
69
+ paramsSchema: {
70
+ type: 'object',
71
+ required: ['email', 'password'],
72
+ additionalProperties: false,
73
+ properties: {
74
+ email: { type: 'string', format: 'email' },
75
+ password: { type: 'string', minLength: 8 }
76
+ }
77
+ }
78
+ },
79
+ async (data, { db }) => {
80
+ const user = await db.collection('users').findOne({ email: data.email })
81
+ if (!user) throw new CallError('unauthenticated', 'Invalid credentials.')
82
+ // ...
83
+ return { token: '...' }
84
+ }
85
+ )
86
+
87
+ const getProduct = onCall<{ productId: string }>(
88
+ {
89
+ roles: ['admin', 'viewer'],
90
+ paramsSchema: {
91
+ type: 'object',
92
+ required: ['productId'],
93
+ additionalProperties: false,
94
+ properties: { productId: { type: 'string', format: 'objectid' } }
95
+ }
96
+ },
97
+ async (data, { db }) => {
98
+ const id = toObjectId(data.productId, 'productId')
99
+ const product = await db.collection('products').findOne({ _id: id })
100
+ if (!product) throw new CallError('not-found', 'Product not found.')
101
+ return product
102
+ }
103
+ )
104
+
105
+ startCallServer({ signIn, getProduct }, 4000, {
106
+ trustProxy: 1,
107
+ corsOrigin: ['https://app.example.com'],
108
+ jwtOptions: {
109
+ issuer: 'api.example.com',
110
+ audience: 'web-app',
111
+ algorithms: ['HS256']
112
+ }
113
+ })
114
+ ```
115
+
116
+ ### Authorization semantics
117
+
118
+ | Configuration | Behaviour |
119
+ | --- | --- |
120
+ | no `roles`, no `requireAuth` | Public function (auth resolved if a token is present) |
121
+ | `requireAuth: true` | Any valid session (active user, matching `tokenVersion`) |
122
+ | `roles: ['admin']` | Auth required + caller role must be `admin` (`superadmin` bypasses) |
123
+ | `writeAccess: true` | Read-only roles (`readOnly` in `_roles`) are rejected (403) |
124
+
125
+ The handler context exposes `{ db, auth, rawHeaders }` where `auth` is
126
+ `{ uid, userDocId, email, role, readOnly, authMethod, claims, user }`.
127
+
128
+ ### Built-in auth endpoints
129
+
130
+ When `AUTH_ENABLED` is not disabled, the server mounts:
131
+
132
+ - `POST {base}/auth/login` — email + password, returns a JWT (and cookies when enabled)
133
+ - `GET {base}/auth/me` — current user + resolved role
134
+ - `POST {base}/auth/change-password` — rotates `tokenVersion` (revokes previous tokens)
135
+ - `POST {base}/auth/logout` — clears session cookies
136
+
137
+ The library connects to an existing MongoDB and assumes the `users` and `_roles`
138
+ collections already exist. Users store a `role` field; role metadata
139
+ (`isActive`, `readOnly`) lives in `_roles`.
140
+
141
+ ## Client SDK
142
+
143
+ ```ts
144
+ import { createCallClient } from '@caprogramacion/mongo-call/client'
145
+
146
+ const client = createCallClient({
147
+ baseUrl: 'http://localhost:4000',
148
+ getToken: async () => localStorage.getItem('token'),
149
+ csrf: true,
150
+ credentials: 'include'
151
+ })
152
+
153
+ const { data } = await client.httpsCallable<{ productId: string }, { name: string }>(
154
+ 'getProduct'
155
+ )({ productId: '507f1f77bcf86cd799439011' })
156
+ ```
157
+
158
+ Errors are thrown as `CallError` with a stable `code`
159
+ (`invalid-argument`, `unauthenticated`, `permission-denied`, `not-found`, ...).
160
+
161
+ ## Swagger UI
162
+
163
+ Auto-generated from `onCall` options. Enabled by default in development and disabled
164
+ when `NODE_ENV=production`. Set `SWAGGER_ENABLED=true` to force it on.
165
+
166
+ ```env
167
+ SWAGGER_PATH=/docs
168
+ API_TITLE=My API
169
+ API_VERSION=1.0.0
170
+ ```
171
+
172
+ ## Security matrix
173
+
174
+ | Vector | Defense |
175
+ | --- | --- |
176
+ | NoSQL injection (`$ne`, `$where`) | Recursive `sanitizeNoSqlPayload` before AJV (default `reject`) |
177
+ | Prototype pollution | Dangerous key inspection + `Object.hasOwn` routing |
178
+ | JWT downgrade / `alg: none` | `jose` with `algorithms`, `issuer`, `audience` + 256-bit secret |
179
+ | Stolen/revoked sessions | `tokenVersion` + `isActive` checked per request against MongoDB |
180
+ | Brute force / DoS | Global + per-function + strict auth rate limiting |
181
+ | CSRF (cookie sessions) | Double-submit cookie + `timingSafeEqual`, `SameSite=lax` |
182
+ | CORS open in prod | Explicit allowlist required in production |
183
+ | Docs exposure in prod | Swagger disabled when `NODE_ENV=production` |
184
+ | Stack trace / BSON leaks | `CallError` mapping + `toObjectId` / `objectid` format |
185
+
186
+ ## Development
187
+
188
+ ```bash
189
+ pnpm install
190
+ pnpm typecheck
191
+ pnpm test
192
+ pnpm build
193
+ ```
194
+
195
+ See `docs/architecture.md` for the internal layout and extension points.
@@ -0,0 +1,113 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/client/index.ts
21
+ var client_exports = {};
22
+ __export(client_exports, {
23
+ CallError: () => CallError,
24
+ createCallClient: () => createCallClient
25
+ });
26
+ module.exports = __toCommonJS(client_exports);
27
+
28
+ // src/shared/errors.ts
29
+ var HTTP_STATUS_MAP = {
30
+ "invalid-argument": 400,
31
+ unauthenticated: 401,
32
+ "permission-denied": 403,
33
+ "not-found": 404,
34
+ "already-exists": 409,
35
+ "failed-precondition": 412,
36
+ "resource-exhausted": 429,
37
+ unavailable: 503,
38
+ internal: 500
39
+ };
40
+ var CallError = class extends Error {
41
+ code;
42
+ statusCode;
43
+ details;
44
+ constructor(code, message, details) {
45
+ super(message);
46
+ this.name = "CallError";
47
+ this.code = code;
48
+ this.statusCode = HTTP_STATUS_MAP[code] ?? 500;
49
+ this.details = details;
50
+ }
51
+ };
52
+
53
+ // src/client/index.ts
54
+ var SAFE_NAME_REGEX = /^[A-Za-z0-9_-]+$/;
55
+ var readCsrfToken = (cookieName) => {
56
+ if (typeof document === "undefined") return null;
57
+ const prefix = `${cookieName}=`;
58
+ const cookie = document.cookie.split(";").map((item) => item.trim()).find((item) => item.startsWith(prefix));
59
+ if (!cookie) return null;
60
+ const value = cookie.slice(prefix.length);
61
+ return decodeURIComponent(value);
62
+ };
63
+ var createCallClient = (config) => {
64
+ const cleanBaseUrl = config.baseUrl.replace(/\/+$/, "");
65
+ const fetchImpl = config.fetchImpl ?? fetch;
66
+ const httpsCallable = (name) => {
67
+ if (!SAFE_NAME_REGEX.test(name)) {
68
+ throw new CallError("invalid-argument", `Invalid function name "${name}".`);
69
+ }
70
+ return async (data) => {
71
+ const headers = {
72
+ "Content-Type": "application/json"
73
+ };
74
+ if (config.getToken) {
75
+ const token = await config.getToken();
76
+ if (token) {
77
+ headers.Authorization = `Bearer ${token}`;
78
+ }
79
+ }
80
+ if (config.csrf) {
81
+ const csrfToken = readCsrfToken(config.csrfCookieName ?? "csrf");
82
+ if (csrfToken) {
83
+ headers[config.csrfHeaderName ?? "x-csrf-token"] = csrfToken;
84
+ }
85
+ }
86
+ let response;
87
+ try {
88
+ response = await fetchImpl(`${cleanBaseUrl}/${name}`, {
89
+ method: "POST",
90
+ headers,
91
+ credentials: config.credentials ?? "same-origin",
92
+ body: JSON.stringify({ data: data ?? {} })
93
+ });
94
+ } catch {
95
+ throw new CallError("unavailable", "Unable to reach the server.");
96
+ }
97
+ let json;
98
+ try {
99
+ json = await response.json();
100
+ } catch {
101
+ throw new CallError("internal", "Server returned an invalid response.");
102
+ }
103
+ const errorBody = json.error;
104
+ if (!response.ok || errorBody) {
105
+ const code = typeof errorBody?.code === "string" ? errorBody.code : "internal";
106
+ const message = typeof errorBody?.message === "string" ? errorBody.message : "Error invoking callable function.";
107
+ throw new CallError(code, message, errorBody?.details);
108
+ }
109
+ return { data: json.result };
110
+ };
111
+ };
112
+ return { httpsCallable };
113
+ };
@@ -0,0 +1,26 @@
1
+ type CallErrorCode = 'invalid-argument' | 'unauthenticated' | 'permission-denied' | 'not-found' | 'already-exists' | 'failed-precondition' | 'resource-exhausted' | 'unavailable' | 'internal';
2
+ declare class CallError extends Error {
3
+ readonly code: CallErrorCode;
4
+ readonly statusCode: number;
5
+ readonly details?: unknown;
6
+ constructor(code: CallErrorCode, message: string, details?: unknown);
7
+ }
8
+
9
+ interface CallClientConfig {
10
+ baseUrl: string;
11
+ getToken?: () => Promise<string | null> | string | null;
12
+ credentials?: RequestCredentials;
13
+ csrf?: boolean;
14
+ csrfCookieName?: string;
15
+ csrfHeaderName?: string;
16
+ fetchImpl?: typeof fetch;
17
+ }
18
+ interface CallableResult<TOutput> {
19
+ data: TOutput;
20
+ }
21
+ declare const createCallClient: (config: CallClientConfig) => {
22
+ httpsCallable: <TInput = unknown, TOutput = unknown>(name: string) => (data?: TInput) => Promise<CallableResult<TOutput>>;
23
+ };
24
+
25
+ export { CallError, createCallClient };
26
+ export type { CallClientConfig, CallErrorCode, CallableResult };
@@ -0,0 +1,26 @@
1
+ type CallErrorCode = 'invalid-argument' | 'unauthenticated' | 'permission-denied' | 'not-found' | 'already-exists' | 'failed-precondition' | 'resource-exhausted' | 'unavailable' | 'internal';
2
+ declare class CallError extends Error {
3
+ readonly code: CallErrorCode;
4
+ readonly statusCode: number;
5
+ readonly details?: unknown;
6
+ constructor(code: CallErrorCode, message: string, details?: unknown);
7
+ }
8
+
9
+ interface CallClientConfig {
10
+ baseUrl: string;
11
+ getToken?: () => Promise<string | null> | string | null;
12
+ credentials?: RequestCredentials;
13
+ csrf?: boolean;
14
+ csrfCookieName?: string;
15
+ csrfHeaderName?: string;
16
+ fetchImpl?: typeof fetch;
17
+ }
18
+ interface CallableResult<TOutput> {
19
+ data: TOutput;
20
+ }
21
+ declare const createCallClient: (config: CallClientConfig) => {
22
+ httpsCallable: <TInput = unknown, TOutput = unknown>(name: string) => (data?: TInput) => Promise<CallableResult<TOutput>>;
23
+ };
24
+
25
+ export { CallError, createCallClient };
26
+ export type { CallClientConfig, CallErrorCode, CallableResult };
@@ -0,0 +1,90 @@
1
+ // src/shared/errors.ts
2
+ var HTTP_STATUS_MAP = {
3
+ "invalid-argument": 400,
4
+ unauthenticated: 401,
5
+ "permission-denied": 403,
6
+ "not-found": 404,
7
+ "already-exists": 409,
8
+ "failed-precondition": 412,
9
+ "resource-exhausted": 429,
10
+ unavailable: 503,
11
+ internal: 500
12
+ };
13
+ var CallError = class extends Error {
14
+ code;
15
+ statusCode;
16
+ details;
17
+ constructor(code, message, details) {
18
+ super(message);
19
+ this.name = "CallError";
20
+ this.code = code;
21
+ this.statusCode = HTTP_STATUS_MAP[code] ?? 500;
22
+ this.details = details;
23
+ }
24
+ };
25
+
26
+ // src/client/index.ts
27
+ var SAFE_NAME_REGEX = /^[A-Za-z0-9_-]+$/;
28
+ var readCsrfToken = (cookieName) => {
29
+ if (typeof document === "undefined") return null;
30
+ const prefix = `${cookieName}=`;
31
+ const cookie = document.cookie.split(";").map((item) => item.trim()).find((item) => item.startsWith(prefix));
32
+ if (!cookie) return null;
33
+ const value = cookie.slice(prefix.length);
34
+ return decodeURIComponent(value);
35
+ };
36
+ var createCallClient = (config) => {
37
+ const cleanBaseUrl = config.baseUrl.replace(/\/+$/, "");
38
+ const fetchImpl = config.fetchImpl ?? fetch;
39
+ const httpsCallable = (name) => {
40
+ if (!SAFE_NAME_REGEX.test(name)) {
41
+ throw new CallError("invalid-argument", `Invalid function name "${name}".`);
42
+ }
43
+ return async (data) => {
44
+ const headers = {
45
+ "Content-Type": "application/json"
46
+ };
47
+ if (config.getToken) {
48
+ const token = await config.getToken();
49
+ if (token) {
50
+ headers.Authorization = `Bearer ${token}`;
51
+ }
52
+ }
53
+ if (config.csrf) {
54
+ const csrfToken = readCsrfToken(config.csrfCookieName ?? "csrf");
55
+ if (csrfToken) {
56
+ headers[config.csrfHeaderName ?? "x-csrf-token"] = csrfToken;
57
+ }
58
+ }
59
+ let response;
60
+ try {
61
+ response = await fetchImpl(`${cleanBaseUrl}/${name}`, {
62
+ method: "POST",
63
+ headers,
64
+ credentials: config.credentials ?? "same-origin",
65
+ body: JSON.stringify({ data: data ?? {} })
66
+ });
67
+ } catch {
68
+ throw new CallError("unavailable", "Unable to reach the server.");
69
+ }
70
+ let json;
71
+ try {
72
+ json = await response.json();
73
+ } catch {
74
+ throw new CallError("internal", "Server returned an invalid response.");
75
+ }
76
+ const errorBody = json.error;
77
+ if (!response.ok || errorBody) {
78
+ const code = typeof errorBody?.code === "string" ? errorBody.code : "internal";
79
+ const message = typeof errorBody?.message === "string" ? errorBody.message : "Error invoking callable function.";
80
+ throw new CallError(code, message, errorBody?.details);
81
+ }
82
+ return { data: json.result };
83
+ };
84
+ };
85
+ return { httpsCallable };
86
+ };
87
+ export {
88
+ CallError,
89
+ createCallClient
90
+ };