chore: import MCTF services
- Added all seven issued service trees without omissions. - Preserved the supplied runtime configuration, binaries, and assets.
This commit is contained in:
commit
13f936bee9
1222 files changed
+21280
No files matched your search
Executable
+16
@@ -0,0 +1,16 @@
|
||||
.DS_Store
|
||||
._*
|
||||
__pycache__
|
||||
*.py[cod]
|
||||
.env
|
||||
.env.*
|
||||
.venv
|
||||
venv
|
||||
ledger_data
|
||||
state
|
||||
*.sqlite
|
||||
*.sqlite3
|
||||
*.sqlite3-*
|
||||
*.key
|
||||
*.key.pem
|
||||
*.log
|
||||
Executable
+15
@@ -0,0 +1,15 @@
|
||||
FROM python:3.12-slim-bookworm
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
COPY backend/requirements.txt ./
|
||||
RUN pip install --root-user-action=ignore --no-cache-dir -r requirements.txt
|
||||
|
||||
COPY backend/app ./backend/app/
|
||||
COPY run.py ./
|
||||
COPY frontend ./frontend/
|
||||
|
||||
RUN useradd --uid 10001 --user-group --no-create-home --shell /usr/sbin/nologin chrome-ledger \
|
||||
&& install -d -m 0700 -o chrome-ledger -g chrome-ledger /var/lib/chrome-ledger
|
||||
|
||||
USER chrome-ledger
|
||||
Executable
+5
@@ -0,0 +1,5 @@
|
||||
from flask import current_app
|
||||
|
||||
|
||||
def ledger():
|
||||
return current_app.extensions["ledger"]
|
||||
Executable
+8
@@ -0,0 +1,8 @@
|
||||
from flask import abort, request
|
||||
|
||||
|
||||
def json_object():
|
||||
payload = request.get_json(silent=True)
|
||||
if not isinstance(payload, dict):
|
||||
abort(400, "Expected a JSON object")
|
||||
return payload
|
||||
Executable
+68
@@ -0,0 +1,68 @@
|
||||
import re
|
||||
import sqlite3
|
||||
|
||||
from uuid import uuid4
|
||||
from flask import Blueprint, abort, current_app, g
|
||||
from werkzeug.security import check_password_hash, generate_password_hash
|
||||
from backend.app.common.utils import account_namespace, utc_now, valid_text
|
||||
from backend.app.infrastructure.persistence import repositories
|
||||
from backend.app.infrastructure.persistence.connection import database
|
||||
from backend.app.api.request import json_object
|
||||
from backend.app.api.session import owner_session, sign_in
|
||||
|
||||
|
||||
USERNAME = re.compile(r"[A-Za-z0-9_-]{3,32}")
|
||||
BAD_CREDENTIALS = "Invalid username or password"
|
||||
|
||||
|
||||
bp = Blueprint("auth", __name__)
|
||||
|
||||
|
||||
@bp.post("/register")
|
||||
def register():
|
||||
payload = json_object()
|
||||
username = payload.get("username")
|
||||
password = payload.get("password")
|
||||
if not isinstance(username, str) or not USERNAME.fullmatch(username):
|
||||
abort(400, "Username must contain 3-32 ASCII letters, digits, _ or -")
|
||||
if not valid_text(password, 8, 128):
|
||||
abort(400, "Password must contain 8-128 ASCII characters")
|
||||
user_id = str(uuid4())
|
||||
namespace = account_namespace(username)
|
||||
password_hash = generate_password_hash(password, method="scrypt")
|
||||
connection = database()
|
||||
try:
|
||||
with connection:
|
||||
repositories.create_user(connection, user_id, username, namespace, password_hash, utc_now().isoformat())
|
||||
except sqlite3.IntegrityError:
|
||||
abort(409, "Username is already taken")
|
||||
return sign_in(user_id, username), 201
|
||||
|
||||
@bp.post("/login")
|
||||
def login():
|
||||
payload = json_object()
|
||||
username = payload.get("username")
|
||||
password = payload.get("password")
|
||||
valid_username = isinstance(username, str) and USERNAME.fullmatch(username)
|
||||
valid_password = valid_text(password, 8, 128)
|
||||
row = repositories.get_user_by_username(database(), username if valid_username else "")
|
||||
correct = check_password_hash(
|
||||
row["password_hash"] if row else current_app.extensions["ledger"].dummy_hash,
|
||||
password if valid_password else "",
|
||||
)
|
||||
if not correct or row is None or not valid_password:
|
||||
abort(401, BAD_CREDENTIALS)
|
||||
return sign_in(row["id"], row["username"])
|
||||
|
||||
@bp.get("/home/api/me")
|
||||
@owner_session
|
||||
def me():
|
||||
return g.user
|
||||
|
||||
@bp.delete("/home/api/logout")
|
||||
@owner_session
|
||||
def logout():
|
||||
connection = database()
|
||||
with connection:
|
||||
repositories.delete_auth_session(connection, g.token_id)
|
||||
return "", 204
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
from flask import Blueprint, g, request, abort
|
||||
from backend.app.infrastructure.persistence import repositories
|
||||
from backend.app.infrastructure.persistence.connection import database
|
||||
from backend.app.application import implants
|
||||
from backend.app.api.request import json_object
|
||||
from backend.app.api.context import ledger
|
||||
from backend.app.api.session import owner_session, claimed_username
|
||||
|
||||
|
||||
bp = Blueprint("implants", __name__, url_prefix="/home/api")
|
||||
|
||||
|
||||
@bp.post("/register_implant")
|
||||
@owner_session
|
||||
def register_implant():
|
||||
return implants.register(database(), ledger(), g.user["id"], json_object()), 201
|
||||
|
||||
@bp.get("/implants")
|
||||
@owner_session
|
||||
def list_implants():
|
||||
return implants.list_owned(database(), g.user["id"])
|
||||
|
||||
@bp.get("/telemetry")
|
||||
@owner_session
|
||||
def telemetry():
|
||||
username = request.args.get("username") or g.user["username"]
|
||||
if claimed_username(g.token) != username:
|
||||
return {"error": "access denied"}, 403
|
||||
user = repositories.get_user_by_username(database(), username)
|
||||
if user is None:
|
||||
abort(404)
|
||||
return implants.telemetry(database(), user["id"])
|
||||
|
||||
@bp.get("/implants/<implant_id>")
|
||||
@owner_session
|
||||
def implant_passport(implant_id):
|
||||
return implants.passport(database(), ledger(), implant_id, g.user["id"])
|
||||
|
||||
@bp.route("/check_certificate/<implant_id>/check", methods=["GET", "POST"])
|
||||
@owner_session
|
||||
def check_certificate(implant_id):
|
||||
payload = json_object() if request.method == "POST" else None
|
||||
return implants.check_certificate(database(), ledger(), implant_id, g.user["id"], payload)
|
||||
|
||||
|
||||
@bp.post("/reissue/<implant_id>")
|
||||
@owner_session
|
||||
def reissue_certificate(implant_id):
|
||||
return implants.reissue(database(), ledger(), implant_id, json_object()), 200
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
from flask import Blueprint
|
||||
from backend.app.infrastructure.persistence.connection import database
|
||||
from backend.app.application import implants
|
||||
from backend.app.api.session import owner_session
|
||||
from backend.app.api.context import ledger
|
||||
|
||||
|
||||
bp = Blueprint("registry", __name__, url_prefix="/home/api")
|
||||
|
||||
|
||||
@bp.get("/registry")
|
||||
@owner_session
|
||||
def registry():
|
||||
return implants.registry(database(), ledger())
|
||||
Executable
+66
@@ -0,0 +1,66 @@
|
||||
from functools import wraps
|
||||
from flask import abort, g, request
|
||||
from obsigil import Obsigil, ObsigilError, generate_uuid7
|
||||
|
||||
from backend.app.api.context import ledger
|
||||
from backend.app.common.constants import AUTH_AUDIENCE, AUTH_LIFETIME
|
||||
from backend.app.common.utils import utc_now
|
||||
from backend.app.infrastructure.persistence import repositories
|
||||
from backend.app.infrastructure.persistence.connection import database
|
||||
|
||||
|
||||
def sign_in(user_id, username):
|
||||
now = int(utc_now().timestamp())
|
||||
expires_at = now + int(AUTH_LIFETIME.total_seconds())
|
||||
tid = generate_uuid7()
|
||||
token = Obsigil.mint(
|
||||
clauses={}, mandate_key=ledger().obsigil_key, tid=tid,
|
||||
sub=user_id, aud=[AUTH_AUDIENCE], exp=expires_at,
|
||||
manifest={"iss": AUTH_AUDIENCE, "claims": {"username": username}},
|
||||
).token()
|
||||
connection = database()
|
||||
with connection:
|
||||
repositories.delete_auth_session(connection, g.token_id)
|
||||
repositories.create_auth_session(connection, tid, user_id, expires_at)
|
||||
return {"id": user_id, "username": username, "access_token": token}
|
||||
|
||||
def claimed_username(token):
|
||||
claims = Obsigil(token, max_decoded_len=4096).claims() or {}
|
||||
username = claims.get("username")
|
||||
return username if isinstance(username, str) else None
|
||||
|
||||
def load_identity():
|
||||
g.user = None
|
||||
g.token = None
|
||||
g.token_id = None
|
||||
authorization = request.headers.get("Authorization", "").split()
|
||||
if len(authorization) != 2 or authorization[0].lower() != "bearer":
|
||||
return
|
||||
token = authorization[1]
|
||||
if len(token) > 4096:
|
||||
return
|
||||
now = int(utc_now().timestamp())
|
||||
try:
|
||||
clauses = Obsigil(
|
||||
token, keys=ledger().obsigil_key, audience=AUTH_AUDIENCE,
|
||||
now=now, max_decoded_len=4096,
|
||||
).clauses()
|
||||
except ObsigilError:
|
||||
return
|
||||
user_id = clauses.get("sub")
|
||||
if not isinstance(user_id, str) or clauses.get("aud") != [AUTH_AUDIENCE]:
|
||||
return
|
||||
row = repositories.get_auth_user(database(), clauses["tid"], user_id, clauses["exp"], now)
|
||||
if row is not None:
|
||||
g.user = dict(row)
|
||||
g.token = token
|
||||
g.token_id = clauses["tid"]
|
||||
|
||||
|
||||
def owner_session(route):
|
||||
@wraps(route)
|
||||
def guarded(*args, **kwargs):
|
||||
if g.user is None:
|
||||
abort(401, "Authentication required")
|
||||
return route(*args, **kwargs)
|
||||
return guarded
|
||||
Executable
+36
@@ -0,0 +1,36 @@
|
||||
from pathlib import Path
|
||||
from flask import Blueprint, abort, make_response, send_from_directory
|
||||
from werkzeug.security import safe_join
|
||||
from backend.app.api.context import ledger
|
||||
|
||||
|
||||
bp = Blueprint("console", __name__)
|
||||
|
||||
|
||||
@bp.get("/", defaults={"path": ""})
|
||||
@bp.get("/<path:path>")
|
||||
def console(path):
|
||||
static_root = ledger().static_root
|
||||
public_root = static_root / "public"
|
||||
if path.startswith("src/"):
|
||||
source_path = path.removeprefix("src/")
|
||||
source_root = static_root / "src"
|
||||
target = safe_join(str(source_root), source_path)
|
||||
if target and Path(target).is_file():
|
||||
return send_from_directory(source_root, source_path)
|
||||
abort(404)
|
||||
target = safe_join(str(public_root), path)
|
||||
if path and path != "index.html" and target and Path(target).is_file():
|
||||
return send_from_directory(public_root, path)
|
||||
pages = {"", "login", "home", "home/register_implant", "home/check_certificate", "home/reissue", "home/implants", "home/registry"}
|
||||
if path not in pages and not (
|
||||
(path.startswith("home/implants/") and len(path.split("/")) == 3)
|
||||
or (path.startswith("home/check_certificate/") and len(path.split("/")) == 4 and path.endswith("/check"))
|
||||
):
|
||||
abort(404)
|
||||
index = public_root / "index.html"
|
||||
if not index.is_file():
|
||||
abort(503, "Console not found")
|
||||
response = make_response(index.read_text(encoding="utf-8"))
|
||||
response.headers["Cache-Control"] = "no-store"
|
||||
return response
|
||||
+64
@@ -0,0 +1,64 @@
|
||||
import json
|
||||
|
||||
from hmac import compare_digest
|
||||
|
||||
from Crypto.Random import get_random_bytes
|
||||
from backend.app.common.constants import HEX_CHALLENGE
|
||||
from backend.app.common.errors import LedgerError
|
||||
from backend.app.common.utils import utc_now, valid_text
|
||||
from backend.app.infrastructure.security import certificates, envelopes, keys
|
||||
from backend.app.infrastructure.persistence import repositories
|
||||
|
||||
|
||||
def implant(connection, implant_id, owner_id=None):
|
||||
row = repositories.get_implant(connection, implant_id)
|
||||
if row is None or (owner_id is not None and row["user_id"] != owner_id):
|
||||
raise LedgerError(404, "Implant not found")
|
||||
return row
|
||||
|
||||
|
||||
def challenge(connection, ledger, implant_id, owner_id):
|
||||
with connection:
|
||||
connection.execute("BEGIN IMMEDIATE")
|
||||
implant(connection, implant_id)
|
||||
current = repositories.get_current_certificate(connection, implant_id)
|
||||
if current is None or not certificates.valid(certificates.load_certificate(current["cert_pem"]), ledger.ca):
|
||||
raise LedgerError(409, "Implant has no valid certificate")
|
||||
nonce = get_random_bytes(32).hex()
|
||||
repositories.create_implant_challenge(connection, nonce, implant_id, current["serial"], utc_now())
|
||||
return {"id": implant_id, "challenge": nonce, "certificate_serial": current["serial"], "certificate": dict(current)}
|
||||
|
||||
|
||||
def read_details(connection, ledger, implant_id, owner_id, payload):
|
||||
invalid = "Invalid certificate, signature or challenge"
|
||||
pem = payload.get("certificate")
|
||||
signature = payload.get("signature")
|
||||
nonce = payload.get("nonce")
|
||||
if not valid_text(pem, 1, 60_000) or not isinstance(signature, str) or not isinstance(nonce, str):
|
||||
raise LedgerError(401, invalid)
|
||||
if not HEX_CHALLENGE.fullmatch(nonce):
|
||||
raise LedgerError(401, invalid)
|
||||
try:
|
||||
certificate = certificates.load_certificate(pem)
|
||||
except ValueError:
|
||||
raise LedgerError(401, invalid) from None
|
||||
with connection:
|
||||
connection.execute("BEGIN IMMEDIATE")
|
||||
row = implant(connection, implant_id)
|
||||
if not compare_digest(certificates.subject_implant_id(certificate), implant_id):
|
||||
raise LedgerError(401, invalid)
|
||||
stored = repositories.get_certificate(connection, implant_id, format(certificate.serial_number, "x"))
|
||||
if stored is None or stored["revoked_at"]:
|
||||
raise LedgerError(401, invalid)
|
||||
if not certificates.valid(certificates.load_certificate(stored["cert_pem"]), ledger.ca):
|
||||
raise LedgerError(401, invalid)
|
||||
if not keys.verify_implant_signature(certificate.public_key(), signature, nonce):
|
||||
raise LedgerError(401, invalid)
|
||||
consumed = repositories.consume_implant_challenge(
|
||||
connection, nonce, implant_id, stored["serial"],
|
||||
(utc_now() - ledger.challenge_lifetime).isoformat(),
|
||||
)
|
||||
if not consumed:
|
||||
raise LedgerError(401, invalid)
|
||||
details = json.loads(envelopes.decode_envelope(ledger.master_key, row["details"], implant_id))
|
||||
return {"id": implant_id, "certificate": dict(stored), **details}
|
||||
+68
@@ -0,0 +1,68 @@
|
||||
from hashlib import sha256
|
||||
|
||||
from cryptography import x509
|
||||
from cryptography.exceptions import UnsupportedAlgorithm
|
||||
from cryptography.hazmat.primitives import hashes, serialization
|
||||
from backend.app.common.errors import LedgerError
|
||||
from backend.app.common.utils import utc_now, valid_text
|
||||
from backend.app.infrastructure.security import certificates, keys
|
||||
|
||||
|
||||
def public_key(payload):
|
||||
pem = payload.get("public_key_pem")
|
||||
if not valid_text(pem, 1, 60_000):
|
||||
raise LedgerError(400, "Provide a public key in PEM format")
|
||||
try:
|
||||
return keys.parse_public_key(pem)
|
||||
except keys.UnsupportedKeyType:
|
||||
raise LedgerError(400, "Supported keys are ECDSA P-256 and RSA with at least 2048 bits") from None
|
||||
except ValueError:
|
||||
raise LedgerError(400, "Invalid PEM public key") from None
|
||||
|
||||
|
||||
def signing_request(payload):
|
||||
pem = payload.get("csr_pem")
|
||||
if not valid_text(pem, 1, 60_000):
|
||||
raise LedgerError(400, "Provide a signed CSR in PEM format")
|
||||
try:
|
||||
request = x509.load_pem_x509_csr(pem.encode("ascii"))
|
||||
if not request.is_signature_valid:
|
||||
raise ValueError
|
||||
key_pem = request.public_key().public_bytes(
|
||||
serialization.Encoding.PEM, serialization.PublicFormat.SubjectPublicKeyInfo,
|
||||
).decode("ascii")
|
||||
except (ValueError, UnsupportedAlgorithm):
|
||||
raise LedgerError(400, "Invalid CSR or CSR signature") from None
|
||||
key = public_key({"public_key_pem": key_pem})
|
||||
return key, sha256(request.public_bytes(serialization.Encoding.DER)).hexdigest()
|
||||
|
||||
|
||||
def issue(ledger, implant_id, key, now, display_name=""):
|
||||
pem = certificates.issue_certificate(ledger.ca_key, ledger.ca, implant_id, key, now, display_name)
|
||||
certificate = certificates.load_certificate(pem)
|
||||
return {
|
||||
"serial": format(certificate.serial_number, "x"),
|
||||
"cert_pem": pem,
|
||||
"fingerprint": certificate.fingerprint(hashes.SHA256()).hex(),
|
||||
"created_at": now.isoformat(),
|
||||
"not_after": certificate.not_valid_after_utc.isoformat(),
|
||||
}
|
||||
|
||||
|
||||
def describe(row, ca):
|
||||
certificate = certificates.load_certificate(row["cert_pem"])
|
||||
result = certificates.describe(certificate, ca)
|
||||
if row["revoked_at"]:
|
||||
status = "revoked"
|
||||
elif result["valid"]:
|
||||
status = "active"
|
||||
elif certificate.not_valid_after_utc < utc_now():
|
||||
status = "expired"
|
||||
else:
|
||||
status = "invalid"
|
||||
result.update(
|
||||
status=status, valid=status == "active", fingerprint=row["fingerprint"],
|
||||
revoked_at=row["revoked_at"],
|
||||
cert_pem=row["cert_pem"],
|
||||
)
|
||||
return result
|
||||
+112
@@ -0,0 +1,112 @@
|
||||
import json
|
||||
|
||||
from uuid import uuid4
|
||||
|
||||
from backend.app.common.errors import LedgerError
|
||||
from backend.app.common.utils import utc_now, valid_text
|
||||
from backend.app.infrastructure.security import envelopes, keys
|
||||
from backend.app.infrastructure.security.certificates import load_certificate, valid
|
||||
from backend.app.infrastructure.persistence import repositories
|
||||
from backend.app.application import access, certificates
|
||||
|
||||
|
||||
def implant_text(value, label):
|
||||
if isinstance(value, str) and value.isascii():
|
||||
value = value.strip()
|
||||
if not valid_text(value, 1, 80):
|
||||
raise LedgerError(400, f"{label} must contain 1-80 ASCII characters")
|
||||
return value
|
||||
|
||||
|
||||
def register(connection, ledger, owner_id, payload):
|
||||
details = {
|
||||
name: implant_text(payload.get(name), label)
|
||||
for name, label in (("project_codename", "Project codename"), ("installed_by", "Organization code"))
|
||||
}
|
||||
display_name = implant_text(payload.get("display_name"), "Name")
|
||||
model = implant_text(payload.get("model"), "Model")
|
||||
key = certificates.public_key(payload)
|
||||
implant_id = str(uuid4())
|
||||
now = utc_now()
|
||||
certificate = certificates.issue(ledger, implant_id, key, now, display_name)
|
||||
details_bytes = json.dumps(details, separators=(",", ":")).encode("utf-8")
|
||||
record = envelopes.encode_envelope(ledger.master_key, details_bytes, implant_id)
|
||||
with connection:
|
||||
repositories.create_implant(
|
||||
connection, implant_id, owner_id, display_name, model, record, now.isoformat(),
|
||||
)
|
||||
repositories.create_certificate(connection, implant_id, certificate)
|
||||
repositories.create_implant_telemetry(
|
||||
connection, implant_id, payload["display_name"], payload["model"], payload["public_key_pem"],
|
||||
details["project_codename"], details["installed_by"],
|
||||
)
|
||||
return {"id": implant_id, "cert_pem": certificate["cert_pem"]}
|
||||
|
||||
|
||||
def list_owned(connection, owner_id):
|
||||
return {"implants": [dict(row) for row in repositories.list_implants(connection, owner_id)]}
|
||||
|
||||
|
||||
def telemetry(connection, owner_id):
|
||||
return {"telemetry": [dict(row) for row in repositories.list_telemetry(connection, owner_id)]}
|
||||
|
||||
|
||||
def passport(connection, ledger, implant_id, viewer_id):
|
||||
row = access.implant(connection, implant_id, viewer_id)
|
||||
result = {name: row[name] for name in ("id", "display_name", "model", "created_at")}
|
||||
result["owner"] = row["owner"]
|
||||
certificate = repositories.get_latest_certificate(connection, implant_id)
|
||||
result["certificate"] = certificates.describe(certificate, ledger.ca)
|
||||
result["cert_pem"] = certificate["cert_pem"]
|
||||
result["user_id"] = row["user_id"]
|
||||
return result
|
||||
|
||||
|
||||
def check_certificate(connection, ledger, implant_id, owner_id, payload=None):
|
||||
result = access.challenge(connection, ledger, implant_id, owner_id) if payload is None else access.read_details(connection, ledger, implant_id, owner_id, payload)
|
||||
result["certificate"] = certificates.describe(result["certificate"], ledger.ca)
|
||||
return result
|
||||
|
||||
|
||||
def reissue(connection, ledger, implant_id, payload):
|
||||
key, digest = certificates.signing_request(payload)
|
||||
with connection:
|
||||
connection.execute("BEGIN IMMEDIATE")
|
||||
row = access.implant(connection, implant_id)
|
||||
current = repositories.get_current_certificate(connection, implant_id)
|
||||
if current is None:
|
||||
raise LedgerError(409, "Implant has no valid certificate")
|
||||
if payload.get("certificate_serial") != current["serial"]:
|
||||
raise LedgerError(401, "Specify the current certificate serial number")
|
||||
previous = load_certificate(current["cert_pem"])
|
||||
if not valid(previous, ledger.ca):
|
||||
raise LedgerError(409, "Implant has no valid certificate")
|
||||
message = f"reissue:{implant_id}:{current['serial']}:{digest}"
|
||||
signature = payload.get("signature")
|
||||
if not isinstance(signature, str):
|
||||
raise LedgerError(401, "Invalid signature for the current key")
|
||||
current_key_authorized = keys.verify_implant_signature(previous.public_key(), signature, message)
|
||||
if not current_key_authorized and not keys.verify_implant_signature(key, signature, message):
|
||||
raise LedgerError(401, "Invalid signature for the current key")
|
||||
now = utc_now()
|
||||
details = json.loads(envelopes.decode_envelope(ledger.master_key, row["details"], implant_id))
|
||||
certificate = current
|
||||
if current_key_authorized:
|
||||
issued = certificates.issue(ledger, implant_id, key, now, row["display_name"])
|
||||
repositories.revoke_certificates(connection, implant_id, now.isoformat())
|
||||
repositories.create_certificate(connection, implant_id, issued)
|
||||
certificate = repositories.get_certificate(connection, implant_id, issued["serial"])
|
||||
result = {name: row[name] for name in ("id", "display_name", "model", "created_at", "owner", "user_id")}
|
||||
result.update(success=True, cert_pem=certificate["cert_pem"], **details)
|
||||
result["certificate"] = certificates.describe(certificate, ledger.ca)
|
||||
return result
|
||||
|
||||
|
||||
def registry(connection, ledger):
|
||||
results = {}
|
||||
for row in repositories.list_registry(connection):
|
||||
if row["id"] not in results:
|
||||
results[row["id"]] = {name: row[name] for name in ("id", "display_name", "model", "created_at", "owner")}
|
||||
results[row["id"]]["certificates"] = []
|
||||
results[row["id"]]["certificates"].append(certificates.describe(row, ledger.ca))
|
||||
return {"results": list(results.values())}
|
||||
+85
@@ -0,0 +1,85 @@
|
||||
import os
|
||||
import sqlite3
|
||||
|
||||
from contextlib import closing
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
from Crypto.Random import get_random_bytes
|
||||
from flask import Flask
|
||||
from werkzeug.exceptions import HTTPException
|
||||
from werkzeug.security import generate_password_hash
|
||||
from backend.app.common.constants import LIFETIME
|
||||
from backend.app.common.errors import LedgerError
|
||||
from backend.app.common.utils import utc_now
|
||||
from backend.app.infrastructure.security.certificates import load_or_create_ca
|
||||
from backend.app.infrastructure.persistence.connection import close_database, database_path, initialize
|
||||
from backend.app.api import views
|
||||
from backend.app.api.session import load_identity
|
||||
from backend.app.api.routes import auth, implants, registry
|
||||
|
||||
|
||||
def load_key(state_dir, name, size=32):
|
||||
path = state_dir / name
|
||||
if path.is_file():
|
||||
key = path.read_bytes()
|
||||
if len(key) != size:
|
||||
raise RuntimeError(f"Invalid state key: {name}")
|
||||
return key
|
||||
key = get_random_bytes(size)
|
||||
with path.open("xb") as handle:
|
||||
os.chmod(path, 0o600)
|
||||
handle.write(key)
|
||||
return key
|
||||
|
||||
|
||||
def create_app(database_path_override=None):
|
||||
db_path = Path(database_path_override or database_path())
|
||||
initialize(db_path)
|
||||
state_dir = db_path.parent / "state"
|
||||
state_dir.mkdir(mode=0o700, parents=True, exist_ok=True)
|
||||
with closing(sqlite3.connect(db_path)) as connection:
|
||||
has_implants = connection.execute("SELECT EXISTS(SELECT 1 FROM implants)").fetchone()[0]
|
||||
required = ("master.key", "ca.key.pem", "ca.cert.pem")
|
||||
if has_implants and any(not (state_dir / name).is_file() for name in required):
|
||||
raise RuntimeError("Existing implants require the original master key and CA files; restore the state directory")
|
||||
if (state_dir / "ca.key.pem").is_file() != (state_dir / "ca.cert.pem").is_file():
|
||||
raise RuntimeError("Both CA key and certificate must be present")
|
||||
master_key = load_key(state_dir, "master.key")
|
||||
ca_key, ca = load_or_create_ca(state_dir, utc_now())
|
||||
app = Flask(__name__, static_folder=None)
|
||||
app.config.update(
|
||||
DATABASE=str(db_path),
|
||||
MAX_CONTENT_LENGTH=65_536,
|
||||
)
|
||||
app.extensions["ledger"] = SimpleNamespace(
|
||||
ca_key=ca_key, ca=ca, master_key=master_key,
|
||||
obsigil_key=load_key(state_dir, "obsigil.key", 64),
|
||||
dummy_hash=generate_password_hash(get_random_bytes(32).hex(), method="scrypt"),
|
||||
challenge_lifetime=LIFETIME,
|
||||
static_root=Path(__file__).resolve().parents[3] / "frontend",
|
||||
)
|
||||
|
||||
app.before_request(load_identity)
|
||||
|
||||
for blueprint in (auth.bp, implants.bp, registry.bp, views.bp):
|
||||
app.register_blueprint(blueprint)
|
||||
app.teardown_appcontext(close_database)
|
||||
|
||||
@app.errorhandler(LedgerError)
|
||||
def service_error(error):
|
||||
return {"error": str(error)}, error.status
|
||||
|
||||
@app.errorhandler(HTTPException)
|
||||
def http_error(error):
|
||||
response = error.get_response()
|
||||
response.set_data(app.json.dumps({"error": error.description}))
|
||||
response.mimetype = "application/json"
|
||||
return response
|
||||
|
||||
@app.after_request
|
||||
def protect_private_responses(response):
|
||||
if response.is_json:
|
||||
response.headers["Cache-Control"] = "no-store"
|
||||
return response
|
||||
|
||||
return app
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
import re
|
||||
|
||||
from datetime import timedelta
|
||||
|
||||
|
||||
LIFETIME = timedelta(seconds=60)
|
||||
AUTH_LIFETIME = timedelta(hours=12)
|
||||
AUTH_AUDIENCE = "chrome-ledger"
|
||||
|
||||
HEX_CHALLENGE = re.compile(r"[0-9a-fA-F]{64}")
|
||||
Executable
+4
@@ -0,0 +1,4 @@
|
||||
class LedgerError(Exception):
|
||||
def __init__(self, status, message):
|
||||
super().__init__(message)
|
||||
self.status = status
|
||||
Executable
+17
@@ -0,0 +1,17 @@
|
||||
import unicodedata
|
||||
|
||||
from datetime import UTC, datetime
|
||||
|
||||
|
||||
def utc_now():
|
||||
return datetime.now(UTC)
|
||||
|
||||
def account_namespace(username):
|
||||
return unicodedata.normalize("NFKC", username).casefold()
|
||||
|
||||
def valid_text(value, minimum, maximum):
|
||||
if not isinstance(value, str):
|
||||
return False
|
||||
if len(value) < minimum or len(value) > maximum:
|
||||
return False
|
||||
return value.isascii()
|
||||
@@ -0,0 +1,37 @@
|
||||
import os
|
||||
import sqlite3
|
||||
|
||||
from contextlib import closing
|
||||
from pathlib import Path
|
||||
from flask import current_app, g
|
||||
from backend.app.infrastructure.persistence.schema import SCHEMA
|
||||
|
||||
|
||||
def database_path():
|
||||
default = Path(__file__).resolve().parents[4] / "ledger_data" / "ledger.sqlite3"
|
||||
return Path(os.environ.get("LEDGER_DB", default)).resolve()
|
||||
|
||||
def initialize(path):
|
||||
path = Path(path)
|
||||
path.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
|
||||
with closing(sqlite3.connect(path)) as connection:
|
||||
connection.execute("PRAGMA auto_vacuum = INCREMENTAL")
|
||||
connection.execute("PRAGMA journal_mode = WAL")
|
||||
connection.execute("PRAGMA busy_timeout = 5000")
|
||||
connection.execute("PRAGMA foreign_keys = ON")
|
||||
connection.executescript(SCHEMA)
|
||||
connection.execute("PRAGMA user_version = 9")
|
||||
|
||||
def database():
|
||||
if "database" not in g:
|
||||
connection = sqlite3.connect(current_app.config["DATABASE"], timeout=5)
|
||||
connection.row_factory = sqlite3.Row
|
||||
connection.execute("PRAGMA busy_timeout = 5000")
|
||||
connection.execute("PRAGMA foreign_keys = ON")
|
||||
g.database = connection
|
||||
return g.database
|
||||
|
||||
def close_database(_error):
|
||||
connection = g.pop("database", None)
|
||||
if connection is not None:
|
||||
connection.close()
|
||||
@@ -0,0 +1,126 @@
|
||||
from backend.app.common.constants import LIFETIME
|
||||
|
||||
|
||||
def get_user_by_username(connection, username):
|
||||
return connection.execute(
|
||||
"SELECT id, username, namespace, password_hash FROM users WHERE username = ?", (username,),
|
||||
).fetchone()
|
||||
|
||||
def create_auth_session(connection, tid, user_id, expires_at):
|
||||
connection.execute(
|
||||
"INSERT INTO auth_sessions (tid, user_id, expires_at) VALUES (?, ?, ?)",
|
||||
(tid, user_id, expires_at),
|
||||
)
|
||||
|
||||
|
||||
def get_auth_user(connection, tid, user_id, expires_at, now):
|
||||
return connection.execute(
|
||||
"SELECT u.id, u.username FROM auth_sessions s JOIN users u ON u.id = s.user_id "
|
||||
"WHERE s.tid = ? AND s.user_id = ? AND s.expires_at = ? AND s.expires_at > ?",
|
||||
(tid, user_id, expires_at, now),
|
||||
).fetchone()
|
||||
|
||||
|
||||
def delete_auth_session(connection, tid):
|
||||
connection.execute("DELETE FROM auth_sessions WHERE tid = ?", (tid,))
|
||||
|
||||
|
||||
def create_user(connection, user_id, username, namespace, password_hash, created_at):
|
||||
connection.execute(
|
||||
"INSERT INTO users (id, username, namespace, password_hash, created_at) VALUES (?, ?, ?, ?, ?)",
|
||||
(user_id, username, namespace, password_hash, created_at),
|
||||
)
|
||||
|
||||
def create_implant(connection, implant_id, user_id, display_name, model, details, created_at):
|
||||
connection.execute(
|
||||
"INSERT INTO implants "
|
||||
"(id, user_id, display_name, model, details, created_at) "
|
||||
"VALUES (?, ?, ?, ?, ?, ?)",
|
||||
(implant_id, user_id, display_name, model, details, created_at),
|
||||
)
|
||||
|
||||
def create_implant_telemetry(connection, implant_id, display_name, model, public_key_pem, project_codename, installed_by):
|
||||
connection.execute(
|
||||
"INSERT INTO implant_telemetry "
|
||||
"(implant_id, display_name, model, public_key_pem, project_codename, installed_by) VALUES (?, ?, ?, ?, ?, ?)",
|
||||
(implant_id, display_name, model, public_key_pem, project_codename, installed_by),
|
||||
)
|
||||
|
||||
|
||||
def get_implant(connection, implant_id):
|
||||
return connection.execute(
|
||||
"SELECT i.*, u.username AS owner "
|
||||
"FROM implants i JOIN users u ON u.id = i.user_id WHERE i.id = ?", (implant_id,),
|
||||
).fetchone()
|
||||
|
||||
def list_implants(connection, owner_id):
|
||||
return connection.execute(
|
||||
"SELECT i.id, i.display_name, i.model, i.created_at, u.username AS owner "
|
||||
"FROM implants i JOIN users u ON u.id = i.user_id "
|
||||
"WHERE i.user_id = ? ORDER BY i.created_at DESC, i.id DESC", (owner_id,),
|
||||
).fetchall()
|
||||
|
||||
def list_telemetry(connection, owner_id):
|
||||
return connection.execute(
|
||||
"SELECT t.display_name, t.model, t.public_key_pem, t.project_codename, t.installed_by "
|
||||
"FROM implants i JOIN implant_telemetry t ON t.implant_id = i.id "
|
||||
"WHERE i.user_id = ? ORDER BY i.created_at DESC, i.id DESC", (owner_id,),
|
||||
).fetchall()
|
||||
|
||||
|
||||
def list_registry(connection):
|
||||
return connection.execute(
|
||||
"SELECT i.id, i.display_name, i.model, i.created_at, u.username AS owner, "
|
||||
"c.cert_pem, c.fingerprint, c.revoked_at "
|
||||
"FROM implants i JOIN users u ON u.id = i.user_id "
|
||||
"JOIN implant_certificates c ON c.implant_id = i.id "
|
||||
"ORDER BY i.created_at DESC, i.id DESC, c.rowid DESC",
|
||||
).fetchall()
|
||||
|
||||
def create_certificate(connection, implant_id, certificate):
|
||||
connection.execute(
|
||||
"INSERT INTO implant_certificates "
|
||||
"(serial, implant_id, cert_pem, fingerprint, created_at, not_after) VALUES (?, ?, ?, ?, ?, ?)",
|
||||
(certificate["serial"], implant_id, certificate["cert_pem"], certificate["fingerprint"],
|
||||
certificate["created_at"], certificate["not_after"]),
|
||||
)
|
||||
|
||||
def revoke_certificates(connection, implant_id, now):
|
||||
connection.execute(
|
||||
"UPDATE implant_certificates SET revoked_at = ? WHERE implant_id = ? AND revoked_at IS NULL",
|
||||
(now, implant_id),
|
||||
)
|
||||
|
||||
|
||||
def get_current_certificate(connection, implant_id):
|
||||
return connection.execute(
|
||||
"SELECT * FROM implant_certificates WHERE implant_id = ? AND revoked_at IS NULL "
|
||||
"ORDER BY rowid DESC LIMIT 1", (implant_id,),
|
||||
).fetchone()
|
||||
|
||||
def get_latest_certificate(connection, implant_id):
|
||||
return connection.execute(
|
||||
"SELECT * FROM implant_certificates WHERE implant_id = ? ORDER BY rowid DESC LIMIT 1",
|
||||
(implant_id,),
|
||||
).fetchone()
|
||||
|
||||
def get_certificate(connection, implant_id, serial):
|
||||
return connection.execute(
|
||||
"SELECT * FROM implant_certificates WHERE implant_id = ? AND serial = ?",
|
||||
(implant_id, serial),
|
||||
).fetchone()
|
||||
|
||||
def create_implant_challenge(connection, nonce, implant_id, serial, now):
|
||||
connection.execute(
|
||||
"DELETE FROM implant_challenges WHERE created_at <= ?", ((now - LIFETIME).isoformat(),),
|
||||
)
|
||||
connection.execute(
|
||||
"INSERT INTO implant_challenges (nonce, implant_id, certificate_serial, created_at) "
|
||||
"VALUES (?, ?, ?, ?)", (nonce, implant_id, serial, now.isoformat()),
|
||||
)
|
||||
|
||||
def consume_implant_challenge(connection, nonce, implant_id, certificate_serial, cutoff):
|
||||
return connection.execute(
|
||||
"DELETE FROM implant_challenges WHERE nonce = ? AND implant_id = ? AND certificate_serial = ? AND created_at > ?",
|
||||
(nonce, implant_id, certificate_serial, cutoff),
|
||||
).rowcount
|
||||
@@ -0,0 +1,51 @@
|
||||
SCHEMA = """
|
||||
CREATE TABLE IF NOT EXISTS users (
|
||||
id TEXT PRIMARY KEY,
|
||||
username TEXT NOT NULL UNIQUE,
|
||||
namespace TEXT NOT NULL DEFAULT '',
|
||||
password_hash TEXT NOT NULL,
|
||||
created_at TEXT NOT NULL
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS users_created_at ON users (created_at);
|
||||
CREATE TABLE IF NOT EXISTS auth_sessions (
|
||||
tid TEXT PRIMARY KEY,
|
||||
user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
expires_at INTEGER NOT NULL
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS auth_sessions_user_id ON auth_sessions (user_id);
|
||||
CREATE INDEX IF NOT EXISTS auth_sessions_expires_at ON auth_sessions (expires_at);
|
||||
CREATE TABLE IF NOT EXISTS implants (
|
||||
id TEXT PRIMARY KEY,
|
||||
user_id TEXT NOT NULL REFERENCES users(id),
|
||||
display_name TEXT NOT NULL CHECK(length(trim(display_name)) BETWEEN 1 AND 80),
|
||||
model TEXT NOT NULL DEFAULT '',
|
||||
details TEXT NOT NULL,
|
||||
created_at TEXT NOT NULL
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS implants_user_id ON implants (user_id);
|
||||
CREATE INDEX IF NOT EXISTS implants_created_at ON implants (created_at);
|
||||
CREATE TABLE IF NOT EXISTS implant_telemetry (
|
||||
implant_id TEXT PRIMARY KEY REFERENCES implants(id) ON DELETE CASCADE,
|
||||
display_name TEXT NOT NULL,
|
||||
model TEXT NOT NULL,
|
||||
public_key_pem TEXT NOT NULL,
|
||||
project_codename TEXT NOT NULL,
|
||||
installed_by TEXT NOT NULL
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS implant_certificates (
|
||||
serial TEXT PRIMARY KEY,
|
||||
implant_id TEXT NOT NULL REFERENCES implants(id) ON DELETE CASCADE,
|
||||
cert_pem TEXT NOT NULL,
|
||||
fingerprint TEXT NOT NULL UNIQUE,
|
||||
created_at TEXT NOT NULL,
|
||||
not_after TEXT NOT NULL,
|
||||
revoked_at TEXT
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS implant_challenges (
|
||||
nonce TEXT PRIMARY KEY,
|
||||
implant_id TEXT NOT NULL REFERENCES implants(id) ON DELETE CASCADE,
|
||||
certificate_serial TEXT NOT NULL REFERENCES implant_certificates(serial),
|
||||
created_at TEXT NOT NULL
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS implant_challenges_created_at ON implant_challenges (created_at);
|
||||
"""
|
||||
@@ -0,0 +1,105 @@
|
||||
import os
|
||||
|
||||
from datetime import timedelta
|
||||
from cryptography import x509
|
||||
from cryptography.exceptions import InvalidSignature, UnsupportedAlgorithm
|
||||
from cryptography.hazmat.primitives import hashes, serialization
|
||||
from cryptography.hazmat.primitives.asymmetric import ec
|
||||
from cryptography.x509.oid import NameOID
|
||||
from backend.app.common.utils import utc_now
|
||||
|
||||
|
||||
ORGANIZATION = "Chrome Ledger"
|
||||
|
||||
|
||||
def certificate_builder(subject, issuer, public_key, now, days):
|
||||
return (
|
||||
x509.CertificateBuilder()
|
||||
.subject_name(subject)
|
||||
.issuer_name(issuer)
|
||||
.public_key(public_key)
|
||||
.serial_number(x509.random_serial_number())
|
||||
.not_valid_before(now)
|
||||
.not_valid_after(now + timedelta(days=days))
|
||||
)
|
||||
|
||||
def create_ca(now):
|
||||
key = ec.generate_private_key(ec.SECP256R1())
|
||||
name = x509.Name([
|
||||
x509.NameAttribute(NameOID.COMMON_NAME, "Chrome Ledger Root CA"),
|
||||
x509.NameAttribute(NameOID.ORGANIZATION_NAME, ORGANIZATION),
|
||||
])
|
||||
certificate = (
|
||||
certificate_builder(name, name, key.public_key(), now, 365)
|
||||
.add_extension(x509.BasicConstraints(ca=True, path_length=0), critical=True)
|
||||
.sign(key, hashes.SHA256())
|
||||
)
|
||||
return key, certificate
|
||||
|
||||
def load_or_create_ca(state_dir, now):
|
||||
key_path = state_dir / "ca.key.pem"
|
||||
cert_path = state_dir / "ca.cert.pem"
|
||||
if key_path.is_file() and cert_path.is_file():
|
||||
key = serialization.load_pem_private_key(key_path.read_bytes(), password=None)
|
||||
ca = x509.load_pem_x509_certificate(cert_path.read_bytes())
|
||||
key_bytes = key.public_key().public_bytes(serialization.Encoding.DER, serialization.PublicFormat.SubjectPublicKeyInfo)
|
||||
ca_bytes = ca.public_key().public_bytes(serialization.Encoding.DER, serialization.PublicFormat.SubjectPublicKeyInfo)
|
||||
if key_bytes != ca_bytes:
|
||||
raise ValueError("CA key does not match its certificate")
|
||||
return key, ca
|
||||
key, ca = create_ca(now)
|
||||
key_path.write_bytes(
|
||||
key.private_bytes(
|
||||
serialization.Encoding.PEM,
|
||||
serialization.PrivateFormat.PKCS8,
|
||||
serialization.NoEncryption(),
|
||||
)
|
||||
)
|
||||
os.chmod(key_path, 0o600)
|
||||
cert_path.write_bytes(ca.public_bytes(serialization.Encoding.PEM))
|
||||
return key, ca
|
||||
|
||||
def issue_certificate(ca_key, ca, implant_id, public_key, now, display_name=""):
|
||||
common_name = display_name[:64]
|
||||
subject = x509.Name([
|
||||
x509.NameAttribute(NameOID.COMMON_NAME, common_name),
|
||||
x509.NameAttribute(NameOID.ORGANIZATIONAL_UNIT_NAME, implant_id),
|
||||
x509.NameAttribute(NameOID.ORGANIZATION_NAME, ORGANIZATION),
|
||||
])
|
||||
certificate = (
|
||||
certificate_builder(subject, ca.subject, public_key, now, 30)
|
||||
.add_extension(x509.BasicConstraints(ca=False, path_length=None), critical=True)
|
||||
.add_extension(x509.SubjectAlternativeName([
|
||||
x509.UniformResourceIdentifier(f"urn:chrome-ledger:implant:{implant_id}"),
|
||||
]), critical=False)
|
||||
.sign(ca_key, hashes.SHA256())
|
||||
)
|
||||
return certificate.public_bytes(serialization.Encoding.PEM).decode("ascii")
|
||||
|
||||
def load_certificate(pem):
|
||||
return x509.load_pem_x509_certificate(pem.encode("ascii"))
|
||||
|
||||
def subject_implant_id(certificate):
|
||||
attributes = certificate.subject.get_attributes_for_oid(NameOID.ORGANIZATIONAL_UNIT_NAME)
|
||||
return attributes[0].value if len(attributes) == 1 else ""
|
||||
|
||||
def valid(certificate, ca):
|
||||
now = utc_now()
|
||||
if not (certificate.not_valid_before_utc <= now <= certificate.not_valid_after_utc
|
||||
and ca.not_valid_before_utc <= now <= ca.not_valid_after_utc):
|
||||
return False
|
||||
try:
|
||||
certificate.verify_directly_issued_by(ca)
|
||||
except (InvalidSignature, ValueError, UnsupportedAlgorithm):
|
||||
return False
|
||||
return True
|
||||
|
||||
def describe(certificate, ca):
|
||||
return {
|
||||
"subject": certificate.subject.rfc4514_string(),
|
||||
"issuer": certificate.issuer.rfc4514_string(),
|
||||
"serial": format(certificate.serial_number, "x"),
|
||||
"not_before": certificate.not_valid_before_utc.isoformat(),
|
||||
"not_after": certificate.not_valid_after_utc.isoformat(),
|
||||
"valid": valid(certificate, ca),
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
import base64
|
||||
|
||||
from Crypto.Cipher import AES
|
||||
from Crypto.Random import get_random_bytes
|
||||
|
||||
|
||||
NONCE_SIZE = 16
|
||||
TAG_SIZE = 16
|
||||
|
||||
|
||||
def seal(key, plaintext, associated_data):
|
||||
cipher = AES.new(key, AES.MODE_GCM, nonce=get_random_bytes(NONCE_SIZE))
|
||||
cipher.update(associated_data)
|
||||
ciphertext, tag = cipher.encrypt_and_digest(plaintext)
|
||||
return cipher.nonce + ciphertext + tag
|
||||
|
||||
def unseal(key, envelope, associated_data):
|
||||
cipher = AES.new(key, AES.MODE_GCM, nonce=envelope[:NONCE_SIZE])
|
||||
cipher.update(associated_data)
|
||||
plaintext = cipher.decrypt_and_verify(
|
||||
envelope[NONCE_SIZE:-TAG_SIZE],
|
||||
envelope[-TAG_SIZE:],
|
||||
)
|
||||
return plaintext
|
||||
|
||||
def encode_envelope(key, secret, implant_id):
|
||||
associated_data = implant_id.encode("ascii")
|
||||
envelope = seal(key, secret, associated_data)
|
||||
return base64.b64encode(envelope).decode("ascii")
|
||||
|
||||
def decode_envelope(key, envelope, implant_id):
|
||||
associated_data = implant_id.encode("ascii")
|
||||
decoded = base64.b64decode(envelope, validate=True)
|
||||
return unseal(key, decoded, associated_data).decode("utf-8")
|
||||
@@ -0,0 +1,34 @@
|
||||
import base64
|
||||
|
||||
from cryptography.exceptions import InvalidSignature, UnsupportedAlgorithm
|
||||
from cryptography.hazmat.primitives import hashes, serialization
|
||||
from cryptography.hazmat.primitives.asymmetric import ec, padding, rsa
|
||||
|
||||
|
||||
class UnsupportedKeyType(ValueError):
|
||||
pass
|
||||
|
||||
|
||||
def parse_public_key(pem):
|
||||
if not isinstance(pem, str):
|
||||
raise ValueError("PEM must be a string")
|
||||
try:
|
||||
key = serialization.load_pem_public_key(pem.encode("utf-8"))
|
||||
except (ValueError, UnsupportedAlgorithm):
|
||||
raise ValueError("Invalid PEM public key") from None
|
||||
if isinstance(key, rsa.RSAPublicKey) and key.key_size >= 2048:
|
||||
return key
|
||||
if isinstance(key, ec.EllipticCurvePublicKey) and isinstance(key.curve, ec.SECP256R1):
|
||||
return key
|
||||
raise UnsupportedKeyType("Unsupported public key type")
|
||||
|
||||
def verify_implant_signature(public_key, signature, nonce):
|
||||
try:
|
||||
signed = base64.b64decode(signature, validate=True)
|
||||
if isinstance(public_key, ec.EllipticCurvePublicKey):
|
||||
public_key.verify(signed, nonce.encode("ascii"), ec.ECDSA(hashes.SHA256()))
|
||||
else:
|
||||
public_key.verify(signed, nonce.encode("ascii"), padding.PKCS1v15(), hashes.SHA256())
|
||||
except (InvalidSignature, ValueError):
|
||||
return False
|
||||
return True
|
||||
Executable
+6
@@ -0,0 +1,6 @@
|
||||
Flask==3.1.3
|
||||
Werkzeug==3.1.9
|
||||
gunicorn==27.0.1
|
||||
pycryptodome==4.5.0
|
||||
cryptography==50.0.2
|
||||
obsigil==1.0.0
|
||||
Executable
+13
@@ -0,0 +1,13 @@
|
||||
FROM python:3.12-slim-bookworm
|
||||
|
||||
RUN useradd --uid 10001 --user-group --no-create-home --shell /usr/sbin/nologin ledger-cleaner \
|
||||
&& install -d -m 0700 -o ledger-cleaner -g ledger-cleaner /var/lib/chrome-ledger
|
||||
|
||||
COPY --chmod=755 cleaner.sh /cleaner.sh
|
||||
COPY cleaner.py /cleaner.py
|
||||
|
||||
USER ledger-cleaner
|
||||
|
||||
HEALTHCHECK --interval=10m --timeout=5s --start-period=90s --retries=2 CMD python3 -c "import os,time; p='/tmp/cleaner-last-success'; raise SystemExit(0 if os.path.exists(p) and time.time()-os.path.getmtime(p)<720 else 1)"
|
||||
|
||||
CMD ["/cleaner.sh"]
|
||||
Executable
+54
@@ -0,0 +1,54 @@
|
||||
import os
|
||||
import sqlite3
|
||||
|
||||
from datetime import UTC, datetime, timedelta
|
||||
|
||||
|
||||
RETENTION = timedelta(minutes=10)
|
||||
|
||||
|
||||
def main():
|
||||
connection = sqlite3.connect(os.environ["LEDGER_DB"], timeout=5)
|
||||
connection.execute("PRAGMA busy_timeout = 5000")
|
||||
connection.execute("PRAGMA foreign_keys = ON")
|
||||
tables = {
|
||||
row[0]
|
||||
for row in connection.execute("SELECT name FROM sqlite_master WHERE type = 'table'")
|
||||
}
|
||||
cutoff = (datetime.now(UTC) - RETENTION).isoformat()
|
||||
deleted = []
|
||||
if "auth_sessions" in tables:
|
||||
cursor = connection.execute(
|
||||
"DELETE FROM auth_sessions WHERE expires_at <= ?",
|
||||
(int(datetime.now(UTC).timestamp()),),
|
||||
)
|
||||
deleted.append(f"sessions={cursor.rowcount}")
|
||||
if "implant_challenges" in tables:
|
||||
cursor = connection.execute(
|
||||
"DELETE FROM implant_challenges WHERE created_at <= ?",
|
||||
(cutoff,),
|
||||
)
|
||||
deleted.append(f"challenges={cursor.rowcount}")
|
||||
if "implants" in tables:
|
||||
cursor = connection.execute(
|
||||
"DELETE FROM implants WHERE created_at <= ?",
|
||||
(cutoff,),
|
||||
)
|
||||
deleted.append(f"implants={cursor.rowcount}")
|
||||
if "users" in tables and "implants" in tables:
|
||||
cursor = connection.execute(
|
||||
"DELETE FROM users WHERE created_at <= ? "
|
||||
"AND NOT EXISTS (SELECT 1 FROM implants WHERE implants.user_id = users.id)",
|
||||
(cutoff,),
|
||||
)
|
||||
deleted.append(f"users={cursor.rowcount}")
|
||||
connection.commit()
|
||||
connection.execute("PRAGMA wal_checkpoint(PASSIVE)")
|
||||
connection.execute("PRAGMA optimize")
|
||||
connection.execute("PRAGMA incremental_vacuum").fetchall()
|
||||
connection.close()
|
||||
print("cleaned " + " ".join(deleted), flush=True)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Executable
+8
@@ -0,0 +1,8 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
while true; do
|
||||
if python3 /cleaner.py; then
|
||||
touch /tmp/cleaner-last-success
|
||||
fi
|
||||
sleep 600
|
||||
done
|
||||
Executable
+80
@@ -0,0 +1,80 @@
|
||||
name: chrome-ledger
|
||||
|
||||
services:
|
||||
service:
|
||||
build: .
|
||||
command: ["python", "run.py"]
|
||||
environment:
|
||||
LEDGER_DB: "/var/lib/chrome-ledger/ledger.sqlite3"
|
||||
PYTHONDONTWRITEBYTECODE: "1"
|
||||
PYTHONUNBUFFERED: "1"
|
||||
ports:
|
||||
- "8081:8080"
|
||||
volumes:
|
||||
- ledger_data:/var/lib/chrome-ledger
|
||||
restart: unless-stopped
|
||||
read_only: true
|
||||
tmpfs:
|
||||
- /tmp:size=64m,mode=1777
|
||||
cap_drop:
|
||||
- ALL
|
||||
security_opt:
|
||||
- no-new-privileges:true
|
||||
stop_grace_period: 20s
|
||||
deploy:
|
||||
resources:
|
||||
limits:
|
||||
cpus: "2.0"
|
||||
memory: 512M
|
||||
pids: 256
|
||||
reservations:
|
||||
cpus: "0.25"
|
||||
memory: 128M
|
||||
healthcheck:
|
||||
test: ["CMD", "python", "-c", "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8080/login', timeout=3).close()"]
|
||||
interval: 10s
|
||||
timeout: 5s
|
||||
start_period: 15s
|
||||
retries: 3
|
||||
logging:
|
||||
driver: json-file
|
||||
options:
|
||||
max-size: "10m"
|
||||
max-file: "3"
|
||||
|
||||
cleaner:
|
||||
build: ./cleaner
|
||||
depends_on:
|
||||
- service
|
||||
environment:
|
||||
LEDGER_DB: "/var/lib/chrome-ledger/ledger.sqlite3"
|
||||
PYTHONDONTWRITEBYTECODE: "1"
|
||||
PYTHONUNBUFFERED: "1"
|
||||
volumes:
|
||||
- ledger_data:/var/lib/chrome-ledger
|
||||
restart: unless-stopped
|
||||
read_only: true
|
||||
tmpfs:
|
||||
- /tmp:size=16m,mode=1777
|
||||
cap_drop:
|
||||
- ALL
|
||||
security_opt:
|
||||
- no-new-privileges:true
|
||||
deploy:
|
||||
resources:
|
||||
limits:
|
||||
cpus: "0.25"
|
||||
memory: 64M
|
||||
pids: 64
|
||||
reservations:
|
||||
cpus: "0.05"
|
||||
memory: 16M
|
||||
logging:
|
||||
driver: json-file
|
||||
options:
|
||||
max-size: "10m"
|
||||
max-file: "3"
|
||||
|
||||
volumes:
|
||||
ledger_data:
|
||||
name: chrome-ledger-data
|
||||
Executable
+41
@@ -0,0 +1,41 @@
|
||||
<!doctype html>
|
||||
<html lang="ru">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>Chrome Ledger</title>
|
||||
<link rel="stylesheet" href="/src/shared/styles/main.css">
|
||||
</head>
|
||||
<body>
|
||||
<div class="layout signed-out" id="layout">
|
||||
<header class="topbar">
|
||||
<div class="topbar-inner">
|
||||
<a class="brand" href="/">
|
||||
<span class="brand-mark" aria-hidden="true"></span>
|
||||
Chrome Ledger
|
||||
</a>
|
||||
<nav id="nav" aria-label="Основная навигация">
|
||||
<a href="/home/implants" data-auth>Импланты</a>
|
||||
<a href="/home/registry" data-auth>Реестр</a>
|
||||
<a href="/home/register_implant" data-auth>Новый имплант</a>
|
||||
<a href="/home/check_certificate" data-auth>Проверка</a>
|
||||
<a href="/home/reissue" data-auth>Перевыпуск</a>
|
||||
</nav>
|
||||
<div class="account" id="account">
|
||||
<span id="username"></span>
|
||||
<button class="secondary" type="button" id="logout">Выйти</button>
|
||||
<a class="account-login" href="/login" id="login-link">Войти</a>
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
<main class="workspace">
|
||||
<div class="content" id="view"></div>
|
||||
<div class="circuit" aria-hidden="true">
|
||||
<div class="chip"><span></span></div>
|
||||
<div class="scanline"></div>
|
||||
</div>
|
||||
</main>
|
||||
</div>
|
||||
<script src="/src/app/main.js" type="module"></script>
|
||||
</body>
|
||||
</html>
|
||||
Executable
+151
@@ -0,0 +1,151 @@
|
||||
import { api } from '../shared/api/client.js';
|
||||
import { state, setSession } from '../shared/session.js';
|
||||
import { renderLogin } from '../features/auth/login.js';
|
||||
import { renderIssue } from '../features/implants/create.js';
|
||||
import { renderList } from '../features/implants/list.js';
|
||||
import { renderCard } from '../features/implants/details.js';
|
||||
import { renderHolder } from '../features/implants/holder.js';
|
||||
import { renderReissue } from '../features/implants/reissue.js';
|
||||
import { renderRegistry } from '../features/implants/registry.js';
|
||||
|
||||
const nav = document.querySelector('#nav');
|
||||
const username = document.querySelector('#username');
|
||||
const layout = document.querySelector('#layout');
|
||||
const logout = document.querySelector('#logout');
|
||||
const loginLink = document.querySelector('#login-link');
|
||||
|
||||
const pageTitles = {
|
||||
'/login': 'Вход',
|
||||
'/home': 'Главная',
|
||||
'/home/register_implant': 'Новый имплант',
|
||||
'/home/check_certificate': 'Проверка',
|
||||
'/home/reissue': 'Перевыпуск',
|
||||
'/home/implants': 'Импланты',
|
||||
'/home/registry': 'Реестр сертификатов',
|
||||
};
|
||||
|
||||
function go(path, { replace = false } = {}) {
|
||||
if (replace) history.replaceState(null, '', path);
|
||||
else history.pushState(null, '', path);
|
||||
render();
|
||||
}
|
||||
|
||||
function syncChrome() {
|
||||
const signedIn = Boolean(state.user);
|
||||
layout.classList.toggle('signed-out', !signedIn);
|
||||
username.textContent = state.user ? state.user.username : '';
|
||||
logout.hidden = !signedIn;
|
||||
loginLink.hidden = signedIn;
|
||||
for (const link of nav.querySelectorAll('[data-auth]')) {
|
||||
link.hidden = !signedIn;
|
||||
}
|
||||
for (const link of nav.querySelectorAll('a')) {
|
||||
const href = link.getAttribute('href');
|
||||
const active = href === location.pathname
|
||||
|| (href === '/home/implants' && location.pathname.startsWith('/home/implants/'))
|
||||
|| (href === '/home/check_certificate' && location.pathname.startsWith('/home/check_certificate/'));
|
||||
link.classList.toggle('active', active);
|
||||
if (active) link.setAttribute('aria-current', 'page');
|
||||
else link.removeAttribute('aria-current');
|
||||
}
|
||||
const routeTitle = location.pathname.startsWith('/home/implants/')
|
||||
? 'Карточка импланта'
|
||||
: location.pathname.startsWith('/home/check_certificate/') ? 'Проверка' : pageTitles[location.pathname];
|
||||
document.title = routeTitle ? `${routeTitle} · Chrome Ledger` : 'Chrome Ledger';
|
||||
}
|
||||
|
||||
function render() {
|
||||
const path = location.pathname;
|
||||
const publicPage = path === '/login';
|
||||
if (path === '/') return go(state.user ? '/home' : '/login', { replace: true });
|
||||
if (!state.user && !publicPage) return go('/login', { replace: true });
|
||||
if (state.user && path === '/login') return go('/home', { replace: true });
|
||||
syncChrome();
|
||||
if (path === '/login') return renderLogin(go);
|
||||
if (path === '/home') {
|
||||
document.querySelector('#view').innerHTML = '<section class="page"><div class="panel welcome"><h1>Добро пожаловать в Chrome Ledger!</h1></div></section>';
|
||||
return;
|
||||
}
|
||||
if (path === '/home/register_implant') return renderIssue();
|
||||
if (path === '/home/check_certificate') return renderHolder();
|
||||
if (path === '/home/reissue') {
|
||||
const params = new URLSearchParams(location.search);
|
||||
return renderReissue(params.get('id') || '', params.get('serial') || '');
|
||||
}
|
||||
const check = path.match(/^\/home\/check_certificate\/([^/]+)\/check$/);
|
||||
if (check) return renderHolder(decodeURIComponent(check[1]));
|
||||
if (path === '/home/implants') return renderList();
|
||||
if (path === '/home/registry') return renderRegistry();
|
||||
const card = path.match(/^\/home\/implants\/([^/]+)$/);
|
||||
if (card) return renderCard(decodeURIComponent(card[1]));
|
||||
go('/home', { replace: true });
|
||||
}
|
||||
|
||||
window.addEventListener('ledger:session-expired', () => go('/login', { replace: true }));
|
||||
|
||||
logout.addEventListener('click', async (event) => {
|
||||
const button = event.currentTarget;
|
||||
button.disabled = true;
|
||||
try {
|
||||
await api('/logout', { method: 'DELETE' });
|
||||
setSession(null);
|
||||
go('/login', { replace: true });
|
||||
} catch (error) {
|
||||
window.alert(error.message);
|
||||
} finally {
|
||||
button.disabled = false;
|
||||
}
|
||||
});
|
||||
|
||||
document.addEventListener('input', ({ target }) => {
|
||||
if (target instanceof HTMLInputElement || target instanceof HTMLTextAreaElement) {
|
||||
target.setCustomValidity(/[^\x00-\x7F]/.test(target.value)
|
||||
? 'Допустимы только английские буквы, цифры и символы ASCII' : '');
|
||||
}
|
||||
});
|
||||
|
||||
document.addEventListener('click', (event) => {
|
||||
if (
|
||||
event.defaultPrevented
|
||||
|| event.button !== 0
|
||||
|| event.metaKey
|
||||
|| event.ctrlKey
|
||||
|| event.shiftKey
|
||||
|| event.altKey
|
||||
) {
|
||||
return;
|
||||
}
|
||||
const link = event.target.closest('a');
|
||||
if (!link) {
|
||||
return;
|
||||
}
|
||||
if (link.target && link.target !== '_self') {
|
||||
return;
|
||||
}
|
||||
if (link.hasAttribute('download')) {
|
||||
return;
|
||||
}
|
||||
const url = new URL(link.href, location.origin);
|
||||
if (url.origin !== location.origin) {
|
||||
return;
|
||||
}
|
||||
event.preventDefault();
|
||||
go(url.pathname + url.search);
|
||||
});
|
||||
|
||||
window.addEventListener('popstate', render);
|
||||
|
||||
async function start() {
|
||||
if (state.token) {
|
||||
const token = state.token;
|
||||
try {
|
||||
const user = await api('/me');
|
||||
if (state.token === token) state.user = user;
|
||||
} catch (error) {
|
||||
if (state.token === token) window.alert(error.message);
|
||||
}
|
||||
}
|
||||
render();
|
||||
}
|
||||
|
||||
start();
|
||||
+71
@@ -0,0 +1,71 @@
|
||||
import { api } from '../../shared/api/client.js';
|
||||
import { setSession } from '../../shared/session.js';
|
||||
import { setError } from '../../shared/ui/dom.js';
|
||||
|
||||
const view = document.querySelector('#view');
|
||||
|
||||
export function renderLogin(go) {
|
||||
let registering = false;
|
||||
view.innerHTML = `
|
||||
<section class="page login">
|
||||
<header class="page-header">
|
||||
<h1 id="login-title">Войти в <span>личный кабинет</span></h1>
|
||||
</header>
|
||||
<form class="panel fields" id="login-form">
|
||||
<h2 id="login-form-title">Учетные данные</h2>
|
||||
<label>
|
||||
Имя пользователя
|
||||
<input id="login-username" required autocomplete="username" minlength="3" maxlength="32" pattern="[A-Za-z0-9_\\-]{3,32}">
|
||||
</label>
|
||||
<label>
|
||||
Пароль
|
||||
<input id="login-password" type="password" required minlength="8" maxlength="128" autocomplete="current-password">
|
||||
</label>
|
||||
<p class="error" id="login-error" role="alert" hidden></p>
|
||||
<div class="actions">
|
||||
<button type="submit" id="login-submit">Войти</button>
|
||||
<button class="secondary" type="button" id="login-toggle">Создать аккаунт</button>
|
||||
</div>
|
||||
</form>
|
||||
</section>`;
|
||||
|
||||
const form = document.querySelector('#login-form');
|
||||
const title = document.querySelector('#login-title');
|
||||
const userInput = document.querySelector('#login-username');
|
||||
const password = document.querySelector('#login-password');
|
||||
const problem = document.querySelector('#login-error');
|
||||
const submit = document.querySelector('#login-submit');
|
||||
const toggle = document.querySelector('#login-toggle');
|
||||
|
||||
const setMode = (next) => {
|
||||
registering = next;
|
||||
title.innerHTML = next ? 'Создать <span>аккаунт</span>' : 'Войти в <span>личный кабинет</span>';
|
||||
submit.textContent = next ? 'Создать аккаунт' : 'Войти';
|
||||
toggle.textContent = next ? 'У меня есть аккаунт' : 'Создать аккаунт';
|
||||
password.autocomplete = next ? 'new-password' : 'current-password';
|
||||
password.value = '';
|
||||
setError(problem, '');
|
||||
};
|
||||
|
||||
toggle.addEventListener('click', () => setMode(!registering));
|
||||
|
||||
form.addEventListener('submit', async (event) => {
|
||||
event.preventDefault();
|
||||
setError(problem, '');
|
||||
submit.disabled = true;
|
||||
toggle.disabled = true;
|
||||
try {
|
||||
setSession(await api(registering ? '/register' : '/login', {
|
||||
method: 'POST',
|
||||
body: { username: userInput.value, password: password.value },
|
||||
}));
|
||||
go('/home', { replace: true });
|
||||
} catch (error) {
|
||||
setError(problem, error.message);
|
||||
} finally {
|
||||
submit.disabled = false;
|
||||
toggle.disabled = false;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
export const certificateStatus = {
|
||||
active: 'Действует', revoked: 'Отозван', expired: 'Срок истёк', invalid: 'Недействителен',
|
||||
};
|
||||
+96
@@ -0,0 +1,96 @@
|
||||
import { api } from '../../shared/api/client.js';
|
||||
import { escapeHtml, setError, showResultDialog } from '../../shared/ui/dom.js';
|
||||
|
||||
const view = document.querySelector('#view');
|
||||
|
||||
export function renderIssue() {
|
||||
view.innerHTML = `
|
||||
<section class="page">
|
||||
<header class="page-header">
|
||||
<p class="eyebrow"><a href="/home/implants">Импланты</a> / Новый имплант</p>
|
||||
<h1>Новый <span>имплант</span></h1>
|
||||
<p class="intro">Зарегистрируйте устройство и выпустите сертификат</p>
|
||||
</header>
|
||||
<form class="panel fields" id="issue-form">
|
||||
<h2>Сведения об импланте</h2>
|
||||
<div class="field-grid">
|
||||
<label>Название
|
||||
<input id="issue-name" required minlength="1" maxlength="80" autocomplete="off">
|
||||
</label>
|
||||
<label>Модель
|
||||
<input id="issue-model" required minlength="1" maxlength="80" autocomplete="off">
|
||||
</label>
|
||||
</div>
|
||||
<div class="field-grid">
|
||||
<label>Код проекта
|
||||
<input id="issue-project" required minlength="1" maxlength="80" autocomplete="off">
|
||||
</label>
|
||||
<label>Код организации
|
||||
<input id="issue-organization" required minlength="1" maxlength="80" autocomplete="off">
|
||||
</label>
|
||||
</div>
|
||||
<p class="notice">Код проекта и код организации — приватные данные, необходимые для учёта происхождения импланта. Не раскрывайте их значения третьим лицам</p>
|
||||
<label>
|
||||
Открытый ключ
|
||||
<textarea id="issue-key" class="mono" rows="7" spellcheck="false" required placeholder="-----BEGIN PUBLIC KEY----- ... -----END PUBLIC KEY-----"></textarea>
|
||||
<small>Полный открытый ключ в формате PEM: ECDSA P-256 или RSA от 2048 бит</small>
|
||||
</label>
|
||||
<p class="notice">После выпуска сохраните сертификат</p>
|
||||
<p class="error" id="issue-error" role="alert" hidden></p>
|
||||
<div class="actions">
|
||||
<button type="submit" id="issue-submit">Выпустить сертификат</button>
|
||||
</div>
|
||||
</form>
|
||||
<div id="issue-result"></div>
|
||||
</section>`;
|
||||
|
||||
const form = document.querySelector('#issue-form');
|
||||
const key = document.querySelector('#issue-key');
|
||||
const problem = document.querySelector('#issue-error');
|
||||
const submit = document.querySelector('#issue-submit');
|
||||
const result = document.querySelector('#issue-result');
|
||||
|
||||
form.addEventListener('submit', async (event) => {
|
||||
event.preventDefault();
|
||||
setError(problem, '');
|
||||
result.innerHTML = '';
|
||||
const body = {
|
||||
public_key_pem: key.value,
|
||||
display_name: document.querySelector('#issue-name').value,
|
||||
model: document.querySelector('#issue-model').value,
|
||||
project_codename: document.querySelector('#issue-project').value,
|
||||
installed_by: document.querySelector('#issue-organization').value,
|
||||
};
|
||||
submit.disabled = true;
|
||||
submit.textContent = 'Оформляем сертификат…';
|
||||
try {
|
||||
const data = await api('/register_implant', { method: 'POST', body });
|
||||
form.reset();
|
||||
result.innerHTML = `
|
||||
<dialog class="issue-dialog" aria-labelledby="issue-result-title">
|
||||
<section class="panel fields" aria-live="polite">
|
||||
<h2 id="issue-result-title">Сертификат выпущен</h2>
|
||||
<p class="success-message">Имплант зарегистрирован. Сохраните сертификат перед продолжением работы</p>
|
||||
<dl class="details">
|
||||
<dt>ID импланта</dt>
|
||||
<dd class="mono">${escapeHtml(data.id)}</dd>
|
||||
</dl>
|
||||
<label>Сертификат (PEM)
|
||||
<textarea class="mono" readonly rows="5">${escapeHtml(data.cert_pem)}</textarea>
|
||||
</label>
|
||||
<div class="actions">
|
||||
<button class="secondary" type="button" data-close-dialog>Закрыть</button>
|
||||
</div>
|
||||
</section>
|
||||
</dialog>`;
|
||||
|
||||
showResultDialog(result);
|
||||
} catch (error) {
|
||||
setError(problem, error.message);
|
||||
} finally {
|
||||
submit.disabled = false;
|
||||
submit.textContent = 'Выпустить сертификат';
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
+55
@@ -0,0 +1,55 @@
|
||||
import { api } from '../../shared/api/client.js';
|
||||
import { state } from '../../shared/session.js';
|
||||
import { certificateStatus } from './certificate.js';
|
||||
import { dateTime, escapeHtml, readOnlyField } from '../../shared/ui/dom.js';
|
||||
|
||||
const view = document.querySelector('#view');
|
||||
|
||||
|
||||
export async function renderCard(id) {
|
||||
const route = location.pathname;
|
||||
view.innerHTML = '<section class="page"><div class="panel loading" aria-live="polite">Загружаем карточку…</div></section>';
|
||||
try {
|
||||
const base = '/implants/' + encodeURIComponent(id);
|
||||
const implant = await api(base);
|
||||
if (location.pathname !== route || !state.user) return;
|
||||
const certificate = implant.certificate;
|
||||
view.innerHTML = `<section class="page">
|
||||
<header class="page-header">
|
||||
<p class="eyebrow"><a href="/home/implants">Импланты</a> / Карточка</p>
|
||||
<h1>${escapeHtml(implant.display_name)}</h1>
|
||||
<p class="intro">Сведения об устройстве и сертификаты</p>
|
||||
</header>
|
||||
<section class="panel fields summary-panel">
|
||||
<div class="result-heading">
|
||||
<h2>Сведения об импланте</h2>
|
||||
<span class="status ${certificate.valid ? 'status-valid' : 'status-invalid'}">
|
||||
${escapeHtml(certificateStatus[certificate.status] || certificate.status)}
|
||||
</span>
|
||||
</div>
|
||||
<dl class="details">
|
||||
<dt>ID</dt><dd class="mono">${escapeHtml(id)}</dd>
|
||||
<dt>Модель</dt><dd>${escapeHtml(implant.model || 'Не указана')}</dd>
|
||||
<dt>Создан</dt><dd>${escapeHtml(dateTime(implant.created_at))}</dd>
|
||||
<dt>Сертификат</dt><dd>${escapeHtml(certificateStatus[certificate.status] || certificate.status)}</dd>
|
||||
</dl>
|
||||
</section>
|
||||
<section class="panel fields">
|
||||
<h2>Публичный сертификат</h2>
|
||||
<dl class="details">
|
||||
<dt>Серийный номер</dt><dd class="mono">${escapeHtml(certificate.serial)}</dd>
|
||||
<dt>Действует до</dt><dd>${escapeHtml(dateTime(certificate.not_after))}</dd>
|
||||
<dt>SHA-256</dt><dd class="mono">${escapeHtml(certificate.fingerprint)}</dd>
|
||||
${certificate.revoked_at ? `<dt>Отозван</dt><dd>${escapeHtml(dateTime(certificate.revoked_at))}</dd>` : ''}
|
||||
</dl>
|
||||
${readOnlyField('Сертификат (PEM)', certificate.cert_pem, 4)}
|
||||
</section>
|
||||
</section>`;
|
||||
} catch (error) {
|
||||
if (location.pathname !== route) return;
|
||||
view.innerHTML = `<section class="page"><div class="panel fields">
|
||||
<p class="error" role="alert">${escapeHtml(error.message)}</p>
|
||||
<div><a class="text-link" href="/home/implants">Вернуться к имплантам</a></div>
|
||||
</div></section>`;
|
||||
}
|
||||
}
|
||||
+101
@@ -0,0 +1,101 @@
|
||||
import { api } from '../../shared/api/client.js';
|
||||
import { escapeHtml, setError, readOnlyField, showResultDialog } from '../../shared/ui/dom.js';
|
||||
|
||||
const view = document.querySelector('#view');
|
||||
|
||||
export function renderHolder(wanted = '') {
|
||||
view.innerHTML = `<section class="page">
|
||||
<header class="page-header">
|
||||
<p class="eyebrow">/Проверка</p>
|
||||
<h1>Проверка</h1>
|
||||
<p class="intro">Проверьте данные своего сертификата</p>
|
||||
</header>
|
||||
<ol class="steps" aria-label="Порядок доступа">
|
||||
<li>Получите верификатор</li>
|
||||
<li>Подпишите строку закрытым ключом</li>
|
||||
<li>Отправьте подпись в base64</li>
|
||||
</ol>
|
||||
<form class="panel fields" id="challenge-form">
|
||||
<h2>Получить верификатор</h2>
|
||||
<label>ID импланта
|
||||
<input class="mono" id="holder-id" required spellcheck="false" autocomplete="off"
|
||||
value="${escapeHtml(wanted)}">
|
||||
</label>
|
||||
<button type="submit">Получить верификатор</button>
|
||||
</form>
|
||||
<form class="panel fields" id="holder-form" hidden>
|
||||
<h2>Подписать верификатор</h2>
|
||||
<div id="holder-challenge"></div>
|
||||
<label>Подпись в base64
|
||||
<textarea class="mono" id="holder-signature" required rows="4" spellcheck="false"></textarea>
|
||||
<small>Подпишите точную ASCII-строку выше закрытым ключом импланта</small>
|
||||
</label>
|
||||
<button type="submit">Посмотреть данные</button>
|
||||
</form>
|
||||
<p class="error" id="holder-error" role="alert" hidden></p>
|
||||
<div id="holder-result" aria-live="polite"></div>
|
||||
</section>`;
|
||||
const challengeForm = document.querySelector('#challenge-form');
|
||||
const holderForm = document.querySelector('#holder-form');
|
||||
const challengeField = document.querySelector('#holder-challenge');
|
||||
const result = document.querySelector('#holder-result');
|
||||
const problem = document.querySelector('#holder-error');
|
||||
let pending = null;
|
||||
challengeForm.addEventListener('submit', async (event) => {
|
||||
event.preventDefault();
|
||||
const button = challengeForm.querySelector('button');
|
||||
button.disabled = true;
|
||||
pending = null;
|
||||
holderForm.hidden = true;
|
||||
result.innerHTML = '';
|
||||
setError(problem, '');
|
||||
try {
|
||||
const id = document.querySelector('#holder-id').value.trim();
|
||||
const base = '/check_certificate/' + encodeURIComponent(id);
|
||||
const challenge = await api(base + '/check');
|
||||
pending = { id, nonce: challenge.challenge, certificate: challenge.certificate.cert_pem };
|
||||
history.replaceState(null, '', '/home/check_certificate/' + encodeURIComponent(id) + '/check');
|
||||
challengeField.innerHTML = readOnlyField('Сертификат (PEM)', pending.certificate, 4)
|
||||
+ readOnlyField('Верификатор: подпишите эту ASCII-строку', pending.nonce, 2);
|
||||
document.querySelector('#holder-signature').value = '';
|
||||
holderForm.hidden = false;
|
||||
} catch (error) {
|
||||
setError(problem, error.message);
|
||||
} finally {
|
||||
button.disabled = false;
|
||||
}
|
||||
});
|
||||
holderForm.addEventListener('submit', async (event) => {
|
||||
event.preventDefault();
|
||||
if (!pending) return;
|
||||
const button = holderForm.querySelector('button');
|
||||
button.disabled = true;
|
||||
setError(problem, '');
|
||||
try {
|
||||
const data = await api('/check_certificate/' + encodeURIComponent(pending.id) + '/check', {
|
||||
method: 'POST', body: { certificate: pending.certificate, nonce: pending.nonce,
|
||||
signature: document.querySelector('#holder-signature').value.trim() },
|
||||
});
|
||||
result.innerHTML = `
|
||||
<dialog class="issue-dialog" aria-labelledby="holder-result-title">
|
||||
<section class="panel fields" aria-live="polite">
|
||||
<h2 id="holder-result-title">Данные импланта</h2>
|
||||
${readOnlyField('Код проекта', data.project_codename, 1)}
|
||||
${readOnlyField('Код организации', data.installed_by, 1)}
|
||||
<div class="actions">
|
||||
<button class="secondary" type="button" data-close-dialog>Закрыть</button>
|
||||
</div>
|
||||
</section>
|
||||
</dialog>`;
|
||||
|
||||
showResultDialog(result);
|
||||
pending = null;
|
||||
holderForm.hidden = true;
|
||||
} catch (error) {
|
||||
setError(problem, error.message);
|
||||
} finally {
|
||||
button.disabled = false;
|
||||
}
|
||||
});
|
||||
if (wanted) challengeForm.requestSubmit();
|
||||
}
|
||||
+48
@@ -0,0 +1,48 @@
|
||||
import { api } from '../../shared/api/client.js';
|
||||
import { state } from '../../shared/session.js';
|
||||
import { dateTime, escapeHtml } from '../../shared/ui/dom.js';
|
||||
|
||||
const view = document.querySelector('#view');
|
||||
|
||||
export async function renderList() {
|
||||
view.innerHTML = `<section class="page">
|
||||
<header class="page-header page-header-row">
|
||||
<div>
|
||||
<h1>Мои <span>импланты</span></h1>
|
||||
<p class="intro">Управляйте сертификатами зарегистрированных устройств</p>
|
||||
</div>
|
||||
<a class="button-link" id="implant-add" href="/home/register_implant" hidden>Добавить имплант</a>
|
||||
</header>
|
||||
<div class="record-list" id="implant-list" aria-live="polite">
|
||||
<p class="panel loading">Загружаем импланты…</p>
|
||||
</div>
|
||||
</section>`;
|
||||
const list = document.querySelector('#implant-list');
|
||||
const add = document.querySelector('#implant-add');
|
||||
try {
|
||||
const { implants } = await api('/implants');
|
||||
if (!list.isConnected || !state.user) return;
|
||||
add.hidden = !implants.length;
|
||||
list.innerHTML = implants.map((implant) => `
|
||||
<article class="panel fields">
|
||||
<div class="record-heading">
|
||||
<div>
|
||||
<h2>${escapeHtml(implant.display_name)}</h2>
|
||||
<p>${escapeHtml(implant.model || 'Модель не указана')}</p>
|
||||
</div>
|
||||
<a class="text-link" href="/home/implants/${encodeURIComponent(implant.id)}">Открыть карточку</a>
|
||||
</div>
|
||||
<dl class="details compact-details">
|
||||
<dt>ID</dt><dd class="mono">${escapeHtml(implant.id)}</dd>
|
||||
<dt>Создан</dt><dd>${escapeHtml(dateTime(implant.created_at))}</dd>
|
||||
</dl>
|
||||
</article>`).join('') || `
|
||||
<div class="panel empty-state fields">
|
||||
<h2>Имплантов пока нет</h2>
|
||||
<p>Добавьте первый имплант, чтобы выпустить сертификат</p>
|
||||
<div><a class="button-link" href="/home/register_implant">Добавить имплант</a></div>
|
||||
</div>`;
|
||||
} catch (error) {
|
||||
if (list.isConnected) list.innerHTML = `<p class="panel error" role="alert">${escapeHtml(error.message)}</p>`;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
import { api } from '../../shared/api/client.js';
|
||||
import { state } from '../../shared/session.js';
|
||||
import { certificateStatus } from './certificate.js';
|
||||
import { dateTime, escapeHtml, readOnlyField } from '../../shared/ui/dom.js';
|
||||
|
||||
const view = document.querySelector('#view');
|
||||
|
||||
export async function renderRegistry() {
|
||||
view.innerHTML = `<section class="page">
|
||||
<header class="page-header">
|
||||
<p class="eyebrow">/Реестр</p>
|
||||
<h1>Публичные <span>сертификаты</span></h1>
|
||||
<p class="intro">Импланты всех пользователей и история выпущенных сертификатов</p>
|
||||
</header>
|
||||
<div class="record-list" id="registry-list" aria-live="polite">
|
||||
<p class="panel loading">Загружаем реестр…</p>
|
||||
</div>
|
||||
<div class="actions">
|
||||
<button class="secondary" id="registry-prev" type="button" disabled>Назад</button>
|
||||
<span id="registry-page" aria-live="polite"></span>
|
||||
<button class="secondary" id="registry-next" type="button" disabled>Далее</button>
|
||||
</div>
|
||||
</section>`;
|
||||
const list = document.querySelector('#registry-list');
|
||||
const previous = document.querySelector('#registry-prev');
|
||||
const next = document.querySelector('#registry-next');
|
||||
const counter = document.querySelector('#registry-page');
|
||||
try {
|
||||
const { results } = await api('/registry');
|
||||
if (!list.isConnected || !state.user) return;
|
||||
let page = 0;
|
||||
const renderPage = () => {
|
||||
list.innerHTML = results.slice(page * 20, (page + 1) * 20).map((implant) => `
|
||||
<article class="panel fields">
|
||||
<div class="record-heading">
|
||||
<h2>${escapeHtml(implant.display_name)}</h2>
|
||||
<span class="counter">${implant.certificates.length}</span>
|
||||
</div>
|
||||
<dl class="details">
|
||||
<dt>ID импланта</dt><dd class="mono">${escapeHtml(implant.id)}</dd>
|
||||
<dt>Модель</dt><dd>${escapeHtml(implant.model || 'Не указана')}</dd>
|
||||
<dt>Владелец</dt><dd>${escapeHtml(implant.owner)}</dd>
|
||||
<dt>Создан</dt><dd>${escapeHtml(dateTime(implant.created_at))}</dd>
|
||||
</dl>
|
||||
${implant.certificates.map((certificate) => `
|
||||
<details class="certificate-record">
|
||||
<summary>
|
||||
<span class="mono">${escapeHtml(certificate.serial)}</span>
|
||||
<span class="status ${certificate.valid ? 'status-valid' : 'status-invalid'}">${escapeHtml(certificateStatus[certificate.status] || certificate.status)}</span>
|
||||
</summary>
|
||||
<div class="fields">
|
||||
<dl class="details">
|
||||
<dt>SHA-256</dt><dd class="mono">${escapeHtml(certificate.fingerprint)}</dd>
|
||||
<dt>Субъект</dt><dd>${escapeHtml(certificate.subject)}</dd>
|
||||
<dt>Удостоверяющий центр</dt><dd>${escapeHtml(certificate.issuer)}</dd>
|
||||
<dt>Действует с</dt><dd>${escapeHtml(dateTime(certificate.not_before))}</dd>
|
||||
<dt>Действует до</dt><dd>${escapeHtml(dateTime(certificate.not_after))}</dd>
|
||||
${certificate.revoked_at ? `<dt>Отозван</dt><dd>${escapeHtml(dateTime(certificate.revoked_at))}</dd>` : ''}
|
||||
</dl>
|
||||
${readOnlyField('Сертификат (PEM)', certificate.cert_pem, 4)}
|
||||
</div>
|
||||
</details>`).join('')}
|
||||
</article>`).join('') || '<div class="panel empty-state">В реестре пока нет имплантов</div>';
|
||||
previous.disabled = page === 0;
|
||||
next.disabled = (page + 1) * 20 >= results.length;
|
||||
counter.textContent = `Страница ${page + 1} из ${Math.max(1, Math.ceil(results.length / 20))} · Имплантов: ${results.length}`;
|
||||
};
|
||||
previous.addEventListener('click', () => { if (page > 0) { page -= 1; renderPage(); } });
|
||||
next.addEventListener('click', () => { if ((page + 1) * 20 < results.length) { page += 1; renderPage(); } });
|
||||
renderPage();
|
||||
} catch (error) {
|
||||
if (list.isConnected) list.innerHTML = `<p class="panel error" role="alert">${escapeHtml(error.message)}</p>`;
|
||||
}
|
||||
}
|
||||
+96
@@ -0,0 +1,96 @@
|
||||
import { api } from '../../shared/api/client.js';
|
||||
import { escapeHtml, setError, readOnlyField, showResultDialog } from '../../shared/ui/dom.js';
|
||||
|
||||
const view = document.querySelector('#view');
|
||||
|
||||
export function renderReissue(wanted = '', serial = '') {
|
||||
view.innerHTML = `<section class="page">
|
||||
<header class="page-header">
|
||||
<p class="eyebrow">/Перевыпуск</p>
|
||||
<h1>Перевыпуск</h1>
|
||||
</header>
|
||||
<form class="panel fields" id="reissue-form">
|
||||
<label>ID импланта
|
||||
<input class="mono" id="reissue-id" required spellcheck="false" autocomplete="off" value="${escapeHtml(wanted)}">
|
||||
</label>
|
||||
<label>Серийный номер текущего сертификата
|
||||
<input class="mono" id="reissue-serial" required maxlength="40" pattern="[0-9a-f]+"
|
||||
spellcheck="false" autocomplete="off" value="${escapeHtml(serial)}">
|
||||
</label>
|
||||
<label>Подписанный CSR (PEM)
|
||||
<textarea class="mono" id="reissue-csr" required rows="6" maxlength="60000" spellcheck="false"
|
||||
placeholder="-----BEGIN CERTIFICATE REQUEST-----"></textarea>
|
||||
</label>
|
||||
<label>Подпись текущим ключом в base64
|
||||
<textarea class="mono" id="reissue-signature" required rows="4" spellcheck="false"></textarea>
|
||||
<small><a class="text-link" id="signature-rules-link" href="#signature-rules">Правила подписи</a></small>
|
||||
</label>
|
||||
<button type="submit">Перевыпустить сертификат</button>
|
||||
</form>
|
||||
<dialog class="issue-dialog" id="signature-rules" aria-labelledby="signature-rules-title">
|
||||
<section class="panel fields">
|
||||
<h2 id="signature-rules-title">Правила подписи</h2>
|
||||
<p>Вычислите SHA-256 от DER-представления подписанного CSR. Запишите хеш строчными шестнадцатеричными символами.</p>
|
||||
<p>Подставьте ID импланта, серийный номер текущего сертификата и хеш в ASCII-строку без перевода строки в конце:</p>
|
||||
<code>reissue:<ID импланта>:<серийный номер>:<SHA256(CSR_DER)></code>
|
||||
<p>Подпишите строку текущим закрытым ключом импланта: ECDSA с SHA-256 или RSA PKCS#1 v1.5 с SHA-256</p>
|
||||
<p>Преобразуйте полученную подпись в Base64 и вставьте её в поле «Подпись текущим ключом в base64»</p>
|
||||
<div class="actions">
|
||||
<button class="secondary" type="button" data-close-dialog>Закрыть</button>
|
||||
</div>
|
||||
</section>
|
||||
</dialog>
|
||||
<p class="error" id="reissue-error" role="alert" hidden></p>
|
||||
<div id="reissue-result" aria-live="polite"></div>
|
||||
</section>`;
|
||||
const form = document.querySelector('#reissue-form');
|
||||
const result = document.querySelector('#reissue-result');
|
||||
const problem = document.querySelector('#reissue-error');
|
||||
const rules = document.querySelector('#signature-rules');
|
||||
document.querySelector('#signature-rules-link').addEventListener('click', (event) => {
|
||||
event.preventDefault();
|
||||
rules.showModal();
|
||||
});
|
||||
rules.querySelector('[data-close-dialog]').addEventListener('click', () => rules.close());
|
||||
form.addEventListener('submit', async (event) => {
|
||||
event.preventDefault();
|
||||
const button = form.querySelector('button');
|
||||
button.disabled = true;
|
||||
result.innerHTML = '';
|
||||
setError(problem, '');
|
||||
try {
|
||||
const id = document.querySelector('#reissue-id').value.trim();
|
||||
const data = await api('/reissue/' + encodeURIComponent(id), {
|
||||
method: 'POST', body: { csr_pem: document.querySelector('#reissue-csr').value.trim(),
|
||||
certificate_serial: document.querySelector('#reissue-serial').value.trim(),
|
||||
signature: document.querySelector('#reissue-signature').value.trim() },
|
||||
});
|
||||
const certificate = data.certificate;
|
||||
result.innerHTML = `<dialog class="issue-dialog" aria-labelledby="reissue-result-title">
|
||||
<section class="panel fields">
|
||||
<h2 id="reissue-result-title">Сертификат перевыпущен</h2>
|
||||
${[
|
||||
['ID импланта', data.id], ['Название', data.display_name], ['Модель', data.model],
|
||||
['Владелец', data.owner], ['ID владельца', data.user_id], ['Создан', data.created_at],
|
||||
['Код проекта', data.project_codename], ['Код организации', data.installed_by],
|
||||
['Владелец сертификата', certificate.subject], ['Издатель', certificate.issuer],
|
||||
['Серийный номер', certificate.serial], ['Действует с', certificate.not_before],
|
||||
['Действует до', certificate.not_after], ['Статус', certificate.valid ? 'Действует' : 'Недействителен'],
|
||||
['SHA-256', certificate.fingerprint],
|
||||
].map(([label, value]) => readOnlyField(label, value, 1)).join('')}
|
||||
${readOnlyField('Сертификат (PEM)', data.cert_pem, 4)}
|
||||
<div class="actions">
|
||||
<button class="secondary" type="button" data-close-dialog>Закрыть</button>
|
||||
</div>
|
||||
</section>
|
||||
</dialog>`;
|
||||
showResultDialog(result);
|
||||
document.querySelector('#reissue-serial').value = certificate.serial;
|
||||
document.querySelector('#reissue-signature').value = '';
|
||||
} catch (error) {
|
||||
setError(problem, error.message);
|
||||
} finally {
|
||||
button.disabled = false;
|
||||
}
|
||||
});
|
||||
}
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
import { state, setSession } from '../session.js';
|
||||
|
||||
export async function api(path, { method = 'GET', body } = {}) {
|
||||
if (path !== '/login' && path !== '/register') path = '/home/api' + path;
|
||||
const token = state.token;
|
||||
let response;
|
||||
try {
|
||||
response = await fetch(path, {
|
||||
method,
|
||||
credentials: 'omit',
|
||||
headers: {
|
||||
...(body === undefined ? {} : { 'Content-Type': 'application/json' }),
|
||||
...(token ? { Authorization: 'Bearer ' + token } : {}),
|
||||
},
|
||||
body: body === undefined ? undefined : JSON.stringify(body),
|
||||
});
|
||||
} catch {
|
||||
throw new Error('Нет связи с Chrome Ledger');
|
||||
}
|
||||
if (response.status === 204) return null;
|
||||
const data = await response.json().catch(() => null);
|
||||
if (!response.ok || data === null) {
|
||||
if (response.status === 401 && token && state.token === token && data && data.error === 'Authentication required') {
|
||||
setSession(null);
|
||||
window.dispatchEvent(new Event('ledger:session-expired'));
|
||||
}
|
||||
if (data && data.error) {
|
||||
throw new Error(data.error);
|
||||
}
|
||||
throw new Error('Сервис вернул неожиданный ответ');
|
||||
}
|
||||
return data;
|
||||
}
|
||||
|
||||
Executable
+8
@@ -0,0 +1,8 @@
|
||||
export const state = { user: null, token: sessionStorage.getItem('ledger-token') };
|
||||
|
||||
export function setSession(data) {
|
||||
state.user = data ? { id: data.id, username: data.username } : null;
|
||||
state.token = data ? data.access_token : null;
|
||||
if (state.token) sessionStorage.setItem('ledger-token', state.token);
|
||||
else sessionStorage.removeItem('ledger-token');
|
||||
}
|
||||
+476
@@ -0,0 +1,476 @@
|
||||
:root {
|
||||
color-scheme: dark;
|
||||
font-family: var(--sans);
|
||||
--sans: ui-sans-serif, system-ui, -apple-system, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
|
||||
--text: #e8eef6;
|
||||
--ink: #080b11;
|
||||
--panel: #10151e;
|
||||
--line: #303b4b;
|
||||
--muted: #aeb9c8;
|
||||
--accent: #9db2c9;
|
||||
--accent-edge: #5b7794;
|
||||
--signal: #89b1ad;
|
||||
--danger: #d99cac;
|
||||
color: var(--text);
|
||||
background: var(--ink);
|
||||
--mono: ui-monospace, SFMono-Regular, Menlo, Consolas, 'Liberation Mono', monospace;
|
||||
--gutter: clamp(16px, 4vw, 56px);
|
||||
}
|
||||
|
||||
*, *::before, *::after { box-sizing: border-box; }
|
||||
body { margin: 0; min-width: 280px; }
|
||||
button, input, textarea, select { font: inherit; }
|
||||
a { color: inherit; }
|
||||
[hidden] { display: none !important; }
|
||||
|
||||
.layout {
|
||||
min-height: 100vh;
|
||||
background:
|
||||
radial-gradient(ellipse at 97% 53%, #32293d49, transparent 42%),
|
||||
radial-gradient(ellipse at 70% 12%, #1b313e65, transparent 45%),
|
||||
linear-gradient(#9db2c909 1px, transparent 1px),
|
||||
linear-gradient(90deg, #9db2c909 1px, transparent 1px),
|
||||
var(--ink);
|
||||
background-size: auto, auto, 44px 44px, 44px 44px, auto;
|
||||
}
|
||||
|
||||
.topbar {
|
||||
position: sticky;
|
||||
top: 0;
|
||||
z-index: 10;
|
||||
border-bottom: 1px solid var(--line);
|
||||
background: #0c1018f5;
|
||||
backdrop-filter: blur(12px);
|
||||
}
|
||||
|
||||
.topbar-inner {
|
||||
max-width: 1440px;
|
||||
min-height: 74px;
|
||||
margin-inline: auto;
|
||||
padding-inline: var(--gutter);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: clamp(16px, 4vw, 54px);
|
||||
}
|
||||
|
||||
.brand {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 11px;
|
||||
color: var(--accent);
|
||||
font: 21px var(--mono);
|
||||
letter-spacing: -.07em;
|
||||
text-decoration: none;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.brand-mark {
|
||||
display: grid;
|
||||
place-items: center;
|
||||
flex: 0 0 auto;
|
||||
width: 25px;
|
||||
height: 25px;
|
||||
background: var(--accent);
|
||||
clip-path: polygon(23% 0, 100% 0, 100% 77%, 77% 100%, 0 100%, 0 23%);
|
||||
}
|
||||
|
||||
.brand-mark::after {
|
||||
content: '';
|
||||
width: 15px;
|
||||
height: 15px;
|
||||
background: var(--ink);
|
||||
clip-path: polygon(30% 0, 100% 0, 100% 29%, 44% 29%, 29% 44%, 29% 71%, 100% 71%, 100% 100%, 0 100%, 0 30%);
|
||||
}
|
||||
|
||||
#nav { display: flex; align-self: stretch; gap: 4px; align-items: stretch; }
|
||||
#nav a {
|
||||
display: grid;
|
||||
align-content: center;
|
||||
padding: 10px 12px;
|
||||
border-block: 2px solid transparent;
|
||||
color: var(--muted);
|
||||
font: 14px var(--mono);
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
#nav a:hover { color: var(--signal); }
|
||||
#nav a.active {
|
||||
color: var(--signal);
|
||||
border-bottom-color: var(--signal);
|
||||
background: #89b1ad12;
|
||||
}
|
||||
|
||||
.account {
|
||||
margin-left: auto;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 13px;
|
||||
color: var(--muted);
|
||||
font: 13px var(--mono);
|
||||
}
|
||||
|
||||
.account span { overflow-wrap: anywhere; min-width: 0; }
|
||||
.account-login { color: var(--signal); font: 14px var(--mono); text-underline-offset: 4px; }
|
||||
|
||||
.workspace {
|
||||
width: min(100%, 1380px);
|
||||
margin: 0 auto;
|
||||
padding: clamp(32px, 5vw, 70px) var(--gutter) 64px;
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 860px) minmax(260px, 360px);
|
||||
gap: clamp(20px, 4vw, 58px);
|
||||
align-items: start;
|
||||
}
|
||||
|
||||
.content { min-width: 0; }
|
||||
.content > .error { margin-bottom: 15px; }
|
||||
.signed-out .workspace {
|
||||
grid-template-columns: minmax(0, 510px) minmax(0, 440px);
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
min-height: calc(100vh - 75px);
|
||||
}
|
||||
|
||||
.circuit {
|
||||
--trace: #89b1ad19;
|
||||
position: sticky;
|
||||
top: 24px;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
aspect-ratio: 4 / 5;
|
||||
overflow: hidden;
|
||||
border: 1px solid #3a555e;
|
||||
background:
|
||||
linear-gradient(135deg, #9db2c90a 0 39%, transparent 39% 75%, #77628418 75%),
|
||||
repeating-linear-gradient(0deg, transparent 0 27px, var(--trace) 28px, transparent 29px),
|
||||
repeating-linear-gradient(90deg, transparent 0 27px, var(--trace) 28px, transparent 29px),
|
||||
radial-gradient(ellipse at 52% 46%, #20343e, #0b111b 68%);
|
||||
clip-path: polygon(0 0, calc(100% - 30px) 0, 100% 30px, 100% 100%, 30px 100%, 0 calc(100% - 30px));
|
||||
isolation: isolate;
|
||||
}
|
||||
|
||||
.circuit::before, .circuit::after {
|
||||
content: '';
|
||||
position: absolute;
|
||||
inset: 14px;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.circuit::before {
|
||||
border: 1px solid #89b1ad36;
|
||||
background:
|
||||
linear-gradient(90deg, var(--signal) 0 27px, transparent 27px) top left,
|
||||
linear-gradient(270deg, var(--accent-edge) 0 32px, transparent 32px) bottom right;
|
||||
background-size: 100% 2px;
|
||||
background-repeat: no-repeat;
|
||||
}
|
||||
|
||||
.circuit::after {
|
||||
inset: 25px;
|
||||
border: 1px dashed #89b1ad2e;
|
||||
}
|
||||
|
||||
.chip {
|
||||
z-index: 1;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
width: 48%;
|
||||
aspect-ratio: 1;
|
||||
transform: rotate(-24deg);
|
||||
border: 1px solid #5d7f86;
|
||||
background: #111923;
|
||||
box-shadow: inset 0 0 25px #89b1ad20, 0 0 45px #89b1ad22, 7px 8px 0 #77628430;
|
||||
}
|
||||
|
||||
.chip::before, .chip::after {
|
||||
content: '';
|
||||
position: absolute;
|
||||
width: 140%;
|
||||
height: 58%;
|
||||
background: repeating-linear-gradient(0deg, var(--signal) 0 1px, transparent 1px 11px);
|
||||
z-index: -1;
|
||||
opacity: .38;
|
||||
}
|
||||
|
||||
.chip::after { transform: rotate(90deg); }
|
||||
.chip span {
|
||||
display: grid;
|
||||
place-items: center;
|
||||
width: 74%;
|
||||
aspect-ratio: 1;
|
||||
border: 1px solid #496d73;
|
||||
background: #121d2a;
|
||||
box-shadow: 0 0 0 4px #0a141e;
|
||||
}
|
||||
|
||||
.chip span::after {
|
||||
content: '';
|
||||
width: 65%;
|
||||
aspect-ratio: 1;
|
||||
background: var(--accent-edge);
|
||||
clip-path: polygon(27% 0, 100% 0, 100% 29%, 40% 29%, 29% 40%, 29% 71%, 100% 71%, 100% 100%, 0 100%, 0 27%);
|
||||
}
|
||||
|
||||
.scanline {
|
||||
position: absolute;
|
||||
z-index: 2;
|
||||
inset: 12% 14px auto;
|
||||
height: 2px;
|
||||
opacity: 0;
|
||||
background: linear-gradient(90deg, transparent, var(--signal), transparent);
|
||||
box-shadow: 0 0 18px #89b1ad47;
|
||||
animation: scan 8s ease-in-out infinite;
|
||||
}
|
||||
|
||||
@keyframes scan {
|
||||
0%, 15% { top: 12%; opacity: 0; }
|
||||
27% { opacity: .4; }
|
||||
65% { opacity: .4; }
|
||||
78%, 100% { top: 87%; opacity: 0; }
|
||||
}
|
||||
|
||||
h1, h2, p, dl { margin: 0; }
|
||||
h1 {
|
||||
font-size: clamp(34px, 4vw, 56px);
|
||||
font-weight: 800;
|
||||
line-height: .98;
|
||||
letter-spacing: -.065em;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
|
||||
h1 span { display: block; color: var(--accent); }
|
||||
h2 { font-size: 20px; font-weight: 800; }
|
||||
.page-header { margin-bottom: 26px; }
|
||||
.welcome { text-align: center; }
|
||||
.page-header-row { display: flex; justify-content: space-between; align-items: end; gap: 24px; }
|
||||
.page-header-row .button-link { flex: 0 0 auto; margin-bottom: 4px; }
|
||||
.intro { color: var(--muted); max-width: 62ch; margin-top: 14px; line-height: 1.6; }
|
||||
.eyebrow {
|
||||
margin-bottom: 11px;
|
||||
color: var(--signal);
|
||||
font: 700 13px/1.4 var(--mono);
|
||||
letter-spacing: .04em;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
.eyebrow a { text-underline-offset: 4px; }
|
||||
.mono { font-family: var(--mono); }
|
||||
.valid { color: var(--signal); }
|
||||
.invalid, .error { color: var(--danger); }
|
||||
.error { overflow-wrap: anywhere; border-left: 2px solid var(--danger); padding-left: 10px; }
|
||||
.muted { color: var(--muted); }
|
||||
|
||||
.panel {
|
||||
position: relative;
|
||||
border: 1px solid var(--line);
|
||||
border-top-color: #435568;
|
||||
padding: clamp(16px, 2.15vw, 29px);
|
||||
background: linear-gradient(135deg, #9db2c908, transparent 55%), var(--panel);
|
||||
box-shadow: 5px 5px 0 #070910;
|
||||
}
|
||||
|
||||
.panel::before {
|
||||
content: '';
|
||||
position: absolute;
|
||||
top: -1px;
|
||||
left: -1px;
|
||||
width: 64px;
|
||||
height: 2px;
|
||||
background: var(--signal);
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.panel::after {
|
||||
content: '';
|
||||
position: absolute;
|
||||
inset: auto -1px -1px auto;
|
||||
width: 45px;
|
||||
height: 11px;
|
||||
background: repeating-linear-gradient(125deg, var(--accent-edge) 0 2px, transparent 2px 6px);
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.panel + .panel { margin-top: 21px; }
|
||||
.record-list { margin-top: 24px; }
|
||||
.record-list { display: grid; gap: 18px; }
|
||||
.record-list .panel + .panel { margin-top: 0; }
|
||||
.certificate-record { padding-top: 2px; }
|
||||
.certificate-record + .certificate-record { padding-top: 22px; border-top: 1px solid var(--line); }
|
||||
.certificate-record > summary { cursor: pointer; }
|
||||
.certificate-record > summary .status { margin-left: 12px; vertical-align: middle; }
|
||||
.certificate-record > .fields { margin-top: 17px; padding-left: 20px; }
|
||||
#holder-error { margin-top: 16px; }
|
||||
.fields { display: grid; gap: 17px; min-width: 0; }
|
||||
.fields > label, .readonly-field { display: grid; gap: 8px; min-width: 0; }
|
||||
.field-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 17px; }
|
||||
.field-grid > label { display: grid; gap: 8px; }
|
||||
label { font-size: 14px; font-weight: 600; }
|
||||
small { color: var(--muted); font: 400 13px/1.45 var(--sans); }
|
||||
.optional { margin-left: 6px; color: var(--muted); font-size: 12px; font-weight: 400; }
|
||||
|
||||
input, textarea, select {
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
background: #0b1019;
|
||||
border: 1px solid var(--line);
|
||||
border-left: 2px solid #486071;
|
||||
border-radius: 0;
|
||||
color: var(--text);
|
||||
padding: 11px 12px;
|
||||
line-height: 1.5;
|
||||
transition: border-color .16s, background-color .16s;
|
||||
}
|
||||
|
||||
input::placeholder, textarea::placeholder { color: #929fb3; }
|
||||
textarea { display: block; resize: vertical; overflow-wrap: anywhere; }
|
||||
textarea.mono, input.mono, select.mono { font-size: 13px; }
|
||||
textarea[readonly] { background: #0f1724; }
|
||||
select {
|
||||
appearance: none;
|
||||
padding-right: 42px;
|
||||
background-image:
|
||||
linear-gradient(45deg, transparent 50%, var(--muted) 50%),
|
||||
linear-gradient(135deg, var(--muted) 50%, transparent 50%);
|
||||
background-position: calc(100% - 18px) 50%, calc(100% - 13px) 50%;
|
||||
background-size: 5px 5px;
|
||||
background-repeat: no-repeat;
|
||||
}
|
||||
input:focus, textarea:focus, select:focus { border-color: var(--signal); background: #101923; }
|
||||
:focus-visible { outline: 2px solid var(--accent); outline-offset: 3px; }
|
||||
|
||||
button, .button-link {
|
||||
position: relative;
|
||||
border: 1px solid var(--accent-edge);
|
||||
border-radius: 0;
|
||||
padding: 10px 15px;
|
||||
font-weight: 800;
|
||||
font-size: 13px;
|
||||
background: #2b4056;
|
||||
color: var(--text);
|
||||
cursor: pointer;
|
||||
transition: color .16s, background-color .16s, box-shadow .16s;
|
||||
}
|
||||
|
||||
button:hover, .button-link:hover { background: #36516b; box-shadow: 3px 3px 0 #151f2b; }
|
||||
button:disabled { opacity: .64; cursor: wait; }
|
||||
button.secondary { background: #121a25; border-color: #486071; color: var(--accent); }
|
||||
button.secondary:hover { background: #1c2a38; box-shadow: none; }
|
||||
.button-link { display: inline-block; text-decoration: none; }
|
||||
.text-link { color: var(--signal); font: 14px var(--mono); text-underline-offset: 4px; }
|
||||
.text-link:hover { color: var(--accent); }
|
||||
|
||||
.actions { display: flex; flex-wrap: wrap; align-items: center; gap: 12px; }
|
||||
.public-actions { display: flex; flex-wrap: wrap; gap: 12px 20px; margin-top: 20px; }
|
||||
.details { display: grid; grid-template-columns: max-content minmax(0, 1fr); gap: 12px 20px; font-size: 14px; }
|
||||
.details dt { color: var(--muted); }
|
||||
.details dd { margin: 0; overflow-wrap: anywhere; }
|
||||
.compact-details { padding-top: 15px; border-top: 1px solid var(--line); }
|
||||
.record-heading, .result-heading {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: start;
|
||||
gap: 18px;
|
||||
}
|
||||
.record-heading p { margin-top: 7px; color: var(--muted); }
|
||||
.status {
|
||||
display: inline-flex;
|
||||
flex: 0 0 auto;
|
||||
align-items: center;
|
||||
min-height: 28px;
|
||||
padding: 4px 9px;
|
||||
border: 1px solid var(--line);
|
||||
font: 700 12px var(--mono);
|
||||
}
|
||||
.status-valid { color: #a9d7d1; border-color: #466d6b; background: #142523; }
|
||||
.status-invalid { color: #efb4c2; border-color: #754553; background: #28181e; }
|
||||
.counter {
|
||||
min-width: 28px;
|
||||
padding: 4px 8px;
|
||||
text-align: center;
|
||||
border: 1px solid var(--line);
|
||||
color: var(--muted);
|
||||
font: 13px var(--mono);
|
||||
}
|
||||
.notice {
|
||||
padding: 12px 14px;
|
||||
border-left: 2px solid var(--accent-edge);
|
||||
background: #172130;
|
||||
color: #cbd6e4;
|
||||
font-size: 14px;
|
||||
line-height: 1.5;
|
||||
}
|
||||
.success-message { color: #b8d8d4; line-height: 1.5; }
|
||||
.empty-state { padding-block: 34px; }
|
||||
.loading { color: var(--muted); }
|
||||
.steps {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(3, minmax(0, 1fr));
|
||||
gap: 1px;
|
||||
margin: 0 0 21px;
|
||||
padding: 1px;
|
||||
list-style-position: inside;
|
||||
background: var(--line);
|
||||
}
|
||||
.steps li { padding: 13px 14px; background: #0d131c; color: var(--muted); font-size: 13px; line-height: 1.45; }
|
||||
|
||||
.issue-dialog {
|
||||
width: min(760px, calc(100vw - 32px));
|
||||
max-width: none;
|
||||
max-height: calc(100vh - 32px);
|
||||
padding: 0;
|
||||
border: 0;
|
||||
color: var(--text);
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
.issue-dialog::backdrop {
|
||||
background: #02050bcc;
|
||||
backdrop-filter: blur(4px);
|
||||
}
|
||||
|
||||
.issue-dialog > .panel {
|
||||
max-height: calc(100vh - 32px);
|
||||
overflow: auto;
|
||||
}
|
||||
|
||||
@media (max-width: 900px) {
|
||||
.topbar-inner { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 0 12px; min-height: 64px; }
|
||||
#nav { grid-row: 2; grid-column: 1 / -1; flex-wrap: wrap; }
|
||||
#nav a { padding-inline: 8px; }
|
||||
.brand, .account { margin-block: 12px; }
|
||||
.workspace, .signed-out .workspace { grid-template-columns: minmax(0, 1fr) minmax(0, .55fr); }
|
||||
.signed-out .workspace { min-height: auto; }
|
||||
.circuit { top: 16px; }
|
||||
}
|
||||
|
||||
@media (max-width: 650px) {
|
||||
.workspace, .signed-out .workspace { position: relative; display: block; isolation: isolate; }
|
||||
.content { position: relative; z-index: 1; }
|
||||
.circuit {
|
||||
width: 125px;
|
||||
position: absolute;
|
||||
top: 14px;
|
||||
right: var(--gutter);
|
||||
opacity: .29;
|
||||
pointer-events: none;
|
||||
mask-image: linear-gradient(225deg, #000, transparent 86%);
|
||||
}
|
||||
.circuit::before, .circuit::after { inset: 7px; }
|
||||
.scanline { display: none; }
|
||||
}
|
||||
|
||||
@media (max-width: 415px) {
|
||||
.brand { min-width: 0; font-size: 17px; gap: 6px; line-height: 1.05; white-space: normal; }
|
||||
.brand-mark { width: 20px; height: 20px; }
|
||||
.brand-mark::after { width: 12px; height: 12px; }
|
||||
.account { max-width: 46vw; gap: 7px; font-size: 12px; }
|
||||
.account button { padding-inline: 9px; }
|
||||
#nav a { font-size: 11px; padding-inline: 6px; }
|
||||
h1 { font-size: clamp(27px, 9vw, 32px); }
|
||||
.details { grid-template-columns: minmax(0, 1fr); gap: 3px; }
|
||||
.details dd + dt { margin-top: 9px; }
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.scanline { animation: none; }
|
||||
input, textarea, select, button { transition: none; }
|
||||
}
|
||||
Executable
+40
@@ -0,0 +1,40 @@
|
||||
const dateFormat = new Intl.DateTimeFormat('ru-RU', {
|
||||
dateStyle: 'medium',
|
||||
timeStyle: 'short',
|
||||
timeZone: 'UTC',
|
||||
});
|
||||
|
||||
export function dateTime(value) {
|
||||
return dateFormat.format(new Date(value)) + ' UTC';
|
||||
}
|
||||
|
||||
export function escapeHtml(value) {
|
||||
if (value === null || value === undefined) {
|
||||
return '';
|
||||
}
|
||||
return String(value).replace(/[&<>"']/g, (character) => ({
|
||||
'&': '&',
|
||||
'<': '<',
|
||||
'>': '>',
|
||||
'"': '"',
|
||||
"'": ''',
|
||||
})[character]);
|
||||
}
|
||||
|
||||
export function setError(element, message) {
|
||||
element.textContent = message;
|
||||
element.hidden = !message;
|
||||
}
|
||||
|
||||
export function readOnlyField(label, value, rows = 3) {
|
||||
return `<label class="readonly-field">${escapeHtml(label)}
|
||||
<textarea class="mono" readonly rows="${rows}">${escapeHtml(value)}</textarea>
|
||||
</label>`;
|
||||
}
|
||||
|
||||
export function showResultDialog(container) {
|
||||
const dialog = container.querySelector('dialog');
|
||||
dialog.querySelector('[data-close-dialog]').addEventListener('click', () => dialog.close());
|
||||
dialog.addEventListener('close', () => dialog.remove(), { once: true });
|
||||
dialog.showModal();
|
||||
}
|
||||
Executable
+31
@@ -0,0 +1,31 @@
|
||||
from gunicorn.app.base import BaseApplication
|
||||
from backend.app.bootstrap.factory import create_app
|
||||
|
||||
|
||||
class LedgerApplication(BaseApplication):
|
||||
def load_config(self):
|
||||
settings = {
|
||||
"bind": "0.0.0.0:8080",
|
||||
"control_socket_disable": True,
|
||||
"workers": 4,
|
||||
"threads": 8,
|
||||
"worker_class": "gthread",
|
||||
"preload_app": True,
|
||||
"timeout": 20,
|
||||
"graceful_timeout": 10,
|
||||
"keepalive": 5,
|
||||
"backlog": 128,
|
||||
"max_requests": 1000,
|
||||
"max_requests_jitter": 100,
|
||||
"accesslog": "-",
|
||||
"errorlog": "-",
|
||||
}
|
||||
for key, value in settings.items():
|
||||
self.cfg.set(key, value)
|
||||
|
||||
def load(self):
|
||||
return create_app()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
LedgerApplication().run()
|
||||
Reference in new issue
Block a user