@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
@@ -0,0 +1,183 @@
1
+ // packages/functions/src/supabase/oauth/exchangeToken.ts
2
+
3
+ /**
4
+ * @fileoverview OAuth token exchange Supabase Edge Function
5
+ * @description Supabase Edge Function for exchanging OAuth codes for tokens
6
+ *
7
+ * @version 0.1.0
8
+ * @since 0.1.0
9
+ * @author AMBROISE PARK Consulting
10
+ */
11
+
12
+ import * as v from 'valibot';
13
+
14
+ import {
15
+ OAUTH_PARTNERS,
16
+ exchangeTokenSchema,
17
+ sanitizeHref,
18
+ type ExchangeTokenRequest,
19
+ type OAuthPartnerId,
20
+ } from '@donotdev/core/server';
21
+
22
+ import { createSupabaseHandler } from '../baseFunction.js';
23
+ import type { SupabaseHandlerContext } from '../baseFunction.js';
24
+
25
+ /**
26
+ * Sanitize profile data from external OAuth providers.
27
+ * Strips HTML tags and limits string length to prevent stored XSS.
28
+ */
29
+ function sanitizeProfileData(
30
+ data: Record<string, unknown>
31
+ ): Record<string, unknown> {
32
+ const result: Record<string, unknown> = {};
33
+ for (const [key, value] of Object.entries(data)) {
34
+ if (typeof value === 'string') {
35
+ result[key] = value.replace(/<[^>]*>/g, '').slice(0, 1000);
36
+ } else if (
37
+ typeof value === 'object' &&
38
+ value !== null &&
39
+ !Array.isArray(value)
40
+ ) {
41
+ result[key] = sanitizeProfileData(value as Record<string, unknown>);
42
+ } else {
43
+ result[key] = value;
44
+ }
45
+ }
46
+ return result;
47
+ }
48
+
49
+ /** Cross-runtime env var access (Deno Edge Functions + Node tests) */
50
+ function getEnv(key: string): string | undefined {
51
+ return typeof Deno !== 'undefined'
52
+ ? Deno.env.get(key)
53
+ : process.env[key];
54
+ }
55
+
56
+ declare const Deno:
57
+ | { env: { get(key: string): string | undefined } }
58
+ | undefined;
59
+
60
+ /**
61
+ * Create an OAuth token exchange Edge Function handler
62
+ *
63
+ * @example
64
+ * ```typescript
65
+ * import { createExchangeToken } from '@donotdev/functions/supabase';
66
+ * Deno.serve(createExchangeToken());
67
+ * ```
68
+ *
69
+ * @version 0.1.0
70
+ * @since 0.1.0
71
+ */
72
+ export function createExchangeToken() {
73
+ return createSupabaseHandler(
74
+ 'exchange-token',
75
+ exchangeTokenSchema,
76
+ async (data: ExchangeTokenRequest, ctx: SupabaseHandlerContext) => {
77
+ const { provider, purpose, code, redirectUri, codeVerifier } = data;
78
+
79
+ // Validate redirectUri scheme (defense-in-depth over Valibot v.url())
80
+ if (!sanitizeHref(redirectUri)) {
81
+ throw new Error('Invalid redirect URI scheme');
82
+ }
83
+
84
+ // Get provider endpoints
85
+ const endpoints = OAUTH_PARTNERS[provider];
86
+ if (!endpoints?.endpoints?.tokenUrl) {
87
+ throw new Error(`Provider ${provider} is not supported`);
88
+ }
89
+
90
+ // Get client credentials from env: {PROVIDER}_CLIENT_ID, {PROVIDER}_CLIENT_SECRET
91
+ const upper = provider.toUpperCase();
92
+ const clientId = getEnv(`${upper}_CLIENT_ID`);
93
+ const clientSecret = getEnv(`${upper}_CLIENT_SECRET`);
94
+
95
+ if (!clientId || !clientSecret) {
96
+ throw new Error(`Provider ${provider} is not configured`);
97
+ }
98
+
99
+ // Exchange code for token
100
+ const tokenResponse = await fetch(endpoints.endpoints.tokenUrl, {
101
+ method: 'POST',
102
+ headers: {
103
+ 'Content-Type': 'application/x-www-form-urlencoded',
104
+ Accept: 'application/json',
105
+ },
106
+ body: new URLSearchParams({
107
+ grant_type: 'authorization_code',
108
+ client_id: clientId,
109
+ client_secret: clientSecret,
110
+ code,
111
+ redirect_uri: redirectUri,
112
+ ...(codeVerifier ? { code_verifier: codeVerifier } : {}),
113
+ }).toString(),
114
+ });
115
+
116
+ if (!tokenResponse.ok) {
117
+ const errorText = await tokenResponse.text();
118
+ console.error(
119
+ `Token exchange error for ${provider}: ${tokenResponse.status}`,
120
+ errorText
121
+ );
122
+ throw new Error(
123
+ `Failed to exchange code for token: ${tokenResponse.status}`
124
+ );
125
+ }
126
+
127
+ const tokenData = (await tokenResponse.json()) as any;
128
+
129
+ // Format credentials
130
+ const credentials = {
131
+ accessToken: tokenData.access_token,
132
+ refreshToken: tokenData.refresh_token || null,
133
+ expiresAt: tokenData.expires_in
134
+ ? Math.floor(Date.now() / 1000) + tokenData.expires_in
135
+ : null,
136
+ idToken: tokenData.id_token || null,
137
+ scope: tokenData.scope ? tokenData.scope.split(' ') : [],
138
+ };
139
+
140
+ // Get user profile
141
+ let profile: Record<string, unknown> | null = null;
142
+ if (credentials.accessToken && endpoints.endpoints.profileUrl) {
143
+ try {
144
+ const profileResponse = await fetch(endpoints.endpoints.profileUrl, {
145
+ headers: {
146
+ Authorization: `Bearer ${credentials.accessToken}`,
147
+ Accept: 'application/json',
148
+ },
149
+ });
150
+ if (profileResponse.ok) {
151
+ const rawProfile = await profileResponse.json();
152
+ // Sanitize profile data from external provider (prevent stored XSS)
153
+ profile = sanitizeProfileData(rawProfile);
154
+ }
155
+ } catch (e) {
156
+ console.warn(`Failed to fetch profile for ${provider}:`, e);
157
+ }
158
+ }
159
+
160
+ // Save connection to Supabase
161
+ const { error: upsertError } = await ctx.supabaseAdmin
162
+ .from('oauth_connections')
163
+ .upsert(
164
+ {
165
+ user_id: ctx.uid,
166
+ provider,
167
+ purpose,
168
+ credentials,
169
+ profile,
170
+ connected: true,
171
+ updated_at: new Date().toISOString(),
172
+ },
173
+ { onConflict: 'user_id,provider,purpose' }
174
+ );
175
+
176
+ if (upsertError) {
177
+ console.error('Error saving OAuth connection:', upsertError);
178
+ }
179
+
180
+ return { success: true, credentials, profile };
181
+ }
182
+ );
183
+ }
@@ -0,0 +1,85 @@
1
+ // packages/functions/src/supabase/oauth/getConnections.ts
2
+
3
+ /**
4
+ * @fileoverview Get OAuth connections Supabase Edge Function
5
+ * @description Supabase Edge Function for retrieving user OAuth connections
6
+ *
7
+ * @version 0.1.0
8
+ * @since 0.1.0
9
+ * @author AMBROISE PARK Consulting
10
+ */
11
+
12
+ import * as v from 'valibot';
13
+
14
+ import type { OAuthPurpose } from '@donotdev/core/server';
15
+
16
+ import { createSupabaseHandler } from '../baseFunction.js';
17
+ import type { SupabaseHandlerContext } from '../baseFunction.js';
18
+
19
+ const getConnectionsSchema = v.object({
20
+ purpose: v.optional(
21
+ v.picklist(['authentication', 'api-access']) as v.BaseSchema<
22
+ unknown,
23
+ OAuthPurpose,
24
+ v.BaseIssue<unknown>
25
+ >
26
+ ),
27
+ });
28
+
29
+ /**
30
+ * Create a get OAuth connections Edge Function handler
31
+ *
32
+ * @example
33
+ * ```typescript
34
+ * import { createGetConnections } from '@donotdev/functions/supabase';
35
+ * Deno.serve(createGetConnections());
36
+ * ```
37
+ *
38
+ * @version 0.1.0
39
+ * @since 0.1.0
40
+ */
41
+ export function createGetConnections() {
42
+ return createSupabaseHandler(
43
+ 'get-connections',
44
+ getConnectionsSchema,
45
+ async (
46
+ data: { purpose?: OAuthPurpose },
47
+ ctx: SupabaseHandlerContext
48
+ ) => {
49
+ let query = ctx.supabaseAdmin
50
+ .from('oauth_connections')
51
+ .select('*')
52
+ .eq('user_id', ctx.uid);
53
+
54
+ if (data.purpose) {
55
+ query = query.eq('purpose', data.purpose);
56
+ }
57
+
58
+ const { data: rows, error } = await query;
59
+
60
+ if (error) {
61
+ throw new Error(`Failed to get connections: ${error.message}`);
62
+ }
63
+
64
+ const connections = (rows || []).map((row: any) => {
65
+ const isExpired = row.credentials?.expiresAt
66
+ ? row.credentials.expiresAt < Math.floor(Date.now() / 1000)
67
+ : false;
68
+
69
+ return {
70
+ id: row.id,
71
+ userId: row.user_id,
72
+ provider: row.provider,
73
+ purpose: row.purpose,
74
+ connected: !isExpired,
75
+ createdAt: row.created_at,
76
+ updatedAt: row.updated_at,
77
+ hasCredentials: !isExpired && !!row.credentials,
78
+ profile: row.profile,
79
+ };
80
+ });
81
+
82
+ return { connections };
83
+ }
84
+ );
85
+ }
@@ -0,0 +1,15 @@
1
+ // packages/functions/src/supabase/oauth/index.ts
2
+
3
+ /**
4
+ * @fileoverview Supabase OAuth functions barrel exports
5
+ * @description Centralized exports for Supabase OAuth Edge Functions
6
+ *
7
+ * @version 0.1.0
8
+ * @since 0.1.0
9
+ * @author AMBROISE PARK Consulting
10
+ */
11
+
12
+ export { createExchangeToken } from './exchangeToken.js';
13
+ export { createDisconnect } from './disconnect.js';
14
+ export { createRefreshToken } from './refreshToken.js';
15
+ export { createGetConnections } from './getConnections.js';
@@ -0,0 +1,130 @@
1
+ // packages/functions/src/supabase/oauth/refreshToken.ts
2
+
3
+ /**
4
+ * @fileoverview OAuth token refresh Supabase Edge Function
5
+ * @description Supabase Edge Function for refreshing OAuth tokens
6
+ *
7
+ * @version 0.1.0
8
+ * @since 0.1.0
9
+ * @author AMBROISE PARK Consulting
10
+ */
11
+
12
+ import * as v from 'valibot';
13
+
14
+ import {
15
+ OAUTH_PARTNERS,
16
+ type OAuthRefreshRequest,
17
+ } from '@donotdev/core/server';
18
+
19
+ import { createSupabaseHandler } from '../baseFunction.js';
20
+ import type { SupabaseHandlerContext } from '../baseFunction.js';
21
+
22
+ /** Cross-runtime env var access (Deno Edge Functions + Node tests) */
23
+ function getEnv(key: string): string | undefined {
24
+ return typeof Deno !== 'undefined'
25
+ ? Deno.env.get(key)
26
+ : process.env[key];
27
+ }
28
+
29
+ declare const Deno:
30
+ | { env: { get(key: string): string | undefined } }
31
+ | undefined;
32
+
33
+ const refreshTokenSchema = v.object({
34
+ provider: v.string() as v.BaseSchema<
35
+ unknown,
36
+ OAuthRefreshRequest['provider'],
37
+ v.BaseIssue<unknown>
38
+ >,
39
+ refreshToken: v.pipe(
40
+ v.string(),
41
+ v.minLength(1, 'Refresh token is required')
42
+ ),
43
+ redirectUri: v.pipe(v.string(), v.url('Valid redirect URI is required')),
44
+ });
45
+
46
+ /**
47
+ * Create an OAuth token refresh Edge Function handler
48
+ *
49
+ * @example
50
+ * ```typescript
51
+ * import { createRefreshToken } from '@donotdev/functions/supabase';
52
+ * Deno.serve(createRefreshToken());
53
+ * ```
54
+ *
55
+ * @version 0.1.0
56
+ * @since 0.1.0
57
+ */
58
+ export function createRefreshToken() {
59
+ return createSupabaseHandler(
60
+ 'refresh-token',
61
+ refreshTokenSchema,
62
+ async (data: OAuthRefreshRequest, ctx: SupabaseHandlerContext) => {
63
+ const { provider, refreshToken: refreshTokenValue, redirectUri } = data;
64
+
65
+ // Get provider endpoints
66
+ const endpoints = OAUTH_PARTNERS[provider];
67
+ if (!endpoints?.endpoints?.tokenUrl) {
68
+ throw new Error(`Provider ${provider} does not support token refresh`);
69
+ }
70
+
71
+ // Get client credentials: {PROVIDER}_CLIENT_ID, {PROVIDER}_CLIENT_SECRET
72
+ const upper = provider.toUpperCase();
73
+ const clientId = getEnv(`${upper}_CLIENT_ID`);
74
+ const clientSecret = getEnv(`${upper}_CLIENT_SECRET`);
75
+
76
+ if (!clientId || !clientSecret) {
77
+ throw new Error(`Provider ${provider} is not configured`);
78
+ }
79
+
80
+ // Refresh the token
81
+ const response = await fetch(endpoints.endpoints.tokenUrl, {
82
+ method: 'POST',
83
+ headers: {
84
+ 'Content-Type': 'application/x-www-form-urlencoded',
85
+ Accept: 'application/json',
86
+ },
87
+ body: new URLSearchParams({
88
+ grant_type: 'refresh_token',
89
+ client_id: clientId,
90
+ client_secret: clientSecret,
91
+ refresh_token: refreshTokenValue,
92
+ redirect_uri: redirectUri,
93
+ }).toString(),
94
+ });
95
+
96
+ if (!response.ok) {
97
+ const errorText = await response.text();
98
+ console.error(`Token refresh error for ${provider}:`, errorText);
99
+ throw new Error(`Failed to refresh token: ${response.status}`);
100
+ }
101
+
102
+ const tokenData = (await response.json()) as any;
103
+
104
+ const credentials = {
105
+ accessToken: tokenData.access_token,
106
+ refreshToken: tokenData.refresh_token || refreshTokenValue,
107
+ expiresAt: tokenData.expires_in
108
+ ? Math.floor(Date.now() / 1000) + tokenData.expires_in
109
+ : null,
110
+ scope: tokenData.scope ? tokenData.scope.split(' ') : [],
111
+ };
112
+
113
+ // Update connection in Supabase
114
+ const { error: updateError } = await ctx.supabaseAdmin
115
+ .from('oauth_connections')
116
+ .update({
117
+ credentials,
118
+ updated_at: new Date().toISOString(),
119
+ })
120
+ .eq('user_id', ctx.uid)
121
+ .eq('provider', provider);
122
+
123
+ if (updateError) {
124
+ console.error('Error updating OAuth connection:', updateError);
125
+ }
126
+
127
+ return { success: true, credentials };
128
+ }
129
+ );
130
+ }
@@ -4,7 +4,7 @@
4
4
  * @fileoverview Auto-register CRUD handlers from entities for Supabase Edge Functions
