Skip to content

Self-improving AI Employees for everyone

2.6 KB
Raw Blame
"""Secret + environment generation for ``company deploy``.

Generates the cryptographic keys + owner password the login gate needs, and
assembles the full env-var map (``app_env``) that Terraform renders into the
VM's brand-specific systemd ``EnvironmentFile``. The map
carries only the deployment overrides + secrets; the VM's ``.env`` (copied
from ``.env.template`` by the package build) supplies the rest of the required
settings, and OS env (the EnvironmentFile) wins over ``.env`` in
pydantic-settings.
"""

from __future__ import annotations

import secrets
import string

_PW_ALPHABET = string.ascii_letters + string.digits


def new_key() -> str:
    """48-char hex secret (>= the 32-char minimum the app enforces)."""
    return secrets.token_hex(24)


def new_password(length: int = 20) -> str:
    """Strong alphanumeric password (avoids shell/systemd-quoting pitfalls)."""
    return "".join(secrets.choice(_PW_ALPHABET) for _ in range(length))


def build_app_env(
    *,
    owner_email: str,
    owner_password: str,
    port: int,
    data_dir: str = "/var/lib/opencompany",
) -> dict[str, str]:
    """The systemd EnvironmentFile map: gate overrides + freshly minted secrets.

    JWT/SECRET/ENCRYPTION keys are generated per deploy. ``JWT_COOKIE_SECURE``
    is ``false`` because the VM is reached over plain HTTP on its IP; flip to
    true once a domain + TLS terminator is in front. Temporal, the event
    framework and ``HOST`` keep their ``.env.template`` values, as in the
    Docker image: chat, triggers and cron need Temporal, and its workers reach
    the backend at ``ws://HOST:PORT/ws/internal`` (``company serve`` binds
    every interface itself).
    """
    return {
        "PORT": str(port),
        "DATA_DIR": data_dir,
        "WORKSPACE_BASE_DIR": "workspaces",
        "SERVE_STATIC_CLIENT": "true",
        "VITE_AUTH_ENABLED": "true",
        "DEPLOYMENT_MODE": "cloud",
        "AUTH_MODE": "single",
        "JWT_COOKIE_SECURE": "false",
        "JWT_COOKIE_SAMESITE": "lax",
        "REDIS_ENABLED": "false",
        "LOG_FORMAT": "text",
        "JWT_SECRET_KEY": new_key(),
        "SECRET_KEY": new_key(),
        "API_KEY_ENCRYPTION_KEY": new_key(),
        "OPENCOMPANY_OWNER_EMAIL": owner_email,
        "OPENCOMPANY_OWNER_NAME": "Owner",
        "OPENCOMPANY_OWNER_PASSWORD": owner_password,
        # Compatibility for servers deployed before the rebrand. Remove only
        # after the legacy settings aliases have completed their deprecation.
        "MACHINA_OWNER_EMAIL": owner_email,
        "MACHINA_OWNER_NAME": "Owner",
        "MACHINA_OWNER_PASSWORD": owner_password,
    }