kimi-code/flake.nix
Haozhe 60dfb68a2d
feat(server): add bearer-token auth and safe host exposure (#1006)
* test(server): add API surface snapshot guardrail

Boot startServer on port 0 and snapshot the documented v1 route table derived from /openapi.json paths, plus the reachability of doc/meta endpoints (/healthz, /openapi.json, /asyncapi.json, /). Gives later auth/--host phases an intentional diff when routes change. M0 makes no production behavior change.

* test(server): add e2e server harness with token support

Add test/helpers/serverHarness.ts: boot() wraps startServer with an isolated lock + home dir and returns a handle (server, address, baseUrl, wsUrl, token, close) plus authedFetch/authedWs that carry Authorization: Bearer <token> (and the kimi-code.bearer.<token> WS subprotocol). serviceOverrides is the generic DI seam later phases use to inject a fixed-token auth service; IAuthTokenService is not referenced yet. closeAll() tears down every booted server and socket. M0 makes no production behavior change; typecheck-only gate.

* feat(server): add privateFiles 0600 atomic write/read utility

* feat(server): add per-start tokenStore

* feat(server): add env-based bcrypt password hash utility

* feat(server): add IAuthTokenService DI seam

* feat(server): add global onRequest auth hook with bypass + redaction

* fix(server): stop reflecting Host header in /asyncapi.json

* feat(server): add WS bearer subprotocol constant and parser

* feat(server): enforce bearer token auth on WS upgrade

* feat(server): add Host header allowlist middleware

* feat(server): add Origin/CORS middleware

* feat(server): wire Host/Origin checks into HTTP and WS

* feat(server): wire token auth, Host/Origin, and WS auth into start.ts

* fix(server): create lock file with 0600 permissions

* fix(server): suppress debug routes on non-loopback binds

* feat(kimi-code): read server token and send Authorization on CLI calls

* feat(kimi-code): inject server token into /web URL fragment

* feat(server): add bindClassify for loopback/lan/public classification

* feat(kimi-code): register --host flag and pass it through the daemon

* feat(server): require password and TLS opt-out on non-loopback binds

* feat(server): rate-limit repeated auth failures on non-loopback binds

* feat(server): disable shutdown and terminals on public binds by default

* feat(server): add security response headers on non-loopback binds

* test(server): cover LAN/public host-exposure hardening end to end

* docs(server): add deployment security and threat-model guide

* changeset: minor kimi-code for server auth and host exposure

* feat(kimi-web): add server bearer-token auth support

* fix: repair CI for server auth and host exposure

- Replace native @node-rs/bcrypt with pure-JS bcryptjs so the ESM CLI
  bundle and the SEA native bundle both build without native-addon
  require issues (node-rs/bcrypt broke the ESM smoke and the SEA
  check-bundle allowlist).
- Remove dead cleanup references (stopSpinner, authLogoBlinkTimer) in
  apps/kimi-web App.vue that failed vue-tsc.
- Fix lint: drop empty spread fallbacks in the e2e auth-header merge,
  void the intentionally-async WS upgrade listener, add missing
  assertions to satisfy jest/expect-expect, and convert a ternary
  statement to if/else.
- Send the bearer token in the snapshot perf/smoke tests so they pass
  under the new global auth hook.
- Refresh the pnpmDeps hash in flake.nix for the updated lockfile.

* feat(server): persist bearer token and add rotate-token command

- persist the server bearer token in <home>/server.token (0600) and reuse it across restarts instead of per-start server-<pid>.token
- add `kimi server rotate-token` to regenerate the token; the token store reloads on mtime/inode change so rotation applies without restart
- print the token and Vite-style Local/Network URLs in the startup banner
- allow non-loopback binds with bearer-token-only auth (password now optional) and update SECURITY.md
- surface daemon boot failures immediately with the exit reason and log tail instead of waiting for the spawn timeout

* feat(server): print full token URLs and re-print links after rotate

- Drop the ready-panel border so token URLs print in full for copying; keep the Kimi sprite beside the title.
- Re-print Local/Network access links after `server rotate-token` (host/port from the lock).
- Extract shared access-URL helpers into access-urls.ts.
- Unify link and token colors between the banner and rotate-token.

* feat(server): dim URL #token= fragment and de-highlight token

- Render the `#token=…` fragment in a dim gray so the host/port stands out in the banner and rotate-token links.
- De-highlight the standalone token; set it off with surrounding whitespace instead of color.
- Add splitTokenFragment helper.

* refactor(cli): polish server ready banner and rotate-token output

- move version onto the ready banner title line; drop the separate
  Ready:/Version: rows and the startup-time metric
- reorder rotate-token output so the new token sits between the
  invalidation note and the access links
- update server CLI tests for the new layout

* feat(server): warn on reuse and refine ready banner

- Warn when `server run` reuses an already-running daemon (its options are not applied) and show the running server's actual URLs.
- Show a `Network: off  use --host 0.0.0.0 to enable` hint on loopback binds.
- Move the version onto the title line and drop the startup-time metric.

* fix(web): relabel auth dialog to token and cover full page

- Relabel the server auth dialog from "password" to "token"; the server accepts the bearer token, with the password only as a fallback.
- Make the auth dialog overlay fully opaque so it covers the whole page instead of revealing the login page underneath.

* fix: resolve CI failures on web auth PR

- Replace chalk.yellow named color with chalk.hex(darkColors.warning)
  in the server reuse notice to satisfy the chalk named color guard.
- Update pnpmDeps hash in flake.nix to match the regenerated
  pnpm-lock.yaml so the Nix build succeeds.
- Retry rmSync in ws-broadcast e2e teardown to ride out EBUSY /
  ENOTEMPTY races while the server flushes files after close().

* test(server): update API surface snapshot for warnings route

The feat/web-auth branch adds GET /api/v1/sessions/{session_id}/warnings
(packages/server/src/routes/sessions.ts), so the API surface guardrail
snapshot needs to record the new documented v1 route.
2026-06-25 17:57:56 +08:00

253 lines
8.2 KiB
Nix

{
description = "Kimi Code CLI";
inputs = {
# Pinned to the 25.11 release channel because nixpkgs-unstable currently
# ships nodejs_24 = 24.14.1, which trips the >= 24.15.0 floor that the
# native SEA build enforces (see apps/kimi-code/scripts/native/build.mjs).
nixpkgs.url = "github:NixOS/nixpkgs/nixos-25.11";
};
outputs =
{ self, nixpkgs }:
let
lib = nixpkgs.lib;
systems = [
"x86_64-linux"
"aarch64-linux"
"x86_64-darwin"
"aarch64-darwin"
];
forAllSystems =
f:
lib.genAttrs systems (
system:
f (import nixpkgs {
inherit system;
})
);
minNodeVersion = "24.15.0";
# Hardcode to Node.js 24.x; fail the evaluation if the pinned nixpkgs
# does not offer a new enough 24.x.
nodejsFor =
pkgs:
let
node = pkgs.nodejs_24;
in
if lib.versionAtLeast node.version minNodeVersion then
node
else
throw ''
Kimi Code requires Node.js >= ${minNodeVersion},
but nixpkgs only offers ${node.version}.
Pin a newer nixpkgs revision or update minNodeVersion in flake.nix.
'';
pnpmFor =
pkgs:
pkgs.pnpm_10.override {
nodejs = nodejsFor pkgs;
};
# -------------------------------------------------------------------
# Workspace members (kept in sync with pnpm-workspace.yaml).
#
# HARD REQUIREMENT: whenever you add or remove a workspace package,
# you MUST update both lists below. Missing a path will break the Nix
# build (src fileset silently drops files); missing a name will break
# pnpmConfigHook (dependencies for that workspace won't be fetched).
# -------------------------------------------------------------------
workspacePaths = [
./packages/acp-adapter
./packages/agent-core
./packages/server
./packages/server-e2e
./packages/kaos
./packages/kimi-migration-legacy
./packages/kosong
./packages/migration-legacy
./packages/node-sdk
./packages/oauth
./packages/protocol
./packages/telemetry
./apps/kimi-code
./apps/kimi-web
./apps/vis
./apps/vis/server
./apps/vis/web
./docs
];
workspaceNames = [
"@moonshot-ai/acp-adapter"
"@moonshot-ai/agent-core"
"@moonshot-ai/server"
"@moonshot-ai/server-e2e"
"@moonshot-ai/kaos"
"@moonshot-ai/kosong"
"@moonshot-ai/migration-legacy"
"@moonshot-ai/kimi-code-sdk"
"@moonshot-ai/kimi-code-oauth"
"@moonshot-ai/protocol"
"@moonshot-ai/kimi-telemetry"
"@moonshot-ai/kimi-code"
"@moonshot-ai/kimi-web"
"@moonshot-ai/vis"
"@moonshot-ai/vis-server"
"@moonshot-ai/vis-web"
"kimi-code-docs"
"kimi-migration-legacy"
];
in
{
packages = forAllSystems (
pkgs:
let
nodejs = nodejsFor pkgs;
pnpm = pnpmFor pkgs;
appPackageJson = builtins.fromJSON (builtins.readFile ./apps/kimi-code/package.json);
nativeTarget =
if pkgs.stdenv.hostPlatform.isLinux && pkgs.stdenv.hostPlatform.isAarch64 then
"linux-arm64"
else if pkgs.stdenv.hostPlatform.isLinux then
"linux-x64"
else if pkgs.stdenv.hostPlatform.isDarwin && pkgs.stdenv.hostPlatform.isAarch64 then
"darwin-arm64"
else if pkgs.stdenv.hostPlatform.isDarwin then
"darwin-x64"
else
throw "Unsupported Kimi Code native target for ${pkgs.stdenv.hostPlatform.system}";
kimi-code = pkgs.stdenv.mkDerivation (finalAttrs: {
pname = "kimi-code";
version = appPackageJson.version;
src = lib.fileset.toSource {
root = ./.;
fileset = lib.fileset.unions (
[
./build
./.npmrc
./.nvmrc
./package.json
./pnpm-lock.yaml
./pnpm-workspace.yaml
./tsconfig.json
./vitest.config.ts
./LICENSE
]
++ workspacePaths
);
};
pnpmWorkspaces = [ "." ] ++ workspaceNames;
pnpmDeps = pkgs.fetchPnpmDeps {
inherit (finalAttrs) pname version src pnpmWorkspaces;
inherit pnpm;
fetcherVersion = 3;
hash = "sha256-O9xDt/5bCakst2mKTyki3oyUph1g+CuH/BIqA/4fgYE=";
};
nativeBuildInputs = [
nodejs
pnpm
(pkgs.pnpmConfigHook.override { inherit pnpm; })
pkgs.makeWrapper
]
# The SEA inject step (postject) invalidates the macOS code
# signature on the copied Node executable; build.mjs then re-applies
# an ad-hoc signature via `codesign`. The Nix darwin sandbox does
# not expose /usr/bin/codesign, so we supply nixpkgs' ad-hoc-only
# replacement instead.
++ lib.optionals pkgs.stdenv.hostPlatform.isDarwin [
pkgs.darwin.sigtool
];
# The SEA binary is produced by `postject`-injecting a blob into a
# plain Node executable. Stripping rewrites section tables and can
# invalidate the injected blob's offsets, so leave the binary
# untouched after the build.
dontStrip = true;
buildPhase = ''
runHook preBuild
export KIMI_CODE_BUILD_TARGET=${nativeTarget}
${lib.optionalString pkgs.stdenv.hostPlatform.isDarwin ''
# pkgs.darwin.sigtool's codesign supports `--sign -` (ad-hoc)
# but not the inspection mode (`-dv`) that 05-verify.mjs runs
# afterwards. Disable the verify step for the Nix build; the
# release CI keeps it via the unmodified script.
substituteInPlace apps/kimi-code/scripts/native/build.mjs \
--replace-fail \
"await runVerifyStep({ requireGatekeeper: false });" \
"// runVerifyStep skipped in nix sandbox (sigtool lacks -dv)"
''}
# The SEA blob step (scripts/native/02-sea-blob.mjs) embeds the
# Kimi web assets from apps/kimi-code/dist-web and fails if that
# directory is missing. Build the web app and stage its assets
# before producing the native executable.
pnpm --filter=@moonshot-ai/kimi-web run build
node apps/kimi-code/scripts/copy-web-assets.mjs
pnpm --filter=@moonshot-ai/kimi-code run build:native:sea
runHook postBuild
'';
installPhase = ''
runHook preInstall
install -Dm755 \
"apps/kimi-code/dist-native/bin/${nativeTarget}/kimi" \
"$out/bin/kimi"
runHook postInstall
'';
postInstall = ''
wrapProgram $out/bin/kimi --prefix PATH : ${lib.makeBinPath [ pkgs.ripgrep pkgs.fd ]}
'';
meta = {
description = "Kimi Code CLI";
homepage = "https://github.com/MoonshotAI/kimi-code";
license = lib.licenses.mit;
mainProgram = "kimi";
platforms = systems;
};
});
in
{
inherit kimi-code;
default = kimi-code;
}
);
apps = forAllSystems (pkgs: {
kimi-code = {
type = "app";
program = "${self.packages.${pkgs.system}.kimi-code}/bin/kimi";
};
default = self.apps.${pkgs.system}.kimi-code;
});
devShells = forAllSystems (pkgs: {
default =
let
nodejs = nodejsFor pkgs;
pnpm = pnpmFor pkgs;
in
pkgs.mkShell {
packages = [
nodejs
pnpm
pkgs.ripgrep
pkgs.fd
];
};
});
};
}