@webship.co/workspace-umami 0.0.0-stage → 1.0.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.
@@ -0,0 +1,397 @@
1
+ #!/usr/bin/env bash
2
+
3
+ # Umami for the Webship Workspace: run the web analytics app from its official image on GHCR, by digest, with the
4
+ # project's PostgreSQL, replace its default admin password at once, and wire the step pack for Umami into the testing
5
+ # setup of such a project.
6
+ #
7
+ # Placed by `plugins.sh --install umami` in core/scripts/plugins/umami/functions/, where bootstrap sources it after the
8
+ # core's own functions. Everything runs in containers:
9
+ # on DDEV the image as a service of the project's own (.ddev/docker-compose.umami.yaml: its Next.js server;
10
+ # its start runs the database's migrations), DDEV's PostgreSQL 17 as its database, and DDEV's nginx
11
+ # sending the project's address to it (the plugin's own nginx config);
12
+ # elsewhere the image as the runtime layer's generic stack (its web container), with the stack's PostgreSQL 17;
13
+ # the image's own start as the server, as the stack's user.
14
+ #
15
+ # The app seeds its admin as admin / umami. At the first start the plugin replaces that password through the app's own
16
+ # API, from this machine (umami-admin.py, Python's standard library), with the one in .webship-umami/admin-password
17
+ # (0600), read on the script's input, never on a command line: the default never stays. Its telemetry and update check
18
+ # are off, and its websites' icons come from the app itself (FAVICON_URL, its PNG icon), so it makes no request elsewhere.
19
+ #
20
+ # The project's folder: .webship-umami/ (0700): umami.env (0600: the app's settings and secret), admin-password (0600),
21
+ # umami-admin.py, line.
22
+ #
23
+ # Its database is PostgreSQL, the core's own: the row's Backup and Restore dump and load it as for any project. A project
24
+ # of this builder is recognised by its mark (.ddev/config.umami.yaml on DDEV, `platform: umami` in compose.yaml
25
+ # elsewhere), and these names are the ones the core's tools look for:
26
+ # set_umami_users none by default
27
+ # add_umami_users the user "webship-viewer" (View only), its password in .webship-umami/
28
+ # cancel_umami_users that user removed
29
+ # testing_configure_umami the step pack in the testing stack (cmd-tools-testing.sh <project>)
30
+ # umami_is_project
31
+
32
+ readonly UMAMI_STEPS_PACKAGE='@webship-js/umami-steps';
33
+ readonly UMAMI_STEPS_VERSION='^2.0.0';
34
+
35
+ # The release the builder is proven with: the official image on GHCR, by digest. A newer one: put its name and digest
36
+ # here (and in the step pack's demo), and run its proofs (README).
37
+ readonly UMAMI_LINE='3.5.1';
38
+ readonly UMAMI_IMAGE='ghcr.io/umami-software/umami@sha256:3a7d6bc4a873db874c0674fd38cddb2507d416dc7beccacd19e2d196d02222a0'; # 3.5.1
39
+ readonly UMAMI_DATABASE='postgres:17';
40
+
41
+ readonly UMAMI_PORT='3000';
42
+ readonly UMAMI_OWN='.webship-umami';
43
+ readonly UMAMI_ADMIN='admin';
44
+ readonly UMAMI_VIEWER='webship-viewer';
45
+ readonly UMAMI_RUNTIMES='ddev docker podman kubernetes';
46
+ # The containers' memory limits, through the core's runtime layer (rt_memory); a person's `memory:` in
47
+ # core/config/plugin.umami.settings.yml wins. The app peaked near 380 MiB in the step pack's demo runs.
48
+ readonly UMAMI_MEMORY='768m';
49
+ readonly UMAMI_DB_MEMORY='384m';
50
+ readonly UMAMI_MAIL_MEMORY='128m';
51
+ readonly UMAMI_DDEV_WEB_MEMORY='512m';
52
+
53
+ # No default users.
54
+ function set_umami_users() {
55
+ users=();
56
+ }
57
+
58
+ function umami_runtime() {
59
+ if declare -f runtime_of > /dev/null ; then runtime_of ; else echo 'ddev' ; fi
60
+ }
61
+
62
+ function umami_url() {
63
+ if declare -f rt_url > /dev/null ; then rt_url ; else echo "https://${PROJECT_NAME}.ddev.site" ; fi
64
+ }
65
+
66
+ function umami_is_project() {
67
+ local project_path="$1";
68
+ [ -f "${project_path}/.ddev/config.umami.yaml" ] && return 0 ;
69
+ declare -f rt_is_platform > /dev/null && rt_is_platform "${project_path}" umami ;
70
+ }
71
+
72
+ function umami_plugin_dir() {
73
+ echo "${WORKSPACE_SCRIPTS}/plugins/umami" ;
74
+ }
75
+
76
+ # The app's settings (0600), read by its image's own start: the project's database (db/db/db, the core's), its secret
77
+ # and its two-factor key (made once), no telemetry, no update check, its websites' icons from itself.
78
+ # umami_write_env <project folder>
79
+ function umami_write_env() {
80
+ local project_path="$1" own ;
81
+ own="${project_path}/${UMAMI_OWN}" ;
82
+ ( umask 077
83
+ [ -s "${own}/app-secret" ] || python3 -c 'import secrets; print(secrets.token_hex(32), end="")' > "${own}/app-secret" ;
84
+ [ -s "${own}/two-factor-key" ] || python3 -c 'import secrets; print(secrets.token_hex(32), end="")' > "${own}/two-factor-key" ;
85
+ {
86
+ echo "# The settings of the project's Umami, written by the Umami builder of the workspace; build again rather than"
87
+ echo "# editing by hand."
88
+ echo "DATABASE_URL=postgresql://db:db@db:5432/db"
89
+ echo "APP_SECRET=$(cat "${own}/app-secret")"
90
+ echo "TWO_FACTOR_ENCRYPTION_KEY=$(cat "${own}/two-factor-key")"
91
+ echo "PORT=${UMAMI_PORT}"
92
+ # No request elsewhere: no telemetry, no update check, and the websites' icons from the app itself: its PNG icon,
93
+ # which a browser draws (an image of its /favicon.ico drew nothing in Chromium: a broken icon).
94
+ echo "DISABLE_TELEMETRY=1"
95
+ echo "DISABLE_UPDATES=1"
96
+ echo "FAVICON_URL=/favicon-32x32.png"
97
+ } > "${own}/umami.env"
98
+ ) ;
99
+ }
100
+
101
+ # The builder's own files: the admin's password (made once, kept on later builds), the line, the admin's script.
102
+ function umami_write_own() {
103
+ local project_path="$1" own from ;
104
+ own="${project_path}/${UMAMI_OWN}" ; from="$(umami_plugin_dir)" ;
105
+ mkdir -p -m 700 "${own}" && chmod 700 "${own}" || return 1 ;
106
+ ( umask 077
107
+ [ -s "${own}/admin-password" ] || python3 -c 'import secrets; print("Ws-" + secrets.token_urlsafe(18), end="")' > "${own}/admin-password" ;
108
+ printf '%s\n' "${UMAMI_LINE}" > "${own}/line" ;
109
+ ) || return 1 ;
110
+ cp "${from}/umami-admin.py" "${own}/" || return 1 ;
111
+ }
112
+
113
+ function umami_write_ddev_config() {
114
+ local project_path="$1" ;
115
+ mkdir -p "${project_path}/.ddev/nginx_full" || return 1 ;
116
+ {
117
+ echo "# Umami in this project: its official image as a service of the project's own, its database DDEV's PostgreSQL, the"
118
+ echo "# project's address sent to it by DDEV's nginx (nginx_full/nginx-site.conf). Written by the Umami builder of the"
119
+ echo "# workspace; build again rather than editing by hand."
120
+ echo "services:"
121
+ echo " umami:"
122
+ echo " container_name: ddev-\${DDEV_SITENAME}-umami"
123
+ echo " image: ${UMAMI_IMAGE}"
124
+ # Its start checks the database at once and stops when it does not answer yet: it waits for DDEV's database to be
125
+ # healthy, and starts again on a failure (a few times), so the project's address always has it behind it.
126
+ echo " restart: on-failure:5"
127
+ echo " init: true"
128
+ echo " env_file:"
129
+ echo " - ../${UMAMI_OWN}/umami.env"
130
+ echo " depends_on:"
131
+ echo " db:"
132
+ echo " condition: service_healthy"
133
+ echo " labels:"
134
+ echo " com.ddev.site-name: \${DDEV_SITENAME}"
135
+ echo " com.ddev.approot: \${DDEV_APPROOT}"
136
+ } > "${project_path}/.ddev/docker-compose.umami.yaml" ;
137
+ {
138
+ echo "# Umami in this project (docker-compose.umami.yaml). Written by the Umami builder of the workspace."
139
+ echo "webimage_extra_packages: []"
140
+ } > "${project_path}/.ddev/config.umami.yaml" ;
141
+ cat > "${project_path}/.ddev/nginx_full/nginx-site.conf" <<NGINX
142
+ # The project's address sent to Umami (the service umami, port ${UMAMI_PORT}). Written by the Umami builder of the
143
+ # workspace (not by DDEV: no generated mark, so DDEV keeps it); build again rather than editing by hand.
144
+ server {
145
+ listen 80 default_server;
146
+ listen 443 ssl default_server;
147
+
148
+ ssl_certificate /etc/ssl/certs/master.crt;
149
+ ssl_certificate_key /etc/ssl/certs/master.key;
150
+
151
+ include /etc/nginx/monitoring.conf;
152
+
153
+ client_max_body_size 20m;
154
+ error_log /dev/stdout info;
155
+ access_log /var/log/nginx/access.log;
156
+
157
+ # DDEV's router ends TLS and comes here over plain http: the scheme the app is told is the router's own
158
+ # (X-Forwarded-Proto), else this server's.
159
+ set \$forwarded_proto \$scheme;
160
+ if (\$http_x_forwarded_proto) {
161
+ set \$forwarded_proto \$http_x_forwarded_proto;
162
+ }
163
+
164
+ location / {
165
+ proxy_pass http://umami:${UMAMI_PORT};
166
+ proxy_http_version 1.1;
167
+ proxy_set_header Upgrade \$http_upgrade;
168
+ proxy_set_header Connection "upgrade";
169
+ proxy_set_header Host \$host;
170
+ proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
171
+ proxy_set_header X-Forwarded-Proto \$forwarded_proto;
172
+ proxy_set_header X-Forwarded-Host \$host;
173
+ proxy_read_timeout 300s;
174
+ proxy_max_temp_file_size 0;
175
+ }
176
+
177
+ include /etc/nginx/common.d/*.conf;
178
+ include /mnt/ddev_config/nginx/*.conf;
179
+ }
180
+ NGINX
181
+ }
182
+
183
+ function umami_runtime_config() {
184
+ rt_claim umami || return 1 ;
185
+ rt_stack image "${UMAMI_IMAGE}" || return 1 ;
186
+ # The image's start runs as its own user; on the stack it runs as the stack's user, so what the start writes (the
187
+ # tracker script it names, Next.js's cache) is given to it, and the image's entry point (its init) is not needed.
188
+ printf '%s\n' "# What the image's start writes, for the stack's user; the serve line is the start itself." \
189
+ "RUN chown -R www-data:www-data /app/public /app/.next" 'ENTRYPOINT []' \
190
+ | rt_web_build umami || return 1 ;
191
+ rt_serve "${UMAMI_PORT}" "$(umami_serve_line)" ;
192
+ }
193
+
194
+ # The command the web container runs off DDEV, from the project's root in it: the image's own start, its settings from
195
+ # the project's file.
196
+ function umami_serve_line() {
197
+ echo "set -a ; . ./${UMAMI_OWN}/umami.env ; set +a ; cd /app && exec sh scripts/start-docker.sh" ;
198
+ }
199
+
200
+ # The containers' memory limits (rt_memory): the app's (the service umami on DDEV, the stack's web container
201
+ # elsewhere), the database's and, off DDEV, the stack's mail catcher's.
202
+ function umami_memory() {
203
+ if [ "${1:-ddev}" = ddev ] ; then
204
+ rt_memory umami "${UMAMI_MEMORY}" || return 1 ;
205
+ rt_memory web "${UMAMI_DDEV_WEB_MEMORY}" || return 1 ;
206
+ else
207
+ rt_memory web "${UMAMI_MEMORY}" || return 1 ;
208
+ rt_memory mail "${UMAMI_MAIL_MEMORY}" || return 1 ;
209
+ fi
210
+ rt_memory db "${UMAMI_DB_MEMORY}" ;
211
+ }
212
+
213
+ # The plugin's script against the app's own API, from this machine, its input from the caller (a user's name, a role
214
+ # and a password, never on a command line). umami_admin_call <project folder> <command> < input
215
+ # command: admin (replace the default admin password), viewer (make or set again the view-only user), remove
216
+ function umami_admin_call() {
217
+ local project_path="$1" command="$2" url ;
218
+ url="$(cd "${project_path}" && PROJECT_NAME="$(basename "${project_path}")" umami_url)" ;
219
+ python3 -I "${project_path}/${UMAMI_OWN}/umami-admin.py" "${url}" "${command}" ;
220
+ }
221
+
222
+ # Replace the default admin password with the one in the project's file (once; a later build keeps it).
223
+ function umami_admin_password() {
224
+ local project_path="$1" ;
225
+ umami_admin_call "${project_path}" admin < "${project_path}/${UMAMI_OWN}/admin-password" | grep -qE '^admin (replaced|kept)$' ;
226
+ }
227
+
228
+ # Make (or set again) the view-only user, or remove it: its name and password on the input, the admin's password after.
229
+ # umami_user <project folder> <name> <viewer|remove> [<password file>]
230
+ function umami_user() {
231
+ local project_path="$1" name="$2" role="$3" file="${4:-}" ;
232
+ {
233
+ cat "${project_path}/${UMAMI_OWN}/admin-password" ; printf '\n%s\n' "${name}" ;
234
+ if [ -n "${file}" ] ; then cat "${file}" ; fi ; printf '\n' ;
235
+ } | umami_admin_call "${project_path}" "${role}" | grep -qE "^(made|removed) ${name}$" ;
236
+ }
237
+
238
+ # The app answers its heartbeat, from this machine.
239
+ function umami_healthy() {
240
+ local project_path="$1" url ;
241
+ url="$(cd "${project_path}" && PROJECT_NAME="$(basename "${project_path}")" umami_url)" ;
242
+ [ "$(curl -ks -o /dev/null -w '%{http_code}' --max-time 10 "${url}/api/heartbeat")" = 200 ] ;
243
+ }
244
+
245
+ # Wait for the app to answer, up to 10 minutes (its first start runs the database's migrations).
246
+ function umami_wait() {
247
+ local project_path="$1" attempt ;
248
+ for attempt in $(seq 1 120) ; do
249
+ umami_healthy "${project_path}" && return 0 ;
250
+ sleep 5 ;
251
+ done
252
+ echo "Umami does not answer its heartbeat." ;
253
+ return 1 ;
254
+ }
255
+
256
+ function umami_build() {
257
+ trim_project_name ;
258
+ local base_url runtime ;
259
+ runtime="$(umami_runtime)" ;
260
+ if [ "${RUNTIME:-_none_}" != '_none_' ] && [ "${RUNTIME}" != "${runtime}" ] ; then
261
+ echo "--runtime ${RUNTIME} needs a Webship Workspace with the container runtimes (webship/workspace#694): update the workspace, or build on DDEV." ;
262
+ exit 1 ;
263
+ fi
264
+ case " ${UMAMI_RUNTIMES} " in
265
+ *" ${runtime} "*) ;;
266
+ *) echo "Umami builds on DDEV, Docker Compose, Podman and Kubernetes for now (--runtime ddev, docker, podman or kubernetes), not on ${runtime}: that runtime is not proven for it yet. Nothing was changed." ; exit 1 ;;
267
+ esac
268
+ if ! declare -F rt_memory > /dev/null ; then
269
+ echo "Umami's containers are capped through the core's runtime layer: it needs Webship Workspace 1.0.60 or newer. Update the workspace. Nothing was changed." ;
270
+ exit 1 ;
271
+ fi
272
+ if [ ${#PROJECT_NAME} -gt 40 ] || ! [[ "${PROJECT_NAME}" =~ ^[a-z0-9][a-z0-9-]*$ ]] ; then
273
+ echo "The project name ${PROJECT_NAME} must be small letters, digits and dashes (its address and its containers take it). Nothing was changed." ;
274
+ exit 1 ;
275
+ fi
276
+ local project_path="${WORKSPACE_ROOT}/${doc_name}/${PROJECT_NAME}" ;
277
+
278
+ cd ${WORKSPACE_ROOT}/${doc_name} || exit 1 ;
279
+ drop_database ;
280
+ rm -rf "${PROJECT_NAME:?}" ;
281
+ mkdir -p "${PROJECT_NAME}" ;
282
+ cd "${project_path}" || exit 1 ;
283
+
284
+ if [ "${runtime}" == 'ddev' ] ; then
285
+ ddev config --project-type=php --docroot="" --database="${UMAMI_DATABASE}" --project-name=${PROJECT_NAME} --auto < /dev/null || exit 1 ;
286
+ else
287
+ ddev config --project-type=generic --webserver-type=generic --docroot="" --database="${UMAMI_DATABASE}" --project-name=${PROJECT_NAME} --auto < /dev/null || exit 1 ;
288
+ fi
289
+ umami_write_own "${project_path}" || { echo "Umami's own files could not be written." ; exit 1 ; } ;
290
+ if [ "${runtime}" == 'ddev' ] ; then
291
+ umami_write_ddev_config "${project_path}" || exit 1 ;
292
+ else
293
+ umami_runtime_config || { echo "Umami's stack could not be written through the runtime layer." ; exit 1 ; } ;
294
+ fi
295
+ base_url="$(umami_url)" ;
296
+ umami_write_env "${project_path}" || { echo "Umami's settings could not be written." ; exit 1 ; } ;
297
+ umami_memory "${runtime}" || { echo "Umami's memory limits could not be written through the runtime layer." ; exit 1 ; } ;
298
+
299
+ if [ "${INSTALL}" == 'yes' ] ; then
300
+ echo "Starting the project: Umami ${UMAMI_LINE} with PostgreSQL 17${runtime:+ on ${runtime}}; its first start runs the database's migrations." ;
301
+ ddev_up start -y < /dev/null || exit 1 ;
302
+ umami_wait "${project_path}" || exit 1 ;
303
+ umami_admin_password "${project_path}" || { echo "Umami's default admin password could not be replaced: do not leave the project running with it." ; exit 1 ; } ;
304
+ echo "${doc_name} ${PROJECT_NAME} is served: Umami ${UMAMI_LINE}, its default admin password replaced." ;
305
+ echo "Go to ${base_url} (sign in as ${UMAMI_ADMIN}; its password is in ${UMAMI_OWN}/admin-password)" ;
306
+ else
307
+ echo "${doc_name} ${PROJECT_NAME} is ready: Umami ${UMAMI_LINE}, at ${base_url} once started; build with --install to replace its default admin password." ;
308
+ fi
309
+ [ "${LAUNCH}" == 'yes' ] && ddev launch ;
310
+ cd ${WORKSPACE_ROOT}/${doc_name};
311
+ }
312
+
313
+ function add_umami_users() {
314
+ local project_path="${WORKSPACE_ROOT}/${doc_name}/${PROJECT_NAME}" own ;
315
+ own="${project_path}/${UMAMI_OWN}" ;
316
+ ( umask 077 ; python3 -c 'import secrets; print("Ws-" + secrets.token_urlsafe(15), end="")' > "${own}/webship-viewer-password" ) || return 1 ;
317
+ umami_user "${project_path}" "${UMAMI_VIEWER}" viewer "${own}/webship-viewer-password" || { echo " The user ${UMAMI_VIEWER} could not be made." ; return 1 ; } ;
318
+ echo " The user ${UMAMI_VIEWER} is made (View only: it reads the statistics and changes nothing); its password is in ${UMAMI_OWN}/webship-viewer-password." ;
319
+ }
320
+
321
+ function cancel_umami_users() {
322
+ local project_path="${WORKSPACE_ROOT}/${doc_name}/${PROJECT_NAME}" ;
323
+ umami_user "${project_path}" "${UMAMI_VIEWER}" remove \
324
+ || { echo " The user ${UMAMI_VIEWER} could not be removed." ; return 1 ; } ;
325
+ rm -f "${project_path}/${UMAMI_OWN}/webship-viewer-password" ;
326
+ echo " The user ${UMAMI_VIEWER} is removed." ;
327
+ }
328
+
329
+ # ---------------------------------------------------------------------------------------------------------------------
330
+ # The step pack in the testing stack
331
+ # ---------------------------------------------------------------------------------------------------------------------
332
+
333
+ # The step pack in the testing stack of a project of this builder: the pack in package.json, its step definitions in
334
+ # cucumber.js after webship-js's own, the project's address where the scaffold has its placeholder, and its settings:
335
+ # the admin's name and the project's file of its password (read at the run, never written into cucumber.js). Every
336
+ # part is skipped when it is already done.
337
+ function testing_configure_umami() {
338
+ local project_path="$1" address ;
339
+ umami_is_project "${project_path}" || return 0 ;
340
+ if [ ! -f "${project_path}/cucumber.js" ] || [ ! -f "${project_path}/package.json" ] ; then
341
+ echo " Umami: cucumber.js is not here yet — run the testing setup again once webship-js is scaffolded." ;
342
+ return 1 ;
343
+ fi
344
+ address="$(cd "${project_path}" && PROJECT_NAME="${PROJECT_NAME:-$(basename "${project_path}")}" umami_url)" ;
345
+ echo "Adding the step pack for Umami (${UMAMI_STEPS_PACKAGE} ${UMAMI_STEPS_VERSION}).";
346
+ python3 - "${project_path}" "${UMAMI_STEPS_PACKAGE}" "${UMAMI_STEPS_VERSION}" "${address}" "${UMAMI_OWN}" "${UMAMI_ADMIN}" <<'PYEOF' || return 1
347
+ import json, re, sys
348
+
349
+ project, pack, version, address, own, admin = sys.argv[1:7]
350
+
351
+ pkg_file = project + '/package.json'
352
+ pkg = json.load(open(pkg_file))
353
+ if pack not in pkg.get('dependencies', {}) and pack not in pkg.get('devDependencies', {}):
354
+ pkg.setdefault('devDependencies', {})[pack] = version
355
+ open(pkg_file, 'w').write(json.dumps(pkg, indent=2) + '\n')
356
+ print(' package.json: %s %s' % (pack, version))
357
+
358
+ cucumber_file = project + '/cucumber.js'
359
+ src = open(cucumber_file).read()
360
+ before = src
361
+
362
+ if ('node_modules/%s/' % pack) not in src:
363
+ entry = "'node_modules/%s/tests/step-definitions/*.js'," % pack
364
+ core = re.search(r"^([ \t]*)'node_modules/webship-js/tests/step-definitions/[^']*',.*$", src, re.M)
365
+ opening = re.search(r"^([ \t]*)require:[ \t]*\[[ \t]*$", src, re.M)
366
+ if core:
367
+ src = src[:core.end()] + '\n' + core.group(1) + entry + src[core.end():]
368
+ elif opening:
369
+ src = src[:opening.end()] + '\n' + opening.group(1) + ' ' + entry + src[opening.end():]
370
+ else:
371
+ sys.exit(" cucumber.js has no require list this can add to. Add this line to it:\n " + entry)
372
+ print(' cucumber.js: the step definitions of %s' % pack)
373
+
374
+ wp = re.search(r"^([ \t]*)worldParameters:[ \t]*\{[ \t]*$", src, re.M)
375
+ if wp and not re.search(r"^\s*webAnalytics:\s*\{", src, re.M):
376
+ indent = wp.group(1) + ' '
377
+ lines = ["// Umami: its admin, and the project's file of the admin's password (read at the run, never written here).",
378
+ "webAnalytics: {",
379
+ " username: %s," % json.dumps(admin),
380
+ " passwordFile: process.env.UMAMI_PASSWORD_FILE || require('path').join(__dirname, '%s/admin-password')," % own,
381
+ "},"]
382
+ src = src[:wp.end()] + '\n' + '\n'.join(indent + l for l in lines) + src[wp.end():]
383
+ print(" cucumber.js: the admin and the file of its password")
384
+
385
+ placeholder = "process.env.LAUNCH_URL || 'http://localhost:8080'"
386
+ if address and placeholder in src:
387
+ src = src.replace(placeholder, "process.env.LAUNCH_URL || '%s'" % address)
388
+ print(' cucumber.js: the address of the app (%s)' % address)
389
+
390
+ if src != before:
391
+ open(cucumber_file, 'w').write(src)
392
+ PYEOF
393
+ local feature="$(umami_plugin_dir)/site.feature" ;
394
+ if [ -f "${feature}" ] && [ ! -f "${project_path}/tests/features/site.feature" ] ; then
395
+ mkdir -p "${project_path}/tests/features" && cp "${feature}" "${project_path}/tests/features/site.feature" && echo " tests/features/site.feature: a first feature" ;
396
+ fi
397
+ }
@@ -0,0 +1,104 @@
1
+ """The admin's password and the users of a project's Umami, through the app's own API, from this machine (Python's
2
+ standard library only). The Umami builder of the Webship Workspace copies this file into the project (.webship-umami/)
3
+ and runs
4
+
5
+ python3 -I umami-admin.py <the app's address> <command> with its input from the builder, never a command line:
6
+
7
+ admin input: the new admin password. The app seeds its admin as admin / umami: the default password is replaced
8
+ with the new one; when the default no longer signs in and the new one does, it is kept. Says "admin replaced"
9
+ or "admin kept".
10
+ viewer input: the admin's password, the user's name, its password. Makes the user (role View only), or sets its
11
+ password and role again when it is there. Says "made <name>".
12
+ remove input: the admin's password, the user's name. Removes the user (never the admin). Says "removed <name>".
13
+
14
+ The project's address may be DDEV's https with its own certificate: the request does not ask a public authority for it.
15
+ """
16
+ import json
17
+ import ssl
18
+ import sys
19
+ import urllib.error
20
+ import urllib.request
21
+
22
+ BASE = sys.argv[1].rstrip('/')
23
+ COMMAND = sys.argv[2] if len(sys.argv) > 2 else ''
24
+ CONTEXT = ssl.create_default_context()
25
+ CONTEXT.check_hostname = False
26
+ CONTEXT.verify_mode = ssl.CERT_NONE
27
+
28
+
29
+ def call(method, path, data=None, token=None):
30
+ req = urllib.request.Request(BASE + path, method=method, data=json.dumps(data).encode() if data is not None else None)
31
+ req.add_header('Content-Type', 'application/json')
32
+ req.add_header('User-Agent', 'webship-workspace')
33
+ if token:
34
+ req.add_header('Authorization', f'Bearer {token}')
35
+ try:
36
+ with urllib.request.urlopen(req, timeout=30, context=CONTEXT) as res:
37
+ body = res.read().decode() or '{}'
38
+ return res.status, (json.loads(body) if body.strip().startswith(('{', '[')) else {})
39
+ except urllib.error.HTTPError as e:
40
+ return e.code, {}
41
+
42
+
43
+ def login(username, password):
44
+ status, body = call('POST', '/api/auth/login', {'username': username, 'password': password})
45
+ return body.get('token') if status == 200 else None
46
+
47
+
48
+ def line():
49
+ # The next line that is not empty (a password file may end with a newline of its own).
50
+ for raw in sys.stdin:
51
+ if raw.strip():
52
+ return raw.strip()
53
+ return ''
54
+
55
+
56
+ def main():
57
+ if COMMAND == 'admin':
58
+ password = line()
59
+ if len(password) < 12:
60
+ raise SystemExit('The admin password must be 12 characters or more.')
61
+ token = login('admin', 'umami')
62
+ if token:
63
+ status, _ = call('POST', '/api/me/password', {'currentPassword': 'umami', 'newPassword': password}, token)
64
+ if status != 200 or not login('admin', password):
65
+ raise SystemExit(f'The default admin password could not be replaced (the app answered {status}).')
66
+ print('admin replaced')
67
+ elif login('admin', password):
68
+ print('admin kept')
69
+ else:
70
+ raise SystemExit('The admin signs in neither with the default password nor with the one in its file.')
71
+ return
72
+ admin_password = line()
73
+ name = line()
74
+ if not name or name.lower() == 'admin':
75
+ raise SystemExit('A user\'s name, please (never the admin\'s).')
76
+ token = login('admin', admin_password)
77
+ if not token:
78
+ raise SystemExit('The admin could not sign in with the password in its file.')
79
+ status, body = call('GET', '/api/admin/users?pageSize=500', token=token)
80
+ users = body.get('data', []) if isinstance(body, dict) else []
81
+ found = [u for u in users if str(u.get('username', '')).lower() == name.lower()]
82
+ if COMMAND == 'viewer':
83
+ password = line()
84
+ if len(password) < 12:
85
+ raise SystemExit('The user\'s password must be 12 characters or more.')
86
+ if found:
87
+ status, _ = call('POST', f'/api/users/{found[0]["id"]}', {'username': name, 'password': password, 'role': 'view-only'}, token)
88
+ else:
89
+ status, _ = call('POST', '/api/users', {'username': name, 'password': password, 'role': 'view-only'}, token)
90
+ if status != 200:
91
+ raise SystemExit(f'The user {name} could not be made (the app answered {status}).')
92
+ print(f'made {name}')
93
+ elif COMMAND == 'remove':
94
+ for u in found:
95
+ if u.get('role') == 'admin' and u.get('username') == 'admin':
96
+ continue
97
+ call('DELETE', f'/api/users/{u["id"]}', token=token)
98
+ print(f'removed {name}')
99
+ else:
100
+ raise SystemExit('A command, please: admin, viewer or remove.')
101
+
102
+
103
+ if __name__ == '__main__':
104
+ main()
@@ -0,0 +1,19 @@
1
+ Feature: The project's Umami
2
+ As the keeper of the project's website statistics
3
+ I want to sign in, add a website and see it counted
4
+ So that I know the app works for its people
5
+
6
+ Scenario: The admin signs in, its sign-in is kept safe, and it signs out
7
+ Given I am signed in to the web analytics as its admin
8
+ Then the web analytics' sign-in should be kept safe for its scheme
9
+ And the web analytics should offer "Add website"
10
+ When I sign out of the web analytics
11
+ Then I should be signed out of the web analytics
12
+ And the web analytics should make no outside requests
13
+
14
+ Scenario: A website added and counted
15
+ Given I am signed in to the web analytics as its admin
16
+ When I add the website "First Site" for the domain "first.example"
17
+ Then the website "First Site" should show its icon
18
+ When I send page views of "/" and "/about" to the website "First Site"
19
+ Then the website "First Site" should count 2 views