Files
zeekayandHanzo Dev 6b68c9299e kv: one name for the store, and it is Hanzo KV
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]>
2026-08-09 10:09:34 -07:00

135 lines
3.8 KiB
TypeScript

import { NextApiRequest, NextApiResponse } from "next";
import { z } from "zod";
import prisma from "@/lib/prisma";
import { ratelimit } from "@/lib/kv";
import { verifyUnsubscribeToken } from "@/lib/utils/unsubscribe";
import { ZViewerNotificationPreferencesSchema } from "@/lib/zod/schemas/notifications";
const UpdatePreferencesSchema = z.object({
frequency: z.enum(["instant", "daily", "weekly", "disabled"]),
});
export default async function handle(
req: NextApiRequest,
res: NextApiResponse,
) {
if (req.method !== "GET" && req.method !== "POST") {
res.status(405).json({ message: "Method Not Allowed" });
return;
}
const { token } = req.query as { token: string };
if (!token) {
res.status(400).json({ message: "Token is required" });
return;
}
const payload = verifyUnsubscribeToken(token);
if (!payload) {
res.status(400).json({ message: "Invalid or expired token" });
return;
}
if (payload.exp && payload.exp < Date.now() / 1000) {
res.status(400).json({ message: "Token expired" });
return;
}
const { viewerId, dataroomId, teamId } = payload;
if (!dataroomId) {
res.status(400).json({ message: "Dataroom ID is required" });
return;
}
if (req.method === "GET") {
return res.redirect(`/notification-preferences?token=${token}`);
}
// POST: update preferences
const ipAddress =
req.headers["x-forwarded-for"] || req.socket.remoteAddress || "127.0.0.1";
const { success, limit, reset, remaining } = await ratelimit(5, "1 m").limit(
`notification_prefs_${ipAddress}`,
);
res.setHeader("Retry-After", reset.toString());
res.setHeader("X-RateLimit-Limit", limit.toString());
res.setHeader("X-RateLimit-Remaining", remaining.toString());
res.setHeader("X-RateLimit-Reset", reset.toString());
if (!success) {
return res.status(429).json({ error: "Too many requests" });
}
// RFC 8058 one-click unsubscribe: email clients POST with
// body "List-Unsubscribe=One-Click" (form-urlencoded)
const isOneClick =
req.body?.["List-Unsubscribe"] === "One-Click" ||
(typeof req.body === "string" &&
req.body.includes("List-Unsubscribe=One-Click"));
try {
const frequency = isOneClick
? "disabled"
: UpdatePreferencesSchema.parse(req.body).frequency;
const viewer = await prisma.viewer.findUnique({
where: { id: viewerId, teamId },
select: { notificationPreferences: true },
});
if (!viewer) {
return res.status(404).json({ message: "Viewer not found" });
}
const parsedPreferences = ZViewerNotificationPreferencesSchema.safeParse(
viewer.notificationPreferences,
);
const rawPrefs =
typeof viewer.notificationPreferences === "object" &&
viewer.notificationPreferences !== null
? (viewer.notificationPreferences as Record<string, unknown>)
: {};
const base = {
...rawPrefs,
...(parsedPreferences.success ? parsedPreferences.data : {}),
};
const isDisabled = frequency === "disabled";
const updatedPreferences = {
...base,
dataroom: {
...(base.dataroom && typeof base.dataroom === "object"
? base.dataroom
: {}),
[dataroomId]: {
enabled: !isDisabled,
frequency: isDisabled ? "instant" : frequency,
},
},
};
await prisma.viewer.update({
where: { id: viewerId, teamId },
data: { notificationPreferences: updatedPreferences },
});
return res
.status(200)
.json({ message: "Notification preferences updated successfully." });
} catch (error) {
if (error instanceof z.ZodError) {
return res.status(400).json({ message: "Invalid request body", errors: error.errors });
}
console.error("Failed to update notification preferences:", error);
return res.status(500).json({ message: "Internal server error" });
}
}