@scalio-cloud/ui 0.43.0 → 0.44.1

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
@@ -54,6 +54,40 @@ COPY --from=build /app/node_modules/@scalio-cloud/ui/nginx/security-headers.conf
54
54
  include /etc/nginx/snippets/security-headers.conf;
55
55
  ```
56
56
 
57
+ ## Access limit by IP and country for nginx (from 0.44.0)
58
+
59
+ `nginx/access-limit.sh` limits who may open an instance (ADR 0085, zugang/Z1). The official nginx image runs it at
60
+ start (`/docker-entrypoint.d/`); it reads the environment and writes two nginx files. Machine paths
61
+ (`nginx/machine-paths.txt`: health, version, provisioning, agent, webhooks) stay open, so Compass, Scalio Monitor and
62
+ the agent keep working. A blocked person sees a page in German and English with their address.
63
+
64
+ ```dockerfile
65
+ COPY --from=build /app/node_modules/@scalio-cloud/ui/nginx/access-limit.sh /docker-entrypoint.d/30-scalio-access.sh
66
+ COPY --from=build /app/node_modules/@scalio-cloud/ui/nginx/machine-paths.txt /etc/nginx/snippets/
67
+ ```
68
+
69
+ ```nginx
70
+ server {
71
+ include /etc/nginx/snippets/scalio-access.conf;
72
+ ...
73
+ }
74
+ ```
75
+
76
+ | Variable | Meaning |
77
+ |---|---|
78
+ | `ALLOWED_CLIENT_IPS` | Addresses and networks, comma separated (`198.51.100.7, 203.0.113.0/24, 2001:db8::/32`) |
79
+ | `ALLOWED_COUNTRIES` | ISO country codes (`CH, LI, DE`); needs the geoip2 module and a country database |
80
+ | `TRUSTED_PROXIES` | Proxies whose `X-Forwarded-For` counts (Caddy, Azure front end); the last entry is used |
81
+ | `SCALIO_APP` | App name (`nexus`, …) for the app-specific machine paths |
82
+ | `SCALIO_GEOIP_DB` | Country database, default `/etc/nginx/geoip/dbip-country.mmdb` |
83
+
84
+ Both lists empty: no limit (both files stay empty). An address passes if it is in the IP list or its country is
85
+ allowed. An invalid entry closes the instance for everyone except the machine paths and names the entry in the log
86
+ (fail closed). Countries set but no database or the geoip2 module not loaded (`load_module` in `nginx.conf` or
87
+ `modules/*.conf`): only the IP list counts, nginx still starts and the log says why. For countries the image needs
88
+ `ngx_http_geoip2_module` and the free DB-IP «IP to Country Lite» database (CC BY 4.0: show «IP Geolocation by DB-IP»
89
+ on the about page). Tests (`test/access.test.js`) run with real nginx when it is installed.
90
+
57
91
  ## Sign-in state (React, from 0.37.0)
58
92
 
59
93
  `createAuth({ api, formatError, signInWithPasskey, passkeyCancelled, legacyTokenKey })` gives `{ AuthProvider,
@@ -563,6 +597,29 @@ The package holds only design values and fonts under the SIL OFL, nothing confid
563
597
  Design tokens and preset: (c) Scalio Cloud LLC, free to use in Scalio apps. Fonts: SIL Open Font License 1.1,
564
598
  see `fonts/licenses/`. Icons in `react/icons.js`: Lucide, ISC license, see `licenses/lucide-LICENSE.txt`.
565
599
 
600
+ ## Eingabefelder prüfen: `Input` (React, from 0.44.0)
601
+
602
+ Taken over from Scalio Kontor, so every app checks fields the same way. `<Input check="…">` is the native
603
+ `<input>` with checks: only allowed characters are taken, the value is tidied up when the field is left
604
+ (`1'250,50` → `1250.50`, IBAN in groups of four, UID `CHE-123.456.788`), a clear German or English message shows
605
+ under the field after leaving it, and the form cannot be sent (`setCustomValidity`) until the value is right.
606
+
607
+ Checks: `text`, `amount`, `signedAmount`, `quantity`, `percent`, `rate`, `integer`, `date`, `email`, `emails`,
608
+ `phone`, `url`, `iban`, `qrIban`, `zip`, `uid`, `vat`, `country`, `account`, `reference` (QR reference or RF…), `bic`.
609
+ `country` (e.g. `"CH"`) makes zip, UID and MWST number strict; `lang` defaults to `<html lang>`.
610
+
611
+ ```jsx
612
+ import { Input, validNear, fieldProblem, fieldProblemText } from "@scalio-cloud/ui/react";
613
+
614
+ <Input check="iban" value={iban} onChange={(e) => setIban(e.target.value)} required testId="iban" />
615
+ <Input check="zip" country={address.country} value={zip} onChange={...} />
616
+ <button onClick={(e) => validNear(e.currentTarget) && save()}>Speichern</button> // outside a <form>
617
+ fieldProblemText(fieldProblem("uid", value, { country: "CH" }), lang) // same rule without a field
618
+ ```
619
+
620
+ The backend checks the same rules again; the pure functions (`fieldProblem`, `normalizeField`, `validIban`,
621
+ `formatUid`, …) work without React.
622
+
566
623
  ## Release
567
624
 
568
625
  1. Change the files and bump `version` in `package.json` (semver; tag without `v`).
@@ -0,0 +1,136 @@
1
+ #!/bin/sh
2
+ # Scalio access limit for the frontend nginx of every app (scalio-docs ADR 0085, zugang/Z1, Z6, Z7).
3
+ # Shipped in @scalio-cloud/ui. The app's Dockerfile copies it to /docker-entrypoint.d/30-scalio-access.sh (the
4
+ # official nginx image runs it before nginx starts) and machine-paths.txt next to it.
5
+ #
6
+ # ALLOWED_CLIENT_IPS CIDR list, comma separated ("203.0.113.0/24, 2001:db8::/48"); empty = no limit
7
+ # ALLOWED_COUNTRIES ISO country codes, comma separated ("CH,DE,AT"); needs SCALIO_GEOIP_DB and the geoip2 module
8
+ # loaded in nginx.conf (load_module, or modules/*.conf as in the Alpine package)
9
+ # TRUSTED_PROXIES CIDR list of the proxy in front (Caddy network, Azure ingress); its X-Forwarded-For counts
10
+ # SCALIO_APP nexus, citadel, … : picks the app's machine paths (machine-paths.txt)
11
+ # SCALIO_GEOIP_DB country database (DB-IP «IP to Country Lite», mmdb); default /etc/nginx/geoip/dbip-country.mmdb
12
+ #
13
+ # Allowed is who is in the IP list OR in an allowed country; machine paths stay open. Everyone else gets 403 with a
14
+ # short page that names the address (and the country), so the customer can add it in Scalio Compass.
15
+ # Both variables empty: the two files are written empty and nothing changes.
16
+ # A wrong entry: fail closed (only machine paths open) and say why in the log. Countries without database or
17
+ # without the geoip2 module: only the IP list counts (nginx still starts) and the log says why.
18
+ set -eu
19
+
20
+ DIR="${SCALIO_ACCESS_DIR:-/etc/nginx}"
21
+ HTTP_CONF="${SCALIO_ACCESS_HTTP:-$DIR/conf.d/00-scalio-access.conf}"
22
+ SERVER_CONF="${SCALIO_ACCESS_SERVER:-$DIR/snippets/scalio-access.conf}"
23
+ PATHS_FILE="${SCALIO_MACHINE_PATHS_FILE:-$(dirname "$0")/machine-paths.txt}"
24
+ [ -f "$PATHS_FILE" ] || PATHS_FILE="$DIR/snippets/machine-paths.txt"
25
+ GEOIP_DB="${SCALIO_GEOIP_DB:-$DIR/geoip/dbip-country.mmdb}"
26
+ NGINX_CONF="${SCALIO_NGINX_CONF:-$DIR/nginx.conf}"
27
+ APP="${SCALIO_APP:-}"
28
+
29
+ log() { echo "scalio-access: $*" >&2; }
30
+
31
+ # "a, b ,c" -> "a b c"
32
+ words() { echo "${1:-}" | tr ',;' ' ' | tr -s ' \t\n' ' ' | sed 's/^ //; s/ $//'; }
33
+
34
+ valid_cidr() {
35
+ case "$1" in
36
+ *[!0-9a-fA-F:./]*|"") return 1 ;;
37
+ esac
38
+ ip="${1%/*}"; bits=""
39
+ [ "$ip" != "$1" ] && bits="${1#*/}"
40
+ case "$ip" in
41
+ *:*) max=128; echo "$ip" | grep -Eq '^[0-9a-fA-F:]+(\.[0-9.]+)?$' || return 1 ;;
42
+ *) max=32
43
+ echo "$ip" | grep -Eq '^([0-9]{1,3}\.){3}[0-9]{1,3}$' || return 1
44
+ for o in $(echo "$ip" | tr '.' ' '); do [ "$o" -le 255 ] || return 1; done ;;
45
+ esac
46
+ if [ -n "$bits" ]; then
47
+ echo "$bits" | grep -Eq '^[0-9]{1,3}$' || return 1
48
+ [ "$bits" -le "$max" ] || return 1
49
+ fi
50
+ return 0
51
+ }
52
+
53
+ IPS=$(words "${ALLOWED_CLIENT_IPS:-}")
54
+ COUNTRIES=$(words "${ALLOWED_COUNTRIES:-}" | tr 'a-z' 'A-Z')
55
+ PROXIES=$(words "${TRUSTED_PROXIES:-}")
56
+ mkdir -p "$(dirname "$HTTP_CONF")" "$(dirname "$SERVER_CONF")"
57
+
58
+ if [ -z "$IPS" ] && [ -z "$COUNTRIES" ]; then
59
+ : > "$HTTP_CONF"
60
+ : > "$SERVER_CONF"
61
+ log "no access limit (ALLOWED_CLIENT_IPS and ALLOWED_COUNTRIES empty)"
62
+ exit 0
63
+ fi
64
+
65
+ broken=""
66
+ for c in $IPS $PROXIES; do valid_cidr "$c" || broken="$broken $c"; done
67
+ for c in $COUNTRIES; do echo "$c" | grep -Eq '^[A-Z]{2}$' || broken="$broken $c"; done
68
+ geo_ok=1
69
+ if [ -n "$COUNTRIES" ] && [ ! -r "$GEOIP_DB" ]; then
70
+ geo_ok=0
71
+ log "ALLOWED_COUNTRIES set, but no country database at $GEOIP_DB: only the IP list counts"
72
+ elif [ -n "$COUNTRIES" ] && ! cat "$NGINX_CONF" "$DIR"/modules/*.conf "$DIR"/modules-enabled/*.conf 2>/dev/null \
73
+ | grep -v '^[[:space:]]*#' | grep -q 'ngx_http_geoip2_module'; then
74
+ # Without load_module nginx would refuse the geoip2 block and not start at all.
75
+ geo_ok=0
76
+ log "ALLOWED_COUNTRIES set, but the geoip2 module is not loaded ($NGINX_CONF): only the IP list counts"
77
+ fi
78
+ if [ -n "$broken" ]; then
79
+ log "invalid entries:$broken -> access closed for everyone except the machine paths"
80
+ IPS=""; COUNTRIES=""
81
+ fi
82
+
83
+ {
84
+ echo "# Written by scalio-access (@scalio-cloud/ui nginx/access-limit.sh) at container start. Do not edit."
85
+ if [ -n "$PROXIES" ]; then
86
+ for p in $PROXIES; do echo "set_real_ip_from $p;"; done
87
+ echo "real_ip_header X-Forwarded-For;"
88
+ echo "real_ip_recursive off;"
89
+ fi
90
+ echo "geo \$scalio_ip_allowed {"
91
+ echo " default 0;"
92
+ for c in $IPS; do echo " $c 1;"; done
93
+ echo "}"
94
+ if [ -n "$COUNTRIES" ] && [ "$geo_ok" = 1 ]; then
95
+ echo "geoip2 $GEOIP_DB {"
96
+ echo " \$scalio_country country iso_code;"
97
+ echo "}"
98
+ echo "map \$scalio_country \$scalio_country_allowed {"
99
+ echo " default 0;"
100
+ for c in $COUNTRIES; do echo " $c 1;"; done
101
+ echo "}"
102
+ else
103
+ echo "map \$remote_addr \$scalio_country { default \"\"; }"
104
+ echo "map \$remote_addr \$scalio_country_allowed { default 0; }"
105
+ fi
106
+ echo "map \$uri \$scalio_machine_path {"
107
+ echo " default 0;"
108
+ grep -v '^[[:space:]]*#' "$PATHS_FILE" | while read -r app path; do
109
+ [ -n "${path:-}" ] || continue
110
+ if [ "$app" = "*" ] || [ "$app" = "$APP" ]; then
111
+ case "$path" in
112
+ */) echo " ~^$(echo "$path" | sed 's/[.]/\\./g') 1;" ;;
113
+ *) echo " $path 1;"; echo " ~^$(echo "$path" | sed 's/[.]/\\./g')/ 1;" ;;
114
+ esac
115
+ fi
116
+ done
117
+ echo "}"
118
+ echo "map \"\$scalio_ip_allowed\$scalio_country_allowed\$scalio_machine_path\" \$scalio_access_denied {"
119
+ echo " default 0;"
120
+ echo " 000 1;"
121
+ echo "}"
122
+ } > "$HTTP_CONF"
123
+
124
+ cat > "$SERVER_CONF" <<'CONF'
125
+ # Written by scalio-access (@scalio-cloud/ui nginx/access-limit.sh). Include it in the app's server block.
126
+ error_page 403 @scalio_access_denied;
127
+ if ($scalio_access_denied) {
128
+ return 403;
129
+ }
130
+ location @scalio_access_denied {
131
+ default_type "text/html; charset=utf-8";
132
+ add_header Cache-Control "no-store" always;
133
+ return 200 '<!doctype html><html lang="de"><meta charset="utf-8"><meta name="viewport" content="width=device-width"><title>Zugriff nicht freigegeben</title><body style="font-family:system-ui,sans-serif;max-width:36rem;margin:4rem auto;padding:0 1rem;line-height:1.5"><h1 style="font-size:1.4rem">Zugriff nicht freigegeben</h1><p>Der Zugriff von Ihrer Adresse <b>$remote_addr</b> $scalio_country ist für diese Instanz nicht freigegeben. Bitten Sie Ihre Administration, die Adresse in Scalio Compass unter «Zugriff eingrenzen» einzutragen.</p><p lang="en" style="color:#666">Access from your address <b>$remote_addr</b> $scalio_country is not allowed for this instance. Ask your administrator to add it in Scalio Compass under «Restrict access».</p></body></html>';
134
+ }
135
+ CONF
136
+ log "access limited: $(echo "$IPS" | wc -w | tr -d ' ') IP range(s), countries: ${COUNTRIES:-none}, trusted proxies: ${PROXIES:-none}"
@@ -0,0 +1,10 @@
1
+ # Paths that stay open when a Scalio instance limits access by IP or country (scalio-docs ADR 0085, zugang/Z6).
2
+ # They carry no customer data or have their own protection (token, HMAC, signature). One line: <app> <path prefix>;
3
+ # app "*" = every app. Same list as MACHINE_PATHS in scalio-infra tests/test_internal_only.py (Dev/Test wall).
4
+ * /api/health
5
+ * /api/version
6
+ * /version.json
7
+ * /api/provision/
8
+ * /api/e2e/status
9
+ nexus /api/agent
10
+ nexus /api/webhook/hris/
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@scalio-cloud/ui",
3
- "version": "0.43.0",
3
+ "version": "0.44.1",
4
4
  "description": "Scalio Control Room design tokens, Tailwind preset, self-hosted fonts, the shared app header, sign-in layout, sidebar and page blocks",
