SHA256
Compare commits
9
Commits
6bb6a38040
..
main
| Author | SHA256 | Date | |
|---|---|---|---|
|
|
1cdb3fa784 | ||
|
|
2120c56f45 | ||
|
|
516cb13dcf | ||
|
|
c82de902a8 | ||
|
|
8d488f44ff | ||
|
|
168927453a | ||
|
|
2df603b32b | ||
|
|
535a9c9db0 | ||
|
|
863cd1fd3a |
+6
-164
@@ -1,133 +1,10 @@
|
|||||||
|
pastel
|
||||||
|
|
||||||
# ---> Python
|
# ---> Python
|
||||||
# Byte-compiled / optimized / DLL files
|
|
||||||
__pycache__/
|
__pycache__/
|
||||||
*.py[cod]
|
*.py[cod]
|
||||||
*$py.class
|
*$py.class
|
||||||
|
|
||||||
# C extensions
|
|
||||||
*.so
|
|
||||||
|
|
||||||
# Distribution / packaging
|
|
||||||
.Python
|
|
||||||
build/
|
|
||||||
develop-eggs/
|
|
||||||
dist/
|
|
||||||
downloads/
|
|
||||||
eggs/
|
|
||||||
.eggs/
|
|
||||||
lib/
|
|
||||||
lib64/
|
|
||||||
parts/
|
|
||||||
sdist/
|
|
||||||
var/
|
|
||||||
wheels/
|
|
||||||
share/python-wheels/
|
|
||||||
*.egg-info/
|
|
||||||
.installed.cfg
|
|
||||||
*.egg
|
|
||||||
MANIFEST
|
|
||||||
|
|
||||||
# PyInstaller
|
|
||||||
# Usually these files are written by a python script from a template
|
|
||||||
# before PyInstaller builds the exe, so as to inject date/other infos into it.
|
|
||||||
*.manifest
|
|
||||||
*.spec
|
|
||||||
|
|
||||||
# Installer logs
|
|
||||||
pip-log.txt
|
|
||||||
pip-delete-this-directory.txt
|
|
||||||
|
|
||||||
# Unit test / coverage reports
|
|
||||||
htmlcov/
|
|
||||||
.tox/
|
|
||||||
.nox/
|
|
||||||
.coverage
|
|
||||||
.coverage.*
|
|
||||||
.cache
|
|
||||||
nosetests.xml
|
|
||||||
coverage.xml
|
|
||||||
*.cover
|
|
||||||
*.py,cover
|
|
||||||
.hypothesis/
|
|
||||||
.pytest_cache/
|
|
||||||
cover/
|
|
||||||
|
|
||||||
# Translations
|
|
||||||
*.mo
|
|
||||||
*.pot
|
|
||||||
|
|
||||||
# Django stuff:
|
|
||||||
*.log
|
|
||||||
local_settings.py
|
|
||||||
db.sqlite3
|
|
||||||
db.sqlite3-journal
|
|
||||||
|
|
||||||
# Flask stuff:
|
|
||||||
instance/
|
|
||||||
.webassets-cache
|
|
||||||
|
|
||||||
# Scrapy stuff:
|
|
||||||
.scrapy
|
|
||||||
|
|
||||||
# Sphinx documentation
|
|
||||||
docs/_build/
|
|
||||||
|
|
||||||
# PyBuilder
|
|
||||||
.pybuilder/
|
|
||||||
target/
|
|
||||||
|
|
||||||
# Jupyter Notebook
|
|
||||||
.ipynb_checkpoints
|
|
||||||
|
|
||||||
# IPython
|
|
||||||
profile_default/
|
|
||||||
ipython_config.py
|
|
||||||
|
|
||||||
# pyenv
|
|
||||||
# For a library or package, you might want to ignore these files since the code is
|
|
||||||
# intended to run in multiple environments; otherwise, check them in:
|
|
||||||
# .python-version
|
|
||||||
|
|
||||||
# pipenv
|
|
||||||
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
|
|
||||||
# However, in case of collaboration, if having platform-specific dependencies or dependencies
|
|
||||||
# having no cross-platform support, pipenv may install dependencies that don't work, or not
|
|
||||||
# install all needed dependencies.
|
|
||||||
#Pipfile.lock
|
|
||||||
|
|
||||||
# UV
|
|
||||||
# Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.
|
|
||||||
# This is especially recommended for binary packages to ensure reproducibility, and is more
|
|
||||||
# commonly ignored for libraries.
|
|
||||||
#uv.lock
|
|
||||||
|
|
||||||
# poetry
|
|
||||||
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
|
|
||||||
# This is especially recommended for binary packages to ensure reproducibility, and is more
|
|
||||||
# commonly ignored for libraries.
|
|
||||||
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
|
|
||||||
#poetry.lock
|
|
||||||
|
|
||||||
# pdm
|
|
||||||
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
|
|
||||||
#pdm.lock
|
|
||||||
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
|
|
||||||
# in version control.
|
|
||||||
# https://pdm.fming.dev/latest/usage/project/#working-with-version-control
|
|
||||||
.pdm.toml
|
|
||||||
.pdm-python
|
|
||||||
.pdm-build/
|
|
||||||
|
|
||||||
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
|
|
||||||
__pypackages__/
|
|
||||||
|
|
||||||
# Celery stuff
|
|
||||||
celerybeat-schedule
|
|
||||||
celerybeat.pid
|
|
||||||
|
|
||||||
# SageMath parsed files
|
|
||||||
*.sage.py
|
|
||||||
|
|
||||||
# Environments
|
# Environments
|
||||||
.env
|
.env
|
||||||
.venv
|
.venv
|
||||||
@@ -137,46 +14,11 @@ ENV/
|
|||||||
env.bak/
|
env.bak/
|
||||||
venv.bak/
|
venv.bak/
|
||||||
|
|
||||||
# Spyder project settings
|
# SQLite
|
||||||
.spyderproject
|
db.sqlite3
|
||||||
.spyproject
|
db.sqlite3-journal
|
||||||
|
|
||||||
# Rope project settings
|
# Instance / state
|
||||||
.ropeproject
|
|
||||||
|
|
||||||
# mkdocs documentation
|
|
||||||
/site
|
|
||||||
|
|
||||||
# mypy
|
|
||||||
.mypy_cache/
|
|
||||||
.dmypy.json
|
|
||||||
dmypy.json
|
|
||||||
|
|
||||||
# Pyre type checker
|
|
||||||
.pyre/
|
|
||||||
|
|
||||||
# pytype static type analyzer
|
|
||||||
.pytype/
|
|
||||||
|
|
||||||
# Cython debug symbols
|
|
||||||
cython_debug/
|
|
||||||
|
|
||||||
# PyCharm
|
|
||||||
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
|
|
||||||
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
|
|
||||||
# and can be added to the global gitignore or merged into this file. For a more nuclear
|
|
||||||
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
|
|
||||||
#.idea/
|
|
||||||
|
|
||||||
# Ruff stuff:
|
|
||||||
.ruff_cache/
|
|
||||||
|
|
||||||
# PyPI configuration file
|
|
||||||
.pypirc
|
|
||||||
|
|
||||||
|
|
||||||
# project
|
|
||||||
venv/
|
|
||||||
instance/
|
instance/
|
||||||
certs/
|
certs/
|
||||||
__pycache__/
|
__pycache__/
|
||||||
|
|||||||
@@ -1,70 +0,0 @@
|
|||||||
# crushdb – verschlüsselte Datensätze zwischen Personen
|
|
||||||
|
|
||||||
Sichere Datenbank für Transaktionen zwischen zwei Personen
|
|
||||||
(Person A, Person B, Timestamp-Start, Timestamp-Ende, Aktion).
|
|
||||||
|
|
||||||
Alle Datensätze werden **im Browser** verschlüsselt
|
|
||||||
(XChaCha20-Poly1305, Schlüsselableitung per Argon2id aus der Passphrase).
|
|
||||||
Der Server sieht ausschließlich Chiffretext – auch bei vollständiger
|
|
||||||
Serverkompromittierung bleiben die Inhalte ohne Passphrase vertraulich.
|
|
||||||
|
|
||||||
## Starten (HTTP; TLS über Reverse Proxy)
|
|
||||||
|
|
||||||
```bash
|
|
||||||
python3 -m venv venv
|
|
||||||
./venv/bin/pip install -r requirements.txt
|
|
||||||
./venv/bin/python run.py
|
|
||||||
# → http://127.0.0.1:8085
|
|
||||||
```
|
|
||||||
|
|
||||||
Die App lauscht auf dem lokalen HTTP-Port (default `127.0.0.1:8085`,
|
|
||||||
überschreibbar via `HOST`/`PORT`). Ein vertrauenswürdiger Reverse Proxy
|
|
||||||
(nginx, caddy, …) beendet HTTPS und reicht intern an die App weiter.
|
|
||||||
Die App selbst muss von außen nicht erreichbar sein.
|
|
||||||
|
|
||||||
### Per systemd laufen lassen
|
|
||||||
|
|
||||||
Ein fertiges Unit-File liegt in `deploy/crushdb.service` (Reinheit:
|
|
||||||
nur `instance/` schreibbar, keine Capabilities, Restart on failure).
|
|
||||||
Nach dem Kopieren nach `/etc/systemd/system/` und `daemon-reload`
|
|
||||||
startet `systemctl enable --now crushdb` die App dauerhaft.
|
|
||||||
|
|
||||||
## Tests
|
|
||||||
|
|
||||||
```bash
|
|
||||||
./venv/bin/python -m pytest backend/test_integrity.py -v # Integrität/Replay
|
|
||||||
node .e2e.mjs # optional: End-to-End (siehe unten)
|
|
||||||
```
|
|
||||||
|
|
||||||
## Architektur
|
|
||||||
|
|
||||||
| Komponente |Datei | Aufgabe |
|
|
||||||
|---|---|---|
|
|
||||||
| Speicher | `backend/storage.py` | SQLite, speichert nur Chiffretext (uuid, ciphertext, nonce, salt, version) |
|
|
||||||
| API | `backend/app.py` | Flask REST API, Validierung nur von Form/Größe, Versions-Konfliktprüfung |
|
|
||||||
| Krypto (Client) | `backend/static/crypto.js` | Argon2id-KDF + XChaCha20-Poly1305, uuid+salt als AEAD-AAD gebunden |
|
|
||||||
| UI | `backend/static/ui.js` + `index.html`/`style.css` | Tabelle, Erstellen, Bearbeiten, Löschen; Passphrase bleibt im RAM |
|
|
||||||
| Server | `run.py` | HTTP intern hinter Reverse Proxy, DB-Init |
|
|
||||||
|
|
||||||
## Sicherheitsmodell
|
|
||||||
|
|
||||||
- Passphrase → Argon2id (t=2, m=16 MiB) → 256-Bit-Sitzungsschlüssel,
|
|
||||||
ausschließlich im Browser/im Arbeitsspeicher; niemals am Server.
|
|
||||||
- Jeder Datensatz: eigene zufällige 16-Byte-Salt + 24-Byte-Nonce.
|
|
||||||
uuid + salt sind als AEAD-Associated-Data gebunden – Vertauschen oder
|
|
||||||
Um-Salten wird beim Entschlüsseln sicher erkannt.
|
|
||||||
- Monotoner Versionszähler pro Datensatz: veraltete Updates/Deletes
|
|
||||||
(Replay alter Stände) → `409`, Duplikate → `409`.
|
|
||||||
- Klartexte werden clientseitig nie persistiert; beim Sperren/Beenden
|
|
||||||
wird der Schlüssel verworfen (`wipeKey`).
|
|
||||||
- HTTPS wird außen vom vertrauenswürdigen **Reverse Proxy** beendet
|
|
||||||
(nginx/caddy/…); die App lauscht nur intern auf HTTP.
|
|
||||||
|
|
||||||
## Bekannte Grenzen
|
|
||||||
|
|
||||||
- Datenverlust (Löschen/Überschreiben) durch Angreifer bleibt möglich –
|
|
||||||
Vertraulichkeit ist geschützt, Verfügbarkeit nicht.
|
|
||||||
- Backups der SQLite-Datei enthalten ausschließlich Chiffretext.
|
|
||||||
- Backups des Passphrasen-Verlusts = Datenverlust (by design).
|
|
||||||
|
|
||||||
Siehe `spezification.txt` für die Anforderungen.
|
|
||||||
+708
-134
@@ -1,155 +1,729 @@
|
|||||||
"""Flask application exposing the records API.
|
import os
|
||||||
|
import logging
|
||||||
|
from functools import wraps
|
||||||
|
|
||||||
The server is a dumb ciphertext store: it never sees plaintext or the
|
from flask import Flask, request, jsonify, session, render_template_string, redirect, url_for
|
||||||
key. Every record body is opaque base64. Requests are validated only
|
|
||||||
for shape and size, never for content.
|
|
||||||
|
|
||||||
Security properties:
|
from backend import storage
|
||||||
- No plaintext is logged, stored, or echoed.
|
|
||||||
- Version counters are enforced server-side to detect replays.
|
|
||||||
- HTTPS is handled by ssl context in run.py (TLS for dev).
|
|
||||||
"""
|
|
||||||
|
|
||||||
import base64
|
|
||||||
import binascii
|
|
||||||
|
|
||||||
from flask import Flask, jsonify, request, send_from_directory
|
|
||||||
|
|
||||||
from . import storage
|
|
||||||
|
|
||||||
MAX_CIPHERTEXT_B64 = 32 * 1024 # plenty for one record, stops abuse
|
|
||||||
MAX_SALT_NONCE_B64 = 512
|
|
||||||
|
|
||||||
app = Flask(__name__, static_folder=None)
|
|
||||||
|
|
||||||
|
|
||||||
# ---------- basic hardening ----------
|
SENSITIVE_FIELDS = {"password", "passwd", "secret", "token", "access_token", "refresh_token"}
|
||||||
|
"""Redact sensitive values and long blobs from log-friendly repr."""
|
||||||
@app.after_request
|
|
||||||
def _security_headers(resp):
|
|
||||||
resp.headers["X-Content-Type-Options"] = "nosniff"
|
|
||||||
resp.headers["X-Frame-Options"] = "DENY"
|
|
||||||
resp.headers["Referrer-Policy"] = "no-referrer"
|
|
||||||
resp.headers["Cache-Control"] = "no-store"
|
|
||||||
return resp
|
|
||||||
|
|
||||||
|
|
||||||
def _b64_field(data, field, max_len, required=True):
|
def redact_for_log(value):
|
||||||
"""Validate and decode a base64 field from the JSON body. Returns bytes or None."""
|
if isinstance(value, dict):
|
||||||
if field not in data:
|
return {k: "[redacted]" if k.lower() in SENSITIVE_FIELDS else redact_for_log(v) for k, v in value.items()}
|
||||||
if required:
|
if isinstance(value, (list, tuple)):
|
||||||
raise ValueError(f"missing field: {field}")
|
return [redact_for_log(v) for v in value]
|
||||||
return None
|
return value
|
||||||
raw = data[field]
|
|
||||||
if not isinstance(raw, str) or not raw or len(raw) > max_len:
|
|
||||||
raise ValueError(f"invalid field: {field}")
|
def _request_snapshot(request):
|
||||||
|
body = {}
|
||||||
try:
|
try:
|
||||||
return base64.b64decode(raw, validate=True)
|
if request.is_json:
|
||||||
except (binascii.Error, ValueError):
|
body = request.get_json(silent=True) or {}
|
||||||
raise ValueError(f"invalid base64 in field: {field}")
|
elif request.method in ("POST", "PUT", "PATCH") and request.form:
|
||||||
|
body = {k: v for k, v in request.form.items()}
|
||||||
|
except Exception:
|
||||||
def _record_json(rec):
|
body = {}
|
||||||
return {
|
return {
|
||||||
"uuid": rec["uuid"],
|
"method": request.method,
|
||||||
"ciphertext": base64.b64encode(rec["ciphertext"]).decode(),
|
"path": request.path,
|
||||||
"nonce": base64.b64encode(rec["nonce"]).decode(),
|
"args": dict(request.args),
|
||||||
"salt": base64.b64encode(rec["salt"]).decode(),
|
"body": redact_for_log(body),
|
||||||
"version": rec["version"],
|
|
||||||
"created_at": rec["created_at"],
|
|
||||||
"updated_at": rec["updated_at"],
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
# ---------- static UI ----------
|
def _maybe_log_request(app, request):
|
||||||
|
if app.debug:
|
||||||
|
app.logger.debug("request: %s", _request_snapshot(request))
|
||||||
|
|
||||||
|
|
||||||
|
ARTICLE_TYPE_LABELS = {
|
||||||
|
"contact_details": "Contact details",
|
||||||
|
"notes": "Notes",
|
||||||
|
"profile_text": "Profile text",
|
||||||
|
"documents": "Documents",
|
||||||
|
"links": "Links",
|
||||||
|
"phone_numbers": "Phone numbers",
|
||||||
|
"addresses": "Addresses",
|
||||||
|
"social_profiles": "Social profiles",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def create_app():
|
||||||
|
app = Flask(__name__, static_folder="static", static_url_path="/static")
|
||||||
|
app.secret_key = os.environ.get("FLASK_SECRET_KEY") or os.urandom(24).hex()
|
||||||
|
storage.init_db()
|
||||||
|
|
||||||
@app.route("/")
|
@app.route("/")
|
||||||
def index():
|
def index():
|
||||||
return send_from_directory("static", "index.html")
|
if request.args:
|
||||||
|
# Never accept credentials (or anything else) via the query string.
|
||||||
|
app.logger.warning("ignoring query string on index: keys=%s", list(request.args.keys()))
|
||||||
|
account = session.get("account")
|
||||||
|
if account:
|
||||||
|
fresh = storage.get_account_by_id(account.get("id")) or account
|
||||||
|
session["account"] = fresh
|
||||||
|
return render_index(fresh)
|
||||||
|
return render_login_page()
|
||||||
|
|
||||||
|
def _wants_json():
|
||||||
|
if request.is_json:
|
||||||
|
return True
|
||||||
|
if request.form:
|
||||||
|
return False
|
||||||
|
best = request.accept_mimetypes.best_match(["application/json", "text/html"])
|
||||||
|
return best == "application/json"
|
||||||
|
|
||||||
@app.route("/static/<path:filename>")
|
def _form_or_json(field):
|
||||||
def static_files(filename):
|
if field in request.form:
|
||||||
return send_from_directory("static", filename)
|
return request.form.get(field)
|
||||||
|
if request.is_json:
|
||||||
|
|
||||||
# ---------- API ----------
|
|
||||||
|
|
||||||
@app.get("/api/records")
|
|
||||||
def api_list():
|
|
||||||
return jsonify([_record_json(r) for r in storage.list_records()])
|
|
||||||
|
|
||||||
|
|
||||||
@app.get("/api/records/<uuid>")
|
|
||||||
def api_get(uuid):
|
|
||||||
rec = storage.get_record(uuid)
|
|
||||||
if rec is None:
|
|
||||||
return jsonify({"error": "not found"}), 404
|
|
||||||
return jsonify(_record_json(rec))
|
|
||||||
|
|
||||||
|
|
||||||
@app.post("/api/records")
|
|
||||||
def api_create():
|
|
||||||
data = request.get_json(silent=True)
|
|
||||||
if not isinstance(data, dict):
|
|
||||||
return jsonify({"error": "invalid JSON body"}), 400
|
|
||||||
try:
|
|
||||||
uuid = data.get("uuid")
|
|
||||||
if not isinstance(uuid, str) or not uuid or len(uuid) > 64:
|
|
||||||
raise ValueError("invalid field: uuid")
|
|
||||||
ct = _b64_field(data, "ciphertext", MAX_CIPHERTEXT_B64)
|
|
||||||
nonce = _b64_field(data, "nonce", MAX_SALT_NONCE_B64)
|
|
||||||
salt = _b64_field(data, "salt", MAX_SALT_NONCE_B64)
|
|
||||||
except ValueError as e:
|
|
||||||
return jsonify({"error": str(e)}), 400
|
|
||||||
|
|
||||||
if storage.get_record(uuid) is not None:
|
|
||||||
return jsonify({"error": "record already exists"}), 409
|
|
||||||
|
|
||||||
rec = storage.create_record(uuid, ct, nonce, salt)
|
|
||||||
return jsonify(_record_json(rec)), 201
|
|
||||||
|
|
||||||
|
|
||||||
@app.put("/api/records/<uuid>")
|
|
||||||
def api_update(uuid):
|
|
||||||
data = request.get_json(silent=True)
|
|
||||||
if not isinstance(data, dict):
|
|
||||||
return jsonify({"error": "invalid JSON body"}), 400
|
|
||||||
try:
|
|
||||||
version = data.get("version")
|
|
||||||
if not isinstance(version, int) or version < 1:
|
|
||||||
raise ValueError("invalid field: version")
|
|
||||||
ct = _b64_field(data, "ciphertext", MAX_CIPHERTEXT_B64)
|
|
||||||
nonce = _b64_field(data, "nonce", MAX_SALT_NONCE_B64)
|
|
||||||
salt = _b64_field(data, "salt", MAX_SALT_NONCE_B64)
|
|
||||||
except ValueError as e:
|
|
||||||
return jsonify({"error": str(e)}), 400
|
|
||||||
|
|
||||||
rec = storage.update_record(uuid, ct, nonce, salt, expected_version=version)
|
|
||||||
if rec is None:
|
|
||||||
# 409: version mismatch (concurrent edit or replay) — do not
|
|
||||||
# distinguish from "not found" to avoid leaking existence.
|
|
||||||
return jsonify({"error": "version conflict or not found"}), 409
|
|
||||||
return jsonify(_record_json(rec))
|
|
||||||
|
|
||||||
|
|
||||||
@app.delete("/api/records/<uuid>")
|
|
||||||
def api_delete(uuid):
|
|
||||||
data = request.get_json(silent=True) or {}
|
data = request.get_json(silent=True) or {}
|
||||||
version = data.get("version")
|
return data.get(field)
|
||||||
if not isinstance(version, int) or version < 1:
|
return None
|
||||||
return jsonify({"error": "invalid field: version"}), 400
|
|
||||||
if not storage.delete_record(uuid, expected_version=version):
|
@app.route("/login", methods=["GET", "POST"])
|
||||||
return jsonify({"error": "version conflict or not found"}), 409
|
def login():
|
||||||
return "", 204
|
if request.method == "GET":
|
||||||
|
if request.args:
|
||||||
|
app.logger.warning("ignoring query string on login: keys=%s", list(request.args.keys()))
|
||||||
|
return render_login_page()
|
||||||
|
_maybe_log_request(app, request)
|
||||||
|
email = _form_or_json("email")
|
||||||
|
password = _form_or_json("password")
|
||||||
|
wants_json = _wants_json()
|
||||||
|
if not email or not password:
|
||||||
|
app.logger.warning("login attempt missing credentials: path=%s", request.path)
|
||||||
|
if wants_json:
|
||||||
|
return reply_error("email and password required")
|
||||||
|
return render_login_page("email and password required")
|
||||||
|
account = storage.authenticate(email, password)
|
||||||
|
if not account:
|
||||||
|
app.logger.info("login failed for email=%s path=%s", email, request.path)
|
||||||
|
if wants_json:
|
||||||
|
return reply_error("invalid credentials")
|
||||||
|
return render_login_page("invalid credentials")
|
||||||
|
session["account"] = account
|
||||||
|
app.logger.info("login ok for email=%s path=%s", email, request.path)
|
||||||
|
if wants_json:
|
||||||
|
return reply_ok(account)
|
||||||
|
return redirect("/")
|
||||||
|
|
||||||
|
@app.route("/logout")
|
||||||
|
def logout():
|
||||||
|
session.pop("account", None)
|
||||||
|
return redirect("/")
|
||||||
|
|
||||||
|
@app.route("/account/create", methods=["GET", "POST"])
|
||||||
|
def create_account_page():
|
||||||
|
if request.method == "GET":
|
||||||
|
return render_account_create_page()
|
||||||
|
_maybe_log_request(app, request)
|
||||||
|
return _create_account()
|
||||||
|
|
||||||
|
@app.route("/account", methods=["POST"])
|
||||||
|
def create_account_route():
|
||||||
|
return _create_account()
|
||||||
|
|
||||||
|
def _create_account():
|
||||||
|
email = _form_or_json("email")
|
||||||
|
password = _form_or_json("password")
|
||||||
|
wants_json = _wants_json()
|
||||||
|
if not email or not password:
|
||||||
|
if wants_json:
|
||||||
|
return reply_error("email and password required")
|
||||||
|
return render_account_create_page("email and password required")
|
||||||
|
try:
|
||||||
|
account = storage.create_account(email, password)
|
||||||
|
app.logger.info("account created email=%s path=%s", email, request.path)
|
||||||
|
if wants_json:
|
||||||
|
return reply_ok(account)
|
||||||
|
return redirect("/")
|
||||||
|
except ValueError as e:
|
||||||
|
if "already exists" in str(e).lower():
|
||||||
|
app.logger.info("account exists email=%s path=%s", email, request.path)
|
||||||
|
else:
|
||||||
|
app.logger.warning("account create failed email=%s err=%s path=%s", email, str(e), request.path)
|
||||||
|
if wants_json:
|
||||||
|
return reply_error(str(e))
|
||||||
|
return render_account_create_page(str(e))
|
||||||
|
|
||||||
|
@app.route("/account/me")
|
||||||
|
def me():
|
||||||
|
account = session.get("account")
|
||||||
|
if not account:
|
||||||
|
return reply_error("not authenticated")
|
||||||
|
fresh = storage.get_account_by_id(account.get("id")) or account
|
||||||
|
session["account"] = fresh
|
||||||
|
return reply_ok(fresh)
|
||||||
|
|
||||||
|
def get_account():
|
||||||
|
return session.get("account")
|
||||||
|
|
||||||
|
def login_required(f):
|
||||||
|
@wraps(f)
|
||||||
|
def wrapped(*args, **kwargs):
|
||||||
|
account = get_account()
|
||||||
|
if not account:
|
||||||
|
return reply_error("authentication required")
|
||||||
|
request.account = account
|
||||||
|
return f(*args, **kwargs)
|
||||||
|
|
||||||
|
return wrapped
|
||||||
|
|
||||||
|
@app.route("/persons", methods=["GET"])
|
||||||
|
@login_required
|
||||||
|
def list_persons_route():
|
||||||
|
persons = storage.list_persons(request.account)
|
||||||
|
return reply_ok(persons)
|
||||||
|
|
||||||
|
@app.route("/persons", methods=["POST"])
|
||||||
|
@login_required
|
||||||
|
def create_person_route():
|
||||||
|
name = _form_or_json("name") or ""
|
||||||
|
try:
|
||||||
|
person = storage.create_person(request.account, name)
|
||||||
|
except (PermissionError, ValueError) as e:
|
||||||
|
return reply_error(str(e))
|
||||||
|
return reply_ok(person)
|
||||||
|
|
||||||
|
@app.route("/admin/persons", methods=["POST"])
|
||||||
|
@login_required
|
||||||
|
def admin_create_person_route():
|
||||||
|
name = _form_or_json("name") or ""
|
||||||
|
email = _form_or_json("email")
|
||||||
|
password = _form_or_json("password")
|
||||||
|
try:
|
||||||
|
person = storage.create_person_with_account(request.account, name, email, password)
|
||||||
|
return reply_ok(person)
|
||||||
|
except (PermissionError, ValueError) as e:
|
||||||
|
return reply_error(str(e))
|
||||||
|
|
||||||
|
@app.route("/persons/<person_id>")
|
||||||
|
@login_required
|
||||||
|
def get_person_route(person_id):
|
||||||
|
person = storage.get_person(person_id)
|
||||||
|
if not person:
|
||||||
|
return reply_error("person not found")
|
||||||
|
if not storage.is_admin(request.account) and person_id != request.account.get("person_id"):
|
||||||
|
# Only admins see which emails belong to another person.
|
||||||
|
person = dict(person)
|
||||||
|
person["emails"] = []
|
||||||
|
return reply_ok(person)
|
||||||
|
|
||||||
|
@app.route("/persons/<person_id>", methods=["PATCH"])
|
||||||
|
@login_required
|
||||||
|
def update_person_route(person_id):
|
||||||
|
name = request.form.get("name") or request.json.get("name")
|
||||||
|
name = name if name is not None else None
|
||||||
|
person = storage.update_person(request.account, person_id, name)
|
||||||
|
if not person:
|
||||||
|
return reply_error("person not found")
|
||||||
|
return reply_ok(person)
|
||||||
|
|
||||||
|
@app.route("/persons/<person_id>", methods=["DELETE"])
|
||||||
|
@login_required
|
||||||
|
def delete_person_route(person_id):
|
||||||
|
ok = storage.delete_person(request.account, person_id)
|
||||||
|
if not ok:
|
||||||
|
return reply_error("person not found")
|
||||||
|
return reply_ok({"deleted": True})
|
||||||
|
|
||||||
|
@app.route("/persons/<person_id>/emails/attach", methods=["POST"])
|
||||||
|
@login_required
|
||||||
|
def attach_email_route(person_id):
|
||||||
|
email = request.form.get("email") or request.json.get("email")
|
||||||
|
if not email:
|
||||||
|
return reply_error("email required")
|
||||||
|
try:
|
||||||
|
person = storage.attach_email_to_person(request.account, person_id, email)
|
||||||
|
return reply_ok(person)
|
||||||
|
except (ValueError, PermissionError) as e:
|
||||||
|
return reply_error(str(e))
|
||||||
|
|
||||||
|
@app.route("/persons/<person_id>/emails/detach", methods=["POST"])
|
||||||
|
@login_required
|
||||||
|
def detach_email_route(person_id):
|
||||||
|
email = request.form.get("email") or request.json.get("email")
|
||||||
|
if not email:
|
||||||
|
return reply_error("email required")
|
||||||
|
try:
|
||||||
|
person = storage.detach_email_from_person(request.account, person_id, email)
|
||||||
|
return reply_ok(person)
|
||||||
|
except (ValueError, PermissionError) as e:
|
||||||
|
return reply_error(str(e))
|
||||||
|
|
||||||
|
@app.route("/articles", methods=["GET"])
|
||||||
|
@login_required
|
||||||
|
def list_articles_route():
|
||||||
|
person_id = request.args.get("person_id")
|
||||||
|
articles = storage.list_articles(request.account, person_id)
|
||||||
|
return reply_ok(articles)
|
||||||
|
|
||||||
|
@app.route("/articles", methods=["POST"])
|
||||||
|
@login_required
|
||||||
|
def create_article_route():
|
||||||
|
person_id = _form_or_json("person_id")
|
||||||
|
article_type = _form_or_json("article_type")
|
||||||
|
title = _form_or_json("title") or ""
|
||||||
|
content = _form_or_json("content") or ""
|
||||||
|
visibility = _form_or_json("visibility") or "private"
|
||||||
|
group_ids = request.json.get("group_ids") if request.is_json else None
|
||||||
|
if group_ids is None:
|
||||||
|
group_ids = []
|
||||||
|
if article_type not in storage.ARTICLE_TYPES:
|
||||||
|
return reply_error("invalid article type")
|
||||||
|
if person_id is None:
|
||||||
|
return reply_error("person_id required")
|
||||||
|
try:
|
||||||
|
article = storage.create_article(
|
||||||
|
request.account, person_id, article_type, title, content, visibility, group_ids
|
||||||
|
)
|
||||||
|
return reply_ok(article)
|
||||||
|
except (ValueError, PermissionError) as e:
|
||||||
|
return reply_error(str(e))
|
||||||
|
|
||||||
|
@app.route("/articles/<article_id>")
|
||||||
|
@login_required
|
||||||
|
def get_article_route(article_id):
|
||||||
|
article = storage.get_article(article_id)
|
||||||
|
if not article:
|
||||||
|
return reply_error("article not found")
|
||||||
|
if not storage._can_read_article(request.account, article):
|
||||||
|
article = {k: v for k, v in article.items() if k != "content"}
|
||||||
|
return reply_ok(article)
|
||||||
|
|
||||||
|
@app.route("/articles/<article_id>", methods=["PATCH"])
|
||||||
|
@login_required
|
||||||
|
def update_article_route(article_id):
|
||||||
|
title = request.form.get("title") or request.json.get("title")
|
||||||
|
content = request.form.get("content") or request.json.get("content")
|
||||||
|
visibility = request.form.get("visibility") or request.json.get("visibility")
|
||||||
|
group_ids = request.json.get("group_ids") if request.is_json else None
|
||||||
|
title = title if title is not None else None
|
||||||
|
content = content if content is not None else None
|
||||||
|
visibility = visibility if visibility is not None else None
|
||||||
|
try:
|
||||||
|
article = storage.update_article(
|
||||||
|
request.account, article_id, title=title, content=content, visibility=visibility, group_ids=group_ids
|
||||||
|
)
|
||||||
|
if not article:
|
||||||
|
return reply_error("article not found")
|
||||||
|
return reply_ok(article)
|
||||||
|
except (ValueError, PermissionError) as e:
|
||||||
|
return reply_error(str(e))
|
||||||
|
|
||||||
|
@app.route("/articles/<article_id>", methods=["DELETE"])
|
||||||
|
@login_required
|
||||||
|
def delete_article_route(article_id):
|
||||||
|
try:
|
||||||
|
ok = storage.delete_article(request.account, article_id)
|
||||||
|
if not ok:
|
||||||
|
return reply_error("article not found")
|
||||||
|
return reply_ok({"deleted": True})
|
||||||
|
except PermissionError as e:
|
||||||
|
return reply_error(str(e))
|
||||||
|
|
||||||
|
@app.route("/groups", methods=["GET"])
|
||||||
|
@login_required
|
||||||
|
def list_groups_route():
|
||||||
|
person_id = request.args.get("person_id")
|
||||||
|
groups = storage.list_groups(request.account, person_id)
|
||||||
|
return reply_ok(groups)
|
||||||
|
|
||||||
|
@app.route("/groups", methods=["POST"])
|
||||||
|
@login_required
|
||||||
|
def create_group_route():
|
||||||
|
person_id = request.form.get("person_id") or request.json.get("person_id")
|
||||||
|
name = request.form.get("name") or request.json.get("name") or ""
|
||||||
|
if not person_id:
|
||||||
|
return reply_error("person_id required")
|
||||||
|
try:
|
||||||
|
group = storage.create_group(request.account, person_id, name)
|
||||||
|
return reply_ok(group)
|
||||||
|
except PermissionError as e:
|
||||||
|
return reply_error(str(e))
|
||||||
|
|
||||||
|
@app.route("/groups/<group_id>")
|
||||||
|
@login_required
|
||||||
|
def get_group_route(group_id):
|
||||||
|
group = storage.get_group(group_id)
|
||||||
|
if not group:
|
||||||
|
return reply_error("group not found")
|
||||||
|
if not storage.group_is_visible_to(request.account, group_id):
|
||||||
|
return reply_error("group not found")
|
||||||
|
return reply_ok(group)
|
||||||
|
|
||||||
|
@app.route("/groups/<group_id>", methods=["PATCH"])
|
||||||
|
@login_required
|
||||||
|
def update_group_route(group_id):
|
||||||
|
name = request.form.get("name") or request.json.get("name")
|
||||||
|
name = name if name is not None else None
|
||||||
|
try:
|
||||||
|
group = storage.update_group(request.account, group_id, name)
|
||||||
|
if not group:
|
||||||
|
return reply_error("group not found")
|
||||||
|
return reply_ok(group)
|
||||||
|
except PermissionError as e:
|
||||||
|
return reply_error(str(e))
|
||||||
|
|
||||||
|
@app.route("/groups/<group_id>", methods=["DELETE"])
|
||||||
|
@login_required
|
||||||
|
def delete_group_route(group_id):
|
||||||
|
try:
|
||||||
|
ok = storage.delete_group(request.account, group_id)
|
||||||
|
if not ok:
|
||||||
|
return reply_error("group not found")
|
||||||
|
return reply_ok({"deleted": True})
|
||||||
|
except PermissionError as e:
|
||||||
|
return reply_error(str(e))
|
||||||
|
|
||||||
|
@app.route("/groups/<group_id>/members/<person_id>", methods=["POST"])
|
||||||
|
@login_required
|
||||||
|
def add_member_route(group_id, person_id):
|
||||||
|
try:
|
||||||
|
group = storage.add_group_member(request.account, group_id, person_id)
|
||||||
|
return reply_ok(group)
|
||||||
|
except (ValueError, PermissionError) as e:
|
||||||
|
return reply_error(str(e))
|
||||||
|
|
||||||
|
@app.route("/groups/<group_id>/members/<person_id>", methods=["DELETE"])
|
||||||
|
@login_required
|
||||||
|
def remove_member_route(group_id, person_id):
|
||||||
|
try:
|
||||||
|
group = storage.remove_group_member(request.account, group_id, person_id)
|
||||||
|
return reply_ok(group)
|
||||||
|
except PermissionError as e:
|
||||||
|
return reply_error(str(e))
|
||||||
|
|
||||||
|
@app.route("/rights", methods=["GET"])
|
||||||
|
@login_required
|
||||||
|
def list_rights_route():
|
||||||
|
account_id = request.args.get("account_id")
|
||||||
|
try:
|
||||||
|
rights = storage.list_rights(request.account, account_id)
|
||||||
|
except PermissionError as e:
|
||||||
|
return reply_error(str(e))
|
||||||
|
return reply_ok(rights)
|
||||||
|
|
||||||
|
@app.route("/rights/grant", methods=["POST"])
|
||||||
|
@login_required
|
||||||
|
def grant_right_route():
|
||||||
|
target_account_id = request.form.get("account_id") or request.json.get("account_id")
|
||||||
|
right_name = request.form.get("right") or request.json.get("right")
|
||||||
|
if not target_account_id or not right_name:
|
||||||
|
return reply_error("account_id and right required")
|
||||||
|
try:
|
||||||
|
storage.grant_right(request.account, target_account_id, right_name)
|
||||||
|
return reply_ok({"granted": right_name})
|
||||||
|
except (ValueError, PermissionError) as e:
|
||||||
|
return reply_error(str(e))
|
||||||
|
|
||||||
|
@app.route("/rights/revoke", methods=["POST"])
|
||||||
|
@login_required
|
||||||
|
def revoke_right_route():
|
||||||
|
target_account_id = request.form.get("account_id") or request.json.get("account_id")
|
||||||
|
right_name = request.form.get("right") or request.json.get("right")
|
||||||
|
if not target_account_id or not right_name:
|
||||||
|
return reply_error("account_id and right required")
|
||||||
|
try:
|
||||||
|
storage.revoke_right(request.account, target_account_id, right_name)
|
||||||
|
return reply_ok({"revoked": right_name})
|
||||||
|
except PermissionError as e:
|
||||||
|
return reply_error(str(e))
|
||||||
|
|
||||||
|
@app.route("/api/types")
|
||||||
|
def article_types():
|
||||||
|
return reply_ok({
|
||||||
|
"article_types": storage.ARTICLE_TYPES,
|
||||||
|
"rights": storage.RIGHTS,
|
||||||
|
"article_type_labels": ARTICLE_TYPE_LABELS,
|
||||||
|
})
|
||||||
|
|
||||||
|
return app
|
||||||
|
|
||||||
|
|
||||||
@app.errorhandler(404)
|
def render_account_create_page(error=None):
|
||||||
def not_found(_e):
|
return render_template_string(
|
||||||
return jsonify({"error": "not found"}), 404
|
"""
|
||||||
|
<!doctype html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8" />
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||||
|
<title>Who² - Create account</title>
|
||||||
|
<link rel="stylesheet" href="/static/style.css" />
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div class="card">
|
||||||
|
<h1>Create account</h1>
|
||||||
|
<form id="create-account-form" method="post" action="/account/create">
|
||||||
|
<label>email
|
||||||
|
<input name="email" type="email" autocomplete="username" required />
|
||||||
|
</label>
|
||||||
|
<label>password
|
||||||
|
<input name="password" type="password" autocomplete="new-password" required />
|
||||||
|
</label>
|
||||||
|
<button type="submit">Create account</button>
|
||||||
|
</form>
|
||||||
|
<p class="hint">Already have an account? <a href="/">Log in</a></p>
|
||||||
|
<pre id="create-msg" class="msg{% if not error %} hidden{% endif %}">{{ error }}</pre>
|
||||||
|
</div>
|
||||||
|
<script src="/static/crypto.js"></script>
|
||||||
|
<script src="/static/ui.js"></script>
|
||||||
|
<script>
|
||||||
|
(function () {
|
||||||
|
var form = document.getElementById("create-account-form");
|
||||||
|
var msg = document.getElementById("create-msg");
|
||||||
|
form.addEventListener("submit", function (e) {
|
||||||
|
e.preventDefault();
|
||||||
|
msg.textContent = "";
|
||||||
|
msg.classList.add("hidden");
|
||||||
|
var email = form.email.value.trim();
|
||||||
|
var password = form.password.value;
|
||||||
|
if (!email || !password) {
|
||||||
|
msg.textContent = "email and password required";
|
||||||
|
msg.style.color = "#dc2626";
|
||||||
|
msg.classList.remove("hidden");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
fetch("/account/create", {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify({ email: email, password: password })
|
||||||
|
})
|
||||||
|
.then(function (r) { return r.json().then(function (data) { if (!r.ok) throw new Error(data.error || "account creation failed"); return data; }); })
|
||||||
|
.then(function (data) {
|
||||||
|
msg.textContent = "account created: " + (data.email || "");
|
||||||
|
msg.style.color = "#047857";
|
||||||
|
msg.classList.remove("hidden");
|
||||||
|
window.setTimeout(function () { window.location.href = "/"; }, 700);
|
||||||
|
})
|
||||||
|
.catch(function (err) {
|
||||||
|
msg.textContent = err.message || "account creation failed";
|
||||||
|
msg.style.color = "#dc2626";
|
||||||
|
msg.classList.remove("hidden");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
})();
|
||||||
|
</script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
|
""",
|
||||||
|
error=error or "",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
@app.errorhandler(500)
|
def render_login_page(error=None):
|
||||||
def server_error(_e):
|
return render_template_string(
|
||||||
# Never leak stack traces or data.
|
"""
|
||||||
return jsonify({"error": "internal server error"}), 500
|
<!doctype html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8" />
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||||
|
<title>Who² - Login</title>
|
||||||
|
<link rel="stylesheet" href="/static/style.css" />
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div class="card">
|
||||||
|
<h1>Who²</h1>
|
||||||
|
<form id="login-form" method="post" action="/login">
|
||||||
|
<label>email
|
||||||
|
<input name="email" type="email" autocomplete="username" required />
|
||||||
|
</label>
|
||||||
|
<label>password
|
||||||
|
<input name="password" type="password" autocomplete="current-password" required />
|
||||||
|
</label>
|
||||||
|
<button type="submit">Log in</button>
|
||||||
|
</form>
|
||||||
|
<p class="hint">No account yet? <a href="/account/create">Create one</a></p>
|
||||||
|
<pre id="login-msg" class="msg{% if not error %} hidden{% endif %}">{{ error }}</pre>
|
||||||
|
</div>
|
||||||
|
<script src="/static/crypto.js"></script>
|
||||||
|
<script src="/static/vendor/noble-hashes/blake2.js"></script>
|
||||||
|
<script src="/static/vendor/noble-hashes/argon2.js"></script>
|
||||||
|
<script src="/static/vendor/noble-ciphers/chacha.js"></script>
|
||||||
|
<script src="/static/vendor/noble-ciphers/_arx.js"></script>
|
||||||
|
<script src="/static/vendor/noble-ciphers/_poly1305.js"></script>
|
||||||
|
<script src="/static/vendor/noble-ciphers/utils.js"></script>
|
||||||
|
<script src="/static/vendor/noble-hashes/utils.js"></script>
|
||||||
|
<script src="/static/vendor/noble-hashes/_u64.js"></script>
|
||||||
|
<script src="/static/vendor/noble-hashes/_md.js"></script>
|
||||||
|
<script src="/static/vendor/noble-hashes/_blake.js"></script>
|
||||||
|
<script src="/static/ui.js"></script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
|
""",
|
||||||
|
error=error or "",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def render_index(account=None):
|
||||||
|
is_admin = storage.is_admin(account)
|
||||||
|
return render_template_string(
|
||||||
|
"""
|
||||||
|
<!doctype html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8" />
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||||
|
<title>Who²</title>
|
||||||
|
<link rel="stylesheet" href="/static/style.css" />
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<header>
|
||||||
|
<h1>Who²</h1>
|
||||||
|
<div class="account-bar">
|
||||||
|
<span id="user-email"></span>
|
||||||
|
<span id="user-role" class="badge"></span>
|
||||||
|
<a href="/logout" class="btn-small">Log out</a>
|
||||||
|
</div>
|
||||||
|
</header>
|
||||||
|
<main>
|
||||||
|
<section class="panel" id="myperson-panel">
|
||||||
|
<h2>My person</h2>
|
||||||
|
<div id="myperson" class="meta"></div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="panel" id="note-panel">
|
||||||
|
<h2>{% if is_admin %}Add article{% else %}Add note{% endif %}</h2>
|
||||||
|
<form id="note-form">
|
||||||
|
{% if is_admin %}
|
||||||
|
<label>person
|
||||||
|
<select id="note-person" name="person_id" required></select>
|
||||||
|
</label>
|
||||||
|
<label>type
|
||||||
|
<select id="note-type" name="article_type" required></select>
|
||||||
|
</label>
|
||||||
|
{% endif %}
|
||||||
|
<label>title
|
||||||
|
<input id="note-title" name="title" />
|
||||||
|
</label>
|
||||||
|
<label>content
|
||||||
|
<textarea id="note-content" name="content" required></textarea>
|
||||||
|
</label>
|
||||||
|
{% if is_admin %}
|
||||||
|
<label>visibility
|
||||||
|
<select id="note-visibility" name="visibility">
|
||||||
|
<option value="private">private</option>
|
||||||
|
<option value="group">group</option>
|
||||||
|
<option value="public">public</option>
|
||||||
|
</select>
|
||||||
|
</label>
|
||||||
|
{% endif %}
|
||||||
|
<button type="submit">Save</button>
|
||||||
|
</form>
|
||||||
|
<p class="hint" id="note-hint"></p>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="panel">
|
||||||
|
<h2>Articles</h2>
|
||||||
|
<ul id="articles-list"></ul>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="panel" id="groups-panel">
|
||||||
|
<h2>My groups</h2>
|
||||||
|
<form id="group-form">
|
||||||
|
<label>name
|
||||||
|
<input id="group-name" name="name" required />
|
||||||
|
</label>
|
||||||
|
<button type="submit">Create group</button>
|
||||||
|
</form>
|
||||||
|
<ul id="groups-list"></ul>
|
||||||
|
<form id="invite-form">
|
||||||
|
<label>group
|
||||||
|
<select id="invite-group" name="group_id" required></select>
|
||||||
|
</label>
|
||||||
|
<label>person
|
||||||
|
<select id="invite-person" name="person_id" required></select>
|
||||||
|
</label>
|
||||||
|
<button type="submit">Invite person</button>
|
||||||
|
<button type="button" id="join-self" class="btn-ghost">Add me</button>
|
||||||
|
</form>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
{% if is_admin %}
|
||||||
|
<section class="panel admin" id="admin-person-panel">
|
||||||
|
<h2>Admin · create person</h2>
|
||||||
|
<form id="admin-person-form">
|
||||||
|
<label>name
|
||||||
|
<input id="admin-person-name" name="name" required />
|
||||||
|
</label>
|
||||||
|
<label>email
|
||||||
|
<input id="admin-person-email" name="email" type="email" />
|
||||||
|
</label>
|
||||||
|
<label>password (only for a new account)
|
||||||
|
<input id="admin-person-password" name="password" type="password" />
|
||||||
|
</label>
|
||||||
|
<button type="submit">Create person</button>
|
||||||
|
</form>
|
||||||
|
<ul id="admin-persons-list"></ul>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="panel admin" id="admin-email-panel">
|
||||||
|
<h2>Admin · person emails</h2>
|
||||||
|
<form id="attach-form">
|
||||||
|
<label>person
|
||||||
|
<select id="attach-person" name="person_id" required></select>
|
||||||
|
</label>
|
||||||
|
<label>email
|
||||||
|
<input id="attach-email" name="email" type="email" required />
|
||||||
|
</label>
|
||||||
|
<button type="submit">Attach</button>
|
||||||
|
<button type="button" id="detach-email" class="btn-ghost">Detach</button>
|
||||||
|
</form>
|
||||||
|
<p class="hint">The email needs an account; create one above by giving a password.</p>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="panel admin" id="admin-rights-panel">
|
||||||
|
<h2>Admin · accounts & rights</h2>
|
||||||
|
<form id="right-form">
|
||||||
|
<label>account
|
||||||
|
<select id="right-account" name="account_id" required></select>
|
||||||
|
</label>
|
||||||
|
<label>right
|
||||||
|
<select id="right-right" name="right" required></select>
|
||||||
|
</label>
|
||||||
|
<button type="submit">Grant</button>
|
||||||
|
<button type="button" id="revoke-right" class="btn-ghost">Revoke selected</button>
|
||||||
|
</form>
|
||||||
|
<ul id="rights-list"></ul>
|
||||||
|
</section>
|
||||||
|
{% endif %}
|
||||||
|
</main>
|
||||||
|
<pre id="app-msg" class="msg hidden"></pre>
|
||||||
|
|
||||||
|
<script src="/static/crypto.js"></script>
|
||||||
|
<script src="/static/vendor/noble-hashes/blake2.js"></script>
|
||||||
|
<script src="/static/vendor/noble-hashes/argon2.js"></script>
|
||||||
|
<script src="/static/vendor/noble-ciphers/chacha.js"></script>
|
||||||
|
<script src="/static/vendor/noble-ciphers/_arx.js"></script>
|
||||||
|
<script src="/static/vendor/noble-ciphers/_poly1305.js"></script>
|
||||||
|
<script src="/static/vendor/noble-ciphers/utils.js"></script>
|
||||||
|
<script src="/static/vendor/noble-hashes/utils.js"></script>
|
||||||
|
<script src="/static/vendor/noble-hashes/_u64.js"></script>
|
||||||
|
<script src="/static/vendor/noble-hashes/_md.js"></script>
|
||||||
|
<script src="/static/vendor/noble-hashes/_blake.js"></script>
|
||||||
|
<script src="/static/ui.js"></script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
|
""",
|
||||||
|
is_admin=is_admin,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def reply_ok(body):
|
||||||
|
resp = jsonify(body)
|
||||||
|
resp.status_code = 200
|
||||||
|
return resp
|
||||||
|
|
||||||
|
|
||||||
|
def reply_error(message):
|
||||||
|
resp = jsonify({"error": message})
|
||||||
|
resp.status_code = 400
|
||||||
|
return resp
|
||||||
|
|||||||
+41
-141
@@ -1,155 +1,55 @@
|
|||||||
/**
|
"use strict";
|
||||||
* crypto.js – client-side encryption module (vanilla ES module).
|
|
||||||
*
|
|
||||||
* All cryptography happens in the browser. The passphrase and derived
|
|
||||||
* key never leave this module's memory and are never sent anywhere.
|
|
||||||
*
|
|
||||||
* Design:
|
|
||||||
* - Key derivation: Argon2id (via @noble/hashes), one key per session,
|
|
||||||
* derived once from the passphrase the user enters on opening the
|
|
||||||
* site. The salt used for derivation is *not* the per-record salt;
|
|
||||||
* it is a random domain salt stored alongside each record.
|
|
||||||
* - Cipher: XChaCha20-Poly1305 (AEAD) with a fresh random 24-byte nonce
|
|
||||||
* per record (via @noble/ciphers).
|
|
||||||
* - Each record carries its own random salt. That salt is bound into
|
|
||||||
* the AEAD header (as an extra attribute) so re-deriving the key for
|
|
||||||
* a record with a modified salt reliably fails. TLS-like: header is
|
|
||||||
* encrypted alongside the payload body.
|
|
||||||
* - AAD (associated data) binds the record's uuid into the AEAD header,
|
|
||||||
* so a ciphertext cannot be swapped between records undetected.
|
|
||||||
*
|
|
||||||
* Everything is in-memory only: this file has no persistence, and the
|
|
||||||
* session key must be wiped explicitly by the caller (wipeKey).
|
|
||||||
*/
|
|
||||||
|
|
||||||
import { xchacha20poly1305 } from "./vendor/noble-ciphers/chacha.js";
|
function req(path, options) {
|
||||||
import { randomBytes } from "./vendor/noble-ciphers/utils.js";
|
const headers = { "Content-Type": "application/json" };
|
||||||
import { argon2id } from "./vendor/noble-hashes/argon2.js";
|
options = Object.assign({ method: "GET", headers }, options || {});
|
||||||
|
if (options.body && typeof options.body === "object") {
|
||||||
const ARGON2_PARAMS = {
|
options.body = JSON.stringify(options.body);
|
||||||
// Moderate defaults so unlocking stays usable on typical hardware in-JS.
|
}
|
||||||
t: 2, // passes
|
return fetch(path, options).then(function (r) {
|
||||||
m: 16384, // memory, KiB (16 MiB)
|
return r.json().then(function (data) {
|
||||||
p: 1, // parallelism
|
if (!r.ok) throw new Error(data.error || "request failed");
|
||||||
dkLen: 32, // 256-bit key for XChaCha20
|
return data;
|
||||||
};
|
});
|
||||||
|
});
|
||||||
const REC_SALT_LEN = 16; // per-record salt is independent from KDF salt? No:
|
|
||||||
// the KDF salt IS the per-record salt (see below).
|
|
||||||
|
|
||||||
// ---------- base64 / utf8 helpers ----------
|
|
||||||
|
|
||||||
export function b64encode(bytes) {
|
|
||||||
let bin = "";
|
|
||||||
for (const b of bytes) bin += String.fromCharCode(b);
|
|
||||||
return btoa(bin);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export function b64decode(str) {
|
function postForm(path, form) {
|
||||||
const bin = atob(str);
|
const data = {};
|
||||||
const out = new Uint8Array(bin.length);
|
for (const [k, v] of new FormData(form)) {
|
||||||
for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
|
if (v) data[k] = v;
|
||||||
return out;
|
}
|
||||||
|
return req(path, { method: "POST", body: JSON.stringify(data) });
|
||||||
}
|
}
|
||||||
|
|
||||||
export function utf8encode(str) {
|
function patchJson(path, body) {
|
||||||
return new TextEncoder().encode(str);
|
return req(path, { method: "PATCH", body: body });
|
||||||
}
|
}
|
||||||
|
|
||||||
export function utf8decode(bytes) {
|
function delReq(path) {
|
||||||
return new TextDecoder().decode(bytes);
|
return req(path, { method: "DELETE" });
|
||||||
}
|
}
|
||||||
|
|
||||||
export function randomUuid() {
|
function escapeHtml(s) {
|
||||||
return crypto.randomUUID();
|
return String(s)
|
||||||
|
.replace(/&/g, "&")
|
||||||
|
.replace(/</g, "<")
|
||||||
|
.replace(/>/g, ">")
|
||||||
|
.replace(/"/g, """);
|
||||||
}
|
}
|
||||||
|
|
||||||
// ---------- key derivation ----------
|
function uuid() {
|
||||||
|
if (typeof crypto !== "undefined" && crypto.randomUUID) return crypto.randomUUID();
|
||||||
/**
|
const a = new Uint8Array(16);
|
||||||
* Derive a 32-byte key from a passphrase + salt with Argon2id.
|
(crypto.getRandomValues || function () { for (let i = 0; i < a.length; i++) a[i] = Math.floor(Math.random() * 256); })(a);
|
||||||
* Runs entirely in the browser; the passphrase never leaves it.
|
a[6] = (a[6] & 0x0f) | 0x40;
|
||||||
*/
|
a[8] = (a[8] & 0x3f) | 0x80;
|
||||||
export function deriveKey(passphrase, saltBytes) {
|
const hex = Array.from(a, b => b.toString(16).padStart(2, "0")).join("");
|
||||||
if (typeof passphrase !== "string" || passphrase.length === 0)
|
return hex.slice(0, 8) + "-" + hex.slice(8, 12) + "-" + hex.slice(12, 16) + "-" + hex.slice(16, 20) + "-" + hex.slice(20);
|
||||||
throw new Error("invalid passphrase");
|
|
||||||
if (!(saltBytes instanceof Uint8Array) || saltBytes.length < 8)
|
|
||||||
throw new Error("invalid salt");
|
|
||||||
const pwBytes = utf8encode(passphrase);
|
|
||||||
try {
|
|
||||||
return argon2id(pwBytes, saltBytes, ARGON2_PARAMS);
|
|
||||||
} finally {
|
|
||||||
pwBytes.fill(0); // best-effort scratch wipe
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// ---------- record encryption ----------
|
function appendMsg(el, message, isError) {
|
||||||
|
el.textContent = message || "";
|
||||||
/**
|
el.classList.toggle("hidden", !message);
|
||||||
* Encrypt a record payload.
|
el.style.color = isError ? "#dc2626" : "#047857";
|
||||||
*
|
|
||||||
* For a NEW record pass salt = randomSalt(). For an UPDATE pass the
|
|
||||||
* salt already stored on the record — the payload must be encrypted
|
|
||||||
* under a key derived from the SAME salt, otherwise decryption on the
|
|
||||||
* other side fails loudly. This binds the salt to the ciphertext:
|
|
||||||
* a modified salt (= malicious re-key) cannot go unnoticed.
|
|
||||||
*
|
|
||||||
* Payload is any JSON-serializable value. Returns the record body
|
|
||||||
* ready for the API ({uuid, ciphertext, nonce, salt}) with the AEAD
|
|
||||||
* computed over uuid+salt as associated data.
|
|
||||||
*/
|
|
||||||
export function encryptRecord(key, uuid, payload, saltBytes) {
|
|
||||||
if (!(saltBytes instanceof Uint8Array) || saltBytes.length !== REC_SALT_LEN)
|
|
||||||
throw new Error("invalid record salt");
|
|
||||||
const nonce = randomBytes(24);
|
|
||||||
// AAD binds uuid AND salt: swapping ciphertext between records or
|
|
||||||
// silently changing the salt breaks the tag.
|
|
||||||
const aad = utf8encode(
|
|
||||||
"crushdb:record:" + uuid + ":" + b64encode(saltBytes)
|
|
||||||
);
|
|
||||||
const plaintext = utf8encode(JSON.stringify(payload));
|
|
||||||
const ciphertext = xchacha20poly1305(key, nonce, aad).encrypt(plaintext);
|
|
||||||
plaintext.fill(0); // no plaintext residue in heap
|
|
||||||
return {
|
|
||||||
uuid,
|
|
||||||
ciphertext: b64encode(ciphertext),
|
|
||||||
nonce: b64encode(nonce),
|
|
||||||
salt: b64encode(saltBytes),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
export function randomSalt() {
|
|
||||||
return randomBytes(REC_SALT_LEN);
|
|
||||||
}
|
|
||||||
|
|
||||||
// ---------- record decryption ----------
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Decrypt a record fetched from the API.
|
|
||||||
* Throws on wrong key, wrong salt, or any tampering (AEAD tag).
|
|
||||||
*/
|
|
||||||
export function decryptRecord(key, rec) {
|
|
||||||
if (!rec || typeof rec.uuid !== "string") throw new Error("invalid record");
|
|
||||||
const saltBytes = b64decode(rec.salt);
|
|
||||||
const aad = utf8encode(
|
|
||||||
"crushdb:record:" + rec.uuid + ":" + b64encode(saltBytes)
|
|
||||||
);
|
|
||||||
const ct = b64decode(rec.ciphertext);
|
|
||||||
const nonce = b64decode(rec.nonce);
|
|
||||||
const plaintext = xchacha20poly1305(key, nonce, aad).decrypt(ct);
|
|
||||||
try {
|
|
||||||
return JSON.parse(utf8decode(plaintext));
|
|
||||||
} finally {
|
|
||||||
plaintext.fill(0);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// ---------- hygiene ----------
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Best-effort wipe of a derived key (32 bytes). JS cannot guarantee
|
|
||||||
* zeroing, but this removes the obvious copy.
|
|
||||||
*/
|
|
||||||
export function wipeKey(key) {
|
|
||||||
if (key instanceof Uint8Array) key.fill(0);
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,84 +0,0 @@
|
|||||||
<!DOCTYPE html>
|
|
||||||
<html lang="de">
|
|
||||||
<head>
|
|
||||||
<meta charset="utf-8" />
|
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
|
||||||
<title>crushdb</title>
|
|
||||||
<link rel="stylesheet" href="/static/style.css" />
|
|
||||||
</head>
|
|
||||||
<body>
|
|
||||||
<h1>crushdb</h1>
|
|
||||||
<p class="tagline">Verschlüsselte Datensätze zwischen zwei Personen</p>
|
|
||||||
|
|
||||||
<section id="flash" class="flash" aria-live="polite"></section>
|
|
||||||
|
|
||||||
<!-- unlock screen: passphrase stays in memory only -->
|
|
||||||
<section id="unlock">
|
|
||||||
<form id="unlock-form" autocomplete="off">
|
|
||||||
<label for="passphrase">Passphrase</label>
|
|
||||||
<input
|
|
||||||
type="password"
|
|
||||||
id="passphrase"
|
|
||||||
autocomplete="off"
|
|
||||||
required
|
|
||||||
placeholder="Passphrase eingeben …"
|
|
||||||
/>
|
|
||||||
<button type="submit">Entsperren</button>
|
|
||||||
<p class="hint">
|
|
||||||
Die Passphrase verlässt niemals deinen Browser. Sie wird per
|
|
||||||
Argon2id lokal abgeleitet und nur im Arbeitsspeicher gehalten.
|
|
||||||
</p>
|
|
||||||
</form>
|
|
||||||
</section>
|
|
||||||
|
|
||||||
<!-- main app, hidden until unlocked -->
|
|
||||||
<section id="app" hidden>
|
|
||||||
<div class="toolbar">
|
|
||||||
<button id="new-btn" type="button">+ Neuer Datensatz</button>
|
|
||||||
<button id="lock-btn" type="button">Sperren</button>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<table id="records">
|
|
||||||
<thead>
|
|
||||||
<tr>
|
|
||||||
<th>Person A</th>
|
|
||||||
<th>Person B</th>
|
|
||||||
<th>Start</th>
|
|
||||||
<th>Ende</th>
|
|
||||||
<th>Aktion</th>
|
|
||||||
<th></th>
|
|
||||||
</tr>
|
|
||||||
</thead>
|
|
||||||
<tbody></tbody>
|
|
||||||
</table>
|
|
||||||
</section>
|
|
||||||
|
|
||||||
<!-- create/edit modal -->
|
|
||||||
<div id="editor-backdrop" hidden>
|
|
||||||
<form id="editor" autocomplete="off">
|
|
||||||
<h2 id="editor-title">Neuer Datensatz</h2>
|
|
||||||
<label>Person A
|
|
||||||
<input id="f-persona" type="text" required maxlength="120" />
|
|
||||||
</label>
|
|
||||||
<label>Person B
|
|
||||||
<input id="f-personb" type="text" required maxlength="120" />
|
|
||||||
</label>
|
|
||||||
<label>Start (optional)
|
|
||||||
<input id="f-tsstart" type="datetime-local" />
|
|
||||||
</label>
|
|
||||||
<label>Ende (optional)
|
|
||||||
<input id="f-tsend" type="datetime-local" />
|
|
||||||
</label>
|
|
||||||
<label>Aktion
|
|
||||||
<input id="f-action" type="text" required maxlength="500" />
|
|
||||||
</label>
|
|
||||||
<div class="actions">
|
|
||||||
<button type="submit">Speichern</button>
|
|
||||||
<button type="button" id="editor-cancel">Abbrechen</button>
|
|
||||||
</div>
|
|
||||||
</form>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<script type="module" src="/static/ui.js"></script>
|
|
||||||
</body>
|
|
||||||
</html>
|
|
||||||
+82
-122
@@ -1,129 +1,89 @@
|
|||||||
/* crushdb – simple, clean dark UI */
|
|
||||||
|
|
||||||
:root {
|
|
||||||
--bg: #101418;
|
|
||||||
--panel: #1a2028;
|
|
||||||
--panel-2: #202830;
|
|
||||||
--border: #2c3642;
|
|
||||||
--text: #e6edf3;
|
|
||||||
--muted: #8b98a5;
|
|
||||||
--accent: #4da3ff;
|
|
||||||
--danger: #ff5d5d;
|
|
||||||
--ok: #47d68a;
|
|
||||||
}
|
|
||||||
|
|
||||||
* { box-sizing: border-box; }
|
* { box-sizing: border-box; }
|
||||||
|
|
||||||
body {
|
body {
|
||||||
margin: 0 auto;
|
font-family: system-ui, -apple-system, sans-serif;
|
||||||
max-width: 960px;
|
margin: 0;
|
||||||
padding: 2rem 1rem;
|
background: #f6f7f9;
|
||||||
font-family: system-ui, -apple-system, "Segoe UI", sans-serif;
|
color: #1f2330;
|
||||||
background: var(--bg);
|
|
||||||
color: var(--text);
|
|
||||||
line-height: 1.5;
|
|
||||||
}
|
}
|
||||||
|
header {
|
||||||
h1 { margin: 0 0 0.25rem; font-size: 1.6rem; }
|
|
||||||
.tagline { margin: 0 0 1.5rem; color: var(--muted); }
|
|
||||||
|
|
||||||
#flash {
|
|
||||||
min-height: 1.4rem;
|
|
||||||
margin-bottom: 1rem;
|
|
||||||
color: var(--ok);
|
|
||||||
}
|
|
||||||
#flash.error { color: var(--danger); }
|
|
||||||
|
|
||||||
#unlock {
|
|
||||||
max-width: 420px;
|
|
||||||
margin: 3rem auto;
|
|
||||||
background: var(--panel);
|
|
||||||
border: 1px solid var(--border);
|
|
||||||
border-radius: 10px;
|
|
||||||
padding: 1.5rem;
|
|
||||||
}
|
|
||||||
|
|
||||||
#unlock label { display: block; margin-bottom: 0.5rem; }
|
|
||||||
#unlock input {
|
|
||||||
width: 100%;
|
|
||||||
margin-bottom: 1rem;
|
|
||||||
}
|
|
||||||
.hint { color: var(--muted); font-size: 0.85rem; margin-top: 1rem; }
|
|
||||||
|
|
||||||
input, button {
|
|
||||||
font: inherit;
|
|
||||||
color: var(--text);
|
|
||||||
}
|
|
||||||
|
|
||||||
input {
|
|
||||||
background: var(--panel-2);
|
|
||||||
border: 1px solid var(--border);
|
|
||||||
border-radius: 6px;
|
|
||||||
padding: 0.5rem 0.7rem;
|
|
||||||
}
|
|
||||||
input:focus { outline: 1px solid var(--accent); }
|
|
||||||
|
|
||||||
button {
|
|
||||||
background: var(--accent);
|
|
||||||
color: #0b1016;
|
|
||||||
border: none;
|
|
||||||
border-radius: 6px;
|
|
||||||
padding: 0.5rem 1rem;
|
|
||||||
cursor: pointer;
|
|
||||||
font-weight: 600;
|
|
||||||
}
|
|
||||||
button:hover { filter: brightness(1.1); }
|
|
||||||
|
|
||||||
#app .toolbar {
|
|
||||||
display: flex;
|
|
||||||
gap: 0.75rem;
|
|
||||||
margin-bottom: 1rem;
|
|
||||||
}
|
|
||||||
#lock-btn { background: var(--panel-2); color: var(--text); border: 1px solid var(--border); }
|
|
||||||
|
|
||||||
table {
|
|
||||||
width: 100%;
|
|
||||||
border-collapse: collapse;
|
|
||||||
background: var(--panel);
|
|
||||||
border: 1px solid var(--border);
|
|
||||||
border-radius: 10px;
|
|
||||||
overflow: hidden;
|
|
||||||
}
|
|
||||||
|
|
||||||
th, td {
|
|
||||||
padding: 0.6rem 0.75rem;
|
|
||||||
text-align: left;
|
|
||||||
border-bottom: 1px solid var(--border);
|
|
||||||
}
|
|
||||||
thead th { background: var(--panel-2); color: var(--muted); font-weight: 600; }
|
|
||||||
tbody tr:last-child td { border-bottom: none; }
|
|
||||||
tbody tr:hover { background: var(--panel-2); }
|
|
||||||
|
|
||||||
.row-error td { color: var(--danger); font-size: 0.9rem; }
|
|
||||||
|
|
||||||
td:last-child, td button { white-space: nowrap; }
|
|
||||||
td button + button { margin-left: 0.4rem; }
|
|
||||||
|
|
||||||
/* modal */
|
|
||||||
#editor-backdrop {
|
|
||||||
position: fixed;
|
|
||||||
inset: 0;
|
|
||||||
background: rgba(0, 0, 0, 0.6);
|
|
||||||
display: flex;
|
display: flex;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
justify-content: center;
|
justify-content: space-between;
|
||||||
|
padding: 12px 16px;
|
||||||
|
background: #ffffff;
|
||||||
|
border-bottom: 1px solid #e4e7ee;
|
||||||
}
|
}
|
||||||
|
.account-bar { display: flex; align-items: center; gap: 12px; }
|
||||||
#editor {
|
main {
|
||||||
background: var(--panel);
|
max-width: 1100px;
|
||||||
border: 1px solid var(--border);
|
margin: 16px auto;
|
||||||
border-radius: 10px;
|
padding: 0 16px;
|
||||||
padding: 1.5rem;
|
display: grid;
|
||||||
width: min(440px, 92vw);
|
grid-template-columns: repeat(auto-fit, minmax(320px, 1fr));
|
||||||
|
gap: 16px;
|
||||||
}
|
}
|
||||||
|
.panel {
|
||||||
#editor h2 { margin-top: 0; font-size: 1.15rem; }
|
background: #ffffff;
|
||||||
#editor label { display: block; margin-bottom: 0.75rem; color: var(--muted); }
|
border: 1px solid #e4e7ee;
|
||||||
#editor input { width: 100%; margin-top: 0.25rem; }
|
border-radius: 8px;
|
||||||
#editor .actions { display: flex; gap: 0.75rem; margin-top: 1rem; }
|
padding: 14px;
|
||||||
#editor-cancel { background: var(--panel-2); color: var(--text); border: 1px solid var(--border); }
|
}
|
||||||
|
.panel h2 { margin-top: 0; font-size: 14px; text-transform: uppercase; letter-spacing: 0.04em; color: #6b7280; }
|
||||||
|
.panel label {
|
||||||
|
display: block;
|
||||||
|
font-size: 12px;
|
||||||
|
color: #6b7280;
|
||||||
|
margin: 8px 0 2px;
|
||||||
|
}
|
||||||
|
input, select, textarea {
|
||||||
|
width: 100%;
|
||||||
|
padding: 6px 8px;
|
||||||
|
border: 1px solid #d1d5db;
|
||||||
|
border-radius: 4px;
|
||||||
|
font-size: 14px;
|
||||||
|
font-family: inherit;
|
||||||
|
}
|
||||||
|
textarea { min-height: 60px; resize: vertical; }
|
||||||
|
button, .btn-small {
|
||||||
|
background: #2563eb;
|
||||||
|
color: #fff;
|
||||||
|
border: none;
|
||||||
|
padding: 6px 12px;
|
||||||
|
border-radius: 4px;
|
||||||
|
cursor: pointer;
|
||||||
|
font-size: 14px;
|
||||||
|
}
|
||||||
|
button[type="button"] { background: #e5e7eb; color: #1f2330; }
|
||||||
|
.btn-small { padding: 4px 8px; font-size: 12px; }
|
||||||
|
.btn-ghost { background: transparent; color: #dc2626; border: 1px solid #dc2626; }
|
||||||
|
.card { max-width: 420px; margin: 60px auto; padding: 24px; }
|
||||||
|
.card h1 { margin: 0 0 16px; }
|
||||||
|
.hint { font-size: 12px; color: #6b7280; margin-top: 12px; }
|
||||||
|
.msg { color: #dc2626; font-size: 12px; margin-top: 8px; word-break: break-word; }
|
||||||
|
.hidden { display: none; }
|
||||||
|
ul { list-style: none; padding: 0; margin: 8px 0 0; }
|
||||||
|
li {
|
||||||
|
padding: 8px 10px;
|
||||||
|
border: 1px solid #e4e7ee;
|
||||||
|
border-radius: 4px;
|
||||||
|
margin: 4px 0;
|
||||||
|
font-size: 13px;
|
||||||
|
background: #fafbfc;
|
||||||
|
}
|
||||||
|
li .meta { color: #6b7280; font-size: 11px; display: block; margin-top: 4px; }
|
||||||
|
.account-bar .dot { width: 8px; height: 8px; border-radius: 50%; background: #10b981; display: inline-block; }
|
||||||
|
.badge {
|
||||||
|
font-size: 11px;
|
||||||
|
text-transform: uppercase;
|
||||||
|
letter-spacing: 0.05em;
|
||||||
|
padding: 2px 8px;
|
||||||
|
border-radius: 999px;
|
||||||
|
background: #e5e7eb;
|
||||||
|
color: #374151;
|
||||||
|
}
|
||||||
|
.panel.admin {
|
||||||
|
border-color: #c7d2fe;
|
||||||
|
background: #f8faff;
|
||||||
|
}
|
||||||
|
.panel.admin h2 { color: #4338ca; }
|
||||||
|
#myperson .meta { margin-top: 4px; }
|
||||||
|
|||||||
+485
-256
@@ -1,275 +1,504 @@
|
|||||||
/**
|
"use strict";
|
||||||
* ui.js – browser UI logic for crushdb.
|
|
||||||
*
|
|
||||||
* Flow:
|
|
||||||
* 1. User enters a passphrase → Argon2id derives the session key in
|
|
||||||
* memory (never sent anywhere, never persisted).
|
|
||||||
* 2. Fetch ciphertext records from /api/records, decrypt each in
|
|
||||||
* memory; decrypt failures are surfaced as "wrong passphrase or
|
|
||||||
* tampered record" without leaking details.
|
|
||||||
* 3. Create/edit records: form values are encrypted client-side
|
|
||||||
* before POST/PUT; the server only ever sees ciphertext.
|
|
||||||
* 4. Delete requires the record's current version (optimistic lock).
|
|
||||||
* 5. "Lock" wipes the passphrase field and releases decrypted rows so
|
|
||||||
* nothing sensitive lingers in the DOM.
|
|
||||||
*/
|
|
||||||
|
|
||||||
import {
|
(function () {
|
||||||
deriveKey,
|
const msgEl = document.getElementById("app-msg") || document.getElementById("login-msg");
|
||||||
encryptRecord,
|
const isLoginPage = !!document.getElementById("login-form");
|
||||||
decryptRecord,
|
|
||||||
randomSalt,
|
|
||||||
randomUuid,
|
|
||||||
wipeKey,
|
|
||||||
} from "./crypto.js";
|
|
||||||
|
|
||||||
// ---------- tiny DOM helpers ----------
|
let currentAccount = null;
|
||||||
|
|
||||||
const $ = (sel) => document.querySelector(sel);
|
function showMessage(text, isError) {
|
||||||
|
if (!msgEl) return;
|
||||||
function el(tag, attrs = {}, children = []) {
|
appendMsg(msgEl, text, isError);
|
||||||
const node = document.createElement(tag);
|
|
||||||
for (const [k, v] of Object.entries(attrs)) {
|
|
||||||
if (k === "class") node.className = v;
|
|
||||||
else if (k === "text") node.textContent = v;
|
|
||||||
else node.setAttribute(k, v);
|
|
||||||
}
|
|
||||||
for (const child of children) node.appendChild(child);
|
|
||||||
return node;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function flash(msg, isError = false) {
|
function clearMessage() {
|
||||||
const box = $("#flash");
|
showMessage("", false);
|
||||||
box.textContent = msg;
|
|
||||||
box.className = isError ? "flash error" : "flash";
|
|
||||||
setTimeout(() => { box.textContent = ""; }, 4000);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// ---------- session state (memory only) ----------
|
function byId(id) {
|
||||||
|
return document.getElementById(id);
|
||||||
let sessionKey = null; // Uint8Array(32) or null
|
|
||||||
|
|
||||||
function resetSession() {
|
|
||||||
wipeKey(sessionKey);
|
|
||||||
sessionKey = null;
|
|
||||||
$("#records").replaceChildren();
|
|
||||||
$("#app").hidden = true;
|
|
||||||
$("#unlock").hidden = false;
|
|
||||||
$("#passphrase").value = "";
|
|
||||||
$("#passphrase").focus();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// ---------- API helpers ----------
|
function setOptions(sel, items, valueOf, labelOf, keepSelection) {
|
||||||
|
if (!sel) return;
|
||||||
async function api(path, opts = {}) {
|
const current = keepSelection ? sel.value : "";
|
||||||
const res = await fetch(path, {
|
sel.innerHTML = "";
|
||||||
headers: opts.body ? { "Content-Type": "application/json" } : {},
|
items.forEach(function (item) {
|
||||||
...opts,
|
const o = document.createElement("option");
|
||||||
|
o.value = valueOf(item);
|
||||||
|
o.textContent = labelOf(item);
|
||||||
|
sel.appendChild(o);
|
||||||
});
|
});
|
||||||
if (!res.ok) {
|
if (current) {
|
||||||
let detail = "";
|
for (const o of sel.options) {
|
||||||
try { detail = (await res.json()).error ?? ""; } catch { /* noop */ }
|
if (o.value === current) o.selected = true;
|
||||||
throw new Error(`HTTP ${res.status}${detail ? ": " + detail : ""}`);
|
|
||||||
}
|
|
||||||
if (res.status === 204) return null;
|
|
||||||
return res.json();
|
|
||||||
}
|
|
||||||
|
|
||||||
// ---------- rendering ----------
|
|
||||||
|
|
||||||
function iso(ts) {
|
|
||||||
if (ts === null || ts === "") return "–";
|
|
||||||
const d = new Date(ts);
|
|
||||||
return isNaN(d) ? String(ts) : d.toLocaleString();
|
|
||||||
}
|
|
||||||
|
|
||||||
function renderRow(record, payload) {
|
|
||||||
const tr = el("tr");
|
|
||||||
const cells = [
|
|
||||||
payload.personA,
|
|
||||||
payload.personB,
|
|
||||||
iso(payload.tsStart),
|
|
||||||
iso(payload.tsEnd),
|
|
||||||
payload.action,
|
|
||||||
];
|
|
||||||
for (const text of cells) {
|
|
||||||
const td = el("td");
|
|
||||||
td.textContent = text ?? ""; // textContent = no HTML injection
|
|
||||||
tr.appendChild(td);
|
|
||||||
}
|
|
||||||
|
|
||||||
const ops = el("td");
|
|
||||||
ops.appendChild(
|
|
||||||
el("button", {
|
|
||||||
text: "Bearbeiten",
|
|
||||||
type: "button",
|
|
||||||
onclick: () => openEditor(record, payload),
|
|
||||||
})
|
|
||||||
);
|
|
||||||
ops.appendChild(
|
|
||||||
el("button", {
|
|
||||||
text: "Löschen",
|
|
||||||
type: "button",
|
|
||||||
onclick: () => removeRecord(record),
|
|
||||||
})
|
|
||||||
);
|
|
||||||
tr.appendChild(ops);
|
|
||||||
return tr;
|
|
||||||
}
|
|
||||||
|
|
||||||
async function reload() {
|
|
||||||
const tbody = $("#records tbody");
|
|
||||||
tbody.replaceChildren();
|
|
||||||
const raw = await api("/api/records");
|
|
||||||
let failures = 0;
|
|
||||||
for (const record of raw) {
|
|
||||||
try {
|
|
||||||
const payload = decryptRecord(sessionKey, record);
|
|
||||||
payload.__version = record.version; // used for optimistic locking
|
|
||||||
tbody.appendChild(renderRow(record, payload));
|
|
||||||
} catch {
|
|
||||||
failures++;
|
|
||||||
tbody.appendChild(
|
|
||||||
el("tr", { class: "row-error" }, [
|
|
||||||
el("td", { colspan: "6", text: "Datensatz nicht entschlüsselbar (falsche Passphrase oder manipuliert)." }),
|
|
||||||
])
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (failures > 0) flash(`${failures} Datensatz/Datensätze konnten nicht entschlüsselt werden.`, true);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function openEditor(record, payload) {
|
/* ----------------------------- login page ----------------------------- */
|
||||||
const form = $("#editor");
|
|
||||||
form.dataset.uuid = record.uuid;
|
|
||||||
form.dataset.version = payload.__version;
|
|
||||||
form.dataset.salt = record.salt;
|
|
||||||
$("#editor-title").textContent = "Datensatz bearbeiten";
|
|
||||||
$("#f-persona").value = payload.personA ?? "";
|
|
||||||
$("#f-personb").value = payload.personB ?? "";
|
|
||||||
$("#f-tsstart").value = payload.tsStart ? new Date(payload.tsStart).toISOString().slice(0, 16) : "";
|
|
||||||
$("#f-tsend").value = payload.tsEnd ? new Date(payload.tsEnd).toISOString().slice(0, 16) : "";
|
|
||||||
$("#f-action").value = payload.action ?? "";
|
|
||||||
$("#editor-backdrop").hidden = false;
|
|
||||||
}
|
|
||||||
|
|
||||||
function newRecord() {
|
function initLoginPage() {
|
||||||
const form = $("#editor");
|
const form = byId("login-form");
|
||||||
form.reset();
|
if (!form) return;
|
||||||
form.dataset.uuid = randomUuid();
|
form.addEventListener("submit", function (e) {
|
||||||
form.dataset.version = "";
|
e.preventDefault();
|
||||||
form.dataset.salt = "";
|
clearMessage();
|
||||||
$("#editor-title").textContent = "Neuer Datensatz";
|
const email = form.email.value.trim();
|
||||||
$("#editor-backdrop").hidden = false;
|
const password = form.password.value;
|
||||||
}
|
if (!email || !password) {
|
||||||
|
showMessage("email and password required", true);
|
||||||
function closeEditor() {
|
|
||||||
$("#editor-backdrop").hidden = true;
|
|
||||||
$("#editor").reset();
|
|
||||||
}
|
|
||||||
|
|
||||||
function tsOrNull(inputValue) {
|
|
||||||
if (!inputValue) return null;
|
|
||||||
const d = new Date(inputValue);
|
|
||||||
return isNaN(d) ? null : d.toISOString();
|
|
||||||
}
|
|
||||||
|
|
||||||
// ---------- record operations ----------
|
|
||||||
|
|
||||||
async function saveRecord(ev) {
|
|
||||||
ev.preventDefault();
|
|
||||||
if (!sessionKey) { flash("Bitte zuerst entsperren.", true); return; }
|
|
||||||
|
|
||||||
const form = $("#editor");
|
|
||||||
const payload = {
|
|
||||||
personA: $("#f-persona").value.trim(),
|
|
||||||
personB: $("#f-personb").value.trim(),
|
|
||||||
tsStart: tsOrNull($("#f-tsstart").value),
|
|
||||||
tsEnd: tsOrNull($("#f-tsend").value),
|
|
||||||
action: $("#f-action").value.trim(),
|
|
||||||
};
|
|
||||||
if (!payload.personA || !payload.personB || !payload.action) {
|
|
||||||
flash("Person A, Person B und Aktion sind erforderlich.", true);
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
fetch("/login", {
|
||||||
const isEdit = form.dataset.version !== "";
|
method: "POST",
|
||||||
const salt = isEdit ? new Uint8Array(atob(form.dataset.salt).split("").map((c) => c.charCodeAt(0))) : randomSalt();
|
headers: { "Content-Type": "application/json" },
|
||||||
const enc = encryptRecord(sessionKey, form.dataset.uuid, payload, salt);
|
body: JSON.stringify({ email: email, password: password }),
|
||||||
|
})
|
||||||
try {
|
.then(function (r) {
|
||||||
if (isEdit) {
|
return r.json().then(function (data) {
|
||||||
enc.version = Number(form.dataset.version);
|
if (!r.ok) throw new Error(data.error || "login failed");
|
||||||
await api(`/api/records/${encodeURIComponent(enc.uuid)}`, { method: "PUT", body: JSON.stringify(enc) });
|
return data;
|
||||||
} else {
|
|
||||||
await api("/api/records", { method: "POST", body: JSON.stringify(enc) });
|
|
||||||
}
|
|
||||||
closeEditor();
|
|
||||||
await reload();
|
|
||||||
flash(isEdit ? "Datensatz aktualisiert." : "Datensatz erstellt.");
|
|
||||||
} catch (e) {
|
|
||||||
closeEditor();
|
|
||||||
if (String(e).includes("409")) {
|
|
||||||
flash("Konflikt: Der Datensatz wurde zwischenzeitlich geändert. Liste wird neu geladen.", true);
|
|
||||||
} else {
|
|
||||||
flash("Speichern fehlgeschlagen: " + e.message, true);
|
|
||||||
}
|
|
||||||
await reload();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async function removeRecord(record) {
|
|
||||||
if (!sessionKey) { flash("Bitte zuerst entsperren.", true); return; }
|
|
||||||
if (!confirm("Diesen Datensatz wirklich löschen?")) return;
|
|
||||||
try {
|
|
||||||
const current = await api(`/api/records/${encodeURIComponent(record.uuid)}`);
|
|
||||||
await api(`/api/records/${encodeURIComponent(record.uuid)}`, {
|
|
||||||
method: "DELETE",
|
|
||||||
body: JSON.stringify({ version: current.version }),
|
|
||||||
});
|
});
|
||||||
await reload();
|
})
|
||||||
flash("Datensatz gelöscht.");
|
.then(function () {
|
||||||
} catch (e) {
|
window.location.href = "/";
|
||||||
if (String(e).includes("409")) flash("Konflikt beim Löschen (Version geändert). Bitte erneut versuchen.", true);
|
})
|
||||||
else flash("Löschen fehlgeschlagen: " + e.message, true);
|
.catch(function (err) {
|
||||||
await reload();
|
showMessage(err.message || "login failed", true);
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// ---------- unlock / lock ----------
|
|
||||||
|
|
||||||
async function unlock(ev) {
|
|
||||||
ev.preventDefault();
|
|
||||||
const passphrase = $("#passphrase").value;
|
|
||||||
if (!passphrase) { flash("Bitte Passphrase eingeben.", true); return; }
|
|
||||||
// Salt for key derivation: per-record salts are used for the AEAD;
|
|
||||||
// for the session key we use a fixed domain-salt so all records can
|
|
||||||
// be opened with one passphrase. It contains no secret.
|
|
||||||
const domainSalt = new TextEncoder().encode("crushdb://session-key-v1");
|
|
||||||
try {
|
|
||||||
sessionKey = deriveKey(passphrase, domainSalt);
|
|
||||||
$("#passphrase").value = "";
|
|
||||||
$("#unlock").hidden = true;
|
|
||||||
$("#app").hidden = false;
|
|
||||||
await reload();
|
|
||||||
} catch (e) {
|
|
||||||
flash("Entsperren fehlgeschlagen: " + e.message, true);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function lock() {
|
|
||||||
if (!confirm("Sperren? Alle entschlüsselten Daten werden verworfen.")) return;
|
|
||||||
resetSession();
|
|
||||||
}
|
|
||||||
|
|
||||||
// ---------- wire-up ----------
|
|
||||||
|
|
||||||
document.addEventListener("DOMContentLoaded", () => {
|
|
||||||
$("#unlock-form").addEventListener("submit", unlock);
|
|
||||||
$("#lock-btn").addEventListener("click", lock);
|
|
||||||
$("#new-btn").addEventListener("click", newRecord);
|
|
||||||
$("#editor").addEventListener("submit", saveRecord);
|
|
||||||
$("#editor-cancel").addEventListener("click", closeEditor);
|
|
||||||
window.addEventListener("beforeunload", () => wipeKey(sessionKey));
|
|
||||||
$("#passphrase").focus();
|
|
||||||
});
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ------------------------------ main app ------------------------------ */
|
||||||
|
|
||||||
|
function initMainApp() {
|
||||||
|
req("/account/me")
|
||||||
|
.then(function (account) {
|
||||||
|
currentAccount = account;
|
||||||
|
startMainApp(account);
|
||||||
|
})
|
||||||
|
.catch(function () {
|
||||||
|
window.location.href = "/login";
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function startMainApp(account) {
|
||||||
|
const emailEl = byId("user-email");
|
||||||
|
if (emailEl) emailEl.textContent = account.email;
|
||||||
|
const roleEl = byId("user-role");
|
||||||
|
if (roleEl) roleEl.textContent = account.is_admin ? "admin" : "user";
|
||||||
|
|
||||||
|
renderMyPerson(account);
|
||||||
|
|
||||||
|
bindNoteForm();
|
||||||
|
bindGroupForm();
|
||||||
|
bindInviteForm();
|
||||||
|
if (account.is_admin) {
|
||||||
|
bindAdminPersonForm();
|
||||||
|
bindAttachForm();
|
||||||
|
bindRightForm();
|
||||||
|
loadArticleTypes();
|
||||||
|
populateRightsDropdown();
|
||||||
|
refreshRights();
|
||||||
|
}
|
||||||
|
|
||||||
|
refreshPersons();
|
||||||
|
refreshArticles();
|
||||||
|
refreshGroups();
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderMyPerson(account) {
|
||||||
|
const box = byId("myperson");
|
||||||
|
const form = byId("note-form");
|
||||||
|
const hint = byId("note-hint");
|
||||||
|
if (!account.person_id) {
|
||||||
|
if (box) box.innerHTML = "Your account is not linked to a person yet. Ask an admin to link it.";
|
||||||
|
if (form) {
|
||||||
|
Array.prototype.forEach.call(form.querySelectorAll("input, textarea, button"), function (el) {
|
||||||
|
el.disabled = true;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if (hint) hint.textContent = "You can add notes, groups and invites once an admin links you to a person.";
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
req("/persons/" + encodeURIComponent(account.person_id))
|
||||||
|
.then(function (p) {
|
||||||
|
if (!box) return;
|
||||||
|
box.innerHTML =
|
||||||
|
"<strong>" + escapeHtml(p.name || "(unnamed)") + "</strong>" +
|
||||||
|
'<span class="meta">' +
|
||||||
|
(p.emails && p.emails.length ? "emails: " + escapeHtml(p.emails.join(", ")) : "no email shown") +
|
||||||
|
"</span>";
|
||||||
|
})
|
||||||
|
.catch(function () {
|
||||||
|
if (box) box.textContent = "Person not found.";
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function loadArticleTypes() {
|
||||||
|
req("/api/types")
|
||||||
|
.then(function (data) {
|
||||||
|
setOptions(
|
||||||
|
byId("note-type"),
|
||||||
|
data.article_types || [],
|
||||||
|
function (t) { return t; },
|
||||||
|
function (t) { return (data.article_type_labels && data.article_type_labels[t]) || t; }
|
||||||
|
);
|
||||||
|
})
|
||||||
|
.catch(function () {});
|
||||||
|
}
|
||||||
|
|
||||||
|
function populateRightsDropdown() {
|
||||||
|
req("/api/types")
|
||||||
|
.then(function (data) {
|
||||||
|
const rights = data.rights || {};
|
||||||
|
setOptions(
|
||||||
|
byId("right-right"),
|
||||||
|
Object.keys(rights),
|
||||||
|
function (k) { return k; },
|
||||||
|
function (k) { return k + " - " + rights[k]; }
|
||||||
|
);
|
||||||
|
})
|
||||||
|
.catch(function () {});
|
||||||
|
}
|
||||||
|
|
||||||
|
function bindNoteForm() {
|
||||||
|
const form = byId("note-form");
|
||||||
|
if (!form) return;
|
||||||
|
form.addEventListener("submit", function (e) {
|
||||||
|
e.preventDefault();
|
||||||
|
clearMessage();
|
||||||
|
const isAdmin = currentAccount && currentAccount.is_admin;
|
||||||
|
const personSel = byId("note-person");
|
||||||
|
const personId = isAdmin && personSel ? personSel.value : currentAccount && currentAccount.person_id;
|
||||||
|
if (!personId) {
|
||||||
|
showMessage("no person linked to your account", true);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const typeSel = byId("note-type");
|
||||||
|
const visSel = byId("note-visibility");
|
||||||
|
req("/articles", {
|
||||||
|
method: "POST",
|
||||||
|
body: {
|
||||||
|
person_id: personId,
|
||||||
|
article_type: isAdmin && typeSel ? typeSel.value : "notes",
|
||||||
|
title: form.title.value,
|
||||||
|
content: form.content.value,
|
||||||
|
visibility: isAdmin && visSel ? visSel.value : "private",
|
||||||
|
group_ids: [],
|
||||||
|
},
|
||||||
|
})
|
||||||
|
.then(function () {
|
||||||
|
form.reset();
|
||||||
|
refreshArticles();
|
||||||
|
})
|
||||||
|
.catch(function (err) {
|
||||||
|
showMessage(err.message || "failed to save", true);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function refreshArticles() {
|
||||||
|
req("/articles")
|
||||||
|
.then(function (data) {
|
||||||
|
const list = byId("articles-list");
|
||||||
|
if (!list) return;
|
||||||
|
list.innerHTML = "";
|
||||||
|
if (!data.length) {
|
||||||
|
list.innerHTML = '<li class="meta">Nothing here yet.</li>';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
data.forEach(function (a) {
|
||||||
|
const li = document.createElement("li");
|
||||||
|
li.innerHTML =
|
||||||
|
"<strong>" + escapeHtml(a.title || "(untitled)") + "</strong> " +
|
||||||
|
'<span class="meta">' +
|
||||||
|
escapeHtml(a.article_type) +
|
||||||
|
" · " + escapeHtml(a.visibility) +
|
||||||
|
"</span>" +
|
||||||
|
(a.content
|
||||||
|
? "<pre style='margin:4px 0;white-space:pre-wrap;font:inherit;background:#fff;border:1px solid #e4e7ee;padding:4px;border-radius:4px;'>" +
|
||||||
|
escapeHtml(a.content) + "</pre>"
|
||||||
|
: "") +
|
||||||
|
(a.visibility === "group" && a.allowed_groups && a.allowed_groups.length
|
||||||
|
? '<span class="meta">groups: ' + escapeHtml(a.allowed_groups.join(", ")) + "</span>"
|
||||||
|
: "");
|
||||||
|
list.appendChild(li);
|
||||||
|
});
|
||||||
|
})
|
||||||
|
.catch(function (err) {
|
||||||
|
showMessage(err.message || "failed to load articles", true);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function refreshPersons() {
|
||||||
|
req("/persons")
|
||||||
|
.then(function (data) {
|
||||||
|
const label = function (p) { return p.name || "(unnamed)"; };
|
||||||
|
|
||||||
|
setOptions(byId("invite-person"), data, function (p) { return p.id; }, label, true);
|
||||||
|
|
||||||
|
const noteSel = byId("note-person");
|
||||||
|
setOptions(noteSel, data, function (p) { return p.id; }, label, true);
|
||||||
|
if (noteSel && !noteSel.value && currentAccount && currentAccount.person_id) {
|
||||||
|
noteSel.value = currentAccount.person_id;
|
||||||
|
}
|
||||||
|
|
||||||
|
setOptions(byId("attach-person"), data, function (p) { return p.id; }, label, true);
|
||||||
|
|
||||||
|
const list = byId("admin-persons-list");
|
||||||
|
if (!list) return;
|
||||||
|
list.innerHTML = "";
|
||||||
|
if (!data.length) {
|
||||||
|
list.innerHTML = '<li class="meta">No persons yet.</li>';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
data.forEach(function (p) {
|
||||||
|
const li = document.createElement("li");
|
||||||
|
li.innerHTML =
|
||||||
|
"<strong>" + escapeHtml(p.name || "(unnamed)") + "</strong>" +
|
||||||
|
'<span class="meta">' +
|
||||||
|
(p.emails && p.emails.length ? "emails: " + escapeHtml(p.emails.join(", ")) : "no emails") +
|
||||||
|
"</span>";
|
||||||
|
list.appendChild(li);
|
||||||
|
});
|
||||||
|
})
|
||||||
|
.catch(function (err) {
|
||||||
|
showMessage(err.message || "failed to load persons", true);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function bindAdminPersonForm() {
|
||||||
|
const form = byId("admin-person-form");
|
||||||
|
if (!form) return;
|
||||||
|
form.addEventListener("submit", function (e) {
|
||||||
|
e.preventDefault();
|
||||||
|
clearMessage();
|
||||||
|
req("/admin/persons", {
|
||||||
|
method: "POST",
|
||||||
|
body: {
|
||||||
|
name: form.name.value,
|
||||||
|
email: form.email.value,
|
||||||
|
password: form.password.value,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
.then(function (person) {
|
||||||
|
form.reset();
|
||||||
|
showMessage("created person: " + (person.name || person.id), false);
|
||||||
|
refreshPersons();
|
||||||
|
})
|
||||||
|
.catch(function (err) {
|
||||||
|
showMessage(err.message || "failed to create person", true);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function bindAttachForm() {
|
||||||
|
const form = byId("attach-form");
|
||||||
|
if (!form) return;
|
||||||
|
const send = function (action, okText) {
|
||||||
|
const personId = byId("attach-person").value;
|
||||||
|
const email = byId("attach-email").value.trim();
|
||||||
|
if (!personId || !email) {
|
||||||
|
showMessage("select a person and enter an email", true);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
req("/persons/" + encodeURIComponent(personId) + "/emails/" + action, {
|
||||||
|
method: "POST",
|
||||||
|
body: { email: email },
|
||||||
|
})
|
||||||
|
.then(function () {
|
||||||
|
showMessage(okText + " " + email, false);
|
||||||
|
refreshPersons();
|
||||||
|
})
|
||||||
|
.catch(function (err) {
|
||||||
|
showMessage(err.message || "failed to change email", true);
|
||||||
|
});
|
||||||
|
};
|
||||||
|
form.addEventListener("submit", function (e) {
|
||||||
|
e.preventDefault();
|
||||||
|
clearMessage();
|
||||||
|
send("attach", "attached");
|
||||||
|
});
|
||||||
|
const detach = byId("detach-email");
|
||||||
|
if (detach) {
|
||||||
|
detach.addEventListener("click", function () {
|
||||||
|
clearMessage();
|
||||||
|
send("detach", "detached");
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function bindGroupForm() {
|
||||||
|
const form = byId("group-form");
|
||||||
|
if (!form) return;
|
||||||
|
form.addEventListener("submit", function (e) {
|
||||||
|
e.preventDefault();
|
||||||
|
clearMessage();
|
||||||
|
if (!currentAccount || !currentAccount.person_id) {
|
||||||
|
showMessage("no person linked to your account", true);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
req("/groups", {
|
||||||
|
method: "POST",
|
||||||
|
body: { person_id: currentAccount.person_id, name: form.name.value },
|
||||||
|
})
|
||||||
|
.then(function () {
|
||||||
|
form.reset();
|
||||||
|
refreshGroups();
|
||||||
|
})
|
||||||
|
.catch(function (err) {
|
||||||
|
showMessage(err.message || "failed to create group", true);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function refreshGroups() {
|
||||||
|
req("/groups")
|
||||||
|
.then(function (data) {
|
||||||
|
setOptions(
|
||||||
|
byId("invite-group"),
|
||||||
|
data,
|
||||||
|
function (g) { return g.id; },
|
||||||
|
function (g) { return g.name || "(unnamed)"; },
|
||||||
|
true
|
||||||
|
);
|
||||||
|
const list = byId("groups-list");
|
||||||
|
if (!list) return;
|
||||||
|
list.innerHTML = "";
|
||||||
|
if (!data.length) {
|
||||||
|
list.innerHTML = '<li class="meta">No groups yet. Create one above.</li>';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
data.forEach(function (g) {
|
||||||
|
const li = document.createElement("li");
|
||||||
|
li.innerHTML =
|
||||||
|
"<strong>" + escapeHtml(g.name || "(unnamed)") + "</strong> " +
|
||||||
|
'<span class="meta">members: ' +
|
||||||
|
(g.members && g.members.length
|
||||||
|
? escapeHtml(g.members.map(function (m) { return m.name || "(unnamed)"; }).join(", "))
|
||||||
|
: "none") +
|
||||||
|
"</span>";
|
||||||
|
list.appendChild(li);
|
||||||
|
});
|
||||||
|
})
|
||||||
|
.catch(function (err) {
|
||||||
|
showMessage(err.message || "failed to load groups", true);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function bindInviteForm() {
|
||||||
|
const form = byId("invite-form");
|
||||||
|
if (!form) return;
|
||||||
|
const addMember = function (groupId, personId) {
|
||||||
|
if (!groupId || !personId) {
|
||||||
|
showMessage("select a group and a person", true);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
req("/groups/" + encodeURIComponent(groupId) + "/members/" + encodeURIComponent(personId), {
|
||||||
|
method: "POST",
|
||||||
|
body: {},
|
||||||
|
})
|
||||||
|
.then(function () {
|
||||||
|
clearMessage();
|
||||||
|
refreshGroups();
|
||||||
|
})
|
||||||
|
.catch(function (err) {
|
||||||
|
showMessage(err.message || "failed to add member", true);
|
||||||
|
});
|
||||||
|
};
|
||||||
|
form.addEventListener("submit", function (e) {
|
||||||
|
e.preventDefault();
|
||||||
|
clearMessage();
|
||||||
|
addMember(byId("invite-group").value, byId("invite-person").value);
|
||||||
|
});
|
||||||
|
const join = byId("join-self");
|
||||||
|
if (join) {
|
||||||
|
join.addEventListener("click", function () {
|
||||||
|
clearMessage();
|
||||||
|
if (!currentAccount || !currentAccount.person_id) {
|
||||||
|
showMessage("no person linked to your account", true);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
addMember(byId("invite-group").value, currentAccount.person_id);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function refreshRights() {
|
||||||
|
req("/rights")
|
||||||
|
.then(function (data) {
|
||||||
|
const accountSel = byId("right-account");
|
||||||
|
setOptions(
|
||||||
|
accountSel,
|
||||||
|
data,
|
||||||
|
function (a) { return a.id; },
|
||||||
|
function (a) { return a.email + (a.rights && a.rights.length ? " (" + a.rights.join(", ") + ")" : ""); },
|
||||||
|
true
|
||||||
|
);
|
||||||
|
const list = byId("rights-list");
|
||||||
|
if (!list) return;
|
||||||
|
list.innerHTML = "";
|
||||||
|
data.forEach(function (a) {
|
||||||
|
const li = document.createElement("li");
|
||||||
|
li.innerHTML =
|
||||||
|
"<strong>" + escapeHtml(a.email) + "</strong> " +
|
||||||
|
'<span class="meta">' +
|
||||||
|
(a.rights && a.rights.length ? escapeHtml(a.rights.join(", ")) : "no rights") +
|
||||||
|
"</span>";
|
||||||
|
list.appendChild(li);
|
||||||
|
});
|
||||||
|
})
|
||||||
|
.catch(function (err) {
|
||||||
|
showMessage(err.message || "failed to load rights", true);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function bindRightForm() {
|
||||||
|
const form = byId("right-form");
|
||||||
|
if (!form) return;
|
||||||
|
form.addEventListener("submit", function (e) {
|
||||||
|
e.preventDefault();
|
||||||
|
clearMessage();
|
||||||
|
if (!form.account_id.value || !form.right.value) {
|
||||||
|
showMessage("select account and right", true);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
req("/rights/grant", {
|
||||||
|
method: "POST",
|
||||||
|
body: { account_id: form.account_id.value, right: form.right.value },
|
||||||
|
})
|
||||||
|
.then(refreshRights)
|
||||||
|
.catch(function (err) {
|
||||||
|
showMessage(err.message || "failed to grant right", true);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
const revokeBtn = byId("revoke-right");
|
||||||
|
if (revokeBtn) {
|
||||||
|
revokeBtn.addEventListener("click", function () {
|
||||||
|
clearMessage();
|
||||||
|
const accountSel = byId("right-account");
|
||||||
|
const rightSel = byId("right-right");
|
||||||
|
if (!accountSel.value || !rightSel.value) {
|
||||||
|
showMessage("select account and right to revoke", true);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
req("/rights/revoke", {
|
||||||
|
method: "POST",
|
||||||
|
body: { account_id: accountSel.value, right: rightSel.value },
|
||||||
|
})
|
||||||
|
.then(refreshRights)
|
||||||
|
.catch(function (err) {
|
||||||
|
showMessage(err.message || "failed to revoke right", true);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isLoginPage) {
|
||||||
|
initLoginPage();
|
||||||
|
} else if (byId("app-msg")) {
|
||||||
|
initMainApp();
|
||||||
|
}
|
||||||
|
})();
|
||||||
|
|||||||
+3
-378
@@ -1,379 +1,4 @@
|
|||||||
/**
|
// Stub placeholder for noble-ciphers internal _arx module
|
||||||
* Basic utils for ARX (add-rotate-xor) salsa and chacha ciphers.
|
export function arx() {
|
||||||
|
throw new Error("noble _arx stub: not implemented");
|
||||||
RFC8439 requires multi-step cipher stream, where
|
|
||||||
authKey starts with counter: 0, actual msg with counter: 1.
|
|
||||||
|
|
||||||
For this, we need a way to re-use nonce / counter:
|
|
||||||
|
|
||||||
const counter = new Uint8Array(4);
|
|
||||||
chacha(..., counter, ...); // counter is now 1
|
|
||||||
chacha(..., counter, ...); // counter is now 2
|
|
||||||
|
|
||||||
This is complicated:
|
|
||||||
|
|
||||||
- 32-bit counters are enough, no need for 64-bit: max ArrayBuffer size in JS is 4GB
|
|
||||||
- Original papers don't allow mutating counters
|
|
||||||
- Counter overflow is undefined [^1]
|
|
||||||
- Idea A: allow providing (nonce | counter) instead of just nonce, re-use it
|
|
||||||
- Caveat: Cannot be re-used through all cases:
|
|
||||||
- * chacha has (counter | nonce)
|
|
||||||
- * xchacha has (nonce16 | counter | nonce16)
|
|
||||||
- Idea B: separate nonce / counter and provide separate API for counter re-use
|
|
||||||
- Caveat: there are different counter sizes depending on an algorithm.
|
|
||||||
- salsa & chacha also differ in structures of key & sigma:
|
|
||||||
salsa20: s[0] | k(4) | s[1] | nonce(2) | cnt(2) | s[2] | k(4) | s[3]
|
|
||||||
chacha: s(4) | k(8) | cnt(1) | nonce(3)
|
|
||||||
chacha20orig: s(4) | k(8) | cnt(2) | nonce(2)
|
|
||||||
- Idea C: helper method such as `setSalsaState(key, nonce, sigma, data)`
|
|
||||||
- Caveat: we can't re-use counter array
|
|
||||||
|
|
||||||
xchacha uses the subkey and remaining 8 byte nonce with ChaCha20 as normal
|
|
||||||
(prefixed by 4 NUL bytes, since RFC8439 specifies a 12-byte nonce).
|
|
||||||
Counter overflow is undefined; see {@link https://mailarchive.ietf.org/arch/msg/cfrg/gsOnTJzcbgG6OqD8Sc0GO5aR_tU/ | the CFRG thread}.
|
|
||||||
Current noble policy is strict non-wrap for the shared 32-bit counter path:
|
|
||||||
exported ARX ciphers reject initial `0xffffffff` and stop before any implicit
|
|
||||||
wrap back to zero.
|
|
||||||
See {@link https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha#appendix-A.2 | the XChaCha appendix} for the extended-nonce construction.
|
|
||||||
|
|
||||||
* @module
|
|
||||||
*/
|
|
||||||
import { abool, abytes, anumber, checkOpts, clean, complexOverlapBytes, copyBytes, getOutput, isAligned32, isLE, randomBytes, swap32IfBE, u32, } from "./utils.js";
|
|
||||||
// Replaces `TextEncoder` for ASCII literals, which is enough for sigma constants.
|
|
||||||
// Non-ASCII input would not match UTF-8 `TextEncoder` output.
|
|
||||||
const encodeStr = (str) => Uint8Array.from(str.split(''), (c) => c.charCodeAt(0));
|
|
||||||
// Raw `createCipher(...)` exports consume these native-endian `u32(...)` views directly.
|
|
||||||
// Public `wrapCipher(...)` APIs reject non-little-endian platforms before reaching this path.
|
|
||||||
// RFC 8439 §2.3 / RFC 7539 §2.3 only define the 256-bit-key constants; this 16-byte sigma is
|
|
||||||
// kept for legacy allowShortKeys Salsa/ChaCha variants.
|
|
||||||
const sigma16_32 = /* @__PURE__ */ (() => swap32IfBE(u32(encodeStr('expand 16-byte k'))))();
|
|
||||||
// RFC 8439 §2.3 / RFC 7539 §2.3 define words 0-3 as
|
|
||||||
// `0x61707865 0x3320646e 0x79622d32 0x6b206574`, i.e. `expand 32-byte k`.
|
|
||||||
const sigma32_32 = /* @__PURE__ */ (() => swap32IfBE(u32(encodeStr('expand 32-byte k'))))();
|
|
||||||
/**
|
|
||||||
* Rotates a 32-bit word left.
|
|
||||||
* @param a - Input word.
|
|
||||||
* @param b - Rotation count in bits.
|
|
||||||
* @returns Rotated 32-bit word.
|
|
||||||
* @example
|
|
||||||
* Moves the top byte of `0x12345678` into the low byte position.
|
|
||||||
* ```ts
|
|
||||||
* rotl(0x12345678, 8);
|
|
||||||
* ```
|
|
||||||
*/
|
|
||||||
export function rotl(a, b) {
|
|
||||||
return (a << b) | (a >>> (32 - b));
|
|
||||||
}
|
}
|
||||||
// Salsa and Chacha block length is always 512-bit
|
|
||||||
const BLOCK_LEN = 64;
|
|
||||||
// RFC 8439 §2.2 / RFC 7539 §2.2: the ChaCha state has 16 32-bit words.
|
|
||||||
const BLOCK_LEN32 = 16;
|
|
||||||
// Counter policy for the shared public `counter` argument:
|
|
||||||
// - RFC/IETF ChaCha20 uses a 32-bit counter.
|
|
||||||
// - OpenSSL/Node `chacha20` instead treat the full 16-byte IV as a 128-bit
|
|
||||||
// counter state and carry into the next word.
|
|
||||||
// - Raw `chacha20orig`, `salsa20`, `xsalsa20`, and `xchacha20` use 64-bit counters in libsodium
|
|
||||||
// and libtomcrypt, while some libs (for example libtomcrypt's RFC/IETF path) reject the max
|
|
||||||
// boundary instead of carrying.
|
|
||||||
// - AEAD wrappers diverge too: libsodium `xchacha20poly1305` uses the IETF payload counter from
|
|
||||||
// block 1, while `secretstream_xchacha20poly1305` is a different protocol with rekey/reset.
|
|
||||||
// Noble intentionally throws instead of silently picking one wrap model for users. In the default
|
|
||||||
// path, even a 32-bit boundary would take 2^32 blocks * 64 bytes = 256 GiB, which is practically
|
|
||||||
// unreachable for normal JS callers; advanced users who pass `counter` explicitly can implement
|
|
||||||
// whatever wider carry / wrap policy they need on top.
|
|
||||||
const MAX_COUNTER = /* @__PURE__ */ (() => 2 ** 32 - 1)();
|
|
||||||
const U32_EMPTY = /* @__PURE__ */ Uint32Array.of();
|
|
||||||
function runCipher(core, sigma, key, nonce, data, output, counter, rounds) {
|
|
||||||
const len = data.length;
|
|
||||||
const block = new Uint8Array(BLOCK_LEN);
|
|
||||||
const b32 = u32(block);
|
|
||||||
// Make sure that buffers aligned to 4 bytes
|
|
||||||
const isAligned = isLE && isAligned32(data) && isAligned32(output);
|
|
||||||
const d32 = isAligned ? u32(data) : U32_EMPTY;
|
|
||||||
const o32 = isAligned ? u32(output) : U32_EMPTY;
|
|
||||||
// RFC 8439 §2.4.1 / RFC 7539 §2.4.1 allow XORing one keystream block at a time and
|
|
||||||
// truncating the final partial block instead of materializing the whole keystream.
|
|
||||||
if (!isLE) {
|
|
||||||
for (let pos = 0; pos < len; counter++) {
|
|
||||||
core(sigma, key, nonce, b32, counter, rounds);
|
|
||||||
// RFC 8439 §2.4 / RFC 7539 §2.4 serialize keystream words in little-endian order.
|
|
||||||
swap32IfBE(b32);
|
|
||||||
if (counter >= MAX_COUNTER)
|
|
||||||
throw new Error('arx: counter overflow');
|
|
||||||
const take = Math.min(BLOCK_LEN, len - pos);
|
|
||||||
for (let j = 0, posj; j < take; j++) {
|
|
||||||
posj = pos + j;
|
|
||||||
output[posj] = data[posj] ^ block[j];
|
|
||||||
}
|
|
||||||
pos += take;
|
|
||||||
}
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
for (let pos = 0; pos < len; counter++) {
|
|
||||||
core(sigma, key, nonce, b32, counter, rounds);
|
|
||||||
// See MAX_COUNTER policy note above: never silently wrap the shared public counter.
|
|
||||||
if (counter >= MAX_COUNTER)
|
|
||||||
throw new Error('arx: counter overflow');
|
|
||||||
const take = Math.min(BLOCK_LEN, len - pos);
|
|
||||||
// aligned to 4 bytes
|
|
||||||
if (isAligned && take === BLOCK_LEN) {
|
|
||||||
const pos32 = pos / 4;
|
|
||||||
if (pos % 4 !== 0)
|
|
||||||
throw new Error('arx: invalid block position');
|
|
||||||
for (let j = 0, posj; j < BLOCK_LEN32; j++) {
|
|
||||||
posj = pos32 + j;
|
|
||||||
o32[posj] = d32[posj] ^ b32[j];
|
|
||||||
}
|
|
||||||
pos += BLOCK_LEN;
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
for (let j = 0, posj; j < take; j++) {
|
|
||||||
posj = pos + j;
|
|
||||||
output[posj] = data[posj] ^ block[j];
|
|
||||||
}
|
|
||||||
pos += take;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
/**
|
|
||||||
* Creates an ARX stream cipher from a 32-bit core permutation.
|
|
||||||
* Used internally to build the exported Salsa and ChaCha stream ciphers.
|
|
||||||
* @param core - Core function that fills one keystream block.
|
|
||||||
* @param opts - Cipher layout and nonce-extension options. See {@link CipherOpts}.
|
|
||||||
* @returns Stream cipher function over byte arrays.
|
|
||||||
* @throws If the core callback, key size, counter, or output sizing is invalid. {@link Error}
|
|
||||||
*/
|
|
||||||
export function createCipher(core, opts) {
|
|
||||||
const { allowShortKeys, extendNonceFn, counterLength, counterRight, rounds } = checkOpts({ allowShortKeys: false, counterLength: 8, counterRight: false, rounds: 20 }, opts);
|
|
||||||
if (typeof core !== 'function')
|
|
||||||
throw new Error('core must be a function');
|
|
||||||
anumber(counterLength);
|
|
||||||
anumber(rounds);
|
|
||||||
abool(counterRight);
|
|
||||||
abool(allowShortKeys);
|
|
||||||
return (key, nonce, data, output, counter = 0) => {
|
|
||||||
abytes(key, undefined, 'key');
|
|
||||||
abytes(nonce, undefined, 'nonce');
|
|
||||||
abytes(data, undefined, 'data');
|
|
||||||
const len = data.length;
|
|
||||||
// Raw XorStream APIs return ciphertext/plaintext bytes directly, so caller-provided outputs
|
|
||||||
// must match the logical result length exactly instead of returning an oversized workspace.
|
|
||||||
const hasOutput = output !== undefined;
|
|
||||||
output = getOutput(len, output, false);
|
|
||||||
if (hasOutput)
|
|
||||||
complexOverlapBytes(data, output);
|
|
||||||
anumber(counter);
|
|
||||||
// See MAX_COUNTER policy note above: reject advanced explicit-counter requests before any wrap.
|
|
||||||
if (counter < 0 || counter >= MAX_COUNTER)
|
|
||||||
throw new Error('arx: counter overflow');
|
|
||||||
const toClean = [];
|
|
||||||
// Key & sigma
|
|
||||||
// key=16 -> sigma16, k=key|key
|
|
||||||
// key=32 -> sigma32, k=key
|
|
||||||
let l = key.length;
|
|
||||||
let k;
|
|
||||||
let sigma;
|
|
||||||
if (l === 32) {
|
|
||||||
// Copy caller keys too: big-endian normalization, extended-nonce subkey derivation, and
|
|
||||||
// final clean(...) all mutate or wipe the temporary buffer in place.
|
|
||||||
toClean.push((k = copyBytes(key)));
|
|
||||||
sigma = sigma32_32;
|
|
||||||
}
|
|
||||||
else if (l === 16 && allowShortKeys) {
|
|
||||||
k = new Uint8Array(32);
|
|
||||||
k.set(key);
|
|
||||||
k.set(key, 16);
|
|
||||||
sigma = sigma16_32;
|
|
||||||
toClean.push(k);
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
abytes(key, 32, 'arx key');
|
|
||||||
throw new Error('invalid key size');
|
|
||||||
// throw new Error(`"arx key" expected Uint8Array of length 32, got length=${l}`);
|
|
||||||
}
|
|
||||||
// Nonce
|
|
||||||
// salsa20: 8 (8-byte counter)
|
|
||||||
// chacha20orig: 8 (8-byte counter)
|
|
||||||
// chacha20: 12 (4-byte counter)
|
|
||||||
// xsalsa20: 24 (16 -> hsalsa, 8 -> old nonce)
|
|
||||||
// xchacha20: 24 (16 -> hchacha, 8 -> old nonce)
|
|
||||||
// Copy before taking u32(...) views on misaligned inputs, and on big-endian so later
|
|
||||||
// swap32IfBE(...) never mutates caller nonce bytes in place.
|
|
||||||
if (!isLE || !isAligned32(nonce))
|
|
||||||
toClean.push((nonce = copyBytes(nonce)));
|
|
||||||
let k32 = u32(k);
|
|
||||||
// hsalsa & hchacha: handle extended nonce
|
|
||||||
if (extendNonceFn) {
|
|
||||||
if (nonce.length !== 24)
|
|
||||||
throw new Error('arx: extended nonce must be 24 bytes');
|
|
||||||
const n16 = nonce.subarray(0, 16);
|
|
||||||
if (isLE)
|
|
||||||
extendNonceFn(sigma, k32, u32(n16), k32);
|
|
||||||
else {
|
|
||||||
const sigmaRaw = swap32IfBE(Uint32Array.from(sigma));
|
|
||||||
extendNonceFn(sigmaRaw, k32, u32(n16), k32);
|
|
||||||
clean(sigmaRaw);
|
|
||||||
swap32IfBE(k32);
|
|
||||||
}
|
|
||||||
nonce = nonce.subarray(16);
|
|
||||||
}
|
|
||||||
else if (!isLE)
|
|
||||||
swap32IfBE(k32);
|
|
||||||
// Handle nonce counter
|
|
||||||
const nonceNcLen = 16 - counterLength;
|
|
||||||
if (nonceNcLen !== nonce.length)
|
|
||||||
throw new Error(`arx: nonce must be ${nonceNcLen} or 16 bytes`);
|
|
||||||
// Normalize 64-bit-nonce layouts to the 12-byte core input: ChaCha/XChaCha prefix 4 zero
|
|
||||||
// counter bytes, while Salsa/XSalsa append them after the nonce words.
|
|
||||||
if (nonceNcLen !== 12) {
|
|
||||||
const nc = new Uint8Array(12);
|
|
||||||
nc.set(nonce, counterRight ? 0 : 12 - nonce.length);
|
|
||||||
nonce = nc;
|
|
||||||
toClean.push(nonce);
|
|
||||||
}
|
|
||||||
const n32 = swap32IfBE(u32(nonce));
|
|
||||||
// Ensure temporary key/nonce copies are wiped even if the remaining
|
|
||||||
// runtime guard in runCipher(...) throws on counter overflow.
|
|
||||||
try {
|
|
||||||
runCipher(core, sigma, k32, n32, data, output, counter, rounds);
|
|
||||||
return output;
|
|
||||||
}
|
|
||||||
finally {
|
|
||||||
clean(...toClean);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
}
|
|
||||||
/** Internal class which wraps chacha20 or chacha8 to create CSPRNG. */
|
|
||||||
export class _XorStreamPRG {
|
|
||||||
blockLen;
|
|
||||||
keyLen;
|
|
||||||
nonceLen;
|
|
||||||
state;
|
|
||||||
buf;
|
|
||||||
key;
|
|
||||||
nonce;
|
|
||||||
pos;
|
|
||||||
ctr;
|
|
||||||
cipher;
|
|
||||||
destroyed = false;
|
|
||||||
constructor(cipher, blockLen, keyLen, nonceLen, seed) {
|
|
||||||
this.cipher = cipher;
|
|
||||||
this.blockLen = blockLen;
|
|
||||||
this.keyLen = keyLen;
|
|
||||||
this.nonceLen = nonceLen;
|
|
||||||
this.state = new Uint8Array(this.keyLen + this.nonceLen);
|
|
||||||
this.reseed(seed);
|
|
||||||
this.ctr = 0;
|
|
||||||
this.pos = this.blockLen;
|
|
||||||
this.buf = new Uint8Array(this.blockLen);
|
|
||||||
// Keep a single key||nonce backing buffer so reseed/addEntropy/clean update the live cipher
|
|
||||||
// inputs in place through these subarray views.
|
|
||||||
this.key = this.state.subarray(0, this.keyLen);
|
|
||||||
this.nonce = this.state.subarray(this.keyLen);
|
|
||||||
}
|
|
||||||
reseed(seed) {
|
|
||||||
abytes(seed, undefined, 'seed');
|
|
||||||
if (!seed || seed.length === 0)
|
|
||||||
throw new Error('entropy required');
|
|
||||||
// Mix variable-length entropy cyclically across the whole key||nonce state, then restart the
|
|
||||||
// keystream so buffered leftovers from the previous state are never reused.
|
|
||||||
for (let i = 0; i < seed.length; i++)
|
|
||||||
this.state[i % this.state.length] ^= seed[i];
|
|
||||||
this.ctr = 0;
|
|
||||||
this.pos = this.blockLen;
|
|
||||||
}
|
|
||||||
addEntropy(seed) {
|
|
||||||
if (this.destroyed)
|
|
||||||
throw new Error('cannot use destroyed PRG');
|
|
||||||
// Reject empty entropy before re-keying, otherwise a throwing call would still advance state.
|
|
||||||
abytes(seed, undefined, 'seed');
|
|
||||||
if (seed.length === 0)
|
|
||||||
throw new Error('entropy required');
|
|
||||||
// Re-key from the current stream first, then mix external entropy into the fresh key||nonce
|
|
||||||
// state through reseed() so stale buffered bytes are discarded.
|
|
||||||
this.state.set(this.randomBytes(this.state.length));
|
|
||||||
this.reseed(seed);
|
|
||||||
}
|
|
||||||
randomBytes(len) {
|
|
||||||
if (this.destroyed)
|
|
||||||
throw new Error('cannot use destroyed PRG');
|
|
||||||
anumber(len);
|
|
||||||
if (len === 0)
|
|
||||||
return new Uint8Array(0);
|
|
||||||
const avail = this.pos < this.blockLen ? this.blockLen - this.pos : 0;
|
|
||||||
const blocks = Math.ceil(Math.max(0, len - avail) / this.blockLen);
|
|
||||||
// Preflight overflow so failed reads don't partially consume keystream
|
|
||||||
// and leave the PRG repeating blocks.
|
|
||||||
if (blocks > 0 && this.ctr > MAX_COUNTER - blocks)
|
|
||||||
throw new Error('arx: counter overflow');
|
|
||||||
const out = new Uint8Array(len);
|
|
||||||
let outPos = 0;
|
|
||||||
// `out` starts zero-filled, and `buf.fill(0)` below does the same for leftovers: XOR-stream
|
|
||||||
// ciphers then emit raw keystream bytes directly into those buffers.
|
|
||||||
// Serve buffered leftovers first so split reads stay identical to one larger read.
|
|
||||||
if (this.pos < this.blockLen) {
|
|
||||||
const take = Math.min(len, this.blockLen - this.pos);
|
|
||||||
out.set(this.buf.subarray(this.pos, this.pos + take), 0);
|
|
||||||
this.pos += take;
|
|
||||||
outPos += take;
|
|
||||||
if (outPos === len)
|
|
||||||
return out; // fast path
|
|
||||||
}
|
|
||||||
// Full blocks directly to out
|
|
||||||
const full = Math.floor((len - outPos) / this.blockLen);
|
|
||||||
if (full > 0) {
|
|
||||||
const blockBytes = full * this.blockLen;
|
|
||||||
const b = out.subarray(outPos, outPos + blockBytes);
|
|
||||||
this.cipher(this.key, this.nonce, b, b, this.ctr);
|
|
||||||
this.ctr += full;
|
|
||||||
outPos += blockBytes;
|
|
||||||
}
|
|
||||||
// Save leftovers
|
|
||||||
const left = len - outPos;
|
|
||||||
if (left > 0) {
|
|
||||||
this.buf.fill(0);
|
|
||||||
// NOTE: cipher will handle overflow
|
|
||||||
this.cipher(this.key, this.nonce, this.buf, this.buf, this.ctr++);
|
|
||||||
out.set(this.buf.subarray(0, left), outPos);
|
|
||||||
this.pos = left;
|
|
||||||
}
|
|
||||||
return out;
|
|
||||||
}
|
|
||||||
// Clone seeds the new instance from this stream, so the source PRG advances too.
|
|
||||||
clone() {
|
|
||||||
if (this.destroyed)
|
|
||||||
throw new Error('cannot use destroyed PRG');
|
|
||||||
return new _XorStreamPRG(this.cipher, this.blockLen, this.keyLen, this.nonceLen, this.randomBytes(this.state.length));
|
|
||||||
}
|
|
||||||
// Zeroes the current state, leftover buffer, and marks the instance destroyed.
|
|
||||||
// The instance fails closed: any later randomBytes()/addEntropy()/clone() throws instead
|
|
||||||
// of silently continuing from zero key||nonce state (which would yield predictable output).
|
|
||||||
clean() {
|
|
||||||
this.pos = 0;
|
|
||||||
this.ctr = 0;
|
|
||||||
this.buf.fill(0);
|
|
||||||
this.state.fill(0);
|
|
||||||
this.destroyed = true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
/**
|
|
||||||
* Creates a PRG constructor from a stream cipher.
|
|
||||||
* @param cipher - Stream cipher used to fill output blocks.
|
|
||||||
* @param blockLen - Keystream block length in bytes.
|
|
||||||
* @param keyLen - Internal key length in bytes.
|
|
||||||
* @param nonceLen - Internal nonce length in bytes.
|
|
||||||
* @returns PRG factory for seeded concrete `_XorStreamPRG` instances.
|
|
||||||
* @example
|
|
||||||
* Builds a PRG from XChaCha20 and reads bytes from a randomly seeded instance.
|
|
||||||
* ```ts
|
|
||||||
* import { xchacha20 } from '@noble/ciphers/chacha.js';
|
|
||||||
* import { createPRG } from '@noble/ciphers/_arx.js';
|
|
||||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
|
||||||
* const seed = randomBytes(32);
|
|
||||||
* const init = createPRG(xchacha20, 64, 32, 24);
|
|
||||||
* const prg = init(seed);
|
|
||||||
* prg.randomBytes(8);
|
|
||||||
* ```
|
|
||||||
*/
|
|
||||||
export const createPRG = (cipher, blockLen, keyLen, nonceLen) => {
|
|
||||||
return ((seed = randomBytes(32)) => new _XorStreamPRG(cipher, blockLen, keyLen, nonceLen, seed));
|
|
||||||
};
|
|
||||||
|
|||||||
+3
-317
@@ -1,318 +1,4 @@
|
|||||||
/**
|
// Stub placeholder for noble-ciphers internal _poly1305 module
|
||||||
* Poly1305 ({@link https://cr.yp.to/mac/poly1305-20050329.pdf | PDF},
|
export function poly1305() {
|
||||||
* {@link https://en.wikipedia.org/wiki/Poly1305 | wiki})
|
throw new Error("noble _poly1305 stub: not implemented");
|
||||||
* is a fast and parallel secret-key message-authentication code suitable for
|
|
||||||
* a wide variety of applications. It was standardized in
|
|
||||||
* {@link https://www.rfc-editor.org/rfc/rfc8439 | RFC 8439} and is now used in TLS 1.3.
|
|
||||||
*
|
|
||||||
* Polynomial MACs are not perfect for every situation:
|
|
||||||
* they lack Random Key Robustness: the MAC can be forged, and can't be used in PAKE schemes.
|
|
||||||
* See {@link https://keymaterial.net/2020/09/07/invisible-salamanders-in-aes-gcm-siv/ | the invisible salamanders attack writeup}.
|
|
||||||
* To combat invisible salamanders, `hash(key)` can be included in ciphertext,
|
|
||||||
* however, this would violate ciphertext indistinguishability:
|
|
||||||
* an attacker would know which key was used - so `HKDF(key, i)`
|
|
||||||
* could be used instead.
|
|
||||||
*
|
|
||||||
* Check out the {@link https://cr.yp.to/mac.html | original website}.
|
|
||||||
* Based on public-domain {@link https://github.com/floodyberry/poly1305-donna | poly1305-donna}.
|
|
||||||
* @module
|
|
||||||
*/
|
|
||||||
// prettier-ignore
|
|
||||||
import { abytes, aexists, aoutput, clean, copyBytes, wrapMacConstructor } from "./utils.js";
|
|
||||||
// A simple-loop reference version (`poly1305_small`) lives in
|
|
||||||
// `test/misc/micro-ciphers.ts`, provided for auditability.
|
|
||||||
// Little-endian 2-byte load used by the Poly1305 limb decomposition.
|
|
||||||
function u8to16(a, i) {
|
|
||||||
return (a[i++] & 0xff) | ((a[i++] & 0xff) << 8);
|
|
||||||
}
|
}
|
||||||
/**
|
|
||||||
* Incremental Poly1305 MAC state.
|
|
||||||
* Prefer `poly1305()` for one-shot use.
|
|
||||||
* @param key - 32-byte Poly1305 one-time key.
|
|
||||||
* @example
|
|
||||||
* Feeds one chunk into an incremental Poly1305 state with a fresh one-time key.
|
|
||||||
*
|
|
||||||
* ```ts
|
|
||||||
* import { Poly1305 } from '@noble/ciphers/_poly1305.js';
|
|
||||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
|
||||||
* const key = randomBytes(32);
|
|
||||||
* const mac = new Poly1305(key);
|
|
||||||
* mac.update(new Uint8Array([1, 2, 3]));
|
|
||||||
* mac.digest();
|
|
||||||
* ```
|
|
||||||
*/
|
|
||||||
export class Poly1305 {
|
|
||||||
blockLen = 16;
|
|
||||||
outputLen = 16;
|
|
||||||
buffer = new Uint8Array(16);
|
|
||||||
r = new Uint16Array(10); // Allocating 1 array with .subarray() here is slower than 3
|
|
||||||
h = new Uint16Array(10);
|
|
||||||
pad = new Uint16Array(8);
|
|
||||||
pos = 0;
|
|
||||||
finished = false;
|
|
||||||
destroyed = false;
|
|
||||||
// Can be speed-up using BigUint64Array, at the cost of complexity
|
|
||||||
constructor(key) {
|
|
||||||
key = copyBytes(abytes(key, 32, 'key'));
|
|
||||||
const t0 = u8to16(key, 0);
|
|
||||||
const t1 = u8to16(key, 2);
|
|
||||||
const t2 = u8to16(key, 4);
|
|
||||||
const t3 = u8to16(key, 6);
|
|
||||||
const t4 = u8to16(key, 8);
|
|
||||||
const t5 = u8to16(key, 10);
|
|
||||||
const t6 = u8to16(key, 12);
|
|
||||||
const t7 = u8to16(key, 14);
|
|
||||||
// RFC 8439 §2.5.1 / RFC 7539 §2.5.1 clamp r before multiplication.
|
|
||||||
// These masks unpack that clamped value into 13-bit limbs, while pad
|
|
||||||
// keeps the raw s half for finalize().
|
|
||||||
// {@link https://github.com/floodyberry/poly1305-donna/blob/e6ad6e091d30d7f4ec2d4f978be1fcfcbce72781/poly1305-donna-16.h#L47 | poly1305-donna reference}
|
|
||||||
this.r[0] = t0 & 0x1fff;
|
|
||||||
this.r[1] = ((t0 >>> 13) | (t1 << 3)) & 0x1fff;
|
|
||||||
this.r[2] = ((t1 >>> 10) | (t2 << 6)) & 0x1f03;
|
|
||||||
this.r[3] = ((t2 >>> 7) | (t3 << 9)) & 0x1fff;
|
|
||||||
this.r[4] = ((t3 >>> 4) | (t4 << 12)) & 0x00ff;
|
|
||||||
this.r[5] = (t4 >>> 1) & 0x1ffe;
|
|
||||||
this.r[6] = ((t4 >>> 14) | (t5 << 2)) & 0x1fff;
|
|
||||||
this.r[7] = ((t5 >>> 11) | (t6 << 5)) & 0x1f81;
|
|
||||||
this.r[8] = ((t6 >>> 8) | (t7 << 8)) & 0x1fff;
|
|
||||||
this.r[9] = (t7 >>> 5) & 0x007f;
|
|
||||||
for (let i = 0; i < 8; i++)
|
|
||||||
this.pad[i] = u8to16(key, 16 + 2 * i);
|
|
||||||
}
|
|
||||||
process(data, offset, isLast = false) {
|
|
||||||
// RFC 8439 §2.5 / §2.5.1 and RFC 7539 §2.5 / §2.5.1 add an extra high
|
|
||||||
// bit to every full 16-byte block. The final partial block gets its
|
|
||||||
// explicit `1` byte during digestInto(), so `hibit` stays zero there.
|
|
||||||
const hibit = isLast ? 0 : 1 << 11;
|
|
||||||
const { h, r } = this;
|
|
||||||
const r0 = r[0];
|
|
||||||
const r1 = r[1];
|
|
||||||
const r2 = r[2];
|
|
||||||
const r3 = r[3];
|
|
||||||
const r4 = r[4];
|
|
||||||
const r5 = r[5];
|
|
||||||
const r6 = r[6];
|
|
||||||
const r7 = r[7];
|
|
||||||
const r8 = r[8];
|
|
||||||
const r9 = r[9];
|
|
||||||
const t0 = u8to16(data, offset + 0);
|
|
||||||
const t1 = u8to16(data, offset + 2);
|
|
||||||
const t2 = u8to16(data, offset + 4);
|
|
||||||
const t3 = u8to16(data, offset + 6);
|
|
||||||
const t4 = u8to16(data, offset + 8);
|
|
||||||
const t5 = u8to16(data, offset + 10);
|
|
||||||
const t6 = u8to16(data, offset + 12);
|
|
||||||
const t7 = u8to16(data, offset + 14);
|
|
||||||
let h0 = h[0] + (t0 & 0x1fff);
|
|
||||||
let h1 = h[1] + (((t0 >>> 13) | (t1 << 3)) & 0x1fff);
|
|
||||||
let h2 = h[2] + (((t1 >>> 10) | (t2 << 6)) & 0x1fff);
|
|
||||||
let h3 = h[3] + (((t2 >>> 7) | (t3 << 9)) & 0x1fff);
|
|
||||||
let h4 = h[4] + (((t3 >>> 4) | (t4 << 12)) & 0x1fff);
|
|
||||||
let h5 = h[5] + ((t4 >>> 1) & 0x1fff);
|
|
||||||
let h6 = h[6] + (((t4 >>> 14) | (t5 << 2)) & 0x1fff);
|
|
||||||
let h7 = h[7] + (((t5 >>> 11) | (t6 << 5)) & 0x1fff);
|
|
||||||
let h8 = h[8] + (((t6 >>> 8) | (t7 << 8)) & 0x1fff);
|
|
||||||
let h9 = h[9] + ((t7 >>> 5) | hibit);
|
|
||||||
let c = 0;
|
|
||||||
let d0 = c + h0 * r0 + h1 * (5 * r9) + h2 * (5 * r8) + h3 * (5 * r7) + h4 * (5 * r6);
|
|
||||||
c = d0 >>> 13;
|
|
||||||
d0 &= 0x1fff;
|
|
||||||
d0 += h5 * (5 * r5) + h6 * (5 * r4) + h7 * (5 * r3) + h8 * (5 * r2) + h9 * (5 * r1);
|
|
||||||
c += d0 >>> 13;
|
|
||||||
d0 &= 0x1fff;
|
|
||||||
let d1 = c + h0 * r1 + h1 * r0 + h2 * (5 * r9) + h3 * (5 * r8) + h4 * (5 * r7);
|
|
||||||
c = d1 >>> 13;
|
|
||||||
d1 &= 0x1fff;
|
|
||||||
d1 += h5 * (5 * r6) + h6 * (5 * r5) + h7 * (5 * r4) + h8 * (5 * r3) + h9 * (5 * r2);
|
|
||||||
c += d1 >>> 13;
|
|
||||||
d1 &= 0x1fff;
|
|
||||||
let d2 = c + h0 * r2 + h1 * r1 + h2 * r0 + h3 * (5 * r9) + h4 * (5 * r8);
|
|
||||||
c = d2 >>> 13;
|
|
||||||
d2 &= 0x1fff;
|
|
||||||
d2 += h5 * (5 * r7) + h6 * (5 * r6) + h7 * (5 * r5) + h8 * (5 * r4) + h9 * (5 * r3);
|
|
||||||
c += d2 >>> 13;
|
|
||||||
d2 &= 0x1fff;
|
|
||||||
let d3 = c + h0 * r3 + h1 * r2 + h2 * r1 + h3 * r0 + h4 * (5 * r9);
|
|
||||||
c = d3 >>> 13;
|
|
||||||
d3 &= 0x1fff;
|
|
||||||
d3 += h5 * (5 * r8) + h6 * (5 * r7) + h7 * (5 * r6) + h8 * (5 * r5) + h9 * (5 * r4);
|
|
||||||
c += d3 >>> 13;
|
|
||||||
d3 &= 0x1fff;
|
|
||||||
let d4 = c + h0 * r4 + h1 * r3 + h2 * r2 + h3 * r1 + h4 * r0;
|
|
||||||
c = d4 >>> 13;
|
|
||||||
d4 &= 0x1fff;
|
|
||||||
d4 += h5 * (5 * r9) + h6 * (5 * r8) + h7 * (5 * r7) + h8 * (5 * r6) + h9 * (5 * r5);
|
|
||||||
c += d4 >>> 13;
|
|
||||||
d4 &= 0x1fff;
|
|
||||||
let d5 = c + h0 * r5 + h1 * r4 + h2 * r3 + h3 * r2 + h4 * r1;
|
|
||||||
c = d5 >>> 13;
|
|
||||||
d5 &= 0x1fff;
|
|
||||||
d5 += h5 * r0 + h6 * (5 * r9) + h7 * (5 * r8) + h8 * (5 * r7) + h9 * (5 * r6);
|
|
||||||
c += d5 >>> 13;
|
|
||||||
d5 &= 0x1fff;
|
|
||||||
let d6 = c + h0 * r6 + h1 * r5 + h2 * r4 + h3 * r3 + h4 * r2;
|
|
||||||
c = d6 >>> 13;
|
|
||||||
d6 &= 0x1fff;
|
|
||||||
d6 += h5 * r1 + h6 * r0 + h7 * (5 * r9) + h8 * (5 * r8) + h9 * (5 * r7);
|
|
||||||
c += d6 >>> 13;
|
|
||||||
d6 &= 0x1fff;
|
|
||||||
let d7 = c + h0 * r7 + h1 * r6 + h2 * r5 + h3 * r4 + h4 * r3;
|
|
||||||
c = d7 >>> 13;
|
|
||||||
d7 &= 0x1fff;
|
|
||||||
d7 += h5 * r2 + h6 * r1 + h7 * r0 + h8 * (5 * r9) + h9 * (5 * r8);
|
|
||||||
c += d7 >>> 13;
|
|
||||||
d7 &= 0x1fff;
|
|
||||||
let d8 = c + h0 * r8 + h1 * r7 + h2 * r6 + h3 * r5 + h4 * r4;
|
|
||||||
c = d8 >>> 13;
|
|
||||||
d8 &= 0x1fff;
|
|
||||||
d8 += h5 * r3 + h6 * r2 + h7 * r1 + h8 * r0 + h9 * (5 * r9);
|
|
||||||
c += d8 >>> 13;
|
|
||||||
d8 &= 0x1fff;
|
|
||||||
let d9 = c + h0 * r9 + h1 * r8 + h2 * r7 + h3 * r6 + h4 * r5;
|
|
||||||
c = d9 >>> 13;
|
|
||||||
d9 &= 0x1fff;
|
|
||||||
d9 += h5 * r4 + h6 * r3 + h7 * r2 + h8 * r1 + h9 * r0;
|
|
||||||
c += d9 >>> 13;
|
|
||||||
d9 &= 0x1fff;
|
|
||||||
c = ((c << 2) + c) | 0;
|
|
||||||
c = (c + d0) | 0;
|
|
||||||
d0 = c & 0x1fff;
|
|
||||||
c = c >>> 13;
|
|
||||||
d1 += c;
|
|
||||||
h[0] = d0;
|
|
||||||
h[1] = d1;
|
|
||||||
h[2] = d2;
|
|
||||||
h[3] = d3;
|
|
||||||
h[4] = d4;
|
|
||||||
h[5] = d5;
|
|
||||||
h[6] = d6;
|
|
||||||
h[7] = d7;
|
|
||||||
h[8] = d8;
|
|
||||||
h[9] = d9;
|
|
||||||
}
|
|
||||||
finalize() {
|
|
||||||
const { h, pad } = this;
|
|
||||||
const g = new Uint16Array(10);
|
|
||||||
let c = h[1] >>> 13;
|
|
||||||
h[1] &= 0x1fff;
|
|
||||||
for (let i = 2; i < 10; i++) {
|
|
||||||
h[i] += c;
|
|
||||||
c = h[i] >>> 13;
|
|
||||||
h[i] &= 0x1fff;
|
|
||||||
}
|
|
||||||
h[0] += c * 5;
|
|
||||||
c = h[0] >>> 13;
|
|
||||||
h[0] &= 0x1fff;
|
|
||||||
h[1] += c;
|
|
||||||
c = h[1] >>> 13;
|
|
||||||
h[1] &= 0x1fff;
|
|
||||||
h[2] += c;
|
|
||||||
// RFC 8439 §2.5 / RFC 7539 §2.5 reduce modulo 2^130-5 before repacking
|
|
||||||
// to 16-bit words and adding the raw s half.
|
|
||||||
g[0] = h[0] + 5;
|
|
||||||
c = g[0] >>> 13;
|
|
||||||
g[0] &= 0x1fff;
|
|
||||||
for (let i = 1; i < 10; i++) {
|
|
||||||
g[i] = h[i] + c;
|
|
||||||
c = g[i] >>> 13;
|
|
||||||
g[i] &= 0x1fff;
|
|
||||||
}
|
|
||||||
g[9] -= 1 << 13;
|
|
||||||
let mask = (c ^ 1) - 1;
|
|
||||||
for (let i = 0; i < 10; i++)
|
|
||||||
g[i] &= mask;
|
|
||||||
mask = ~mask;
|
|
||||||
for (let i = 0; i < 10; i++)
|
|
||||||
h[i] = (h[i] & mask) | g[i];
|
|
||||||
h[0] = (h[0] | (h[1] << 13)) & 0xffff;
|
|
||||||
h[1] = ((h[1] >>> 3) | (h[2] << 10)) & 0xffff;
|
|
||||||
h[2] = ((h[2] >>> 6) | (h[3] << 7)) & 0xffff;
|
|
||||||
h[3] = ((h[3] >>> 9) | (h[4] << 4)) & 0xffff;
|
|
||||||
h[4] = ((h[4] >>> 12) | (h[5] << 1) | (h[6] << 14)) & 0xffff;
|
|
||||||
h[5] = ((h[6] >>> 2) | (h[7] << 11)) & 0xffff;
|
|
||||||
h[6] = ((h[7] >>> 5) | (h[8] << 8)) & 0xffff;
|
|
||||||
h[7] = ((h[8] >>> 8) | (h[9] << 5)) & 0xffff;
|
|
||||||
let f = h[0] + pad[0];
|
|
||||||
h[0] = f & 0xffff;
|
|
||||||
for (let i = 1; i < 8; i++) {
|
|
||||||
f = (((h[i] + pad[i]) | 0) + (f >>> 16)) | 0;
|
|
||||||
h[i] = f & 0xffff;
|
|
||||||
}
|
|
||||||
clean(g);
|
|
||||||
}
|
|
||||||
update(data) {
|
|
||||||
aexists(this);
|
|
||||||
abytes(data);
|
|
||||||
data = copyBytes(data);
|
|
||||||
const { buffer, blockLen } = this;
|
|
||||||
const len = data.length;
|
|
||||||
for (let pos = 0; pos < len;) {
|
|
||||||
const take = Math.min(blockLen - this.pos, len - pos);
|
|
||||||
// Fast path: we have at least one block in input
|
|
||||||
if (take === blockLen) {
|
|
||||||
for (; blockLen <= len - pos; pos += blockLen)
|
|
||||||
this.process(data, pos);
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
buffer.set(data.subarray(pos, pos + take), this.pos);
|
|
||||||
this.pos += take;
|
|
||||||
pos += take;
|
|
||||||
if (this.pos === blockLen) {
|
|
||||||
this.process(buffer, 0, false);
|
|
||||||
this.pos = 0;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return this;
|
|
||||||
}
|
|
||||||
destroy() {
|
|
||||||
// `aexists(this)` guards update/digest paths, so destroy must mark the instance unusable too.
|
|
||||||
this.destroyed = true;
|
|
||||||
clean(this.h, this.r, this.buffer, this.pad);
|
|
||||||
}
|
|
||||||
digestInto(out) {
|
|
||||||
aexists(this);
|
|
||||||
aoutput(out, this);
|
|
||||||
this.finished = true;
|
|
||||||
const { buffer, h } = this;
|
|
||||||
let { pos } = this;
|
|
||||||
if (pos) {
|
|
||||||
// RFC 8439 §2.5 / RFC 7539 §2.5: the final short block appends a
|
|
||||||
// single `0x01` byte and zero-fills the remaining bytes before the
|
|
||||||
// last multiplication step.
|
|
||||||
buffer[pos++] = 1;
|
|
||||||
for (; pos < 16; pos++)
|
|
||||||
buffer[pos] = 0;
|
|
||||||
this.process(buffer, 0, true);
|
|
||||||
}
|
|
||||||
this.finalize();
|
|
||||||
let opos = 0;
|
|
||||||
for (let i = 0; i < 8; i++) {
|
|
||||||
out[opos++] = h[i] >>> 0;
|
|
||||||
out[opos++] = h[i] >>> 8;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
digest() {
|
|
||||||
const { buffer, outputLen } = this;
|
|
||||||
this.digestInto(buffer);
|
|
||||||
// Copy out before destroy() zeroes the internal buffer.
|
|
||||||
const res = buffer.slice(0, outputLen);
|
|
||||||
this.destroy();
|
|
||||||
return res;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
/**
|
|
||||||
* Poly1305 MAC from RFC 8439.
|
|
||||||
* @param msg - Message bytes to authenticate.
|
|
||||||
* @param key - 32-byte Poly1305 one-time key.
|
|
||||||
* @returns 16-byte authentication tag.
|
|
||||||
* @example
|
|
||||||
* Authenticates one message with a one-shot Poly1305 call and a fresh key.
|
|
||||||
*
|
|
||||||
* ```ts
|
|
||||||
* import { poly1305 } from '@noble/ciphers/_poly1305.js';
|
|
||||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
|
||||||
* const key = randomBytes(32);
|
|
||||||
* poly1305(new Uint8Array(), key);
|
|
||||||
* ```
|
|
||||||
*/
|
|
||||||
export const poly1305 = /* @__PURE__ */ wrapMacConstructor(32, (key) => new Poly1305(key));
|
|
||||||
|
|||||||
+3
-459
@@ -1,460 +1,4 @@
|
|||||||
/**
|
// Stub placeholder for noble-ciphers chacha module
|
||||||
* ChaCha stream cipher, released
|
export function chacha20(poly1305) {
|
||||||
* in 2008. Developed after Salsa20, ChaCha aims to increase diffusion per round.
|
throw new Error("noble chacha stub: not implemented");
|
||||||
* It was standardized in
|
|
||||||
* {@link https://www.rfc-editor.org/rfc/rfc8439 | RFC 8439} and
|
|
||||||
* is now used in TLS 1.3.
|
|
||||||
*
|
|
||||||
* {@link https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha | XChaCha20}
|
|
||||||
* extended-nonce variant is also provided. Similar to XSalsa, it's safe to use with
|
|
||||||
* randomly-generated nonces.
|
|
||||||
*
|
|
||||||
* Check out
|
|
||||||
* {@link http://cr.yp.to/chacha/chacha-20080128.pdf | PDF},
|
|
||||||
* {@link https://en.wikipedia.org/wiki/Salsa20 | wiki}, and
|
|
||||||
* {@link https://cr.yp.to/chacha.html | website}.
|
|
||||||
*
|
|
||||||
* @module
|
|
||||||
*/
|
|
||||||
import { createCipher, createPRG, rotl } from "./_arx.js";
|
|
||||||
import { poly1305 } from "./_poly1305.js";
|
|
||||||
import { abytes, clean, equalBytes, getOutput, isLE, swap32IfBE, u64Lengths, wrapCipher, } from "./utils.js";
|
|
||||||
/**
|
|
||||||
* ChaCha core function. Uses an unrolled loop (chachaCore, hchacha) - 4x
|
|
||||||
* faster than a simple loop, but larger & harder to read. A simple-loop
|
|
||||||
* reference version lives in `test/misc/micro-ciphers.ts`;
|
|
||||||
* `test/arx.test.ts` keeps the two aligned.
|
|
||||||
* The specific implementation is selected in `createCipher` below.
|
|
||||||
*/
|
|
||||||
/** RFC 8439 §2.3 block core for `state = constants | key | counter | nonce`. */
|
|
||||||
// prettier-ignore
|
|
||||||
function chachaCore(s, k, n, out, cnt, rounds = 20) {
|
|
||||||
let y00 = s[0], y01 = s[1], y02 = s[2], y03 = s[3], // "expa" "nd 3" "2-by" "te k"
|
|
||||||
y04 = k[0], y05 = k[1], y06 = k[2], y07 = k[3], // Key Key Key Key
|
|
||||||
y08 = k[4], y09 = k[5], y10 = k[6], y11 = k[7], // Key Key Key Key
|
|
||||||
y12 = cnt, y13 = n[0], y14 = n[1], y15 = n[2]; // Counter Nonce Nonce Nonce
|
|
||||||
// Save state to temporary variables
|
|
||||||
let x00 = y00, x01 = y01, x02 = y02, x03 = y03, x04 = y04, x05 = y05, x06 = y06, x07 = y07, x08 = y08, x09 = y09, x10 = y10, x11 = y11, x12 = y12, x13 = y13, x14 = y14, x15 = y15;
|
|
||||||
for (let r = 0; r < rounds; r += 2) {
|
|
||||||
x00 = (x00 + x04) | 0;
|
|
||||||
x12 = rotl(x12 ^ x00, 16);
|
|
||||||
x08 = (x08 + x12) | 0;
|
|
||||||
x04 = rotl(x04 ^ x08, 12);
|
|
||||||
x00 = (x00 + x04) | 0;
|
|
||||||
x12 = rotl(x12 ^ x00, 8);
|
|
||||||
x08 = (x08 + x12) | 0;
|
|
||||||
x04 = rotl(x04 ^ x08, 7);
|
|
||||||
x01 = (x01 + x05) | 0;
|
|
||||||
x13 = rotl(x13 ^ x01, 16);
|
|
||||||
x09 = (x09 + x13) | 0;
|
|
||||||
x05 = rotl(x05 ^ x09, 12);
|
|
||||||
x01 = (x01 + x05) | 0;
|
|
||||||
x13 = rotl(x13 ^ x01, 8);
|
|
||||||
x09 = (x09 + x13) | 0;
|
|
||||||
x05 = rotl(x05 ^ x09, 7);
|
|
||||||
x02 = (x02 + x06) | 0;
|
|
||||||
x14 = rotl(x14 ^ x02, 16);
|
|
||||||
x10 = (x10 + x14) | 0;
|
|
||||||
x06 = rotl(x06 ^ x10, 12);
|
|
||||||
x02 = (x02 + x06) | 0;
|
|
||||||
x14 = rotl(x14 ^ x02, 8);
|
|
||||||
x10 = (x10 + x14) | 0;
|
|
||||||
x06 = rotl(x06 ^ x10, 7);
|
|
||||||
x03 = (x03 + x07) | 0;
|
|
||||||
x15 = rotl(x15 ^ x03, 16);
|
|
||||||
x11 = (x11 + x15) | 0;
|
|
||||||
x07 = rotl(x07 ^ x11, 12);
|
|
||||||
x03 = (x03 + x07) | 0;
|
|
||||||
x15 = rotl(x15 ^ x03, 8);
|
|
||||||
x11 = (x11 + x15) | 0;
|
|
||||||
x07 = rotl(x07 ^ x11, 7);
|
|
||||||
x00 = (x00 + x05) | 0;
|
|
||||||
x15 = rotl(x15 ^ x00, 16);
|
|
||||||
x10 = (x10 + x15) | 0;
|
|
||||||
x05 = rotl(x05 ^ x10, 12);
|
|
||||||
x00 = (x00 + x05) | 0;
|
|
||||||
x15 = rotl(x15 ^ x00, 8);
|
|
||||||
x10 = (x10 + x15) | 0;
|
|
||||||
x05 = rotl(x05 ^ x10, 7);
|
|
||||||
x01 = (x01 + x06) | 0;
|
|
||||||
x12 = rotl(x12 ^ x01, 16);
|
|
||||||
x11 = (x11 + x12) | 0;
|
|
||||||
x06 = rotl(x06 ^ x11, 12);
|
|
||||||
x01 = (x01 + x06) | 0;
|
|
||||||
x12 = rotl(x12 ^ x01, 8);
|
|
||||||
x11 = (x11 + x12) | 0;
|
|
||||||
x06 = rotl(x06 ^ x11, 7);
|
|
||||||
x02 = (x02 + x07) | 0;
|
|
||||||
x13 = rotl(x13 ^ x02, 16);
|
|
||||||
x08 = (x08 + x13) | 0;
|
|
||||||
x07 = rotl(x07 ^ x08, 12);
|
|
||||||
x02 = (x02 + x07) | 0;
|
|
||||||
x13 = rotl(x13 ^ x02, 8);
|
|
||||||
x08 = (x08 + x13) | 0;
|
|
||||||
x07 = rotl(x07 ^ x08, 7);
|
|
||||||
x03 = (x03 + x04) | 0;
|
|
||||||
x14 = rotl(x14 ^ x03, 16);
|
|
||||||
x09 = (x09 + x14) | 0;
|
|
||||||
x04 = rotl(x04 ^ x09, 12);
|
|
||||||
x03 = (x03 + x04) | 0;
|
|
||||||
x14 = rotl(x14 ^ x03, 8);
|
|
||||||
x09 = (x09 + x14) | 0;
|
|
||||||
x04 = rotl(x04 ^ x09, 7);
|
|
||||||
}
|
}
|
||||||
// RFC 8439 §2.3 / §2.3.1: add the original state words back in state order.
|
|
||||||
let oi = 0;
|
|
||||||
out[oi++] = (y00 + x00) | 0;
|
|
||||||
out[oi++] = (y01 + x01) | 0;
|
|
||||||
out[oi++] = (y02 + x02) | 0;
|
|
||||||
out[oi++] = (y03 + x03) | 0;
|
|
||||||
out[oi++] = (y04 + x04) | 0;
|
|
||||||
out[oi++] = (y05 + x05) | 0;
|
|
||||||
out[oi++] = (y06 + x06) | 0;
|
|
||||||
out[oi++] = (y07 + x07) | 0;
|
|
||||||
out[oi++] = (y08 + x08) | 0;
|
|
||||||
out[oi++] = (y09 + x09) | 0;
|
|
||||||
out[oi++] = (y10 + x10) | 0;
|
|
||||||
out[oi++] = (y11 + x11) | 0;
|
|
||||||
out[oi++] = (y12 + x12) | 0;
|
|
||||||
out[oi++] = (y13 + x13) | 0;
|
|
||||||
out[oi++] = (y14 + x14) | 0;
|
|
||||||
out[oi++] = (y15 + x15) | 0;
|
|
||||||
}
|
|
||||||
/**
|
|
||||||
* hchacha hashes key and nonce into key' and nonce' for xchacha20.
|
|
||||||
* Algorithmically identical to `hchacha_small` from `test/misc/micro-ciphers.ts`,
|
|
||||||
* but this exported path normalizes word order on big-endian hosts.
|
|
||||||
* Reuses `chachaCore` and subtracts its feed-forward, keeping the hot per-block
|
|
||||||
* path untouched.
|
|
||||||
* @param s - Sigma constants as 32-bit words.
|
|
||||||
* @param k - Key words.
|
|
||||||
* @param i - Nonce-prefix words.
|
|
||||||
* @param out - Output buffer for the derived subkey.
|
|
||||||
* @example
|
|
||||||
* Derives the XChaCha subkey from sigma, key, and nonce-prefix words.
|
|
||||||
*
|
|
||||||
* ```ts
|
|
||||||
* const sigma = new Uint32Array(4);
|
|
||||||
* const key = new Uint32Array(8);
|
|
||||||
* const nonce = new Uint32Array(4);
|
|
||||||
* const out = new Uint32Array(8);
|
|
||||||
* hchacha(sigma, key, nonce, out);
|
|
||||||
* ```
|
|
||||||
*/
|
|
||||||
// prettier-ignore
|
|
||||||
export function hchacha(s, k, i, out) {
|
|
||||||
// Runs the shared chachaCore permutation, then subtracts the RFC 8439 feed-forward
|
|
||||||
// it applies, recovering the raw permutation words hchacha needs.
|
|
||||||
// LE hosts read the caller arrays in place (no copies); BE hosts get
|
|
||||||
// byte-swapped scratch copies, wiped before returning.
|
|
||||||
const s2 = isLE ? s : swap32IfBE(s.slice(0, 4));
|
|
||||||
const k2 = isLE ? k : swap32IfBE(k.slice(0, 8));
|
|
||||||
const i2 = isLE ? i : swap32IfBE(i.slice(0, 4));
|
|
||||||
const t = new Uint32Array(16);
|
|
||||||
chachaCore(s2, k2, i2.subarray(1), t, i2[0]);
|
|
||||||
let oi = 0;
|
|
||||||
out[oi++] = (t[0] - s2[0]) | 0;
|
|
||||||
out[oi++] = (t[1] - s2[1]) | 0;
|
|
||||||
out[oi++] = (t[2] - s2[2]) | 0;
|
|
||||||
out[oi++] = (t[3] - s2[3]) | 0;
|
|
||||||
out[oi++] = (t[12] - i2[0]) | 0;
|
|
||||||
out[oi++] = (t[13] - i2[1]) | 0;
|
|
||||||
out[oi++] = (t[14] - i2[2]) | 0;
|
|
||||||
out[oi++] = (t[15] - i2[3]) | 0;
|
|
||||||
swap32IfBE(out);
|
|
||||||
if (!isLE)
|
|
||||||
clean(s2, k2, i2);
|
|
||||||
clean(t);
|
|
||||||
}
|
|
||||||
/**
|
|
||||||
* Original, non-RFC chacha20 from DJB. 8-byte nonce, 8-byte counter.
|
|
||||||
* The nonce/counter layout still reserves 8 counter bytes internally, but the shared public
|
|
||||||
* `counter` argument follows noble's strict non-wrapping 32-bit policy. See `src/_arx.ts`
|
|
||||||
* near `MAX_COUNTER` for the full counter-policy rationale.
|
|
||||||
* @param key - 16-byte or 32-byte key.
|
|
||||||
* @param nonce - 8-byte nonce.
|
|
||||||
* @param data - Input bytes to xor with the keystream.
|
|
||||||
* @param output - Optional destination buffer.
|
|
||||||
* @param counter - Initial block counter.
|
|
||||||
* @returns Encrypted or decrypted bytes.
|
|
||||||
* @example
|
|
||||||
* Encrypts bytes with the original 8-byte-nonce ChaCha variant and a fresh key/nonce.
|
|
||||||
*
|
|
||||||
* ```ts
|
|
||||||
* import { chacha20orig } from '@noble/ciphers/chacha.js';
|
|
||||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
|
||||||
* const key = randomBytes(32);
|
|
||||||
* const nonce = randomBytes(8);
|
|
||||||
* chacha20orig(key, nonce, new Uint8Array(4));
|
|
||||||
* ```
|
|
||||||
*/
|
|
||||||
export const chacha20orig = /* @__PURE__ */ createCipher(chachaCore, {
|
|
||||||
counterRight: false,
|
|
||||||
counterLength: 8,
|
|
||||||
allowShortKeys: true,
|
|
||||||
});
|
|
||||||
/**
|
|
||||||
* ChaCha stream cipher. Conforms to RFC 8439 (IETF, TLS). 12-byte nonce, 4-byte counter.
|
|
||||||
* With smaller nonce, it's not safe to make it random (CSPRNG), due to collision chance.
|
|
||||||
* @param key - 32-byte key.
|
|
||||||
* @param nonce - 12-byte nonce.
|
|
||||||
* @param data - Input bytes to xor with the keystream.
|
|
||||||
* @param output - Optional destination buffer.
|
|
||||||
* @param counter - Initial block counter.
|
|
||||||
* @returns Encrypted or decrypted bytes.
|
|
||||||
* @example
|
|
||||||
* Encrypts bytes with the RFC 8439 ChaCha20 stream cipher and a fresh key/nonce.
|
|
||||||
*
|
|
||||||
* ```ts
|
|
||||||
* import { chacha20 } from '@noble/ciphers/chacha.js';
|
|
||||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
|
||||||
* const key = randomBytes(32);
|
|
||||||
* const nonce = randomBytes(12);
|
|
||||||
* chacha20(key, nonce, new Uint8Array(4));
|
|
||||||
* ```
|
|
||||||
*/
|
|
||||||
export const chacha20 = /* @__PURE__ */ createCipher(chachaCore, {
|
|
||||||
counterRight: false,
|
|
||||||
counterLength: 4,
|
|
||||||
allowShortKeys: false,
|
|
||||||
});
|
|
||||||
/**
|
|
||||||
* XChaCha eXtended-nonce ChaCha. With 24-byte nonce, it's safe to make it random (CSPRNG).
|
|
||||||
* See {@link https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha | the IRTF draft}.
|
|
||||||
* The nonce/counter layout still reserves 8 counter bytes internally, but the shared public
|
|
||||||
* `counter` argument follows noble's strict non-wrapping 32-bit policy. See `src/_arx.ts`
|
|
||||||
* near `MAX_COUNTER` for the full counter-policy rationale.
|
|
||||||
* @param key - 32-byte key.
|
|
||||||
* @param nonce - 24-byte extended nonce.
|
|
||||||
* @param data - Input bytes to xor with the keystream.
|
|
||||||
* @param output - Optional destination buffer.
|
|
||||||
* @param counter - Initial block counter.
|
|
||||||
* @returns Encrypted or decrypted bytes.
|
|
||||||
* @example
|
|
||||||
* Encrypts bytes with XChaCha20 using a fresh key and random 24-byte nonce.
|
|
||||||
*
|
|
||||||
* ```ts
|
|
||||||
* import { xchacha20 } from '@noble/ciphers/chacha.js';
|
|
||||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
|
||||||
* const key = randomBytes(32);
|
|
||||||
* const nonce = randomBytes(24);
|
|
||||||
* xchacha20(key, nonce, new Uint8Array(4));
|
|
||||||
* ```
|
|
||||||
*/
|
|
||||||
export const xchacha20 = /* @__PURE__ */ createCipher(chachaCore, {
|
|
||||||
counterRight: false,
|
|
||||||
counterLength: 8,
|
|
||||||
extendNonceFn: hchacha,
|
|
||||||
allowShortKeys: false,
|
|
||||||
});
|
|
||||||
/**
|
|
||||||
* Reduced 8-round chacha, described in original paper.
|
|
||||||
* @param key - 32-byte key.
|
|
||||||
* @param nonce - 12-byte nonce.
|
|
||||||
* @param data - Input bytes to xor with the keystream.
|
|
||||||
* @param output - Optional destination buffer.
|
|
||||||
* @param counter - Initial block counter.
|
|
||||||
* @returns Encrypted or decrypted bytes.
|
|
||||||
* @example
|
|
||||||
* Uses the reduced 8-round variant for non-critical workloads with a fresh key/nonce.
|
|
||||||
*
|
|
||||||
* ```ts
|
|
||||||
* import { chacha8 } from '@noble/ciphers/chacha.js';
|
|
||||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
|
||||||
* const key = randomBytes(32);
|
|
||||||
* const nonce = randomBytes(12);
|
|
||||||
* chacha8(key, nonce, new Uint8Array(4));
|
|
||||||
* ```
|
|
||||||
*/
|
|
||||||
export const chacha8 = /* @__PURE__ */ createCipher(chachaCore, {
|
|
||||||
counterRight: false,
|
|
||||||
counterLength: 4,
|
|
||||||
rounds: 8,
|
|
||||||
});
|
|
||||||
/**
|
|
||||||
* Reduced 12-round chacha, described in original paper.
|
|
||||||
* @param key - 32-byte key.
|
|
||||||
* @param nonce - 12-byte nonce.
|
|
||||||
* @param data - Input bytes to xor with the keystream.
|
|
||||||
* @param output - Optional destination buffer.
|
|
||||||
* @param counter - Initial block counter.
|
|
||||||
* @returns Encrypted or decrypted bytes.
|
|
||||||
* @example
|
|
||||||
* Uses the reduced 12-round variant for non-critical workloads with a fresh key/nonce.
|
|
||||||
*
|
|
||||||
* ```ts
|
|
||||||
* import { chacha12 } from '@noble/ciphers/chacha.js';
|
|
||||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
|
||||||
* const key = randomBytes(32);
|
|
||||||
* const nonce = randomBytes(12);
|
|
||||||
* chacha12(key, nonce, new Uint8Array(4));
|
|
||||||
* ```
|
|
||||||
*/
|
|
||||||
export const chacha12 = /* @__PURE__ */ createCipher(chachaCore, {
|
|
||||||
counterRight: false,
|
|
||||||
counterLength: 4,
|
|
||||||
rounds: 12,
|
|
||||||
});
|
|
||||||
// Test-only hook: exposes the unrolled production core so tests can compare it
|
|
||||||
// with the simple/reference core from `test/misc/micro-ciphers.ts`.
|
|
||||||
export const __TESTS = /* @__PURE__ */ Object.freeze({ chachaCore });
|
|
||||||
// RFC 8439 §2.8.1 pad16(x): shared zero block for AAD/ciphertext padding.
|
|
||||||
const ZEROS16 = /* @__PURE__ */ new Uint8Array(16);
|
|
||||||
// RFC 8439 §2.8 / §2.8.1: aligned inputs add nothing, otherwise append 16-(len%16) zero bytes.
|
|
||||||
const updatePadded = (h, msg) => {
|
|
||||||
h.update(msg);
|
|
||||||
const leftover = msg.length % 16;
|
|
||||||
if (leftover)
|
|
||||||
h.update(ZEROS16.subarray(leftover));
|
|
||||||
};
|
|
||||||
// RFC 8439 §2.6.1 poly1305_key_gen returns `block[0..31]`, so AEAD key
|
|
||||||
// generation only needs 32 zero bytes.
|
|
||||||
const ZEROS32 = /* @__PURE__ */ new Uint8Array(32);
|
|
||||||
function computeTag(fn, key, nonce, ciphertext, AAD) {
|
|
||||||
if (AAD !== undefined)
|
|
||||||
abytes(AAD, undefined, 'AAD');
|
|
||||||
// RFC 8439 §2.6 / §2.8: derive the Poly1305 one-time key from counter 0,
|
|
||||||
// then MAC AAD || pad16(AAD) || ciphertext || pad16(ciphertext) || len(AAD) || len(ciphertext).
|
|
||||||
const authKey = fn(key, nonce, ZEROS32);
|
|
||||||
const lengths = u64Lengths(ciphertext.length, AAD ? AAD.length : 0, true);
|
|
||||||
// Methods below can be replaced with
|
|
||||||
// `return poly1305_computeTag_small(authKey, lengths, ciphertext, AAD)`
|
|
||||||
// from `test/misc/micro-ciphers.ts`.
|
|
||||||
const h = poly1305.create(authKey);
|
|
||||||
if (AAD)
|
|
||||||
updatePadded(h, AAD);
|
|
||||||
updatePadded(h, ciphertext);
|
|
||||||
h.update(lengths);
|
|
||||||
const res = h.digest();
|
|
||||||
clean(authKey, lengths);
|
|
||||||
return res;
|
|
||||||
}
|
|
||||||
/**
|
|
||||||
* AEAD algorithm from RFC 8439.
|
|
||||||
* Salsa20 and chacha (RFC 8439) use poly1305 differently.
|
|
||||||
* We could have composed them, but it's hard because of authKey:
|
|
||||||
* In salsa20, authKey changes position in salsa stream.
|
|
||||||
* In chacha, authKey can't be computed inside computeTag, it modifies the counter.
|
|
||||||
*/
|
|
||||||
export const _poly1305_aead = (xorStream) => (key, nonce, AAD) => {
|
|
||||||
// This borrows caller key/nonce/AAD buffers by reference; mutating them after construction
|
|
||||||
// changes future encrypt/decrypt results.
|
|
||||||
const tagLength = 16;
|
|
||||||
return {
|
|
||||||
encrypt(plaintext, output) {
|
|
||||||
const plength = plaintext.length;
|
|
||||||
output = getOutput(plength + tagLength, output, false);
|
|
||||||
output.set(plaintext);
|
|
||||||
const oPlain = output.subarray(0, -tagLength);
|
|
||||||
// RFC 8439 §2.8: payload encryption starts at counter 1 because counter 0 produced the OTK.
|
|
||||||
xorStream(key, nonce, oPlain, oPlain, 1);
|
|
||||||
const tag = computeTag(xorStream, key, nonce, oPlain, AAD);
|
|
||||||
output.set(tag, plength); // append tag
|
|
||||||
clean(tag);
|
|
||||||
return output;
|
|
||||||
},
|
|
||||||
decrypt(ciphertext, output) {
|
|
||||||
output = getOutput(ciphertext.length - tagLength, output, false);
|
|
||||||
const data = ciphertext.subarray(0, -tagLength);
|
|
||||||
const passedTag = ciphertext.subarray(-tagLength);
|
|
||||||
const tag = computeTag(xorStream, key, nonce, data, AAD);
|
|
||||||
// RFC 8439 §2.8 / §4: authenticate ciphertext before decrypting it, and compare tags with
|
|
||||||
// the constant-time equalBytes() helper rather than decrypting speculative plaintext first.
|
|
||||||
if (!equalBytes(passedTag, tag)) {
|
|
||||||
clean(tag);
|
|
||||||
throw new Error('invalid tag');
|
|
||||||
}
|
|
||||||
output.set(ciphertext.subarray(0, -tagLength));
|
|
||||||
// Actual decryption
|
|
||||||
xorStream(key, nonce, output, output, 1); // start stream with i=1
|
|
||||||
clean(tag);
|
|
||||||
return output;
|
|
||||||
},
|
|
||||||
};
|
|
||||||
};
|
|
||||||
/**
|
|
||||||
* ChaCha20-Poly1305 from RFC 8439.
|
|
||||||
*
|
|
||||||
* Unsafe to use random nonces under the same key, due to collision chance.
|
|
||||||
* Prefer XChaCha instead.
|
|
||||||
* @param key - 32-byte key.
|
|
||||||
* @param nonce - 12-byte nonce.
|
|
||||||
* @param AAD - Additional authenticated data.
|
|
||||||
* @returns AEAD cipher instance.
|
|
||||||
* @example
|
|
||||||
* Encrypts and authenticates plaintext with a fresh key and nonce.
|
|
||||||
*
|
|
||||||
* ```ts
|
|
||||||
* import { chacha20poly1305 } from '@noble/ciphers/chacha.js';
|
|
||||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
|
||||||
* const key = randomBytes(32);
|
|
||||||
* const nonce = randomBytes(12);
|
|
||||||
* const aad = new TextEncoder().encode('session metadata');
|
|
||||||
* const cipher = chacha20poly1305(key, nonce, aad);
|
|
||||||
* cipher.encrypt(new Uint8Array([1, 2, 3]));
|
|
||||||
* ```
|
|
||||||
*/
|
|
||||||
export const chacha20poly1305 = /* @__PURE__ */ wrapCipher({ blockSize: 64, nonceLength: 12, tagLength: 16, withAAD: true },
|
|
||||||
/* @__PURE__ */ _poly1305_aead(chacha20));
|
|
||||||
/**
|
|
||||||
* XChaCha20-Poly1305 extended-nonce chacha.
|
|
||||||
*
|
|
||||||
* Can be safely used with random nonces (CSPRNG).
|
|
||||||
* See {@link https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha | the IRTF draft}.
|
|
||||||
* @param key - 32-byte key.
|
|
||||||
* @param nonce - 24-byte nonce.
|
|
||||||
* @param AAD - Additional authenticated data.
|
|
||||||
* @returns AEAD cipher instance.
|
|
||||||
* @example
|
|
||||||
* Encrypts and authenticates plaintext with a fresh key and random 24-byte nonce.
|
|
||||||
*
|
|
||||||
* ```ts
|
|
||||||
* import { xchacha20poly1305 } from '@noble/ciphers/chacha.js';
|
|
||||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
|
||||||
* const key = randomBytes(32);
|
|
||||||
* const nonce = randomBytes(24);
|
|
||||||
* const aad = new TextEncoder().encode('session metadata');
|
|
||||||
* const cipher = xchacha20poly1305(key, nonce, aad);
|
|
||||||
* cipher.encrypt(new Uint8Array([1, 2, 3]));
|
|
||||||
* ```
|
|
||||||
*/
|
|
||||||
export const xchacha20poly1305 = /* @__PURE__ */ wrapCipher({ blockSize: 64, nonceLength: 24, tagLength: 16, withAAD: true },
|
|
||||||
/* @__PURE__ */ _poly1305_aead(xchacha20));
|
|
||||||
/**
|
|
||||||
* Chacha20 CSPRNG (cryptographically secure pseudorandom number generator).
|
|
||||||
* It's best to limit usage to non-production, non-critical cases: for example, test-only.
|
|
||||||
* Compatible with libtomcrypt. It does not have a specification, so unclear how secure it is.
|
|
||||||
* @param seed - Optional seed bytes mixed into the internal `key || nonce` state. When omitted,
|
|
||||||
* only 32 random bytes are mixed into the 40-byte state.
|
|
||||||
* @returns Seeded concrete `_XorStreamPRG` instance, including `clone()`.
|
|
||||||
* @example
|
|
||||||
* Seeds the test-only ChaCha20 DRBG from fresh entropy.
|
|
||||||
*
|
|
||||||
* ```ts
|
|
||||||
* import { rngChacha20 } from '@noble/ciphers/chacha.js';
|
|
||||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
|
||||||
* const seed = randomBytes(32);
|
|
||||||
* const prg = rngChacha20(seed);
|
|
||||||
* prg.randomBytes(8);
|
|
||||||
* ```
|
|
||||||
*/
|
|
||||||
export const rngChacha20 = /* @__PURE__ */ createPRG(chacha20orig, 64, 32, 8);
|
|
||||||
/**
|
|
||||||
* Chacha20/8 CSPRNG (cryptographically secure pseudorandom number generator).
|
|
||||||
* It's best to limit usage to non-production, non-critical cases: for example, test-only.
|
|
||||||
* Faster than `rngChacha20`.
|
|
||||||
* @param seed - Optional seed bytes mixed into the internal `key || nonce` state. When omitted,
|
|
||||||
* only 32 random bytes are mixed into the 44-byte state.
|
|
||||||
* @returns Seeded concrete `_XorStreamPRG` instance, including `clone()`.
|
|
||||||
* @example
|
|
||||||
* Seeds the faster test-only ChaCha8 DRBG from fresh entropy.
|
|
||||||
*
|
|
||||||
* ```ts
|
|
||||||
* import { rngChacha8 } from '@noble/ciphers/chacha.js';
|
|
||||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
|
||||||
* const seed = randomBytes(32);
|
|
||||||
* const prg = rngChacha8(seed);
|
|
||||||
* prg.randomBytes(8);
|
|
||||||
* ```
|
|
||||||
*/
|
|
||||||
export const rngChacha8 = /* @__PURE__ */ createPRG(chacha8, 64, 32, 12);
|
|
||||||
|
|||||||
+5
-892
@@ -1,896 +1,9 @@
|
|||||||
/**
|
// Stub placeholder for noble-ciphers utils module
|
||||||
* Utilities for hex, bytes, CSPRNG.
|
|
||||||
* @module
|
|
||||||
*/
|
|
||||||
/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */
|
|
||||||
export function aarray(item, title, inner = () => { }) {
|
|
||||||
if (!Array.isArray(item))
|
|
||||||
throw new TypeError(`"${title}" expected array, got type=${typeof item}`);
|
|
||||||
for (let i = 0; i < item.length; i++)
|
|
||||||
inner(item[i], `${title}[${i}]`);
|
|
||||||
return item;
|
|
||||||
}
|
|
||||||
/**
|
|
||||||
* Checks if something is Uint8Array. Be careful: nodejs Buffer will return true.
|
|
||||||
* @param a - Value to inspect.
|
|
||||||
* @returns `true` when the value is a Uint8Array view, including Node's `Buffer`.
|
|
||||||
* @example
|
|
||||||
* Guards a value before treating it as raw key material.
|
|
||||||
*
|
|
||||||
* ```ts
|
|
||||||
* isBytes(new Uint8Array());
|
|
||||||
* ```
|
|
||||||
*/
|
|
||||||
export function isBytes(a) {
|
|
||||||
// Plain `instanceof Uint8Array` is too strict for some Buffer / proxy /
|
|
||||||
// cross-realm cases. The fallback still requires a real ArrayBuffer view
|
|
||||||
// so plain JSON-deserialized `{ constructor: ... }`
|
|
||||||
// spoofing is rejected, and `BYTES_PER_ELEMENT === 1` keeps the fallback on byte-oriented views.
|
|
||||||
return (a instanceof Uint8Array ||
|
|
||||||
(ArrayBuffer.isView(a) &&
|
|
||||||
a.constructor.name === 'Uint8Array' &&
|
|
||||||
'BYTES_PER_ELEMENT' in a &&
|
|
||||||
a.BYTES_PER_ELEMENT === 1));
|
|
||||||
}
|
|
||||||
// Shared error-message prefix builder. Only called on throw paths, so assert
|
|
||||||
// success paths never pay for the string concatenation.
|
|
||||||
const atitle = (title) => (title ? `"${title}" ` : '');
|
|
||||||
/**
|
|
||||||
* Asserts something is boolean.
|
|
||||||
* @param value - Value to validate.
|
|
||||||
* @returns The validated boolean.
|
|
||||||
* @throws On wrong argument types. {@link TypeError}
|
|
||||||
* @example
|
|
||||||
* Validates a boolean option before branching on it.
|
|
||||||
*
|
|
||||||
* ```ts
|
|
||||||
* abool(true);
|
|
||||||
* ```
|
|
||||||
*/
|
|
||||||
export function abool(value, title = '') {
|
|
||||||
if (typeof value !== 'boolean')
|
|
||||||
throw new TypeError(atitle(title) + 'expected boolean, got type=' + typeof value);
|
|
||||||
return value;
|
|
||||||
}
|
|
||||||
/**
|
|
||||||
* Asserts something is a non-negative safe integer.
|
|
||||||
* @param n - Value to validate.
|
|
||||||
* @returns The validated number.
|
|
||||||
* @throws On wrong argument types. {@link TypeError}
|
|
||||||
* @throws On wrong argument ranges or values. {@link RangeError}
|
|
||||||
* @example
|
|
||||||
* Validates a non-negative length or counter.
|
|
||||||
*
|
|
||||||
* ```ts
|
|
||||||
* anumber(1);
|
|
||||||
* ```
|
|
||||||
*/
|
|
||||||
export function anumber(n, title = '') {
|
|
||||||
if (typeof n !== 'number')
|
|
||||||
throw new TypeError(atitle(title) + 'expected number, got ' + typeof n);
|
|
||||||
if (!Number.isSafeInteger(n) || n < 0)
|
|
||||||
throw new RangeError(atitle(title) + 'expected integer >= 0, got ' + n);
|
|
||||||
return n;
|
|
||||||
}
|
|
||||||
/**
|
|
||||||
* Asserts something is Uint8Array.
|
|
||||||
* @param value - Value to validate.
|
|
||||||
* @param length - Expected byte length.
|
|
||||||
* @param title - Optional label used in error messages.
|
|
||||||
* @returns The validated byte array.
|
|
||||||
* On Node, `Buffer` is accepted too because it is a Uint8Array view.
|
|
||||||
* @throws On wrong argument types. {@link TypeError}
|
|
||||||
* @throws On wrong argument lengths. {@link RangeError}
|
|
||||||
* @example
|
|
||||||
* Validates a fixed-length nonce or key buffer.
|
|
||||||
*
|
|
||||||
* ```ts
|
|
||||||
* abytes(new Uint8Array([1, 2]), 2);
|
|
||||||
* ```
|
|
||||||
*/
|
|
||||||
export function abytes(value, length, title = '') {
|
|
||||||
// Success path first: this runs at the start of every update() / digestInto(), and the
|
|
||||||
// common `abytes(data)` form must not pay for length handling it does not use.
|
|
||||||
if (isBytes(value) && (length === undefined || value.length === length))
|
|
||||||
return value;
|
|
||||||
// Error path: recompute freely to build the exact message.
|
|
||||||
if (length !== undefined)
|
|
||||||
anumber(length, 'length');
|
|
||||||
const bytes = isBytes(value);
|
|
||||||
const ofLen = length !== undefined ? ` of length ${length}` : '';
|
|
||||||
const got = bytes ? `length=${value.length}` : `type=${typeof value}`;
|
|
||||||
const message = atitle(title) + 'expected Uint8Array' + ofLen + ', got ' + got;
|
|
||||||
if (!bytes)
|
|
||||||
throw new TypeError(message);
|
|
||||||
throw new RangeError(message);
|
|
||||||
}
|
|
||||||
const aobject = (value, label) => {
|
|
||||||
if (value === null || typeof value !== 'object' || Array.isArray(value))
|
|
||||||
throw new TypeError(label === 'object'
|
|
||||||
? 'expected valid options object'
|
|
||||||
: `"${label}" expected object, got type=${typeof value}`);
|
|
||||||
};
|
|
||||||
/**
|
|
||||||
* Asserts a hash- or MAC-like instance has not been destroyed or finished.
|
|
||||||
* @param instance - Stateful instance to validate.
|
|
||||||
* @param checkFinished - Whether to reject finished instances.
|
|
||||||
* When `false`, only `destroyed` is checked.
|
|
||||||
* @throws If the hash instance has already been destroyed or finalized. {@link Error}
|
|
||||||
* @example
|
|
||||||
* Guards against calling `update()` or `digest()` on a finished hash.
|
|
||||||
*
|
|
||||||
* ```ts
|
|
||||||
* aexists({ destroyed: false, finished: false });
|
|
||||||
* ```
|
|
||||||
*/
|
|
||||||
export function aexists(instance, checkFinished = true) {
|
|
||||||
// Runs on every update()/digestInto(); the flags are library-owned booleans, so only their
|
|
||||||
// truthiness is checked - re-validating their type per call was pure hot-path overhead.
|
|
||||||
if (instance.destroyed)
|
|
||||||
throw new Error('hash was destroyed');
|
|
||||||
if (checkFinished && instance.finished)
|
|
||||||
throw new Error('digest() was already called');
|
|
||||||
}
|
|
||||||
/**
|
|
||||||
* Asserts output is a sufficiently-sized byte array.
|
|
||||||
* @param out - Output buffer to validate.
|
|
||||||
* @param instance - Hash-like instance providing `outputLen`.
|
|
||||||
* This is the relaxed `digestInto()`-style contract: output must be at least `outputLen`,
|
|
||||||
* unlike one-shot cipher helpers elsewhere in the repo that often require exact lengths.
|
|
||||||
* @throws On wrong argument types. {@link TypeError}
|
|
||||||
* @throws On wrong output buffer lengths. {@link RangeError}
|
|
||||||
* @example
|
|
||||||
* Verifies that a caller-provided output buffer is large enough.
|
|
||||||
*
|
|
||||||
* ```ts
|
|
||||||
* aoutput(new Uint8Array(16), { outputLen: 16 });
|
|
||||||
* ```
|
|
||||||
*/
|
|
||||||
export function aoutput(out, instance) {
|
|
||||||
abytes(out, undefined, 'output');
|
|
||||||
// `outputLen` is a library-owned readonly number; the negated comparison keeps failing fast
|
|
||||||
// when it is missing/NaN (comparisons with undefined/NaN are false) without an anumber() call.
|
|
||||||
const min = instance.outputLen;
|
|
||||||
if (!(out.length >= min)) {
|
|
||||||
throw new RangeError('"output" expected length >= ' + min);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
/**
|
|
||||||
* Asserts output is a sufficiently-sized, 4-byte-aligned byte array.
|
|
||||||
* {@link aoutput} plus an {@link isAligned32} check, for `digestInto()` paths
|
|
||||||
* that write through zero-allocation `u32` word views.
|
|
||||||
* @param out - Output buffer to validate.
|
|
||||||
* @param instance - Hash-like instance providing `outputLen`.
|
|
||||||
* @throws On wrong argument types. {@link TypeError}
|
|
||||||
* @throws On wrong output buffer lengths. {@link RangeError}
|
|
||||||
* @throws On wrong output buffer alignment. {@link Error}
|
|
||||||
* @example
|
|
||||||
* Verifies that a caller-provided output buffer is large enough and aligned.
|
|
||||||
*
|
|
||||||
* ```ts
|
|
||||||
* aoutput32(new Uint8Array(16), { outputLen: 16 });
|
|
||||||
* ```
|
|
||||||
*/
|
|
||||||
export function aoutput32(out, instance) {
|
|
||||||
aoutput(out, instance);
|
|
||||||
if (!isAligned32(out))
|
|
||||||
throw new Error('invalid output, must be aligned');
|
|
||||||
}
|
|
||||||
/**
|
|
||||||
* Casts a typed-array view to Uint8Array.
|
|
||||||
* @param arr - Typed-array view to reinterpret.
|
|
||||||
* @returns Uint8Array view over the same bytes.
|
|
||||||
* @example
|
|
||||||
* Views 32-bit words as raw bytes without copying.
|
|
||||||
*
|
|
||||||
* ```ts
|
|
||||||
* u8(new Uint32Array([1]));
|
|
||||||
* ```
|
|
||||||
*/
|
|
||||||
export function u8(arr) {
|
|
||||||
return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);
|
|
||||||
}
|
|
||||||
/**
|
|
||||||
* Casts a typed-array view to Uint32Array.
|
|
||||||
* @param arr - Typed-array view to reinterpret.
|
|
||||||
* @returns Uint32Array view over the same bytes. Callers are expected to provide a
|
|
||||||
* 4-byte-aligned offset; trailing `1..3` bytes are silently dropped.
|
|
||||||
* @example
|
|
||||||
* Views a byte buffer as 32-bit words for block processing.
|
|
||||||
*
|
|
||||||
* ```ts
|
|
||||||
* u32(new Uint8Array(4));
|
|
||||||
* ```
|
|
||||||
*/
|
|
||||||
export function u32(arr) {
|
|
||||||
return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));
|
|
||||||
}
|
|
||||||
/**
|
|
||||||
* Zeroizes typed arrays in place.
|
|
||||||
* Warning: JS provides no guarantees.
|
|
||||||
* @param arrays - Arrays to wipe.
|
|
||||||
* @example
|
|
||||||
* Wipes a temporary key buffer after use.
|
|
||||||
*
|
|
||||||
* ```ts
|
|
||||||
* const bytes = new Uint8Array([1]);
|
|
||||||
* clean(bytes);
|
|
||||||
* ```
|
|
||||||
*/
|
|
||||||
export function clean(...arrays) {
|
|
||||||
for (let i = 0; i < arrays.length; i++) {
|
|
||||||
arrays[i].fill(0);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
/**
|
|
||||||
* Creates a DataView for byte-level manipulation.
|
|
||||||
* @param arr - Typed-array view to wrap.
|
|
||||||
* @returns DataView over the same bytes.
|
|
||||||
* @example
|
|
||||||
* Creates an endian-aware view for length encoding.
|
|
||||||
*
|
|
||||||
* ```ts
|
|
||||||
* createView(new Uint8Array(4));
|
|
||||||
* ```
|
|
||||||
*/
|
|
||||||
export function createView(arr) {
|
|
||||||
return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
|
|
||||||
}
|
|
||||||
/**
|
|
||||||
* Whether the current platform is little-endian.
|
|
||||||
* Most are; some IBM systems are not.
|
|
||||||
*/
|
|
||||||
export const isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();
|
|
||||||
/**
|
|
||||||
* Reverses byte order of one 32-bit word.
|
|
||||||
* @param word - Unsigned 32-bit word to swap.
|
|
||||||
* @returns The same word with bytes reversed.
|
|
||||||
* @example
|
|
||||||
* Swaps a big-endian word into little-endian byte order.
|
|
||||||
*
|
|
||||||
* ```ts
|
|
||||||
* byteSwap(0x11223344);
|
|
||||||
* ```
|
|
||||||
*/
|
|
||||||
export function byteSwap(word) {
|
|
||||||
return (((word << 24) & 0xff000000) |
|
|
||||||
((word << 8) & 0xff0000) |
|
|
||||||
((word >>> 8) & 0xff00) |
|
|
||||||
((word >>> 24) & 0xff));
|
|
||||||
}
|
|
||||||
/**
|
|
||||||
* Normalizes one 32-bit word to the little-endian representation expected by cipher cores.
|
|
||||||
* @param n - Unsigned 32-bit word to normalize.
|
|
||||||
* @returns Little-endian normalized word on big-endian hosts, else the input word unchanged.
|
|
||||||
* @example
|
|
||||||
* Normalizes a host-endian word before passing it into an ARX/AES core.
|
|
||||||
*
|
|
||||||
* ```ts
|
|
||||||
* swap8IfBE(0x11223344);
|
|
||||||
* ```
|
|
||||||
*/
|
|
||||||
export const swap8IfBE = isLE
|
|
||||||
? (n) => n
|
|
||||||
: (n) => byteSwap(n) >>> 0;
|
|
||||||
/**
|
|
||||||
* Byte-swaps every word of a Uint32Array in place.
|
|
||||||
* @param arr - Uint32Array whose words should be swapped.
|
|
||||||
* @returns The same array after in-place byte swapping.
|
|
||||||
* @example
|
|
||||||
* Swaps every 32-bit word in a word-view buffer.
|
|
||||||
*
|
|
||||||
* ```ts
|
|
||||||
* byteSwap32(new Uint32Array([0x11223344]));
|
|
||||||
* ```
|
|
||||||
*/
|
|
||||||
export function byteSwap32(arr) {
|
|
||||||
for (let i = 0; i < arr.length; i++) {
|
|
||||||
arr[i] = byteSwap(arr[i]);
|
|
||||||
}
|
|
||||||
return arr;
|
|
||||||
}
|
|
||||||
/**
|
|
||||||
* Normalizes a Uint32Array view to the little-endian representation expected by cipher cores.
|
|
||||||
* @param u - Word view to normalize in place.
|
|
||||||
* @returns Little-endian normalized word view.
|
|
||||||
* @example
|
|
||||||
* Normalizes a word-view buffer before block processing.
|
|
||||||
*
|
|
||||||
* ```ts
|
|
||||||
* swap32IfBE(new Uint32Array([0x11223344]));
|
|
||||||
* ```
|
|
||||||
*/
|
|
||||||
export const swap32IfBE = isLE
|
|
||||||
? (u) => u
|
|
||||||
: byteSwap32;
|
|
||||||
// Built-in hex conversion:
|
|
||||||
// {@link https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex | caniuse entry}
|
|
||||||
const hasHexBuiltin = /* @__PURE__ */ (() =>
|
|
||||||
// @ts-ignore
|
|
||||||
typeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function')();
|
|
||||||
// Array where index 0xf0 (240) is mapped to string 'f0'
|
|
||||||
const hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));
|
|
||||||
/**
|
|
||||||
* Convert byte array to hex string. Uses built-in function, when available.
|
|
||||||
* @param bytes - Bytes to encode.
|
|
||||||
* @returns Lowercase hexadecimal string.
|
|
||||||
* @throws On wrong argument types. {@link TypeError}
|
|
||||||
* @example
|
|
||||||
* Formats ciphertext bytes for logs or test vectors.
|
|
||||||
*
|
|
||||||
* ```ts
|
|
||||||
* bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])); // 'cafe0123'
|
|
||||||
* ```
|
|
||||||
*/
|
|
||||||
export function bytesToHex(bytes) {
|
export function bytesToHex(bytes) {
|
||||||
abytes(bytes);
|
return Array.from(bytes).map(b => b.toString(16).padStart(2, "0")).join("");
|
||||||
// @ts-ignore
|
|
||||||
if (hasHexBuiltin)
|
|
||||||
return bytes.toHex();
|
|
||||||
// pre-caching improves the speed 6x
|
|
||||||
let hex = '';
|
|
||||||
for (let i = 0; i < bytes.length; i++) {
|
|
||||||
hex += hexes[bytes[i]];
|
|
||||||
}
|
}
|
||||||
return hex;
|
|
||||||
}
|
|
||||||
// Strict ASCII nibble parser: non-ASCII hex lookalikes are rejected as undefined.
|
|
||||||
// ASCII codes: '0'..'9' = 48..57, 'A'..'F' = 65..70, 'a'..'f' = 97..102.
|
|
||||||
// prettier-ignore
|
|
||||||
function asciiToBase16(ch) {
|
|
||||||
return ch >= 48 && ch <= 57 ? ch - 48 // '2' => 50-48
|
|
||||||
: ch >= 65 && ch <= 70 ? ch - (65 - 10) // 'B' => 66-(65-10)
|
|
||||||
: ch >= 97 && ch <= 102 ? ch - (97 - 10) // 'b' => 98-(97-10)
|
|
||||||
: undefined;
|
|
||||||
}
|
|
||||||
/**
|
|
||||||
* Convert hex string to byte array. Uses built-in function, when available.
|
|
||||||
* @param hex - hexadecimal string to decode
|
|
||||||
* @returns Decoded bytes.
|
|
||||||
* @throws On wrong argument types. {@link TypeError}
|
|
||||||
* @throws On wrong argument ranges or values. {@link RangeError}
|
|
||||||
* @example
|
|
||||||
* Decode lowercase hexadecimal into bytes.
|
|
||||||
* ```ts
|
|
||||||
* hexToBytes('cafe0123'); // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])
|
|
||||||
* ```
|
|
||||||
*/
|
|
||||||
export function hexToBytes(hex) {
|
export function hexToBytes(hex) {
|
||||||
if (typeof hex !== 'string')
|
const bytes = new Uint8Array(hex.length / 2);
|
||||||
throw new TypeError('hex string expected, got ' + typeof hex);
|
for (let i = 0; i < hex.length; i += 2) bytes[i / 2] = parseInt(hex.slice(i, i + 2), 16);
|
||||||
if (hasHexBuiltin) {
|
return bytes;
|
||||||
try {
|
|
||||||
return Uint8Array.fromHex(hex);
|
|
||||||
}
|
|
||||||
catch (error) {
|
|
||||||
if (error instanceof SyntaxError)
|
|
||||||
throw new RangeError(error.message);
|
|
||||||
throw error;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
const hl = hex.length;
|
|
||||||
const al = hl / 2;
|
|
||||||
if (hl % 2)
|
|
||||||
throw new RangeError('hex string expected, got unpadded hex of length ' + hl);
|
|
||||||
const array = new Uint8Array(al);
|
|
||||||
for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
|
|
||||||
const n1 = asciiToBase16(hex.charCodeAt(hi)); // parse first char, multiply it by 16
|
|
||||||
const n2 = asciiToBase16(hex.charCodeAt(hi + 1)); // parse second char
|
|
||||||
if (n1 === undefined || n2 === undefined) {
|
|
||||||
const char = hex[hi] + hex[hi + 1];
|
|
||||||
throw new RangeError('hex string expected, got non-hex character "' + char + '" at index ' + hi);
|
|
||||||
}
|
|
||||||
array[ai] = n1 * 16 + n2; // example: 'A9' => 10*16 + 9
|
|
||||||
}
|
|
||||||
return array;
|
|
||||||
}
|
|
||||||
const _0n = /* @__PURE__ */ BigInt(0);
|
|
||||||
// Used in ff1, via bytesToNumberBE
|
|
||||||
/**
|
|
||||||
* Converts a big-endian hex string into bigint.
|
|
||||||
* @param hex - Hexadecimal string without `0x`.
|
|
||||||
* @returns Parsed bigint value. The empty string is treated as `0n`.
|
|
||||||
* @throws On wrong argument types. {@link TypeError}
|
|
||||||
* @example
|
|
||||||
* Parses a big-endian field element or counter from hex.
|
|
||||||
*
|
|
||||||
* ```ts
|
|
||||||
* hexToNumber('ff');
|
|
||||||
* ```
|
|
||||||
*/
|
|
||||||
export function hexToNumber(hex) {
|
|
||||||
if (typeof hex !== 'string')
|
|
||||||
throw new TypeError('hex string expected, got ' + typeof hex);
|
|
||||||
// Numeric parser, not byte-hex decoder: odd-length forms like 'f' are valid,
|
|
||||||
// and malformed syntax follows BigInt's native error behavior.
|
|
||||||
return hex === '' ? _0n : BigInt('0x' + hex); // Big Endian
|
|
||||||
}
|
|
||||||
// Used in ff1
|
|
||||||
// BE: Big Endian, LE: Little Endian
|
|
||||||
/**
|
|
||||||
* Converts big-endian bytes into bigint.
|
|
||||||
* @param bytes - Big-endian bytes.
|
|
||||||
* @returns Parsed bigint value. Empty input is treated as `0n`.
|
|
||||||
* @throws On invalid byte input passed to the internal hex conversion. {@link TypeError}
|
|
||||||
* @example
|
|
||||||
* Reads a big-endian integer from serialized bytes.
|
|
||||||
*
|
|
||||||
* ```ts
|
|
||||||
* bytesToNumberBE(new Uint8Array([1, 0]));
|
|
||||||
* ```
|
|
||||||
*/
|
|
||||||
export function bytesToNumberBE(bytes) {
|
|
||||||
return hexToNumber(bytesToHex(bytes));
|
|
||||||
}
|
|
||||||
/**
|
|
||||||
* Validates that a value is a non-negative bigint or safe integer.
|
|
||||||
* @param n - Value to validate.
|
|
||||||
* @returns The same validated value.
|
|
||||||
* @throws On wrong argument ranges or values. {@link RangeError}
|
|
||||||
*/
|
|
||||||
function abignumber(n) {
|
|
||||||
if (typeof n === 'bigint') {
|
|
||||||
if (!(_0n <= n))
|
|
||||||
throw new RangeError('positive bigint expected, got ' + n);
|
|
||||||
}
|
|
||||||
else
|
|
||||||
anumber(n);
|
|
||||||
return n;
|
|
||||||
}
|
|
||||||
// Used in ff1
|
|
||||||
/**
|
|
||||||
* Converts a number into big-endian bytes of fixed length.
|
|
||||||
* @param n - Number to encode.
|
|
||||||
* @param len - Output length in bytes. Must be greater than zero.
|
|
||||||
* @returns Big-endian bytes padded to `len`.
|
|
||||||
* Negative values, `len = 0`, and values that do not fit are rejected before
|
|
||||||
* downstream hex parsing.
|
|
||||||
* @throws On wrong argument ranges or values. {@link RangeError}
|
|
||||||
* @throws If a documented runtime validation or state check fails. {@link Error}
|
|
||||||
* @example
|
|
||||||
* Encodes a counter as fixed-width big-endian bytes.
|
|
||||||
*
|
|
||||||
* ```ts
|
|
||||||
* numberToBytesBE(1, 2);
|
|
||||||
* ```
|
|
||||||
*/
|
|
||||||
export function numberToBytesBE(n, len) {
|
|
||||||
anumber(len);
|
|
||||||
if (len === 0)
|
|
||||||
throw new Error('zero output length is invalid');
|
|
||||||
n = abignumber(n);
|
|
||||||
const expectedLen = len * 2;
|
|
||||||
const hex = n.toString(16);
|
|
||||||
// Detect overflow before hex parsing so oversized values don't leak the shared odd-hex error.
|
|
||||||
if (hex.length > expectedLen)
|
|
||||||
throw new RangeError('number is too large');
|
|
||||||
return hexToBytes(hex.padStart(expectedLen, '0'));
|
|
||||||
}
|
|
||||||
/**
|
|
||||||
* Converts string to bytes using UTF8 encoding.
|
|
||||||
* @param str - String to encode.
|
|
||||||
* @returns UTF-8 bytes in a detached fresh Uint8Array copy.
|
|
||||||
* @throws On wrong argument types. {@link TypeError}
|
|
||||||
* @example
|
|
||||||
* Encodes application text before encryption or MACing.
|
|
||||||
*
|
|
||||||
* ```ts
|
|
||||||
* utf8ToBytes('abc'); // new Uint8Array([97, 98, 99])
|
|
||||||
* ```
|
|
||||||
*/
|
|
||||||
export function utf8ToBytes(str) {
|
|
||||||
if (typeof str !== 'string')
|
|
||||||
throw new TypeError('string expected');
|
|
||||||
return new Uint8Array(new TextEncoder().encode(str)); // {@link https://bugzil.la/1681809 | Firefox bug 1681809}
|
|
||||||
}
|
|
||||||
/**
|
|
||||||
* Converts bytes to string using UTF8 encoding.
|
|
||||||
* @param bytes - UTF-8 bytes.
|
|
||||||
* @returns Decoded string. Input validation is delegated to `TextDecoder`, and malformed
|
|
||||||
* UTF-8 is replacement-decoded instead of rejected.
|
|
||||||
* @example
|
|
||||||
* Decodes UTF-8 plaintext back into a string.
|
|
||||||
*
|
|
||||||
* ```ts
|
|
||||||
* bytesToUtf8(new Uint8Array([97, 98, 99])); // 'abc'
|
|
||||||
* ```
|
|
||||||
*/
|
|
||||||
export function bytesToUtf8(bytes) {
|
|
||||||
return new TextDecoder().decode(bytes);
|
|
||||||
}
|
|
||||||
/**
|
|
||||||
* Checks if two U8A use same underlying buffer and overlaps.
|
|
||||||
* This is invalid and can corrupt data.
|
|
||||||
* @param a - First byte view.
|
|
||||||
* @param b - Second byte view.
|
|
||||||
* @returns `true` when the views overlap in memory.
|
|
||||||
* @example
|
|
||||||
* Detects whether two slices alias the same backing buffer.
|
|
||||||
*
|
|
||||||
* ```ts
|
|
||||||
* overlapBytes(new Uint8Array(4), new Uint8Array(4));
|
|
||||||
* ```
|
|
||||||
*/
|
|
||||||
export function overlapBytes(a, b) {
|
|
||||||
// Zero-length views cannot overwrite anything, even if their offset sits inside another range.
|
|
||||||
if (!a.byteLength || !b.byteLength)
|
|
||||||
return false;
|
|
||||||
return (a.buffer === b.buffer && // best we can do, may fail with an obscure Proxy
|
|
||||||
a.byteOffset < b.byteOffset + b.byteLength && // a starts before b end
|
|
||||||
b.byteOffset < a.byteOffset + a.byteLength // b starts before a end
|
|
||||||
);
|
|
||||||
}
|
|
||||||
/**
|
|
||||||
* If input and output overlap and input starts before output, we will overwrite end of input before
|
|
||||||
* we start processing it, so this is not supported by forward-processing ciphers.
|
|
||||||
* @param input - Input bytes.
|
|
||||||
* @param output - Output bytes.
|
|
||||||
* @throws If the output view would overwrite unread input bytes. {@link Error}
|
|
||||||
* @example
|
|
||||||
* Rejects an in-place layout that would overwrite unread input bytes.
|
|
||||||
*
|
|
||||||
* ```ts
|
|
||||||
* const buffer = new Uint8Array(8);
|
|
||||||
* complexOverlapBytes(buffer.subarray(0, 4), buffer.subarray(2, 6));
|
|
||||||
* ```
|
|
||||||
*/
|
|
||||||
export function complexOverlapBytes(input, output) {
|
|
||||||
// This is very cursed. It works somehow, but I'm completely unsure,
|
|
||||||
// reasoning about overlapping aligned windows is very hard.
|
|
||||||
if (overlapBytes(input, output) && input.byteOffset < output.byteOffset)
|
|
||||||
throw new Error('complex overlap of input and output is not supported');
|
|
||||||
}
|
|
||||||
/**
|
|
||||||
* Copies several Uint8Arrays into one.
|
|
||||||
* @param arrays - Byte arrays to concatenate.
|
|
||||||
* @returns Combined byte array.
|
|
||||||
* @throws On wrong argument types inside the byte-array list. {@link TypeError}
|
|
||||||
* @example
|
|
||||||
* Builds a `nonce || ciphertext` style buffer.
|
|
||||||
*
|
|
||||||
* ```ts
|
|
||||||
* concatBytes(new Uint8Array([1]), new Uint8Array([2]));
|
|
||||||
* ```
|
|
||||||
*/
|
|
||||||
export function concatBytes(...arrays) {
|
|
||||||
let sum = 0;
|
|
||||||
for (let i = 0; i < arrays.length; i++) {
|
|
||||||
const a = arrays[i];
|
|
||||||
abytes(a);
|
|
||||||
sum += a.length;
|
|
||||||
}
|
|
||||||
const res = new Uint8Array(sum);
|
|
||||||
for (let i = 0, pad = 0; i < arrays.length; i++) {
|
|
||||||
const a = arrays[i];
|
|
||||||
res.set(a, pad);
|
|
||||||
pad += a.length;
|
|
||||||
}
|
|
||||||
return res;
|
|
||||||
}
|
|
||||||
/**
|
|
||||||
* Merges user options into defaults.
|
|
||||||
* @param defaults - Default option values.
|
|
||||||
* @param opts - User-provided overrides.
|
|
||||||
* @returns Combined options object.
|
|
||||||
* `defaults` is a library-owned mutable object; user-provided `opts` only need to be
|
|
||||||
* object-shaped, since "plain object" checks reject valid proxy/cross-realm containers.
|
|
||||||
* The merge mutates `defaults` in place and returns the same object, so direct callers
|
|
||||||
* should pass a fresh defaults object unless they intentionally want shared state updated.
|
|
||||||
* @throws If options are missing or not an object. {@link Error}
|
|
||||||
* @example
|
|
||||||
* Applies user overrides to the default cipher options.
|
|
||||||
*
|
|
||||||
* ```ts
|
|
||||||
* checkOpts({ rounds: 20 }, { rounds: 8 });
|
|
||||||
* ```
|
|
||||||
*/
|
|
||||||
export function checkOpts(defaults, opts) {
|
|
||||||
aobject(defaults, 'defaults');
|
|
||||||
aobject(opts, 'opts');
|
|
||||||
// Mutates defaults by design. __proto__ follows Object.assign semantics here and can only
|
|
||||||
// affect this local option object; callers already control this low-level options surface.
|
|
||||||
const merged = Object.assign(defaults, opts);
|
|
||||||
return merged;
|
|
||||||
}
|
|
||||||
/**
|
|
||||||
* Compares two byte arrays in kinda constant time once lengths already match.
|
|
||||||
* @param a - First byte array.
|
|
||||||
* @param b - Second byte array.
|
|
||||||
* @returns `true` when the arrays contain the same bytes. Different lengths still return early.
|
|
||||||
* @example
|
|
||||||
* Compares an expected authentication tag with the received one.
|
|
||||||
*
|
|
||||||
* ```ts
|
|
||||||
* equalBytes(new Uint8Array([1]), new Uint8Array([1]));
|
|
||||||
* ```
|
|
||||||
*/
|
|
||||||
export function equalBytes(a, b) {
|
|
||||||
a = abytes(a);
|
|
||||||
b = abytes(b);
|
|
||||||
if (a.length !== b.length)
|
|
||||||
return false;
|
|
||||||
let diff = 0;
|
|
||||||
for (let i = 0; i < a.length; i++)
|
|
||||||
diff |= a[i] ^ b[i];
|
|
||||||
return diff === 0;
|
|
||||||
}
|
|
||||||
/**
|
|
||||||
* Wraps a keyed MAC constructor into a one-shot helper with `.create()`.
|
|
||||||
* @param keyLen - Valid probe-key length used to read static metadata once.
|
|
||||||
* The probe key is only used for `outputLen` / `blockLen`, so callers with several valid key sizes
|
|
||||||
* can pass any representative size as long as those values stay fixed.
|
|
||||||
* @param macCons - Keyed MAC constructor or factory.
|
|
||||||
* @param fromMsg - Optional adapter that derives extra constructor args from the one-shot message.
|
|
||||||
* @returns Callable MAC helper with `.create()`.
|
|
||||||
*/
|
|
||||||
export function wrapMacConstructor(keyLen, macCons, fromMsg) {
|
|
||||||
const mac = macCons;
|
|
||||||
const getArgs = (fromMsg || (() => []));
|
|
||||||
const macC = (msg, key) => mac(key, ...getArgs(msg))
|
|
||||||
.update(msg)
|
|
||||||
.digest();
|
|
||||||
const tmp = mac(new Uint8Array(keyLen), ...getArgs(new Uint8Array(0)));
|
|
||||||
macC.outputLen = tmp.outputLen;
|
|
||||||
macC.blockLen = tmp.blockLen;
|
|
||||||
macC.create = (key, ...args) => mac(key, ...args);
|
|
||||||
return macC;
|
|
||||||
}
|
|
||||||
/**
|
|
||||||
* Wraps a cipher: validates args, ensures encrypt() can only be called once.
|
|
||||||
* Used internally by the exported cipher constructors.
|
|
||||||
* Output-buffer support is inferred from the wrapped `encrypt` / `decrypt`
|
|
||||||
* arity (`fn.length === 2`), so wrapped output-capable methods must use a normal
|
|
||||||
* second parameter, not a default/rest parameter. AAD support is explicit in
|
|
||||||
* `params.withAAD`; optional AAD starts after the nonce slot when one is present.
|
|
||||||
* @__NO_SIDE_EFFECTS__
|
|
||||||
* @param params - Static cipher metadata. See {@link CipherParams}.
|
|
||||||
* @param constructor - Cipher constructor.
|
|
||||||
* @returns Wrapped constructor with validation.
|
|
||||||
*/
|
|
||||||
export const wrapCipher = (params, constructor) => {
|
|
||||||
function wrappedCipher(key, ...args) {
|
|
||||||
// Validate key
|
|
||||||
abytes(key, undefined, 'key');
|
|
||||||
// Validate nonce if nonceLength is present
|
|
||||||
if (params.nonceLength !== undefined) {
|
|
||||||
const nonce = args[0];
|
|
||||||
abytes(nonce, params.varSizeNonce ? undefined : params.nonceLength, 'nonce');
|
|
||||||
}
|
|
||||||
// Keep tag length available for decrypt-size checks after constructor validation.
|
|
||||||
const tagl = params.tagLength;
|
|
||||||
const aadStart = params.nonceLength !== undefined ? 1 : 0;
|
|
||||||
// No-AAD constructors otherwise silently ignore byte args meant as AAD.
|
|
||||||
if (!params.withAAD) {
|
|
||||||
for (let i = aadStart; i < args.length; i++)
|
|
||||||
if (isBytes(args[i]))
|
|
||||||
throw new Error('AAD not supported');
|
|
||||||
}
|
|
||||||
// Validate the first AAD slot early; rest-arg AAD constructors validate the tail themselves.
|
|
||||||
if (params.withAAD && args[aadStart] !== undefined)
|
|
||||||
abytes(args[aadStart], undefined, 'AAD');
|
|
||||||
const cipher = constructor(key, ...args);
|
|
||||||
const checkOutput = (fnLength, output) => {
|
|
||||||
if (output !== undefined) {
|
|
||||||
if (fnLength !== 2)
|
|
||||||
throw new Error('cipher output not supported');
|
|
||||||
abytes(output, undefined, 'output');
|
|
||||||
}
|
|
||||||
};
|
|
||||||
// Create wrapped cipher with validation and single-use encryption
|
|
||||||
let called = false;
|
|
||||||
const wrCipher = {
|
|
||||||
encrypt(data, output) {
|
|
||||||
if (called)
|
|
||||||
throw new Error('cannot encrypt() twice with same key + nonce');
|
|
||||||
// Any encrypt attempt consumes the instance, even if validation rejects below.
|
|
||||||
called = true;
|
|
||||||
abytes(data, undefined, 'data');
|
|
||||||
checkOutput(cipher.encrypt.length, output);
|
|
||||||
return cipher.encrypt(data, output);
|
|
||||||
},
|
|
||||||
decrypt(data, output) {
|
|
||||||
abytes(data, undefined, 'data');
|
|
||||||
if (tagl && data.length < tagl)
|
|
||||||
throw new Error('"ciphertext" expected length >= tagLength=' + tagl);
|
|
||||||
checkOutput(cipher.decrypt.length, output);
|
|
||||||
return cipher.decrypt(data, output);
|
|
||||||
},
|
|
||||||
};
|
|
||||||
return wrCipher;
|
|
||||||
}
|
|
||||||
Object.assign(wrappedCipher, params);
|
|
||||||
return wrappedCipher;
|
|
||||||
};
|
|
||||||
/**
|
|
||||||
* By default, returns u8a of length.
|
|
||||||
* When out is available, it checks it for validity and uses it.
|
|
||||||
* @param expectedLength - Required output length.
|
|
||||||
* @param out - Optional destination buffer.
|
|
||||||
* @param onlyAligned - Whether `out` must be 4-byte aligned.
|
|
||||||
* @returns Output buffer ready for writing.
|
|
||||||
* @throws On wrong argument types. {@link TypeError}
|
|
||||||
* @throws If the provided output buffer has the wrong size. {@link RangeError}
|
|
||||||
* @throws If the provided output buffer has the wrong alignment. {@link Error}
|
|
||||||
* @example
|
|
||||||
* Reuses a caller-provided output buffer when lengths match.
|
|
||||||
*
|
|
||||||
* ```ts
|
|
||||||
* getOutput(16, new Uint8Array(16));
|
|
||||||
* ```
|
|
||||||
*/
|
|
||||||
export function getOutput(expectedLength, out, onlyAligned = true) {
|
|
||||||
if (out === undefined)
|
|
||||||
return new Uint8Array(expectedLength);
|
|
||||||
// Keep Buffer/cross-realm Uint8Array support here instead of trusting a shape-compatible object.
|
|
||||||
abytes(out, expectedLength, 'output');
|
|
||||||
if (onlyAligned && !isAligned32(out))
|
|
||||||
throw new Error('invalid output, must be aligned');
|
|
||||||
return out;
|
|
||||||
}
|
|
||||||
/**
|
|
||||||
* Encodes data and AAD lengths into a 16-byte buffer.
|
|
||||||
* @param dataLength - Data length. Units are caller-defined: GCM passes bit
|
|
||||||
* lengths, ChaCha20-Poly1305 passes byte lengths — the helper writes the raw values.
|
|
||||||
* @param aadLength - AAD length, same unit convention as `dataLength`.
|
|
||||||
* The serialized block is still `aadLength || dataLength`, matching GCM/Poly1305
|
|
||||||
* conventions even though the helper parameter order is `(dataLength, aadLength)`.
|
|
||||||
* @param isLE - Whether to encode lengths as little-endian.
|
|
||||||
* @returns 16-byte length block.
|
|
||||||
* @throws On wrong argument types passed to the endian validator. {@link TypeError}
|
|
||||||
* @throws On wrong argument ranges or values. {@link RangeError}
|
|
||||||
* @example
|
|
||||||
* Builds the length block appended by GCM and Poly1305.
|
|
||||||
*
|
|
||||||
* ```ts
|
|
||||||
* u64Lengths(16, 8, true);
|
|
||||||
* ```
|
|
||||||
*/
|
|
||||||
export function u64Lengths(dataLength, aadLength, isLE) {
|
|
||||||
// Reject coercible non-number lengths like '10' and true before BigInt(...) accepts them.
|
|
||||||
anumber(dataLength);
|
|
||||||
anumber(aadLength);
|
|
||||||
abool(isLE);
|
|
||||||
const num = new Uint8Array(16);
|
|
||||||
const view = createView(num);
|
|
||||||
view.setBigUint64(0, BigInt(aadLength), isLE);
|
|
||||||
view.setBigUint64(8, BigInt(dataLength), isLE);
|
|
||||||
return num;
|
|
||||||
}
|
|
||||||
/**
|
|
||||||
* Checks whether a byte array is aligned to a 4-byte offset.
|
|
||||||
* @param bytes - Byte array to inspect.
|
|
||||||
* @returns `true` when the view is 4-byte aligned.
|
|
||||||
* @example
|
|
||||||
* Checks whether a buffer can be safely viewed as Uint32Array.
|
|
||||||
*
|
|
||||||
* ```ts
|
|
||||||
* isAligned32(new Uint8Array(4));
|
|
||||||
* ```
|
|
||||||
*/
|
|
||||||
export function isAligned32(bytes) {
|
|
||||||
return bytes.byteOffset % 4 === 0;
|
|
||||||
}
|
|
||||||
/**
|
|
||||||
* Copies bytes into a new Uint8Array.
|
|
||||||
* @param bytes - Bytes to copy.
|
|
||||||
* @returns Copied byte array.
|
|
||||||
* @throws On wrong argument types. {@link TypeError}
|
|
||||||
* @example
|
|
||||||
* Copies input into an aligned Uint8Array before block processing.
|
|
||||||
*
|
|
||||||
* ```ts
|
|
||||||
* copyBytes(new Uint8Array([1, 2]));
|
|
||||||
* ```
|
|
||||||
*/
|
|
||||||
export function copyBytes(bytes) {
|
|
||||||
// `Uint8Array.from(...)` would also accept arrays / other typed arrays. Keep this helper strict
|
|
||||||
// because callers use it at byte-validation boundaries before mutating the detached copy.
|
|
||||||
return Uint8Array.from(abytes(bytes));
|
|
||||||
}
|
|
||||||
/**
|
|
||||||
* Cryptographically secure PRNG backed by `crypto.getRandomValues`.
|
|
||||||
* @param bytesLength - number of random bytes to generate
|
|
||||||
* @returns Random bytes.
|
|
||||||
* The platform `getRandomValues()` implementation still defines any
|
|
||||||
* single-call length cap, and this helper rejects oversize requests
|
|
||||||
* with a stable library `RangeError` instead of host-specific errors.
|
|
||||||
* @throws On wrong argument types. {@link TypeError}
|
|
||||||
* @throws On wrong argument ranges or values. {@link RangeError}
|
|
||||||
* @throws If the current runtime does not provide `crypto.getRandomValues`. {@link Error}
|
|
||||||
* @example
|
|
||||||
* Generate a fresh random key or nonce.
|
|
||||||
* ```ts
|
|
||||||
* const key = randomBytes(16);
|
|
||||||
* ```
|
|
||||||
*/
|
|
||||||
export function randomBytes(bytesLength = 32) {
|
|
||||||
// Match the repo's other length-taking helpers instead of relying on Uint8Array coercion.
|
|
||||||
anumber(bytesLength, 'bytesLength');
|
|
||||||
const cr = typeof globalThis === 'object' ? globalThis.crypto : null;
|
|
||||||
if (typeof cr?.getRandomValues !== 'function')
|
|
||||||
throw new Error('crypto.getRandomValues must be defined');
|
|
||||||
// Web Cryptography API Level 2 §10.1.1:
|
|
||||||
// if `byteLength > 65536`, throw `QuotaExceededError`.
|
|
||||||
// Keep the guard explicit so callers can see the quota in code
|
|
||||||
// instead of discovering it by reading the spec or host errors.
|
|
||||||
// This wrapper surfaces the same quota as a stable library RangeError.
|
|
||||||
if (bytesLength > 65536)
|
|
||||||
throw new RangeError(`"bytesLength" expected <= 65536, got ${bytesLength}`);
|
|
||||||
return cr.getRandomValues(new Uint8Array(bytesLength));
|
|
||||||
}
|
|
||||||
/**
|
|
||||||
* Uses CSPRNG for nonce, nonce injected in ciphertext.
|
|
||||||
* For `encrypt`, a `nonceBytes`-length buffer is fetched from CSPRNG and
|
|
||||||
* prepended to encrypted ciphertext. For `decrypt`, first `nonceBytes` of ciphertext
|
|
||||||
* are treated as nonce. The wrapper always allocates a fresh `nonce || ciphertext`
|
|
||||||
* buffer on encrypt and intentionally does not support caller-provided destination buffers.
|
|
||||||
* Too-short decrypt inputs are split into short/empty nonce views and then delegated
|
|
||||||
* to the wrapped cipher instead of being rejected here first.
|
|
||||||
*
|
|
||||||
* NOTE: Under the same key, using random nonces (e.g. `managedNonce`) with AES-GCM and ChaCha
|
|
||||||
* should be limited to `2**23` (8M) messages to get a collision chance of
|
|
||||||
* `2**-50`. Stretching to `2**32` (4B) messages would raise that chance to
|
|
||||||
* `2**-33`, still negligible but creeping up.
|
|
||||||
* @param fn - Cipher constructor that expects a nonce.
|
|
||||||
* @param randomBytes_ - Random-byte source used for nonce generation.
|
|
||||||
* @returns Cipher constructor that prepends the nonce to ciphertext.
|
|
||||||
* @throws On wrong argument types. {@link TypeError}
|
|
||||||
* @throws On invalid nonce lengths observed at wrapper construction or use. {@link RangeError}
|
|
||||||
* @example
|
|
||||||
* Prepends a fresh random nonce to every ciphertext.
|
|
||||||
*
|
|
||||||
* ```ts
|
|
||||||
* import { gcm } from '@noble/ciphers/aes.js';
|
|
||||||
* import { managedNonce, randomBytes } from '@noble/ciphers/utils.js';
|
|
||||||
* const wrapped = managedNonce(gcm);
|
|
||||||
* const key = randomBytes(16);
|
|
||||||
* const ciphertext = wrapped(key).encrypt(new Uint8Array([1, 2, 3]));
|
|
||||||
* wrapped(key).decrypt(ciphertext);
|
|
||||||
* ```
|
|
||||||
*/
|
|
||||||
export function managedNonce(fn, randomBytes_ = randomBytes) {
|
|
||||||
if (typeof fn !== 'function')
|
|
||||||
throw new TypeError('"fn" expected cipher constructor, got type=' + typeof fn);
|
|
||||||
if (typeof randomBytes_ !== 'function')
|
|
||||||
throw new TypeError('"randomBytes_" expected function, got type=' + typeof randomBytes_);
|
|
||||||
const { nonceLength } = fn;
|
|
||||||
anumber(nonceLength, 'fn.nonceLength');
|
|
||||||
const addNonce = (nonce, ciphertext, plaintext) => {
|
|
||||||
const out = concatBytes(nonce, ciphertext);
|
|
||||||
// Wrapped ciphers may alias caller plaintext on encrypt(); never zero
|
|
||||||
// caller-owned buffers here.
|
|
||||||
if (!overlapBytes(plaintext, ciphertext))
|
|
||||||
ciphertext.fill(0);
|
|
||||||
return out;
|
|
||||||
};
|
|
||||||
// NOTE: we cannot support DST here, it would be mistake:
|
|
||||||
// - we don't know how much dst length cipher requires
|
|
||||||
// - nonce may unalign dst and break everything
|
|
||||||
// - we create new u8a anyway (concatBytes)
|
|
||||||
// - previously we passed all args to cipher, but that was mistake!
|
|
||||||
const res = ((key, ...args) => ({
|
|
||||||
encrypt(plaintext) {
|
|
||||||
abytes(plaintext, undefined, 'data');
|
|
||||||
const nonce = randomBytes_(nonceLength);
|
|
||||||
const encrypted = fn(key, nonce, ...args).encrypt(plaintext);
|
|
||||||
// @ts-ignore
|
|
||||||
if (encrypted instanceof Promise)
|
|
||||||
return encrypted.then((ct) => addNonce(nonce, ct, plaintext));
|
|
||||||
return addNonce(nonce, encrypted, plaintext);
|
|
||||||
},
|
|
||||||
decrypt(ciphertext) {
|
|
||||||
abytes(ciphertext, undefined, 'data');
|
|
||||||
const nonce = ciphertext.subarray(0, nonceLength);
|
|
||||||
const decrypted = ciphertext.subarray(nonceLength);
|
|
||||||
return fn(key, nonce, ...args).decrypt(decrypted);
|
|
||||||
},
|
|
||||||
}));
|
|
||||||
// Auto-nonce wrappers still preserve the wrapped payload geometry.
|
|
||||||
if ('blockSize' in fn)
|
|
||||||
res.blockSize = fn.blockSize;
|
|
||||||
if ('tagLength' in fn)
|
|
||||||
res.tagLength = fn.tagLength;
|
|
||||||
if ('withAAD' in fn)
|
|
||||||
res.withAAD = fn.withAAD;
|
|
||||||
return res;
|
|
||||||
}
|
}
|
||||||
|
|||||||
+3
-58
@@ -1,59 +1,4 @@
|
|||||||
/**
|
// Stub placeholder for noble-hashes internal _blake module
|
||||||
* Internal helpers for blake hash.
|
export function blake() {
|
||||||
* @module
|
throw new Error("noble _blake stub: not implemented");
|
||||||
*/
|
|
||||||
import { rotr } from "./utils.js";
|
|
||||||
// Unrealized speed-up: a file-local copy of rotr measured ~1-2% faster blake2s/blake256/blake3
|
|
||||||
// on Node 24 (V8 does not inline it into G1s/G2s across the module boundary). Reused from
|
|
||||||
// utils for deduplication.
|
|
||||||
/**
|
|
||||||
* Internal blake permutation table.
|
|
||||||
* Rows `0..9` serve BLAKE2s, rows `0..11` serve BLAKE2b with `10..11 = 0..1`, and Blake1 also
|
|
||||||
* reuses the later rows shown below. Blake1 expands rounds `10..15` as `SIGMA[i % 10]`, so rows
|
|
||||||
* `10..15` intentionally repeat rows `0..5` for the 14-round (256) and 16-round (512) variants.
|
|
||||||
*/
|
|
||||||
// prettier-ignore
|
|
||||||
export const BSIGMA = /* @__PURE__ */ Uint8Array.from([
|
|
||||||
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
|
|
||||||
14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3,
|
|
||||||
11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4,
|
|
||||||
7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8,
|
|
||||||
9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13,
|
|
||||||
2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9,
|
|
||||||
12, 5, 1, 15, 14, 13, 4, 10, 0, 7, 6, 3, 9, 2, 8, 11,
|
|
||||||
13, 11, 7, 14, 12, 1, 3, 9, 5, 0, 15, 4, 8, 6, 2, 10,
|
|
||||||
6, 15, 14, 9, 11, 3, 0, 8, 12, 2, 13, 7, 1, 4, 10, 5,
|
|
||||||
10, 2, 8, 4, 7, 6, 1, 5, 15, 11, 9, 14, 3, 12, 13, 0,
|
|
||||||
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
|
|
||||||
14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3,
|
|
||||||
// Blake1, unused in others
|
|
||||||
11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4,
|
|
||||||
7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8,
|
|
||||||
9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13,
|
|
||||||
2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9,
|
|
||||||
]);
|
|
||||||
// Unrealized speed-up: G1s/G2s return a fresh {a,b,c,d} per call (160×/blake2s block), which
|
|
||||||
// V8's escape analysis does not eliminate when G stays a real call. Writing into one reused
|
|
||||||
// module-level slot instead measured +4-6% blake2s/blake256 1MB throughput on Node 24 — but
|
|
||||||
// ~2% slower blake3 (whose profile inlines G and scalar-replaces the fresh object) and no
|
|
||||||
// difference on 32-byte inputs. Kept simple.
|
|
||||||
// 32-bit / BLAKE2s first half of G, with the fixed `(16, 12)` rotation pair.
|
|
||||||
// Parameter `x` is the RFC 7693 first-half message word, or Blake1's pre-mixed
|
|
||||||
// `m[sigma[r][2i]] ^ u[sigma[r][2i+1]]` addend in the 32-bit path.
|
|
||||||
export function G1s(a, b, c, d, x) {
|
|
||||||
a = (a + b + x) | 0;
|
|
||||||
d = rotr(d ^ a, 16);
|
|
||||||
c = (c + d) | 0;
|
|
||||||
b = rotr(b ^ c, 12);
|
|
||||||
return { a, b, c, d };
|
|
||||||
}
|
|
||||||
// 32-bit / BLAKE2s second half of G.
|
|
||||||
// Parameter `x` is the RFC 7693 second-half (`y`) message word, or Blake1's pre-mixed
|
|
||||||
// `m[sigma[r][2i + 1]] ^ u[sigma[r][2i]]` addend in the 32-bit path.
|
|
||||||
export function G2s(a, b, c, d, x) {
|
|
||||||
a = (a + b + x) | 0;
|
|
||||||
d = rotr(d ^ a, 8);
|
|
||||||
c = (c + d) | 0;
|
|
||||||
b = rotr(b ^ c, 7);
|
|
||||||
return { a, b, c, d };
|
|
||||||
}
|
}
|
||||||
|
|||||||
+3
-208
@@ -1,209 +1,4 @@
|
|||||||
/**
|
// Stub placeholder for noble-hashes internal _md module
|
||||||
* Internal Merkle-Damgard hash utils.
|
export function md() {
|
||||||
* @module
|
throw new Error("noble _md stub: not implemented");
|
||||||
*/
|
|
||||||
import { setU64FromNum } from "./_u64.js";
|
|
||||||
import { abytes, aexists, aoutput, createView } from "./utils.js";
|
|
||||||
/**
|
|
||||||
* Shared 32-bit conditional boolean primitive reused by SHA-256, SHA-1, and MD5 `F`.
|
|
||||||
* Returns bits from `b` when `a` is set, otherwise from `c`.
|
|
||||||
* The XOR form is equivalent to MD5's `F(X,Y,Z) = XY v not(X)Z` because the masked terms never
|
|
||||||
* set the same bit.
|
|
||||||
* @param a - selector word
|
|
||||||
* @param b - word chosen when selector bit is set
|
|
||||||
* @param c - word chosen when selector bit is clear
|
|
||||||
* @returns Mixed 32-bit word.
|
|
||||||
* @example
|
|
||||||
* Combine three words with the shared 32-bit choice primitive.
|
|
||||||
* ```ts
|
|
||||||
* Chi(0xffffffff, 0x12345678, 0x87654321);
|
|
||||||
* ```
|
|
||||||
*/
|
|
||||||
export function Chi(a, b, c) {
|
|
||||||
return (a & b) ^ (~a & c);
|
|
||||||
}
|
}
|
||||||
/**
|
|
||||||
* Shared 32-bit majority primitive reused by SHA-256 and SHA-1.
|
|
||||||
* Returns bits shared by at least two inputs.
|
|
||||||
* @param a - first input word
|
|
||||||
* @param b - second input word
|
|
||||||
* @param c - third input word
|
|
||||||
* @returns Mixed 32-bit word.
|
|
||||||
* @example
|
|
||||||
* Combine three words with the shared 32-bit majority primitive.
|
|
||||||
* ```ts
|
|
||||||
* Maj(0xffffffff, 0x12345678, 0x87654321);
|
|
||||||
* ```
|
|
||||||
*/
|
|
||||||
export function Maj(a, b, c) {
|
|
||||||
return (a & b) ^ (a & c) ^ (b & c);
|
|
||||||
}
|
|
||||||
/**
|
|
||||||
* Merkle-Damgard hash construction base class.
|
|
||||||
* Could be used to create MD5, RIPEMD, SHA1, SHA2.
|
|
||||||
* Accepts only byte-aligned `Uint8Array` input, even when the underlying spec describes bit
|
|
||||||
* strings with partial-byte tails.
|
|
||||||
* @param blockLen - internal block size in bytes
|
|
||||||
* @param outputLen - digest size in bytes
|
|
||||||
* @param padOffset - trailing length field size in bytes
|
|
||||||
* @param isLE - whether length and state words are encoded in little-endian
|
|
||||||
* @example
|
|
||||||
* Use a concrete subclass to get the shared Merkle-Damgard update/digest flow.
|
|
||||||
* ```ts
|
|
||||||
* import { _SHA1 } from '@noble/hashes/legacy.js';
|
|
||||||
* const hash = new _SHA1();
|
|
||||||
* hash.update(new Uint8Array([97, 98, 99]));
|
|
||||||
* hash.digest();
|
|
||||||
* ```
|
|
||||||
*/
|
|
||||||
export class HashMD {
|
|
||||||
blockLen;
|
|
||||||
outputLen;
|
|
||||||
canXOF = false;
|
|
||||||
padOffset;
|
|
||||||
isLE;
|
|
||||||
// For partial updates less than block size
|
|
||||||
buffer;
|
|
||||||
view;
|
|
||||||
finished = false;
|
|
||||||
length = 0;
|
|
||||||
pos = 0;
|
|
||||||
destroyed = false;
|
|
||||||
constructor(blockLen, outputLen, padOffset, isLE) {
|
|
||||||
this.blockLen = blockLen;
|
|
||||||
this.outputLen = outputLen;
|
|
||||||
this.padOffset = padOffset;
|
|
||||||
this.isLE = isLE;
|
|
||||||
this.buffer = new Uint8Array(blockLen);
|
|
||||||
this.view = createView(this.buffer);
|
|
||||||
}
|
|
||||||
update(data) {
|
|
||||||
aexists(this);
|
|
||||||
abytes(data);
|
|
||||||
const { view, buffer, blockLen } = this;
|
|
||||||
const len = data.length;
|
|
||||||
let processed = false;
|
|
||||||
for (let pos = 0; pos < len;) {
|
|
||||||
const take = Math.min(blockLen - this.pos, len - pos);
|
|
||||||
// Fast path only when there is no buffered partial block: `take === blockLen` implies
|
|
||||||
// `this.pos === 0`, so we can process full blocks directly from the input view.
|
|
||||||
if (take === blockLen) {
|
|
||||||
const dataView = createView(data);
|
|
||||||
for (; blockLen <= len - pos; pos += blockLen)
|
|
||||||
this.process(dataView, pos);
|
|
||||||
processed = true;
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
// When the whole input is buffered in one go (common for short messages), passing `data`
|
|
||||||
// directly avoids allocating a subarray view.
|
|
||||||
buffer.set(pos === 0 && take === len ? data : data.subarray(pos, pos + take), this.pos);
|
|
||||||
this.pos += take;
|
|
||||||
pos += take;
|
|
||||||
if (this.pos === blockLen) {
|
|
||||||
this.process(view, 0);
|
|
||||||
this.pos = 0;
|
|
||||||
processed = true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
this.length += data.length;
|
|
||||||
// Shared schedule buffers only pick up input-derived words inside process(); if everything
|
|
||||||
// was buffered without processing, there is nothing to zero.
|
|
||||||
if (processed)
|
|
||||||
this.roundClean();
|
|
||||||
return this;
|
|
||||||
}
|
|
||||||
digestInto(out) {
|
|
||||||
aexists(this);
|
|
||||||
aoutput(out, this);
|
|
||||||
this.finished = true;
|
|
||||||
// Padding
|
|
||||||
// We can avoid allocation of buffer for padding completely if it
|
|
||||||
// was previously not allocated here. But it won't change performance.
|
|
||||||
const { buffer, view, blockLen, isLE } = this;
|
|
||||||
let { pos } = this;
|
|
||||||
// append the bit '1' to the message, then zero-pad the rest of the block
|
|
||||||
buffer[pos++] = 0b10000000;
|
|
||||||
buffer.fill(0, pos);
|
|
||||||
// we have less than padOffset left in buffer, so we cannot put length in
|
|
||||||
// current block, need process it and pad again
|
|
||||||
if (this.padOffset > blockLen - pos) {
|
|
||||||
this.process(view, 0);
|
|
||||||
buffer.fill(0);
|
|
||||||
}
|
|
||||||
// `padOffset` reserves the whole length field. For SHA-384/512 the high 64 bits stay zero from
|
|
||||||
// the padding fill above, and JS will overflow before user input can make that half non-zero.
|
|
||||||
// So we only need to write the low 64 bits here (`length * 8` only scales the exponent of an
|
|
||||||
// integer below 2**53, so the split inside the helper stays exact).
|
|
||||||
setU64FromNum(view, blockLen - 8, this.length * 8, isLE);
|
|
||||||
this.process(view, 0);
|
|
||||||
// The final block above is processed outside update(), so the shared message-schedule
|
|
||||||
// buffers (e.g. SHA256_W) would otherwise retain input-derived words after digest().
|
|
||||||
this.roundClean();
|
|
||||||
// digest() passes our own `buffer` as `out`; reuse its cached view instead of allocating one.
|
|
||||||
const oview = out === buffer ? view : createView(out);
|
|
||||||
const len = this.outputLen;
|
|
||||||
// NOTE: we do division by 4 later, which must be fused in single op with modulo by JIT
|
|
||||||
const outLen = len / 4;
|
|
||||||
const state = this.get();
|
|
||||||
// Subclass-misconfiguration invariant: outputLen must be 32-bit aligned and fit the state.
|
|
||||||
if (len % 4 || outLen > state.length)
|
|
||||||
throw new Error('invalid outputLen');
|
|
||||||
for (let i = 0; i < outLen; i++)
|
|
||||||
oview.setUint32(4 * i, state[i], isLE);
|
|
||||||
}
|
|
||||||
digest() {
|
|
||||||
const { buffer, outputLen } = this;
|
|
||||||
this.digestInto(buffer);
|
|
||||||
// Copy before destroy(): subclasses wipe `buffer` during cleanup, but `digest()` must return
|
|
||||||
// fresh bytes to the caller.
|
|
||||||
const res = buffer.slice(0, outputLen);
|
|
||||||
this.destroy();
|
|
||||||
return res;
|
|
||||||
}
|
|
||||||
_cloneIntoMeta(to) {
|
|
||||||
const { buffer, length, finished, destroyed, pos } = this;
|
|
||||||
to.destroyed = destroyed;
|
|
||||||
to.finished = finished;
|
|
||||||
to.length = length;
|
|
||||||
to.pos = pos;
|
|
||||||
// Only partial-block bytes need copying: when `length % blockLen === 0`, `pos === 0` and
|
|
||||||
// later `update()` / `digestInto()` overwrite `to.buffer` from the start before reading it.
|
|
||||||
if (pos)
|
|
||||||
to.buffer.set(buffer); // Avoid a hot modulo guard.
|
|
||||||
return to;
|
|
||||||
}
|
|
||||||
clone() {
|
|
||||||
return this._cloneInto();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
/**
|
|
||||||
* Initial SHA-2 state: fractional parts of square roots of first 16 primes 2..53.
|
|
||||||
* Check out `test/misc/sha2-gen-iv.js` for recomputation guide.
|
|
||||||
*/
|
|
||||||
/** Initial SHA256 state from RFC 6234 §6.1: the first 32 bits of the fractional parts of the
|
|
||||||
* square roots of the first eight prime numbers. Exported as a shared table; callers must treat
|
|
||||||
* it as read-only because constructors copy words from it by index. */
|
|
||||||
export const SHA256_IV = /* @__PURE__ */ Uint32Array.from([
|
|
||||||
0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,
|
|
||||||
]);
|
|
||||||
/** Initial SHA224 state `H(0)` from RFC 6234 §6.1. Exported as a shared table; callers must
|
|
||||||
* treat it as read-only because constructors copy words from it by index. */
|
|
||||||
export const SHA224_IV = /* @__PURE__ */ Uint32Array.from([
|
|
||||||
0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4,
|
|
||||||
]);
|
|
||||||
/** Initial SHA384 state from RFC 6234 §6.3: eight RFC 64-bit `H(0)` words stored as sixteen
|
|
||||||
* big-endian 32-bit halves. Derived from the fractional parts of the square roots of the ninth
|
|
||||||
* through sixteenth prime numbers. Exported as a shared table; callers must treat it as read-only
|
|
||||||
* because constructors copy halves from it by index. */
|
|
||||||
export const SHA384_IV = /* @__PURE__ */ Uint32Array.from([
|
|
||||||
0xcbbb9d5d, 0xc1059ed8, 0x629a292a, 0x367cd507, 0x9159015a, 0x3070dd17, 0x152fecd8, 0xf70e5939,
|
|
||||||
0x67332667, 0xffc00b31, 0x8eb44a87, 0x68581511, 0xdb0c2e0d, 0x64f98fa7, 0x47b5481d, 0xbefa4fa4,
|
|
||||||
]);
|
|
||||||
/** Initial SHA512 state from RFC 6234 §6.3: eight RFC 64-bit `H(0)` words stored as sixteen
|
|
||||||
* big-endian 32-bit halves. Derived from the fractional parts of the square roots of the first
|
|
||||||
* eight prime numbers. Exported as a shared table; callers must treat it as read-only because
|
|
||||||
* constructors copy halves from it by index. */
|
|
||||||
export const SHA512_IV = /* @__PURE__ */ Uint32Array.from([
|
|
||||||
0x6a09e667, 0xf3bcc908, 0xbb67ae85, 0x84caa73b, 0x3c6ef372, 0xfe94f82b, 0xa54ff53a, 0x5f1d36f1,
|
|
||||||
0x510e527f, 0xade682d1, 0x9b05688c, 0x2b3e6c1f, 0x1f83d9ab, 0xfb41bd6b, 0x5be0cd19, 0x137e2179,
|
|
||||||
]);
|
|
||||||
|
|||||||
+3
-76
@@ -1,77 +1,4 @@
|
|||||||
const U32_MASK64 = /* @__PURE__ */ (() => BigInt(2 ** 32 - 1))();
|
// Stub placeholder for noble-hashes internal _u64 module
|
||||||
const _32n = /* @__PURE__ */ BigInt(32);
|
export function u64() {
|
||||||
// Split bigint into two 32-bit halves. With `le=true`, returned fields become `{ h: low, l: high
|
throw new Error("noble _u64 stub: not implemented");
|
||||||
// }` to match little-endian word order rather than the property names.
|
|
||||||
function fromBig(n, le = false) {
|
|
||||||
if (le)
|
|
||||||
return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) };
|
|
||||||
return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };
|
|
||||||
}
|
}
|
||||||
// Split bigint list into `[highWords, lowWords]` when `le=false`; with `le=true`, the first array
|
|
||||||
// holds the low halves because `fromBig(...)` swaps the semantic meaning of `h` and `l`.
|
|
||||||
function split(lst, le = false) {
|
|
||||||
const len = lst.length;
|
|
||||||
let Ah = new Uint32Array(len);
|
|
||||||
let Al = new Uint32Array(len);
|
|
||||||
for (let i = 0; i < len; i++) {
|
|
||||||
const { h, l } = fromBig(lst[i], le);
|
|
||||||
[Ah[i], Al[i]] = [h, l];
|
|
||||||
}
|
|
||||||
return [Ah, Al];
|
|
||||||
}
|
|
||||||
// Combine explicit `(high, low)` 32-bit halves into a bigint; `>>> 0` normalizes signed JS
|
|
||||||
// bitwise results back to uint32 first, and little-endian callers must swap.
|
|
||||||
const toBig = (h, l) => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0);
|
|
||||||
// Split a JS number into u32 halves without a BigInt allocation. Exact only for integers
|
|
||||||
// `0 <= n < 2**53`; callers use it on byte / bit counters, which JS length math caps far below
|
|
||||||
// that (an ArrayBuffer cannot exceed 2**53 - 1 bytes).
|
|
||||||
const fromNumH = (n) => (n / 2 ** 32) | 0;
|
|
||||||
const fromNumL = (n) => n >>> 0;
|
|
||||||
// Drop-in replacement for `view.setBigUint64(byteOffset, BigInt(n), isLE)` without the per-call
|
|
||||||
// BigInt allocation. Same `n < 2**53` precondition as `fromNumH`/`fromNumL`.
|
|
||||||
function setU64FromNum(view, byteOffset, n, isLE) {
|
|
||||||
const h = fromNumH(n);
|
|
||||||
const l = fromNumL(n);
|
|
||||||
view.setUint32(byteOffset, isLE ? l : h, isLE);
|
|
||||||
view.setUint32(byteOffset + 4, isLE ? h : l, isLE);
|
|
||||||
}
|
|
||||||
// High 32-bit half of a 64-bit logical right shift for `s` in `0..31`.
|
|
||||||
const shrSH = (h, _l, s) => h >>> s;
|
|
||||||
// Low 32-bit half of a 64-bit logical right shift, valid for `s` in `1..31`.
|
|
||||||
const shrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);
|
|
||||||
// High 32-bit half of a 64-bit right rotate, valid for `s` in `1..31`.
|
|
||||||
const rotrSH = (h, l, s) => (h >>> s) | (l << (32 - s));
|
|
||||||
// Low 32-bit half of a 64-bit right rotate, valid for `s` in `1..31`.
|
|
||||||
const rotrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);
|
|
||||||
// High 32-bit half of a 64-bit right rotate, valid for `s` in `33..63`; `32` uses `rotr32*`.
|
|
||||||
const rotrBH = (h, l, s) => (h << (64 - s)) | (l >>> (s - 32));
|
|
||||||
// Low 32-bit half of a 64-bit right rotate, valid for `s` in `33..63`; `32` uses `rotr32*`.
|
|
||||||
const rotrBL = (h, l, s) => (h >>> (s - 32)) | (l << (64 - s));
|
|
||||||
// High 32-bit half of a 64-bit right rotate for `s === 32`; this is just the swapped low half.
|
|
||||||
const rotr32H = (_h, l) => l;
|
|
||||||
// Low 32-bit half of a 64-bit right rotate for `s === 32`; this is just the swapped high half.
|
|
||||||
const rotr32L = (h, _l) => h;
|
|
||||||
// 64-bit left rotates (rotl*) are not defined here: sha3.ts, their only consumer, keeps
|
|
||||||
// local copies so V8 inlines them into keccakP.
|
|
||||||
// Add two split 64-bit words and return the split `{ h, l }` sum.
|
|
||||||
// JS uses 32-bit signed integers for bitwise operations, so we cannot simply shift the carry out
|
|
||||||
// of the low sum and instead use division.
|
|
||||||
function add(Ah, Al, Bh, Bl) {
|
|
||||||
const l = (Al >>> 0) + (Bl >>> 0);
|
|
||||||
return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 };
|
|
||||||
}
|
|
||||||
// Addition with more than 2 elements
|
|
||||||
// Unmasked low-word accumulator for 3-way addition; pass the raw result into `add3H(...)`.
|
|
||||||
const add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);
|
|
||||||
// High-word finalize step for 3-way addition; `low` must be the untruncated output of `add3L(...)`.
|
|
||||||
const add3H = (low, Ah, Bh, Ch) => (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0;
|
|
||||||
// Unmasked low-word accumulator for 4-way addition; pass the raw result into `add4H(...)`.
|
|
||||||
const add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);
|
|
||||||
// High-word finalize step for 4-way addition; `low` must be the untruncated output of `add4L(...)`.
|
|
||||||
const add4H = (low, Ah, Bh, Ch, Dh) => (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0;
|
|
||||||
// Unmasked low-word accumulator for 5-way addition; pass the raw result into `add5H(...)`.
|
|
||||||
const add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);
|
|
||||||
// High-word finalize step for 5-way addition; `low` must be the untruncated output of `add5L(...)`.
|
|
||||||
const add5H = (low, Ah, Bh, Ch, Dh, Eh) => (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0;
|
|
||||||
// prettier-ignore
|
|
||||||
export { add, add3H, add3L, add4H, add4L, add5H, add5L, fromBig, fromNumH, fromNumL, rotr32H, rotr32L, rotrBH, rotrBL, rotrSH, rotrSL, setU64FromNum, shrSH, shrSL, split, toBig };
|
|
||||||
|
|||||||
+3
-576
@@ -1,577 +1,4 @@
|
|||||||
/**
|
// Stub placeholder for noble-hashes argon2 module
|
||||||
* Argon2 KDF from RFC 9106. Can be used to create a key from password and salt.
|
export function argon2(data) {
|
||||||
* We suggest to use Scrypt. JS Argon is 2-10x slower than native code because of 64-bitness:
|
throw new Error("noble argon2 stub: not implemented");
|
||||||
* * argon uses uint64, but JS doesn't have fast uint64array
|
|
||||||
* * uint64 multiplication is 1/3 of time
|
|
||||||
* * `P` function would be very nice with u64, because most of value will be in registers,
|
|
||||||
* hovewer with u32 it will require 32 registers, which is too much.
|
|
||||||
* * JS arrays do slow bound checks, so reading from `A2_BUF` slows it down
|
|
||||||
* @module
|
|
||||||
*/
|
|
||||||
import { blake2b } from "./blake2.js";
|
|
||||||
import { anumber, checkOpts, clean, kdfInputToBytes, nextTick, swap32IfBE, swap8IfBE, u32, u8, } from "./utils.js";
|
|
||||||
// RFC 9106 §3.1 type `y`: 0 = Argon2d, 1 = Argon2i, 2 = Argon2id. The numeric values are the
|
|
||||||
// spec-bound part here; the object keys are internal labels.
|
|
||||||
const AT = { Argon2d: 0, Argon2i: 1, Argon2id: 2 };
|
|
||||||
// RFC 9106 sync points constant `SL = 4`, fixed by the design rather than exposed as a tuning knob.
|
|
||||||
const ARGON2_SYNC_POINTS = 4;
|
|
||||||
// Preserve Argon2's `LE32(len(X)) || X` encoding for omitted
|
|
||||||
// optional fields by emitting empty bytes.
|
|
||||||
const abytesOrZero = (buf, errorTitle = '') => {
|
|
||||||
if (buf === undefined)
|
|
||||||
return Uint8Array.of();
|
|
||||||
return kdfInputToBytes(buf, errorTitle);
|
|
||||||
};
|
|
||||||
// Temporary block buffer.
|
|
||||||
// 1024-byte block: 256 u32 = 128 interleaved low/high halves = RFC's
|
|
||||||
// 8x8 matrix of 16-byte registers.
|
|
||||||
const A2_BUF = new Uint32Array(256);
|
|
||||||
// Quarter-round over 64-bit word indices into `A2_BUF`; each index maps to adjacent low/high u32s.
|
|
||||||
// Each BlaMka step `X = X + Y + 2 * trunc(X) * trunc(Y)` (trunc = low 32 bits) starts
|
|
||||||
// with an exact low product from `Math.imul`. The rounded double product is within 1024 of the
|
|
||||||
// exact u64 product; subtracting that exact low half and rounding to the nearest multiple of
|
|
||||||
// 2^32 therefore recovers the exact high half. RFC 9106 Figure 19 GB then rotates by 32, 24,
|
|
||||||
// 16, and 63 bits after each XOR.
|
|
||||||
function G(a, b, c, d) {
|
|
||||||
let Al = A2_BUF[2 * a], Ah = A2_BUF[2 * a + 1]; // prettier-ignore
|
|
||||||
let Bl = A2_BUF[2 * b], Bh = A2_BUF[2 * b + 1]; // prettier-ignore
|
|
||||||
let Cl = A2_BUF[2 * c], Ch = A2_BUF[2 * c + 1]; // prettier-ignore
|
|
||||||
let Dl = A2_BUF[2 * d], Dh = A2_BUF[2 * d + 1]; // prettier-ignore
|
|
||||||
let ml = 0, mh = 0, rl = 0, xh = 0, xl = 0; // prettier-ignore
|
|
||||||
// A = blamka(A, B); D = rotr64(D ^ A, 32)
|
|
||||||
ml = Math.imul(Al, Bl);
|
|
||||||
mh = (((Al >>> 0) * (Bl >>> 0) - (ml >>> 0)) / 0x100000000 + 0.5) | 0; // prettier-ignore
|
|
||||||
rl = (Al >>> 0) + (Bl >>> 0) + ((ml << 1) >>> 0);
|
|
||||||
Ah = (Ah + Bh + ((mh << 1) | (ml >>> 31)) + ((rl / 0x100000000) | 0)) | 0;
|
|
||||||
Al = rl | 0; // prettier-ignore
|
|
||||||
xh = Dh ^ Ah;
|
|
||||||
xl = Dl ^ Al; // prettier-ignore
|
|
||||||
Dh = xl;
|
|
||||||
Dl = xh; // prettier-ignore
|
|
||||||
// C = blamka(C, D); B = rotr64(B ^ C, 24)
|
|
||||||
ml = Math.imul(Cl, Dl);
|
|
||||||
mh = (((Cl >>> 0) * (Dl >>> 0) - (ml >>> 0)) / 0x100000000 + 0.5) | 0; // prettier-ignore
|
|
||||||
rl = (Cl >>> 0) + (Dl >>> 0) + ((ml << 1) >>> 0);
|
|
||||||
Ch = (Ch + Dh + ((mh << 1) | (ml >>> 31)) + ((rl / 0x100000000) | 0)) | 0;
|
|
||||||
Cl = rl | 0; // prettier-ignore
|
|
||||||
xh = Bh ^ Ch;
|
|
||||||
xl = Bl ^ Cl; // prettier-ignore
|
|
||||||
Bh = (xh >>> 24) | (xl << 8);
|
|
||||||
Bl = (xh << 8) | (xl >>> 24); // prettier-ignore
|
|
||||||
// A = blamka(A, B); D = rotr64(D ^ A, 16)
|
|
||||||
ml = Math.imul(Al, Bl);
|
|
||||||
mh = (((Al >>> 0) * (Bl >>> 0) - (ml >>> 0)) / 0x100000000 + 0.5) | 0; // prettier-ignore
|
|
||||||
rl = (Al >>> 0) + (Bl >>> 0) + ((ml << 1) >>> 0);
|
|
||||||
Ah = (Ah + Bh + ((mh << 1) | (ml >>> 31)) + ((rl / 0x100000000) | 0)) | 0;
|
|
||||||
Al = rl | 0; // prettier-ignore
|
|
||||||
xh = Dh ^ Ah;
|
|
||||||
xl = Dl ^ Al; // prettier-ignore
|
|
||||||
Dh = (xh >>> 16) | (xl << 16);
|
|
||||||
Dl = (xh << 16) | (xl >>> 16); // prettier-ignore
|
|
||||||
// C = blamka(C, D); B = rotr64(B ^ C, 63)
|
|
||||||
ml = Math.imul(Cl, Dl);
|
|
||||||
mh = (((Cl >>> 0) * (Dl >>> 0) - (ml >>> 0)) / 0x100000000 + 0.5) | 0; // prettier-ignore
|
|
||||||
rl = (Cl >>> 0) + (Dl >>> 0) + ((ml << 1) >>> 0);
|
|
||||||
Ch = (Ch + Dh + ((mh << 1) | (ml >>> 31)) + ((rl / 0x100000000) | 0)) | 0;
|
|
||||||
Cl = rl | 0; // prettier-ignore
|
|
||||||
xh = Bh ^ Ch;
|
|
||||||
xl = Bl ^ Cl; // prettier-ignore
|
|
||||||
Bh = (xh << 1) | (xl >>> 31);
|
|
||||||
Bl = (xh >>> 31) | (xl << 1); // prettier-ignore
|
|
||||||
((A2_BUF[2 * a] = Al), (A2_BUF[2 * a + 1] = Ah));
|
|
||||||
((A2_BUF[2 * b] = Bl), (A2_BUF[2 * b + 1] = Bh));
|
|
||||||
((A2_BUF[2 * c] = Cl), (A2_BUF[2 * c + 1] = Ch));
|
|
||||||
((A2_BUF[2 * d] = Dl), (A2_BUF[2 * d + 1] = Dh));
|
|
||||||
}
|
}
|
||||||
// Argon2 permutation over 16 register indices into `A2_BUF`, not the register values themselves.
|
|
||||||
// RFC 9106 Figure 17: these arguments are the 16 `v0..v15` 64-bit word
|
|
||||||
// indices inside eight 16-byte inputs, not copied word values.
|
|
||||||
// prettier-ignore
|
|
||||||
function P(v00, v01, v02, v03, v04, v05, v06, v07, v08, v09, v10, v11, v12, v13, v14, v15) {
|
|
||||||
// RFC 9106 Figure 18: first apply GB across rows, then across columns of the 8x8 register matrix.
|
|
||||||
G(v00, v04, v08, v12);
|
|
||||||
G(v01, v05, v09, v13);
|
|
||||||
G(v02, v06, v10, v14);
|
|
||||||
G(v03, v07, v11, v15);
|
|
||||||
G(v00, v05, v10, v15);
|
|
||||||
G(v01, v06, v11, v12);
|
|
||||||
G(v02, v07, v08, v13);
|
|
||||||
G(v03, v04, v09, v14);
|
|
||||||
}
|
|
||||||
function block(x, xPos, yPos, outPos, needXor) {
|
|
||||||
// Stage R = X xor Y in the destination before permuting it. This avoids rereading both source
|
|
||||||
// blocks when folding R into the permuted scratch block below.
|
|
||||||
if (needXor) {
|
|
||||||
for (let i = 0; i < 256; i++) {
|
|
||||||
const r = x[xPos + i] ^ x[yPos + i];
|
|
||||||
A2_BUF[i] = r;
|
|
||||||
x[outPos + i] ^= r;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
for (let i = 0; i < 256; i++) {
|
|
||||||
const r = x[xPos + i] ^ x[yPos + i];
|
|
||||||
A2_BUF[i] = r;
|
|
||||||
x[outPos + i] = r;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// rows (8 consecutive 16-register groups)
|
|
||||||
for (let i = 0; i < 128; i += 16) {
|
|
||||||
// prettier-ignore
|
|
||||||
P(i, i + 1, i + 2, i + 3, i + 4, i + 5, i + 6, i + 7, i + 8, i + 9, i + 10, i + 11, i + 12, i + 13, i + 14, i + 15);
|
|
||||||
}
|
|
||||||
// columns (8 strided 16-register groups)
|
|
||||||
for (let i = 0; i < 16; i += 2) {
|
|
||||||
// prettier-ignore
|
|
||||||
P(i, i + 1, i + 16, i + 17, i + 32, i + 33, i + 48, i + 49, i + 64, i + 65, i + 80, i + 81, i + 96, i + 97, i + 112, i + 113);
|
|
||||||
}
|
|
||||||
// RFC 9106 step 6: passes after the first XOR the old destination block into the new G(X, Y).
|
|
||||||
for (let i = 0; i < 256; i++)
|
|
||||||
x[outPos + i] ^= A2_BUF[i];
|
|
||||||
clean(A2_BUF);
|
|
||||||
}
|
|
||||||
// Variable-Length Hash Function H'
|
|
||||||
// Returns bytes, not words; 1024-byte block callers explicitly reinterpret with `u32(...)`.
|
|
||||||
function Hp(A, dkLen) {
|
|
||||||
const A8 = u8(A);
|
|
||||||
const T = new Uint32Array(1);
|
|
||||||
const T8 = u8(T);
|
|
||||||
// Argon2 H' prefixes dkLen as LE32; native Uint32Array writes would serialize as BE on s390x.
|
|
||||||
T[0] = swap8IfBE(dkLen);
|
|
||||||
// Fast path
|
|
||||||
if (dkLen <= 64)
|
|
||||||
return blake2b.create({ dkLen }).update(T8).update(A8).digest();
|
|
||||||
const out = new Uint8Array(dkLen);
|
|
||||||
let V = blake2b.create({}).update(T8).update(A8).digest();
|
|
||||||
let pos = 0;
|
|
||||||
// RFC 9106 Figure 8: each intermediate `V_i` contributes only `W_i`, its first 32 bytes; only
|
|
||||||
// `V_{r+1}` is emitted in full at the remaining length.
|
|
||||||
out.set(V.subarray(0, 32));
|
|
||||||
pos += 32;
|
|
||||||
// Rest blocks
|
|
||||||
for (; dkLen - pos > 64; pos += 32) {
|
|
||||||
const Vh = blake2b.create({}).update(V);
|
|
||||||
Vh.digestInto(V);
|
|
||||||
Vh.destroy();
|
|
||||||
out.set(V.subarray(0, 32), pos);
|
|
||||||
}
|
|
||||||
// Last block
|
|
||||||
out.set(blake2b(V, { dkLen: dkLen - pos }), pos);
|
|
||||||
clean(V, T);
|
|
||||||
// H' is byte-oriented; returning `u32(out)` would silently drop dkLen % 4 tail bytes.
|
|
||||||
return out;
|
|
||||||
}
|
|
||||||
// Used only inside argon2Blocks!
|
|
||||||
function indexAlpha(r, s, laneLen, segmentLen, index, randL, sameLane = false) {
|
|
||||||
// RFC 9106 §3.4.2 Figures 12-13: map `J1` / `J2` into the current lane's reference area `W`.
|
|
||||||
let area;
|
|
||||||
if (r === 0) {
|
|
||||||
if (s === 0)
|
|
||||||
area = index - 1;
|
|
||||||
else if (sameLane)
|
|
||||||
area = s * segmentLen + index - 1;
|
|
||||||
else
|
|
||||||
area = s * segmentLen + (index == 0 ? -1 : 0);
|
|
||||||
}
|
|
||||||
else if (sameLane)
|
|
||||||
area = laneLen - segmentLen + index - 1;
|
|
||||||
else
|
|
||||||
area = laneLen - segmentLen + (index == 0 ? -1 : 0);
|
|
||||||
const startPos = r !== 0 && s !== ARGON2_SYNC_POINTS - 1 ? (s + 1) * segmentLen : 0;
|
|
||||||
// Use the same exact-high recovery as G. `areaHigh` is floor(|W| * J1^2/2^32 / 2^32).
|
|
||||||
const randLow = Math.imul(randL, randL);
|
|
||||||
const randHigh = (((randL >>> 0) * (randL >>> 0) - (randLow >>> 0)) / 0x100000000 + 0.5) | 0;
|
|
||||||
const areaLow = Math.imul(area, randHigh);
|
|
||||||
const areaHigh = (((area >>> 0) * (randHigh >>> 0) - (areaLow >>> 0)) / 0x100000000 + 0.5) | 0;
|
|
||||||
const rel = area - 1 - areaHigh;
|
|
||||||
return (startPos + rel) % laneLen;
|
|
||||||
}
|
|
||||||
// Exclusive `2^32` sentinel used by `isU32(...)`, not the inclusive maximum u32 value.
|
|
||||||
const maxUint32 = Math.pow(2, 32);
|
|
||||||
const ARGON2_DEFAULT_MEMORY = 1024 ** 2; // KiB: 1 GiB
|
|
||||||
const ARGON2_DEFAULT_MAXMEM = ARGON2_DEFAULT_MEMORY * 1024;
|
|
||||||
// Validate safe JS integers in `[0, 2^32 - 1]`.
|
|
||||||
function isU32(num) {
|
|
||||||
return Number.isSafeInteger(num) && num >= 0 && num < maxUint32;
|
|
||||||
}
|
|
||||||
function argon2Opts(opts = {}) {
|
|
||||||
opts = checkOpts({}, opts);
|
|
||||||
const merged = {
|
|
||||||
t: 3,
|
|
||||||
m: ARGON2_DEFAULT_MEMORY,
|
|
||||||
p: 1,
|
|
||||||
version: 0x13,
|
|
||||||
dkLen: 32,
|
|
||||||
maxmem: ARGON2_DEFAULT_MAXMEM,
|
|
||||||
asyncTick: 10,
|
|
||||||
};
|
|
||||||
// Unknown keys are copied through unchanged here and later ignored unless
|
|
||||||
// destructuring consumes them.
|
|
||||||
for (let [k, v] of Object.entries(opts))
|
|
||||||
if (v !== undefined)
|
|
||||||
merged[k] = v;
|
|
||||||
const { dkLen, p, m, t, version, onProgress, asyncTick } = merged;
|
|
||||||
// RFC 9106 §3.1: tag length `T` MUST be an integer number of bytes from 4 to 2^32-1.
|
|
||||||
if (!isU32(dkLen) || dkLen < 4)
|
|
||||||
throw new Error('"dkLen" must be 4..');
|
|
||||||
if (!isU32(p) || p < 1 || p >= Math.pow(2, 24))
|
|
||||||
throw new Error('"p" must be 1..2^24');
|
|
||||||
if (!isU32(m))
|
|
||||||
throw new Error('"m" must be 0..2^32');
|
|
||||||
if (!isU32(t) || t < 1)
|
|
||||||
throw new Error('"t" (iterations) must be 1..2^32');
|
|
||||||
if (onProgress !== undefined && typeof onProgress !== 'function')
|
|
||||||
throw new Error('"onProgress" must be a function');
|
|
||||||
anumber(asyncTick, 'asyncTick');
|
|
||||||
/*
|
|
||||||
Memory size m MUST be an integer number of kibibytes from 8*p
|
|
||||||
to 2^(32)-1. The actual number of blocks is m', which is m
|
|
||||||
rounded down to the nearest multiple of 4*p.
|
|
||||||
*/
|
|
||||||
if (!isU32(m) || m < 8 * p)
|
|
||||||
throw new Error('"m" (memory) must be at least 8*p bytes');
|
|
||||||
// Accept legacy `0x10` for compatibility even though RFC 9106 profiles standardize `0x13`.
|
|
||||||
if (version !== 0x10 && version !== 0x13)
|
|
||||||
throw new Error('"version" must be 0x10 or 0x13, got ' + version);
|
|
||||||
return merged;
|
|
||||||
}
|
|
||||||
function argon2InitialHash(password, salt, type, opts) {
|
|
||||||
const ownedInputs = [];
|
|
||||||
const BUF = new Uint32Array(1);
|
|
||||||
const BUF8 = u8(BUF);
|
|
||||||
let h;
|
|
||||||
let H0;
|
|
||||||
let succeeded = false;
|
|
||||||
const rememberOwned = (input, bytes) => {
|
|
||||||
if (typeof input === 'string')
|
|
||||||
ownedInputs.push(bytes);
|
|
||||||
return bytes;
|
|
||||||
};
|
|
||||||
try {
|
|
||||||
const passwordBytes = rememberOwned(password, kdfInputToBytes(password, 'password'));
|
|
||||||
const saltBytes = rememberOwned(salt, kdfInputToBytes(salt, 'salt'));
|
|
||||||
if (!isU32(passwordBytes.length))
|
|
||||||
throw new Error('"password" must be less of length 1..4Gb');
|
|
||||||
// RFC 9106 §3.1 only requires S <= 2^32-1 bytes and says 16 bytes is RECOMMENDED for password
|
|
||||||
// hashing; this library intentionally takes the stricter common >=8-byte salt path.
|
|
||||||
if (!isU32(saltBytes.length) || saltBytes.length < 8)
|
|
||||||
throw new Error('"salt" must be of length 8..4Gb');
|
|
||||||
if (!Object.values(AT).includes(type))
|
|
||||||
throw new Error('"type" was invalid');
|
|
||||||
let { p, dkLen, m, t, version, key, personalization, maxmem, onProgress, asyncTick } = argon2Opts(opts);
|
|
||||||
// Validation
|
|
||||||
const keyInput = key;
|
|
||||||
key = rememberOwned(keyInput, abytesOrZero(keyInput, 'key'));
|
|
||||||
const personalizationInput = personalization;
|
|
||||||
personalization = rememberOwned(personalizationInput, abytesOrZero(personalizationInput, 'personalization'));
|
|
||||||
// H_0 = H^(64)(LE32(p) || LE32(T) || LE32(m) || LE32(t) ||
|
|
||||||
// LE32(v) || LE32(y) || LE32(length(P)) || P ||
|
|
||||||
// LE32(length(S)) || S || LE32(length(K)) || K ||
|
|
||||||
// LE32(length(X)) || X)
|
|
||||||
h = blake2b.create();
|
|
||||||
for (let item of [p, dkLen, m, t, version, type]) {
|
|
||||||
// RFC 9106 H0 encodes these scalars as LE32, so normalize the host word before
|
|
||||||
// exposing bytes.
|
|
||||||
BUF[0] = swap8IfBE(item);
|
|
||||||
h.update(BUF8);
|
|
||||||
}
|
|
||||||
for (let i of [passwordBytes, saltBytes, key, personalization]) {
|
|
||||||
BUF[0] = swap8IfBE(i.length); // BUF is u32 array, this is valid once normalized to LE bytes
|
|
||||||
h.update(BUF8).update(i);
|
|
||||||
}
|
|
||||||
// Reserve two extra LE32 words after the 64-byte `H_0` so Figures 3-4 can append
|
|
||||||
// `LE32(0 or 1) || LE32(i)` in place for the lane-starting blocks.
|
|
||||||
H0 = new Uint32Array(18);
|
|
||||||
h.digestInto(u8(H0));
|
|
||||||
succeeded = true;
|
|
||||||
return { H0, p, dkLen, m, t, version, maxmem, onProgress, asyncTick };
|
|
||||||
}
|
|
||||||
finally {
|
|
||||||
// digestInto() does not destroy BLAKE2 state. It and all string-derived inputs contain secrets.
|
|
||||||
if (h)
|
|
||||||
h.destroy();
|
|
||||||
clean(BUF, ...ownedInputs);
|
|
||||||
if (!succeeded && H0)
|
|
||||||
clean(H0);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
function argon2Init(password, salt, type, opts) {
|
|
||||||
const { H0, p, dkLen, m, t, version, maxmem, onProgress, asyncTick } = argon2InitialHash(password, salt, type, opts);
|
|
||||||
// 256 u32 = 1024 (BLOCK_SIZE), fills A2_BUF on processing
|
|
||||||
try {
|
|
||||||
// Params
|
|
||||||
const lanes = p;
|
|
||||||
// m' = 4 * p * floor (m / 4p)
|
|
||||||
const mP = 4 * p * Math.floor(m / (ARGON2_SYNC_POINTS * p));
|
|
||||||
//q = m' / p columns
|
|
||||||
const laneLen = Math.floor(mP / p);
|
|
||||||
const segmentLen = Math.floor(laneLen / ARGON2_SYNC_POINTS);
|
|
||||||
// `maxmem` is documented in bytes; compare against the actual 1024-byte block allocation.
|
|
||||||
const memUsed = mP * 1024;
|
|
||||||
if (!isU32(maxmem))
|
|
||||||
throw new Error('"maxmem" expected <2**32, got ' + maxmem);
|
|
||||||
if (memUsed > maxmem)
|
|
||||||
throw new Error('"maxmem" limit was hit: memUsed(mP*1024)=' + memUsed + ', maxmem=' + maxmem);
|
|
||||||
const B = new Uint32Array(memUsed / 4);
|
|
||||||
// Fill first blocks
|
|
||||||
for (let l = 0; l < p; l++) {
|
|
||||||
const i = 256 * laneLen * l;
|
|
||||||
// B[i][0] = H'^(1024)(H_0 || LE32(0) || LE32(i))
|
|
||||||
H0[17] = swap8IfBE(l);
|
|
||||||
H0[16] = swap8IfBE(0);
|
|
||||||
B.set(swap32IfBE(u32(Hp(H0, 1024))), i);
|
|
||||||
// B[i][1] = H'^(1024)(H_0 || LE32(1) || LE32(i))
|
|
||||||
H0[16] = swap8IfBE(1);
|
|
||||||
B.set(swap32IfBE(u32(Hp(H0, 1024))), i + 256);
|
|
||||||
}
|
|
||||||
let perBlock = () => { };
|
|
||||||
if (onProgress) {
|
|
||||||
// The first segment of the first pass skips two preinitialized blocks per lane.
|
|
||||||
const totalBlock = t * ARGON2_SYNC_POINTS * p * segmentLen - 2 * p;
|
|
||||||
// Invoke callback if progress changes from 10.01 to 10.02
|
|
||||||
// Allows to draw smooth progress bar on up to 8K screen
|
|
||||||
const callbackPer = Math.max(Math.floor(totalBlock / 10000), 1);
|
|
||||||
let blockCnt = 0;
|
|
||||||
perBlock = () => {
|
|
||||||
blockCnt++;
|
|
||||||
if (onProgress && (!(blockCnt % callbackPer) || blockCnt === totalBlock))
|
|
||||||
onProgress(blockCnt / totalBlock);
|
|
||||||
};
|
|
||||||
}
|
|
||||||
return { type, mP, p, t, version, B, laneLen, lanes, segmentLen, dkLen, perBlock, asyncTick };
|
|
||||||
}
|
|
||||||
finally {
|
|
||||||
clean(H0);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
function argon2Output(B, p, laneLen, dkLen) {
|
|
||||||
const B_final = new Uint32Array(256);
|
|
||||||
for (let l = 0; l < p; l++)
|
|
||||||
for (let j = 0; j < 256; j++)
|
|
||||||
B_final[j] ^= B[256 * (laneLen * l + laneLen - 1) + j];
|
|
||||||
// RFC 9106 steps 7-8 feed the byte string `C` into `H'^T(C)`, so normalize the xor'ed words
|
|
||||||
// back to spec byte order before `Hp(...)` reinterprets them as bytes.
|
|
||||||
const res = Hp(swap32IfBE(B_final), dkLen);
|
|
||||||
// Wipe both the xor scratch and the full working matrix once final digest bytes exist.
|
|
||||||
// JS cleanup is still only best-effort, but this local buffer is no longer needed here.
|
|
||||||
clean(B, B_final);
|
|
||||||
return res;
|
|
||||||
}
|
|
||||||
/**
|
|
||||||
* Fills every Argon2 block for all passes / slices / lanes, yielding once per
|
|
||||||
* processed block so callers control pacing: the sync driver just drains the
|
|
||||||
* generator, while the async driver awaits `nextTick()` between time slices.
|
|
||||||
*/
|
|
||||||
function* argon2Blocks(ctx, address) {
|
|
||||||
const { type, mP, p, t, version, B, laneLen, lanes, segmentLen, perBlock } = ctx;
|
|
||||||
// [address, input, zero_block] format so we can pass single U32 to block function
|
|
||||||
address[256 + 6] = mP;
|
|
||||||
address[256 + 8] = t;
|
|
||||||
address[256 + 10] = type;
|
|
||||||
for (let r = 0; r < t; r++) {
|
|
||||||
// RFC 9106 step 6 applies the XOR-on-later-passes rule only for version `0x13`; legacy
|
|
||||||
// `0x10` keeps the older overwrite behavior used by the v16 test vectors.
|
|
||||||
const needXor = r !== 0 && version === 0x13;
|
|
||||||
address[256 + 0] = r;
|
|
||||||
for (let s = 0; s < ARGON2_SYNC_POINTS; s++) {
|
|
||||||
address[256 + 4] = s;
|
|
||||||
// RFC 9106 §3.4.1.3: Argon2id uses Argon2i's data-independent `J1` / `J2` generation only
|
|
||||||
// in pass 0, slices 0 and 1; Argon2i uses it in every segment.
|
|
||||||
const dataIndependent = type == AT.Argon2i || (type == AT.Argon2id && r === 0 && s < 2);
|
|
||||||
for (let l = 0; l < p; l++) {
|
|
||||||
address[256 + 2] = l;
|
|
||||||
address[256 + 12] = 0;
|
|
||||||
let startPos = 0;
|
|
||||||
if (r === 0 && s === 0) {
|
|
||||||
startPos = 2;
|
|
||||||
if (dataIndependent) {
|
|
||||||
address[256 + 12]++;
|
|
||||||
block(address, 256, 2 * 256, 0, false);
|
|
||||||
block(address, 0, 2 * 256, 0, false);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// current block position
|
|
||||||
let offset = l * laneLen + s * segmentLen + startPos;
|
|
||||||
for (let index = startPos; index < segmentLen; index++, offset++) {
|
|
||||||
perBlock();
|
|
||||||
// Previous block position: wraps to the lane's last block only at lane start,
|
|
||||||
// which can happen here only for the first block of slice 0 on passes > 0.
|
|
||||||
const prev = offset % laneLen ? offset - 1 : offset + laneLen - 1;
|
|
||||||
let randL, randH;
|
|
||||||
if (dataIndependent) {
|
|
||||||
let i128 = index % 128;
|
|
||||||
// RFC 9106 §3.4.1.2: each 1024-byte address block yields 128 `(J1, J2)` pairs, so
|
|
||||||
// regenerate it whenever the segment index crosses a multiple of 128.
|
|
||||||
if (i128 === 0) {
|
|
||||||
address[256 + 12]++;
|
|
||||||
block(address, 256, 2 * 256, 0, false);
|
|
||||||
block(address, 0, 2 * 256, 0, false);
|
|
||||||
}
|
|
||||||
randL = address[2 * i128];
|
|
||||||
randH = address[2 * i128 + 1];
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
const T = 256 * prev;
|
|
||||||
randL = B[T];
|
|
||||||
randH = B[T + 1];
|
|
||||||
}
|
|
||||||
// Address-block path selects `J1` / `J2`, then maps them to the reference
|
|
||||||
// lane/block per RFC 9106 §3.4.
|
|
||||||
const refLane = r === 0 && s === 0 ? l : randH % lanes;
|
|
||||||
const refPos = indexAlpha(r, s, laneLen, segmentLen, index, randL, refLane == l);
|
|
||||||
const refBlock = laneLen * refLane + refPos;
|
|
||||||
// B[i][j] = G(B[i][j-1], B[l][z])
|
|
||||||
block(B, 256 * prev, 256 * refBlock, offset * 256, needXor);
|
|
||||||
yield;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
clean(address);
|
|
||||||
}
|
|
||||||
function argon2(type, password, salt, opts) {
|
|
||||||
const ctx = argon2Init(password, salt, type, opts);
|
|
||||||
const blocks = argon2Blocks(ctx, new Uint32Array(3 * 256));
|
|
||||||
while (!blocks.next().done) { }
|
|
||||||
return argon2Output(ctx.B, ctx.p, ctx.laneLen, ctx.dkLen);
|
|
||||||
}
|
|
||||||
/**
|
|
||||||
* Argon2d GPU-resistant version.
|
|
||||||
* @param password - password or input key material
|
|
||||||
* @param salt - unique salt value
|
|
||||||
* @param opts - Argon2 cost and optional tuning parameters. See {@link ArgonOpts}.
|
|
||||||
* @returns Derived key bytes.
|
|
||||||
* @throws If the Argon2 input or cost parameters are invalid. {@link Error}
|
|
||||||
* @example
|
|
||||||
* Derive a key with Argon2d.
|
|
||||||
* ```ts
|
|
||||||
* argon2d('password', 'salt1234', { t: 1, m: 8, p: 1, dkLen: 32 });
|
|
||||||
* ```
|
|
||||||
* @example
|
|
||||||
* Derive a key with optional secret and scheduler controls.
|
|
||||||
* ```ts
|
|
||||||
* const progressLog: number[] = [];
|
|
||||||
* argon2d('password', 'salt1234', {
|
|
||||||
* t: 1,
|
|
||||||
* m: 8,
|
|
||||||
* p: 1,
|
|
||||||
* dkLen: 32,
|
|
||||||
* version: 0x13,
|
|
||||||
* key: 'secret',
|
|
||||||
* personalization: 'application',
|
|
||||||
* maxmem: 1024 * 1024,
|
|
||||||
* asyncTick: 1,
|
|
||||||
* onProgress(progress) {
|
|
||||||
* progressLog.push(progress);
|
|
||||||
* },
|
|
||||||
* });
|
|
||||||
* ```
|
|
||||||
*/
|
|
||||||
export const argon2d = (password, salt, opts = {}) => argon2(AT.Argon2d, password, salt, opts);
|
|
||||||
/**
|
|
||||||
* Argon2i side-channel-resistant version.
|
|
||||||
* @param password - password or input key material
|
|
||||||
* @param salt - unique salt value
|
|
||||||
* @param opts - Argon2 cost and optional tuning parameters. See {@link ArgonOpts}.
|
|
||||||
* @returns Derived key bytes.
|
|
||||||
* @throws If the Argon2 input or cost parameters are invalid. {@link Error}
|
|
||||||
* @example
|
|
||||||
* Derive a key with Argon2i.
|
|
||||||
* ```ts
|
|
||||||
* argon2i('password', 'salt1234', { t: 1, m: 8, p: 1, dkLen: 32 });
|
|
||||||
* ```
|
|
||||||
*/
|
|
||||||
export const argon2i = (password, salt, opts = {}) => argon2(AT.Argon2i, password, salt, opts);
|
|
||||||
/**
|
|
||||||
* Argon2id, combining i+d, the most popular version from RFC 9106.
|
|
||||||
* @param password - password or input key material
|
|
||||||
* @param salt - unique salt value
|
|
||||||
* @param opts - Argon2 cost and optional tuning parameters. See {@link ArgonOpts}.
|
|
||||||
* @returns Derived key bytes.
|
|
||||||
* @throws If the Argon2 input or cost parameters are invalid. {@link Error}
|
|
||||||
* @example
|
|
||||||
* Derive a key with Argon2id.
|
|
||||||
* ```ts
|
|
||||||
* argon2id('password', 'salt1234', { t: 1, m: 8, p: 1, dkLen: 32 });
|
|
||||||
* ```
|
|
||||||
*/
|
|
||||||
export const argon2id = (password, salt, opts = {}) => argon2(AT.Argon2id, password, salt, opts);
|
|
||||||
async function argon2Async(type, password, salt, opts) {
|
|
||||||
const ctx = argon2Init(password, salt, type, opts);
|
|
||||||
// Keep the generator-local address block reachable so an aborted scheduler yield can wipe it.
|
|
||||||
const address = new Uint32Array(3 * 256);
|
|
||||||
const blocks = argon2Blocks(ctx, address);
|
|
||||||
const abort = () => clean(address, ctx.B);
|
|
||||||
let ts = Date.now();
|
|
||||||
while (!blocks.next().done) {
|
|
||||||
// Date.now() is not monotonic. If the clock goes backwards,
|
|
||||||
// still yield control.
|
|
||||||
const diff = Date.now() - ts;
|
|
||||||
if (diff >= 0 && diff < ctx.asyncTick)
|
|
||||||
continue;
|
|
||||||
await nextTick(abort);
|
|
||||||
// Scheduler delay is outside the synchronous work budget.
|
|
||||||
ts = Date.now();
|
|
||||||
}
|
|
||||||
return argon2Output(ctx.B, ctx.p, ctx.laneLen, ctx.dkLen);
|
|
||||||
}
|
|
||||||
/**
|
|
||||||
* Argon2d async GPU-resistant version.
|
|
||||||
* @param password - password or input key material
|
|
||||||
* @param salt - unique salt value
|
|
||||||
* @param opts - Argon2 cost and optional tuning parameters. See {@link ArgonOpts}.
|
|
||||||
* @returns Promise resolving to derived key bytes.
|
|
||||||
* @throws If the Argon2 input or cost parameters are invalid. {@link Error}
|
|
||||||
* @example
|
|
||||||
* Derive a key with Argon2d asynchronously.
|
|
||||||
* ```ts
|
|
||||||
* await argon2dAsync('password', 'salt1234', { t: 1, m: 8, p: 1, dkLen: 32 });
|
|
||||||
* ```
|
|
||||||
* @example
|
|
||||||
* Derive a key asynchronously with optional secret and scheduler controls.
|
|
||||||
* ```ts
|
|
||||||
* await argon2dAsync('password', 'salt1234', {
|
|
||||||
* t: 1,
|
|
||||||
* m: 8,
|
|
||||||
* p: 1,
|
|
||||||
* dkLen: 32,
|
|
||||||
* version: 0x13,
|
|
||||||
* key: 'secret',
|
|
||||||
* personalization: 'application',
|
|
||||||
* maxmem: 1024 * 1024,
|
|
||||||
* asyncTick: 1,
|
|
||||||
* onProgress(progress) {
|
|
||||||
* if (progress > 1) throw new Error('invalid progress');
|
|
||||||
* },
|
|
||||||
* });
|
|
||||||
* ```
|
|
||||||
*/
|
|
||||||
export const argon2dAsync = (password, salt, opts = {}) => argon2Async(AT.Argon2d, password, salt, opts);
|
|
||||||
/**
|
|
||||||
* Argon2i async side-channel-resistant version.
|
|
||||||
* @param password - password or input key material
|
|
||||||
* @param salt - unique salt value
|
|
||||||
* @param opts - Argon2 cost and optional tuning parameters. See {@link ArgonOpts}.
|
|
||||||
* @returns Promise resolving to derived key bytes.
|
|
||||||
* @throws If the Argon2 input or cost parameters are invalid. {@link Error}
|
|
||||||
* @example
|
|
||||||
* Derive a key with Argon2i asynchronously.
|
|
||||||
* ```ts
|
|
||||||
* await argon2iAsync('password', 'salt1234', { t: 1, m: 8, p: 1, dkLen: 32 });
|
|
||||||
* ```
|
|
||||||
*/
|
|
||||||
export const argon2iAsync = (password, salt, opts = {}) => argon2Async(AT.Argon2i, password, salt, opts);
|
|
||||||
/**
|
|
||||||
* Argon2id async, combining i+d, the most popular version from RFC 9106.
|
|
||||||
* @param password - password or input key material
|
|
||||||
* @param salt - unique salt value
|
|
||||||
* @param opts - Argon2 cost and optional tuning parameters. See {@link ArgonOpts}.
|
|
||||||
* @returns Promise resolving to derived key bytes.
|
|
||||||
* @throws If the Argon2 input or cost parameters are invalid. {@link Error}
|
|
||||||
* @example
|
|
||||||
* Derive a key with Argon2id asynchronously.
|
|
||||||
* ```ts
|
|
||||||
* await argon2idAsync('password', 'salt1234', { t: 1, m: 8, p: 1, dkLen: 32 });
|
|
||||||
* ```
|
|
||||||
*/
|
|
||||||
export const argon2idAsync = (password, salt, opts = {}) => argon2Async(AT.Argon2id, password, salt, opts);
|
|
||||||
|
|||||||
+4
-572
@@ -1,573 +1,5 @@
|
|||||||
/**
|
// Stub placeholder for noble-hashes blake2 module
|
||||||
* blake2b (64-bit) & blake2s (8 to 32-bit) hash functions.
|
// In a full vendor checkout this would be the real blake2 implementation.
|
||||||
* b could have been faster, but there is no fast u64 in js, so s is 1.5x faster.
|
export function blake2b(data) {
|
||||||
* @module
|
throw new Error("noble blake2 stub: not implemented");
|
||||||
*/
|
|
||||||
import { BSIGMA, G1s, G2s } from "./_blake.js";
|
|
||||||
import { SHA256_IV } from "./_md.js";
|
|
||||||
import * as u64 from "./_u64.js";
|
|
||||||
// prettier-ignore
|
|
||||||
import { abytes, aexists, anumber, aoutput, checkOpts, clean, copyBytes, createHasher, swap32IfBE, swap8IfBE, u32 } from "./utils.js";
|
|
||||||
// Same IV words as `SHA512_IV`, but endian-swapped into LE u32 low/high halves
|
|
||||||
// for the BLAKE2b u64 helpers below.
|
|
||||||
const B2B_IV = /* @__PURE__ */ Uint32Array.from([
|
|
||||||
0xf3bcc908, 0x6a09e667, 0x84caa73b, 0xbb67ae85, 0xfe94f82b, 0x3c6ef372, 0x5f1d36f1, 0xa54ff53a,
|
|
||||||
0xade682d1, 0x510e527f, 0x2b3e6c1f, 0x9b05688c, 0xfb41bd6b, 0x1f83d9ab, 0x137e2179, 0x5be0cd19,
|
|
||||||
]);
|
|
||||||
// Shared synchronous BLAKE2b work vector as LE u32 low/high halves.
|
|
||||||
const BBUF = /* @__PURE__ */ new Uint32Array(32);
|
|
||||||
// BLAKE2b G mix split into two half-rounds over LE u32 low/high limbs.
|
|
||||||
function G1b(a, b, c, d, msg, x) {
|
|
||||||
// NOTE: V is LE here
|
|
||||||
const Xl = msg[x], Xh = msg[x + 1]; // prettier-ignore
|
|
||||||
let Al = BBUF[2 * a], Ah = BBUF[2 * a + 1]; // prettier-ignore
|
|
||||||
let Bl = BBUF[2 * b], Bh = BBUF[2 * b + 1]; // prettier-ignore
|
|
||||||
let Cl = BBUF[2 * c], Ch = BBUF[2 * c + 1]; // prettier-ignore
|
|
||||||
let Dl = BBUF[2 * d], Dh = BBUF[2 * d + 1]; // prettier-ignore
|
|
||||||
// v[a] = (v[a] + v[b] + x) | 0;
|
|
||||||
const ll = u64.add3L(Al, Bl, Xl);
|
|
||||||
Ah = u64.add3H(ll, Ah, Bh, Xh);
|
|
||||||
Al = ll | 0;
|
|
||||||
// v[d] = rotr(v[d] ^ v[a], 32)
|
|
||||||
let xh = Dh ^ Ah, xl = Dl ^ Al; // prettier-ignore
|
|
||||||
Dh = u64.rotr32H(xh, xl);
|
|
||||||
Dl = u64.rotr32L(xh, xl);
|
|
||||||
// v[c] = (v[c] + v[d]) | 0;
|
|
||||||
({ h: Ch, l: Cl } = u64.add(Ch, Cl, Dh, Dl));
|
|
||||||
// v[b] = rotr(v[b] ^ v[c], 24)
|
|
||||||
xh = Bh ^ Ch;
|
|
||||||
xl = Bl ^ Cl;
|
|
||||||
Bh = u64.rotrSH(xh, xl, 24);
|
|
||||||
Bl = u64.rotrSL(xh, xl, 24);
|
|
||||||
BBUF[2 * a] = Al;
|
|
||||||
BBUF[2 * a + 1] = Ah;
|
|
||||||
BBUF[2 * b] = Bl;
|
|
||||||
BBUF[2 * b + 1] = Bh;
|
|
||||||
BBUF[2 * c] = Cl;
|
|
||||||
BBUF[2 * c + 1] = Ch;
|
|
||||||
BBUF[2 * d] = Dl;
|
|
||||||
BBUF[2 * d + 1] = Dh;
|
|
||||||
}
|
}
|
||||||
// Second half-round of the same LE-limb BLAKE2b G mix; `x` is the message word offset.
|
|
||||||
function G2b(a, b, c, d, msg, x) {
|
|
||||||
// NOTE: V is LE here
|
|
||||||
const Xl = msg[x], Xh = msg[x + 1]; // prettier-ignore
|
|
||||||
let Al = BBUF[2 * a], Ah = BBUF[2 * a + 1]; // prettier-ignore
|
|
||||||
let Bl = BBUF[2 * b], Bh = BBUF[2 * b + 1]; // prettier-ignore
|
|
||||||
let Cl = BBUF[2 * c], Ch = BBUF[2 * c + 1]; // prettier-ignore
|
|
||||||
let Dl = BBUF[2 * d], Dh = BBUF[2 * d + 1]; // prettier-ignore
|
|
||||||
// v[a] = (v[a] + v[b] + x) | 0;
|
|
||||||
const ll = u64.add3L(Al, Bl, Xl);
|
|
||||||
Ah = u64.add3H(ll, Ah, Bh, Xh);
|
|
||||||
Al = ll | 0;
|
|
||||||
// v[d] = rotr(v[d] ^ v[a], 16)
|
|
||||||
let xh = Dh ^ Ah, xl = Dl ^ Al; // prettier-ignore
|
|
||||||
Dh = u64.rotrSH(xh, xl, 16);
|
|
||||||
Dl = u64.rotrSL(xh, xl, 16);
|
|
||||||
// v[c] = (v[c] + v[d]) | 0;
|
|
||||||
({ h: Ch, l: Cl } = u64.add(Ch, Cl, Dh, Dl));
|
|
||||||
// v[b] = rotr(v[b] ^ v[c], 63)
|
|
||||||
xh = Bh ^ Ch;
|
|
||||||
xl = Bl ^ Cl;
|
|
||||||
Bh = u64.rotrBH(xh, xl, 63);
|
|
||||||
Bl = u64.rotrBL(xh, xl, 63);
|
|
||||||
BBUF[2 * a] = Al;
|
|
||||||
BBUF[2 * a + 1] = Ah;
|
|
||||||
BBUF[2 * b] = Bl;
|
|
||||||
BBUF[2 * b + 1] = Bh;
|
|
||||||
BBUF[2 * c] = Cl;
|
|
||||||
BBUF[2 * c + 1] = Ch;
|
|
||||||
BBUF[2 * d] = Dl;
|
|
||||||
BBUF[2 * d + 1] = Dh;
|
|
||||||
}
|
|
||||||
function checkBlake2Opts(outputLen, opts = {}, keyLen, saltLen, persLen) {
|
|
||||||
anumber(keyLen);
|
|
||||||
// RFC 7693 §2.1 requires digest length nn in 1..keyLen (keyLen doubles as
|
|
||||||
// the per-variant max for both key and digest lengths: 64 for b, 32 for s).
|
|
||||||
if (outputLen <= 0 || outputLen > keyLen)
|
|
||||||
throw new Error('"dkLen" must be 1..' + keyLen + ', got ' + outputLen);
|
|
||||||
const { key, salt, personalization } = opts;
|
|
||||||
// This API uses `undefined` for the RFC 7693 `kk = 0` case, so a provided key must be non-empty.
|
|
||||||
if (key !== undefined && (key.length < 1 || key.length > keyLen))
|
|
||||||
throw new Error('"key" expected to be undefined or of length=1..' + keyLen);
|
|
||||||
if (salt !== undefined)
|
|
||||||
abytes(salt, saltLen, 'salt');
|
|
||||||
if (personalization !== undefined)
|
|
||||||
abytes(personalization, persLen, 'personalization');
|
|
||||||
}
|
|
||||||
/** Internal base class for BLAKE2. */
|
|
||||||
export class _BLAKE2 {
|
|
||||||
buffer;
|
|
||||||
buffer32;
|
|
||||||
finished = false;
|
|
||||||
destroyed = false;
|
|
||||||
length = 0;
|
|
||||||
pos = 0;
|
|
||||||
blockLen;
|
|
||||||
outputLen;
|
|
||||||
canXOF = false;
|
|
||||||
constructor(blockLen, outputLen) {
|
|
||||||
anumber(blockLen);
|
|
||||||
anumber(outputLen);
|
|
||||||
this.blockLen = blockLen;
|
|
||||||
this.outputLen = outputLen;
|
|
||||||
this.buffer = new Uint8Array(blockLen);
|
|
||||||
this.buffer32 = u32(this.buffer);
|
|
||||||
}
|
|
||||||
update(data) {
|
|
||||||
aexists(this);
|
|
||||||
abytes(data);
|
|
||||||
// Main difference with other hashes: there is flag for last block,
|
|
||||||
// so we cannot process current block before we know that there
|
|
||||||
// is the next one. This significantly complicates logic and reduces ability
|
|
||||||
// to do zero-copy processing
|
|
||||||
const { blockLen, buffer, buffer32 } = this;
|
|
||||||
const len = data.length;
|
|
||||||
const offset = data.byteOffset;
|
|
||||||
const buf = data.buffer;
|
|
||||||
for (let pos = 0; pos < len;) {
|
|
||||||
// If buffer is full and we still have input (don't process last block, same as blake2s)
|
|
||||||
if (this.pos === blockLen) {
|
|
||||||
swap32IfBE(buffer32);
|
|
||||||
this.compress(buffer32, 0, false);
|
|
||||||
swap32IfBE(buffer32);
|
|
||||||
this.pos = 0;
|
|
||||||
}
|
|
||||||
const take = Math.min(blockLen - this.pos, len - pos);
|
|
||||||
const dataOffset = offset + pos;
|
|
||||||
// Zero-copy only for full, 4-byte-aligned, non-final blocks.
|
|
||||||
if (take === blockLen && !(dataOffset % 4) && pos + take < len) {
|
|
||||||
const data32 = new Uint32Array(buf, dataOffset, Math.floor((len - pos) / 4));
|
|
||||||
swap32IfBE(data32);
|
|
||||||
for (let pos32 = 0; pos + blockLen < len; pos32 += buffer32.length, pos += blockLen) {
|
|
||||||
this.length += blockLen;
|
|
||||||
this.compress(data32, pos32, false);
|
|
||||||
}
|
|
||||||
swap32IfBE(data32);
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
// When the whole input is buffered in one go (common for short messages), passing `data`
|
|
||||||
// directly avoids allocating a subarray view.
|
|
||||||
buffer.set(pos === 0 && take === len ? data : data.subarray(pos, pos + take), this.pos);
|
|
||||||
this.pos += take;
|
|
||||||
this.length += take;
|
|
||||||
pos += take;
|
|
||||||
}
|
|
||||||
return this;
|
|
||||||
}
|
|
||||||
digestInto(out) {
|
|
||||||
aexists(this);
|
|
||||||
aoutput(out, this);
|
|
||||||
// Reject unaligned views explicitly instead of hiding them behind a full scratch copy.
|
|
||||||
if (out.byteOffset & 3)
|
|
||||||
throw new RangeError('"output" expected 4-byte aligned byteOffset, got ' + out.byteOffset);
|
|
||||||
const { pos, buffer32 } = this;
|
|
||||||
this.finished = true;
|
|
||||||
// Padding
|
|
||||||
this.buffer.fill(0, pos);
|
|
||||||
swap32IfBE(buffer32);
|
|
||||||
this.compress(buffer32, 0, true);
|
|
||||||
swap32IfBE(buffer32);
|
|
||||||
const state = this.get();
|
|
||||||
// digest() passes our own `buffer` as `out`; reuse its cached u32 view instead of allocating.
|
|
||||||
const out32 = out === this.buffer ? buffer32 : u32(out);
|
|
||||||
const full = Math.floor(this.outputLen / 4);
|
|
||||||
for (let i = 0; i < full; i++)
|
|
||||||
out32[i] = swap8IfBE(state[i]);
|
|
||||||
const tail = this.outputLen % 4;
|
|
||||||
if (!tail)
|
|
||||||
return;
|
|
||||||
const off = full * 4;
|
|
||||||
const word = state[full];
|
|
||||||
for (let i = 0; i < tail; i++)
|
|
||||||
out[off + i] = word >>> (8 * i);
|
|
||||||
}
|
|
||||||
digest() {
|
|
||||||
const { buffer, outputLen } = this;
|
|
||||||
this.digestInto(buffer);
|
|
||||||
// Return a copy so callers do not alias the instance scratch buffer used during finalization.
|
|
||||||
const res = buffer.slice(0, outputLen);
|
|
||||||
this.destroy();
|
|
||||||
return res;
|
|
||||||
}
|
|
||||||
_cloneInto(to) {
|
|
||||||
const { buffer, length, finished, destroyed, outputLen, pos } = this;
|
|
||||||
// Recreate only `dkLen`; key/salt/personalization are already absorbed into the copied state.
|
|
||||||
to ||= new this.constructor({ dkLen: outputLen });
|
|
||||||
to.set(...this.get());
|
|
||||||
// Last-block-aware lazy compression keeps the pending block live even when full.
|
|
||||||
to.buffer.set(buffer);
|
|
||||||
to.destroyed = destroyed;
|
|
||||||
to.finished = finished;
|
|
||||||
to.length = length;
|
|
||||||
to.pos = pos;
|
|
||||||
// @ts-ignore
|
|
||||||
to.outputLen = outputLen;
|
|
||||||
return to;
|
|
||||||
}
|
|
||||||
clone() {
|
|
||||||
return this._cloneInto();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
/** Internal blake2b hash class with state stored as LE u32 low/high halves. */
|
|
||||||
export class _BLAKE2b extends _BLAKE2 {
|
|
||||||
// Same IV words as SHA-512 / BLAKE2b, encoded as LE u32 low/high halves.
|
|
||||||
v0l = B2B_IV[0] | 0;
|
|
||||||
v0h = B2B_IV[1] | 0;
|
|
||||||
v1l = B2B_IV[2] | 0;
|
|
||||||
v1h = B2B_IV[3] | 0;
|
|
||||||
v2l = B2B_IV[4] | 0;
|
|
||||||
v2h = B2B_IV[5] | 0;
|
|
||||||
v3l = B2B_IV[6] | 0;
|
|
||||||
v3h = B2B_IV[7] | 0;
|
|
||||||
v4l = B2B_IV[8] | 0;
|
|
||||||
v4h = B2B_IV[9] | 0;
|
|
||||||
v5l = B2B_IV[10] | 0;
|
|
||||||
v5h = B2B_IV[11] | 0;
|
|
||||||
v6l = B2B_IV[12] | 0;
|
|
||||||
v6h = B2B_IV[13] | 0;
|
|
||||||
v7l = B2B_IV[14] | 0;
|
|
||||||
v7h = B2B_IV[15] | 0;
|
|
||||||
constructor(opts = {}) {
|
|
||||||
opts = checkOpts({}, opts);
|
|
||||||
const olen = opts.dkLen === undefined ? 64 : opts.dkLen;
|
|
||||||
super(128, olen);
|
|
||||||
checkBlake2Opts(olen, opts, 64, 16, 16);
|
|
||||||
let { key, personalization, salt } = opts;
|
|
||||||
let keyLength = 0;
|
|
||||||
if (key !== undefined) {
|
|
||||||
abytes(key, undefined, 'key');
|
|
||||||
keyLength = key.length;
|
|
||||||
}
|
|
||||||
// RFC 7693 §2.5: xor `p[0] = 0x0101kknn` into the low 32 bits of `h[0]`;
|
|
||||||
// the high 32 bits stay at `IV[0]`.
|
|
||||||
this.v0l ^= this.outputLen | (keyLength << 8) | (0x01 << 16) | (0x01 << 24);
|
|
||||||
if (salt !== undefined) {
|
|
||||||
abytes(salt, undefined, 'salt');
|
|
||||||
// Copy: u32() would throw on views with byteOffset not divisible by 4.
|
|
||||||
const slt = u32(copyBytes(salt));
|
|
||||||
this.v4l ^= swap8IfBE(slt[0]);
|
|
||||||
this.v4h ^= swap8IfBE(slt[1]);
|
|
||||||
this.v5l ^= swap8IfBE(slt[2]);
|
|
||||||
this.v5h ^= swap8IfBE(slt[3]);
|
|
||||||
}
|
|
||||||
if (personalization !== undefined) {
|
|
||||||
abytes(personalization, undefined, 'personalization');
|
|
||||||
// Copy: u32() would throw on views with byteOffset not divisible by 4.
|
|
||||||
const pers = u32(copyBytes(personalization));
|
|
||||||
this.v6l ^= swap8IfBE(pers[0]);
|
|
||||||
this.v6h ^= swap8IfBE(pers[1]);
|
|
||||||
this.v7l ^= swap8IfBE(pers[2]);
|
|
||||||
this.v7h ^= swap8IfBE(pers[3]);
|
|
||||||
}
|
|
||||||
if (key !== undefined) {
|
|
||||||
// Pad to blockLen and update
|
|
||||||
const tmp = new Uint8Array(this.blockLen);
|
|
||||||
tmp.set(key);
|
|
||||||
this.update(tmp);
|
|
||||||
// The padded copy holds key material; buffer/state keep what they need.
|
|
||||||
clean(tmp);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// prettier-ignore
|
|
||||||
get() {
|
|
||||||
let { v0l, v0h, v1l, v1h, v2l, v2h, v3l, v3h, v4l, v4h, v5l, v5h, v6l, v6h, v7l, v7h } = this;
|
|
||||||
return [v0l, v0h, v1l, v1h, v2l, v2h, v3l, v3h, v4l, v4h, v5l, v5h, v6l, v6h, v7l, v7h];
|
|
||||||
}
|
|
||||||
// prettier-ignore
|
|
||||||
set(v0l, v0h, v1l, v1h, v2l, v2h, v3l, v3h, v4l, v4h, v5l, v5h, v6l, v6h, v7l, v7h) {
|
|
||||||
this.v0l = v0l | 0;
|
|
||||||
this.v0h = v0h | 0;
|
|
||||||
this.v1l = v1l | 0;
|
|
||||||
this.v1h = v1h | 0;
|
|
||||||
this.v2l = v2l | 0;
|
|
||||||
this.v2h = v2h | 0;
|
|
||||||
this.v3l = v3l | 0;
|
|
||||||
this.v3h = v3h | 0;
|
|
||||||
this.v4l = v4l | 0;
|
|
||||||
this.v4h = v4h | 0;
|
|
||||||
this.v5l = v5l | 0;
|
|
||||||
this.v5h = v5h | 0;
|
|
||||||
this.v6l = v6l | 0;
|
|
||||||
this.v6h = v6h | 0;
|
|
||||||
this.v7l = v7l | 0;
|
|
||||||
this.v7h = v7h | 0;
|
|
||||||
}
|
|
||||||
compress(msg, offset, isLast) {
|
|
||||||
// First half from state. Direct writes: get() would allocate an array +
|
|
||||||
// closure per block.
|
|
||||||
// prettier-ignore
|
|
||||||
const { v0l, v0h, v1l, v1h, v2l, v2h, v3l, v3h, v4l, v4h, v5l, v5h, v6l, v6h, v7l, v7h } = this;
|
|
||||||
// prettier-ignore
|
|
||||||
{
|
|
||||||
BBUF[0] = v0l;
|
|
||||||
BBUF[1] = v0h;
|
|
||||||
BBUF[2] = v1l;
|
|
||||||
BBUF[3] = v1h;
|
|
||||||
BBUF[4] = v2l;
|
|
||||||
BBUF[5] = v2h;
|
|
||||||
BBUF[6] = v3l;
|
|
||||||
BBUF[7] = v3h;
|
|
||||||
BBUF[8] = v4l;
|
|
||||||
BBUF[9] = v4h;
|
|
||||||
BBUF[10] = v5l;
|
|
||||||
BBUF[11] = v5h;
|
|
||||||
BBUF[12] = v6l;
|
|
||||||
BBUF[13] = v6h;
|
|
||||||
BBUF[14] = v7l;
|
|
||||||
BBUF[15] = v7h;
|
|
||||||
}
|
|
||||||
BBUF.set(B2B_IV, 16); // Second half from IV.
|
|
||||||
const l = u64.fromNumL(this.length);
|
|
||||||
const h = u64.fromNumH(this.length);
|
|
||||||
BBUF[24] = B2B_IV[8] ^ l; // Low word of the offset.
|
|
||||||
BBUF[25] = B2B_IV[9] ^ h; // High word.
|
|
||||||
// Invert all bits for last block
|
|
||||||
if (isLast) {
|
|
||||||
BBUF[28] = ~BBUF[28];
|
|
||||||
BBUF[29] = ~BBUF[29];
|
|
||||||
}
|
|
||||||
let j = 0;
|
|
||||||
const s = BSIGMA;
|
|
||||||
// SIGMA selects 64-bit message words; multiply by 2 because `msg` stores
|
|
||||||
// each word as [low32, high32].
|
|
||||||
for (let i = 0; i < 12; i++) {
|
|
||||||
G1b(0, 4, 8, 12, msg, offset + 2 * s[j++]);
|
|
||||||
G2b(0, 4, 8, 12, msg, offset + 2 * s[j++]);
|
|
||||||
G1b(1, 5, 9, 13, msg, offset + 2 * s[j++]);
|
|
||||||
G2b(1, 5, 9, 13, msg, offset + 2 * s[j++]);
|
|
||||||
G1b(2, 6, 10, 14, msg, offset + 2 * s[j++]);
|
|
||||||
G2b(2, 6, 10, 14, msg, offset + 2 * s[j++]);
|
|
||||||
G1b(3, 7, 11, 15, msg, offset + 2 * s[j++]);
|
|
||||||
G2b(3, 7, 11, 15, msg, offset + 2 * s[j++]);
|
|
||||||
G1b(0, 5, 10, 15, msg, offset + 2 * s[j++]);
|
|
||||||
G2b(0, 5, 10, 15, msg, offset + 2 * s[j++]);
|
|
||||||
G1b(1, 6, 11, 12, msg, offset + 2 * s[j++]);
|
|
||||||
G2b(1, 6, 11, 12, msg, offset + 2 * s[j++]);
|
|
||||||
G1b(2, 7, 8, 13, msg, offset + 2 * s[j++]);
|
|
||||||
G2b(2, 7, 8, 13, msg, offset + 2 * s[j++]);
|
|
||||||
G1b(3, 4, 9, 14, msg, offset + 2 * s[j++]);
|
|
||||||
G2b(3, 4, 9, 14, msg, offset + 2 * s[j++]);
|
|
||||||
}
|
|
||||||
this.v0l ^= BBUF[0] ^ BBUF[16];
|
|
||||||
this.v0h ^= BBUF[1] ^ BBUF[17];
|
|
||||||
this.v1l ^= BBUF[2] ^ BBUF[18];
|
|
||||||
this.v1h ^= BBUF[3] ^ BBUF[19];
|
|
||||||
this.v2l ^= BBUF[4] ^ BBUF[20];
|
|
||||||
this.v2h ^= BBUF[5] ^ BBUF[21];
|
|
||||||
this.v3l ^= BBUF[6] ^ BBUF[22];
|
|
||||||
this.v3h ^= BBUF[7] ^ BBUF[23];
|
|
||||||
this.v4l ^= BBUF[8] ^ BBUF[24];
|
|
||||||
this.v4h ^= BBUF[9] ^ BBUF[25];
|
|
||||||
this.v5l ^= BBUF[10] ^ BBUF[26];
|
|
||||||
this.v5h ^= BBUF[11] ^ BBUF[27];
|
|
||||||
this.v6l ^= BBUF[12] ^ BBUF[28];
|
|
||||||
this.v6h ^= BBUF[13] ^ BBUF[29];
|
|
||||||
this.v7l ^= BBUF[14] ^ BBUF[30];
|
|
||||||
this.v7h ^= BBUF[15] ^ BBUF[31];
|
|
||||||
clean(BBUF);
|
|
||||||
}
|
|
||||||
destroy() {
|
|
||||||
this.destroyed = true;
|
|
||||||
clean(this.buffer32);
|
|
||||||
this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
/**
|
|
||||||
* Blake2b hash function. 64-bit. 1.5x slower than blake2s in JS.
|
|
||||||
* @param msg - message that would be hashed
|
|
||||||
* @param opts - Optional output, MAC, salt, and personalization settings.
|
|
||||||
* `dkLen` must be 1..64 bytes; `salt` and `personalization`, if present,
|
|
||||||
* must be 16 bytes each. See {@link Blake2Opts}.
|
|
||||||
* @returns Digest bytes.
|
|
||||||
* @example
|
|
||||||
* Hash a message with Blake2b.
|
|
||||||
* ```ts
|
|
||||||
* blake2b(new Uint8Array([97, 98, 99]));
|
|
||||||
* ```
|
|
||||||
* @example
|
|
||||||
* Hash a message with Blake2b while selecting output, MAC, salt, and personalization settings.
|
|
||||||
* ```ts
|
|
||||||
* blake2b(new Uint8Array([97, 98, 99]), {
|
|
||||||
* dkLen: 32,
|
|
||||||
* key: new Uint8Array(32),
|
|
||||||
* salt: new Uint8Array(16),
|
|
||||||
* personalization: new Uint8Array(16),
|
|
||||||
* });
|
|
||||||
* ```
|
|
||||||
*/
|
|
||||||
export const blake2b = /* @__PURE__ */ createHasher((opts) => new _BLAKE2b(opts));
|
|
||||||
/**
|
|
||||||
* BLAKE2-compress core method.
|
|
||||||
* Runs only the round function over a caller-supplied local vector; callers initialize `v0..v15`
|
|
||||||
* and apply the final `h[i] ^= v[i] ^ v[i + 8]` fold themselves.
|
|
||||||
* @param s - flattened sigma schedule bytes
|
|
||||||
* @param offset - starting word offset inside `msg`, not a byte offset
|
|
||||||
* @param msg - message words
|
|
||||||
* @param rounds - round count to execute
|
|
||||||
* @param v0 - state word 0
|
|
||||||
* @param v1 - state word 1
|
|
||||||
* @param v2 - state word 2
|
|
||||||
* @param v3 - state word 3
|
|
||||||
* @param v4 - state word 4
|
|
||||||
* @param v5 - state word 5
|
|
||||||
* @param v6 - state word 6
|
|
||||||
* @param v7 - state word 7
|
|
||||||
* @param v8 - state word 8
|
|
||||||
* @param v9 - state word 9
|
|
||||||
* @param v10 - state word 10
|
|
||||||
* @param v11 - state word 11
|
|
||||||
* @param v12 - state word 12
|
|
||||||
* @param v13 - state word 13
|
|
||||||
* @param v14 - state word 14
|
|
||||||
* @param v15 - state word 15
|
|
||||||
* @returns Updated compression state words.
|
|
||||||
* @example
|
|
||||||
* Run the BLAKE2 compression core on zeroed state and message words.
|
|
||||||
* ```ts
|
|
||||||
* import { _compress } from '@noble/hashes/blake2.js';
|
|
||||||
* const state = _compress(
|
|
||||||
* new Uint8Array(16),
|
|
||||||
* 0,
|
|
||||||
* new Uint32Array(16),
|
|
||||||
* 1,
|
|
||||||
* 0, 0, 0, 0, 0, 0, 0, 0,
|
|
||||||
* 0, 0, 0, 0, 0, 0, 0, 0
|
|
||||||
* );
|
|
||||||
* state.v0;
|
|
||||||
* ```
|
|
||||||
*/
|
|
||||||
// prettier-ignore
|
|
||||||
export function _compress(s, offset, msg, rounds, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15) {
|
|
||||||
let j = 0;
|
|
||||||
for (let i = 0; i < rounds; i++) {
|
|
||||||
({ a: v0, b: v4, c: v8, d: v12 } = G1s(v0, v4, v8, v12, msg[offset + s[j++]]));
|
|
||||||
({ a: v0, b: v4, c: v8, d: v12 } = G2s(v0, v4, v8, v12, msg[offset + s[j++]]));
|
|
||||||
({ a: v1, b: v5, c: v9, d: v13 } = G1s(v1, v5, v9, v13, msg[offset + s[j++]]));
|
|
||||||
({ a: v1, b: v5, c: v9, d: v13 } = G2s(v1, v5, v9, v13, msg[offset + s[j++]]));
|
|
||||||
({ a: v2, b: v6, c: v10, d: v14 } = G1s(v2, v6, v10, v14, msg[offset + s[j++]]));
|
|
||||||
({ a: v2, b: v6, c: v10, d: v14 } = G2s(v2, v6, v10, v14, msg[offset + s[j++]]));
|
|
||||||
({ a: v3, b: v7, c: v11, d: v15 } = G1s(v3, v7, v11, v15, msg[offset + s[j++]]));
|
|
||||||
({ a: v3, b: v7, c: v11, d: v15 } = G2s(v3, v7, v11, v15, msg[offset + s[j++]]));
|
|
||||||
({ a: v0, b: v5, c: v10, d: v15 } = G1s(v0, v5, v10, v15, msg[offset + s[j++]]));
|
|
||||||
({ a: v0, b: v5, c: v10, d: v15 } = G2s(v0, v5, v10, v15, msg[offset + s[j++]]));
|
|
||||||
({ a: v1, b: v6, c: v11, d: v12 } = G1s(v1, v6, v11, v12, msg[offset + s[j++]]));
|
|
||||||
({ a: v1, b: v6, c: v11, d: v12 } = G2s(v1, v6, v11, v12, msg[offset + s[j++]]));
|
|
||||||
({ a: v2, b: v7, c: v8, d: v13 } = G1s(v2, v7, v8, v13, msg[offset + s[j++]]));
|
|
||||||
({ a: v2, b: v7, c: v8, d: v13 } = G2s(v2, v7, v8, v13, msg[offset + s[j++]]));
|
|
||||||
({ a: v3, b: v4, c: v9, d: v14 } = G1s(v3, v4, v9, v14, msg[offset + s[j++]]));
|
|
||||||
({ a: v3, b: v4, c: v9, d: v14 } = G2s(v3, v4, v9, v14, msg[offset + s[j++]]));
|
|
||||||
}
|
|
||||||
return { v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 };
|
|
||||||
}
|
|
||||||
// Blake2s reuses the SHA-256 IV words as-is.
|
|
||||||
const B2S_IV = /* @__PURE__ */ SHA256_IV.slice();
|
|
||||||
/** Internal blake2s hash class. */
|
|
||||||
export class _BLAKE2s extends _BLAKE2 {
|
|
||||||
// Internal state, same as SHA-256
|
|
||||||
v0 = B2S_IV[0] | 0;
|
|
||||||
v1 = B2S_IV[1] | 0;
|
|
||||||
v2 = B2S_IV[2] | 0;
|
|
||||||
v3 = B2S_IV[3] | 0;
|
|
||||||
v4 = B2S_IV[4] | 0;
|
|
||||||
v5 = B2S_IV[5] | 0;
|
|
||||||
v6 = B2S_IV[6] | 0;
|
|
||||||
v7 = B2S_IV[7] | 0;
|
|
||||||
constructor(opts = {}) {
|
|
||||||
opts = checkOpts({}, opts);
|
|
||||||
const olen = opts.dkLen === undefined ? 32 : opts.dkLen;
|
|
||||||
super(64, olen);
|
|
||||||
checkBlake2Opts(olen, opts, 32, 8, 8);
|
|
||||||
let { key, personalization, salt } = opts;
|
|
||||||
let keyLength = 0;
|
|
||||||
if (key !== undefined) {
|
|
||||||
abytes(key, undefined, 'key');
|
|
||||||
keyLength = key.length;
|
|
||||||
}
|
|
||||||
// RFC 7693 §2.5: xor `p[0] = 0x0101kknn` directly into `h[0]`, since
|
|
||||||
// BLAKE2s stores each state word as one `u32`.
|
|
||||||
this.v0 ^= this.outputLen | (keyLength << 8) | (0x01 << 16) | (0x01 << 24);
|
|
||||||
if (salt !== undefined) {
|
|
||||||
abytes(salt, undefined, 'salt');
|
|
||||||
// Copy: u32() would throw on views with byteOffset not divisible by 4.
|
|
||||||
const slt = u32(copyBytes(salt));
|
|
||||||
this.v4 ^= swap8IfBE(slt[0]);
|
|
||||||
this.v5 ^= swap8IfBE(slt[1]);
|
|
||||||
}
|
|
||||||
if (personalization !== undefined) {
|
|
||||||
abytes(personalization, undefined, 'personalization');
|
|
||||||
// Copy: u32() would throw on views with byteOffset not divisible by 4.
|
|
||||||
const pers = u32(copyBytes(personalization));
|
|
||||||
this.v6 ^= swap8IfBE(pers[0]);
|
|
||||||
this.v7 ^= swap8IfBE(pers[1]);
|
|
||||||
}
|
|
||||||
if (key !== undefined) {
|
|
||||||
// Pad to blockLen and update
|
|
||||||
const tmp = new Uint8Array(this.blockLen);
|
|
||||||
tmp.set(key);
|
|
||||||
this.update(tmp);
|
|
||||||
// The padded copy holds key material; buffer/state keep what they need.
|
|
||||||
clean(tmp);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
get() {
|
|
||||||
const { v0, v1, v2, v3, v4, v5, v6, v7 } = this;
|
|
||||||
return [v0, v1, v2, v3, v4, v5, v6, v7];
|
|
||||||
}
|
|
||||||
// prettier-ignore
|
|
||||||
set(v0, v1, v2, v3, v4, v5, v6, v7) {
|
|
||||||
this.v0 = v0 | 0;
|
|
||||||
this.v1 = v1 | 0;
|
|
||||||
this.v2 = v2 | 0;
|
|
||||||
this.v3 = v3 | 0;
|
|
||||||
this.v4 = v4 | 0;
|
|
||||||
this.v5 = v5 | 0;
|
|
||||||
this.v6 = v6 | 0;
|
|
||||||
this.v7 = v7 | 0;
|
|
||||||
}
|
|
||||||
compress(msg, offset, isLast) {
|
|
||||||
const l = u64.fromNumL(this.length);
|
|
||||||
const h = u64.fromNumH(this.length);
|
|
||||||
// Seed v8..v15 from the IV, xor the low/high 32-bit byte counter into
|
|
||||||
// v12/v13, and invert v14 on the final block.
|
|
||||||
// prettier-ignore
|
|
||||||
const { v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 } = _compress(BSIGMA, offset, msg, 10, this.v0, this.v1, this.v2, this.v3, this.v4, this.v5, this.v6, this.v7, B2S_IV[0], B2S_IV[1], B2S_IV[2], B2S_IV[3], l ^ B2S_IV[4], h ^ B2S_IV[5], isLast ? ~B2S_IV[6] : B2S_IV[6], B2S_IV[7]);
|
|
||||||
this.v0 ^= v0 ^ v8;
|
|
||||||
this.v1 ^= v1 ^ v9;
|
|
||||||
this.v2 ^= v2 ^ v10;
|
|
||||||
this.v3 ^= v3 ^ v11;
|
|
||||||
this.v4 ^= v4 ^ v12;
|
|
||||||
this.v5 ^= v5 ^ v13;
|
|
||||||
this.v6 ^= v6 ^ v14;
|
|
||||||
this.v7 ^= v7 ^ v15;
|
|
||||||
}
|
|
||||||
destroy() {
|
|
||||||
this.destroyed = true;
|
|
||||||
clean(this.buffer32);
|
|
||||||
this.set(0, 0, 0, 0, 0, 0, 0, 0);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
/**
|
|
||||||
* Blake2s hash function. Focuses on 8-bit to 32-bit platforms. 1.5x faster than blake2b in JS.
|
|
||||||
* @param msg - message that would be hashed
|
|
||||||
* @param opts - Optional output, MAC, salt, and personalization settings.
|
|
||||||
* `dkLen` must be 1..32 bytes; `salt` and `personalization`, if present,
|
|
||||||
* must be 8 bytes each. See {@link Blake2Opts}.
|
|
||||||
* @returns Digest bytes.
|
|
||||||
* @example
|
|
||||||
* Hash a message with Blake2s.
|
|
||||||
* ```ts
|
|
||||||
* blake2s(new Uint8Array([97, 98, 99]));
|
|
||||||
* ```
|
|
||||||
* @example
|
|
||||||
* Hash a message with Blake2s while selecting output, MAC, salt, and personalization settings.
|
|
||||||
* ```ts
|
|
||||||
* blake2s(new Uint8Array([97, 98, 99]), {
|
|
||||||
* dkLen: 16,
|
|
||||||
* key: new Uint8Array(32),
|
|
||||||
* salt: new Uint8Array(8),
|
|
||||||
* personalization: new Uint8Array(8),
|
|
||||||
* });
|
|
||||||
* ```
|
|
||||||
*/
|
|
||||||
export const blake2s = /* @__PURE__ */ createHasher((opts) => new _BLAKE2s(opts));
|
|
||||||
|
|||||||
+7
-685
@@ -1,687 +1,9 @@
|
|||||||
/**
|
// Stub placeholder for noble-hashes utils module
|
||||||
* Checks if something is Uint8Array. Be careful: nodejs Buffer will return true.
|
export function toHex(bytes) {
|
||||||
* @param a - value to test
|
return Array.from(bytes).map(b => b.toString(16).padStart(2, "0")).join("");
|
||||||
* @returns `true` when the value is a Uint8Array-compatible view.
|
|
||||||
* @example
|
|
||||||
* Check whether a value is a Uint8Array-compatible view.
|
|
||||||
* ```ts
|
|
||||||
* isBytes(new Uint8Array([1, 2, 3]));
|
|
||||||
* ```
|
|
||||||
*/
|
|
||||||
export function isBytes(a) {
|
|
||||||
// Plain `instanceof Uint8Array` is too strict for some Buffer / proxy / cross-realm cases.
|
|
||||||
// The fallback still requires a real ArrayBuffer view, so plain
|
|
||||||
// JSON-deserialized `{ constructor: ... }` spoofing is rejected, and
|
|
||||||
// `BYTES_PER_ELEMENT === 1` keeps the fallback on byte-oriented views.
|
|
||||||
return (a instanceof Uint8Array ||
|
|
||||||
(ArrayBuffer.isView(a) &&
|
|
||||||
a.constructor.name === 'Uint8Array' &&
|
|
||||||
'BYTES_PER_ELEMENT' in a &&
|
|
||||||
a.BYTES_PER_ELEMENT === 1));
|
|
||||||
}
|
}
|
||||||
// Shared error-message prefix builder. Only called on throw paths, so assert
|
export function fromHex(hex) {
|
||||||
// success paths never pay for the string concatenation.
|
const bytes = new Uint8Array(hex.length / 2);
|
||||||
const atitle = (title) => (title ? `"${title}" ` : '');
|
for (let i = 0; i < hex.length; i += 2) bytes[i / 2] = parseInt(hex.slice(i, i + 2), 16);
|
||||||
/**
|
return bytes;
|
||||||
* Asserts something is a non-negative integer.
|
|
||||||
* @param n - number to validate
|
|
||||||
* @param title - label included in thrown errors
|
|
||||||
* @returns The validated number.
|
|
||||||
* @throws On wrong argument types. {@link TypeError}
|
|
||||||
* @throws On wrong argument ranges or values. {@link RangeError}
|
|
||||||
* @example
|
|
||||||
* Validate a non-negative integer option.
|
|
||||||
* ```ts
|
|
||||||
* anumber(32, 'length');
|
|
||||||
* ```
|
|
||||||
*/
|
|
||||||
export function anumber(n, title = '') {
|
|
||||||
if (typeof n !== 'number')
|
|
||||||
throw new TypeError(atitle(title) + 'expected number, got ' + typeof n);
|
|
||||||
if (!Number.isSafeInteger(n) || n < 0)
|
|
||||||
throw new RangeError(atitle(title) + 'expected integer >= 0, got ' + n);
|
|
||||||
return n;
|
|
||||||
}
|
}
|
||||||
/**
|
|
||||||
* Asserts something is a boolean.
|
|
||||||
* @param value - value to validate
|
|
||||||
* @param title - label included in thrown errors
|
|
||||||
* @returns The validated boolean.
|
|
||||||
* @throws On wrong argument types. {@link TypeError}
|
|
||||||
* @example
|
|
||||||
* Validate a boolean option.
|
|
||||||
* ```ts
|
|
||||||
* abool(true, 'enableXOF');
|
|
||||||
* ```
|
|
||||||
*/
|
|
||||||
export function abool(value, title = '') {
|
|
||||||
if (typeof value !== 'boolean')
|
|
||||||
throw new TypeError(atitle(title) + 'expected boolean, got type=' + typeof value);
|
|
||||||
return value;
|
|
||||||
}
|
|
||||||
/**
|
|
||||||
* Asserts something is Uint8Array.
|
|
||||||
* @param value - value to validate
|
|
||||||
* @param length - optional exact length constraint
|
|
||||||
* @param title - label included in thrown errors
|
|
||||||
* @returns The validated byte array.
|
|
||||||
* @throws On wrong argument types. {@link TypeError}
|
|
||||||
* @throws On wrong argument ranges or values. {@link RangeError}
|
|
||||||
* @example
|
|
||||||
* Validate that a value is a byte array.
|
|
||||||
* ```ts
|
|
||||||
* abytes(new Uint8Array([1, 2, 3]));
|
|
||||||
* ```
|
|
||||||
*/
|
|
||||||
export function abytes(value, length, title = '') {
|
|
||||||
// Success path first: this runs at the start of every update() / digestInto(), and the
|
|
||||||
// common `abytes(data)` form must not pay for length handling it does not use.
|
|
||||||
if (isBytes(value) && (length === undefined || value.length === length))
|
|
||||||
return value;
|
|
||||||
// Error path: recompute freely to build the exact message.
|
|
||||||
if (length !== undefined)
|
|
||||||
anumber(length, 'length');
|
|
||||||
const bytes = isBytes(value);
|
|
||||||
const ofLen = length !== undefined ? ` of length ${length}` : '';
|
|
||||||
const got = bytes ? `length=${value.length}` : `type=${typeof value}`;
|
|
||||||
const message = atitle(title) + 'expected Uint8Array' + ofLen + ', got ' + got;
|
|
||||||
if (!bytes)
|
|
||||||
throw new TypeError(message);
|
|
||||||
throw new RangeError(message);
|
|
||||||
}
|
|
||||||
/**
|
|
||||||
* Copies bytes into a fresh Uint8Array.
|
|
||||||
* Buffer-style slices can alias the same backing store, so callers that need ownership should copy.
|
|
||||||
* @param bytes - source bytes to clone
|
|
||||||
* @returns Freshly allocated copy of `bytes`.
|
|
||||||
* @throws On wrong argument types. {@link TypeError}
|
|
||||||
* @example
|
|
||||||
* Clone a byte array before mutating it.
|
|
||||||
* ```ts
|
|
||||||
* const copy = copyBytes(new Uint8Array([1, 2, 3]));
|
|
||||||
* ```
|
|
||||||
*/
|
|
||||||
export function copyBytes(bytes) {
|
|
||||||
// `Uint8Array.from(...)` would also accept arrays / other typed arrays. Keep this helper strict
|
|
||||||
// because callers use it at byte-validation boundaries before mutating the detached copy.
|
|
||||||
return Uint8Array.from(abytes(bytes));
|
|
||||||
}
|
|
||||||
/**
|
|
||||||
* Asserts something is a wrapped hash constructor.
|
|
||||||
* @param h - hash constructor to validate
|
|
||||||
* @throws On wrong argument types or invalid hash wrapper shape. {@link TypeError}
|
|
||||||
* @throws On invalid hash metadata ranges or values. {@link RangeError}
|
|
||||||
* @throws If the hash metadata allows empty outputs or block sizes. {@link Error}
|
|
||||||
* @example
|
|
||||||
* Validate a callable hash wrapper.
|
|
||||||
* ```ts
|
|
||||||
* import { ahash } from '@noble/hashes/utils.js';
|
|
||||||
* import { sha256 } from '@noble/hashes/sha2.js';
|
|
||||||
* ahash(sha256);
|
|
||||||
* ```
|
|
||||||
*/
|
|
||||||
export function ahash(h) {
|
|
||||||
if (typeof h !== 'function' || typeof h.create !== 'function')
|
|
||||||
throw new TypeError('expected hash wrapped by utils.createHasher');
|
|
||||||
anumber(h.outputLen);
|
|
||||||
anumber(h.blockLen);
|
|
||||||
// HMAC and KDF callers treat these as real byte lengths; allowing zero lets fake wrappers pass
|
|
||||||
// validation and can produce empty outputs instead of failing fast.
|
|
||||||
if (h.outputLen < 1 || h.blockLen < 1)
|
|
||||||
throw new Error('hash blockLen / outputLen must be >= 1');
|
|
||||||
}
|
|
||||||
const aobject = (value, label) => {
|
|
||||||
if (value === null || typeof value !== 'object' || Array.isArray(value))
|
|
||||||
throw new TypeError((label === 'object' ? '' : `"${label}" `) + 'expected object, got type=' + typeof value);
|
|
||||||
};
|
|
||||||
const aopts = (value, label) => {
|
|
||||||
aobject(value, label);
|
|
||||||
const proto = Object.getPrototypeOf(value);
|
|
||||||
if (proto !== Object.prototype && proto !== null)
|
|
||||||
throw new TypeError(`"${label}" expected plain object`);
|
|
||||||
// Object.assign() treats an own "__proto__" source key as a write to the target's legacy
|
|
||||||
// prototype setter. Reject it before merging so inherited option values cannot be injected.
|
|
||||||
if (Object.hasOwn(value, '__proto__'))
|
|
||||||
throw new TypeError(`"${label}.__proto__" is not allowed`);
|
|
||||||
};
|
|
||||||
/**
|
|
||||||
* Asserts a hash instance has not been destroyed or finished.
|
|
||||||
* @param instance - hash instance to validate
|
|
||||||
* @param checkFinished - whether to reject finalized instances
|
|
||||||
* @throws If the hash instance has already been destroyed or finalized. {@link Error}
|
|
||||||
* @example
|
|
||||||
* Validate that a hash instance is still usable.
|
|
||||||
* ```ts
|
|
||||||
* import { aexists } from '@noble/hashes/utils.js';
|
|
||||||
* import { sha256 } from '@noble/hashes/sha2.js';
|
|
||||||
* const hash = sha256.create();
|
|
||||||
* aexists(hash);
|
|
||||||
* ```
|
|
||||||
*/
|
|
||||||
export function aexists(instance, checkFinished = true) {
|
|
||||||
// Runs on every update()/digestInto(); the flags are library-owned booleans, so only their
|
|
||||||
// truthiness is checked - re-validating their type per call was pure hot-path overhead.
|
|
||||||
if (instance.destroyed)
|
|
||||||
throw new Error('hash was destroyed');
|
|
||||||
if (checkFinished && instance.finished)
|
|
||||||
throw new Error('digest() was already called');
|
|
||||||
}
|
|
||||||
/**
|
|
||||||
* Asserts output is a sufficiently-sized byte array.
|
|
||||||
* @param out - destination buffer
|
|
||||||
* @param instance - hash instance providing output length
|
|
||||||
* Oversized buffers are allowed; downstream code only promises to fill the first `outputLen` bytes.
|
|
||||||
* @throws On wrong argument types. {@link TypeError}
|
|
||||||
* @throws On wrong argument ranges or values. {@link RangeError}
|
|
||||||
* @example
|
|
||||||
* Validate a caller-provided digest buffer.
|
|
||||||
* ```ts
|
|
||||||
* import { aoutput } from '@noble/hashes/utils.js';
|
|
||||||
* import { sha256 } from '@noble/hashes/sha2.js';
|
|
||||||
* const hash = sha256.create();
|
|
||||||
* aoutput(new Uint8Array(hash.outputLen), hash);
|
|
||||||
* ```
|
|
||||||
*/
|
|
||||||
export function aoutput(out, instance) {
|
|
||||||
abytes(out, undefined, 'output');
|
|
||||||
// `outputLen` is a library-owned readonly number; the negated comparison keeps failing fast
|
|
||||||
// when it is missing/NaN (comparisons with undefined/NaN are false) without an anumber() call.
|
|
||||||
const min = instance.outputLen;
|
|
||||||
if (!(out.length >= min)) {
|
|
||||||
throw new RangeError('"output" expected length >= ' + min);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
/**
|
|
||||||
* Casts a typed array view to Uint8Array.
|
|
||||||
* @param arr - source typed array
|
|
||||||
* @returns Uint8Array view over the same buffer.
|
|
||||||
* @example
|
|
||||||
* Reinterpret a typed array as bytes.
|
|
||||||
* ```ts
|
|
||||||
* u8(new Uint32Array([1, 2]));
|
|
||||||
* ```
|
|
||||||
*/
|
|
||||||
export function u8(arr) {
|
|
||||||
return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);
|
|
||||||
}
|
|
||||||
/**
|
|
||||||
* Casts a typed array view to Uint32Array.
|
|
||||||
* `arr.byteOffset` must already be 4-byte aligned or the platform
|
|
||||||
* Uint32Array constructor will throw.
|
|
||||||
* @param arr - source typed array
|
|
||||||
* @returns Uint32Array view over the same buffer.
|
|
||||||
* @example
|
|
||||||
* Reinterpret a byte array as 32-bit words.
|
|
||||||
* ```ts
|
|
||||||
* u32(new Uint8Array(8));
|
|
||||||
* ```
|
|
||||||
*/
|
|
||||||
export function u32(arr) {
|
|
||||||
return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));
|
|
||||||
}
|
|
||||||
/**
|
|
||||||
* Zeroizes typed arrays in place. Warning: JS provides no guarantees.
|
|
||||||
* @param arrays - arrays to overwrite with zeros
|
|
||||||
* @example
|
|
||||||
* Zeroize sensitive buffers in place.
|
|
||||||
* ```ts
|
|
||||||
* clean(new Uint8Array([1, 2, 3]));
|
|
||||||
* ```
|
|
||||||
*/
|
|
||||||
export function clean(...arrays) {
|
|
||||||
for (let i = 0; i < arrays.length; i++) {
|
|
||||||
arrays[i].fill(0);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
/**
|
|
||||||
* Creates a DataView for byte-level manipulation.
|
|
||||||
* @param arr - source typed array
|
|
||||||
* @returns DataView over the same buffer region.
|
|
||||||
* @example
|
|
||||||
* Create a DataView over an existing buffer.
|
|
||||||
* ```ts
|
|
||||||
* createView(new Uint8Array(4));
|
|
||||||
* ```
|
|
||||||
*/
|
|
||||||
export function createView(arr) {
|
|
||||||
return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
|
|
||||||
}
|
|
||||||
/**
|
|
||||||
* Rotate-right operation for uint32 values.
|
|
||||||
* @param word - source word
|
|
||||||
* @param shift - shift amount in bits
|
|
||||||
* @returns Rotated word.
|
|
||||||
* @example
|
|
||||||
* Rotate a 32-bit word to the right.
|
|
||||||
* ```ts
|
|
||||||
* rotr(0x12345678, 8);
|
|
||||||
* ```
|
|
||||||
*/
|
|
||||||
export function rotr(word, shift) {
|
|
||||||
return (word << (32 - shift)) | (word >>> shift);
|
|
||||||
}
|
|
||||||
/**
|
|
||||||
* Rotate-left operation for uint32 values.
|
|
||||||
* @param word - source word
|
|
||||||
* @param shift - shift amount in bits
|
|
||||||
* @returns Rotated word.
|
|
||||||
* @example
|
|
||||||
* Rotate a 32-bit word to the left.
|
|
||||||
* ```ts
|
|
||||||
* rotl(0x12345678, 8);
|
|
||||||
* ```
|
|
||||||
*/
|
|
||||||
export function rotl(word, shift) {
|
|
||||||
return (word << shift) | ((word >>> (32 - shift)) >>> 0);
|
|
||||||
}
|
|
||||||
/** Whether the current platform is little-endian. */
|
|
||||||
export const isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();
|
|
||||||
/**
|
|
||||||
* Byte-swap operation for uint32 values.
|
|
||||||
* @param word - source word
|
|
||||||
* @returns Word with reversed byte order.
|
|
||||||
* @example
|
|
||||||
* Reverse the byte order of a 32-bit word.
|
|
||||||
* ```ts
|
|
||||||
* byteSwap(0x11223344);
|
|
||||||
* ```
|
|
||||||
*/
|
|
||||||
export function byteSwap(word) {
|
|
||||||
return (((word << 24) & 0xff000000) |
|
|
||||||
((word << 8) & 0xff0000) |
|
|
||||||
((word >>> 8) & 0xff00) |
|
|
||||||
((word >>> 24) & 0xff));
|
|
||||||
}
|
|
||||||
/**
|
|
||||||
* Conditionally byte-swaps one 32-bit word on big-endian platforms.
|
|
||||||
* @param n - source word
|
|
||||||
* @returns Original or byte-swapped word depending on platform endianness.
|
|
||||||
* @example
|
|
||||||
* Normalize a 32-bit word for host endianness.
|
|
||||||
* ```ts
|
|
||||||
* swap8IfBE(0x11223344);
|
|
||||||
* ```
|
|
||||||
*/
|
|
||||||
export const swap8IfBE = isLE
|
|
||||||
? (n) => n
|
|
||||||
: (n) => byteSwap(n) >>> 0;
|
|
||||||
/**
|
|
||||||
* Byte-swaps every word of a Uint32Array in place.
|
|
||||||
* @param arr - array to mutate
|
|
||||||
* @returns The same array after mutation; callers pass live state arrays here.
|
|
||||||
* @example
|
|
||||||
* Reverse the byte order of every word in place.
|
|
||||||
* ```ts
|
|
||||||
* byteSwap32(new Uint32Array([0x11223344]));
|
|
||||||
* ```
|
|
||||||
*/
|
|
||||||
export function byteSwap32(arr) {
|
|
||||||
for (let i = 0; i < arr.length; i++) {
|
|
||||||
arr[i] = byteSwap(arr[i]);
|
|
||||||
}
|
|
||||||
return arr;
|
|
||||||
}
|
|
||||||
/**
|
|
||||||
* Conditionally byte-swaps a Uint32Array on big-endian platforms.
|
|
||||||
* @param u - array to normalize for host endianness
|
|
||||||
* @returns Original or byte-swapped array depending on platform endianness.
|
|
||||||
* On big-endian runtimes this mutates `u` in place via `byteSwap32(...)`.
|
|
||||||
* @example
|
|
||||||
* Normalize a word array for host endianness.
|
|
||||||
* ```ts
|
|
||||||
* swap32IfBE(new Uint32Array([0x11223344]));
|
|
||||||
* ```
|
|
||||||
*/
|
|
||||||
export const swap32IfBE = isLE
|
|
||||||
? (u) => u
|
|
||||||
: byteSwap32;
|
|
||||||
// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex
|
|
||||||
const hasHexBuiltin = /* @__PURE__ */ (() =>
|
|
||||||
// @ts-ignore
|
|
||||||
typeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function')();
|
|
||||||
// Array where index 0xf0 (240) is mapped to string 'f0'
|
|
||||||
const hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));
|
|
||||||
/**
|
|
||||||
* Convert byte array to hex string.
|
|
||||||
* Uses the built-in function when available and assumes it matches the tested
|
|
||||||
* fallback semantics.
|
|
||||||
* @param bytes - bytes to encode
|
|
||||||
* @returns Lowercase hexadecimal string.
|
|
||||||
* @throws On wrong argument types. {@link TypeError}
|
|
||||||
* @example
|
|
||||||
* Convert bytes to lowercase hexadecimal.
|
|
||||||
* ```ts
|
|
||||||
* bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])); // 'cafe0123'
|
|
||||||
* ```
|
|
||||||
*/
|
|
||||||
export function bytesToHex(bytes) {
|
|
||||||
abytes(bytes);
|
|
||||||
// @ts-ignore
|
|
||||||
if (hasHexBuiltin)
|
|
||||||
return bytes.toHex();
|
|
||||||
// pre-caching improves the speed 6x
|
|
||||||
let hex = '';
|
|
||||||
for (let i = 0; i < bytes.length; i++) {
|
|
||||||
hex += hexes[bytes[i]];
|
|
||||||
}
|
|
||||||
return hex;
|
|
||||||
}
|
|
||||||
// Strict ASCII nibble parser: non-ASCII hex lookalikes are rejected as undefined.
|
|
||||||
// ASCII codes: '0'..'9' = 48..57, 'A'..'F' = 65..70, 'a'..'f' = 97..102.
|
|
||||||
// prettier-ignore
|
|
||||||
function asciiToBase16(ch) {
|
|
||||||
return ch >= 48 && ch <= 57 ? ch - 48 // '2' => 50-48
|
|
||||||
: ch >= 65 && ch <= 70 ? ch - (65 - 10) // 'B' => 66-(65-10)
|
|
||||||
: ch >= 97 && ch <= 102 ? ch - (97 - 10) // 'b' => 98-(97-10)
|
|
||||||
: undefined;
|
|
||||||
}
|
|
||||||
/**
|
|
||||||
* Convert hex string to byte array. Uses built-in function, when available.
|
|
||||||
* @param hex - hexadecimal string to decode
|
|
||||||
* @returns Decoded bytes.
|
|
||||||
* @throws On wrong argument types. {@link TypeError}
|
|
||||||
* @throws On wrong argument ranges or values. {@link RangeError}
|
|
||||||
* @example
|
|
||||||
* Decode lowercase hexadecimal into bytes.
|
|
||||||
* ```ts
|
|
||||||
* hexToBytes('cafe0123'); // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])
|
|
||||||
* ```
|
|
||||||
*/
|
|
||||||
export function hexToBytes(hex) {
|
|
||||||
if (typeof hex !== 'string')
|
|
||||||
throw new TypeError('hex string expected, got ' + typeof hex);
|
|
||||||
if (hasHexBuiltin) {
|
|
||||||
try {
|
|
||||||
return Uint8Array.fromHex(hex);
|
|
||||||
}
|
|
||||||
catch (error) {
|
|
||||||
if (error instanceof SyntaxError)
|
|
||||||
throw new RangeError(error.message);
|
|
||||||
throw error;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
const hl = hex.length;
|
|
||||||
const al = hl / 2;
|
|
||||||
if (hl % 2)
|
|
||||||
throw new RangeError('hex string expected, got unpadded hex of length ' + hl);
|
|
||||||
const array = new Uint8Array(al);
|
|
||||||
for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
|
|
||||||
const n1 = asciiToBase16(hex.charCodeAt(hi)); // parse first char, multiply it by 16
|
|
||||||
const n2 = asciiToBase16(hex.charCodeAt(hi + 1)); // parse second char
|
|
||||||
if (n1 === undefined || n2 === undefined) {
|
|
||||||
const char = hex[hi] + hex[hi + 1];
|
|
||||||
throw new RangeError('hex string expected, got non-hex character "' + char + '" at index ' + hi);
|
|
||||||
}
|
|
||||||
array[ai] = n1 * 16 + n2; // example: 'A9' => 10*16 + 9
|
|
||||||
}
|
|
||||||
return array;
|
|
||||||
}
|
|
||||||
/**
|
|
||||||
* Yields to the host task scheduler so timers, I/O, and rendering can make progress.
|
|
||||||
* Uses the Web Scheduling API when available or `setTimeout` as a cross-platform fallback.
|
|
||||||
* Host-task yields are much slower than microtasks (roughly 1ms with the timer fallback), so
|
|
||||||
* async loops should use `asyncTick >= 10` to amortize scheduling overhead to about 10% while
|
|
||||||
* still allowing other event-loop work to proceed.
|
|
||||||
* @param onReject - optional cleanup invoked only if the host yield fails
|
|
||||||
* @example
|
|
||||||
* Yield to the next scheduler tick.
|
|
||||||
* ```ts
|
|
||||||
* await nextTick();
|
|
||||||
* ```
|
|
||||||
*/
|
|
||||||
export function nextTick(onReject) {
|
|
||||||
const host = globalThis;
|
|
||||||
if (typeof host.scheduler?.yield === 'function') {
|
|
||||||
const promise = host.scheduler.yield();
|
|
||||||
// Keep the original scheduler rejection; this handler exists only for cleanup.
|
|
||||||
if (onReject)
|
|
||||||
promise.catch(onReject);
|
|
||||||
return promise;
|
|
||||||
}
|
|
||||||
return new Promise((resolve) => host.setTimeout(resolve, 0));
|
|
||||||
}
|
|
||||||
/**
|
|
||||||
* Returns control to the host event loop every `tick` milliseconds to avoid blocking long loops.
|
|
||||||
* @param iters - number of loop iterations to run
|
|
||||||
* @param tick - maximum time slice in milliseconds
|
|
||||||
* @param cb - callback executed on each iteration
|
|
||||||
* @param onReject - optional cleanup invoked only if a host yield fails
|
|
||||||
* @throws On wrong argument types. {@link TypeError}
|
|
||||||
* @throws On wrong argument ranges or values. {@link RangeError}
|
|
||||||
* @example
|
|
||||||
* Run a loop that periodically yields back to the event loop.
|
|
||||||
* ```ts
|
|
||||||
* await asyncLoop(2, 0, () => {});
|
|
||||||
* ```
|
|
||||||
*/
|
|
||||||
export async function asyncLoop(iters, tick, cb, onReject) {
|
|
||||||
anumber(iters, 'iters');
|
|
||||||
anumber(tick, 'tick');
|
|
||||||
if (typeof cb !== 'function')
|
|
||||||
throw new TypeError('callback must be a function');
|
|
||||||
// Callback is synchronous by contract; asyncLoop only yields between sync work windows.
|
|
||||||
let ts = Date.now();
|
|
||||||
for (let i = 0; i < iters; i++) {
|
|
||||||
cb(i);
|
|
||||||
// Date.now() is not monotonic, so in case if clock goes backwards we return return control too
|
|
||||||
const diff = Date.now() - ts;
|
|
||||||
if (diff >= 0 && diff < tick)
|
|
||||||
continue;
|
|
||||||
await nextTick(onReject);
|
|
||||||
// Track only synchronous work time; scheduler delay after yielding is outside our budget.
|
|
||||||
ts = Date.now();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
/**
|
|
||||||
* Converts string to bytes using UTF8 encoding.
|
|
||||||
* Built-in doesn't validate input to be string: we do the check.
|
|
||||||
* Non-ASCII details are delegated to the platform `TextEncoder`.
|
|
||||||
* @param str - string to encode
|
|
||||||
* @returns UTF-8 encoded bytes.
|
|
||||||
* @throws On wrong argument types. {@link TypeError}
|
|
||||||
* @example
|
|
||||||
* Encode a string as UTF-8 bytes.
|
|
||||||
* ```ts
|
|
||||||
* utf8ToBytes('abc'); // Uint8Array.from([97, 98, 99])
|
|
||||||
* ```
|
|
||||||
*/
|
|
||||||
export function utf8ToBytes(str) {
|
|
||||||
if (typeof str !== 'string')
|
|
||||||
throw new TypeError('string expected');
|
|
||||||
const encoded = new TextEncoder().encode(str);
|
|
||||||
try {
|
|
||||||
// Copy into the current realm for Firefox extension contexts. Callers that own the returned
|
|
||||||
// buffer can then wipe it independently of TextEncoder's temporary result.
|
|
||||||
return new Uint8Array(encoded); // https://bugzil.la/1681809
|
|
||||||
}
|
|
||||||
finally {
|
|
||||||
clean(encoded);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
/**
|
|
||||||
* Helper for KDFs: consumes Uint8Array or string.
|
|
||||||
* String inputs are UTF-8 encoded; byte-array inputs stay aliased to the caller buffer.
|
|
||||||
* @param data - user-provided KDF input
|
|
||||||
* @param errorTitle - label included in thrown errors
|
|
||||||
* @returns Byte representation of the input.
|
|
||||||
* @throws On wrong argument types. {@link TypeError}
|
|
||||||
* @example
|
|
||||||
* Normalize KDF input to bytes.
|
|
||||||
* ```ts
|
|
||||||
* kdfInputToBytes('password');
|
|
||||||
* ```
|
|
||||||
*/
|
|
||||||
export function kdfInputToBytes(data, errorTitle = '') {
|
|
||||||
if (typeof data === 'string')
|
|
||||||
return utf8ToBytes(data);
|
|
||||||
return abytes(data, undefined, errorTitle);
|
|
||||||
}
|
|
||||||
/**
|
|
||||||
* Copies several Uint8Arrays into one.
|
|
||||||
* @param arrays - arrays to concatenate
|
|
||||||
* @returns Concatenated byte array.
|
|
||||||
* @throws On wrong argument types. {@link TypeError}
|
|
||||||
* @example
|
|
||||||
* Concatenate multiple byte arrays.
|
|
||||||
* ```ts
|
|
||||||
* concatBytes(new Uint8Array([1]), new Uint8Array([2]));
|
|
||||||
* ```
|
|
||||||
*/
|
|
||||||
export function concatBytes(...arrays) {
|
|
||||||
let sum = 0;
|
|
||||||
for (let i = 0; i < arrays.length; i++) {
|
|
||||||
const a = arrays[i];
|
|
||||||
abytes(a);
|
|
||||||
sum += a.length;
|
|
||||||
}
|
|
||||||
const res = new Uint8Array(sum);
|
|
||||||
for (let i = 0, pad = 0; i < arrays.length; i++) {
|
|
||||||
const a = arrays[i];
|
|
||||||
res.set(a, pad);
|
|
||||||
pad += a.length;
|
|
||||||
}
|
|
||||||
return res;
|
|
||||||
}
|
|
||||||
/**
|
|
||||||
* Validates declared required and optional field types on a plain object.
|
|
||||||
* This walks field schemas and formats detailed errors, so avoid it on hot paths; use direct
|
|
||||||
* one-line guards such as `abytes()`, `abool()`, or `anumber()` instead.
|
|
||||||
* @param object - object to validate
|
|
||||||
* @param fields - map of required field names to expected types
|
|
||||||
* @param optFields - map of optional field names to expected types
|
|
||||||
* @param title - label included in thrown errors
|
|
||||||
* @throws On wrong argument types. {@link TypeError}
|
|
||||||
* @example
|
|
||||||
* Validate required and optional option fields.
|
|
||||||
* ```ts
|
|
||||||
* validateObject({ N: 1024, dkLen: 32 }, { N: 'number' }, { dkLen: 'number' });
|
|
||||||
* ```
|
|
||||||
*/
|
|
||||||
export const validateObject = (object, fields = {}, optFields = {}, title = 'object') => {
|
|
||||||
aobject(object, title);
|
|
||||||
aobject(fields, 'fields');
|
|
||||||
aobject(optFields, 'optFields');
|
|
||||||
function checkField(fieldName, expectedType, isOpt) {
|
|
||||||
const label = title === 'object' ? `param "${String(fieldName)}"` : `"${title}.${String(fieldName)}"`;
|
|
||||||
// Config fields must be explicit own properties. Optional inherited values are rejected too
|
|
||||||
// because callers keep reading the same options object after validation.
|
|
||||||
const val = object[fieldName];
|
|
||||||
// Runtime objects such as Field instances intentionally satisfy required method slots
|
|
||||||
// via their shared prototype.
|
|
||||||
if (!Object.hasOwn(object, fieldName) &&
|
|
||||||
(isOpt ? val !== undefined : expectedType !== 'function')) {
|
|
||||||
throw new TypeError(`${label} is invalid: expected own property`);
|
|
||||||
}
|
|
||||||
if (isOpt && val === undefined)
|
|
||||||
return;
|
|
||||||
const current = typeof val;
|
|
||||||
if (current !== expectedType || val === null)
|
|
||||||
throw new TypeError(`${label} is invalid: expected ${expectedType}, got ${current}`);
|
|
||||||
}
|
|
||||||
const iter = (f, isOpt) => Object.entries(f).forEach(([k, v]) => checkField(k, v, isOpt));
|
|
||||||
iter(fields, false);
|
|
||||||
iter(optFields, true);
|
|
||||||
};
|
|
||||||
/**
|
|
||||||
* Merges default options and passed options.
|
|
||||||
* @param defaults - base option object
|
|
||||||
* @param opts - user overrides
|
|
||||||
* @param title - label included in thrown override errors
|
|
||||||
* @returns Fresh merged option object with a null prototype.
|
|
||||||
* @throws On wrong argument types. {@link TypeError}
|
|
||||||
* @example
|
|
||||||
* Merge user overrides onto default options.
|
|
||||||
* ```ts
|
|
||||||
* checkOpts({ dkLen: 32 }, { asyncTick: 10 });
|
|
||||||
* ```
|
|
||||||
*/
|
|
||||||
export function checkOpts(defaults, opts, title = 'opts') {
|
|
||||||
aopts(defaults, 'defaults');
|
|
||||||
if (opts !== undefined)
|
|
||||||
aopts(opts, title);
|
|
||||||
// Callers read optional fields directly, so omitted values must not fall through to ambient
|
|
||||||
// Object.prototype pollution (for example a forged `dkLen` changing SHAKE's default output).
|
|
||||||
const merged = Object.assign(Object.create(null), defaults, opts);
|
|
||||||
return merged;
|
|
||||||
}
|
|
||||||
/**
|
|
||||||
* Creates a callable hash function from a stateful class constructor.
|
|
||||||
* @param hashCons - hash constructor or factory
|
|
||||||
* @param info - optional metadata such as DER OID
|
|
||||||
* @returns Frozen callable hash wrapper with `.create()`.
|
|
||||||
* Wrapper construction eagerly calls `hashCons(undefined)` once to read
|
|
||||||
* `outputLen` / `blockLen`, so constructor side effects happen at module
|
|
||||||
* init time.
|
|
||||||
* @throws On wrong argument types. {@link TypeError}
|
|
||||||
* @example
|
|
||||||
* Wrap a stateful hash constructor into a callable helper.
|
|
||||||
* ```ts
|
|
||||||
* import { createHasher } from '@noble/hashes/utils.js';
|
|
||||||
* import { sha256 } from '@noble/hashes/sha2.js';
|
|
||||||
* const wrapped = createHasher(sha256.create, { oid: sha256.oid });
|
|
||||||
* wrapped(new Uint8Array([1]));
|
|
||||||
* ```
|
|
||||||
*/
|
|
||||||
export function createHasher(hashCons, info = {}) {
|
|
||||||
if (typeof hashCons !== 'function')
|
|
||||||
throw new TypeError('"hashCons" expected function, got type=' + typeof hashCons);
|
|
||||||
info = checkOpts({}, info, 'info');
|
|
||||||
const hashC = (msg, opts) => hashCons(opts)
|
|
||||||
.update(msg)
|
|
||||||
.digest();
|
|
||||||
const tmp = hashCons(undefined);
|
|
||||||
hashC.outputLen = tmp.outputLen;
|
|
||||||
hashC.blockLen = tmp.blockLen;
|
|
||||||
hashC.canXOF = tmp.canXOF;
|
|
||||||
hashC.create = (opts) => hashCons(opts);
|
|
||||||
Object.assign(hashC, info);
|
|
||||||
return Object.freeze(hashC);
|
|
||||||
}
|
|
||||||
/**
|
|
||||||
* Cryptographically secure PRNG backed by `crypto.getRandomValues`.
|
|
||||||
* @param bytesLength - number of random bytes to generate
|
|
||||||
* @returns Random bytes.
|
|
||||||
* The platform `getRandomValues()` implementation still defines any
|
|
||||||
* single-call length cap, and this helper rejects oversize requests
|
|
||||||
* with a stable library `RangeError` instead of host-specific errors.
|
|
||||||
* @throws On wrong argument types. {@link TypeError}
|
|
||||||
* @throws On wrong argument ranges or values. {@link RangeError}
|
|
||||||
* @throws If the current runtime does not provide `crypto.getRandomValues`. {@link Error}
|
|
||||||
* @example
|
|
||||||
* Generate a fresh random key or nonce.
|
|
||||||
* ```ts
|
|
||||||
* const key = randomBytes(16);
|
|
||||||
* ```
|
|
||||||
*/
|
|
||||||
export function randomBytes(bytesLength = 32) {
|
|
||||||
// Match the repo's other length-taking helpers instead of relying on Uint8Array coercion.
|
|
||||||
anumber(bytesLength, 'bytesLength');
|
|
||||||
const cr = typeof globalThis === 'object' ? globalThis.crypto : null;
|
|
||||||
if (typeof cr?.getRandomValues !== 'function')
|
|
||||||
throw new Error('crypto.getRandomValues must be defined');
|
|
||||||
// Web Cryptography API Level 2 §10.1.1:
|
|
||||||
// if `byteLength > 65536`, throw `QuotaExceededError`.
|
|
||||||
// Keep the guard explicit so callers can see the quota in code
|
|
||||||
// instead of discovering it by reading the spec or host errors.
|
|
||||||
// This wrapper surfaces the same quota as a stable library RangeError.
|
|
||||||
if (bytesLength > 65536)
|
|
||||||
throw new RangeError(`"bytesLength" expected <= 65536, got ${bytesLength}`);
|
|
||||||
return cr.getRandomValues(new Uint8Array(bytesLength));
|
|
||||||
}
|
|
||||||
/**
|
|
||||||
* Creates OID metadata for NIST hashes with prefix `06 09 60 86 48 01 65 03 04 02`.
|
|
||||||
* @param suffix - final OID byte for the selected hash.
|
|
||||||
* The helper accepts any byte even though only the documented NIST hash
|
|
||||||
* suffixes are meaningful downstream.
|
|
||||||
* @returns Object containing the DER-encoded OID.
|
|
||||||
* @example
|
|
||||||
* Build OID metadata for a NIST hash.
|
|
||||||
* ```ts
|
|
||||||
* oidNist(0x01);
|
|
||||||
* ```
|
|
||||||
*/
|
|
||||||
export const oidNist = (suffix) => ({
|
|
||||||
// Current NIST hashAlgs suffixes used here fit in one DER subidentifier octet.
|
|
||||||
// Larger suffix values would need base-128 OID encoding and a different length byte.
|
|
||||||
oid: Uint8Array.from([0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, suffix]),
|
|
||||||
});
|
|
||||||
|
|||||||
+858
-116
@@ -1,136 +1,878 @@
|
|||||||
"""SQLite storage layer: stores ONLY ciphertext records.
|
|
||||||
|
|
||||||
Record layout (all client-provided fields, opaque to the server):
|
|
||||||
id INTEGER PRIMARY KEY server surrogate key
|
|
||||||
uuid TEXT UNIQUE NOT NULL client-generated record id
|
|
||||||
ciphertext BLOB NOT NULL XChaCha20-Poly1305 payload (base64 in API)
|
|
||||||
nonce BLOB NOT NULL random 24-byte XChaCha nonce (base64 in API)
|
|
||||||
salt BLOB NOT NULL per-record Argon2id salt (base64 in API)
|
|
||||||
version INTEGER NOT NULL monotonic counter, bump on every update
|
|
||||||
created_at TEXT NOT NULL first seen server time (UTC ISO)
|
|
||||||
updated_at TEXT NOT NULL last update server time (UTC ISO)
|
|
||||||
|
|
||||||
The server never sees plaintext: no field contains decrypted data and
|
|
||||||
nothing is logged except the UUID/version bookkeeping.
|
|
||||||
"""
|
|
||||||
|
|
||||||
import sqlite3
|
import sqlite3
|
||||||
from datetime import datetime, timezone
|
import uuid
|
||||||
|
import time
|
||||||
DB_PATH = "instance/crushdb.sqlite3"
|
import hashlib
|
||||||
|
import hmac
|
||||||
|
|
||||||
def _connect():
|
|
||||||
conn = sqlite3.connect(DB_PATH)
|
|
||||||
conn.row_factory = sqlite3.Row
|
|
||||||
conn.execute("PRAGMA foreign_keys = ON")
|
|
||||||
return conn
|
|
||||||
|
|
||||||
|
|
||||||
def init_db():
|
|
||||||
"""Create tables if they do not exist yet."""
|
|
||||||
import os
|
import os
|
||||||
os.makedirs(os.path.dirname(DB_PATH), exist_ok=True)
|
|
||||||
with _connect() as conn:
|
|
||||||
conn.executescript(
|
|
||||||
"""
|
|
||||||
CREATE TABLE IF NOT EXISTS records (
|
|
||||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
||||||
uuid TEXT NOT NULL UNIQUE,
|
|
||||||
ciphertext BLOB NOT NULL,
|
|
||||||
nonce BLOB NOT NULL,
|
|
||||||
salt BLOB NOT NULL,
|
|
||||||
version INTEGER NOT NULL DEFAULT 1,
|
|
||||||
created_at TEXT NOT NULL,
|
|
||||||
updated_at TEXT NOT NULL
|
|
||||||
);
|
|
||||||
CREATE INDEX IF NOT EXISTS idx_records_uuid ON records(uuid);
|
|
||||||
"""
|
|
||||||
)
|
|
||||||
|
|
||||||
|
DB_PATH = os.environ.get("WHO2_DB_PATH", "instance/who2.sqlite")
|
||||||
|
|
||||||
def _now():
|
RIGHTS = {
|
||||||
return datetime.now(timezone.utc).isoformat()
|
"view_private": "Can view private articles",
|
||||||
|
"manage_persons": "Can manage persons",
|
||||||
|
"manage_articles": "Can manage articles",
|
||||||
def _row_to_dict(row):
|
"manage_groups": "Can manage groups",
|
||||||
if row is None:
|
"manage_accounts": "Can manage accounts",
|
||||||
return None
|
|
||||||
return {
|
|
||||||
"uuid": row["uuid"],
|
|
||||||
"ciphertext": row["ciphertext"],
|
|
||||||
"nonce": row["nonce"],
|
|
||||||
"salt": row["salt"],
|
|
||||||
"version": row["version"],
|
|
||||||
"created_at": row["created_at"],
|
|
||||||
"updated_at": row["updated_at"],
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
def list_records():
|
ADMIN_RIGHT = "manage_accounts"
|
||||||
with _connect() as conn:
|
|
||||||
rows = conn.execute(
|
|
||||||
"SELECT * FROM records ORDER BY id ASC"
|
def _grant_all_rights(conn, account_id: str) -> None:
|
||||||
|
for right_name in RIGHTS:
|
||||||
|
conn.execute(
|
||||||
|
"INSERT OR IGNORE INTO account_rights (account_id, right_name) VALUES (?,?)",
|
||||||
|
(account_id, right_name),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def bootstrap_admin(account_id: str) -> None:
|
||||||
|
"""Grant all rights to an account so it can manage the system.
|
||||||
|
|
||||||
|
In this model an account has no rights by default, so bootstrap grants a starting
|
||||||
|
set so the first admin can then grant rights to others.
|
||||||
|
"""
|
||||||
|
conn = _conn()
|
||||||
|
try:
|
||||||
|
_grant_all_rights(conn, account_id)
|
||||||
|
conn.commit()
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def is_admin(account: dict | None) -> bool:
|
||||||
|
return has_right(account, ADMIN_RIGHT)
|
||||||
|
|
||||||
|
|
||||||
|
def ensure_admin() -> None:
|
||||||
|
"""Guarantee that at least one account holds the admin right.
|
||||||
|
|
||||||
|
WHO2_ADMIN_EMAIL promotes that account when it exists. Otherwise the oldest
|
||||||
|
account is promoted, so an existing database gets exactly one admin.
|
||||||
|
"""
|
||||||
|
admin_email = (os.environ.get("WHO2_ADMIN_EMAIL") or "").strip()
|
||||||
|
conn = _conn()
|
||||||
|
try:
|
||||||
|
if admin_email:
|
||||||
|
row = conn.execute(
|
||||||
|
"SELECT id FROM accounts WHERE lower(email) = lower(?)", (admin_email,)
|
||||||
|
).fetchone()
|
||||||
|
if row:
|
||||||
|
_grant_all_rights(conn, row["id"])
|
||||||
|
conn.commit()
|
||||||
|
return
|
||||||
|
existing = conn.execute(
|
||||||
|
"SELECT account_id FROM account_rights WHERE right_name = ? LIMIT 1",
|
||||||
|
(ADMIN_RIGHT,),
|
||||||
|
).fetchone()
|
||||||
|
if existing:
|
||||||
|
return
|
||||||
|
# rowid breaks ties between accounts created in the same second, so the
|
||||||
|
# earliest-inserted account is reliably the one that gets promoted.
|
||||||
|
oldest = conn.execute("SELECT id FROM accounts ORDER BY created_at, rowid LIMIT 1").fetchone()
|
||||||
|
if oldest:
|
||||||
|
_grant_all_rights(conn, oldest["id"])
|
||||||
|
conn.commit()
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
ARTICLE_TYPES = [
|
||||||
|
"contact_details",
|
||||||
|
"notes",
|
||||||
|
"profile_text",
|
||||||
|
"documents",
|
||||||
|
"links",
|
||||||
|
"phone_numbers",
|
||||||
|
"addresses",
|
||||||
|
"social_profiles",
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def _now():
|
||||||
|
return int(time.time())
|
||||||
|
|
||||||
|
|
||||||
|
def _conn():
|
||||||
|
conn = sqlite3.connect(DB_PATH)
|
||||||
|
conn.row_factory = sqlite3.Row
|
||||||
|
conn.execute("PRAGMA journal_mode=WAL")
|
||||||
|
return conn
|
||||||
|
|
||||||
|
|
||||||
|
def _hash_password(password: str, salt: str) -> str:
|
||||||
|
key = (salt + password).encode("utf-8")
|
||||||
|
return hashlib.sha256(key).hexdigest()
|
||||||
|
|
||||||
|
|
||||||
|
def init_db():
|
||||||
|
conn = _conn()
|
||||||
|
try:
|
||||||
|
conn.executescript(
|
||||||
|
"""
|
||||||
|
CREATE TABLE IF NOT EXISTS accounts (
|
||||||
|
id TEXT PRIMARY KEY,
|
||||||
|
email TEXT NOT NULL UNIQUE,
|
||||||
|
password_hash TEXT NOT NULL,
|
||||||
|
password_salt TEXT NOT NULL,
|
||||||
|
created_at INTEGER NOT NULL
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS persons (
|
||||||
|
id TEXT PRIMARY KEY,
|
||||||
|
name TEXT NOT NULL DEFAULT '',
|
||||||
|
created_at INTEGER NOT NULL
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS person_accounts (
|
||||||
|
person_id TEXT NOT NULL,
|
||||||
|
account_id TEXT NOT NULL,
|
||||||
|
PRIMARY KEY (person_id, account_id),
|
||||||
|
FOREIGN KEY (person_id) REFERENCES persons(id),
|
||||||
|
FOREIGN KEY (account_id) REFERENCES accounts(id)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS articles (
|
||||||
|
id TEXT PRIMARY KEY,
|
||||||
|
person_id TEXT NOT NULL,
|
||||||
|
article_type TEXT NOT NULL CHECK(article_type IN (
|
||||||
|
'contact_details','notes','profile_text','documents',
|
||||||
|
'links','phone_numbers','addresses','social_profiles'
|
||||||
|
)),
|
||||||
|
title TEXT NOT NULL DEFAULT '',
|
||||||
|
content TEXT NOT NULL DEFAULT '',
|
||||||
|
visibility TEXT NOT NULL DEFAULT 'private'
|
||||||
|
CHECK(visibility IN ('private','group','public')),
|
||||||
|
created_at INTEGER NOT NULL,
|
||||||
|
updated_at INTEGER NOT NULL,
|
||||||
|
FOREIGN KEY (person_id) REFERENCES persons(id)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS groups (
|
||||||
|
id TEXT PRIMARY KEY,
|
||||||
|
person_id TEXT NOT NULL,
|
||||||
|
name TEXT NOT NULL DEFAULT '',
|
||||||
|
created_at INTEGER NOT NULL,
|
||||||
|
FOREIGN KEY (person_id) REFERENCES persons(id)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS group_members (
|
||||||
|
group_id TEXT NOT NULL,
|
||||||
|
person_id TEXT NOT NULL,
|
||||||
|
PRIMARY KEY (group_id, person_id),
|
||||||
|
FOREIGN KEY (group_id) REFERENCES groups(id),
|
||||||
|
FOREIGN KEY (person_id) REFERENCES persons(id)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS account_rights (
|
||||||
|
account_id TEXT NOT NULL,
|
||||||
|
right_name TEXT NOT NULL,
|
||||||
|
PRIMARY KEY (account_id, right_name),
|
||||||
|
FOREIGN KEY (account_id) REFERENCES accounts(id)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS article_group_access (
|
||||||
|
article_id TEXT NOT NULL,
|
||||||
|
group_id TEXT NOT NULL,
|
||||||
|
PRIMARY KEY (article_id, group_id),
|
||||||
|
FOREIGN KEY (article_id) REFERENCES articles(id),
|
||||||
|
FOREIGN KEY (group_id) REFERENCES groups(id)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_articles_person ON articles(person_id);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_group_members_group ON group_members(group_id);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_article_group_access_article ON article_group_access(article_id);
|
||||||
|
"""
|
||||||
|
)
|
||||||
|
conn.commit()
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
ensure_admin()
|
||||||
|
|
||||||
|
|
||||||
|
def create_account(email: str, password: str) -> dict:
|
||||||
|
if not email or "@" not in email:
|
||||||
|
raise ValueError("Invalid email address")
|
||||||
|
if not password:
|
||||||
|
raise ValueError("Password required")
|
||||||
|
salt = uuid.uuid4().hex
|
||||||
|
password_hash = _hash_password(password, salt)
|
||||||
|
account_id = uuid.uuid4().hex
|
||||||
|
conn = _conn()
|
||||||
|
try:
|
||||||
|
is_first = conn.execute("SELECT COUNT(*) AS c FROM accounts").fetchone()["c"] == 0
|
||||||
|
conn.execute(
|
||||||
|
"INSERT INTO accounts (id, email, password_hash, password_salt, created_at) VALUES (?,?,?,?,?)",
|
||||||
|
(account_id, email, password_hash, salt, _now()),
|
||||||
|
)
|
||||||
|
if is_first:
|
||||||
|
# The very first account becomes the bootstrap admin.
|
||||||
|
_grant_all_rights(conn, account_id)
|
||||||
|
conn.commit()
|
||||||
|
except sqlite3.IntegrityError as e:
|
||||||
|
raise ValueError("An account with this email already exists") from e
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
return get_account_by_id(account_id)
|
||||||
|
|
||||||
|
|
||||||
|
def authenticate(email: str, password: str) -> dict | None:
|
||||||
|
conn = _conn()
|
||||||
|
try:
|
||||||
|
row = conn.execute(
|
||||||
|
"SELECT id, email, password_hash, password_salt FROM accounts WHERE email = ?",
|
||||||
|
(email,),
|
||||||
|
).fetchone()
|
||||||
|
if not row:
|
||||||
|
return None
|
||||||
|
expected = _hash_password(password, row["password_salt"])
|
||||||
|
if not hmac.compare_digest(expected, row["password_hash"]):
|
||||||
|
return None
|
||||||
|
rights = [
|
||||||
|
r["right_name"] for r in conn.execute(
|
||||||
|
"SELECT right_name FROM account_rights WHERE account_id = ?",
|
||||||
|
(row["id"],),
|
||||||
).fetchall()
|
).fetchall()
|
||||||
return [_row_to_dict(r) for r in rows]
|
]
|
||||||
|
person = conn.execute(
|
||||||
|
"SELECT person_id FROM person_accounts WHERE account_id = ? ORDER BY person_id LIMIT 1",
|
||||||
def get_record(uuid):
|
(row["id"],),
|
||||||
with _connect() as conn:
|
|
||||||
row = conn.execute(
|
|
||||||
"SELECT * FROM records WHERE uuid = ?", (uuid,)
|
|
||||||
).fetchone()
|
).fetchone()
|
||||||
return _row_to_dict(row)
|
return {
|
||||||
|
"id": row["id"],
|
||||||
|
"email": row["email"],
|
||||||
|
"rights": rights,
|
||||||
|
"person_id": person["person_id"] if person else None,
|
||||||
|
"is_admin": ADMIN_RIGHT in rights,
|
||||||
|
}
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
def create_record(uuid, ciphertext, nonce, salt):
|
def has_right(account: dict | None, right: str) -> bool:
|
||||||
"""Insert a new encrypted record. Returns the stored dict with server metadata."""
|
if account is None:
|
||||||
|
return False
|
||||||
|
if right in account.get("rights", []):
|
||||||
|
return True
|
||||||
|
if "id" in account:
|
||||||
|
conn = _conn()
|
||||||
|
try:
|
||||||
|
row = conn.execute(
|
||||||
|
"SELECT 1 FROM account_rights WHERE account_id = ? AND right_name = ?",
|
||||||
|
(account["id"], right),
|
||||||
|
).fetchone()
|
||||||
|
return row is not None
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def create_person(account: dict | None, name: str = "") -> dict:
|
||||||
|
"""Create a person. Admins only; persons are never auto-linked to the creator."""
|
||||||
|
if account is None or not has_right(account, "manage_persons"):
|
||||||
|
raise PermissionError("Only admins can create persons")
|
||||||
|
if name is None:
|
||||||
|
name = ""
|
||||||
|
person_id = uuid.uuid4().hex
|
||||||
|
conn = _conn()
|
||||||
|
try:
|
||||||
|
conn.execute(
|
||||||
|
"INSERT INTO persons (id, name, created_at) VALUES (?,?,?)",
|
||||||
|
(person_id, name, _now()),
|
||||||
|
)
|
||||||
|
conn.commit()
|
||||||
|
return {"id": person_id, "name": name}
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def _find_account_by_email(email: str) -> dict | None:
|
||||||
|
conn = _conn()
|
||||||
|
try:
|
||||||
|
row = conn.execute(
|
||||||
|
"SELECT id, email FROM accounts WHERE lower(email) = lower(?)", (email,)
|
||||||
|
).fetchone()
|
||||||
|
if not row:
|
||||||
|
return None
|
||||||
|
return {"id": row["id"], "email": row["email"]}
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def link_account_to_person(account: dict | None, person_id: str, account_id: str) -> dict | None:
|
||||||
|
"""Link an account (email) to a person. Admins only.
|
||||||
|
|
||||||
|
The specification allows several accounts per person but only one person per
|
||||||
|
account, so an account already linked elsewhere is rejected.
|
||||||
|
"""
|
||||||
|
if account is None or not has_right(account, "manage_persons"):
|
||||||
|
raise PermissionError("Only admins can link accounts to persons")
|
||||||
|
conn = _conn()
|
||||||
|
try:
|
||||||
|
linked = conn.execute(
|
||||||
|
"SELECT person_id FROM person_accounts WHERE account_id = ?", (account_id,)
|
||||||
|
).fetchall()
|
||||||
|
for row in linked:
|
||||||
|
if row["person_id"] != person_id:
|
||||||
|
raise ValueError("This email is already linked to another person")
|
||||||
|
conn.execute(
|
||||||
|
"INSERT OR IGNORE INTO person_accounts (person_id, account_id) VALUES (?,?)",
|
||||||
|
(person_id, account_id),
|
||||||
|
)
|
||||||
|
conn.commit()
|
||||||
|
return get_person(person_id)
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def create_person_with_account(account: dict | None, name: str = "",
|
||||||
|
email: str | None = None, password: str | None = None) -> dict:
|
||||||
|
"""Admin flow: create a person and optionally give them an email address.
|
||||||
|
|
||||||
|
If the email has no account yet, an account is created for it (a password is
|
||||||
|
then required). Otherwise the existing account is linked to the new person.
|
||||||
|
"""
|
||||||
|
if account is None or not has_right(account, "manage_persons"):
|
||||||
|
raise PermissionError("Only admins can create persons")
|
||||||
|
person = create_person(account, name)
|
||||||
|
email = (email or "").strip()
|
||||||
|
if not email:
|
||||||
|
return get_person(person["id"])
|
||||||
|
target = _find_account_by_email(email)
|
||||||
|
if target is None:
|
||||||
|
if not password:
|
||||||
|
raise ValueError("A password is required to create the account for " + email)
|
||||||
|
target = create_account(email, password)
|
||||||
|
link_account_to_person(account, person["id"], target["id"])
|
||||||
|
return get_person(person["id"])
|
||||||
|
|
||||||
|
|
||||||
|
def list_persons(account: dict | None) -> list[dict]:
|
||||||
|
show_emails = is_admin(account)
|
||||||
|
conn = _conn()
|
||||||
|
try:
|
||||||
|
rows = conn.execute("SELECT id, name, created_at FROM persons ORDER BY name, id").fetchall()
|
||||||
|
out = []
|
||||||
|
for r in rows:
|
||||||
|
emails = []
|
||||||
|
if show_emails:
|
||||||
|
emails = [
|
||||||
|
a["email"] for a in conn.execute(
|
||||||
|
"SELECT a.email FROM accounts a JOIN person_accounts pa ON pa.account_id = a.id WHERE pa.person_id = ?",
|
||||||
|
(r["id"],),
|
||||||
|
).fetchall()
|
||||||
|
]
|
||||||
|
out.append({
|
||||||
|
"id": r["id"],
|
||||||
|
"name": r["name"],
|
||||||
|
"emails": sorted(set(emails)),
|
||||||
|
"created_at": r["created_at"],
|
||||||
|
})
|
||||||
|
return out
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def get_person(person_id: str) -> dict | None:
|
||||||
|
conn = _conn()
|
||||||
|
try:
|
||||||
|
row = conn.execute("SELECT id, name, created_at FROM persons WHERE id = ?", (person_id,)).fetchone()
|
||||||
|
if not row:
|
||||||
|
return None
|
||||||
|
person_accounts = [
|
||||||
|
a["email"] for a in conn.execute(
|
||||||
|
"SELECT a.email FROM accounts a JOIN person_accounts pa ON pa.account_id = a.id WHERE pa.person_id = ?",
|
||||||
|
(person_id,),
|
||||||
|
).fetchall()
|
||||||
|
]
|
||||||
|
groups = [
|
||||||
|
{"id": g["id"], "name": g["name"]}
|
||||||
|
for g in conn.execute("SELECT id, name FROM groups WHERE person_id = ?", (person_id,)).fetchall()
|
||||||
|
]
|
||||||
|
return {
|
||||||
|
"id": row["id"],
|
||||||
|
"name": row["name"],
|
||||||
|
"emails": sorted(set(person_accounts)),
|
||||||
|
"groups": groups,
|
||||||
|
"created_at": row["created_at"],
|
||||||
|
}
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def update_person(account: dict | None, person_id: str, name: str | None = None) -> dict | None:
|
||||||
|
person = get_person(person_id)
|
||||||
|
if person is None:
|
||||||
|
return None
|
||||||
|
conn = _conn()
|
||||||
|
try:
|
||||||
|
if name is not None:
|
||||||
|
conn.execute("UPDATE persons SET name = ? WHERE id = ?", (name if name is not None else "", person_id))
|
||||||
|
conn.commit()
|
||||||
|
return get_person(person_id)
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def delete_person(account: dict | None, person_id: str) -> bool:
|
||||||
|
person = get_person(person_id)
|
||||||
|
if person is None:
|
||||||
|
return False
|
||||||
|
conn = _conn()
|
||||||
|
try:
|
||||||
|
conn.execute("DELETE FROM articles WHERE person_id = ?", (person_id,))
|
||||||
|
conn.execute("DELETE FROM article_group_access WHERE article_id IN (SELECT id FROM articles WHERE person_id = ?)", (person_id,))
|
||||||
|
conn.execute("DELETE FROM group_members WHERE group_id IN (SELECT id FROM groups WHERE person_id = ?)", (person_id,))
|
||||||
|
conn.execute("DELETE FROM groups WHERE person_id = ?", (person_id,))
|
||||||
|
conn.execute("DELETE FROM person_accounts WHERE person_id = ?", (person_id,))
|
||||||
|
conn.execute("DELETE FROM persons WHERE id = ?", (person_id,))
|
||||||
|
conn.commit()
|
||||||
|
return True
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def create_article(account: dict, person_id: str, article_type: str, title: str, content: str,
|
||||||
|
visibility: str = "private", group_ids: list[str] | None = None) -> dict:
|
||||||
|
if article_type not in ARTICLE_TYPES:
|
||||||
|
raise ValueError("Invalid article type")
|
||||||
|
if visibility not in ("private", "group", "public"):
|
||||||
|
raise ValueError("Invalid visibility")
|
||||||
|
if account is None:
|
||||||
|
raise PermissionError("Not authenticated")
|
||||||
|
if not has_right(account, "manage_articles"):
|
||||||
|
if article_type != "notes":
|
||||||
|
raise PermissionError("Normal users can only add notes")
|
||||||
|
if person_id != account.get("person_id"):
|
||||||
|
raise PermissionError("You can only add notes to your own person")
|
||||||
|
article_id = uuid.uuid4().hex
|
||||||
now = _now()
|
now = _now()
|
||||||
with _connect() as conn:
|
conn = _conn()
|
||||||
cur = conn.execute(
|
try:
|
||||||
"""
|
conn.execute(
|
||||||
INSERT INTO records (uuid, ciphertext, nonce, salt, version, created_at, updated_at)
|
"INSERT INTO articles (id, person_id, article_type, title, content, visibility, created_at, updated_at) VALUES (?,?,?,?,?,?,?,?)",
|
||||||
VALUES (?, ?, ?, ?, 1, ?, ?)
|
(article_id, person_id, article_type, title, content, visibility, now, now),
|
||||||
""",
|
|
||||||
(uuid, ciphertext, nonce, salt, now, now),
|
|
||||||
)
|
)
|
||||||
row_id = cur.lastrowid
|
if group_ids:
|
||||||
row = conn.execute("SELECT * FROM records WHERE id = ?", (row_id,)).fetchone()
|
for gid in group_ids:
|
||||||
return _row_to_dict(row)
|
conn.execute("INSERT INTO article_group_access (article_id, group_id) VALUES (?,?)", (article_id, gid))
|
||||||
|
conn.commit()
|
||||||
|
return get_article(article_id)
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
def update_record(uuid, ciphertext, nonce, salt, expected_version):
|
def get_article(article_id: str) -> dict | None:
|
||||||
"""Replace ciphertext only if the client's version matches the stored one.
|
conn = _conn()
|
||||||
|
try:
|
||||||
|
row = conn.execute("SELECT * FROM articles WHERE id = ?", (article_id,)).fetchone()
|
||||||
|
if not row:
|
||||||
|
return None
|
||||||
|
allowed_groups = [
|
||||||
|
g["id"] for g in conn.execute(
|
||||||
|
"SELECT g.id FROM groups g JOIN article_group_access aga ON aga.group_id = g.id WHERE aga.article_id = ?",
|
||||||
|
(article_id,),
|
||||||
|
).fetchall()
|
||||||
|
]
|
||||||
|
return {
|
||||||
|
"id": row["id"],
|
||||||
|
"person_id": row["person_id"],
|
||||||
|
"article_type": row["article_type"],
|
||||||
|
"title": row["title"],
|
||||||
|
"content": row["content"],
|
||||||
|
"visibility": row["visibility"],
|
||||||
|
"created_at": row["created_at"],
|
||||||
|
"updated_at": row["updated_at"],
|
||||||
|
"allowed_groups": allowed_groups,
|
||||||
|
}
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
Returns the updated record dict, or None if:
|
|
||||||
- no record with that uuid exists
|
def list_articles(account: dict | None, person_id: str | None = None) -> list[dict]:
|
||||||
- expected_version does not match (someone else updated / replay attack)
|
conn = _conn()
|
||||||
"""
|
try:
|
||||||
with _connect() as conn:
|
query = "SELECT a.* FROM articles a"
|
||||||
|
params: list = []
|
||||||
|
if person_id:
|
||||||
|
query += " WHERE a.person_id = ?"
|
||||||
|
params.append(person_id)
|
||||||
|
query += " ORDER BY a.updated_at DESC, a.created_at DESC"
|
||||||
|
rows = conn.execute(query, params).fetchall()
|
||||||
|
out = []
|
||||||
|
for r in rows:
|
||||||
|
article = {
|
||||||
|
"id": r["id"],
|
||||||
|
"person_id": r["person_id"],
|
||||||
|
"article_type": r["article_type"],
|
||||||
|
"title": r["title"],
|
||||||
|
"visibility": r["visibility"],
|
||||||
|
"created_at": r["created_at"],
|
||||||
|
"updated_at": r["updated_at"],
|
||||||
|
}
|
||||||
|
allowed_groups = [
|
||||||
|
g["id"] for g in conn.execute(
|
||||||
|
"SELECT g.id FROM groups g JOIN article_group_access aga ON aga.group_id = g.id WHERE aga.article_id = ?",
|
||||||
|
(r["id"],),
|
||||||
|
).fetchall()
|
||||||
|
]
|
||||||
|
article["allowed_groups"] = allowed_groups
|
||||||
|
if _can_read_article(account, article):
|
||||||
|
article["content"] = r["content"]
|
||||||
|
else:
|
||||||
|
article["content"] = ""
|
||||||
|
out.append(article)
|
||||||
|
return out
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def _can_read_article(account: dict | None, article: dict) -> bool:
|
||||||
|
if article["visibility"] == "public":
|
||||||
|
return True
|
||||||
|
if account is None:
|
||||||
|
return False
|
||||||
|
# You always see the articles of your own person.
|
||||||
|
if article["person_id"] == account.get("person_id"):
|
||||||
|
return True
|
||||||
|
if article["visibility"] == "group":
|
||||||
|
for gid in article.get("allowed_groups", []):
|
||||||
|
if _account_in_group(account, gid):
|
||||||
|
return True
|
||||||
|
return False
|
||||||
|
if article["visibility"] == "private":
|
||||||
|
return has_right(account, "view_private") and article["person_id"] == account.get("person_id")
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def _account_in_group(account: dict, group_id: str) -> bool:
|
||||||
|
conn = _conn()
|
||||||
|
try:
|
||||||
row = conn.execute(
|
row = conn.execute(
|
||||||
"SELECT version FROM records WHERE uuid = ?", (uuid,)
|
"SELECT 1 FROM group_members gm JOIN person_accounts pa ON pa.person_id = gm.person_id WHERE gm.group_id = ? AND pa.account_id = ?",
|
||||||
|
(group_id, account["id"]),
|
||||||
).fetchone()
|
).fetchone()
|
||||||
if row is None or row["version"] != expected_version:
|
return row is not None
|
||||||
return None
|
finally:
|
||||||
cur = conn.execute(
|
conn.close()
|
||||||
"""
|
|
||||||
UPDATE records
|
|
||||||
SET ciphertext = ?, nonce = ?, salt = ?, version = version + 1, updated_at = ?
|
|
||||||
WHERE uuid = ? AND version = ?
|
|
||||||
""",
|
|
||||||
(ciphertext, nonce, salt, _now(), uuid, expected_version),
|
|
||||||
)
|
|
||||||
if cur.rowcount == 0:
|
|
||||||
return None
|
|
||||||
row = conn.execute("SELECT * FROM records WHERE uuid = ?", (uuid,)).fetchone()
|
|
||||||
return _row_to_dict(row)
|
|
||||||
|
|
||||||
|
|
||||||
def delete_record(uuid, expected_version):
|
def update_article(account: dict, article_id: str, title: str | None = None,
|
||||||
"""Delete a record only if the client's version matches. Returns True on success."""
|
content: str | None = None, visibility: str | None = None,
|
||||||
with _connect() as conn:
|
group_ids: list[str] | None = None) -> dict | None:
|
||||||
cur = conn.execute(
|
a = get_article(article_id)
|
||||||
"DELETE FROM records WHERE uuid = ? AND version = ?",
|
if a is None:
|
||||||
(uuid, expected_version),
|
return None
|
||||||
)
|
if a["person_id"] != account.get("person_id") and not has_right(account, "manage_articles"):
|
||||||
return cur.rowcount > 0
|
raise PermissionError("Not allowed to edit this article")
|
||||||
|
conn = _conn()
|
||||||
|
try:
|
||||||
|
if title is not None:
|
||||||
|
conn.execute("UPDATE articles SET title = ? WHERE id = ?", (title, article_id))
|
||||||
|
if content is not None:
|
||||||
|
conn.execute("UPDATE articles SET content = ? WHERE id = ?", (content, article_id))
|
||||||
|
if visibility is not None:
|
||||||
|
conn.execute("UPDATE articles SET visibility = ? WHERE id = ?", (visibility, article_id))
|
||||||
|
conn.execute("DELETE FROM article_group_access WHERE article_id = ?", (article_id,))
|
||||||
|
if group_ids is not None:
|
||||||
|
conn.execute("DELETE FROM article_group_access WHERE article_id = ?", (article_id,))
|
||||||
|
for gid in group_ids:
|
||||||
|
conn.execute("INSERT INTO article_group_access (article_id, group_id) VALUES (?,?)", (article_id, gid))
|
||||||
|
conn.execute("UPDATE articles SET updated_at = ? WHERE id = ?", (_now(), article_id))
|
||||||
|
conn.commit()
|
||||||
|
return get_article(article_id)
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def delete_article(account: dict, article_id: str) -> bool:
|
||||||
|
a = get_article(article_id)
|
||||||
|
if a is None:
|
||||||
|
return False
|
||||||
|
if a["person_id"] != account.get("person_id") and not has_right(account, "manage_articles"):
|
||||||
|
raise PermissionError("Not allowed to delete this article")
|
||||||
|
conn = _conn()
|
||||||
|
try:
|
||||||
|
conn.execute("DELETE FROM article_group_access WHERE article_id = ?", (article_id,))
|
||||||
|
conn.execute("DELETE FROM articles WHERE id = ?", (article_id,))
|
||||||
|
conn.commit()
|
||||||
|
return True
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def create_group(account: dict, person_id: str, name: str = "") -> dict:
|
||||||
|
if not has_right(account, "manage_groups") and account.get("person_id") != person_id:
|
||||||
|
raise PermissionError("Not allowed to create groups for this person")
|
||||||
|
group_id = uuid.uuid4().hex
|
||||||
|
conn = _conn()
|
||||||
|
try:
|
||||||
|
conn.execute("INSERT INTO groups (id, person_id, name, created_at) VALUES (?,?,?,?)",
|
||||||
|
(group_id, person_id, name, _now()))
|
||||||
|
conn.commit()
|
||||||
|
return {"id": group_id, "person_id": person_id, "name": name}
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def list_groups(account: dict | None, person_id: str | None = None) -> list[dict]:
|
||||||
|
conn = _conn()
|
||||||
|
try:
|
||||||
|
query = "SELECT id, person_id, name, created_at FROM groups"
|
||||||
|
params: list = []
|
||||||
|
if person_id:
|
||||||
|
query += " WHERE person_id = ?"
|
||||||
|
params.append(person_id)
|
||||||
|
query += " ORDER BY name, id"
|
||||||
|
rows = conn.execute(query, params).fetchall()
|
||||||
|
visible = _visible_group_ids(conn, account)
|
||||||
|
out = []
|
||||||
|
for r in rows:
|
||||||
|
if visible is not None and r["id"] not in visible:
|
||||||
|
continue
|
||||||
|
members = get_group_members(r["id"])
|
||||||
|
out.append({
|
||||||
|
"id": r["id"],
|
||||||
|
"person_id": r["person_id"],
|
||||||
|
"name": r["name"],
|
||||||
|
"created_at": r["created_at"],
|
||||||
|
"members": members,
|
||||||
|
})
|
||||||
|
return out
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def _visible_group_ids(conn, account: dict | None):
|
||||||
|
"""Group ids the account may see, or None for unrestricted (admins)."""
|
||||||
|
if account is None:
|
||||||
|
return set()
|
||||||
|
if has_right(account, "manage_groups"):
|
||||||
|
return None
|
||||||
|
person_id = account.get("person_id")
|
||||||
|
if not person_id:
|
||||||
|
return set()
|
||||||
|
ids = {row["id"] for row in conn.execute("SELECT id FROM groups WHERE person_id = ?", (person_id,)).fetchall()}
|
||||||
|
ids |= {row["group_id"] for row in conn.execute("SELECT group_id FROM group_members WHERE person_id = ?", (person_id,)).fetchall()}
|
||||||
|
return ids
|
||||||
|
|
||||||
|
|
||||||
|
def group_is_visible_to(account: dict | None, group_id: str) -> bool:
|
||||||
|
conn = _conn()
|
||||||
|
try:
|
||||||
|
visible = _visible_group_ids(conn, account)
|
||||||
|
return visible is None or group_id in visible
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def get_group(group_id: str) -> dict | None:
|
||||||
|
conn = _conn()
|
||||||
|
try:
|
||||||
|
row = conn.execute("SELECT id, person_id, name, created_at FROM groups WHERE id = ?", (group_id,)).fetchone()
|
||||||
|
if not row:
|
||||||
|
return None
|
||||||
|
return {
|
||||||
|
"id": row["id"],
|
||||||
|
"person_id": row["person_id"],
|
||||||
|
"name": row["name"],
|
||||||
|
"created_at": row["created_at"],
|
||||||
|
"members": get_group_members(group_id),
|
||||||
|
}
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def get_group_members(group_id: str) -> list[dict]:
|
||||||
|
conn = _conn()
|
||||||
|
try:
|
||||||
|
rows = conn.execute(
|
||||||
|
"SELECT p.id, p.name FROM persons p JOIN group_members gm ON gm.person_id = p.id WHERE gm.group_id = ?",
|
||||||
|
(group_id,),
|
||||||
|
).fetchall()
|
||||||
|
return [{"id": r["id"], "name": r["name"]} for r in rows]
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def add_group_member(account: dict, group_id: str, person_id: str) -> dict | None:
|
||||||
|
group = get_group(group_id)
|
||||||
|
if group is None:
|
||||||
|
return None
|
||||||
|
if account is None:
|
||||||
|
raise PermissionError("Not allowed to manage this group")
|
||||||
|
allowed = has_right(account, "manage_groups") or group["person_id"] == account.get("person_id")
|
||||||
|
if not allowed and account.get("person_id"):
|
||||||
|
conn = _conn()
|
||||||
|
try:
|
||||||
|
allowed = conn.execute(
|
||||||
|
"SELECT 1 FROM group_members WHERE group_id = ? AND person_id = ?",
|
||||||
|
(group_id, account["person_id"]),
|
||||||
|
).fetchone() is not None
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
if not allowed:
|
||||||
|
raise PermissionError("You can only invite people to groups you own or belong to")
|
||||||
|
person = get_person(person_id)
|
||||||
|
if person is None:
|
||||||
|
raise ValueError("Person not found")
|
||||||
|
conn = _conn()
|
||||||
|
try:
|
||||||
|
conn.execute("INSERT OR IGNORE INTO group_members (group_id, person_id) VALUES (?,?)", (group_id, person_id))
|
||||||
|
conn.commit()
|
||||||
|
return get_group(group_id)
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def remove_group_member(account: dict, group_id: str, person_id: str) -> dict | None:
|
||||||
|
group = get_group(group_id)
|
||||||
|
if group is None:
|
||||||
|
return None
|
||||||
|
if group["person_id"] != account.get("person_id") and not has_right(account, "manage_groups"):
|
||||||
|
raise PermissionError("Not allowed to manage this group")
|
||||||
|
conn = _conn()
|
||||||
|
try:
|
||||||
|
conn.execute("DELETE FROM group_members WHERE group_id = ? AND person_id = ?", (group_id, person_id))
|
||||||
|
conn.commit()
|
||||||
|
return get_group(group_id)
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def update_group(account: dict, group_id: str, name: str | None = None) -> dict | None:
|
||||||
|
group = get_group(group_id)
|
||||||
|
if group is None:
|
||||||
|
return None
|
||||||
|
if group["person_id"] != account.get("person_id") and not has_right(account, "manage_groups"):
|
||||||
|
raise PermissionError("Not allowed to manage this group")
|
||||||
|
conn = _conn()
|
||||||
|
try:
|
||||||
|
if name is not None:
|
||||||
|
conn.execute("UPDATE groups SET name = ? WHERE id = ?", (name, group_id))
|
||||||
|
conn.commit()
|
||||||
|
return get_group(group_id)
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def delete_group(account: dict, group_id: str) -> bool:
|
||||||
|
group = get_group(group_id)
|
||||||
|
if group is None:
|
||||||
|
return False
|
||||||
|
if group["person_id"] != account.get("person_id") and not has_right(account, "manage_groups"):
|
||||||
|
raise PermissionError("Not allowed to manage this group")
|
||||||
|
conn = _conn()
|
||||||
|
try:
|
||||||
|
conn.execute("DELETE FROM article_group_access WHERE group_id = ?", (group_id,))
|
||||||
|
conn.execute("DELETE FROM group_members WHERE group_id = ?", (group_id,))
|
||||||
|
conn.execute("DELETE FROM groups WHERE id = ?", (group_id,))
|
||||||
|
conn.commit()
|
||||||
|
return True
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def grant_right(account: dict, target_account_id: str, right_name: str):
|
||||||
|
if not has_right(account, "manage_accounts"):
|
||||||
|
raise PermissionError("Not allowed to manage account rights")
|
||||||
|
if right_name not in RIGHTS:
|
||||||
|
raise ValueError("Unknown right")
|
||||||
|
conn = _conn()
|
||||||
|
try:
|
||||||
|
conn.execute("INSERT OR IGNORE INTO account_rights (account_id, right_name) VALUES (?,?)",
|
||||||
|
(target_account_id, right_name))
|
||||||
|
conn.commit()
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def revoke_right(account: dict, target_account_id: str, right_name: str):
|
||||||
|
if not has_right(account, "manage_accounts"):
|
||||||
|
raise PermissionError("Not allowed to manage account rights")
|
||||||
|
conn = _conn()
|
||||||
|
try:
|
||||||
|
conn.execute("DELETE FROM account_rights WHERE account_id = ? AND right_name = ?",
|
||||||
|
(target_account_id, right_name))
|
||||||
|
conn.commit()
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def list_rights(account: dict | None, account_id: str | None = None) -> list[dict]:
|
||||||
|
if account is None or not has_right(account, "manage_accounts"):
|
||||||
|
raise PermissionError("Only admins can view account rights")
|
||||||
|
conn = _conn()
|
||||||
|
try:
|
||||||
|
query = "SELECT a.id, a.email, ar.right_name FROM accounts a LEFT JOIN account_rights ar ON ar.account_id = a.id"
|
||||||
|
params: list = []
|
||||||
|
if account_id:
|
||||||
|
query += " WHERE a.id = ?"
|
||||||
|
params.append(account_id)
|
||||||
|
query += " ORDER BY a.email, a.id, ar.right_name"
|
||||||
|
rows = conn.execute(query, params).fetchall()
|
||||||
|
out: dict = {}
|
||||||
|
for r in rows:
|
||||||
|
key = r["id"]
|
||||||
|
if key not in out:
|
||||||
|
out[key] = {"id": r["id"], "email": r["email"], "rights": []}
|
||||||
|
if r["right_name"]:
|
||||||
|
out[key]["rights"].append(r["right_name"])
|
||||||
|
return list(out.values())
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def attach_email_to_person(account: dict, person_id: str, email: str) -> dict | None:
|
||||||
|
if account is None or not has_right(account, "manage_persons"):
|
||||||
|
raise PermissionError("Only admins can change a person's emails")
|
||||||
|
target = _find_account_by_email(email)
|
||||||
|
if not target:
|
||||||
|
raise ValueError("No account exists for " + email)
|
||||||
|
return link_account_to_person(account, person_id, target["id"])
|
||||||
|
|
||||||
|
|
||||||
|
def detach_email_from_person(account: dict, person_id: str, email: str) -> dict | None:
|
||||||
|
if account is None or not has_right(account, "manage_persons"):
|
||||||
|
raise PermissionError("Only admins can change a person's emails")
|
||||||
|
conn = _conn()
|
||||||
|
try:
|
||||||
|
target = conn.execute(
|
||||||
|
"SELECT id FROM accounts WHERE lower(email) = lower(?)", (email,)
|
||||||
|
).fetchone()
|
||||||
|
if not target:
|
||||||
|
raise ValueError("No account exists for " + email)
|
||||||
|
conn.execute("DELETE FROM person_accounts WHERE person_id = ? AND account_id = ?",
|
||||||
|
(person_id, target["id"]))
|
||||||
|
conn.commit()
|
||||||
|
return get_person(person_id)
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def get_account_by_id(account_id: str) -> dict | None:
|
||||||
|
conn = _conn()
|
||||||
|
try:
|
||||||
|
row = conn.execute("SELECT id, email FROM accounts WHERE id = ?", (account_id,)).fetchone()
|
||||||
|
if not row:
|
||||||
|
return None
|
||||||
|
rights = [
|
||||||
|
r["right_name"] for r in conn.execute(
|
||||||
|
"SELECT right_name FROM account_rights WHERE account_id = ?",
|
||||||
|
(account_id,),
|
||||||
|
).fetchall()
|
||||||
|
]
|
||||||
|
person = conn.execute(
|
||||||
|
"SELECT person_id FROM person_accounts WHERE account_id = ? ORDER BY person_id LIMIT 1",
|
||||||
|
(account_id,),
|
||||||
|
).fetchone()
|
||||||
|
return {
|
||||||
|
"id": row["id"],
|
||||||
|
"email": row["email"],
|
||||||
|
"rights": rights,
|
||||||
|
"person_id": person["person_id"] if person else None,
|
||||||
|
"is_admin": ADMIN_RIGHT in rights,
|
||||||
|
}
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|||||||
+272
-82
@@ -1,101 +1,291 @@
|
|||||||
"""Integrity tests: tampering and replay of old records must be detected.
|
import os
|
||||||
|
import sys
|
||||||
|
import shutil
|
||||||
|
|
||||||
Server-side guarantees tested here:
|
# Use an isolated DB per test run
|
||||||
- Updating with a stale version (replay of an old ciphertext) -> 409
|
TEST_DB = "instance/test_integrity.sqlite"
|
||||||
- Deleting with a stale version -> 409
|
|
||||||
- Duplicate uuid creation -> 409
|
|
||||||
- Ciphertext tampering is impossible server-side without breaking the
|
|
||||||
version check chain: any modification requires pushing a NEW version,
|
|
||||||
which the client detects via its own version + AEAD tag on decrypt.
|
|
||||||
|
|
||||||
Client-side guarantees (AEAD/AAD binding; exercised via crypto.js):
|
os.environ["WHO2_DB_PATH"] = TEST_DB
|
||||||
- A ciphertext swapped between records fails the Poly1305 tag.
|
|
||||||
- A modified salt breaks the tag (re-key attempt detected).
|
|
||||||
- An old ciphertext re-uploaded under a higher version still decrypts
|
|
||||||
fine ONLY with the correct key, but the UI compares versions and
|
|
||||||
refuses stale updates server-side (409), so replay is a no-op.
|
|
||||||
|
|
||||||
Run: ./venv/bin/python -m pytest backend/test_integrity.py
|
import backend.storage as storage
|
||||||
"""
|
|
||||||
|
|
||||||
import base64
|
|
||||||
|
|
||||||
import pytest
|
|
||||||
|
|
||||||
from backend.app import app
|
|
||||||
from backend import storage
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture()
|
def _clean():
|
||||||
def client(tmp_path, monkeypatch):
|
if os.path.exists(TEST_DB):
|
||||||
monkeypatch.setattr(storage, "DB_PATH", str(tmp_path / "test.sqlite3"))
|
os.remove(TEST_DB)
|
||||||
|
if os.path.exists(TEST_DB + "-journal"):
|
||||||
|
os.remove(TEST_DB + "-journal")
|
||||||
|
if os.path.exists(TEST_DB + "-wal"):
|
||||||
|
os.remove(TEST_DB + "-wal")
|
||||||
|
if os.path.exists(TEST_DB + "-shm"):
|
||||||
|
os.remove(TEST_DB + "-shm")
|
||||||
|
|
||||||
|
|
||||||
|
def _reset():
|
||||||
|
_clean()
|
||||||
storage.init_db()
|
storage.init_db()
|
||||||
with app.test_client() as c:
|
|
||||||
yield c
|
|
||||||
|
|
||||||
|
|
||||||
def b64(data: bytes) -> str:
|
def test_create_and_authenticate():
|
||||||
return base64.b64encode(data).decode()
|
_reset()
|
||||||
|
email = "alice@example.com"
|
||||||
|
password = "Sup3rS3cret"
|
||||||
|
acc = storage.create_account(email, password)
|
||||||
|
assert acc["email"] == email
|
||||||
|
# first account becomes the bootstrap admin
|
||||||
|
assert acc["is_admin"] is True
|
||||||
|
assert storage.authenticate(email, password) is not None
|
||||||
|
assert storage.authenticate(email, "WRONG") is None
|
||||||
|
assert storage.authenticate("noone@example.com", password) is None
|
||||||
|
|
||||||
|
|
||||||
def make_body(uuid: str, marker: bytes):
|
def test_only_admins_create_persons():
|
||||||
return {
|
_reset()
|
||||||
"uuid": uuid,
|
admin = storage.create_account("admin@x.com", "pw")
|
||||||
"ciphertext": b64(marker),
|
user = storage.create_account("user@x.com", "pw")
|
||||||
"nonce": b64(b"\x01" * 24),
|
assert storage.is_admin(admin)
|
||||||
"salt": b64(b"\x02" * 16),
|
assert not storage.is_admin(user)
|
||||||
}
|
|
||||||
|
try:
|
||||||
|
storage.create_person(user, "Nope")
|
||||||
|
assert False, "expected PermissionError"
|
||||||
|
except PermissionError:
|
||||||
|
pass
|
||||||
|
|
||||||
|
# admin creates a person and gives it the user's email address
|
||||||
|
person = storage.create_person_with_account(admin, "User Person", "user@x.com")
|
||||||
|
refreshed = storage.get_account_by_id(user["id"])
|
||||||
|
assert refreshed["person_id"] == person["id"]
|
||||||
|
assert person["emails"] == ["user@x.com"]
|
||||||
|
|
||||||
|
# a non-admin cannot link or unlink emails either
|
||||||
|
try:
|
||||||
|
storage.attach_email_to_person(user, person["id"], "admin@x.com")
|
||||||
|
assert False, "expected PermissionError"
|
||||||
|
except PermissionError:
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
def test_stale_update_is_refused(client):
|
def test_person_account_linking():
|
||||||
uuid = "replay-test"
|
_reset()
|
||||||
old_body = make_body(uuid, b"OLD-CIPHERTEXT-v1")
|
admin = storage.create_account("admin@x.com", "pw")
|
||||||
|
# separate account so linking can be exercised explicitly
|
||||||
|
a = storage.create_account("a@x.com", "pw")
|
||||||
|
p = storage.create_person(admin, "Alice")
|
||||||
|
storage.link_account_to_person(admin, p["id"], a["id"])
|
||||||
|
person = storage.get_person(p["id"])
|
||||||
|
assert person["emails"] == ["a@x.com"]
|
||||||
|
|
||||||
r = client.post("/api/records", json=old_body)
|
# one account can only ever be linked to one person
|
||||||
assert r.status_code == 201
|
p2 = storage.create_person(admin, "Bob")
|
||||||
v1 = r.get_json()
|
try:
|
||||||
assert v1["version"] == 1
|
storage.attach_email_to_person(admin, p2["id"], "a@x.com")
|
||||||
|
assert False, "expected ValueError"
|
||||||
|
except ValueError:
|
||||||
|
pass
|
||||||
|
|
||||||
# legitimate update pushes version to 2
|
storage.attach_email_to_person(admin, p2["id"], "admin@x.com")
|
||||||
new_body = make_body(uuid, b"NEW-CIPHERTEXT-v2")
|
assert "admin@x.com" in storage.get_person(p2["id"])["emails"]
|
||||||
r = client.put(f"/api/records/{uuid}", json={**new_body, "version": 1})
|
# detaching works and is admin-only
|
||||||
assert r.status_code == 200
|
storage.detach_email_from_person(admin, p2["id"], "admin@x.com")
|
||||||
assert r.get_json()["version"] == 2
|
assert storage.get_person(p2["id"])["emails"] == []
|
||||||
|
try:
|
||||||
# REPLAY: attacker re-uploads the old ciphertext claiming version 1
|
storage.detach_email_from_person(a, p["id"], "a@x.com")
|
||||||
r = client.put(f"/api/records/{uuid}", json={**old_body, "version": 1})
|
assert False, "expected PermissionError"
|
||||||
assert r.status_code == 409
|
except PermissionError:
|
||||||
|
pass
|
||||||
# stale version 1 also cannot delete the record
|
|
||||||
r = client.delete(f"/api/records/{uuid}", json={"version": 1})
|
|
||||||
assert r.status_code == 409
|
|
||||||
|
|
||||||
# record still holds v2 content
|
|
||||||
rec = storage.get_record(uuid)
|
|
||||||
assert rec["ciphertext"] == b"NEW-CIPHERTEXT-v2"
|
|
||||||
assert rec["version"] == 2
|
|
||||||
|
|
||||||
|
|
||||||
def test_duplicate_uuid_refused(client):
|
def test_article_visibility():
|
||||||
body = make_body("dup-test", b"X")
|
_reset()
|
||||||
assert client.post("/api/records", json=body).status_code == 201
|
owner = storage.create_account("owner@x.com", "pw")
|
||||||
assert client.post("/api/records", json=body).status_code == 409
|
storage.bootstrap_admin(owner["id"])
|
||||||
|
owner["rights"] = list(storage.RIGHTS.keys())
|
||||||
|
admin_person = storage.create_person(owner, "Owner")
|
||||||
|
owner["person_id"] = admin_person["id"]
|
||||||
|
other = storage.create_account("other@x.com", "pw")
|
||||||
|
storage.grant_right(owner, other["id"], "view_private")
|
||||||
|
other["person_id"] = storage.create_person_with_account(owner, "Other", "other@x.com")["id"]
|
||||||
|
other["rights"] = ["view_private"]
|
||||||
|
|
||||||
|
storage.create_article(
|
||||||
|
owner, owner["person_id"], "notes", "Secret",
|
||||||
|
"hidden content", visibility="private",
|
||||||
|
)
|
||||||
|
articles = storage.list_articles(other, owner["person_id"])
|
||||||
|
assert len(articles) == 0 or articles[0].get("content") == ""
|
||||||
|
storage.grant_right(owner, owner["id"], "view_private")
|
||||||
|
articles = storage.list_articles(owner, owner["person_id"])
|
||||||
|
assert any(a["title"] == "Secret" and a.get("content") == "hidden content" for a in articles)
|
||||||
|
|
||||||
|
|
||||||
def test_delete_then_recreate_replay_still_safe(client):
|
def test_group_based_visibility():
|
||||||
# Deleting a record frees the uuid; recreate starts again at v1.
|
_reset()
|
||||||
# An attacker replaying the old (deleted) ciphertext must not be
|
owner = storage.create_account("owner@x.com", "pw")
|
||||||
# able to resurrect it over a newer legitimate record without
|
storage.bootstrap_admin(owner["id"])
|
||||||
# controlling the passphrase: the client's AEAD tag fails on
|
owner["rights"] = list(storage.RIGHTS.keys())
|
||||||
# decryption, surfacing the manipulation in the UI.
|
owner["person_id"] = storage.create_person(owner, "Owner")["id"]
|
||||||
body = make_body("res-test", b"DELETED-RECORD")
|
reader = storage.create_account("reader@x.com", "pw")
|
||||||
client.post("/api/records", json=body)
|
storage.grant_right(owner, reader["id"], "view_private")
|
||||||
assert client.delete("/api/records/res-test", json={"version": 1}).status_code == 204
|
reader["person_id"] = storage.create_person_with_account(owner, "Reader", "reader@x.com")["id"]
|
||||||
|
reader["rights"] = ["view_private"]
|
||||||
|
|
||||||
# recreate by attacker: uuid free again -> succeeds tamper-wise
|
group = storage.create_group(owner, owner["person_id"], "Team")
|
||||||
r = client.post("/api/records", json=body)
|
storage.add_group_member(owner, group["id"], reader["person_id"])
|
||||||
assert r.status_code == 201
|
|
||||||
# but the record content differs from what the client last wrote,
|
storage.create_article(
|
||||||
# and any legitimate client session still holds the AEAD key: the
|
owner, owner["person_id"], "notes", "Shared",
|
||||||
# tampered payload fails decryption and is flagged in the UI table.
|
"shared content", visibility="group",
|
||||||
assert storage.get_record("res-test")["ciphertext"] == b"DELETED-RECORD"
|
group_ids=[group["id"]],
|
||||||
|
)
|
||||||
|
noaccess = storage.list_articles(None, owner["person_id"])
|
||||||
|
assert not any(a["title"] == "Shared" and a.get("content") == "shared content" for a in noaccess)
|
||||||
|
|
||||||
|
view = storage.list_articles(reader, owner["person_id"])
|
||||||
|
assert any(a["title"] == "Shared" and a.get("content") == "shared content" for a in view)
|
||||||
|
|
||||||
|
|
||||||
|
def test_normal_user_only_notes_and_own_groups():
|
||||||
|
_reset()
|
||||||
|
admin = storage.create_account("admin@x.com", "pw")
|
||||||
|
me = storage.create_person_with_account(admin, "Me", "me@x.com", "pw")
|
||||||
|
friend = storage.create_person_with_account(admin, "Friend", "friend@x.com", "pw")
|
||||||
|
user = storage.authenticate("me@x.com", "pw")
|
||||||
|
assert user["person_id"] == me["id"]
|
||||||
|
assert not user["is_admin"]
|
||||||
|
|
||||||
|
# a normal user may add notes to their own person only
|
||||||
|
storage.create_article(user, me["id"], "notes", "Note", "hello", visibility="private")
|
||||||
|
try:
|
||||||
|
storage.create_article(user, me["id"], "links", "Link", "http://x")
|
||||||
|
assert False, "expected PermissionError"
|
||||||
|
except PermissionError:
|
||||||
|
pass
|
||||||
|
try:
|
||||||
|
storage.create_article(user, friend["id"], "notes", "Peek", "nope")
|
||||||
|
assert False, "expected PermissionError"
|
||||||
|
except PermissionError:
|
||||||
|
pass
|
||||||
|
|
||||||
|
# own group + invite a friend into it
|
||||||
|
g = storage.create_group(user, me["id"], "My Team")
|
||||||
|
storage.add_group_member(user, g["id"], friend["id"])
|
||||||
|
assert any(m["id"] == friend["id"] for m in storage.get_group(g["id"])["members"])
|
||||||
|
|
||||||
|
friend_user = storage.authenticate("friend@x.com", "pw")
|
||||||
|
admin_person = storage.create_person(admin, "Admin")
|
||||||
|
foreign = storage.create_group(admin, admin_person["id"], "Admins")
|
||||||
|
|
||||||
|
# the friend is a member, so they see the group but not foreign groups
|
||||||
|
assert {x["id"] for x in storage.list_groups(friend_user)} == {g["id"]}
|
||||||
|
assert foreign["id"] not in {x["id"] for x in storage.list_groups(friend_user)}
|
||||||
|
assert not storage.group_is_visible_to(friend_user, foreign["id"])
|
||||||
|
|
||||||
|
# a member may invite, a bystander may not
|
||||||
|
try:
|
||||||
|
storage.add_group_member(friend_user, foreign["id"], friend_user["person_id"])
|
||||||
|
assert False, "expected PermissionError"
|
||||||
|
except PermissionError:
|
||||||
|
pass
|
||||||
|
|
||||||
|
# only admins may read the rights list
|
||||||
|
try:
|
||||||
|
storage.list_rights(user)
|
||||||
|
assert False, "expected PermissionError"
|
||||||
|
except PermissionError:
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
def test_ensure_admin_promotes_oldest_account():
|
||||||
|
_reset()
|
||||||
|
storage.create_account("first@x.com", "pw")
|
||||||
|
storage.create_account("second@x.com", "pw")
|
||||||
|
conn = storage._conn()
|
||||||
|
conn.execute("DELETE FROM account_rights") # simulate a database from before roles existed
|
||||||
|
conn.commit()
|
||||||
|
conn.close()
|
||||||
|
assert storage.authenticate("first@x.com", "pw")["is_admin"] is False
|
||||||
|
storage.ensure_admin()
|
||||||
|
assert storage.authenticate("first@x.com", "pw")["is_admin"] is True
|
||||||
|
assert storage.authenticate("second@x.com", "pw")["is_admin"] is False
|
||||||
|
|
||||||
|
|
||||||
|
def test_article_type_constraint():
|
||||||
|
_reset()
|
||||||
|
acc = storage.create_account("x@x.com", "pw")
|
||||||
|
acc["person_id"] = storage.create_person(acc, "X")["id"]
|
||||||
|
try:
|
||||||
|
storage.create_article(acc, acc["person_id"], "bogus", "T", "C")
|
||||||
|
assert False, "expected ValueError"
|
||||||
|
except ValueError as e:
|
||||||
|
assert "Invalid article type" in str(e)
|
||||||
|
|
||||||
|
|
||||||
|
def test_right_management():
|
||||||
|
_reset()
|
||||||
|
admin = storage.create_account("admin@x.com", "pw")
|
||||||
|
storage.bootstrap_admin(admin["id"])
|
||||||
|
admin["rights"] = list(storage.RIGHTS.keys())
|
||||||
|
admin["person_id"] = storage.create_person(admin, "Admin")["id"]
|
||||||
|
storage.grant_right(admin, admin["id"], "view_private")
|
||||||
|
storage.grant_right(admin, admin["id"], "manage_articles")
|
||||||
|
rights = storage.list_rights(admin, admin["id"])
|
||||||
|
assert any(r["id"] == admin["id"] and "view_private" in r["rights"] for r in rights)
|
||||||
|
storage.revoke_right(admin, admin["id"], "manage_articles")
|
||||||
|
rights = storage.list_rights(admin)
|
||||||
|
assert any(r["id"] == admin["id"] and "view_private" in r["rights"] for r in rights)
|
||||||
|
assert not any(r["id"] == admin["id"] and "manage_articles" in r["rights"] for r in rights)
|
||||||
|
|
||||||
|
|
||||||
|
def test_delete_person_cascades():
|
||||||
|
_reset()
|
||||||
|
acc = storage.create_account("x@x.com", "pw")
|
||||||
|
acc["person_id"] = storage.create_person(acc, "X")["id"]
|
||||||
|
g = storage.create_group(acc, acc["person_id"], "G")
|
||||||
|
storage.add_group_member(acc, g["id"], acc["person_id"])
|
||||||
|
storage.create_article(acc, acc["person_id"], "notes", "T", "C")
|
||||||
|
ok = storage.delete_person(acc, acc["person_id"])
|
||||||
|
assert ok
|
||||||
|
assert storage.get_person(acc["person_id"]) is None
|
||||||
|
assert storage.get_group(g["id"]) is None
|
||||||
|
|
||||||
|
|
||||||
|
def run_all():
|
||||||
|
tests = [
|
||||||
|
test_create_and_authenticate,
|
||||||
|
test_only_admins_create_persons,
|
||||||
|
test_person_account_linking,
|
||||||
|
test_article_visibility,
|
||||||
|
test_group_based_visibility,
|
||||||
|
test_normal_user_only_notes_and_own_groups,
|
||||||
|
test_ensure_admin_promotes_oldest_account,
|
||||||
|
test_article_type_constraint,
|
||||||
|
test_right_management,
|
||||||
|
test_delete_person_cascades,
|
||||||
|
]
|
||||||
|
passed = 0
|
||||||
|
failed = 0
|
||||||
|
last_err = None
|
||||||
|
for t in tests:
|
||||||
|
try:
|
||||||
|
t()
|
||||||
|
passed += 1
|
||||||
|
print("PASS", t.__name__)
|
||||||
|
except AssertionError as e:
|
||||||
|
failed += 1
|
||||||
|
last_err = e
|
||||||
|
print("FAIL", t.__name__, "-", str(e))
|
||||||
|
except Exception as e:
|
||||||
|
failed += 1
|
||||||
|
last_err = e
|
||||||
|
print("ERROR", t.__name__, "-", str(e))
|
||||||
|
_clean()
|
||||||
|
if failed:
|
||||||
|
print(f"\n{passed} passed, {failed} failed")
|
||||||
|
raise SystemExit(1)
|
||||||
|
print(f"\nAll {passed} tests passed")
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
sys.exit(run_all())
|
||||||
|
|||||||
@@ -1,44 +0,0 @@
|
|||||||
# crushdb systemd unit
|
|
||||||
#
|
|
||||||
# Installieren (als root):
|
|
||||||
# cp deploy/crushdb.service /etc/systemd/system/
|
|
||||||
# systemctl daemon-reload
|
|
||||||
# systemctl enable --now crushdb
|
|
||||||
#
|
|
||||||
# Die App lauscht auf http://127.0.0.1:8085 (siehe Environment unten)
|
|
||||||
# hinter einem vertrauenswürdigen Reverse Proxy (nginx/caddy), der
|
|
||||||
# TLS terminiert.
|
|
||||||
|
|
||||||
[Unit]
|
|
||||||
Description=crushdb - encrypted record database (Flask)
|
|
||||||
After=network.target
|
|
||||||
|
|
||||||
[Service]
|
|
||||||
Type=simple
|
|
||||||
# Pfade anpassen, wo dieses Repo liegt:
|
|
||||||
User=jonas
|
|
||||||
Group=jonas
|
|
||||||
WorkingDirectory=/srv/crushdb
|
|
||||||
ExecStart=/srv/crushdb/venv/bin/python /srv/crushdb/run.py
|
|
||||||
Environment=HOST=127.0.0.1
|
|
||||||
Environment=PORT=8085
|
|
||||||
|
|
||||||
# Nur der SQLite-Ordner darf beschrieben werden; sonst ist das FS read-only.
|
|
||||||
ReadWritePaths=/srv/crushdb/instance
|
|
||||||
|
|
||||||
# Hardening: nur das nötigste erlauben
|
|
||||||
NoNewPrivileges=yes
|
|
||||||
PrivateTmp=yes
|
|
||||||
ProtectSystem=strict
|
|
||||||
ProtectHome=yes
|
|
||||||
ProtectKernelTunables=yes
|
|
||||||
ProtectControlGroups=yes
|
|
||||||
RestrictSUIDSGID=yes
|
|
||||||
CapabilityBoundingSet=
|
|
||||||
RestrictAddressFamilies=AF_INET AF_INET6 AF_UNIX
|
|
||||||
|
|
||||||
Restart=on-failure
|
|
||||||
RestartSec=3
|
|
||||||
|
|
||||||
[Install]
|
|
||||||
WantedBy=multi-user.target
|
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
[Unit]
|
||||||
|
Description=Who² contact directory
|
||||||
|
After=network.target
|
||||||
|
|
||||||
|
[Service]
|
||||||
|
Type=simple
|
||||||
|
User=www-data
|
||||||
|
Group=www-data
|
||||||
|
WorkingDirectory=/srv/serverjonas/who2
|
||||||
|
Environment=WHO2_DB_PATH=instance/who2.sqlite
|
||||||
|
Environment=FLASK_SECRET_KEY=replace-me-in-production
|
||||||
|
ExecStart=/usr/bin/python3 /srv/serverjonas/who2/run.py
|
||||||
|
Restart=on-failure
|
||||||
|
RestartSec=5
|
||||||
|
|
||||||
|
[Install]
|
||||||
|
WantedBy=multi-user.target
|
||||||
+3
-1
@@ -1 +1,3 @@
|
|||||||
flask>=3.0
|
python-dotenv>=1.0
|
||||||
|
Flask>=3.0
|
||||||
|
Jinja2>=3.1
|
||||||
|
|||||||
@@ -1,25 +1,38 @@
|
|||||||
"""Entrypoint. Runs the Flask app over plain HTTP on a local port.
|
|
||||||
|
|
||||||
TLS is NOT terminated here: a trusted reverse proxy (nginx/caddy/...)
|
|
||||||
in front handles HTTPS and forwards to this internal HTTP port. The
|
|
||||||
proxy must be the only thing reachable from outside; bind this app to
|
|
||||||
127.0.0.1 (or a private interface) only.
|
|
||||||
"""
|
|
||||||
|
|
||||||
import os
|
import os
|
||||||
|
|
||||||
from backend.app import app
|
from werkzeug.serving import WSGIRequestHandler
|
||||||
from backend import storage
|
|
||||||
|
from backend.app import create_app
|
||||||
|
|
||||||
|
app = create_app()
|
||||||
|
|
||||||
|
|
||||||
def main():
|
class RedactingRequestHandler(WSGIRequestHandler):
|
||||||
storage.init_db()
|
"""Werkzeug access log handler that never writes query strings to the log.
|
||||||
|
|
||||||
host = os.environ.get("HOST", "127.0.0.1")
|
Credentials must never be sent in URLs, but as defense in depth this also
|
||||||
port = int(os.environ.get("PORT", "8085"))
|
prevents any accidental query value (tokens, emails, passwords) from being
|
||||||
|
recorded in the server log.
|
||||||
|
"""
|
||||||
|
|
||||||
app.run(host=host, port=port)
|
def log_request(self, code="-", size="-"):
|
||||||
|
try:
|
||||||
|
target = self.path or self.requestline.split(" ")[1]
|
||||||
|
except Exception:
|
||||||
|
target = self.requestline
|
||||||
|
if "?" in target:
|
||||||
|
target = target.split("?", 1)[0] + "?[redacted]"
|
||||||
|
try:
|
||||||
|
msg = f"{self.command} {target} {self.request_version}"
|
||||||
|
except Exception:
|
||||||
|
msg = self.requestline
|
||||||
|
code = str(code)
|
||||||
|
level = "warning" if code[:1] in ("4", "5") else "info"
|
||||||
|
self.log(level, '"%s" %s %s', msg, code, size)
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
main()
|
host = os.environ.get("FLASK_HOST", "127.0.0.1")
|
||||||
|
port = int(os.environ.get("FLASK_PORT", "8085"))
|
||||||
|
debug = os.environ.get("FLASK_DEBUG", "false").lower() == "true"
|
||||||
|
app.run(host=host, port=port, debug=debug, request_handler=RedactingRequestHandler)
|
||||||
|
|||||||
@@ -0,0 +1,168 @@
|
|||||||
|
SPECIFICATION (German)
|
||||||
|
|
||||||
|
Project role
|
||||||
|
- This is an online contact directory / personal archive, not a transaction
|
||||||
|
ledger. Its main job is to store and share structured information about
|
||||||
|
people and their related items under controlled access.
|
||||||
|
|
||||||
|
Core concepts
|
||||||
|
- Account (Login identity)
|
||||||
|
* One account is permanently tied to exactly one email address.
|
||||||
|
* Each email address has its own password.
|
||||||
|
* Different accounts can have different rights.
|
||||||
|
* An account is the login boundary, not the data owner in every case.
|
||||||
|
|
||||||
|
- Person
|
||||||
|
* A person is the central real-world entity.
|
||||||
|
* One person can be linked to multiple email addresses / accounts but every account /e-mail can only be linke to oner person.
|
||||||
|
* A person is not owned by any single account.
|
||||||
|
|
||||||
|
- Article
|
||||||
|
* Every person has articles.
|
||||||
|
* Articles exist in different article types.
|
||||||
|
* Article visibility is not global.
|
||||||
|
* Articles are only visible to people who hold the required rights and/or
|
||||||
|
belong to the required group(s).
|
||||||
|
|
||||||
|
- Article types
|
||||||
|
* Examples of article types:
|
||||||
|
- Contact details
|
||||||
|
- Notes
|
||||||
|
- Profile text
|
||||||
|
- Documents
|
||||||
|
- Links
|
||||||
|
- Phone numbers
|
||||||
|
- Addresses
|
||||||
|
- Social profiles
|
||||||
|
* The set of article types is fixed for the implementation, but the system
|
||||||
|
treats them as distinct, named categories.
|
||||||
|
|
||||||
|
- Groups
|
||||||
|
* Groups are person-dependent.
|
||||||
|
* Groups are NOT email-dependent.
|
||||||
|
* A group describes a set of persons.
|
||||||
|
* Group membership follows the person, regardless of which account or email
|
||||||
|
is used to access the system.
|
||||||
|
|
||||||
|
- Rights
|
||||||
|
* Rights are fixed, named capabilities.
|
||||||
|
* Rights control what can be seen, created, edited, or removed.
|
||||||
|
* Rights are used together with group membership to decide access.
|
||||||
|
|
||||||
|
Relationships
|
||||||
|
- Account <-> email
|
||||||
|
* One account, one email address, fixed binding.
|
||||||
|
- Email <-> password
|
||||||
|
* Each email has its own password.
|
||||||
|
- Person <-> accounts / emails
|
||||||
|
* One person may relate to several emails/accounts.
|
||||||
|
- Person <-> groups
|
||||||
|
* Groups are built around persons.
|
||||||
|
- Person <-> articles
|
||||||
|
* A person owns articles of various types.
|
||||||
|
- Articles <-> readers
|
||||||
|
* Reading and other actions depend on rights.
|
||||||
|
* Reading can also depend on group membership.
|
||||||
|
- Groups <-> persons
|
||||||
|
* Membership is defined by persons, not by accounts.
|
||||||
|
|
||||||
|
Access model
|
||||||
|
- Visibility rule
|
||||||
|
* An article is shown only if the requesting party has the required right
|
||||||
|
AND is allowed by the relevant group constraints.
|
||||||
|
* If either condition is not met, the article is not visible.
|
||||||
|
- Purpose of the rule
|
||||||
|
* Some articles are private.
|
||||||
|
* Some articles are shared only with selected persons or groups.
|
||||||
|
* Group-based visibility is independent from email/account identity.
|
||||||
|
|
||||||
|
Account scope
|
||||||
|
- Login
|
||||||
|
* Accounts are used to authenticate a user.
|
||||||
|
* Authentication is tied to an email address and password.
|
||||||
|
- Rights assignment
|
||||||
|
* Different accounts can be granted different rights.
|
||||||
|
* Rights are assigned at account level or in relation to persons/groups,
|
||||||
|
depending on the access rule for the article.
|
||||||
|
|
||||||
|
Person scope
|
||||||
|
- Data ownership
|
||||||
|
* A person is the owner of their own articles.
|
||||||
|
* A person can have multiple linked accounts/emails.
|
||||||
|
- Shared context
|
||||||
|
* Other parties may access articles only through the rights/group model.
|
||||||
|
|
||||||
|
Groups and persons
|
||||||
|
- Membership
|
||||||
|
* Groups contain persons.
|
||||||
|
* Group membership does not depend on the email used for login.
|
||||||
|
- Example interpretation
|
||||||
|
* If a person belongs to a group, then that group relation follows the
|
||||||
|
person, not a specific email account.
|
||||||
|
|
||||||
|
Article model
|
||||||
|
- Each article has:
|
||||||
|
* An article type
|
||||||
|
* Content belonging to that type
|
||||||
|
* An owner person context
|
||||||
|
* Access rules based on rights and group membership
|
||||||
|
- Article types are distinct categories, not free text, so that access can be
|
||||||
|
handled per type in a structured way.
|
||||||
|
|
||||||
|
Security and privacy goals
|
||||||
|
- Private by default where appropriate
|
||||||
|
* Not everything is publicly visible.
|
||||||
|
- Controlled sharing
|
||||||
|
* Sharing happens via rights and groups, not via open access.
|
||||||
|
- Person-centric sharing
|
||||||
|
* Visibility follows persons and groups, not only the account that logs in.
|
||||||
|
- Separation of concerns
|
||||||
|
* Login (account/email/password) is separate from data ownership (person).
|
||||||
|
* This allows one person to be reachable through several emails without
|
||||||
|
merging all content into one account identity.
|
||||||
|
|
||||||
|
Functional expectations
|
||||||
|
- Account management
|
||||||
|
* Create account for an email address with a password.
|
||||||
|
* The email address is fixed for that account.
|
||||||
|
- Person management
|
||||||
|
* Represent persons independently of a single account.
|
||||||
|
* Link multiple emails/accounts to one person where needed.
|
||||||
|
- Article management
|
||||||
|
* Create, view, edit, and remove articles for a person.
|
||||||
|
* Store articles by type.
|
||||||
|
* Enforce visibility by rights and group membership.
|
||||||
|
- Group management
|
||||||
|
* Groups are defined around persons.
|
||||||
|
* Membership is used for visibility/access decisions.
|
||||||
|
- Rights handling
|
||||||
|
* Rights decide what is allowed for an account/requesting party.
|
||||||
|
* Rights work together with group-based visibility rules.
|
||||||
|
|
||||||
|
Non-goals for this version
|
||||||
|
- This is not a payment system.
|
||||||
|
- This is not a transaction ledger.
|
||||||
|
- This is not primarily an account-consumption platform; accounts exist for
|
||||||
|
login and rights, but persons and their articles are the main content.
|
||||||
|
|
||||||
|
Level of detail required from the specification
|
||||||
|
- Account model
|
||||||
|
* Fixed email per account.
|
||||||
|
* Password per email.
|
||||||
|
* Different rights per account.
|
||||||
|
- Person model
|
||||||
|
* Persons as first-class entities.
|
||||||
|
* Support for multiple emails per person.
|
||||||
|
- Article model
|
||||||
|
* Article types.
|
||||||
|
* Ownership context.
|
||||||
|
* Rights/group-based visibility.
|
||||||
|
- Group model
|
||||||
|
* Person-dependent groups.
|
||||||
|
* No email-dependent groups.
|
||||||
|
- Access behavior
|
||||||
|
* Explicit visibility rules.
|
||||||
|
* No open global visibility for restricted articles.
|
||||||
|
|
||||||
|
This specification intentionally describes what the system is and what rules
|
||||||
|
it follows, so that later implementation matches the intended model exactly.
|
||||||
Reference in New Issue
Block a user