@donotdev/functions 0.2.2 → 0.3.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.
- package/README.md +1 -1
- package/lib/chunks/chunk-522YXGDA.js +23 -0
- package/lib/chunks/chunk-522YXGDA.js.map +7 -0
- package/lib/chunks/chunk-7ODXXXES.js +151 -0
- package/lib/chunks/chunk-7ODXXXES.js.map +7 -0
- package/lib/chunks/chunk-CP3NNKO5.js +22 -0
- package/lib/chunks/chunk-CP3NNKO5.js.map +7 -0
- package/lib/chunks/{chunk-2A4FPYNB.js → chunk-CVYSXC27.js} +2 -2
- package/lib/chunks/chunk-CVYSXC27.js.map +7 -0
- package/lib/chunks/{chunk-PJCJ5H2O.js → chunk-HZM5X5A7.js} +2 -2
- package/lib/chunks/chunk-ICNQCRLV.js +22 -0
- package/lib/chunks/chunk-ICNQCRLV.js.map +7 -0
- package/lib/chunks/chunk-OAZ2JYSD.js +22 -0
- package/lib/chunks/chunk-OAZ2JYSD.js.map +7 -0
- package/lib/chunks/chunk-OKRR7ST5.js +22 -0
- package/lib/chunks/chunk-OKRR7ST5.js.map +7 -0
- package/lib/chunks/chunk-PDBNKSBQ.js +22 -0
- package/lib/chunks/chunk-PDBNKSBQ.js.map +7 -0
- package/lib/chunks/chunk-TJPJXJEK.js +22 -0
- package/lib/chunks/{chunk-OZX5ZG44.js.map → chunk-TJPJXJEK.js.map} +1 -1
- package/lib/chunks/chunk-W6W4L44F.js +22 -0
- package/lib/chunks/chunk-W6W4L44F.js.map +7 -0
- package/lib/chunks/{monitoring-UIDJS2KA.js → monitoring-UCBNPPW2.js} +2 -2
- package/lib/chunks/{rateLimiter-WNWHI3B4.js → rateLimiter-XKECWM33.js} +2 -2
- package/lib/chunks/{server-RYGEBS2B.js → server-24XGDDO3.js} +2 -2
- package/lib/firebase/auth/removeCustomClaims.d.ts +1 -1
- package/lib/firebase/crud/aggregate.d.ts +1 -1
- package/lib/firebase/crud/create.d.ts +22 -1
- package/lib/firebase/crud/update.d.ts +27 -3
- package/lib/firebase/index.js +1 -1
- package/lib/firebase/index.js.map +3 -3
- package/lib/shared/billing/checkoutValidation.d.ts +1 -1
- package/lib/shared/billing/createCheckout.d.ts +1 -1
- package/lib/shared/billing/helpers/subscriptionManagement.d.ts +2 -2
- package/lib/shared/billing/helpers/updateUserSubscription.d.ts +2 -8
- package/lib/shared/billing/index.d.ts +2 -0
- package/lib/shared/billing/orderWebhook.d.ts +29 -2
- package/lib/shared/billing/stripePinned.d.ts +43 -0
- package/lib/shared/billing/verifyOrderCheckout.d.ts +53 -0
- package/lib/shared/crud/bulkCore.d.ts +38 -10
- package/lib/shared/crud/index.d.ts +1 -0
- package/lib/shared/crud/written.d.ts +21 -0
- package/lib/shared/denoEnv.d.ts +25 -0
- package/lib/shared/github.d.ts +0 -8
- package/lib/shared/index.d.ts +0 -1
- package/lib/shared/index.js +1 -1
- package/lib/shared/logger.d.ts +14 -14
- package/lib/shared/utils/external/subscription.d.ts +0 -8
- package/lib/shared/utils.d.ts +13 -10
- package/lib/supabase/auth/deleteAccount.d.ts +34 -2
- package/lib/supabase/crud/bulk.d.ts +7 -0
- package/lib/supabase/crud/create.d.ts +5 -9
- package/lib/supabase/crud/entityStore.d.ts +67 -14
- package/lib/supabase/crud/update.d.ts +7 -10
- package/lib/supabase/index.d.ts +5 -0
- package/lib/supabase/index.js +1 -1
- package/lib/supabase/index.js.map +4 -4
- package/lib/vercel/api/crud/create.d.ts +6 -1
- package/lib/vercel/api/crud/update.d.ts +8 -1
- package/lib/vercel/api/index.js +1 -1
- package/lib/vercel/api/index.js.map +3 -3
- package/package.json +9 -9
- package/src/firebase/auth/getCustomClaims.ts +2 -0
- package/src/firebase/auth/getUserAuthStatus.ts +2 -0
- package/src/firebase/auth/removeCustomClaims.ts +33 -1
- package/src/firebase/auth/setCustomClaims.ts +6 -0
- package/src/firebase/baseFunction.ts +5 -2
- package/src/firebase/billing/changePlan.ts +6 -5
- package/src/firebase/billing/createCustomerPortal.ts +6 -4
- package/src/firebase/billing/refreshSubscriptionStatus.ts +7 -5
- package/src/firebase/billing/webhookHandler.ts +4 -4
- package/src/firebase/crud/__tests__/bulk.test.ts +50 -1
- package/src/firebase/crud/__tests__/create.test.ts +64 -0
- package/src/firebase/crud/__tests__/update.test.ts +97 -0
- package/src/firebase/crud/aggregate.ts +37 -19
- package/src/firebase/crud/bulk.ts +30 -10
- package/src/firebase/crud/create.ts +40 -26
- package/src/firebase/crud/delete.ts +6 -1
- package/src/firebase/crud/get.ts +12 -14
- package/src/firebase/crud/list.ts +23 -12
- package/src/firebase/crud/update.ts +49 -25
- package/src/firebase/helpers/githubAccessHelper.ts +3 -0
- package/src/firebase/helpers/githubTeamAccessHelper.ts +1 -0
- package/src/firebase/oauth/exchangeToken.ts +4 -0
- package/src/firebase/oauth/getConnections.ts +1 -1
- package/src/firebase/oauth/githubAccess.ts +3 -0
- package/src/firebase/oauth/refreshToken.ts +1 -0
- package/src/firebase/registerCrudFunctions.ts +1 -0
- package/src/firebase/scheduled/checkExpiredSubscriptions.ts +4 -1
- package/src/shared/__tests__/bulkCore.test.ts +191 -0
- package/src/shared/__tests__/removeCustomClaims.test.ts +117 -0
- package/src/shared/__tests__/setCustomClaims.test.ts +103 -0
- package/src/shared/__tests__/utils.test.ts +0 -30
- package/src/shared/ai/classifyAIError.ts +18 -10
- package/src/shared/ai/createAIRoute.ts +2 -1
- package/src/shared/ai/resolveModelTier.ts +2 -1
- package/src/shared/billing/__tests__/createCheckout.test.ts +94 -0
- package/src/shared/billing/__tests__/firestoreIdempotency.emulator.test.ts +1 -1
- package/src/shared/billing/__tests__/updateUserSubscription.test.ts +139 -0
- package/src/shared/billing/__tests__/verifyOrderCheckout.exports.test.ts +47 -0
- package/src/shared/billing/__tests__/verifyOrderCheckout.supabase.integration.test.ts +107 -0
- package/src/shared/billing/__tests__/verifyOrderCheckout.test.ts +233 -0
- package/src/shared/billing/__tests__/webhookHandler.test.ts +108 -0
- package/src/shared/billing/checkoutValidation.ts +19 -2
- package/src/shared/billing/createCheckout.ts +56 -11
- package/src/shared/billing/helpers/subscriptionManagement.ts +14 -10
- package/src/shared/billing/helpers/updateUserSubscription.ts +10 -14
- package/src/shared/billing/index.ts +2 -0
- package/src/shared/billing/orderWebhook.ts +69 -1
- package/src/shared/billing/stripeClient.ts +2 -1
- package/src/shared/billing/stripePinned.ts +71 -0
- package/src/shared/billing/tierWebhookEvents.ts +3 -2
- package/src/shared/billing/verifyOrderCheckout.ts +142 -0
- package/src/shared/billing/webhookHandler.ts +5 -1
- package/src/shared/crud/bulkCore.ts +112 -82
- package/src/shared/crud/index.ts +1 -0
- package/src/shared/crud/written.ts +56 -0
- package/src/shared/denoEnv.ts +29 -0
- package/src/shared/email/createEmailRoute.ts +2 -2
- package/src/shared/errorHandling.ts +8 -8
- package/src/shared/firebase.ts +26 -9
- package/src/shared/github.ts +15 -5
- package/src/shared/index.d.ts +0 -9
- package/src/shared/index.ts +0 -1
- package/src/shared/logger.ts +37 -38
- package/src/shared/utils/external/date.ts +4 -4
- package/src/shared/utils/external/subscription.ts +2 -89
- package/src/shared/utils/firebaseHelpers.ts +2 -0
- package/src/shared/utils/internal/idempotency.ts +3 -0
- package/src/shared/utils/internal/monitoring.ts +6 -5
- package/src/shared/utils/internal/validation.ts +2 -0
- package/src/shared/utils/schemaValidation.ts +1 -0
- package/src/shared/utils/validation.ts +10 -20
- package/src/shared/utils.ts +4 -42
- package/src/supabase/__tests__/aggregate.test.ts +132 -0
- package/src/supabase/__tests__/bulk.test.ts +60 -2
- package/src/supabase/__tests__/create.test.ts +86 -0
- package/src/supabase/__tests__/entityStore.test.ts +91 -25
- package/src/supabase/__tests__/update.test.ts +107 -0
- package/src/supabase/auth/__tests__/deleteAccount.test.ts +102 -0
- package/src/supabase/auth/deleteAccount.ts +72 -5
- package/src/supabase/auth/removeCustomClaims.ts +7 -2
- package/src/supabase/auth/setCustomClaims.ts +4 -2
- package/src/supabase/billing/refreshSubscriptionStatus.ts +6 -5
- package/src/supabase/crud/aggregate.ts +85 -72
- package/src/supabase/crud/bulk.ts +50 -0
- package/src/supabase/crud/create.ts +27 -33
- package/src/supabase/crud/delete.ts +2 -1
- package/src/supabase/crud/entityStore.ts +107 -18
- package/src/supabase/crud/get.ts +5 -13
- package/src/supabase/crud/list.ts +28 -21
- package/src/supabase/crud/update.ts +29 -24
- package/src/supabase/edgeFunction.ts +2 -1
- package/src/supabase/email/createEmailFunction.ts +2 -1
- package/src/supabase/index.ts +8 -0
- package/src/supabase/oauth/exchangeToken.ts +1 -0
- package/src/supabase/oauth/getConnections.ts +1 -1
- package/src/supabase/oauth/refreshToken.ts +1 -0
- package/src/supabase/registerCrudFunctions.ts +1 -0
- package/src/supabase/utils/idempotency.ts +1 -1
- package/src/supabase/utils/monitoring.ts +1 -0
- package/src/vercel/__tests__/bulk.test.ts +16 -8
- package/src/vercel/api/billing/change-plan.ts +6 -5
- package/src/vercel/api/billing/refresh-subscription-status.ts +3 -1
- package/src/vercel/api/crud/bulk.ts +34 -6
- package/src/vercel/api/crud/create.ts +22 -21
- package/src/vercel/api/crud/delete.ts +5 -2
- package/src/vercel/api/crud/get.ts +10 -8
- package/src/vercel/api/crud/list.ts +10 -8
- package/src/vercel/api/crud/update.ts +25 -20
- package/src/vercel/api/oauth/check-github-access.ts +1 -0
- package/src/vercel/api/oauth/exchange-token.ts +5 -2
- package/src/vercel/api/oauth/grant-github-access.ts +1 -0
- package/src/vercel/api/oauth/revoke-github-access.ts +1 -0
- package/src/vercel/baseFunction.ts +5 -1
- package/lib/chunks/chunk-2A4FPYNB.js.map +0 -7
- package/lib/chunks/chunk-2IFFIUFV.js +0 -23
- package/lib/chunks/chunk-2IFFIUFV.js.map +0 -7
- package/lib/chunks/chunk-FQSQGOBN.js +0 -22
- package/lib/chunks/chunk-FQSQGOBN.js.map +0 -7
- package/lib/chunks/chunk-G4FO76EA.js +0 -22
- package/lib/chunks/chunk-G4FO76EA.js.map +0 -7
- package/lib/chunks/chunk-LSM5Y2E5.js +0 -22
- package/lib/chunks/chunk-LSM5Y2E5.js.map +0 -7
- package/lib/chunks/chunk-M4JV2JCF.js +0 -22
- package/lib/chunks/chunk-M4JV2JCF.js.map +0 -7
- package/lib/chunks/chunk-OZX5ZG44.js +0 -22
- package/lib/chunks/chunk-PWAGW4R6.js +0 -22
- package/lib/chunks/chunk-PWAGW4R6.js.map +0 -7
- package/lib/chunks/chunk-UYI56E6Q.js +0 -151
- package/lib/chunks/chunk-UYI56E6Q.js.map +0 -7
- package/lib/chunks/chunk-ZVHC2CAV.js +0 -22
- package/lib/chunks/chunk-ZVHC2CAV.js.map +0 -7
- package/lib/shared/schema.d.ts +0 -56
- package/lib/shared/utils/functionWrapper.d.ts +0 -36
- package/src/shared/__tests__/schema.test.ts +0 -219
- package/src/shared/schema.ts +0 -192
- package/src/shared/utils/__tests__/functionWrapper.test.ts +0 -122
- package/src/shared/utils/functionWrapper.ts +0 -73
- /package/lib/chunks/{chunk-PJCJ5H2O.js.map → chunk-HZM5X5A7.js.map} +0 -0
- /package/lib/chunks/{monitoring-UIDJS2KA.js.map → monitoring-UCBNPPW2.js.map} +0 -0
- /package/lib/chunks/{rateLimiter-WNWHI3B4.js.map → rateLimiter-XKECWM33.js.map} +0 -0
- /package/lib/chunks/{server-RYGEBS2B.js.map → server-24XGDDO3.js.map} +0 -0
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview Unit tests for `createDeleteAccount`.
|
|
3
|
+
* @description `beforeDelete` runs first; a throw refuses the deletion with a 409
|
|
4
|
+
* carrying the error's message and code, and the auth user is kept.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import { describe, it, expect, vi } from 'vitest';
|
|
8
|
+
|
|
9
|
+
vi.mock('../../baseFunction.js', () => ({
|
|
10
|
+
createSupabaseHandler: vi.fn(
|
|
11
|
+
(_operationName: string, _schema: unknown, handler: any) => handler
|
|
12
|
+
),
|
|
13
|
+
}));
|
|
14
|
+
|
|
15
|
+
import { createDeleteAccount } from '../deleteAccount.js';
|
|
16
|
+
|
|
17
|
+
type Handler = (data: unknown, ctx: unknown) => Promise<unknown>;
|
|
18
|
+
|
|
19
|
+
function setup(deleteError: unknown = null) {
|
|
20
|
+
const order: string[] = [];
|
|
21
|
+
const deleteUser = vi.fn(async () => {
|
|
22
|
+
order.push('deleteUser');
|
|
23
|
+
return { error: deleteError };
|
|
24
|
+
});
|
|
25
|
+
const ctx = {
|
|
26
|
+
uid: 'user-1',
|
|
27
|
+
userRole: 'user',
|
|
28
|
+
supabaseAdmin: { auth: { admin: { deleteUser } } },
|
|
29
|
+
};
|
|
30
|
+
return { ctx, deleteUser, order };
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
describe('createDeleteAccount', () => {
|
|
34
|
+
it('deletes the caller without options (unchanged behaviour)', async () => {
|
|
35
|
+
const { ctx, deleteUser } = setup();
|
|
36
|
+
const handler = createDeleteAccount() as unknown as Handler;
|
|
37
|
+
await expect(handler({}, ctx)).resolves.toEqual({ success: true });
|
|
38
|
+
expect(deleteUser).toHaveBeenCalledWith('user-1');
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
it('runs beforeDelete with the context before deleting the user', async () => {
|
|
42
|
+
const { ctx, deleteUser, order } = setup();
|
|
43
|
+
const beforeDelete = vi.fn(async (c: unknown) => {
|
|
44
|
+
expect(c).toBe(ctx);
|
|
45
|
+
order.push('beforeDelete');
|
|
46
|
+
});
|
|
47
|
+
const handler = createDeleteAccount({ beforeDelete }) as unknown as Handler;
|
|
48
|
+
await expect(handler({}, ctx)).resolves.toEqual({ success: true });
|
|
49
|
+
expect(order).toEqual(['beforeDelete', 'deleteUser']);
|
|
50
|
+
expect(deleteUser).toHaveBeenCalledTimes(1);
|
|
51
|
+
});
|
|
52
|
+
|
|
53
|
+
it('refuses with 409 { error, code } and keeps the user when beforeDelete throws', async () => {
|
|
54
|
+
const { ctx, deleteUser } = setup();
|
|
55
|
+
const refusal = Object.assign(new Error('open_orders'), { code: 'P0001' });
|
|
56
|
+
const handler = createDeleteAccount({
|
|
57
|
+
beforeDelete: async () => {
|
|
58
|
+
throw refusal;
|
|
59
|
+
},
|
|
60
|
+
}) as unknown as Handler;
|
|
61
|
+
const res = (await handler({}, ctx)) as Response;
|
|
62
|
+
expect(res).toBeInstanceOf(Response);
|
|
63
|
+
expect(res.status).toBe(409);
|
|
64
|
+
expect(await res.json()).toEqual({ error: 'open_orders', code: 'P0001' });
|
|
65
|
+
expect(deleteUser).not.toHaveBeenCalled();
|
|
66
|
+
});
|
|
67
|
+
|
|
68
|
+
it('refuses an error without a code with its message only', async () => {
|
|
69
|
+
const { ctx, deleteUser } = setup();
|
|
70
|
+
const handler = createDeleteAccount({
|
|
71
|
+
beforeDelete: async () => {
|
|
72
|
+
throw new Error('unpaid_terms');
|
|
73
|
+
},
|
|
74
|
+
}) as unknown as Handler;
|
|
75
|
+
const res = (await handler({}, ctx)) as Response;
|
|
76
|
+
expect(res.status).toBe(409);
|
|
77
|
+
expect(await res.json()).toEqual({ error: 'unpaid_terms' });
|
|
78
|
+
expect(deleteUser).not.toHaveBeenCalled();
|
|
79
|
+
});
|
|
80
|
+
|
|
81
|
+
it('refuses a plain-object rejection (PostgREST { message, code } shape)', async () => {
|
|
82
|
+
const { ctx, deleteUser } = setup();
|
|
83
|
+
const handler = createDeleteAccount({
|
|
84
|
+
beforeDelete: async () => {
|
|
85
|
+
// eslint-disable-next-line @typescript-eslint/only-throw-error -- why: PostgREST rejects with plain objects
|
|
86
|
+
throw { message: 'open_orders', code: 'P0001', details: null };
|
|
87
|
+
},
|
|
88
|
+
}) as unknown as Handler;
|
|
89
|
+
const res = (await handler({}, ctx)) as Response;
|
|
90
|
+
expect(await res.json()).toEqual({ error: 'open_orders', code: 'P0001' });
|
|
91
|
+
expect(deleteUser).not.toHaveBeenCalled();
|
|
92
|
+
});
|
|
93
|
+
|
|
94
|
+
it('throws when Supabase fails to delete the user', async () => {
|
|
95
|
+
const failure = new Error('db down');
|
|
96
|
+
const { ctx } = setup(failure);
|
|
97
|
+
const handler = createDeleteAccount({
|
|
98
|
+
beforeDelete: async () => {},
|
|
99
|
+
}) as unknown as Handler;
|
|
100
|
+
await expect(handler({}, ctx)).rejects.toBe(failure);
|
|
101
|
+
});
|
|
102
|
+
});
|
|
@@ -2,9 +2,10 @@
|
|
|
2
2
|
|
|
3
3
|
/**
|
|
4
4
|
* @fileoverview Delete Account Supabase Edge Function
|
|
5
|
-
* @description Deletes the authenticated user's account via Supabase Admin
|
|
5
|
+
* @description Deletes the authenticated user's account via Supabase Admin, after an
|
|
6
|
+
* optional consumer `beforeDelete` step that can refuse the deletion.
|
|
6
7
|
*
|
|
7
|
-
* @version 0.
|
|
8
|
+
* @version 0.2.0
|
|
8
9
|
* @since 0.5.0
|
|
9
10
|
* @author AMBROISE PARK Consulting
|
|
10
11
|
*/
|
|
@@ -12,6 +13,7 @@
|
|
|
12
13
|
import * as v from 'valibot';
|
|
13
14
|
|
|
14
15
|
import { createSupabaseHandler } from '../baseFunction.js';
|
|
16
|
+
import type { SupabaseHandlerContext } from '../baseFunction.js';
|
|
15
17
|
|
|
16
18
|
// =============================================================================
|
|
17
19
|
// Schema
|
|
@@ -19,13 +21,55 @@ import { createSupabaseHandler } from '../baseFunction.js';
|
|
|
19
21
|
|
|
20
22
|
const deleteAccountSchema = v.object({});
|
|
21
23
|
|
|
24
|
+
// =============================================================================
|
|
25
|
+
// Types
|
|
26
|
+
// =============================================================================
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Options for {@link createDeleteAccount}.
|
|
30
|
+
*
|
|
31
|
+
* @version 0.2.0
|
|
32
|
+
* @since 0.2.3
|
|
33
|
+
*/
|
|
34
|
+
export interface DeleteAccountOptions {
|
|
35
|
+
/**
|
|
36
|
+
* Runs before the auth user is deleted (close the account, anonymize data, cancel
|
|
37
|
+
* subscriptions...). Throwing refuses the deletion: the user is NOT deleted and the
|
|
38
|
+
* client receives HTTP 409 `{ error: message, code }` (`code` when the thrown error
|
|
39
|
+
* carries a string `code`). The message and code reach the browser unmasked, so
|
|
40
|
+
* throw client-safe values only — a refusal code such as `open_orders` that the
|
|
41
|
+
* client translates under `auth:deleteAccount.errors.<code>` (see `useDeleteAccount`).
|
|
42
|
+
*/
|
|
43
|
+
beforeDelete?: (ctx: SupabaseHandlerContext) => Promise<void>;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** HTTP status of a refusal raised by `beforeDelete`. */
|
|
47
|
+
const REFUSAL_STATUS = 409;
|
|
48
|
+
|
|
22
49
|
// =============================================================================
|
|
23
50
|
// Handler
|
|
24
51
|
// =============================================================================
|
|
25
52
|
|
|
53
|
+
/** The 409 response carrying a `beforeDelete` refusal to the client. */
|
|
54
|
+
function refusalResponse(error: unknown): Response {
|
|
55
|
+
// why: PostgREST/Supabase errors may arrive as plain { message, code } objects
|
|
56
|
+
const record =
|
|
57
|
+
typeof error === 'object' && error !== null
|
|
58
|
+
? (error as { message?: unknown; code?: unknown })
|
|
59
|
+
: {};
|
|
60
|
+
const message =
|
|
61
|
+
typeof record.message === 'string' ? record.message : String(error);
|
|
62
|
+
const code = typeof record.code === 'string' ? record.code : undefined;
|
|
63
|
+
return new Response(JSON.stringify({ error: message, code }), {
|
|
64
|
+
status: REFUSAL_STATUS,
|
|
65
|
+
headers: { 'Content-Type': 'application/json' },
|
|
66
|
+
});
|
|
67
|
+
}
|
|
68
|
+
|
|
26
69
|
/**
|
|
27
70
|
* Create a Supabase Edge Function handler for account deletion.
|
|
28
71
|
*
|
|
72
|
+
* @param options - Optional `beforeDelete` step; without it, deletes the user directly
|
|
29
73
|
* @returns `(req: Request) => Promise<Response>` handler
|
|
30
74
|
*
|
|
31
75
|
* @example
|
|
@@ -35,14 +79,37 @@ const deleteAccountSchema = v.object({});
|
|
|
35
79
|
* Deno.serve(createDeleteAccount());
|
|
36
80
|
* ```
|
|
37
81
|
*
|
|
38
|
-
* @
|
|
82
|
+
* @example
|
|
83
|
+
* ```typescript
|
|
84
|
+
* // Refuse while the account still has open orders (the SQL function raises 'open_orders')
|
|
85
|
+
* Deno.serve(
|
|
86
|
+
* createDeleteAccount({
|
|
87
|
+
* beforeDelete: async ({ supabaseAdmin, uid }) => {
|
|
88
|
+
* const { error } = await supabaseAdmin.rpc('close_my_account', { p_uid: uid });
|
|
89
|
+
* if (error) throw error; // → 409 { error: 'open_orders', code: 'P0001' }
|
|
90
|
+
* },
|
|
91
|
+
* })
|
|
92
|
+
* );
|
|
93
|
+
* ```
|
|
94
|
+
*
|
|
95
|
+
* @version 0.2.0
|
|
39
96
|
* @since 0.5.0
|
|
40
97
|
*/
|
|
41
|
-
export function createDeleteAccount() {
|
|
98
|
+
export function createDeleteAccount(options: DeleteAccountOptions = {}) {
|
|
99
|
+
const { beforeDelete } = options;
|
|
42
100
|
return createSupabaseHandler(
|
|
43
101
|
'delete-account',
|
|
44
102
|
deleteAccountSchema,
|
|
45
|
-
async (_data, ctx) => {
|
|
103
|
+
async (_data, ctx): Promise<{ success: true } | Response> => {
|
|
104
|
+
if (beforeDelete) {
|
|
105
|
+
try {
|
|
106
|
+
await beforeDelete(ctx);
|
|
107
|
+
} catch (error) {
|
|
108
|
+
console.error('[delete-account] beforeDelete refused:', error);
|
|
109
|
+
return refusalResponse(error);
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
|
|
46
113
|
const { error } = await ctx.supabaseAdmin.auth.admin.deleteUser(ctx.uid);
|
|
47
114
|
if (error) throw error;
|
|
48
115
|
|
|
@@ -43,6 +43,7 @@ const BLOCKED_CLAIM_KEYS = new Set([
|
|
|
43
43
|
'elevated',
|
|
44
44
|
'plan',
|
|
45
45
|
'tier',
|
|
46
|
+
'subscription',
|
|
46
47
|
'provider',
|
|
47
48
|
'providers',
|
|
48
49
|
'sub',
|
|
@@ -102,10 +103,14 @@ export function createRemoveCustomClaims() {
|
|
|
102
103
|
delete existingClaims[key];
|
|
103
104
|
}
|
|
104
105
|
|
|
105
|
-
//
|
|
106
|
+
// Supabase merges app_metadata; omitted keys survive. Null deletes a key.
|
|
107
|
+
// Patch only requested keys, never replay stale subscription/role metadata.
|
|
108
|
+
const removals = Object.fromEntries(
|
|
109
|
+
data.claimsToRemove.map((key) => [key, null])
|
|
110
|
+
);
|
|
106
111
|
const { error: updateError } =
|
|
107
112
|
await ctx.supabaseAdmin.auth.admin.updateUserById(ctx.uid, {
|
|
108
|
-
app_metadata:
|
|
113
|
+
app_metadata: removals,
|
|
109
114
|
});
|
|
110
115
|
if (updateError) throw updateError;
|
|
111
116
|
|
|
@@ -42,6 +42,7 @@ const BLOCKED_CLAIM_KEYS = new Set([
|
|
|
42
42
|
'elevated',
|
|
43
43
|
'plan',
|
|
44
44
|
'tier',
|
|
45
|
+
'subscription',
|
|
45
46
|
'provider',
|
|
46
47
|
'providers',
|
|
47
48
|
'sub',
|
|
@@ -123,10 +124,11 @@ export function createSetCustomClaims(options: SetCustomClaimsOptions) {
|
|
|
123
124
|
>;
|
|
124
125
|
const updatedClaims = { ...existingClaims, ...data.customClaims };
|
|
125
126
|
|
|
126
|
-
//
|
|
127
|
+
// Supabase merges app_metadata server-side. Send only allowed changes so a
|
|
128
|
+
// stale read cannot replay subscription/role over a concurrent trusted update.
|
|
127
129
|
const { error: updateError } =
|
|
128
130
|
await ctx.supabaseAdmin.auth.admin.updateUserById(ctx.uid, {
|
|
129
|
-
app_metadata:
|
|
131
|
+
app_metadata: data.customClaims,
|
|
130
132
|
});
|
|
131
133
|
if (updateError) throw updateError;
|
|
132
134
|
|
|
@@ -15,6 +15,7 @@ import * as v from 'valibot';
|
|
|
15
15
|
import { initStripe, stripe, validateStripeEnvironment } from '../../shared/billing/stripeClient.js';
|
|
16
16
|
import { createSupabaseHandler } from '../baseFunction.js';
|
|
17
17
|
import { createSupabaseAuthProvider } from '../helpers/authProvider.js';
|
|
18
|
+
import { pinnedSubscriptionPeriod } from '../../shared/billing/stripePinned.js';
|
|
18
19
|
|
|
19
20
|
// =============================================================================
|
|
20
21
|
// Schema
|
|
@@ -66,12 +67,12 @@ export function createRefreshSubscriptionStatus() {
|
|
|
66
67
|
...(currentClaims.subscription as Record<string, unknown>),
|
|
67
68
|
status: subscription.status,
|
|
68
69
|
currentPeriodStart: new Date(
|
|
69
|
-
(subscription
|
|
70
|
+
pinnedSubscriptionPeriod(subscription).current_period_start * 1000
|
|
70
71
|
).toISOString(),
|
|
71
72
|
currentPeriodEnd: new Date(
|
|
72
|
-
(subscription
|
|
73
|
+
pinnedSubscriptionPeriod(subscription).current_period_end * 1000
|
|
73
74
|
).toISOString(),
|
|
74
|
-
cancelAtPeriodEnd:
|
|
75
|
+
cancelAtPeriodEnd: subscription.cancel_at_period_end,
|
|
75
76
|
},
|
|
76
77
|
};
|
|
77
78
|
|
|
@@ -82,9 +83,9 @@ export function createRefreshSubscriptionStatus() {
|
|
|
82
83
|
userId: data.userId,
|
|
83
84
|
status: subscription.status,
|
|
84
85
|
currentPeriodEnd: new Date(
|
|
85
|
-
(subscription
|
|
86
|
+
pinnedSubscriptionPeriod(subscription).current_period_end * 1000
|
|
86
87
|
).toISOString(),
|
|
87
|
-
cancelAtPeriodEnd:
|
|
88
|
+
cancelAtPeriodEnd: subscription.cancel_at_period_end,
|
|
88
89
|
};
|
|
89
90
|
}
|
|
90
91
|
);
|
|
@@ -16,11 +16,13 @@ import { defaultFieldMapper } from '@donotdev/supabase/server';
|
|
|
16
16
|
|
|
17
17
|
import { DoNotDevError } from '../../shared/utils.js';
|
|
18
18
|
import { createSupabaseHandler } from '../baseFunction.js';
|
|
19
|
+
import type { Filterable } from './entityStore.js';
|
|
19
20
|
|
|
20
21
|
const mapper = defaultFieldMapper;
|
|
21
22
|
|
|
22
23
|
/** Request payload for aggregate operations (COUNT, SUM, AVG, MIN, MAX) on entities. */
|
|
23
24
|
export type AggregateEntityRequest = {
|
|
25
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- why: exported request type; consumers reading where values would get unknown (breaking)
|
|
24
26
|
where?: Array<[string, any, any]>;
|
|
25
27
|
aggregate: {
|
|
26
28
|
field: string;
|
|
@@ -29,12 +31,12 @@ export type AggregateEntityRequest = {
|
|
|
29
31
|
groupBy?: string[];
|
|
30
32
|
};
|
|
31
33
|
|
|
32
|
-
function applyOperator(
|
|
33
|
-
query:
|
|
34
|
+
function applyOperator<Q extends Filterable>(
|
|
35
|
+
query: Q,
|
|
34
36
|
column: string,
|
|
35
37
|
operator: string,
|
|
36
|
-
value:
|
|
37
|
-
):
|
|
38
|
+
value: unknown
|
|
39
|
+
): Q {
|
|
38
40
|
switch (operator) {
|
|
39
41
|
case '==':
|
|
40
42
|
return query.eq(column, value);
|
|
@@ -59,6 +61,35 @@ function applyOperator(
|
|
|
59
61
|
}
|
|
60
62
|
}
|
|
61
63
|
|
|
64
|
+
/**
|
|
65
|
+
* Aggregate one column over rows. `count` counts rows; the numeric operations
|
|
66
|
+
* ignore null and non-numeric values and return 0 when none remain.
|
|
67
|
+
*/
|
|
68
|
+
function reduceRows(
|
|
69
|
+
rows: Record<string, unknown>[],
|
|
70
|
+
operation: AggregateEntityRequest['aggregate']['operation'],
|
|
71
|
+
column: string
|
|
72
|
+
): number {
|
|
73
|
+
if (operation === 'count') return rows.length;
|
|
74
|
+
|
|
75
|
+
const values = rows
|
|
76
|
+
.map((row) => row[column])
|
|
77
|
+
.filter((value) => value != null && !isNaN(Number(value)))
|
|
78
|
+
.map(Number);
|
|
79
|
+
if (values.length === 0) return 0;
|
|
80
|
+
|
|
81
|
+
switch (operation) {
|
|
82
|
+
case 'sum':
|
|
83
|
+
return values.reduce((a, b) => a + b, 0);
|
|
84
|
+
case 'avg':
|
|
85
|
+
return values.reduce((a, b) => a + b, 0) / values.length;
|
|
86
|
+
case 'min':
|
|
87
|
+
return Math.min(...values);
|
|
88
|
+
case 'max':
|
|
89
|
+
return Math.max(...values);
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
62
93
|
/**
|
|
63
94
|
* Create a Supabase Edge Function handler for aggregating entities.
|
|
64
95
|
*
|
|
@@ -69,11 +100,12 @@ function applyOperator(
|
|
|
69
100
|
*/
|
|
70
101
|
export function createSupabaseAggregateEntities(
|
|
71
102
|
collection: string,
|
|
103
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- why: accepts schemas of any output type; v.GenericSchema would make InferOutput unknown for callers (breaking)
|
|
72
104
|
documentSchema: v.BaseSchema<unknown, any, v.BaseIssue<unknown>>,
|
|
73
105
|
requiredRole: UserRole
|
|
74
106
|
) {
|
|
75
107
|
const requestSchema = v.object({
|
|
76
|
-
where: v.optional(v.array(v.tuple([v.string(), v.
|
|
108
|
+
where: v.optional(v.array(v.tuple([v.string(), v.unknown(), v.unknown()]))),
|
|
77
109
|
aggregate: v.object({
|
|
78
110
|
field: v.string(),
|
|
79
111
|
operation: v.picklist(['count', 'sum', 'avg', 'min', 'max']),
|
|
@@ -89,8 +121,26 @@ export function createSupabaseAggregateEntities(
|
|
|
89
121
|
const { supabaseAdmin } = ctx;
|
|
90
122
|
|
|
91
123
|
const aggregateColumn = mapper.toBackendField(aggregate.field);
|
|
92
|
-
|
|
93
|
-
|
|
124
|
+
const groupColumns = (groupBy ?? []).map((f) => mapper.toBackendField(f));
|
|
125
|
+
const isGrouped = groupColumns.length > 0;
|
|
126
|
+
const isUngroupedCount = !isGrouped && aggregate.operation === 'count';
|
|
127
|
+
|
|
128
|
+
// select() first: filters exist on the filter builder it returns, not on from().
|
|
129
|
+
// Ungrouped count needs no rows (head request); otherwise fetch only the
|
|
130
|
+
// group and aggregate columns and aggregate in JS (PostgREST has no GROUP BY).
|
|
131
|
+
const selectColumns = isUngroupedCount
|
|
132
|
+
? '*'
|
|
133
|
+
: [
|
|
134
|
+
...new Set([
|
|
135
|
+
...groupColumns,
|
|
136
|
+
...(aggregate.operation === 'count' ? [] : [aggregateColumn]),
|
|
137
|
+
]),
|
|
138
|
+
].join(', ');
|
|
139
|
+
let query = isUngroupedCount
|
|
140
|
+
? supabaseAdmin
|
|
141
|
+
.from(collection)
|
|
142
|
+
.select(selectColumns, { count: 'exact', head: true })
|
|
143
|
+
: supabaseAdmin.from(collection).select(selectColumns);
|
|
94
144
|
|
|
95
145
|
for (const [field, operator, value] of where) {
|
|
96
146
|
query = applyOperator(
|
|
@@ -101,24 +151,6 @@ export function createSupabaseAggregateEntities(
|
|
|
101
151
|
);
|
|
102
152
|
}
|
|
103
153
|
|
|
104
|
-
if (groupBy && groupBy.length > 0) {
|
|
105
|
-
const groupByColumns = groupBy
|
|
106
|
-
.map((f) => mapper.toBackendField(f))
|
|
107
|
-
.join(', ');
|
|
108
|
-
const selectFields = `${groupByColumns}, ${aggregate.operation}(${aggregateColumn})`;
|
|
109
|
-
query = query.select(selectFields);
|
|
110
|
-
for (const field of groupBy) {
|
|
111
|
-
query = query.group(mapper.toBackendField(field));
|
|
112
|
-
}
|
|
113
|
-
} else {
|
|
114
|
-
if (aggregate.operation === 'count') {
|
|
115
|
-
query = query.select('*', { count: 'exact', head: true });
|
|
116
|
-
} else {
|
|
117
|
-
query = query.select(aggregateColumn);
|
|
118
|
-
}
|
|
119
|
-
}
|
|
120
|
-
|
|
121
|
-
// Execute query
|
|
122
154
|
const { data: rows, error, count } = await query;
|
|
123
155
|
|
|
124
156
|
if (error) {
|
|
@@ -128,54 +160,35 @@ export function createSupabaseAggregateEntities(
|
|
|
128
160
|
);
|
|
129
161
|
}
|
|
130
162
|
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
case 'sum':
|
|
159
|
-
result = values.reduce((a: number, b: number) => a + b, 0);
|
|
160
|
-
break;
|
|
161
|
-
case 'avg':
|
|
162
|
-
result =
|
|
163
|
-
values.reduce((a: number, b: number) => a + b, 0) /
|
|
164
|
-
values.length;
|
|
165
|
-
break;
|
|
166
|
-
case 'min':
|
|
167
|
-
result = Math.min(...values);
|
|
168
|
-
break;
|
|
169
|
-
case 'max':
|
|
170
|
-
result = Math.max(...values);
|
|
171
|
-
break;
|
|
172
|
-
default:
|
|
173
|
-
result = 0;
|
|
174
|
-
}
|
|
175
|
-
|
|
176
|
-
return { value: result };
|
|
177
|
-
}
|
|
163
|
+
if (isUngroupedCount) {
|
|
164
|
+
return { value: count ?? 0 };
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
// why: select() with a runtime column string types rows as a parser-error type
|
|
168
|
+
const typedRows = (rows ?? []) as unknown as Record<string, unknown>[];
|
|
169
|
+
|
|
170
|
+
if (!isGrouped) {
|
|
171
|
+
return {
|
|
172
|
+
value: reduceRows(typedRows, aggregate.operation, aggregateColumn),
|
|
173
|
+
};
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
const groups = new Map<string, Record<string, unknown>[]>();
|
|
177
|
+
for (const row of typedRows) {
|
|
178
|
+
const groupKey = groupColumns.map((c) => String(row[c])).join('|');
|
|
179
|
+
const groupRows = groups.get(groupKey);
|
|
180
|
+
if (groupRows) groupRows.push(row);
|
|
181
|
+
else groups.set(groupKey, [row]);
|
|
182
|
+
}
|
|
183
|
+
const grouped: Record<string, number> = {};
|
|
184
|
+
for (const [groupKey, groupRows] of groups) {
|
|
185
|
+
grouped[groupKey] = reduceRows(
|
|
186
|
+
groupRows,
|
|
187
|
+
aggregate.operation,
|
|
188
|
+
aggregateColumn
|
|
189
|
+
);
|
|
178
190
|
}
|
|
191
|
+
return { value: grouped };
|
|
179
192
|
},
|
|
180
193
|
requiredRole
|
|
181
194
|
);
|
|
@@ -23,6 +23,7 @@ import {
|
|
|
23
23
|
BulkCollisionError,
|
|
24
24
|
BulkRequestSchema,
|
|
25
25
|
DoNotDevError,
|
|
26
|
+
statusOf,
|
|
26
27
|
} from '@donotdev/core/server';
|
|
27
28
|
import type {
|
|
28
29
|
BulkRequest,
|
|
@@ -42,6 +43,13 @@ import { createSupabaseHandler } from '../baseFunction.js';
|
|
|
42
43
|
|
|
43
44
|
const mapper = defaultFieldMapper;
|
|
44
45
|
|
|
46
|
+
/**
|
|
47
|
+
* SQLSTATE `crud_bulk` raises when an updated row's status is not the one read
|
|
48
|
+
* before the RPC (custom `PT409`, HTTP 409 via PostgREST, never retried): the bulk was validated against a stale
|
|
49
|
+
* status, nothing is written.
|
|
50
|
+
*/
|
|
51
|
+
const STATUS_CHANGED_SQLSTATE = 'PT409';
|
|
52
|
+
|
|
45
53
|
/** Request payload accepted by the bulk handler — mirrors {@link BulkRequestSchema}. */
|
|
46
54
|
export type BulkEntityRequest = BulkRequest;
|
|
47
55
|
|
|
@@ -103,6 +111,13 @@ function preparePatch(
|
|
|
103
111
|
* which wraps `BEGIN ... COMMIT` — any failure triggers `ROLLBACK` and the
|
|
104
112
|
* client observes a rejected promise with no partial state.
|
|
105
113
|
*
|
|
114
|
+
* The stored rows of the updated ids are read before the RPC (their status picks
|
|
115
|
+
* each patch's schema, the CRUD rules). The statuses read are passed as
|
|
116
|
+
* `p_expected_statuses`; `crud_bulk` locks each updated row (`FOR UPDATE`) and
|
|
117
|
+
* rejects the whole bulk (`unavailable`, nothing written) when a status changed in
|
|
118
|
+
* between. Requires the `crud_bulk_status_guard` migration (5-argument
|
|
119
|
+
* `crud_bulk`); against an older database the RPC call fails (function not found).
|
|
120
|
+
*
|
|
106
121
|
* The factory returns a handler that is auto-registered as `bulk_${collection}`
|
|
107
122
|
* by {@link createSupabaseCrudFunctions}.
|
|
108
123
|
*
|
|
@@ -138,8 +153,11 @@ function preparePatch(
|
|
|
138
153
|
*/
|
|
139
154
|
export function createSupabaseBulkEntity(
|
|
140
155
|
collection: string,
|
|
156
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- why: accepts schemas of any output type; v.GenericSchema would make InferOutput unknown for callers (breaking)
|
|
141
157
|
createSchema: v.BaseSchema<unknown, any, v.BaseIssue<unknown>>,
|
|
158
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- why: accepts schemas of any output type; v.GenericSchema would make InferOutput unknown for callers (breaking)
|
|
142
159
|
draftCreateSchema: v.BaseSchema<unknown, any, v.BaseIssue<unknown>>,
|
|
160
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- why: accepts schemas of any output type; v.GenericSchema would make InferOutput unknown for callers (breaking)
|
|
143
161
|
updateSchema: v.BaseSchema<unknown, any, v.BaseIssue<unknown>>,
|
|
144
162
|
access: EntityAccessConfig
|
|
145
163
|
): (req: Request) => Promise<Response> {
|
|
@@ -161,6 +179,9 @@ export function createSupabaseBulkEntity(
|
|
|
161
179
|
BulkRequestSchema,
|
|
162
180
|
async (data: BulkEntityRequest, ctx): Promise<BulkResponse> => {
|
|
163
181
|
const { uid, userRole, supabaseAdmin } = ctx;
|
|
182
|
+
// Status of each updated row as read by `readStored` (id → status), re-checked
|
|
183
|
+
// by `crud_bulk` under lock before any write.
|
|
184
|
+
const expectedStatuses: Record<string, string | null> = {};
|
|
164
185
|
|
|
165
186
|
try {
|
|
166
187
|
return await executeBulk({
|
|
@@ -174,6 +195,28 @@ export function createSupabaseBulkEntity(
|
|
|
174
195
|
userRole,
|
|
175
196
|
// Supabase's `crud_bulk` RPC mints ids server-side — skip the
|
|
176
197
|
// client-side mint hook so the RPC owns the id space.
|
|
198
|
+
// Stored rows of the updated ids: their status decides each patch's
|
|
199
|
+
// schema. This read is outside the RPC transaction: the statuses read
|
|
200
|
+
// are sent to `crud_bulk`, which re-checks them under lock.
|
|
201
|
+
readStored: async (ids) => {
|
|
202
|
+
const { data: rows, error: readError } = await supabaseAdmin
|
|
203
|
+
.from(collection)
|
|
204
|
+
.select('*')
|
|
205
|
+
.in('id', [...ids]);
|
|
206
|
+
if (readError) {
|
|
207
|
+
throw new DoNotDevError(
|
|
208
|
+
`Failed to read rows for bulk: ${readError.message}`,
|
|
209
|
+
'internal'
|
|
210
|
+
);
|
|
211
|
+
}
|
|
212
|
+
const stored = new Map<string, Record<string, unknown>>();
|
|
213
|
+
for (const row of (rows ?? []) as Record<string, unknown>[]) {
|
|
214
|
+
const mapped = mapper.fromBackendRow(row) as Record<string, unknown>;
|
|
215
|
+
stored.set(String(mapped.id), mapped);
|
|
216
|
+
expectedStatuses[String(mapped.id)] = statusOf(mapped);
|
|
217
|
+
}
|
|
218
|
+
return stored;
|
|
219
|
+
},
|
|
177
220
|
stampInsertMetadata: prepareInsertRow,
|
|
178
221
|
stampUpdateMetadata: preparePatch,
|
|
179
222
|
transact: async ({ inserts, updates, deletes }) => {
|
|
@@ -183,7 +226,14 @@ export function createSupabaseBulkEntity(
|
|
|
183
226
|
p_inserts: inserts.map((i) => i.row),
|
|
184
227
|
p_updates: updates.map((u) => ({ id: u.id, patch: u.patch })),
|
|
185
228
|
p_deletes: deletes,
|
|
229
|
+
p_expected_statuses: expectedStatuses,
|
|
186
230
|
});
|
|
231
|
+
if (rpcError?.code === STATUS_CHANGED_SQLSTATE) {
|
|
232
|
+
throw new DoNotDevError(
|
|
233
|
+
`Bulk rejected, nothing written: ${rpcError.message}. Reload and retry.`,
|
|
234
|
+
'unavailable'
|
|
235
|
+
);
|
|
236
|
+
}
|
|
187
237
|
if (rpcError) {
|
|
188
238
|
throw new DoNotDevError(
|
|
189
239
|
`Failed to execute bulk: ${rpcError.message}`,
|