feat: add board-claim flow for local_trusted -> authenticated migration
One-time high-entropy claim URL printed at startup when the only instance admin is local-board. Signed-in user claims ownership, gets promoted to instance_admin, and receives active memberships across all existing companies. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
149
server/src/board-claim.ts
Normal file
149
server/src/board-claim.ts
Normal file
@@ -0,0 +1,149 @@
|
||||
import { randomBytes } from "node:crypto";
|
||||
import { and, eq } from "drizzle-orm";
|
||||
import type { Db } from "@paperclip/db";
|
||||
import { companies, companyMemberships, instanceUserRoles } from "@paperclip/db";
|
||||
import type { DeploymentMode } from "@paperclip/shared";
|
||||
|
||||
const LOCAL_BOARD_USER_ID = "local-board";
|
||||
const CLAIM_TTL_MS = 1000 * 60 * 60 * 24;
|
||||
|
||||
type ChallengeStatus = "available" | "claimed" | "expired" | "invalid";
|
||||
|
||||
type ClaimChallenge = {
|
||||
token: string;
|
||||
code: string;
|
||||
createdAt: Date;
|
||||
expiresAt: Date;
|
||||
claimedAt: Date | null;
|
||||
claimedByUserId: string | null;
|
||||
};
|
||||
|
||||
let activeChallenge: ClaimChallenge | null = null;
|
||||
|
||||
function createChallenge(now = new Date()): ClaimChallenge {
|
||||
return {
|
||||
token: randomBytes(24).toString("hex"),
|
||||
code: randomBytes(12).toString("hex"),
|
||||
createdAt: now,
|
||||
expiresAt: new Date(now.getTime() + CLAIM_TTL_MS),
|
||||
claimedAt: null,
|
||||
claimedByUserId: null,
|
||||
};
|
||||
}
|
||||
|
||||
function getChallengeStatus(token: string, code: string | undefined): ChallengeStatus {
|
||||
if (!activeChallenge) return "invalid";
|
||||
if (activeChallenge.token !== token) return "invalid";
|
||||
if (activeChallenge.code !== (code ?? "")) return "invalid";
|
||||
if (activeChallenge.claimedAt) return "claimed";
|
||||
if (activeChallenge.expiresAt.getTime() <= Date.now()) return "expired";
|
||||
return "available";
|
||||
}
|
||||
|
||||
export async function initializeBoardClaimChallenge(
|
||||
db: Db,
|
||||
opts: { deploymentMode: DeploymentMode },
|
||||
): Promise<void> {
|
||||
if (opts.deploymentMode !== "authenticated") {
|
||||
activeChallenge = null;
|
||||
return;
|
||||
}
|
||||
|
||||
const admins = await db
|
||||
.select({ userId: instanceUserRoles.userId })
|
||||
.from(instanceUserRoles)
|
||||
.where(eq(instanceUserRoles.role, "instance_admin"));
|
||||
|
||||
const onlyLocalBoardAdmin = admins.length === 1 && admins[0]?.userId === LOCAL_BOARD_USER_ID;
|
||||
if (!onlyLocalBoardAdmin) {
|
||||
activeChallenge = null;
|
||||
return;
|
||||
}
|
||||
|
||||
if (!activeChallenge || activeChallenge.expiresAt.getTime() <= Date.now() || activeChallenge.claimedAt) {
|
||||
activeChallenge = createChallenge();
|
||||
}
|
||||
}
|
||||
|
||||
export function getBoardClaimWarningUrl(host: string, port: number): string | null {
|
||||
if (!activeChallenge) return null;
|
||||
if (activeChallenge.claimedAt || activeChallenge.expiresAt.getTime() <= Date.now()) return null;
|
||||
const visibleHost = host === "0.0.0.0" ? "localhost" : host;
|
||||
return `http://${visibleHost}:${port}/board-claim/${activeChallenge.token}?code=${activeChallenge.code}`;
|
||||
}
|
||||
|
||||
export function inspectBoardClaimChallenge(token: string, code: string | undefined) {
|
||||
const status = getChallengeStatus(token, code);
|
||||
return {
|
||||
status,
|
||||
requiresSignIn: true,
|
||||
expiresAt: activeChallenge?.expiresAt?.toISOString() ?? null,
|
||||
claimedByUserId: activeChallenge?.claimedByUserId ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
export async function claimBoardOwnership(
|
||||
db: Db,
|
||||
opts: { token: string; code: string | undefined; userId: string },
|
||||
): Promise<{ status: ChallengeStatus; claimedByUserId?: string }> {
|
||||
const status = getChallengeStatus(opts.token, opts.code);
|
||||
if (status !== "available") return { status };
|
||||
|
||||
await db.transaction(async (tx) => {
|
||||
const existingTargetAdmin = await tx
|
||||
.select({ id: instanceUserRoles.id })
|
||||
.from(instanceUserRoles)
|
||||
.where(and(eq(instanceUserRoles.userId, opts.userId), eq(instanceUserRoles.role, "instance_admin")))
|
||||
.then((rows) => rows[0] ?? null);
|
||||
if (!existingTargetAdmin) {
|
||||
await tx.insert(instanceUserRoles).values({
|
||||
userId: opts.userId,
|
||||
role: "instance_admin",
|
||||
});
|
||||
}
|
||||
|
||||
await tx
|
||||
.delete(instanceUserRoles)
|
||||
.where(and(eq(instanceUserRoles.userId, LOCAL_BOARD_USER_ID), eq(instanceUserRoles.role, "instance_admin")));
|
||||
|
||||
const allCompanies = await tx.select({ id: companies.id }).from(companies);
|
||||
for (const company of allCompanies) {
|
||||
const existing = await tx
|
||||
.select({ id: companyMemberships.id, status: companyMemberships.status })
|
||||
.from(companyMemberships)
|
||||
.where(
|
||||
and(
|
||||
eq(companyMemberships.companyId, company.id),
|
||||
eq(companyMemberships.principalType, "user"),
|
||||
eq(companyMemberships.principalId, opts.userId),
|
||||
),
|
||||
)
|
||||
.then((rows) => rows[0] ?? null);
|
||||
|
||||
if (!existing) {
|
||||
await tx.insert(companyMemberships).values({
|
||||
companyId: company.id,
|
||||
principalType: "user",
|
||||
principalId: opts.userId,
|
||||
status: "active",
|
||||
membershipRole: "owner",
|
||||
});
|
||||
continue;
|
||||
}
|
||||
|
||||
if (existing.status !== "active") {
|
||||
await tx
|
||||
.update(companyMemberships)
|
||||
.set({ status: "active", membershipRole: "owner", updatedAt: new Date() })
|
||||
.where(eq(companyMemberships.id, existing.id));
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
if (activeChallenge && activeChallenge.token === opts.token) {
|
||||
activeChallenge.claimedAt = new Date();
|
||||
activeChallenge.claimedByUserId = opts.userId;
|
||||
}
|
||||
|
||||
return { status: "claimed", claimedByUserId: opts.userId };
|
||||
}
|
||||
@@ -24,6 +24,7 @@ import { setupLiveEventsWebSocketServer } from "./realtime/live-events-ws.js";
|
||||
import { heartbeatService } from "./services/index.js";
|
||||
import { createStorageServiceFromConfig } from "./storage/index.js";
|
||||
import { printStartupBanner } from "./startup-banner.js";
|
||||
import { getBoardClaimWarningUrl, initializeBoardClaimChallenge } from "./board-claim.js";
|
||||
import {
|
||||
createBetterAuthHandler,
|
||||
createBetterAuthInstance,
|
||||
@@ -337,6 +338,7 @@ if (config.deploymentMode === "authenticated") {
|
||||
const auth = createBetterAuthInstance(db as any, config);
|
||||
betterAuthHandler = createBetterAuthHandler(auth);
|
||||
resolveSession = (req) => resolveBetterAuthSession(auth, req);
|
||||
await initializeBoardClaimChallenge(db as any, { deploymentMode: config.deploymentMode });
|
||||
authReady = true;
|
||||
}
|
||||
|
||||
@@ -404,6 +406,22 @@ server.listen(listenPort, config.host, () => {
|
||||
heartbeatSchedulerEnabled: config.heartbeatSchedulerEnabled,
|
||||
heartbeatSchedulerIntervalMs: config.heartbeatSchedulerIntervalMs,
|
||||
});
|
||||
|
||||
const boardClaimUrl = getBoardClaimWarningUrl(config.host, listenPort);
|
||||
if (boardClaimUrl) {
|
||||
const red = "\x1b[41m\x1b[30m";
|
||||
const yellow = "\x1b[33m";
|
||||
const reset = "\x1b[0m";
|
||||
console.log(
|
||||
[
|
||||
`${red} BOARD CLAIM REQUIRED ${reset}`,
|
||||
`${yellow}This instance was previously local_trusted and still has local-board as the only admin.${reset}`,
|
||||
`${yellow}Sign in with a real user and open this one-time URL to claim ownership:${reset}`,
|
||||
`${yellow}${boardClaimUrl}${reset}`,
|
||||
`${yellow}If you are connecting over Tailscale, replace the host in this URL with your Tailscale IP/MagicDNS name.${reset}`,
|
||||
].join("\n"),
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
if (embeddedPostgres && embeddedPostgresStartedByThisProcess) {
|
||||
|
||||
@@ -21,6 +21,7 @@ import { forbidden, conflict, notFound, unauthorized, badRequest } from "../erro
|
||||
import { validate } from "../middleware/validate.js";
|
||||
import { accessService, agentService, logActivity } from "../services/index.js";
|
||||
import { assertCompanyAccess } from "./authz.js";
|
||||
import { claimBoardOwnership, inspectBoardClaimChallenge } from "../board-claim.js";
|
||||
|
||||
function hashToken(token: string) {
|
||||
return createHash("sha256").update(token).digest("hex");
|
||||
@@ -101,6 +102,40 @@ export function accessRoutes(db: Db) {
|
||||
if (!allowed) throw forbidden("Instance admin required");
|
||||
}
|
||||
|
||||
router.get("/board-claim/:token", async (req, res) => {
|
||||
const token = (req.params.token as string).trim();
|
||||
const code = typeof req.query.code === "string" ? req.query.code.trim() : undefined;
|
||||
if (!token) throw notFound("Board claim challenge not found");
|
||||
const challenge = inspectBoardClaimChallenge(token, code);
|
||||
if (challenge.status === "invalid") throw notFound("Board claim challenge not found");
|
||||
res.json(challenge);
|
||||
});
|
||||
|
||||
router.post("/board-claim/:token/claim", async (req, res) => {
|
||||
const token = (req.params.token as string).trim();
|
||||
const code = typeof req.body?.code === "string" ? req.body.code.trim() : undefined;
|
||||
if (!token) throw notFound("Board claim challenge not found");
|
||||
if (!code) throw badRequest("Claim code is required");
|
||||
if (req.actor.type !== "board" || req.actor.source !== "session" || !req.actor.userId) {
|
||||
throw unauthorized("Sign in before claiming board ownership");
|
||||
}
|
||||
|
||||
const claimed = await claimBoardOwnership(db, {
|
||||
token,
|
||||
code,
|
||||
userId: req.actor.userId,
|
||||
});
|
||||
|
||||
if (claimed.status === "invalid") throw notFound("Board claim challenge not found");
|
||||
if (claimed.status === "expired") throw conflict("Board claim challenge expired. Restart server to generate a new one.");
|
||||
if (claimed.status === "claimed") {
|
||||
res.json({ claimed: true, userId: claimed.claimedByUserId ?? req.actor.userId });
|
||||
return;
|
||||
}
|
||||
|
||||
throw conflict("Board claim challenge is no longer available");
|
||||
});
|
||||
|
||||
async function assertCompanyPermission(req: Request, companyId: string, permissionKey: any) {
|
||||
assertCompanyAccess(req, companyId);
|
||||
if (req.actor.type === "agent") {
|
||||
|
||||
Reference in New Issue
Block a user