-
Notifications
You must be signed in to change notification settings - Fork 0
/
setup.mjs
313 lines (289 loc) · 9.02 KB
/
setup.mjs
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
import { execSync } from 'child_process'
import crypto from 'crypto'
import { parse, stringify } from 'envfile'
import fs from 'fs'
import inquirer from 'inquirer'
import path from 'path'
import pg from 'pg'
import sodium from 'sodium-native'
function generatePassword(n_bytes = 16) {
return crypto.randomBytes(n_bytes).toString('base64url')
}
function generateSecureSessionKey() {
const buf = Buffer.allocUnsafe(sodium.crypto_secretbox_KEYBYTES)
sodium.randombytes_buf(buf)
return buf.toString('hex')
}
const envValues = fs.existsSync('.env')
? parse(fs.readFileSync('.env', { encoding: 'utf-8' }))
: {}
const answers = await inquirer.prompt(
[
{
type: 'input',
name: 'ROOT_DATABASE_URL',
message:
'Superuser connection string (to a _different_ database), so databases can be dropped/created (may not be necessary in production)',
default: 'postgres:///template1',
},
{
type: 'input',
name: 'DATABASE_HOST',
message: 'Where is the database?',
default: 'localhost',
},
{
type: 'number',
name: 'DATABASE_PORT',
message: 'Where is the port at the host?',
default: 5432,
},
{
type: 'input',
name: 'DATABASE_NAME',
message: 'What is the name of the database?',
default: 'null814_cms',
},
{
type: 'input',
name: 'SUPERUSER_DATABASE_URL',
message:
'Can a superuser connect to the database? Helpful for setting up watchers.',
default: (answers) => `postgres:///${answers.DATABASE_NAME}`,
},
{
type: 'input',
name: 'DATABASE_OWNER',
message: 'Who owns the database?',
default: (answers) => `${answers.DATABASE_NAME}_owner`,
},
{
type: 'input',
name: 'DATABASE_OWNER_PASSWORD',
message: 'Password of database owner.',
default: () => generatePassword(),
},
{
type: 'input',
name: 'DATABASE_AUTHENTICATOR',
message:
'Who is the Postgraphile database user? (Can be logged in, but has few privileges.)',
default: (answers) => `${answers.DATABASE_NAME}_graphile`,
},
{
type: 'input',
name: 'DATABASE_AUTHENTICATOR_PASSWORD',
message: 'Password of graphile user.',
default: () => generatePassword(),
},
{
type: 'input',
name: 'DATABASE_VISITOR',
message:
'Who is the database user representing application users? (Cannot be logged in directly.)',
default: (answers) => `${answers.DATABASE_NAME}_app_users`,
},
{
type: 'input',
name: 'SECRET',
message: 'A secret to encrypt sessions or other sensitive data.',
default: () => generatePassword(),
},
{
type: 'input',
name: 'JWT_SECRET',
message: 'A secret for signing and verifying tokens.',
default: () => generatePassword(),
},
{
type: 'input',
name: 'COOKIE_KEY',
message: 'A key to sign cookies, mainly used for fastify-secure-session',
default: () => generateSecureSessionKey(),
},
{
type: 'number',
name: 'FRONTEND_PORT',
message: 'Port for the nuxt application.',
default: 3000,
},
{
type: 'number',
name: 'BACKEND_PORT',
message: 'Port for the nuxt application.',
default: (answers) => answers.FRONTEND_PORT + 1,
},
{
type: 'input',
name: 'ROOT_URL',
message:
'The root url. This is needed any time we use absolute URLs. Must NOT end with a slash.',
default: (answers) => `http://localhost:${answers.FRONTEND_PORT}`,
transformer: (value) => value.trim().replace(/\/$/, ''),
},
{
type: 'input',
name: 'UPLOAD_FOLDER',
message: 'This is where file uploads are stored.',
default: () => path.join(process.cwd(), 'uploads'),
},
{
type: 'input',
name: 'SMTP_HOST',
message: 'Hostname for sending e-mails via SMTP:',
},
{
type: 'number',
name: 'SMTP_PORT',
message: 'SMTP port:',
default: 587,
},
{
type: 'input',
name: 'SMTP_USER',
message: 'SMTP username:',
},
{
type: 'password',
name: 'SMTP_PASSWORD',
message: 'SMTP password:',
mask: true,
},
{
type: 'confirm',
name: 'SMTP_REJECT_UNAUTHORIZED_CERTS',
message: 'Should I reject unauthorized TLS certs for SMTP?',
default: true,
},
],
envValues
)
async function connectToDatabase() {
const client = new pg.Client({
connectionString: answers.ROOT_DATABASE_URL,
})
await client.connect()
return client
}
const client = await connectToDatabase()
const {
rows: [{ exists: existingOwner }],
} = await client.query(
'SELECT EXISTS(SELECT 1 FROM pg_roles WHERE rolname = $1)',
[answers.DATABASE_OWNER]
)
const {
rows: [{ exists: existingAuthenticator }],
} = await client.query(
'SELECT EXISTS(SELECT 1 FROM pg_roles WHERE rolname = $1)',
[answers.DATABASE_AUTHENTICATOR]
)
const {
rows: [{ exists: existingVisitor }],
} = await client.query(
'SELECT EXISTS(SELECT 1 FROM pg_roles WHERE rolname = $1)',
[answers.DATABASE_VISITOR]
)
const {
rows: [{ exists: existingDatabase }],
} = await client.query(
'SELECT EXISTS(SELECT 1 FROM pg_database WHERE datname = $1)',
[answers.DATABASE_NAME]
)
const {
rows: [{ exists: existingTestDatabase }],
} = await client.query(
'SELECT EXISTS(SELECT 1 FROM pg_database WHERE datname = $1)',
[answers.DATABASE_NAME + '_test']
)
const {
rows: [{ exists: existingShadowDatabase }],
} = await client.query(
'SELECT EXISTS(SELECT 1 FROM pg_database WHERE datname = $1)',
[answers.DATABASE_NAME + '_shadow']
)
await client.end()
const dbSetupIsComplete =
existingOwner &&
existingAuthenticator &&
existingVisitor &&
existingDatabase &&
existingTestDatabase &&
existingShadowDatabase
const dbSetupIsPartlyComplete =
existingOwner ||
existingAuthenticator ||
existingVisitor ||
existingDatabase ||
existingTestDatabase ||
existingShadowDatabase
async function runDatabaseSetup() {
const client = await connectToDatabase()
// RESET database
await client.query(`DROP DATABASE IF EXISTS ${answers.DATABASE_NAME};`)
await client.query(`DROP DATABASE IF EXISTS ${answers.DATABASE_NAME}_shadow;`)
await client.query(`DROP DATABASE IF EXISTS ${answers.DATABASE_NAME}_test;`)
await client.query(`DROP ROLE IF EXISTS ${answers.DATABASE_VISITOR};`)
await client.query(`DROP ROLE IF EXISTS ${answers.DATABASE_AUTHENTICATOR};`)
await client.query(`DROP ROLE IF EXISTS ${answers.DATABASE_OWNER};`)
// Now to set up the database cleanly:
// Ref: https://devcenter.heroku.com/articles/heroku-postgresql#connection-permissions
// This is the root role for the database`);
await client.query(
`CREATE ROLE ${answers.DATABASE_OWNER} WITH LOGIN PASSWORD '${answers.DATABASE_OWNER_PASSWORD}';`
)
// This is the no-access role that PostGraphile will run as by default`);
await client.query(
`CREATE ROLE ${answers.DATABASE_AUTHENTICATOR} WITH LOGIN PASSWORD '${answers.DATABASE_AUTHENTICATOR_PASSWORD}' NOINHERIT;`
)
// This is the role that PostGraphile will switch to (from ${DATABASE_AUTHENTICATOR}) during a GraphQL request
await client.query(`CREATE ROLE ${answers.DATABASE_VISITOR};`)
// This enables PostGraphile to switch from ${DATABASE_AUTHENTICATOR} to ${DATABASE_VISITOR}
await client.query(
`GRANT ${answers.DATABASE_VISITOR} TO ${answers.DATABASE_AUTHENTICATOR};`
)
await client.query(
`CREATE DATABASE ${answers.DATABASE_NAME} OWNER ${answers.DATABASE_OWNER} TEMPLATE template0 ENCODING 'UTF8' LC_COLLATE='de_DE.UTF-8' LC_CTYPE='de_DE.UTF-8';`
)
await client.query(
`CREATE DATABASE ${answers.DATABASE_NAME}_test OWNER ${answers.DATABASE_OWNER} TEMPLATE template0 ENCODING 'UTF8' LC_COLLATE='de_DE.UTF-8' LC_CTYPE='de_DE.UTF-8';`
)
await client.query(
`CREATE DATABASE ${answers.DATABASE_NAME}_shadow OWNER ${answers.DATABASE_OWNER} TEMPLATE template0 ENCODING 'UTF8' LC_COLLATE='de_DE.UTF-8' LC_CTYPE='de_DE.UTF-8';`
)
await client.end()
console.log(
execSync('npm run --workspace @app/database reset -- --erase').toString(
'utf-8'
)
)
console.log(
execSync(
'PYTHONPATH=. poetry run -- procrastinate --app=python_worker.app schema --apply',
{ cwd: '@app/python-worker' }
).toString('utf-8')
)
}
answers.NUXT_PORT = answers.FRONTEND_PORT
answers.NITRO_PORT = answers.FRONTEND_PORT
answers.NUXT_BACKEND_PORT = answers.BACKEND_PORT
fs.writeFileSync('.env', stringify(answers), { encoding: 'utf-8' })
execSync('PYTHONPATH=. poetry install', { cwd: '@app/python-worker' })
if (dbSetupIsPartlyComplete) {
const confirm = await inquirer.prompt({
type: 'confirm',
name: 'reinstallDatabase',
message: dbSetupIsComplete
? 'Database setup already complete. Reinstall?'
: 'Database setup broken. Reinstall?',
default: !dbSetupIsComplete,
})
if (confirm.reinstallDatabase) {
console.log('Running the database setup...')
await runDatabaseSetup()
console.log('ok')
}
} else {
await runDatabaseSetup()
}
await client.end()