diff --git a/bun.lock b/bun.lock index dd13644..ff0f349 100644 --- a/bun.lock +++ b/bun.lock @@ -6,6 +6,7 @@ "name": "deckyvault", "dependencies": { "@aws-sdk/client-s3": "^3.1036.0", + "@better-auth/api-key": "^1.6.22", "@better-auth/drizzle-adapter": "^1.6.9", "@better-auth/expo": "^1.6.11", "@better-auth/passkey": "^1.6.9", @@ -189,6 +190,8 @@ "@babel/types": ["@babel/types@7.29.0", "", { "dependencies": { "@babel/helper-string-parser": "^7.27.1", "@babel/helper-validator-identifier": "^7.28.5" } }, "sha512-LwdZHpScM4Qz8Xw2iKSzS+cfglZzJGvofQICy7W7v4caru4EaAmyUuO6BGrbyQ2mYV11W0U8j5mBhd14dd3B0A=="], + "@better-auth/api-key": ["@better-auth/api-key@1.6.22", "", { "dependencies": { "zod": "^4.3.6" }, "peerDependencies": { "@better-auth/core": "^1.6.22", "@better-auth/utils": "0.4.2", "better-auth": "^1.6.22", "better-call": "1.3.7" } }, "sha512-HDiiLYF0ov0zqhKv4CMTyLwpjTZ3UWl2dug451uTw40VM9zGxWSNxwILDcMDZ6hS5evaTHmmk7R5gciskEk2nQ=="], + "@better-auth/core": ["@better-auth/core@1.6.9", "", { "dependencies": { "@opentelemetry/semantic-conventions": "^1.39.0", "@standard-schema/spec": "^1.1.0", "zod": "^4.3.6" }, "peerDependencies": { "@better-auth/utils": "0.4.0", "@better-fetch/fetch": "1.1.21", "@cloudflare/workers-types": ">=4", "@opentelemetry/api": "^1.9.0", "better-call": "1.3.5", "jose": "^6.1.0", "kysely": "^0.28.5", "nanostores": "^1.0.1" }, "optionalPeers": ["@cloudflare/workers-types", "@opentelemetry/api"] }, "sha512-ADFk5pwmLybmc+LvYvXJ6M1x2oY/EyYLkwLuH0x28FUq12DfjL0wnE7g+WRDf3yozDO+qIxTpFGXDGwLKbfz0w=="], "@better-auth/drizzle-adapter": ["@better-auth/drizzle-adapter@1.6.9", "", { "peerDependencies": { "@better-auth/core": "^1.6.9", "@better-auth/utils": "0.4.0", "drizzle-orm": "^0.45.2" }, "optionalPeers": ["drizzle-orm"] }, "sha512-Lcco5hOGrMgc4XKAkvB6x72eQm4wCcya8IevMg4wBHY9W9GVg8pu23rpRX6VsVQSO4Ux13S7lFwUWtF7/r9aKw=="], diff --git a/components/profile/settings-api-keys-tab.tsx b/components/profile/settings-api-keys-tab.tsx new file mode 100644 index 0000000..12df467 --- /dev/null +++ b/components/profile/settings-api-keys-tab.tsx @@ -0,0 +1,474 @@ +"use client" + +import { useState, useEffect, useCallback } from "react" +import { authClient } from "@/lib/auth-client" +import { + Loader2, + Key, + Plus, + Trash2, + Copy, + Check, + Eye, + EyeOff, + Clock, + AlertCircle, +} from "lucide-react" +import { motion, AnimatePresence } from "motion/react" + +// Raw API key type from Better Auth (dates are Date objects from the API) +interface RawApiKey { + id: string + name: string | null + start: string | null + prefix: string | null + enabled: boolean + expiresAt: Date | null + lastRequest: Date | null + remaining: number | null + createdAt: Date + updatedAt: Date + referenceId: string + metadata: Record | null + permissions: Record | null + configId: string + refillInterval: number | null + refillAmount: number | null + lastRefillAt: Date | null + rateLimitEnabled: boolean + rateLimitTimeWindow: number | null + rateLimitMax: number | null + requestCount: number +} + +interface CreatedApiKey extends RawApiKey { + key: string // Only returned on creation +} + +export function SettingsApiKeysTab() { + const [apiKeys, setApiKeys] = useState([]) + const [isLoading, setIsLoading] = useState(true) + const [error, setError] = useState(null) + + // Create form state + const [showCreateForm, setShowCreateForm] = useState(false) + const [newKeyName, setNewKeyName] = useState("") + const [newKeyExpiresIn, setNewKeyExpiresIn] = useState("") + const [isCreating, setIsCreating] = useState(false) + const [createdKey, setCreatedKey] = useState(null) + const [createError, setCreateError] = useState(null) + + // Delete state + const [deletingId, setDeletingId] = useState(null) + const [message, setMessage] = useState<{ + type: "success" | "error" + text: string + } | null>(null) + + // Copy state + const [copied, setCopied] = useState(false) + const [showKey, setShowKey] = useState(false) + + const fetchApiKeys = useCallback(async () => { + try { + const { data, error } = await authClient.apiKey.list({}) + if (error) { + setError(error.message || "Failed to load API keys") + setApiKeys([]) + } else { + setApiKeys((data?.apiKeys ?? []) as RawApiKey[]) + setError(null) + } + } catch { + setError("Failed to load API keys. Please try again.") + setApiKeys([]) + } finally { + setIsLoading(false) + } + }, []) + + useEffect(() => { + fetchApiKeys() + }, [fetchApiKeys]) + + const handleCreate = async (e: React.FormEvent) => { + e.preventDefault() + setCreateError(null) + + if (!newKeyName.trim()) { + setCreateError("Name is required") + return + } + + setIsCreating(true) + try { + const expiresIn = newKeyExpiresIn + ? parseInt(newKeyExpiresIn) * 24 * 60 * 60 + : undefined + + const { data, error } = await authClient.apiKey.create({ + name: newKeyName.trim(), + expiresIn, + }) + + if (error) { + setCreateError(error.message || "Failed to create API key") + } else if (data) { + setCreatedKey(data as unknown as CreatedApiKey) + await fetchApiKeys() + setNewKeyName("") + setNewKeyExpiresIn("") + setShowCreateForm(false) + } + } catch { + setCreateError("An unexpected error occurred") + } finally { + setIsCreating(false) + } + } + + const handleDelete = async (keyId: string) => { + setDeletingId(keyId) + setMessage(null) + try { + const { error } = await authClient.apiKey.delete({ keyId }) + if (error) { + setMessage({ + type: "error", + text: error.message || "Failed to delete API key", + }) + } else { + setMessage({ type: "success", text: "API key deleted" }) + await fetchApiKeys() + } + } catch { + setMessage({ + type: "error", + text: "Failed to delete API key. Please try again.", + }) + } finally { + setDeletingId(null) + } + } + + const formatDate = (date: Date | string | null): string => { + if (!date) return "Never" + try { + const d = date instanceof Date ? date : new Date(date) + return d.toLocaleDateString("en-US", { + month: "short", + day: "numeric", + year: "numeric", + hour: "2-digit", + minute: "2-digit", + }) + } catch { + return String(date) + } + } + + const handleCopyKey = async () => { + if (createdKey?.key) { + try { + await navigator.clipboard.writeText(createdKey.key) + setCopied(true) + setTimeout(() => setCopied(false), 2000) + } catch { + // Fallback for older browsers + const textarea = document.createElement("textarea") + textarea.value = createdKey.key + document.body.appendChild(textarea) + textarea.select() + document.execCommand("copy") + document.body.removeChild(textarea) + setCopied(true) + setTimeout(() => setCopied(false), 2000) + } + } + } + + + + // Show the created key modal + if (createdKey) { + return ( + +
+
+ +

+ API Key Created +

+
+ +

+ Copy your API key now. You won't be able to see it again. +

+ +
+
+ {showKey + ? createdKey.key + : `${createdKey.key.substring(0, 12)}${"•".repeat(Math.min(createdKey.key.length - 12, 20))}`} +
+
+ + +
+
+ + {createdKey.name && ( +

+ Name: {createdKey.name} +

+ )} + {createdKey.expiresAt && ( +

+ Expires:{" "} + + {formatDate(createdKey.expiresAt)} + +

+ )} + + +
+
+ ) + } + + return ( + + {/* Header */} +
+

+ + API Keys +

+ +
+ + {/* Message */} + {message && ( +
+ {message.text} +
+ )} + + {/* Create Form */} + + {showCreateForm && ( + +
+
+ + setNewKeyName(e.target.value)} + className='w-full px-3 py-2 rounded-lg bg-text/5 border border-border text-sm text-text focus:outline-none focus:border-primary/60 focus:ring-1 focus:ring-primary/30 transition-colors' + placeholder='e.g. Decky Loader Plugin' + maxLength={32} + required + /> +
+
+ + setNewKeyExpiresIn(e.target.value)} + className='w-full px-3 py-2 rounded-lg bg-text/5 border border-border text-sm text-text focus:outline-none focus:border-primary/60 focus:ring-1 focus:ring-primary/30 transition-colors' + placeholder='Leave empty for no expiry' + min={1} + max={365} + /> +
+ + {createError && ( +

+ + {createError} +

+ )} + + +
+
+ )} +
+ + {/* Key List */} + {error ? ( +
+

{error}

+ +
+ ) : isLoading ? ( +
+ + Loading API keys... +
+ ) : apiKeys.length === 0 ? ( +
+ +

+ No API keys created yet. +

+

+ Create an API key to use with the Decky Loader plugin or other external tools. +

+
+ ) : ( +
+ + {apiKeys.map((ak) => ( + +
+
+ +

+ {ak.name || "Unnamed key"} +

+ {!ak.enabled && ( + + Disabled + + )} +
+
+ {ak.start && ( + + {ak.start}... + + )} + {ak.expiresAt && ( + + + Expires {formatDate(ak.expiresAt)} + + )} + {ak.lastRequest && ( + + Last used {formatDate(ak.lastRequest)} + + )} + + Created {formatDate(ak.createdAt)} + +
+
+ +
+ ))} +
+
+ )} + + {/* Info */} +
+

