Files
community-rule/app/api/rules/[id]/share/route.ts
T
adilallo 5cbda35e32 Start every Rule private, with a rotating link and files that follow its readers.
New Rules stay off lists until the person who holds the pen turns on a share link, or the team features one. Uploaded files are readable only by those readers, stripped of location metadata, and deleted with the Rule, draft, or account.
2026-11-09 19:54:04 -07:00

87 lines
2.8 KiB
TypeScript

import { NextRequest, NextResponse } from "next/server";
import { apiRoute } from "../../../../../lib/server/apiRoute";
import { isDatabaseConfigured } from "../../../../../lib/server/env";
import { getPublicOrigin } from "../../../../../lib/server/publicOrigin";
import {
dbUnavailable,
errorJson,
forbidden,
notFound,
unauthorized,
} from "../../../../../lib/server/responses";
import {
getOwnedRuleShareSettings,
patchOwnedRuleShare,
} from "../../../../../lib/server/ruleShare";
import { getSessionUser } from "../../../../../lib/server/session";
import { patchRuleShareBodySchema } from "../../../../../lib/server/validation/createFlowSchemas";
import { readLimitedJson } from "../../../../../lib/server/validation/requestBody";
import { jsonFromZodError } from "../../../../../lib/server/validation/zodHttp";
type RouteContext = { params: Promise<{ id: string }> };
export const GET = apiRoute<RouteContext>(
"rules.share.get",
async (request, context) => {
if (!isDatabaseConfigured()) {
return dbUnavailable();
}
const user = await getSessionUser();
if (!user) {
return unauthorized();
}
const { id } = await context.params;
const settings = await getOwnedRuleShareSettings({
ruleId: id,
user,
origin: getPublicOrigin(request),
});
if (settings === "not_found") return notFound();
if (settings === "forbidden") {
return forbidden("You do not have permission to share this rule");
}
return NextResponse.json({ share: settings });
},
);
export const PATCH = apiRoute<RouteContext>(
"rules.share.patch",
async (request: NextRequest, context) => {
if (!isDatabaseConfigured()) {
return dbUnavailable();
}
const user = await getSessionUser();
if (!user) {
return unauthorized();
}
const { id } = await context.params;
const parsedBody = await readLimitedJson(request);
if (parsedBody.ok === false) {
return parsedBody.response;
}
const validated = patchRuleShareBodySchema.safeParse(parsedBody.value);
if (!validated.success) {
return jsonFromZodError(validated.error);
}
const result = await patchOwnedRuleShare({
ruleId: id,
user,
origin: getPublicOrigin(request),
visibility: validated.data.visibility,
communityAgreed: validated.data.communityAgreed,
});
if (result.ok === false) {
if (result.reason === "not_found") return notFound();
if (result.reason === "community_agreed") {
return errorJson(
"validation_error",
"Our community agreed to share this Rule is required.",
400,
);
}
return forbidden("You do not have permission to change this rule");
}
return NextResponse.json({ share: result.settings });
},
);