at://Press
1import type { AstroCookies } from "astro";
2import { isOwner } from "./auth";
3import { BLOG_URL, PDS_URL, DID, SESSION_DID_COOKIE } from "./constants";
4
5export function checkOrigin(request: Request): Response | null {
6 const origin = request.headers.get("origin");
7 if (!origin || origin !== BLOG_URL) {
8 return new Response(JSON.stringify({ error: "Forbidden" }), { status: 403 });
9 }
10 return null;
11}
12
13export function checkAuth(cookies: AstroCookies): Response | null {
14 const sessionDid = cookies.get(SESSION_DID_COOKIE)?.value;
15 if (!sessionDid || !isOwner(sessionDid)) {
16 return new Response(JSON.stringify({ error: "Not authorized" }), { status: 403 });
17 }
18 return null;
19}
20
21export async function parseJsonBody(
22 request: Request
23): Promise<[Record<string, unknown>, null] | [null, Response]> {
24 try {
25 const body = await request.json();
26 return [body as Record<string, unknown>, null];
27 } catch {
28 return [
29 null,
30 new Response(JSON.stringify({ error: "Invalid JSON body" }), { status: 400 }),
31 ];
32 }
33}
34
35export async function createPdsSession(): Promise<[string, null] | [null, Response]> {
36 const pdsPassword = process.env.PDS_APP_PASSWORD;
37 if (!pdsPassword) {
38 return [
39 null,
40 new Response(JSON.stringify({ error: "PDS credentials not configured" }), { status: 500 }),
41 ];
42 }
43
44 const sessionRes = await fetch(
45 `${PDS_URL}/xrpc/com.atproto.server.createSession`,
46 {
47 method: "POST",
48 headers: { "Content-Type": "application/json" },
49 body: JSON.stringify({ identifier: DID, password: pdsPassword }),
50 }
51 );
52
53 if (!sessionRes.ok) {
54 console.error("PDS createSession failed:", sessionRes.status);
55 return [
56 null,
57 new Response(JSON.stringify({ error: "PDS auth failed" }), { status: 500 }),
58 ];
59 }
60
61 const session = (await sessionRes.json()) as { accessJwt: string };
62 return [session.accessJwt, null];
63}