-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathsetup.ts
More file actions
371 lines (306 loc) · 11.9 KB
/
Copy pathsetup.ts
File metadata and controls
371 lines (306 loc) · 11.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
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
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
import { exec } from 'node:child_process';
import { promises as fs } from 'node:fs';
import { promisify } from 'node:util';
import crypto from 'node:crypto';
import path from 'node:path';
import { WorkOS } from '@workos-inc/node';
import Stripe from 'stripe';
import chalk from 'chalk';
import { input, password } from '@inquirer/prompts';
const execAsync = promisify(exec);
function question(query: string, options: { secret?: boolean } = {}): Promise<string> {
if (options.secret) {
return password({ message: query, mask: '*' });
} else {
return input({ message: query });
}
}
async function getStripeSecretKey(): Promise<string> {
console.log(`\n${chalk.bold('Getting Stripe Secret Key')}`);
console.log('You can find your Stripe Test Secret Key at: https://dashboard.stripe.com/test/apikeys');
const key = await question('Enter your Stripe Secret Key: ', { secret: true });
if (key.includes('sk_test_')) {
return key;
}
console.log(chalk.red('Invalid Stripe Secret Key'));
console.log('Please use your test secret key and not your live secret key.');
return await getStripeSecretKey();
}
async function generateStripeProducts(stripeApiKey: string) {
const answer = await question('\nDo you want to generate Stripe test mode products? (y/n): ');
if (answer.toLowerCase() !== 'y') {
return;
}
const stripe = new Stripe(stripeApiKey);
console.log('\nGenerating Stripe test mode products and prices...');
try {
await stripe.prices.create({
currency: 'usd',
unit_amount: 500,
recurring: {
interval: 'month',
},
product_data: {
name: 'Basic',
},
lookup_key: 'basic',
});
await stripe.prices.create({
currency: 'usd',
unit_amount: 1000,
recurring: {
interval: 'month',
},
product_data: {
name: 'Standard',
},
lookup_key: 'standard',
});
const enterprisePrice = await stripe.prices.create({
currency: 'usd',
unit_amount: 10000,
recurring: {
interval: 'month',
},
product_data: {
name: 'Enterprise',
},
lookup_key: 'enterprise',
});
const auditLogsFeature = await stripe.entitlements.features.create({
name: 'Audit logs',
lookup_key: 'audit-logs',
});
await stripe.products.createFeature(enterprisePrice.product as string, {
entitlement_feature: auditLogsFeature.id,
});
console.log(chalk.green('Stripe test mode products and prices generated successfully'));
} catch (error) {
console.log(chalk.red('Failed to generate Stripe test mode prices:\n'));
console.error(error);
process.exit(1);
}
}
async function connectStripeToWorkOS() {
console.log(`\n${chalk.bold('Connecting Stripe to WorkOS')}`);
console.log(
'\nFor automatic Stripe entitlements in access tokens, you need to connect your Stripe account to your WorkOS account.',
);
console.log(
'You can do this in the WorkOS dashboard in the "Add-ons" section of the "Authentication" sidebar: https://dashboard.workos.com/',
);
await question('Hit enter after you have connected your Stripe account to your WorkOS account');
}
async function getWorkOSSecretKey(): Promise<string> {
console.log(`\n${chalk.bold('Getting WorkOS API Keys')}`);
console.log(
'You can find your test WorkOS API Key in the dashboard under the "Quick start" section: https://dashboard.workos.com/get-started',
);
const key = await question('Enter your test WorkOS API Key: ', { secret: true });
if (key.includes('sk_test_')) {
return key;
}
console.log(chalk.red('Invalid WorkOS Secret Key'));
console.log('Please use your test secret key and not your live secret key.');
return await getWorkOSSecretKey();
}
async function getWorkOSClientId(): Promise<string> {
console.log(`\n${chalk.bold('Getting WorkOS Client ID')}`);
console.log(
'You can find your WorkOS Client ID in the dashboard under the "Quick start" section: https://dashboard.workos.com/get-started',
);
return await question('Enter your WorkOS Client ID: ');
}
function generateAuthSecret(): string {
console.log(`\n${chalk.bold('Generating WORKOS_COOKIE_PASSWORD')}`);
return crypto.randomBytes(32).toString('hex');
}
async function setAuditLogSchema(workosApiKey: string) {
console.log(`\n${chalk.bold('Creating audit log schema')}`);
console.log('Creating schema for "user.logged_in" and "user.logged_out events');
try {
const workos = new WorkOS(workosApiKey);
await workos.auditLogs.createSchema({
action: 'user.logged_in',
actor: {
metadata: {
role: 'string',
},
},
targets: [
{
type: 'user',
},
],
});
console.log(chalk.green('Created schema for "user.logged_in" event'));
await workos.auditLogs.createSchema({
action: 'user.logged_out',
actor: {
metadata: {
role: 'string',
},
},
targets: [
{
type: 'user',
},
],
});
console.log(chalk.green('Created schema for "user.logged_out" event'));
} catch (error) {
console.log(chalk.red('Failed to create schemas for "user.logged_in" and "user.logged_out" events:'));
console.log(error);
}
}
async function promptRedirectURI() {
console.log(`\n${chalk.bold('Set redirect URI in WorkOS dashboard')}`);
console.log(
'Set the redirect URI to: http://localhost:3000/callback in the WorkOS dashboard in the "Redirects" section',
);
return await question('Hit enter after you have set the redirect URI');
}
async function promptRoleCreation() {
console.log(`\n${chalk.bold('Create roles in WorkOS')}`);
console.log('Add the "Admin" role in the WorkOS dashboard in the "Roles" section');
return await question('Hit enter after you have created the "Admin" role');
}
async function writeEnvFile(envVars: Record<string, string>) {
console.log(`\n${chalk.bold('Writing environment variables to .env')}`);
const envPath = path.join(process.cwd(), '.env.local');
let existingContent: string | null = null;
try {
existingContent = await fs.readFile(envPath, 'utf8');
} catch (error) {
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {
throw error;
}
}
if (existingContent === null) {
const envContent = Object.entries(envVars)
.map(([key, value]) => `${key}=${value}`)
.join('\n');
await fs.writeFile(envPath, envContent);
console.log('.env.local file created with the necessary variables.');
return;
}
const remaining = new Map(Object.entries(envVars));
const lines = existingContent.split('\n');
// Update matching entries in place, preserving the existing file's structure.
const updatedLines = lines.map((line) => {
const match = line.match(/^(\s*)([A-Za-z_][A-Za-z0-9_]*)=/);
if (!match) {
return line;
}
const key = match[2];
if (!remaining.has(key)) {
return line;
}
const value = remaining.get(key)!;
remaining.delete(key);
return `${match[1]}${key}=${value}`;
});
// Append any variables that weren't already present.
const newEntries = [...remaining].map(([key, value]) => `${key}=${value}`);
let output = updatedLines.join('\n');
if (newEntries.length > 0) {
if (output.length > 0 && !output.endsWith('\n')) {
output += '\n';
}
output += newEntries.join('\n');
}
await fs.writeFile(envPath, output);
console.log('.env.local file updated with the necessary variables.');
}
async function setupConvex() {
console.log(`\n${chalk.bold('Setting up Convex')}`);
console.log(`Log into Convex in a separate terminal window with: ${chalk.bold('npx convex login')}`);
await question('Hit enter after you have logged into Convex');
const projectName = await question('\nEnter a name for your new Convex project: ');
try {
console.log('Creating new Convex project (this will take a few moments)');
await execAsync(`npx convex dev --once --configure=new --project=${projectName}`);
console.log(chalk.green('Created new Convex project'));
} catch (error) {
console.log(chalk.red('Failed to create new Convex project or connect to existing one'));
console.log(error);
process.exit(1);
}
}
async function setStripeApiKeyInConvex(stripeApiKey: string) {
try {
console.log('\nAdding Stripe API key as deployment variable in Convex');
await execAsync(`npx convex env set STRIPE_API_KEY ${stripeApiKey}`);
console.log(chalk.green('Stripe API key set as deployment variable in Convex'));
} catch (error) {
console.log(chalk.red('Failed to set Stripe API key as deployment variable in Convex'));
console.log(error);
process.exit(1);
}
}
async function setupWorkOSWebhook(workosApiKey: string, webhookUrl: string) {
console.log(`\n${chalk.bold('Setting up WorkOS webhook')}`);
console.log('Add a new webhook to WorkOS:\n');
console.log(`1. Navigate to the ${chalk.bold('Webhooks')} page in the WorkOS dashboard`);
console.log(`2. Click ${chalk.bold('Create Webhook')}`);
console.log(`3. Paste the following URL into the 'Endpoint URL' field: ${chalk.blue.bold(webhookUrl)}`);
console.log(
`4. Enable the following events: user.created, user.updated, user.deleted, organization.created, organization.deleted, organization.updated`,
);
console.log(`5. Click ${chalk.bold('Create with 6 events')}`);
console.log(`6. Open the webhook endpoint you just created, copy the webhook signing secret, and enter it here:`);
console.log('\nCopy the webhook signing secret and enter it here:');
const workOSWebhookSecret = await question('WorkOS webhook secret: ', { secret: true });
try {
console.log('\nSetting WorkOS webhook signing secret as deployment variable in Convex');
await execAsync(`npx convex env set WORKOS_WEBHOOK_SECRET ${workOSWebhookSecret}`);
console.log(chalk.green('WorkOS webhook signing secret set as deployment variable in Convex'));
} catch (error) {
console.log(chalk.red('Failed to set WorkOS webhook signing secret as deployment variable in Convex'));
console.log(error);
process.exit(1);
}
try {
console.log('\nSetting WorkOS API key as deployment variable in Convex');
await execAsync(`npx convex env set WORKOS_API_KEY ${workosApiKey}`);
console.log(chalk.green('WorkOS API key set as deployment variable in Convex'));
} catch (error) {
console.log(chalk.red('Failed to set WorkOS API key as deployment variable in Convex'));
console.log(error);
process.exit(1);
}
}
async function main() {
const STRIPE_API_KEY = await getStripeSecretKey();
await generateStripeProducts(STRIPE_API_KEY);
await connectStripeToWorkOS();
const WORKOS_API_KEY = await getWorkOSSecretKey();
const WORKOS_CLIENT_ID = await getWorkOSClientId();
const NEXT_PUBLIC_BASE_URL = 'http://localhost:3000';
const NEXT_PUBLIC_WORKOS_REDIRECT_URI = `${NEXT_PUBLIC_BASE_URL}/callback`;
const WORKOS_COOKIE_PASSWORD = generateAuthSecret();
await setAuditLogSchema(WORKOS_API_KEY);
await promptRedirectURI();
await promptRoleCreation();
await writeEnvFile({
STRIPE_API_KEY,
WORKOS_API_KEY,
WORKOS_CLIENT_ID,
NEXT_PUBLIC_WORKOS_REDIRECT_URI,
WORKOS_COOKIE_PASSWORD,
NEXT_PUBLIC_BASE_URL,
});
await setupConvex();
// read from .env.local and extract the NEXT_PUBLIC_CONVEX_URL
const env = await fs.readFile(path.join(process.cwd(), '.env.local'), 'utf8');
const convexUrl = env.match(/NEXT_PUBLIC_CONVEX_URL=(.*)/)?.[1];
const webhookUrl = convexUrl?.replace('.cloud', '.site');
// Entitlement sync is handled by WorkOS via the Stripe (Entitlements)
// integration — the app does NOT need its own Stripe webhook. We only need
// the Stripe API key available to Convex (used by convex/stripe.ts).
await setStripeApiKeyInConvex(STRIPE_API_KEY);
await setupWorkOSWebhook(WORKOS_API_KEY, webhookUrl + '/workos-webhook');
console.log('\n🎉 Setup completed successfully!');
console.log('\nYou can now start the development server with: pnpm run dev');
}
main().catch(console.error);