mirror of
https://github.com/bitbaum/kivvi.git
synced 2026-12-04 05:37:22 +01:00
* chore: add a formatter, matching the style this repo already writes singleQuote=false was chosen by counting this repo's own imports, not by fleet decree. The fleet is genuinely split and the two repos that already had a .prettierrc disagreed with each other, so there was no standard to restore. Quote style does not cross repo boundaries; having a gate does. Markdown is ignored for now — prettier rewraps prose, which would bury the real diff. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * style: format with prettier (759 files) Mechanical. No behaviour change. This SHA is listed in .git-blame-ignore-revs so `git blame` skips it. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * chore: teach git blame to skip the reformat Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix(ci): resolve the lockfile with the pnpm major CI runs The previous commit regenerated pnpm-lock.yaml with local pnpm 11, which re-resolved the `github:catomean/ai-forms` shorthand from a codeload tarball to git+ssh. CI runs pnpm 9, which cannot read that entry — and could not fetch over SSH even if it could, having no key. The lockfile was valid on the machine that wrote it and broken everywhere else. Resolved with pnpm 9 instead. The rollout script now derives the major from packageManager/PNPM_VERSION and refuses any lockfile that gains an ssh-form resolution. * fix(ci): resolve ai-forms over https, not ssh pnpm records whichever transport it could use when the lockfile was written. This laptop has an SSH key, so pnpm wrote git+ssh; CI has none and the install died on 'Permission denied (publickey)'. Resolving with GIT_SSH_COMMAND=/bin/false reproduces CI's capabilities and yields git+https, which needs no credentials for a public repo. * fix(ci): keep the lockfile byte-identical apart from the pin kivvi already depended on prettier, so this PR is script wiring, not a new dependency — and it should not have rewritten the lockfile at all. Regenerating it re-resolved the `github:catomean/ai-forms` shorthand three different ways, none of which CI could use: git+ssh (no key on the runner), then git+https (fetches, but pnpm's virtual-store path for a git dep failed to import). Only main's original codeload tarball works. The resolution recorded in a lockfile depends on what the machine writing it could reach, which makes 'it resolved fine locally' worth nothing. So: restore main's lockfile and change only the specifier, which is what --frozen-lockfile actually compares, and format with 3.8.0 — the version this repo's own lockfile already pinned — rather than dragging it to the fleet's 3.9.6 and reformatting against a version it does not install. --------- Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
116 lines
3.4 KiB
TypeScript
116 lines
3.4 KiB
TypeScript
import { NextRequest, NextResponse } from "next/server";
|
|
import { z } from "zod";
|
|
import type { MembershipRole } from "@kivvi/database";
|
|
import { auth } from "./auth";
|
|
import { extractBearerToken, validateApiToken } from "./api-auth";
|
|
import { findMembership } from "@kivvi/core/src/domain/memberships";
|
|
import { db } from "./db";
|
|
|
|
interface ApiContext {
|
|
companyId: string;
|
|
userId: string;
|
|
}
|
|
|
|
/** Role hierarchy levels for comparison */
|
|
const ROLE_LEVEL: Record<MembershipRole, number> = {
|
|
viewer: 0,
|
|
member: 1,
|
|
admin: 2,
|
|
owner: 3,
|
|
};
|
|
|
|
/**
|
|
* Authenticate an API request using either:
|
|
* 1. Bearer token (API key) from Authorization header
|
|
* 2. Session cookie (NextAuth)
|
|
*
|
|
* Optionally enforces a minimum role via `minRole`.
|
|
* Returns the authenticated context or an error response.
|
|
*/
|
|
export async function authenticateApi(
|
|
request: NextRequest,
|
|
minRole?: MembershipRole,
|
|
): Promise<ApiContext | NextResponse> {
|
|
// Try API key first
|
|
const authHeader = request.headers.get("authorization");
|
|
const bearerToken = extractBearerToken(authHeader);
|
|
|
|
let ctx: ApiContext;
|
|
|
|
if (bearerToken) {
|
|
const result = await validateApiToken(bearerToken);
|
|
if (!result) {
|
|
return NextResponse.json(
|
|
{ success: false, error: "Invalid or expired API token" },
|
|
{ status: 401 },
|
|
);
|
|
}
|
|
ctx = { companyId: result.companyId, userId: result.userId };
|
|
} else {
|
|
// Fall back to session auth
|
|
const session = await auth();
|
|
if (!session?.user?.companyId) {
|
|
return NextResponse.json(
|
|
{
|
|
success: false,
|
|
error: "Unauthorized. Provide a Bearer token or authenticate via session.",
|
|
},
|
|
{ status: 401 },
|
|
);
|
|
}
|
|
ctx = { companyId: session.user.companyId, userId: session.user.id };
|
|
}
|
|
|
|
// Enforce minimum role if specified
|
|
if (minRole) {
|
|
const membership = await findMembership(db, ctx.userId, ctx.companyId);
|
|
const userRole = (membership?.role ?? "viewer") as MembershipRole;
|
|
if (ROLE_LEVEL[userRole] < ROLE_LEVEL[minRole]) {
|
|
return NextResponse.json(
|
|
{ success: false, error: "Insufficient permissions" },
|
|
{ status: 403 },
|
|
);
|
|
}
|
|
}
|
|
|
|
return ctx;
|
|
}
|
|
|
|
/**
|
|
* Standard API error response.
|
|
*/
|
|
export function apiError(message: string, status: number = 400): NextResponse {
|
|
return NextResponse.json({ success: false, error: message }, { status });
|
|
}
|
|
|
|
/** Shorthand for 500 Internal Server Error responses. */
|
|
export function apiInternalError(): NextResponse {
|
|
return apiError("Internal server error", 500);
|
|
}
|
|
|
|
/**
|
|
* Formats a Zod validation error as a 400 API response.
|
|
* @param error - The ZodError from a failed safeParse
|
|
* @param context - "query parameters" or "body" (default: "parameters")
|
|
*/
|
|
export function apiZodError(error: z.ZodError, context: string = "parameters"): NextResponse {
|
|
const details = error.issues.map((i) => `${i.path}: ${i.message}`).join(", ");
|
|
return apiError(`Invalid ${context}: ${details}`);
|
|
}
|
|
|
|
/**
|
|
* Standard API success response.
|
|
*/
|
|
export function apiSuccess<T>(data: T, meta?: Record<string, unknown>): NextResponse {
|
|
return NextResponse.json({ success: true, data, ...(meta ? { meta } : {}) });
|
|
}
|
|
|
|
/**
|
|
* Shared pagination fields for v1 API query schemas.
|
|
* Spread into route-specific z.object() to add page/pageSize params.
|
|
*/
|
|
export const paginationQueryFields = {
|
|
page: z.coerce.number().int().positive().default(1),
|
|
pageSize: z.coerce.number().int().positive().max(200).default(50),
|
|
};
|