ramdb2-cli 2.0.0-alpha.0 → 2.0.0-alpha.10

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/src/generate.js CHANGED
@@ -1,5 +1,5 @@
1
- import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
2
- import { dirname, join } from 'node:path'
1
+ import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
2
+ import { dirname, join, posix } from 'node:path'
3
3
  import { readSchema } from './model.js'
4
4
  import { classFiles } from './generate/classes.js'
5
5
  import { clientFiles } from './generate/client.js'
@@ -9,24 +9,29 @@ import { operationsFile } from './generate/operations.js'
9
9
  /**
10
10
  * Generates the database layer of a project from its preTypeDefs (spec section 12).
11
11
  * Generated files are rewritten; files written by hand (extended classes) are created only when missing.
12
+ * The generated classes of a type gone from the schema are removed, its extended class is named in a warning.
12
13
  * @param {{schema: string | string[], dest: string}} options schema file(s), destination folder
13
- * @returns {{written: string[], kept: string[], warnings: string[]}} paths relative to dest
14
+ * @returns {{written: string[], kept: string[], removed: string[], warnings: string[]}} paths relative to dest
14
15
  */
15
16
  export function generate({ schema, dest }) {
16
17
  const model = readSchemaFiles(schema)
17
- return { ...writeFiles([...classFiles(model), typeDefsFile(model), operationsFile(model)], dest), warnings: model.warnings }
18
+ const files = [...classFiles(model), typeDefsFile(model), operationsFile(model)]
19
+ const { removed, warnings } = removeOrphans(files, dest)
20
+ return { ...writeFiles(files, dest), removed, warnings: [...model.warnings, ...warnings] }
18
21
  }
19
22
 
20
23
  /**
21
24
  * Generates the classes of a ramdb2-client application from the preTypeDefs of its server (spec section 12, D49):
22
- * generated/<table>.js (rewritten), extended/<table>.js (created once) and index.js, in dest.
25
+ * generated/<table>.js (rewritten), extended/<table>.js (created once) and index.js, in dest. Orphans are handled
26
+ * as by generate.
23
27
  * @param {{schema: string | string[], dest: string}} options schema file(s), destination folder
24
- * @returns {{written: string[], kept: string[], warnings: string[]}} paths relative to dest
28
+ * @returns {{written: string[], kept: string[], removed: string[], warnings: string[]}} paths relative to dest
25
29
  */
26
30
  export function generateClient({ schema, dest }) {
27
31
  const model = readSchemaFiles(schema)
28
32
  const { files, warnings } = clientFiles(model)
29
- return { ...writeFiles(files, dest), warnings: [...model.warnings, ...warnings] }
33
+ const orphans = removeOrphans(files, dest)
34
+ return { ...writeFiles(files, dest), removed: orphans.removed, warnings: [...model.warnings, ...warnings, ...orphans.warnings] }
30
35
  }
31
36
 
32
37
  function readSchemaFiles(schema) {
@@ -49,3 +54,36 @@ function writeFiles(files, dest) {
49
54
  }
50
55
  return { written, kept }
51
56
  }
