From 79fd7a7f79aa8da6af84c30c68e2041f01a12046 Mon Sep 17 00:00:00 2001 From: unimatrixgit <95320811+unimatrixgit@users.noreply.github.com> Date: Tue, 13 Oct 2026 15:06:02 +0200 Subject: [PATCH] Add independent forums, YouSMP community page and private player support portal --- website/.env.example | 4 +++ website/.openai/hosting.json | 2 +- website/FORUMS-PORTAL.md | 19 +++++++++++ website/README.md | 7 ++-- website/drizzle/0000_forums.sql | 41 +++++++++++++++++++++++ website/drizzle/0001_profiles_tickets.sql | 37 ++++++++++++++++++++ website/drizzle/meta/_journal.json | 1 + website/package.json | 10 +++++- website/scripts/build.mjs | 3 +- website/tests/d1-adapter.mjs | 7 ++++ website/tests/forum-api.test.mjs | 10 ++++++ website/tests/portal-api.test.mjs | 11 ++++++ website/tests/worker.test.mjs | 2 +- website/web/admin.html | 2 +- website/web/arrakis.html | 2 +- website/web/community.css | 3 ++ website/web/discord.html | 1 + website/web/discord.js | 1 + website/web/equipment.html | 2 +- website/web/exchange.html | 2 +- website/web/forums.html | 5 +++ website/web/forums.js | 20 +++++++++++ website/web/index.html | 4 +-- website/web/install.html | 2 +- website/web/manual.html | 2 +- website/web/minecraft.css | 2 ++ website/web/news.html | 2 +- website/web/portal.css | 1 + website/web/portal.html | 1 + website/web/portal.js | 17 ++++++++++ website/web/profile.html | 1 + website/web/races.html | 2 +- website/web/smugglers.html | 2 +- website/web/tickets.html | 1 + website/worker/community-api.mjs | 2 ++ website/worker/forum-api.mjs | 40 ++++++++++++++++++++++ website/worker/portal-api.mjs | 26 ++++++++++++++ website/worker/runtime.mjs | 5 ++- 38 files changed, 284 insertions(+), 18 deletions(-) create mode 100644 website/FORUMS-PORTAL.md create mode 100644 website/drizzle/0000_forums.sql create mode 100644 website/drizzle/0001_profiles_tickets.sql create mode 100644 website/drizzle/meta/_journal.json create mode 100644 website/tests/d1-adapter.mjs create mode 100644 website/tests/forum-api.test.mjs create mode 100644 website/tests/portal-api.test.mjs create mode 100644 website/web/community.css create mode 100644 website/web/discord.html create mode 100644 website/web/discord.js create mode 100644 website/web/forums.html create mode 100644 website/web/forums.js create mode 100644 website/web/portal.css create mode 100644 website/web/portal.html create mode 100644 website/web/portal.js create mode 100644 website/web/profile.html create mode 100644 website/web/tickets.html create mode 100644 website/worker/community-api.mjs create mode 100644 website/worker/forum-api.mjs create mode 100644 website/worker/portal-api.mjs diff --git a/website/.env.example b/website/.env.example index 872bea95..a6548e06 100644 --- a/website/.env.example +++ b/website/.env.example @@ -4,3 +4,7 @@ DISCORD_BOT_TOKEN= DISCORD_PUBLISHER_ID= DISCORD_EXCHANGE_CHANNEL_ID= DISCORD_NEWS_CHANNEL_ID= + +# Comma-separated staff account emails; store as secrets in Sites. +FORUM_ADMIN_EMAILS= +SUPPORT_STAFF_EMAILS= diff --git a/website/.openai/hosting.json b/website/.openai/hosting.json index 2bce02cd..1de37eec 100644 --- a/website/.openai/hosting.json +++ b/website/.openai/hosting.json @@ -1,5 +1,5 @@ { "project_id": "appgprj_6ace145fede88191b193de34d1753c02", - "d1": null, + "d1": "DB", "r2": null } diff --git a/website/FORUMS-PORTAL.md b/website/FORUMS-PORTAL.md new file mode 100644 index 00000000..d639c51b --- /dev/null +++ b/website/FORUMS-PORTAL.md @@ -0,0 +1,19 @@ +# Community and player portal + +The public website has independent Forums and Discord pages. Forums store topics, replies and reports in the hosted D1 database. Reading is public; posting requires ChatGPT sign-in. Public display names are chosen by players. The YouSMP Discord page links the verified community invitation and reads public member/online counts from Discord's invite API. Website discussions are not forwarded to Discord. + +## Private player support + +Open **Player portal → Your profile → Support tickets**. Sign in with ChatGPT and save a display name and optional Minecraft/Discord names. Names are self-reported, not verified account links. A Minecraft name is required for a ban appeal. Choose **Ban appeal** or **Staff support**, enter a subject and full description, then submit. Appeals should describe the ban reason, approximate date and why staff should reconsider it. + +Tickets and replies persist in D1 and are accessible only to the owning account and authorised staff. The owner can reply, close and reopen a closed case. Staff can reply and set Open, In progress, Waiting on player, Resolved or Closed. Each status change appears in the private case history. Closed cases must be reopened before replying. An appeal does not automatically unban a Minecraft account. No Discord messages or notifications are sent by this ticket system; staff should check the portal queue. + +The portal overview lists recent cases and the number of active tickets. The profile page links directly to support tickets. Staff access is checked server-side using trusted Sites identity headers and the secret `SUPPORT_STAFF_EMAILS` allowlist; `FORUM_ADMIN_EMAILS` also grants support access. Configure comma-separated account emails through Sites environment variables, never in source or browser code. The site owner's moderator account is configured initially. Minecraft operator status alone does not grant website permissions. + +Rate limits: three new tickets per hour, five active cases per account, five replies per minute. Requests validate length, use SQL parameters and require same-origin writes. Public topics/replies can be removed by their owner or moderators; authenticated players can report them. Moderators review reports separately from private support tickets. + +## Hosting + +`.openai/hosting.json` declares the `DB` binding. Schema-only migrations live in `drizzle/` and are packaged into `dist/.openai/drizzle`; Sites applies them before publication. Keep applied migration history immutable. Runtime secrets are managed in Sites. Game exchange/news integration remains separately configured through the existing DiscordSRV bridge and Discord bot channels; joining YouSMP does not configure those feeds. + +Build with `node scripts/build.mjs`, then run `node --test tests/*.test.mjs`. Tests use a temporary SQLite database and do not create public topics or real support requests. diff --git a/website/README.md b/website/README.md index 9ae423fe..a1b3b166 100644 --- a/website/README.md +++ b/website/README.md @@ -6,8 +6,11 @@ The home page is a Minecraft-styled banner and navigation hub. Every topic has i Browser files are in `web/`. The server-only Discord API is in `worker/feed-api.mjs`. Hosting configuration is in `.openai/hosting.json`. `node scripts/build.mjs` creates a Worker ESM bundle with the website assets embedded, avoiding separate asset bindings. No dependency installation is required. -Run `node scripts/preview.mjs` for the local site and honest unconnected feed responses. Run `node --test tests/feed-api.test.mjs` for API transport and validation checks. Site publishing uses the supported Sites source workflow and packaging helpers. +Run `node scripts/preview.mjs` for the local site and honest unconnected feed responses. Run `node --test tests/*.test.mjs` for API transport and validation checks. Site publishing uses the supported Sites source workflow and packaging helpers. See [DiscordSRV feed setup](DISCORD-FEEDS.md) for the optional DuneCore 1.0.9 bridge, required server-side secret names, channel setup and snapshot protocol. No credentials are committed or delivered to the browser. Feed data is read-only; trades stay inside Minecraft. -Art is reused from the Project Dune manual and optimized into WebP. Concept-art claims are identified on the page. No game server address or live market records are invented. The website retains the Site's owner-private audience until changed explicitly. +Art is reused from the Project Dune manual and optimized into WebP. Concept-art claims are identified on the page. No game server address or live market records are invented. The website is public. Private portal data requires sign-in and server-side authorisation. + +See [Forums and player support](FORUMS-PORTAL.md) for independent forums, the YouSMP Discord page and private profile-based tickets. + diff --git a/website/drizzle/0000_forums.sql b/website/drizzle/0000_forums.sql new file mode 100644 index 00000000..6b190c7b --- /dev/null +++ b/website/drizzle/0000_forums.sql @@ -0,0 +1,41 @@ +CREATE TABLE forum_topics ( + id TEXT PRIMARY KEY NOT NULL, + category TEXT NOT NULL CHECK(category IN ('help','gameplay','lore','feedback')), + title TEXT NOT NULL, + body TEXT NOT NULL, + author_id TEXT NOT NULL, + author_name TEXT NOT NULL, + created_at INTEGER NOT NULL, + last_activity_at INTEGER NOT NULL, + closed INTEGER NOT NULL DEFAULT 0, + deleted INTEGER NOT NULL DEFAULT 0 +); +--> statement-breakpoint +CREATE INDEX forum_topics_activity ON forum_topics(deleted,last_activity_at); +--> statement-breakpoint +CREATE INDEX forum_topics_author ON forum_topics(author_id,created_at); +--> statement-breakpoint +CREATE TABLE forum_posts ( + id TEXT PRIMARY KEY NOT NULL, + topic_id TEXT NOT NULL REFERENCES forum_topics(id), + body TEXT NOT NULL, + author_id TEXT NOT NULL, + author_name TEXT NOT NULL, + created_at INTEGER NOT NULL, + deleted INTEGER NOT NULL DEFAULT 0 +); +--> statement-breakpoint +CREATE INDEX forum_posts_topic ON forum_posts(topic_id,deleted,created_at); +--> statement-breakpoint +CREATE INDEX forum_posts_author ON forum_posts(author_id,created_at); +--> statement-breakpoint +CREATE TABLE forum_reports ( + id TEXT PRIMARY KEY NOT NULL, + target_type TEXT NOT NULL CHECK(target_type IN ('topic','post')), + target_id TEXT NOT NULL, + reporter_id TEXT NOT NULL, + reason TEXT NOT NULL, + created_at INTEGER NOT NULL, + resolved INTEGER NOT NULL DEFAULT 0, + UNIQUE(target_type,target_id,reporter_id) +); diff --git a/website/drizzle/0001_profiles_tickets.sql b/website/drizzle/0001_profiles_tickets.sql new file mode 100644 index 00000000..69a0e64f --- /dev/null +++ b/website/drizzle/0001_profiles_tickets.sql @@ -0,0 +1,37 @@ +CREATE TABLE player_profiles ( + user_id TEXT PRIMARY KEY NOT NULL, + display_name TEXT NOT NULL, + minecraft_name TEXT NOT NULL DEFAULT '', + discord_name TEXT NOT NULL DEFAULT '', + created_at INTEGER NOT NULL, + updated_at INTEGER NOT NULL +); +--> statement-breakpoint +CREATE TABLE support_tickets ( + id TEXT PRIMARY KEY NOT NULL, + user_id TEXT NOT NULL REFERENCES player_profiles(user_id), + category TEXT NOT NULL CHECK(category IN ('ban-appeal','staff-support')), + subject TEXT NOT NULL, + body TEXT NOT NULL, + status TEXT NOT NULL DEFAULT 'open' CHECK(status IN ('open','in_progress','waiting_on_player','resolved','closed')), + created_at INTEGER NOT NULL, + updated_at INTEGER NOT NULL +); +--> statement-breakpoint +CREATE INDEX support_tickets_owner ON support_tickets(user_id,updated_at); +--> statement-breakpoint +CREATE INDEX support_tickets_status ON support_tickets(status,updated_at); +--> statement-breakpoint +CREATE TABLE support_messages ( + id TEXT PRIMARY KEY NOT NULL, + ticket_id TEXT NOT NULL REFERENCES support_tickets(id), + author_id TEXT NOT NULL, + author_name TEXT NOT NULL, + author_role TEXT NOT NULL CHECK(author_role IN ('player','staff','system')), + body TEXT NOT NULL, + created_at INTEGER NOT NULL +); +--> statement-breakpoint +CREATE INDEX support_messages_ticket ON support_messages(ticket_id,created_at); +--> statement-breakpoint +CREATE INDEX support_messages_author ON support_messages(author_id,created_at); diff --git a/website/drizzle/meta/_journal.json b/website/drizzle/meta/_journal.json new file mode 100644 index 00000000..2609ad3b --- /dev/null +++ b/website/drizzle/meta/_journal.json @@ -0,0 +1 @@ +{"version":"7","dialect":"sqlite","entries":[{"idx":0,"version":"6","when":1791892800000,"tag":"0000_forums","breakpoints":true},{"idx":1,"version":"6","when":1791896400000,"tag":"0001_profiles_tickets","breakpoints":true}]} diff --git a/website/package.json b/website/package.json index f307d713..6af6e018 100644 --- a/website/package.json +++ b/website/package.json @@ -1 +1,9 @@ -{"name":"project-dune-website","private":true,"type":"module","scripts":{"build":"node scripts/build.mjs","test":"node --test tests/feed-api.test.mjs"}} +{ + "name": "project-dune-website", + "private": true, + "type": "module", + "scripts": { + "build": "node scripts/build.mjs", + "test": "node --test tests/*.test.mjs" + } +} diff --git a/website/scripts/build.mjs b/website/scripts/build.mjs index 971d259c..687e36f1 100644 --- a/website/scripts/build.mjs +++ b/website/scripts/build.mjs @@ -2,6 +2,7 @@ import {readFileSync,writeFileSync,readdirSync,statSync,mkdirSync,existsSync,rmS const root=path.resolve(path.dirname(fileURLToPath(import.meta.url)),'..'),web=path.join(root,'web'),dist=path.join(root,'dist'); const assets={};const types={'.html':'text/html; charset=utf-8','.css':'text/css; charset=utf-8','.js':'text/javascript; charset=utf-8','.json':'application/json; charset=utf-8','.webp':'image/webp','.svg':'image/svg+xml'}; function collect(directory){for(const entry of readdirSync(directory)){const p=path.join(directory,entry);if(statSync(p).isDirectory())collect(p);else{const type=types[path.extname(entry)];if(!type)throw Error('Unexpected asset: '+entry);assets['/'+path.relative(web,p).split(path.sep).join('/')]=[type,readFileSync(p).toString('base64')]}}}collect(web); -let api=readFileSync(path.join(root,'worker/feed-api.mjs'),'utf8').replace(/export /g,'');let runtime=readFileSync(path.join(root,'worker/runtime.mjs'),'utf8').replace("import {handleFeed} from './feed-api.mjs';",''); +let api=['feed-api.mjs','forum-api.mjs','community-api.mjs','portal-api.mjs'].map(file=>readFileSync(path.join(root,'worker',file),'utf8').replace(/export /g,'')).join('\n');let runtime=readFileSync(path.join(root,'worker/runtime.mjs'),'utf8').replace(/^import .*;$/gm,''); if(existsSync(dist)){const resolved=path.resolve(dist);if(resolved!==path.join(root,'dist'))throw Error('Invalid dist directory');rmSync(resolved,{recursive:true,force:true})} mkdirSync(path.join(dist,'server'),{recursive:true});mkdirSync(path.join(dist,'.openai'),{recursive:true});writeFileSync(path.join(dist,'server/index.js'),'const ASSET_DATA='+JSON.stringify(assets)+';\n'+api+'\n'+runtime);cpSync(path.join(root,'.openai/hosting.json'),path.join(dist,'.openai/hosting.json'));console.log('Built Worker with',Object.keys(assets).length,'embedded website assets'); +if(existsSync(path.join(root,'drizzle')))cpSync(path.join(root,'drizzle'),path.join(dist,'.openai/drizzle'),{recursive:true}); diff --git a/website/tests/d1-adapter.mjs b/website/tests/d1-adapter.mjs new file mode 100644 index 00000000..5c36271e --- /dev/null +++ b/website/tests/d1-adapter.mjs @@ -0,0 +1,7 @@ +import {DatabaseSync} from 'node:sqlite'; +export class LocalD1 { + constructor(schema,filename=':memory:'){this.sqlite=new DatabaseSync(filename);this.sqlite.exec('PRAGMA foreign_keys=ON');if(schema)this.sqlite.exec(schema)} + prepare(sql){const db=this.sqlite;let values=[];return {bind(...args){values=args;return this},async first(){return db.prepare(sql).get(...values)||null},async all(){return {results:db.prepare(sql).all(...values)}},async run(){const r=db.prepare(sql).run(...values);return {success:true,meta:{changes:Number(r.changes)}}}}} + async batch(statements){this.sqlite.exec('BEGIN');try{const results=[];for(const s of statements)results.push(await s.run());this.sqlite.exec('COMMIT');return results}catch(error){this.sqlite.exec('ROLLBACK');throw error}} + close(){this.sqlite.close()} +} diff --git a/website/tests/forum-api.test.mjs b/website/tests/forum-api.test.mjs new file mode 100644 index 00000000..f74f47a8 --- /dev/null +++ b/website/tests/forum-api.test.mjs @@ -0,0 +1,10 @@ +import test from 'node:test';import assert from 'node:assert/strict';import {readFileSync,mkdtempSync,rmSync} from 'node:fs';import {tmpdir} from 'node:os';import path from 'node:path';import {handleForum} from '../worker/forum-api.mjs';import {LocalD1} from './d1-adapter.mjs'; +const schema=readFileSync(new URL('../drizzle/0000_forums.sql',import.meta.url),'utf8'); +function request(endpoint,{user,method='GET',body,origin='https://example.test',email}={}){return new Request('https://example.test/api/forum'+endpoint,{method,headers:{'Content-Type':'application/json',Origin:origin,...(user?{'oai-authenticated-user-id':user}:{}),...(email?{'oai-authenticated-user-email':email}:{})},...(body?{body:JSON.stringify(body)}:{})})} +async function create(env){const r=await handleForum(request('/topics',{user:'alice',method:'POST',body:{title:'An Arrakis expedition',body:'How should I prepare my first stillsuit?',displayName:'Alice',category:'help'}}),env);assert.equal(r.status,201);return (await r.json()).id} +test('Anonymous readers can browse but cannot post',async()=>{const DB=new LocalD1(schema);try{const list=await handleForum(request('/topics'),{DB});assert.deepEqual((await list.json()).topics,[]);const r=await handleForum(request('/topics',{method:'POST',body:{}}),{DB});assert.equal(r.status,401)}finally{DB.close()}}); +test('Topics and replies persist, with public identity IDs excluded',async()=>{const directory=mkdtempSync(path.join(tmpdir(),'dune-forum-test-')),file=path.join(directory,'forum.sqlite');let DB=new LocalD1(schema,file);try{const id=await create({DB});const reply=await handleForum(request('/topics/'+id+'/replies',{user:'bob',method:'POST',body:{displayName:'Bob',body:'Equip all four tagged pieces.'}}),{DB});assert.equal(reply.status,201);DB.close();DB=new LocalD1(null,file);const response=await handleForum(request('/topics/'+id),{DB});const data=await response.json();assert.equal(data.replies.length,1);assert.equal(data.replies[0].body,'Equip all four tagged pieces.');assert.equal(data.topic.canManage,false);assert.ok(!JSON.stringify(data).includes('author_id'))}finally{DB.close();rmSync(directory,{recursive:true,force:true})}}); +test('Cross-site writes and forged management attempts fail',async()=>{const DB=new LocalD1(schema);try{const id=await create({DB});assert.equal((await handleForum(request('/topics/'+id,{method:'DELETE',user:'bob'}),{DB})).status,403);assert.equal((await handleForum(request('/topics',{method:'POST',user:'bob',origin:'https://other.test',body:{}}),{DB})).status,403)}finally{DB.close()}}); +test('Closed topics reject replies and can be reopened by their owner',async()=>{const DB=new LocalD1(schema);try{const id=await create({DB});assert.equal((await handleForum(request('/topics/'+id+'/close',{method:'POST',user:'alice',body:{closed:true}}),{DB})).status,200);const reply=await handleForum(request('/topics/'+id+'/replies',{user:'bob',method:'POST',body:{body:'Test reply',displayName:'Bob'}}),{DB});assert.equal(reply.status,409);assert.equal((await handleForum(request('/topics/'+id+'/close',{method:'POST',user:'alice',body:{closed:false}}),{DB})).status,200)}finally{DB.close()}}); +test('Post validation, rate limits and parameterized search resist abuse',async()=>{const DB=new LocalD1(schema);try{await create({DB});const second=await handleForum(request('/topics',{user:'alice',method:'POST',body:{title:'Another topic',body:'A second post too soon.',displayName:'Alice',category:'help'}}),{DB});assert.equal(second.status,429);assert.equal((await handleForum(request('/topics',{user:'bob',method:'POST',body:{title:'x',body:'Short',displayName:'Bob',category:'help'}}),{DB})).status,400);const search=await handleForum(request('/topics?q='+encodeURIComponent("' OR 1=1 --")),{DB});assert.deepEqual((await search.json()).topics,[])}finally{DB.close()}}); +test('Reports are visible only to moderators; removal hides rather than erases',async()=>{const DB=new LocalD1(schema),env={DB,FORUM_ADMIN_EMAILS:'owner@example.invalid'};try{const id=await create(env);const report=await handleForum(request('/reports',{user:'bob',method:'POST',body:{targetType:'topic',targetId:id,reason:'Please review this topic.'}}),env);assert.equal(report.status,201);assert.equal((await handleForum(request('/reports',{user:'bob'}),env)).status,403);const moderator={user:'owner',email:'owner@example.invalid'};const reports=await handleForum(request('/reports',moderator),env);assert.equal((await reports.json()).reports.length,1);assert.equal((await handleForum(request('/topics/'+id,{...moderator,method:'DELETE'}),env)).status,200);assert.equal((await handleForum(request('/topics/'+id),env)).status,404);assert.equal(DB.sqlite.prepare('SELECT deleted FROM forum_topics WHERE id=?').get(id).deleted,1)}finally{DB.close()}}); diff --git a/website/tests/portal-api.test.mjs b/website/tests/portal-api.test.mjs new file mode 100644 index 00000000..65a9c6b4 --- /dev/null +++ b/website/tests/portal-api.test.mjs @@ -0,0 +1,11 @@ +import test from 'node:test';import assert from 'node:assert/strict';import {readFileSync,mkdtempSync,rmSync} from 'node:fs';import {tmpdir} from 'node:os';import path from 'node:path';import {LocalD1} from './d1-adapter.mjs';import {handlePortal} from '../worker/portal-api.mjs'; +const schema=['0000_forums','0001_profiles_tickets'].map(n=>readFileSync(new URL('../drizzle/'+n+'.sql',import.meta.url),'utf8')).join('\n'); +function req(endpoint,user='alice',method='GET',body,email,origin='https://example.test'){return new Request('https://example.test/api/'+endpoint,{method,headers:{'Content-Type':'application/json',Origin:origin,...(user?{'oai-authenticated-user-id':user}:{}),...(email?{'oai-authenticated-user-email':email}:{})},...(body!==undefined?{body:JSON.stringify(body)}:{})})} +const profile={displayName:'Alice',minecraftName:'DesertPlayer',discordName:'OptionalHandle'}; +async function setup(env){assert.equal((await handlePortal(req('profile','alice','POST',profile),env)).status,200);const r=await handlePortal(req('tickets','alice','POST',{category:'ban-appeal',subject:'Please review my ban',body:'I would like staff to review the reason for my ban.'}),env);assert.equal(r.status,201);return (await r.json()).id} +test('Portal data requires authentication and same-origin writes',async()=>{const DB=new LocalD1(schema);try{assert.equal((await handlePortal(req('profile',null),{DB})).status,401);assert.equal((await handlePortal(req('profile','alice','POST',profile,null,'https://evil.test'),{DB})).status,403);assert.equal((await handlePortal(req('profile','alice','POST',null),{DB})).status,400)}finally{DB.close()}}); +test('Tickets are tied to profiles and appeals require a Minecraft name',async()=>{const DB=new LocalD1(schema);try{const body={category:'ban-appeal',subject:'Review my account ban',body:'Here is my explanation for staff review.'};assert.equal((await handlePortal(req('tickets','alice','POST',body),{DB})).status,422);await handlePortal(req('profile','alice','POST',{...profile,minecraftName:''}),{DB});assert.equal((await handlePortal(req('tickets','alice','POST',body),{DB})).status,422);body.category='staff-support';assert.equal((await handlePortal(req('tickets','alice','POST',body),{DB})).status,201)}finally{DB.close()}}); +test('Other players cannot read or alter a private ticket',async()=>{const DB=new LocalD1(schema);try{const id=await setup({DB});assert.equal((await handlePortal(req('tickets/'+id,'bob'),{DB})).status,404);assert.equal((await handlePortal(req('tickets/'+id+'/replies','bob','POST',{body:'Forged reply'}),{DB})).status,404);assert.equal((await handlePortal(req('tickets/'+id+'/status','bob','POST',{status:'closed'}),{DB})).status,404);assert.deepEqual((await (await handlePortal(req('tickets','bob'),{DB})).json()).tickets,[]);assert.equal((await handlePortal(req('tickets?view=staff','bob'),{DB})).status,403);const own=await (await handlePortal(req('tickets/'+id),{DB})).json();assert.ok(!JSON.stringify(own).includes('user_id'));assert.equal(own.ticket.minecraft_name,'DesertPlayer')}finally{DB.close()}}); +test('Only authorised staff can triage; replies carry verified staff roles',async()=>{const DB=new LocalD1(schema),env={DB,SUPPORT_STAFF_EMAILS:'staff@example.invalid'};try{const id=await setup(env);assert.equal((await handlePortal(req('tickets/'+id+'/status','alice','POST',{status:'resolved'}),env)).status,403);assert.equal((await handlePortal(req('tickets/'+id+'/status','moderator','POST',{status:'in_progress'},'staff@example.invalid'),env)).status,200);assert.equal((await handlePortal(req('tickets/'+id+'/replies','moderator','POST',{body:'We are reviewing your case.',author_role:'player'},'staff@example.invalid'),env)).status,201);const data=await (await handlePortal(req('tickets/'+id),env)).json();assert.equal(data.ticket.status,'in_progress');assert.equal(data.messages.find(m=>m.body==='We are reviewing your case.').author_role,'staff');assert.equal((await (await handlePortal(req('tickets?view=staff','moderator','GET',undefined,'staff@example.invalid'),env)).json()).tickets.length,1)}finally{DB.close()}}); +test('Owners close and reopen tickets; closed cases block replies and rate limits apply',async()=>{const DB=new LocalD1(schema),env={DB};try{const id=await setup(env);await handlePortal(req('tickets/'+id+'/status','alice','POST',{status:'closed'}),env);assert.equal((await handlePortal(req('tickets/'+id+'/replies','alice','POST',{body:'Hello again'}),env)).status,409);await handlePortal(req('tickets/'+id+'/status','alice','POST',{status:'open'}),env);for(let i=0;i<5;i++)assert.equal((await handlePortal(req('tickets/'+id+'/replies','alice','POST',{body:'Reply number '+i}),env)).status,201);assert.equal((await handlePortal(req('tickets/'+id+'/replies','alice','POST',{body:'Too many replies'}),env)).status,429)}finally{DB.close()}}); +test('Private profiles and ticket history persist after database restart',async()=>{const dir=mkdtempSync(path.join(tmpdir(),'dune-tickets-')),file=path.join(dir,'db.sqlite');let DB=new LocalD1(schema,file);try{const id=await setup({DB});DB.close();DB=new LocalD1(null,file);assert.equal((await (await handlePortal(req('tickets/'+id),{DB})).json()).ticket.subject,'Please review my ban');assert.equal((await (await handlePortal(req('tickets'),{DB})).json()).activeCount,1);assert.equal((await (await handlePortal(req('profile','bob'),{DB})).json()).profile,null)}finally{DB.close();rmSync(dir,{recursive:true,force:true})}}); diff --git a/website/tests/worker.test.mjs b/website/tests/worker.test.mjs index 9a5dc432..a2b02dae 100644 --- a/website/tests/worker.test.mjs +++ b/website/tests/worker.test.mjs @@ -1,4 +1,4 @@ import test from 'node:test';import assert from 'node:assert/strict';import worker from '../dist/server/index.js'; -test('Built Worker serves all ten separate pages and site assets',async()=>{for(const path of ['/','/arrakis.html','/smugglers.html','/equipment.html','/admin.html','/install.html','/manual.html','/races.html','/exchange.html','/news.html','/manual-data.json','/assets/item-0.webp']){const response=await worker.fetch(new Request('https://example.test'+path),{});assert.equal(response.status,200,path);assert.ok((await response.arrayBuffer()).byteLength>0,path)}}); +test('Built Worker serves all fifteen separate pages and site assets',async()=>{for(const path of ['/','/arrakis.html','/smugglers.html','/equipment.html','/admin.html','/install.html','/manual.html','/races.html','/exchange.html','/news.html','/forums.html','/discord.html','/portal.html','/profile.html','/tickets.html','/manual-data.json','/assets/item-0.webp']){const response=await worker.fetch(new Request('https://example.test'+path),{});assert.equal(response.status,200,path);assert.ok((await response.arrayBuffer()).byteLength>0,path)}}); test('Built Worker retains unconnected feed state without leaking secrets',async()=>{const response=await worker.fetch(new Request('https://example.test/api/news'),{});const text=await response.text();assert.equal(JSON.parse(text).status,'not_connected');assert.ok(!text.includes('DISCORD_BOT_TOKEN'))}); test('Unsupported paths and write requests are rejected',async()=>{assert.equal((await worker.fetch(new Request('https://example.test/missing'),{})).status,404);assert.equal((await worker.fetch(new Request('https://example.test/api/exchange',{method:'POST'}),{})).status,405)}); diff --git a/website/web/admin.html b/website/web/admin.html index 7f5cec53..bd9d003a 100644 --- a/website/web/admin.html +++ b/website/web/admin.html @@ -1 +1 @@ -Admin tools — Project Dune
✦ PROJECT DUNEMINECRAFT REALMS

