# luxfi/kms — MPC-backed KMS + secrets UI on Hanzo Base
# Frontend: KMS React SPA
# Backend: Go + sqlcipher + MPC/ZAP

FROM node:22-alpine AS frontend
WORKDIR /src/frontend
COPY frontend/package.json frontend/pnpm-lock.yaml ./
RUN corepack enable pnpm && pnpm install --frozen-lockfile
COPY frontend/ .
RUN pnpm vite build

FROM golang:1.26.4-bookworm AS builder
# Auto-fetch the toolchain pinned in go.mod (avoids synctest panic with stale local toolchain)
ENV GOTOOLCHAIN=auto
RUN apt-get update && apt-get install -y --no-install-recommends \
    libsqlcipher-dev gcc libc6-dev pkg-config git ca-certificates \
    && rm -rf /var/lib/apt/lists/*

ARG GITHUB_TOKEN
RUN git config --global url."https://${GITHUB_TOKEN}@github.com/".insteadOf "https://github.com/"
ENV GOPRIVATE=github.com/luxfi/*,github.com/hanzoai/*

WORKDIR /build
COPY go.mod go.sum ./
RUN go mod download
COPY . .

# Embed the React SPA into the Go binary at the embed.FS path (cmd/kms/web).
# The Makefile `copy-ui` target does this; we replicate it inline so the
# Dockerfile path is independent of `make`. Without this step, registerWebUI
# embeds an empty filesystem and `/` returns 404 even though the SPA is
# bundled at /app/frontend in the runtime layer.
COPY --from=frontend /src/frontend/dist /build/cmd/kms/web

# Per SCALE_STANDARD.md §2 (https://github.com/hanzoai/hips/blob/main/docs/SCALE_STANDARD.md)
# — every Go production Dockerfile that emits JSON to a client builds
# with GOEXPERIMENT=jsonv2. Verified -12% time / -23% allocs on the
# edge POST roundtrip vs encoding/json v1.
ARG GO_EXPERIMENT=jsonv2
ENV GOEXPERIMENT=${GO_EXPERIMENT}

# GOFLAGS=-mod=mod forces Go to fetch from the module cache instead of the
# in-tree vendor/. vendor/ is missing C headers for supranational/blst (.h
# files live in blst's source tree but `go mod vendor` strips them on the
# Go-only files filter). The cache has full module trees, so blst.h is
# resolvable. We do `go mod download` above to prime the cache.
RUN CGO_ENABLED=1 GOFLAGS=-mod=mod go build -tags "sqlite_fts5 sqlcipher" \
    -ldflags="-s -w" -o /usr/local/bin/kms ./cmd/kms

FROM debian:bookworm-slim
RUN apt-get update && apt-get install -y --no-install-recommends \
    libsqlcipher0 ca-certificates curl \
    && rm -rf /var/lib/apt/lists/*

COPY --from=builder /usr/local/bin/kms /usr/local/bin/kms
COPY --from=frontend /src/frontend/dist /app/frontend
RUN mkdir -p /data/kms

ENV KMS_FRONTEND_DIR=/app/frontend
ENV BASE_SKIP_ROOT_REDIRECT=1
ENV BASE_DISABLE_ADMIN_UI=1

EXPOSE 8080
HEALTHCHECK --interval=10s --timeout=3s --retries=3 \
  CMD curl -f http://localhost:8080/healthz || exit 1
ENTRYPOINT ["kms", "serve", "--http=0.0.0.0:8080"]
