@xeplr/cli 0.6.0 → 0.7.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.
package/README.md CHANGED
@@ -41,6 +41,23 @@ Already working, with nothing to wire up:
41
41
  - **Menu**: rename, reorder and hide the side rail's items.
42
42
 
43
43
  Nobody else sees it, and the API refuses everyone else.
44
+ - **Settings that never fail a deploy** ([`@xeplr/setup`](https://www.npmjs.com/package/@xeplr/setup)) —
45
+ `api/setup.schema.js` describes every setting `api/env.required.js` lists.
46
+ On a server with no settings yet the API does not exit: it serves a **setup
47
+ page** on its own port (`/setup`, behind a one-time code in `api/SETUP_CODE`,
48
+ never printed), asks only what a person knows (database server and password,
49
+ database names, data folder, Super Admin email, domain), generates or works
50
+ out the rest (keys, the encrypted logins, email links, the first Super Admin
51
+ password in `api/FIRST_LOGIN`), and restarts into the app, which makes its
52
+ databases. The sign-in service waits meanwhile. Mail is a feature: missing,
53
+ the app runs without it. `deploy/api.service` and `deploy/auth.service` are
54
+ systemd units with `Restart=always`.
55
+ - **App settings** for Super Admin, in the settings menu — the install's
56
+ settings seen and changed in place ([`@xeplr/ui-setup`](https://www.npmjs.com/package/@xeplr/ui-setup)
57
+ on `/api/app-settings`): secrets shown only as *set*, generated keys never
58
+ changeable, the database login tried before saving, every change recorded in
59
+ `settings_audit` (names only), then both services restart into it. A
60
+ `system`-scope API mapped to Super Admin alone (`migrations-auth/0006`).
44
61
  - **Flows, in every app** — your forms one after another. Designed in
45
62
  Configure UI → Flows: for each screen, the app's functions that run around
46
63
  its records (its events) and where the journey goes once it is saved — a
@@ -94,6 +111,8 @@ These are architecture decisions, not defaults to tune — each one exists becau
94
111
  | **Every file the app keeps is under `XEPLR_DATA_DIR`** — absolute, a folder per company. | `@xeplr/actions`, `@xeplr/factory`, `api/development.env` | One folder to back up, and no company reads another's files. A relative or missing folder is refused rather than read as empty. |
95
112
  | **Every data address is under `/api`.** | `api/routes`, `ui/vite.config.js` | A page path and a data path must never collide. |
96
113
  | **No guessed database names or connections.** | `api/development.env` | A wrong-but-present value starts cleanly and reads as empty data. |
114
+ | **A missing setting never stops a deploy.** Core missing → the setup page; a feature's (mail) → that feature off; set but unreadable (a login this key cannot decrypt) → the setup page asks again. | `api/setup.schema.js`, `@xeplr/setup`, `@xeplr/base-apis` | Nobody hand-writes a production env file, and nothing crash-loops waiting for one. |
115
+ | **App settings is Super Admin only, and audited.** | `api/routes/appSettings.js`, `migrations-auth/0006` | It rewrites the whole install for every company on it; a company admin's rights end at their company. |
97
116
  | **Email is checked at start, never fatal.** The sign-in banner shows `email ✓ …` or `✗ NOT WORKING — reason`. | `@xeplr/auth` | Sign-in works without email; activation, invite and reset links cannot be sent until `EMAIL_PROVIDER` is set. |
98
117
 
99
118
  ## Before you start
@@ -228,8 +247,9 @@ above it in `api/development.env`.
228
247
  That is deliberate. Host, port, user and password are encrypted together into a
229
248
  single string, and a guessed value would start cleanly, migrate, serve traffic,
230
249
  and read as *empty data* rather than as an error — the most expensive way for
231
- this to go wrong. Until you fill it in, the app refuses to start and names the
232
- setting.
250
+ this to go wrong. Until you fill it in, the API serves its setup page
251
+ (`http://127.0.0.1:<api port>/setup`, the code in `api/SETUP_CODE`) and the
252
+ sign-in service waits — or fill it from the terminal with `npm run db:encrypt`.
233
253
 
234
254
  The same rule applies to every database name and storage path in a xeplr app:
235
255
  no defaults, ever.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@xeplr/cli",
3
- "version": "0.6.0",
3
+ "version": "0.7.0",
4
4
  "description": "Creates a working xeplr application — API, sign-in and UI — from a few answers.",
5
5
  "license": "MIT",
6
6
  "author": "xeppie <admin@xeplr.com>",
@@ -87,6 +87,8 @@ breaks nothing.
87
87
  Activate new accounts there. Designing and publishing forms stays Super Admin
88
88
  only (`api/routes/access.js`).
89
89
 
90
+ **App settings** (settings menu, Super Admin only): the install's own settings — database login, mail, folders, domain — changed in place; the app restarts into them (about 20 seconds). Secrets show only *set*; generated keys cannot be changed; the database login is tried before anything is saved; every change is recorded (who, when, which names). On a new server the API shows a **setup page** at `/setup` first (the code is in `api/SETUP_CODE` on the server).
91
+
90
92
  A button only some people may press — Reopen, for managers — checks the
91
93
  caller's roles inside its function (step 6, `system.access.roles`).
92
94
 
@@ -76,6 +76,8 @@ Replace the bold parts. Add behaviour in the same message if you want it — "a
76
76
  - A published screen's design lives in the **database**. Editing its `.screen.json` changes nothing afterwards: publish the change in Configure UI → Forms.
77
77
  - Every data address is under `/api` (a page and a data path must never collide). New routes go in `api/routes/index.js`, and `ui/vite.config.js` must proxy their prefix.
78
78
  - Designing and publishing are **Super Admin only** (`api/routes/access.js`); every other route checks the permission catalog.
79
+ - **Settings never fail a deploy** (`api/setup.schema.js`, `@xeplr/setup`). A new required setting goes in `api/env.required.js` AND gets its description in `setup.schema.js` (`generated`, `derived`, `where: 'database'|'path'`, `secret`, or a feature list when the app can run without it) — never a `process.env.X || 'default'`. Core missing → the API serves `/setup`; **App settings** (`/settings/app`, `api/routes/appSettings.js`) changes them later, Super Admin only, audited in `settings_audit` (names only). Never print or log a secret, the setup code or the first password.
80
+ - Every new API route: its `apis` row (name + group) and role mappings in a new `api/migrations-auth/000N_*.sql`, same change. Super Admin alone only for `scope 'system'` rows (like `0006_app_settings.sql`).
79
81
  - The browser is not a security boundary: anything that must hold goes in a server function, named in the screen's events.
80
82
  - Hooks and models are **methods** calling `super` — never arrow-function properties.
81
83
  - `authFetch` returns the parsed body, not a Response.
@@ -42,9 +42,33 @@ locally (`ui/vite.config.js`, from `ui/.env`), nginx in production.
42
42
 
43
43
  ### Production
44
44
 
45
- `api/production.env.example` lists every setting (copy it to
46
- `api/production.env`, fill in, start with `NODE_ENV=production`). Build the UI
47
- (`cd ui && npm run build`) and let nginx serve it and route the paths:
45
+ **Settings never fail a deploy** (`@xeplr/setup`, `api/setup.schema.js`).
46
+ Start the two services with the units in `deploy/` (`api.service`,
47
+ `auth.service` — `Restart=always`, `NODE_ENV=production`). With no
48
+ `api/production.env` yet — or one missing something only a person knows —
49
+ the API does not exit: it serves **the setup page** on its own port
50
+ (`https://<domain>/setup`, or `http://127.0.0.1:__API_PORT__/setup`), behind a
51
+ one-time code written to `api/SETUP_CODE` (read it on the server; it is never
52
+ printed). The page asks for the database server and password, the database
53
+ names, the data folder, the Super Admin's email and the domain; everything
54
+ else is generated or worked out — the encryption key, the sign-in secret, the
55
+ encrypted logins, the email links, and the first Super Admin password (in
56
+ `api/FIRST_LOGIN`, never printed). Saving writes `api/production.env`, the
57
+ services restart into it, and the API makes its databases. The sign-in
58
+ service waits meanwhile instead of crash-looping. The API's port
59
+ (`__PREFIX___PORT`) must be in the file (or the unit's environment) for the
60
+ page to be reachable: copy `api/production.env.example` as a start.
61
+
62
+ Mail (`SMTP_*`) is a feature: missing, the app runs and only the Super Admin
63
+ can get in; `GET /setup/status` says what it needs.
64
+
65
+ **After setup**, the Super Admin changes settings on **App settings** (the
66
+ settings menu, top right; `@xeplr/ui-setup`). Generated values are never
67
+ changeable there; secrets show only *set*; every live check (the database
68
+ login) must pass; every change is recorded in `settings_audit` (names only,
69
+ never values); then both services restart into it.
70
+
71
+ Build the UI (`cd ui && npm run build`) and let nginx serve it and route the paths:
48
72
 
49
73
  ```nginx
50
74
  server {
@@ -55,6 +79,7 @@ server {
55
79
  location /api/ { proxy_pass http://127.0.0.1:__API_PORT__; }
56
80
  location = /health { proxy_pass http://127.0.0.1:__API_PORT__; }
57
81
  location = /whoami { proxy_pass http://127.0.0.1:__API_PORT__; }
82
+ location /setup { proxy_pass http://127.0.0.1:__API_PORT__; } # setup page + /setup/status
58
83
  location / { try_files $uri /index.html; } # the React app's own pages
59
84
  }
60
85
  ```
@@ -65,6 +90,7 @@ Every one of these checks the same sign-in token, so one login covers them all.
65
90
 
66
91
  - **Sign-in** — login, register, password reset, profile, and the admin screens for users, roles and permissions (`@xeplr/auth`, `@xeplr/ui-account`).
67
92
  - **Tasks** — a sample built from screens: a list, and a form it opens on a page of its own, saved into an ordinary `tasks` table. The form is filled in over three steps and uses every control there is — text, a dropdown, radio buttons, a tick box, a date, a date and time, several tags at once, and a file.
93
+ - **App settings** — in the settings menu, for Super Admin: every setting the install runs with (its env file), changed in place; the app restarts into the change, and every change is recorded (`@xeplr/setup`, `@xeplr/ui-setup`). Before the first setup the API serves a setup page instead — see Production.
68
94
  - **Configure UI** — in the settings menu, for Super Admin: every form (make one, design it, publish it, add it to the side rail), every flow (screens one after another — each screen's events, and where it goes next) and the side rail itself (rename, reorder, hide).
69
95
  - **Flows** — in the side rail: the journeys people can start, run by `@xeplr/workflow-api` inside the API.
70
96
  - **A phone app** — `mobile/` (Expo): every form added to the menu, its list, add / edit, its buttons and the journeys, drawn natively from what the server holds — no screen code, nothing to change when a form is added (see `mobile/README.md`).
@@ -91,6 +117,8 @@ __WF_README__
91
117
  | A **key** and a **label**, everywhere: code uses keys (form keys, menu keys); people read labels, renamed in Configure UI. | Renaming what people see never breaks code. |
92
118
  | **`REDIS_PREFIX`** in `api/development.env` is required and unique to this app. | Apps sharing a Redis would otherwise serve each other's sessions and permissions. |
93
119
  | Designing and publishing forms is **Super Admin only**. | Publishing changes database tables. |
120
+ | **App settings** is **Super Admin only** (a `system`-scope API); generated values (`ENCRYPTION_KEY`, `AUTH_JWT_SECRET`) are never changeable, secrets never shown, every change audited by name. | It changes the whole install, for every company on it. A new key would make every stored login unreadable. |
121
+ | A missing setting **never stops the deploy**: core missing → the setup page; a feature's (mail) → that feature off. | Nobody hand-writes the env file; nothing crash-loops. |
94
122
  | Rules that must hold go in **server functions** (`api/functions/`), named in a screen's events; the browser only shapes what people see and send. | The browser is not a security boundary. |
95
123
  | Every data address is under **`/api`**. | A page and a data path must never collide. |
96
124
  | A screen is a **document**; a button is a **registered function and its parameters**; a page written by hand is **web only**, listed in `ui/pages.json` with the reason. | What is a document can be drawn anywhere — a phone app too. The pre-commit hook and Configure UI → Menu say which pages are not. |
@@ -7,8 +7,8 @@ The API (`@xeplr/base-apis`) and the sign-in service (`@xeplr/auth`), with this
7
7
  | Command | Does |
8
8
  |---|---|
9
9
  | `npm run setup` | create both databases (`__DB_AUTH__`, `__DB_API__`), the sign-in tables, permissions and menus |
10
- | `npm run start-auth` | the sign-in service, port __AUTH_PORT__ — refuses to start without Redis or `REDIS_PREFIX`; its banner says whether email works |
11
- | `npm run start-api` | the API, port __API_PORT__ — runs `migrations/` and publishes never-published screens on start |
10
+ | `npm run start-auth` | the sign-in service (`bin/auth.js`), port __AUTH_PORT__ — waits while the app is being set up, makes its database when missing; refuses to start without Redis or `REDIS_PREFIX`; its banner says whether email works |
11
+ | `npm run start-api` | the API, port __API_PORT__ — core settings missing: serves the **setup page** at `/setup` instead (the code is in `SETUP_CODE`); otherwise makes `DB_API` when missing, runs `migrations/` and publishes never-published screens on start |
12
12
  | `npm run migrate:auth` | apply new `migrations-auth/*.sql` (a new menu row, say), then restart sign-in |
13
13
  | `npm run db:encrypt` | redo the encrypted database connection |
14
14
  | `npm run check-env` | check every required setting is present |
@@ -20,7 +20,11 @@ The API (`@xeplr/base-apis`) and the sign-in service (`@xeplr/auth`), with this
20
20
  | Path | What |
21
21
  |---|---|
22
22
  | `development.env` | every setting — ports, the encrypted connection, `REDIS_PREFIX`, secrets, the super admin, email |
23
- | `env.required.js` | the settings that must be present; the API refuses to start and names any that are missing |
23
+ | `env.required.js` | the settings that must be present — every library's own `requiredEnv` spread in |
24
+ | `setup.schema.js` | how each of those gets its value (`@xeplr/setup`): generated (keys, the first Super Admin password → `FIRST_LOGIN`), worked out (the encrypted logins from `DB_HOST`/`DB_PASSWORD`, the email links from `SERVER_NAME`, `AUTH_URL`), or asked on the setup page; mail (`SMTP_*`) is the `email` feature — missing means off, not a stopped app |
25
+ | `bin/www`, `bin/auth.js` | the API and the sign-in service: setup mode / wait for setup; in production `bin/auth.js` restarts when the env file changes (`restartOnChange`) |
26
+ | `routes/appSettings.js` | **App settings** — `/api/app-settings` (`@xeplr/setup` `settingsRouter`): Super Admin only (`requireApi` + role), audited into `settings_audit` (`migrations/0002`), names only; restarts the API (exit 75) |
27
+ | `../deploy/*.service` | systemd units, `Restart=always` — how a saved setting takes effect |
24
28
  | `app.js` | the Express app: the auth gate, and the routes |
25
29
  | `routes/index.js` | this app's own routes — every data address under `/api` |
26
30
  | `routes/access.js` | who may design and publish forms (Super Admin) |
@@ -34,9 +38,14 @@ The API (`@xeplr/base-apis`) and the sign-in service (`@xeplr/auth`), with this
34
38
 
35
39
  ## Settings to know
36
40
 
41
+ On a server none of these is typed by hand: the setup page asks what only a person knows, the rest is generated or worked out, and **App settings** changes them later (Super Admin). `SETUP_CODE` and `FIRST_LOGIN` (beside the env file, 0600) hold the setup code and the first Super Admin password — never printed.
42
+
43
+
37
44
  | Setting | |
38
45
  |---|---|
39
46
  | `REDIS_PREFIX` | **required, unique to this app** (`__NAME__:`) |
47
+ | `DB_HOST`, `DB_PORT`, `DB_USER`, `DB_PASSWORD` | asked by the setup page / App settings only to make the encrypted logins below; the password is cleared from the file once encrypted |
48
+ | `SERVER_NAME` | the domain people open — the email links are built from it when they are not set |
40
49
  | `XEPLR_DATA_DIR` | **required, absolute, existing**: where every file the app keeps lives, a folder per company (`<root>/__NAME__/<company>/…`). Generated as `api/data`; on a server, somewhere backed up |
41
50
  | `__PREFIX___CONNECTION`, `AUTH_DB_CONNECTION_INFO_ENCRYPTED` | the database, encrypted — `npm run db:encrypt` |
42
51
  | `DB_API`, `AUTH_DB_NAME` | the two database names — never guessed |
@@ -2,6 +2,7 @@ var createApp = require('@xeplr/base-apis/express');
2
2
  var factory = require('@xeplr/factory');
3
3
  var routes = require('./routes');
4
4
  var access = require('./routes/access');
5
+ var appSettings = require('./routes/appSettings');
5
6
  __MT_APP_REQUIRE__
6
7
 
7
8
  // Every screen route first checks the caller may use the request's
@@ -15,9 +16,26 @@ var port = process.env.__PREFIX___PORT;
15
16
  module.exports = buildApp;
16
17
  // bin/www hands the same gate to the flows router it starts (workflow.js).
17
18
  module.exports.memberGate = memberGate;
19
+ module.exports.setupMode = setupMode;
18
20
 
19
- function buildApp(extraRoutes) {
21
+ /**
22
+ * Core settings missing (bin/www): NO app — the setup page on this port,
23
+ * served by @xeplr/setup through createApp. → { setupMode: true, ready }
24
+ */
25
+ function setupMode(setupConfig, invalid) {
26
+ return createApp(port, '__NAME___api', { setup: Object.assign({}, setupConfig, { invalid: invalid || [] }) });
27
+ }
28
+
29
+ /**
30
+ * @param {object} [extraRoutes] { '<mountPath>': router }
31
+ * @param {object} [opts] { setup: setup.schema.js config() + { env } } — bin/www
32
+ */
33
+ function buildApp(extraRoutes, opts) {
34
+ opts = opts || {};
20
35
  return createApp(port, '__NAME___api', {
36
+ // GET /setup/status (before the gate): which features are off for which
37
+ // setting. bin/www already decided this is not setup mode.
38
+ setup: opts.setup,
21
39
  // Every route needs a valid token, checked against the auth service at
22
40
  // AUTH_URL. This app names no `middleware` of its own — it takes the
23
41
  // framework's gate rather than writing one.
@@ -30,6 +48,11 @@ function buildApp(extraRoutes) {
30
48
  __MT_APP_MIDDLEWARE__
31
49
  routes: Object.assign({}, extraRoutes || {}, {
32
50
  '/': routes,
51
+
52
+ // THE APP'S OWN SETTINGS (settings menu → App settings, Super Admin
53
+ // only): the env file seen and changed after setup; the app restarts
54
+ // into the change (routes/appSettings.js, migrations-auth/0006).
55
+ '/api/app-settings': appSettings(opts.setup),
33
56
  __MT_APP_ROUTES__
34
57
 
35
58
  // THE SCREENS — every form, one set of routes:
@@ -0,0 +1,37 @@
1
+ #!/usr/bin/env node
2
+
3
+ // THE SIGN-IN SERVICE — @xeplr/auth does the work; this is its entry point
4
+ // for this app, so it loads its settings the same way bin/www does
5
+ // (<NODE_ENV>.env beside it) and follows the same setup.
6
+ require('dotenv').config({ path: require('path').join(__dirname, '..', (process.env.NODE_ENV || 'development') + '.env') });
7
+
8
+ var path = require('path');
9
+ var setup = require('@xeplr/setup');
10
+ var setupConfig = require('../setup.schema.js').config(path.join(__dirname, '..'));
11
+
12
+ // While the app is being set up (core settings missing — the API serves the
13
+ // setup page) this waits instead of crash-looping, and exits 75 once the env
14
+ // file is complete, so the service manager starts it again.
15
+ var waiting = setup.waitForSetup(setupConfig.schema, process.env, { envFile: setupConfig.envFile, appName: 'auth' });
16
+
17
+ // A change on the App settings page (routes/appSettings.js) restarts this
18
+ // service too: exit 75 when a setting in the env file changes. In production
19
+ // only — there a service manager (deploy/auth.service, Restart=always) starts
20
+ // it again; locally nothing would.
21
+ if (!waiting && process.env.NODE_ENV === 'production') {
22
+ setup.restartOnChange({ envFile: setupConfig.envFile, schema: setupConfig.schema, appName: 'auth' });
23
+ }
24
+
25
+ async function start() {
26
+ // The sign-in database, made when missing — after the setup page nobody is
27
+ // there to run `npm run setup`. Then @xeplr/auth migrates it itself.
28
+ var made = await require('@xeplr/db').ensureDatabaseFor(process.env.AUTH_DB_CONNECTION_INFO_ENCRYPTED, process.env.AUTH_DB_NAME);
29
+ if (made && made.created) console.log('[auth] made database ' + process.env.AUTH_DB_NAME);
30
+ await require('@xeplr/auth').boot();
31
+ if (process.send) process.send({ status: 'ready' });
32
+ }
33
+
34
+ if (!waiting) start().catch(function(err) {
35
+ console.error('[auth] startup failed:', err.stack || err.message);
36
+ process.exit(1);
37
+ });
@@ -2,34 +2,22 @@
2
2
 
3
3
  require('dotenv').config({ path: require('path').join(__dirname, '..', (process.env.NODE_ENV || 'development') + '.env') });
4
4
 
5
- // ── the database connection, checked first and by name ──────────────────
6
- //
7
- // BEFORE the general check, because this one has a fix that nobody can guess
8
- // from a variable name. The generic check can only say "this is missing";
9
- // these two settings hold an ENCRYPTED value that has to be produced by a
10
- // command, so a bare name sends somebody looking for a password to type into
11
- // a field that will not accept one.
12
- var CONNECTION_SETTINGS = ['__PREFIX___CONNECTION', 'AUTH_DB_CONNECTION_INFO_ENCRYPTED'];
13
- var blank = CONNECTION_SETTINGS.filter(function (name) { return !process.env[name]; });
14
-
15
- if (blank.length) {
16
- console.error('\n[api] No database connection.\n');
17
- console.error(' ' + blank.join(' and '));
18
- console.error(' ' + (blank.length > 1 ? 'are' : 'is') + ' blank in development.env.\n');
19
- console.error(' These hold your database host, port, user and password,');
20
- console.error(' encrypted together into one value. To fill them in:\n');
21
- console.error(' npm run db:encrypt\n');
22
- console.error(' It asks for the details and writes both settings for you.');
23
- console.error(' Non-interactively:\n');
24
- console.error(' npm run db:encrypt -- --host localhost --port 5432 \\');
25
- console.error(' --user postgres --password \'<yours>\' --write\n');
26
- process.exit(1);
27
- }
5
+ var path = require('path');
6
+ var setup = require('@xeplr/setup');
28
7
 
29
- // Fail fast on the rest — shared check from @xeplr/base-apis.
30
- require('@xeplr/base-apis').checkEnv(require('../env.required.js'), { appName: 'api' });
8
+ // A MISSING SETTING NEVER STOPS THIS PROCESS (@xeplr/setup, setup.schema.js).
9
+ // Core settings missing, or set but unusable (an encrypted login this
10
+ // ENCRYPTION_KEY cannot read) → SETUP MODE: no app, no migrations — the setup
11
+ // page on this API's port (/setup, behind the one-time code in SETUP_CODE),
12
+ // which writes the env file and exits 75 so the service manager starts this
13
+ // again as the app. Locally, `npm run db:encrypt` fills the database login
14
+ // from the terminal instead.
15
+ // Only a feature's settings missing (email) → the app runs with it off, and
16
+ // GET /setup/status says what it needs.
17
+ var setupConfig = require('../setup.schema.js').config(path.join(__dirname, '..'));
18
+ var bootEnv = Object.assign({}, process.env);
19
+ var envState = require('@xeplr/base-apis').checkEnv(require('../env.required.js'), { appName: 'api', setup: setupConfig.schema });
31
20
 
32
- var path = require('path');
33
21
  var { resolveConfig } = require('@xeplr/db');
34
22
  var { up } = require('@xeplr/db').sqlMigrator;
35
23
  var factory = require('@xeplr/factory');
@@ -40,6 +28,16 @@ require('../functions');
40
28
  var screens = require('../screens');
41
29
 
42
30
  async function start() {
31
+ // Set, but unusable? Core values this process cannot use mean setup mode too.
32
+ var invalid = envState.setupMode ? [] : (await setup.verify(setupConfig.schema, process.env)).filter(function(p) { return !p.feature; });
33
+ if (envState.setupMode || invalid.length) {
34
+ if (!envState.setupMode) console.warn('[api] ' + invalid.map(function(p) { return p.name + ': ' + p.reason; }).join('; ') + ' — starting in setup mode');
35
+ var out = require('../app').setupMode(setupConfig, invalid);
36
+ var ready = await out.ready;
37
+ console.warn('[api] SETUP MODE on port ' + process.env.__PREFIX___PORT + ': open /setup — the code is in ' + ready.codeFile);
38
+ return;
39
+ }
40
+
43
41
  // WHICH PRODUCT THIS IS, for every file it keeps: each company's files live
44
42
  // in <XEPLR_DATA_DIR>/__NAME__/<company>/… and nowhere else. Fixed here, at
45
43
  // boot — never from a request.
@@ -47,7 +45,13 @@ async function start() {
47
45
 
48
46
  // Name the connection before anything uses it — the migrator resolves by
49
47
  // name from a registry that getConnection does not populate.
50
- await resolveConfig('api', process.env.__PREFIX___CONNECTION);
48
+ var resolved = await resolveConfig('api', process.env.__PREFIX___CONNECTION);
49
+
50
+ // This app's database, made when missing — after the setup page nobody is
51
+ // there to run `npm run setup` (the login needs CREATEDB; without it, make
52
+ // the database once by hand).
53
+ var made = await require('@xeplr/db').ensureDatabaseFor(resolved, process.env.DB_API);
54
+ if (made && made.created) console.log('[api] made database ' + process.env.DB_API);
51
55
 
52
56
  // Migrations run ON BOOT, so starting the API is the only thing anyone has
53
57
  // to remember. Already-applied ones are skipped.
@@ -89,7 +93,7 @@ async function start() {
89
93
  var buildApp = require('../app');
90
94
  require('../routes/flows').mount(await require('../workflow')(buildApp.memberGate));
91
95
 
92
- buildApp();
96
+ buildApp(null, { setup: Object.assign({}, setupConfig, { env: bootEnv }) });
93
97
  }
94
98
 
95
99
  start().catch(function(err) {
@@ -7,3 +7,5 @@ production.env
7
7
  *.local.env
8
8
  # The app's files (XEPLR_DATA_DIR): what people attach, a folder per company.
9
9
  data/
10
+ SETUP_CODE
11
+ FIRST_LOGIN
@@ -0,0 +1,18 @@
1
+ -- 0002_settings_audit.sql
2
+ -- WHO CHANGED WHICH APP SETTING, AND WHEN (settings menu → App settings,
3
+ -- routes/appSettings.js over @xeplr/setup settingsRouter).
4
+ --
5
+ -- A change that cannot be recorded here is not saved — the library puts the
6
+ -- env file back. Setting NAMES only, never a value: a row here must be safe
7
+ -- to show anyone who may read the table.
8
+ --
9
+ -- Install-wide (no tenant columns): a setting belongs to the install, not to
10
+ -- a company. Never pruned by anything.
11
+ CREATE TABLE IF NOT EXISTS "settings_audit" (
12
+ "id" varchar(25) PRIMARY KEY,
13
+ "userId" varchar(25),
14
+ "userEmail" varchar(320),
15
+ "names" jsonb NOT NULL,
16
+ "changedAt" timestamptz NOT NULL DEFAULT now()
17
+ );
18
+ CREATE INDEX IF NOT EXISTS "settings_audit_when" ON "settings_audit" ("changedAt" DESC);
@@ -0,0 +1,44 @@
1
+ -- 0006_app_settings.sql
2
+ -- THE APP'S OWN SETTINGS (settings menu → App settings): the install's env
3
+ -- file seen and changed after setup, then the app restarts into it
4
+ -- (routes/appSettings.js over @xeplr/setup settingsRouter; the page is
5
+ -- @xeplr/ui-setup's, mounted in ui/src/App.jsx).
6
+ --
7
+ -- SUPER ADMIN ONLY, deliberately: it changes the whole install (database
8
+ -- login, mail, data folder) for every company on it, so a company admin,
9
+ -- whose rights end at their own company, must never reach it. Marked scope
10
+ -- 'system' — the one kind of API that may be mapped to Super Admin alone.
11
+ --
12
+ -- settings:app — Super Admin only (system)
13
+ -- View app settings GET /api/app-settings
14
+ -- Check app settings POST /api/app-settings/check
15
+ -- Save app settings POST /api/app-settings
16
+ --
17
+ -- Insert-if-absent throughout: safe to run again.
18
+
19
+ INSERT INTO "apis" (id, name, "apiGroup", "scope", "scopeLocked", "isPublic", "isActive", "mtId1", "recordCreatedDate", "recordModifiedDate")
20
+ SELECT encode(gen_random_bytes(12), 'hex'), v.name, v."group", 'system', true, false, true, '*', now(), now()
21
+ FROM (VALUES
22
+ ('View app settings', 'settings:app'),
23
+ ('Check app settings', 'settings:app'),
24
+ ('Save app settings', 'settings:app')
25
+ ) AS v(name, "group")
26
+ WHERE NOT EXISTS (SELECT 1 FROM "apis" a WHERE a.name = v.name AND a."apiGroup" = v."group");
27
+
28
+ INSERT INTO "apisRolesMapping" (id, "roleId", "apiId", "isActive", "mtId1", "recordCreatedDate", "recordModifiedDate")
29
+ SELECT encode(gen_random_bytes(12), 'hex'), r.id, a.id, true, '*', now(), now()
30
+ FROM "roles" r CROSS JOIN "apis" a
31
+ WHERE a."apiGroup" = 'settings:app' AND r.name = 'Super Admin'
32
+ AND NOT EXISTS (SELECT 1 FROM "apisRolesMapping" m WHERE m."roleId" = r.id AND m."apiId" = a.id);
33
+
34
+ -- The page, in the settings menu. The name is the KEY: it must match
35
+ -- ui/src/App.jsx's settingsOverrides `key` EXACTLY ('App settings').
36
+ INSERT INTO "menus" (id, name, "menuGroup", "isPublic", "isActive", "mtId1", "recordCreatedDate", "recordModifiedDate")
37
+ SELECT encode(gen_random_bytes(12), 'hex'), 'App settings', 'settings:app', false, true, '*', now(), now()
38
+ WHERE NOT EXISTS (SELECT 1 FROM "menus" WHERE name = 'App settings');
39
+
40
+ INSERT INTO "menuRolesMapping" (id, "roleId", "menuId", "isActive", "mtId1", "recordCreatedDate", "recordModifiedDate")
41
+ SELECT encode(gen_random_bytes(12), 'hex'), r.id, m.id, true, '*', now(), now()
42
+ FROM "roles" r CROSS JOIN "menus" m
43
+ WHERE r.name = 'Super Admin' AND m.name = 'App settings'
44
+ AND NOT EXISTS (SELECT 1 FROM "menuRolesMapping" x WHERE x."roleId" = r.id AND x."menuId" = m.id);
@@ -13,12 +13,12 @@
13
13
  "db:create:api": "dotenv -e development.env -- xeplr-migrate create-db --connectionName api --connection-env __PREFIX___CONNECTION --db-env DB_API",
14
14
  "migrate:auth": "dotenv -e development.env -- xeplr-auth-migrate up --connection-env AUTH_DB_CONNECTION_INFO_ENCRYPTED",
15
15
  "migrate:up": "dotenv -e development.env -- xeplr-migrate up --dir ./migrations --connectionName api --connection-env __PREFIX___CONNECTION",
16
- "start-auth": "dotenv -e ./development.env -- xeplr-auth-server",
16
+ "start-auth": "node ./bin/auth.js",
17
17
  "start-api": "node ./bin/www"
18
18
  },
19
19
  "dependencies": {
20
20
  "@xeplr/auth": "^1.5.3",
21
- "@xeplr/base-apis": "^3.0.4",
21
+ "@xeplr/base-apis": "^3.1.3",
22
22
  "@xeplr/db": "^1.1.0",
23
23
  "@xeplr/factory": "^3.0.3",
24
24
  "@xeplr/ui-factory": "^1.18.0",
@@ -30,7 +30,8 @@
30
30
  "@xeplr/actions": "^2.2.1",
31
31
  "@xeplr/workflow-api": "^3.0.0",
32
32
  "@xeplr/workflow-engine": "^5.0.0",
33
- "@xeplr/jobs": "^3.1.0"
33
+ "@xeplr/jobs": "^3.1.0",
34
+ "@xeplr/setup": "^0.2.0"
34
35
  },
35
36
  "devDependencies": {
36
37
  "dotenv-cli": "^8.0.0",
@@ -3,7 +3,12 @@
3
3
  # production.env is never committed (.gitignore).
4
4
  #
5
5
  # Every value that is a secret is blank here. Generate new ones for production
6
- # — never reuse development's.
6
+ # — never reuse development's. Or leave them blank: the API then serves its
7
+ # SETUP PAGE (/setup, the code in api/SETUP_CODE) — it generates the keys and
8
+ # the first Super Admin password (api/FIRST_LOGIN), encrypts the database login
9
+ # from DB_HOST / DB_PASSWORD, builds the email links from SERVER_NAME, and asks
10
+ # for anything else missing (setup.schema.js). Keep the ports: the page is
11
+ # served on __PREFIX___PORT.
7
12
 
8
13
  NODE_ENV=production
9
14
  LOG_DIR=./logs
@@ -35,6 +40,8 @@ AUTH_TENANT_HEADER=none
35
40
  # ── Public addresses (what people's browsers open) ──
36
41
  AUTH_ACTIVATION_URL=https://app.example.com/auth/activate
37
42
  AUTH_INVITE_URL=https://app.example.com/auth/accept-invite
43
+ AUTH_RESET_URL=https://app.example.com/auth/reset-password
44
+ AUTH_REGISTER_ROLES=Viewer
38
45
 
39
46
  # ── Where this app's files live — an absolute folder that exists ──
40
47
  # A folder per company inside it: <XEPLR_DATA_DIR>/__NAME__/<company>/…
@@ -0,0 +1,67 @@
1
+ // THE APP'S OWN SETTINGS (settings menu → App settings) — the install's env
2
+ // file seen and changed after setup; the app restarts into the change.
3
+ //
4
+ // GET /api/app-settings every setting, grouped Core / each feature;
5
+ // secrets only "set"
6
+ // POST /api/app-settings/check { values } — refusals + the live database
7
+ // login check, nothing written
8
+ // POST /api/app-settings { values } — save, audit, answer, restart (exit 75)
9
+ //
10
+ // SUPER ADMIN ONLY, twice over: requireApi (the apis rows of
11
+ // migrations-auth/0006, mapped to Super Admin alone, scope 'system') and the
12
+ // role itself checked here (routes/access.js) — this route rewrites the
13
+ // whole install's settings for everyone on it.
14
+ //
15
+ // WHAT may be changed is @xeplr/setup's settingsRouter and the schema
16
+ // (setup.schema.js): the same refusals and checks as the setup page. What
17
+ // lives here: who may, and the audit row (settings_audit, migrations/0002) —
18
+ // setting NAMES only, never values. A change that cannot be recorded is not
19
+ // saved: the library puts the file back.
20
+ var express = require('express');
21
+ var crypto = require('crypto');
22
+ var setup = require('@xeplr/setup');
23
+ var { requireApi } = require('@xeplr/base-apis');
24
+ var access = require('./access');
25
+
26
+ var API = {
27
+ view: 'View app settings',
28
+ check: 'Check app settings',
29
+ save: 'Save app settings'
30
+ };
31
+
32
+ /** One audit row. Install-wide: no tenant columns. */
33
+ async function audit(change, req) {
34
+ var knex = await require('../db/setup');
35
+ await knex('settings_audit').insert({
36
+ id: crypto.randomBytes(12).toString('hex'),
37
+ userId: (req.user && req.user.id) || null,
38
+ userEmail: (req.user && req.user.email) || change.who || null,
39
+ names: JSON.stringify(change.names),
40
+ changedAt: new Date(change.at)
41
+ });
42
+ }
43
+
44
+ /**
45
+ * @param {object} cfg setup.schema.js config() + { env } (the env as bin/www found it)
46
+ * @param {object} [opts] { envFile, onRestart, restartDelayMs } — tests only
47
+ */
48
+ module.exports = function appSettingsRoutes(cfg, opts) {
49
+ opts = opts || {};
50
+ var router = express.Router();
51
+ if (!cfg) return router; // built without setup (a test app): no settings screen
52
+ var handler = setup.settingsRouter({
53
+ schema: cfg.schema,
54
+ envFile: opts.envFile || cfg.envFile,
55
+ env: cfg.env,
56
+ // RestartSec=5 in deploy/*.service, then migrations and the boot.
57
+ restartSeconds: 20,
58
+ restartDelayMs: opts.restartDelayMs,
59
+ onRestart: opts.onRestart,
60
+ onChange: audit
61
+ });
62
+ router.get('/', requireApi(API.view), access.superAdminOnly, handler);
63
+ router.post('/check', requireApi(API.check), access.superAdminOnly, handler);
64
+ router.post('/', requireApi(API.save), access.superAdminOnly, handler);
65
+ return router;
66
+ };
67
+ module.exports.API = API;
@@ -0,0 +1,142 @@
1
+ /**
2
+ * EVERY SETTING THIS APP NEEDS, AND HOW EACH ONE GETS A VALUE (@xeplr/setup).
3
+ *
4
+ * So that a deploy never fails because of a setting:
5
+ * - what can be generated (ENCRYPTION_KEY, AUTH_JWT_SECRET, the first Super
6
+ * Admin's password) or worked out (the encrypted database logins, the
7
+ * links in emails, AUTH_URL) is written into the env file by the app;
8
+ * - what only a person knows (the database server and password, the
9
+ * database names, the data folder, the Super Admin's email) is asked ONCE
10
+ * on the app's own setup page — http://<api>/setup, behind the one-time
11
+ * code in api/SETUP_CODE — when it is missing (bin/www);
12
+ * - a feature whose settings are missing is OFF, the app runs:
13
+ * email SMTP_* (when EMAIL_PROVIDER is smtp) — without it nobody but
14
+ * the Super Admin can get in (no invites, resets, activations).
15
+ *
16
+ * After setup the same schema is the Super Admin's App settings page
17
+ * (routes/appSettings.js, @xeplr/ui-setup in the UI).
18
+ *
19
+ * The lists come from env.required.js — every library's own requiredEnv —
20
+ * so a requirement a library adds shows up here with nothing to re-type.
21
+ *
22
+ * config(apiDir, env) → { schema, envFile, codeFile, title }
23
+ */
24
+ var path = require('path');
25
+ var setup = require('@xeplr/setup');
26
+
27
+ // The ONE database login, encrypted into each of these (`xeplr encrypt`
28
+ // writes the same two).
29
+ var CONNECTIONS = ['__PREFIX___CONNECTION', 'AUTH_DB_CONNECTION_INFO_ENCRYPTED'];
30
+ var DATABASES = ['DB_API', 'AUTH_DB_NAME', 'DB_WORKFLOW', 'DB_JOBS'];
31
+ var SMTP = ['SMTP_HOST', 'SMTP_USER', 'SMTP_PASS', 'SMTP_FROM'];
32
+
33
+ function notExample(v) { return /@example\.(com|org)$/.test(v) ? 'still the example address' : null; }
34
+
35
+ /** https://SERVER_NAME — the address people open. */
36
+ function publicUrl(v) { return 'https://' + v.SERVER_NAME; }
37
+
38
+ /** The database login, encrypted with this install's key; one encryption for both settings. */
39
+ function encryptedLogin(encrypt) {
40
+ var made = {};
41
+ return function(v) {
42
+ var login = JSON.stringify([v.DB_HOST, v.DB_PORT, v.DB_USER, v.DB_PASSWORD, v.ENCRYPTION_KEY]);
43
+ if (!made[login]) made[login] = encrypt(JSON.stringify({
44
+ host: v.DB_HOST,
45
+ port: parseInt(v.DB_PORT || '5432', 10),
46
+ user: v.DB_USER || 'postgres',
47
+ password: v.DB_PASSWORD || ''
48
+ }), v.ENCRYPTION_KEY);
49
+ return made[login];
50
+ };
51
+ }
52
+
53
+ function about(encrypt, decrypt) {
54
+ var a = {
55
+ ENCRYPTION_KEY: { kind: 'generated', generate: 'hex', secret: true, label: 'Encryption key',
56
+ locked: 'Encrypts the stored database logins: a new key would make every one of them unreadable.' },
57
+ AUTH_JWT_SECRET: { kind: 'generated', generate: 'hex', secret: true, label: 'Sign-in token secret',
58
+ locked: 'Signs every sign-in: made once and kept.' },
59
+ AUTH_SUPER_ADMIN_PASSWORD: { kind: 'generated', generate: 'password', secret: true, label: 'Super Admin password',
60
+ locked: 'Used once, to make the first Super Admin. Change the password from the account menu instead.',
61
+ // Never printed: a deploy's output ends up in logs.
62
+ note: { file: 'FIRST_LOGIN', label: 'The first sign-in', text: function(pw, v) {
63
+ return 'Super Admin: ' + (v.AUTH_SUPER_ADMIN_EMAIL || '(AUTH_SUPER_ADMIN_EMAIL)') + '\n' +
64
+ 'Password: ' + pw + '\n\nChange it after the first login, then delete this file.\n';
65
+ } } },
66
+
67
+ DB_HOST: { input: true, label: 'Database server', help: 'The Postgres server every database of this app lives on, e.g. 127.0.0.1.' },
68
+ DB_PORT: { input: true, optional: true, label: 'Database port', help: 'Empty means 5432.' },
69
+ DB_USER: { input: true, optional: true, label: 'Database user', help: 'Empty means postgres. It must be allowed to create databases.' },
70
+ DB_PASSWORD: { input: true, secret: true, optional: true, label: 'Database password', help: 'Encrypted into the app\'s connections; the plain text is not kept.' },
71
+
72
+ SERVER_NAME: { input: true, label: 'Domain', help: 'The address people open, e.g. app.yourcompany.com — the links in emails are built from it.' },
73
+ AUTH_ACTIVATION_URL: { kind: 'derived', from: ['SERVER_NAME'], derive: function(v) { return publicUrl(v) + '/auth/activate'; }, label: 'Activation link' },
74
+ AUTH_INVITE_URL: { kind: 'derived', from: ['SERVER_NAME'], derive: function(v) { return publicUrl(v) + '/auth/accept-invite'; }, label: 'Invite link' },
75
+ AUTH_RESET_URL: { kind: 'derived', from: ['SERVER_NAME'], derive: function(v) { return publicUrl(v) + '/auth/reset-password'; }, label: 'Password reset link' },
76
+
77
+ // Where THIS server reaches the sign-in service (not the public address).
78
+ AUTH_URL: { kind: 'derived', from: ['AUTH_PORT'], derive: function(v) { return 'http://127.0.0.1:' + v.AUTH_PORT; }, label: 'Sign-in service address' },
79
+ __PREFIX___PORT: { label: 'API port', help: 'The port this API listens on (the setup page is on it too).' },
80
+ AUTH_PORT: { label: 'Sign-in service port' },
81
+
82
+ // Fixed for this app when it was generated — not questions for a person.
83
+ REDIS_PREFIX: { kind: 'derived', from: [], derive: function() { return '__NAME__:'; }, label: 'Redis key prefix',
84
+ locked: 'Keeps this app\'s sign-in keys apart from other apps on the same Redis.' },
85
+ AUTH_TENANT_HEADER: { kind: 'derived', from: [], derive: function() { return 'none'; }, label: 'Company header for roles', locked: 'Part of how this app was generated.' },
86
+ AUTH_REGISTER_ROLES: { kind: 'derived', from: [], derive: function() { return 'Viewer'; }, label: 'Role of a new sign-up' },
87
+ XEPLR_AUTH_MIGRATIONS: { kind: 'derived', from: [],
88
+ derive: function() { return './node_modules/@xeplr/factory/migrations-auth,./node_modules/@xeplr/workflow-api/migrations-auth,./migrations-auth'; },
89
+ label: 'Sign-in permission files', locked: 'The permission files this app ships, in order.' },
90
+
91
+ XEPLR_DATA_DIR: { where: 'path', label: 'Data folder', help: 'Absolute path, e.g. /var/lib/__NAME__/data. Every company\'s files live in their own folder under it.' },
92
+ LOG_DIR: { optional: true, label: 'Log folder', help: 'Empty means ./logs.' },
93
+
94
+ AUTH_SUPER_ADMIN_EMAIL: { label: 'Super Admin email', help: 'Who signs in first.', validate: notExample },
95
+ SMTP_HOST: { label: 'Mail server', help: 'Activation, invite and reset emails go out through it.' },
96
+ SMTP_USER: { label: 'Mail user' },
97
+ SMTP_PASS: { label: 'Mail password', secret: true },
98
+ SMTP_FROM: { label: 'Mail from address', validate: notExample }
99
+ };
100
+ var login = encrypt ? encryptedLogin(encrypt) : null;
101
+ CONNECTIONS.forEach(function(name) {
102
+ a[name] = { kind: 'derived', secret: true, from: ['DB_HOST'], uses: ['DB_PORT', 'DB_USER', 'DB_PASSWORD'], clears: ['DB_PASSWORD'],
103
+ derive: login || function() { throw new Error('cannot encrypt the database login: @xeplr/utils is not installed'); },
104
+ // Set, but can this install's key read it? (setup.verify, bin/www)
105
+ verify: decrypt ? function(v, env) {
106
+ return Promise.resolve(decrypt(v, env.ENCRYPTION_KEY)).then(function(text) {
107
+ var l = JSON.parse(text);
108
+ return l && l.host ? null : 'holds no database server';
109
+ }, function() { return 'cannot be read with this ENCRYPTION_KEY — give the database login again'; });
110
+ } : undefined,
111
+ label: 'Database login (' + name + ')' };
112
+ });
113
+ DATABASES.forEach(function(name) { a[name] = { where: 'database', label: 'Database name (' + name + ')' }; });
114
+ return a;
115
+ }
116
+
117
+ /** The schema for an env as it stands (mail is asked only when it goes out over SMTP). */
118
+ function schemaFor(env, required, encrypt, decrypt) {
119
+ var core = required.concat(CONNECTIONS, ['AUTH_INVITE_URL', 'LOG_DIR']);
120
+ var lists = { core: core };
121
+ if ((env.EMAIL_PROVIDER || 'smtp') === 'smtp') lists.email = SMTP;
122
+ return setup.fromRequired(lists, about(encrypt, decrypt), {
123
+ features: { email: { label: 'Email', help: 'Without it only the Super Admin can get in: invites, activations and password resets each send a link.' } },
124
+ checks: [setup.checks.postgres({ label: 'Database login' })]
125
+ });
126
+ }
127
+
128
+ /** This process's schema and env file: <api>/<NODE_ENV>.env, the code file beside it. */
129
+ function config(apiDir, env, opts) {
130
+ opts = opts || {};
131
+ env = env || process.env;
132
+ var crypto = opts.crypto || require('@xeplr/utils/isomorphic/crypto');
133
+ var envFile = path.join(apiDir, (env.NODE_ENV || 'development') + '.env');
134
+ return {
135
+ schema: schemaFor(env, opts.required || require('./env.required.js'), crypto.encrypt, crypto.decrypt),
136
+ envFile: envFile,
137
+ codeFile: path.join(apiDir, 'SETUP_CODE'),
138
+ title: '__NAME__'
139
+ };
140
+ }
141
+
142
+ module.exports = { config: config, schemaFor: schemaFor, CONNECTIONS: CONNECTIONS };
@@ -0,0 +1,25 @@
1
+ # __NAME__ — the api service. Copy to /etc/systemd/system/__NAME__-api.service,
2
+ # change the paths and user if yours differ, then:
3
+ # systemctl daemon-reload && systemctl enable --now __NAME__-api
4
+ #
5
+ # Restart=always IS PART OF HOW SETTINGS WORK. The setup page and the App
6
+ # settings page write api/production.env and exit with code 75; this unit
7
+ # starts the service again into the new settings (RestartSec, then the boot —
8
+ # the App settings page tells people about 20 seconds).
9
+ [Unit]
10
+ Description=__NAME__: the API (and, until it is set up, the setup page)
11
+ After=network-online.target postgresql.service redis-server.service
12
+
13
+ [Service]
14
+ Type=simple
15
+ User=__NAME__
16
+ Group=__NAME__
17
+ WorkingDirectory=/srv/__NAME__/api
18
+ Environment=NODE_ENV=production
19
+ ExecStart=/usr/bin/env node bin/www
20
+ Restart=always
21
+ RestartSec=5
22
+ PrivateTmp=true
23
+
24
+ [Install]
25
+ WantedBy=multi-user.target
@@ -0,0 +1,25 @@
1
+ # __NAME__ — the auth service. Copy to /etc/systemd/system/__NAME__-auth.service,
2
+ # change the paths and user if yours differ, then:
3
+ # systemctl daemon-reload && systemctl enable --now __NAME__-auth
4
+ #
5
+ # Restart=always IS PART OF HOW SETTINGS WORK. The setup page and the App
6
+ # settings page write api/production.env and exit with code 75; this unit
7
+ # starts the service again into the new settings (RestartSec, then the boot —
8
+ # the App settings page tells people about 20 seconds).
9
+ [Unit]
10
+ Description=__NAME__: sign-in (@xeplr/auth)
11
+ After=network-online.target postgresql.service redis-server.service
12
+
13
+ [Service]
14
+ Type=simple
15
+ User=__NAME__
16
+ Group=__NAME__
17
+ WorkingDirectory=/srv/__NAME__/api
18
+ Environment=NODE_ENV=production
19
+ ExecStart=/usr/bin/env node bin/auth.js
20
+ Restart=always
21
+ RestartSec=5
22
+ PrivateTmp=true
23
+
24
+ [Install]
25
+ WantedBy=multi-user.target
@@ -7,7 +7,7 @@ npm run dev # http://localhost:__UI_PORT__
7
7
  npm run build # → dist/
8
8
  ```
9
9
 
10
- `.env` holds the port and where the sign-in service and the API are; `vite.config.js` proxies `/auth/api` to sign-in and `/api` (and `/health`, `/whoami`) to the API. A new data prefix must be added there too.
10
+ `.env` holds the port and where the sign-in service and the API are; `vite.config.js` proxies `/auth/api` to sign-in and `/api` (and `/health`, `/whoami`, `/setup`) to the API. A new data prefix must be added there too.
11
11
 
12
12
  ## Layout
13
13
 
@@ -18,6 +18,7 @@ npm run build # → dist/
18
18
  | `src/menu.js` | every menu key this app uses; forms added to the menu are `form:<key>` |
19
19
  | `src/api/factory.js` | the calls to the API's forms routes — with `authFetchFile`, so a form's stored pictures show as thumbnails |
20
20
  | `src/pages/Tasks.jsx` | the sample list. It opens records on a **page** (`onOpenRecord` → `/tasks/new`, `/tasks/:id`), and `EditTask.jsx` is that page — it also holds the task form's **front-end hooks** (`TaskHooks extends FactoryHooks` — every method calls `super`, including `step`, run before a stepper moves) and sends **Done** back to the list |
21
+ | `/settings/app` (in `src/App.jsx`) | **App settings** — `@xeplr/ui-setup`'s `AppSettingsPage` on `/api/app-settings`, Super Admin only (menu row `App settings`). Re-skin it with `design={...}`; a design must render the ids in that package's README or it does not load |
21
22
  | `src/pages/ConfigureUI.jsx` | Configure UI (Super Admin): `Forms.jsx` and `MenuSettings.jsx` tabs; `FormDesigner.jsx` designs one form |
22
23
  | `src/pages/FormRecords.jsx` | opens any published form — what a form added to the menu links to |
23
24
 
@@ -19,7 +19,8 @@
19
19
  "react": "^19.2.4",
20
20
  "react-dom": "^19.2.4",
21
21
  "react-router-dom": "^7.13.2",
22
- "@xeplr/ui-utils": "^1.1.8"
22
+ "@xeplr/ui-setup": "^0.1.0",
23
+ "@xeplr/ui-utils": "^1.1.14"
23
24
  },
24
25
  "devDependencies": {
25
26
  "@vitejs/plugin-react": "^5.2.0",
@@ -12,6 +12,7 @@
12
12
  "webOnly": [
13
13
  { "path": "/home", "menu": "Home", "reason": "The starter page that proves sign-in and the API work — replace it with your first page." },
14
14
  { "path": "/configure/flows/:flow", "reason": "The flow designer is a tool for building, used on a computer." },
15
+ { "path": "/settings/app", "menu": "App settings", "reason": "The install's own settings (database login, mail, folders) — a Super Admin tool, used on a computer." },
15
16
  { "path": "/configure", "menu": "Configure UI", "reason": "The form designer and menu settings are tools for building, used on a computer." },
16
17
  { "path": "/configure/forms/:form/design/:part", "reason": "The form designer is a tool for building, used on a computer." }
17
18
  ]
@@ -1,6 +1,7 @@
1
1
  import { useMemo } from 'react'
2
2
  import { Routes, Route, Outlet, Navigate, useNavigate } from 'react-router-dom'
3
- import { authRoutes, authPath, NavPage, ProtectedRoute, useAccess } from '@xeplr/ui-account'
3
+ import { authRoutes, authPath, authFetch, NavPage, ProtectedRoute, useAccess } from '@xeplr/ui-account'
4
+ import { AppSettingsPage } from '@xeplr/ui-setup'
4
5
  import Home from './pages/Home.jsx'
5
6
  import Tasks from './pages/Tasks.jsx'
6
7
  import EditTask from './pages/EditTask.jsx'
@@ -59,7 +60,10 @@ const notifications = { count: 0, onClick: () => {} }
59
60
  const settingsOverrides = [
60
61
  { key: 'Admin', path: authPath('userRoles') },
61
62
  // Super Admin only (migrations-auth/0003): every form, and the side rail.
62
- { key: 'Configure UI', path: '/configure' }
63
+ { key: 'Configure UI', path: '/configure' },
64
+ // Super Admin only (migrations-auth/0006): the install's own settings — the
65
+ // env file — changed in place; the app restarts into them (@xeplr/ui-setup).
66
+ { key: 'App settings', path: '/settings/app' }
63
67
  ]
64
68
 
65
69
 
@@ -128,6 +132,7 @@ __MT_SELECT_ROUTE__
128
132
  <Route path="/tasks/:id" element={<EditTask />} />
129
133
  <Route path="/forms/:form" element={<FormRecords />} />
130
134
  <Route path="/configure" element={<ConfigureUI />} />
135
+ <Route path="/settings/app" element={<AppSettingsPage base="/api/app-settings" fetch={authFetch} statusUrl="/setup/status" />} />
131
136
  <Route path="/configure/forms/:form/design/:part" element={<FormDesigner />} />
132
137
  {/* Flows — run by @xeplr/workflow inside this app's own API. */}
133
138
  <Route path="/flows" element={<FlowsHome />} />
@@ -14,5 +14,6 @@ export const APP_MENU_KEYS = [
14
14
  'Flows',
15
15
  __MT_MENU_KEY__
16
16
  'Admin',
17
- 'Configure UI'
17
+ 'Configure UI',
18
+ 'App settings'
18
19
  ]
@@ -10,6 +10,9 @@ import react from '@vitejs/plugin-react'
10
10
  const API_PATHS = [
11
11
  '/health',
12
12
  '/whoami',
13
+ // The setup page and its status (@xeplr/setup, served by the API before
14
+ // sign-in): the App settings page asks /setup/status while the app restarts.
15
+ '/setup',
13
16
  // Every data address lives under /api, so a PAGE path and a DATA path can
14
17
  // never collide. Without that split, adding '/tasks' here shadowed the UI's
15
18
  // own /tasks page — opening it showed raw JSON instead of the app.