PROJECT DUNE / MINECRAFT REALMS

Admin tools

The Imperial Scepter. Your operator controls for the worlds and their inhabitants.

An Imperial administrator with a glowing scepter beside Guild and smuggler NPCs

04 / KEEPERS OF THE REALMS

Your world.
Your command.

Operators receive the Imperial Admin Scepter automatically. Right-click the modified blaze rod to open the administration GUI.

  • Summon a sandworm at your position or coordinates.
  • Place Guild Navigators and Arrakis smugglers.
  • Manage NPCs, view active contracts and return to the main admin menu.
  • Access spice bloom tools, kits, menus and politics.

GUI controls require operator status. Sandworm summoning uses the dune.admin permission.

\ No newline at end of file +Admin tools — Project Dune
✦ PROJECT DUNEMINECRAFT REALMS

PROJECT DUNE / MINECRAFT REALMS

Admin tools

The Imperial Scepter. Your operator controls for the worlds and their inhabitants.

An Imperial administrator with a glowing scepter beside Guild and smuggler NPCs

04 / KEEPERS OF THE REALMS

Your world.
Your command.

Operators receive the Imperial Admin Scepter automatically. Right-click the modified blaze rod to open the administration GUI.

  • Summon a sandworm at your position or coordinates.
  • Place Guild Navigators and Arrakis smugglers.
  • Manage NPCs, view active contracts and return to the main admin menu.
  • Access spice bloom tools, kits, menus and politics.

