commit 9a4ce930c791f03fef8029a8cf823e1829a52466 Author: Meghdad <61308304+MeghdadFadaee@users.noreply.github.com> Date: Mon Oct 12 23:20:56 2026 +0330 Update Site source diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..1aa7f9b --- /dev/null +++ b/.env.example @@ -0,0 +1,2 @@ +# Server-side administrator email. Configure the production value through Sites. +ADMIN_EMAIL= diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..eada38c --- /dev/null +++ b/.gitignore @@ -0,0 +1,61 @@ +# See https://help.github.com/articles/ignoring-files/ for more about ignoring files. + +# dependencies +/node_modules +/.pnp +.pnp.* +.yarn/* +!.yarn/patches +!.yarn/plugins +!.yarn/releases +!.yarn/versions + +# testing +/coverage + +# next.js +/.next/ +/.vinext/ +/out/ + +# misc +.DS_Store +*.pem + +# debug +npm-debug.log* +yarn-debug.log* +yarn-error.log* +.pnpm-debug.log* + +# env files (can opt-in for committing if needed) +.env* + +# vercel +.vercel + +# typescript +next-env.d.ts + +# Maintained Vite plugin and worker sources. +!/build/ +/build/* +!/build/connector-preview-plugin.mjs +!/build/connector-preview-worker.mjs +!/build/sites-vite-plugin.LICENSE +!/build/sites-vite-plugin.ts +!/build/sites-worker.ts + +/dist/ +/.wrangler/ +# Checkout-local execution profile and tool state; never publish them. +/.sites-runtime/ +/.agents/ +/.codex/ +/outputs/ +/work/ + +/.dev.vars +!.env.example + +*.tsbuildinfo diff --git a/.npmrc b/.npmrc new file mode 100644 index 0000000..9f274d6 --- /dev/null +++ b/.npmrc @@ -0,0 +1,3 @@ +audit=false +fund=false +update-notifier=false diff --git a/.openai/hosting.json b/.openai/hosting.json new file mode 100644 index 0000000..a2de41a --- /dev/null +++ b/.openai/hosting.json @@ -0,0 +1,5 @@ +{ + "d1": "DB", + "r2": null, + "project_id": "appgprj_6acd3761005c81918297663c2aae588d" +} diff --git a/README.md b/README.md new file mode 100644 index 0000000..5372d63 --- /dev/null +++ b/README.md @@ -0,0 +1,15 @@ +# Siphoned Guild Vault + +Persian RTL Albion Online guild ledger. Public read access; ChatGPT-authenticated admin write access restricted by the server-side `ADMIN_EMAIL` runtime secret. The supplied 17 transactions are the initial immutable ledger baseline; subsequent imports are stored in D1 and merged with that baseline on every read. + +## Run + +`npm run dev` for local preview, `node --test lib/ledger.test.mjs` for ledger tests, `npm run db:generate` for schema migrations, `npm run build` for production. + +Apply the generated SQL to local D1 before previewing the ledger API. Production migrations are deployed through Sites. Configure `ADMIN_EMAIL` in the hosted environment before deployment. The local starter simulates ChatGPT as `seedy@sites.test`; grant that email only in an ignored local environment file when testing the admin workflow locally. Never configure it as the production administrator. + +## Data rules + +Paste the tab-separated Albion export with Date, Player, Reason, Amount headers. Imports accept up to 2,000 records, reject the entire import if any row is invalid, and use an atomic D1 batch with INSERT OR IGNORE. Identity is the exact game timestamp, case-insensitive player name, reason, and integer amount. Genuine indistinguishable rows cannot be differentiated because the game export supplies no transaction ID. Different amounts, timestamps, players, or reasons remain distinct. No timezone conversion is applied to game timestamps. + +Balances are net amounts in the supplied history, without any inferred opening balance. Minimum readiness balance is 10. Rank is net balance, not total deposits. Import writes require authenticated administrator identity and same-origin requests. Public responses have no cache so balances update on refresh. diff --git a/app/admin/page.tsx b/app/admin/page.tsx new file mode 100644 index 0000000..01d10cb --- /dev/null +++ b/app/admin/page.tsx @@ -0,0 +1,5 @@ +import Dashboard from '../dashboard'; +import { requireChatGPTUser } from '../chatgpt-auth'; +import { isAdmin } from '../../lib/server'; +export const dynamic='force-dynamic'; +export default async function Admin(){await requireChatGPTUser('/admin');if(!await isAdmin())return

دسترسی محدود است

این حساب اجازهٔ مدیریت خزانه را ندارد.