5
5
  * @description Utility to automatically generate CRUD Edge Function handlers for all entities
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
  */
@@ -20,6 +20,7 @@ import {
20
20
  createSupabaseListEntities,
21
21
  createSupabaseAggregateEntities,
22
22
  } from './crud/index.js';
23
+ import { createEdgeFunction } from './edgeFunction.js';
23
24
 
24
25
  type SupabaseHandler = (req: Request) => Promise<Response>;
25
26
 
@@ -122,49 +123,36 @@ export function createSupabaseCrudFunctions(
122
123
  }
123
124
 
124
125
  /**
125
- * Serve dispatcher: reads _functionName from request body, routes to correct handler
126
+ * Serve dispatcher: CORS via createEdgeFunction, then routes by _functionName.
127
+ * Auth is NOT checked here (requireAuth: false) — individual handlers
128
+ * use createSupabaseHandler which enforces auth + RBAC per operation.
126
129
  */
127
- const serve = async (req: Request): Promise<Response> => {
128
- try {
129
- const body = await req.json().catch(() => ({}));
130
- const functionName = (body as Record<string, unknown>)
131
- ._functionName as string;
132
-
133
- if (!functionName) {
134
- return new Response(
135
- JSON.stringify({ error: 'Missing _functionName in request body' }),
136
- { status: 400, headers: { 'Content-Type': 'application/json' } }
137
- );
138
- }
139
-
140
- const handler = handlers[functionName];
141
- if (!handler) {
142
- return new Response(
143
- JSON.stringify({ error: `Unknown function: ${functionName}` }),
144
- { status: 404, headers: { 'Content-Type': 'application/json' } }
145
- );
146
- }
147
-
148
- // Remove _functionName from body before passing to handler
149
- const { _functionName, ...handlerData } = body as Record<string, unknown>;
150
-
151
- // Create new request with cleaned body
152
- const handlerReq = new Request(req.url, {
153
- method: req.method,
154
- headers: req.headers,
155
- body: JSON.stringify(handlerData),
156
- });
157
-
158
- return handler(handlerReq);
159
- } catch (error) {
160
- const message =
161
- error instanceof Error ? error.message : 'Internal server error';
162
- return new Response(JSON.stringify({ error: message }), {
163
- status: 500,
164
- headers: { 'Content-Type': 'application/json' },
165
- });
130
+ const serve = createEdgeFunction(async (req, ctx) => {
131
+ const body = await req.json().catch(() => ({}));
132
+ const functionName = (body as Record<string, unknown>)
133
+ ._functionName as string;
134
+
135
+ if (!functionName) {
136
+ return ctx.error('Missing _functionName in request body', 400);
137
+ }
138
+
139
+ const handler = handlers[functionName];
140
+ if (!handler) {
141
+ return ctx.error(`Unknown function: ${functionName}`, 404);
166
142
  }
167
- };
143
+
144
+ // Remove _functionName from body before passing to handler
145
+ const { _functionName, ...handlerData } = body as Record<string, unknown>;
146
+
147
+ // Create new request with cleaned body
148
+ const handlerReq = new Request(req.url, {
149
+ method: req.method,
150
+ headers: req.headers,
151
+ body: JSON.stringify(handlerData),
152
+ });
153
+
154
+ return handler(handlerReq);
155
+ }, { requireAuth: false });
168
156
 
169
157
  return { handlers, serve };
170
158
  }