GUI controls require operator status. Sandworm summoning uses the dune.admin permission.

\ No newline at end of file diff --git a/website/web/arrakis.html b/website/web/arrakis.html index 0295b23a..0e39d40c 100644 --- a/website/web/arrakis.html +++ b/website/web/arrakis.html @@ -1 +1 @@ -Arrakis — Project Dune
✦ PROJECT DUNEMINECRAFT REALMS

PROJECT DUNE / MINECRAFT REALMS

Arrakis

The desert world. Spice, survival, sietches and Shai-Hulud.

01 / ARRAKIS FIELD NOTES

Nothing here
comes easily.

Water is precious. Spice is power. Every expedition begins with a stillsuit and ends with a story.

A Minecraft-inspired spice harvesting expedition among Arrakis rock formations
MELANGE AMONG THE TERRACES / ARRAKIS
01

Walk a living desert

Dunes, oasis trees, cave sietches and darkstone formations up to three plateaus high. Find shelter before the Arrakis sun finds you.

02

Harvest the wealth of worlds

Use the tagged Spice Harvest Shovel to collect melange. Sell for Solaris, fill CHOAM quotas, or work a player-sponsored spice contract.

03

Prepare for Shai-Hulud

A desert-skinned Sniffer carries the sandworm’s form, with native zombie AI. Survive the encounter; its death leaves a rich spice field.

✦

A WORD FROM THE SPACING GUILD

A sighting begins with coordinates on Arrakis. Fifteen real minutes later, the Guild announces it across the proxy network.

15 MINUTES
A colossal block-built sandworm rising through Arrakis dunes

THE MAKER BENEATH THE SAND

Respect the desert.
It remembers.

Watch the sightings. Prepare for the encounter.
The dunes are never truly empty.

\ No newline at end of file +Arrakis — Project Dune
✦ PROJECT DUNEMINECRAFT REALMS

PROJECT DUNE / MINECRAFT REALMS

Arrakis

The desert world. Spice, survival, sietches and Shai-Hulud.

01 / ARRAKIS FIELD NOTES

Nothing here
comes easily.

Water is precious. Spice is power. Every expedition begins with a stillsuit and ends with a story.

A Minecraft-inspired spice harvesting expedition among Arrakis rock formations
MELANGE AMONG THE TERRACES / ARRAKIS
01

Walk a living desert

Dunes, oasis trees, cave sietches and darkstone formations up to three plateaus high. Find shelter before the Arrakis sun finds you.

02

Harvest the wealth of worlds

Use the tagged Spice Harvest Shovel to collect melange. Sell for Solaris, fill CHOAM quotas, or work a player-sponsored spice contract.

03

Prepare for Shai-Hulud

A desert-skinned Sniffer carries the sandworm’s form, with native zombie AI. Survive the encounter; its death leaves a rich spice field.

✦

A WORD FROM THE SPACING GUILD

A sighting begins with coordinates on Arrakis. Fifteen real minutes later, the Guild announces it across the proxy network.

15 MINUTES
A colossal block-built sandworm rising through Arrakis dunes

THE MAKER BENEATH THE SAND

Respect the desert.
It remembers.

Watch the sightings. Prepare for the encounter.
The dunes are never truly empty.

