mirror of
https://github.com/hanzo-apps/dataroom.git
synced 2026-11-02 22:04:20 +00:00
The client was already @hanzo/kv; only the vocabulary was still Redis. Every module, symbol and comment now says what it connects to: lib/redis.ts -> lib/kv.ts (exports kv, lockKv) lib/redis-job-store.ts -> lib/kv-job-store.ts (KvJobStore) lib/redis-download-job-store.ts -> lib/kv-download-job-store.ts lib/files/tus-redis-locker.ts -> lib/files/tus-kv-locker.ts (KvLocker, KvLock) lib/api/domains/redis.ts -> lib/api/domains/kv.ts (getKey) lib/redis/ -> lib/kv-queue/ KV_URL is now the only endpoint variable — the REDIS_URL fallback and the redis://localhost default are gone, and the default scheme is kv://, which @hanzo/kv parses natively (utils/index.js). .env.example gained the KV_URL it never documented, and lost UPSTASH_REDIS_REST_LOCKER_URL/TOKEN: nothing has read those since the client changed — the locker opens a second connection to the same KV, so there is no second endpoint to configure. The second connection is `lockKv`, not `locker`: both tus routes already have a local `const locker = new KvLocker(...)`, so naming the client `locker` made the lock take itself as its own client. Verified against the repo's own gate (npx tsc --noEmit): 100 errors before and after, 0 introduced, compared set-wise by file:line:code. Behaviour is untouched — this is naming, one connection string, and dead config. Co-authored-by: Hanzo Dev <[email protected]>
172 lines
4.8 KiB
TypeScript
172 lines
4.8 KiB
TypeScript
import { NextApiRequest, NextApiResponse } from "next";
|
|
|
|
import { getServerSession } from "next-auth/next";
|
|
|
|
import { setDomainRedirectUrl } from "@/lib/api/domains/kv";
|
|
import { validateRedirectUrl } from "@/lib/api/domains/validate-redirect-url";
|
|
import { addDomainToVercel, validDomainRegex } from "@/lib/domains";
|
|
import { errorhandler } from "@/lib/errorHandler";
|
|
import prisma from "@/lib/prisma";
|
|
import { CustomUser } from "@/lib/types";
|
|
import { log } from "@/lib/utils";
|
|
|
|
import { authOptions } from "../../../auth/[...nextauth]";
|
|
|
|
export default async function handle(
|
|
req: NextApiRequest,
|
|
res: NextApiResponse,
|
|
) {
|
|
if (req.method === "GET") {
|
|
// GET /api/teams/:teamId/domains
|
|
const session = await getServerSession(req, res, authOptions);
|
|
if (!session) {
|
|
return res.status(401).end("Unauthorized");
|
|
}
|
|
|
|
const { teamId } = req.query as { teamId: string };
|
|
|
|
const userId = (session.user as CustomUser).id;
|
|
|
|
try {
|
|
const hasTeamAccess = await prisma.userTeam.findUnique({
|
|
where: {
|
|
userId_teamId: {
|
|
userId,
|
|
teamId,
|
|
},
|
|
},
|
|
});
|
|
if (!hasTeamAccess) {
|
|
return res.status(401).end("Unauthorized");
|
|
}
|
|
|
|
const domains = await prisma.domain.findMany({
|
|
where: {
|
|
teamId,
|
|
},
|
|
select: {
|
|
slug: true,
|
|
verified: true,
|
|
isDefault: true,
|
|
redirectUrl: true,
|
|
},
|
|
orderBy: {
|
|
createdAt: "asc",
|
|
},
|
|
});
|
|
|
|
return res.status(200).json(domains);
|
|
} catch (error) {
|
|
errorhandler(error, res);
|
|
}
|
|
} else if (req.method === "POST") {
|
|
// POST /api/teams/:teamId/domains
|
|
const session = await getServerSession(req, res, authOptions);
|
|
if (!session) {
|
|
res.status(401).end("Unauthorized");
|
|
return;
|
|
}
|
|
|
|
const userId = (session.user as CustomUser).id;
|
|
const { teamId } = req.query as { teamId: string };
|
|
|
|
if (!teamId) {
|
|
return res.status(401).json("Unauthorized");
|
|
}
|
|
|
|
try {
|
|
const hasTeamAccess = await prisma.userTeam.findUnique({
|
|
where: {
|
|
userId_teamId: {
|
|
userId,
|
|
teamId,
|
|
},
|
|
},
|
|
});
|
|
if (!hasTeamAccess) {
|
|
return res.status(401).end("Unauthorized");
|
|
}
|
|
|
|
const { domain, redirectUrl } = req.body;
|
|
|
|
// Sanitize domain by removing whitespace, protocol, and paths
|
|
const sanitizedDomain = domain
|
|
.trim()
|
|
.toLowerCase()
|
|
.replace(/^(?:https?:\/\/)?(?:www\.)?/i, "")
|
|
.split("/")[0];
|
|
|
|
// Check if domain is valid
|
|
const validDomain = validDomainRegex.test(sanitizedDomain);
|
|
if (validDomain !== true) {
|
|
return res.status(422).json("Invalid domain");
|
|
}
|
|
|
|
// Check if domain contains the host brand name
|
|
if (sanitizedDomain.toLowerCase().includes("hanzo")) {
|
|
return res
|
|
.status(400)
|
|
.json({ message: "Domain cannot contain 'hanzo'" });
|
|
}
|
|
|
|
// Check if domain already exists
|
|
const existingDomain = await prisma.domain.findFirst({
|
|
where: {
|
|
slug: sanitizedDomain,
|
|
},
|
|
});
|
|
|
|
if (existingDomain) {
|
|
return res.status(400).json({
|
|
message: "Unable to add this domain. Please try a different one.",
|
|
});
|
|
}
|
|
|
|
let validatedRedirectUrl: string | undefined;
|
|
if (redirectUrl) {
|
|
const result = await validateRedirectUrl(redirectUrl, teamId);
|
|
if (!result.valid) {
|
|
return res.status(422).json({ message: result.message });
|
|
}
|
|
validatedRedirectUrl = result.url || undefined;
|
|
}
|
|
|
|
const response = await prisma.domain.create({
|
|
data: {
|
|
slug: sanitizedDomain,
|
|
userId,
|
|
teamId,
|
|
...(validatedRedirectUrl && { redirectUrl: validatedRedirectUrl }),
|
|
},
|
|
});
|
|
await addDomainToVercel(sanitizedDomain);
|
|
|
|
if (validatedRedirectUrl) {
|
|
try {
|
|
await setDomainRedirectUrl(sanitizedDomain, validatedRedirectUrl);
|
|
} catch {
|
|
// Domain is functional but redirect failed to persist in KV.
|
|
// Remove redirectUrl from DB so the two stores stay consistent.
|
|
await prisma.domain.update({
|
|
where: { id: response.id },
|
|
data: { redirectUrl: null },
|
|
});
|
|
}
|
|
}
|
|
|
|
return res.status(201).json(response);
|
|
} catch (error) {
|
|
log({
|
|
message: `Failed to add domain. \n\n ${error} \n\n*Metadata*: \`{teamId: ${teamId}, userId: ${userId}}\``,
|
|
type: "error",
|
|
mention: true,
|
|
});
|
|
errorhandler(error, res);
|
|
}
|
|
} else {
|
|
// We only allow GET and POST requests
|
|
res.setHeader("Allow", ["GET", "POST"]);
|
|
return res.status(405).end(`Method ${req.method} Not Allowed`);
|
|
}
|
|
}
|