@donotdev/functions 0.3.2 → 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/lib/chunks/chunk-7T2RZ5A4.js +22 -0
- package/lib/chunks/chunk-7T2RZ5A4.js.map +7 -0
- package/lib/firebase/auth/index.d.ts +1 -0
- package/lib/firebase/auth/listAuthUsers.d.ts +24 -0
- package/lib/firebase/index.js +1 -1
- package/lib/firebase/index.js.map +4 -4
- 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/index.js +1 -1
- package/package.json +3 -3
- 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/crud/delete.ts +57 -1
- 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/lib/chunks/chunk-TBHRDSX5.js +0 -22
- package/lib/chunks/chunk-TBHRDSX5.js.map +0 -7
|
@@ -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';
|
|
@@ -1,22 +0,0 @@
|
|
|
1
|
-
import { createRequire as __createRequire } from 'node:module';
|
|
2
|
-
import { fileURLToPath } from 'node:url';
|
|
3
|
-
import { dirname } from 'node:path';
|
|
4
|
-
import { Buffer } from 'node:buffer';
|
|
5
|
-
import process from 'node:process';
|
|
6
|
-
|
|
7
|
-
const require = __createRequire(import.meta.url);
|
|
8
|
-
const __filename = fileURLToPath(import.meta.url);
|
|
9
|
-
const __dirname = dirname(__filename);
|
|
10
|
-
|
|
11
|
-
if (typeof globalThis !== 'undefined') {
|
|
12
|
-
globalThis.require = require;
|
|
13
|
-
globalThis.__filename = __filename;
|
|
14
|
-
globalThis.__dirname = __dirname;
|
|
15
|
-
globalThis.Buffer = Buffer;
|
|
16
|
-
globalThis.process = process;
|
|
17
|
-
if (typeof global === 'undefined') {
|
|
18
|
-
globalThis.global = globalThis;
|
|
19
|
-
}
|
|
20
|
-
}
|
|
21
|
-
import{B as w,a,m as E,w as S}from"./chunk-LJXSA7EP.js";import{a as i}from"./chunk-AYY7UXNI.js";function C(e){if(!e?.uid)return"guest";let r=e.token?.role;return r==="super"?"super":r==="admin"?"admin":e.token?.isSuper?"super":e.token?.isAdmin?"admin":"user"}i(C,"getUserRole");function A(e){return{success:!0,data:e}}i(A,"createSuccessResponse");function y(e){if(!e||typeof e!="string")throw new Error("Collection name is required");if(e.includes("/")||e.includes("..")||e.startsWith("_"))throw new Error('Invalid collection name: must not contain "/", "..", or start with "_"')}i(y,"validateCollectionName");async function x(e,r,s){let c=[];if(!s?.incoming?.length)return c;let{getFirebaseAdminFirestore:o}=await import("./server-YXYTPMRF.js"),n=o();for(let t of s.incoming){let p=await n.collection(t.sourceCollection).where(t.sourceField,"==",r).limit(1).get();p.empty||c.push({collection:t.sourceCollection,field:t.sourceField,count:p.size})}return c}i(x,"findReferences");import v from"stripe";var f=null;function I(e){if(!e)throw new Error("Stripe API key is required");let r=process.env.STRIPE_API_VERSION||E;return f=new v(e,{apiVersion:r}),f}i(I,"initStripe");function R(){if(!f){let e=process.env.STRIPE_SECRET_KEY;if(e)I(e);else throw new Error("Stripe not initialized. Call initStripe() or set STRIPE_SECRET_KEY env var.")}return f}i(R,"getStripe");var l=new Proxy({},{get(e,r){return R()[r]}});function g(){if(!process.env.STRIPE_SECRET_KEY)throw new Error("Missing STRIPE_SECRET_KEY environment variable")}i(g,"validateStripeEnvironment");async function M(e,r){g();let o=((await r.getUser(e)).customClaims||{}).subscription,n=o?.subscriptionId;if(!n)throw a(new Error("No active subscription found"));let t=await l.subscriptions.update(n,{cancel_at_period_end:!0}),m=w(["active","canceled","past_due","trialing","incomplete"],t.status)?t.status:"incomplete";return await S(e,{tier:o?.tier||"free",status:m,subscriptionEnd:new Date(t.current_period_end*1e3).toISOString(),cancelAtPeriodEnd:!0,subscriptionId:t.id,customerId:t.customer},r),{success:!0,endsAt:new Date(t.current_period_end*1e3).toISOString()}}i(M,"cancelUserSubscription");async function W(e,r,s,c,o){g();let n=c[s];if(!n||n.type!=="StripeSubscription")throw a(new Error("Invalid plan"));if(n.priceId!==r)throw a(new Error("Price ID mismatch with configuration"));let d=((await o.getUser(e)).customClaims||{}).subscription?.subscriptionId;if(!d)throw a(new Error("No active subscription found"));let b=await l.subscriptions.retrieve(d),u=await l.subscriptions.update(d,{items:[{id:b.items.data[0]?.id,price:r}],proration_behavior:"create_prorations"}),_=w(["active","canceled","past_due","trialing","incomplete"],u.status)?u.status:"incomplete";return await S(e,{tier:n.tier,status:_,subscriptionEnd:new Date(u.current_period_end*1e3).toISOString(),cancelAtPeriodEnd:u.cancel_at_period_end,subscriptionId:u.id,customerId:u.customer},o),{success:!0,newTier:n.tier,newPrice:n.price}}i(W,"changeUserPlan");async function $(e,r,s){g();let t=((await r.getUser(e)).customClaims||{}).subscription?.customerId;if(!t)throw a(new Error("No customer found"));if(s){let m=new URL(s),d=new URL(process.env.FRONTEND_URL||"");if(m.origin!==d.origin)throw new Error("Invalid return URL: must match frontend domain")}return{url:(await l.billingPortal.sessions.create({customer:t,return_url:s||`${process.env.FRONTEND_URL}/billing`})).url}}i($,"createCustomerPortalSession");export{C as a,A as b,y as c,x as d,I as e,l as f,g,M as h,W as i,$ as j};
|
|
22
|
-
//# sourceMappingURL=chunk-TBHRDSX5.js.map
|
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
"version": 3,
|
|
3
|
-
"sources": ["../../src/shared/utils.ts", "../../src/shared/billing/stripeClient.ts", "../../src/shared/billing/helpers/subscriptionManagement.ts"],
|
|
4
|
-
"sourcesContent": ["// packages/functions/src/shared/utils.ts\n\n/**\n * @fileoverview Shared utilities for Firebase and Vercel functions\n * @description Common utilities that can be used by both Firebase and Vercel function implementations\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\n\n\nimport { DoNotDevError } from '@donotdev/core/server';\nimport type { OAuthPartnerId, UserRole } from '@donotdev/core/server';\n\n// Re-export DoNotDevError for external use\nexport { DoNotDevError };\n\n/**\n * Get user role from Firebase auth context\n *\n * Determines the user's role for visibility filtering based on:\n * - auth.uid: If missing \u2192 'guest'\n * - auth.token.isSuper: If true \u2192 'super'\n * - auth.token.isAdmin: If true \u2192 'admin'\n * - Otherwise \u2192 'user' (authenticated)\n *\n * @param auth - Firebase auth context from callable function\n * @returns UserRole for visibility filtering\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\nexport function getUserRole(\n auth: { uid?: string; token?: Record<string, unknown> } | null | undefined\n): UserRole {\n if (!auth?.uid) return 'guest';\n\n // Check role claim (standard pattern: auth.token.role = 'admin' | 'super' | etc.)\n const role = auth.token?.role;\n if (role === 'super') return 'super';\n if (role === 'admin') return 'admin';\n\n // Fallback: check legacy boolean flags for backward compatibility\n if (auth.token?.isSuper) return 'super';\n if (auth.token?.isAdmin) return 'admin';\n\n return 'user';\n}\n\n/**\n * Creates a standardized success response\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\nexport function createSuccessResponse<T>(data: T): { success: true; data: T } {\n return {\n success: true,\n data,\n };\n}\n\n/**\n * Creates a standardized error response\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\nexport function createErrorResponse(error: unknown): {\n success: false;\n error: {\n code: string;\n message: string;\n details?: Record<string, unknown>;\n };\n} {\n if (error instanceof DoNotDevError) {\n return {\n success: false,\n error: {\n code: error.code,\n message: error.message,\n details: error.details,\n },\n };\n }\n\n if (error instanceof Error) {\n return {\n success: false,\n error: {\n code: 'internal',\n message: error.message,\n },\n };\n }\n\n return {\n success: false,\n error: {\n code: 'internal',\n message: 'An unexpected error occurred',\n },\n };\n}\n\n/**\n * Validates a Firestore collection name from client-supplied schema.\n *\n * W22: Vercel CRUD handlers accept `schema` (including collection name) from\n * the client. This is a known design limitation. As a defense-in-depth measure,\n * reject collection names that could be used for path traversal or access to\n * internal collections.\n *\n * @param name - Collection name to validate\n * @throws Error if the name is unsafe\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\nexport function validateCollectionName(name: string): void {\n if (!name || typeof name !== 'string') {\n throw new Error('Collection name is required');\n }\n if (name.includes('/') || name.includes('..') || name.startsWith('_')) {\n throw new Error(\n 'Invalid collection name: must not contain \"/\", \"..\", or start with \"_\"'\n );\n }\n}\n\n/**\n * Verifies Firebase auth token\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\nexport async function verifyFirebaseAuthToken(token: string): Promise<string> {\n if (!token) {\n throw new DoNotDevError('Missing authentication token', 'unauthenticated');\n }\n\n // Lazy: the Vercel/Supabase entries must load without firebase-admin\n const { getFirebaseAdminAuth } = await import('@donotdev/firebase/server');\n try {\n const decodedToken = await getFirebaseAdminAuth().verifyIdToken(token);\n return decodedToken.uid;\n } catch (error) {\n throw new DoNotDevError('Invalid or expired token', 'unauthenticated');\n }\n}\n\n/**\n * Finds references to a document\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\nexport async function findReferences(\n collection: string,\n docId: string,\n referenceMetadata?: {\n incoming?: Array<{\n sourceCollection: string;\n sourceField: string;\n }>;\n }\n): Promise<Array<{ collection: string; field: string; count: number }>> {\n const references: Array<{\n collection: string;\n field: string;\n count: number;\n }> = [];\n\n if (!referenceMetadata?.incoming?.length) {\n return references;\n }\n\n // Lazy: the Vercel/Supabase entries must load without firebase-admin\n const { getFirebaseAdminFirestore } =\n await import('@donotdev/firebase/server');\n const db = getFirebaseAdminFirestore();\n\n for (const ref of referenceMetadata.incoming) {\n const snapshot = await db\n .collection(ref.sourceCollection)\n .where(ref.sourceField, '==', docId)\n .limit(1)\n .get();\n\n if (!snapshot.empty) {\n references.push({\n collection: ref.sourceCollection,\n field: ref.sourceField,\n count: snapshot.size,\n });\n }\n }\n\n return references;\n}\n", "// packages/functions/src/shared/billing/stripeClient.ts\n\n/**\n * @fileoverview Stripe client for billing functions\n * @description Lazily initialized Stripe SDK instance shared by the Firebase,\n * Vercel and Supabase billing handlers. Kept apart from `shared/utils.ts` so\n * code that does not bill (CRUD, auth) never loads the Stripe SDK.\n *\n * @version 0.2.1\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\n\nimport Stripe from 'stripe';\n\nimport { STRIPE_API_VERSION_PIN } from './apiVersion.js';\n\n// Lazy initialization of Stripe\nlet _stripe: Stripe | null = null;\n\n/**\n * Initialize Stripe explicitly (e.g. with a secret from defineSecret).\n * API version: `STRIPE_API_VERSION`, else {@link STRIPE_API_VERSION_PIN}.\n * @param apiKey - Stripe secret key\n *\n * @version 0.2.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\nexport function initStripe(apiKey: string) {\n if (!apiKey) throw new Error('Stripe API key is required');\n\n // Unset: the framework pin (pre-basil fields are still read by subscription handlers)\n const apiVersion = process.env.STRIPE_API_VERSION || STRIPE_API_VERSION_PIN;\n\n _stripe = new Stripe(apiKey, {\n // why: SDK types accept only the latest API version; the pinned/env version is older by design\n apiVersion: apiVersion as Stripe.LatestApiVersion,\n });\n return _stripe;\n}\n\n/**\n * Get Stripe instance with lazy initialization\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\nexport function getStripe(): Stripe {\n if (!_stripe) {\n // Legacy/Vercel fallback: Try process.env\n const STRIPE_SECRET_KEY = process.env.STRIPE_SECRET_KEY;\n if (STRIPE_SECRET_KEY) {\n initStripe(STRIPE_SECRET_KEY);\n } else {\n throw new Error(\n 'Stripe not initialized. Call initStripe() or set STRIPE_SECRET_KEY env var.'\n );\n }\n }\n // We know _stripe is set here or we threw\n return _stripe!;\n}\n\n/**\n * Lazy-initialized Stripe instance proxy\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\nexport const stripe = new Proxy({} as Stripe, {\n get(target, prop) {\n return getStripe()[prop as keyof Stripe];\n },\n});\n\n/**\n * Validates that required Stripe environment variables are set\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\nexport function validateStripeEnvironment(): void {\n // Functions v2 automatically injects secrets as process.env when declared in config\n const STRIPE_SECRET_KEY = process.env.STRIPE_SECRET_KEY;\n if (!STRIPE_SECRET_KEY) {\n throw new Error('Missing STRIPE_SECRET_KEY environment variable');\n }\n}\n", "// packages/functions/src/shared/billing/helpers/subscriptionManagement.ts\n\n/**\n * @fileoverview Shared Subscription Management Logic\n * @description Platform-agnostic subscription management functions\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\n\nimport type Stripe from 'stripe';\n\nimport { SUBSCRIPTION_STATUS } from '@donotdev/core/server';\nimport type {\n BillingAuthProvider,\n StripeBackConfig,\n} from '@donotdev/core/server';\n\nimport { updateUserSubscription } from './updateUserSubscription.js';\nimport { handleError } from '../../errorHandling.js';\nimport { stripe, validateStripeEnvironment } from '../stripeClient.js';\nimport { isOneOf, pinnedSubscriptionPeriod } from '../stripePinned.js';\n\n/**\n * Cancel user subscription at period end\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\nexport async function cancelUserSubscription(\n userId: string,\n authProvider: BillingAuthProvider\n): Promise<{ success: boolean; endsAt: string }> {\n validateStripeEnvironment();\n\n // Get user's current subscription\n const user = await authProvider.getUser(userId);\n const currentClaims = user.customClaims || {};\n const subscription = currentClaims.subscription as\n | { subscriptionId?: string; tier?: string }\n | undefined;\n const subscriptionId = subscription?.subscriptionId;\n\n if (!subscriptionId) {\n throw handleError(new Error('No active subscription found'));\n }\n\n // Cancel at period end (don't delete immediately)\n const updatedSubscription = (await stripe.subscriptions.update(\n subscriptionId,\n {\n cancel_at_period_end: true,\n }\n )) as Stripe.Subscription;\n\n // Filter status to valid SubscriptionStatus values\n const validStatuses = [\n 'active',\n 'canceled',\n 'past_due',\n 'trialing',\n 'incomplete',\n ] as const;\n const status = isOneOf(validStatuses, updatedSubscription.status)\n ? updatedSubscription.status\n : 'incomplete';\n\n // Update Firebase Auth claims\n await updateUserSubscription(\n userId,\n {\n tier: subscription?.tier || 'free',\n status,\n subscriptionEnd: new Date(\n pinnedSubscriptionPeriod(updatedSubscription).current_period_end * 1000\n ).toISOString(),\n cancelAtPeriodEnd: true,\n subscriptionId: updatedSubscription.id,\n customerId: updatedSubscription.customer as string,\n },\n authProvider\n );\n\n return {\n success: true,\n endsAt: new Date(\n pinnedSubscriptionPeriod(updatedSubscription).current_period_end * 1000\n ).toISOString(),\n };\n}\n\n/**\n * Change user subscription plan\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\nexport async function changeUserPlan(\n userId: string,\n newPriceId: string,\n billingConfigKey: string,\n billingConfig: StripeBackConfig,\n authProvider: BillingAuthProvider\n): Promise<{ success: boolean; newTier: string; newPrice: number }> {\n validateStripeEnvironment();\n\n // Validate new plan exists in config\n const billingItem = billingConfig[billingConfigKey];\n if (!billingItem || billingItem.type !== 'StripeSubscription') {\n throw handleError(new Error('Invalid plan'));\n }\n\n // Validate price ID matches config\n if (billingItem.priceId !== newPriceId) {\n throw handleError(new Error('Price ID mismatch with configuration'));\n }\n\n // Get current subscription\n const user = await authProvider.getUser(userId);\n const currentClaims = user.customClaims || {};\n const subscription = currentClaims.subscription as\n | { subscriptionId?: string }\n | undefined;\n const subscriptionId = subscription?.subscriptionId;\n\n if (!subscriptionId) {\n throw handleError(new Error('No active subscription found'));\n }\n\n // Get current subscription from Stripe\n const currentSubscription = (await stripe.subscriptions.retrieve(\n subscriptionId\n )) as Stripe.Subscription;\n\n // Update subscription in Stripe\n const updatedSubscription = (await stripe.subscriptions.update(\n subscriptionId,\n {\n items: [\n {\n id: currentSubscription.items.data[0]?.id,\n price: newPriceId,\n },\n ],\n proration_behavior: 'create_prorations', // Pro-rate the change\n }\n )) as Stripe.Subscription;\n\n // Filter status to valid SubscriptionStatus values\n const validStatuses = [\n 'active',\n 'canceled',\n 'past_due',\n 'trialing',\n 'incomplete',\n ] as const;\n const status = isOneOf(validStatuses, updatedSubscription.status)\n ? updatedSubscription.status\n : 'incomplete';\n\n // Update Firebase Auth claims\n await updateUserSubscription(\n userId,\n {\n tier: billingItem.tier,\n status,\n subscriptionEnd: new Date(\n pinnedSubscriptionPeriod(updatedSubscription).current_period_end * 1000\n ).toISOString(),\n cancelAtPeriodEnd: updatedSubscription.cancel_at_period_end,\n subscriptionId: updatedSubscription.id,\n customerId: updatedSubscription.customer as string,\n },\n authProvider\n );\n\n return {\n success: true,\n newTier: billingItem.tier,\n newPrice: billingItem.price,\n };\n}\n\n/**\n * Create Stripe Customer Portal session\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\nexport async function createCustomerPortalSession(\n userId: string,\n authProvider: BillingAuthProvider,\n returnUrl?: string\n): Promise<{ url: string }> {\n validateStripeEnvironment();\n\n // Get customer ID from user claims\n const user = await authProvider.getUser(userId);\n const currentClaims = user.customClaims || {};\n const subscription = currentClaims.subscription as\n | { customerId?: string }\n | undefined;\n const customerId = subscription?.customerId;\n\n if (!customerId) {\n throw handleError(new Error('No customer found'));\n }\n\n // Validate returnUrl domain\n if (returnUrl) {\n const parsed = new URL(returnUrl);\n const frontendUrl = new URL(process.env.FRONTEND_URL || '');\n if (parsed.origin !== frontendUrl.origin) {\n throw new Error('Invalid return URL: must match frontend domain');\n }\n }\n\n // Create portal session\n const session = await stripe.billingPortal.sessions.create({\n customer: customerId,\n return_url: returnUrl || `${process.env.FRONTEND_URL}/billing`,\n });\n\n return {\n url: session.url,\n };\n}\n"],
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;;;gGAkCO,SAASA,EACdC,EACU,CACV,GAAI,CAACA,GAAM,IAAK,MAAO,QAGvB,IAAMC,EAAOD,EAAK,OAAO,KACzB,OAAIC,IAAS,QAAgB,QACzBA,IAAS,QAAgB,QAGzBD,EAAK,OAAO,QAAgB,QAC5BA,EAAK,OAAO,QAAgB,QAEzB,MACT,CAfgBE,EAAAH,EAAA,eAwB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,CAAC,GAGc,GACf,CACF,CArCsBR,EAAAO,EAAA",
|
|
6
|
-
"names": ["getUserRole", "auth", "role", "__name", "createSuccessResponse", "data", "validateCollectionName", "name", "__name", "findReferences", "collection", "docId", "referenceMetadata", "references", "getFirebaseAdminFirestore", "db", "ref", "snapshot", "__name", "Stripe", "_stripe", "initStripe", "apiKey", "apiVersion", "STRIPE_API_VERSION_PIN", "Stripe", "__name", "getStripe", "STRIPE_SECRET_KEY", "stripe", "target", "prop", "validateStripeEnvironment", "cancelUserSubscription", "userId", "authProvider", "validateStripeEnvironment", "subscription", "subscriptionId", "handleError", "updatedSubscription", "stripe", "status", "isOneOf", "updateUserSubscription", "__name", "changeUserPlan", "newPriceId", "billingConfigKey", "billingConfig", "billingItem", "currentSubscription", "createCustomerPortalSession", "returnUrl", "customerId", "parsed", "frontendUrl"]
|
|
7
|
-
}
|