@donotdev/functions 0.0.20 → 0.1.1

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.
Files changed (303) hide show
  1. package/LICENSE.md +3 -3
  2. package/guidelines/FUNCTIONS.md +9 -0
  3. package/guidelines/VERCEL.md +260 -0
  4. package/lib/firebase/auth/getCustomClaims.d.ts +2 -2
  5. package/lib/firebase/auth/getUserAuthStatus.d.ts +2 -2
  6. package/lib/firebase/auth/index.d.ts +1 -1
  7. package/lib/firebase/auth/removeCustomClaims.d.ts +2 -2
  8. package/lib/firebase/auth/setCustomClaims.d.ts +2 -2
  9. package/lib/firebase/baseFunction.d.ts +1 -1
  10. package/lib/firebase/billing/cancelSubscription.d.ts +1 -1
  11. package/lib/firebase/billing/changePlan.d.ts +1 -1
  12. package/lib/firebase/billing/createCheckoutSession.d.ts +10 -13
  13. package/lib/firebase/billing/createCustomerPortal.d.ts +1 -1
  14. package/lib/firebase/billing/index.d.ts +1 -1
  15. package/lib/firebase/billing/refreshSubscriptionStatus.d.ts +2 -2
  16. package/lib/firebase/config/constants.d.ts +4 -4
  17. package/lib/firebase/config/index.d.ts +1 -1
  18. package/lib/firebase/crud/aggregate.d.ts +2 -2
  19. package/lib/firebase/crud/delete.d.ts +1 -1
  20. package/lib/firebase/crud/get.d.ts +1 -1
  21. package/lib/firebase/crud/index.d.ts +1 -1
  22. package/lib/firebase/crud/update.d.ts +1 -1
  23. package/lib/firebase/helpers/githubAccessHelper.d.ts +3 -3
  24. package/lib/firebase/helpers/githubTeamAccessHelper.d.ts +2 -2
  25. package/lib/firebase/helpers/index.d.ts +1 -1
  26. package/lib/firebase/index.d.ts +1 -1
  27. package/lib/firebase/index.js +3 -3
  28. package/lib/firebase/index.js.map +4 -4
  29. package/lib/firebase/oauth/disconnect.d.ts +1 -1
  30. package/lib/firebase/oauth/exchangeToken.d.ts +1 -1
  31. package/lib/firebase/oauth/getConnections.d.ts +1 -1
  32. package/lib/firebase/oauth/githubAccess.d.ts +6 -6
  33. package/lib/firebase/oauth/index.d.ts +1 -1
  34. package/lib/firebase/oauth/refreshToken.d.ts +1 -1
  35. package/lib/firebase/scheduled/index.d.ts +1 -1
  36. package/lib/shared/ai/classifyAIError.d.ts +35 -0
  37. package/lib/shared/ai/costTracker.d.ts +20 -0
  38. package/lib/shared/ai/createAIRoute.d.ts +20 -0
  39. package/lib/shared/ai/index.d.ts +6 -0
  40. package/lib/shared/ai/resolveModelTier.d.ts +14 -0
  41. package/lib/shared/billing/createCheckout.d.ts +11 -5
  42. package/lib/shared/billing/helpers/index.d.ts +1 -1
  43. package/lib/shared/billing/helpers/subscriptionManagement.d.ts +3 -3
  44. package/lib/shared/billing/helpers/updateUserSubscription.d.ts +4 -4
  45. package/lib/shared/billing/idempotency.d.ts +2 -2
  46. package/lib/shared/billing/index.d.ts +1 -1
  47. package/lib/shared/billing/webhookHandler.d.ts +1 -1
  48. package/lib/shared/email/createEmailRoute.d.ts +30 -0
  49. package/lib/shared/email/index.d.ts +3 -0
  50. package/lib/shared/email/provider.d.ts +30 -0
  51. package/lib/shared/email/resendProvider.d.ts +22 -0
  52. package/lib/shared/errorHandling.d.ts +1 -1
  53. package/lib/shared/firebase.d.ts +7 -7
  54. package/lib/shared/github.d.ts +16 -11
  55. package/lib/shared/index.d.ts +3 -1
  56. package/lib/shared/index.js +4 -3
  57. package/lib/shared/index.js.map +4 -4
  58. package/lib/shared/logger.d.ts +8 -6
  59. package/lib/shared/metadata.d.ts +3 -3
  60. package/lib/shared/oauth/exchangeToken.d.ts +3 -2
  61. package/lib/shared/oauth/grantAccess.d.ts +3 -2
  62. package/lib/shared/oauth/index.d.ts +1 -1
  63. package/lib/shared/schema.d.ts +2 -2
  64. package/lib/shared/utils/detectFirestore.d.ts +3 -3
  65. package/lib/shared/utils/external/date.d.ts +2 -2
  66. package/lib/shared/utils/external/index.d.ts +1 -1
  67. package/lib/shared/utils/external/references.d.ts +1 -1
  68. package/lib/shared/utils/external/subscription.d.ts +5 -5
  69. package/lib/shared/utils/firebaseHelpers.d.ts +2 -2
  70. package/lib/shared/utils/functionWrapper.d.ts +4 -4
  71. package/lib/shared/utils/index.d.ts +1 -1
  72. package/lib/shared/utils/internal/auth.d.ts +4 -4
  73. package/lib/shared/utils/internal/idempotency.d.ts +3 -2
  74. package/lib/shared/utils/internal/index.d.ts +1 -1
  75. package/lib/shared/utils/internal/monitoring.d.ts +7 -7
  76. package/lib/shared/utils/internal/rateLimiter.d.ts +5 -5
  77. package/lib/shared/utils/internal/validation.d.ts +4 -4
  78. package/lib/shared/utils/schemaValidation.d.ts +6 -6
  79. package/lib/shared/utils/validation.d.ts +9 -9
  80. package/lib/shared/utils/vercelHelpers.d.ts +2 -2
  81. package/lib/shared/utils.d.ts +19 -19
  82. package/lib/shared/validation.d.ts +2 -2
  83. package/lib/supabase/ai/createAIFunction.d.ts +30 -0
  84. package/lib/supabase/auth/deleteAccount.d.ts +1 -1
  85. package/lib/supabase/auth/getCustomClaims.d.ts +1 -1
  86. package/lib/supabase/auth/getUserAuthStatus.d.ts +1 -1
  87. package/lib/supabase/auth/removeCustomClaims.d.ts +1 -1
  88. package/lib/supabase/auth/setCustomClaims.d.ts +12 -4
  89. package/lib/supabase/baseFunction.d.ts +2 -2
  90. package/lib/supabase/billing/cancelSubscription.d.ts +1 -1
  91. package/lib/supabase/billing/changePlan.d.ts +2 -2
  92. package/lib/supabase/billing/createCheckoutSession.d.ts +1 -1
  93. package/lib/supabase/billing/createCustomerPortal.d.ts +1 -1
  94. package/lib/supabase/billing/refreshSubscriptionStatus.d.ts +1 -1
  95. package/lib/supabase/crud/aggregate.d.ts +2 -1
  96. package/lib/supabase/crud/create.d.ts +2 -1
  97. package/lib/supabase/crud/delete.d.ts +1 -0
  98. package/lib/supabase/crud/get.d.ts +2 -1
  99. package/lib/supabase/crud/index.d.ts +1 -1
  100. package/lib/supabase/crud/list.d.ts +2 -1
  101. package/lib/supabase/crud/update.d.ts +2 -1
  102. package/lib/supabase/edgeFunction.d.ts +56 -0
  103. package/lib/supabase/email/createEmailFunction.d.ts +31 -0
  104. package/lib/supabase/helpers/authProvider.d.ts +2 -2
  105. package/lib/supabase/index.d.ts +11 -2
  106. package/lib/supabase/index.js +3 -2
  107. package/lib/supabase/index.js.map +4 -4
  108. package/lib/supabase/oauth/disconnect.d.ts +13 -0
  109. package/lib/supabase/oauth/exchangeToken.d.ts +13 -0
  110. package/lib/supabase/oauth/getConnections.d.ts +13 -0
  111. package/lib/supabase/oauth/index.d.ts +12 -0
  112. package/lib/supabase/oauth/refreshToken.d.ts +13 -0
  113. package/lib/supabase/utils/idempotency.d.ts +1 -1
  114. package/lib/supabase/utils/monitoring.d.ts +1 -1
  115. package/lib/supabase/utils/rateLimiter.d.ts +1 -1
  116. package/lib/vercel/api/ai/chat.d.ts +29 -0
  117. package/lib/vercel/api/ai/index.d.ts +1 -0
  118. package/lib/vercel/api/auth/index.d.ts +1 -1
  119. package/lib/vercel/api/billing/cancel.d.ts +1 -1
  120. package/lib/vercel/api/billing/change-plan.d.ts +1 -1
  121. package/lib/vercel/api/billing/create-checkout-session.d.ts +1 -1
  122. package/lib/vercel/api/billing/index.d.ts +1 -1
  123. package/lib/vercel/api/billing/refresh-subscription-status.d.ts +1 -1
  124. package/lib/vercel/api/billing/webhook-handler.d.ts +2 -2
  125. package/lib/vercel/api/config/constants.d.ts +9 -9
  126. package/lib/vercel/api/config/firebase-admin.d.ts +2 -2
  127. package/lib/vercel/api/config/index.d.ts +1 -1
  128. package/lib/vercel/api/crud/index.d.ts +1 -1
  129. package/lib/vercel/api/index.d.ts +2 -1
  130. package/lib/vercel/api/index.js +3 -2
  131. package/lib/vercel/api/index.js.map +4 -4
  132. package/lib/vercel/api/oauth/check-github-access.d.ts +1 -1
  133. package/lib/vercel/api/oauth/grant-github-access.d.ts +1 -1
  134. package/lib/vercel/api/oauth/index.d.ts +1 -1
  135. package/lib/vercel/api/oauth/revoke-github-access.d.ts +1 -1
  136. package/lib/vercel/api/utils/cors.d.ts +4 -4
  137. package/lib/vercel/baseFunction.d.ts +2 -2
  138. package/package.json +38 -5
  139. package/src/firebase/auth/getCustomClaims.ts +3 -3
  140. package/src/firebase/auth/getUserAuthStatus.ts +3 -3
  141. package/src/firebase/auth/index.ts +1 -1
  142. package/src/firebase/auth/removeCustomClaims.ts +3 -3
  143. package/src/firebase/auth/setCustomClaims.ts +70 -69
  144. package/src/firebase/baseFunction.ts +2 -2
  145. package/src/firebase/billing/cancelSubscription.ts +3 -3
  146. package/src/firebase/billing/changePlan.ts +3 -3
  147. package/src/firebase/billing/createCheckoutSession.ts +79 -187
  148. package/src/firebase/billing/createCustomerPortal.ts +1 -1
  149. package/src/firebase/billing/healthCheck.ts +1 -1
  150. package/src/firebase/billing/index.d.ts +11 -11
  151. package/src/firebase/billing/index.ts +1 -1
  152. package/src/firebase/billing/refreshSubscriptionStatus.ts +3 -3
  153. package/src/firebase/billing/webhookHandler.ts +1 -1
  154. package/src/firebase/config/constants.ts +4 -4
  155. package/src/firebase/config/index.ts +1 -1
  156. package/src/firebase/config/secrets.ts +1 -1
  157. package/src/firebase/crud/aggregate.ts +2 -2
  158. package/src/firebase/crud/create.ts +2 -2
  159. package/src/firebase/crud/delete.ts +3 -3
  160. package/src/firebase/crud/get.ts +1 -1
  161. package/src/firebase/crud/index.ts +1 -1
  162. package/src/firebase/crud/list.ts +1 -1
  163. package/src/firebase/crud/update.ts +2 -2
  164. package/src/firebase/helpers/githubAccessHelper.ts +4 -4
  165. package/src/firebase/helpers/githubTeamAccessHelper.ts +3 -3
  166. package/src/firebase/helpers/index.ts +1 -1
  167. package/src/firebase/index.d.ts +9 -9
  168. package/src/firebase/index.ts +1 -1
  169. package/src/firebase/oauth/disconnect.ts +2 -2
  170. package/src/firebase/oauth/exchangeToken.ts +6 -6
  171. package/src/firebase/oauth/getConnections.ts +2 -2
  172. package/src/firebase/oauth/githubAccess.ts +10 -10
  173. package/src/firebase/oauth/index.ts +1 -1
  174. package/src/firebase/oauth/refreshToken.ts +6 -6
  175. package/src/firebase/registerCrudFunctions.ts +1 -1
  176. package/src/firebase/scheduled/checkExpiredSubscriptions.ts +1 -1
  177. package/src/firebase/scheduled/index.ts +1 -1
  178. package/src/shared/__tests__/auth.test.ts +46 -0
  179. package/src/shared/__tests__/errorHandling.test.ts +66 -1
  180. package/src/shared/__tests__/firebase.test.ts +293 -0
  181. package/src/shared/__tests__/internalValidation.test.ts +190 -0
  182. package/src/shared/__tests__/metadata.test.ts +66 -0
  183. package/src/shared/__tests__/schema.test.ts +219 -0
  184. package/src/shared/__tests__/schemaValidation.test.ts +72 -0
  185. package/src/shared/__tests__/subscription.test.ts +45 -0
  186. package/src/shared/__tests__/utils.test.ts +281 -0
  187. package/src/shared/__tests__/validation-env.test.ts +73 -0
  188. package/src/shared/ai/__tests__/costTracker.test.ts +121 -0
  189. package/src/shared/ai/classifyAIError.ts +163 -0
  190. package/src/shared/ai/costTracker.ts +51 -0
  191. package/src/shared/ai/createAIRoute.ts +397 -0
  192. package/src/shared/ai/index.ts +8 -0
  193. package/src/shared/ai/resolveModelTier.ts +58 -0
  194. package/src/shared/billing/__tests__/createCheckout.test.ts +1 -1
  195. package/src/shared/billing/__tests__/webhookHandler.test.ts +1 -1
  196. package/src/shared/billing/createCheckout.ts +156 -11
  197. package/src/shared/billing/helpers/index.ts +1 -1
  198. package/src/shared/billing/helpers/subscriptionManagement.ts +13 -4
  199. package/src/shared/billing/helpers/updateUserSubscription.ts +4 -4
  200. package/src/shared/billing/idempotency.ts +9 -4
  201. package/src/shared/billing/index.ts +1 -1
  202. package/src/shared/billing/webhookHandler.ts +7 -7
  203. package/src/shared/email/createEmailRoute.ts +81 -0
  204. package/src/shared/email/index.ts +5 -0
  205. package/src/shared/email/provider.ts +31 -0
  206. package/src/shared/email/resendProvider.ts +56 -0
  207. package/src/shared/errorHandling.ts +12 -6
  208. package/src/shared/firebase.ts +7 -7
  209. package/src/shared/github.ts +49 -11
  210. package/src/shared/index.d.ts +9 -9
  211. package/src/shared/index.ts +3 -1
  212. package/src/shared/logger.ts +10 -8
  213. package/src/shared/metadata.ts +3 -3
  214. package/src/shared/oauth/__tests__/exchangeToken.test.ts +1 -1
  215. package/src/shared/oauth/exchangeToken.ts +3 -2
  216. package/src/shared/oauth/grantAccess.ts +3 -2
  217. package/src/shared/oauth/index.ts +1 -1
  218. package/src/shared/schema.ts +4 -4
  219. package/src/shared/utils/__tests__/functionWrapper.test.ts +1 -1
  220. package/src/shared/utils/detectFirestore.ts +3 -3
  221. package/src/shared/utils/external/date.ts +5 -5
  222. package/src/shared/utils/external/index.ts +1 -1
  223. package/src/shared/utils/external/references.ts +2 -2
  224. package/src/shared/utils/external/subscription.ts +5 -5
  225. package/src/shared/utils/firebaseHelpers.ts +3 -3
  226. package/src/shared/utils/functionWrapper.ts +4 -4
  227. package/src/shared/utils/index.ts +1 -1
  228. package/src/shared/utils/internal/auth.ts +7 -7
  229. package/src/shared/utils/internal/firebase.ts +1 -1
  230. package/src/shared/utils/internal/idempotency.ts +4 -3
  231. package/src/shared/utils/internal/index.ts +1 -1
  232. package/src/shared/utils/internal/monitoring.ts +8 -8
  233. package/src/shared/utils/internal/rateLimiter.ts +12 -9
  234. package/src/shared/utils/internal/validation.ts +5 -5
  235. package/src/shared/utils/schemaValidation.ts +6 -6
  236. package/src/shared/utils/validation.ts +10 -10
  237. package/src/shared/utils/vercelHelpers.ts +3 -3
  238. package/src/shared/utils.ts +19 -19
  239. package/src/shared/validation.ts +3 -3
  240. package/src/supabase/ai/createAIFunction.ts +75 -0
  241. package/src/supabase/auth/deleteAccount.ts +2 -2
  242. package/src/supabase/auth/getCustomClaims.ts +2 -2
  243. package/src/supabase/auth/getUserAuthStatus.ts +2 -2
  244. package/src/supabase/auth/removeCustomClaims.ts +38 -2
  245. package/src/supabase/auth/setCustomClaims.ts +66 -5
  246. package/src/supabase/baseFunction.ts +29 -5
  247. package/src/supabase/billing/cancelSubscription.ts +2 -2
  248. package/src/supabase/billing/changePlan.ts +8 -3
  249. package/src/supabase/billing/createCheckoutSession.ts +18 -4
  250. package/src/supabase/billing/createCustomerPortal.ts +2 -2
  251. package/src/supabase/billing/refreshSubscriptionStatus.ts +2 -2
  252. package/src/supabase/crud/aggregate.ts +2 -1
  253. package/src/supabase/crud/create.ts +2 -1
  254. package/src/supabase/crud/delete.ts +2 -1
  255. package/src/supabase/crud/get.ts +2 -1
  256. package/src/supabase/crud/index.ts +1 -1
  257. package/src/supabase/crud/list.ts +2 -1
  258. package/src/supabase/crud/update.ts +2 -1
  259. package/src/supabase/edgeFunction.ts +195 -0
  260. package/src/supabase/email/createEmailFunction.ts +75 -0
  261. package/src/supabase/helpers/authProvider.ts +2 -2
  262. package/src/supabase/index.ts +22 -2
  263. package/src/supabase/oauth/disconnect.ts +104 -0
  264. package/src/supabase/oauth/exchangeToken.ts +183 -0
  265. package/src/supabase/oauth/getConnections.ts +85 -0
  266. package/src/supabase/oauth/index.ts +15 -0
  267. package/src/supabase/oauth/refreshToken.ts +130 -0
  268. package/src/supabase/registerCrudFunctions.ts +30 -42
  269. package/src/supabase/utils/idempotency.ts +7 -3
  270. package/src/supabase/utils/monitoring.ts +1 -1
  271. package/src/supabase/utils/rateLimiter.ts +1 -1
  272. package/src/vercel/api/ai/chat.ts +77 -0
  273. package/src/vercel/api/ai/index.ts +1 -0
  274. package/src/vercel/api/auth/get-custom-claims.ts +1 -1
  275. package/src/vercel/api/auth/get-user-auth-status.ts +1 -1
  276. package/src/vercel/api/auth/index.ts +1 -1
  277. package/src/vercel/api/auth/remove-custom-claims.ts +1 -1
  278. package/src/vercel/api/auth/set-custom-claims.ts +2 -4
  279. package/src/vercel/api/billing/cancel.ts +3 -3
  280. package/src/vercel/api/billing/change-plan.ts +3 -3
  281. package/src/vercel/api/billing/create-checkout-session.ts +30 -7
  282. package/src/vercel/api/billing/customer-portal.ts +1 -1
  283. package/src/vercel/api/billing/index.ts +1 -1
  284. package/src/vercel/api/billing/refresh-subscription-status.ts +1 -1
  285. package/src/vercel/api/billing/webhook-handler.ts +11 -4
  286. package/src/vercel/api/config/constants.ts +9 -9
  287. package/src/vercel/api/config/firebase-admin.ts +3 -3
  288. package/src/vercel/api/config/index.ts +1 -1
  289. package/src/vercel/api/crud/create.ts +1 -1
  290. package/src/vercel/api/crud/delete.ts +1 -1
  291. package/src/vercel/api/crud/get.ts +1 -1
  292. package/src/vercel/api/crud/index.ts +1 -1
  293. package/src/vercel/api/crud/list.ts +1 -1
  294. package/src/vercel/api/crud/update.ts +1 -1
  295. package/src/vercel/api/index.d.ts +1 -1
  296. package/src/vercel/api/index.ts +2 -1
  297. package/src/vercel/api/oauth/check-github-access.ts +3 -3
  298. package/src/vercel/api/oauth/exchange-token.ts +25 -2
  299. package/src/vercel/api/oauth/grant-github-access.ts +3 -3
  300. package/src/vercel/api/oauth/index.ts +1 -1
  301. package/src/vercel/api/oauth/revoke-github-access.ts +1 -1
  302. package/src/vercel/api/utils/cors.ts +10 -4
  303. package/src/vercel/baseFunction.ts +2 -2