بازگشت به خزانه
;return ;} diff --git a/app/api/import/route.ts b/app/api/import/route.ts new file mode 100644 index 0000000..7546116 --- /dev/null +++ b/app/api/import/route.ts @@ -0,0 +1,14 @@ +import { env } from 'cloudflare:workers'; +import { isAdmin } from '../../../lib/server'; +import { getChatGPTUser } from '../../chatgpt-auth'; +import { parseLog, seed, identity } from '../../../lib/ledger.mjs'; +export const dynamic='force-dynamic'; +export async function POST(request:Request){ + if(!await isAdmin())return Response.json({error:'فقط مدیر خزانه اجازهٔ ثبت لاگ دارد.'},{status:403}); + if(request.headers.get('origin')!==new URL(request.url).origin)return Response.json({error:'درخواست مجاز نیست.'},{status:403}); + if(Number(request.headers.get('content-length'))>1100000)return Response.json({error:'حجم لاگ بیش از حد مجاز است.'},{status:413}); + let rows;try{const body=await request.json() as {log?:unknown};rows=parseLog(body.log);}catch(e){return Response.json({error:e instanceof Error?e.message:'لاگ معتبر نیست.'},{status:400});} + if(!env.DB)return Response.json({error:'پایگاه داده در دسترس نیست.'},{status:503}); + const user=await getChatGPTUser();const baseline=new Set(seed.map(identity));const candidates=rows.filter(r=>!baseline.has(identity(r))); + try{const results=candidates.length?await env.DB.batch(candidates.map(r=>env.DB!.prepare('INSERT OR IGNORE INTO transactions (id,date,player,reason,amount,imported_at,imported_by) VALUES (?,?,?,?,?,?,?)').bind(r.id,r.date,r.player,r.reason,r.amount,new Date().toISOString(),user!.userId))):[];const added=results.reduce((n,r)=>n+(r.meta.changes||0),0);return Response.json({added,duplicates:rows.length-added,total:rows.length});}catch{return Response.json({error:'ذخیره انجام نشد؛ دوباره تلاش کنید.'},{status:503});} +} diff --git a/app/api/ledger/route.ts b/app/api/ledger/route.ts new file mode 100644 index 0000000..7c9ab00 --- /dev/null +++ b/app/api/ledger/route.ts @@ -0,0 +1,3 @@ +import { readLedger, isAdmin } from '../../../lib/server'; +export const dynamic='force-dynamic'; +export async function GET(){try{return Response.json({rows:await readLedger(),admin:await isAdmin()},{headers:{'Cache-Control':'no-store'}});}catch{return Response.json({error:'بارگذاری خزانه ممکن نشد. دوباره تلاش کنید.'},{status:503});}} diff --git a/app/chatgpt-auth.ts b/app/chatgpt-auth.ts new file mode 100644 index 0000000..a0ae2ed --- /dev/null +++ b/app/chatgpt-auth.ts @@ -0,0 +1,90 @@ +import { headers } from "next/headers"; +import { redirect } from "next/navigation"; + +export type ChatGPTUser = { + userId: string; + displayName: string; + email: string; + fullName: string | null; +}; + +const USER_ID_HEADER = "oai-authenticated-user-id"; +const USER_EMAIL_HEADER = "oai-authenticated-user-email"; +const USER_FULL_NAME_HEADER = "oai-authenticated-user-full-name"; +const USER_FULL_NAME_ENCODING_HEADER = + "oai-authenticated-user-full-name-encoding"; +const PERCENT_ENCODED_UTF8 = "percent-encoded-utf-8"; +const SIGN_IN_PATH = "/signin-with-chatgpt"; +const SIGN_OUT_PATH = "/signout-with-chatgpt"; +const CALLBACK_PATH = "/callback"; + +export async function getChatGPTUser(): Promise { + const requestHeaders = await headers(); + const userId = requestHeaders.get(USER_ID_HEADER); + const email = requestHeaders.get(USER_EMAIL_HEADER); + if (!userId || !email) return null; + + const encodedFullName = requestHeaders.get(USER_FULL_NAME_HEADER); + const fullName = + encodedFullName && + requestHeaders.get(USER_FULL_NAME_ENCODING_HEADER) === PERCENT_ENCODED_UTF8 + ? safeDecodeURIComponent(encodedFullName) + : null; + + return { + userId, + displayName: fullName ?? email, + email, + fullName, + }; +} + +export async function requireChatGPTUser( + returnTo: string, +): Promise { + const user = await getChatGPTUser(); + if (user) return user; + + redirect(chatGPTSignInPath(returnTo)); +} + +export function chatGPTSignInPath(returnTo: string): string { + const safeReturnTo = safeRelativeReturnPath(returnTo); + return `${SIGN_IN_PATH}?return_to=${encodeURIComponent(safeReturnTo)}`; +} + +export function chatGPTSignOutPath(returnTo = "/"): string { + const safeReturnTo = safeRelativeReturnPath(returnTo); + return `${SIGN_OUT_PATH}?return_to=${encodeURIComponent(safeReturnTo)}`; +} + +function safeRelativeReturnPath(value: string): string { + if (!value.startsWith("/") || value.startsWith("//")) return "/"; + + let url: URL; + try { + url = new URL(value, "https://app.local"); + } catch { + return "/"; + } + if (url.origin !== "https://app.local") return "/"; + if (isReservedAuthPath(url.pathname)) return "/"; + + return `${url.pathname}${url.search}${url.hash}`; +} + +function isReservedAuthPath(pathname: string): boolean { + return ( + pathname === SIGN_IN_PATH || + pathname === SIGN_OUT_PATH || + pathname === CALLBACK_PATH + ); +} + +function safeDecodeURIComponent(value: string): string | null { + try { + return decodeURIComponent(value); + } catch { + return null; + } +} diff --git a/app/dashboard.tsx b/app/dashboard.tsx new file mode 100644 index 0000000..e995f16 --- /dev/null +++ b/app/dashboard.tsx @@ -0,0 +1,28 @@ +'use client'; +import {useEffect,useState,useMemo} from 'react'; +import {Shield,ArrowUpRight,ArrowDownLeft,Search,ChevronLeft,Trophy,Flame,Coins,History,Lock,Upload,CheckCircle2,AlertTriangle,X,RefreshCw,Copy} from 'lucide-react'; +import {seed,summarize,parseLog,identity,minimum} from '../lib/ledger.mjs'; +type Row={id:string;date:string;player:string;reason:string;amount:number}; +const num=(n:number)=>n.toLocaleString('en-US'); +function status(n:number){return n<0?'بدهکار':n(seed as Row[]),[loading,setLoading]=useState(true),[error,setError]=useState(''),[query,setQuery]=useState(''),[tab,setTab]=useState('all'),[selected,setSelected]=useState(null),[log,setLog]=useState(''),[message,setMessage]=useState(''),[saving,setSaving]=useState(false),[admin,setAdmin]=useState(false),[view,setView]=useState('leaderboard'); + async function refresh(){setLoading(true);setError('');try{const r=await fetch('/api/ledger');const d=await r.json() as {error?:string;rows:Row[];admin:boolean};if(!r.ok)throw Error(d.error);setRows(d.rows);setAdmin(d.admin);}catch(e){setError(e instanceof Error?e.message:'ارتباط برقرار نشد.');}finally{setLoading(false);}} + useEffect(()=>{refresh();},[]); + const players=useMemo(()=>summarize(rows),[rows]);const low=players.filter(p=>p.balances+p.balance,0);const deposits=rows.reduce((s,r)=>s+Math.max(r.amount,0),0);const withdrawals=rows.reduce((s,r)=>s+Math.max(-r.amount,0),0); + const filtered=players.filter(p=>p.name.toLowerCase().includes(query.toLowerCase())&&(tab!=='low'||p.balance{if(!selected)return;const onKey=(e:KeyboardEvent)=>{if(e.key==='Escape')setSelected(null);};document.addEventListener('keydown',onKey);return()=>document.removeEventListener('keydown',onKey);},[selected]); + const profile=players.find(p=>p.name.toLowerCase()===selected?.toLowerCase()); + const preview=useMemo(()=>{if(!log.trim())return null;try{const parsed=parseLog(log);const ids=new Set(rows.map(identity));let fresh=0;for(const r of parsed){const id=identity(r);if(!ids.has(id)){fresh++;ids.add(id);}}return {total:parsed.length,fresh,duplicates:parsed.length-fresh,error:''};}catch(e){return {error:(e as Error).message,total:0,fresh:0,duplicates:0};}},[log,rows]); + async function importLog(){setSaving(true);setMessage('');try{const r=await fetch('/api/import',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({log})});const d=await r.json() as {error?:string;added:number;duplicates:number};if(!r.ok)throw Error(d.error);setMessage(`${d.added} تراکنش جدید ثبت شد؛ ${d.duplicates} رکورد تکراری کنار گذاشته شد.`);setLog('');await refresh();}catch(e){setMessage((e as Error).message);}finally{setSaving(false);}} + return
+
گیلد خزانهٔ Siphoned
نمای عمومی
THE GUILD'S LIFEBLOOD

خزانه پُر. گیلد قدرتمند.

سهمت را ببین، جایگاهت را بشناس و برای نبرد بعدی آماده باش.

شفاف برای همهٔ اعضا به‌روزرسانی با لاگ بازی
+ {error&&
{error} داده‌های اولیه نمایش داده می‌شوند.
} +
بالانس خزانه
{num(total)}SIPHONEDخالص واریز و برداشت اعضا
کل واریزها
{num(deposits)}+ DEPOSITسهم اعضا در قدرت گیلد
کل برداشت‌ها
{num(withdrawals)}WITHDRAWAL{num(rows.length)} تراکنش ثبت‌شده
اعضای نیازمند اقدام
{num(low.length)}از {num(players.length)} عضوبالانس کمتر از {minimum} Siphoned
+ {adminMode&&
KEEP THE VAULT UP TO DATE

ورود لاگ خزانه

خروجی بازی را همراه عنوان ستون‌ها اینجا پیست کن. پیش‌نمایش را بررسی و سپس ثبت کن.