@donotdev/functions 0.0.20 → 0.1.0

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 (270) hide show
  1. package/LICENSE.md +3 -3
  2. package/lib/firebase/auth/getCustomClaims.d.ts +2 -2
  3. package/lib/firebase/auth/getUserAuthStatus.d.ts +2 -2
  4. package/lib/firebase/auth/index.d.ts +1 -1
  5. package/lib/firebase/auth/removeCustomClaims.d.ts +2 -2
  6. package/lib/firebase/auth/setCustomClaims.d.ts +2 -2
  7. package/lib/firebase/baseFunction.d.ts +1 -1
  8. package/lib/firebase/billing/cancelSubscription.d.ts +1 -1
  9. package/lib/firebase/billing/changePlan.d.ts +1 -1
  10. package/lib/firebase/billing/createCustomerPortal.d.ts +1 -1
  11. package/lib/firebase/billing/index.d.ts +1 -1
  12. package/lib/firebase/billing/refreshSubscriptionStatus.d.ts +2 -2
  13. package/lib/firebase/config/constants.d.ts +4 -4
  14. package/lib/firebase/config/index.d.ts +1 -1
  15. package/lib/firebase/crud/aggregate.d.ts +2 -2
  16. package/lib/firebase/crud/delete.d.ts +1 -1
  17. package/lib/firebase/crud/get.d.ts +1 -1
  18. package/lib/firebase/crud/index.d.ts +1 -1
  19. package/lib/firebase/crud/update.d.ts +1 -1
  20. package/lib/firebase/helpers/githubAccessHelper.d.ts +3 -3
  21. package/lib/firebase/helpers/githubTeamAccessHelper.d.ts +2 -2
  22. package/lib/firebase/helpers/index.d.ts +1 -1
  23. package/lib/firebase/index.d.ts +1 -1
  24. package/lib/firebase/index.js +3 -3
  25. package/lib/firebase/index.js.map +2 -2
  26. package/lib/firebase/oauth/disconnect.d.ts +1 -1
  27. package/lib/firebase/oauth/exchangeToken.d.ts +1 -1
  28. package/lib/firebase/oauth/getConnections.d.ts +1 -1
  29. package/lib/firebase/oauth/githubAccess.d.ts +6 -6
  30. package/lib/firebase/oauth/index.d.ts +1 -1
  31. package/lib/firebase/oauth/refreshToken.d.ts +1 -1
  32. package/lib/firebase/scheduled/index.d.ts +1 -1
  33. package/lib/shared/billing/createCheckout.d.ts +4 -4
  34. package/lib/shared/billing/helpers/index.d.ts +1 -1
  35. package/lib/shared/billing/helpers/subscriptionManagement.d.ts +3 -3
  36. package/lib/shared/billing/helpers/updateUserSubscription.d.ts +4 -4
  37. package/lib/shared/billing/idempotency.d.ts +2 -2
  38. package/lib/shared/billing/index.d.ts +1 -1
  39. package/lib/shared/billing/webhookHandler.d.ts +1 -1
  40. package/lib/shared/errorHandling.d.ts +1 -1
  41. package/lib/shared/firebase.d.ts +7 -7
  42. package/lib/shared/github.d.ts +11 -11
  43. package/lib/shared/index.d.ts +1 -1
  44. package/lib/shared/index.js +3 -3
  45. package/lib/shared/index.js.map +2 -2
  46. package/lib/shared/logger.d.ts +6 -6
  47. package/lib/shared/metadata.d.ts +3 -3
  48. package/lib/shared/oauth/exchangeToken.d.ts +2 -2
  49. package/lib/shared/oauth/grantAccess.d.ts +2 -2
  50. package/lib/shared/oauth/index.d.ts +1 -1
  51. package/lib/shared/schema.d.ts +2 -2
  52. package/lib/shared/utils/detectFirestore.d.ts +3 -3
  53. package/lib/shared/utils/external/date.d.ts +2 -2
  54. package/lib/shared/utils/external/index.d.ts +1 -1
  55. package/lib/shared/utils/external/references.d.ts +1 -1
  56. package/lib/shared/utils/external/subscription.d.ts +5 -5
  57. package/lib/shared/utils/firebaseHelpers.d.ts +2 -2
  58. package/lib/shared/utils/functionWrapper.d.ts +4 -4
  59. package/lib/shared/utils/index.d.ts +1 -1
  60. package/lib/shared/utils/internal/auth.d.ts +4 -4
  61. package/lib/shared/utils/internal/idempotency.d.ts +2 -2
  62. package/lib/shared/utils/internal/index.d.ts +1 -1
  63. package/lib/shared/utils/internal/monitoring.d.ts +7 -7
  64. package/lib/shared/utils/internal/rateLimiter.d.ts +5 -5
  65. package/lib/shared/utils/internal/validation.d.ts +4 -4
  66. package/lib/shared/utils/schemaValidation.d.ts +6 -6
  67. package/lib/shared/utils/validation.d.ts +9 -9
  68. package/lib/shared/utils/vercelHelpers.d.ts +2 -2
  69. package/lib/shared/utils.d.ts +19 -19
  70. package/lib/shared/validation.d.ts +2 -2
  71. package/lib/supabase/auth/deleteAccount.d.ts +1 -1
  72. package/lib/supabase/auth/getCustomClaims.d.ts +1 -1
  73. package/lib/supabase/auth/getUserAuthStatus.d.ts +1 -1
  74. package/lib/supabase/auth/removeCustomClaims.d.ts +1 -1
  75. package/lib/supabase/auth/setCustomClaims.d.ts +1 -1
  76. package/lib/supabase/baseFunction.d.ts +2 -2
  77. package/lib/supabase/billing/cancelSubscription.d.ts +1 -1
  78. package/lib/supabase/billing/changePlan.d.ts +1 -1
  79. package/lib/supabase/billing/createCheckoutSession.d.ts +1 -1
  80. package/lib/supabase/billing/createCustomerPortal.d.ts +1 -1
  81. package/lib/supabase/billing/refreshSubscriptionStatus.d.ts +1 -1
  82. package/lib/supabase/crud/aggregate.d.ts +1 -1
  83. package/lib/supabase/crud/create.d.ts +1 -1
  84. package/lib/supabase/crud/get.d.ts +1 -1
  85. package/lib/supabase/crud/index.d.ts +1 -1
  86. package/lib/supabase/crud/list.d.ts +1 -1
  87. package/lib/supabase/crud/update.d.ts +1 -1
  88. package/lib/supabase/helpers/authProvider.d.ts +2 -2
  89. package/lib/supabase/index.d.ts +3 -2
  90. package/lib/supabase/index.js +2 -2
  91. package/lib/supabase/index.js.map +4 -4
  92. package/lib/supabase/oauth/disconnect.d.ts +13 -0
  93. package/lib/supabase/oauth/exchangeToken.d.ts +13 -0
  94. package/lib/supabase/oauth/getConnections.d.ts +13 -0
  95. package/lib/supabase/oauth/index.d.ts +12 -0
  96. package/lib/supabase/oauth/refreshToken.d.ts +13 -0
  97. package/lib/supabase/utils/idempotency.d.ts +1 -1
  98. package/lib/supabase/utils/monitoring.d.ts +1 -1
  99. package/lib/supabase/utils/rateLimiter.d.ts +1 -1
  100. package/lib/vercel/api/auth/index.d.ts +1 -1
  101. package/lib/vercel/api/billing/cancel.d.ts +1 -1
  102. package/lib/vercel/api/billing/change-plan.d.ts +1 -1
  103. package/lib/vercel/api/billing/create-checkout-session.d.ts +1 -1
  104. package/lib/vercel/api/billing/index.d.ts +1 -1
  105. package/lib/vercel/api/billing/refresh-subscription-status.d.ts +1 -1
  106. package/lib/vercel/api/billing/webhook-handler.d.ts +2 -2
  107. package/lib/vercel/api/config/constants.d.ts +9 -9
  108. package/lib/vercel/api/config/firebase-admin.d.ts +2 -2
  109. package/lib/vercel/api/config/index.d.ts +1 -1
  110. package/lib/vercel/api/crud/index.d.ts +1 -1
  111. package/lib/vercel/api/index.d.ts +1 -1
  112. package/lib/vercel/api/index.js +2 -2
  113. package/lib/vercel/api/index.js.map +2 -2
  114. package/lib/vercel/api/oauth/check-github-access.d.ts +1 -1
  115. package/lib/vercel/api/oauth/grant-github-access.d.ts +1 -1
  116. package/lib/vercel/api/oauth/index.d.ts +1 -1
  117. package/lib/vercel/api/oauth/revoke-github-access.d.ts +1 -1
  118. package/lib/vercel/api/utils/cors.d.ts +4 -4
  119. package/lib/vercel/baseFunction.d.ts +2 -2
  120. package/package.json +4 -4
  121. package/src/firebase/auth/getCustomClaims.ts +3 -3
  122. package/src/firebase/auth/getUserAuthStatus.ts +3 -3
  123. package/src/firebase/auth/index.ts +1 -1
  124. package/src/firebase/auth/removeCustomClaims.ts +3 -3
  125. package/src/firebase/auth/setCustomClaims.ts +70 -69
  126. package/src/firebase/baseFunction.ts +2 -2
  127. package/src/firebase/billing/cancelSubscription.ts +3 -3
  128. package/src/firebase/billing/changePlan.ts +3 -3
  129. package/src/firebase/billing/createCheckoutSession.ts +1 -1
  130. package/src/firebase/billing/createCustomerPortal.ts +1 -1
  131. package/src/firebase/billing/healthCheck.ts +1 -1
  132. package/src/firebase/billing/index.d.ts +11 -11
  133. package/src/firebase/billing/index.ts +1 -1
  134. package/src/firebase/billing/refreshSubscriptionStatus.ts +3 -3
  135. package/src/firebase/billing/webhookHandler.ts +1 -1
  136. package/src/firebase/config/constants.ts +4 -4
  137. package/src/firebase/config/index.ts +1 -1
  138. package/src/firebase/config/secrets.ts +1 -1
  139. package/src/firebase/crud/aggregate.ts +2 -2
  140. package/src/firebase/crud/create.ts +2 -2
  141. package/src/firebase/crud/delete.ts +3 -3
  142. package/src/firebase/crud/get.ts +1 -1
  143. package/src/firebase/crud/index.ts +1 -1
  144. package/src/firebase/crud/list.ts +1 -1
  145. package/src/firebase/crud/update.ts +2 -2
  146. package/src/firebase/helpers/githubAccessHelper.ts +4 -4
  147. package/src/firebase/helpers/githubTeamAccessHelper.ts +3 -3
  148. package/src/firebase/helpers/index.ts +1 -1
  149. package/src/firebase/index.d.ts +9 -9
  150. package/src/firebase/index.ts +1 -1
  151. package/src/firebase/oauth/disconnect.ts +2 -2
  152. package/src/firebase/oauth/exchangeToken.ts +2 -2
  153. package/src/firebase/oauth/getConnections.ts +2 -2
  154. package/src/firebase/oauth/githubAccess.ts +10 -10
  155. package/src/firebase/oauth/index.ts +1 -1
  156. package/src/firebase/oauth/refreshToken.ts +2 -2
  157. package/src/firebase/registerCrudFunctions.ts +1 -1
  158. package/src/firebase/scheduled/checkExpiredSubscriptions.ts +1 -1
  159. package/src/firebase/scheduled/index.ts +1 -1
  160. package/src/shared/__tests__/auth.test.ts +46 -0
  161. package/src/shared/__tests__/errorHandling.test.ts +66 -1
  162. package/src/shared/__tests__/firebase.test.ts +293 -0
  163. package/src/shared/__tests__/internalValidation.test.ts +190 -0
  164. package/src/shared/__tests__/metadata.test.ts +66 -0
  165. package/src/shared/__tests__/schema.test.ts +219 -0
  166. package/src/shared/__tests__/schemaValidation.test.ts +72 -0
  167. package/src/shared/__tests__/subscription.test.ts +45 -0
  168. package/src/shared/__tests__/utils.test.ts +281 -0
  169. package/src/shared/__tests__/validation-env.test.ts +73 -0
  170. package/src/shared/billing/__tests__/createCheckout.test.ts +1 -1
  171. package/src/shared/billing/__tests__/webhookHandler.test.ts +1 -1
  172. package/src/shared/billing/createCheckout.ts +4 -4
  173. package/src/shared/billing/helpers/index.ts +1 -1
  174. package/src/shared/billing/helpers/subscriptionManagement.ts +4 -4
  175. package/src/shared/billing/helpers/updateUserSubscription.ts +4 -4
  176. package/src/shared/billing/idempotency.ts +4 -4
  177. package/src/shared/billing/index.ts +1 -1
  178. package/src/shared/billing/webhookHandler.ts +7 -7
  179. package/src/shared/errorHandling.ts +2 -2
  180. package/src/shared/firebase.ts +7 -7
  181. package/src/shared/github.ts +11 -11
  182. package/src/shared/index.d.ts +9 -9
  183. package/src/shared/index.ts +1 -1
  184. package/src/shared/logger.ts +8 -8
  185. package/src/shared/metadata.ts +3 -3
  186. package/src/shared/oauth/__tests__/exchangeToken.test.ts +1 -1
  187. package/src/shared/oauth/exchangeToken.ts +2 -2
  188. package/src/shared/oauth/grantAccess.ts +2 -2
  189. package/src/shared/oauth/index.ts +1 -1
  190. package/src/shared/schema.ts +4 -4
  191. package/src/shared/utils/__tests__/functionWrapper.test.ts +1 -1
  192. package/src/shared/utils/detectFirestore.ts +3 -3
  193. package/src/shared/utils/external/date.ts +5 -5
  194. package/src/shared/utils/external/index.ts +1 -1
  195. package/src/shared/utils/external/references.ts +2 -2
  196. package/src/shared/utils/external/subscription.ts +5 -5
  197. package/src/shared/utils/firebaseHelpers.ts +3 -3
  198. package/src/shared/utils/functionWrapper.ts +4 -4
  199. package/src/shared/utils/index.ts +1 -1
  200. package/src/shared/utils/internal/auth.ts +7 -7
  201. package/src/shared/utils/internal/firebase.ts +1 -1
  202. package/src/shared/utils/internal/idempotency.ts +3 -3
  203. package/src/shared/utils/internal/index.ts +1 -1
  204. package/src/shared/utils/internal/monitoring.ts +8 -8
  205. package/src/shared/utils/internal/rateLimiter.ts +6 -6
  206. package/src/shared/utils/internal/validation.ts +5 -5
  207. package/src/shared/utils/schemaValidation.ts +6 -6
  208. package/src/shared/utils/validation.ts +10 -10
  209. package/src/shared/utils/vercelHelpers.ts +3 -3
  210. package/src/shared/utils.ts +19 -19
  211. package/src/shared/validation.ts +2 -2
  212. package/src/supabase/auth/deleteAccount.ts +2 -2
  213. package/src/supabase/auth/getCustomClaims.ts +2 -2
  214. package/src/supabase/auth/getUserAuthStatus.ts +2 -2
  215. package/src/supabase/auth/removeCustomClaims.ts +2 -2
  216. package/src/supabase/auth/setCustomClaims.ts +2 -2
  217. package/src/supabase/baseFunction.ts +3 -3
  218. package/src/supabase/billing/cancelSubscription.ts +2 -2
  219. package/src/supabase/billing/changePlan.ts +2 -2
  220. package/src/supabase/billing/createCheckoutSession.ts +2 -2
  221. package/src/supabase/billing/createCustomerPortal.ts +2 -2
  222. package/src/supabase/billing/refreshSubscriptionStatus.ts +2 -2
  223. package/src/supabase/crud/aggregate.ts +1 -1
  224. package/src/supabase/crud/create.ts +1 -1
  225. package/src/supabase/crud/delete.ts +1 -1
  226. package/src/supabase/crud/get.ts +1 -1
  227. package/src/supabase/crud/index.ts +1 -1
  228. package/src/supabase/crud/list.ts +1 -1
  229. package/src/supabase/crud/update.ts +1 -1
  230. package/src/supabase/helpers/authProvider.ts +2 -2
  231. package/src/supabase/index.ts +10 -2
  232. package/src/supabase/oauth/disconnect.ts +104 -0
  233. package/src/supabase/oauth/exchangeToken.ts +152 -0
  234. package/src/supabase/oauth/getConnections.ts +85 -0
  235. package/src/supabase/oauth/index.ts +15 -0
  236. package/src/supabase/oauth/refreshToken.ts +131 -0
  237. package/src/supabase/registerCrudFunctions.ts +1 -1
  238. package/src/supabase/utils/idempotency.ts +1 -1
  239. package/src/supabase/utils/monitoring.ts +1 -1
  240. package/src/supabase/utils/rateLimiter.ts +1 -1
  241. package/src/vercel/api/auth/get-custom-claims.ts +1 -1
  242. package/src/vercel/api/auth/get-user-auth-status.ts +1 -1
  243. package/src/vercel/api/auth/index.ts +1 -1
  244. package/src/vercel/api/auth/remove-custom-claims.ts +1 -1
  245. package/src/vercel/api/auth/set-custom-claims.ts +2 -4
  246. package/src/vercel/api/billing/cancel.ts +3 -3
  247. package/src/vercel/api/billing/change-plan.ts +3 -3
  248. package/src/vercel/api/billing/create-checkout-session.ts +3 -3
  249. package/src/vercel/api/billing/customer-portal.ts +1 -1
  250. package/src/vercel/api/billing/index.ts +1 -1
  251. package/src/vercel/api/billing/refresh-subscription-status.ts +1 -1
  252. package/src/vercel/api/billing/webhook-handler.ts +3 -3
  253. package/src/vercel/api/config/constants.ts +9 -9
  254. package/src/vercel/api/config/firebase-admin.ts +3 -3
  255. package/src/vercel/api/config/index.ts +1 -1
  256. package/src/vercel/api/crud/create.ts +1 -1
  257. package/src/vercel/api/crud/delete.ts +1 -1
  258. package/src/vercel/api/crud/get.ts +1 -1
  259. package/src/vercel/api/crud/index.ts +1 -1
  260. package/src/vercel/api/crud/list.ts +1 -1
  261. package/src/vercel/api/crud/update.ts +1 -1
  262. package/src/vercel/api/index.d.ts +1 -1
  263. package/src/vercel/api/index.ts +1 -1
  264. package/src/vercel/api/oauth/check-github-access.ts +3 -3
  265. package/src/vercel/api/oauth/exchange-token.ts +1 -1
  266. package/src/vercel/api/oauth/grant-github-access.ts +3 -3
  267. package/src/vercel/api/oauth/index.ts +1 -1
  268. package/src/vercel/api/oauth/revoke-github-access.ts +1 -1
  269. package/src/vercel/api/utils/cors.ts +4 -4
  270. package/src/vercel/baseFunction.ts +2 -2