@@ -4,7 +4,7 @@
4
4
  * @fileoverview Create Checkout Session Algorithm
5
5
  * @description Platform-agnostic algorithm for creating Stripe checkout sessions
6
6
  *
7
- * @version 0.0.1
7
+ * @version 0.1.0
8
8
  * @since 0.0.1
9
9
  * @author AMBROISE PARK Consulting
10
10
  */
@@ -18,13 +18,19 @@ import type {
18
18
  /**
19
19
  * Provider interface for Stripe checkout operations
20
20
  *
21
- * @version 0.0.1
21
+ * @version 0.1.0
22
22
  * @since 0.0.1
23
23
  * @author AMBROISE PARK Consulting
24
24
  */
25
25
  export interface StripeCheckoutProvider {
26
26
  createCheckoutSession(params: {
27
- priceId: string;
27
+ priceId?: string;
28
+ /** Amount in cents (dynamic pricing mode) */
29
+ unitAmount?: number;
30
+ /** Product name for Stripe checkout (dynamic pricing mode) */
31
+ productName?: string;
32
+ /** Currency code, defaults to 'eur' */
33
+ currency?: string;
28
34
  customerEmail?: string;
29
35
  metadata: Record<string, string>;
30
36
  allowPromotionCodes: boolean;
@@ -40,7 +46,7 @@ export interface StripeCheckoutProvider {
40
46
  /**
41
47
  * Provider interface for authentication operations
42
48
  *
43
- * @version 0.0.1
49
+ * @version 0.1.0
44
50
  * @since 0.0.1
45
51
  * @author AMBROISE PARK Consulting
46
52
  */
@@ -50,10 +56,64 @@ export interface AuthCheckoutProvider {
50
56
  }>;
51
57
  }
52
58
 
59
+ /**
60
+ * Validate URL has http/https protocol.
61
+ * Platform-agnostic (no firebase logger dependency).
62
+ */
63
+ function validateCheckoutUrl(url: string, name: string): void {
64
+ try {
65
+ const parsed = new URL(url);
66
+ if (!['http:', 'https:'].includes(parsed.protocol)) {
67
+ throw new Error(`Invalid protocol: ${parsed.protocol}`);
68
+ }
69
+ } catch (error) {
70
+ throw new Error(
71
+ `Invalid ${name} URL: ${url}. ${error instanceof Error ? error.message : 'Invalid URL format'}`
72
+ );
73
+ }
74
+ }
75
+
76
+ /**
77
+ * Sanitize metadata: enforce string values, strip script injection, cap lengths.
78
+ * Platform-agnostic (no firebase logger dependency).
79
+ */
80
+ function sanitizeMetadata(
81
+ metadata: Record<string, any>
82
+ ): Record<string, string> {
83
+ const sanitized: Record<string, string> = {};
84
+
85
+ for (const [key, value] of Object.entries(metadata)) {
86
+ if (typeof value !== 'string') {
87
+ throw new Error(
88
+ `Metadata value for key '${key}' must be a string, got ${typeof value}`
89
+ );
90
+ }
91
+
92
+ const sanitizedValue = value
93
+ .replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, '')
94
+ .replace(/javascript:/gi, '')
95
+ .replace(/on\w+\s*=/gi, '');
96
+
97
+ if (sanitizedValue.length > 1000) {
98
+ throw new Error(
99
+ `Metadata value for key '${key}' is too long (max 1000 characters)`
100
+ );
101
+ }
102
+
103
+ if (key.length > 100) {
104
+ throw new Error(`Metadata key '${key}' is too long (max 100 characters)`);
105
+ }
106
+
107
+ sanitized[key] = sanitizedValue;
108
+ }
109
+
110
+ return sanitized;
111
+ }
112
+
53
113
  /**
54
114
  * Create checkout session algorithm
55
115
  *
56
- * @version 0.0.1
116
+ * @version 0.2.0
57
117
  * @since 0.0.1
58
118
  * @author AMBROISE PARK Consulting
59
119
  */
@@ -63,8 +123,15 @@ export async function createCheckoutAlgorithm(
63
123
  authProvider: AuthCheckoutProvider,
64
124
  billingConfig: StripeBackConfig
65
125
  ): Promise<CreateCheckoutSessionResponse> {
126
+ if (!process.env.FRONTEND_URL) {
127
+ throw new Error('FRONTEND_URL environment variable is required');
128
+ }
129
+
66
130
  const {
67
131
  priceId,
132
+ unitAmount,
133
+ productName,
134
+ currency,
68
135
  userId,
69
136
  customerEmail,
70
137
  metadata = {},
@@ -86,9 +153,41 @@ export async function createCheckoutAlgorithm(
86
153
  throw new Error(`Invalid billing config key: ${configKey}`);
87
154
  }
88
155
 
89
- // ✅ VALIDATE: priceId matches config
90
- if (billingItem.priceId !== priceId) {
91
- throw new Error('Price ID mismatch with configuration');
156
+ // ✅ VALIDATE: either priceId or (unitAmount + productName)
157
+ const useDynamicPricing = !priceId && unitAmount && productName;
158
+ if (!priceId && !useDynamicPricing) {
159
+ throw new Error(
160
+ 'Either priceId or (unitAmount + productName) is required'
161
+ );
162
+ }
163
+
164
+ // ✅ VALIDATE: price_data not supported for subscriptions
165
+ if (useDynamicPricing && mode === 'subscription') {
166
+ throw new Error(
167
+ 'Dynamic pricing (unitAmount) is not supported for subscriptions. Use a Stripe priceId.'
168
+ );
169
+ }
170
+
171
+ if (priceId) {
172
+ // Fixed pricing: validate priceId matches config (if config has one)
173
+ if (billingItem.priceId && billingItem.priceId !== priceId) {
174
+ throw new Error('Price ID mismatch with configuration');
175
+ }
176
+ } else {
177
+ // Dynamic pricing: maxUnitAmount is required as a security cap
178
+ if (!billingItem.maxUnitAmount) {
179
+ throw new Error(
180
+ 'Dynamic pricing requires maxUnitAmount in billing config for security'
181
+ );
182
+ }
183
+ if (unitAmount! > billingItem.maxUnitAmount) {
184
+ throw new Error(
185
+ `Unit amount ${unitAmount} exceeds maximum allowed: ${billingItem.maxUnitAmount}`
186
+ );
187
+ }
188
+ if (unitAmount! < 100) {
189
+ throw new Error('Unit amount must be at least 100 cents (1.00)');
190
+ }
92
191
  }
93
192
 
94
193
  // ✅ VALIDATE: userId exists
@@ -99,18 +198,64 @@ export async function createCheckoutAlgorithm(
99
198
  // Verify user exists
100
199
  await authProvider.getUser(userId);
101
200
 
201
+ // ✅ HOOK: beforeCheckout (ownership check, status validation, server-resolved pricing)
202
+ let finalUnitAmount = unitAmount;
203
+ let finalProductName = productName;
204
+
205
+ if (billingItem.beforeCheckout) {
206
+ const hookResult = await billingItem.beforeCheckout(
207
+ userId,
208
+ { priceId, unitAmount, productName, currency, mode, metadata, allowPromotionCodes },
209
+ sanitizeMetadata(metadata)
210
+ );
211
+
212
+ if (!hookResult.allowed) {
213
+ throw new Error(hookResult.reason || 'Checkout blocked by beforeCheckout hook');
214
+ }
215
+
216
+ if (hookResult.overrides) {
217
+ if (hookResult.overrides.unitAmount !== undefined) {
218
+ finalUnitAmount = hookResult.overrides.unitAmount;
219
+ }
220
+ if (hookResult.overrides.productName !== undefined) {
221
+ finalProductName = hookResult.overrides.productName;
222
+ }
223
+ }
224
+ }
225
+
226
+ const finalUseDynamicPricing = !priceId && finalUnitAmount && finalProductName;
227
+
228
+ // ✅ VALIDATE: overridden amount still respects security cap
229
+ if (finalUseDynamicPricing && billingItem.maxUnitAmount && finalUnitAmount! > billingItem.maxUnitAmount) {
230
+ throw new Error(
231
+ `Hook-overridden unit amount ${finalUnitAmount} exceeds maximum allowed: ${billingItem.maxUnitAmount}`
232
+ );
233
+ }
234
+
235
+ // ✅ VALIDATE: URLs are valid http/https
236
+ const resolvedSuccessUrl = successUrl || `${process.env.FRONTEND_URL}/billing/success`;
237
+ const resolvedCancelUrl = cancelUrl || `${process.env.FRONTEND_URL}/billing/cancel`;
238
+ validateCheckoutUrl(resolvedSuccessUrl, 'success');
239
+ validateCheckoutUrl(resolvedCancelUrl, 'cancel');
240
+
241
+ // ✅ SANITIZE: metadata values (strip scripts, cap lengths)
242
+ const sanitizedMetadata = sanitizeMetadata(metadata);
243
+
102
244
  // Create checkout session
103
245
  const session = await stripeProvider.createCheckoutSession({
104
246
  priceId,
247
+ unitAmount: finalUseDynamicPricing ? finalUnitAmount : undefined,
248
+ productName: finalUseDynamicPricing ? finalProductName : undefined,
249
+ currency: currency || billingItem.currency || 'eur',
105
250
  customerEmail,
106
251
  metadata: {
107
- ...metadata,
252
+ ...sanitizedMetadata,
108
253
  userId,
109
254
  billingConfigKey: configKey as string, // ✅ Server values AFTER spread — cannot be overwritten by client
110
255
  },
111
256
  allowPromotionCodes,
112
- successUrl: successUrl || `${process.env.FRONTEND_URL}/billing/success`,
113
- cancelUrl: cancelUrl || `${process.env.FRONTEND_URL}/billing/cancel`,
257
+ successUrl: resolvedSuccessUrl,
258
+ cancelUrl: resolvedCancelUrl,
114
259
  mode,
115
260
  });
116
261
 
@@ -4,7 +4,7 @@
4
4
  * @fileoverview Billing helpers barrel exports
5
5
  * @description Centralized exports for billing helper functions
6
6
  *
7
- * @version 0.0.1
7
+ * @version 0.1.0
8
8
  * @since 0.0.1
9
9
  * @author AMBROISE PARK Consulting
10
10
  */
@@ -4,7 +4,7 @@
4
4
  * @fileoverview Shared Subscription Management Logic
5
5
  * @description Platform-agnostic subscription management functions
6
6
  *
7
- * @version 0.0.1
7
+ * @version 0.1.0
8
8
  * @since 0.0.1
9
9
  * @author AMBROISE PARK Consulting
10
10
  */
@@ -23,7 +23,7 @@ import type Stripe from 'stripe';
23
23
  /**
24
24
  * Cancel user subscription at period end
25
25
  *
26
- * @version 0.0.1
26
+ * @version 0.1.0
27
27
  * @since 0.0.1
28
28
  * @author AMBROISE PARK Consulting
29
29
  */
@@ -92,7 +92,7 @@ export async function cancelUserSubscription(
92
92
  /**
93
93
  * Change user subscription plan
94
94
  *
95
- * @version 0.0.1
95
+ * @version 0.1.0
96
96
  * @since 0.0.1
97
97
  * @author AMBROISE PARK Consulting
98
98
  */
@@ -185,7 +185,7 @@ export async function changeUserPlan(
185
185
  /**
186
186
  * Create Stripe Customer Portal session
187
187
  *
188
- * @version 0.0.1
188
+ * @version 0.1.0
189
189
  * @since 0.0.1
190
190
  * @author AMBROISE PARK Consulting
191
191
  */
@@ -208,6 +208,15 @@ export async function createCustomerPortalSession(
208
208
  throw handleError(new Error('No customer found'));
209
209
  }
210
210
 
211
+ // Validate returnUrl domain
212
+ if (returnUrl) {
213
+ const parsed = new URL(returnUrl);
214
+ const frontendUrl = new URL(process.env.FRONTEND_URL || '');
215
+ if (parsed.origin !== frontendUrl.origin) {
216
+ throw new Error('Invalid return URL: must match frontend domain');
217
+ }
218
+ }
219
+
211
220
  // Create portal session
212
221
  const session = await stripe.billingPortal.sessions.create({
213
222
  customer: customerId,
@@ -4,7 +4,7 @@
4
4
  * @fileoverview User subscription update utilities
5
5
  * @description Functions for updating user subscription data
6
6
  *
7
- * @version 0.0.1
7
+ * @version 0.1.0
8
8
  * @since 0.0.1
9
9
  * @author AMBROISE PARK Consulting
10
10
  */
@@ -14,7 +14,7 @@
14
14
  /**
15
15
  * Subscription data structure
16
16
  *
17
- * @version 0.0.1
17
+ * @version 0.1.0
18
18
  * @since 0.0.1
19
19
  * @author AMBROISE PARK Consulting
20
20
  */
@@ -30,7 +30,7 @@ export interface SubscriptionData {
30
30
  /**
31
31
  * Platform-agnostic auth provider interface
32
32
  *
33
- * @version 0.0.1
33
+ * @version 0.1.0
34
34
  * @since 0.0.1
35
35
  * @author AMBROISE PARK Consulting
36
36
  */
@@ -48,7 +48,7 @@ export interface AuthProvider {
48
48
  * Platform-agnostic subscription update using dependency injection
49
49
  * Works on Firebase Functions, Vercel, AWS Lambda, etc.
50
50
  *
51
- * @version 0.0.1
51
+ * @version 0.1.0
52
52
  * @since 0.0.1
53
53
  * @author AMBROISE PARK Consulting
54
54
  */
@@ -4,7 +4,7 @@
4
4
  * @fileoverview Adaptive Idempotency for Billing Webhooks
5
5
  * @description Auto-detects Firestore, gracefully degrades to in-memory
6
6
  *
7
- * @version 0.0.1
7
+ * @version 0.1.0
8
8
  * @since 0.0.1
9
9
  * @author AMBROISE PARK Consulting
10
10
  */
@@ -15,7 +15,7 @@ import { isFirestoreConfigured } from '../utils/detectFirestore.js';
15
15
  /**
16
16
  * Idempotency store interface
17
17
  *
18
- * @version 0.0.1
18
+ * @version 0.1.0
19
19
  * @since 0.0.1
20
20
  * @author AMBROISE PARK Consulting
21
21
  */
@@ -57,6 +57,11 @@ class InMemoryIdempotency implements IdempotencyStore {
57
57
  }
58
58
  }
59
59
 
60
+ /**
61
+ * @limitation Not truly atomic for concurrent async operations within the same event loop tick.
62
+ * Two webhook retries arriving simultaneously could both pass the check.
63
+ * For production billing, use the Firestore/Supabase implementations which provide true atomicity.
64
+ */
60
65
  async checkAndReserve(eventId: string): Promise<boolean> {
61
66
  if (this.store.has(eventId)) return true;
62
67
  this.store.add(eventId);
@@ -172,7 +177,7 @@ class FirestoreIdempotency implements IdempotencyStore {
172
177
  *
173
178
  * Falls back to in-memory if Firestore not available
174
179
  *
175
- * @version 0.0.1
180
+ * @version 0.1.0
176
181
  * @since 0.0.1
177
182
  * @author AMBROISE PARK Consulting
178
183
  */
@@ -196,7 +201,7 @@ export function createIdempotencyStore(): IdempotencyStore {
196
201
  /**
197
202
  * Reset cached store (for testing only)
198
203
  *
199
- * @version 0.0.1
204
+ * @version 0.1.0
200
205
  * @since 0.0.1
201
206
  * @author AMBROISE PARK Consulting
202
207
  */
@@ -4,7 +4,7 @@
4
4
  * @fileoverview Billing utilities barrel exports
5
5
  * @description Centralized exports for billing-related functions
6
6
  *
7
- * @version 0.0.1
7
+ * @version 0.1.0
8
8
  * @since 0.0.1
9
9
  * @author AMBROISE PARK Consulting
10
10
  */
@@ -4,7 +4,7 @@
4
4
  * @fileoverview Stripe webhook handler
5
5
  * @description Handles Stripe webhook events for subscription management
6
6
  *
7
- * @version 0.0.1
7
+ * @version 0.1.0
8
8
  * @since 0.0.1
9
9
  * @author AMBROISE PARK Consulting
10
10
  */
@@ -70,7 +70,7 @@ export type UpdateSubscriptionFn = (
70
70
  * @param billingConfig - Billing configuration
71
71
  * @param updateSubscription - Function to update user subscription
72
72
  *
73
- * @version 0.0.1
73
+ * @version 0.1.0
74
74
  * @since 0.0.1
75
75
  * @author AMBROISE PARK Consulting
76
76
  */
@@ -130,7 +130,7 @@ export async function processWebhook(
130
130
  /**
131
131
  * Route events to appropriate handlers
132
132
  *
133
- * @version 0.0.1
133
+ * @version 0.1.0
134
134
  * @since 0.0.1
135
135
  * @author AMBROISE PARK Consulting
136
136
  */
@@ -183,7 +183,7 @@ async function routeEvent(
183
183
  /**
184
184
  * Handle checkout completed with graceful hook execution
185
185
  *
186
- * @version 0.0.1
186
+ * @version 0.1.0
187
187
  * @since 0.0.1
188
188
  * @author AMBROISE PARK Consulting
189
189
  */
@@ -297,7 +297,7 @@ async function handleCheckoutCompleted(
297
297
  /**
298
298
  * Handle subscription renewal
299
299
  *
300
- * @version 0.0.1
300
+ * @version 0.1.0
301
301
  * @since 0.0.1
302
302
  * @author AMBROISE PARK Consulting
303
303
  */
@@ -378,7 +378,7 @@ async function handleInvoicePaymentSucceeded(
378
378
  /**
379
379
  * Handle subscription cancellation
380
380
  *
381
- * @version 0.0.1
381
+ * @version 0.1.0
382
382
  * @since 0.0.1
383
383
  * @author AMBROISE PARK Consulting
384
384
  */
@@ -443,7 +443,7 @@ async function handleSubscriptionDeleted(
443
443
  /**
444
444
  * Handle payment failure
445
445
  *
446
- * @version 0.0.1
446
+ * @version 0.1.0
447
447
  * @since 0.0.1
448
448
  * @author AMBROISE PARK Consulting
449
449
  */
@@ -0,0 +1,81 @@
1
+ // packages/functions/src/shared/email/createEmailRoute.ts
2
+
3
+ /**
4
+ * @fileoverview Email Route Handler
5
+ * @description Platform-agnostic handler for email send requests.
6
+ * Validates request, resolves template, renders with locale, sends via provider.
7
+ *
8
+ * @version 0.1.0
9
+ * @since 0.1.0
10
+ * @author AMBROISE PARK Consulting
11
+ */
12
+
13
+ import type {
14
+ EmailRouteConfig,
15
+ SendEmailRequest,
16
+ SendEmailResponse,
17
+ } from '@donotdev/core/server';
18
+ import { validateSendEmailRequest } from '@donotdev/core/server';
19
+
20
+ import type { EmailProviderAdapter } from './provider.js';
21
+
22
+ /**
23
+ * Handle an email send request.
24
+ * Validates input, resolves the template from the registry, renders with locale, and sends.
25
+ *
26
+ * @param request - Email send request (templateId, to, data, locale)
27
+ * @param config - Email route configuration (provider, templates, defaultFrom)
28
+ * @param provider - Email provider adapter (Resend, etc.)
29
+ * @returns Send result with success status and messageId
30
+ *
31
+ * @example
32
+ * ```typescript
33
+ * const result = await handleEmailRequest(
34
+ * { templateId: 'order-confirmation', to: 'user@example.com', data: { orderId: '123' }, locale: 'fr' },
35
+ * emailConfig,
36
+ * resendProvider
37
+ * );
38
+ * ```
39
+ */
40
+ export async function handleEmailRequest(
41
+ request: SendEmailRequest,
42
+ config: EmailRouteConfig,
43
+ provider: EmailProviderAdapter
44
+ ): Promise<SendEmailResponse> {
45
+ // Validate request
46
+ const validation = validateSendEmailRequest(request);
47
+ if (!validation.success) {
48
+ return {
49
+ success: false,
50
+ error: `Invalid email request: ${validation.issues?.map((i) => i.message).join(', ')}`,
51
+ };
52
+ }
53
+
54
+ // Resolve template
55
+ const template = config.templates[request.templateId];
56
+ if (!template) {
57
+ return {
58
+ success: false,
59
+ error: `Template not found: ${request.templateId}`,
60
+ };
61
+ }
62
+
63
+ // Render template with locale
64
+ const locale = request.locale || 'fr';
65
+ const subject = template.subject(request.data as any, locale);
66
+ const html = template.html(request.data as any, locale);
67
+
68
+ // Send via provider
69
+ const result = await provider.send({
70
+ from: request.from || config.defaultFrom,
71
+ to: request.to,
72
+ subject,
73
+ html,
74
+ replyTo: request.replyTo || config.replyTo,
75
+ });
76
+
77
+ return {
78
+ success: true,
79
+ messageId: result.messageId,
80
+ };
81
+ }
@@ -0,0 +1,5 @@
1
+ // packages/functions/src/shared/email/index.ts
2
+
3
+ export { handleEmailRequest } from './createEmailRoute.js';
4
+ export type { EmailProviderAdapter } from './provider.js';
5
+ export { createResendProvider } from './resendProvider.js';
@@ -0,0 +1,31 @@
1
+ // packages/functions/src/shared/email/provider.ts
2
+
3
+ /**
4
+ * @fileoverview Email Provider Adapter Interface
5
+ * @description Abstract interface for email sending. Providers implement this.
6
+ *
7
+ * @version 0.1.0
8
+ * @since 0.1.0
9
+ * @author AMBROISE PARK Consulting
10
+ */
11
+
12
+ /**
13
+ * Email provider adapter interface.
14
+ * Each provider (Resend, SES, etc.) implements this single method.
15
+ */
16
+ export interface EmailProviderAdapter {
17
+ /**
18
+ * Send an email via the provider.
19
+ *
20
+ * @param params - Email parameters
21
+ * @returns Provider message ID for tracking
22
+ * @throws On provider error (network, auth, etc.)
23
+ */
24
+ send(params: {
25
+ from: string;
26
+ to: string;
27
+ subject: string;
28
+ html: string;
29
+ replyTo?: string;
30
+ }): Promise<{ messageId: string }>;
31
+ }
@@ -0,0 +1,56 @@
1
+ // packages/functions/src/shared/email/resendProvider.ts
2
+
3
+ /**
4
+ * @fileoverview Resend Email Provider
5
+ * @description Zero-dependency Resend implementation using raw fetch.
6
+ *
7
+ * @version 0.1.0
8
+ * @since 0.1.0
9
+ * @author AMBROISE PARK Consulting
10
+ */
11
+
12
+ import type { EmailProviderAdapter } from './provider.js';
13
+
14
+ const RESEND_API_URL = 'https://api.resend.com/emails';
15
+
16
+ /**
17
+ * Create a Resend email provider adapter.
18
+ *
19
+ * @param apiKey - Resend API key
20
+ * @returns EmailProviderAdapter implementation
21
+ *
22
+ * @example
23
+ * ```typescript
24
+ * const provider = createResendProvider(Deno.env.get('RESEND_API_KEY')!);
25
+ * await provider.send({ from: 'noreply@app.com', to: 'user@example.com', subject: 'Hello', html: '<p>Hi</p>' });
26
+ * ```
27
+ */
28
+ export function createResendProvider(apiKey: string): EmailProviderAdapter {
29
+ if (!apiKey) {
30
+ throw new Error('Resend API key is required');
31
+ }
32
+
33
+ return {
34
+ async send({ from, to, subject, html, replyTo }) {
35
+ const body: Record<string, string> = { from, to, subject, html };
36
+ if (replyTo) body.reply_to = replyTo;
37
+
38
+ const response = await fetch(RESEND_API_URL, {
39
+ method: 'POST',
40
+ headers: {
41
+ 'Authorization': `Bearer ${apiKey}`,
42
+ 'Content-Type': 'application/json',
43
+ },
44
+ body: JSON.stringify(body),
45
+ });
46
+
47
+ if (!response.ok) {
48
+ const errorText = await response.text().catch(() => 'Unknown error');
49
+ throw new Error(`Resend API error (${response.status}): ${errorText}`);
50
+ }
51
+
52
+ const result = await response.json();
53
+ return { messageId: result.id };
54
+ },
55
+ };
56
+ }
@@ -5,7 +5,7 @@
5
5
  * @description Platform-agnostic error classification. Always throws DoNotDevError.
6
6
  * Platform adapters (Firebase baseFunction, Vercel route handler) catch and convert.
7
7
  *
8
- * @version 0.0.2
8
+ * @version 0.1.0
9
9
  * @since 0.0.1
10
10
  * @author AMBROISE PARK Consulting
11
11
  */
@@ -23,7 +23,7 @@ export { DoNotDevError };
23
23
  * @param error - The error to handle
24
24
  * @throws DoNotDevError always
25
25
  *
26
- * @version 0.0.2
26
+ * @version 0.1.0
27
27
  * @since 0.0.1
28
28
  * @author AMBROISE PARK Consulting
29
29
  */
@@ -89,13 +89,19 @@ export function handleError(error: unknown): never {
89
89
  details = undefined;
90
90
  } else {
91
91
  code = 'internal';
92
- // W10: Never expose error.stack in details — it leaks internal file paths
93
- // and implementation details to clients. Log server-side only.
94
- message =
95
- error instanceof Error ? error.message : 'An unexpected error occurred';
92
+ // W10: Never expose error.message for internal errors — it may leak
93
+ // internal file paths, SQL queries, or implementation details to clients.
94
+ // Log server-side only; clients always get the generic message.
95
+ message = 'An unexpected error occurred';
96
96
  details = undefined;
97
97
  }
98
98
 
99
+ // For internal errors, always use the generic message regardless of source.
100
+ // Other error codes may carry safe, developer-authored messages.
101
+ if (code === 'internal') {
102
+ message = 'An unexpected error occurred';
103
+ }
104
+
99
105
  throw new DoNotDevError(
100
106
  message,
101
107
  code as any,