\ No newline at end of file diff --git a/website/web/community.css b/website/web/community.css new file mode 100644 index 00000000..ce22e577 --- /dev/null +++ b/website/web/community.css @@ -0,0 +1,3 @@ +.banner-menu{grid-template-columns:repeat(6,minmax(0,1fr))}.intro-community{background-image:linear-gradient(90deg,#0e1f16ed,#0e1f1688),url('assets/guild.webp')}.forum-section,.discord-section{padding:55px 6% 75px;max-width:1500px;margin:auto}.forum-toolbar{display:flex;justify-content:space-between;align-items:end;gap:20px;flex-wrap:wrap}.forum-account{display:flex;gap:15px;align-items:center}.forum-account .button{padding:13px 18px}.forum-action{background:#233b29;color:var(--gold);padding:9px 13px;border:2px solid #8b7946;font-size:11px;box-shadow:2px 3px 0 #09180f}.forum-account [hidden],#forum-more[hidden]{display:none}.forum-topic-list{display:grid;gap:14px}.forum-topic-card{display:flex;align-items:center;gap:22px;border:3px solid #817044;padding:23px;background:#243b2a;box-shadow:inset 2px 2px 0 #566343,4px 5px 0 #07120b}.forum-topic-card:hover{border-color:var(--gold);background:#30472f}.forum-topic-icon{font-family:VT323,monospace;font-size:44px;color:var(--gold)}.forum-topic-card h3{font-size:33px;margin:8px 0 7px;overflow-wrap:anywhere}.forum-topic-card p{font-size:10px;color:var(--muted);margin:0}.forum-tag{font-size:8px;letter-spacing:.12em;color:var(--gold)}.forum-reply-count{margin-left:auto;font-family:VT323,monospace;font-size:38px;color:var(--gold);text-align:center;min-width:45px}.forum-reply-count small{font:9px Manrope,Arial,sans-serif;display:block}.forum-rules{margin-top:45px;border-top:2px solid var(--line);padding-top:25px;color:var(--muted);font-size:12px;max-width:880px}.forum-rules h3{color:var(--gold);font-size:31px}.forum-rules a{color:var(--gold)}.forum-post{margin:25px 0;padding:30px;background:#ebdcba;color:#233921;border:4px solid #ab8c4e;box-shadow:inset 2px 2px 0 #fff2d1,4px 5px 0 #07140b}.forum-original{background:linear-gradient(#f2e4c6ee,#f2e4c6f3),url('assets/ornament.webp') center/cover}.forum-original h2{font-size:55px;overflow-wrap:anywhere;text-shadow:2px 2px 0 #b29a6850}.forum-original .eyebrow{color:#8c6227;margin-bottom:15px}.forum-meta{font-size:10px;color:#655e42}.forum-message{white-space:pre-wrap;overflow-wrap:anywhere;font-size:14px;line-height:1.85}.forum-post-actions{display:flex;gap:13px;margin-top:24px;flex-wrap:wrap}.forum-post-actions .forum-action{font-size:10px;background:#cfbc8b;color:#3b4426;box-shadow:2px 2px 0 #a99260}.forum-reply-form{padding:28px;border:3px solid #8d7a48;background:#213724;margin-top:32px;max-width:950px}.forum-reply-form h3{color:var(--gold)}.forum-reply-form p{font-size:10px;color:var(--muted)}.forum-reply-form label,dialog label{display:flex;flex-direction:column;gap:8px;font-size:11px;color:var(--gold);margin:17px 0}.forum-reply-form input,.forum-reply-form textarea,dialog input,dialog textarea,dialog select{font:13px Manrope,Arial,sans-serif;background:#102319;color:var(--paper);border:3px solid #667252;padding:12px;box-shadow:inset 2px 2px 0 #07150c;width:100%;border-radius:0;resize:vertical}.forum-reply-form input{max-width:350px}.forum-reply-form button:disabled,dialog button:disabled{opacity:.55;cursor:wait}dialog{background:#1b3425;color:var(--paper);border:5px solid #ba9853;box-shadow:inset 2px 2px 0 #8f985a,7px 8px 0 #04140d;padding:30px;width:min(650px,90vw);max-height:90vh;overflow:auto}dialog::backdrop{background:#04130cd9}.dialog-heading{display:flex;align-items:start;gap:20px;justify-content:space-between}.dialog-heading h2{font-size:46px;color:var(--gold);margin-bottom:8px}.dialog-heading button{font-size:26px;line-height:1;background:#253f2c;color:var(--gold);border:2px solid #927d41;padding:5px 10px}dialog p{font-size:11px;color:var(--muted)}#new-topic-error{color:#ffd099}.discord-panel{display:grid;grid-template-columns:1fr 1.15fr;background:#213928;border:4px solid #9b8247;box-shadow:5px 7px 0 #05140b;gap:0}.discord-community-art{position:relative;min-height:420px}.discord-community-art img{width:100%;height:100%;object-fit:cover}.discord-community-art span{position:absolute;bottom:25px;left:25px;right:25px;background:#112918e8;padding:17px;text-align:center;border:2px solid #a08a4f;font:22px VT323,monospace;color:var(--gold)}.discord-community-copy{padding:38px}.discord-community-copy h2{font-size:80px}.discord-community-copy>p:not(.eyebrow){font-size:13px;color:var(--muted)}.discord-stats{display:flex;gap:38px;margin:28px 0}.discord-stats strong{display:block;font:52px VT323,monospace;color:var(--gold);line-height:1}.discord-stats span{font-size:8px;letter-spacing:.15em}.discord-community-copy #discord-state{font-size:10px}.discord-join{background:linear-gradient(#7780ed,#535bbb);color:#fff8dc;border-color:#929ae6;box-shadow:inset 2px 2px 0 #c5cafd66,3px 4px 0 #141b38}.discord-join:hover{background:#7881e4}.community-links{display:grid;grid-template-columns:repeat(3,1fr);gap:25px;margin-top:40px}.community-links article{border:3px solid #7f7546;padding:27px;background:#203725;box-shadow:3px 4px 0 #04160b}.community-links img{width:55px;height:55px;margin-bottom:23px}.community-links h3{font-size:34px}.community-links p{font-size:12px;color:var(--muted)}@media(max-width:1100px){.banner-menu{grid-template-columns:repeat(3,minmax(0,1fr))}.discord-community-copy{padding:28px}.discord-panel{grid-template-columns:1fr 1.15fr}}@media(max-width:720px){.forum-section,.discord-section{padding:32px 7% 55px}.forum-topic-card{padding:18px 13px;gap:13px}.forum-topic-icon{display:none}.forum-topic-card h3{font-size:29px}.forum-topic-card p{font-size:9px}.forum-post{padding:23px 19px}.forum-original h2{font-size:44px}.forum-message{font-size:13px}.forum-reply-form{padding:22px 17px}.forum-reply-form input{max-width:none}.discord-panel{grid-template-columns:1fr}.discord-community-art{min-height:220px;height:240px}.discord-community-art span{font-size:20px}.discord-community-copy{padding:28px 22px}.discord-community-copy h2{font-size:73px}.community-links{grid-template-columns:1fr}.dialog-heading h2{font-size:39px}dialog{padding:23px 19px}}@media(max-width:600px){.banner-menu{grid-template-columns:repeat(2,minmax(0,1fr))}} + +.intro-community h1{font-size:clamp(58px,7vw,100px);overflow-wrap:anywhere} diff --git a/website/web/discord.html b/website/web/discord.html new file mode 100644 index 00000000..b335f90d --- /dev/null +++ b/website/web/discord.html @@ -0,0 +1 @@ +YouSMP Discord — Project Dune
✦ PROJECT DUNEMINECRAFT REALMS

PROJECT DUNE / COMMUNITY

YouSMP Discord

Meet the community beyond the dunes.

Minecraft-inspired Dune sietch and underground reservoirY O U S M P / C O M M U N I T Y

THE YOUsMP DISCORD COMMUNITY

YouSMP

Meet the YouSMP community, talk about the network and find other players. The Discord community and this website's discussion forum are separate.

—MEMBERS
—ONLINE

Checking the Discord community…

\ No newline at end of file diff --git a/website/web/discord.js b/website/web/discord.js new file mode 100644 index 00000000..5fdc872f --- /dev/null +++ b/website/web/discord.js @@ -0,0 +1 @@ +fetch('/api/community').then(r=>r.json()).then(data=>{document.querySelector('#discord-name').textContent=data.name||'YouSMP';if(data.status==='connected'){document.querySelector('#discord-state').textContent='YouSMP Discord · Invite verified';document.querySelector('#discord-members').textContent=data.memberCount.toLocaleString();document.querySelector('#discord-online').textContent=data.onlineCount.toLocaleString()}else document.querySelector('#discord-state').textContent='Discord counts are temporarily unavailable.'}).catch(()=>document.querySelector('#discord-state').textContent='Discord counts are temporarily unavailable.'); diff --git a/website/web/equipment.html b/website/web/equipment.html index 640e8ac5..6dd73cd7 100644 --- a/website/web/equipment.html +++ b/website/web/equipment.html @@ -1 +1 @@ -Equipment — Project Dune
✦ PROJECT DUNEMINECRAFT REALMS

PROJECT DUNE / MINECRAFT REALMS

Equipment

Tagged stillsuits, harvest tools and an inventory ready for the dunes.

THE INVENTORY / EQUIP YOUR EXPEDITION

Every slot
tells a story.

Familiar Minecraft materials. Dune rules, tagged equipment, and a purpose for every piece of your kit.

Select an item to open its manual chapter. Illustrated icons are reference art; in-game equipment uses the models and resource pack described in the guide.

Minecraft-inspired cave sietch with a supply chest and underground reservoir
SHELTER / THE HIDDEN SIETCH
Block-built Spacing Guild travel scene
TRAVEL / GUILD NAVIGATORS
Purple-lit desert smuggler camp with block-built sandstone
MISSIONS / WATER & SPICE
\ No newline at end of file +Equipment — Project Dune
✦ PROJECT DUNEMINECRAFT REALMS

PROJECT DUNE / MINECRAFT REALMS

Equipment

Tagged stillsuits, harvest tools and an inventory ready for the dunes.

THE INVENTORY / EQUIP YOUR EXPEDITION

Every slot
tells a story.

Familiar Minecraft materials. Dune rules, tagged equipment, and a purpose for every piece of your kit.

Select an item to open its manual chapter. Illustrated icons are reference art; in-game equipment uses the models and resource pack described in the guide.

Minecraft-inspired cave sietch with a supply chest and underground reservoir
SHELTER / THE HIDDEN SIETCH
Block-built Spacing Guild travel scene
TRAVEL / GUILD NAVIGATORS
Purple-lit desert smuggler camp with block-built sandstone
MISSIONS / WATER & SPICE
\ No newline at end of file diff --git a/website/web/exchange.html b/website/web/exchange.html index 0e6995ef..5ccdb164 100644 --- a/website/web/exchange.html +++ b/website/web/exchange.html @@ -1 +1 @@ -The Spice Exchange — Project Dune
✦ PROJECT DUNEMINECRAFT REALMS

LIVE REALM RECORDS / DISCORDSRV

The
Spice Exchange

Trade beyond the dunes.

Browse live buy and sell offers, and player-sponsored harvesting contracts. Listings come from the connected game server through DiscordSRV.

Checking the server connection…

✦

Opening the Guild records…

The current in-game exchange

Player-posted listings are spice harvesting contracts: 15% of earnings go to the worker, 85% to the sponsor. They are distinct from item sell orders. The normal spice sale is a standing sale to the economy at 15 Solaris per unit by default, with the Imperial bonus and Trust levy applied in game.

The website is a read-only market board. Complete trades or accept contracts inside Minecraft. It does not spend Solaris or hold items.

Read the exchange manual →
\ No newline at end of file +The Spice Exchange — Project Dune
✦ PROJECT DUNEMINECRAFT REALMS

LIVE REALM RECORDS / DISCORDSRV

The
Spice Exchange

Trade beyond the dunes.

Browse live buy and sell offers, and player-sponsored harvesting contracts. Listings come from the connected game server through DiscordSRV.

Checking the server connection…

✦

Opening the Guild records…

The current in-game exchange

Player-posted listings are spice harvesting contracts: 15% of earnings go to the worker, 85% to the sponsor. They are distinct from item sell orders. The normal spice sale is a standing sale to the economy at 15 Solaris per unit by default, with the Imperial bonus and Trust levy applied in game.

The website is a read-only market board. Complete trades or accept contracts inside Minecraft. It does not spend Solaris or hold items.

Read the exchange manual →
\ No newline at end of file diff --git a/website/web/forums.html b/website/web/forums.html new file mode 100644 index 00000000..f6cba9fd --- /dev/null +++ b/website/web/forums.html @@ -0,0 +1,5 @@ +Community forums — Project Dune
✦ PROJECT DUNEMINECRAFT REALMS

PROJECT DUNE / COMMUNITY

Community forums

Questions, expeditions, lore and ideas. Your own place in the sietch.

Opening the forum…

Opening the sietch records…

+

Start a discussion

Posted publicly to this website forum.

+ +

Report a post

+

Remove this post?

It will be hidden from the public forum.

\ No newline at end of file diff --git a/website/web/forums.js b/website/web/forums.js new file mode 100644 index 00000000..9ec18e63 --- /dev/null +++ b/website/web/forums.js @@ -0,0 +1,20 @@ +const forumRoot=document.querySelector('#forum-content'),forumStatus=document.querySelector('#forum-status');let forumSession={authenticated:false,moderator:false},forumOffset=null,forumTopic=null,forumPosts=[],forumSearchTimer; +const forumEl=(tag,text,cls)=>{const e=document.createElement(tag);if(text!==undefined)e.textContent=text;if(cls)e.className=cls;return e}; +async function forumRequest(path,options={}){const response=await fetch('/api/forum'+path,{...options,headers:{'Content-Type':'application/json',...(options.headers||{})},cache:'no-store'});const data=await response.json();if(!response.ok)throw Error(data.message||({forbidden:'You do not have permission to do that.',not_found:'This discussion is no longer available.',topic_closed:'This topic is closed.'}[data.error]||'The forum is temporarily unavailable.'));return data} +function forumNotice(message){const t=document.querySelector('.toast');t.textContent=message;t.classList.add('visible');clearTimeout(forumSearchTimer);forumSearchTimer=setTimeout(()=>t.classList.remove('visible'),3500)} +function forumDate(value){return new Date(value).toLocaleString()} +function forumButton(text,action,cls='forum-action'){const b=forumEl('button',text,cls);b.type='button';b.addEventListener('click',action);return b} +function forumEmpty(title,body){const box=forumEl('div',undefined,'feed-empty');box.append(forumEl('span','✦','seal'),forumEl('h2',title),forumEl('p',body));forumRoot.replaceChildren(box)} +function configureForumSession(){const signin=document.querySelector('#forum-signin'),newTopic=document.querySelector('#new-topic');signin.hidden=forumSession.authenticated;newTopic.hidden=!forumSession.authenticated;document.querySelector('#moderation-button').hidden=!forumSession.moderator;forumStatus.textContent=forumSession.authenticated?'Signed in · Topics and replies stay on this website':'Everyone can read · Sign in with ChatGPT to post';} +async function loadForumList(append=false){forumTopic=null;const category=document.querySelector('#forum-category').value,q=document.querySelector('#forum-search').value;try{const data=await forumRequest('/topics?'+new URLSearchParams({category,q,offset:append?forumOffset||0:0}));forumOffset=data.nextOffset;const list=append?document.querySelector('.forum-topic-list'):forumEl('div',undefined,'forum-topic-list');if(!append)forumRoot.replaceChildren(list);for(const topic of data.topics){const a=forumEl('a',undefined,'forum-topic-card');a.href='#topic='+topic.id;const icon=forumEl('span',topic.closed?'▣':'▤','forum-topic-icon');const text=forumEl('div');text.append(forumEl('span',document.querySelector(`#forum-category option[value="${topic.category}"]`)?.textContent||topic.category,'forum-tag'),forumEl('h3',topic.title),forumEl('p',`${topic.author_name} · ${forumDate(topic.created_at)}${topic.closed?' · Closed':''}`));const replies=forumEl('span',String(topic.replyCount),'forum-reply-count');replies.append(forumEl('small','replies'));a.append(icon,text,replies);list.append(a)}document.querySelector('#forum-more').hidden=forumOffset===null;if(!append&&!data.topics.length)forumEmpty(q?'No matching topics':'The sietch is quiet',q?'Try another search or category.':'Start the first discussion: share an expedition, ask for help or suggest a feature.')}catch(error){forumEmpty('Forum unavailable',error.message);document.querySelector('#forum-more').hidden=true}} +async function forumReport(type,id){if(!forumSession.authenticated){forumNotice('Sign in with ChatGPT to report a post.');return}document.querySelector('#report-type').value=type;document.querySelector('#report-target').value=id;document.querySelector('#report-form').reset();document.querySelector('#report-type').value=type;document.querySelector('#report-target').value=id;document.querySelector('#report-dialog').showModal()} +async function loadForumTopic(id,append=false){try{const data=await forumRequest('/topics/'+id+(append?'?offset='+forumOffset:''));forumTopic=data.topic;forumOffset=data.nextOffset;forumPosts=append?[...forumPosts,...data.replies]:data.replies;document.querySelector('#forum-more').hidden=true;forumRoot.replaceChildren();const back=forumEl('a','← All discussions','text-link');back.href='#';forumRoot.append(back);const root=forumEl('article',undefined,'forum-post forum-original');root.append(forumEl('p',document.querySelector(`#forum-category option[value="${forumTopic.category}"]`)?.textContent,'eyebrow'),forumEl('h2',forumTopic.title),forumEl('p',`${forumTopic.author_name} · ${forumDate(forumTopic.created_at)}${forumTopic.closed?' · Closed':''}`,'forum-meta'),forumEl('div',forumTopic.body,'forum-message'));const actions=forumEl('div',undefined,'forum-post-actions');if(forumSession.authenticated)actions.append(forumButton('Report',()=>forumReport('topic',id)));if(forumTopic.canManage){actions.append(forumButton(forumTopic.closed?'Reopen topic':'Close topic',async()=>{try{await forumRequest('/topics/'+id+'/close',{method:'POST',body:JSON.stringify({closed:!forumTopic.closed})});loadForumTopic(id)}catch(error){forumNotice(error.message)}}),forumButton('Remove topic',()=>openRemove('topic',id)))}root.append(actions);forumRoot.append(root);for(const post of forumPosts){const article=forumEl('article',undefined,'forum-post');article.append(forumEl('p',`${post.author_name} · ${forumDate(post.created_at)}`,'forum-meta'),forumEl('div',post.body,'forum-message'));const tools=forumEl('div',undefined,'forum-post-actions');if(forumSession.authenticated)tools.append(forumButton('Report',()=>forumReport('post',post.id)));if(post.canManage)tools.append(forumButton('Remove reply',()=>openRemove('post',post.id)));article.append(tools);forumRoot.append(article)}if(forumOffset!==null)forumRoot.append(forumButton('Load more replies',()=>loadForumTopic(id,true),'button'));if(!forumTopic.closed){if(forumSession.authenticated){const panel=document.querySelector('#reply-template').content.cloneNode(true);const form=panel.querySelector('form');form.querySelector('[name="displayName"]').value=localStorage.getItem('duneForumName')||'';form.addEventListener('submit',async e=>{e.preventDefault();const b=form.querySelector('button[type="submit"]');b.disabled=true;try{const values=Object.fromEntries(new FormData(form));await forumRequest('/topics/'+id+'/replies',{method:'POST',body:JSON.stringify(values)});localStorage.setItem('duneForumName',values.displayName);forumNotice('Reply posted.');loadForumTopic(id)}catch(error){forumNotice(error.message)}finally{b.disabled=false}});forumRoot.append(panel)}else{const sign=forumEl('a','Sign in with ChatGPT to reply','button gold');sign.href='/signin-with-chatgpt?return_to=%2Fforums.html';sign.target='_top';forumRoot.append(sign)}}}catch(error){forumEmpty('Discussion unavailable',error.message)}} +function openRemove(type,id){document.querySelector('#remove-type').value=type;document.querySelector('#remove-target').value=id;document.querySelector('#remove-dialog').showModal()} +async function loadModeration(){try{const data=await forumRequest('/reports');forumRoot.replaceChildren(forumEl('h2','Reported posts'));for(const report of data.reports){const row=forumEl('article',undefined,'forum-post');row.append(forumEl('p',`${report.target_type} · ${forumDate(report.created_at)}`,'forum-meta'),forumEl('p',report.reason,'forum-message'));const a=forumEl('a','Open discussion →','text-link');a.href='#topic='+report.topicId;row.append(a,forumButton('Mark reviewed',async()=>{try{await forumRequest('/reports/'+report.id+'/resolve',{method:'POST'});loadModeration()}catch(error){forumNotice(error.message)}}));forumRoot.append(row)}if(!data.reports.length)forumRoot.append(forumEl('p','No outstanding reports.'))}catch(error){forumNotice(error.message)}} +function navigateForum(){const match=location.hash.match(/^#topic=([0-9a-f-]+)$/i);if(match)loadForumTopic(match[1]);else loadForumList()} +document.querySelector('#forum-category').addEventListener('change',()=>{if(location.hash)location.hash='';else loadForumList()});document.querySelector('#forum-search').addEventListener('input',()=>{clearTimeout(forumSearchTimer);forumSearchTimer=setTimeout(()=>{if(location.hash)location.hash='';else loadForumList()},300)});document.querySelector('#forum-more').addEventListener('click',()=>loadForumList(true));document.querySelector('#moderation-button').addEventListener('click',loadModeration); +document.querySelector('#new-topic').addEventListener('click',()=>{document.querySelector('#new-topic-form').reset();document.querySelector('#new-display-name').value=localStorage.getItem('duneForumName')||'';document.querySelector('#new-topic-dialog').showModal()});document.querySelectorAll('[data-close-dialog]').forEach(b=>b.addEventListener('click',()=>b.closest('dialog').close())); +document.querySelector('#new-topic-form').addEventListener('submit',async e=>{e.preventDefault();const form=e.currentTarget,b=form.querySelector('button[type="submit"]');b.disabled=true;try{const values=Object.fromEntries(new FormData(form));const data=await forumRequest('/topics',{method:'POST',body:JSON.stringify(values)});localStorage.setItem('duneForumName',values.displayName);document.querySelector('#new-topic-dialog').close();forumNotice('Topic posted.');location.hash='topic='+data.id}catch(error){document.querySelector('#new-topic-error').textContent=error.message}finally{b.disabled=false}}); +document.querySelector('#report-form').addEventListener('submit',async e=>{e.preventDefault();try{await forumRequest('/reports',{method:'POST',body:JSON.stringify(Object.fromEntries(new FormData(e.currentTarget)))});document.querySelector('#report-dialog').close();forumNotice('Report sent to the website moderators.')}catch(error){forumNotice(error.message)}}); +document.querySelector('#remove-confirm').addEventListener('click',async()=>{const type=document.querySelector('#remove-type').value,id=document.querySelector('#remove-target').value;try{await forumRequest('/'+(type==='topic'?'topics':'posts')+'/'+id,{method:'DELETE'});document.querySelector('#remove-dialog').close();if(type==='topic')location.hash='';else loadForumTopic(forumTopic.id);forumNotice('Removed from the public forum.')}catch(error){forumNotice(error.message)}}); +window.addEventListener('hashchange',navigateForum);forumRequest('/session').then(data=>{forumSession=data;configureForumSession();navigateForum()}).catch(error=>forumEmpty('Forum unavailable',error.message)); diff --git a/website/web/index.html b/website/web/index.html index bc126a34..68a7f9e0 100644 --- a/website/web/index.html +++ b/website/web/index.html @@ -3,6 +3,6 @@ Project Dune — The spice must flow -
✦ PROJECT DUNEMINECRAFT REALMS
-
Minecraft voxel Arrakis with stillsuit adventurers, glowing spice, rocky terraces and a sandworm

PAPER 1.21.4 JAVA 21 PROJECT DUNE

The spice
must flow.

A desert worth surviving.
A universe worth building.

Bring Arrakis to Minecraft. Choose your House, walk the dunes, harvest melange, and face the maker beneath the sand.

01 / THE DESERT AWAITSEXPLORE ARRAKIS →FAN-MADE · MINECRAFT JAVA
+
✦ PROJECT DUNEMINECRAFT REALMS
+
Minecraft voxel Arrakis with stillsuit adventurers, glowing spice, rocky terraces and a sandworm

PAPER 1.21.4 JAVA 21 PROJECT DUNE

The spice
must flow.

A desert worth surviving.
A universe worth building.

Bring Arrakis to Minecraft. Choose your House, walk the dunes, harvest melange, and face the maker beneath the sand.

01 / THE DESERT AWAITSEXPLORE ARRAKIS →FAN-MADE · MINECRAFT JAVA
diff --git a/website/web/install.html b/website/web/install.html index a0547d46..ff9b2c01 100644 --- a/website/web/install.html +++ b/website/web/install.html @@ -1 +1 @@ -Get the plugin — Project Dune
✦ PROJECT DUNEMINECRAFT REALMS

PROJECT DUNE / MINECRAFT REALMS

Get the plugin

Paper 1.21.4. Java 21. Your next expedition starts here.

06 / BEGIN YOUR EXPEDITION

The next step
is yours.

Install the suite on Paper 1.21.4 with Java 21. Enable the resource pack for the desert sandworm, haunted Fremen, spice and smuggler textures.

Download the latest build ↗

Open a successful run and download the DuneRealms-Server-Package artifact. GitHub may require sign-in.

Explore the source on GitHub ↗
  1. 01

    Prepare your server

    Stop Paper and back up worlds, plugin data and your database before upgrading.

  2. 02

    Install the complete suite

    Place Vault, DuneCore, DuneNPC, DuneTerrain and DuneEss JARs in plugins/. Keep one JAR per plugin.

  3. 03

    Set your world, equip your players

    Match backend planet settings, restart, and enable DuneResourcePack.zip on clients. Use /dune help to begin.

Running a network with the Spacing Guild +

Use one Paper backend per planet behind Velocity, matching plugin planet IDs and proxy server names. Enable BungeeCord plugin-message compatibility. Cross-server sightings need an online player connection on Arrakis; due notices wait while that backend is empty. Consult the manual for PostgreSQL, travel, persistence and current prototype limits.

Resource pack and gameplay notes +

The resource pack works with vanilla and Fabric Java 1.21.4 clients. Put the ZIP in .minecraft/resourcepacks and enable it in Options. Sandworms use Sniffer geometry with an invisible Husk controller. Smuggler textures change vanilla wandering traders; their missions run on Arrakis. Live Paper and Velocity behavior still needs staging-server verification.

\ No newline at end of file +Get the plugin — Project Dune
✦ PROJECT DUNEMINECRAFT REALMS

PROJECT DUNE / MINECRAFT REALMS

Get the plugin

Paper 1.21.4. Java 21. Your next expedition starts here.

06 / BEGIN YOUR EXPEDITION

The next step
is yours.

Install the suite on Paper 1.21.4 with Java 21. Enable the resource pack for the desert sandworm, haunted Fremen, spice and smuggler textures.

Download the latest build ↗

Open a successful run and download the DuneRealms-Server-Package artifact. GitHub may require sign-in.

Explore the source on GitHub ↗
  1. 01

    Prepare your server

    Stop Paper and back up worlds, plugin data and your database before upgrading.

  2. 02

    Install the complete suite

    Place Vault, DuneCore, DuneNPC, DuneTerrain and DuneEss JARs in plugins/. Keep one JAR per plugin.

  3. 03

    Set your world, equip your players

    Match backend planet settings, restart, and enable DuneResourcePack.zip on clients. Use /dune help to begin.

Running a network with the Spacing Guild +

Use one Paper backend per planet behind Velocity, matching plugin planet IDs and proxy server names. Enable BungeeCord plugin-message compatibility. Cross-server sightings need an online player connection on Arrakis; due notices wait while that backend is empty. Consult the manual for PostgreSQL, travel, persistence and current prototype limits.

Resource pack and gameplay notes +

The resource pack works with vanilla and Fabric Java 1.21.4 clients. Put the ZIP in .minecraft/resourcepacks and enable it in Options. Sandworms use Sniffer geometry with an invisible Husk controller. Smuggler textures change vanilla wandering traders; their missions run on Arrakis. Live Paper and Velocity behavior still needs staging-server verification.

\ No newline at end of file diff --git a/website/web/manual.html b/website/web/manual.html index 7d3671ea..be066298 100644 --- a/website/web/manual.html +++ b/website/web/manual.html @@ -1 +1 @@ -The Field Manual — Project Dune
✦ PROJECT DUNEMINECRAFT REALMS

THE ILLUSTRATED FIELD MANUAL

Your guide to the dunes.

Download PDF ↓

Loading the illustrated manual…

\ No newline at end of file +The Field Manual — Project Dune
✦ PROJECT DUNEMINECRAFT REALMS

THE ILLUSTRATED FIELD MANUAL

Your guide to the dunes.

Download PDF ↓

Loading the illustrated manual…

\ No newline at end of file diff --git a/website/web/minecraft.css b/website/web/minecraft.css index 27b94d33..65724b4b 100644 --- a/website/web/minecraft.css +++ b/website/web/minecraft.css @@ -25,3 +25,5 @@ nav>a:not(.nav-cta):hover{background:#284536;box-shadow:0 3px 0 var(--gold)}.nav @media(max-width:1100px){.banner-menu{grid-template-columns:repeat(3,minmax(0,1fr))}.banner-menu a:last-child{grid-column:auto}} @media(max-width:600px){.banner-menu{grid-template-columns:repeat(2,minmax(0,1fr))}.banner-menu a:last-child{grid-column:span 2}.hero h1{font-size:74px}.hero{max-height:none}} .banner-menu a[aria-current=page]{background:linear-gradient(#635b2c,#394927);border-color:#e9bd5c;box-shadow:inset 2px 2px 0 #b9b071,3px 4px 0 #07130b}.banner-menu a[aria-current=page] span{color:#ffe297} + +.banner-menu{grid-template-columns:repeat(6,minmax(0,1fr))}.banner-menu a:last-child{grid-column:auto}@media(max-width:1100px){.banner-menu{grid-template-columns:repeat(3,minmax(0,1fr))}}@media(max-width:600px){.banner-menu{grid-template-columns:repeat(2,minmax(0,1fr))}} diff --git a/website/web/news.html b/website/web/news.html index 1b1d2bc6..23943c76 100644 --- a/website/web/news.html +++ b/website/web/news.html @@ -1 +1 @@ -The Guild Dispatch — Project Dune
✦ PROJECT DUNEMINECRAFT REALMS

LIVE REALM RECORDS / DISCORDSRV

The
Guild Dispatch

Word travels across worlds.

Arrakis sightings, Guild announcements, CHOAM rotations and Imperial developments. A live record of public in-game notifications.

Checking the server connection…

✦

Opening the Guild records…

Only public game announcements

This feed covers public server notifications forwarded to the dedicated DiscordSRV news channel. It excludes private player messages, commands and console logs. The fifteen-minute Guild announcement is recorded when it is actually delivered.

Read the Guild notice guide →
\ No newline at end of file +The Guild Dispatch — Project Dune
✦ PROJECT DUNEMINECRAFT REALMS

LIVE REALM RECORDS / DISCORDSRV

The
Guild Dispatch

Word travels across worlds.

Arrakis sightings, Guild announcements, CHOAM rotations and Imperial developments. A live record of public in-game notifications.

Checking the server connection…

✦

Opening the Guild records…

Only public game announcements

This feed covers public server notifications forwarded to the dedicated DiscordSRV news channel. It excludes private player messages, commands and console logs. The fifteen-minute Guild announcement is recorded when it is actually delivered.

Read the Guild notice guide →
\ No newline at end of file diff --git a/website/web/portal.css b/website/web/portal.css new file mode 100644 index 00000000..7cdce728 --- /dev/null +++ b/website/web/portal.css @@ -0,0 +1 @@ +.portal-section{padding:45px 6% 80px;max-width:1450px;margin:auto}.portal-tabs{display:flex;gap:14px;flex-wrap:wrap;margin-bottom:35px}.portal-tabs a{border:3px solid #8b7b4b;background:#253f2b;padding:12px 20px;box-shadow:inset 2px 2px 0 #58694b,3px 4px 0 #07170e;font:25px VT323,monospace}.portal-tabs a.current{color:var(--gold);border-color:#d8b25c;background:#344b2b}.portal-signin-panel,.portal-empty,.portal-error{border:4px solid #9b834c;padding:40px;background:linear-gradient(#233e2aee,#17321dec),url('assets/sietch.webp') center/cover;box-shadow:4px 6px 0 #061a0c}.portal-signin-panel h2,.portal-empty h2{font-size:55px}.portal-signin-panel p,.portal-empty p{max-width:800px;color:var(--muted);font-size:13px}.portal-overview{display:grid;grid-template-columns:1.25fr 1fr;gap:28px}.portal-profile-card,.portal-support-card,.portal-recent{border:4px solid #8f7d46;padding:30px;background:#243e2a;box-shadow:4px 5px 0 #05170b}.portal-profile-card{display:flex;gap:28px;align-items:center}.portal-profile-card img{width:120px;height:120px;border:4px solid #8c7841;background:#cbb985}.portal-profile-card h2{font-size:54px;margin:8px 0}.portal-profile-card p{font-size:12px;color:var(--muted)}.portal-support-card h3,.portal-recent h3{font-size:36px;color:var(--gold)}.portal-support-card p{font-size:12px;color:var(--muted)}.portal-support-card strong{font:55px VT323,monospace;color:var(--gold)}.portal-recent{grid-column:1/-1}.portal-recent-ticket{display:block;padding:13px 0;border-bottom:1px solid var(--line);font-size:12px;color:var(--gold)}.player-profile-form{max-width:800px;background:#213c27;border:4px solid #9b844b;padding:35px;box-shadow:4px 5px 0 #07180d}.player-profile-form label{display:flex;flex-direction:column;gap:8px;font-size:12px;color:var(--gold);margin:20px 0}.player-profile-form input{background:#102619;border:3px solid #6e7c51;box-shadow:inset 2px 2px 0 #07150c;color:var(--paper);padding:13px;font:14px Manrope,Arial,sans-serif}.player-profile-form h2{font-size:53px}.player-profile-form p{font-size:12px;color:var(--muted)}.player-profile-form [role=status]{color:var(--gold)}.profile-ticket-link{display:block;padding-top:25px;margin-top:25px;border-top:1px solid var(--line);font:28px VT323,monospace;color:var(--gold)}.ticket-toolbar{display:flex;align-items:end;justify-content:space-between;gap:22px;flex-wrap:wrap;margin:25px 0}.ticket-toolbar .actions{gap:15px}.ticket-list{display:grid;gap:15px}.ticket-card{padding:25px;border:3px solid #8a7942;background:#253d29;box-shadow:3px 4px 0 #08170b;display:flex;justify-content:space-between;align-items:center;gap:25px}.ticket-card:hover{border-color:var(--gold)}.ticket-card h3{font-size:33px;margin:12px 0 8px}.ticket-card p{font-size:10px;color:var(--muted);margin:0}.ticket-status{display:inline-block;padding:7px 12px;border:2px solid #758255;background:#2d4930;color:#d4e4b2;font-size:10px;white-space:nowrap}.status-in_progress{background:#2f4653;border-color:#6d97a4;color:#d0e6e9}.status-waiting_on_player{background:#605027;border-color:#b99443;color:#fff0b3}.status-resolved{background:#315535;border-color:#7bb478}.status-closed{background:#3b4032;border-color:#7f826d;color:#c9cbb5}.private-ticket,.ticket-message{padding:30px;background:#efe0bd;border:4px solid #a98b4c;color:#243b25;margin:25px 0;box-shadow:4px 5px 0 #07170d}.private-ticket{background:linear-gradient(#f1e4c9f1,#f1e4c9f4),url('assets/ornament.webp') center/cover}.private-ticket h2{font-size:56px;overflow-wrap:anywhere}.private-ticket .eyebrow{color:#966a2f;margin-bottom:16px}.private-ticket .ticket-status{margin-bottom:15px}.ticket-player-details{background:#d7c69d80;border:1px solid #b29a63;padding:11px 15px;margin:20px 0}.ticket-player-details p{font-size:11px;margin:3px 0}.ticket-message.role-staff{border-color:#80955c;background:#e3e4c4}.ticket-message.role-system{background:#1d3725;color:#c8d7b6;padding:14px 20px;border-width:2px}.ticket-message.role-system .forum-meta{color:#c0cda5}.ticket-state-controls{display:flex;gap:15px;align-items:center;flex-wrap:wrap;margin:20px 0}.ticket-state-controls select{padding:10px;border:3px solid #7d844b;background:#19341f;color:var(--paper);font:12px Manrope,Arial,sans-serif}.ticket-context{color:var(--gold);font-size:10px;margin-bottom:20px}.ticket-context a{text-decoration:underline}.ticket-help{font-size:11px;color:var(--muted);max-width:800px;margin:25px 0}#ticket-controls[hidden],#ticket-more[hidden],#staff-queue-link[hidden]{display:none}.portal-recent [hidden]{display:none}@media(max-width:850px){.portal-overview{grid-template-columns:1fr}.portal-recent{grid-column:auto}}@media(max-width:600px){.portal-section{padding:30px 7% 55px}.portal-tabs{gap:8px}.portal-tabs a{font-size:24px;padding:10px 12px}.portal-signin-panel,.portal-empty{padding:28px 22px}.portal-signin-panel h2{font-size:45px}.portal-profile-card{display:block;padding:25px}.portal-profile-card img{margin-bottom:23px;width:90px;height:90px}.portal-profile-card h2{font-size:50px}.portal-support-card,.portal-recent,.player-profile-form{padding:25px 21px}.ticket-card{display:block;padding:22px 18px}.ticket-card .ticket-status{margin-top:18px}.private-ticket,.ticket-message{padding:24px 20px}.private-ticket h2{font-size:46px}} diff --git a/website/web/portal.html b/website/web/portal.html new file mode 100644 index 00000000..6afb36dc --- /dev/null +++ b/website/web/portal.html @@ -0,0 +1 @@ +Player portal — Project Dune
✦ PROJECT DUNEMINECRAFT REALMS

PROJECT DUNE / PLAYER PORTAL

Player portal

Your identity, your expeditions, your private line to staff.

Portal / Your profile / Support tickets

Opening your private portal…

\ No newline at end of file diff --git a/website/web/portal.js b/website/web/portal.js new file mode 100644 index 00000000..8ad0637f --- /dev/null +++ b/website/web/portal.js @@ -0,0 +1,17 @@ +const portalRoot=document.querySelector('#portal-content'),portalMode=document.body.dataset.portal;let playerSession={authenticated:false,staff:false},playerProfile=null,ticketPageOffset=null,currentTicket=null,ticketMessages=[],portalToastTimer; +const portalEl=(tag,text,cls)=>{const e=document.createElement(tag);if(text!==undefined)e.textContent=text;if(cls)e.className=cls;return e}; +async function portalRequest(path,options={}){const r=await fetch('/api/'+path,{...options,headers:{'Content-Type':'application/json',...(options.headers||{})},cache:'no-store'});const data=await r.json();if(!r.ok)throw Error(data.message||({not_found:'This ticket is unavailable or does not belong to your account.',forbidden:'This action requires an authorised staff account.'}[data.error]||'The player portal is temporarily unavailable.'));return data} +function portalNotify(message){const t=document.querySelector('.toast');t.textContent=message;t.classList.add('visible');clearTimeout(portalToastTimer);portalToastTimer=setTimeout(()=>t.classList.remove('visible'),3500)} +function portalDate(time){return new Date(time).toLocaleString()} +function portalButton(text,handler,cls='forum-action'){const b=portalEl('button',text,cls);b.type='button';b.addEventListener('click',handler);return b} +function portalSignIn(){const panel=portalEl('div',undefined,'portal-signin-panel');panel.append(portalEl('h2','Your private player portal'),portalEl('p','Sign in with ChatGPT to save your profile, submit ban appeals and request staff support. Only you and authorised staff can read your tickets.'));const a=portalEl('a','Sign in with ChatGPT ↗','button gold');a.href='/signin-with-chatgpt?return_to='+encodeURIComponent('/'+(portalMode==='profile'?'profile.html':portalMode==='tickets'?'tickets.html':'portal.html'));a.target='_top';panel.append(a);portalRoot.replaceChildren(panel)} +function portalError(message){portalRoot.replaceChildren(portalEl('div',message,'portal-error'))} +async function showPortalOverview(){const data=await portalRequest('tickets');const template=document.querySelector('#portal-overview-template').content.cloneNode(true);template.querySelector('[data-profile-name]').textContent=playerProfile?.display_name||'Explorer';template.querySelector('[data-minecraft-name]').textContent=playerProfile?.minecraft_name||'Add your Minecraft name in your profile';template.querySelector('[data-ticket-count]').textContent=String(data.activeCount??data.tickets.filter(t=>!['closed','resolved'].includes(t.status)).length);const recent=template.querySelector('[data-recent-tickets]');for(const ticket of data.tickets.slice(0,5)){const a=portalEl('a',`${ticket.subject} · ${playerSession.ticketStates[ticket.status]}`,'portal-recent-ticket');a.href='tickets.html#ticket='+ticket.id;recent.append(a)}if(!data.tickets.length)recent.append(portalEl('p','You have no support tickets yet.'));const staff=template.querySelector('[data-staff-link]');staff.hidden=!playerSession.staff;portalRoot.replaceChildren(template)} +function showPlayerProfile(){const template=document.querySelector('#profile-template').content.cloneNode(true),form=template.querySelector('form');for(const [field,key]of [['displayName','display_name'],['minecraftName','minecraft_name'],['discordName','discord_name']])form.elements[field].value=playerProfile?.[key]||'';form.addEventListener('submit',async e=>{e.preventDefault();const button=form.querySelector('button[type="submit"]');button.disabled=true;try{const values=Object.fromEntries(new FormData(form));await portalRequest('profile',{method:'POST',body:JSON.stringify(values)});localStorage.setItem('duneForumName',values.displayName);playerProfile=(await portalRequest('profile')).profile;form.querySelector('[role="status"]').textContent='Your profile has been saved.';portalNotify('Profile saved.')}catch(error){form.querySelector('[role="status"]').textContent=error.message}finally{button.disabled=false}});portalRoot.replaceChildren(template)} +function staffTicketView(){return playerSession.staff&&new URLSearchParams(location.search).get('view')==='staff'} +async function showTicketList(append=false){currentTicket=null;const toolbar=document.querySelector('#ticket-controls');toolbar.hidden=false;const staff=staffTicketView(),status=document.querySelector('#ticket-status-filter').value,category=document.querySelector('#ticket-category-filter').value;try{const data=await portalRequest('tickets?'+new URLSearchParams({view:staff?'staff':'mine',status,category,offset:append?ticketPageOffset||0:0}));ticketPageOffset=data.nextOffset;document.querySelector('#ticket-list-heading').textContent=staff?'Staff support queue':'My support tickets';const list=append?document.querySelector('.ticket-list'):portalEl('div',undefined,'ticket-list');if(!append)portalRoot.replaceChildren(list);for(const ticket of data.tickets){const a=portalEl('a',undefined,'ticket-card');a.href='#ticket='+ticket.id;const details=portalEl('div');details.append(portalEl('span',playerSession.ticketCategories[ticket.category]+' · #'+ticket.id.slice(0,8),'forum-tag'),portalEl('h3',ticket.subject),portalEl('p',`${staff?ticket.owner_name+' · ':''}Updated ${portalDate(ticket.updated_at)}`));a.append(details,portalEl('span',playerSession.ticketStates[ticket.status],'ticket-status status-'+ticket.status));list.append(a)}document.querySelector('#ticket-more').hidden=ticketPageOffset===null;if(!append&&!data.tickets.length){const box=portalEl('div',undefined,'portal-empty');box.append(portalEl('h2',staff?'The queue is clear':'No tickets here yet'),portalEl('p',staff?'There are no requests matching these filters.':'Open a ban appeal or request help from staff. Your case stays under your profile.'));portalRoot.replaceChildren(box)}}catch(error){portalError(error.message)}} +async function updateTicketStatus(status){try{await portalRequest('tickets/'+currentTicket.id+'/status',{method:'POST',body:JSON.stringify({status})});portalNotify('Ticket status updated.');showTicketDetail(currentTicket.id)}catch(error){portalNotify(error.message)}} +async function showTicketDetail(id,append=false){try{const data=await portalRequest('tickets/'+id+(append?'?offset='+ticketPageOffset:''));currentTicket=data.ticket;ticketMessages=append?[...ticketMessages,...data.messages]:data.messages;ticketPageOffset=data.nextOffset;document.querySelector('#ticket-controls').hidden=true;document.querySelector('#ticket-more').hidden=true;portalRoot.replaceChildren();const back=portalEl('a',staffTicketView()?'← Staff queue':'← My tickets','text-link');back.href='#';portalRoot.append(back);const original=portalEl('article',undefined,'private-ticket');original.append(portalEl('p',playerSession.ticketCategories[currentTicket.category]+' · #'+id.slice(0,8),'eyebrow'),portalEl('h2',currentTicket.subject),portalEl('span',playerSession.ticketStates[currentTicket.status],'ticket-status status-'+currentTicket.status),portalEl('p',`${currentTicket.owner_name} · ${portalDate(currentTicket.created_at)}`,'forum-meta'));const names=portalEl('div',undefined,'ticket-player-details');names.append(portalEl('p','Minecraft: '+(currentTicket.minecraft_name||'Not specified')));if(currentTicket.discord_name)names.append(portalEl('p','Discord handle: '+currentTicket.discord_name));original.append(names,portalEl('div',currentTicket.body,'forum-message'));portalRoot.append(original);const controls=portalEl('div',undefined,'ticket-state-controls');if(playerSession.staff){const select=portalEl('select');select.setAttribute('aria-label','Ticket status');for(const [key,label]of Object.entries(playerSession.ticketStates)){const option=portalEl('option',label);option.value=key;select.append(option)}select.value=currentTicket.status;controls.append(select,portalButton('Update status',()=>updateTicketStatus(select.value)))}else if(currentTicket.isOwner){controls.append(portalButton(currentTicket.status==='closed'?'Reopen my ticket':'Close my ticket',()=>updateTicketStatus(currentTicket.status==='closed'?'open':'closed')))}portalRoot.append(controls);for(const message of ticketMessages){const row=portalEl('article',undefined,'ticket-message role-'+message.author_role);row.append(portalEl('p',`${message.author_name} · ${message.author_role==='staff'?'Staff reply · ':message.author_role==='system'?'Status update · ':''}${portalDate(message.created_at)}`,'forum-meta'),portalEl('div',message.body,'forum-message'));portalRoot.append(row)}if(ticketPageOffset!==null)portalRoot.append(portalButton('Load more replies',()=>showTicketDetail(id,true),'pagination-button'));if(currentTicket.status!=='closed'){const panel=document.querySelector('#ticket-reply-template').content.cloneNode(true),form=panel.querySelector('form');form.querySelector('h3').textContent=playerSession.staff?'Staff reply':'Reply to staff';form.addEventListener('submit',async e=>{e.preventDefault();const b=form.querySelector('button[type="submit"]');b.disabled=true;try{await portalRequest('tickets/'+id+'/replies',{method:'POST',body:JSON.stringify(Object.fromEntries(new FormData(form)))});portalNotify('Private reply sent.');showTicketDetail(id)}catch(error){portalNotify(error.message)}finally{b.disabled=false}});portalRoot.append(panel)}else portalRoot.append(portalEl('p','This ticket is closed. Reopen it if you need to continue.','small-note'))}catch(error){portalError(error.message)}} +function navigateTickets(){const match=location.hash.match(/^#ticket=([0-9a-f-]+)$/i);if(match)showTicketDetail(match[1]);else showTicketList()} +function initTicketControls(){const controls=document.querySelector('#ticket-controls');controls.hidden=false;document.querySelector('#staff-queue-link').hidden=!playerSession.staff;for(const [id,options]of [['ticket-status-filter',playerSession.ticketStates],['ticket-category-filter',playerSession.ticketCategories]]){const select=document.querySelector('#'+id);for(const [key,label]of Object.entries(options)){const option=portalEl('option',label);option.value=key;select.append(option)}select.addEventListener('change',()=>{if(location.hash)location.hash='';else showTicketList()})}const form=document.querySelector('#new-ticket-form'),category=form.elements.category;for(const [key,label]of Object.entries(playerSession.ticketCategories)){const o=portalEl('option',label);o.value=key;category.append(o)}document.querySelector('#new-ticket-button').addEventListener('click',()=>{if(!playerProfile){portalNotify('Save your player profile before opening a ticket.');return}form.reset();document.querySelector('#new-ticket-error').textContent='';document.querySelector('#new-ticket-dialog').showModal()});form.addEventListener('submit',async e=>{e.preventDefault();const b=form.querySelector('button[type="submit"]');b.disabled=true;try{const data=await portalRequest('tickets',{method:'POST',body:JSON.stringify(Object.fromEntries(new FormData(form)))});document.querySelector('#new-ticket-dialog').close();portalNotify('Your private ticket has been opened.');location.hash='ticket='+data.id}catch(error){document.querySelector('#new-ticket-error').textContent=error.message}finally{b.disabled=false}});document.querySelectorAll('[data-close-dialog]').forEach(b=>b.addEventListener('click',()=>b.closest('dialog').close()));document.querySelector('#ticket-more').addEventListener('click',()=>showTicketList(true));window.addEventListener('hashchange',navigateTickets);navigateTickets()} +portalRequest('portal/session').then(async data=>{playerSession=data;if(!playerSession.authenticated){portalSignIn();return}playerProfile=(await portalRequest('profile')).profile;if(portalMode==='profile')showPlayerProfile();else if(portalMode==='tickets')initTicketControls();else await showPortalOverview()}).catch(error=>portalError(error.message)); diff --git a/website/web/profile.html b/website/web/profile.html new file mode 100644 index 00000000..49196d1a --- /dev/null +++ b/website/web/profile.html @@ -0,0 +1 @@ +Your profile — Project Dune
✦ PROJECT DUNEMINECRAFT REALMS

PROJECT DUNE / PLAYER PORTAL

Your profile

Your player record, with support tickets kept under your account.

Portal / Your profile / Support tickets

Opening your private portal…

\ No newline at end of file diff --git a/website/web/races.html b/website/web/races.html index 0bf612cf..69df6b57 100644 --- a/website/web/races.html +++ b/website/web/races.html @@ -1 +1 @@ -Races & Great Houses — Project Dune
✦ PROJECT DUNEMINECRAFT REALMS

ALLEGIANCE / EQUIPMENT / HOMEWORLDS

Races &
Great Houses.

The plugin’s five selectable factions, drawn from the current field manual. Choose an allegiance, equip its stillsuit and learn its abilities.

These choices are implemented as factions rather than biological race classes. Spacing Guild NPCs support travel; the Guild is not a selectable faction.

Illustrated Arrakis

ARRAKIS / ORANGE STILLSUIT

Fremen

Unbreaking III on every kit piece; Swift Sneak III on leggings. Two spice units per deposit.

Fremen helmetFremen chestplateFremen leggingsFremen bootsFremen winged stillsuit

Wear all four tagged stillsuit pieces for Arrakis sun protection and the matching full-set effects. Winged upgrades use a carried Elytra and cost 1,000,000 Solaris.

Read the equipment chapter →
Illustrated Giedi Prime

GIEDI PRIME / RED STILLSUIT

Harkonnen

Combat damage +15%; matching full set refreshes Strength II.

Harkonnen helmetHarkonnen chestplateHarkonnen leggingsHarkonnen bootsHarkonnen winged stillsuit

Wear all four tagged stillsuit pieces for Arrakis sun protection and the matching full-set effects. Winged upgrades use a carried Elytra and cost 1,000,000 Solaris.

Read the equipment chapter →
Illustrated Kaitain

KAITAIN / PURPLE STILLSUIT

Corrino

Protection III on kit armor; entity-caused incoming combat damage is reduced by 15%.

Corrino helmetCorrino chestplateCorrino leggingsCorrino bootsCorrino winged stillsuit

Wear all four tagged stillsuit pieces for Arrakis sun protection and the matching full-set effects. Winged upgrades use a carried Elytra and cost 1,000,000 Solaris.

Read the equipment chapter →
Illustrated Caladan

CALADAN / BLUE STILLSUIT

Atreides

Movement can refresh Speed I. Matching full set adds four hearts while equipped.

Atreides helmetAtreides chestplateAtreides leggingsAtreides bootsAtreides winged stillsuit

Wear all four tagged stillsuit pieces for Arrakis sun protection and the matching full-set effects. Winged upgrades use a carried Elytra and cost 1,000,000 Solaris.

Read the equipment chapter →
Illustrated Sigma Draconis IV

SIGMA DRACONIS IV / GREEN STILLSUIT

Ordos

Matching full set enables five-second Shadow Step on main-hand Ender Pearl use.

Ordos helmetOrdos chestplateOrdos leggingsOrdos bootsOrdos winged stillsuit

Wear all four tagged stillsuit pieces for Arrakis sun protection and the matching full-set effects. Winged upgrades use a carried Elytra and cost 1,000,000 Solaris.

Read the equipment chapter →

BEFORE YOU CHOOSE

Wear your allegiance.

A normal player cannot change an existing faction selection. Choosing supplies a kit and requests a free first homeworld arrival. The kit enters your inventory; equip it yourself. Renamed or merely dyed armor does not replace the plugin’s tagged gear.

Read faction rules →

World art is illustrative. Arrakis has the full gameplay guide; other worlds have terrain profiles and reserved expansion chapters.

\ No newline at end of file +Races & Great Houses — Project Dune
✦ PROJECT DUNEMINECRAFT REALMS

ALLEGIANCE / EQUIPMENT / HOMEWORLDS

Races &
Great Houses.

The plugin’s five selectable factions, drawn from the current field manual. Choose an allegiance, equip its stillsuit and learn its abilities.

These choices are implemented as factions rather than biological race classes. Spacing Guild NPCs support travel; the Guild is not a selectable faction.

Illustrated Arrakis

ARRAKIS / ORANGE STILLSUIT

Fremen

Unbreaking III on every kit piece; Swift Sneak III on leggings. Two spice units per deposit.

Fremen helmetFremen chestplateFremen leggingsFremen bootsFremen winged stillsuit

Wear all four tagged stillsuit pieces for Arrakis sun protection and the matching full-set effects. Winged upgrades use a carried Elytra and cost 1,000,000 Solaris.

Read the equipment chapter →
Illustrated Giedi Prime

GIEDI PRIME / RED STILLSUIT

Harkonnen

Combat damage +15%; matching full set refreshes Strength II.

Harkonnen helmetHarkonnen chestplateHarkonnen leggingsHarkonnen bootsHarkonnen winged stillsuit

Wear all four tagged stillsuit pieces for Arrakis sun protection and the matching full-set effects. Winged upgrades use a carried Elytra and cost 1,000,000 Solaris.

Read the equipment chapter →
Illustrated Kaitain

KAITAIN / PURPLE STILLSUIT

Corrino

Protection III on kit armor; entity-caused incoming combat damage is reduced by 15%.

Corrino helmetCorrino chestplateCorrino leggingsCorrino bootsCorrino winged stillsuit

Wear all four tagged stillsuit pieces for Arrakis sun protection and the matching full-set effects. Winged upgrades use a carried Elytra and cost 1,000,000 Solaris.

Read the equipment chapter →
Illustrated Caladan

CALADAN / BLUE STILLSUIT

Atreides

Movement can refresh Speed I. Matching full set adds four hearts while equipped.

Atreides helmetAtreides chestplateAtreides leggingsAtreides bootsAtreides winged stillsuit

Wear all four tagged stillsuit pieces for Arrakis sun protection and the matching full-set effects. Winged upgrades use a carried Elytra and cost 1,000,000 Solaris.

Read the equipment chapter →
Illustrated Sigma Draconis IV

SIGMA DRACONIS IV / GREEN STILLSUIT

Ordos

Matching full set enables five-second Shadow Step on main-hand Ender Pearl use.

Ordos helmetOrdos chestplateOrdos leggingsOrdos bootsOrdos winged stillsuit

Wear all four tagged stillsuit pieces for Arrakis sun protection and the matching full-set effects. Winged upgrades use a carried Elytra and cost 1,000,000 Solaris.

Read the equipment chapter →

BEFORE YOU CHOOSE

Wear your allegiance.

A normal player cannot change an existing faction selection. Choosing supplies a kit and requests a free first homeworld arrival. The kit enters your inventory; equip it yourself. Renamed or merely dyed armor does not replace the plugin’s tagged gear.

Read faction rules →

World art is illustrative. Arrakis has the full gameplay guide; other worlds have terrain profiles and reserved expansion chapters.

\ No newline at end of file diff --git a/website/web/smugglers.html b/website/web/smugglers.html index a4686cee..47968853 100644 --- a/website/web/smugglers.html +++ b/website/web/smugglers.html @@ -1 +1 @@ -Smugglers — Project Dune
✦ PROJECT DUNEMINECRAFT REALMS

PROJECT DUNE / MINECRAFT REALMS

Smugglers

Contacts beyond the ledgers. Carry spice and water between the hidden camps.

03 / CONTACTS BEYOND THE LEDGERS

A deal in
the shadows.

Roaming smugglers carry two offers. Accept a contract, carry its cargo, and find another contact before time runs out.

A desert smuggler with green particles beside a spice courier
SPICE SMUGGLING

The Unmarked Spice Run

Carry 64 tagged spice to a different smuggler, at least 64 horizontal blocks from your departure point.

Default gross reward
1,392 Solaris
Contract window
30 real minutes
Purple particles around an illuminated water smuggler camp at night
WATER SMUGGLING

Water for the Hidden Sietch

Deliver 4 finite-source water buckets to another contact. Your empty buckets return when the mission is completed.

Default gross reward
41 Solaris
Contract window
30 real minutes

Green / roaming

No open contracts from this contact.

Purple / active camp

The source NPC stays still and its camp lights up until its last contract ends.

◷

The clock keeps running

Offline time counts. Expiry keeps your cargo and pays no reward.

Rewards are before the Trust levy. Imperial Spice Steward and House of Water appointees use ordinary spice sales with a 33% gross bonus instead of smuggler missions.

\ No newline at end of file +Smugglers — Project Dune
✦ PROJECT DUNEMINECRAFT REALMS

PROJECT DUNE / MINECRAFT REALMS

Smugglers

Contacts beyond the ledgers. Carry spice and water between the hidden camps.

03 / CONTACTS BEYOND THE LEDGERS

A deal in
the shadows.

Roaming smugglers carry two offers. Accept a contract, carry its cargo, and find another contact before time runs out.

A desert smuggler with green particles beside a spice courier
SPICE SMUGGLING

The Unmarked Spice Run

Carry 64 tagged spice to a different smuggler, at least 64 horizontal blocks from your departure point.

Default gross reward
1,392 Solaris
Contract window
30 real minutes
Purple particles around an illuminated water smuggler camp at night
WATER SMUGGLING

Water for the Hidden Sietch

Deliver 4 finite-source water buckets to another contact. Your empty buckets return when the mission is completed.

Default gross reward
41 Solaris
Contract window
30 real minutes

Green / roaming

No open contracts from this contact.

Purple / active camp

The source NPC stays still and its camp lights up until its last contract ends.

◷

The clock keeps running

Offline time counts. Expiry keeps your cargo and pays no reward.

Rewards are before the Trust levy. Imperial Spice Steward and House of Water appointees use ordinary spice sales with a 33% gross bonus instead of smuggler missions.

\ No newline at end of file diff --git a/website/web/tickets.html b/website/web/tickets.html new file mode 100644 index 00000000..23036b19 --- /dev/null +++ b/website/web/tickets.html @@ -0,0 +1 @@ +Support tickets — Project Dune
✦ PROJECT DUNEMINECRAFT REALMS

PROJECT DUNE / PLAYER PORTAL

Support tickets

Ban appeals and staff help. Private conversations attached to your profile.

Portal / Your profile / Support tickets

Opening your private portal…

Private support ticket

Visible only to you and authorised staff. Never include passwords or account tokens.

\ No newline at end of file diff --git a/website/worker/community-api.mjs b/website/worker/community-api.mjs new file mode 100644 index 00000000..1baade5d --- /dev/null +++ b/website/worker/community-api.mjs @@ -0,0 +1,2 @@ +const communityInvite='jS4cx7eSGh',communityGuild='356127541632958477';let communityCached=null; +export async function handleCommunity(request){if(request.method!=='GET')return Response.json({error:'method_not_allowed'},{status:405});if(communityCached&&Date.now()-communityCached.time<300000)return Response.json(communityCached.data,{headers:{'Cache-Control':'public, max-age=60'}});try{const response=await fetch(`https://discord.com/api/v10/invites/${communityInvite}?with_counts=true`,{signal:AbortSignal.timeout(8000)});if(!response.ok)throw Error();const invite=await response.json();if(invite.guild?.id!==communityGuild)throw Error();const data={status:'connected',name:invite.guild.name,inviteUrl:`https://discord.gg/${communityInvite}`,memberCount:Number(invite.approximate_member_count)||0,onlineCount:Number(invite.approximate_presence_count)||0};communityCached={time:Date.now(),data};return Response.json(data,{headers:{'Cache-Control':'public, max-age=60'}})}catch{return Response.json({status:'unavailable',name:'YouSMP',inviteUrl:`https://discord.gg/${communityInvite}`},{headers:{'Cache-Control':'no-store'}})}} diff --git a/website/worker/forum-api.mjs b/website/worker/forum-api.mjs new file mode 100644 index 00000000..660c3864 --- /dev/null +++ b/website/worker/forum-api.mjs @@ -0,0 +1,40 @@ +const forumCategories={help:'Guides & help',gameplay:'Gameplay & expeditions',lore:'Houses & lore',feedback:'Feedback & bugs'}; +const forumId=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; +const forumJson=(data,status=200)=>Response.json(data,{status,headers:{'Cache-Control':'no-store','X-Content-Type-Options':'nosniff'}}); +function forumIdentity(request,env){const id=request.headers.get('oai-authenticated-user-id')||'';const email=(request.headers.get('oai-authenticated-user-email')||'').toLowerCase();const moderators=(env.FORUM_ADMIN_EMAILS||'').split(',').map(s=>s.trim().toLowerCase()).filter(Boolean);return {id,authenticated:Boolean(id&&id.length<=200),moderator:Boolean(id&&email&&moderators.includes(email))}} +function forumText(value,min,max,name){if(typeof value!=='string')throw Object.assign(Error(`${name} is required.`),{status:400});const clean=value.trim();if(clean.lengthmax)throw Object.assign(Error(`${name} must be ${min}–${max} characters.`),{status:400});return clean} +async function forumBody(request){if(!/^application\/json(?:;|$)/i.test(request.headers.get('Content-Type')||''))throw Object.assign(Error('Send JSON content.'),{status:415});const reader=request.body?.getReader();if(!reader)throw Object.assign(Error('A request body is required.'),{status:400});let size=0,text='';const decoder=new TextDecoder();while(true){const {value,done}=await reader.read();if(done)break;size+=value.byteLength;if(size>48000){await reader.cancel();throw Object.assign(Error('Post is too large.'),{status:413})}text+=decoder.decode(value,{stream:true})}text+=decoder.decode();try{const value=JSON.parse(text);if(!value||Array.isArray(value)||typeof value!=='object')throw Error();return value}catch{throw Object.assign(Error('Invalid JSON.'),{status:400})}} +function publicTopic(row,user){const {author_id,body,...rest}=row;return {...rest,closed:Boolean(rest.closed),canManage:user.moderator||author_id===user.id}} +function publicPost(row,user){const {author_id,...rest}=row;return {...rest,canManage:user.moderator||author_id===user.id}} +async function getForumTopic(db,id){return db.prepare('SELECT * FROM forum_topics WHERE id=? AND deleted=0').bind(id).first()} +export async function handleForum(request,env){const url=new URL(request.url),path=url.pathname.slice('/api/forum'.length),user=forumIdentity(request,env),db=env.DB;const write=!['GET','HEAD'].includes(request.method); + try{ + if(path==='/session'&&request.method==='GET')return forumJson({authenticated:user.authenticated,moderator:user.moderator,categories:forumCategories}); + if(write){if(!user.authenticated)return forumJson({error:'sign_in_required',message:'Sign in with ChatGPT to post.'},401);if(request.headers.get('Origin')!==url.origin)return forumJson({error:'forbidden_origin'},403)} + if(!db)return forumJson({error:'forums_unavailable',message:'The forum is temporarily unavailable.'},503); + if(path==='/topics'&&request.method==='GET'){ + const category=url.searchParams.get('category')||'all',q=(url.searchParams.get('q')||'').trim().slice(0,120),offset=Number(url.searchParams.get('offset')||0);if((category!=='all'&&!forumCategories[category])||!Number.isSafeInteger(offset)||offset<0||offset>100000)return forumJson({error:'invalid_filter'},400); + const term='%'+q.replace(/[\\%_]/g,c=>'\\'+c)+'%';const conditions="t.deleted=0 AND (?='all' OR t.category=?) AND (t.title LIKE ? ESCAPE '\\' OR t.body LIKE ? ESCAPE '\\')"; + const rows=await db.prepare(`SELECT t.*, (SELECT COUNT(*) FROM forum_posts p WHERE p.topic_id=t.id AND p.deleted=0) AS replyCount FROM forum_topics t WHERE ${conditions} ORDER BY t.last_activity_at DESC,t.id LIMIT 51 OFFSET ?`).bind(category,category,term,term,offset).all(); + return forumJson({topics:rows.results.slice(0,50).map(r=>publicTopic(r,user)),nextOffset:rows.results.length>50?offset+50:null}); + } + if(path==='/topics'&&request.method==='POST'){ + const data=await forumBody(request),title=forumText(data.title,5,120,'Title'),body=forumText(data.body,10,10000,'Message'),name=forumText(data.displayName,2,40,'Display name');if(!forumCategories[data.category])return forumJson({error:'invalid_category'},400);const now=Date.now(),id=crypto.randomUUID(); + const result=await db.prepare('INSERT INTO forum_topics(id,category,title,body,author_id,author_name,created_at,last_activity_at) SELECT ?,?,?,?,?,?,?,? WHERE (SELECT COUNT(*) FROM forum_topics WHERE author_id=? AND created_at>?)<10 AND NOT EXISTS(SELECT 1 FROM forum_topics WHERE author_id=? AND created_at>?)').bind(id,data.category,title,body,user.id,name,now,now,user.id,now-3600000,user.id,now-30000).run(); + if(!result.meta.changes)return forumJson({error:'rate_limited',message:'Please wait before starting another topic.'},429);return forumJson({id},201); + } + const topicMatch=path.match(/^\/topics\/([^/]+)(?:\/(replies|close))?$/); + if(topicMatch){const [,id,action]=topicMatch;if(!forumId.test(id))return forumJson({error:'not_found'},404);const topic=await getForumTopic(db,id);if(!topic)return forumJson({error:'not_found'},404); + if(!action&&request.method==='GET'){const offset=Number(url.searchParams.get('offset')||0);if(!Number.isSafeInteger(offset)||offset<0||offset>100000)return forumJson({error:'invalid_offset'},400);const posts=await db.prepare('SELECT id,body,author_id,author_name,created_at FROM forum_posts WHERE topic_id=? AND deleted=0 ORDER BY created_at,id LIMIT 51 OFFSET ?').bind(id,offset).all();return forumJson({topic:{...publicTopic(topic,user),body:topic.body},replies:posts.results.slice(0,50).map(p=>publicPost(p,user)),nextOffset:posts.results.length>50?offset+50:null})} + if(action==='replies'&&request.method==='POST'){if(topic.closed)return forumJson({error:'topic_closed',message:'This topic is closed.'},409);const data=await forumBody(request),body=forumText(data.body,2,10000,'Reply'),name=forumText(data.displayName,2,40,'Display name'),now=Date.now(),postId=crypto.randomUUID();const batch=await db.batch([db.prepare('INSERT INTO forum_posts(id,topic_id,body,author_id,author_name,created_at) SELECT ?,?,?,?,?,? WHERE EXISTS(SELECT 1 FROM forum_topics WHERE id=? AND closed=0 AND deleted=0) AND (SELECT COUNT(*) FROM forum_posts WHERE author_id=? AND created_at>?)<5').bind(postId,id,body,user.id,name,now,id,user.id,now-60000),db.prepare('UPDATE forum_topics SET last_activity_at=? WHERE id=? AND EXISTS(SELECT 1 FROM forum_posts WHERE id=?)').bind(now,id,postId)]);if(!batch[0].meta.changes)return forumJson({error:'rate_limited',message:'Please wait before replying again.'},429);return forumJson({id:postId},201)} + if(!action&&request.method==='DELETE'){if(topic.author_id!==user.id&&!user.moderator)return forumJson({error:'forbidden'},403);await db.prepare('UPDATE forum_topics SET deleted=1 WHERE id=?').bind(id).run();return forumJson({ok:true})} + if(action==='close'&&request.method==='POST'){if(topic.author_id!==user.id&&!user.moderator)return forumJson({error:'forbidden'},403);const data=await forumBody(request);if(typeof data.closed!=='boolean')return forumJson({error:'invalid_state'},400);await db.prepare('UPDATE forum_topics SET closed=? WHERE id=?').bind(data.closed?1:0,id).run();return forumJson({ok:true})} + } + const postMatch=path.match(/^\/posts\/([^/]+)$/); + if(postMatch&&request.method==='DELETE'){const id=postMatch[1];if(!forumId.test(id))return forumJson({error:'not_found'},404);const post=await db.prepare('SELECT * FROM forum_posts WHERE id=? AND deleted=0').bind(id).first();if(!post)return forumJson({error:'not_found'},404);if(post.author_id!==user.id&&!user.moderator)return forumJson({error:'forbidden'},403);await db.prepare('UPDATE forum_posts SET deleted=1 WHERE id=?').bind(id).run();return forumJson({ok:true})} + if(path==='/reports'&&request.method==='POST'){const data=await forumBody(request),reason=forumText(data.reason,5,1000,'Reason');if(!['topic','post'].includes(data.targetType)||!forumId.test(data.targetId||''))return forumJson({error:'invalid_report'},400);const target=data.targetType==='topic'?await getForumTopic(db,data.targetId):await db.prepare('SELECT id FROM forum_posts WHERE id=? AND deleted=0').bind(data.targetId).first();if(!target)return forumJson({error:'not_found'},404);const now=Date.now();await db.prepare('INSERT OR IGNORE INTO forum_reports(id,target_type,target_id,reporter_id,reason,created_at) SELECT ?,?,?,?,?,? WHERE (SELECT COUNT(*) FROM forum_reports WHERE reporter_id=? AND created_at>?)<20').bind(crypto.randomUUID(),data.targetType,data.targetId,user.id,reason,now,user.id,now-3600000).run();return forumJson({ok:true},201)} + if(path==='/reports'&&request.method==='GET'){if(!user.moderator)return forumJson({error:'forbidden'},403);const rows=await db.prepare("SELECT r.id,r.target_type,r.target_id,r.reason,r.created_at,CASE WHEN r.target_type='topic' THEN r.target_id ELSE (SELECT topic_id FROM forum_posts WHERE id=r.target_id) END AS topicId FROM forum_reports r WHERE resolved=0 ORDER BY created_at DESC LIMIT 100").all();return forumJson({reports:rows.results})} + const reportMatch=path.match(/^\/reports\/([^/]+)\/resolve$/);if(reportMatch&&request.method==='POST'){if(!user.moderator)return forumJson({error:'forbidden'},403);if(!forumId.test(reportMatch[1]))return forumJson({error:'not_found'},404);await db.prepare('UPDATE forum_reports SET resolved=1 WHERE id=?').bind(reportMatch[1]).run();return forumJson({ok:true})} + return forumJson({error:'not_found'},404); + }catch(error){if(error.status)return forumJson({error:'invalid_request',message:error.message},error.status);return forumJson({error:'forums_unavailable',message:'The forum is temporarily unavailable.'},503)} +} diff --git a/website/worker/portal-api.mjs b/website/worker/portal-api.mjs new file mode 100644 index 00000000..b7e6490b --- /dev/null +++ b/website/worker/portal-api.mjs @@ -0,0 +1,26 @@ +const ticketCategories={'ban-appeal':'Ban appeal','staff-support':'Staff support'}; +const ticketStates={open:'Open',in_progress:'In progress',waiting_on_player:'Waiting on player',resolved:'Resolved',closed:'Closed'}; +const portalId=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; +const portalJson=(data,status=200)=>Response.json(data,{status,headers:{'Cache-Control':'no-store','X-Content-Type-Options':'nosniff'}}); +function portalIdentity(request,env){const id=request.headers.get('oai-authenticated-user-id')||'',email=(request.headers.get('oai-authenticated-user-email')||'').toLowerCase(),staff=[env.FORUM_ADMIN_EMAILS,env.SUPPORT_STAFF_EMAILS].filter(Boolean).join(',').split(',').map(x=>x.trim().toLowerCase()).filter(Boolean);return {id,authenticated:Boolean(id&&id.length<=200),staff:Boolean(id&&email&&staff.includes(email))}} +function portalText(value,min,max,name){if(typeof value!=='string')throw Object.assign(Error(`${name} is required.`),{status:400});const clean=value.trim();if(clean.lengthmax)throw Object.assign(Error(`${name} must be ${min}–${max} characters.`),{status:400});return clean} +async function portalBody(request){if(!/^application\/json(?:;|$)/i.test(request.headers.get('Content-Type')||''))throw Object.assign(Error('Send JSON content.'),{status:415});const reader=request.body?.getReader();if(!reader)throw Object.assign(Error('A request body is required.'),{status:400});let bytes=0,text='';const decoder=new TextDecoder();while(true){const {value,done}=await reader.read();if(done)break;bytes+=value.byteLength;if(bytes>60000){await reader.cancel();throw Object.assign(Error('Message is too large.'),{status:413})}text+=decoder.decode(value,{stream:true})}try{const data=JSON.parse(text+decoder.decode());if(!data||typeof data!=='object'||Array.isArray(data))throw Error('Invalid object');return data}catch{throw Object.assign(Error('Invalid JSON.'),{status:400})}} +function privateTicket(row,user){const {user_id,body,...data}=row;return {...data,isOwner:user_id===user.id,canManage:user.staff||user_id===user.id}} +async function getPrivateTicket(db,id,user){if(!portalId.test(id))return null;return db.prepare('SELECT t.*,p.display_name AS owner_name,p.minecraft_name,p.discord_name FROM support_tickets t JOIN player_profiles p ON p.user_id=t.user_id WHERE t.id=? AND (t.user_id=? OR ?=1)').bind(id,user.id,user.staff?1:0).first()} +export async function handlePortal(request,env){const url=new URL(request.url),path=url.pathname,user=portalIdentity(request,env),db=env.DB;try{ + if(path==='/api/portal/session'&&request.method==='GET')return portalJson({authenticated:user.authenticated,staff:user.staff,ticketCategories,ticketStates}); + if(!user.authenticated)return portalJson({error:'sign_in_required',message:'Sign in with ChatGPT to open your player portal.'},401); + if(!['GET','HEAD'].includes(request.method)&&request.headers.get('Origin')!==url.origin)return portalJson({error:'forbidden_origin'},403); + if(!db)return portalJson({error:'portal_unavailable',message:'The player portal is temporarily unavailable.'},503); + if(path==='/api/profile'&&request.method==='GET'){const profile=await db.prepare('SELECT display_name,minecraft_name,discord_name,created_at,updated_at FROM player_profiles WHERE user_id=?').bind(user.id).first();return portalJson({profile})} + if(path==='/api/profile'&&request.method==='POST'){const data=await portalBody(request),name=portalText(data.displayName,2,40,'Display name'),minecraft=portalText(data.minecraftName||'',0,32,'Minecraft name'),discord=portalText(data.discordName||'',0,50,'Discord handle'),now=Date.now();await db.prepare('INSERT INTO player_profiles(user_id,display_name,minecraft_name,discord_name,created_at,updated_at) VALUES(?,?,?,?,?,?) ON CONFLICT(user_id) DO UPDATE SET display_name=excluded.display_name,minecraft_name=excluded.minecraft_name,discord_name=excluded.discord_name,updated_at=excluded.updated_at').bind(user.id,name,minecraft,discord,now,now).run();return portalJson({ok:true})} + if(path==='/api/tickets'&&request.method==='GET'){const staffView=url.searchParams.get('view')==='staff';if(staffView&&!user.staff)return portalJson({error:'forbidden'},403);const status=url.searchParams.get('status')||'all',category=url.searchParams.get('category')||'all',offset=Number(url.searchParams.get('offset')||0);if((status!=='all'&&!ticketStates[status])||(category!=='all'&&!ticketCategories[category])||!Number.isSafeInteger(offset)||offset<0||offset>100000)return portalJson({error:'invalid_filter'},400);const rows=await db.prepare("SELECT t.*,p.display_name AS owner_name FROM support_tickets t JOIN player_profiles p ON p.user_id=t.user_id WHERE (?=1 OR t.user_id=?) AND (?='all' OR t.status=?) AND (?='all' OR t.category=?) ORDER BY t.updated_at DESC,t.id LIMIT 51 OFFSET ?").bind(staffView?1:0,user.id,status,status,category,category,offset).all();const count=await db.prepare("SELECT COUNT(*) AS count FROM support_tickets WHERE user_id=? AND status NOT IN ('closed','resolved')").bind(user.id).first();return portalJson({activeCount:count.count,tickets:rows.results.slice(0,50).map(r=>privateTicket(r,user)),nextOffset:rows.results.length>50?offset+50:null})} + if(path==='/api/tickets'&&request.method==='POST'){const profile=await db.prepare('SELECT * FROM player_profiles WHERE user_id=?').bind(user.id).first();if(!profile)return portalJson({error:'profile_required',message:'Save your player profile before opening a ticket.'},422);const data=await portalBody(request),subject=portalText(data.subject,5,120,'Subject'),body=portalText(data.body,10,12000,'Description');if(!ticketCategories[data.category])return portalJson({error:'invalid_category'},400);if(data.category==='ban-appeal'&&!profile.minecraft_name.trim())return portalJson({error:'minecraft_name_required',message:'Add your Minecraft player name to your profile before submitting a ban appeal.'},422);const id=crypto.randomUUID(),now=Date.now();const result=await db.prepare("INSERT INTO support_tickets(id,user_id,category,subject,body,created_at,updated_at) SELECT ?,?,?,?,?,?,? WHERE (SELECT COUNT(*) FROM support_tickets WHERE user_id=? AND created_at>?)<3 AND (SELECT COUNT(*) FROM support_tickets WHERE user_id=? AND status NOT IN ('resolved','closed'))<5").bind(id,user.id,data.category,subject,body,now,now,user.id,now-3600000,user.id).run();if(!result.meta.changes)return portalJson({error:'rate_limited',message:'You have reached the current limit for new tickets. Please continue an existing request or try later.'},429);return portalJson({id},201)} + const match=path.match(/^\/api\/tickets\/([^/]+)(?:\/(replies|status))?$/); + if(match){const [,id,action]=match;const ticket=await getPrivateTicket(db,id,user);if(!ticket)return portalJson({error:'not_found'},404); + if(!action&&request.method==='GET'){const offset=Number(url.searchParams.get('offset')||0);if(!Number.isSafeInteger(offset)||offset<0||offset>100000)return portalJson({error:'invalid_offset'},400);const messages=await db.prepare('SELECT id,author_name,author_role,body,created_at FROM support_messages WHERE ticket_id=? ORDER BY created_at,id LIMIT 51 OFFSET ?').bind(id,offset).all();return portalJson({ticket:{...privateTicket(ticket,user),body:ticket.body},messages:messages.results.slice(0,50),nextOffset:messages.results.length>50?offset+50:null})} + if(action==='replies'&&request.method==='POST'){if(ticket.status==='closed')return portalJson({error:'ticket_closed',message:'This ticket is closed. Reopen it before replying.'},409);const data=await portalBody(request),body=portalText(data.body,2,12000,'Reply'),profile=await db.prepare('SELECT display_name FROM player_profiles WHERE user_id=?').bind(user.id).first(),now=Date.now(),messageId=crypto.randomUUID();const results=await db.batch([db.prepare("INSERT INTO support_messages(id,ticket_id,author_id,author_name,author_role,body,created_at) SELECT ?,?,?,?,?,?,? WHERE EXISTS(SELECT 1 FROM support_tickets WHERE id=? AND status!='closed') AND (SELECT COUNT(*) FROM support_messages WHERE author_id=? AND author_role!='system' AND created_at>?)<5").bind(messageId,id,user.id,user.staff?'Staff':profile?.display_name||'Player',user.staff?'staff':'player',body,now,id,user.id,now-60000),db.prepare('UPDATE support_tickets SET updated_at=? WHERE id=? AND EXISTS(SELECT 1 FROM support_messages WHERE id=?)').bind(now,id,messageId)]);if(!results[0].meta.changes)return portalJson({error:'rate_limited',message:'Please wait before replying again.'},429);return portalJson({id:messageId},201)} + if(action==='status'&&request.method==='POST'){const data=await portalBody(request),status=data.status;if(!ticketStates[status])return portalJson({error:'invalid_status'},400);if(!user.staff&&!(ticket.user_id===user.id&&(status==='closed'||(status==='open'&&ticket.status==='closed'))))return portalJson({error:'forbidden'},403);if(status===ticket.status)return portalJson({ok:true});const now=Date.now();await db.batch([db.prepare('UPDATE support_tickets SET status=?,updated_at=? WHERE id=?').bind(status,now,id),db.prepare('INSERT INTO support_messages(id,ticket_id,author_id,author_name,author_role,body,created_at) VALUES(?,?,?,?,?,?,?)').bind(crypto.randomUUID(),id,user.id,user.staff?'Staff':'Player','system',`Status changed to ${ticketStates[status]}.`,now)]);return portalJson({ok:true})} + } + return portalJson({error:'not_found'},404); + }catch(error){if(error.status)return portalJson({error:'invalid_request',message:error.message},error.status);return portalJson({error:'portal_unavailable',message:'The player portal is temporarily unavailable.'},503)}} diff --git a/website/worker/runtime.mjs b/website/worker/runtime.mjs index add4d2bc..f781088d 100644 --- a/website/worker/runtime.mjs +++ b/website/worker/runtime.mjs @@ -1,4 +1,7 @@ import {handleFeed} from './feed-api.mjs'; +import {handleForum} from './forum-api.mjs'; +import {handleCommunity} from './community-api.mjs'; +import {handlePortal} from './portal-api.mjs'; // ASSET_DATA is injected by scripts/build.mjs. No credentials enter this bundle. const security={'X-Content-Type-Options':'nosniff','Referrer-Policy':'strict-origin-when-cross-origin','Content-Security-Policy':"default-src 'self'; img-src 'self' data:; style-src 'self' https://fonts.googleapis.com; font-src 'self' https://fonts.gstatic.com; script-src 'self'; connect-src 'self'; frame-ancestors 'self' https://chatgpt.com https://*.chatgpt.com; base-uri 'self'; object-src 'none'"}; -export default {async fetch(request,env){const url=new URL(request.url);if(url.pathname.startsWith('/api/'))return handleFeed(request,env);if(!['GET','HEAD'].includes(request.method))return new Response('Method not allowed',{status:405});let key;try{key=decodeURIComponent(url.pathname)}catch{return new Response('Bad request',{status:400})}if(key==='/')key='/index.html';const asset=ASSET_DATA[key];if(!asset)return new Response('Page not found',{status:404,headers:security});const [mime,b64]=asset;const data=request.method==='HEAD'?null:Uint8Array.from(atob(b64),c=>c.charCodeAt(0));return new Response(data,{headers:{...security,'Content-Type':mime,'Cache-Control':key.startsWith('/assets/')?'public, max-age=86400':'no-cache'}})}}; +export default {async fetch(request,env){const url=new URL(request.url);if(url.pathname==='/api/community')return handleCommunity(request);if(url.pathname==='/api/profile'||url.pathname.startsWith('/api/portal/')||url.pathname.startsWith('/api/tickets'))return handlePortal(request,env);if(url.pathname.startsWith('/api/forum'))return handleForum(request,env);if(url.pathname.startsWith('/api/'))return handleFeed(request,env);if(!['GET','HEAD'].includes(request.method))return new Response('Method not allowed',{status:405});let key;try{key=decodeURIComponent(url.pathname)}catch{return new Response('Bad request',{status:400})}if(key==='/')key='/index.html';const asset=ASSET_DATA[key];if(!asset)return new Response('Page not found',{status:404,headers:security});const [mime,b64]=asset;const data=request.method==='HEAD'?null:Uint8Array.from(atob(b64),c=>c.charCodeAt(0));return new Response(data,{headers:{...security,'Content-Type':mime,'Cache-Control':key.startsWith('/assets/')?'public, max-age=86400':'no-cache'}})}};