@@ -0,0 +1,152 @@
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
+ type ExchangeTokenRequest,
18
+ type OAuthPartnerId,
19
+ } from '@donotdev/core/server';
20
+
21
+ import { createSupabaseHandler } from '../baseFunction.js';
22
+ import type { SupabaseHandlerContext } from '../baseFunction.js';
23
+
24
+ /** Cross-runtime env var access (Deno Edge Functions + Node tests) */
25
+ function getEnv(key: string): string | undefined {
26
+ return typeof Deno !== 'undefined'
27
+ ? Deno.env.get(key)
28
+ : process.env[key];
29
+ }
30
+
31
+ declare const Deno:
32
+ | { env: { get(key: string): string | undefined } }
33
+ | undefined;
34
+
35
+ /**
36
+ * Create an OAuth token exchange Edge Function handler
37
+ *
38
+ * @example
39
+ * ```typescript
40
+ * import { createExchangeToken } from '@donotdev/functions/supabase';
41
+ * Deno.serve(createExchangeToken());
42
+ * ```
43
+ *
44
+ * @version 0.1.0
45
+ * @since 0.1.0
46
+ */
47
+ export function createExchangeToken() {
48
+ return createSupabaseHandler(
49
+ 'exchange-token',
50
+ exchangeTokenSchema,
51
+ async (data: ExchangeTokenRequest, ctx: SupabaseHandlerContext) => {
52
+ const { provider, purpose, code, redirectUri, codeVerifier } = data;
53
+
54
+ // Get provider endpoints
55
+ const endpoints = OAUTH_PARTNERS[provider];
56
+ if (!endpoints?.endpoints?.tokenUrl) {
57
+ throw new Error(`Provider ${provider} is not supported`);
58
+ }
59
+
60
+ // Get client credentials from env
61
+ const clientId =
62
+ getEnv(`OAUTH_${provider.toUpperCase()}_CLIENT_ID`);
63
+ const clientSecret =
64
+ getEnv(`OAUTH_${provider.toUpperCase()}_CLIENT_SECRET`);
65
+
66
+ if (!clientId || !clientSecret) {
67
+ throw new Error(`Provider ${provider} is not configured`);
68
+ }
69
+
70
+ // Exchange code for token
71
+ const tokenResponse = await fetch(endpoints.endpoints.tokenUrl, {
72
+ method: 'POST',
73
+ headers: {
74
+ 'Content-Type': 'application/x-www-form-urlencoded',
75
+ Accept: 'application/json',
76
+ },
77
+ body: new URLSearchParams({
78
+ grant_type: 'authorization_code',
79
+ client_id: clientId,
80
+ client_secret: clientSecret,
81
+ code,
82
+ redirect_uri: redirectUri,
83
+ ...(codeVerifier ? { code_verifier: codeVerifier } : {}),
84
+ }).toString(),
85
+ });
86
+
87
+ if (!tokenResponse.ok) {
88
+ const errorText = await tokenResponse.text();
89
+ console.error(
90
+ `Token exchange error for ${provider}: ${tokenResponse.status}`,
91
+ errorText
92
+ );
93
+ throw new Error(
94
+ `Failed to exchange code for token: ${tokenResponse.status}`
95
+ );
96
+ }
97
+
98
+ const tokenData = (await tokenResponse.json()) as any;
99
+
100
+ // Format credentials
101
+ const credentials = {
102
+ accessToken: tokenData.access_token,
103
+ refreshToken: tokenData.refresh_token || null,
104
+ expiresAt: tokenData.expires_in
105
+ ? Math.floor(Date.now() / 1000) + tokenData.expires_in
106
+ : null,
107
+ idToken: tokenData.id_token || null,
108
+ scope: tokenData.scope ? tokenData.scope.split(' ') : [],
109
+ };
110
+
111
+ // Get user profile
112
+ let profile = null;
113
+ if (credentials.accessToken && endpoints.endpoints.profileUrl) {
114
+ try {
115
+ const profileResponse = await fetch(endpoints.endpoints.profileUrl, {
116
+ headers: {
117
+ Authorization: `Bearer ${credentials.accessToken}`,
118
+ Accept: 'application/json',
119
+ },
120
+ });
121
+ if (profileResponse.ok) {
122
+ profile = await profileResponse.json();
123
+ }
124
+ } catch (e) {
125
+ console.warn(`Failed to fetch profile for ${provider}:`, e);
126
+ }
127
+ }
128
+
129
+ // Save connection to Supabase
130
+ const { error: upsertError } = await ctx.supabaseAdmin
131
+ .from('oauth_connections')
132
+ .upsert(
133
+ {
134
+ user_id: ctx.uid,
135
+ provider,
136
+ purpose,
137
+ credentials,
138
+ profile,
139
+ connected: true,
140
+ updated_at: new Date().toISOString(),
141
+ },
142
+ { onConflict: 'user_id,provider,purpose' }
143
+ );
144
+
145
+ if (upsertError) {
146
+ console.error('Error saving OAuth connection:', upsertError);
147
+ }
148
+
149
+ return { success: true, credentials, profile };
150
+ }
151
+ );
152
+ }
@@ -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,131 @@
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
72
+ const clientId =
73
+ getEnv(`OAUTH_${provider.toUpperCase()}_CLIENT_ID`);
74
+ const clientSecret =
75
+ getEnv(`OAUTH_${provider.toUpperCase()}_CLIENT_SECRET`);
76
+
77
+ if (!clientId || !clientSecret) {
78
+ throw new Error(`Provider ${provider} is not configured`);
79
+ }
80
+
81
+ // Refresh the token
82
+ const response = await fetch(endpoints.endpoints.tokenUrl, {
83
+ method: 'POST',
84
+ headers: {
85
+ 'Content-Type': 'application/x-www-form-urlencoded',
86
+ Accept: 'application/json',
87
+ },
88
+ body: new URLSearchParams({
89
+ grant_type: 'refresh_token',
90
+ client_id: clientId,
91
+ client_secret: clientSecret,
92
+ refresh_token: refreshTokenValue,
93
+ redirect_uri: redirectUri,
94
+ }).toString(),
95
+ });
96
+
97
+ if (!response.ok) {
98
+ const errorText = await response.text();
99
+ console.error(`Token refresh error for ${provider}:`, errorText);
100
+ throw new Error(`Failed to refresh token: ${response.status}`);
101
+ }
102
+
103
+ const tokenData = (await response.json()) as any;
104
+
105
+ const credentials = {
106
+ accessToken: tokenData.access_token,
107
+ refreshToken: tokenData.refresh_token || refreshTokenValue,
108
+ expiresAt: tokenData.expires_in
109
+ ? Math.floor(Date.now() / 1000) + tokenData.expires_in
110
+ : null,
111
+ scope: tokenData.scope ? tokenData.scope.split(' ') : [],
112
+ };
113
+
114
+ // Update connection in Supabase
115
+ const { error: updateError } = await ctx.supabaseAdmin
116
+ .from('oauth_connections')
117
+ .update({
118
+ credentials,
119
+ updated_at: new Date().toISOString(),
120
+ })
121
+ .eq('user_id', ctx.uid)
122
+ .eq('provider', provider);
123
+
124
+ if (updateError) {
125
+ console.error('Error updating OAuth connection:', updateError);
126
+ }
127
+
128
+ return { success: true, credentials };
129
+ }
130
+ );
131
+ }
@@ -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
  */
