feat: GitHub OAuth + encrypted CF token storage + settings page + fix input theme
This commit is contained in:
@@ -0,0 +1,5 @@
|
||||
import NextAuth from "next-auth";
|
||||
import { authOptions } from "@/lib/authOptions";
|
||||
|
||||
const handler = NextAuth(authOptions);
|
||||
export { handler as GET, handler as POST };
|
||||
@@ -0,0 +1,30 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { getServerSession } from "next-auth";
|
||||
import { authOptions } from "@/lib/authOptions";
|
||||
import { saveCFCreds, loadCFCreds } from "@/lib/credentials";
|
||||
|
||||
export async function GET() {
|
||||
const session = await getServerSession(authOptions);
|
||||
if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
||||
|
||||
const creds = await loadCFCreds();
|
||||
if (!creds) return NextResponse.json({ configured: false });
|
||||
return NextResponse.json({
|
||||
configured: true,
|
||||
accountId: creds.accountId,
|
||||
apiTokenMasked: `${creds.apiToken.slice(0, 6)}${"*".repeat(20)}`,
|
||||
});
|
||||
}
|
||||
|
||||
export async function PUT(req: NextRequest) {
|
||||
const session = await getServerSession(authOptions);
|
||||
if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
||||
|
||||
const { accountId, apiToken } = await req.json();
|
||||
if (!accountId?.trim() || !apiToken?.trim()) {
|
||||
return NextResponse.json({ error: "accountId and apiToken are required" }, { status: 400 });
|
||||
}
|
||||
|
||||
await saveCFCreds({ accountId: accountId.trim(), apiToken: apiToken.trim() });
|
||||
return NextResponse.json({ ok: true });
|
||||
}
|
||||
@@ -306,20 +306,20 @@ export default function CreatePage() {
|
||||
.form-input {
|
||||
width: 100%;
|
||||
border-radius: 0.75rem;
|
||||
border: 1px solid rgb(39 39 42);
|
||||
background: rgb(24 24 27 / 0.8);
|
||||
border: 1px solid var(--border);
|
||||
background: var(--bg-subtle);
|
||||
padding: 0.625rem 0.875rem;
|
||||
font-size: 0.875rem;
|
||||
color: rgb(228 228 231);
|
||||
color: var(--text);
|
||||
outline: none;
|
||||
transition: all 0.15s;
|
||||
}
|
||||
.form-input:focus {
|
||||
border-color: rgb(16 185 129 / 0.5);
|
||||
box-shadow: 0 0 0 2px rgb(16 185 129 / 0.1);
|
||||
border-color: var(--accent-border);
|
||||
box-shadow: 0 0 0 2px var(--accent-dim);
|
||||
}
|
||||
.form-input::placeholder {
|
||||
color: rgb(113 113 122);
|
||||
color: var(--text-faint);
|
||||
}
|
||||
`}</style>
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
"use client";
|
||||
|
||||
import { signIn } from "next-auth/react";
|
||||
import { Monitor, Github } from "lucide-react";
|
||||
|
||||
export default function LoginPage() {
|
||||
return (
|
||||
<div className="min-h-[calc(100vh-3.5rem)] flex items-center justify-center p-4">
|
||||
<div className="w-full max-w-sm">
|
||||
<div className="rounded-2xl border border-[var(--border)] bg-[var(--bg-card)] p-8 text-center shadow-xl">
|
||||
<div className="w-12 h-12 rounded-2xl bg-[var(--accent-dim)] border border-[var(--accent-border)] flex items-center justify-center mx-auto mb-5">
|
||||
<Monitor className="w-6 h-6 text-emerald-500" />
|
||||
</div>
|
||||
<h1 className="text-xl font-bold text-[var(--text)] mb-1">SSH Launcher</h1>
|
||||
<p className="text-sm text-[var(--text-muted)] mb-8">
|
||||
Sign in to manage your Cloudflare Zero Trust SSH hosts
|
||||
</p>
|
||||
<button
|
||||
onClick={() => signIn("github", { callbackUrl: "/" })}
|
||||
className="w-full flex items-center justify-center gap-3 rounded-xl bg-[var(--text)] text-[var(--bg)] font-semibold py-3 px-4 hover:opacity-90 transition"
|
||||
>
|
||||
<Github className="w-4 h-4" />
|
||||
Continue with GitHub
|
||||
</button>
|
||||
<p className="text-xs text-[var(--text-faint)] mt-6">
|
||||
Your Cloudflare credentials are stored encrypted in your browser session.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,11 +1,14 @@
|
||||
"use client";
|
||||
|
||||
import { ThemeProvider } from "next-themes";
|
||||
import { SessionProvider } from "next-auth/react";
|
||||
|
||||
export default function Providers({ children }: { children: React.ReactNode }) {
|
||||
return (
|
||||
<ThemeProvider attribute="class" defaultTheme="system" enableSystem disableTransitionOnChange>
|
||||
{children}
|
||||
</ThemeProvider>
|
||||
<SessionProvider>
|
||||
<ThemeProvider attribute="class" defaultTheme="system" enableSystem disableTransitionOnChange>
|
||||
{children}
|
||||
</ThemeProvider>
|
||||
</SessionProvider>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,195 @@
|
||||
"use client";
|
||||
|
||||
import { useState, useEffect } from "react";
|
||||
import { Settings, Key, Save, Check, AlertTriangle, Eye, EyeOff, RefreshCw } from "lucide-react";
|
||||
|
||||
interface SettingsState {
|
||||
configured: boolean;
|
||||
accountId?: string;
|
||||
apiTokenMasked?: string;
|
||||
}
|
||||
|
||||
export default function SettingsPage() {
|
||||
const [state, setState] = useState<SettingsState | null>(null);
|
||||
const [accountId, setAccountId] = useState("");
|
||||
const [apiToken, setApiToken] = useState("");
|
||||
const [showToken, setShowToken] = useState(false);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [saved, setSaved] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
fetch("/api/settings")
|
||||
.then((r) => r.json())
|
||||
.then((d) => {
|
||||
setState(d);
|
||||
if (d.accountId) setAccountId(d.accountId);
|
||||
})
|
||||
.catch(() => setState({ configured: false }));
|
||||
}, []);
|
||||
|
||||
async function handleSave(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
setSaving(true);
|
||||
setError(null);
|
||||
try {
|
||||
const res = await fetch("/api/settings", {
|
||||
method: "PUT",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ accountId, apiToken }),
|
||||
});
|
||||
const data = await res.json();
|
||||
if (!res.ok) throw new Error(data.error);
|
||||
setSaved(true);
|
||||
setState({ configured: true, accountId, apiTokenMasked: `${apiToken.slice(0, 6)}${"*".repeat(20)}` });
|
||||
setApiToken("");
|
||||
setTimeout(() => setSaved(false), 3000);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : "Failed to save");
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="min-h-[calc(100vh-3.5rem)]">
|
||||
<div className="max-w-xl mx-auto px-4 sm:px-6 py-8 sm:py-12">
|
||||
<div className="flex items-center gap-3 mb-8">
|
||||
<div className="w-10 h-10 rounded-xl bg-[var(--bg-card)] border border-[var(--border)] flex items-center justify-center">
|
||||
<Settings className="w-5 h-5 text-[var(--text-muted)]" />
|
||||
</div>
|
||||
<div>
|
||||
<h1 className="text-xl font-bold text-[var(--text)]">Settings</h1>
|
||||
<p className="text-sm text-[var(--text-muted)]">
|
||||
Cloudflare API credentials
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Current status */}
|
||||
{state && (
|
||||
<div className={`rounded-xl border p-4 mb-6 flex items-start gap-3 ${
|
||||
state.configured
|
||||
? "border-emerald-500/20 bg-emerald-500/5"
|
||||
: "border-amber-500/20 bg-amber-500/5"
|
||||
}`}>
|
||||
{state.configured ? (
|
||||
<Check className="w-4 h-4 text-emerald-500 mt-0.5 shrink-0" />
|
||||
) : (
|
||||
<AlertTriangle className="w-4 h-4 text-amber-500 mt-0.5 shrink-0" />
|
||||
)}
|
||||
<div className="text-sm min-w-0">
|
||||
{state.configured ? (
|
||||
<>
|
||||
<p className="font-medium text-emerald-600 dark:text-emerald-400">Credentials configured</p>
|
||||
<p className="text-[var(--text-faint)] mt-0.5 font-mono text-xs break-all">
|
||||
Account: {state.accountId}<br />
|
||||
Token: {state.apiTokenMasked}
|
||||
</p>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<p className="font-medium text-amber-600 dark:text-amber-400">Not configured</p>
|
||||
<p className="text-[var(--text-faint)] mt-0.5 text-xs">
|
||||
Enter your Cloudflare API credentials below. They'll be stored
|
||||
encrypted in your session cookie (90 days).
|
||||
</p>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Form */}
|
||||
<form onSubmit={handleSave} className="rounded-xl border border-[var(--border)] bg-[var(--bg-card)] p-6 space-y-5">
|
||||
<div>
|
||||
<label className="flex items-center gap-1.5 text-sm font-medium text-[var(--text)] mb-1.5">
|
||||
<Key className="w-3.5 h-3.5 text-[var(--text-muted)]" />
|
||||
Account ID
|
||||
</label>
|
||||
<input
|
||||
type="text"
|
||||
value={accountId}
|
||||
onChange={(e) => setAccountId(e.target.value)}
|
||||
placeholder="Your Cloudflare Account ID"
|
||||
className="settings-input"
|
||||
required
|
||||
/>
|
||||
<p className="text-xs text-[var(--text-faint)] mt-1">
|
||||
Found in Cloudflare Dashboard → right sidebar
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="flex items-center gap-1.5 text-sm font-medium text-[var(--text)] mb-1.5">
|
||||
<Key className="w-3.5 h-3.5 text-[var(--text-muted)]" />
|
||||
API Token
|
||||
</label>
|
||||
<div className="relative">
|
||||
<input
|
||||
type={showToken ? "text" : "password"}
|
||||
value={apiToken}
|
||||
onChange={(e) => setApiToken(e.target.value)}
|
||||
placeholder={state?.configured ? "Enter new token to update" : "Your Cloudflare API Token"}
|
||||
className="settings-input pr-10"
|
||||
required={!state?.configured}
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowToken(!showToken)}
|
||||
className="absolute right-3 top-1/2 -translate-y-1/2 text-[var(--text-faint)] hover:text-[var(--text-muted)]"
|
||||
>
|
||||
{showToken ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
|
||||
</button>
|
||||
</div>
|
||||
<p className="text-xs text-[var(--text-faint)] mt-1">
|
||||
Needs: Access Write · Tunnel Edit · DNS Edit · Zone Read
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<p className="text-sm text-red-500 flex items-center gap-1.5">
|
||||
<AlertTriangle className="w-3.5 h-3.5 shrink-0" />
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
|
||||
<button
|
||||
type="submit"
|
||||
disabled={saving}
|
||||
className="w-full flex items-center justify-center gap-2 rounded-xl bg-emerald-600 hover:bg-emerald-500 disabled:opacity-50 text-white font-semibold py-2.5 transition"
|
||||
>
|
||||
{saving ? (
|
||||
<><RefreshCw className="w-4 h-4 animate-spin" /> Saving...</>
|
||||
) : saved ? (
|
||||
<><Check className="w-4 h-4" /> Saved!</>
|
||||
) : (
|
||||
<><Save className="w-4 h-4" /> Save Credentials</>
|
||||
)}
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
<style jsx>{`
|
||||
.settings-input {
|
||||
width: 100%;
|
||||
border-radius: 0.75rem;
|
||||
border: 1px solid var(--border);
|
||||
background: var(--bg-subtle);
|
||||
padding: 0.625rem 0.875rem;
|
||||
font-size: 0.875rem;
|
||||
color: var(--text);
|
||||
outline: none;
|
||||
transition: all 0.15s;
|
||||
}
|
||||
.settings-input:focus {
|
||||
border-color: var(--accent-border);
|
||||
box-shadow: 0 0 0 2px var(--accent-dim);
|
||||
}
|
||||
.settings-input::placeholder {
|
||||
color: var(--text-faint);
|
||||
}
|
||||
`}</style>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -4,12 +4,14 @@ import Link from "next/link";
|
||||
import { usePathname } from "next/navigation";
|
||||
import { useTheme } from "next-themes";
|
||||
import { useEffect, useState } from "react";
|
||||
import { Monitor, PlusCircle, Server, Sun, Moon, User } from "lucide-react";
|
||||
import { useSession, signIn, signOut } from "next-auth/react";
|
||||
import { Monitor, PlusCircle, Server, Sun, Moon, Settings, LogOut, LogIn } from "lucide-react";
|
||||
|
||||
const links = [
|
||||
{ href: "/", label: "Hosts", icon: Monitor },
|
||||
{ href: "/create", label: "Deploy", icon: PlusCircle },
|
||||
{ href: "/tunnels", label: "Tunnels", icon: Server },
|
||||
{ href: "/settings", label: "Settings", icon: Settings },
|
||||
];
|
||||
|
||||
function ThemeToggle() {
|
||||
@@ -28,6 +30,45 @@ function ThemeToggle() {
|
||||
);
|
||||
}
|
||||
|
||||
function UserWidget() {
|
||||
const { data: session, status } = useSession();
|
||||
if (status === "loading") return <div className="w-8 h-8" />;
|
||||
|
||||
if (!session) {
|
||||
return (
|
||||
<button
|
||||
onClick={() => signIn("github")}
|
||||
className="flex items-center gap-1.5 px-2.5 py-1.5 rounded-lg bg-emerald-600 hover:bg-emerald-500 text-white text-xs font-medium transition"
|
||||
>
|
||||
<LogIn className="w-3.5 h-3.5" />
|
||||
<span className="hidden sm:inline">Sign in</span>
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex items-center gap-1.5">
|
||||
{session.user?.image ? (
|
||||
<img
|
||||
src={session.user.image}
|
||||
alt={session.user.name ?? ""}
|
||||
className="w-7 h-7 rounded-full border border-[var(--border)]"
|
||||
/>
|
||||
) : null}
|
||||
<span className="hidden sm:inline text-xs text-[var(--text-muted)] max-w-[120px] truncate">
|
||||
{session.user?.name ?? session.user?.email}
|
||||
</span>
|
||||
<button
|
||||
onClick={() => signOut({ callbackUrl: "/login" })}
|
||||
className="w-7 h-7 flex items-center justify-center rounded-lg text-[var(--text-faint)] hover:text-red-500 hover:bg-[var(--bg-card)] transition"
|
||||
title="Sign out"
|
||||
>
|
||||
<LogOut className="w-3.5 h-3.5" />
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default function Navigation() {
|
||||
const pathname = usePathname();
|
||||
|
||||
@@ -66,10 +107,7 @@ export default function Navigation() {
|
||||
|
||||
<div className="flex items-center gap-2">
|
||||
<ThemeToggle />
|
||||
<div className="hidden sm:flex items-center gap-1.5 px-2.5 py-1 rounded-lg bg-[var(--bg-card)] border border-[var(--border)] text-xs text-[var(--text-muted)]">
|
||||
<User className="w-3 h-3" />
|
||||
<span>CF Access</span>
|
||||
</div>
|
||||
<UserWidget />
|
||||
</div>
|
||||
</div>
|
||||
</nav>
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
import type { NextAuthOptions } from "next-auth";
|
||||
import GithubProvider from "next-auth/providers/github";
|
||||
|
||||
export const authOptions: NextAuthOptions = {
|
||||
providers: [
|
||||
GithubProvider({
|
||||
clientId: process.env.GITHUB_CLIENT_ID ?? "",
|
||||
clientSecret: process.env.GITHUB_CLIENT_SECRET ?? "",
|
||||
}),
|
||||
],
|
||||
secret: process.env.NEXTAUTH_SECRET,
|
||||
pages: {
|
||||
signIn: "/login",
|
||||
},
|
||||
callbacks: {
|
||||
async session({ session, token }) {
|
||||
if (session.user && token.sub) {
|
||||
(session.user as { id?: string }).id = token.sub;
|
||||
}
|
||||
return session;
|
||||
},
|
||||
},
|
||||
};
|
||||
+17
-22
@@ -74,20 +74,15 @@ export interface SetupResult {
|
||||
}
|
||||
|
||||
// ─── Credentials ─────────────────────────────────────────────────────────────
|
||||
// Reads from env vars first, falls back to encrypted cookie set via /settings
|
||||
import { requireCFCreds } from "@/lib/credentials";
|
||||
|
||||
function getCredentials() {
|
||||
const accountId = process.env.CLOUDFLARE_ACCOUNT_ID;
|
||||
const apiToken = process.env.CLOUDFLARE_API_TOKEN;
|
||||
if (!accountId || !apiToken) {
|
||||
throw new Error(
|
||||
"Missing CLOUDFLARE_ACCOUNT_ID or CLOUDFLARE_API_TOKEN env vars"
|
||||
);
|
||||
}
|
||||
return { accountId, apiToken };
|
||||
async function getCredentials() {
|
||||
return requireCFCreds();
|
||||
}
|
||||
|
||||
async function cfGet(path: string, revalidateSec = 60) {
|
||||
const { apiToken } = getCredentials();
|
||||
const { apiToken } = await getCredentials();
|
||||
const res = await fetch(`${CF_API_BASE}${path}`, {
|
||||
headers: { Authorization: `Bearer ${apiToken}` },
|
||||
next: { revalidate: revalidateSec },
|
||||
@@ -100,7 +95,7 @@ async function cfGet(path: string, revalidateSec = 60) {
|
||||
}
|
||||
|
||||
async function cfPost(path: string, body: unknown) {
|
||||
const { apiToken } = getCredentials();
|
||||
const { apiToken } = await getCredentials();
|
||||
const res = await fetch(`${CF_API_BASE}${path}`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
@@ -119,7 +114,7 @@ async function cfPost(path: string, body: unknown) {
|
||||
}
|
||||
|
||||
async function cfPut(path: string, body: unknown) {
|
||||
const { apiToken } = getCredentials();
|
||||
const { apiToken } = await getCredentials();
|
||||
const res = await fetch(`${CF_API_BASE}${path}`, {
|
||||
method: "PUT",
|
||||
headers: {
|
||||
@@ -138,7 +133,7 @@ async function cfPut(path: string, body: unknown) {
|
||||
}
|
||||
|
||||
async function cfDelete(path: string) {
|
||||
const { apiToken } = getCredentials();
|
||||
const { apiToken } = await getCredentials();
|
||||
const res = await fetch(`${CF_API_BASE}${path}`, {
|
||||
method: "DELETE",
|
||||
headers: { Authorization: `Bearer ${apiToken}` },
|
||||
@@ -155,7 +150,7 @@ async function cfDelete(path: string) {
|
||||
// ─── Access Applications ─────────────────────────────────────────────────────
|
||||
|
||||
export async function listAccessApps(): Promise<AccessApp[]> {
|
||||
const { accountId } = getCredentials();
|
||||
const { accountId } = await getCredentials();
|
||||
const allApps: AccessApp[] = [];
|
||||
let page = 1;
|
||||
const perPage = 50;
|
||||
@@ -216,7 +211,7 @@ export async function getSshAppById(id: string): Promise<SshApp | null> {
|
||||
// ─── Tunnels ─────────────────────────────────────────────────────────────────
|
||||
|
||||
export async function listTunnels(): Promise<Tunnel[]> {
|
||||
const { accountId } = getCredentials();
|
||||
const { accountId } = await getCredentials();
|
||||
const json = await cfGet(
|
||||
`/accounts/${accountId}/cfd_tunnel?is_deleted=false&per_page=50`,
|
||||
30
|
||||
@@ -225,7 +220,7 @@ export async function listTunnels(): Promise<Tunnel[]> {
|
||||
}
|
||||
|
||||
export async function createTunnel(name: string): Promise<Tunnel> {
|
||||
const { accountId } = getCredentials();
|
||||
const { accountId } = await getCredentials();
|
||||
const tunnelSecret = Buffer.from(
|
||||
crypto.getRandomValues(new Uint8Array(32))
|
||||
).toString("base64");
|
||||
@@ -238,12 +233,12 @@ export async function createTunnel(name: string): Promise<Tunnel> {
|
||||
}
|
||||
|
||||
export async function deleteTunnel(tunnelId: string): Promise<void> {
|
||||
const { accountId } = getCredentials();
|
||||
const { accountId } = await getCredentials();
|
||||
await cfDelete(`/accounts/${accountId}/cfd_tunnel/${tunnelId}`);
|
||||
}
|
||||
|
||||
export async function getTunnelToken(tunnelId: string): Promise<string> {
|
||||
const { accountId } = getCredentials();
|
||||
const { accountId } = await getCredentials();
|
||||
const json = await cfGet(
|
||||
`/accounts/${accountId}/cfd_tunnel/${tunnelId}/token`,
|
||||
0
|
||||
@@ -256,7 +251,7 @@ export async function configureTunnel(
|
||||
hostname: string,
|
||||
sshPort: number
|
||||
): Promise<void> {
|
||||
const { accountId } = getCredentials();
|
||||
const { accountId } = await getCredentials();
|
||||
await cfPut(`/accounts/${accountId}/cfd_tunnel/${tunnelId}/configurations`, {
|
||||
config: {
|
||||
ingress: [
|
||||
@@ -311,7 +306,7 @@ export async function createAccessApp(
|
||||
appName: string,
|
||||
allowedEmails: string[]
|
||||
): Promise<{ appId: string; metricsHostname: string }> {
|
||||
const { accountId } = getCredentials();
|
||||
const { accountId } = await getCredentials();
|
||||
|
||||
const policies = [];
|
||||
|
||||
@@ -353,7 +348,7 @@ export async function createAccessApp(
|
||||
export async function getOrCreateCaCert(
|
||||
appId: string
|
||||
): Promise<string | null> {
|
||||
const { accountId } = getCredentials();
|
||||
const { accountId } = await getCredentials();
|
||||
try {
|
||||
// Try to get existing CA
|
||||
const json = await cfGet(
|
||||
@@ -425,7 +420,7 @@ export async function runFullSetup(input: SetupInput): Promise<SetupResult> {
|
||||
// Step 3: Configure tunnel ingress (SSH + metrics HTTP)
|
||||
const metricsDomain = `metrics.${input.hostname}`;
|
||||
try {
|
||||
const { accountId } = getCredentials();
|
||||
const { accountId } = await getCredentials();
|
||||
await cfPut(`/accounts/${accountId}/cfd_tunnel/${tunnelId}/configurations`, {
|
||||
config: {
|
||||
ingress: [
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
import { cookies } from "next/headers";
|
||||
import { jwtDecrypt, EncryptJWT } from "jose";
|
||||
|
||||
export interface CFCreds {
|
||||
accountId: string;
|
||||
apiToken: string;
|
||||
}
|
||||
|
||||
function encKey(): Uint8Array {
|
||||
const s = process.env.NEXTAUTH_SECRET ?? process.env.AUTH_SECRET ?? "dev-secret-change-me";
|
||||
const buf = Buffer.from(s.padEnd(32, "0").slice(0, 32), "utf8");
|
||||
return new Uint8Array(buf);
|
||||
}
|
||||
|
||||
export async function saveCFCreds(creds: CFCreds): Promise<void> {
|
||||
const token = await new EncryptJWT({ ...creds })
|
||||
.setProtectedHeader({ alg: "dir", enc: "A256GCM" })
|
||||
.setExpirationTime("90d")
|
||||
.encrypt(encKey());
|
||||
|
||||
const jar = await cookies();
|
||||
jar.set("cf_creds", token, {
|
||||
httpOnly: true,
|
||||
secure: process.env.NODE_ENV === "production",
|
||||
sameSite: "lax",
|
||||
maxAge: 60 * 60 * 24 * 90,
|
||||
path: "/",
|
||||
});
|
||||
}
|
||||
|
||||
export async function loadCFCreds(): Promise<CFCreds | null> {
|
||||
if (process.env.CLOUDFLARE_ACCOUNT_ID && process.env.CLOUDFLARE_API_TOKEN) {
|
||||
return {
|
||||
accountId: process.env.CLOUDFLARE_ACCOUNT_ID,
|
||||
apiToken: process.env.CLOUDFLARE_API_TOKEN,
|
||||
};
|
||||
}
|
||||
try {
|
||||
const jar = await cookies();
|
||||
const raw = jar.get("cf_creds")?.value;
|
||||
if (!raw) return null;
|
||||
const { payload } = await jwtDecrypt(raw, encKey());
|
||||
return {
|
||||
accountId: payload.accountId as string,
|
||||
apiToken: payload.apiToken as string,
|
||||
};
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export async function requireCFCreds(): Promise<CFCreds> {
|
||||
const creds = await loadCFCreds();
|
||||
if (!creds) {
|
||||
throw new Error("Cloudflare credentials not configured. Visit /settings to set them up.");
|
||||
}
|
||||
return creds;
|
||||
}
|
||||
Reference in New Issue
Block a user