+ Using API keys: Pass your API key as the{" "} + x-api-key header when + making requests to DeckyVault's API. You can use these keys with the Decky + Loader plugin or any automation tool. +

+
+
+ ) +} \ No newline at end of file diff --git a/components/profile/settings-container.tsx b/components/profile/settings-container.tsx index 7a0a0cf..f9a0820 100644 --- a/components/profile/settings-container.tsx +++ b/components/profile/settings-container.tsx @@ -1,10 +1,11 @@ "use client" import { useState, useEffect } from "react" -import { User, Shield, Link as LinkIcon } from "lucide-react" +import { User, Shield, Link as LinkIcon, Key } from "lucide-react" import { SettingsProfileTab } from "@/components/profile/settings-profile-tab" import { SettingsSecurityTab } from "@/components/profile/settings-security-tab" import { SettingsAccountsTab } from "@/components/profile/settings-accounts-tab" +import { SettingsApiKeysTab } from "@/components/profile/settings-api-keys-tab" interface AuthMethods { hasPassword: boolean @@ -13,12 +14,13 @@ interface AuthMethods { totalAuthMethods: number } -type SettingsSubTab = "profile" | "security" | "accounts" +type SettingsSubTab = "profile" | "security" | "accounts" | "api-keys" const subTabs: { id: SettingsSubTab; label: string; icon: typeof User }[] = [ { id: "profile", label: "Profile", icon: User }, { id: "security", label: "Security", icon: Shield }, { id: "accounts", label: "Linked Accounts", icon: LinkIcon }, + { id: "api-keys", label: "API Keys", icon: Key }, ] interface SettingsContainerProps { @@ -145,6 +147,9 @@ export function SettingsContainer({ onRefreshAuthMethods={refreshAuthMethods} /> )} + {activeSubTab === "api-keys" && ( + + )} ) diff --git a/drizzle/0027_slimy_stryfe.sql b/drizzle/0027_slimy_stryfe.sql new file mode 100644 index 0000000..174a74e --- /dev/null +++ b/drizzle/0027_slimy_stryfe.sql @@ -0,0 +1,28 @@ +CREATE TABLE "apikey" ( + "id" text PRIMARY KEY NOT NULL, + "config_id" text DEFAULT 'default' NOT NULL, + "name" text, + "start" text, + "reference_id" text NOT NULL, + "prefix" text, + "key" text NOT NULL, + "refill_interval" integer, + "refill_amount" integer, + "last_refill_at" timestamp, + "enabled" boolean DEFAULT true NOT NULL, + "rate_limit_enabled" boolean DEFAULT true NOT NULL, + "rate_limit_time_window" integer, + "rate_limit_max" integer, + "request_count" integer DEFAULT 0 NOT NULL, + "remaining" integer, + "last_request" timestamp, + "expires_at" timestamp, + "created_at" timestamp DEFAULT now() NOT NULL, + "updated_at" timestamp DEFAULT now() NOT NULL, + "permissions" text, + "metadata" text +); +--> statement-breakpoint +CREATE INDEX "apikey_config_id_idx" ON "apikey" USING btree ("config_id");--> statement-breakpoint +CREATE INDEX "apikey_reference_id_idx" ON "apikey" USING btree ("reference_id");--> statement-breakpoint +CREATE INDEX "apikey_key_idx" ON "apikey" USING btree ("key"); \ No newline at end of file diff --git a/drizzle/meta/0027_snapshot.json b/drizzle/meta/0027_snapshot.json new file mode 100644 index 0000000..0954fb3 --- /dev/null +++ b/drizzle/meta/0027_snapshot.json @@ -0,0 +1,2640 @@ +{ + "id": "1e0b0a96-5871-49cf-9081-29944205d936", + "prevId": "7e7813e4-686e-4d98-b36f-fa2a2a82fa5d", + "version": "7", + "dialect": "postgresql", + "tables": { + "public.account": { + "name": "account", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "account_id": { + "name": "account_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "provider_id": { + "name": "provider_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "access_token": { + "name": "access_token", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "refresh_token": { + "name": "refresh_token", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "id_token": { + "name": "id_token", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "access_token_expires_at": { + "name": "access_token_expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "refresh_token_expires_at": { + "name": "refresh_token_expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "scope": { + "name": "scope", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "password": { + "name": "password", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "account_userId_idx": { + "name": "account_userId_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "account_user_id_user_id_fk": { + "name": "account_user_id_user_id_fk", + "tableFrom": "account", + "tableTo": "user", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.apikey": { + "name": "apikey", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "config_id": { + "name": "config_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'default'" + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "start": { + "name": "start", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "reference_id": { + "name": "reference_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "prefix": { + "name": "prefix", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "key": { + "name": "key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "refill_interval": { + "name": "refill_interval", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "refill_amount": { + "name": "refill_amount", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "last_refill_at": { + "name": "last_refill_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "enabled": { + "name": "enabled", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "rate_limit_enabled": { + "name": "rate_limit_enabled", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "rate_limit_time_window": { + "name": "rate_limit_time_window", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "rate_limit_max": { + "name": "rate_limit_max", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "request_count": { + "name": "request_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "remaining": { + "name": "remaining", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "last_request": { + "name": "last_request", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "permissions": { + "name": "permissions", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "metadata": { + "name": "metadata", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "apikey_config_id_idx": { + "name": "apikey_config_id_idx", + "columns": [ + { + "expression": "config_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "apikey_reference_id_idx": { + "name": "apikey_reference_id_idx", + "columns": [ + { + "expression": "reference_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "apikey_key_idx": { + "name": "apikey_key_idx", + "columns": [ + { + "expression": "key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.passkey": { + "name": "passkey", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "public_key": { + "name": "public_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "credential_id": { + "name": "credential_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "counter": { + "name": "counter", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "device_type": { + "name": "device_type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "backed_up": { + "name": "backed_up", + "type": "boolean", + "primaryKey": false, + "notNull": true + }, + "transports": { + "name": "transports", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "aaguid": { + "name": "aaguid", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "passkey_userId_idx": { + "name": "passkey_userId_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "passkey_credentialID_idx": { + "name": "passkey_credentialID_idx", + "columns": [ + { + "expression": "credential_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "passkey_user_id_user_id_fk": { + "name": "passkey_user_id_user_id_fk", + "tableFrom": "passkey", + "tableTo": "user", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.session": { + "name": "session", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "token": { + "name": "token", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "ip_address": { + "name": "ip_address", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "user_agent": { + "name": "user_agent", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "impersonated_by": { + "name": "impersonated_by", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "session_userId_idx": { + "name": "session_userId_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "session_user_id_user_id_fk": { + "name": "session_user_id_user_id_fk", + "tableFrom": "session", + "tableTo": "user", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "session_token_unique": { + "name": "session_token_unique", + "nullsNotDistinct": false, + "columns": [ + "token" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.user": { + "name": "user", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "email": { + "name": "email", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "email_verified": { + "name": "email_verified", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "image": { + "name": "image", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "role": { + "name": "role", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "banned": { + "name": "banned", + "type": "boolean", + "primaryKey": false, + "notNull": false, + "default": false + }, + "ban_reason": { + "name": "ban_reason", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "ban_expires": { + "name": "ban_expires", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "last_login_method": { + "name": "last_login_method", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "user_email_unique": { + "name": "user_email_unique", + "nullsNotDistinct": false, + "columns": [ + "email" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.verification": { + "name": "verification", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "identifier": { + "name": "identifier", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "value": { + "name": "value", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "verification_identifier_idx": { + "name": "verification_identifier_idx", + "columns": [ + { + "expression": "identifier", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.community_suggestions": { + "name": "community_suggestions", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "game_id": { + "name": "game_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "field_name": { + "name": "field_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "current_value": { + "name": "current_value", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "proposed_value": { + "name": "proposed_value", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "reason": { + "name": "reason", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "suggestion_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'pending'" + }, + "reviewed_by": { + "name": "reviewed_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "reviewed_at": { + "name": "reviewed_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "review_note": { + "name": "review_note", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "community_suggestions_game_field_user": { + "name": "community_suggestions_game_field_user", + "columns": [ + { + "expression": "game_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "field_name", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "suggestions_status_idx": { + "name": "suggestions_status_idx", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "community_suggestions_game_id_games_id_fk": { + "name": "community_suggestions_game_id_games_id_fk", + "tableFrom": "community_suggestions", + "tableTo": "games", + "columnsFrom": [ + "game_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "community_suggestions_user_id_user_id_fk": { + "name": "community_suggestions_user_id_user_id_fk", + "tableFrom": "community_suggestions", + "tableTo": "user", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "community_suggestions_reviewed_by_user_id_fk": { + "name": "community_suggestions_reviewed_by_user_id_fk", + "tableFrom": "community_suggestions", + "tableTo": "user", + "columnsFrom": [ + "reviewed_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.entry_screenshots": { + "name": "entry_screenshots", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "entry_id": { + "name": "entry_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "storage_key": { + "name": "storage_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "order_index": { + "name": "order_index", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "mime_type": { + "name": "mime_type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "width": { + "name": "width", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "height": { + "name": "height", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "original_name": { + "name": "original_name", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "entry_screenshots_entry_idx": { + "name": "entry_screenshots_entry_idx", + "columns": [ + { + "expression": "entry_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "entry_screenshots_entry_id_performance_entries_id_fk": { + "name": "entry_screenshots_entry_id_performance_entries_id_fk", + "tableFrom": "entry_screenshots", + "tableTo": "performance_entries", + "columnsFrom": [ + "entry_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.game_comments": { + "name": "game_comments", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "game_id": { + "name": "game_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "parent_id": { + "name": "parent_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "content": { + "name": "content", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "upvotes": { + "name": "upvotes", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "is_removed": { + "name": "is_removed", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "comments_game_created_idx": { + "name": "comments_game_created_idx", + "columns": [ + { + "expression": "game_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "comments_parent_idx": { + "name": "comments_parent_idx", + "columns": [ + { + "expression": "parent_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "game_comments_game_id_games_id_fk": { + "name": "game_comments_game_id_games_id_fk", + "tableFrom": "game_comments", + "tableTo": "games", + "columnsFrom": [ + "game_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "game_comments_user_id_user_id_fk": { + "name": "game_comments_user_id_user_id_fk", + "tableFrom": "game_comments", + "tableTo": "user", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "game_comments_parent_id_game_comments_id_fk": { + "name": "game_comments_parent_id_game_comments_id_fk", + "tableFrom": "game_comments", + "tableTo": "game_comments", + "columnsFrom": [ + "parent_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.game_platform_support": { + "name": "game_platform_support", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "game_id": { + "name": "game_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "hardware_slug": { + "name": "hardware_slug", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "is_supported": { + "name": "is_supported", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "proton_status": { + "name": "proton_status", + "type": "proton_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'unknown'" + }, + "anti_cheat_relevant": { + "name": "anti_cheat_relevant", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "anti_cheat_name": { + "name": "anti_cheat_name", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "anti_cheat_version": { + "name": "anti_cheat_version", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "anti_cheat_status": { + "name": "anti_cheat_status", + "type": "anti_cheat_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'unknown'" + }, + "playability_status": { + "name": "playability_status", + "type": "playability_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'unknown'" + }, + "playability_override": { + "name": "playability_override", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "playability_calculated_at": { + "name": "playability_calculated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "game_platform_support_game_id_games_id_fk": { + "name": "game_platform_support_game_id_games_id_fk", + "tableFrom": "game_platform_support", + "tableTo": "games", + "columnsFrom": [ + "game_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "game_platform_support_hardware_slug_hardware_slug_fk": { + "name": "game_platform_support_hardware_slug_hardware_slug_fk", + "tableFrom": "game_platform_support", + "tableTo": "hardware", + "columnsFrom": [ + "hardware_slug" + ], + "columnsTo": [ + "slug" + ], + "onDelete": "restrict", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "game_hardware_unique": { + "name": "game_hardware_unique", + "nullsNotDistinct": false, + "columns": [ + "game_id", + "hardware_slug" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.game_versions": { + "name": "game_versions", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "game_id": { + "name": "game_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "build_id": { + "name": "build_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "version_string": { + "name": "version_string", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "is_latest": { + "name": "is_latest", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "perf_game_lookup_idx": { + "name": "perf_game_lookup_idx", + "columns": [ + { + "expression": "game_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "game_versions_game_id_games_id_fk": { + "name": "game_versions_game_id_games_id_fk", + "tableFrom": "game_versions", + "tableTo": "games", + "columnsFrom": [ + "game_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "game_build_unique": { + "name": "game_build_unique", + "nullsNotDistinct": false, + "columns": [ + "game_id", + "build_id" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.games": { + "name": "games", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "steam_app_id": { + "name": "steam_app_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "source": { + "name": "source", + "type": "game_source", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'steam'" + }, + "slug": { + "name": "slug", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "publisher": { + "name": "publisher", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "developer": { + "name": "developer", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "genres": { + "name": "genres", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "header_image": { + "name": "header_image", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "capsule_image": { + "name": "capsule_image", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "store_url": { + "name": "store_url", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "online_multiplayer_status": { + "name": "online_multiplayer_status", + "type": "online_multiplayer_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'unknown'" + }, + "system_requirements": { + "name": "system_requirements", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "metacritic_score": { + "name": "metacritic_score", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "metacritic_url": { + "name": "metacritic_url", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "recommendations_total": { + "name": "recommendations_total", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "steam_review_score": { + "name": "steam_review_score", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "steam_review_sentiment": { + "name": "steam_review_sentiment", + "type": "steam_review_sentiment", + "typeSchema": "public", + "primaryKey": false, + "notNull": false + }, + "steam_review_count": { + "name": "steam_review_count", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "playability_status": { + "name": "playability_status", + "type": "playability_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'unknown'" + }, + "playability_override": { + "name": "playability_override", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "playability_calculated_at": { + "name": "playability_calculated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "price_current": { + "name": "price_current", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "price_initial": { + "name": "price_initial", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "price_currency": { + "name": "price_currency", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "is_free": { + "name": "is_free", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "release_date": { + "name": "release_date", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "categories": { + "name": "categories", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "platforms": { + "name": "platforms", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "last_sync": { + "name": "last_sync", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "sync_status": { + "name": "sync_status", + "type": "text", + "primaryKey": false, + "notNull": false, + "default": "'pending'" + }, + "sync_error": { + "name": "sync_error", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "sync_retry_count": { + "name": "sync_retry_count", + "type": "integer", + "primaryKey": false, + "notNull": false, + "default": 0 + }, + "sync_next_retry": { + "name": "sync_next_retry", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "games_source_idx": { + "name": "games_source_idx", + "columns": [ + { + "expression": "source", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "games_sync_status_idx": { + "name": "games_sync_status_idx", + "columns": [ + { + "expression": "sync_status", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "steam_app_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "games_steam_app_id_unique": { + "name": "games_steam_app_id_unique", + "nullsNotDistinct": false, + "columns": [ + "steam_app_id" + ] + }, + "games_slug_unique": { + "name": "games_slug_unique", + "nullsNotDistinct": false, + "columns": [ + "slug" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.hardware": { + "name": "hardware", + "schema": "", + "columns": { + "slug": { + "name": "slug", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "device_type": { + "name": "device_type", + "type": "device_type", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "image": { + "name": "image", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "watt_hours": { + "name": "watt_hours", + "type": "real", + "primaryKey": false, + "notNull": false + }, + "tdp_max": { + "name": "tdp_max", + "type": "real", + "primaryKey": false, + "notNull": false + }, + "sort_order": { + "name": "sort_order", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.performance_entries": { + "name": "performance_entries", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "version_id": { + "name": "version_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "hardware_slug": { + "name": "hardware_slug", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "fps_avg": { + "name": "fps_avg", + "type": "real", + "primaryKey": false, + "notNull": true + }, + "fps_low": { + "name": "fps_low", + "type": "real", + "primaryKey": false, + "notNull": false + }, + "fps_one_percent_low": { + "name": "fps_one_percent_low", + "type": "real", + "primaryKey": false, + "notNull": false + }, + "fps_high": { + "name": "fps_high", + "type": "real", + "primaryKey": false, + "notNull": false + }, + "proton_version": { + "name": "proton_version", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "os_version": { + "name": "os_version", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "upscaler_type": { + "name": "upscaler_type", + "type": "upscaler_type", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'none'" + }, + "upscaler_version": { + "name": "upscaler_version", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "frame_gen_method": { + "name": "frame_gen_method", + "type": "frame_gen_method", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'none'" + }, + "load_time_ssd": { + "name": "load_time_ssd", + "type": "real", + "primaryKey": false, + "notNull": false + }, + "load_time_sd": { + "name": "load_time_sd", + "type": "real", + "primaryKey": false, + "notNull": false + }, + "launch_options": { + "name": "launch_options", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "settings_json": { + "name": "settings_json", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "user_notes": { + "name": "user_notes", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "tdp_watts": { + "name": "tdp_watts", + "type": "real", + "primaryKey": false, + "notNull": false + }, + "youtube_video_id": { + "name": "youtube_video_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "custom_system": { + "name": "custom_system", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "is_removed": { + "name": "is_removed", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "is_pinned": { + "name": "is_pinned", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "pinned_at": { + "name": "pinned_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "removed_reason": { + "name": "removed_reason", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "upvotes": { + "name": "upvotes", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "downvotes": { + "name": "downvotes", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "verified_at": { + "name": "verified_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "verified_by": { + "name": "verified_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "perf_hardware_upscaler_idx": { + "name": "perf_hardware_upscaler_idx", + "columns": [ + { + "expression": "hardware_slug", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "upscaler_type", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "perf_version_idx": { + "name": "perf_version_idx", + "columns": [ + { + "expression": "version_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "perf_user_idx": { + "name": "perf_user_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "perf_removed_created_idx": { + "name": "perf_removed_created_idx", + "columns": [ + { + "expression": "is_removed", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": false, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "perf_upvotes_idx": { + "name": "perf_upvotes_idx", + "columns": [ + { + "expression": "upvotes", + "isExpression": false, + "asc": false, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "performance_entries_version_id_game_versions_id_fk": { + "name": "performance_entries_version_id_game_versions_id_fk", + "tableFrom": "performance_entries", + "tableTo": "game_versions", + "columnsFrom": [ + "version_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "performance_entries_hardware_slug_hardware_slug_fk": { + "name": "performance_entries_hardware_slug_hardware_slug_fk", + "tableFrom": "performance_entries", + "tableTo": "hardware", + "columnsFrom": [ + "hardware_slug" + ], + "columnsTo": [ + "slug" + ], + "onDelete": "restrict", + "onUpdate": "no action" + }, + "performance_entries_user_id_user_id_fk": { + "name": "performance_entries_user_id_user_id_fk", + "tableFrom": "performance_entries", + "tableTo": "user", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "performance_entries_verified_by_user_id_fk": { + "name": "performance_entries_verified_by_user_id_fk", + "tableFrom": "performance_entries", + "tableTo": "user", + "columnsFrom": [ + "verified_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.saved_games": { + "name": "saved_games", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "game_id": { + "name": "game_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "saved_games_user_id_user_id_fk": { + "name": "saved_games_user_id_user_id_fk", + "tableFrom": "saved_games", + "tableTo": "user", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "saved_games_game_id_games_id_fk": { + "name": "saved_games_game_id_games_id_fk", + "tableFrom": "saved_games", + "tableTo": "games", + "columnsFrom": [ + "game_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "saved_games_user_game_unique": { + "name": "saved_games_user_game_unique", + "nullsNotDistinct": false, + "columns": [ + "user_id", + "game_id" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.reports": { + "name": "reports", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "entry_id": { + "name": "entry_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "reporter_id": { + "name": "reporter_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "reason": { + "name": "reason", + "type": "report_reason", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "details": { + "name": "details", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "report_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'open'" + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "reports_entry_reporter_unique": { + "name": "reports_entry_reporter_unique", + "columns": [ + { + "expression": "entry_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "reporter_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "reports_status_idx": { + "name": "reports_status_idx", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "reports_entry_id_performance_entries_id_fk": { + "name": "reports_entry_id_performance_entries_id_fk", + "tableFrom": "reports", + "tableTo": "performance_entries", + "columnsFrom": [ + "entry_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "reports_reporter_id_user_id_fk": { + "name": "reports_reporter_id_user_id_fk", + "tableFrom": "reports", + "tableTo": "user", + "columnsFrom": [ + "reporter_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.saved_filters": { + "name": "saved_filters", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "filters": { + "name": "filters", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "saved_filters_user_id_user_id_fk": { + "name": "saved_filters_user_id_user_id_fk", + "tableFrom": "saved_filters", + "tableTo": "user", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "saved_filters_user_name": { + "name": "saved_filters_user_name", + "nullsNotDistinct": false, + "columns": [ + "user_id", + "name" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.storage_objects": { + "name": "storage_objects", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "key": { + "name": "key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "bucket": { + "name": "bucket", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "size": { + "name": "size", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "mime_type": { + "name": "mime_type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "entity_type": { + "name": "entity_type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "entity_id": { + "name": "entity_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "uploaded_by": { + "name": "uploaded_by", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "last_accessed_at": { + "name": "last_accessed_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "is_orphaned": { + "name": "is_orphaned", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + } + }, + "indexes": { + "storage_entity_idx": { + "name": "storage_entity_idx", + "columns": [ + { + "expression": "entity_type", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "entity_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "storage_key_idx": { + "name": "storage_key_idx", + "columns": [ + { + "expression": "key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "storage_objects_uploaded_by_user_id_fk": { + "name": "storage_objects_uploaded_by_user_id_fk", + "tableFrom": "storage_objects", + "tableTo": "user", + "columnsFrom": [ + "uploaded_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + } + }, + "enums": { + "public.suggestion_status": { + "name": "suggestion_status", + "schema": "public", + "values": [ + "pending", + "approved", + "rejected" + ] + }, + "public.anti_cheat_status": { + "name": "anti_cheat_status", + "schema": "public", + "values": [ + "none", + "supported", + "unsupported", + "unknown" + ] + }, + "public.proton_status": { + "name": "proton_status", + "schema": "public", + "values": [ + "native", + "proton", + "unsupported", + "unknown" + ] + }, + "public.game_source": { + "name": "game_source", + "schema": "public", + "values": [ + "steam", + "manual", + "gog", + "epic" + ] + }, + "public.online_multiplayer_status": { + "name": "online_multiplayer_status", + "schema": "public", + "values": [ + "none", + "supported", + "unknown" + ] + }, + "public.playability_status": { + "name": "playability_status", + "schema": "public", + "values": [ + "great", + "playable", + "needs_tweaks", + "unplayable", + "unknown" + ] + }, + "public.steam_review_sentiment": { + "name": "steam_review_sentiment", + "schema": "public", + "values": [ + "overwhelmingly_positive", + "very_positive", + "positive", + "mostly_positive", + "mixed", + "mostly_negative", + "negative", + "very_negative", + "overwhelmingly_negative" + ] + }, + "public.device_type": { + "name": "device_type", + "schema": "public", + "values": [ + "handheld", + "console" + ] + }, + "public.frame_gen_method": { + "name": "frame_gen_method", + "schema": "public", + "values": [ + "none", + "fsr_fg", + "dlss_fg", + "lsfg", + "other" + ] + }, + "public.upscaler_type": { + "name": "upscaler_type", + "schema": "public", + "values": [ + "none", + "fsr", + "dlss", + "xess", + "lsfg", + "other" + ] + }, + "public.report_reason": { + "name": "report_reason", + "schema": "public", + "values": [ + "inaccurate", + "spam", + "inappropriate", + "other" + ] + }, + "public.report_status": { + "name": "report_status", + "schema": "public", + "values": [ + "open", + "reviewed", + "dismissed" + ] + } + }, + "schemas": {}, + "sequences": {}, + "roles": {}, + "policies": {}, + "views": {}, + "_meta": { + "columns": {}, + "schemas": {}, + "tables": {} + } +} \ No newline at end of file diff --git a/drizzle/meta/_journal.json b/drizzle/meta/_journal.json index 86a87e5..4d2d5b4 100644 --- a/drizzle/meta/_journal.json +++ b/drizzle/meta/_journal.json @@ -190,6 +190,13 @@ "when": 1779214557250, "tag": "0026_polite_drax", "breakpoints": true + }, + { + "idx": 27, + "version": "7", + "when": 1782593630361, + "tag": "0027_slimy_stryfe", + "breakpoints": true } ] } \ No newline at end of file diff --git a/lib/api/app.ts b/lib/api/app.ts index ccc9938..508f2cb 100644 --- a/lib/api/app.ts +++ b/lib/api/app.ts @@ -50,6 +50,8 @@ import { db } from "@/lib/db" import { user } from "@/lib/db/schema/auth" import { eq } from "drizzle-orm" import { mobileRoutes } from "@/lib/api/mobile" +import { gamesLookupRoutes } from "@/lib/api/games-lookup" +import { performanceImportRoutes } from "@/lib/api/performance-import" const betterAuth = new Elysia({ name: "better-auth" }) .mount(auth.handler) @@ -241,6 +243,7 @@ export const app = new Elysia({ prefix: "/api" }) .use(standaloneVersionTestRoutes) .use(gamesManualRoutes) .use(screenshotRoutes) + .use(gamesLookupRoutes) .use(mobileRoutes) ) // ── Write routes ─────────────────────────────────────────── @@ -256,6 +259,7 @@ export const app = new Elysia({ prefix: "/api" }) .use(adminPerformanceRoutes) .use(adminCommentRoutes) .use(adminStorageRoutes) + .use(performanceImportRoutes) .use(adminAnalyticsRoutes) ) // ── Public forms (no auth) ───────────────────────────────── diff --git a/lib/api/games-lookup.ts b/lib/api/games-lookup.ts new file mode 100644 index 0000000..b4225e9 --- /dev/null +++ b/lib/api/games-lookup.ts @@ -0,0 +1,93 @@ +import { Elysia, t } from "elysia" +import { db } from "@/lib/db/index" +import { games, gameVersions } from "@/lib/db/schema" +import { eq, and } from "drizzle-orm" + +export const gamesLookupRoutes = new Elysia({ + prefix: "/games", + detail: { tags: ["Games"] }, +}).get( + "/lookup", + async ({ query, set }) => { + const { steamAppId } = query + + if (!steamAppId) { + set.status = 400 + return { error: "steamAppId query parameter is required" } + } + + // Look up the game + const [game] = await db + .select({ + id: games.id, + steamAppId: games.steamAppId, + title: games.title, + slug: games.slug, + headerImage: games.headerImage, + capsuleImage: games.capsuleImage, + developer: games.developer, + publisher: games.publisher, + source: games.source, + }) + .from(games) + .where(eq(games.steamAppId, steamAppId)) + .limit(1) + + if (!game) { + set.status = 404 + return { error: `No game found with steamAppId ${steamAppId}` } + } + + // Find the latest version + const [latestVersion] = await db + .select({ + id: gameVersions.id, + versionString: gameVersions.versionString, + buildId: gameVersions.buildId, + isLatest: gameVersions.isLatest, + createdAt: gameVersions.createdAt, + }) + .from(gameVersions) + .where( + and( + eq(gameVersions.gameId, game.id), + eq(gameVersions.isLatest, true), + ), + ) + .limit(1) + + // If no latest version, get the most recent one + const version = + latestVersion ?? + (await db + .select({ + id: gameVersions.id, + versionString: gameVersions.versionString, + buildId: gameVersions.buildId, + isLatest: gameVersions.isLatest, + createdAt: gameVersions.createdAt, + }) + .from(gameVersions) + .where(eq(gameVersions.gameId, game.id)) + .orderBy(gameVersions.createdAt) + .limit(1) + .then((rows) => rows[0] ?? null)) + + return { + game: { + ...game, + steamAppId: game.steamAppId ?? null, + }, + version, + } + }, + { + query: t.Object({ + steamAppId: t.Numeric(), + }), + detail: { + description: + "Look up a game and its latest version by Steam App ID. Used by the DeckyVault Decky Loader plugin to resolve game info before importing benchmarks.", + }, + }, +) \ No newline at end of file diff --git a/lib/api/index.ts b/lib/api/index.ts index c2d90da..e2c481c 100644 --- a/lib/api/index.ts +++ b/lib/api/index.ts @@ -30,3 +30,5 @@ export { dashboardPublicRoutes } from "./dashboard-public" export { cronRoutes } from "./cron" export { profilePhotoRoutes } from "./profile-photo" export { mobileRoutes } from "./mobile" +export { gamesLookupRoutes } from "./games-lookup" +export { performanceImportRoutes } from "./performance-import" diff --git a/lib/api/performance-import.ts b/lib/api/performance-import.ts new file mode 100644 index 0000000..a59aad5 --- /dev/null +++ b/lib/api/performance-import.ts @@ -0,0 +1,284 @@ +import { Elysia, t } from "elysia" +import { db } from "@/lib/db/index" +import { + performanceEntries, + gameVersions, + games, + hardware, + gamePlatformSupport, +} from "@/lib/db/schema" +import { eq, and } from "drizzle-orm" +import { requireAuthWithApiKeyFallback } from "@/lib/auth/api-key-guard" +import { recalculatePlayability } from "./playability" + +const VALID_UPSCALER_TYPES = ["none", "fsr", "dlss", "xess", "lsfg", "other"] as const +const VALID_FRAME_GEN_METHODS = ["none", "fsr_fg", "dlss_fg", "lsfg", "other"] as const +const VALID_ANTICHEAT_STATUSES = ["none", "supported", "unsupported", "unknown"] as const + +type UpscalerType = (typeof VALID_UPSCALER_TYPES)[number] +type FrameGenMethod = (typeof VALID_FRAME_GEN_METHODS)[number] +type AntiCheatStatus = (typeof VALID_ANTICHEAT_STATUSES)[number] + +export const performanceImportRoutes = new Elysia({ + prefix: "/performance", + detail: { tags: ["Performance"] }, +}).post( + "/import", + async ({ body, request, set }) => { + // ── Auth: session or API key ────────────────────────────────── + const guard = await requireAuthWithApiKeyFallback(request.headers) + if (!guard.ok) { + set.status = guard.status + return { error: guard.error } + } + + // ── Validate version (1 only for now) ───────────────────────── + if (body.version !== 1) { + set.status = 400 + return { error: "Unsupported import format version" } + } + + // ── Resolve game version from steamAppId ────────────────────── + const steamAppId = body.steamAppId + if (!steamAppId) { + set.status = 400 + return { error: "steamAppId is required" } + } + + const [game] = await db + .select({ id: games.id }) + .from(games) + .where(eq(games.steamAppId, steamAppId)) + .limit(1) + + if (!game) { + set.status = 404 + return { + error: `No game found with steamAppId ${steamAppId}. Submit the game on DeckyVault first.`, + } + } + + // Find the latest version, or create one if needed + let [version] = await db + .select({ id: gameVersions.id }) + .from(gameVersions) + .where( + and( + eq(gameVersions.gameId, game.id), + eq(gameVersions.isLatest, true), + ), + ) + .limit(1) + + if (!version) { + // Get the most recent version + const [existing] = await db + .select({ id: gameVersions.id }) + .from(gameVersions) + .where(eq(gameVersions.gameId, game.id)) + .orderBy(gameVersions.createdAt) + .limit(1) + + if (existing) { + version = existing + } else { + // Create a stub version so we can create the entry + const [newVersion] = await db + .insert(gameVersions) + .values({ + gameId: game.id, + isLatest: true, + }) + .returning({ id: gameVersions.id }) + version = newVersion + } + } + + // ── Validate hardware ───────────────────────────────────────── + const hardwareSlug = body.hardwareSlug + const [device] = await db + .select({ slug: hardware.slug, deviceType: hardware.deviceType }) + .from(hardware) + .where(eq(hardware.slug, hardwareSlug)) + .limit(1) + + if (!device) { + set.status = 400 + return { + error: `Unknown hardware slug: "${hardwareSlug}". Available devices: see /api/hardware`, + } + } + + // ── Validate FPS fields ─────────────────────────────────────── + const fpsAvg = Number(body.fpsAvg) + if (isNaN(fpsAvg) || fpsAvg < 1 || fpsAvg > 500) { + set.status = 400 + return { error: "fpsAvg must be between 1 and 500" } + } + + const fpsLow = body.fpsLow != null ? Number(body.fpsLow) : null + if (fpsLow !== null && (isNaN(fpsLow) || fpsLow < 0 || fpsLow > 500)) { + set.status = 400 + return { error: "fpsLow must be between 0 and 500" } + } + + const fpsOnePercentLow = + body.fpsOnePercentLow != null ? Number(body.fpsOnePercentLow) : null + if ( + fpsOnePercentLow !== null && + (isNaN(fpsOnePercentLow) || fpsOnePercentLow < 0 || fpsOnePercentLow > 500) + ) { + set.status = 400 + return { error: "fpsOnePercentLow must be between 0 and 500" } + } + + const fpsHigh = body.fpsHigh != null ? Number(body.fpsHigh) : null + if (fpsHigh !== null && (isNaN(fpsHigh) || fpsHigh < 0 || fpsHigh > 500)) { + set.status = 400 + return { error: "fpsHigh must be between 0 and 500" } + } + + // ── Validate enums ──────────────────────────────────────────── + const rawUpscalerType = body.upscalerType ?? "none" + const upscalerType: UpscalerType = VALID_UPSCALER_TYPES.includes( + rawUpscalerType as UpscalerType, + ) + ? (rawUpscalerType as UpscalerType) + : "none" + + const rawFrameGenMethod = body.frameGenMethod ?? "none" + const frameGenMethod: FrameGenMethod = VALID_FRAME_GEN_METHODS.includes( + rawFrameGenMethod as FrameGenMethod, + ) + ? (rawFrameGenMethod as FrameGenMethod) + : "none" + + // ── Validate other numeric fields ───────────────────────────── + const tdpWatts = body.tdpWatts != null ? Number(body.tdpWatts) : null + if (tdpWatts !== null && (isNaN(tdpWatts) || tdpWatts <= 0)) { + set.status = 400 + return { error: "tdpWatts must be greater than 0" } + } + + const loadTimeSsd = body.loadTimeSsd != null ? Number(body.loadTimeSsd) : null + const loadTimeSd = body.loadTimeSd != null ? Number(body.loadTimeSd) : null + + // ── Validate userNotes length ───────────────────────────────── + const userNotes = body.userNotes ?? null + if (userNotes && typeof userNotes === "string" && userNotes.length > 5000) { + set.status = 400 + return { error: "userNotes must be 5000 characters or less" } + } + + // ── Create the performance entry ────────────────────────────── + const [entry] = await db + .insert(performanceEntries) + .values({ + versionId: version.id, + hardwareSlug, + userId: guard.user.id, + fpsAvg, + fpsLow, + fpsOnePercentLow, + fpsHigh, + protonVersion: body.protonVersion ?? null, + osVersion: body.osVersion ?? null, + upscalerType, + upscalerVersion: body.upscalerVersion ?? null, + frameGenMethod, + loadTimeSsd, + loadTimeSd, + tdpWatts, + launchOptions: body.launchOptions ?? null, + settingsJson: body.settingsJson ?? null, + userNotes, + customSystem: body.customSystem ?? false, + }) + .returning() + + // ── Update / create gamePlatformSupport ────────────────────── + const [existingSupport] = await db + .select() + .from(gamePlatformSupport) + .where( + and( + eq(gamePlatformSupport.gameId, game.id), + eq(gamePlatformSupport.hardwareSlug, hardwareSlug), + ), + ) + .limit(1) + + if (existingSupport) { + await db + .update(gamePlatformSupport) + .set({ + antiCheatRelevant: + body.antiCheatRelevant ?? existingSupport.antiCheatRelevant, + antiCheatName: body.antiCheatRelevant + ? (body.antiCheatName ?? existingSupport.antiCheatName) + : null, + antiCheatStatus: (body.antiCheatStatus ?? + existingSupport.antiCheatStatus) as AntiCheatStatus, + updatedAt: new Date(), + }) + .where(eq(gamePlatformSupport.id, existingSupport.id)) + } else { + await db.insert(gamePlatformSupport).values({ + gameId: game.id, + hardwareSlug, + isSupported: true, + protonStatus: "unknown", + antiCheatRelevant: body.antiCheatRelevant ?? false, + antiCheatName: body.antiCheatRelevant ? (body.antiCheatName ?? null) : null, + antiCheatStatus: (body.antiCheatStatus ?? "unknown") as AntiCheatStatus, + playabilityStatus: "unknown", + }) + } + + // Fire-and-forget playability recalculation + recalculatePlayability(game.id).catch((err) => + console.error("Failed to recalculate playability:", err), + ) + + set.status = 201 + return { + id: entry.id, + gameId: game.id, + versionId: version.id, + createdAt: entry.createdAt.toISOString(), + authMethod: guard.keyId ? "api-key" : "session", + } + }, + { + body: t.Object({ + version: t.Number(), + steamAppId: t.Number(), + hardwareSlug: t.String(), + fpsAvg: t.Number(), + fpsLow: t.Optional(t.Nullable(t.Number())), + fpsOnePercentLow: t.Optional(t.Nullable(t.Number())), + fpsHigh: t.Optional(t.Nullable(t.Number())), + protonVersion: t.Optional(t.Nullable(t.String())), + osVersion: t.Optional(t.Nullable(t.String())), + upscalerType: t.Optional(t.String()), + upscalerVersion: t.Optional(t.Nullable(t.String())), + frameGenMethod: t.Optional(t.String()), + tdpWatts: t.Optional(t.Nullable(t.Number())), + loadTimeSsd: t.Optional(t.Nullable(t.Number())), + loadTimeSd: t.Optional(t.Nullable(t.Number())), + launchOptions: t.Optional(t.Nullable(t.String())), + settingsJson: t.Optional(t.Nullable(t.Any())), + userNotes: t.Optional(t.Nullable(t.String())), + customSystem: t.Optional(t.Boolean()), + antiCheatRelevant: t.Optional(t.Boolean()), + antiCheatName: t.Optional(t.Nullable(t.String())), + antiCheatStatus: t.Optional(t.String()), + }), + detail: { + description: + "Import a performance benchmark from a DeckyVault plugin export (.deckyvault.json). " + + "Accepts either session cookies or an x-api-key header for authentication. " + + "The steamAppId is used to resolve the game and its latest version automatically.", + }, + }, +) \ No newline at end of file diff --git a/lib/auth-client.ts b/lib/auth-client.ts index 0055432..70580c9 100644 --- a/lib/auth-client.ts +++ b/lib/auth-client.ts @@ -1,6 +1,7 @@ import { createAuthClient } from 'better-auth/react' import { adminClient, emailOTPClient, lastLoginMethodClient } from 'better-auth/client/plugins' import { passkeyClient } from '@better-auth/passkey/client' +import { apiKeyClient } from '@better-auth/api-key/client' export const authClient = createAuthClient({ baseURL: process.env.NEXT_PUBLIC_SITE_URL || "https://localhost:3000", @@ -8,7 +9,8 @@ export const authClient = createAuthClient({ emailOTPClient(), passkeyClient(), lastLoginMethodClient(), - adminClient() + adminClient(), + apiKeyClient(), ] }) diff --git a/lib/auth.ts b/lib/auth.ts index 83daae1..340e8df 100644 --- a/lib/auth.ts +++ b/lib/auth.ts @@ -2,6 +2,7 @@ import { betterAuth } from 'better-auth' import { admin, captcha, emailOTP, lastLoginMethod } from 'better-auth/plugins' import { passkey } from '@better-auth/passkey' import { expo } from '@better-auth/expo' +import { apiKey } from '@better-auth/api-key' import { drizzleAdapter } from '@better-auth/drizzle-adapter' import { db } from '@/lib/db/index' import { ac, admin as adminRole, moderator, contributor, user } from '@/lib/auth/permissions' @@ -72,6 +73,19 @@ export const auth = betterAuth({ defaultRole: 'user', adminRoles: ['admin'], }), + apiKey({ + defaultPrefix: 'dv_', + requireName: true, + keyExpiration: { + defaultExpiresIn: null, + disableCustomExpiresTime: false, + }, + rateLimit: { + enabled: true, + timeWindow: 1000 * 60 * 60, // 1 hour + maxRequests: 1000, + }, + }), expo(), ], socialProviders: { diff --git a/lib/auth/api-key-guard.ts b/lib/auth/api-key-guard.ts new file mode 100644 index 0000000..84cbccd --- /dev/null +++ b/lib/auth/api-key-guard.ts @@ -0,0 +1,98 @@ +import { auth } from "@/lib/auth" +import { db } from "@/lib/db/index" +import { user } from "@/lib/db/schema/auth" +import { eq } from "drizzle-orm" +import type { Session } from "better-auth" + +type User = typeof auth.$Infer.Session.user + +type ApiKeyGuardResult = + | { ok: true; user: User; session: Session | null; keyId: string } + | { ok: false; error: string; status: number } + +/** + * Attempts to authenticate a request using an API key from the x-api-key header. + * Verifies the key via Better Auth and looks up the user from the database. + */ +export async function authenticateWithApiKey( + requestHeaders: Headers, +): Promise { + const apiKey = requestHeaders.get("x-api-key") + if (!apiKey) { + return { ok: false, error: "Missing x-api-key header", status: 401 } + } + + try { + const result = await auth.api.verifyApiKey({ + body: { + key: apiKey, + }, + }) + + if (!result.valid || !result.key) { + const errorMessage = String(result.error?.message ?? "Invalid API key") + return { ok: false, error: errorMessage, status: 401 } + } + + const userId = result.key.referenceId + const keyId = result.key.id + + // Look up the user directly from the database + const [dbUser] = await db + .select() + .from(user) + .where(eq(user.id, userId)) + .limit(1) + + if (!dbUser) { + return { ok: false, error: "User not found for API key", status: 401 } + } + + // Build a minimal user object matching Better Auth's Session.user type + const authedUser: User = { + id: dbUser.id, + name: dbUser.name, + email: dbUser.email, + emailVerified: dbUser.emailVerified, + image: dbUser.image, + createdAt: dbUser.createdAt, + updatedAt: dbUser.updatedAt, + role: dbUser.role ?? "user", + banned: dbUser.banned ?? null, + banReason: dbUser.banReason ?? null, + banExpires: dbUser.banExpires ?? null, + } + + return { + ok: true, + user: authedUser, + session: null, + keyId, + } + } catch (err) { + console.error("[api-key-guard] API key verification failed:", err) + return { ok: false, error: "API key verification failed", status: 500 } + } +} + +/** + * Combined auth guard: first tries session auth (cookie), then falls back + * to API key auth (x-api-key header). Returns the authenticated user. + */ +export async function requireAuthWithApiKeyFallback( + requestHeaders: Headers, +): Promise { + // Try session auth first + const session = await auth.api.getSession({ headers: requestHeaders }) + if (session) { + return { + ok: true, + user: session.user, + session: session.session, + keyId: "", + } + } + + // Fall back to API key + return authenticateWithApiKey(requestHeaders) +} \ No newline at end of file diff --git a/lib/db/schema/auth.ts b/lib/db/schema/auth.ts index cda957e..2b1b8cc 100644 --- a/lib/db/schema/auth.ts +++ b/lib/db/schema/auth.ts @@ -135,3 +135,46 @@ export const passkeyRelations = relations(passkey, ({ one }) => ({ references: [user.id], }), })) + +export const apikey = pgTable( + "apikey", + { + id: text("id").primaryKey(), + configId: text("config_id").notNull().default("default"), + name: text("name"), + start: text("start"), + referenceId: text("reference_id").notNull(), + prefix: text("prefix"), + key: text("key").notNull(), + refillInterval: integer("refill_interval"), + refillAmount: integer("refill_amount"), + lastRefillAt: timestamp("last_refill_at"), + enabled: boolean("enabled").default(true).notNull(), + rateLimitEnabled: boolean("rate_limit_enabled").default(true).notNull(), + rateLimitTimeWindow: integer("rate_limit_time_window"), + rateLimitMax: integer("rate_limit_max"), + requestCount: integer("request_count").default(0).notNull(), + remaining: integer("remaining"), + lastRequest: timestamp("last_request"), + expiresAt: timestamp("expires_at"), + createdAt: timestamp("created_at").defaultNow().notNull(), + updatedAt: timestamp("updated_at") + .defaultNow() + .$onUpdate(() => new Date()) + .notNull(), + permissions: text("permissions"), + metadata: text("metadata"), + }, + (table) => [ + index("apikey_config_id_idx").on(table.configId), + index("apikey_reference_id_idx").on(table.referenceId), + index("apikey_key_idx").on(table.key), + ], +) + +export const apikeyRelations = relations(apikey, ({ one }) => ({ + user: one(user, { + fields: [apikey.referenceId], + references: [user.id], + }), +})) diff --git a/package.json b/package.json index 8ded1e8..9392c39 100644 --- a/package.json +++ b/package.json @@ -18,6 +18,7 @@ }, "dependencies": { "@aws-sdk/client-s3": "^3.1036.0", + "@better-auth/api-key": "^1.6.22", "@better-auth/drizzle-adapter": "^1.6.9", "@better-auth/expo": "^1.6.11", "@better-auth/passkey": "^1.6.9",