@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 Shared utilities for Firebase and Vercel functions
5
5
  * @description Common utilities that can be used by both Firebase and Vercel function implementations
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
  */
@@ -32,7 +32,7 @@ export { DoNotDevError };
32
32
  * Get Firestore instance using @donotdev/firebase/server
33
33
  * Provider handles initialization and caching
34
34
  *
35
- * @version 0.0.1
35
+ * @version 0.1.0
36
36
  * @since 0.0.1
37
37
  * @author AMBROISE PARK Consulting
38
38
  */
@@ -44,7 +44,7 @@ export function getFirestore() {
44
44
  * Get Auth instance using @donotdev/firebase/server
45
45
  * Provider handles initialization and caching
46
46
  *
47
- * @version 0.0.1
47
+ * @version 0.1.0
48
48
  * @since 0.0.1
49
49
  * @author AMBROISE PARK Consulting
50
50
  */
@@ -73,7 +73,7 @@ export function initStripe(apiKey: string) {
73
73
  /**
74
74
  * Get Stripe instance with lazy initialization
75
75
  *
76
- * @version 0.0.1
76
+ * @version 0.1.0
77
77
  * @since 0.0.1
78
78
  * @author AMBROISE PARK Consulting
79
79
  */
@@ -96,7 +96,7 @@ export function getStripe(): Stripe {
96
96
  /**
97
97
  * Lazy-initialized Stripe instance proxy
98
98
  *
99
- * @version 0.0.1
99
+ * @version 0.1.0
100
100
  * @since 0.0.1
101
101
  * @author AMBROISE PARK Consulting
102
102
  */
@@ -116,7 +116,7 @@ export const stripe = new Proxy({} as Stripe, {
116
116
  * @param auth - Firebase callable request auth context (object with `.uid`)
117
117
  * @returns The authenticated user's uid
118
118
  *
119
- * @version 0.0.3
119
+ * @version 0.1.0
120
120
  * @since 0.0.1
121
121
  * @author AMBROISE PARK Consulting
122
122
  */
@@ -140,7 +140,7 @@ export function assertAuthenticated(auth: any): string {
140
140
  * @param auth - Firebase auth context from callable function
141
141
  * @returns UserRole for visibility filtering
142
142
  *
143
- * @version 0.0.1
143
+ * @version 0.1.0
144
144
  * @since 0.0.1
145
145
  * @author AMBROISE PARK Consulting
146
146
  */
@@ -162,7 +162,7 @@ export function getUserRole(auth: any): UserRole {
162
162
  /**
163
163
  * Validates that required Stripe environment variables are set
164
164
  *
165
- * @version 0.0.1
165
+ * @version 0.1.0
166
166
  * @since 0.0.1
167
167
  * @author AMBROISE PARK Consulting
168
168
  */
@@ -177,7 +177,7 @@ export function validateStripeEnvironment(): void {
177
177
  /**
178
178
  * Creates a standardized success response
179
179
  *
180
- * @version 0.0.1
180
+ * @version 0.1.0
181
181
  * @since 0.0.1
182
182
  * @author AMBROISE PARK Consulting
183
183
  */
@@ -191,7 +191,7 @@ export function createSuccessResponse<T>(data: T): { success: true; data: T } {
191
191
  /**
192
192
  * Creates a standardized error response
193
193
  *
194
- * @version 0.0.1
194
+ * @version 0.1.0
195
195
  * @since 0.0.1
196
196
  * @author AMBROISE PARK Consulting
197
197
  */
@@ -251,7 +251,7 @@ export function createErrorResponse(error: unknown): {
251
251
  * (which requires an authProvider) instead.
252
252
  *
253
253
  * @deprecated Import `updateUserSubscription` from `@donotdev/functions/shared/billing/helpers/updateUserSubscription`.
254
- * @version 0.0.2
254
+ * @version 0.1.0
255
255
  * @since 0.0.1
256
256
  * @author AMBROISE PARK Consulting
257
257
  */
@@ -271,7 +271,7 @@ export async function updateUserSubscription(
271
271
  * C10: This was a silent no-op stub. Now throws to surface the missing implementation.
272
272
  *
273
273
  * @deprecated Import from `@donotdev/functions/shared/billing/helpers` or implement directly using Firebase Admin SDK / Stripe API.
274
- * @version 0.0.2
274
+ * @version 0.1.0
275
275
  * @since 0.0.1
276
276
  * @author AMBROISE PARK Consulting
277
277
  */
@@ -288,7 +288,7 @@ export async function getUserSubscription(_firebaseUid: string): Promise<any> {
288
288
  * C10: This was a silent no-op stub. Now throws to surface the missing implementation.
289
289
  *
290
290
  * @deprecated Import `cancelUserSubscription` from `@donotdev/functions/shared/billing/helpers/subscriptionManagement`.
291
- * @version 0.0.2
291
+ * @version 0.1.0
292
292
  * @since 0.0.1
293
293
  * @author AMBROISE PARK Consulting
294
294
  */
@@ -308,7 +308,7 @@ export async function cancelUserSubscription(
308
308
  * C10: This was a silent no-op stub. Now throws to surface the missing implementation.
309
309
  *
310
310
  * @deprecated Handle via Stripe webhook events. Use `processWebhook` from `@donotdev/functions/shared/billing/webhookHandler`.
311
- * @version 0.0.2
311
+ * @version 0.1.0
312
312
  * @since 0.0.1
313
313
  * @author AMBROISE PARK Consulting
314
314
  */
@@ -329,7 +329,7 @@ export async function handleSubscriptionCancellation(
329
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
- * @version 0.0.3
332
+ * @version 0.1.0
333
333
  * @since 0.0.1
334
334
  * @author AMBROISE PARK Consulting
335
335
  */
@@ -340,7 +340,7 @@ export async function assertAdmin(uid: string): Promise<string> {
340
340
  /**
341
341
  * Validates document data
342
342
  *
343
- * @version 0.0.1
343
+ * @version 0.1.0
344
344
  * @since 0.0.1
345
345
  * @author AMBROISE PARK Consulting
346
346
  */
@@ -387,7 +387,7 @@ export function validateDocument(data: any, schema?: any): void {
387
387
  * @param name - Collection name to validate
388
388
  * @throws Error if the name is unsafe
389
389
  *
390
- * @version 0.0.1
390
+ * @version 0.1.0
391
391
  * @since 0.0.1
392
392
  * @author AMBROISE PARK Consulting
393
393
  */
@@ -405,7 +405,7 @@ export function validateCollectionName(name: string): void {
405
405
  /**
406
406
  * Verifies Firebase auth token
407
407
  *
408
- * @version 0.0.1
408
+ * @version 0.1.0
409
409
  * @since 0.0.1
410
410
  * @author AMBROISE PARK Consulting
411
411
  */
@@ -425,7 +425,7 @@ export async function verifyFirebaseAuthToken(token: string): Promise<string> {
425
425
  /**
426
426
  * Finds references to a document
427
427
  *
428
- * @version 0.0.1
428
+ * @version 0.1.0
429
429
  * @since 0.0.1
430
430
  * @author AMBROISE PARK Consulting
431
431
  */
@@ -4,7 +4,7 @@
4
4
  * @fileoverview Environment validation utilities
5
5
  * @description Validate required environment variables on module load
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
  */
@@ -12,7 +12,7 @@
12
12
  /**
13
13
  * Validates required environment variables
14
14
  *
15
- * @version 0.0.1
15
+ * @version 0.1.0
16
16
  * @since 0.0.1
17
17
  * @author AMBROISE PARK Consulting
18
18
  */
@@ -52,7 +52,7 @@ export function validateEnvironment(): void {
52
52
  if (!secretKey.startsWith('sk_')) {
53
53
  throw new Error(
54
54
  `❌ Invalid STRIPE_SECRET_KEY format\n` +
55
- `Secret keys must start with "sk_" (found: "${secretKey.substring(0, 3)}...")`
55
+ `Secret keys must start with "sk_" (found: "[redacted]")`
56
56
  );
57
57
  }
58
58
 
@@ -0,0 +1,75 @@
1
+ // packages/functions/src/supabase/ai/createAIFunction.ts
2
+
3
+ /**
4
+ * @fileoverview AI Chat - Supabase Edge Function Factory
5
+ * @description Wraps the shared AI route handler for Supabase Edge Functions.
6
+ * Uses Vercel AI SDK via createAIRoute for streaming and non-streaming.
7
+ *
8
+ * @version 0.1.0
9
+ * @since 0.1.0
10
+ * @author AMBROISE PARK Consulting
11
+ */
12
+
13
+ import type {
14
+ AIChatRequest,
15
+ AICostRecord,
16
+ AIRouteConfig,
17
+ } from '@donotdev/core/server';
18
+ import { AIChatRequestSchema } from '@donotdev/core/server';
19
+
20
+ import { handleAIRequest } from '../../shared/ai/index.js';
21
+ import { createSupabaseHandler } from '../baseFunction.js';
22
+
23
+ /**
24
+ * Create a Supabase Edge Function handler for AI chat.
25
+ *
26
+ * @param config - AI route configuration
27
+ * @returns `(req: Request) => Promise<Response>` handler
28
+ *
29
+ * @example
30
+ * ```typescript
31
+ * // supabase/functions/ai-chat/index.ts
32
+ * import { createAIFunction } from '@donotdev/functions/supabase';
33
+ *
34
+ * const handler = createAIFunction({
35
+ * provider: 'anthropic',
36
+ * model: 'claude-sonnet-4-20250514',
37
+ * cost: { markup: 4.0, monthlyBudgetTokens: 500_000, showCostToUsers: false, displayCurrency: 'eur' },
38
+ * });
39
+ * Deno.serve(handler);
40
+ * ```
41
+ */
42
+ export function createAIFunction(config: AIRouteConfig) {
43
+ return createSupabaseHandler(
44
+ 'ai-chat',
45
+ AIChatRequestSchema,
46
+ async (data: AIChatRequest, ctx) => {
47
+ return handleAIRequest(data, config, {
48
+ userId: ctx.uid,
49
+ requestId: crypto.randomUUID(),
50
+ onCostRecord: async (record: AICostRecord) => {
51
+ // Write cost record to Supabase
52
+ const { error } = await ctx.supabaseAdmin
53
+ .from('ai_usage')
54
+ .insert({
55
+ user_id: record.userId,
56
+ model: record.model,
57
+ provider: record.provider,
58
+ prompt_tokens: record.usage.promptTokens,
59
+ completion_tokens: record.usage.completionTokens,
60
+ total_tokens: record.usage.totalTokens,
61
+ provider_cost: record.providerCost,
62
+ billed_cost: record.billedCost,
63
+ markup: record.markup,
64
+ request_id: record.requestId,
65
+ created_at: record.timestamp,
66
+ });
67
+
68
+ if (error) {
69
+ console.error('[AI] Failed to record cost to Supabase:', error.message);
70
+ }
71
+ },
72
+ });
73
+ }
74
+ );
75
+ }
@@ -4,7 +4,7 @@
4
4
  * @fileoverview Delete Account Supabase Edge Function
5
5
  * @description Deletes the authenticated user's account via Supabase Admin.
6
6
  *
7
- * @version 0.0.1
7
+ * @version 0.1.0
8
8
  * @since 0.5.0
9
9
  * @author AMBROISE PARK Consulting
10
10
  */
@@ -35,7 +35,7 @@ const deleteAccountSchema = v.object({});
35
35
  * Deno.serve(createDeleteAccount());
36
36
  * ```
37
37
  *
38
- * @version 0.0.1
38
+ * @version 0.1.0
39
39
  * @since 0.5.0
40
40
  */
41
41
  export function createDeleteAccount() {
@@ -4,7 +4,7 @@
4
4
  * @fileoverview Get Custom Claims Supabase Edge Function
5
5
  * @description Returns the authenticated user's app_metadata (custom claims).
6
6
  *
7
- * @version 0.0.1
7
+ * @version 0.1.0
8
8
  * @since 0.6.0
9
9
  * @author AMBROISE PARK Consulting
10
10
  */
@@ -35,7 +35,7 @@ const getCustomClaimsSchema = v.object({});
35
35
  * Deno.serve(createGetCustomClaims());
36
36
  * ```
37
37
  *
38
- * @version 0.0.1
38
+ * @version 0.1.0
39
39
  * @since 0.6.0
40
40
  */
41
41
  export function createGetCustomClaims() {
@@ -4,7 +4,7 @@
4
4
  * @fileoverview Get User Auth Status Supabase Edge Function
5
5
  * @description Returns the authenticated user's profile and custom claims.
6
6
  *
7
- * @version 0.0.1
7
+ * @version 0.1.0
8
8
  * @since 0.6.0
9
9
  * @author AMBROISE PARK Consulting
10
10
  */
@@ -37,7 +37,7 @@ const getUserAuthStatusSchema = v.object({});
37
37
  * Deno.serve(createGetUserAuthStatus());
38
38
  * ```
39
39
  *
40
- * @version 0.0.1
40
+ * @version 0.1.0
41
41
  * @since 0.6.0
42
42
  */
43
43
  export function createGetUserAuthStatus() {
@@ -3,8 +3,9 @@
3
3
  /**
4
4
  * @fileoverview Remove Custom Claims Supabase Edge Function
5
5
  * @description Removes specific keys from the user's app_metadata.
6
+ * Blocklist prevents removal of security-critical claims.
6
7
  *
7
- * @version 0.0.1
8
+ * @version 0.2.0
8
9
  * @since 0.6.0
9
10
  * @author AMBROISE PARK Consulting
10
11
  */
@@ -24,6 +25,31 @@ const removeCustomClaimsSchema = v.object({
24
25
  ),
25
26
  });
26
27
 
28
+ /**
29
+ * Claim keys that must NEVER be removed by users - privilege/integrity vectors.
30
+ * Matches BLOCKED_CLAIM_KEYS in setCustomClaims.ts.
31
+ */
32
+ const BLOCKED_CLAIM_KEYS = new Set([
33
+ 'admin',
34
+ 'isAdmin',
35
+ 'isSuper',
36
+ 'isSuperAdmin',
37
+ 'role',
38
+ 'roles',
39
+ 'permissions',
40
+ 'superuser',
41
+ 'moderator',
42
+ 'staff',
43
+ 'elevated',
44
+ 'plan',
45
+ 'tier',
46
+ 'provider',
47
+ 'providers',
48
+ 'sub',
49
+ 'iss',
50
+ 'aud',
51
+ ]);
52
+
27
53
  // =============================================================================
28
54
  // Handler
29
55
  // =============================================================================
@@ -40,7 +66,7 @@ const removeCustomClaimsSchema = v.object({
40
66
  * Deno.serve(createRemoveCustomClaims());
41
67
  * ```
42
68
  *
43
- * @version 0.0.1
69
+ * @version 0.2.0
44
70
  * @since 0.6.0
45
71
  */
46
72
  export function createRemoveCustomClaims() {
@@ -48,6 +74,16 @@ export function createRemoveCustomClaims() {
48
74
  'remove-custom-claims',
49
75
  removeCustomClaimsSchema,
50
76
  async (data, ctx) => {
77
+ // Block removal of security-critical claims
78
+ const blocked = data.claimsToRemove.filter((k) =>
79
+ BLOCKED_CLAIM_KEYS.has(k)
80
+ );
81
+ if (blocked.length > 0) {
82
+ throw new Error(
83
+ `Protected claims cannot be removed: ${blocked.join(', ')}`
84
+ );
85
+ }
86
+
51
87
  // Get current app_metadata
52
88
  const {
53
89
  data: { user },
@@ -3,8 +3,10 @@
3
3
  /**
4
4
  * @fileoverview Set Custom Claims Supabase Edge Function
5
5
  * @description Merges custom claims into the user's app_metadata.
6
+ * Mirrors the Firebase pattern: consumer provides an explicit allowlist,
7
+ * framework enforces a blocklist as safety net.
6
8
  *
7
- * @version 0.0.1
9
+ * @version 0.2.0
8
10
  * @since 0.6.0
9
11
  * @author AMBROISE PARK Consulting
10
12
  */
@@ -22,6 +24,41 @@ const setCustomClaimsSchema = v.object({
22
24
  idempotencyKey: v.optional(v.string()),
23
25
  });
24
26
 
27
+ /**
28
+ * Claim keys that must NEVER be self-assignable - privilege escalation vectors.
29
+ * Matches Firebase `BLOCKED_CLAIM_KEYS`.
30
+ */
31
+ const BLOCKED_CLAIM_KEYS = new Set([
32
+ 'admin',
33
+ 'isAdmin',
34
+ 'isSuper',
35
+ 'isSuperAdmin',
36
+ 'role',
37
+ 'roles',
38
+ 'permissions',
39
+ 'superuser',
40
+ 'moderator',
41
+ 'staff',
42
+ 'elevated',
43
+ 'plan',
44
+ 'tier',
45
+ 'provider',
46
+ 'providers',
47
+ 'sub',
48
+ 'iss',
49
+ 'aud',
50
+ ]);
51
+
52
+ // =============================================================================
53
+ // Types
54
+ // =============================================================================
55
+
56
+ /** Options for the set-custom-claims edge function factory. */
57
+ export interface SetCustomClaimsOptions {
58
+ /** Explicit allowlist of claim keys users may set on themselves. Required. */
59
+ allowedClaimKeys: string[];
60
+ }
61
+
25
62
  // =============================================================================
26
63
  // Handler
27
64
  // =============================================================================
@@ -29,25 +66,49 @@ const setCustomClaimsSchema = v.object({
29
66
  /**
30
67
  * Create a Supabase Edge Function handler for setting custom claims (app_metadata).
31
68
  *
32
- * Merges provided claims into the user's existing app_metadata.
69
+ * Consumers MUST specify which claim keys are self-assignable.
70
+ * The framework enforces a blocklist as a safety net even if the consumer
71
+ * accidentally includes a privilege key.
33
72
  *
73
+ * @param options - Configuration with allowedClaimKeys
34
74
  * @returns `(req: Request) => Promise<Response>` handler
35
75
  *
36
76
  * @example
37
77
  * ```typescript
38
78
  * // supabase/functions/set-custom-claims/index.ts
39
79
  * import { createSetCustomClaims } from '@donotdev/functions/supabase';
40
- * Deno.serve(createSetCustomClaims());
80
+ * Deno.serve(createSetCustomClaims({ allowedClaimKeys: ['theme', 'locale'] }));
41
81
  * ```
42
82
  *
43
- * @version 0.0.1
83
+ * @version 0.2.0
44
84
  * @since 0.6.0
45
85
  */
46
- export function createSetCustomClaims() {
86
+ export function createSetCustomClaims(options: SetCustomClaimsOptions) {
87
+ const allowedKeys = new Set(options.allowedClaimKeys);
88
+
89
+ // Fail fast if consumer accidentally allows a privilege key
90
+ for (const key of allowedKeys) {
91
+ if (BLOCKED_CLAIM_KEYS.has(key)) {
92
+ throw new Error(
93
+ `Claim key "${key}" is blocked - it is a privilege-escalation vector and cannot be self-assigned.`
94
+ );
95
+ }
96
+ }
97
+
47
98
  return createSupabaseHandler(
48
99
  'set-custom-claims',
49
100
  setCustomClaimsSchema,
50
101
  async (data, ctx) => {
102
+ // Only allow keys from the consumer-provided allowlist
103
+ const disallowedKeys = Object.keys(data.customClaims).filter(
104
+ (k) => !allowedKeys.has(k)
105
+ );
106
+ if (disallowedKeys.length > 0) {
107
+ throw new Error(
108
+ `Claim keys not allowed: ${disallowedKeys.join(', ')}`
109
+ );
110
+ }
111
+
51
112
  // Get current app_metadata
52
113
  const {
53
114
  data: { user },
@@ -5,7 +5,7 @@
5
5
  * @description Handles auth verification, request validation, and error responses
6
6
  * for Supabase Edge Functions. Mirrors the Firebase/Vercel base function pattern.
7
7
  *
8
- * @version 0.0.1
8
+ * @version 0.1.0
9
9
  * @since 0.5.0
10
10
  * @author AMBROISE PARK Consulting
11
11
  */
@@ -32,7 +32,7 @@ import type { SupabaseClient } from '@supabase/supabase-js';
32
32
  /**
33
33
  * Context passed to Supabase Edge Function business logic
34
34
  *
35
- * @version 0.0.1
35
+ * @version 0.1.0
36
36
  * @since 0.5.0
37
37
  */
38
38
  export interface SupabaseHandlerContext {
@@ -70,7 +70,7 @@ export interface SupabaseHandlerContext {
70
70
  * }, 'admin');
71
71
  * ```
72
72
  *
73
- * @version 0.0.1
73
+ * @version 0.1.0
74
74
  * @since 0.5.0
75
75
  */
76
76
  export function createSupabaseHandler<TReq, TRes>(
@@ -259,12 +259,36 @@ export function createSupabaseHandler<TReq, TRes>(
259
259
  }
260
260
  }
261
261
 
262
+ // Passthrough for streaming responses (e.g., AI SSE streams)
263
+ if (result instanceof Response) {
264
+ const headers = new Headers(result.headers);
265
+ headers.set('Access-Control-Allow-Origin', allowedOrigin);
266
+ return new Response(result.body, {
267
+ status: result.status,
268
+ statusText: result.statusText,
269
+ headers,
270
+ });
271
+ }
272
+
262
273
  return respond(result, 200);
263
274
  } catch (error) {
264
275
  console.error(`[${operationName}] Error:`, error);
265
- const message =
276
+ const rawMessage =
266
277
  error instanceof Error ? error.message : 'Internal server error';
267
- const status = getErrorStatus(message);
278
+ const errorCode = getErrorCode(rawMessage);
279
+ // Only pass through messages for known safe error codes.
280
+ // All other/unknown errors get a generic message to prevent information leaks.
281
+ const SAFE_ERROR_CODES = new Set([
282
+ 'rate-limit-exceeded',
283
+ 'not-found',
284
+ 'permission-denied',
285
+ 'invalid-argument',
286
+ 'already-exists',
287
+ ]);
288
+ const message = SAFE_ERROR_CODES.has(errorCode)
289
+ ? rawMessage
290
+ : 'Internal server error';
291
+ const status = getErrorStatus(rawMessage);
268
292
  // allowedOrigin may not be set if error occurred before that line; fall back to '*'
269
293
  const origin = getEnv('ALLOWED_ORIGIN', '*');
270
294
  return jsonResponse({ error: message }, status, origin);
@@ -4,7 +4,7 @@
4
4
  * @fileoverview Cancel Subscription — Supabase Edge Function
5
5
  * @description Wraps the shared `cancelUserSubscription` for Supabase.
6
6
  *
7
- * @version 0.0.1
7
+ * @version 0.1.0
8
8
  * @since 0.5.0
9
9
  * @author AMBROISE PARK Consulting
10
10
  */
@@ -33,7 +33,7 @@ const cancelSubscriptionSchema = v.object({
33
33
  *
34
34
  * @returns `(req: Request) => Promise<Response>` handler
35
35
  *
36
- * @version 0.0.1
36
+ * @version 0.1.0
37
37
  * @since 0.5.0
38
38
  */
39
39
  export function createCancelSubscription() {
@@ -4,14 +4,14 @@
4
4
  * @fileoverview Change Plan — Supabase Edge Function
5
5
  * @description Wraps the shared `changeUserPlan` for Supabase.
6
6
  *
7
- * @version 0.0.1
7
+ * @version 0.1.0
8
8
  * @since 0.5.0
9
9
  * @author AMBROISE PARK Consulting
10
10
  */
11
11
 
12
12
  import * as v from 'valibot';
13
13
 
14
- import type { StripeBackConfig } from '@donotdev/core/server';
14
+ import { hasRoleAccess, type StripeBackConfig } from '@donotdev/core/server';
15
15
 
16
16
  import { changeUserPlan } from '../../shared/billing/helpers/subscriptionManagement.js';
17
17
  import { initStripe } from '../../shared/utils.js';
@@ -41,7 +41,7 @@ const changePlanSchema = v.object({
41
41
  * @param billingConfig - Billing configuration with product definitions
42
42
  * @returns `(req: Request) => Promise<Response>` handler
43
43
  *
44
- * @version 0.0.1
44
+ * @version 0.1.0
45
45
  * @since 0.5.0
46
46
  */
47
47
  export function createChangePlan(billingConfig: StripeBackConfig) {
@@ -49,6 +49,11 @@ export function createChangePlan(billingConfig: StripeBackConfig) {
49
49
  'change-plan',
50
50
  changePlanSchema,
51
51
  async (data, ctx) => {
52
+ // Non-admin users can only change their own plan
53
+ if (!hasRoleAccess(ctx.userRole, 'admin') && data.userId !== ctx.uid) {
54
+ throw new Error('Forbidden: cannot change another user\'s plan');
55
+ }
56
+
52
57
  initStripe(getStripeKey());
53
58
  const authProvider = createSupabaseAuthProvider(ctx.supabaseAdmin);
54
59
  return changeUserPlan(
@@ -4,7 +4,7 @@
4
4
  * @fileoverview Create Checkout Session — Supabase Edge Function
5
5
  * @description Wraps the shared `createCheckoutAlgorithm` for Supabase.
6
6
  *
7
- * @version 0.0.1
7
+ * @version 0.1.0
8
8
  * @since 0.5.0
9
9
  * @author AMBROISE PARK Consulting
10
10
  */
@@ -32,7 +32,7 @@ import { createSupabaseAuthProvider } from '../helpers/authProvider.js';
32
32
  * @param billingConfig - Billing configuration with product definitions
33
33
  * @returns `(req: Request) => Promise<Response>` handler
34
34
  *
35
- * @version 0.0.1
35
+ * @version 0.1.0
36
36
  * @since 0.5.0
37
37
  */
38
38
  export function createCheckoutSession(billingConfig: StripeBackConfig) {
@@ -47,7 +47,10 @@ export function createCheckoutSession(billingConfig: StripeBackConfig) {
47
47
 
48
48
  const stripeProvider = {
49
49
  async createCheckoutSession(params: {
50
- priceId: string;
50
+ priceId?: string;
51
+ unitAmount?: number;
52
+ productName?: string;
53
+ currency?: string;
51
54
  customerEmail?: string;
52
55
  metadata: Record<string, string>;
53
56
  allowPromotionCodes: boolean;
@@ -57,7 +60,18 @@ export function createCheckoutSession(billingConfig: StripeBackConfig) {
57
60
  }) {
58
61
  const session = await stripe.checkout.sessions.create({
59
62
  mode: params.mode || 'payment',
60
- line_items: [{ price: params.priceId, quantity: 1 }],
63
+ line_items: [
64
+ params.priceId
65
+ ? { price: params.priceId, quantity: 1 }
66
+ : {
67
+ price_data: {
68
+ currency: params.currency || 'eur',
69
+ unit_amount: params.unitAmount!,
70
+ product_data: { name: params.productName! },
71
+ },
72
+ quantity: 1,
73
+ },
74
+ ],
61
75
  customer_email: params.customerEmail || undefined,
62
76
  success_url: params.successUrl,
63
77
  cancel_url: params.cancelUrl,
@@ -4,7 +4,7 @@
4
4
  * @fileoverview Create Customer Portal — Supabase Edge Function
5
5
  * @description Wraps the shared `createCustomerPortalSession` for Supabase.
6
6
  *
7
- * @version 0.0.1
7
+ * @version 0.1.0
8
8
  * @since 0.5.0
9
9
  * @author AMBROISE PARK Consulting
10
10
  */
@@ -34,7 +34,7 @@ const customerPortalSchema = v.object({
34
34
  *
35
35
  * @returns `(req: Request) => Promise<Response>` handler
36
36
  *
37
- * @version 0.0.1
37
+ * @version 0.1.0
38
38
  * @since 0.5.0
39
39
  */
40
40
  export function createCustomerPortal() {