@@ -4,7 +4,7 @@
4
4
  * @fileoverview Idempotency utilities for Supabase Edge Functions
5
5
  * @description Provides idempotency checking and storage using Postgres table
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
  */
@@ -56,9 +56,13 @@ export async function checkIdempotency<T>(
56
56
 
57
57
  return data.result as T;
58
58
  } catch (error) {
59
- // Fail open - allow the operation if idempotency check fails
59
+ // Fail closed — in billing context, allowing a duplicate operation is worse
60
+ // than rejecting a legitimate retry. Throw so the caller surfaces an error
61
+ // rather than silently double-processing a payment.
60
62
  console.error('[idempotency] Check failed:', error);
61
- return null;
63
+ throw new Error(
64
+ '[idempotency] Unable to verify idempotency. Operation rejected to prevent potential duplicate processing.'
65
+ );
62
66
  }
63
67
  }
64
68
 
@@ -4,7 +4,7 @@
4
4
  * @fileoverview Monitoring and metrics utilities for Supabase Edge Functions
5
5
  * @description Provides metrics collection and analytics queries using Postgres table
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
  */
@@ -18,7 +18,7 @@
18
18
  * On RPC error or unexpected failure, this function FAILS CLOSED (blocks the request).
19
19
  * A broken rate limiter must not silently allow unlimited access to protected resources.
