Files
PaperClipAI/server/src/__tests__/health.test.ts
T
DottaandPaperclip 57bd302c81 feat(antigravity): add hosted Google loopback-relay sign-in (#22932)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Google Antigravity supports Google account sign-in through Paperclip
Runner's pinned, isolated `agy_acp_server.par` process.
> - On `authenticated + public` deployments (including hosted Cloud
instances), `supportsLocalAiLogin` returns `false`, and the user's
browser cannot directly reach the server's `127.0.0.1:<ephemeral_port>`
loopback callback listener.
> - Because `client_secret` lives only inside `agy_acp_server.par` and
uses PKCE with a one-shot `127.0.0.1` listener, hosted deployments need
an authenticated relay path instead of an anonymous callback route or
extracted secret.
> - This pull request adds an authenticated loopback-relay flow across
Runner, server policy/routes/redaction, and the UI so users on hosted
deployments can sign in with Google, copy the `127.0.0.1` redirect URL
from their address bar, and paste it to complete authentication.
> - The benefit is that Google Antigravity subscription sign-in works on
hosted public deployments while keeping Claude, OpenAI, and Grok
server-host login disabled and preventing SSRF, secret leakage, or
cross-tenant access.

## Linked Issues or Issue Description

Refs #22923

**Subsystem affected**
Cross-cutting (packages/paperclip-runner, packages/shared, server/, ui/)

**Problem or motivation**
Google Antigravity sign-in launches Paperclip's pinned, isolated
`agy_acp_server.par` closure, which opens a one-shot
`127.0.0.1:<ephemeral_port>` OAuth callback listener. On hosted
`authenticated + public` deployments, server-host login routes are
blocked and the user's browser cannot connect to the server's loopback
interface, so users cannot sign in with a Google account on Cloud or
remote instances.

**Proposed solution**
Add an authenticated loopback-relay flow:
1. Runner exposes a single-use `submitRedirect(rawRedirectUrl)` handler
on `AntigravityBrowserLoginState` that validates the pasted URL (length,
printable ASCII, `http://127.0.0.1:<expectedPort>/`, no
credentials/hash, no duplicate `state`/`code`, no `error` param,
`timingSafeEqual` state check, bounded 5-attempt bad-paste cap, SHA-256
reused-code tracking) and issues an SSRF-proof reconstructed `GET` to
`expectedRedirect.origin` with `redirect: "manual"`.
2. Server adds `supportsHostedGoogleAiLogin` (exposed on `/api/health`
as `hostedGoogleAiLoginSupported`), permits Google through the
authenticated `/api/companies/:companyId/ai-connections/local/*` routes
while keeping `anthropic`/`openai`/`xai` blocked on public deployments,
accepts up to 4096-character redirect URLs on `/code` while preserving
Claude's 512-byte limit, runs the loopback relay outside DB
transactions, falls back cleanly when a stack has no active `local`
environment row, and redacts `browserCode`/`redirectUrl` and marks
`/code` secret-sensitive.
3. UI enables Google sign-in for `antigravity_runtime` on non-local
environments when `hostedGoogleAiLoginSupported` is true, renders the
external Google sign-in link plus plain-language `127.0.0.1` copy/paste
instructions with analytics masking/no-capture markers, and triggers an
immediate status check after submission.

**Alternatives considered**
- Adding an anonymous public OAuth callback route on the server:
rejected because it widens the unauthenticated attack surface and cannot
change the loopback `redirect_uri` bound inside `agy_acp_server.par`.
- Extracting Google OAuth `client_secret` out of `agy_acp_server.par`:
rejected by policy; secrets remain owned solely inside the pinned
closure.

## What Changed

- `packages/paperclip-runner/src/drivers/acpx/antigravity-auth.ts` &
`packages/paperclip-runner/src/index.ts` &
`server/src/vendor/paperclip-runner/index.ts`: add single-use
`submitRedirect` on `AntigravityBrowserLoginState` with strict
validation, `timingSafeEqual` state verification, 5-attempt cap, bounded
SHA-256 reused-code set, and SSRF-proof loopback relay.
- `packages/shared/src/ai-connections.ts`: add
`LOCAL_AI_LOGIN_CODE_MAX_LENGTH` (4096), `localAiLoginCodeSchema`, and
`submitLocalAiLoginCodeSchema` while preserving Claude's 512-byte
`BROWSER_CODE_MAX_LENGTH` and `browserCodeSchema`.
- `server/src/services/local-ai-login-policy.ts` &
`server/src/routes/health.ts`: add `supportsHostedGoogleAiLogin` and
expose `hostedGoogleAiLoginSupported` on `/api/health`.
- `server/src/services/local-ai-browser-login.ts`,
`server/src/services/local-ai-login.ts`,
`server/src/routes/ai-connections.ts`: permit hosted Google sign-in on
authenticated public deployments while keeping Claude/OpenAI/Grok
blocked; enforce `Cache-Control: no-store`, owner/company/active/expiry
checks, and Claude's 512-byte cap; run Google `submitRedirect` outside
any DB transaction; fall back cleanly to an active environment or
savepoint-wrapped `ensureLocalEnvironment` when no active `local`
environment row exists.
- `server/src/middleware/redact-sensitive.ts`,
`server/src/middleware/http-log-redaction.ts`,
`server/src/middleware/http-log-policy.ts`: redact
`browserCode`/`redirectUrl`/`redirect_url` unconditionally and classify
`/api/companies/:companyId/ai-connections/local/attempts/:sessionId/code`
as secret-sensitive (`local_ai_login_code`).
- `ui/src/api/health.ts`,
`ui/src/components/ai-connections/useLocalAiLogin.ts`,
`ui/src/components/AdapterLoginChrome.tsx`,
`ui/src/components/new-agent/AgentProviderConnection.tsx`,
`ui/src/components/ai-connections/AiConnectionCredentialStep.tsx`,
`ui/src/components/OnboardingWizard.tsx`: enable hosted Google sign-in
for `antigravity_runtime` on hosted/non-local environments, render the
hosted `127.0.0.1` redirect paste flow with `ANALYTICS_MASK_CLASS` and
`ANALYTICS_NO_CAPTURE_CLASS`, preserve retryable paste errors inline,
and trigger immediate status re-check on submit.
- `tests/runner-e2e/source-sdk-public-inputs.json`: refreshed for the
updated `packages/shared/src/ai-connections.ts` schema.
- Unit, integration, and UI tests across `antigravity-auth.test.ts`,
`local-ai-login-policy.test.ts`, `health.test.ts`,
`health-dev-server-token.test.ts`, `redact-sensitive.test.ts`,
`http-log-policy.test.ts`, `antigravity-local-ai-login.test.ts`,
`ai-connections.test.ts`, `AdapterLoginChrome.test.tsx`,
`useLocalAiLogin.test.tsx`, and `AgentProviderConnection.test.tsx`.

## Verification

- `pnpm --filter @paperclipai/shared build && pnpm --filter
@paperclipai/shared typecheck && pnpm --filter
@paperclipai/paperclip-runner typecheck && pnpm --filter
@paperclipai/server typecheck && pnpm --filter @paperclipai/ui
typecheck` — passed.
- `pnpm --filter @paperclipai/shared exec vitest run
src/validators/claude-setup-token-session.test.ts` — 15/15 passed.
- `pnpm --filter @paperclipai/paperclip-runner exec vitest run
src/drivers/acpx/antigravity-auth.test.ts
src/drivers/acpx/antigravity-auth-stream-order.test.ts` — 33/33 passed
(including real `127.0.0.1` loopback HTTP relay with fake ACP peer,
bad-paste cap, reused-code rejection, single-use, and non-200 failure).
- `pnpm --filter @paperclipai/server exec vitest run
src/__tests__/local-ai-login-policy.test.ts src/__tests__/health.test.ts
src/__tests__/health-dev-server-token.test.ts
src/__tests__/redact-sensitive.test.ts
src/__tests__/http-log-policy.test.ts
src/__tests__/antigravity-local-ai-login.test.ts` — all passed.
- `pnpm --filter @paperclipai/server exec vitest run
src/__tests__/ai-connections.test.ts` — 167/167 passed against embedded
PostgreSQL (including hosted Google end-to-end route test, redaction of
activity and HTTP logs, and continued blocking of Anthropic/OpenAI/xAI
on hosted public deployments).
- `pnpm --filter @paperclipai/ui exec vitest run
src/components/AdapterLoginChrome.test.tsx
src/components/ai-connections/useLocalAiLogin.test.tsx
src/components/new-agent/AgentProviderConnection.test.tsx` — 30/30
passed.
- `pnpm verify --explain` returned exit 2
(`tests/runner-e2e/source-sdk-public-inputs.json` broad input); required
CI supplies full-repo coverage.
- Note: live end-to-end sign-in against real `agy_acp_server.par` and
Google OAuth on a live Cloud stack was not run in this unit/integration
environment and remains a live-staging verification step.

## Risks

- Low-to-moderate risk. All hosted Google sign-in endpoints stay
authenticated, company-scoped, owner-bound, and `Cache-Control:
no-store`; `localAiLoginSupported` remains `false` on `authenticated +
public` deployments so Claude, OpenAI, and Grok server-host login stay
blocked.
- Loopback relay runs strictly against the validated
`127.0.0.1:<ephemeral_port>` origin printed by `agy_acp_server.par` with
`redirect: "manual"` and a 5-second timeout, outside any database
transaction.
- No database migrations are required.

## Model Used

- Google Gemini (Antigravity agent with tool use and code execution)

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [x] All Paperclip CI gates are green
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-11-25 07:36:36 -06:00

627 lines
21 KiB
TypeScript

import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import express from "express";
import request from "supertest";
import type { Db } from "@paperclipai/db";
import { healthRoutes } from "../routes/health.js";
import * as devServerStatus from "../dev-server-status.js";
import { serverVersion } from "../version.js";
const mockReadPersistedDevServerStatus = vi.hoisted(() => vi.fn());
const testServerInfo = {
processStartedAt: "2026-06-26T00:00:00.000Z",
git: {
available: true,
fullSha: "0123456789abcdef0123456789abcdef01234567",
shortSha: "0123456",
branchName: "master",
subject: "Add server info debug view",
committedAt: "2026-06-25T23:00:00.000Z",
localChanges: {
available: true,
hasLocalChanges: false,
stagedFileCount: 0,
unstagedFileCount: 0,
untrackedFileCount: 0,
},
},
} as const;
function createHealthyDb(): Db {
return {
execute: vi.fn().mockResolvedValue([{ "?column?": 1 }]),
} as unknown as Db;
}
vi.mock("../dev-server-status.js", () => ({
readPersistedDevServerStatus: mockReadPersistedDevServerStatus,
toDevServerHealthStatus: vi.fn(),
}));
function createApp(
db?: Db,
serverInfo: NonNullable<Parameters<typeof healthRoutes>[1]>["serverInfo"] = testServerInfo,
databaseBackupHealth?: NonNullable<Parameters<typeof healthRoutes>[1]>["databaseBackupHealth"],
runtimeEnv?: NonNullable<Parameters<typeof healthRoutes>[1]>["runtimeEnv"],
) {
const app = express();
app.use(
"/health",
healthRoutes(db, {
deploymentMode: "local_trusted",
deploymentExposure: "private",
authReady: true,
companyDeletionEnabled: true,
serverInfo,
databaseBackupHealth,
runtimeEnv,
}),
);
return app;
}
describe("GET /health", () => {
beforeEach(() => {
vi.clearAllMocks();
mockReadPersistedDevServerStatus.mockReturnValue(undefined);
});
afterEach(() => {
vi.restoreAllMocks();
vi.unstubAllEnvs();
});
it("returns 200 with status ok", async () => {
const app = createApp();
const res = await request(app).get("/health");
expect(res.status).toBe(200);
expect(res.body).toEqual({ status: "ok", version: serverVersion, serverVersion: serverVersion, commit: testServerInfo.git.fullSha, serverInfo: testServerInfo });
}, 15_000);
it("keeps the self-hosted health response byte-identical and omits cloud", async () => {
const app = createApp(undefined, testServerInfo, undefined, {});
const res = await request(app).get("/health");
const baseline = {
status: "ok",
version: serverVersion,
serverVersion,
commit: testServerInfo.git.fullSha,
serverInfo: testServerInfo,
};
expect(res.text).toBe(JSON.stringify(baseline));
expect(Object.prototype.hasOwnProperty.call(res.body, "cloud")).toBe(false);
});
it("exposes public stack metadata on cloud-simulated health", async () => {
const app = createApp(undefined, testServerInfo, undefined, {
PAPERCLIP_CLOUD_TENANT_SERVER_TOKEN: "tenant-token",
PAPERCLIP_CLOUD_STACK_ID: "stack-1",
PAPERCLIP_STACK_SLUG: "acme",
PAPERCLIP_CLOUD_ACCOUNT_GROUP_ID: "account-group-1",
PAPERCLIP_PRIMARY_HOST: "acme.paperclip.app",
PAPERCLIP_CLOUD_API_ORIGIN: "https://app.paperclip.app",
});
const res = await request(app).get("/health");
expect(res.status).toBe(200);
expect(res.body.cloud).toEqual({
managed: true,
managedBy: "paperclip-cloud",
stackSlug: "acme",
cloudBaseUrl: "https://app.paperclip.app",
});
});
it("publishes deployment harness policy and reflects configuration updates", async () => {
const env = {
PAPERCLIP_CLOUD_TENANT_SERVER_TOKEN: "tenant-token",
PAPERCLIP_PRIMARY_HOST: "example.paperclip.app",
PAPERCLIP_AVAILABLE_HARNESSES: '["gemini_local","plugin:example"]',
};
const app = createApp(undefined, testServerInfo, undefined, env);
expect((await request(app).get("/health")).body.cloud.availableHarnesses).toEqual(["gemini_local", "plugin:example"]);
env.PAPERCLIP_AVAILABLE_HARNESSES = "[]";
expect((await request(app).get("/health")).body.cloud.availableHarnesses).toEqual([]);
env.PAPERCLIP_AVAILABLE_HARNESSES = "invalid";
expect((await request(app).get("/health")).body.cloud.availableHarnesses).toEqual([]);
});
it("lists operator-hidden settings and drops unknown keys", async () => {
const app = createApp(undefined, testServerInfo, undefined, {
PAPERCLIP_HIDDEN_SETTINGS: "instance.plugins,instance.adapters,instance.bogus",
});
const res = await request(app).get("/health");
expect(res.status).toBe(200);
expect(res.body.hiddenSettings).toEqual(["instance.plugins", "instance.adapters"]);
});
it("omits hiddenSettings entirely when nothing is hidden", async () => {
const app = createApp(undefined, testServerInfo, undefined, {});
const res = await request(app).get("/health");
expect(res.status).toBe(200);
expect(Object.prototype.hasOwnProperty.call(res.body, "hiddenSettings")).toBe(false);
});
it("reveals staging experiments while retaining other Cloud settings restrictions", async () => {
const env = {
PAPERCLIP_CLOUD_TENANT_SERVER_TOKEN: "tenant-token",
PAPERCLIP_PRIMARY_HOST: "team.paperclip.app",
PAPERCLIP_HIDDEN_SETTINGS: "instance.plugins,instance.experimental,instance.experimental.*",
};
const app = createApp(undefined, testServerInfo, undefined, env);
const production = await request(app).get("/health");
expect(production.body.hiddenSettings).toContain("instance.experimental");
expect(production.body.hiddenSettings).toContain("instance.experimental.enableChatConnectors");
env.PAPERCLIP_PRIMARY_HOST = "team.staging.paperclip.app";
const staging = await request(app).get("/health");
expect(staging.body.hiddenSettings).toContain("instance.plugins");
expect(staging.body.hiddenSettings).toContain("instance.experimental.enableManagedSandboxOnly");
expect(staging.body.hiddenSettings).toContain("instance.experimental.enableOwnerInstanceAdmin");
expect(staging.body.hiddenSettings).not.toContain("instance.experimental");
expect(staging.body.hiddenSettings).not.toContain("instance.experimental.enableChatConnectors");
env.PAPERCLIP_PRIMARY_HOST = "team.paperclip.app";
expect((await request(app).get("/health")).body.hiddenSettings).toEqual(production.body.hiddenSettings);
});
it("publishes concrete wildcard restrictions to the UI and refreshes changed exceptions", async () => {
const env = { PAPERCLIP_HIDDEN_SETTINGS: "instance.plugins,instance.experimental.*,!instance.experimental.enableEnvironments" };
const app = createApp(undefined, testServerInfo, undefined, env);
const first = await request(app).get("/health");
expect(first.status).toBe(200);
expect(first.body.hiddenSettings).toContain("instance.plugins");
expect(first.body.hiddenSettings).toContain("instance.experimental.enableMemoryConnectors");
expect(first.body.hiddenSettings).not.toContain("instance.experimental.enableEnvironments");
expect(first.body.hiddenSettings.some((key: string) => key.includes("*") || key.startsWith("!"))).toBe(false);
env.PAPERCLIP_HIDDEN_SETTINGS = "instance.experimental.*,!instance.experimental.enableMemoryConnectors";
const second = await request(app).get("/health");
expect(second.body.hiddenSettings).toContain("instance.experimental.enableEnvironments");
expect(second.body.hiddenSettings).not.toContain("instance.experimental.enableMemoryConnectors");
});
it("returns 200 when the database probe succeeds", async () => {
const db = {
execute: vi.fn().mockResolvedValue([{ "?column?": 1 }]),
} as unknown as Db;
const app = createApp(db);
const res = await request(app).get("/health");
expect(res.status).toBe(200);
expect(db.execute).toHaveBeenCalledTimes(1);
expect(res.body).toMatchObject({
status: "ok",
version: serverVersion,
serverInfo: testServerInfo,
});
});
it("returns 503 when the database probe fails", async () => {
const db = {
execute: vi.fn().mockRejectedValue(new Error("connect ECONNREFUSED")),
} as unknown as Db;
const app = createApp(db);
const res = await request(app).get("/health");
expect(res.status).toBe(503);
expect(res.body).toEqual({
status: "unhealthy",
version: serverVersion,
serverVersion,
commit: testServerInfo.git.fullSha,
error: "database_unreachable",
serverInfo: testServerInfo,
});
});
it("returns safe server info fallbacks when git metadata is unavailable", async () => {
const app = createApp(undefined, {
processStartedAt: "2026-06-26T00:00:00.000Z",
git: {
available: false,
unavailableReason: "git_unavailable",
},
});
const res = await request(app).get("/health");
expect(res.status).toBe(200);
expect(res.body.serverInfo).toEqual({
processStartedAt: "2026-06-26T00:00:00.000Z",
git: {
available: false,
unavailableReason: "git_unavailable",
},
});
// With no git metadata baked in, the exposed commit is null (not omitted).
expect(res.body.commit).toBeNull();
});
it("surfaces a stale database backup warning in full health details", async () => {
const backupDir = fs.mkdtempSync(path.join(os.tmpdir(), "paperclip-health-backups-"));
const backupFile = path.join(backupDir, "paperclip-20260705-031702.sql.gz");
fs.writeFileSync(backupFile, "backup");
fs.utimesSync(
backupFile,
new Date("2026-07-05T03:17:02.000Z"),
new Date("2026-07-05T03:17:02.000Z"),
);
const app = createApp(createHealthyDb(), testServerInfo, {
enabled: true,
backupDir,
maxAgeHours: 26,
now: new Date("2026-07-06T13:00:00.000Z"),
});
const res = await request(app).get("/health");
expect(res.status).toBe(200);
expect(res.body.databaseBackup).toMatchObject({
status: "warning",
backupDir,
maxAgeHours: 26,
latestBackup: {
name: "paperclip-20260705-031702.sql.gz",
ageHours: 33.7,
},
warnings: [
{
code: "database_backup_stale",
},
],
});
expect(res.body.warnings).toEqual(res.body.databaseBackup.warnings);
});
it("surfaces database backup failure markers in full health details", async () => {
const backupDir = fs.mkdtempSync(path.join(os.tmpdir(), "paperclip-health-backups-"));
const backupFile = path.join(backupDir, "paperclip-20260706-031702.sql.gz");
const alertFile = path.join(backupDir, "db-backup-to-s3.failure");
fs.writeFileSync(backupFile, "backup");
fs.writeFileSync(alertFile, "db-backup-to-s3 failed at 2026-07-06T03:17:00.000Z exit=1\n");
const app = createApp(createHealthyDb(), testServerInfo, {
enabled: true,
backupDir,
maxAgeHours: 26,
alertFile,
now: new Date("2026-07-06T04:00:00.000Z"),
});
const res = await request(app).get("/health");
expect(res.status).toBe(200);
expect(res.body.databaseBackup).toMatchObject({
status: "warning",
lastFailure: {
path: alertFile,
message: "db-backup-to-s3 failed at 2026-07-06T03:17:00.000Z exit=1",
},
warnings: [
{
code: "database_backup_last_failure",
message: "db-backup-to-s3 failed at 2026-07-06T03:17:00.000Z exit=1",
},
],
});
});
it("finds conventional database backup failure markers without an explicit alert file", async () => {
const backupRoot = fs.mkdtempSync(path.join(os.tmpdir(), "paperclip-health-backups-root-"));
const backupDir = path.join(backupRoot, "backups");
fs.mkdirSync(backupDir);
const backupFile = path.join(backupDir, "paperclip-20260706-031702.sql.gz");
const alertFile = path.join(backupRoot, "db-backup-to-s3.failure");
fs.writeFileSync(backupFile, "backup");
fs.writeFileSync(alertFile, "db-backup-to-s3 failed beside backups\n");
const app = createApp(createHealthyDb(), testServerInfo, {
enabled: true,
backupDir,
maxAgeHours: 26,
now: new Date("2026-07-06T04:00:00.000Z"),
});
const res = await request(app).get("/health");
expect(res.status).toBe(200);
expect(res.body.databaseBackup).toMatchObject({
status: "warning",
lastFailure: {
path: alertFile,
message: "db-backup-to-s3 failed beside backups",
},
warnings: [
{
code: "database_backup_last_failure",
message: "db-backup-to-s3 failed beside backups",
},
],
});
});
it("surfaces redacted database backup warnings for anonymous authenticated probes", async () => {
const backupDir = fs.mkdtempSync(path.join(os.tmpdir(), "paperclip-health-redacted-backups-"));
const backupFile = path.join(backupDir, "paperclip-20260705-031702.sql.gz");
fs.writeFileSync(backupFile, "backup");
fs.utimesSync(
backupFile,
new Date("2026-07-05T03:17:02.000Z"),
new Date("2026-07-05T03:17:02.000Z"),
);
const { healthRoutes } = await import("../routes/health.js");
const db = {
execute: vi.fn().mockResolvedValue([{ "?column?": 1 }]),
select: vi.fn(() => ({
from: vi.fn(() => ({
where: vi.fn().mockResolvedValue([{ count: 1 }]),
})),
})),
} as unknown as Db;
const app = express();
app.use((req, _res, next) => {
(req as any).actor = { type: "none", source: "none" };
next();
});
app.use(
"/health",
healthRoutes(db, {
deploymentMode: "authenticated",
deploymentExposure: "public",
authReady: true,
companyDeletionEnabled: false,
serverInfo: testServerInfo,
databaseBackupHealth: {
enabled: true,
backupDir,
maxAgeHours: 26,
now: new Date("2026-07-06T13:00:00.000Z"),
},
}),
);
const res = await request(app).get("/health");
expect(res.status).toBe(200);
expect(res.body).toEqual({
status: "ok",
deploymentMode: "authenticated",
deploymentExposure: "public",
localAiLoginSupported: false,
hostedGoogleAiLoginSupported: true,
commit: testServerInfo.git.fullSha,
bootstrapStatus: "ready",
bootstrapInviteActive: false,
databaseBackup: {
enabled: true,
status: "warning",
warnings: [
{
code: "database_backup_stale",
message: "Latest database backup is stale.",
},
],
},
warnings: [
{
code: "database_backup_stale",
message: "Latest database backup is stale.",
},
],
});
});
it("redacts detailed metadata for anonymous requests in authenticated mode", async () => {
const devServerStatus = await import("../dev-server-status.js");
vi.spyOn(devServerStatus, "readPersistedDevServerStatus").mockReturnValue(null);
const { healthRoutes } = await import("../routes/health.js");
const db = {
execute: vi.fn().mockResolvedValue([{ "?column?": 1 }]),
select: vi.fn(() => ({
from: vi.fn(() => ({
where: vi.fn().mockResolvedValue([{ count: 1 }]),
})),
})),
} as unknown as Db;
const app = express();
app.use((req, _res, next) => {
(req as any).actor = { type: "none", source: "none" };
next();
});
app.use(
"/health",
healthRoutes(db, {
deploymentMode: "authenticated",
deploymentExposure: "public",
authReady: true,
companyDeletionEnabled: false,
serverInfo: testServerInfo,
}),
);
const res = await request(app).get("/health");
expect(res.status).toBe(200);
expect(res.body).toEqual({
status: "ok",
deploymentMode: "authenticated",
deploymentExposure: "public",
localAiLoginSupported: false,
hostedGoogleAiLoginSupported: true,
commit: testServerInfo.git.fullSha,
bootstrapStatus: "ready",
bootstrapInviteActive: false,
});
expect(res.body.serverInfo).toBeUndefined();
});
it("redacts detailed metadata when authenticated mode is reached without auth middleware", async () => {
const devServerStatus = await import("../dev-server-status.js");
vi.spyOn(devServerStatus, "readPersistedDevServerStatus").mockReturnValue(null);
const { healthRoutes } = await import("../routes/health.js");
const db = {
execute: vi.fn().mockResolvedValue([{ "?column?": 1 }]),
select: vi.fn(() => ({
from: vi.fn(() => ({
where: vi.fn().mockResolvedValue([{ count: 1 }]),
})),
})),
} as unknown as Db;
const app = express();
app.use(
"/health",
healthRoutes(db, {
deploymentMode: "authenticated",
deploymentExposure: "public",
authReady: true,
companyDeletionEnabled: false,
serverInfo: testServerInfo,
}),
);
const res = await request(app).get("/health");
expect(res.status).toBe(200);
expect(res.body).toEqual({
status: "ok",
deploymentMode: "authenticated",
deploymentExposure: "public",
localAiLoginSupported: false,
hostedGoogleAiLoginSupported: true,
commit: testServerInfo.git.fullSha,
bootstrapStatus: "ready",
bootstrapInviteActive: false,
});
expect(res.body.serverInfo).toBeUndefined();
});
it("keeps detailed metadata for authenticated requests in authenticated mode", async () => {
const devServerStatus = await import("../dev-server-status.js");
vi.spyOn(devServerStatus, "readPersistedDevServerStatus").mockReturnValue(null);
const { healthRoutes } = await import("../routes/health.js");
const db = {
execute: vi.fn().mockResolvedValue([{ "?column?": 1 }]),
select: vi.fn(() => ({
from: vi.fn(() => ({
where: vi.fn().mockResolvedValue([{ count: 1 }]),
})),
})),
} as unknown as Db;
const app = express();
app.use((req, _res, next) => {
(req as any).actor = { type: "board", userId: "user-1", source: "session" };
next();
});
app.use(
"/health",
healthRoutes(db, {
deploymentMode: "authenticated",
deploymentExposure: "public",
authReady: true,
companyDeletionEnabled: false,
serverInfo: testServerInfo,
}),
);
const res = await request(app).get("/health");
expect(res.status).toBe(200);
expect(res.body).toMatchObject({
status: "ok",
version: serverVersion,
serverVersion,
deploymentMode: "authenticated",
deploymentExposure: "public",
authReady: true,
bootstrapStatus: "ready",
bootstrapInviteActive: false,
features: {
companyDeletionEnabled: false,
},
serverInfo: testServerInfo,
});
});
it("reports bootstrap_pending in authenticated mode when no instance admin exists", async () => {
const { healthRoutes } = await import("../routes/health.js");
const db = {
execute: vi.fn().mockResolvedValue([{ "?column?": 1 }]),
select: vi.fn(() => ({
from: vi.fn(() => ({
where: vi.fn().mockResolvedValue([{ count: 0 }]),
})),
})),
} as unknown as Db;
const app = express();
app.use((req, _res, next) => {
(req as any).actor = { type: "none", source: "none" };
next();
});
app.use(
"/health",
healthRoutes(db, {
deploymentMode: "authenticated",
deploymentExposure: "public",
authReady: true,
companyDeletionEnabled: false,
serverInfo: testServerInfo,
}),
);
const res = await request(app).get("/health");
expect(res.status).toBe(200);
expect(res.body).toMatchObject({
status: "ok",
bootstrapStatus: "bootstrap_pending",
bootstrapInviteActive: false,
});
});
it("reports bootstrapStatus ready for cloud-managed instances regardless of instance admin count", async () => {
vi.stubEnv("PAPERCLIP_CLOUD_TENANT_SERVER_TOKEN", "test-tenant-server-token");
const { healthRoutes } = await import("../routes/health.js");
const db = {
execute: vi.fn().mockResolvedValue([{ "?column?": 1 }]),
select: vi.fn(() => ({
from: vi.fn(() => ({
where: vi.fn().mockResolvedValue([{ count: 0 }]),
})),
})),
} as unknown as Db;
const app = express();
app.use((req, _res, next) => {
(req as any).actor = { type: "none", source: "none" };
next();
});
app.use(
"/health",
healthRoutes(db, {
deploymentMode: "authenticated",
deploymentExposure: "public",
authReady: true,
companyDeletionEnabled: false,
serverInfo: testServerInfo,
}),
);
const res = await request(app).get("/health");
expect(res.status).toBe(200);
expect(res.body).toMatchObject({
status: "ok",
bootstrapStatus: "ready",
bootstrapInviteActive: false,
});
});
});