5
5
  "license": "SEE LICENSE IN README.md",
6
6
  "private": false,
@@ -0,0 +1,486 @@
1
+ "use strict";
2
+ // Input checks for form fields, shared by all apps (taken over from Scalio Kontor, lib/validate.ts and lib/Input.tsx;
3
+ // Backlog «Prüf-Baustein für Eingabefelder»). What may be typed, how a value is tidied up when the field is left,
4
+ // and which message a wrong value gets, in German ("Sie") and English. Pure functions plus the component <Input>.
5
+ // The backend of an app checks the same rules again.
6
+ //
7
+ // h(ui.Input, { check: "iban", value, onChange, required: true })
8
+ // ui.validNear(button) // a button outside a form: checks the fields of its card, dialog or form
9
+ const React = require("react");
10
+ const h = React.createElement;
11
+
12
+ const CHECKS = ["text", "amount", "signedAmount", "quantity", "percent", "rate", "integer", "date", "email", "emails",
13
+ "phone", "url", "iban", "qrIban", "zip", "uid", "vat", "country", "account", "reference", "bic"];
14
+
15
+ const FIELD_TEXTS = {
16
+ de: {
17
+ fixFields: "Bitte die markierten Felder korrigieren.",
18
+ required: "Bitte ausfüllen.",
19
+ tooLong: "Höchstens {n} Zeichen.",
20
+ tooShort: "Mindestens {n} Zeichen.",
21
+ number: "Bitte eine Zahl eingeben, z. B. 12.5.",
22
+ amount: "Bitte einen Betrag eingeben, z. B. 1250.50 oder 1'250.50.",
23
+ negative: "Bitte keinen negativen Wert eingeben.",
24
+ positive: "Bitte einen Wert grösser als 0 eingeben.",
25
+ decimals: "Höchstens {n} Stellen nach dem Punkt.",
26
+ tooBig: "Diese Zahl ist zu gross.",
27
+ integer: "Bitte eine ganze Zahl ohne Komma eingeben.",
28
+ min: "Mindestens {n}.",
29
+ max: "Höchstens {n}.",
30
+ percent: "Bitte einen Prozentsatz von 0 bis 100 eingeben (höchstens 2 Stellen nach dem Punkt).",
31
+ date: "Bitte ein gültiges Datum eingeben (TT.MM.JJJJ).",
32
+ dateMin: "Das Datum darf nicht vor dem {d} liegen.",
33
+ dateMax: "Das Datum darf nicht nach dem {d} liegen.",
34
+ email: "Bitte eine gültige E-Mail-Adresse eingeben, z. B. name@firma.ch.",
35
+ emails: "Bitte gültige E-Mail-Adressen eingeben, mehrere mit Komma getrennt.",
36
+ phone: "Bitte eine gültige Telefonnummer eingeben, z. B. +41 44 123 45 67.",
37
+ url: "Bitte eine gültige Webadresse eingeben, z. B. www.firma.ch.",
38
+ iban: "Diese IBAN ist ungültig. Bitte prüfen, z. B. CH93 0076 2011 6238 5295 7.",
39
+ qrIban: "Das ist keine QR-IBAN. Eine QR-IBAN hat an Stelle 5 bis 9 eine Zahl von 30000 bis 31999.",
40
+ zipCH: "PLZ mit 4 Ziffern, z. B. 8001.",
41
+ zip4: "PLZ mit 4 Ziffern.",
42
+ zip5: "PLZ mit 5 Ziffern.",
43
+ zip: "Bitte eine gültige PLZ eingeben.",
44
+ uid: "Bitte eine gültige UID eingeben, z. B. CHE-123.456.788 (die letzte Ziffer ist eine Prüfziffer).",
45
+ vat: "Bitte eine gültige MWST-Nummer eingeben, z. B. CHE-123.456.788 MWST.",
46
+ vatForeign: "Bitte eine gültige MWST-Nummer mit Ländercode eingeben, z. B. DE123456789.",
47
+ country: "2 Buchstaben, z. B. CH.",
48
+ account: "Bitte eine Kontonummer mit 4 bis 6 Ziffern eingeben, z. B. 1020.",
49
+ reference: "Bitte eine gültige QR-Referenz (27 Ziffern) oder Creditor Reference (RF…) eingeben.",
50
+ bic: "Bitte einen gültigen BIC mit 8 oder 11 Zeichen eingeben.",
51
+ pattern: "Bitte das richtige Format verwenden.",
52
+ },
53
+ en: {
54
+ fixFields: "Please correct the marked fields.",
55
+ required: "Please fill in this field.",
56
+ tooLong: "At most {n} characters.",
57
+ tooShort: "At least {n} characters.",
58
+ number: "Please enter a number, e.g. 12.5.",
59
+ amount: "Please enter an amount, e.g. 1250.50 or 1'250.50.",
60
+ negative: "Please do not enter a negative value.",
61
+ positive: "Please enter a value greater than 0.",
62
+ decimals: "At most {n} digits after the point.",
63
+ tooBig: "This number is too large.",
64
+ integer: "Please enter a whole number.",
65
+ min: "At least {n}.",
66
+ max: "At most {n}.",
67
+ percent: "Please enter a percentage from 0 to 100 (at most 2 digits after the point).",
68
+ date: "Please enter a valid date.",
69
+ dateMin: "The date must not be before {d}.",
70
+ dateMax: "The date must not be after {d}.",
71
+ email: "Please enter a valid email address, e.g. name@company.ch.",
72
+ emails: "Please enter valid email addresses, several separated by commas.",
73
+ phone: "Please enter a valid phone number, e.g. +41 44 123 45 67.",
74
+ url: "Please enter a valid web address, e.g. www.company.ch.",
75
+ iban: "This IBAN is not valid. Please check it, e.g. CH93 0076 2011 6238 5295 7.",
76
+ qrIban: "This is not a QR-IBAN. A QR-IBAN has a number from 30000 to 31999 at positions 5 to 9.",
77
+ zipCH: "Postcode with 4 digits, e.g. 8001.",
78
+ zip4: "Postcode with 4 digits.",
79
+ zip5: "Postcode with 5 digits.",
80
+ zip: "Please enter a valid postcode.",
81
+ uid: "Please enter a valid UID, e.g. CHE-123.456.788 (the last digit is a check digit).",
82
+ vat: "Please enter a valid VAT number, e.g. CHE-123.456.788 MWST.",
83
+ vatForeign: "Please enter a valid VAT number with country code, e.g. DE123456789.",
84
+ country: "2 letters, e.g. CH.",
85
+ account: "Please enter an account number with 4 to 6 digits, e.g. 1020.",
86
+ reference: "Please enter a valid QR reference (27 digits) or Creditor Reference (RF…).",
87
+ bic: "Please enter a valid BIC with 8 or 11 characters.",
88
+ pattern: "Please use the expected format.",
89
+ },
90
+ };
91
+
92
+ const SWISS = new Set(["CH", "LI"]);
93
+
94
+ // Characters allowed while typing; anything else is not taken into the field.
95
+ const ALLOWED = {
96
+ amount: /^[0-9.,'’ ]*$/,
97
+ signedAmount: /^-?[0-9.,'’ ]*$/,
98
+ quantity: /^[0-9.,'’ ]*$/,
99
+ percent: /^[0-9.,]*$/,
100
+ rate: /^[0-9.,]*$/,
101
+ integer: /^[0-9]*$/,
102
+ phone: /^[+0-9 ()/.-]*$/,
103
+ iban: /^[A-Za-z0-9 ]*$/,
104
+ qrIban: /^[A-Za-z0-9 ]*$/,
105
+ country: /^[A-Za-z]{0,2}$/,
106
+ account: /^[0-9]*$/,
107
+ reference: /^[A-Za-z0-9 ]*$/,
108
+ bic: /^[A-Za-z0-9]*$/,
109
+ };
110
+
111
+ function allowed(check, value) {
112
+ const re = ALLOWED[check];
113
+ return !re || re.test(value);
114
+ }
115
+
116
+ // Letters that are always written in capitals.
117
+ function upper(check) {
118
+ return ["iban", "qrIban", "country", "reference", "bic", "uid", "vat"].includes(check);
119
+ }
120
+
121
+ // "1'250,50 " -> "1250.50": Swiss thousands separators and the decimal comma are accepted.
122
+ function normalizeNumber(value) {
123
+ return String(value).replace(/[\s'’]/g, "").replace(",", ".");
124
+ }
125
+
126
+ function groupIban(value) {
127
+ return value.replace(/\s+/g, "").toUpperCase().replace(/(.{4})/g, "$1 ").trim();
128
+ }
129
+
130
+ // Swiss UID "CHE-123.456.788" (mod 11 check digit); null if it is not a valid UID.
131
+ function formatUid(value) {
132
+ const m = String(value).toUpperCase().replace(/[\s.-]/g, "").match(/^CHE([0-9]{9})$/);
133
+ if (!m) return null;
134
+ const d = m[1].split("").map(Number);
135
+ const weights = [5, 4, 3, 2, 7, 6, 5, 4];
136
+ const sum = weights.reduce((s, w, i) => s + w * d[i], 0);
137
+ const check = (11 - (sum % 11)) % 11;
138
+ if (check === 10 || check !== d[8]) return null;
139
+ return `CHE-${m[1].slice(0, 3)}.${m[1].slice(3, 6)}.${m[1].slice(6)}`;
140
+ }
141
+
142
+ // The value as it is kept once the field is left; empty stays empty.
143
+ function normalize(check, value) {
144
+ const v = String(value).trim();
145
+ if (!v) return "";
146
+ switch (check) {
147
+ case "amount": case "signedAmount": case "quantity": case "percent": case "rate":
148
+ return normalizeNumber(v);
149
+ case "iban": case "qrIban":
150
+ return groupIban(v);
151
+ case "reference":
152
+ return v.replace(/\s+/g, "").toUpperCase();
153
+ case "country": case "bic":
154
+ return v.toUpperCase();
155
+ case "uid":
156
+ return formatUid(v) || v.toUpperCase();
157
+ case "vat": {
158
+ const m = v.toUpperCase().match(/^(CHE[-.\s\d]+?)\s*(MWST|TVA|IVA)?$/);
159
+ const uid = m && formatUid(m[1]);
160
+ return uid ? `${uid} ${m[2] || "MWST"}` : v.toUpperCase();
161
+ }
162
+ case "url": case "email":
163
+ return v;
164
+ default:
165
+ return value;
166
+ }
167
+ }
168
+
169
+ function decimal(value, places, opts) {
170
+ const signed = !!(opts && opts.signed);
171
+ const max = opts && opts.max;
172
+ const v = normalizeNumber(value);
173
+ if (!/^-?[0-9]+([.][0-9]+)?$/.test(v) && !/^-?[.][0-9]+$/.test(v)) return { key: "number" };
174
+ if (!signed && v.startsWith("-")) return { key: "negative" };
175
+ const parts = v.replace("-", "").split(".");
176
+ const int = parts[0];
177
+ const frac = parts[1] || "";
178
+ if (frac.length > places) return { key: "decimals", values: { n: places } };
179
+ if (int.length > 16) return { key: "tooBig" };
180
+ if (max !== undefined && Number(v) > max) return { key: "max", values: { n: max } };
181
+ return null;
182
+ }
183
+
184
+ function mod97(s) {
185
+ let rest = 0;
186
+ for (const c of s) {
187
+ const n = parseInt(c, 36).toString();
188
+ for (const d of n) rest = (rest * 10 + Number(d)) % 97;
189
+ }
190
+ return rest;
191
+ }
192
+
193
+ // ISO 13616 check (mod 97); Swiss and Liechtenstein IBANs have 21 characters.
194
+ function validIban(value) {
195
+ const iban = String(value).replace(/\s+/g, "").toUpperCase();
196
+ if (!/^[A-Z]{2}[0-9]{2}[A-Z0-9]{11,30}$/.test(iban)) return false;
197
+ if (SWISS.has(iban.slice(0, 2)) && iban.length !== 21) return false;
198
+ return mod97(iban.slice(4) + iban.slice(0, 4)) === 1;
199
+ }
200
+
201
+ // QR-IBAN: Swiss IBAN whose institution id is 30000 to 31999 (QR bill).
202
+ function validQrIban(value) {
203
+ const iban = String(value).replace(/\s+/g, "").toUpperCase();
204
+ const iid = Number(iban.slice(4, 9));
205
+ return validIban(iban) && SWISS.has(iban.slice(0, 2)) && iid >= 30000 && iid <= 31999;
206
+ }
207
+
208
+ // QR reference: 27 digits with recursive mod 10 check digit.
209
+ function validQrReference(ref) {
210
+ if (!/^[0-9]{27}$/.test(ref)) return false;
211
+ const table = [0, 9, 4, 6, 8, 2, 7, 1, 3, 5];
212
+ let carry = 0;
213
+ for (const c of ref.slice(0, 26)) carry = table[(carry + Number(c)) % 10];
214
+ return (10 - carry) % 10 === Number(ref[26]);
215
+ }
216
+
217
+ // Creditor Reference ISO 11649 ("RF" + 2 check digits + up to 21 characters).
218
+ function validScor(ref) {
219
+ if (!/^RF[0-9]{2}[A-Z0-9]{1,21}$/.test(ref)) return false;
220
+ return mod97(ref.slice(4) + ref.slice(0, 4)) === 1;
221
+ }
222
+
223
+ const ZIP = {
224
+ CH: { re: /^[1-9][0-9]{3}$/, key: "zipCH" },
225
+ LI: { re: /^94[89][0-9]$/, key: "zipCH" },
226
+ AT: { re: /^[1-9][0-9]{3}$/, key: "zip4" },
227
+ DE: { re: /^[0-9]{5}$/, key: "zip5" },
228
+ FR: { re: /^[0-9]{5}$/, key: "zip5" },
229
+ IT: { re: /^[0-9]{5}$/, key: "zip5" },
230
+ ES: { re: /^[0-9]{5}$/, key: "zip5" },
231
+ US: { re: /^[0-9]{5}(-[0-9]{4})?$/, key: "zip" },
232
+ };
233
+
234
+ // The problem with a value ({key, values}), or null if it is fine. An empty value is fine here; "required" is
235
+ // the input's own attribute. opts.country: the country of the address (zip, UID, MWST strict for CH and LI).
236
+ function problem(check, value, opts) {
237
+ const v = String(value == null ? "" : value).trim();
238
+ if (!v) return null;
239
+ const country = String((opts && opts.country) || "").toUpperCase();
240
+ switch (check) {
241
+ case "amount": case "signedAmount": {
242
+ const p = decimal(v, 2, { signed: check === "signedAmount" });
243
+ return p && p.key === "number" ? { key: "amount" } : p;
244
+ }
245
+ case "quantity":
246
+ return decimal(v, 4);
247
+ case "percent":
248
+ return decimal(v, 2, { max: 100 }) && { key: "percent" };
249
+ case "rate": {
250
+ const p = decimal(v, 8);
251
+ if (p) return p;
252
+ return Number(normalizeNumber(v)) > 0 ? null : { key: "positive" };
253
+ }
254
+ case "integer":
255
+ return /^[0-9]+$/.test(v) ? null : { key: "integer" };
256
+ case "date":
257
+ return /^[0-9]{4}-[0-9]{2}-[0-9]{2}$/.test(v) && !Number.isNaN(Date.parse(v)) ? null : { key: "date" };
258
+ case "email":
259
+ return /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(v) && v.length <= 320 ? null : { key: "email" };
260
+ case "emails": {
261
+ const list = v.split(/[,;\s]+/).filter(Boolean);
262
+ return list.every((a) => problem("email", a) === null) ? null : { key: "emails" };
263
+ }
264
+ case "phone": {
265
+ const digits = v.replace(/[^0-9]/g, "").length;
266
+ return /^\+?[0-9 ()/.-]+$/.test(v) && digits >= 6 && digits <= 15 ? null : { key: "phone" };
267
+ }
268
+ case "url":
269
+ return /^(https?:\/\/)?([a-z0-9äöü](-*[a-z0-9äöü])*\.)+[a-z]{2,}(:[0-9]{1,5})?(\/\S*)?$/i.test(v)
270
+ ? null : { key: "url" };
271
+ case "iban":
272
+ return validIban(v) ? null : { key: "iban" };
273
+ case "qrIban":
274
+ if (!validIban(v)) return { key: "iban" };
275
+ return validQrIban(v) ? null : { key: "qrIban" };
276
+ case "zip": {
277
+ const rule = ZIP[country];
278
+ if (rule) return rule.re.test(v) ? null : { key: rule.key };
279
+ return /^[A-Za-z0-9][A-Za-z0-9 -]{1,9}$/.test(v) ? null : { key: "zip" };
280
+ }
281
+ case "uid":
282
+ if (SWISS.has(country) || /^CHE/i.test(v)) return formatUid(v) ? null : { key: "uid" };
283
+ return /^[A-Za-z0-9 .\-/]{2,20}$/.test(v) ? null : { key: "pattern" };
284
+ case "vat": {
285
+ if (SWISS.has(country) || /^CHE/i.test(v)) {
286
+ const m = v.toUpperCase().match(/^(CHE[-.\s\d]+?)\s*(MWST|TVA|IVA)?$/);
287
+ return m && formatUid(m[1]) ? null : { key: "vat" };
288
+ }
289
+ return /^[A-Z]{2}[A-Z0-9 .+*-]{2,28}$/i.test(v) ? null : { key: "vatForeign" };
290
+ }
291
+ case "country":
292
+ return /^[A-Z]{2}$/i.test(v) ? null : { key: "country" };
293
+ case "account":
294
+ return /^[1-9][0-9]{3,5}$/.test(v) ? null : { key: "account" };
295
+ case "reference": {
296
+ const r = v.replace(/\s+/g, "").toUpperCase();
297
+ return validQrReference(r) || validScor(r) ? null : { key: "reference" };
298
+ }
299
+ case "bic":
300
+ return /^[A-Z]{4}[A-Z]{2}[A-Z0-9]{2}([A-Z0-9]{3})?$/i.test(v) ? null : { key: "bic" };
301
+ default:
302
+ return null;
303
+ }
304
+ }
305
+
306
+ // Defaults for the native input per check: type, keyboard on phones, autocomplete, length.
307
+ function inputDefaults(check) {
308
+ switch (check) {
309
+ case "amount": case "signedAmount": case "quantity": case "percent": case "rate":
310
+ return { inputMode: "decimal", maxLength: 24 };
311
+ case "integer": case "account":
312
+ return { inputMode: "numeric", maxLength: check === "account" ? 6 : 12 };
313
+ case "date":
314
+ return { type: "date", min: "1900-01-01", max: "2099-12-31" };
315
+ case "email":
316
+ return { type: "email", inputMode: "email", autoComplete: "email", maxLength: 320 };
317
+ case "phone":
318
+ return { type: "tel", inputMode: "tel", autoComplete: "tel", maxLength: 40 };
319
+ case "url":
320
+ return { inputMode: "url", autoComplete: "url", maxLength: 200 };
321
+ case "iban": case "qrIban":
322
+ return { maxLength: 42, autoComplete: "off" };
323
+ case "zip":
324
+ return { maxLength: 10, autoComplete: "postal-code" };
325
+ case "uid":
326
+ return { maxLength: 20 };
327
+ case "vat":
328
+ return { maxLength: 30 };
329
+ case "country":
330
+ return { maxLength: 2, autoComplete: "country" };
331
+ case "reference":
332
+ return { maxLength: 40, autoComplete: "off" };
333
+ case "bic":
334
+ return { maxLength: 11 };
335
+ default:
336
+ return {};
337
+ }
338
+ }
339
+
340
+ // "{n}" placeholders filled in.
341
+ function fill(text, values) {
342
+ return String(text).replace(/\{(\w+)\}/g, (_, k) => String((values || {})[k] == null ? "" : values[k]));
343
+ }
344
+
345
+ function fieldTexts(lang) {
346
+ return FIELD_TEXTS[lang === "en" ? "en" : "de"];
347
+ }
348
+
349
+ // The message for a problem in the given language ("" for null).
350
+ function problemText(p, lang) {
351
+ if (!p) return "";
352
+ return fill(fieldTexts(lang)[p.key] || fieldTexts(lang).pattern, p.values);
353
+ }
354
+
355
+ function pageLang() {
356
+ return typeof document !== "undefined" && document.documentElement.lang === "en" ? "en" : "de";
357
+ }
358
+
359
+ // "2026-11-06" -> "06.11.2026" in German, ISO in English.
360
+ function day(iso, lang) {
361
+ const [y, m, d] = String(iso).split("-");
362
+ return lang === "de" && d && m && y ? `${d}.${m}.${y}` : iso;
363
+ }
364
+
365
+ // Sets the value like a person would, so React's onChange runs (used for the tidied-up value).
366
+ function setValue(el, value) {
367
+ const proto = el.ownerDocument.defaultView.HTMLInputElement.prototype;
368
+ const desc = Object.getOwnPropertyDescriptor(proto, "value");
369
+ if (desc && desc.set) desc.set.call(el, value);
370
+ el.dispatchEvent(new el.ownerDocument.defaultView.Event("input", { bubbles: true }));
371
+ }
372
+
373
+ // The message for the field's current value, or "" if it is fine.
374
+ function messageFor(el, check, lang, country) {
375
+ const V = fieldTexts(lang);
376
+ const v = el.validity;
377
+ if (v.valueMissing) return V.required;
378
+ if (v.badInput) return el.type === "date" ? V.date : V.number;
379
+ if (el.type === "date" && (v.rangeUnderflow || v.rangeOverflow))
380
+ return fill(v.rangeUnderflow ? V.dateMin : V.dateMax, { d: day(v.rangeUnderflow ? el.min : el.max, lang) });
381
+ if (v.rangeUnderflow) return fill(V.min, { n: el.min });
382
+ if (v.rangeOverflow) return fill(V.max, { n: el.max });
383
+ if (v.stepMismatch) return V.integer;
384
+ if (v.tooLong) return fill(V.tooLong, { n: el.maxLength });
385
+ if (v.tooShort) return fill(V.tooShort, { n: el.minLength });
386
+ if (v.typeMismatch) return el.type === "email" ? V.email : el.type === "url" ? V.url : V.pattern;
387
+ if (check) {
388
+ const p = problem(check, el.value, { country });
389
+ if (p) return problemText(p, lang);
390
+ }
391
+ if (v.patternMismatch) return el.title || V.pattern;
392
+ return "";
393
+ }
394
+
395
+ // <Input check="iban" …>: the native input with checks. Takes only allowed characters, tidies the value up when the
396
+ // field is left, shows a clear message under the field and blocks the form (setCustomValidity) until it is right.
397
+ // Props: check, country (zip, UID, MWST), lang ("de" | "en", default the page's <html lang>), inputRef, and every
398
+ // prop of <input>. className defaults to "input"; a wrong field also gets "border-destructive".
399
+ function Input(props) {
400
+ const { check, country, lang: langProp, inputRef, onChange, onBlur, className = "input", testId, ...rest } = props;
401
+ const lang = langProp || pageLang();
402
+ const id = React.useId();
403
+ const own = React.useRef(null);
404
+ const [msg, setMsg] = React.useState("");
405
+ const [shown, setShown] = React.useState(false);
406
+ const attrs = Object.assign({}, check ? inputDefaults(check) : {}, rest);
407
+
408
+ // Re-check after every render: the value, required, min and max may all have changed.
409
+ React.useLayoutEffect(() => {
410
+ const el = own.current;
411
+ if (!el) return;
412
+ el.setCustomValidity("");
413
+ const m = messageFor(el, check, lang, country);
414
+ el.setCustomValidity(m);
415
+ if (m !== msg) setMsg(m);
416
+ });
417
+
418
+ React.useLayoutEffect(() => {
419
+ const el = own.current;
420
+ if (!el) return undefined;
421
+ const show = () => setShown(true);
422
+ el.addEventListener("invalid", show);
423
+ return () => el.removeEventListener("invalid", show);
424
+ }, []);
425
+
426
+ function change(e) {
427
+ const el = e.target;
428
+ if (check && !allowed(check, el.value)) return; // not taken: the field keeps its value
429
+ if (check && upper(check) && el.value !== el.value.toUpperCase()) {
430
+ const pos = el.selectionStart;
431
+ el.value = el.value.toUpperCase();
432
+ if (pos !== null && pos !== undefined) el.setSelectionRange(pos, pos);
433
+ }
434
+ if (onChange) onChange(e);
435
+ }
436
+
437
+ function blur(e) {
438
+ const el = e.target;
439
+ if (check && !rest.readOnly && !rest.disabled) {
440
+ const tidy = normalize(check, el.value);
441
+ if (tidy !== el.value && problem(check, tidy, { country }) === null) setValue(el, tidy);
442
+ }
443
+ setShown(true);
444
+ if (onBlur) onBlur(e);
445
+ }
446
+
447
+ const error = shown && msg;
448
+ return h(React.Fragment, null,
449
+ h("input", Object.assign({}, attrs, {
450
+ ref: (el) => {
451
+ own.current = el;
452
+ if (typeof inputRef === "function") inputRef(el);
453
+ else if (inputRef) inputRef.current = el;
454
+ },
455
+ className: error ? `${className} border-destructive` : className,
456
+ "aria-invalid": error ? true : rest["aria-invalid"],
457
+ "aria-describedby": error ? `${id}-error` : rest["aria-describedby"],
458
+ "data-testid": testId,
459
+ onChange: change,
460
+ onBlur: blur,
461
+ })),
462
+ error ? h("small", { id: `${id}-error`, role: "alert", className: "text-xs text-destructive",
463
+ "data-testid": testId ? `${testId}-error` : undefined }, msg) : null);
464
+ }
465
+
466
+ // Checks all fields inside `root` (for steps and buttons that do not submit a form): shows the messages and puts
467
+ // the cursor into the first wrong field; true if all are fine.
468
+ function fieldsValid(root) {
469
+ if (!root) return true;
470
+ const fields = Array.from(root.querySelectorAll("input, select, textarea"));
471
+ const wrong = fields.filter((f) => !f.checkValidity());
472
+ if (wrong[0]) wrong[0].focus();
473
+ return wrong.length === 0;
474
+ }
475
+
476
+ // For a button outside a form: checks the fields of the nearest `data-fields` box, form, dialog or card.
477
+ function validNear(el) {
478
+ return fieldsValid(el && el.closest("[data-fields], form, [role=dialog], .card"));
479
+ }
480
+
481
+ module.exports = {
482
+ Input, FIELD_CHECKS: CHECKS, FIELD_TEXTS, fieldAllowed: allowed, fieldUpper: upper, normalizeNumber,
483
+ normalizeField: normalize, fieldProblem: problem, fieldProblemText: problemText, fieldMessageFor: messageFor,
484
+ inputDefaults, fillText: fill, validIban, validQrIban, formatUid, validQrReference, validScor, fieldsValid,
485
+ validNear,
486
+ };
package/react/index.js CHANGED
@@ -378,6 +378,6 @@ module.exports = {
378
378
  TEST_IDS,
379
379
  initials,
380
380
  };
381
- Object.assign(module.exports, Nav, Blocks, require("./settings"), require("./support"), require("./beacon"), require("./security"), require("./license"), require("./palette"), require("./unify"), require("./profile"), require("./actions"), require("./selftest"), require("./users"), require("./customers"), require("./roles"), require("./wizard"), require("./maintenance"), require("./backup"), require("./audit"), require("./mail"), require("./saas_updates"), require("./pages"), require("./tenant"));
381
+ Object.assign(module.exports, Nav, Blocks, require("./settings"), require("./support"), require("./beacon"), require("./security"), require("./license"), require("./palette"), require("./unify"), require("./profile"), require("./actions"), require("./selftest"), require("./users"), require("./customers"), require("./roles"), require("./wizard"), require("./maintenance"), require("./backup"), require("./audit"), require("./mail"), require("./saas_updates"), require("./pages"), require("./tenant"), require("./fields"));
382
382
  // After the exports above: auth.js uses LanguageToggle and ThemeToggle from this module.
383
383
  Object.assign(module.exports, require("./auth"), require("./session"), require("./setup"));