57
+
58
+ // The marker of a file written by ramdb2-cli: only such a file is ever removed
59
+ const GENERATED = '// Generated by ramdb2-cli'
60
+
61
+ // The classes of a type removed from the schema (D61): in each folder of generated classes, a generated file that
62
+ // this generation does not write is removed; in each folder of extended classes, a file without its generated
63
+ // class is only named in a warning, since it was written by hand.
64
+ function removeOrphans(files, dest) {
65
+ const removed = []
66
+ const warnings = []
67
+ const folders = new Map()
68
+ for (const file of files) {
69
+ const folder = posix.dirname(file.path)
70
+ if (!['generated', 'extended'].includes(posix.basename(folder))) continue
71
+ if (!folders.has(folder)) folders.set(folder, new Set())
72
+ folders.get(folder).add(posix.basename(file.path))
73
+ }
74
+ for (const [folder, names] of folders) {
75
+ const path = join(dest, folder)
76
+ if (!existsSync(path)) continue
77
+ for (const entry of readdirSync(path, { withFileTypes: true })) {
78
+ if (!entry.isFile() || !entry.name.endsWith('.js') || names.has(entry.name)) continue
79
+ const relative = posix.join(folder, entry.name)
80
+ if (posix.basename(folder) === 'extended') {
81
+ warnings.push(`${relative}: its type is no longer in the schema, remove it by hand if it is not used`)
82
+ } else if (readFileSync(join(path, entry.name), 'utf8').startsWith(GENERATED)) {
83
+ rmSync(join(path, entry.name))
84
+ removed.push(relative)
85
+ }
86
+ }
87
+ }
88
+ return { removed, warnings }
89
+ }
package/src/index.js CHANGED
@@ -6,3 +6,9 @@ export { query, expiryOf } from './query.js'
6
6
  export { readSchema, SchemaError } from './model.js'
7
7
  export { DIRECTIVES } from './directives.js'
8
8
  export { operationNames } from './generate/operations.js'
