@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.
@@ -0,0 +1,265 @@
1
+ import { Server } from 'node:http';
2
+ import { Express } from 'express';
3
+ import { Db, ObjectId } from 'mongodb';
4
+ export { Collection, Db, Document, Filter, ObjectId, UpdateFilter } from 'mongodb';
5
+ import { HelmetOptions } from 'helmet';
6
+ import Ajv, { Options, ValidateFunction } from 'ajv';
7
+ export { JSONSchemaType } from 'ajv';
8
+ export { SignJWT } from 'jose';
9
+
10
+ type DbProvider = () => Promise<Db>;
11
+ declare function getDatabase(uri?: string, dbName?: string): Promise<Db>;
12
+ declare const ensureMongoIndexes: (db: Db, names?: {
13
+ users?: string;
14
+ }) => Promise<void>;
15
+ declare const pingDatabase: (db: Db) => Promise<boolean>;
16
+ declare const closeDatabase: () => Promise<void>;
17
+
18
+ interface StoredDocument {
19
+ id: string;
20
+ data: Record<string, unknown>;
21
+ }
22
+ interface CollectionNames {
23
+ users?: string;
24
+ roles?: string;
25
+ }
26
+ interface UserStore {
27
+ getUserById(id: string): Promise<StoredDocument | null>;
28
+ findUserByEmail(email: string): Promise<StoredDocument | null>;
29
+ findUserByFirebaseUid(uid: string): Promise<StoredDocument | null>;
30
+ getRole(roleId: string): Promise<StoredDocument | null>;
31
+ createUser(data: Record<string, unknown>, explicitId?: string): Promise<StoredDocument>;
32
+ setUser(id: string, data: Record<string, unknown>, options?: {
33
+ merge?: boolean;
34
+ }): Promise<void>;
35
+ hasAnyUser(): Promise<boolean>;
36
+ }
37
+ declare class MongoUserStore implements UserStore {
38
+ private readonly db;
39
+ private readonly usersCollection;
40
+ private readonly rolesCollection;
41
+ constructor(db: Db, names?: CollectionNames);
42
+ private coll;
43
+ getUserById(id: string): Promise<StoredDocument | null>;
44
+ findUserByEmail(email: string): Promise<StoredDocument | null>;
45
+ findUserByFirebaseUid(uid: string): Promise<StoredDocument | null>;
46
+ getRole(roleId: string): Promise<StoredDocument | null>;
47
+ createUser(data: Record<string, unknown>, explicitId?: string): Promise<StoredDocument>;
48
+ setUser(id: string, data: Record<string, unknown>, options?: {
49
+ merge?: boolean;
50
+ }): Promise<void>;
51
+ hasAnyUser(): Promise<boolean>;
52
+ }
53
+ declare class InMemoryUserStore implements UserStore {
54
+ private readonly users;
55
+ private readonly roles;
56
+ constructor(initial?: {
57
+ users?: Record<string, Record<string, unknown>>;
58
+ roles?: Record<string, Record<string, unknown>>;
59
+ });
60
+ private normalizeEmail;
61
+ getUserById(id: string): Promise<StoredDocument | null>;
62
+ findUserByEmail(email: string): Promise<StoredDocument | null>;
63
+ findUserByFirebaseUid(uid: string): Promise<StoredDocument | null>;
64
+ getRole(roleId: string): Promise<StoredDocument | null>;
65
+ createUser(data: Record<string, unknown>, explicitId?: string): Promise<StoredDocument>;
66
+ setUser(id: string, data: Record<string, unknown>, options?: {
67
+ merge?: boolean;
68
+ }): Promise<void>;
69
+ hasAnyUser(): Promise<boolean>;
70
+ }
71
+ declare const createLazyUserStore: (provider: DbProvider, names?: CollectionNames) => UserStore;
72
+
73
+ type NoSqlSanitizeMode = 'reject' | 'strip' | 'off';
74
+ declare function sanitizeNoSqlPayload<T>(input: T, mode?: NoSqlSanitizeMode, currentPath?: string): T;
75
+ declare function toObjectId(id: string, fieldName?: string): ObjectId;
76
+
77
+ interface ValidatorConfig {
78
+ allErrors?: boolean;
79
+ coerceTypes?: boolean;
80
+ removeAdditional?: boolean | 'all' | 'failing';
81
+ useDefaults?: boolean;
82
+ enableFormats?: boolean;
83
+ rawAjvOptions?: Options;
84
+ }
85
+ declare function createAjvInstance(config?: ValidatorConfig): Ajv;
86
+ declare function validatePayload<T>(validateFn: ValidateFunction, payload: unknown): T;
87
+
88
+ type PasswordHashAlgo = 'auto' | 'argon2' | 'scrypt';
89
+ interface PasswordHashOptions {
90
+ algo?: PasswordHashAlgo;
91
+ minLength?: number;
92
+ scryptN?: number;
93
+ scryptR?: number;
94
+ scryptP?: number;
95
+ scryptKeyLength?: number;
96
+ }
97
+ declare function assertPasswordComplexity(password: unknown, minLength?: number): string;
98
+ declare function hashPassword(password: string, options?: PasswordHashOptions): Promise<string>;
99
+ declare function verifyPassword(hash: string, candidate: string): Promise<boolean>;
100
+
101
+ interface RateLimitConfig {
102
+ windowMs?: number;
103
+ max?: number;
104
+ message?: string;
105
+ skipSuccessfulRequests?: boolean;
106
+ }
107
+ interface SwaggerConfig {
108
+ enabled?: boolean;
109
+ path?: string;
110
+ title?: string;
111
+ version?: string;
112
+ description?: string;
113
+ serverUrl?: string;
114
+ }
115
+ interface JwtVerifyConfig {
116
+ secret?: string;
117
+ algorithms?: string[];
118
+ issuer?: string;
119
+ audience?: string;
120
+ ttlSeconds?: number;
121
+ }
122
+ interface CookieConfig {
123
+ enabled?: boolean;
124
+ secure?: boolean;
125
+ sessionCookieName?: string;
126
+ csrfCookieName?: string;
127
+ csrfHeaderName?: string;
128
+ }
129
+ interface AuthConfig {
130
+ enabled?: boolean;
131
+ returnToken?: boolean;
132
+ loginRateLimit?: RateLimitConfig;
133
+ allowPasswordRotationGate?: boolean;
134
+ }
135
+ interface ServerConfig {
136
+ mongoUri?: string;
137
+ dbName?: string;
138
+ usersCollection?: string;
139
+ rolesCollection?: string;
140
+ dbProvider?: DbProvider;
141
+ store?: UserStore;
142
+ jwtSecret?: string;
143
+ jwtOptions?: JwtVerifyConfig;
144
+ auth?: AuthConfig;
145
+ cookies?: CookieConfig;
146
+ corsOrigin?: string | string[] | boolean;
147
+ bodyLimit?: string;
148
+ trustProxy?: boolean | number;
149
+ helmet?: boolean | HelmetOptions;
150
+ rateLimit?: RateLimitConfig | false;
151
+ noSqlSanitize?: NoSqlSanitizeMode;
152
+ validator?: ValidatorConfig;
153
+ swagger?: SwaggerConfig;
154
+ minPasswordLength?: number;
155
+ passwordHashAlgo?: PasswordHashAlgo;
156
+ apiBasePath?: string;
157
+ port?: number;
158
+ }
159
+ declare const loadEnv: () => void;
160
+ declare const loadServerConfig: (env?: Record<string, string | undefined>) => ServerConfig;
161
+
162
+ interface AuthContext {
163
+ uid: string;
164
+ userDocId: string;
165
+ email?: string;
166
+ emailVerified: boolean;
167
+ displayName?: string;
168
+ role: string;
169
+ readOnly: boolean;
170
+ authMethod: 'classic';
171
+ claims: Record<string, unknown>;
172
+ user: Record<string, unknown>;
173
+ }
174
+ interface CallContext {
175
+ db: Db;
176
+ auth: AuthContext | null;
177
+ rawHeaders: Record<string, string | string[] | undefined>;
178
+ }
179
+ interface OnCallOptions {
180
+ requireAuth?: boolean;
181
+ roles?: string[];
182
+ superadminBypass?: boolean;
183
+ writeAccess?: boolean;
184
+ allowPasswordRotationGate?: boolean;
185
+ paramsSchema?: Record<string, unknown>;
186
+ validatorOptions?: ValidatorConfig;
187
+ noSqlSanitize?: NoSqlSanitizeMode;
188
+ rateLimit?: RateLimitConfig;
189
+ responseSchema?: Record<string, unknown>;
190
+ summary?: string;
191
+ description?: string;
192
+ tags?: string[];
193
+ }
194
+ type CallHandler<TInput, TOutput> = (data: TInput, context: CallContext) => Promise<TOutput> | TOutput;
195
+ interface CallableDefinition<TInput = unknown, TOutput = unknown> {
196
+ __isMongoCallable: true;
197
+ options: OnCallOptions;
198
+ handler(data: TInput, context: CallContext): Promise<TOutput> | TOutput;
199
+ }
200
+ declare function onCall<TInput = unknown, TOutput = unknown>(handler: CallHandler<TInput, TOutput>): CallableDefinition<TInput, TOutput>;
201
+ declare function onCall<TInput = unknown, TOutput = unknown>(options: OnCallOptions, handler: CallHandler<TInput, TOutput>): CallableDefinition<TInput, TOutput>;
202
+ declare const createCallApp: (functions: Record<string, CallableDefinition>, config?: ServerConfig) => Express;
203
+ declare const startCallServer: (functions: Record<string, CallableDefinition>, portOrConfig?: number | ServerConfig, config?: ServerConfig) => Promise<Server>;
204
+
205
+ interface SessionClaims {
206
+ userId: string;
207
+ tokenVersion: number;
208
+ authMethod: 'classic';
209
+ }
210
+ interface SignSessionOptions {
211
+ secret: string;
212
+ ttlSeconds: number;
213
+ issuer?: string;
214
+ audience?: string;
215
+ }
216
+ interface VerifySessionOptions {
217
+ secret: string;
218
+ algorithms?: string[];
219
+ issuer?: string;
220
+ audience?: string;
221
+ }
222
+ declare function signSessionToken(claims: SessionClaims, options: SignSessionOptions): Promise<string>;
223
+ declare function verifySessionToken(token: string, options: VerifySessionOptions): Promise<SessionClaims>;
224
+
225
+ declare global {
226
+ namespace Express {
227
+ interface Request {
228
+ caller?: AuthenticatedCaller | null;
229
+ }
230
+ }
231
+ }
232
+ interface AuthenticatedCaller {
233
+ uid: string;
234
+ userDocId: string;
235
+ email: string | null;
236
+ emailVerified: boolean;
237
+ displayName: string | null;
238
+ authMethod: 'classic';
239
+ mustChangePassword: boolean;
240
+ tokenClaims: Record<string, unknown>;
241
+ userData: Record<string, unknown>;
242
+ }
243
+
244
+ interface CallerAccess {
245
+ role: string;
246
+ readOnly: boolean;
247
+ userDocId?: string;
248
+ }
249
+ declare const resolveCallerRole: (store: UserStore, caller: AuthenticatedCaller | null) => Promise<CallerAccess>;
250
+ declare const assertAllowedRole: (access: CallerAccess, allowedRoles: readonly string[], options?: {
251
+ superadminBypass?: boolean;
252
+ writeAccess?: boolean;
253
+ }) => void;
254
+
255
+ type CallErrorCode = 'invalid-argument' | 'unauthenticated' | 'permission-denied' | 'not-found' | 'already-exists' | 'failed-precondition' | 'resource-exhausted' | 'unavailable' | 'internal';
256
+ declare class CallError extends Error {
257
+ readonly code: CallErrorCode;
258
+ readonly statusCode: number;
259
+ readonly details?: unknown;
260
+ constructor(code: CallErrorCode, message: string, details?: unknown);
261
+ }
262
+ declare const isCallError: (err: unknown) => err is CallError;
263
+
264
+ export { CallError, InMemoryUserStore, MongoUserStore, assertAllowedRole, assertPasswordComplexity, closeDatabase, createAjvInstance, createCallApp, createLazyUserStore, ensureMongoIndexes, getDatabase, hashPassword, isCallError, loadEnv, loadServerConfig, onCall, pingDatabase, resolveCallerRole, sanitizeNoSqlPayload, signSessionToken, startCallServer, toObjectId, validatePayload, verifyPassword, verifySessionToken };
265
+ export type { AuthConfig, AuthContext, CallContext, CallErrorCode, CallHandler, CallableDefinition, CallerAccess, CookieConfig, DbProvider, JwtVerifyConfig, NoSqlSanitizeMode, OnCallOptions, PasswordHashAlgo, RateLimitConfig, ServerConfig, SessionClaims, StoredDocument, SwaggerConfig, UserStore, ValidatorConfig };