@@ -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
  */
@@ -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
  */
@@ -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
  */
@@ -4,7 +4,7 @@
4
4
  * @fileoverview Set custom claims API handler
5
5
  * @description Vercel API route for setting 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
  */
@@ -74,9 +74,7 @@ export function createSetCustomClaimsHandler(
74
74
  );
75
75
  if (disallowedKeys.length > 0) {
76
76
  throw handleError(
77
- new Error(
78
- `Claim keys not allowed: ${disallowedKeys.join(', ')}`
79
- )
77
+ new Error(`Claim keys not allowed: ${disallowedKeys.join(', ')}`)
80
78
  );
81
79
  }
82
80
 
@@ -4,7 +4,7 @@
4
4
  * @fileoverview Vercel Cancel Subscription Handler
5
5
  * @description Next.js API route wrapper for cancelSubscription
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
  */
@@ -26,7 +26,7 @@ const cancelSubscriptionSchema = v.object({
26
26
  * Business logic for canceling subscription
27
27
  * Base function handles: validation, auth, rate limiting, monitoring
28
28
  *
29
- * @version 0.0.1
29
+ * @version 0.1.0
30
30
  * @since 0.0.1
31
31
  * @author AMBROISE PARK Consulting
32
32
  */
@@ -60,7 +60,7 @@ async function cancelSubscriptionLogic(
60
60
  /**
61
61
  * Cancel subscription function
62
62
  *
63
- * @version 0.0.1
63
+ * @version 0.1.0
64
64
  * @since 0.0.1
65
65
  * @author AMBROISE PARK Consulting
66
66
  */
@@ -4,7 +4,7 @@
4
4
  * @fileoverview Vercel Change Plan Handler
5
5
  * @description Next.js API route wrapper for changePlan
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 @@ const changePlanSchema = v.object({
32
32
  * Business logic for changing subscription plan
33
33
  * Base function handles: validation, auth, rate limiting, monitoring
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
  */
@@ -124,7 +124,7 @@ async function changePlanLogic(
124
124
  /**
125
125
  * Change subscription plan function
126
126
  *
127
- * @version 0.0.1
127
+ * @version 0.1.0
128
128
  * @since 0.0.1
129
129
  * @author AMBROISE PARK Consulting
130
130
  */
@@ -4,7 +4,7 @@
4
4
  * @fileoverview Create checkout session API handler
5
5
  * @description Vercel API route 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
  */
@@ -27,7 +27,7 @@ import type * as v from 'valibot';
27
27
  * Business logic for creating checkout sessions
28
28
  * Base function handles: validation, auth, rate limiting, monitoring
29
29
  *
30
- * @version 0.0.1
30
+ * @version 0.1.0
31
31
  * @since 0.0.1
32
32
  * @author AMBROISE PARK Consulting
33
33
  */
@@ -81,7 +81,7 @@ async function createCheckoutSessionLogic(
81
81
  * Vercel API handler for creating checkout sessions
82
82
  * Base function handles all common concerns automatically
83
83
  *
84
- * @version 0.0.1
84
+ * @version 0.1.0
85
85
  * @since 0.0.1
86
86
  * @author AMBROISE PARK Consulting
87
87
  */
@@ -4,7 +4,7 @@
4
4
  * @fileoverview Vercel Customer Portal Handler
5
5
  * @description Next.js API route wrapper for createCustomerPortal
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 billing barrel exports
5
5
  * @description Centralized exports for Vercel API billing 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 Refresh subscription status API handler
5
5
  * @description Vercel API route for refreshing user subscription 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 Stripe webhook handler API
5
5
  * @description Vercel API route for handling Stripe webhook events
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 { NextApiRequest, NextApiResponse } from 'next';
23
23
  /**
24
24
  * Create Vercel webhook handler from billing config
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
  */
@@ -107,7 +107,7 @@ async function getRawBody(req: NextApiRequest): Promise<Buffer> {
107
107
  /**
108
108
  * Next.js API route configuration
109
109
  *
110
- * @version 0.0.1
110
+ * @version 0.1.0
111
111
  * @since 0.0.1
112
112
  * @author AMBROISE PARK Consulting
113
113
  */