@donotdev/functions 0.2.1 → 0.2.3
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 +2 -2
- package/lib/chunks/chunk-6NXIK35R.js +23 -0
- package/lib/chunks/chunk-6NXIK35R.js.map +7 -0
- package/lib/chunks/chunk-EZKRLLSQ.js +22 -0
- package/lib/chunks/chunk-EZKRLLSQ.js.map +7 -0
- package/lib/chunks/chunk-F3PHE627.js +22 -0
- package/lib/chunks/chunk-F3PHE627.js.map +7 -0
- package/lib/chunks/chunk-F3WBFWPO.js +151 -0
- package/lib/chunks/chunk-F3WBFWPO.js.map +7 -0
- package/lib/chunks/chunk-G5DRV3DH.js +22 -0
- package/lib/chunks/chunk-G5DRV3DH.js.map +7 -0
- package/lib/chunks/{chunk-5IPULSUX.js → chunk-GDIUOJMD.js} +2 -2
- package/lib/chunks/chunk-GDIUOJMD.js.map +7 -0
- package/lib/chunks/chunk-Q2WLRFOE.js +22 -0
- package/lib/chunks/chunk-Q2WLRFOE.js.map +7 -0
- package/lib/chunks/chunk-QXIOO2RL.js +22 -0
- package/lib/chunks/chunk-QXIOO2RL.js.map +7 -0
- package/lib/chunks/{chunk-3F4BWKQD.js → chunk-UH445BGK.js} +2 -2
- package/lib/chunks/chunk-W6W4L44F.js +22 -0
- package/lib/chunks/chunk-W6W4L44F.js.map +7 -0
- package/lib/chunks/chunk-W74UL7AY.js +22 -0
- package/lib/chunks/chunk-W74UL7AY.js.map +7 -0
- package/lib/chunks/{monitoring-E7JBYBHQ.js → monitoring-LXNVBD3G.js} +2 -2
- package/lib/chunks/{rateLimiter-SQISLOP5.js → rateLimiter-GG5LPWXJ.js} +2 -2
- package/lib/chunks/server-NODQAE3F.js +22 -0
- package/lib/firebase/billing/index.d.ts +2 -2
- package/lib/firebase/crud/aggregate.d.ts +1 -1
- package/lib/firebase/index.d.ts +1 -1
- package/lib/firebase/index.js +1 -1
- package/lib/firebase/index.js.map +4 -4
- package/lib/firebase/registerCrudFunctions.d.ts +0 -5
- package/lib/shared/billing/checkoutPrice.d.ts +3 -6
- package/lib/shared/billing/checkoutValidation.d.ts +1 -1
- package/lib/shared/billing/createCheckout.d.ts +4 -4
- package/lib/shared/billing/firestoreIdempotency.d.ts +2 -2
- package/lib/shared/billing/helpers/subscriptionManagement.d.ts +2 -2
- package/lib/shared/billing/idempotency.d.ts +3 -23
- package/lib/shared/billing/idempotencyContract.d.ts +0 -20
- package/lib/shared/billing/orderWebhook.d.ts +29 -2
- package/lib/shared/billing/stripePinned.d.ts +43 -0
- package/lib/shared/denoEnv.d.ts +25 -0
- package/lib/shared/github.d.ts +0 -8
- package/lib/shared/index.js +1 -1
- package/lib/shared/logger.d.ts +14 -14
- package/lib/shared/utils/external/subscription.d.ts +0 -8
- package/lib/shared/utils/internal/auth.d.ts +1 -5
- package/lib/shared/utils.d.ts +12 -83
- package/lib/supabase/auth/deleteAccount.d.ts +34 -2
- package/lib/supabase/crud/create.d.ts +0 -8
- package/lib/supabase/crud/entityStore.d.ts +13 -0
- package/lib/supabase/crud/update.d.ts +0 -8
- package/lib/supabase/index.d.ts +1 -0
- package/lib/supabase/index.js +1 -1
- package/lib/supabase/index.js.map +4 -4
- package/lib/vercel/api/index.js +1 -1
- package/lib/vercel/api/index.js.map +3 -3
- package/package.json +9 -9
- package/src/firebase/auth/getCustomClaims.ts +2 -0
- package/src/firebase/auth/getUserAuthStatus.ts +2 -0
- package/src/firebase/auth/removeCustomClaims.ts +2 -0
- package/src/firebase/auth/setCustomClaims.ts +3 -0
- package/src/firebase/baseFunction.ts +8 -4
- package/src/firebase/billing/changePlan.ts +6 -5
- package/src/firebase/billing/createCustomerPortal.ts +6 -4
- package/src/firebase/billing/index.d.ts +0 -12
- package/src/firebase/billing/index.ts +0 -3
- package/src/firebase/billing/refreshSubscriptionStatus.ts +7 -5
- package/src/firebase/billing/webhookHandler.ts +4 -4
- package/src/firebase/crud/aggregate.ts +41 -12
- package/src/firebase/crud/bulk.ts +7 -0
- package/src/firebase/crud/create.ts +21 -8
- package/src/firebase/crud/delete.ts +6 -1
- package/src/firebase/crud/get.ts +9 -2
- package/src/firebase/crud/list.ts +18 -8
- package/src/firebase/crud/update.ts +15 -7
- package/src/firebase/helpers/githubAccessHelper.ts +3 -0
- package/src/firebase/helpers/githubTeamAccessHelper.ts +1 -0
- package/src/firebase/index.ts +0 -1
- package/src/firebase/oauth/disconnect.ts +2 -2
- package/src/firebase/oauth/exchangeToken.ts +6 -2
- package/src/firebase/oauth/getConnections.ts +3 -3
- package/src/firebase/oauth/githubAccess.ts +7 -4
- package/src/firebase/oauth/refreshToken.ts +3 -2
- package/src/firebase/registerCrudFunctions.ts +0 -19
- package/src/firebase/scheduled/checkExpiredSubscriptions.ts +4 -1
- package/src/shared/__tests__/idempotency.test.ts +0 -32
- package/src/shared/__tests__/utils.test.ts +0 -25
- package/src/shared/ai/classifyAIError.ts +18 -10
- package/src/shared/ai/createAIRoute.ts +2 -1
- package/src/shared/ai/resolveModelTier.ts +2 -1
- package/src/shared/billing/__tests__/createCheckout.compat.test.ts +4 -110
- package/src/shared/billing/__tests__/createCheckout.test.ts +94 -0
- package/src/shared/billing/__tests__/firestoreIdempotency.emulator.test.ts +1 -1
- package/src/shared/billing/__tests__/webhookHandler.test.ts +108 -0
- package/src/shared/billing/checkoutPrice.ts +7 -42
- package/src/shared/billing/checkoutValidation.ts +19 -2
- package/src/shared/billing/createCheckout.ts +59 -30
- package/src/shared/billing/firestoreIdempotency.ts +2 -21
- package/src/shared/billing/helpers/subscriptionManagement.ts +14 -10
- package/src/shared/billing/idempotency.ts +4 -54
- package/src/shared/billing/idempotencyContract.ts +0 -21
- package/src/shared/billing/orderWebhook.ts +69 -1
- package/src/shared/billing/stripeClient.ts +2 -1
- package/src/shared/billing/stripePinned.ts +71 -0
- package/src/shared/billing/tierWebhookEvents.ts +3 -2
- package/src/shared/billing/webhookHandler.ts +5 -1
- package/src/shared/crud/bulkCore.ts +3 -2
- package/src/shared/denoEnv.ts +29 -0
- package/src/shared/email/createEmailRoute.ts +2 -2
- package/src/shared/errorHandling.ts +8 -8
- package/src/shared/firebase.ts +26 -9
- package/src/shared/github.ts +15 -5
- package/src/shared/logger.ts +37 -38
- package/src/shared/schema.ts +6 -10
- package/src/shared/utils/external/date.ts +4 -4
- package/src/shared/utils/external/subscription.ts +2 -89
- package/src/shared/utils/firebaseHelpers.ts +2 -0
- package/src/shared/utils/internal/auth.ts +1 -6
- package/src/shared/utils/internal/idempotency.ts +3 -0
- package/src/shared/utils/internal/monitoring.ts +6 -5
- package/src/shared/utils/internal/validation.ts +2 -0
- package/src/shared/utils/schemaValidation.ts +1 -0
- package/src/shared/utils/validation.ts +10 -20
- package/src/shared/utils.ts +12 -138
- package/src/supabase/__tests__/aggregate.test.ts +132 -0
- package/src/supabase/auth/__tests__/deleteAccount.test.ts +102 -0
- package/src/supabase/auth/deleteAccount.ts +72 -5
- package/src/supabase/billing/refreshSubscriptionStatus.ts +6 -5
- package/src/supabase/crud/aggregate.ts +85 -72
- package/src/supabase/crud/bulk.ts +3 -0
- package/src/supabase/crud/create.ts +13 -9
- package/src/supabase/crud/delete.ts +2 -1
- package/src/supabase/crud/entityStore.ts +1 -1
- package/src/supabase/crud/get.ts +2 -1
- package/src/supabase/crud/list.ts +23 -17
- package/src/supabase/crud/update.ts +9 -6
- package/src/supabase/edgeFunction.ts +2 -1
- package/src/supabase/email/createEmailFunction.ts +2 -1
- package/src/supabase/index.ts +1 -0
- package/src/supabase/oauth/exchangeToken.ts +1 -0
- package/src/supabase/oauth/getConnections.ts +1 -1
- package/src/supabase/oauth/refreshToken.ts +1 -0
- package/src/supabase/utils/idempotency.ts +1 -1
- package/src/supabase/utils/monitoring.ts +1 -0
- package/src/vercel/api/billing/change-plan.ts +6 -5
- package/src/vercel/api/billing/refresh-subscription-status.ts +3 -1
- package/src/vercel/api/crud/bulk.ts +7 -2
- package/src/vercel/api/crud/create.ts +6 -3
- package/src/vercel/api/crud/delete.ts +5 -2
- package/src/vercel/api/crud/get.ts +5 -2
- package/src/vercel/api/crud/list.ts +6 -3
- package/src/vercel/api/crud/update.ts +6 -3
- package/src/vercel/api/oauth/check-github-access.ts +1 -0
- package/src/vercel/api/oauth/exchange-token.ts +5 -2
- package/src/vercel/api/oauth/grant-github-access.ts +1 -0
- package/src/vercel/api/oauth/revoke-github-access.ts +1 -0
- package/src/vercel/baseFunction.ts +5 -1
- package/lib/chunks/chunk-5IPULSUX.js.map +0 -7
- package/lib/chunks/chunk-6USHTJED.js +0 -22
- package/lib/chunks/chunk-6USHTJED.js.map +0 -7
- package/lib/chunks/chunk-CXBSROEW.js +0 -23
- package/lib/chunks/chunk-CXBSROEW.js.map +0 -7
- package/lib/chunks/chunk-GYTCWMXV.js +0 -22
- package/lib/chunks/chunk-GYTCWMXV.js.map +0 -7
- package/lib/chunks/chunk-LCDLG4VG.js +0 -151
- package/lib/chunks/chunk-LCDLG4VG.js.map +0 -7
- package/lib/chunks/chunk-MQANUSY3.js +0 -22
- package/lib/chunks/chunk-MQANUSY3.js.map +0 -7
- package/lib/chunks/chunk-OFQVO3FD.js +0 -22
- package/lib/chunks/chunk-OFQVO3FD.js.map +0 -7
- package/lib/chunks/chunk-PWAGW4R6.js +0 -22
- package/lib/chunks/chunk-PWAGW4R6.js.map +0 -7
- package/lib/chunks/chunk-US2VOP4S.js +0 -22
- package/lib/chunks/chunk-US2VOP4S.js.map +0 -7
- package/lib/chunks/chunk-YTKDNZNW.js +0 -22
- package/lib/chunks/chunk-YTKDNZNW.js.map +0 -7
- package/lib/chunks/server-IQ5JNJOM.js +0 -22
- package/lib/shared/utils/functionWrapper.d.ts +0 -36
- package/src/shared/utils/__tests__/functionWrapper.test.ts +0 -122
- package/src/shared/utils/functionWrapper.ts +0 -73
- /package/lib/chunks/{chunk-3F4BWKQD.js.map → chunk-UH445BGK.js.map} +0 -0
- /package/lib/chunks/{monitoring-E7JBYBHQ.js.map → monitoring-LXNVBD3G.js.map} +0 -0
- /package/lib/chunks/{rateLimiter-SQISLOP5.js.map → rateLimiter-GG5LPWXJ.js.map} +0 -0
- /package/lib/chunks/{server-IQ5JNJOM.js.map → server-NODQAE3F.js.map} +0 -0
package/src/shared/schema.ts
CHANGED
|
@@ -15,11 +15,7 @@ import type * as v from 'valibot';
|
|
|
15
15
|
type Visibility = 'guest' | 'user' | 'admin' | 'technical' | 'hidden' | 'owner';
|
|
16
16
|
|
|
17
17
|
// Define a type for the custom visibility property we might add to Valibot schemas
|
|
18
|
-
interface ValibotSchemaWithVisibility extends v.
|
|
19
|
-
unknown,
|
|
20
|
-
any,
|
|
21
|
-
v.BaseIssue<unknown>
|
|
22
|
-
> {
|
|
18
|
+
interface ValibotSchemaWithVisibility extends v.GenericSchema {
|
|
23
19
|
visibility?: Visibility;
|
|
24
20
|
}
|
|
25
21
|
|
|
@@ -34,7 +30,7 @@ interface ValibotSchemaWithVisibility extends v.BaseSchema<
|
|
|
34
30
|
* @since 0.0.1
|
|
35
31
|
* @author AMBROISE PARK Consulting
|
|
36
32
|
*/
|
|
37
|
-
function getFieldVisibility(field:
|
|
33
|
+
function getFieldVisibility(field: unknown): Visibility | undefined {
|
|
38
34
|
// Check if the field has visibility property
|
|
39
35
|
if (field && typeof field === 'object' && 'visibility' in field) {
|
|
40
36
|
return (field as ValibotSchemaWithVisibility).visibility;
|
|
@@ -119,6 +115,7 @@ export function isFieldVisible(
|
|
|
119
115
|
* @author AMBROISE PARK Consulting
|
|
120
116
|
*/
|
|
121
117
|
export function getVisibleFields(
|
|
118
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- why: exported signature; narrowing it is a breaking change for importers (deferred to a major, any-audit 2026-11-11)
|
|
122
119
|
schema: any, // Accept any Valibot type, but process only objects
|
|
123
120
|
isAdmin: boolean
|
|
124
121
|
): string[] {
|
|
@@ -132,10 +129,7 @@ export function getVisibleFields(
|
|
|
132
129
|
}
|
|
133
130
|
|
|
134
131
|
// Extract the entries (field definitions) from the schema
|
|
135
|
-
const entries = schema.entries
|
|
136
|
-
string,
|
|
137
|
-
v.BaseSchema<unknown, any, v.BaseIssue<unknown>>
|
|
138
|
-
>;
|
|
132
|
+
const entries: Record<string, unknown> = schema.entries;
|
|
139
133
|
const visibleFieldNames: string[] = [];
|
|
140
134
|
|
|
141
135
|
// Iterate over each field defined in the schema's entries
|
|
@@ -164,8 +158,10 @@ export function getVisibleFields(
|
|
|
164
158
|
* @returns {Partial<T>} A new object containing only the fields visible to the user,
|
|
165
159
|
* or an empty object if input data is null/undefined.
|
|
166
160
|
*/
|
|
161
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- why: interface-typed records have no implicit index signature; Record<string, unknown> would reject them
|
|
167
162
|
export function filterVisibleFields<T extends Record<string, any>>(
|
|
168
163
|
data: T | null | undefined,
|
|
164
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- why: exported signature; narrowing it is a breaking change for importers (deferred to a major, any-audit 2026-11-11)
|
|
169
165
|
schema: any, // Use any for broader compatibility
|
|
170
166
|
isAdmin: boolean
|
|
171
167
|
): Partial<T> {
|
|
@@ -42,9 +42,8 @@ export function toISOString(date: DateValue): string {
|
|
|
42
42
|
return date.toISOString();
|
|
43
43
|
}
|
|
44
44
|
if (typeof date === 'object' && date !== null && 'toDate' in date) {
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
return timestamp.toDate().toISOString();
|
|
45
|
+
if (typeof date.toDate === 'function') {
|
|
46
|
+
return date.toDate().toISOString();
|
|
48
47
|
}
|
|
49
48
|
}
|
|
50
49
|
|
|
@@ -58,7 +57,8 @@ export function toISOString(date: DateValue): string {
|
|
|
58
57
|
}
|
|
59
58
|
|
|
60
59
|
// Fallback for any other type
|
|
61
|
-
|
|
60
|
+
// why: unreachable for typed callers; keeps the runtime path for untyped values (numbers, plain objects)
|
|
61
|
+
const parsed = new Date(date as unknown as string);
|
|
62
62
|
if (isNaN(parsed.getTime())) {
|
|
63
63
|
throw new Error('Invalid date format');
|
|
64
64
|
}
|
|
@@ -9,11 +9,7 @@
|
|
|
9
9
|
* @author AMBROISE PARK Consulting
|
|
10
10
|
*/
|
|
11
11
|
|
|
12
|
-
import type {
|
|
13
|
-
SubscriptionStatus,
|
|
14
|
-
SubscriptionClaims,
|
|
15
|
-
} from '@donotdev/core/server';
|
|
16
|
-
import { SUBSCRIPTION_STATUS } from '@donotdev/core/server';
|
|
12
|
+
import type { SubscriptionClaims } from '@donotdev/core/server';
|
|
17
13
|
import {
|
|
18
14
|
getFirebaseAdminAuth,
|
|
19
15
|
getFirebaseAdminFirestore,
|
|
@@ -42,90 +38,6 @@ export function getTierFromPriceId(priceId: string): string {
|
|
|
42
38
|
return tierMapping[priceId] || 'free';
|
|
43
39
|
}
|
|
44
40
|
|
|
45
|
-
/**
|
|
46
|
-
* Validates subscription status and updates Firebase custom claims
|
|
47
|
-
*
|
|
48
|
-
* @version 0.1.0
|
|
49
|
-
* @since 0.0.1
|
|
50
|
-
* @author AMBROISE PARK Consulting
|
|
51
|
-
*/
|
|
52
|
-
export async function updateFirebaseUserSubscription(
|
|
53
|
-
firebaseUid: string,
|
|
54
|
-
subscription: any
|
|
55
|
-
): Promise<void> {
|
|
56
|
-
if (!firebaseUid) {
|
|
57
|
-
throw new Error('Firebase UID is required to update subscription');
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
const priceId = subscription.items?.data?.[0]?.price?.id;
|
|
61
|
-
const tier = getTierFromPriceId(priceId);
|
|
62
|
-
|
|
63
|
-
// Validate status: must be a framework value OR a valid custom consumer value (non-empty string)
|
|
64
|
-
// Default to 'incomplete' if invalid/empty
|
|
65
|
-
const frameworkStatuses = Object.values(SUBSCRIPTION_STATUS);
|
|
66
|
-
const rawStatus = subscription.status || '';
|
|
67
|
-
const isValidFrameworkStatus = frameworkStatuses.includes(rawStatus as any);
|
|
68
|
-
const isValidCustomStatus =
|
|
69
|
-
typeof rawStatus === 'string' && rawStatus.trim().length > 0;
|
|
70
|
-
|
|
71
|
-
const status: SubscriptionStatus =
|
|
72
|
-
isValidFrameworkStatus || isValidCustomStatus
|
|
73
|
-
? (rawStatus as SubscriptionStatus)
|
|
74
|
-
: SUBSCRIPTION_STATUS.INCOMPLETE;
|
|
75
|
-
|
|
76
|
-
const subscriptionClaims: SubscriptionClaims = {
|
|
77
|
-
tier,
|
|
78
|
-
subscriptionId: subscription.id,
|
|
79
|
-
customerId: subscription.customer,
|
|
80
|
-
status,
|
|
81
|
-
subscriptionEnd: subscription.current_period_end
|
|
82
|
-
? new Date(subscription.current_period_end * 1000).toISOString()
|
|
83
|
-
: null,
|
|
84
|
-
cancelAtPeriodEnd: subscription.cancel_at_period_end || false,
|
|
85
|
-
updatedAt: new Date().toISOString(),
|
|
86
|
-
};
|
|
87
|
-
|
|
88
|
-
try {
|
|
89
|
-
const auth = getFirebaseAdminAuth();
|
|
90
|
-
const db = getFirebaseAdminFirestore();
|
|
91
|
-
|
|
92
|
-
// Read existing claims and merge to avoid overwriting other claims
|
|
93
|
-
const user = await auth.getUser(firebaseUid);
|
|
94
|
-
const currentClaims = user.customClaims || {};
|
|
95
|
-
|
|
96
|
-
// Update Firebase Auth custom claims
|
|
97
|
-
await auth.setCustomUserClaims(firebaseUid, {
|
|
98
|
-
...currentClaims,
|
|
99
|
-
subscription: subscriptionClaims,
|
|
100
|
-
});
|
|
101
|
-
|
|
102
|
-
// Also save to Firestore for redundancy and querying
|
|
103
|
-
await db
|
|
104
|
-
.collection('subscriptions')
|
|
105
|
-
.doc(firebaseUid)
|
|
106
|
-
.set(
|
|
107
|
-
{
|
|
108
|
-
...subscriptionClaims,
|
|
109
|
-
priceId,
|
|
110
|
-
createdAt: subscription.created
|
|
111
|
-
? new Date(subscription.created * 1000).toISOString()
|
|
112
|
-
: new Date().toISOString(),
|
|
113
|
-
updatedAt: new Date().toISOString(),
|
|
114
|
-
},
|
|
115
|
-
{ merge: true }
|
|
116
|
-
);
|
|
117
|
-
|
|
118
|
-
console.log(`Subscription updated for user ${firebaseUid}:`, {
|
|
119
|
-
tier,
|
|
120
|
-
status: subscription.status,
|
|
121
|
-
subscriptionId: subscription.id,
|
|
122
|
-
});
|
|
123
|
-
} catch (error) {
|
|
124
|
-
console.error('Failed to update user subscription:', error);
|
|
125
|
-
throw new Error('Failed to update user subscription');
|
|
126
|
-
}
|
|
127
|
-
}
|
|
128
|
-
|
|
129
41
|
/**
|
|
130
42
|
* Cancels user subscription and resets to free tier
|
|
131
43
|
*
|
|
@@ -135,6 +47,7 @@ export async function updateFirebaseUserSubscription(
|
|
|
135
47
|
*/
|
|
136
48
|
export async function cancelUserSubscription(
|
|
137
49
|
firebaseUid: string,
|
|
50
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- why: exported signature; narrowing it is a breaking change for importers (deferred to a major, any-audit 2026-11-11)
|
|
138
51
|
subscription: any
|
|
139
52
|
): Promise<void> {
|
|
140
53
|
if (!firebaseUid) {
|
|
@@ -23,6 +23,7 @@ import { withSchemaValidation } from './schemaValidation.js';
|
|
|
23
23
|
* @author AMBROISE PARK Consulting
|
|
24
24
|
*/
|
|
25
25
|
export function createFirebaseCallable<TRequest, TResponse>(
|
|
26
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- why: exported signature; narrowing it is a breaking change for importers (deferred to a major, any-audit 2026-11-11)
|
|
26
27
|
config: any,
|
|
27
28
|
defaultSchema: v.BaseSchema<unknown, TRequest, v.BaseIssue<unknown>>,
|
|
28
29
|
handler: (
|
|
@@ -56,6 +57,7 @@ export function createFirebaseCallable<TRequest, TResponse>(
|
|
|
56
57
|
* @author AMBROISE PARK Consulting
|
|
57
58
|
*/
|
|
58
59
|
export function createFirebaseFunctionExports<TRequest, TResponse>(
|
|
60
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- why: exported signature; narrowing it is a breaking change for importers (deferred to a major, any-audit 2026-11-11)
|
|
59
61
|
config: any,
|
|
60
62
|
defaultSchema: v.BaseSchema<unknown, TRequest, v.BaseIssue<unknown>>,
|
|
61
63
|
handler: (
|
|
@@ -75,7 +75,7 @@ async function getFirebaseAuth() {
|
|
|
75
75
|
* @since 0.0.1
|
|
76
76
|
* @author AMBROISE PARK Consulting
|
|
77
77
|
*/
|
|
78
|
-
export function assertAuthenticated(uid: string): string {
|
|
78
|
+
export function assertAuthenticated(uid: string | undefined): string {
|
|
79
79
|
// G62: Validate uid is a non-empty string — reject non-string values at runtime
|
|
80
80
|
if (!uid || typeof uid !== 'string') {
|
|
81
81
|
throw new Error('Authentication required');
|
|
@@ -258,8 +258,3 @@ export async function verifyAuthToken(
|
|
|
258
258
|
const { uid } = await verifyToken(token, provider);
|
|
259
259
|
return uid;
|
|
260
260
|
}
|
|
261
|
-
|
|
262
|
-
/**
|
|
263
|
-
* @deprecated Use verifyAuthToken instead. Kept for backwards compatibility.
|
|
264
|
-
*/
|
|
265
|
-
export const verifyFirebaseAuthToken = verifyAuthToken;
|
|
@@ -14,6 +14,7 @@ import { logger } from 'firebase-functions/v2';
|
|
|
14
14
|
import { getFirebaseAdminFirestore } from '@donotdev/firebase/server';
|
|
15
15
|
|
|
16
16
|
/** Stored result of a previously processed idempotent operation. */
|
|
17
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- why: exported signature; narrowing it is a breaking change for importers (deferred to a major, any-audit 2026-11-11)
|
|
17
18
|
export interface IdempotencyResult<T = any> {
|
|
18
19
|
result: T;
|
|
19
20
|
processedAt: string;
|
|
@@ -27,6 +28,7 @@ export interface IdempotencyResult<T = any> {
|
|
|
27
28
|
* @since 0.0.1
|
|
28
29
|
* @author AMBROISE PARK Consulting
|
|
29
30
|
*/
|
|
31
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- why: exported signature; narrowing it is a breaking change for importers (deferred to a major, any-audit 2026-11-11)
|
|
30
32
|
export async function checkIdempotency<T = any>(
|
|
31
33
|
key: string,
|
|
32
34
|
operation: string
|
|
@@ -70,6 +72,7 @@ export async function checkIdempotency<T = any>(
|
|
|
70
72
|
* @since 0.0.1
|
|
71
73
|
* @author AMBROISE PARK Consulting
|
|
72
74
|
*/
|
|
75
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- why: exported signature; narrowing it is a breaking change for importers (deferred to a major, any-audit 2026-11-11)
|
|
73
76
|
export async function storeIdempotencyResult<T = any>(
|
|
74
77
|
key: string,
|
|
75
78
|
operation: string,
|
|
@@ -35,6 +35,7 @@ export interface PaymentMetrics {
|
|
|
35
35
|
currency?: string;
|
|
36
36
|
status: 'success' | 'failed' | 'pending';
|
|
37
37
|
timestamp: string;
|
|
38
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- why: exported signature; narrowing it is a breaking change for importers (deferred to a major, any-audit 2026-11-11)
|
|
38
39
|
metadata?: Record<string, any>;
|
|
39
40
|
}
|
|
40
41
|
|
|
@@ -109,7 +110,7 @@ export async function checkPaymentFailureRate(
|
|
|
109
110
|
|
|
110
111
|
const totalPayments = recentMetrics.size;
|
|
111
112
|
const failedPayments = recentMetrics.docs.filter(
|
|
112
|
-
(doc
|
|
113
|
+
(doc) => doc.data().status === 'failed'
|
|
113
114
|
).length;
|
|
114
115
|
|
|
115
116
|
const failureRate = (failedPayments / totalPayments) * 100;
|
|
@@ -157,7 +158,7 @@ export async function checkPaymentVolume(
|
|
|
157
158
|
.get();
|
|
158
159
|
|
|
159
160
|
let totalVolume = 0;
|
|
160
|
-
todayMetrics.docs.forEach((doc
|
|
161
|
+
todayMetrics.docs.forEach((doc) => {
|
|
161
162
|
const data = doc.data();
|
|
162
163
|
if (data.amount && data.currency === 'usd') {
|
|
163
164
|
totalVolume += data.amount / 100; // Convert cents to dollars
|
|
@@ -284,7 +285,7 @@ export async function getPaymentMetricsSummary(
|
|
|
284
285
|
let failedPayments = 0;
|
|
285
286
|
let totalVolume = 0;
|
|
286
287
|
|
|
287
|
-
metrics.docs.forEach((doc
|
|
288
|
+
metrics.docs.forEach((doc) => {
|
|
288
289
|
const data = doc.data();
|
|
289
290
|
totalPayments++;
|
|
290
291
|
|
|
@@ -349,7 +350,7 @@ export async function cleanupOldMetrics(
|
|
|
349
350
|
|
|
350
351
|
if (!oldMetrics.empty) {
|
|
351
352
|
const batch = db.batch();
|
|
352
|
-
oldMetrics.docs.forEach((doc
|
|
353
|
+
oldMetrics.docs.forEach((doc) => batch.delete(doc.ref));
|
|
353
354
|
await batch.commit();
|
|
354
355
|
}
|
|
355
356
|
|
|
@@ -365,7 +366,7 @@ export async function cleanupOldMetrics(
|
|
|
365
366
|
|
|
366
367
|
if (!oldAlerts.empty) {
|
|
367
368
|
const batch = db.batch();
|
|
368
|
-
oldAlerts.docs.forEach((doc
|
|
369
|
+
oldAlerts.docs.forEach((doc) => batch.delete(doc.ref));
|
|
369
370
|
await batch.commit();
|
|
370
371
|
}
|
|
371
372
|
|
|
@@ -20,6 +20,7 @@ import { DoNotDevError } from '@donotdev/core/server';
|
|
|
20
20
|
* @since 0.0.1
|
|
21
21
|
* @author AMBROISE PARK Consulting
|
|
22
22
|
*/
|
|
23
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- why: exported signature; narrowing it is a breaking change for importers (deferred to a major, any-audit 2026-11-11)
|
|
23
24
|
export function safeJsonParse<T = any>(json: string): T | null {
|
|
24
25
|
try {
|
|
25
26
|
return JSON.parse(json);
|
|
@@ -64,6 +65,7 @@ export function validateCollectionName(name: string): void {
|
|
|
64
65
|
* @since 0.0.1
|
|
65
66
|
* @author AMBROISE PARK Consulting
|
|
66
67
|
*/
|
|
68
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- why: exported signature; narrowing it is a breaking change for importers (deferred to a major, any-audit 2026-11-11)
|
|
67
69
|
export function validateDocument(data: any, schema?: any): void {
|
|
68
70
|
// G63: Throw DoNotDevError instead of plain Error for consistent error handling
|
|
69
71
|
if (!data || typeof data !== 'object') {
|
|
@@ -21,6 +21,7 @@ import * as v from 'valibot';
|
|
|
21
21
|
* @author AMBROISE PARK Consulting
|
|
22
22
|
*/
|
|
23
23
|
export function validateRequestData<T>(
|
|
24
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- why: exported signature; narrowing it is a breaking change for importers (deferred to a major, any-audit 2026-11-11)
|
|
24
25
|
data: any,
|
|
25
26
|
defaultSchema: v.BaseSchema<unknown, T, v.BaseIssue<unknown>>,
|
|
26
27
|
customSchema?: v.BaseSchema<unknown, T, v.BaseIssue<unknown>>
|
|
@@ -57,6 +57,7 @@ export const StripeValidationSchemas = {
|
|
|
57
57
|
export interface ValidationResult {
|
|
58
58
|
isValid: boolean;
|
|
59
59
|
errors: string[];
|
|
60
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- why: exported signature; narrowing it is a breaking change for importers (deferred to a major, any-audit 2026-11-11)
|
|
60
61
|
data?: any;
|
|
61
62
|
}
|
|
62
63
|
|
|
@@ -67,6 +68,7 @@ export interface ValidationResult {
|
|
|
67
68
|
* @since 0.0.1
|
|
68
69
|
* @author AMBROISE PARK Consulting
|
|
69
70
|
*/
|
|
71
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- why: exported signature; narrowing it is a breaking change for importers (deferred to a major, any-audit 2026-11-11)
|
|
70
72
|
export function validateWebhookEvent(data: any): ValidationResult {
|
|
71
73
|
try {
|
|
72
74
|
const validatedData = v.parse(StripeValidationSchemas.webhookEvent, data);
|
|
@@ -76,16 +78,9 @@ export function validateWebhookEvent(data: any): ValidationResult {
|
|
|
76
78
|
errors: [],
|
|
77
79
|
};
|
|
78
80
|
} catch (error) {
|
|
79
|
-
if (
|
|
80
|
-
error
|
|
81
|
-
|
|
82
|
-
'issues' in error &&
|
|
83
|
-
((error instanceof Error && error.name === 'ValiError') ||
|
|
84
|
-
(error as any).name === 'ValiError')
|
|
85
|
-
) {
|
|
86
|
-
const valiError = error as any;
|
|
87
|
-
const errors = valiError.issues.map(
|
|
88
|
-
(err: v.BaseIssue<unknown>) =>
|
|
81
|
+
if (v.isValiError(error)) {
|
|
82
|
+
const errors = error.issues.map(
|
|
83
|
+
(err) =>
|
|
89
84
|
`${err.path?.map((p) => p.key).join('.') || ''}: ${err.message}`
|
|
90
85
|
);
|
|
91
86
|
logger.warn('Webhook event validation failed', { errors, data });
|
|
@@ -108,6 +103,7 @@ export function validateWebhookEvent(data: any): ValidationResult {
|
|
|
108
103
|
* @since 0.0.1
|
|
109
104
|
* @author AMBROISE PARK Consulting
|
|
110
105
|
*/
|
|
106
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- why: exported signature; narrowing it is a breaking change for importers (deferred to a major, any-audit 2026-11-11)
|
|
111
107
|
export function validatePurchaseRequest(data: any): ValidationResult {
|
|
112
108
|
try {
|
|
113
109
|
const validatedData = v.parse(
|
|
@@ -120,16 +116,9 @@ export function validatePurchaseRequest(data: any): ValidationResult {
|
|
|
120
116
|
errors: [],
|
|
121
117
|
};
|
|
122
118
|
} catch (error) {
|
|
123
|
-
if (
|
|
124
|
-
error
|
|
125
|
-
|
|
126
|
-
'issues' in error &&
|
|
127
|
-
((error instanceof Error && error.name === 'ValiError') ||
|
|
128
|
-
(error as any).name === 'ValiError')
|
|
129
|
-
) {
|
|
130
|
-
const valiError = error as any;
|
|
131
|
-
const errors = valiError.issues.map(
|
|
132
|
-
(err: v.BaseIssue<unknown>) =>
|
|
119
|
+
if (v.isValiError(error)) {
|
|
120
|
+
const errors = error.issues.map(
|
|
121
|
+
(err) =>
|
|
133
122
|
`${err.path?.map((p) => p.key).join('.') || ''}: ${err.message}`
|
|
134
123
|
);
|
|
135
124
|
logger.warn('Purchase request validation failed', { errors, data });
|
|
@@ -223,6 +212,7 @@ export function validateUrl(url: string, name: string = 'URL'): string {
|
|
|
223
212
|
* @author AMBROISE PARK Consulting
|
|
224
213
|
*/
|
|
225
214
|
export function validateMetadata(
|
|
215
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- why: exported signature; narrowing it is a breaking change for importers (deferred to a major, any-audit 2026-11-11)
|
|
226
216
|
metadata: Record<string, any>
|
|
227
217
|
): Record<string, string> {
|
|
228
218
|
const sanitized: Record<string, string> = {};
|
package/src/shared/utils.ts
CHANGED
|
@@ -14,36 +14,9 @@ import * as v from 'valibot';
|
|
|
14
14
|
import { DoNotDevError } from '@donotdev/core/server';
|
|
15
15
|
import type { OAuthPartnerId, UserRole } from '@donotdev/core/server';
|
|
16
16
|
|
|
17
|
-
import {
|
|
18
|
-
assertAuthenticated as internalAssertAuthenticated,
|
|
19
|
-
assertAdmin as internalAssertAdmin,
|
|
20
|
-
} from './utils/internal/auth.js';
|
|
21
|
-
|
|
22
17
|
// Re-export DoNotDevError for external use
|
|
23
18
|
export { DoNotDevError };
|
|
24
19
|
|
|
25
|
-
/**
|
|
26
|
-
* Assert that a user is authenticated from a Firebase callable auth context.
|
|
27
|
-
*
|
|
28
|
-
* @deprecated Import `assertAuthenticated` from `@donotdev/functions/shared/utils/internal/auth` instead.
|
|
29
|
-
* This wrapper extracts uid from a Firebase callable auth context and delegates
|
|
30
|
-
* to the canonical version.
|
|
31
|
-
*
|
|
32
|
-
* @param auth - Firebase callable request auth context (object with `.uid`)
|
|
33
|
-
* @returns The authenticated user's uid
|
|
34
|
-
*
|
|
35
|
-
* @version 0.1.0
|
|
36
|
-
* @since 0.0.1
|
|
37
|
-
* @author AMBROISE PARK Consulting
|
|
38
|
-
*/
|
|
39
|
-
export function assertAuthenticated(auth: any): string {
|
|
40
|
-
const uid = auth?.uid;
|
|
41
|
-
if (!uid) {
|
|
42
|
-
throw new Error('User must be authenticated');
|
|
43
|
-
}
|
|
44
|
-
return internalAssertAuthenticated(uid);
|
|
45
|
-
}
|
|
46
|
-
|
|
47
20
|
/**
|
|
48
21
|
* Get user role from Firebase auth context
|
|
49
22
|
*
|
|
@@ -60,7 +33,9 @@ export function assertAuthenticated(auth: any): string {
|
|
|
60
33
|
* @since 0.0.1
|
|
61
34
|
* @author AMBROISE PARK Consulting
|
|
62
35
|
*/
|
|
63
|
-
export function getUserRole(
|
|
36
|
+
export function getUserRole(
|
|
37
|
+
auth: { uid?: string; token?: Record<string, unknown> } | null | undefined
|
|
38
|
+
): UserRole {
|
|
64
39
|
if (!auth?.uid) return 'guest';
|
|
65
40
|
|
|
66
41
|
// Check role claim (standard pattern: auth.token.role = 'admin' | 'super' | etc.)
|
|
@@ -101,7 +76,7 @@ export function createErrorResponse(error: unknown): {
|
|
|
101
76
|
error: {
|
|
102
77
|
code: string;
|
|
103
78
|
message: string;
|
|
104
|
-
details?:
|
|
79
|
+
details?: Record<string, unknown>;
|
|
105
80
|
};
|
|
106
81
|
} {
|
|
107
82
|
if (error instanceof DoNotDevError) {
|
|
@@ -134,110 +109,6 @@ export function createErrorResponse(error: unknown): {
|
|
|
134
109
|
};
|
|
135
110
|
}
|
|
136
111
|
|
|
137
|
-
/**
|
|
138
|
-
* Updates user subscription in Firebase.
|
|
139
|
-
*
|
|
140
|
-
* **Architecture decision — throwing stubs for billing functions:**
|
|
141
|
-
* These subscription functions (`updateUserSubscription`, `getUserSubscription`,
|
|
142
|
-
* `cancelUserSubscription`, `handleSubscriptionCancellation`) are intentional
|
|
143
|
-
* placeholder implementations. They exist so the framework compiles and
|
|
144
|
-
* type-checks out of the box, but throw at runtime to surface missing
|
|
145
|
-
* integration early. Consumer apps replace them with their billing provider
|
|
146
|
-
* integration (Stripe, Paddle, LemonSqueezy, etc.) via the documented
|
|
147
|
-
* `shared/billing/helpers/` modules.
|
|
148
|
-
*
|
|
149
|
-
* C10: This was a silent no-op stub. It now throws to surface the missing
|
|
150
|
-
* implementation at startup rather than silently dropping webhook events.
|
|
151
|
-
* Use `updateUserSubscription` from `shared/billing/helpers/updateUserSubscription.ts`
|
|
152
|
-
* (which requires an authProvider) instead.
|
|
153
|
-
*
|
|
154
|
-
* @deprecated Import `updateUserSubscription` from `@donotdev/functions/shared/billing/helpers/updateUserSubscription`.
|
|
155
|
-
* @version 0.1.0
|
|
156
|
-
* @since 0.0.1
|
|
157
|
-
* @author AMBROISE PARK Consulting
|
|
158
|
-
*/
|
|
159
|
-
export async function updateUserSubscription(
|
|
160
|
-
_firebaseUid: string,
|
|
161
|
-
_subscription: any
|
|
162
|
-
): Promise<void> {
|
|
163
|
-
throw new DoNotDevError(
|
|
164
|
-
'updateUserSubscription stub called — import from shared/billing/helpers/updateUserSubscription.ts and supply an authProvider',
|
|
165
|
-
'unimplemented'
|
|
166
|
-
);
|
|
167
|
-
}
|
|
168
|
-
|
|
169
|
-
/**
|
|
170
|
-
* Gets user subscription from Firebase.
|
|
171
|
-
*
|
|
172
|
-
* C10: This was a silent no-op stub. Now throws to surface the missing implementation.
|
|
173
|
-
*
|
|
174
|
-
* @deprecated Import from `@donotdev/functions/shared/billing/helpers` or implement directly using Firebase Admin SDK / Stripe API.
|
|
175
|
-
* @version 0.1.0
|
|
176
|
-
* @since 0.0.1
|
|
177
|
-
* @author AMBROISE PARK Consulting
|
|
178
|
-
*/
|
|
179
|
-
export async function getUserSubscription(_firebaseUid: string): Promise<any> {
|
|
180
|
-
throw new DoNotDevError(
|
|
181
|
-
'getUserSubscription stub called — implement using Firebase Admin SDK or Stripe API',
|
|
182
|
-
'unimplemented'
|
|
183
|
-
);
|
|
184
|
-
}
|
|
185
|
-
|
|
186
|
-
/**
|
|
187
|
-
* Cancels user subscription.
|
|
188
|
-
*
|
|
189
|
-
* C10: This was a silent no-op stub. Now throws to surface the missing implementation.
|
|
190
|
-
*
|
|
191
|
-
* @deprecated Import `cancelUserSubscription` from `@donotdev/functions/shared/billing/helpers/subscriptionManagement`.
|
|
192
|
-
* @version 0.1.0
|
|
193
|
-
* @since 0.0.1
|
|
194
|
-
* @author AMBROISE PARK Consulting
|
|
195
|
-
*/
|
|
196
|
-
export async function cancelUserSubscription(
|
|
197
|
-
_firebaseUid: string,
|
|
198
|
-
_subscription: any
|
|
199
|
-
): Promise<void> {
|
|
200
|
-
throw new DoNotDevError(
|
|
201
|
-
'cancelUserSubscription stub called — import from shared/billing/helpers/subscriptionManagement.ts',
|
|
202
|
-
'unimplemented'
|
|
203
|
-
);
|
|
204
|
-
}
|
|
205
|
-
|
|
206
|
-
/**
|
|
207
|
-
* Handles subscription cancellation.
|
|
208
|
-
*
|
|
209
|
-
* C10: This was a silent no-op stub. Now throws to surface the missing implementation.
|
|
210
|
-
*
|
|
211
|
-
* @deprecated Handle via Stripe webhook events. Use `processWebhook` from `@donotdev/functions/shared/billing/webhookHandler`.
|
|
212
|
-
* @version 0.1.0
|
|
213
|
-
* @since 0.0.1
|
|
214
|
-
* @author AMBROISE PARK Consulting
|
|
215
|
-
*/
|
|
216
|
-
export async function handleSubscriptionCancellation(
|
|
217
|
-
_firebaseUid: string,
|
|
218
|
-
_subscription: any
|
|
219
|
-
): Promise<void> {
|
|
220
|
-
throw new DoNotDevError(
|
|
221
|
-
'handleSubscriptionCancellation stub called — handle via Stripe webhook events',
|
|
222
|
-
'unimplemented'
|
|
223
|
-
);
|
|
224
|
-
}
|
|
225
|
-
|
|
226
|
-
/**
|
|
227
|
-
* Asserts that a user has admin privileges
|
|
228
|
-
* Uses role hierarchy: super > admin > user > guest
|
|
229
|
-
*
|
|
230
|
-
* @deprecated Import `assertAdmin` from `@donotdev/functions/shared/utils/internal/auth` instead.
|
|
231
|
-
* This is a thin wrapper that delegates to the canonical provider-agnostic version.
|
|
232
|
-
*
|
|
233
|
-
* @version 0.1.0
|
|
234
|
-
* @since 0.0.1
|
|
235
|
-
* @author AMBROISE PARK Consulting
|
|
236
|
-
*/
|
|
237
|
-
export async function assertAdmin(uid: string): Promise<string> {
|
|
238
|
-
return internalAssertAdmin(uid);
|
|
239
|
-
}
|
|
240
|
-
|
|
241
112
|
/**
|
|
242
113
|
* Validates document data
|
|
243
114
|
*
|
|
@@ -245,7 +116,10 @@ export async function assertAdmin(uid: string): Promise<string> {
|
|
|
245
116
|
* @since 0.0.1
|
|
246
117
|
* @author AMBROISE PARK Consulting
|
|
247
118
|
*/
|
|
248
|
-
export function validateDocument(
|
|
119
|
+
export function validateDocument(
|
|
120
|
+
data: unknown,
|
|
121
|
+
schema?: v.GenericSchema
|
|
122
|
+
): void {
|
|
249
123
|
if (!data || typeof data !== 'object') {
|
|
250
124
|
throw new Error('Invalid document data');
|
|
251
125
|
}
|
|
@@ -258,12 +132,12 @@ export function validateDocument(data: any, schema?: any): void {
|
|
|
258
132
|
if (schema) {
|
|
259
133
|
try {
|
|
260
134
|
v.parse(schema, data);
|
|
261
|
-
} catch (error
|
|
262
|
-
if (error
|
|
135
|
+
} catch (error) {
|
|
136
|
+
if (v.isValiError(error)) {
|
|
263
137
|
const messages = error.issues
|
|
264
138
|
.map(
|
|
265
|
-
(issue
|
|
266
|
-
`${issue.path?.map((p
|
|
139
|
+
(issue) =>
|
|
140
|
+
`${issue.path?.map((p) => p.key).join('.') || 'root'}: ${issue.message}`
|
|
267
141
|
)
|
|
268
142
|
.join('; ');
|
|
269
143
|
throw new DoNotDevError(
|