9
+ export { readInfra, InfraError } from './infra/config.js'
10
+ export { buildInfra, serverFiles, certificates } from './infra/build.js'
11
+ export { deploy } from './infra/deploy.js'
12
+ export { down } from './infra/down.js'
13
+ export { keygen } from './infra/keygen.js'
14
+ export { listBackups, restore, fetch as fetchBackup } from './infra/backups.js'
@@ -0,0 +1,77 @@
1
+ // ramdb2-cli infra backups, restore and fetch (D56), from the deployment machine: ramdb2-server-backup run in the
2
+ // backup container of the site, on its server (DOCKER_HOST), with the key of the server. The deployment machine
3
+ // needs no access to the backup server.
4
+ import { renameSync, rmSync } from 'node:fs'
5
+ import { check, runCommand, serverOf, withServer } from './server.js'
6
+
7
+ const BACKUP = '/app/node_modules/.bin/ramdb2-server-backup'
8
+
9
+ /**
10
+ * The backups of a site, oldest first.
11
+ * @param {import('./config.js').Infra} infra
12
+ * @param {string} site
13
+ * @param {{run?: import('./server.js').Runner}} [options]
14
+ * @returns {Promise<string[]>}
15
+ */
16
+ export async function listBackups(infra, site, { run = runCommand } = {}) {
17
+ return withServer(infra, serverOf(infra, site), run, async ({ compose, env }) => {
18
+ const result = await run('docker', [...compose, 'run', '--rm', '--no-deps', '-T', '-e', 'LOG_LEVEL=warn',
19
+ `${site}-backup`, BACKUP, 'list'], { env, capture: true })
20
+ if (result.code !== 0) throw new Error(`The backups of ${site} could not be listed: ${result.stderr.trim()}`)
21
+ return result.stdout.split('\n').filter(line => line !== '')
22
+ })
23
+ }
24
+
25
+ /**
26
+ * Restores the last backup of a site at or before `moment` (UTC; the last one by default): stops its API and its
27
+ * backups, restores, starts them again, even when the restore failed (the database is then unchanged).
28
+ * @param {import('./config.js').Infra} infra
29
+ * @param {string} site
30
+ * @param {object} [options]
31
+ * @param {string} [options.moment]
32
+ * @param {import('./server.js').Runner} [options.run]
33
+ * @param {(line: string) => void} [options.print]
34
+ */
35
+ export async function restore(infra, site, { moment, run = runCommand, print = console.log } = {}) {
36
+ const server = serverOf(infra, site)
37
+ return withServer(infra, server, run, async ({ compose, env }) => {
38
+ const services = [`${site}-api`, `${site}-backup`]
39
+ print(`${site}: stopping ${services.join(', ')} on ${server}`)
40
+ await check(run('docker', [...compose, 'stop', ...services], { env }), 'docker compose stop')
41
+ let restored
42
+ try {
43
+ restored = await run('docker', [...compose, 'run', '--rm', '--no-deps', '-T', `${site}-backup`, BACKUP, 'restore',
44
+ ...(moment === undefined ? [] : [moment])], { env })
45
+ } finally {
46
+ print(`${site}: starting ${services.join(', ')}`)
47
+ await check(run('docker', [...compose, 'start', ...services], { env }), 'docker compose start')
48
+ }
49
+ if (restored.code !== 0) throw new Error(`The restore of ${site} failed: its database is unchanged`)
50
+ print(`${site}: restored`)
51
+ })
52
+ }
53
+
54
+ /**
55
+ * Writes a backup of a site to a local file, decompressed and checked: the last one at or before `moment`.
56
+ * @param {import('./config.js').Infra} infra
57
+ * @param {string} site
58
+ * @param {string} file
59
+ * @param {object} [options]
60
+ * @param {string} [options.moment]
61
+ * @param {import('./server.js').Runner} [options.run]
62
+ */
63
+ export async function fetch(infra, site, file, { moment, run = runCommand } = {}) {
64
+ return withServer(infra, serverOf(infra, site), run, async ({ compose, env }) => {
65
+ // The database comes on the standard output; the messages of the command go to the error output
66
+ const script = `${BACKUP} fetch /tmp/fetched.db "$@" >&2 && cat /tmp/fetched.db`
67
+ const part = `${file}.part`
68
+ try {
69
+ const result = await run('docker', [...compose, 'run', '--rm', '--no-deps', '-T', '-e', 'LOG_LEVEL=warn',
70
+ `${site}-backup`, 'sh', '-c', script, 'sh', ...(moment === undefined ? [] : [moment])], { env, stdout: part })
71
+ if (result.code !== 0) throw new Error(`The backup of ${site} could not be fetched`)
72
+ renameSync(part, file)
73
+ } finally {
74
+ rmSync(part, { force: true })
75
+ }
76
+ })
77
+ }
@@ -0,0 +1,372 @@
1
+ // ramdb2-cli infra build (D55): the files of each server, in build/<server>/, from infra.yaml.
2
+ // Nothing is mounted from the deployment machine (DOCKER_HOST=ssh://): what comes from it goes through a build
3
+ // context (nginx configuration, Dockerfiles) or the environment of docker compose (secrets).
4
+ import { copyFileSync, mkdirSync, rmSync, writeFileSync } from 'node:fs'
5
+ import { join, relative } from 'node:path'
6
+ import { stringify } from 'yaml'
7
+
8
+ const HEADER = 'Generated by ramdb2-cli infra build from infra.yaml: do not edit, it is rewritten.'
9
+ const LOGGING = { driver: 'local', options: { 'max-size': '10m', 'max-file': '5' } }
10
+ const API_PORT = 4000
11
+
12
+ /**
13
+ * Writes build/<server>/ for each server (or for the given ones), replacing what was there.
14
+ * @param {import('./config.js').Infra} infra
15
+ * @param {string[]} [only] server names
16
+ * @returns {{server: string, dir: string, files: string[]}[]}
17
+ */
18
+ export function buildInfra(infra, only) {
19
+ const servers = only === undefined || only.length === 0 ? infra.servers : only.map(name => {
20
+ const server = infra.servers.find(candidate => candidate.name === name)
21
+ if (server === undefined) throw new Error(`No server ${name} in infra.yaml`)
22
+ return server
23
+ })
24
+ return servers.map(server => {
25
+ const dir = join(infra.dir, 'build', server.name)
26
+ rmSync(dir, { recursive: true, force: true })
27
+ const files = []
28
+ const write = (path, content) => {
29
+ const file = join(dir, path)
30
+ mkdirSync(join(file, '..'), { recursive: true })
31
+ writeFileSync(file, content, path.endsWith('.sh') ? { mode: 0o755 } : undefined)
32
+ files.push(file)
33
+ }
34
+ for (const [path, content] of Object.entries(serverFiles(infra, server, dir))) write(path, content)
35
+ for (const custom of server.custom) {
36
+ const file = join(dir, 'nginx', 'conf.d', `50-custom-${custom.name}.conf`)
37
+ copyFileSync(custom.nginx, file)
38
+ files.push(file)
39
+ }
40
+ return { server: server.name, dir, files }
41
+ })
42
+ }
43
+
44
+ /**
45
+ * The generated files of one server, by path in build/<server>/ (the custom nginx files are copied apart).
46
+ * @param {import('./config.js').Infra} infra
47
+ * @param {import('./config.js').Server} server
48
+ * @param {string} dir build/<server>/
49
+ * @returns {Record<string, string>}
50
+ */
51
+ export function serverFiles(infra, server, dir) {
52
+ const files = {
53
+ 'compose.yaml': compose(infra, server, dir),
54
+ 'certificates.json': JSON.stringify(certificates(server), null, 2) + '\n',
55
+ 'nginx/Dockerfile': FRONT_DOCKERFILE,
56
+ 'nginx/ramdb2-certs.sh': CERTS_SCRIPT,
57
+ 'nginx/certificates': certificates(server).map(certificate => certificate.name).join('\n') + '\n',
58
+ 'nginx/conf.d/00-ramdb2.conf': FRONT_DEFAULTS,
59
+ }
60
+ for (const site of server.sites) {
61
+ files[`nginx/conf.d/10-${site.name}.conf`] = siteNginx(site)
62
+ files[`${site.name}/api.Dockerfile`] = apiDockerfile(site)
63
+ files[`${site.name}/api.Dockerfile.dockerignore`] = DOCKERIGNORE
64
+ if (site.withClient) {
65
+ files[`${site.name}/web.Dockerfile`] = WEB_DOCKERFILE
66
+ files[`${site.name}/web.Dockerfile.dockerignore`] = DOCKERIGNORE
67
+ files[`${site.name}/web.nginx.conf`] = WEB_NGINX
68
+ }
69
+ }
70
+ return files
71
+ }
72
+
73
+ /**
74
+ * The certificates of a server: one per ramdb2 site (its domain and aliases), one per custom site with domains.
75
+ * The certificate is named after its first domain, its folder in /etc/letsencrypt/live/ and /etc/nginx/certs/.
76
+ * @param {import('./config.js').Server} server
77
+ * @returns {{name: string, domains: string[]}[]}
78
+ */
79
+ export function certificates(server) {
80
+ return [
81
+ ...server.sites.map(site => ({ name: site.domain, domains: [site.domain, ...site.aliases] })),
82
+ ...server.custom.filter(custom => custom.domains.length > 0).map(custom => ({ name: custom.domains[0], domains: custom.domains })),
83
+ ]
84
+ }
85
+
86
+ function compose(infra, server, dir) {
87
+ const services = {
88
+ nginx: {
89
+ build: './nginx',
90
+ ports: ['80:80', '443:443'],
91
+ volumes: ['letsencrypt:/etc/letsencrypt:ro', 'certbot-www:/var/www/certbot:ro'],
92
+ restart: 'unless-stopped',
93
+ logging: LOGGING,
94
+ },
95
+ certbot: {
96
+ image: 'certbot/certbot',
97
+ entrypoint: ['/bin/sh', '-c',
98
+ 'trap exit TERM; while :; do certbot renew --webroot -w /var/www/certbot --quiet; sleep 12h & wait $${!}; done'],
99
+ volumes: ['letsencrypt:/etc/letsencrypt', 'certbot-www:/var/www/certbot'],
100
+ restart: 'unless-stopped',
101
+ logging: LOGGING,
102
+ },
103
+ }
104
+ const volumes = { letsencrypt: {}, 'certbot-www': {} }
105
+ for (const site of server.sites) {
106
+ const context = relative(dir, site.source) || '.'
107
+ const dockerfile = join(dir, site.name, 'api.Dockerfile')
108
+ const database = `/data/${site.name}.db`
109
+ services[`${site.name}-api`] = {
110
+ build: { context, dockerfile, target: 'api' },
111
+ env_file: [`\${RAMDB2_SECRETS:?run ramdb2-cli infra deploy}/${site.name}.env`],
112
+ environment: { PORT: String(API_PORT), DB_PATH: database, NODE_ENV: 'production', TRUST_PROXY: '1' },
113
+ volumes: [`${site.name}-data:/data`],
114
+ ...(site.memory === undefined ? {} : { mem_limit: site.memory }),
115
+ stop_grace_period: '30s',
116
+ healthcheck: {
117
+ test: ['CMD', 'node', '-e', HEALTH_CHECK],
118
+ interval: '30s',
119
+ timeout: '5s',
120
+ retries: 3,
121
+ start_period: '60s',
122
+ },
123
+ restart: 'unless-stopped',
124
+ logging: LOGGING,
125
+ }
126
+ services[`${site.name}-backup`] = {
127
+ build: { context, dockerfile, target: 'backup' },
128
+ environment: {
129
+ DB_PATH: database,
130
+ BACKUP_TARGET: infra.backup.target,
131
+ BACKUP_SITE: site.name,
132
+ BACKUP_SSH_KEY: '${BACKUP_SSH_KEY:?run ramdb2-cli infra deploy}',
133
+ },
134
+ volumes: [`${site.name}-data:/data`],
135
+ stop_grace_period: '2m',
136
+ restart: 'unless-stopped',
137
+ logging: LOGGING,
138
+ }
139
+ if (site.withClient) {
140
+ services[`${site.name}-web`] = {
141
+ build: {
142
+ context,
143
+ dockerfile: join(dir, site.name, 'web.Dockerfile'),
144
+ additional_contexts: { infra: `./${site.name}` },
145
+ },
146
+ restart: 'unless-stopped',
147
+ logging: LOGGING,
148
+ }
149
+ }
150
+ volumes[`${site.name}-data`] = {}
151
+ }
152
+ const include = server.custom.filter(custom => custom.compose !== undefined).map(custom => relative(dir, custom.compose))
153
+ const document = { name: server.name, ...(include.length > 0 ? { include } : {}), services, volumes }
154
+ return `# ${HEADER}\n# Server ${server.name}: deploy with ramdb2-cli infra deploy ${server.name}\n`
155
+ + stringify(document, { lineWidth: 0, aliasDuplicateObjects: false })
156
+ }
157
+
158
+ // The GraphQL query health of the project (ramdb2-cli new), answered by the API itself
159
+ const HEALTH_CHECK = `fetch('http://127.0.0.1:${API_PORT}/', { method: 'POST', headers: { 'content-type': 'application/json' }, `
160
+ + `body: '{"query":"{ health }"}' }).then(response => response.json())`
161
+ + `.then(body => process.exit(body.data?.health?.open ? 0 : 1), () => process.exit(1))`
162
+
163
+ function siteNginx(site) {
164
+ const cert = ` ssl_certificate /etc/nginx/certs/${site.domain}/fullchain.pem;\n`
165
+ + ` ssl_certificate_key /etc/nginx/certs/${site.domain}/privkey.pem;\n`
166
+ const proxy = ' proxy_set_header Host $host;\n'
167
+ + ' proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;\n'
168
+ + ' proxy_set_header X-Forwarded-Proto $scheme;\n'
169
+ const aliases = site.aliases.length === 0 ? '' : `
170
+ # The aliases: redirected to ${site.domain}
171
+ server {
172
+ listen 443 ssl;
173
+ http2 on;
174
+ server_name ${site.aliases.join(' ')};
175
+ ${cert} return 301 https://${site.domain}$request_uri;
176
+ }
177
+ `
178
+ const locations = site.withClient ? ` # The API (the server answers on /, as with the proxy of Vite in development)
179
+ location = /graphql {
180
+ rewrite ^ / break;
181
+ proxy_pass $api;
182
+ ${proxy} }
183
+
184
+ # The web site
185
+ location / {
186
+ proxy_pass $web;
187
+ ${proxy} }
188
+ ` : ` # The API
189
+ location / {
190
+ proxy_pass $api;
191
+ ${proxy} }
192
+ `
193
+ return `# ${HEADER}
194
+ # Site ${site.name}
195
+
196
+ server {
197
+ listen 80;
198
+ server_name ${[site.domain, ...site.aliases].join(' ')};
199
+
200
+ location /.well-known/acme-challenge/ {
201
+ root /var/www/certbot;
202
+ }
203
+
204
+ location / {
205
+ return 301 https://${site.domain}$request_uri;
206
+ }
207
+ }
208
+ ${aliases}
209
+ server {
210
+ listen 443 ssl;
211
+ http2 on;
212
+ server_name ${site.domain};
213
+ ${cert} add_header Strict-Transport-Security "max-age=31536000" always;
214
+ client_max_body_size 10m;
215
+
216
+ # Resolved at each request: nginx starts even when a container of the site is down
217
+ set $api http://${site.name}-api:${API_PORT};
218
+ ${site.withClient ? ` set $web http://${site.name}-web:80;\n` : ''}
219
+ ${locations}}
220
+ `
221
+ }
222
+
223
+ function apiDockerfile(site) {
224
+ const install = site.withClient
225
+ ? `COPY package.json package-lock.json ./
226
+ COPY server/package.json server/
227
+ COPY web/package.json web/
228
+ RUN npm ci --omit=dev --ignore-scripts -w server
229
+ COPY server/ server/
230
+ WORKDIR /app/server`
231
+ : `COPY package.json package-lock.json ./
232
+ RUN npm ci --omit=dev --ignore-scripts
233
+ COPY . .`
234
+ return `# syntax=docker/dockerfile:1
235
+ # ${HEADER}
236
+ # Site ${site.name}: the API (target api) and its backups (target backup), on the same image.
237
+
238
+ FROM node:22-alpine AS api
239
+ WORKDIR /app
240
+ # --ignore-scripts: better-sqlite3 ships its compiled binaries (musl, x64 and arm64), found when it loads; without
241
+ # it, npm would compile it again (node-gyp, which needs Python and a compiler)
242
+ ${install}
243
+ # The database volume, owned by the user that runs the server
244
+ RUN mkdir -p /data && chown node:node /data
245
+ USER node
246
+ ENV NODE_ENV=production
247
+ # node itself, not npm: SIGTERM reaches the server, which closes SQLite
248
+ CMD ["node", "src/index.js"]
249
+
250
+ FROM api AS backup
251
+ USER root
252
+ RUN apk add --no-cache openssh-client
253
+ USER node
254
+ CMD ["/app/node_modules/.bin/ramdb2-server-backup", "schedule"]
255
+ `
256
+ }
257
+
258
+ const WEB_DOCKERFILE = `# syntax=docker/dockerfile:1
259
+ # ${HEADER}
260
+ # The web site: compiled by Vite, then served by nginx.
261
+
262
+ FROM node:22-alpine AS build
263
+ WORKDIR /app
264
+ COPY package.json package-lock.json ./
265
+ COPY server/package.json server/
266
+ COPY web/package.json web/
267
+ RUN npm ci --ignore-scripts -w web
268
+ COPY web/ web/
269
+ RUN npm run build -w web
270
+
271
+ FROM nginx:alpine
272
+ RUN rm /etc/nginx/conf.d/default.conf
273
+ COPY --from=infra web.nginx.conf /etc/nginx/conf.d/web.conf
274
+ COPY --from=build /app/web/dist /usr/share/nginx/html
275
+ `
276
+
277
+ const WEB_NGINX = `# ${HEADER}
278
+ server {
279
+ listen 80;
280
+ root /usr/share/nginx/html;
281
+
282
+ # The pages of the Vue router: index.html, never cached, so that a new version is seen at once
283
+ location / {
284
+ try_files $uri $uri/ /index.html;
285
+ add_header Cache-Control "no-cache";
286
+ }
287
+
288
+ # The compiled files carry a hash in their name: cached for a year
289
+ location /assets/ {
290
+ try_files $uri =404;
291
+ add_header Cache-Control "public, max-age=31536000, immutable";
292
+ }
293
+ }
294
+ `
295
+
296
+ const DOCKERIGNORE = `# ${HEADER}
297
+ # Never in an image: the dependencies (installed by npm ci), the databases, the backups, the secrets.
298
+ **/node_modules
299
+ data
300
+ backups
301
+ server/data
302
+ server/backups
303
+ dist
304
+ web/dist
305
+ .env
306
+ .env.*
307
+ **/.env
308
+ **/.env.*
309
+ .git
310
+ **/test-results
311
+ **/playwright-report
312
+ `
313
+
314
+ const FRONT_DOCKERFILE = `# syntax=docker/dockerfile:1
315
+ # ${HEADER}
316
+ # The front nginx: HTTPS, one domain per site. The configuration is in the image (nothing mounted).
317
+
318
+ FROM nginx:alpine
319
+ RUN apk add --no-cache openssl && rm /etc/nginx/conf.d/default.conf
320
+ COPY --chmod=755 ramdb2-certs.sh /usr/local/bin/ramdb2-certs
321
+ COPY certificates /etc/nginx/ramdb2-certificates
322
+ COPY conf.d/ /etc/nginx/conf.d/
323
+ # The certificates linked, then a reload every 6 hours, for the certificates renewed by certbot
324
+ CMD ["/bin/sh", "-c", "ramdb2-certs || exit 1; (while :; do sleep 6h; ramdb2-certs && nginx -s reload; done) & exec nginx -g 'daemon off;'"]
325
+ `
326
+
327
+ const CERTS_SCRIPT = `#!/bin/sh
328
+ # ${HEADER}
329
+ # Points /etc/nginx/certs/<name> to the Let's Encrypt certificate <name>, or, until certbot has it, to a self-signed
330
+ # one: nginx can start before the first certificate.
331
+ set -e
332
+ mkdir -p /etc/nginx/certs /etc/nginx/self-signed
333
+ while read -r name; do
334
+ [ -n "$name" ] || continue
335
+ if [ -f "/etc/letsencrypt/live/$name/fullchain.pem" ]; then
336
+ ln -sfn "/etc/letsencrypt/live/$name" "/etc/nginx/certs/$name"
337
+ else
338
+ if [ ! -f "/etc/nginx/self-signed/$name/fullchain.pem" ]; then
339
+ mkdir -p "/etc/nginx/self-signed/$name"
340
+ openssl req -x509 -nodes -newkey rsa:2048 -days 30 -subj "/CN=$name" \\
341
+ -keyout "/etc/nginx/self-signed/$name/privkey.pem" -out "/etc/nginx/self-signed/$name/fullchain.pem" 2>/dev/null
342
+ fi
343
+ ln -sfn "/etc/nginx/self-signed/$name" "/etc/nginx/certs/$name"
344
+ fi
345
+ done < /etc/nginx/ramdb2-certificates
346
+ `
347
+
348
+ const FRONT_DEFAULTS = `# ${HEADER}
349
+ server_tokens off;
350
+ # The DNS of Docker: the containers are found by their name, at each request
351
+ resolver 127.0.0.11 valid=10s ipv6=off;
352
+ gzip on;
353
+ gzip_types text/css application/javascript application/json image/svg+xml;
354
+
355
+ # An unknown domain: no answer
356
+ server {
357
+ listen 80 default_server;
358
+
359
+ location /.well-known/acme-challenge/ {
360
+ root /var/www/certbot;
361
+ }
362
+
363
+ location / {
364
+ return 444;
365
+ }
366
+ }
367
+
368
+ server {
369
+ listen 443 ssl default_server;
370
+ ssl_reject_handshake on;
371
+ }
372
+ `