20
20
  *
21
- * @version 0.0.2
21
+ * @version 0.1.0
22
22
  * @since 0.5.0
23
23
  * @author AMBROISE PARK Consulting
24
24
  */
@@ -0,0 +1,77 @@
1
+ // packages/functions/src/vercel/api/ai/chat.ts
2
+
3
+ /**
4
+ * @fileoverview AI Chat - Vercel Route Handler
5
+ * @description Next.js App Router route handler for AI chat.
6
+ * Uses Vercel AI SDK via shared handleAIRequest.
7
+ *
8
+ * @version 0.1.0
9
+ * @since 0.1.0
10
+ * @author AMBROISE PARK Consulting
11
+ */
12
+
13
+ import type { AIRouteConfig } from '@donotdev/core/server';
14
+ import { AIChatRequestSchema } from '@donotdev/core/server';
15
+ import * as v from 'valibot';
16
+
17
+ import { handleAIRequest } from '../../../shared/ai/index.js';
18
+ import { verifyToken } from '../../../shared/utils/internal/auth.js';
19
+
20
+ /**
21
+ * Create a Next.js App Router POST handler for AI chat.
22
+ *
23
+ * @param config - AI route configuration
24
+ * @returns `(req: Request) => Promise<Response>` handler
25
+ *
26
+ * @example
27
+ * ```typescript
28
+ * // app/api/ai/chat/route.ts
29
+ * import { createAIChatRoute } from '@donotdev/functions/vercel';
30
+ *
31
+ * export const POST = createAIChatRoute({
32
+ * provider: 'anthropic',
33
+ * model: 'claude-sonnet-4-20250514',
34
+ * cost: { markup: 4.0, monthlyBudgetTokens: 0, showCostToUsers: false, displayCurrency: 'eur' },
35
+ * });
36
+ * ```
37
+ */
38
+ export function createAIChatRoute(config: AIRouteConfig) {
39
+ return async (req: Request): Promise<Response> => {
40
+ // Auth
41
+ const authHeader = req.headers.get('authorization');
42
+ if (!authHeader?.startsWith('Bearer ')) {
43
+ return new Response(
44
+ JSON.stringify({ error: 'Missing authorization header' }),
45
+ { status: 401, headers: { 'Content-Type': 'application/json' } }
46
+ );
47
+ }
48
+
49
+ const token = authHeader.slice(7);
50
+ let uid: string;
51
+ try {
52
+ const decoded = await verifyToken(token);
53
+ uid = decoded.uid;
54
+ } catch {
55
+ return new Response(
56
+ JSON.stringify({ error: 'Invalid or expired token' }),
57
+ { status: 401, headers: { 'Content-Type': 'application/json' } }
58
+ );
59
+ }
60
+
61
+ // Parse + validate body
62
+ const body = await req.json().catch(() => ({}));
63
+ const validation = v.safeParse(AIChatRequestSchema, body);
64
+ if (!validation.success) {
65
+ const issues = validation.issues.map((i) => i.message).join(', ');
66
+ return new Response(
67
+ JSON.stringify({ error: `Validation failed: ${issues}` }),
68
+ { status: 400, headers: { 'Content-Type': 'application/json' } }
69
+ );
70
+ }
71
+
72
+ return handleAIRequest(validation.output, config, {
73
+ userId: uid,
74
+ requestId: crypto.randomUUID(),
75
+ });
76
+ };
77
+ }
@@ -0,0 +1 @@
1
+ export { createAIChatRoute } from './chat.js';
@@ -4,7 +4,7 @@
4
4
  * @fileoverview Get custom claims API handler
5
5
  * @description Vercel API route for retrieving custom user claims
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 Get user authentication status API handler
5
5
  * @description Vercel API route for retrieving user authentication status
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 Vercel API auth barrel exports
5
5
  * @description Centralized exports for Vercel API authentication 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 Remove custom claims API handler
5
5
  * @description Vercel API route for removing custom user claims
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
  */