@donotdev/functions 0.3.1 → 0.3.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/guidelines/VERCEL.md +24 -15
- package/lib/chunks/{chunk-2N73OZFE.js → chunk-4BJP372Z.js} +2 -2
- package/lib/chunks/chunk-7T2RZ5A4.js +22 -0
- package/lib/chunks/chunk-7T2RZ5A4.js.map +7 -0
- package/lib/chunks/chunk-CCEGC2T6.js +22 -0
- package/lib/chunks/chunk-CCEGC2T6.js.map +7 -0
- package/lib/chunks/{chunk-DGBZDD6D.js → chunk-IO4MUTT6.js} +2 -2
- package/lib/chunks/chunk-LJXSA7EP.js +151 -0
- package/lib/chunks/chunk-LJXSA7EP.js.map +7 -0
- package/lib/chunks/chunk-MJ5VZTLM.js +22 -0
- package/lib/chunks/chunk-MJ5VZTLM.js.map +7 -0
- package/lib/chunks/chunk-NP4Y2LAO.js +22 -0
- package/lib/chunks/chunk-NP4Y2LAO.js.map +7 -0
- package/lib/chunks/{chunk-XWMG2FWZ.js → chunk-WJUL2W7Y.js} +2 -2
- package/lib/chunks/{chunk-XWMG2FWZ.js.map → chunk-WJUL2W7Y.js.map} +1 -1
- package/lib/chunks/{chunk-ZCY6GTIC.js → chunk-Y6BR2QOV.js} +2 -2
- package/lib/chunks/{chunk-ZCY6GTIC.js.map → chunk-Y6BR2QOV.js.map} +1 -1
- package/lib/chunks/{monitoring-KF7FRUQ6.js → monitoring-B2DYDCYC.js} +2 -2
- package/lib/chunks/{rateLimiter-S7TITXOD.js → rateLimiter-JCBEG33M.js} +2 -2
- package/lib/chunks/{server-SU4BVPPF.js → server-YXYTPMRF.js} +2 -2
- package/lib/firebase/auth/index.d.ts +1 -0
- package/lib/firebase/auth/listAuthUsers.d.ts +24 -0
- package/lib/firebase/billing/cancelSubscription.d.ts +2 -1
- package/lib/firebase/billing/changePlan.d.ts +2 -1
- package/lib/firebase/billing/createCheckoutSession.d.ts +2 -1
- package/lib/firebase/billing/createCustomerPortal.d.ts +4 -0
- package/lib/firebase/billing/healthCheck.d.ts +2 -0
- package/lib/firebase/billing/refreshSubscriptionStatus.d.ts +2 -1
- package/lib/firebase/billing/webhookHandler.d.ts +2 -0
- package/lib/firebase/index.js +1 -1
- package/lib/firebase/index.js.map +4 -4
- package/lib/firebase/oauth/exchangeToken.d.ts +21 -4
- package/lib/firebase/oauth/providerSecrets.d.ts +22 -0
- package/lib/firebase/oauth/refreshToken.d.ts +34 -4
- package/lib/shared/index.js +1 -1
- package/lib/shared/utils.d.ts +5 -27
- package/lib/supabase/auth/listAuthUsers.d.ts +19 -0
- package/lib/supabase/index.d.ts +1 -0
- package/lib/supabase/index.js +1 -1
- package/lib/supabase/index.js.map +4 -4
- package/lib/vercel/api/auth/index.d.ts +3 -3
- package/lib/vercel/api/crud/index.d.ts +6 -6
- package/lib/vercel/api/index.js +1 -1
- package/lib/vercel/api/index.js.map +4 -4
- package/lib/vercel/api/oauth/index.d.ts +4 -4
- package/package.json +5 -5
- package/src/firebase/auth/__tests__/listAuthUsers.test.ts +130 -0
- package/src/firebase/auth/index.ts +1 -0
- package/src/firebase/auth/listAuthUsers.ts +110 -0
- package/src/firebase/billing/__tests__/secretDeclarations.test.ts +55 -0
- package/src/firebase/billing/cancelSubscription.ts +9 -2
- package/src/firebase/billing/changePlan.ts +6 -2
- package/src/firebase/billing/createCheckoutSession.ts +6 -2
- package/src/firebase/billing/createCustomerPortal.ts +8 -1
- package/src/firebase/billing/healthCheck.ts +13 -1
- package/src/firebase/billing/refreshSubscriptionStatus.ts +14 -2
- package/src/firebase/billing/webhookHandler.ts +9 -1
- package/src/firebase/crud/delete.ts +57 -1
- package/src/firebase/oauth/__tests__/tokenFactories.test.ts +99 -0
- package/src/firebase/oauth/exchangeToken.ts +53 -8
- package/src/firebase/oauth/providerSecrets.ts +65 -0
- package/src/firebase/oauth/refreshToken.ts +57 -12
- package/src/shared/email/provider.ts +0 -0
- package/src/shared/email/resendProvider.ts +0 -0
- package/src/shared/utils.ts +5 -75
- package/src/supabase/__tests__/firebaseBoundary.test.ts +53 -0
- package/src/supabase/auth/__tests__/listAuthUsers.test.ts +156 -0
- package/src/supabase/auth/listAuthUsers.ts +98 -0
- package/src/supabase/baseFunction.ts +0 -0
- package/src/supabase/index.ts +1 -0
- package/src/vercel/__tests__/firebaseOptional.test.ts +24 -0
- package/src/vercel/api/auth/index.ts +4 -3
- package/src/vercel/api/crud/index.ts +7 -6
- package/src/vercel/api/oauth/index.ts +5 -4
- package/lib/chunks/chunk-472JD6X7.js +0 -22
- package/lib/chunks/chunk-472JD6X7.js.map +0 -7
- package/lib/chunks/chunk-BTWJEJCV.js +0 -22
- package/lib/chunks/chunk-BTWJEJCV.js.map +0 -7
- package/lib/chunks/chunk-CN6WXKYF.js +0 -22
- package/lib/chunks/chunk-CN6WXKYF.js.map +0 -7
- package/lib/chunks/chunk-GBZQPOX4.js +0 -151
- package/lib/chunks/chunk-GBZQPOX4.js.map +0 -7
- package/lib/chunks/chunk-ORBGTVJI.js +0 -22
- package/lib/chunks/chunk-ORBGTVJI.js.map +0 -7
- package/lib/chunks/chunk-R3I7U5QT.js +0 -22
- package/lib/chunks/chunk-R3I7U5QT.js.map +0 -7
- /package/lib/chunks/{chunk-2N73OZFE.js.map → chunk-4BJP372Z.js.map} +0 -0
- /package/lib/chunks/{chunk-DGBZDD6D.js.map → chunk-IO4MUTT6.js.map} +0 -0
- /package/lib/chunks/{monitoring-KF7FRUQ6.js.map → monitoring-B2DYDCYC.js.map} +0 -0
- /package/lib/chunks/{rateLimiter-S7TITXOD.js.map → rateLimiter-JCBEG33M.js.map} +0 -0
- /package/lib/chunks/{server-SU4BVPPF.js.map → server-YXYTPMRF.js.map} +0 -0
|
@@ -2,14 +2,16 @@
|
|
|
2
2
|
|
|
3
3
|
/**
|
|
4
4
|
* @fileoverview OAuth token exchange Firebase function
|
|
5
|
-
* @description Firebase callable
|
|
5
|
+
* @description Factory for the Firebase callable that exchanges OAuth codes for
|
|
6
|
+
* tokens, for the providers the app enables.
|
|
6
7
|
*
|
|
7
|
-
* @version 0.
|
|
8
|
+
* @version 0.2.0
|
|
8
9
|
* @since 0.0.1
|
|
9
10
|
* @author AMBROISE PARK Consulting
|
|
10
11
|
*/
|
|
11
12
|
|
|
12
13
|
import { onCall, HttpsError } from 'firebase-functions/v2/https';
|
|
14
|
+
import type { CallableFunction } from 'firebase-functions/v2/https';
|
|
13
15
|
|
|
14
16
|
import {
|
|
15
17
|
OAUTH_PARTNERS,
|
|
@@ -22,20 +24,56 @@ import {
|
|
|
22
24
|
} from '@donotdev/firebase/server';
|
|
23
25
|
|
|
24
26
|
import { assertAuthenticated } from '../../shared/utils/internal/auth.js';
|
|
27
|
+
import { defineOAuthProviderSecrets } from './providerSecrets.js';
|
|
25
28
|
|
|
26
29
|
/**
|
|
27
|
-
*
|
|
30
|
+
* Create the callable that exchanges an OAuth authorization code for tokens.
|
|
28
31
|
*
|
|
29
|
-
*
|
|
32
|
+
* Serves only `providers`: it declares `${PROVIDER}_CLIENT_SECRET` for each one
|
|
33
|
+
* (bound at deploy) and rejects a request for any other provider with
|
|
34
|
+
* `invalid-argument`. `${PROVIDER}_CLIENT_ID` stays plain config in functions/.env.
|
|
35
|
+
*
|
|
36
|
+
* @param providers - OAuth partner ids from `OAUTH_PARTNERS` (at least one)
|
|
37
|
+
* @returns The `exchangeToken` callable
|
|
38
|
+
* @throws Error when `providers` is empty or lists an unknown provider
|
|
39
|
+
*
|
|
40
|
+
* @example
|
|
41
|
+
* ```typescript
|
|
42
|
+
* // functions/src/index.ts
|
|
43
|
+
* import { createExchangeToken } from '@donotdev/functions/firebase';
|
|
44
|
+
*
|
|
45
|
+
* export const exchangeToken = createExchangeToken(['github', 'google']);
|
|
46
|
+
* ```
|
|
47
|
+
*
|
|
48
|
+
* @version 0.2.0
|
|
30
49
|
* @since 0.0.1
|
|
31
50
|
* @author AMBROISE PARK Consulting
|
|
32
51
|
*/
|
|
33
|
-
export
|
|
52
|
+
export function createExchangeToken(
|
|
53
|
+
providers: readonly OAuthPartnerId[]
|
|
54
|
+
): CallableFunction<ExchangeTokenRequest, Promise<unknown>> {
|
|
55
|
+
const { allowed, secrets } = defineOAuthProviderSecrets(
|
|
56
|
+
providers,
|
|
57
|
+
'createExchangeToken'
|
|
58
|
+
);
|
|
59
|
+
return onCall<ExchangeTokenRequest>({ secrets }, (request) =>
|
|
60
|
+
exchangeTokenHandler(request.auth?.uid, request.data, allowed)
|
|
61
|
+
);
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* Exchange OAuth authorization code for access token (enabled providers only).
|
|
66
|
+
*/
|
|
67
|
+
async function exchangeTokenHandler(
|
|
68
|
+
authUid: string | undefined,
|
|
69
|
+
data: ExchangeTokenRequest,
|
|
70
|
+
allowed: ReadonlySet<string>
|
|
71
|
+
): Promise<unknown> {
|
|
34
72
|
// Verify authentication
|
|
35
|
-
const uid = assertAuthenticated(
|
|
73
|
+
const uid = assertAuthenticated(authUid);
|
|
36
74
|
|
|
37
75
|
const { provider, purpose, code, redirectUri, codeVerifier, idempotencyKey } =
|
|
38
|
-
|
|
76
|
+
data;
|
|
39
77
|
|
|
40
78
|
// W17: Validate idempotency key length and content.
|
|
41
79
|
if (idempotencyKey !== undefined) {
|
|
@@ -62,6 +100,13 @@ export const exchangeToken = onCall<ExchangeTokenRequest>(async (request) => {
|
|
|
62
100
|
throw new HttpsError('invalid-argument', 'Missing required parameters');
|
|
63
101
|
}
|
|
64
102
|
|
|
103
|
+
if (!allowed.has(provider)) {
|
|
104
|
+
throw new HttpsError(
|
|
105
|
+
'invalid-argument',
|
|
106
|
+
`Provider ${provider} is not enabled`
|
|
107
|
+
);
|
|
108
|
+
}
|
|
109
|
+
|
|
65
110
|
// C9: Atomic idempotency check using Firestore transaction to prevent TOCTOU race.
|
|
66
111
|
// A concurrent request with the same key would see the 'pending' sentinel and wait
|
|
67
112
|
// or return early instead of executing duplicate business logic.
|
|
@@ -203,7 +248,7 @@ export const exchangeToken = onCall<ExchangeTokenRequest>(async (request) => {
|
|
|
203
248
|
: 'Failed to exchange code for token'
|
|
204
249
|
);
|
|
205
250
|
}
|
|
206
|
-
}
|
|
251
|
+
}
|
|
207
252
|
|
|
208
253
|
/**
|
|
209
254
|
* Fetch user profile from OAuth provider
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
// packages/functions/src/firebase/oauth/providerSecrets.ts
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* @fileoverview OAuth provider secrets for the token callables
|
|
5
|
+
* @description Validates the providers an app enables and declares one
|
|
6
|
+
* `${PROVIDER}_CLIENT_SECRET` secret per provider, so the deploy binds exactly
|
|
7
|
+
* those to the function. `${PROVIDER}_CLIENT_ID` is not a secret: it stays
|
|
8
|
+
* plain config in functions/.env.
|
|
9
|
+
*
|
|
10
|
+
* @version 0.1.0
|
|
11
|
+
* @since 0.3.2
|
|
12
|
+
* @author AMBROISE PARK Consulting
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
import { defineSecret } from 'firebase-functions/params';
|
|
16
|
+
import type { SecretParam } from 'firebase-functions/params';
|
|
17
|
+
|
|
18
|
+
import { OAUTH_PARTNERS, type OAuthPartnerId } from '@donotdev/core/server';
|
|
19
|
+
|
|
20
|
+
/** Providers a token callable serves and the secrets it declares for them. */
|
|
21
|
+
export interface OAuthProviderSecrets {
|
|
22
|
+
/** Enabled providers; a request for any other provider is rejected. */
|
|
23
|
+
allowed: ReadonlySet<string>;
|
|
24
|
+
/** One `${PROVIDER}_CLIENT_SECRET` per enabled provider. */
|
|
25
|
+
secrets: SecretParam[];
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Validate the providers a token callable serves and declare their client secrets.
|
|
30
|
+
*
|
|
31
|
+
* @param providers - OAuth partner ids from `OAUTH_PARTNERS` (at least one)
|
|
32
|
+
* @param factory - Factory name, used in error messages
|
|
33
|
+
* @returns Enabled providers and their declared secrets
|
|
34
|
+
* @throws Error when `providers` is empty or lists an id `OAUTH_PARTNERS` does not have
|
|
35
|
+
*
|
|
36
|
+
* @version 0.1.0
|
|
37
|
+
* @since 0.3.2
|
|
38
|
+
* @author AMBROISE PARK Consulting
|
|
39
|
+
*/
|
|
40
|
+
export function defineOAuthProviderSecrets(
|
|
41
|
+
providers: readonly OAuthPartnerId[],
|
|
42
|
+
factory: string
|
|
43
|
+
): OAuthProviderSecrets {
|
|
44
|
+
if (!Array.isArray(providers) || providers.length === 0) {
|
|
45
|
+
throw new Error(
|
|
46
|
+
`${factory}: providers is required and must list at least one OAuth provider (${Object.keys(OAUTH_PARTNERS).join(', ')}).`
|
|
47
|
+
);
|
|
48
|
+
}
|
|
49
|
+
const allowed = new Set<string>();
|
|
50
|
+
for (const provider of providers) {
|
|
51
|
+
if (
|
|
52
|
+
typeof provider !== 'string' ||
|
|
53
|
+
!Object.hasOwn(OAUTH_PARTNERS, provider)
|
|
54
|
+
) {
|
|
55
|
+
throw new Error(
|
|
56
|
+
`${factory}: unknown OAuth provider "${String(provider)}". Known providers: ${Object.keys(OAUTH_PARTNERS).join(', ')}.`
|
|
57
|
+
);
|
|
58
|
+
}
|
|
59
|
+
allowed.add(provider);
|
|
60
|
+
}
|
|
61
|
+
const secrets = [...allowed].map((provider) =>
|
|
62
|
+
defineSecret(`${provider.toUpperCase()}_CLIENT_SECRET`)
|
|
63
|
+
);
|
|
64
|
+
return { allowed, secrets };
|
|
65
|
+
}
|
|
@@ -2,17 +2,20 @@
|
|
|
2
2
|
|
|
3
3
|
/**
|
|
4
4
|
* @fileoverview OAuth token refresh Firebase function
|
|
5
|
-
* @description Firebase callable
|
|
5
|
+
* @description Factory for the Firebase callable that refreshes OAuth tokens,
|
|
6
|
+
* for the providers the app enables.
|
|
6
7
|
*
|
|
7
|
-
* @version 0.
|
|
8
|
+
* @version 0.2.0
|
|
8
9
|
* @since 0.0.1
|
|
9
10
|
* @author AMBROISE PARK Consulting
|
|
10
11
|
*/
|
|
11
12
|
|
|
12
13
|
import { onCall, HttpsError } from 'firebase-functions/v2/https';
|
|
14
|
+
import type { CallableFunction } from 'firebase-functions/v2/https';
|
|
13
15
|
|
|
14
16
|
import {
|
|
15
17
|
OAUTH_PARTNERS,
|
|
18
|
+
type OAuthPartnerId,
|
|
16
19
|
type OAuthRefreshRequest,
|
|
17
20
|
} from '@donotdev/core/server';
|
|
18
21
|
import {
|
|
@@ -21,23 +24,65 @@ import {
|
|
|
21
24
|
} from '@donotdev/firebase/server';
|
|
22
25
|
|
|
23
26
|
import { assertAuthenticated } from '../../shared/utils/internal/auth.js';
|
|
27
|
+
import { defineOAuthProviderSecrets } from './providerSecrets.js';
|
|
24
28
|
|
|
25
29
|
/**
|
|
26
|
-
*
|
|
30
|
+
* Create the callable that refreshes an OAuth token.
|
|
27
31
|
*
|
|
28
|
-
*
|
|
32
|
+
* Serves only `providers`: it declares `${PROVIDER}_CLIENT_SECRET` for each one
|
|
33
|
+
* (bound at deploy) and rejects a request for any other provider with
|
|
34
|
+
* `invalid-argument`. `${PROVIDER}_CLIENT_ID` stays plain config in functions/.env.
|
|
35
|
+
*
|
|
36
|
+
* @param providers - OAuth partner ids from `OAUTH_PARTNERS` (at least one)
|
|
37
|
+
* @returns The `refreshToken` callable
|
|
38
|
+
* @throws Error when `providers` is empty or lists an unknown provider
|
|
39
|
+
*
|
|
40
|
+
* @example
|
|
41
|
+
* ```typescript
|
|
42
|
+
* // functions/src/index.ts
|
|
43
|
+
* import { createRefreshToken } from '@donotdev/functions/firebase';
|
|
44
|
+
*
|
|
45
|
+
* export const refreshToken = createRefreshToken(['github', 'google']);
|
|
46
|
+
* ```
|
|
47
|
+
*
|
|
48
|
+
* @version 0.2.0
|
|
29
49
|
* @since 0.0.1
|
|
30
50
|
* @author AMBROISE PARK Consulting
|
|
31
51
|
*/
|
|
32
|
-
export
|
|
52
|
+
export function createRefreshToken(
|
|
53
|
+
providers: readonly OAuthPartnerId[]
|
|
54
|
+
): CallableFunction<
|
|
55
|
+
OAuthRefreshRequest,
|
|
56
|
+
ReturnType<typeof refreshTokenHandler>
|
|
57
|
+
> {
|
|
58
|
+
const { allowed, secrets } = defineOAuthProviderSecrets(
|
|
59
|
+
providers,
|
|
60
|
+
'createRefreshToken'
|
|
61
|
+
);
|
|
62
|
+
return onCall<OAuthRefreshRequest>({ secrets }, (request) =>
|
|
63
|
+
refreshTokenHandler(request.auth?.uid, request.data, allowed)
|
|
64
|
+
);
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Refresh an OAuth token (enabled providers only).
|
|
69
|
+
*/
|
|
70
|
+
async function refreshTokenHandler(
|
|
71
|
+
authUid: string | undefined,
|
|
72
|
+
data: OAuthRefreshRequest,
|
|
73
|
+
allowed: ReadonlySet<string>
|
|
74
|
+
) {
|
|
33
75
|
// Verify authentication
|
|
34
|
-
const uid = assertAuthenticated(
|
|
76
|
+
const uid = assertAuthenticated(authUid);
|
|
77
|
+
|
|
78
|
+
const { provider, refreshToken: refreshTokenValue, redirectUri } = data;
|
|
35
79
|
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
80
|
+
if (!allowed.has(provider)) {
|
|
81
|
+
throw new HttpsError(
|
|
82
|
+
'invalid-argument',
|
|
83
|
+
`Provider ${provider} is not enabled`
|
|
84
|
+
);
|
|
85
|
+
}
|
|
41
86
|
|
|
42
87
|
try {
|
|
43
88
|
// Get provider endpoints
|
|
@@ -146,4 +191,4 @@ export const refreshToken = onCall<OAuthRefreshRequest>(async (request) => {
|
|
|
146
191
|
error instanceof Error ? error.message : 'Failed to refresh token'
|
|
147
192
|
);
|
|
148
193
|
}
|
|
149
|
-
}
|
|
194
|
+
}
|
|
File without changes
|
|
File without changes
|
package/src/shared/utils.ts
CHANGED
|
@@ -1,8 +1,11 @@
|
|
|
1
1
|
// packages/functions/src/shared/utils.ts
|
|
2
2
|
|
|
3
3
|
/**
|
|
4
|
-
* @fileoverview Shared utilities for Firebase and
|
|
5
|
-
* @description Common utilities
|
|
4
|
+
* @fileoverview Shared utilities for Firebase, Vercel and Supabase functions
|
|
5
|
+
* @description Common utilities for every function implementation. Provider-neutral:
|
|
6
|
+
* Supabase Edge Functions import this module, and the edge bundler resolves every
|
|
7
|
+
* import in it (even a lazy `import()` that is never called). Firebase-only code
|
|
8
|
+
* lives under `firebase/`.
|
|
6
9
|
*
|
|
7
10
|
* @version 0.1.0
|
|
8
11
|
* @since 0.0.1
|
|
@@ -133,76 +136,3 @@ export function validateCollectionName(name: string): void {
|
|
|
133
136
|
);
|
|
134
137
|
}
|
|
135
138
|
}
|
|
136
|
-
|
|
137
|
-
/**
|
|
138
|
-
* Verifies Firebase auth token
|
|
139
|
-
*
|
|
140
|
-
* @version 0.1.0
|
|
141
|
-
* @since 0.0.1
|
|
142
|
-
* @author AMBROISE PARK Consulting
|
|
143
|
-
*/
|
|
144
|
-
export async function verifyFirebaseAuthToken(token: string): Promise<string> {
|
|
145
|
-
if (!token) {
|
|
146
|
-
throw new DoNotDevError('Missing authentication token', 'unauthenticated');
|
|
147
|
-
}
|
|
148
|
-
|
|
149
|
-
// Lazy: the Vercel/Supabase entries must load without firebase-admin
|
|
150
|
-
const { getFirebaseAdminAuth } = await import('@donotdev/firebase/server');
|
|
151
|
-
try {
|
|
152
|
-
const decodedToken = await getFirebaseAdminAuth().verifyIdToken(token);
|
|
153
|
-
return decodedToken.uid;
|
|
154
|
-
} catch (error) {
|
|
155
|
-
throw new DoNotDevError('Invalid or expired token', 'unauthenticated');
|
|
156
|
-
}
|
|
157
|
-
}
|
|
158
|
-
|
|
159
|
-
/**
|
|
160
|
-
* Finds references to a document
|
|
161
|
-
*
|
|
162
|
-
* @version 0.1.0
|
|
163
|
-
* @since 0.0.1
|
|
164
|
-
* @author AMBROISE PARK Consulting
|
|
165
|
-
*/
|
|
166
|
-
export async function findReferences(
|
|
167
|
-
collection: string,
|
|
168
|
-
docId: string,
|
|
169
|
-
referenceMetadata?: {
|
|
170
|
-
incoming?: Array<{
|
|
171
|
-
sourceCollection: string;
|
|
172
|
-
sourceField: string;
|
|
173
|
-
}>;
|
|
174
|
-
}
|
|
175
|
-
): Promise<Array<{ collection: string; field: string; count: number }>> {
|
|
176
|
-
const references: Array<{
|
|
177
|
-
collection: string;
|
|
178
|
-
field: string;
|
|
179
|
-
count: number;
|
|
180
|
-
}> = [];
|
|
181
|
-
|
|
182
|
-
if (!referenceMetadata?.incoming?.length) {
|
|
183
|
-
return references;
|
|
184
|
-
}
|
|
185
|
-
|
|
186
|
-
// Lazy: the Vercel/Supabase entries must load without firebase-admin
|
|
187
|
-
const { getFirebaseAdminFirestore } =
|
|
188
|
-
await import('@donotdev/firebase/server');
|
|
189
|
-
const db = getFirebaseAdminFirestore();
|
|
190
|
-
|
|
191
|
-
for (const ref of referenceMetadata.incoming) {
|
|
192
|
-
const snapshot = await db
|
|
193
|
-
.collection(ref.sourceCollection)
|
|
194
|
-
.where(ref.sourceField, '==', docId)
|
|
195
|
-
.limit(1)
|
|
196
|
-
.get();
|
|
197
|
-
|
|
198
|
-
if (!snapshot.empty) {
|
|
199
|
-
references.push({
|
|
200
|
-
collection: ref.sourceCollection,
|
|
201
|
-
field: ref.sourceField,
|
|
202
|
-
count: snapshot.size,
|
|
203
|
-
});
|
|
204
|
-
}
|
|
205
|
-
}
|
|
206
|
-
|
|
207
|
-
return references;
|
|
208
|
-
}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
// packages/functions/src/supabase/__tests__/firebaseBoundary.test.ts
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* @fileoverview Regression test: the Supabase entry never references Firebase
|
|
5
|
+
* @description A Supabase app does not install `@donotdev/firebase`,
|
|
6
|
+
* `firebase-admin` or `firebase-functions`. The edge bundler (esbuild) resolves
|
|
7
|
+
* every import reachable from `@donotdev/functions/supabase`, a lazy `import()`
|
|
8
|
+
* included, even one that is never called: a single Firebase specifier anywhere
|
|
9
|
+
* in that graph fails every edge function with `Could not resolve
|
|
10
|
+
* "@donotdev/firebase/server"` (shared/utils.ts did this through
|
|
11
|
+
* `verifyFirebaseAuthToken`). Module mocks cannot see an unexecuted `import()`,
|
|
12
|
+
* so this test walks the import graph with esbuild, as the edge bundler does.
|
|
13
|
+
*
|
|
14
|
+
* @version 0.1.0
|
|
15
|
+
* @since 0.3.3
|
|
16
|
+
* @author AMBROISE PARK Consulting
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
import { fileURLToPath } from 'node:url';
|
|
20
|
+
|
|
21
|
+
import { build } from 'esbuild';
|
|
22
|
+
import { describe, expect, it } from 'vitest';
|
|
23
|
+
|
|
24
|
+
const FIREBASE = /^(@donotdev\/firebase|firebase-admin|firebase-functions)(\/|$)/;
|
|
25
|
+
|
|
26
|
+
describe('supabase entry without firebase', () => {
|
|
27
|
+
it('reaches no Firebase specifier, static or dynamic', async () => {
|
|
28
|
+
const hits: string[] = [];
|
|
29
|
+
await build({
|
|
30
|
+
entryPoints: [fileURLToPath(new URL('../index.ts', import.meta.url))],
|
|
31
|
+
bundle: true,
|
|
32
|
+
write: false,
|
|
33
|
+
format: 'esm',
|
|
34
|
+
platform: 'neutral',
|
|
35
|
+
logLevel: 'silent',
|
|
36
|
+
plugins: [
|
|
37
|
+
{
|
|
38
|
+
name: 'record-firebase',
|
|
39
|
+
setup(pluginBuild) {
|
|
40
|
+
// Follow the package's own (relative) modules; record Firebase, keep other packages out
|
|
41
|
+
pluginBuild.onResolve({ filter: /^[^./]/ }, (args) => {
|
|
42
|
+
if (FIREBASE.test(args.path)) {
|
|
43
|
+
hits.push(`${args.path} (${args.kind}) from ${args.importer}`);
|
|
44
|
+
}
|
|
45
|
+
return { path: args.path, external: true };
|
|
46
|
+
});
|
|
47
|
+
},
|
|
48
|
+
},
|
|
49
|
+
],
|
|
50
|
+
});
|
|
51
|
+
expect(hits).toEqual([]);
|
|
52
|
+
}, 60_000);
|
|
53
|
+
});
|
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview Unit tests for `createListAuthUsers` (Supabase).
|
|
3
|
+
* @description Runs the real `createSupabaseHandler`: a non-admin gets 403 and no
|
|
4
|
+
* listing; an admin gets every page of `auth.admin.listUsers`, mapped.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
|
|
8
|
+
|
|
9
|
+
const getUser = vi.fn();
|
|
10
|
+
const listUsers = vi.fn();
|
|
11
|
+
|
|
12
|
+
vi.mock('@supabase/supabase-js', () => ({
|
|
13
|
+
createClient: vi.fn(() => ({
|
|
14
|
+
auth: { getUser, admin: { listUsers } },
|
|
15
|
+
})),
|
|
16
|
+
}));
|
|
17
|
+
|
|
18
|
+
import { createListAuthUsers } from '../listAuthUsers.js';
|
|
19
|
+
|
|
20
|
+
const ENV = {
|
|
21
|
+
SUPABASE_URL: 'https://example.supabase.co',
|
|
22
|
+
SUPABASE_SECRET_KEY: 'secret',
|
|
23
|
+
DISABLE_RATE_LIMITING: 'true',
|
|
24
|
+
};
|
|
25
|
+
|
|
26
|
+
function request(): Request {
|
|
27
|
+
return new Request(
|
|
28
|
+
'https://example.supabase.co/functions/v1/list-auth-users',
|
|
29
|
+
{
|
|
30
|
+
method: 'POST',
|
|
31
|
+
headers: {
|
|
32
|
+
authorization: 'Bearer token',
|
|
33
|
+
'content-type': 'application/json',
|
|
34
|
+
},
|
|
35
|
+
body: '{}',
|
|
36
|
+
}
|
|
37
|
+
);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function caller(role?: string) {
|
|
41
|
+
getUser.mockResolvedValue({
|
|
42
|
+
data: { user: { id: 'caller', app_metadata: role ? { role } : {} } },
|
|
43
|
+
error: null,
|
|
44
|
+
});
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** A GoTrue user; `n` makes ids unique. */
|
|
48
|
+
function authUser(n: number, extra: Record<string, unknown> = {}) {
|
|
49
|
+
return {
|
|
50
|
+
id: `u${n}`,
|
|
51
|
+
email: `u${n}@example.com`,
|
|
52
|
+
created_at: '2026-01-01T00:00:00Z',
|
|
53
|
+
user_metadata: {},
|
|
54
|
+
app_metadata: {},
|
|
55
|
+
...extra,
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function page(users: unknown[]) {
|
|
60
|
+
return { data: { users, aud: 'authenticated' }, error: null };
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
describe('createListAuthUsers', () => {
|
|
64
|
+
beforeEach(() => {
|
|
65
|
+
getUser.mockReset();
|
|
66
|
+
listUsers.mockReset();
|
|
67
|
+
Object.assign(process.env, ENV);
|
|
68
|
+
vi.spyOn(console, 'error').mockImplementation(() => {});
|
|
69
|
+
});
|
|
70
|
+
afterEach(() => {
|
|
71
|
+
for (const key of Object.keys(ENV)) delete process.env[key];
|
|
72
|
+
vi.restoreAllMocks();
|
|
73
|
+
});
|
|
74
|
+
|
|
75
|
+
it.each([undefined, 'user'])(
|
|
76
|
+
'refuses a non-admin caller (role %s) with 403',
|
|
77
|
+
async (role) => {
|
|
78
|
+
caller(role);
|
|
79
|
+
const res = await createListAuthUsers()(request());
|
|
80
|
+
expect(res.status).toBe(403);
|
|
81
|
+
expect(listUsers).not.toHaveBeenCalled();
|
|
82
|
+
}
|
|
83
|
+
);
|
|
84
|
+
|
|
85
|
+
it('pages through every page (perPage 1000) until a short page', async () => {
|
|
86
|
+
caller('admin');
|
|
87
|
+
const full = Array.from({ length: 1000 }, (_, i) => authUser(i));
|
|
88
|
+
listUsers
|
|
89
|
+
.mockResolvedValueOnce(page(full))
|
|
90
|
+
.mockResolvedValueOnce(page([authUser(1000)]));
|
|
91
|
+
const res = await createListAuthUsers()(request());
|
|
92
|
+
expect(res.status).toBe(200);
|
|
93
|
+
const { users } = (await res.json()) as { users: { id: string }[] };
|
|
94
|
+
expect(users).toHaveLength(1001);
|
|
95
|
+
expect(users[1000]!.id).toBe('u1000');
|
|
96
|
+
expect(listUsers.mock.calls).toEqual([
|
|
97
|
+
[{ page: 1, perPage: 1000 }],
|
|
98
|
+
[{ page: 2, perPage: 1000 }],
|
|
99
|
+
]);
|
|
100
|
+
});
|
|
101
|
+
|
|
102
|
+
it('maps the user (displayName: full_name, then name; nulls when absent)', async () => {
|
|
103
|
+
caller('super');
|
|
104
|
+
listUsers.mockResolvedValueOnce(
|
|
105
|
+
page([
|
|
106
|
+
authUser(1, {
|
|
107
|
+
email_confirmed_at: '2026-01-02T00:00:00Z',
|
|
108
|
+
last_sign_in_at: '2026-01-03T00:00:00Z',
|
|
109
|
+
user_metadata: { full_name: 'Ana', name: 'ignored' },
|
|
110
|
+
}),
|
|
111
|
+
authUser(2, { email: undefined, user_metadata: { name: 'Bo' } }),
|
|
112
|
+
authUser(3, { user_metadata: { full_name: 42 } }),
|
|
113
|
+
])
|
|
114
|
+
);
|
|
115
|
+
const res = await createListAuthUsers()(request());
|
|
116
|
+
expect(await res.json()).toEqual({
|
|
117
|
+
users: [
|
|
118
|
+
{
|
|
119
|
+
id: 'u1',
|
|
120
|
+
email: 'u1@example.com',
|
|
121
|
+
emailConfirmedAt: '2026-01-02T00:00:00Z',
|
|
122
|
+
createdAt: '2026-01-01T00:00:00Z',
|
|
123
|
+
lastSignInAt: '2026-01-03T00:00:00Z',
|
|
124
|
+
displayName: 'Ana',
|
|
125
|
+
},
|
|
126
|
+
{
|
|
127
|
+
id: 'u2',
|
|
128
|
+
email: null,
|
|
129
|
+
emailConfirmedAt: null,
|
|
130
|
+
createdAt: '2026-01-01T00:00:00Z',
|
|
131
|
+
lastSignInAt: null,
|
|
132
|
+
displayName: 'Bo',
|
|
133
|
+
},
|
|
134
|
+
{
|
|
135
|
+
id: 'u3',
|
|
136
|
+
email: 'u3@example.com',
|
|
137
|
+
emailConfirmedAt: null,
|
|
138
|
+
createdAt: '2026-01-01T00:00:00Z',
|
|
139
|
+
lastSignInAt: null,
|
|
140
|
+
displayName: null,
|
|
141
|
+
},
|
|
142
|
+
],
|
|
143
|
+
});
|
|
144
|
+
});
|
|
145
|
+
|
|
146
|
+
it('fails (500, generic message) when Supabase returns an error', async () => {
|
|
147
|
+
caller('admin');
|
|
148
|
+
listUsers.mockResolvedValueOnce({
|
|
149
|
+
data: { users: [] },
|
|
150
|
+
error: new Error('db down'),
|
|
151
|
+
});
|
|
152
|
+
const res = await createListAuthUsers()(request());
|
|
153
|
+
expect(res.status).toBe(500);
|
|
154
|
+
expect(await res.json()).toEqual({ error: 'Internal server error' });
|
|
155
|
+
});
|
|
156
|
+
});
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
// packages/functions/src/supabase/auth/listAuthUsers.ts
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* @fileoverview List Auth Users Supabase Edge Function
|
|
5
|
+
* @description Admin-only: lists every auth account (email, confirmation, sign-in dates)
|
|
6
|
+
* straight from Supabase Auth (`auth.admin.listUsers`). No view, no copied table.
|
|
7
|
+
*
|
|
8
|
+
* @version 0.1.0
|
|
9
|
+
* @since 0.3.3
|
|
10
|
+
* @author AMBROISE PARK Consulting
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
import type { User } from '@supabase/supabase-js';
|
|
14
|
+
import * as v from 'valibot';
|
|
15
|
+
|
|
16
|
+
import type {
|
|
17
|
+
AuthUserSummary,
|
|
18
|
+
ListAuthUsersResponse,
|
|
19
|
+
} from '@donotdev/core/server';
|
|
20
|
+
|
|
21
|
+
import { createSupabaseHandler } from '../baseFunction.js';
|
|
22
|
+
|
|
23
|
+
// =============================================================================
|
|
24
|
+
// Schema
|
|
25
|
+
// =============================================================================
|
|
26
|
+
|
|
27
|
+
const listAuthUsersSchema = v.object({});
|
|
28
|
+
|
|
29
|
+
/** Page size of `auth.admin.listUsers` (the GoTrue maximum). */
|
|
30
|
+
const PER_PAGE = 1000;
|
|
31
|
+
|
|
32
|
+
// =============================================================================
|
|
33
|
+
// Mapping
|
|
34
|
+
// =============================================================================
|
|
35
|
+
|
|
36
|
+
/** A user_metadata value when it is a string. */
|
|
37
|
+
function metaString(meta: Record<string, unknown>, key: string): string | null {
|
|
38
|
+
const value = meta[key];
|
|
39
|
+
return typeof value === 'string' ? value : null;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Map a Supabase auth user to an {@link AuthUserSummary}. `displayName` reads
|
|
44
|
+
* `user_metadata.full_name`, then `name`, like the Supabase client provider.
|
|
45
|
+
*/
|
|
46
|
+
function toAuthUserSummary(user: User): AuthUserSummary {
|
|
47
|
+
const meta = (user.user_metadata ?? {}) as Record<string, unknown>;
|
|
48
|
+
return {
|
|
49
|
+
id: user.id,
|
|
50
|
+
email: user.email ?? null,
|
|
51
|
+
emailConfirmedAt: user.email_confirmed_at ?? null,
|
|
52
|
+
createdAt: user.created_at,
|
|
53
|
+
lastSignInAt: user.last_sign_in_at ?? null,
|
|
54
|
+
displayName: metaString(meta, 'full_name') ?? metaString(meta, 'name'),
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
// =============================================================================
|
|
59
|
+
// Handler
|
|
60
|
+
// =============================================================================
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* Create the admin-only Supabase Edge Function handler that lists every auth user.
|
|
64
|
+
* Pages through `auth.admin.listUsers` (1000 per page) until the last page.
|
|
65
|
+
* Callers without `app_metadata.role` admin (or super) get 403.
|
|
66
|
+
* Client side: `useAuthUsers()` / `useAuth('listUsers')` from `@donotdev/auth`.
|
|
67
|
+
*
|
|
68
|
+
* @returns `(req: Request) => Promise<Response>` handler answering `{ users }`
|
|
69
|
+
*
|
|
70
|
+
* @example
|
|
71
|
+
* ```typescript
|
|
72
|
+
* // supabase/functions/list-auth-users/index.ts
|
|
73
|
+
* import { createListAuthUsers } from '@donotdev/functions/supabase';
|
|
74
|
+
* Deno.serve(createListAuthUsers());
|
|
75
|
+
* ```
|
|
76
|
+
*
|
|
77
|
+
* @version 0.1.0
|
|
78
|
+
* @since 0.3.3
|
|
79
|
+
*/
|
|
80
|
+
export function createListAuthUsers(): (req: Request) => Promise<Response> {
|
|
81
|
+
return createSupabaseHandler(
|
|
82
|
+
'list-auth-users',
|
|
83
|
+
listAuthUsersSchema,
|
|
84
|
+
async (_data, ctx): Promise<ListAuthUsersResponse> => {
|
|
85
|
+
const users: AuthUserSummary[] = [];
|
|
86
|
+
for (let page = 1; ; page++) {
|
|
87
|
+
const { data, error } = await ctx.supabaseAdmin.auth.admin.listUsers({
|
|
88
|
+
page,
|
|
89
|
+
perPage: PER_PAGE,
|
|
90
|
+
});
|
|
91
|
+
if (error) throw error;
|
|
92
|
+
users.push(...data.users.map(toAuthUserSummary));
|
|
93
|
+
if (data.users.length < PER_PAGE) return { users };
|
|
94
|
+
}
|
|
95
|
+
},
|
|
96
|
+
'admin'
|
|
97
|
+
);
|
|
98
|
+
}
|
|
File without changes
|
package/src/supabase/index.ts
CHANGED
|
@@ -29,6 +29,7 @@ export type { SetCustomClaimsOptions } from './auth/setCustomClaims.js';
|
|
|
29
29
|
export { createGetCustomClaims } from './auth/getCustomClaims.js';
|
|
30
30
|
export { createRemoveCustomClaims } from './auth/removeCustomClaims.js';
|
|
31
31
|
export { createGetUserAuthStatus } from './auth/getUserAuthStatus.js';
|
|
32
|
+
export { createListAuthUsers } from './auth/listAuthUsers.js';
|
|
32
33
|
|
|
33
34
|
// Billing
|
|
34
35
|
export { createCheckoutSession } from './billing/createCheckoutSession.js';
|