@donotdev/functions 0.0.14 → 0.0.16
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/lib/firebase/index.js +1532 -575
- package/lib/firebase/index.js.map +4 -4
- package/lib/shared/index.js +333 -163
- package/lib/shared/index.js.map +4 -4
- package/lib/vercel/api/index.js +325 -190
- package/lib/vercel/api/index.js.map +4 -4
- package/package.json +4 -4
- package/src/firebase/baseFunction.ts +29 -6
- package/src/firebase/crud/create.ts +6 -1
- package/src/firebase/crud/delete.ts +7 -0
- package/src/firebase/crud/list.ts +17 -6
- package/src/firebase/crud/update.ts +2 -1
- package/src/shared/__tests__/errorHandling.test.ts +53 -72
- package/src/shared/billing/helpers/updateUserSubscription.ts +9 -0
- package/src/shared/billing/idempotency.ts +3 -3
- package/src/shared/billing/webhookHandler.ts +18 -1
- package/src/shared/errorHandling.ts +13 -79
- package/src/shared/utils/internal/auth.ts +2 -1
- package/src/shared/utils/internal/validation.ts +10 -3
- package/src/shared/utils.ts +6 -6
- package/src/supabase/baseFunction.ts +21 -2
- package/src/supabase/crud/create.ts +8 -3
- package/src/supabase/crud/delete.ts +7 -0
- package/src/supabase/crud/list.ts +24 -1
- package/src/supabase/crud/update.ts +3 -0
- package/src/supabase/utils/rateLimiter.ts +17 -6
- package/src/vercel/api/crud/get.ts +7 -2
- package/src/vercel/baseFunction.ts +37 -30
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@donotdev/functions",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.16",
|
|
4
4
|
"private": false,
|
|
5
5
|
"description": "Backend functions for DoNotDev Framework - Firebase, Vercel, and platform-agnostic implementations for auth, billing, CRUD, and OAuth",
|
|
6
6
|
"main": "./lib/firebase/index.js",
|
|
@@ -47,9 +47,9 @@
|
|
|
47
47
|
"serve": "firebase emulators:start --only functions"
|
|
48
48
|
},
|
|
49
49
|
"dependencies": {
|
|
50
|
-
"@donotdev/core": "^0.0.
|
|
51
|
-
"@donotdev/firebase": "^0.0.
|
|
52
|
-
"@donotdev/supabase": "^0.0.
|
|
50
|
+
"@donotdev/core": "^0.0.29",
|
|
51
|
+
"@donotdev/firebase": "^0.0.15",
|
|
52
|
+
"@donotdev/supabase": "^0.0.5"
|
|
53
53
|
},
|
|
54
54
|
"peerDependencies": {
|
|
55
55
|
"@sentry/node": "^10.39.0",
|
|
@@ -18,7 +18,7 @@ import type { UserRole } from '@donotdev/core/server';
|
|
|
18
18
|
import type { SecurityContext } from '@donotdev/core';
|
|
19
19
|
|
|
20
20
|
import { FUNCTION_CONFIG } from './config/constants.js';
|
|
21
|
-
import { handleError } from '../shared/errorHandling.js';
|
|
21
|
+
import { handleError, DoNotDevError } from '../shared/errorHandling.js';
|
|
22
22
|
import { assertAuthenticated, getUserRole } from '../shared/utils.js';
|
|
23
23
|
|
|
24
24
|
import type {
|
|
@@ -171,9 +171,16 @@ export function createBaseFunction<TRequest, TResponse>(
|
|
|
171
171
|
userId: request.auth?.uid || 'anonymous',
|
|
172
172
|
hasData: request.data !== undefined && request.data !== null,
|
|
173
173
|
dataKeys: request.data ? Object.keys(request.data) : [],
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
174
|
+
// G73: Wrap in try-catch to avoid broken mid-JSON output on circular refs
|
|
175
|
+
dataPreview: (() => {
|
|
176
|
+
if (!request.data) return 'null';
|
|
177
|
+
try {
|
|
178
|
+
const json = JSON.stringify(request.data);
|
|
179
|
+
return json.length > 200 ? json.substring(0, 200) + '...' : json;
|
|
180
|
+
} catch {
|
|
181
|
+
return '[unserializable]';
|
|
182
|
+
}
|
|
183
|
+
})(),
|
|
177
184
|
});
|
|
178
185
|
|
|
179
186
|
// App Check monitoring (logs missing tokens for visibility)
|
|
@@ -258,7 +265,11 @@ export function createBaseFunction<TRequest, TResponse>(
|
|
|
258
265
|
? `ip_${getClientIp(request)}`
|
|
259
266
|
: `uid_${uid}`;
|
|
260
267
|
const rateLimitKey = `${operation}_${rateLimitIdentifier}`;
|
|
261
|
-
|
|
268
|
+
// G52: Guard against prototype pollution — only allow own properties on limits
|
|
269
|
+
const rateLimitConfig =
|
|
270
|
+
Object.hasOwn(limits!, operation)
|
|
271
|
+
? limits![operation as keyof typeof limits]
|
|
272
|
+
: limits!.api;
|
|
262
273
|
const rateLimitResult = await checkLimit!(
|
|
263
274
|
rateLimitKey,
|
|
264
275
|
rateLimitConfig
|
|
@@ -321,7 +332,19 @@ export function createBaseFunction<TRequest, TResponse>(
|
|
|
321
332
|
});
|
|
322
333
|
}
|
|
323
334
|
|
|
324
|
-
|
|
335
|
+
try {
|
|
336
|
+
handleError(error);
|
|
337
|
+
} catch (classified) {
|
|
338
|
+
if (classified instanceof DoNotDevError) {
|
|
339
|
+
const { HttpsError } = await import('firebase-functions/v2/https');
|
|
340
|
+
throw new HttpsError(
|
|
341
|
+
classified.code as any,
|
|
342
|
+
classified.message,
|
|
343
|
+
classified.details
|
|
344
|
+
);
|
|
345
|
+
}
|
|
346
|
+
throw classified;
|
|
347
|
+
}
|
|
325
348
|
}
|
|
326
349
|
}
|
|
327
350
|
);
|
|
@@ -9,6 +9,7 @@
|
|
|
9
9
|
* @author AMBROISE PARK Consulting
|
|
10
10
|
*/
|
|
11
11
|
|
|
12
|
+
import { logger } from 'firebase-functions/v2';
|
|
12
13
|
import * as v from 'valibot';
|
|
13
14
|
|
|
14
15
|
import { DEFAULT_STATUS_VALUE } from '@donotdev/core/server';
|
|
@@ -228,7 +229,11 @@ function createEntityLogicFactory(
|
|
|
228
229
|
);
|
|
229
230
|
|
|
230
231
|
if (checkResult.found && checkResult.findOrCreate) {
|
|
231
|
-
//
|
|
232
|
+
// G54: Log when returning existing document instead of creating new one
|
|
233
|
+
logger.info('[create_entity] findOrCreate: returning existing document', {
|
|
234
|
+
collection,
|
|
235
|
+
existingId: checkResult.existingDoc.id,
|
|
236
|
+
});
|
|
232
237
|
return checkResult.existingDoc;
|
|
233
238
|
}
|
|
234
239
|
// If found but not findOrCreate, checkUniqueKeys already threw an error
|
|
@@ -9,6 +9,7 @@
|
|
|
9
9
|
* @author AMBROISE PARK Consulting
|
|
10
10
|
*/
|
|
11
11
|
|
|
12
|
+
import { logger } from 'firebase-functions/v2';
|
|
12
13
|
import * as v from 'valibot';
|
|
13
14
|
|
|
14
15
|
import type { UserRole } from '@donotdev/core/server';
|
|
@@ -40,6 +41,12 @@ function deleteEntityLogicFactory(collection: string) {
|
|
|
40
41
|
) {
|
|
41
42
|
const { id } = data;
|
|
42
43
|
|
|
44
|
+
// G55: Warn when referenceMetadata is not configured — reference checking is skipped
|
|
45
|
+
logger.warn('[delete_entity] No referenceMetadata configured, skipping reference check', {
|
|
46
|
+
collection,
|
|
47
|
+
docId: id,
|
|
48
|
+
});
|
|
49
|
+
|
|
43
50
|
// Check for references to this document
|
|
44
51
|
const references = await findReferences(collection, id);
|
|
45
52
|
|
|
@@ -9,6 +9,7 @@
|
|
|
9
9
|
* @author AMBROISE PARK Consulting
|
|
10
10
|
*/
|
|
11
11
|
|
|
12
|
+
import { logger } from 'firebase-functions/v2';
|
|
12
13
|
import * as v from 'valibot';
|
|
13
14
|
|
|
14
15
|
import {
|
|
@@ -101,14 +102,16 @@ function listEntitiesLogicFactory(
|
|
|
101
102
|
) {
|
|
102
103
|
query = applyPublicCondition(query, ownership.publicCondition);
|
|
103
104
|
} else if (!isListCard && ownership.ownerFields.length > 0) {
|
|
104
|
-
//
|
|
105
|
-
//
|
|
106
|
-
const firstOwnerField = ownership.ownerFields[0];
|
|
107
|
-
query = query.where(firstOwnerField, '==', uid);
|
|
105
|
+
// G53: Multiple ownerFields are not supported in a single Firestore query.
|
|
106
|
+
// Throw an explicit error instead of silently degrading to first field only.
|
|
108
107
|
if (ownership.ownerFields.length > 1) {
|
|
109
|
-
|
|
110
|
-
|
|
108
|
+
throw new DoNotDevError(
|
|
109
|
+
`Multiple ownerFields (${ownership.ownerFields.join(', ')}) are not supported for Firestore list queries. Use a single ownerIds array field with array-contains instead.`,
|
|
110
|
+
'invalid-argument'
|
|
111
|
+
);
|
|
111
112
|
}
|
|
113
|
+
const firstOwnerField = ownership.ownerFields[0];
|
|
114
|
+
query = query.where(firstOwnerField, '==', uid);
|
|
112
115
|
}
|
|
113
116
|
}
|
|
114
117
|
|
|
@@ -181,6 +184,14 @@ function listEntitiesLogicFactory(
|
|
|
181
184
|
limit !== undefined && limit > 0
|
|
182
185
|
? Math.min(limit, MAX_LIST_LIMIT)
|
|
183
186
|
: MAX_LIST_LIMIT;
|
|
187
|
+
// G56: Warn when the requested limit exceeds MAX_LIST_LIMIT
|
|
188
|
+
if (limit !== undefined && limit > MAX_LIST_LIMIT) {
|
|
189
|
+
logger.warn(`[list_entities] Requested limit ${limit} exceeds MAX_LIST_LIMIT (${MAX_LIST_LIMIT}), capping`, {
|
|
190
|
+
requestedLimit: limit,
|
|
191
|
+
effectiveLimit,
|
|
192
|
+
collection,
|
|
193
|
+
});
|
|
194
|
+
}
|
|
184
195
|
query = query.limit(effectiveLimit);
|
|
185
196
|
|
|
186
197
|
// Execute the query
|
|
@@ -209,7 +209,8 @@ function updateEntityLogicFactory(
|
|
|
209
209
|
throw new DoNotDevError('Entity not found', 'not-found');
|
|
210
210
|
}
|
|
211
211
|
|
|
212
|
-
// Get the current data and merge with the update payload
|
|
212
|
+
// Get the current data and merge with the update payload.
|
|
213
|
+
// Note: simple spread merge — concurrent partial updates use last-write-wins, no conflict detection.
|
|
213
214
|
const currentData = transformFirestoreData(doc.data());
|
|
214
215
|
const mergedData = { ...currentData, ...payload };
|
|
215
216
|
|
|
@@ -1,41 +1,19 @@
|
|
|
1
|
-
import { describe, it, expect, vi, beforeEach
|
|
2
|
-
|
|
3
|
-
// Mock firebase-functions
|
|
4
|
-
vi.mock('firebase-functions/v2/https', () => ({
|
|
5
|
-
HttpsError: class HttpsError extends Error {
|
|
6
|
-
code: string;
|
|
7
|
-
details: any;
|
|
8
|
-
constructor(code: string, message: string, details?: any) {
|
|
9
|
-
super(message);
|
|
10
|
-
this.code = code;
|
|
11
|
-
this.details = details;
|
|
12
|
-
this.name = 'HttpsError';
|
|
13
|
-
}
|
|
14
|
-
},
|
|
15
|
-
}));
|
|
16
|
-
|
|
17
|
-
vi.mock('firebase-functions/v2', () => ({
|
|
18
|
-
logger: { warn: vi.fn(), info: vi.fn(), error: vi.fn(), log: vi.fn() },
|
|
19
|
-
}));
|
|
20
|
-
|
|
21
|
-
vi.mock('@donotdev/firebase/server', () => ({
|
|
22
|
-
getFirebaseAdminFirestore: vi.fn(),
|
|
23
|
-
}));
|
|
1
|
+
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
|
24
2
|
|
|
25
3
|
import { handleError, DoNotDevError } from '../errorHandling';
|
|
26
4
|
|
|
27
5
|
describe('DoNotDevError (functions)', () => {
|
|
28
|
-
it('creates with default code "
|
|
6
|
+
it('creates with default code "internal"', () => {
|
|
29
7
|
const error = new DoNotDevError('test');
|
|
30
8
|
|
|
31
|
-
expect(error.code).toBe('
|
|
9
|
+
expect(error.code).toBe('internal');
|
|
32
10
|
expect(error.message).toBe('test');
|
|
33
11
|
expect(error.name).toBe('DoNotDevError');
|
|
34
12
|
});
|
|
35
13
|
|
|
36
14
|
it('creates with explicit code and details', () => {
|
|
37
15
|
const error = new DoNotDevError('bad input', 'invalid-argument', {
|
|
38
|
-
field: 'email',
|
|
16
|
+
details: { field: 'email' },
|
|
39
17
|
});
|
|
40
18
|
|
|
41
19
|
expect(error.code).toBe('invalid-argument');
|
|
@@ -48,18 +26,6 @@ describe('DoNotDevError (functions)', () => {
|
|
|
48
26
|
expect(error.toString()).toBe('DoNotDevError [not-found]: test');
|
|
49
27
|
});
|
|
50
28
|
|
|
51
|
-
it('toJSON includes all fields', () => {
|
|
52
|
-
const error = new DoNotDevError('test', 'internal', { key: 'val' });
|
|
53
|
-
const json = error.toJSON();
|
|
54
|
-
|
|
55
|
-
expect(json).toEqual({
|
|
56
|
-
name: 'DoNotDevError',
|
|
57
|
-
code: 'internal',
|
|
58
|
-
message: 'test',
|
|
59
|
-
details: { key: 'val' },
|
|
60
|
-
});
|
|
61
|
-
});
|
|
62
|
-
|
|
63
29
|
it('instanceof chain works', () => {
|
|
64
30
|
const error = new DoNotDevError('test');
|
|
65
31
|
|
|
@@ -69,54 +35,62 @@ describe('DoNotDevError (functions)', () => {
|
|
|
69
35
|
});
|
|
70
36
|
|
|
71
37
|
describe('handleError', () => {
|
|
72
|
-
const originalEnv = { ...process.env };
|
|
73
|
-
|
|
74
38
|
beforeEach(() => {
|
|
75
39
|
vi.spyOn(console, 'error').mockImplementation(() => {});
|
|
76
|
-
// Clear env to force fallback (no Firebase, no Vercel)
|
|
77
|
-
delete process.env.FUNCTIONS_EMULATOR;
|
|
78
|
-
delete process.env.FIREBASE_CONFIG;
|
|
79
|
-
delete process.env.GCLOUD_PROJECT;
|
|
80
|
-
delete process.env.VERCEL;
|
|
81
|
-
delete process.env.VERCEL_ENV;
|
|
82
40
|
});
|
|
83
41
|
|
|
84
|
-
|
|
85
|
-
process.env = { ...originalEnv };
|
|
86
|
-
});
|
|
87
|
-
|
|
88
|
-
it('throws for DoNotDevError (fallback env)', () => {
|
|
42
|
+
it('throws DoNotDevError for DoNotDevError input', () => {
|
|
89
43
|
const original = new DoNotDevError('Bad', 'invalid-argument');
|
|
90
44
|
|
|
91
|
-
|
|
45
|
+
try {
|
|
46
|
+
handleError(original);
|
|
47
|
+
expect.fail('should have thrown');
|
|
48
|
+
} catch (error) {
|
|
49
|
+
expect(error).toBeInstanceOf(DoNotDevError);
|
|
50
|
+
expect((error as DoNotDevError).code).toBe('invalid-argument');
|
|
51
|
+
expect((error as DoNotDevError).message).toBe('Bad');
|
|
52
|
+
}
|
|
92
53
|
});
|
|
93
54
|
|
|
94
|
-
it('
|
|
95
|
-
const original = new
|
|
55
|
+
it('preserves details from DoNotDevError input', () => {
|
|
56
|
+
const original = new DoNotDevError('Bad', 'invalid-argument', {
|
|
57
|
+
details: { field: 'email' },
|
|
58
|
+
});
|
|
96
59
|
|
|
97
|
-
|
|
60
|
+
try {
|
|
61
|
+
handleError(original);
|
|
62
|
+
expect.fail('should have thrown');
|
|
63
|
+
} catch (error) {
|
|
64
|
+
expect(error).toBeInstanceOf(DoNotDevError);
|
|
65
|
+
expect((error as DoNotDevError).details).toEqual({ field: 'email' });
|
|
66
|
+
}
|
|
98
67
|
});
|
|
99
68
|
|
|
100
|
-
it('throws
|
|
101
|
-
|
|
102
|
-
'
|
|
103
|
-
|
|
69
|
+
it('throws DoNotDevError with code "internal" for generic Error', () => {
|
|
70
|
+
try {
|
|
71
|
+
handleError(new Error('Something broke'));
|
|
72
|
+
expect.fail('should have thrown');
|
|
73
|
+
} catch (error) {
|
|
74
|
+
expect(error).toBeInstanceOf(DoNotDevError);
|
|
75
|
+
expect((error as DoNotDevError).code).toBe('internal');
|
|
76
|
+
expect((error as DoNotDevError).message).toBe('Something broke');
|
|
77
|
+
}
|
|
104
78
|
});
|
|
105
79
|
|
|
106
|
-
it('throws
|
|
107
|
-
process.env.FIREBASE_CONFIG = '{}';
|
|
108
|
-
|
|
80
|
+
it('throws DoNotDevError with generic message for non-Error', () => {
|
|
109
81
|
try {
|
|
110
|
-
handleError(
|
|
82
|
+
handleError('random string');
|
|
111
83
|
expect.fail('should have thrown');
|
|
112
|
-
} catch (error
|
|
113
|
-
expect(error
|
|
114
|
-
expect(error.code).toBe('
|
|
84
|
+
} catch (error) {
|
|
85
|
+
expect(error).toBeInstanceOf(DoNotDevError);
|
|
86
|
+
expect((error as DoNotDevError).code).toBe('internal');
|
|
87
|
+
expect((error as DoNotDevError).message).toBe(
|
|
88
|
+
'An unexpected error occurred'
|
|
89
|
+
);
|
|
115
90
|
}
|
|
116
91
|
});
|
|
117
92
|
|
|
118
93
|
it('maps EntityHookError types correctly', () => {
|
|
119
|
-
// Simulate EntityHookError (name-based detection)
|
|
120
94
|
const entityError = new Error('Permission denied');
|
|
121
95
|
(entityError as any).name = 'EntityHookError';
|
|
122
96
|
(entityError as any).type = 'PERMISSION_DENIED';
|
|
@@ -124,12 +98,14 @@ describe('handleError', () => {
|
|
|
124
98
|
try {
|
|
125
99
|
handleError(entityError);
|
|
126
100
|
expect.fail('should have thrown');
|
|
127
|
-
} catch (error
|
|
128
|
-
expect(error
|
|
101
|
+
} catch (error) {
|
|
102
|
+
expect(error).toBeInstanceOf(DoNotDevError);
|
|
103
|
+
expect((error as DoNotDevError).code).toBe('permission-denied');
|
|
104
|
+
expect((error as DoNotDevError).message).toBe('Permission denied');
|
|
129
105
|
}
|
|
130
106
|
});
|
|
131
107
|
|
|
132
|
-
it('maps ValiError to invalid-argument', () => {
|
|
108
|
+
it('maps ValiError to invalid-argument with details', () => {
|
|
133
109
|
const valiError = new Error('Validation failed');
|
|
134
110
|
(valiError as any).name = 'ValiError';
|
|
135
111
|
(valiError as any).issues = [{ path: [], message: 'required' }];
|
|
@@ -137,8 +113,13 @@ describe('handleError', () => {
|
|
|
137
113
|
try {
|
|
138
114
|
handleError(valiError);
|
|
139
115
|
expect.fail('should have thrown');
|
|
140
|
-
} catch (error
|
|
141
|
-
expect(error
|
|
116
|
+
} catch (error) {
|
|
117
|
+
expect(error).toBeInstanceOf(DoNotDevError);
|
|
118
|
+
expect((error as DoNotDevError).code).toBe('invalid-argument');
|
|
119
|
+
expect((error as DoNotDevError).message).toBe('Validation failed');
|
|
120
|
+
expect((error as DoNotDevError).details).toEqual({
|
|
121
|
+
validationErrors: [{ path: [], message: 'required' }],
|
|
122
|
+
});
|
|
142
123
|
}
|
|
143
124
|
});
|
|
144
125
|
});
|
|
@@ -64,6 +64,15 @@ export async function updateUserSubscription(
|
|
|
64
64
|
throw new Error('Invalid subscription data: missing tier or status');
|
|
65
65
|
}
|
|
66
66
|
|
|
67
|
+
// G57: Warn when customerId is undefined — falling back to userId loses the
|
|
68
|
+
// Stripe customer ID, which makes future Stripe API calls unreliable.
|
|
69
|
+
if (!subscriptionData.customerId) {
|
|
70
|
+
console.warn(
|
|
71
|
+
`[updateUserSubscription] customerId is undefined for user ${userId}. ` +
|
|
72
|
+
`Falling back to userId. This may cause issues with Stripe API calls.`
|
|
73
|
+
);
|
|
74
|
+
}
|
|
75
|
+
|
|
67
76
|
const subscriptionClaims = {
|
|
68
77
|
tier: subscriptionData.tier,
|
|
69
78
|
subscriptionId: subscriptionData.subscriptionId || null,
|
|
@@ -48,10 +48,10 @@ class InMemoryIdempotency implements IdempotencyStore {
|
|
|
48
48
|
async markProcessed(eventId: string): Promise<void> {
|
|
49
49
|
this.store.add(eventId);
|
|
50
50
|
|
|
51
|
-
//
|
|
51
|
+
// G58: FIFO cleanup — delete the oldest (first-inserted) entry via iterator
|
|
52
52
|
if (this.store.size > 1000) {
|
|
53
|
-
const
|
|
54
|
-
if (
|
|
53
|
+
const oldest = this.store.values().next().value;
|
|
54
|
+
if (oldest) this.store.delete(oldest);
|
|
55
55
|
}
|
|
56
56
|
}
|
|
57
57
|
}
|
|
@@ -108,6 +108,14 @@ export async function processWebhook(
|
|
|
108
108
|
return { success: true, message: 'Event already processed' };
|
|
109
109
|
}
|
|
110
110
|
|
|
111
|
+
// G59: Warn when authProvider is null — subscription update events will fail
|
|
112
|
+
if (!authProvider) {
|
|
113
|
+
logger.warn('[Webhook] authProvider is null — subscription-related events will fail', {
|
|
114
|
+
eventType: event.type,
|
|
115
|
+
eventId: event.id,
|
|
116
|
+
});
|
|
117
|
+
}
|
|
118
|
+
|
|
111
119
|
// Route to handler
|
|
112
120
|
await routeEvent(event, config, updateSubscription, stripe, authProvider);
|
|
113
121
|
|
|
@@ -307,7 +315,16 @@ async function handleInvoicePaymentSucceeded(
|
|
|
307
315
|
// ✅ FIX: Fetch subscription to get metadata
|
|
308
316
|
const subscription = await stripe.subscriptions.retrieve(subscriptionId);
|
|
309
317
|
const { userId, billingConfigKey } = subscription.metadata || {};
|
|
310
|
-
if (!userId || !billingConfigKey)
|
|
318
|
+
if (!userId || !billingConfigKey) {
|
|
319
|
+
// G60: Log when subscription metadata is missing — silent return loses the event
|
|
320
|
+
logger.error('[Webhook] Subscription metadata missing userId or billingConfigKey', {
|
|
321
|
+
subscriptionId,
|
|
322
|
+
hasUserId: !!userId,
|
|
323
|
+
hasBillingConfigKey: !!billingConfigKey,
|
|
324
|
+
operation: 'invoice_payment_succeeded_metadata_missing',
|
|
325
|
+
});
|
|
326
|
+
return;
|
|
327
|
+
}
|
|
311
328
|
|
|
312
329
|
const billingItem = config[billingConfigKey];
|
|
313
330
|
if (!billingItem || billingItem.type !== 'StripeSubscription') return;
|
|
@@ -2,30 +2,31 @@
|
|
|
2
2
|
|
|
3
3
|
/**
|
|
4
4
|
* @fileoverview Shared Error Handling
|
|
5
|
-
* @description Platform-
|
|
5
|
+
* @description Platform-agnostic error classification. Always throws DoNotDevError.
|
|
6
|
+
* Platform adapters (Firebase baseFunction, Vercel route handler) catch and convert.
|
|
6
7
|
*
|
|
7
|
-
* @version 0.0.
|
|
8
|
+
* @version 0.0.2
|
|
8
9
|
* @since 0.0.1
|
|
9
10
|
* @author AMBROISE PARK Consulting
|
|
10
11
|
*/
|
|
11
12
|
|
|
12
|
-
import * as v from 'valibot';
|
|
13
|
-
|
|
14
13
|
import { DoNotDevError, EntityHookError } from '@donotdev/core/server';
|
|
15
14
|
|
|
16
15
|
// Re-export DoNotDevError so existing imports from this module continue to work
|
|
17
16
|
export { DoNotDevError };
|
|
18
17
|
|
|
19
18
|
/**
|
|
20
|
-
*
|
|
19
|
+
* Classify and throw a DoNotDevError from any unknown error.
|
|
20
|
+
* Pure classification — no platform imports, no env detection.
|
|
21
|
+
*
|
|
21
22
|
* @param error - The error to handle
|
|
22
|
-
* @throws
|
|
23
|
+
* @throws DoNotDevError always
|
|
23
24
|
*
|
|
24
|
-
* @version 0.0.
|
|
25
|
+
* @version 0.0.2
|
|
25
26
|
* @since 0.0.1
|
|
26
27
|
* @author AMBROISE PARK Consulting
|
|
27
28
|
*/
|
|
28
|
-
export
|
|
29
|
+
export function handleError(error: unknown): never {
|
|
29
30
|
// W11: Log only in development to avoid double-logging with platform loggers.
|
|
30
31
|
// Known DoNotDevError, ValiError, and EntityHookError are handled by callers.
|
|
31
32
|
if (
|
|
@@ -94,76 +95,9 @@ export async function handleError(error: unknown): Promise<never> {
|
|
|
94
95
|
details = undefined;
|
|
95
96
|
}
|
|
96
97
|
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
throwVercelError(code, message, details);
|
|
102
|
-
} else {
|
|
103
|
-
// Fallback - just throw a regular error
|
|
104
|
-
throw new Error(`${code}: ${message}`);
|
|
105
|
-
}
|
|
106
|
-
}
|
|
107
|
-
|
|
108
|
-
/**
|
|
109
|
-
* Detect if we're running in Firebase environment
|
|
110
|
-
*
|
|
111
|
-
* @version 0.0.1
|
|
112
|
-
* @since 0.0.1
|
|
113
|
-
* @author AMBROISE PARK Consulting
|
|
114
|
-
*/
|
|
115
|
-
function isFirebaseEnvironment(): boolean {
|
|
116
|
-
return (
|
|
117
|
-
typeof process !== 'undefined' &&
|
|
118
|
-
(process.env.FUNCTIONS_EMULATOR === 'true' ||
|
|
119
|
-
process.env.FIREBASE_CONFIG !== undefined ||
|
|
120
|
-
process.env.GCLOUD_PROJECT !== undefined)
|
|
98
|
+
throw new DoNotDevError(
|
|
99
|
+
message,
|
|
100
|
+
code as any,
|
|
101
|
+
details ? { details } : undefined
|
|
121
102
|
);
|
|
122
103
|
}
|
|
123
|
-
|
|
124
|
-
/**
|
|
125
|
-
* Detect if we're running in Vercel environment
|
|
126
|
-
*
|
|
127
|
-
* @version 0.0.1
|
|
128
|
-
* @since 0.0.1
|
|
129
|
-
* @author AMBROISE PARK Consulting
|
|
130
|
-
*/
|
|
131
|
-
function isVercelEnvironment(): boolean {
|
|
132
|
-
return (
|
|
133
|
-
typeof process !== 'undefined' &&
|
|
134
|
-
(process.env.VERCEL === '1' || process.env.VERCEL_ENV !== undefined)
|
|
135
|
-
);
|
|
136
|
-
}
|
|
137
|
-
|
|
138
|
-
/**
|
|
139
|
-
* Throw Firebase-specific error
|
|
140
|
-
*
|
|
141
|
-
* @version 0.0.1
|
|
142
|
-
* @since 0.0.1
|
|
143
|
-
* @author AMBROISE PARK Consulting
|
|
144
|
-
*/
|
|
145
|
-
async function throwFirebaseError(
|
|
146
|
-
code: string,
|
|
147
|
-
message: string,
|
|
148
|
-
details?: any
|
|
149
|
-
): Promise<never> {
|
|
150
|
-
// Dynamic import — firebase-functions is only loaded in Firebase environments
|
|
151
|
-
const { HttpsError } = await import('firebase-functions/v2/https');
|
|
152
|
-
throw new HttpsError(code as any, message, details);
|
|
153
|
-
}
|
|
154
|
-
|
|
155
|
-
/**
|
|
156
|
-
* Throw Vercel-specific error
|
|
157
|
-
*
|
|
158
|
-
* @version 0.0.1
|
|
159
|
-
* @since 0.0.1
|
|
160
|
-
* @author AMBROISE PARK Consulting
|
|
161
|
-
*/
|
|
162
|
-
function throwVercelError(code: string, message: string, details?: any): never {
|
|
163
|
-
// For Vercel, we can throw a regular Error and let the API route handle it
|
|
164
|
-
// Or we could create a custom VercelError class
|
|
165
|
-
const error = new Error(message);
|
|
166
|
-
(error as any).code = code;
|
|
167
|
-
(error as any).details = details;
|
|
168
|
-
throw error;
|
|
169
|
-
}
|
|
@@ -28,7 +28,8 @@ export type AuthProvider = 'firebase' | 'supabase';
|
|
|
28
28
|
* @author AMBROISE PARK Consulting
|
|
29
29
|
*/
|
|
30
30
|
export function assertAuthenticated(uid: string): string {
|
|
31
|
-
|
|
31
|
+
// G62: Validate uid is a non-empty string — reject non-string values at runtime
|
|
32
|
+
if (!uid || typeof uid !== 'string') {
|
|
32
33
|
throw new Error('Authentication required');
|
|
33
34
|
}
|
|
34
35
|
return uid;
|
|
@@ -11,6 +11,8 @@
|
|
|
11
11
|
|
|
12
12
|
import * as v from 'valibot';
|
|
13
13
|
|
|
14
|
+
import { DoNotDevError } from '@donotdev/core/server';
|
|
15
|
+
|
|
14
16
|
/**
|
|
15
17
|
* Validates environment variables required for Stripe
|
|
16
18
|
*
|
|
@@ -81,12 +83,13 @@ export function validateCollectionName(name: string): void {
|
|
|
81
83
|
* @author AMBROISE PARK Consulting
|
|
82
84
|
*/
|
|
83
85
|
export function validateDocument(data: any, schema?: any): void {
|
|
86
|
+
// G63: Throw DoNotDevError instead of plain Error for consistent error handling
|
|
84
87
|
if (!data || typeof data !== 'object') {
|
|
85
|
-
throw new
|
|
88
|
+
throw new DoNotDevError('Invalid document data', 'invalid-argument');
|
|
86
89
|
}
|
|
87
90
|
|
|
88
91
|
if (Array.isArray(data)) {
|
|
89
|
-
throw new
|
|
92
|
+
throw new DoNotDevError('Document data cannot be an array', 'invalid-argument');
|
|
90
93
|
}
|
|
91
94
|
|
|
92
95
|
// W1: Perform schema validation when a Valibot schema is supplied.
|
|
@@ -99,7 +102,11 @@ export function validateDocument(data: any, schema?: any): void {
|
|
|
99
102
|
`${issue.path?.map((p) => (p as any).key).join('.') || 'root'}: ${issue.message}`
|
|
100
103
|
)
|
|
101
104
|
.join('; ');
|
|
102
|
-
throw new
|
|
105
|
+
throw new DoNotDevError(
|
|
106
|
+
`Validation failed: ${messages}`,
|
|
107
|
+
'invalid-argument',
|
|
108
|
+
{ details: { validationErrors: result.issues } }
|
|
109
|
+
);
|
|
103
110
|
}
|
|
104
111
|
}
|
|
105
112
|
}
|
package/src/shared/utils.ts
CHANGED
|
@@ -109,7 +109,7 @@ export const stripe = new Proxy({} as Stripe, {
|
|
|
109
109
|
/**
|
|
110
110
|
* Assert that a user is authenticated from a Firebase callable auth context.
|
|
111
111
|
*
|
|
112
|
-
* @deprecated
|
|
112
|
+
* @deprecated Import `assertAuthenticated` from `@donotdev/functions/shared/utils/internal/auth` instead.
|
|
113
113
|
* This wrapper extracts uid from a Firebase callable auth context and delegates
|
|
114
114
|
* to the canonical version.
|
|
115
115
|
*
|
|
@@ -250,7 +250,7 @@ export function createErrorResponse(error: unknown): {
|
|
|
250
250
|
* Use `updateUserSubscription` from `shared/billing/helpers/updateUserSubscription.ts`
|
|
251
251
|
* (which requires an authProvider) instead.
|
|
252
252
|
*
|
|
253
|
-
* @deprecated
|
|
253
|
+
* @deprecated Import `updateUserSubscription` from `@donotdev/functions/shared/billing/helpers/updateUserSubscription`.
|
|
254
254
|
* @version 0.0.2
|
|
255
255
|
* @since 0.0.1
|
|
256
256
|
* @author AMBROISE PARK Consulting
|
|
@@ -270,7 +270,7 @@ export async function updateUserSubscription(
|
|
|
270
270
|
*
|
|
271
271
|
* C10: This was a silent no-op stub. Now throws to surface the missing implementation.
|
|
272
272
|
*
|
|
273
|
-
* @deprecated
|
|
273
|
+
* @deprecated Import from `@donotdev/functions/shared/billing/helpers` or implement directly using Firebase Admin SDK / Stripe API.
|
|
274
274
|
* @version 0.0.2
|
|
275
275
|
* @since 0.0.1
|
|
276
276
|
* @author AMBROISE PARK Consulting
|
|
@@ -287,7 +287,7 @@ export async function getUserSubscription(_firebaseUid: string): Promise<any> {
|
|
|
287
287
|
*
|
|
288
288
|
* C10: This was a silent no-op stub. Now throws to surface the missing implementation.
|
|
289
289
|
*
|
|
290
|
-
* @deprecated
|
|
290
|
+
* @deprecated Import `cancelUserSubscription` from `@donotdev/functions/shared/billing/helpers/subscriptionManagement`.
|
|
291
291
|
* @version 0.0.2
|
|
292
292
|
* @since 0.0.1
|
|
293
293
|
* @author AMBROISE PARK Consulting
|
|
@@ -307,7 +307,7 @@ export async function cancelUserSubscription(
|
|
|
307
307
|
*
|
|
308
308
|
* C10: This was a silent no-op stub. Now throws to surface the missing implementation.
|
|
309
309
|
*
|
|
310
|
-
* @deprecated
|
|
310
|
+
* @deprecated Handle via Stripe webhook events. Use `processWebhook` from `@donotdev/functions/shared/billing/webhookHandler`.
|
|
311
311
|
* @version 0.0.2
|
|
312
312
|
* @since 0.0.1
|
|
313
313
|
* @author AMBROISE PARK Consulting
|
|
@@ -326,7 +326,7 @@ export async function handleSubscriptionCancellation(
|
|
|
326
326
|
* Asserts that a user has admin privileges
|
|
327
327
|
* Uses role hierarchy: super > admin > user > guest
|
|
328
328
|
*
|
|
329
|
-
* @deprecated
|
|
329
|
+
* @deprecated Import `assertAdmin` from `@donotdev/functions/shared/utils/internal/auth` instead.
|
|
330
330
|
* This is a thin wrapper that delegates to the canonical provider-agnostic version.
|
|
331
331
|
*
|
|
332
332
|
* @version 0.0.3
|