From ebdb8608660fc76df52e24a30faff1da42980e0d Mon Sep 17 00:00:00 2001 From: unimatrixgit <95320811+unimatrixgit@users.noreply.github.com> Date: Wed, 18 Nov 2026 21:43:44 +0100 Subject: [PATCH 1/4] Keep dev-key tests outside website-only deployment archive --- .forgejo/workflows/web-deploy.yml | 173 +++++++++--------- .../tests/jarvis-dev-clan-reset.test.mjs | 6 +- .../tests/jarvis-dev-key.test.mjs | 2 +- 3 files changed, 91 insertions(+), 90 deletions(-) rename {website => tools}/tests/jarvis-dev-clan-reset.test.mjs (93%) rename {website => tools}/tests/jarvis-dev-key.test.mjs (95%) diff --git a/.forgejo/workflows/web-deploy.yml b/.forgejo/workflows/web-deploy.yml index 101ef3e8..bd4621c4 100644 --- a/.forgejo/workflows/web-deploy.yml +++ b/.forgejo/workflows/web-deploy.yml @@ -1,86 +1,87 @@ -name: DuneRealms Web CI - -on: - push: - branches: - - main - paths: - - 'website/**' - - '.forgejo/workflows/web-deploy.yml' - workflow_dispatch: - -jobs: - web: - runs-on: dune-ci - steps: - - name: Checkout - shell: bash - env: - REPO_TOKEN: ${{ secrets.GITHUB_TOKEN }} - run: | - git init . - git -c http.extraheader="AUTHORIZATION: basic $(printf 'x-access-token:%s' "$REPO_TOKEN" | base64 -w0)" fetch --depth=1 https://www.dunerealms.com/git/unimatrix/MC.git "$GITHUB_SHA" - git checkout --detach FETCH_HEAD - - - name: Install Node 22 - uses: actions/setup-node@v4 - with: - node-version: '22' - - - name: Prepare publication comparison - shell: bash - env: - REPO_TOKEN: ${{ secrets.GITHUB_TOKEN }} - run: | - BEFORE=$(node -e 'const fs=require("fs");const p=process.env.GITHUB_EVENT_PATH;const e=p&&fs.existsSync(p)?JSON.parse(fs.readFileSync(p)):{};process.stdout.write(e.before||"");') - if [[ ! "$BEFORE" =~ ^[0-9a-f]{40}$ || "$BEFORE" =~ ^0+$ ]]; then - git -c http.extraheader="AUTHORIZATION: basic $(printf 'x-access-token:%s' "$REPO_TOKEN" | base64 -w0)" fetch --deepen=1 https://www.dunerealms.com/git/unimatrix/MC.git "$GITHUB_SHA" - BEFORE=$(git rev-parse HEAD^) - else - git -c http.extraheader="AUTHORIZATION: basic $(printf 'x-access-token:%s' "$REPO_TOKEN" | base64 -w0)" fetch --depth=1 https://www.dunerealms.com/git/unimatrix/MC.git "$BEFORE" - fi - node website/scripts/publication-changes.mjs "$BEFORE" "$GITHUB_SHA" - - - name: Verify deployment policy - run: | - node --test .forgejo/tests/web-deploy.test.mjs - python3 -m unittest discover -s website/ops -p 'test_*.py' - - - name: Build and test website - working-directory: website - run: | - corepack enable - corepack pnpm install --frozen-lockfile - corepack pnpm build - corepack pnpm test - - - name: Upload website build - if: github.ref == 'refs/heads/main' - uses: actions/upload-artifact@v3 - with: - name: DuneRealms-Website - path: website/dist/ - if-no-files-found: error - retention-days: 1 - - - name: Trigger deployment after successful CI - if: github.ref == 'refs/heads/main' - shell: bash - env: - DEPLOY_KEY: ${{ secrets.DUNEREALMS_DEPLOY_KEY }} - run: | - install -m 700 -d ~/.ssh - printf '%s\n' "$DEPLOY_KEY" > ~/.ssh/deploy_key - chmod 600 ~/.ssh/deploy_key - trap 'rm -f ~/.ssh/deploy_key' EXIT - printf '%s\n' '91.107.196.242 ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIC8x/XocsIz41fWHGty0DbZhSvafSQFt9jaHHgzdr55W root@ubuntu-4gb-fsn1-1' >> ~/.ssh/known_hosts - ssh -p 22 -i ~/.ssh/deploy_key -o IdentitiesOnly=yes -o BatchMode=yes -o StrictHostKeyChecking=yes dunedeploy@91.107.196.242 "$GITHUB_SHA" - rm -f ~/.ssh/deploy_key - - - name: Prune previous CI artifacts after confirmed publication - if: github.ref == 'refs/heads/main' - continue-on-error: true - shell: bash - env: - REPO_TOKEN: ${{ secrets.GITHUB_TOKEN }} - run: node website/scripts/prune-ci-artifacts.mjs +name: DuneRealms Web CI + +on: + push: + branches: + - main + paths: + - 'website/**' + - '.forgejo/workflows/web-deploy.yml' + workflow_dispatch: + +jobs: + web: + runs-on: dune-ci + steps: + - name: Checkout + shell: bash + env: + REPO_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + git init . + git -c http.extraheader="AUTHORIZATION: basic $(printf 'x-access-token:%s' "$REPO_TOKEN" | base64 -w0)" fetch --depth=1 https://www.dunerealms.com/git/unimatrix/MC.git "$GITHUB_SHA" + git checkout --detach FETCH_HEAD + + - name: Install Node 22 + uses: actions/setup-node@v4 + with: + node-version: '22' + + - name: Prepare publication comparison + shell: bash + env: + REPO_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + BEFORE=$(node -e 'const fs=require("fs");const p=process.env.GITHUB_EVENT_PATH;const e=p&&fs.existsSync(p)?JSON.parse(fs.readFileSync(p)):{};process.stdout.write(e.before||"");') + if [[ ! "$BEFORE" =~ ^[0-9a-f]{40}$ || "$BEFORE" =~ ^0+$ ]]; then + git -c http.extraheader="AUTHORIZATION: basic $(printf 'x-access-token:%s' "$REPO_TOKEN" | base64 -w0)" fetch --deepen=1 https://www.dunerealms.com/git/unimatrix/MC.git "$GITHUB_SHA" + BEFORE=$(git rev-parse HEAD^) + else + git -c http.extraheader="AUTHORIZATION: basic $(printf 'x-access-token:%s' "$REPO_TOKEN" | base64 -w0)" fetch --depth=1 https://www.dunerealms.com/git/unimatrix/MC.git "$BEFORE" + fi + node website/scripts/publication-changes.mjs "$BEFORE" "$GITHUB_SHA" + + - name: Verify deployment policy + run: | + node --test .forgejo/tests/web-deploy.test.mjs + python3 -m unittest discover -s website/ops -p 'test_*.py' + + - name: Build and test website + working-directory: website + run: | + corepack enable + corepack pnpm install --frozen-lockfile + corepack pnpm build + corepack pnpm test + node --test --test-concurrency=1 ../tools/tests/*.test.mjs + + - name: Upload website build + if: github.ref == 'refs/heads/main' + uses: actions/upload-artifact@v3 + with: + name: DuneRealms-Website + path: website/dist/ + if-no-files-found: error + retention-days: 1 + + - name: Trigger deployment after successful CI + if: github.ref == 'refs/heads/main' + shell: bash + env: + DEPLOY_KEY: ${{ secrets.DUNEREALMS_DEPLOY_KEY }} + run: | + install -m 700 -d ~/.ssh + printf '%s\n' "$DEPLOY_KEY" > ~/.ssh/deploy_key + chmod 600 ~/.ssh/deploy_key + trap 'rm -f ~/.ssh/deploy_key' EXIT + printf '%s\n' '91.107.196.242 ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIC8x/XocsIz41fWHGty0DbZhSvafSQFt9jaHHgzdr55W root@ubuntu-4gb-fsn1-1' >> ~/.ssh/known_hosts + ssh -p 22 -i ~/.ssh/deploy_key -o IdentitiesOnly=yes -o BatchMode=yes -o StrictHostKeyChecking=yes dunedeploy@91.107.196.242 "$GITHUB_SHA" + rm -f ~/.ssh/deploy_key + + - name: Prune previous CI artifacts after confirmed publication + if: github.ref == 'refs/heads/main' + continue-on-error: true + shell: bash + env: + REPO_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: node website/scripts/prune-ci-artifacts.mjs diff --git a/website/tests/jarvis-dev-clan-reset.test.mjs b/tools/tests/jarvis-dev-clan-reset.test.mjs similarity index 93% rename from website/tests/jarvis-dev-clan-reset.test.mjs rename to tools/tests/jarvis-dev-clan-reset.test.mjs index d4e26874..b8ad15f8 100644 --- a/website/tests/jarvis-dev-clan-reset.test.mjs +++ b/tools/tests/jarvis-dev-clan-reset.test.mjs @@ -1,7 +1,7 @@ import test from 'node:test';import assert from 'node:assert/strict';import {randomUUID} from 'node:crypto'; -import {BankFixture} from './postbank-fixture.mjs'; -import {createDevKeyAuthority} from '../../tools/jarvis-dev-key.mjs'; -import {clanResetManifest,executeClanReset} from '../../tools/jarvis-dev-clan-reset.mjs'; +import {BankFixture} from '../../website/tests/postbank-fixture.mjs'; +import {createDevKeyAuthority} from '../jarvis-dev-key.mjs'; +import {clanResetManifest,executeClanReset} from '../jarvis-dev-clan-reset.mjs'; function fixture(){const db=new BankFixture();db.sqlite.exec(` CREATE TABLE site_accounts(id TEXT PRIMARY KEY,username TEXT); CREATE TABLE site_clans(id TEXT PRIMARY KEY,name TEXT,owner_id TEXT,active INT,version INT,updated_at INT); diff --git a/website/tests/jarvis-dev-key.test.mjs b/tools/tests/jarvis-dev-key.test.mjs similarity index 95% rename from website/tests/jarvis-dev-key.test.mjs rename to tools/tests/jarvis-dev-key.test.mjs index 3ee2be96..6e19600d 100644 --- a/website/tests/jarvis-dev-key.test.mjs +++ b/tools/tests/jarvis-dev-key.test.mjs @@ -1,5 +1,5 @@ import test from 'node:test';import assert from 'node:assert/strict'; -import {createDevKeyAuthority} from '../../tools/jarvis-dev-key.mjs'; +import {createDevKeyAuthority} from '../jarvis-dev-key.mjs'; const dev={id:'developer'},manifest={action:'clan-reset',state:'planned',deleteClanIds:['test'],retainClanIds:['official','mine']}; const setup=(extra={})=>createDevKeyAuthority({secret:'ab'.repeat(32),environment:'test',authorize:async actor=>actor.id===dev.id,...extra}); test('dev key binds exact manifest, actor and environment, and audit contains no secret',async()=>{ From bf8cedaf43947d37486fe39952107302ebc08a38 Mon Sep 17 00:00:00 2001 From: unimatrixgit <95320811+unimatrixgit@users.noreply.github.com> Date: Wed, 18 Nov 2026 22:44:56 +0100 Subject: [PATCH 2/4] Share complete dropdown chrome with forums and support; keep menus above cards --- website/scripts/install-shared-header.mjs | 9 ++++++--- website/web/portal-navigation.css | 11 +++++++++++ 2 files changed, 17 insertions(+), 3 deletions(-) diff --git a/website/scripts/install-shared-header.mjs b/website/scripts/install-shared-header.mjs index 61e3e9cf..3bf12b5c 100644 --- a/website/scripts/install-shared-header.mjs +++ b/website/scripts/install-shared-header.mjs @@ -4,6 +4,9 @@ import {existsSync, readFileSync,writeFileSync,copyFileSync} from 'node:fs'; import {SHARED_HEADER,SHARED_HEAD,PORTAL_SCRIPT,PORTAL_CSS,CONTEXT_SCRIPT,CONTEXT_CSS} from './portal-navigation.mjs'; const release=process.argv[2],integrations=process.argv[3]; if(!release||!integrations)throw Error('Provide release and integration directories'); +// Native apps receive the complete canonical chrome, including dropdowns. +const navigationCSS=readFileSync(release+'/web/portal-navigation.css','utf8'); +const navigationJS=readFileSync(release+'/web/portal-navigation.js','utf8'); const cp=release+'/control-panel/public/cp-v2/index.html';let html=readFileSync(cp,'utf8'); html=html.replace(/]*>[\s\S]*?<\/header>/,SHARED_HEADER); if(!html.includes('https://www.dunerealms.com/portal-navigation.js'))html=html.replace('',SHARED_HEAD+''); @@ -15,8 +18,8 @@ copyFileSync(release+'/integrations/osticket/dune-support.css',integrations+'/os for(const app of ['mybb','osticket']){ writeFileSync(integrations+'/'+app+'/dune-actions.css',BUTTON_CSS); writeFileSync(integrations+'/'+app+'/dune-actions.js',BUTTON_SCRIPT); - writeFileSync(integrations+'/'+app+'/dune-navigation.js',PORTAL_SCRIPT+CONTEXT_SCRIPT+BUTTON_SCRIPT+RELEASE_SCRIPT); - writeFileSync(integrations+'/'+app+'/dune-navigation.css',PORTAL_CSS+CONTEXT_CSS+BUTTON_CSS+RELEASE_CSS); + writeFileSync(integrations+'/'+app+'/dune-navigation.js',navigationJS+CONTEXT_SCRIPT+BUTTON_SCRIPT+RELEASE_SCRIPT); + writeFileSync(integrations+'/'+app+'/dune-navigation.css',navigationCSS+CONTEXT_CSS+BUTTON_CSS+RELEASE_CSS); } let server=readFileSync(release+'/control-panel/server.mjs','utf8'); server=server.replace("script-src 'self'; style-src 'self' https://fonts.googleapis.com;", "script-src 'self' https://www.dunerealms.com; style-src 'self' https://www.dunerealms.com https://fonts.googleapis.com;"); @@ -26,7 +29,7 @@ console.log('Shared header installed in CP and native integration templates'); // The Clan center serves local copies to retain the same masthead styles. const clans='/home/dunerealms/htdocs/clans.dunerealms.com'; -if(existsSync(clans+'/index.html')){writeFileSync(clans+'/dune-navigation.css',PORTAL_CSS+CONTEXT_CSS+BUTTON_CSS+RELEASE_CSS);writeFileSync(clans+'/dune-navigation.js',PORTAL_SCRIPT+CONTEXT_SCRIPT+BUTTON_SCRIPT+RELEASE_SCRIPT);} +if(existsSync(clans+'/index.html')){writeFileSync(clans+'/dune-navigation.css',navigationCSS+CONTEXT_CSS+BUTTON_CSS+RELEASE_CSS);writeFileSync(clans+'/dune-navigation.js',navigationJS+CONTEXT_SCRIPT+BUTTON_SCRIPT+RELEASE_SCRIPT);} // Persistent shared nginx aliases read these exact files on every site. const chrome='/var/lib/dunerealms-public-rates'; diff --git a/website/web/portal-navigation.css b/website/web/portal-navigation.css index 5c828746..535543ea 100644 --- a/website/web/portal-navigation.css +++ b/website/web/portal-navigation.css @@ -133,3 +133,14 @@ header.dune-site-header nav[aria-label="Main navigation"] a,header.dune-site-hea /* Central click/tap dropdown navigation. */ header nav[aria-label="Main navigation"]{gap:14px!important}header nav[aria-label="Main navigation"]>a,header nav[aria-label="Main navigation"] summary{font:600 15px/1.3 system-ui,sans-serif!important;min-height:58px;padding:8px 10px!important;display:flex;align-items:center;gap:8px;color:#edddbc;cursor:pointer;box-sizing:border-box}header nav[aria-label="Main navigation"]>a>img,header nav[aria-label="Main navigation"] summary>img{width:42px!important;height:42px!important;object-fit:contain}header nav[aria-label="Main navigation"] .dune-menu-group{position:relative}header nav[aria-label="Main navigation"] summary{list-style:none;border:1px solid transparent;border-radius:8px}header nav[aria-label="Main navigation"] summary::-webkit-details-marker{display:none}header nav[aria-label="Main navigation"] summary:after{content:'▾';font-size:11px;color:#d1ad61}header nav[aria-label="Main navigation"] details[open]>summary,header nav[aria-label="Main navigation"] summary:hover{background:#254639;border-color:#b89a55}header nav[aria-label="Main navigation"] .dune-menu-dropdown{position:absolute;z-index:300;top:calc(100% + 8px);left:0;min-width:250px;padding:9px;background:linear-gradient(140deg,#213e31,#0c241c);border:1px solid #bb9d55;border-radius:10px;box-shadow:0 15px 35px #0008}header nav[aria-label="Main navigation"] details:last-of-type .dune-menu-dropdown{left:auto;right:0}header nav[aria-label="Main navigation"] .dune-menu-dropdown a{display:flex;align-items:center;gap:12px;padding:9px 12px;min-height:48px;color:#edddbc;text-decoration:none;white-space:nowrap;font:500 14px/1.3 system-ui;border-radius:6px}header nav[aria-label="Main navigation"] .dune-menu-dropdown img{width:36px;height:36px;object-fit:contain}header nav[aria-label="Main navigation"] .dune-menu-dropdown a:hover,header nav[aria-label="Main navigation"] .dune-menu-dropdown a:focus-visible{background:#42604b;color:#ffe4a4}header nav[aria-label="Main navigation"] summary:focus-visible{outline:2px solid #e9c573;outline-offset:3px}@media(max-width:1240px){header nav[aria-label="Main navigation"] .dune-menu-group{min-width:0}header nav[aria-label="Main navigation"] .dune-menu-dropdown{position:static;min-width:0;margin-top:5px}header nav[aria-label="Main navigation"] .dune-menu-dropdown a{white-space:normal}header nav[aria-label="Main navigation"] summary{font-size:16px!important}header nav[aria-label="Main navigation"]>a{justify-content:flex-start}} + +/* Canonical chrome stays above portal cards and native application surfaces. */ +header.dune-site-header{position:relative!important;z-index:1000!important;isolation:isolate;overflow:visible!important} +header.dune-site-header nav[aria-label="Main navigation"]{position:relative!important;z-index:10;overflow:visible!important} +header.dune-site-header nav[aria-label="Main navigation"]>.dune-menu-group{display:block;float:none;margin:0;min-width:0} +header.dune-site-header nav[aria-label="Main navigation"] .dune-menu-group:not([open])>.dune-menu-dropdown{display:none!important} +header.dune-site-header nav[aria-label="Main navigation"] .dune-menu-group[open]{z-index:20} +header.dune-site-header nav[aria-label="Main navigation"] .dune-menu-dropdown{box-sizing:border-box;max-width:calc(100vw - 24px)} + +/* Reserve the dedication's height so it never covers Home or another menu. */ +@media(min-width:1101px){header.dune-site-header:has(>.dune-memorial)>.wordmark{min-height:240px;display:flex;flex-direction:column;align-items:center;justify-content:center}} From 12da2b6a85979def75dd44eeef766a6ebed90ade Mon Sep 17 00:00:00 2001 From: unimatrixgit <95320811+unimatrixgit@users.noreply.github.com> Date: Wed, 18 Nov 2026 22:50:51 +0100 Subject: [PATCH 3/4] Classify JARVIS player keys and sealed system instruments; hide system redemption secrets --- website/control-panel/clan-key-receipts.mjs | 5 ++-- .../public/codex-code-format.mjs | 4 +-- .../public/cp-v2/cp-v2-jarvis-register.mjs | 2 +- .../public/cp-v2/cp-v2-rewards.mjs | 4 +-- website/node/jarvis-management.mjs | 4 ++- website/node/organisation-key-policy.mjs | 25 +++++++++++++++++ website/node/organisation-keys.mjs | 27 +++++++------------ .../tests/organisation-key-policy.test.mjs | 17 ++++++++++++ website/tests/original-keys.test.mjs | 12 +++++++++ 9 files changed, 75 insertions(+), 25 deletions(-) create mode 100644 website/node/organisation-key-policy.mjs create mode 100644 website/tests/organisation-key-policy.test.mjs diff --git a/website/control-panel/clan-key-receipts.mjs b/website/control-panel/clan-key-receipts.mjs index d014daf6..019b309f 100644 --- a/website/control-panel/clan-key-receipts.mjs +++ b/website/control-panel/clan-key-receipts.mjs @@ -4,6 +4,7 @@ import {accessFor} from '../node/permissions.mjs'; import {ensureOriginalKeys} from '../node/organisation-key-service.mjs'; import {upgradeOriginalClan} from '../node/clan-key-upgrade.mjs'; import {OrganisationKeyError} from '../node/organisation-keys.mjs'; +import {privateKeyPresentation} from '../node/organisation-key-policy.mjs'; export function createClanKeyReceipts(db,{authenticate=r=>identity(r,db),access=u=>accessFor(db,u),keys=null,origin='https://cp.dunerealms.com'}={}){return async request=>{ const reply=(data,status=200)=>Response.json(data,{status,headers:{'Cache-Control':'private, no-store',Vary:'Cookie'}}); if(!['GET','POST'].includes(request.method))return reply({message:'Method not allowed.'},405); @@ -21,7 +22,7 @@ export function createClanKeyReceipts(db,{authenticate=r=>identity(r,db),access= } if(keys)await ensureOriginalKeys(keys,user.id); const secrets=keys?new Map((await keys.list(user.id)).map(r=>[r.id,r])):new Map(); - const {results}=await db.prepare("SELECT k.id,k.key_type,k.created_at,k.used_at,k.expires_at,k.revoked_at,k.target_id,c.name,c.tag,ch.charter_kind FROM organisation_keys k LEFT JOIN site_clans c ON c.id=k.target_id AND k.key_type IN ('clan-founding','clan-subhouse','political-appointment') LEFT JOIN site_clan_charters ch ON ch.clan_id=c.id WHERE k.account_id=? AND k.key_type IN ('clan-founding','company-founding','political-appointment','political-clan','clan-subhouse','company-subsidiary') ORDER BY k.created_at,k.id LIMIT 100").bind(user.id).all(); + const {results}=await db.prepare("SELECT k.id,k.key_type,k.created_at,k.used_at,k.expires_at,k.revoked_at,k.target_id,c.name,c.tag,ch.charter_kind FROM organisation_keys k LEFT JOIN site_clans c ON c.id=k.target_id AND k.key_type IN ('clan-founding','clan-subhouse','political-appointment') LEFT JOIN site_clan_charters ch ON ch.clan_id=c.id WHERE k.account_id=? AND k.key_type IN ('clan-founding','company-founding','political-appointment','political-clan','clan-subhouse','company-subsidiary','xp-correction','xp-transfer') ORDER BY k.created_at,k.id LIMIT 100").bind(user.id).all(); if(db.companyDeedsEnabled){const ids=[...new Set(results.filter(r=>['company-founding','company-subsidiary'].includes(r.key_type)&&r.target_id).map(r=>r.target_id))];if(ids.length){const {results:companies}=await db.prepare('SELECT c.id,c.name,d.charter_kind FROM corrino_companies c JOIN site_company_deeds d ON d.company_id=c.id WHERE c.id IN ('+ids.map(()=>'?').join(',')+')').bind(...ids).all();const map=new Map(companies.map(c=>[c.id,c]));for(const record of results)if(['company-founding','company-subsidiary'].includes(record.key_type)&&map.has(record.target_id))Object.assign(record,{name:map.get(record.target_id).name,charter_kind:map.get(record.target_id).charter_kind});}} - return reply({keys:results.map(r=>({id:r.id,type:r.key_type==='clan-founding'?'clan':r.key_type==='company-founding'?'company':r.key_type==='political-clan'?'politics-clan':r.key_type==='clan-subhouse'?'subhouse':r.key_type==='company-subsidiary'?'subsidiary':'politics',createdAt:Number(r.created_at),status:r.revoked_at!=null?'Revoked':r.used_at!=null?'Applied':r.expires_at!=null&&Number(r.expires_at)<=Date.now()?'Expired':keys?'Available':'Issued',clan:r.name||null,clanId:r.target_id,charter:r.charter_kind||null,code:secrets.get(r.id)?.code||null,edition:secrets.get(r.id)?.edition||null}))}); + return reply({keys:results.map(r=>({id:r.id,...privateKeyPresentation(r.key_type),type:r.key_type==='clan-founding'?'clan':r.key_type==='company-founding'?'company':r.key_type==='political-clan'?'politics-clan':r.key_type==='clan-subhouse'?'subhouse':r.key_type==='company-subsidiary'?'subsidiary':r.key_type==='xp-correction'?'xp-correction':r.key_type==='xp-transfer'?'xp-transfer':'politics',createdAt:Number(r.created_at),status:r.revoked_at!=null?'Revoked':r.used_at!=null?'Applied':r.expires_at!=null&&Number(r.expires_at)<=Date.now()?'Expired':keys?'Available':'Issued',clan:r.name||null,clanId:r.target_id,charter:r.charter_kind||null,code:privateKeyPresentation(r.key_type).showCode?(secrets.get(r.id)?.code||null):null,edition:secrets.get(r.id)?.edition||null}))}); };} diff --git a/website/control-panel/public/codex-code-format.mjs b/website/control-panel/public/codex-code-format.mjs index 9425b44f..278413fc 100644 --- a/website/control-panel/public/codex-code-format.mjs +++ b/website/control-panel/public/codex-code-format.mjs @@ -1,6 +1,6 @@ // Shared syntax only: a readable edition is never proof of ownership or authority. -const legacy=/^(ECO-SNAP|STAFF-LINK|STAFF-COM|STAFF-POL|XFR|CLAN-SUB|COM-SUB|POL-CLAN|QST|QSM|CLAN|COM|POL)-([A-F0-9]{48})$/; -const versioned=/^(ECO-SNAP|STAFF-LINK|STAFF-COM|STAFF-POL|XFR|CLAN-SUB|COM-SUB|POL-CLAN|QST|QSM|CLAN|COM|POL)-(ALPHA|BETA|LIVE)-((?:0|[1-9]\d{0,2})(?:\.(?:0|[1-9]\d{0,2})){3})-(S\d{2,4})-([A-F0-9]{8}(?:-[A-F0-9]{8}){5})$/; +const legacy=/^(PRG|NEWS|XPC|XPX|ECO-SNAP|STAFF-LINK|STAFF-COM|STAFF-POL|XFR|CLAN-SUB|COM-SUB|POL-CLAN|QST|QSM|CLAN|COM|POL)-([A-F0-9]{48})$/; +const versioned=/^(PRG|NEWS|XPC|XPX|ECO-SNAP|STAFF-LINK|STAFF-COM|STAFF-POL|XFR|CLAN-SUB|COM-SUB|POL-CLAN|QST|QSM|CLAN|COM|POL)-(ALPHA|BETA|LIVE)-((?:0|[1-9]\d{0,2})(?:\.(?:0|[1-9]\d{0,2})){3})-(S\d{2,4})-([A-F0-9]{8}(?:-[A-F0-9]{8}){5})$/; export function parseOrganisationCode(value){ if(typeof value!=='string'||value.length>128)throw new TypeError('Invalid organisation code'); const code=value.trim().toUpperCase(),old=code.match(legacy); diff --git a/website/control-panel/public/cp-v2/cp-v2-jarvis-register.mjs b/website/control-panel/public/cp-v2/cp-v2-jarvis-register.mjs index 9443572b..3ac02bc1 100644 --- a/website/control-panel/public/cp-v2/cp-v2-jarvis-register.mjs +++ b/website/control-panel/public/cp-v2/cp-v2-jarvis-register.mjs @@ -1,7 +1,7 @@ import {createUserAPI} from './cp-v2-user-api.mjs'; const el=(tag,text)=>{const node=document.createElement(tag);if(text!==undefined)node.textContent=text;return node;}; const date=value=>value?new Date(Number(value)).toLocaleString('en-GB'):'—'; -const columns={keys:[['ID','id'],['Type','type'],['Recipient','recipient'],['Issued','created_at'],['State',row=>row.revoked_at?'Revoked':row.used_at?'Used':row.expires_at&&Number(row.expires_at)<=Date.now()?'Expired':'Available']],deeds:[['ID','id'],['Office','type'],['Holder','holder'],['Starts','starts_at'],['Expires','expires_at'],['State','state']],listings:[['Listing','title'],['Type','type'],['Organisation','owner'],['State','state'],['Created','created_at']],delivery:[['Listing','listing'],['Channel','channel'],['State','state'],['Attempts','attempts'],['Next attempt','next_attempt']],history:[['Time','created_at'],['Instrument','instrument'],['Action','action'],['Account','actor'],['Target','target_id']]}; +const columns={keys:[['ID','id'],['Type','type'],['Family','family'],['Operation','operation'],['Recipient','recipient'],['Issued','created_at'],['State',row=>row.revoked_at?'Revoked':row.used_at?'Used':row.expires_at&&Number(row.expires_at)<=Date.now()?'Expired':'Available']],deeds:[['ID','id'],['Office','type'],['Holder','holder'],['Starts','starts_at'],['Expires','expires_at'],['State','state']],listings:[['Listing','title'],['Type','type'],['Organisation','owner'],['State','state'],['Created','created_at']],delivery:[['Listing','listing'],['Channel','channel'],['State','state'],['Attempts','attempts'],['Next attempt','next_attempt']],history:[['Time','created_at'],['Instrument','instrument'],['Action','action'],['Account','actor'],['Target','target_id']]}; export function createJarvisRegister(section,{fetcher=fetch}={}){ const controller=new AbortController(),api=createUserAPI(fetcher,controller.signal),root=el('section'),status=el('p'),records=el('div'),nav=el('nav');root.className='codex-live-register';status.setAttribute('role','status');let active=true,loaded=false,busy=false,page=1; const previous=el('button','← Previous'),next=el('button','Next →'),refresh=el('button','Refresh'),pageLabel=el('span');for(const button of [previous,next,refresh])button.type='button';nav.append(previous,pageLabel,next,refresh);root.append(status,records,nav); diff --git a/website/control-panel/public/cp-v2/cp-v2-rewards.mjs b/website/control-panel/public/cp-v2/cp-v2-rewards.mjs index 8fb0ef7e..c1f80f6b 100644 --- a/website/control-panel/public/cp-v2/cp-v2-rewards.mjs +++ b/website/control-panel/public/cp-v2/cp-v2-rewards.mjs @@ -19,7 +19,7 @@ function table(target,head,rows){const wrap=el('div',undefined,'cp-v2-company-ta export function mountRewards(host,{fetcher=fetch,initialTab}={}){ let active=true,busy=false,uncertain=false,orders=[];const controller=new AbortController(),{request}=createUserAPI(fetcher,controller.signal); const codes=el('section'),community=el('section'),tokens=el('section'),refresh=el('button','Refresh codes'),status=el('p','Opening your private rewards register…');status.setAttribute('role','status');refresh.type='button';codes.append(refresh); - const directory=el('section',undefined,'reward-code-directory'),filter=el('input'),typeFilter=el('select'),listing=el('div'),groups=new Map();filter.type='search';filter.placeholder='Search codes, rewards or references';filter.setAttribute('aria-label','Search your codes');typeFilter.setAttribute('aria-label','Filter code type');for(const [value,label] of [['all','All code types'],['kit','Kits'],['token','Upgrade Tokens'],['clan','Clan founding'],['company','Company clan founding'],['politics-clan','Political clan membership'],['subhouse','Subhouse founding'],['subsidiary','Subsidiary founding'],['politics','Political decisions'],['community','Community rewards']]){const option=el('option',label);option.value=value;typeFilter.append(option);}const controls=el('div',undefined,'reward-code-controls');controls.append(filter,typeFilter);const banner=el('header',undefined,'reward-code-banner'),crest=el('img');crest.src='https://www.dunerealms.com/assets/imperial-seal-128.png';crest.alt='';const copy=el('div');copy.append(el('small','SPOST · PRIVATE ENTITLEMENT REGISTER'),el('h4','Your codes. Your next chapter.'),el('p','Kits KIT-… · Upgrades UP-… · Clans CLAN-… · Companies COM-… · Royal POL-…'));banner.append(crest,copy);directory.append(banner,controls,listing);codes.append(status,directory); + const directory=el('section',undefined,'reward-code-directory'),filter=el('input'),typeFilter=el('select'),listing=el('div'),groups=new Map();filter.type='search';filter.placeholder='Search codes, rewards or references';filter.setAttribute('aria-label','Search your codes');typeFilter.setAttribute('aria-label','Filter code type');for(const [value,label] of [['all','All code types'],['kit','Kits'],['token','Upgrade Tokens'],['clan','Clan founding'],['company','Company clan founding'],['politics-clan','Political clan membership'],['subhouse','Subhouse founding'],['subsidiary','Subsidiary founding'],['politics','Political decisions'],['community','Community rewards'],['xp-correction','XP compensation'],['xp-transfer','Season XP transfer']]){const option=el('option',label);option.value=value;typeFilter.append(option);}const controls=el('div',undefined,'reward-code-controls');controls.append(filter,typeFilter);const banner=el('header',undefined,'reward-code-banner'),crest=el('img');crest.src='https://www.dunerealms.com/assets/imperial-seal-128.png';crest.alt='';const copy=el('div');copy.append(el('small','SPOST · PRIVATE ENTITLEMENT REGISTER'),el('h4','Your codes. Your next chapter.'),el('p','Kits KIT-… · Upgrades UP-… · Clans CLAN-… · Companies COM-… · Royal POL-…'));banner.append(crest,copy);directory.append(banner,controls,listing);codes.append(status,directory); function paintCodes(){const q=filter.value.trim().toLowerCase(),rows=[];for(const [kind,group] of groups){if(typeFilter.value!=='all'&&typeFilter.value!==kind)continue;for(const row of group.rows){if(q&&!([group.title,...row.map(v=>typeof v==='object'?v.textContent:v)].join(' ').toLowerCase().includes(q)))continue;rows.push([createCodeTypeIcon(kind),...row]);}}table(listing,['Type','Reward / entitlement','Reference / amount','Status','Private code / action'],rows);} function setCodes(kind,title,rows){groups.set(kind,{title,rows:rows.length?rows:[[title+' register','—','No records','—']]});paintCodes();} for(const [kind,title] of [['clan','Clan founding'],['company','Company clan founding'],['politics-clan','Political clan membership'],['subhouse','Subhouse founding'],['subsidiary','Subsidiary founding']])setCodes(kind,title,[[title+' register','Once per account','Loading…','—']]);for(const [kind,title] of [['kit','Kit'],['token','Upgrade Token'],['community','Community reward']])setCodes(kind,title,[[title+' register','—','Loading…','—']]);filter.oninput=typeFilter.onchange=paintCodes;const tailor=el('a','Apply Upgrade Tokens in Imperial Tailor →');tailor.href='#realm/kits-exchange';directory.append(tailor);directory.append(el('p','Clan and Royal grants appear here after issuance. Applied grants are receipts and cannot be reused. Formats: KIT-…, UP-…, CLAN-… and COM-…. Existing DRK/DRU codes remain valid.','reward-code-note')); @@ -34,7 +34,7 @@ export function mountRewards(host,{fetcher=fetch,initialTab}={}){ if(data[0].status==='fulfilled'){orders=data[0].value.orders;groupKitReceipts(orders);render();uncertain=false;}else{orders=[];setCodes('kit','Kit',[['Kit register','—',data[0].reason.message,'—']]);} community.replaceChildren();if(data[1].status==='fulfilled'){const d=data[1].value;if(!Array.isArray(d.available)||!Array.isArray(d.history))setCodes('community','Community reward',[['Community register','—','Community reward records could not be confirmed.','—']]);else{setCodes('community','Community reward',[...d.available,...d.history].map(row=>[row.month==='season-tavren-ii'?'Tavren II Aedrecht':row.month,row.reward_amount+' DM',row.delivered_at?'Delivered':row.delivery_ready===false?'Delivery not available':'Available',row.personal_code&&row.delivery_ready!==false&&/^[a-z0-9-]{8,128}$/i.test(row.personal_code)?codeCell('/communitycode '+row.personal_code,true):'—']));if(!d.linked)community.append(el('p','Link your Minecraft identity to see earned community rewards.'));}}else setCodes('community','Community reward',[['Community register','—',data[1].reason.message,'—']]); tokens.replaceChildren();if(data[2].status==='fulfilled'&&Array.isArray(data[2].value.tokens)){setCodes('token','Upgrade Token',data[2].value.tokens.map(row=>['Upgrade Token',new Date(row.createdAt).toLocaleString(),row.usedAt?'Used':'Available',!row.usedAt&&/^DRU-[A-F0-9]{48}$/.test(row.code||'')?codeCell(row.code):'—']));const workshop=el('a','Apply tokens in Imperial Tailor →');workshop.href='#realm/kits-exchange';tokens.append(workshop);}else setCodes('token','Upgrade Token',[['Token register','—',data[2].reason?.message||'Upgrade Token records could not be confirmed.','—']]); - if(data[3].status==='fulfilled'){const records=data[3].value.keys||[];for(const [kind,title]of [['clan','Clan founding'],['company','Company clan founding'],['politics-clan','Political clan membership'],['subhouse','Subhouse founding'],['subsidiary','Subsidiary founding'],['politics','Royal appointment']])setCodes(kind,title,records.filter(r=>r.type===kind).map(r=>[r.clan||title,r.id,r.status,r.status==='Applied'?'Applied to '+(r.clan||'your organisation')+' · '+(['subhouse','subsidiary'].includes(r.type)?'Parent-bound charter':r.type==='politics-clan'?'Office membership':r.charter==='royal'?'Royal House':'Registered charter'):r.code?codeCell(r.code):'—']));}else for(const [kind,title]of [['clan','Clan founding'],['company','Company clan founding'],['politics-clan','Political clan membership'],['subhouse','Subhouse founding'],['subsidiary','Subsidiary founding'],['politics','Royal appointment']])setCodes(kind,title,[[title,'—',data[3].reason.message,'—']]); + if(data[3].status==='fulfilled'){const records=(data[3].value.keys||[]).filter(row=>row.family!=='system');for(const [kind,title]of [['clan','Clan founding'],['company','Company clan founding'],['politics-clan','Political clan membership'],['subhouse','Subhouse founding'],['subsidiary','Subsidiary founding'],['politics','Royal appointment'],['xp-correction','XP compensation'],['xp-transfer','Season XP transfer']])setCodes(kind,title,records.filter(r=>r.type===kind).map(r=>[r.clan||title,r.id,r.status,r.status==='Applied'?'Applied to '+(r.clan||'your organisation')+' · '+(['subhouse','subsidiary'].includes(r.type)?'Parent-bound charter':r.type==='politics-clan'?'Office membership':r.charter==='royal'?'Royal House':'Registered charter'):r.code?codeCell(r.code):'—']));}else for(const [kind,title]of [['clan','Clan founding'],['company','Company clan founding'],['politics-clan','Political clan membership'],['subhouse','Subhouse founding'],['subsidiary','Subsidiary founding'],['politics','Royal appointment'],['xp-correction','XP compensation'],['xp-transfer','Season XP transfer']])setCodes(kind,title,[[title,'—',data[3].reason.message,'—']]); status.textContent=data.every(row=>row.status==='fulfilled')?'Your private reward records are loaded.':'Some reward services are unavailable. Other records remain visible.'; }catch(error){if(active){status.textContent=error.message;groups.clear();paintCodes();orders=[];community.replaceChildren();tokens.replaceChildren();uncertain=true;}}finally{busy=false;if(active){refresh.disabled=false;desk.setLocked(uncertain);}} } diff --git a/website/node/jarvis-management.mjs b/website/node/jarvis-management.mjs index 46edec76..afce4103 100644 --- a/website/node/jarvis-management.mjs +++ b/website/node/jarvis-management.mjs @@ -1,5 +1,6 @@ import {identity} from './auth.mjs'; import {can} from './permissions.mjs'; +import {KEY_TYPES} from './organisation-key-policy.mjs'; import {currentCodexEdition} from './organisation-key-service.mjs'; const reply=(body,status=200)=>Response.json(body,{status,headers:{'Cache-Control':'private, no-store','X-Content-Type-Options':'nosniff'}}); const SECTIONS={ @@ -24,7 +25,8 @@ export function createJarvisManagement(central,bank,settings={},deps={}){ const db=definition.store==='central'?central:bank;if(!db)return reply({message:'Register temporarily unavailable.'},503); try{ const args=[26,(page-1)*25],sql=definition.sql+' LIMIT ? OFFSET ?',rows=definition.store==='central'?(await db.prepare(sql).bind(...args).all()).results:await db.query(sql,args); - return reply({section,page,hasMore:rows.length>25,records:rows.slice(0,25)}); + const records=rows.slice(0,25).map(row=>section==='keys'?{...row,family:KEY_TYPES[row.type]?.family||'unclassified',operation:KEY_TYPES[row.type]?.operation||'restricted',playerRedeemable:KEY_TYPES[row.type]?.playerRedeemable===true}:row); + return reply({section,page,hasMore:rows.length>25,records}); }catch(error){if(/doesn't exist|no such table|unknown column/i.test(error.message||''))return reply({message:'This register is not installed yet.'},503);throw error;} }; } diff --git a/website/node/organisation-key-policy.mjs b/website/node/organisation-key-policy.mjs new file mode 100644 index 00000000..99e6e2aa --- /dev/null +++ b/website/node/organisation-key-policy.mjs @@ -0,0 +1,25 @@ +// Single server-side catalogue. Developer capabilities deliberately do not belong +// here: they have no website issuance, receipt or redemption surface. +const player=(prefix,purpose)=>Object.freeze({prefix,purpose,family:'player',operation:'redeem',playerRedeemable:true}); +const system=(prefix,purpose,operation='execute')=>Object.freeze({prefix,purpose,family:'system',operation,playerRedeemable:false}); +export const KEY_TYPES=Object.freeze({ + 'progression-policy':system('PRG','progression-policy-configuration'), + 'gazette-news':system('NEWS','public-news-record','record'), + 'xp-correction':player('XPC','approved-xp-correction'), + 'xp-transfer':player('XPX','season-xp-transfer'), + 'economy-snapshot':system('ECO-SNAP','immutable-economic-record','record'), + 'staff-parent-link':system('STAFF-LINK','protected-parent-link'), + 'entity-transfer':system('XFR','entity-transfer'), + 'quest':system('QST','persistent-quest'), + 'quest-milestone':system('QSM','progression-milestone','record'), + 'staff-office-royal':system('STAFF-POL','protected-office-royal'), + 'staff-company-royal':system('STAFF-COM','company-royal'), + 'clan-subhouse':player('CLAN-SUB','subhouse-founding'), + 'company-subsidiary':player('COM-SUB','subsidiary-founding'), + 'political-clan':system('POL-CLAN','office-membership'), + 'clan-founding':player('CLAN','original-founding'), + 'company-founding':player('COM','original-founding'), + 'political-appointment':player('POL','appointment') +}); +export function keyPolicy(type){const value=KEY_TYPES[type];if(!Object.hasOwn(KEY_TYPES,type))throw TypeError('Unknown organisation key type');return value;} +export function privateKeyPresentation(type){const {family,operation,playerRedeemable}=keyPolicy(type);return {family,operation,playerRedeemable,showCode:playerRedeemable};} diff --git a/website/node/organisation-keys.mjs b/website/node/organisation-keys.mjs index c1acefc0..ed5bfb64 100644 --- a/website/node/organisation-keys.mjs +++ b/website/node/organisation-keys.mjs @@ -1,22 +1,9 @@ +import {KEY_TYPES,keyPolicy} from './organisation-key-policy.mjs'; import {parseOrganisationCode,formatOrganisationCode} from '../control-panel/public/codex-code-format.mjs'; import {createHash,createCipheriv,createDecipheriv,randomBytes,randomUUID} from 'node:crypto'; // Server-only. A secret grants a recorded entitlement; it is never an API credential. -export const ORGANISATION_KEY_TYPES=Object.freeze({ - 'economy-snapshot':Object.freeze({prefix:'ECO-SNAP',purpose:'immutable-economic-record'}), - 'staff-parent-link':Object.freeze({prefix:'STAFF-LINK',purpose:'protected-parent-link'}), - 'entity-transfer':Object.freeze({prefix:'XFR',purpose:'entity-transfer'}), - 'quest':Object.freeze({prefix:'QST',purpose:'persistent-quest'}), - 'quest-milestone':Object.freeze({prefix:'QSM',purpose:'progression-milestone'}), - 'staff-office-royal':Object.freeze({prefix:'STAFF-POL',purpose:'protected-office-royal'}), - 'staff-company-royal':Object.freeze({prefix:'STAFF-COM',purpose:'company-royal'}), - 'clan-subhouse':Object.freeze({prefix:'CLAN-SUB',purpose:'subhouse-founding'}), - 'company-subsidiary':Object.freeze({prefix:'COM-SUB',purpose:'subsidiary-founding'}), - 'political-clan':Object.freeze({prefix:'POL-CLAN',purpose:'office-membership'}), - 'clan-founding':Object.freeze({prefix:'CLAN',purpose:'original-founding'}), - 'company-founding':Object.freeze({prefix:'COM',purpose:'original-founding'}), - 'political-appointment':Object.freeze({prefix:'POL',purpose:'appointment'}) -}); +export const ORGANISATION_KEY_TYPES=KEY_TYPES; export const STAFF_OFFICE_ACCOUNT_ID='00000000-0000-4000-8000-000000000041'; export const organisationKeySchema=Object.freeze([ `CREATE TABLE IF NOT EXISTS organisation_keys (id CHAR(36) PRIMARY KEY,account_id CHAR(36) NOT NULL,key_type VARCHAR(32) NOT NULL,scope_id VARCHAR(160) NOT NULL,code_hash CHAR(64) NOT NULL UNIQUE,code_sealed TEXT NOT NULL,created_at BIGINT NOT NULL,expires_at BIGINT NULL,revoked_at BIGINT NULL,used_at BIGINT NULL,target_id CHAR(36) NULL,request_id CHAR(36) NULL,UNIQUE KEY organisation_key_grant(account_id,key_type,scope_id),INDEX organisation_key_owner(account_id,created_at)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`, @@ -54,6 +41,9 @@ export function createOrganisationKeys(db,{secret,editions=null}={}){ async inspect(code,{accountId=null,expectedType=null}={}){let parsed,keyType,hash;try{parsed=parseOrganisationCode(code);keyType=Object.keys(ORGANISATION_KEY_TYPES).find(k=>ORGANISATION_KEY_TYPES[k].prefix===parsed.prefix);if(!keyType)return{valid:false,state:'unsupported'};hash=hashOrganisationKey(code,keyType);}catch{return{valid:false,state:'invalid'};}const row=await db.first('SELECT id,account_id,key_type,expires_at,revoked_at,used_at FROM organisation_keys WHERE code_hash=?',[hash]);if(!row||accountId&&row.account_id!==accountId||expectedType&&row.key_type!==expectedType)return{valid:false,state:'invalid'};if(parsed.edition){if(!editions)return{valid:false,state:'unavailable'};const edition=await editions.read(row.id);if(['stage','version','season'].some(k=>edition[k]!==parsed.edition[k]))return{valid:false,state:'invalid'};}return{valid:true,type:row.key_type,purpose:type(row.key_type).purpose,state:row.revoked_at!=null?'revoked':row.used_at!=null?'used':row.expires_at!=null&&Number(row.expires_at)<=Date.now()?'expired':'available'};}, async issue({accountId,keyType,scopeId,expiresAt=null,authorize=null}){ type(keyType); + if(keyType==='progression-policy'&&(accountId!==STAFF_OFFICE_ACCOUNT_ID||expiresAt!==null||typeof authorize!=='function'||!/^policy:S\d{2,4}:v[1-9]\d{0,5}$/.test(scopeId)))throw new TypeError('Progression policies require the system configuration adapter'); + if(keyType==='gazette-news'&&(accountId!==STAFF_OFFICE_ACCOUNT_ID||expiresAt!==null||typeof authorize!=='function'||!/^news:[a-f0-9-]{36}:v[1-9]\d{0,5}$/i.test(scopeId)))throw new TypeError('Gazette instruments require a confirmed system publication adapter'); + if(['xp-correction','xp-transfer'].includes(keyType)&&(expiresAt!==null||typeof authorize!=='function'))throw new TypeError('XP instruments require a domain authority adapter'); if(keyType==='economy-snapshot'&&(accountId!==STAFF_OFFICE_ACCOUNT_ID||expiresAt!==null||!/^snapshot:[a-f0-9-]{36}$/i.test(scopeId)||typeof authorize!=='function'))throw new TypeError('Economic snapshots require a system record and authority adapter'); if(!uuid(accountId)||typeof scopeId!=='string'||!scopeId.trim()||scopeId.length>160||expiresAt!==null&&(!Number.isSafeInteger(expiresAt)||expiresAt<=Date.now()))throw new TypeError('Invalid key grant'); // Founding is once per account for its entire lifetime, including after sale/archive. @@ -66,9 +56,12 @@ export function createOrganisationKeys(db,{secret,editions=null}={}){ if(keyType==='staff-company-royal'&&(accountId!==STAFF_OFFICE_ACCOUNT_ID||expiresAt!==null||!/^company:[a-f0-9-]{36}$/i.test(scopeId)||typeof authorize!=='function'))throw new TypeError('Staff company keys require the system issuer and a company authority adapter'); const code=generateOrganisationKey(keyType),id=randomUUID(),now=Date.now(),issuedEdition=editions?await editions.current():null; try{return await db.transaction(async tx=>{ + if(keyType==='progression-policy')await authorize(tx,{accountId,keyType,scopeId,keyId:id}); + if(keyType==='gazette-news')await authorize(tx,{accountId,keyType,scopeId,keyId:id}); + if(['xp-correction','xp-transfer'].includes(keyType))await authorize(tx,{accountId,keyType,scopeId,keyId:id}); if(keyType==='economy-snapshot')await authorize(tx,{accountId,keyType,scopeId,keyId:id}); if(['staff-parent-link','entity-transfer'].includes(keyType))await authorize(tx,{accountId,keyType,scopeId}); - if(['quest','quest-milestone'].includes(keyType))await authorize(tx,{accountId,keyType,scopeId}); + if(['quest','quest-milestone'].includes(keyType))await authorize(tx,{accountId,keyType,scopeId,keyId:id}); if(keyType==='staff-office-royal')await authorize(tx,{accountId,keyType,scopeId}); if(keyType==='staff-company-royal')await authorize(tx,{accountId,keyType,scopeId}); if(['clan-subhouse','company-subsidiary'].includes(keyType))await authorize(tx,{accountId,keyType,scopeId}); @@ -98,7 +91,7 @@ export function createOrganisationKeys(db,{secret,editions=null}={}){ return rows.map(row=>{const edition=editionMap?.get(row.id);if(editions&&!edition)throw Error('Code edition is unavailable');const available=row.revoked_at==null&&row.used_at==null&&(row.expires_at==null||Number(row.expires_at)>Date.now());const raw=available?unseal(row.code_sealed,`${row.id}:${accountId}:${row.key_type}`):null;return {id:row.id,edition,keyType:row.key_type,scopeId:row.scope_id,createdAt:Number(row.created_at),targetId:row.target_id,status:row.revoked_at!=null?'revoked':row.used_at!=null?'used':row.expires_at!=null&&Number(row.expires_at)<=Date.now()?'expired':'available',code:raw&&edition?formatOrganisationCode(raw,edition):raw};}); }, async consume({accountId,keyType,code,targetId,requestId,apply}){ - if(keyType==='economy-snapshot')throw new OrganisationKeyError('Economic snapshots are sealed records and cannot be redeemed'); + if(keyPolicy(keyType).operation==='record')throw new OrganisationKeyError('Sealed system records cannot be redeemed'); if(!uuid(accountId)||!uuid(targetId)||!uuid(requestId)||typeof apply!=='function')throw new TypeError('Invalid key redemption'); const hash=hashOrganisationKey(code,keyType); return db.transaction(async tx=>{ diff --git a/website/tests/organisation-key-policy.test.mjs b/website/tests/organisation-key-policy.test.mjs new file mode 100644 index 00000000..7617835f --- /dev/null +++ b/website/tests/organisation-key-policy.test.mjs @@ -0,0 +1,17 @@ +import test from 'node:test';import assert from 'node:assert/strict';import {randomUUID} from 'node:crypto'; +import {KEY_TYPES,keyPolicy,privateKeyPresentation} from '../node/organisation-key-policy.mjs'; +import {companyFixture} from './company-deed-fixture.mjs';import {STAFF_OFFICE_ACCOUNT_ID} from '../node/organisation-keys.mjs'; +test('every registered key has one explicit family and operation; dev keys are absent',()=>{ + for(const policy of Object.values(KEY_TYPES)){assert(['player','system'].includes(policy.family));assert(['redeem','execute','record'].includes(policy.operation));assert.equal(policy.playerRedeemable,policy.family==='player');assert.equal(Object.isFrozen(policy),true);} + assert.throws(()=>keyPolicy('dev-batch'));assert.throws(()=>keyPolicy('__proto__')); + for(const type of ['economy-snapshot','gazette-news','quest','quest-milestone','political-clan'])assert.equal(privateKeyPresentation(type).showCode,false); + for(const type of ['clan-founding','company-founding','xp-correction','xp-transfer'])assert.equal(privateKeyPresentation(type).showCode,true); +}); +test('news instruments cannot be issued as player rewards or redeemed through consume',async()=>{ + const {db,keys,people}=await companyFixture();try{ + const scopeId='news:'+randomUUID()+':v1'; + await assert.rejects(keys.issue({accountId:people.Owner.id,keyType:'gazette-news',scopeId,authorize:async()=>{}}),/system publication/); + const record=await keys.issue({accountId:STAFF_OFFICE_ACCOUNT_ID,keyType:'gazette-news',scopeId,authorize:async()=>{}}); + await assert.rejects(keys.consume({accountId:STAFF_OFFICE_ACCOUNT_ID,keyType:'gazette-news',code:record.code,targetId:randomUUID(),requestId:randomUUID(),apply:async()=>{throw Error('Must not run');}}),/cannot be redeemed/); + }finally{db.close();} +}); diff --git a/website/tests/original-keys.test.mjs b/website/tests/original-keys.test.mjs index 57441407..22efa0d9 100644 --- a/website/tests/original-keys.test.mjs +++ b/website/tests/original-keys.test.mjs @@ -24,6 +24,18 @@ function fixture(){ db.prepare=statement=>{let values=[];return {bind(...v){values=v;return this;},async all(){return {results:await db.query(statement,values)};},async first(){return db.first(statement,values);}};}; return {sql,db,keys,close:()=>sql.close()}; } +test('system office receipts never expose a player redemption secret',async()=>{ + const f=fixture();try{ + f.sql.exec('CREATE TABLE political_office_terms(id TEXT,user_id TEXT,faction TEXT,office TEXT,outcome TEXT,starts_at INT,expires_at INT)'); + const now=Date.now(),expiry=now+60000;await f.db.query("INSERT INTO political_office_terms VALUES(?,?, 'atreides','house_leader','winner',?,?)",[requestId,owner,now-1000,expiry]); + const instrument=await f.keys.issue({accountId:owner,keyType:'political-clan',scopeId:requestId,expiresAt:expiry});assert(instrument.code); + const route=createClanKeyReceipts(f.db,{keys:f.keys,authenticate:async()=>({id:owner})}); + const data=await (await route(new Request('https://cp.dunerealms.com/api/organisation-keys'))).json(); + const receipt=data.keys.find(r=>r.id===instrument.id);assert.equal(receipt.family,'system');assert.equal(receipt.playerRedeemable,false);assert.equal(receipt.code,null); + assert(data.keys.some(r=>r.type==='clan'&&r.family==='player'&&r.code)); + }finally{f.close();} +}); + test('all accounts receive exactly two lifetime grants and retries preserve the original secrets',async()=>{ const f=fixture();try{ assert.deepEqual(await grantCurrentAccountKeys(f.db,f.keys),{accounts:2,created:4,existing:0}); From 907eca40fcb97aadbe31e2c5ec12de8a69b1f593 Mon Sep 17 00:00:00 2001 From: unimatrixgit <95320811+unimatrixgit@users.noreply.github.com> Date: Wed, 18 Nov 2026 22:53:36 +0100 Subject: [PATCH 4/4] Connect personal mission trees to transactional JARVIS quests, XP, claims and private history --- docs/operations/PROGRESSION-BACKEND.md | 63 ++++++++++ .../cp-v2/cp-v2-personal-progression.mjs | 74 ++++++++++++ .../public/cp-v2/cp-v2-progression.mjs | 7 +- website/control-panel/server.mjs | 11 +- website/node/permissions.mjs | 3 + website/node/progression-api.mjs | 49 ++++++++ website/node/progression-definitions.mjs | 49 ++++++++ website/node/progression-policy.mjs | 27 +++++ website/node/progression-quests.mjs | 108 ++++++++++++++++++ website/node/progression-reward-defaults.mjs | 13 +++ website/node/progression-runtime.mjs | 52 +++++++++ website/node/progression-schema.mjs | 16 +++ website/node/progression-xp-instruments.mjs | 65 +++++++++++ website/node/progression-xp-ledger.mjs | 19 +++ website/node/progression-xp-store.mjs | 20 ++++ website/tests/progression-api.test.mjs | 35 ++++++ .../progression-completion-policy.test.mjs | 20 ++++ website/tests/progression-policy.test.mjs | 22 ++++ website/tests/progression-quests.test.mjs | 45 ++++++++ .../tests/progression-xp-instruments.test.mjs | 39 +++++++ website/tests/progression-xp-ledger.test.mjs | 18 +++ 21 files changed, 750 insertions(+), 5 deletions(-) create mode 100644 docs/operations/PROGRESSION-BACKEND.md create mode 100644 website/control-panel/public/cp-v2/cp-v2-personal-progression.mjs create mode 100644 website/node/progression-api.mjs create mode 100644 website/node/progression-definitions.mjs create mode 100644 website/node/progression-policy.mjs create mode 100644 website/node/progression-quests.mjs create mode 100644 website/node/progression-reward-defaults.mjs create mode 100644 website/node/progression-runtime.mjs create mode 100644 website/node/progression-schema.mjs create mode 100644 website/node/progression-xp-instruments.mjs create mode 100644 website/node/progression-xp-ledger.mjs create mode 100644 website/node/progression-xp-store.mjs create mode 100644 website/tests/progression-api.test.mjs create mode 100644 website/tests/progression-completion-policy.test.mjs create mode 100644 website/tests/progression-policy.test.mjs create mode 100644 website/tests/progression-quests.test.mjs create mode 100644 website/tests/progression-xp-instruments.test.mjs create mode 100644 website/tests/progression-xp-ledger.test.mjs diff --git a/docs/operations/PROGRESSION-BACKEND.md b/docs/operations/PROGRESSION-BACKEND.md new file mode 100644 index 00000000..01f401d3 --- /dev/null +++ b/docs/operations/PROGRESSION-BACKEND.md @@ -0,0 +1,63 @@ +# Personal progression backend + +This batch connects the approved personal mission interface to the central +J.A.R.V.I.S. quest register. Organisation decisions and organisation mission +definitions remain in preview until their own domain adapters are connected. + +## Installed components + +- A versioned system instrument installs the initial six-month S01 season, + level cap 70 and configurable XP rewards. Restarts preserve existing settings. +- All nine personal branches and the optional company/clan acquisition tiers + have server-owned conditions. The browser cannot submit counters or XP. +- Starting a mission creates one persistent quest instrument. Claiming consumes + that instrument transactionally with the XP ledger and history. +- Optional rewards grant double XP. Reaching the seasonal completion threshold + queues the remaining mandatory claims; optional objectives remain independent. +- Excess XP remains in reserve. A sealed next-season instrument moves existing + reserve rather than crediting lifetime XP a second time. +- Halfway and completion milestones enter the existing-style transactional + outbox once per account and season. Public Gazette delivery is a separate + adapter, not an announcement already sent by this batch. +- The personal mission page displays real progress, server eligibility, claims + and private history. It preserves the shared CP theme and selected context. + +## Connected sources and boundaries + +The website reader currently verifies onboarding, profile and faction choice; +linked forum registration and eligible contributions; and posted personal bank +transfers and payroll income. A failed source remains unavailable. No browser +event is evidence of gameplay completion. + +Minecraft travel, harvesting, kit repair, equipment upgrades and other gameplay +facts remain unconnected. No Minecraft code is included. Physical/DM rewards +are not issued by the initial XP-only configuration. Reward jobs are retained +for the existing delivery integration when a reviewed reward is configured. + +Acquisitions require a verified deed-settlement adapter. A relation label is +insufficient evidence and the runtime rejects it by default. Founding does not +count as acquisition. Conquest and voluntary submission share the clan tiers. + +XP corrections require an approved, recipient-bound case with an explicit XP +budget. The default runtime resolver rejects issuance until that approval +adapter is connected. Next-season transfers require a separately authorised +season transition; installing this batch does not reset any balance or season. + +Staff generation permissions are separate from ordinary play. System records +are not redeemable player codes. Dev keys remain server-only and never appear +in the website generator or player receipts. + +## Validation + +Domain tests cover replay safety, prerequisites, revision conflicts, rollback, +XP ceilings and reserve, case-budget checks, and automatic mandatory completion. +HTTP tests cover identity, account scope, foreign origins and forged counters. +Local browser checks cover desktop/mobile claims, acquisition navigation and +view disposal. A push is not a production deployment. + +## Release packaging + +The server release builder was repaired on 2026-11-18 to archive `website tools` +instead of `website` alone. Dev-key tests live under `tools/tests` and run as an +explicit CI step. Keep those CLI-only capabilities out of web routes and assets; +including their source in the immutable release does not expose a web endpoint. diff --git a/website/control-panel/public/cp-v2/cp-v2-personal-progression.mjs b/website/control-panel/public/cp-v2/cp-v2-personal-progression.mjs new file mode 100644 index 00000000..873d3cf2 --- /dev/null +++ b/website/control-panel/public/cp-v2/cp-v2-personal-progression.mjs @@ -0,0 +1,74 @@ +import {element as el} from './cp-v2-page-template.mjs'; +import {MISSION_BRANCHES} from './cp-v2-progression-catalogue.mjs'; + +const art='https://www.dunerealms.com/assets/'; +const labels={claimed:'Reward claimed',completed:'Ready to claim',active:'In progress','not-started':'Not started'}; +const branches=[...MISSION_BRANCHES.filter(b=>b.id!=='discoveries'),{id:'acquisitions',title:'Acquisitions'}]; +const button=(text,fn)=>{const b=el('button',text);b.type='button';b.onclick=fn;return b;}; +const image=file=>{const img=el('img');img.src=art+file;img.alt='';img.loading='lazy';return img;}; +const date=n=>new Date(n).toLocaleString(undefined,{dateStyle:'medium',timeStyle:'short'}); + +// The server supplies all state, eligibility and rewards. The browser sends only +// the selected definition and its displayed revision, never XP or counters. +export function mountPersonalProgression(host,{view='missions',fetcher=fetch}={}){ + const controller=new AbortController(),status=el('p','Opening your mission journal…','progression-notice'),body=el('div'); + status.setAttribute('role','status');host.replaceChildren(status,body); + let active=true,data=null,branch='a',selected=null,busy=false,uncertain=false,page=1,loadSequence=0,connectorObserver=null; + const requestIds=new Map(); + async function api(path,options={}){ + const response=await fetcher('/api/progression'+path,{credentials:'same-origin',cache:'no-store',signal:controller.signal,...options}); + const value=await response.json();if(!response.ok)throw Error(value.message||'The journal could not be loaded.');return value; + } + function message(text){if(active)status.textContent=text;} + async function load(){ + const sequence=++loadSequence; + try{ + const fresh=await api(view==='history'?'/history?page='+page:'');if(!active||sequence!==loadSequence)return; + data=fresh;uncertain=false;requestIds.clear();render(); + message(view==='history'?'Your recorded J.A.R.V.I.S. activity.':data.state==='active'?'Only verified objectives can be claimed. Unconnected gameplay objectives remain pending.':'The next season has not opened yet.'); + }catch(error){if(!active||sequence!==loadSequence)return;message(error.message);body.replaceChildren(button('Reload journal',load));} + } + async function act(row){ + if(busy||uncertain||!active)return;busy=true;render(); + const claim=row.canClaim,path=claim?'/claim':'/start'; + const id=requestIds.get(row.id)||crypto.randomUUID();requestIds.set(row.id,id); + const payload=claim?{definitionId:row.id,revision:row.revision,requestId:id,confirmed:true}:{definitionId:row.id,confirmed:true}; + try{await api(path,{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(payload)});await load();} + catch(error){if(active){uncertain=true;message(error.message+' Reload the journal to confirm the recorded result.');}} + finally{busy=false;if(active)render();} + } + function render(){ + connectorObserver?.disconnect(); + body.replaceChildren();if(!data)return; + const reload=button('Reload journal',load);reload.disabled=busy;body.append(reload); + if(view==='history'){ + if(!data.records.length)body.append(el('p','No recorded progression activity yet.')); + for(const record of data.records){const box=el('article',undefined,'progression-history-record');box.append(el('strong',record.action.replaceAll('-',' ')),el('p',date(record.createdAt)));if(record.details?.definitionId)box.append(el('p',record.details.definitionId));if(Number.isSafeInteger(record.details?.xp))box.append(el('p',record.details.xp+' XP'));body.append(box);} + const prev=button('Previous',()=>{page--;load();}),next=button('Next',()=>{page++;load();});prev.disabled=page===1;next.disabled=!data.hasMore;body.append(prev,el('span',' Page '+page+' '),next);return; + } + if(data.state!=='active')return; + const stats=el('div',undefined,'progression-stats');stats.append(el('strong','Level '+data.profile.level+' / '+data.season.levelCap),el('span',data.profile.effectiveXP.toLocaleString()+' seasonal XP'),el('span','Season ends '+date(data.season.endsAt))); + const progress=el('progress');progress.max=data.season.levelCap;progress.value=data.profile.level;progress.setAttribute('aria-label','Season level');stats.append(progress);body.append(stats); + const select=el('select');select.setAttribute('aria-label','Mission branch'); + for(const b of branches){if(!data.quests.some(q=>q.branch===b.id))continue;const option=el('option',b.title);option.value=b.id;select.append(option);} + if(!data.quests.some(q=>q.branch===branch))branch=data.quests[0]?.branch; + select.value=branch;select.onchange=()=>{branch=select.value;selected=null;render();};body.append(select); + const rows=data.quests.filter(q=>q.branch===branch);selected=rows.find(q=>q.id===selected)?.id||rows[0]?.id; + const layout=el('div',undefined,'progression-layout'),tree=el('div',undefined,'progression-tree');tree.setAttribute('aria-label','Mission tree'); + for(const row of rows){const card=button('',()=>{selected=row.id;render();});card.className='progression-mission';card.dataset.missionId=row.id;card.setAttribute('aria-pressed',String(row.id===selected));card.append(image(branch==='acquisitions'?'nav-clan-v2.webp':'exchange-quests-v1.png'),el('strong',row.title),el('span',labels[row.state]||'Awaiting verification','progression-badge'));tree.append(card);} + layout.append(tree);const row=rows.find(q=>q.id===selected); + if(row){const pane=el('aside',undefined,'progression-detail');pane.setAttribute('aria-label','Selected mission');pane.append(image('exchange-quests-v1.png'),el('small',row.id),el('h3',row.title)); + const source=data.sources?.sources?.find(s=>s.metrics?.includes(row.metric)); + const quantity=value=>row.metric?.endsWith('-minor')?(value/100).toLocaleString(undefined,{minimumFractionDigits:2,maximumFractionDigits:2})+' DM':value.toLocaleString(); + const dl=el('dl');for(const [label,value]of [['Progress',quantity(row.progress)+' / '+quantity(row.target)],['Status',labels[row.state]||'Awaiting verification'],['Verification',source?.state==='available'?'Connected website records':source?'Source temporarily unavailable':'Gameplay integration pending'],['XP',row.xp===null?'Not configured':String(row.xp)],['Objective',row.optional?'Optional':'Required']])dl.append(el('dt',label),el('dd',value));pane.append(dl); + if(row.title==='Repair Your Starter Kit'){const parts=el('div',undefined,'progression-repair');for(const [file,title]of [['iron_ingot.png','Repair plate'],['leather_chestplate.png','Binding patch'],['copper_ingot.png','Tool fitting'],['quartz.png','Calibration piece']]){const part=el('figure');part.append(image('minecraft-items/'+file),el('figcaption',title+' · awaiting gameplay integration'));parts.append(part);}pane.append(parts);} + if(row.branch==='acquisitions')pane.append(el('p','Settled purchases and clan submissions or conquests count. Founding an organisation does not count.')); + const action=button(row.state==='claimed'?'Reward claimed':row.canClaim?'Claim reward':row.state==='active'?'Awaiting verified progress':row.canStart?'Start mission':'Complete the previous mission',()=>act(row));action.disabled=busy||uncertain||row.state==='claimed'||!row.canClaim&&(!row.canStart||row.state==='active');pane.append(action); + if(row.keyId)pane.append(el('small','J.A.R.V.I.S. reference: '+row.keyId));layout.append(pane); + }body.append(layout); + const svg=document.createElementNS('http://www.w3.org/2000/svg','svg');svg.classList.add('progression-connectors');svg.setAttribute('aria-hidden','true');tree.prepend(svg); + const connect=()=>{if(!active||!tree.isConnected)return;const box=tree.getBoundingClientRect();svg.setAttribute('viewBox','0 0 '+box.width+' '+box.height);svg.replaceChildren();const cards=new Map([...tree.querySelectorAll('[data-mission-id]')].map(n=>[n.dataset.missionId,n]));for(const row of rows)for(const dependency of row.requires||[]){if(!cards.has(dependency))continue;const a=cards.get(dependency).getBoundingClientRect(),b=cards.get(row.id).getBoundingClientRect(),line=document.createElementNS(svg.namespaceURI,'path'),sameRow=Math.abs(a.top-b.top)<5,x1=(sameRow?a.right:a.left+a.width/2)-box.left,y1=(sameRow?a.top+a.height/2:a.bottom)-box.top,x2=(sameRow?b.left:b.left+b.width/2)-box.left,y2=(sameRow?b.top+b.height/2:b.top)-box.top;line.setAttribute('d',sameRow?`M ${x1} ${y1} H ${x2}`:`M ${x1} ${y1} V ${y1+14} H ${x2} V ${y2}`);svg.append(line);}}; + connectorObserver=new ResizeObserver(connect);connectorObserver.observe(tree);requestAnimationFrame(connect); + } + load();return()=>{active=false;connectorObserver?.disconnect();controller.abort();}; +} diff --git a/website/control-panel/public/cp-v2/cp-v2-progression.mjs b/website/control-panel/public/cp-v2/cp-v2-progression.mjs index 72c038fa..e13c6ccb 100644 --- a/website/control-panel/public/cp-v2/cp-v2-progression.mjs +++ b/website/control-panel/public/cp-v2/cp-v2-progression.mjs @@ -1,3 +1,4 @@ +import {mountPersonalProgression} from './cp-v2-personal-progression.mjs'; import {element as el} from './cp-v2-page-template.mjs'; import {MISSION_BRANCHES,DECISION_CATALOGUE} from './cp-v2-progression-catalogue.mjs'; const ASSETS='https://www.dunerealms.com/assets/'; @@ -14,7 +15,7 @@ export function mountProgressionDesign(host,{context='personal',dashboard=false, if(!document.querySelector('link[data-progression-design]')){const link=el('link');link.rel='stylesheet';link.href=new URL('./cp-v2-progression.css',import.meta.url).href;link.dataset.progressionDesign='';document.head.append(link);} const root=el('section',undefined,'progression-workspace'),notice=el('p','Design preview · Sample layout only. No XP, rewards, appointments or payments are issued.','progression-notice'); let activeContext=context,tab='missions',selected=null,branch='a',officeCode=office,query=''; - let connectorObserver=null; + let connectorObserver=null,disposePersonal=null; const hero=el('header',undefined,'progression-hero'),head=el('div');head.append(el('small',manage?'IMPERIAL BUREAU · J.A.R.V.I.S.':'REALM PROGRESSION'),el('h2',manage?'Progression definitions':dashboard?'Quest Dashboard':'Missions & Decisions'),el('p','Your objectives, authority and recorded achievements.'));hero.append(image('exchange-quests-v1.png'),head);root.append(hero,notice); const contextNav=el('nav',undefined,'progression-contexts'),gallery=el('section',undefined,'progression-gallery'),nav=el('nav',undefined,'progression-tabs'),content=el('section',undefined,'progression-content');nav.setAttribute('aria-label','Progression views');contextNav.setAttribute('aria-label','Progression contexts'); if(dashboard)root.append(contextNav);root.append(gallery,nav,content);host.replaceChildren(root); @@ -40,6 +41,6 @@ export function mountProgressionDesign(host,{context='personal',dashboard=false, function renderDecisions(){const toolbar=el('div',undefined,'progression-toolbar'),search=el('input');search.type='search';search.placeholder='Search decisions';search.setAttribute('aria-label','Search decisions');search.value=query;search.oninput=()=>{query=search.value;renderDecisionsList();};toolbar.append(search);if((dashboard&&activeContext==='politics')||manage){const chooser=field('Office catalogue',OFFICES.map(([,name])=>name));chooser.querySelector('select').selectedIndex=OFFICES.findIndex(([id])=>id===officeCode);chooser.onchange=e=>{officeCode=OFFICES[e.target.selectedIndex][0];selected=null;render();};toolbar.append(chooser);}content.append(toolbar);const listHost=el('div');content.append(listHost); function renderDecisionsList(){listHost.replaceChildren();let rows=activeContext==='politics'||manage?DECISION_CATALOGUE.filter(d=>d.office===officeCode):activeContext==='personal'?[{id:'P-MARK',title:'Equipment Mark eligibility',effect:'Level, materials and equipment restrictions remain necessary.',level:0,xp:0,cost:'Pending configuration'},{id:'P-RARITY',title:'Rarity enhancement eligibility',effect:'Use the existing rarity and Legendary upgrade policy.',level:0,xp:0,cost:'Pending configuration'},{id:'P-SEASON',title:'Seasonal completion entitlement',effect:'One non-tradable completion kit after all mandatory objectives.',level:0,xp:0,cost:'Earned entitlement'}]:[];rows=rows.filter(r=>(r.title+' '+r.effect).toLowerCase().includes(query.toLowerCase()));if(!rows.length){listHost.append(el('p','No decision definitions available for this selection. No authority is inferred.'));return;}selected=rows.find(r=>r.id===selected)?.id||rows[0].id;const layout=el('div',undefined,'progression-layout'),cards=el('div',undefined,'progression-decisions');for(const row of rows){const card=button('',()=>{selected=row.id;renderDecisionsList();},'progression-decision');card.setAttribute('aria-pressed',String(row.id===selected));card.append(image('exchange-political-positions-v1.png'),el('small',row.id),el('strong',row.title),el('span','View proposal · execution unavailable'));cards.append(card);}layout.append(cards,details(rows.find(r=>r.id===selected),true));listHost.append(layout);}renderDecisionsList(); } - function render(){connectorObserver?.disconnect();root.dataset.context=activeContext;contextNav.replaceChildren();for(const[id,[label]]of Object.entries(CONTEXTS)){const b=button(label,()=>{activeContext=id;selected=null;query='';render();});b.setAttribute('aria-pressed',String(id===activeContext));contextNav.append(b);}renderGallery();nav.replaceChildren();for(const[id,label]of [['missions',manage?'Mission Definitions':'Missions'],['decisions',manage?'Decision Definitions':'Decisions'],...(manage?[['rewards','Progression & Rewards']]:[]),['history','History']]){const b=button(label,()=>{tab=id;selected=null;render();});b.setAttribute('aria-pressed',String(tab===id));nav.append(b);}content.replaceChildren();if(tab==='missions')renderMissions();else if(tab==='decisions')renderDecisions();else if(tab==='rewards'){content.append(el('h3','Progression & Rewards'),field('Season cap',['70 · proposed']),field('Milestone announcements',['Halfway and completion only']),el('p','Rewards, XP curves, repair recipes and signing editions await backend review. No configuration writes enabled.'));}else content.append(el('h3','J.A.R.V.I.S. History'),el('p','Verified completion, claims, decisions and any staff overrides will appear here after integration. No sample audit records are shown.'));} - render();return()=>{connectorObserver?.disconnect();root.remove();}; + function render(){connectorObserver?.disconnect();disposePersonal?.();disposePersonal=null;notice.textContent=activeContext==='personal'&&!manage?'Personal missions use verified J.A.R.V.I.S. records. Decision and organisation integrations remain in preview.':'Design preview · No office actions or organisation rewards are issued.';root.dataset.context=activeContext;contextNav.replaceChildren();for(const[id,[label]]of Object.entries(CONTEXTS)){const b=button(label,()=>{activeContext=id;selected=null;query='';render();});b.setAttribute('aria-pressed',String(id===activeContext));contextNav.append(b);}renderGallery();nav.replaceChildren();for(const[id,label]of [['missions',manage?'Mission Definitions':'Missions'],['decisions',manage?'Decision Definitions':'Decisions'],...(manage?[['rewards','Progression & Rewards']]:[]),['history','History']]){const b=button(label,()=>{tab=id;selected=null;render();});b.setAttribute('aria-pressed',String(tab===id));nav.append(b);}content.replaceChildren();if(activeContext==='personal'&&!manage&&['missions','history'].includes(tab))disposePersonal=mountPersonalProgression(content,{view:tab});else if(tab==='missions')renderMissions();else if(tab==='decisions')renderDecisions();else if(tab==='rewards'){content.append(el('h3','Progression & Rewards'),field('Season cap',['70 · proposed']),field('Milestone announcements',['Halfway and completion only']),el('p','Rewards, XP curves, repair recipes and signing editions await backend review. No configuration writes enabled.'));}else content.append(el('h3','J.A.R.V.I.S. History'),el('p','Verified completion, claims, decisions and any staff overrides will appear here after integration. No sample audit records are shown.'));} + render();return()=>{connectorObserver?.disconnect();disposePersonal?.();root.remove();}; } diff --git a/website/control-panel/server.mjs b/website/control-panel/server.mjs index 5bdab31a..a92c0a06 100644 --- a/website/control-panel/server.mjs +++ b/website/control-panel/server.mjs @@ -1,4 +1,8 @@ import {ECONOMIC_SNAPSHOT_SCHEMA} from '../node/jarvis-economic-snapshots.mjs'; +import {initializeProgression} from '../node/progression-schema.mjs'; +import {ensureProgressionPolicy} from '../node/progression-policy.mjs'; +import {createProgressionRuntime} from '../node/progression-runtime.mjs'; +import {createProgressionAPI} from '../node/progression-api.mjs'; import {createNaibCouncilAPI} from '../node/naib-council-api.mjs'; import {NAIB_COUNCIL_SCHEMA,createNaibCouncil,reconcileNaibChairs} from '../node/naib-council.mjs'; import {configurePromotionDelivery} from '../node/jarvis-promotions.mjs'; @@ -185,6 +189,8 @@ export function createPanel(db,settings={},dependencies={}){ const staffBureauRead=createStaffBureauReadApi(db); const citizenDirectory=createCitizenDirectory(db);const lifeStatus=createLifeStatus(db,{origin}); const auctionRuntime=dependencies.officeAuctionRuntime||createOfficeAuctionRuntime(db,dependencies.bankDatabase||null);const politicalActions=createPoliticalActions(db,{enabled:!!auctionRuntime,origin});const officeAuctionAPI=createOfficeAuctionAPI(db,dependencies.bankDatabase||null,auctionRuntime,settings,dependencies.officeAuctionAPI); + const progressionRuntime=dependencies.progressionRuntime||(dependencies.organisationKeys?createProgressionRuntime(db,dependencies.bankDatabase||null,dependencies.organisationKeys):null); + const progression=createProgressionAPI(db,{...progressionRuntime,origin}); const keyValidation=createKeyValidation(db,dependencies.organisationKeys,{origin}); const politicalJobs=createPoliticalJobAPI(db,dependencies.bankDatabase||null,settings,{promotionChannels:dependencies.promotionDelivery?.channels||[]}); const naibCouncil=createNaibCouncilAPI(db,settings); @@ -344,6 +350,7 @@ export function createPanel(db,settings={},dependencies={}){ if(path==='/api/v1/company-claims/home-block')return companyClaims.homeBlock(request); if(path==='/api/v1/company-claims/upgrades')return companyClaims.upgrades(request); if(path==='/api/exchange/listings')return exchange(request); + if(path==='/api/progression'||path.startsWith('/api/progression/'))return progression(request); if(path.startsWith('/api/cp/'))return community(request); if(path.startsWith('/luckperms-editor/')){ const user=await identity(request,db);if(!user)return json({message:'Sign in first.'},401); @@ -417,9 +424,9 @@ export async function startPanel(settings=process.env){ inventoryPool.on('error',()=>console.error('Inventory database connection unavailable.')); } const bankDatabase=await openPostbankDatabase(settings); - const db=await openDatabase(settings);await db.query(ECONOMIC_SNAPSHOT_SCHEMA);await initializeCodexEquipment(db);await initializeFirstLogin(db);await db.prepare(accountSchema).run();await initializeProclamations(db);await initializeCharters(db);await initializeApplications(db);await initializeRounds(db);await initializeBallots(db);await initializeOfficeLedger(db);await initializeContactEmails(db);await initializeBanEvidence(db);await initializeClans(db);await db.prepare(CHARACTER_PREFERENCE_SCHEMA+' ENGINE=InnoDB DEFAULT CHARSET=utf8mb4').run();await db.prepare(CHARACTER_SCHEMA+' ENGINE=InnoDB DEFAULT CHARSET=utf8mb4').run();await applyRoyalClanRollout(db);const organisationKeys=await openOrganisationKeyService(db,settings);await ensurePoliticalOfficeCharters(db,organisationKeys);const keyGrants=await grantCurrentAccountKeys(db,organisationKeys);console.log('Original founding key grants reconciled',JSON.stringify(keyGrants));await resetOwnerTestClaims(db,bankDatabase);await initializeClanShop(db);await initializeMailIdentities(db);await initializeGitIdentities(db);await initializeRanks(db);await initializeHonours(db);await initializeStaffBureau(db);await initializeOrganisation(db);await initializeLifeStatus(db);await initializeBadges(db);await initializeSealEntitlements(db);await initializeSealCatalog(db);await initializeCompanyRegistry(db);await initializeCompanyDeeds(db);await applyUnicorpRoyalMailbox(db,organisationKeys,{apply:true}).catch(error=>console.error('Unicorp Royal mailbox rollout pending:',error.message));await initializeShareLedger(db);await initializeNews(db);await initializeCommunityAccess(db);await initializeQuestAccess(db);await initializeBankAccess(db);await initializeGameRanks(db);await db.query(NETWORK_LAYOUT_SCHEMA);db.networkLayoutsEnabled=true;await ensureJarvisIdentity(db);await db.query(VALIDATION_CASE_SCHEMA);await reconcileCrysknifeCompany(db,organisationKeys);await provisionRihlaAccounts(db,bankDatabase);await initializeOfficeAuctionRuntime(db,bankDatabase);for(const sql of [...POLITICAL_JOB_SCHEMA,...NAIB_COUNCIL_SCHEMA])await db.query(sql);db.naibCouncilEnabled=true;const officeAuctionRuntime=createOfficeAuctionRuntime(db,bankDatabase);const promotionDelivery=bankDatabase?await configurePromotionDelivery(db,bankDatabase,settings):null;const handle=createPanel(db,settings,{inventoryPool,bankDatabase,organisationKeys,officeAuctionRuntime,promotionDelivery}),origin=settings.CP_ORIGIN||'https://cp.dunerealms.com'; + const db=await openDatabase(settings);await db.query(ECONOMIC_SNAPSHOT_SCHEMA);await initializeCodexEquipment(db);await initializeFirstLogin(db);await db.prepare(accountSchema).run();await initializeProclamations(db);await initializeCharters(db);await initializeApplications(db);await initializeRounds(db);await initializeBallots(db);await initializeOfficeLedger(db);await initializeContactEmails(db);await initializeBanEvidence(db);await initializeClans(db);await db.prepare(CHARACTER_PREFERENCE_SCHEMA+' ENGINE=InnoDB DEFAULT CHARSET=utf8mb4').run();await db.prepare(CHARACTER_SCHEMA+' ENGINE=InnoDB DEFAULT CHARSET=utf8mb4').run();await applyRoyalClanRollout(db);const organisationKeys=await openOrganisationKeyService(db,settings);await ensurePoliticalOfficeCharters(db,organisationKeys);const keyGrants=await grantCurrentAccountKeys(db,organisationKeys);console.log('Original founding key grants reconciled',JSON.stringify(keyGrants));await resetOwnerTestClaims(db,bankDatabase);await initializeClanShop(db);await initializeMailIdentities(db);await initializeGitIdentities(db);await initializeRanks(db);await initializeHonours(db);await initializeStaffBureau(db);await initializeOrganisation(db);await initializeLifeStatus(db);await initializeBadges(db);await initializeSealEntitlements(db);await initializeSealCatalog(db);await initializeCompanyRegistry(db);await initializeCompanyDeeds(db);await applyUnicorpRoyalMailbox(db,organisationKeys,{apply:true}).catch(error=>console.error('Unicorp Royal mailbox rollout pending:',error.message));await initializeShareLedger(db);await initializeNews(db);await initializeCommunityAccess(db);await initializeQuestAccess(db);await initializeBankAccess(db);await initializeGameRanks(db);await db.query(NETWORK_LAYOUT_SCHEMA);db.networkLayoutsEnabled=true;await ensureJarvisIdentity(db);await db.query(VALIDATION_CASE_SCHEMA);await reconcileCrysknifeCompany(db,organisationKeys);await provisionRihlaAccounts(db,bankDatabase);await initializeOfficeAuctionRuntime(db,bankDatabase);for(const sql of [...POLITICAL_JOB_SCHEMA,...NAIB_COUNCIL_SCHEMA])await db.query(sql);db.naibCouncilEnabled=true;await initializeProgression(db);await ensureProgressionPolicy(db,organisationKeys);const progressionRuntime=createProgressionRuntime(db,bankDatabase,organisationKeys);const officeAuctionRuntime=createOfficeAuctionRuntime(db,bankDatabase);const promotionDelivery=bankDatabase?await configurePromotionDelivery(db,bankDatabase,settings):null;const handle=createPanel(db,settings,{inventoryPool,bankDatabase,organisationKeys,officeAuctionRuntime,promotionDelivery,progressionRuntime}),origin=settings.CP_ORIGIN||'https://cp.dunerealms.com'; await initializeInternalMailAccess(db);const stopElectionClock=startElectionClock(db);const stopOfficeLedger=startOfficeLedger(db); - const stopBanSync=startModerationSync(db,settings),stopInternalMail=startInternalMailSync(db,{jarvisStore:bankDatabase}),stopCentralScheduler=startCentralScheduler(db,bankDatabase,settings,{extraTasks:bankDatabase?[{key:'naib_council',slot:now=>Math.floor(now/60000)*60000,run:async()=>{await reconcileNaibChairs(db);return createNaibCouncil(db).reconcile();}},{key:'jarvis_promotions',slot:now=>Math.floor(now/15000)*15000,run:()=>promotionDelivery.drain()},{key:'political_jobs',slot:now=>Math.floor(now/60000)*60000,run:async()=>{await createPoliticalJobs(db,bankDatabase).reconcile();return drainPoliticalJobNotifications(db,{broker:internalMailBroker,eligible:internalMailEligible});}},{key:'order_membership',slot:now=>Math.floor(now/60000)*60000,run:()=>reconcileCrysknifeCompany(db,organisationKeys)},{key:'office_auctions',slot:now=>Math.floor(now/60000)*60000,run:()=>officeAuctionRuntime.process()},{key:'jarvis_settlement',slot:now=>standardCycle(now).cutoff,async run(cutoff){const payments=createJarvisPayments(bankDatabase,createPostbankAuthority(db,{bank:bankDatabase}));for(let i=0;i<40;i++){const result=await payments.settle(cutoff);if(result.failed)return result;if(result.attempted<100)return result;}return {failed:1};}}]:[]}); + const stopBanSync=startModerationSync(db,settings),stopInternalMail=startInternalMailSync(db,{jarvisStore:bankDatabase}),stopCentralScheduler=startCentralScheduler(db,bankDatabase,settings,{extraTasks:bankDatabase?[{key:'progression_completion',slot:now=>Math.floor(now/60000)*60000,run:()=>progressionRuntime.quests.processCompletions()},{key:'naib_council',slot:now=>Math.floor(now/60000)*60000,run:async()=>{await reconcileNaibChairs(db);return createNaibCouncil(db).reconcile();}},{key:'jarvis_promotions',slot:now=>Math.floor(now/15000)*15000,run:()=>promotionDelivery.drain()},{key:'political_jobs',slot:now=>Math.floor(now/60000)*60000,run:async()=>{await createPoliticalJobs(db,bankDatabase).reconcile();return drainPoliticalJobNotifications(db,{broker:internalMailBroker,eligible:internalMailEligible});}},{key:'order_membership',slot:now=>Math.floor(now/60000)*60000,run:()=>reconcileCrysknifeCompany(db,organisationKeys)},{key:'office_auctions',slot:now=>Math.floor(now/60000)*60000,run:()=>officeAuctionRuntime.process()},{key:'jarvis_settlement',slot:now=>standardCycle(now).cutoff,async run(cutoff){const payments=createJarvisPayments(bankDatabase,createPostbankAuthority(db,{bank:bankDatabase}));for(let i=0;i<40;i++){const result=await payments.settle(cutoff);if(result.failed)return result;if(result.attempted<100)return result;}return {failed:1};}}]:[]}); const security={'X-Robots-Tag':'noindex, nofollow, noarchive','X-Content-Type-Options':'nosniff','Referrer-Policy':'no-referrer','Cache-Control':'no-store','Content-Security-Policy':"default-src 'self'; script-src 'self' https://www.dunerealms.com; style-src 'self' https://www.dunerealms.com https://fonts.googleapis.com; font-src 'self' https://fonts.gstatic.com; connect-src 'self' https://www.dunerealms.com; img-src 'self' data: https://www.dunerealms.com https://support.dunerealms.com; frame-src 'self' https://luckperms.net https://www.dunerealms.com https://support.dunerealms.com https://forums.dunerealms.com https://clans.dunerealms.com https://corp.dunerealms.com https://wiki.dunerealms.com; object-src 'none'; base-uri 'none'; form-action 'self'; frame-ancestors 'self' https://www.dunerealms.com https://dunerealms.com https://clans.dunerealms.com"}; const server=createServer(async(req,res)=>{try{ req.setTimeout(req.url==='/api/internal-mail/messages/send'?120000:30000);const bodyLimit=panelBodyLimit(req.method,req.url);let length=0;const chunks=[];for await(const chunk of req){length+=chunk.length;if(length>bodyLimit){res.writeHead(413,{...security,'Content-Type':'application/json'});res.end(JSON.stringify({message:'The upload exceeds the permitted request size.'}));return;}chunks.push(chunk);} diff --git a/website/node/permissions.mjs b/website/node/permissions.mjs index 9a6dd023..3cf167a3 100644 --- a/website/node/permissions.mjs +++ b/website/node/permissions.mjs @@ -1,6 +1,9 @@ import {JARVIS_IDENTITY,isJarvisIdentity} from './jarvis-identity.mjs'; import {organisationRuntimeAccess} from './organisation-runtime.mjs'; export const NODES={ + 'web.progression.xp.correct':'Issue support-approved XP correction instruments', + 'web.progression.seasons.manage':'Manage sealed seasonal XP transfers', + 'web.projects.review':'Review and fund server projects from the Tax treasury', 'web.forum.admin':'Native Forum administration (Dev service only after migration)', 'web.tickets.support':'Work Customer Support tickets', 'web.tickets.sales':'Work Sales and Account Services tickets', diff --git a/website/node/progression-api.mjs b/website/node/progression-api.mjs new file mode 100644 index 00000000..08e7cc25 --- /dev/null +++ b/website/node/progression-api.mjs @@ -0,0 +1,49 @@ +import {identity} from './auth.mjs'; +import {parseOrganisationCode} from '../control-panel/public/codex-code-format.mjs'; +const uuid=v=>typeof v==='string'&&/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(v); +export function createProgressionAPI(db,{quests,xp,collect=async()=>{},authenticate=r=>identity(r,db),origin='https://cp.dunerealms.com'}={}){ + const reply=(data,status=200)=>Response.json(data,{status,headers:{'Cache-Control':'private, no-store',Vary:'Cookie','X-Content-Type-Options':'nosniff'}}); + return async request=>{ + const url=new URL(request.url),user=await authenticate(request);if(!user)return reply({message:'Sign in to open your mission journal.'},401); + const actor={...user,revalidate:async()=>authenticate(request)}; + if(!quests)return reply({message:'The quest service is not available.'},503); + try{ + if(request.method==='GET'){ + if(url.pathname==='/api/progression'&&!url.search){const sources=await collect(actor);return reply({...await quests.list(actor),sources});} + if(url.pathname==='/api/progression/history'){ + if([...url.searchParams.keys()].some(k=>k!=='page')||url.searchParams.getAll('page').length>1||!/^\d{1,4}$/.test(url.searchParams.get('page')||'1'))return reply({message:'Choose a valid history page.'},400); + const page=Number(url.searchParams.get('page')||1);if(page<1)return reply({message:'Choose a valid history page.'},400); + const rows=await db.query('SELECT key_id,action,details_json,created_at FROM jarvis_progression_history WHERE account_id=? ORDER BY created_at DESC,id DESC LIMIT 26 OFFSET '+((page-1)*25),[user.id]); + return reply({page,hasMore:rows.length>25,records:rows.slice(0,25).map(r=>({keyId:r.key_id,action:r.action,details:JSON.parse(r.details_json),createdAt:Number(r.created_at)}))}); + } + return reply({message:'Mission route not found.'},404); + } + if(request.method!=='POST')return reply({message:'Method not allowed.'},405); + if(request.headers.get('origin')!==origin||url.search)return reply({message:'Origin or account override rejected.'},403); + if(!/^application\/json(?:;|$)/i.test(request.headers.get('content-type')||''))return reply({message:'JSON required.'},415); + const reader=request.body?.getReader();if(!reader)return reply({message:'Request body required.'},400);let raw='',size=0;const decoder=new TextDecoder(); + while(true){const {done,value}=await reader.read();if(done)break;size+=value.length;if(size>4096){await reader.cancel();return reply({message:'Request too large.'},413);}raw+=decoder.decode(value,{stream:true});}raw+=decoder.decode(); + let body;try{body=JSON.parse(raw);}catch{return reply({message:'Invalid mission request.'},400);} + if(!body||typeof body!=='object'||Array.isArray(body)||body.confirmed!==true)return reply({message:'Confirm the selected action.'},400); + if(url.pathname==='/api/progression/start'){ + if(Object.keys(body).some(k=>!['definitionId','confirmed'].includes(k))||typeof body.definitionId!=='string')return reply({message:'Choose a mission.'},400); + await collect(actor);const result=await quests.start(actor,body);return reply({ok:true,keyId:result.id,created:result.created}); + } + if(url.pathname==='/api/progression/claim'){ + if(Object.keys(body).some(k=>!['definitionId','requestId','revision','confirmed'].includes(k))||typeof body.definitionId!=='string'||!uuid(body.requestId)||!Number.isSafeInteger(body.revision)||body.revision<1)return reply({message:'Review the current mission reward.'},400); + await collect(actor);const result=await quests.claim(actor,body);await quests.processCompletions({accountId:user.id});return reply({ok:true,...result}); + } + if(url.pathname==='/api/progression/xp/redeem'){ + if(!xp||Object.keys(body).some(k=>!['code','requestId','confirmed'].includes(k))||typeof body.code!=='string'||!uuid(body.requestId))return reply({message:'Provide a complete XP instrument.'},400); + let parsed;try{parsed=parseOrganisationCode(body.code);}catch{return reply({message:'Provide a complete XP instrument.'},400);} + const keyType=parsed.prefix==='XPC'?'xp-correction':parsed.prefix==='XPX'?'xp-transfer':null;if(!keyType)return reply({message:'This instrument is not a player XP key.'},400); + const fresh=await authenticate(request);if(fresh?.id!==user.id)return reply({message:'Your session changed.'},403); + const result=await xp.redeem(actor,{code:body.code,keyType,requestId:body.requestId});await quests.processCompletions({accountId:user.id});return reply({ok:true,...result}); + } + return reply({message:'Mission route not found.'},404); + }catch(error){ + const safe=/^(Quest|XP |Season|Unknown quest|Current player|A single matching|An approved matching|Trusted observation|Verified deed|No reserved|Source season|Mandatory reward)/.test(error.message||''); + return reply({message:safe?error.message:'The mission service could not confirm this action. Reload before retrying.'},safe?409:503); + } + }; +} diff --git a/website/node/progression-definitions.mjs b/website/node/progression-definitions.mjs new file mode 100644 index 00000000..ad83c59c --- /dev/null +++ b/website/node/progression-definitions.mjs @@ -0,0 +1,49 @@ +import {MISSION_BRANCHES} from '../control-panel/public/cp-v2/cp-v2-progression-catalogue.mjs'; +import {defaultQuestXP} from './progression-reward-defaults.mjs'; +const spec={ + a:[['onboarding',1],['faction',1],['profile',1],['guild-travel',1],['citizen-introduction',1]], + b:[['earned-minor',100000],['bank-deposit',1],['bank-transfer',1],['shop-purchase',1],['earned-minor',2500000],['earned-minor',10000000],['earned-minor',50000000]], + c:[100,1000,5000,25000,100000,250000,500000,1000000].map(n=>['spice-harvest',n]), + d:[['arrakduin-visit',1],['arrakduin-active-minutes',30],['sietch-discovery',1],['oasis-discovery',1],['accessible-planets',1],['arrakduin-active-minutes',600],['advanced-survival',1]], + e:[1,5,20,50,100].map(n=>['jobs-completed',n]).concat([['employment',1],['wage-received',1]]), + f:[['forum-registration',1],...[1,10,25,50,100].map(n=>['forum-contributions',n]),['recognition',1]], + g:[['political-interface',1],['civic-activity',1],['civic-ballot-equivalent',1],['civic-additional',1],['public-event-equivalent',1]], + h:[['faction-kit',1],['starter-kit-repair',1],['equipment-use',1],['mark-upgrade',1],['rarity-enhancement',1],['equipment-mark',7],['equipment-mark',12],['equipment-mark',14]], + i:[['kit-design',1],['kit-publication',1],...[1,5,25,100,500].map(n=>['eligible-kit-sales',n])] +}; +// Definitions are server-owned. Browser labels never supply counters, rewards or authority. +export const QUEST_DEFINITIONS=Object.freeze([...MISSION_BRANCHES.filter(b=>b.id!=='discoveries').flatMap(branch=>branch.missions.map((mission,index)=>{ + const [metric,target]=spec[branch.id][index]||[];if(!metric)throw Error('Missing quest condition '+mission.id); + const previous=branch.missions[index-1],requires=previous?[previous.id]:[]; + return Object.freeze({...mission,branch:branch.id,metric,target,requires,requiresAny:[],season:'S01',xp:defaultQuestXP({branch:branch.id},index),reward:null,revision:1}); +})),...['company','clan'].flatMap(kind=>(kind==='company'?[1,3,5]:[1,5,10]).map((target,index)=>Object.freeze({ + id:`S1-ACQUIRE-${kind.toUpperCase()}-${target}`,title:`Acquire ${target} ${kind}${target===1?'':'s'}`, + branch:'acquisitions',optional:true,metric:`acquired-${kind}`,target, + requires:index?[`S1-ACQUIRE-${kind.toUpperCase()}-${(kind==='company'?[1,3,5]:[1,5,10])[index-1]}`]:[], + requiresAny:[],season:'S01',xp:defaultQuestXP({branch:'acquisitions',metric:`acquired-${kind}`},index),reward:null,revision:1 +})))]); +export const QUEST_METRICS=Object.freeze([...new Set(QUEST_DEFINITIONS.map(d=>d.metric))]); +export const XP_POLICY=Object.freeze({version:1,base:25,seasonCap:70,season:'S01',months:6}); +export function xpAtLevel(level,base=XP_POLICY.base){if(!Number.isSafeInteger(level)||level<1||level>1000||!Number.isSafeInteger(base)||base<1||base>100000)throw TypeError('Invalid XP curve');return base*level*(level-1)/2;} +export function levelForXP(xp,{base=XP_POLICY.base,cap=XP_POLICY.seasonCap}={}){if(!Number.isSafeInteger(xp)||xp<0||!Number.isSafeInteger(cap)||cap<1||cap>1000)throw TypeError('Invalid XP state');let level=1;while(level=xpAtLevel(level+1,base))level++;return level;} +export function questPrerequisites(definition,claimed){return definition.requires.every(id=>claimed.has(id))&&(!definition.requiresAny.length||definition.requiresAny.some(id=>claimed.has(id)));} + +// Only settled acquisitions count. Creating an entity is not acquiring one. +export function acquisitionMetric(kind,origin){ + if(kind==='clan'&&['conquest','bend-the-knee'].includes(origin))return 'acquired-clan'; + if(kind==='company'&&origin==='purchase')return 'acquired-company'; + return null; +} +export function questAwardXP(definition,baseXP){ + if(!Number.isSafeInteger(baseXP)||baseXP<0)throw TypeError('Invalid quest XP'); + const award=baseXP*(definition.optional?2:1); + if(!Number.isSafeInteger(award))throw TypeError('Invalid quest XP'); + return award; +} +// This selects completion records only: it must never fabricate underlying +// gameplay facts or execute unperformed objectives' domain effects. +export function completionByXP(definitions,{earnedXP,thresholdXP,completed=new Set()}){ + if(!Number.isSafeInteger(earnedXP)||earnedXP<0||!Number.isSafeInteger(thresholdXP)||thresholdXP<1)throw TypeError('Invalid completion threshold'); + if(earnedXP!d.optional&&!completed.has(d.id)).map(d=>({definitionId:d.id,reason:'xp-threshold'})); +} diff --git a/website/node/progression-policy.mjs b/website/node/progression-policy.mjs new file mode 100644 index 00000000..74599257 --- /dev/null +++ b/website/node/progression-policy.mjs @@ -0,0 +1,27 @@ +import {randomUUID} from 'node:crypto'; +import {QUEST_DEFINITIONS,XP_POLICY} from './progression-definitions.mjs'; +import {STAFF_OFFICE_ACCOUNT_ID} from './organisation-keys.mjs'; +export function sixMonthsAfter(timestamp){ + const start=new Date(timestamp),day=start.getUTCDate(),target=new Date(timestamp);target.setUTCDate(1);target.setUTCMonth(target.getUTCMonth()+6); + const last=new Date(Date.UTC(target.getUTCFullYear(),target.getUTCMonth()+1,0)).getUTCDate();target.setUTCDate(Math.min(day,last));return target.getTime(); +} +// Installation is an ordinary recorded system instrument, not manual data editing. +// Custom configuration is never overwritten by an application restart. +export async function ensureProgressionPolicy(db,keys,{clock=Date.now}={}){ + const scopeId='policy:'+XP_POLICY.season+':v'+XP_POLICY.version; + const grant=await keys.issue({accountId:STAFF_OFFICE_ACCOUNT_ID,keyType:'progression-policy',scopeId,authorize:async()=>{}}); + const key=(await keys.list(STAFF_OFFICE_ACCOUNT_ID)).find(k=>k.id===grant.id); + if(key.status==='used')return {configured:false,replayed:true}; + if(!key.code||key.status!=='available')throw Error('Progression policy instrument unavailable'); + return keys.consume({accountId:STAFF_OFFICE_ACCOUNT_ID,keyType:'progression-policy',code:key.code,targetId:STAFF_OFFICE_ACCOUNT_ID,requestId:grant.id,apply:async(tx,{keyId})=>{ + const now=clock(),existing=await tx.first('SELECT * FROM jarvis_progression_seasons WHERE season_id=? FOR UPDATE',[XP_POLICY.season]); + if(!existing){ + const active=await tx.query("SELECT season_id FROM jarvis_progression_seasons WHERE state='active' FOR UPDATE");if(active.length)throw Error('A different active season requires an explicit transition'); + await tx.query("INSERT INTO jarvis_progression_seasons(season_id,starts_at,ends_at,level_cap,curve_base,state) VALUES(?,?,?,?,?,'active')",[XP_POLICY.season,now,sixMonthsAfter(now),XP_POLICY.seasonCap,XP_POLICY.base]); + } + let added=0;for(const d of QUEST_DEFINITIONS){const previous=await tx.first('SELECT definition_id FROM jarvis_quest_config WHERE definition_id=? FOR UPDATE',[d.id]);if(previous)continue; + await tx.query('INSERT INTO jarvis_quest_config(definition_id,revision,xp,reward_json,updated_by,updated_at) VALUES(?,?,?,NULL,?,?)',[d.id,1,d.xp,STAFF_OFFICE_ACCOUNT_ID,now]);added++; + } + await tx.query('INSERT INTO jarvis_progression_history(id,account_id,key_id,action,details_json,created_at) VALUES(?,?,?,?,?,?)',[randomUUID(),STAFF_OFFICE_ACCOUNT_ID,keyId,'policy-configured',JSON.stringify({season:XP_POLICY.season,added,monetaryPayouts:false}),now]); + }}); +} diff --git a/website/node/progression-quests.mjs b/website/node/progression-quests.mjs new file mode 100644 index 00000000..e3ee2ef8 --- /dev/null +++ b/website/node/progression-quests.mjs @@ -0,0 +1,108 @@ +import {createHash,randomUUID} from 'node:crypto'; +import {QUEST_DEFINITIONS,questPrerequisites,questAwardXP,xpAtLevel,acquisitionMetric} from './progression-definitions.mjs'; +import {creditXP} from './progression-xp-ledger.mjs'; +import {lockXPAccount,readActiveXPSeason,saveXPAccount} from './progression-xp-store.mjs'; +const uuid=v=>typeof v==='string'&&/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(v); +const digest=value=>createHash('sha256').update(JSON.stringify(value)).digest('hex'); +const cap=season=>xpAtLevel(Number(season.level_cap),Number(season.curve_base)); +const read=async(db,sql,args=[])=>{const rows=await db.query(sql,args);return rows[0]||null;}; +const deterministicId=text=>{const h=createHash('sha256').update(text).digest('hex');return h.slice(0,8)+'-'+h.slice(8,12)+'-5'+h.slice(13,16)+'-8'+h.slice(17,20)+'-'+h.slice(20,32);}; +export function createQuestProgression(db,keys,{definitions=QUEST_DEFINITIONS,authorizePlayer,authorizeObservation,verifyAcquisition,resolvePlayer,clock=Date.now}){ + if(![authorizePlayer,authorizeObservation,verifyAcquisition,resolvePlayer].every(f=>typeof f==='function'))throw TypeError('Verified quest adapters required'); + const types=new Map(definitions.map(d=>[d.id,d])),metrics=new Set(definitions.map(d=>d.metric)); + if(types.size!==definitions.length)throw TypeError('Duplicate quest definitions'); + const definition=id=>{const d=types.get(id);if(!d)throw Error('Unknown quest definition');return d;}; + async function player(actor,store=db){if(!uuid(actor?.id)||!await authorizePlayer(actor,store))throw Error('Current player identity required');} + async function claimed(store,id,season){return new Set((await store.query('SELECT s.definition_id FROM jarvis_quest_states s JOIN jarvis_quest_claims c ON c.key_id=s.key_id WHERE s.account_id=? AND s.season_id=?',[id,season])).map(r=>r.definition_id));} + async function eligibility(store,id,d,season,state){ + const completed=await claimed(store,id,season.season_id),fact=await read(store,'SELECT quantity FROM jarvis_progression_facts WHERE account_id=? AND season_id=? AND metric=?',[id,season.season_id,d.metric]); + const bypass=!d.optional&&state.effectiveXP>=cap(season),prerequisites=questPrerequisites(d,completed); + return {progress:Number(fact?.quantity||0),ready:bypass||prerequisites&&Number(fact?.quantity||0)>=d.target,prerequisites:bypass||prerequisites,reason:bypass?'xp-threshold':'verified-objective'}; + } + async function updateFact(tx,{accountId,season,metric,value}){ + const old=await tx.first('SELECT quantity FROM jarvis_progression_facts WHERE account_id=? AND season_id=? AND metric=? FOR UPDATE',[accountId,season.season_id,metric]); + const quantity=Math.max(Number(old?.quantity||0),value); + await tx.query('INSERT INTO jarvis_progression_facts(account_id,season_id,metric,quantity,updated_at) VALUES(?,?,?,?,?) ON DUPLICATE KEY UPDATE quantity=VALUES(quantity),updated_at=VALUES(updated_at)',[accountId,season.season_id,metric,quantity,clock()]); + const states=await tx.query("SELECT definition_id,key_id FROM jarvis_quest_states WHERE account_id=? AND season_id=? AND state='active' FOR UPDATE",[accountId,season.season_id]); + for(const row of states){const d=definition(row.definition_id);if(d.metric!==metric)continue;const profile=await lockXPAccount(tx,accountId,clock()),eligible=await eligibility(tx,accountId,d,season,profile); + await tx.query('UPDATE jarvis_quest_states SET progress_value=?,state=?,completed_at=? WHERE key_id=?',[Math.min(quantity,d.target),eligible.ready?'completed':'active',eligible.ready?clock():null,row.key_id]); + } + return quantity; + } + const service={ + async list(actor){ + await player(actor);const now=clock(),seasons=await db.query("SELECT * FROM jarvis_progression_seasons WHERE state='active' AND starts_at<=? AND ends_at>?",[now,now]); + if(!seasons.length)return {state:'season-not-configured',quests:[]};if(seasons.length!==1)throw Error('Season configuration is ambiguous'); + const season=seasons[0],row=await read(db,'SELECT * FROM jarvis_progression_accounts WHERE account_id=?',[actor.id]),profile={totalXP:Number(row?.total_xp||0),effectiveXP:Number(row?.effective_xp||0),reserveXP:Number(row?.total_xp||0)-Number(row?.effective_xp||0),level:Number(row?.level_no||1)}; + const states=await db.query('SELECT * FROM jarvis_quest_states WHERE account_id=? AND season_id=?',[actor.id,season.season_id]),configs=await db.query('SELECT * FROM jarvis_quest_config'),done=await claimed(db,actor.id,season.season_id),quests=[]; + const facts=new Map((await db.query('SELECT metric,quantity FROM jarvis_progression_facts WHERE account_id=? AND season_id=?',[actor.id,season.season_id])).map(f=>[f.metric,Number(f.quantity)])); + for(const d of definitions.filter(d=>d.season===season.season_id)){const state=states.find(s=>s.definition_id===d.id),config=configs.find(c=>c.definition_id===d.id),progress=facts.get(d.metric)||0,bypass=!d.optional&&profile.effectiveXP>=cap(season),prerequisites=bypass||questPrerequisites(d,done),eligible={progress,prerequisites,ready:bypass||prerequisites&&progress>=d.target},configured=Number.isSafeInteger(config?.xp)&&config.xp>=0; + quests.push({id:d.id,title:d.title,branch:d.branch,metric:d.metric,requires:d.requires,optional:!!d.optional,target:d.target,progress:Math.min(eligible.progress,d.target),state:done.has(d.id)?'claimed':eligible.ready?'completed':state?.state||'not-started',keyId:state?.key_id||null,canStart:eligible.prerequisites&&!done.has(d.id),canClaim:eligible.ready&&configured&&!done.has(d.id),revision:config?Number(config.revision):null,xp:configured?questAwardXP(d,config.xp):null,rewardConfigured:configured}); + } + return {state:'active',season:{id:season.season_id,startsAt:Number(season.starts_at),endsAt:Number(season.ends_at),levelCap:Number(season.level_cap)},profile,quests}; + }, + async start(actor,{definitionId}){ + const d=definition(definitionId);await player(actor); + return keys.issue({accountId:actor.id,keyType:'quest',scopeId:d.season+':'+d.id,authorize:async(tx,{keyId})=>{ + await player(actor,tx);const state=await lockXPAccount(tx,actor.id,clock()),season=await readActiveXPSeason(tx,clock(),d.season),prior=await tx.first('SELECT key_id FROM jarvis_quest_states WHERE account_id=? AND definition_id=? AND season_id=? FOR UPDATE',[actor.id,d.id,season.season_id]);if(prior)return; + const e=await eligibility(tx,actor.id,d,season,state);if(!e.prerequisites)throw Error('Quest prerequisites are not completed'); + await tx.query('INSERT INTO jarvis_quest_states(key_id,account_id,definition_id,season_id,state,progress_value,revision,started_at,completed_at) VALUES(?,?,?,?,?,?,?,?,?)',[keyId,actor.id,d.id,season.season_id,e.ready?'completed':'active',Math.min(e.progress,d.target),d.revision,clock(),e.ready?clock():null]); + }}); + }, + async observe(actor,input){ + const {accountId,seasonId,metric,value,eventId,source}=input||{}; + if(!uuid(accountId)||!metrics.has(metric)||metric.startsWith('acquired-')||!Number.isSafeInteger(value)||value<0||typeof eventId!=='string'||eventId.length<1||eventId.length>160||typeof source!=='string'||source.length<1||source.length>32)throw TypeError('Invalid verified quest observation'); + const fingerprint=digest([accountId,seasonId,metric,value,source]); + return db.transaction(async tx=>{ + if(!await authorizeObservation(actor,input,tx))throw Error('Trusted observation authority required'); + await lockXPAccount(tx,accountId,clock());const season=await readActiveXPSeason(tx,clock(),seasonId),prior=await tx.first('SELECT fingerprint FROM jarvis_progression_observations WHERE event_id=? FOR UPDATE',[eventId]); + if(prior){if(prior.fingerprint!==fingerprint)throw Error('Observation reference conflict');return {replayed:true};} + await tx.query('INSERT INTO jarvis_progression_observations(event_id,account_id,season_id,fingerprint,source,created_at) VALUES(?,?,?,?,?,?)',[eventId,accountId,season.season_id,fingerprint,source,clock()]); + return {replayed:false,progress:await updateFact(tx,{accountId,season,metric,value})}; + }); + }, + async recordAcquisition(actor,{accountId,kind,entityId,origin}){ + const metric=acquisitionMetric(kind,origin);if(!uuid(accountId)||!uuid(entityId)||!metric)throw TypeError('Only confirmed acquisitions count'); + return db.transaction(async tx=>{ + if(!await verifyAcquisition(actor,{accountId,kind,entityId,origin},tx))throw Error('Verified deed settlement required'); + await lockXPAccount(tx,accountId,clock());const season=await readActiveXPSeason(tx,clock()),prior=await tx.first('SELECT origin FROM jarvis_progression_acquisitions WHERE account_id=? AND entity_kind=? AND entity_id=? FOR UPDATE',[accountId,kind,entityId]); + if(prior)return {replayed:true}; + await tx.query('INSERT INTO jarvis_progression_acquisitions(account_id,entity_kind,entity_id,origin,created_at) VALUES(?,?,?,?,?)',[accountId,kind,entityId,origin,clock()]); + const count=await tx.first('SELECT COUNT(*) total FROM jarvis_progression_acquisitions WHERE account_id=? AND entity_kind=?',[accountId,kind]);return {replayed:false,progress:await updateFact(tx,{accountId,season,metric,value:Number(count.total)})}; + }); + }, + async claim(actor,{definitionId,requestId,revision}){ + if(!uuid(requestId)||!Number.isSafeInteger(revision)||revision<1)throw TypeError('Review the current quest reward'); + await player(actor);const d=definition(definitionId),grant=await service.start(actor,{definitionId}),prior=await read(db,'SELECT request_id,account_id FROM jarvis_quest_claims WHERE key_id=?',[grant.id]); + if(prior){if(prior.account_id!==actor.id)throw Error('Quest claim unavailable');return {keyId:grant.id,replayed:true};} + const key=(await keys.list(actor.id)).find(k=>k.id===grant.id);if(!key?.code)throw Error('Quest instrument is unavailable'); + return keys.consume({accountId:actor.id,keyType:'quest',code:key.code,targetId:actor.id,requestId,apply:async(tx,{keyId,scopeId})=>{ + await player(actor,tx);const state=await lockXPAccount(tx,actor.id,clock()),season=await readActiveXPSeason(tx,clock(),d.season),e=await eligibility(tx,actor.id,d,season,state); + if(scopeId!==d.season+':'+d.id||!e.ready)throw Error('Quest objective is not complete'); + const config=await tx.first('SELECT * FROM jarvis_quest_config WHERE definition_id=? FOR UPDATE',[d.id]); + if(!config||!Number.isSafeInteger(config.xp)||config.xp<0||Number(config.revision)!==revision)throw Error('Quest reward changed or is not configured'); + const xp=questAwardXP(d,config.xp),reward=config.reward_json?JSON.parse(config.reward_json):{}; + await tx.query('INSERT INTO jarvis_quest_claims(key_id,request_id,account_id,xp,reward_json,claimed_at) VALUES(?,?,?,?,?,?)',[keyId,requestId,actor.id,xp,JSON.stringify(reward),clock()]); + await saveXPAccount(tx,actor.id,creditXP(state,xp,{capXP:cap(season)}),season,keyId,'quest-claimed',{definitionId:d.id,xp,reason:e.reason},clock()); + await tx.query("UPDATE jarvis_quest_states SET state='claimed',completed_at=COALESCE(completed_at,?) WHERE key_id=?",[clock(),keyId]); + if(Object.keys(reward).length)await tx.query("INSERT INTO jarvis_quest_reward_jobs(key_id,account_id,season_id,payload_json,state,created_at) VALUES(?,?,?,?,'queued',?)",[keyId,actor.id,season.season_id,JSON.stringify(reward),clock()]); + }}); + }, + async completeMandatory(actor){ + await player(actor);const view=await service.list(actor);if(view.state!=='active')throw Error('No active quest season'); + const season=await read(db,'SELECT * FROM jarvis_progression_seasons WHERE season_id=?',[view.season.id]);if(view.profile.effectiveXP!q.optional&&q.state!=='claimed')){ + if(!quest.rewardConfigured)throw Error('Mandatory reward configuration is incomplete'); + await service.claim(actor,{definitionId:quest.id,revision:quest.revision,requestId:deterministicId('automatic:'+actor.id+':'+season.season_id+':'+quest.id)});completed++; + } + return {completed}; + }, + async processCompletions({accountId=null}={}){ + if(accountId!==null&&!uuid(accountId))throw TypeError('Invalid completion account'); + const jobs=await db.query("SELECT * FROM jarvis_progression_outbox WHERE purpose='mandatory-completion' AND state='queued'"+(accountId?' AND account_id=?':'')+' ORDER BY created_at,id LIMIT 20',accountId?[accountId]:[]);let completed=0,failed=0; + for(const job of jobs)try{const actor=await resolvePlayer(job.account_id);if(!actor)throw Error('Player unavailable');const view=await service.list(actor);if(view.season?.id!==job.season_id)throw Error('Season is no longer active');await service.completeMandatory(actor);await db.query("UPDATE jarvis_progression_outbox SET state='completed' WHERE id=? AND state='queued'",[job.id]);completed++;}catch{failed++;} + return {completed,failed}; + } + }; + return Object.freeze(service); +} diff --git a/website/node/progression-reward-defaults.mjs b/website/node/progression-reward-defaults.mjs new file mode 100644 index 00000000..06103731 --- /dev/null +++ b/website/node/progression-reward-defaults.mjs @@ -0,0 +1,13 @@ +// Configurable Alpha XP defaults. No automatic DM issuance: monetary rewards +// require a separately funded, approved reward configuration and delivery adapter. +const XP={ + a:[100,100,150,150,250],b:[200,150,200,200,500,1000,2000], + c:[100,250,500,1000,2000,4000,6000,9000], + d:[200,250,300,300,500,1500,2500],e:[250,500,1000,2000,4000,300,500], + f:[150,100,250,500,1000,2000,2500],g:[150,250,400,500,700], + h:[300,350,500,750,1250,2000,2500,3500],i:[300,500,500,1000,1500,2500,5000] +}; +export function defaultQuestXP(definition,index){ + if(definition.branch==='acquisitions')return definition.metric==='acquired-company'?[750,1750,3500][index]:[1000,3000,6000][index]; + const result=XP[definition.branch]?.[index];if(!Number.isSafeInteger(result))throw Error('Missing Alpha reward default');return result; +} diff --git a/website/node/progression-runtime.mjs b/website/node/progression-runtime.mjs new file mode 100644 index 00000000..3ae54cc1 --- /dev/null +++ b/website/node/progression-runtime.mjs @@ -0,0 +1,52 @@ +import {createQuestProgression} from './progression-quests.mjs'; +import {createXPInstruments} from './progression-xp-instruments.mjs'; +import {firstLoginState} from './first-login.mjs'; +import {can} from './permissions.mjs'; +const first=async(db,sql,args=[])=>{const rows=await db.query(sql,args);return rows[0]||null;}; +export function createProgressionRuntime(central,bank,keys,{clock=Date.now,resolveCase=async()=>null,verifyAcquisition=async()=>false}={}){ + const observer=Object.freeze({internal:'progression-source-reader'}); + const resolvePlayer=id=>first(central,"SELECT id,username,display_name,role FROM site_accounts WHERE id=? AND password_hash NOT LIKE '!%'",[id]); + async function authorizePlayer(actor,store){ + if(typeof actor.revalidate==='function'&&(await actor.revalidate())?.id!==actor.id)return false; + return !!await first(store,"SELECT id FROM site_accounts WHERE id=? AND password_hash NOT LIKE '!%'",[actor.id]); + } + const quests=createQuestProgression(central,keys,{clock,authorizePlayer,resolvePlayer, + authorizeObservation:async actor=>actor===observer, + // A relation label alone cannot prove a settled transfer or its beneficiary. + // The existing deed settlement flow must supply its verified adapter. + verifyAcquisition:async(actor,input,tx)=>actor===observer&&await verifyAcquisition(input,tx) + }); + const xp=createXPInstruments(central,keys,{clock,resolveCase,authorizeIssue:async(actor,type)=>{ + const fresh=await resolvePlayer(actor.id);if(!fresh)return false; + return can(central,fresh,type==='xp-correction'?'web.progression.xp.correct':'web.progression.seasons.manage'); + }}); + async function collect(actor){ + if(!await authorizePlayer(actor,central))throw Error('Current player identity required'); + const now=clock(),seasons=await central.query("SELECT season_id,starts_at FROM jarvis_progression_seasons WHERE state='active' AND starts_at<=? AND ends_at>?",[now,now]); + if(seasons.length!==1)return {state:'season-not-configured',sources:[]};const season=seasons[0],sources=[]; + const save=async(metric,value)=>{ + const quantity=Number(value);if(!Number.isSafeInteger(quantity)||quantity<0)throw Error('Source counter is not safe'); + await quests.observe(observer,{accountId:actor.id,seasonId:season.season_id,metric,value:quantity,eventId:'web:'+actor.id+':'+season.season_id+':'+metric+':'+quantity,source:'verified-website'}); + }; + const source=async(name,metrics,work)=>{try{await work();sources.push({name,metrics,state:'available'});}catch{sources.push({name,metrics,state:'unavailable'});}}; + await source('profile',['onboarding','profile','faction'],async()=>{ + const profile=await first(central,'SELECT a.display_name,p.bio,l.minecraft_uuid FROM site_accounts a LEFT JOIN site_profiles p ON p.user_id=a.id LEFT JOIN site_game_links l ON l.user_id=a.id WHERE a.id=?',[actor.id]); + if(profile?.minecraft_uuid&&!await firstLoginState(central,actor))await save('onboarding',1); + if(profile?.display_name?.trim()&&String(profile.bio||'').trim().length>=10)await save('profile',1); + const choice=await first(central,'SELECT c.faction FROM site_character_choices c JOIN site_game_links l ON l.user_id=c.user_id AND l.minecraft_uuid=c.minecraft_uuid WHERE c.user_id=?',[actor.id]);if(choice?.faction)await save('faction',1); + }); + await source('forum',['forum-registration','forum-contributions'],async()=>{ + const account=await first(central,'SELECT uid FROM drforum_dune_accounts WHERE website_id=?',[actor.id]);if(!account)return;await save('forum-registration',1); + // Count unique meaningful, moderated-visible messages, with at most the first + // eligible contribution per thread/day; copied text never adds extra progress. + const count=await first(central,"SELECT COUNT(DISTINCT SHA2(LOWER(TRIM(p.message)),256)) total FROM drforum_posts p JOIN drforum_threads t ON t.tid=p.tid WHERE p.uid=? AND p.visible=1 AND t.visible=1 AND p.dateline>=? AND LENGTH(TRIM(p.message))>=40 AND NOT EXISTS(SELECT 1 FROM drforum_posts earlier WHERE earlier.uid=p.uid AND earlier.tid=p.tid AND earlier.visible=1 AND LENGTH(TRIM(earlier.message))>=40 AND FLOOR(earlier.dateline/86400)=FLOOR(p.dateline/86400) AND earlier.pid{ + const transfers=await first(bank,"SELECT COUNT(*) total FROM pb_orders o JOIN pb_accounts a ON a.id=o.source_id JOIN pb_clients c ON c.client_number=a.client_number JOIN pb_entities e ON e.id=c.entity_id JOIN pb_accounts target ON target.id=o.target_id WHERE e.kind='person' AND e.external_key=? AND o.state='posted' AND o.mode IN ('standard','instant') AND o.posted_at>=? AND o.source_id<>o.target_id AND (target.client_number IS NULL OR target.client_number<>a.client_number)",[actor.id,Number(season.starts_at)]);await save('bank-transfer',transfers.total); + const wages=await first(bank,"SELECT COUNT(*) total,COALESCE(SUM(o.amount_minor),0) earned FROM pb_orders o JOIN pb_accounts a ON a.id=o.target_id JOIN pb_clients c ON c.client_number=a.client_number JOIN pb_entities e ON e.id=c.entity_id WHERE e.kind='person' AND e.external_key=? AND o.state='posted' AND o.mode='payroll' AND o.posted_at>=?",[actor.id,Number(season.starts_at)]);await save('wage-received',wages.total);await save('earned-minor',wages.earned); + }); + return {state:'verified',sources}; + } + return Object.freeze({quests,xp,collect}); +} diff --git a/website/node/progression-schema.mjs b/website/node/progression-schema.mjs new file mode 100644 index 00000000..2d7e1577 --- /dev/null +++ b/website/node/progression-schema.mjs @@ -0,0 +1,16 @@ +const table=sql=>sql+' ENGINE=InnoDB DEFAULT CHARSET=utf8mb4'; +export const PROGRESSION_SCHEMA=Object.freeze([ + table(`CREATE TABLE IF NOT EXISTS jarvis_quest_reward_jobs(key_id CHAR(36) PRIMARY KEY,account_id CHAR(36) NOT NULL,season_id VARCHAR(8) NOT NULL,payload_json TEXT NOT NULL,state VARCHAR(24) NOT NULL,created_at BIGINT NOT NULL)`), + table(`CREATE TABLE IF NOT EXISTS jarvis_progression_acquisitions(account_id CHAR(36) NOT NULL,entity_kind VARCHAR(12) NOT NULL,entity_id CHAR(36) NOT NULL,origin VARCHAR(24) NOT NULL,created_at BIGINT NOT NULL,PRIMARY KEY(account_id,entity_kind,entity_id))`), + table(`CREATE TABLE IF NOT EXISTS jarvis_xp_instruments(key_id CHAR(36) PRIMARY KEY,account_id CHAR(36) NOT NULL,kind VARCHAR(24) NOT NULL,amount_xp BIGINT NOT NULL,source_reference VARCHAR(96) NOT NULL,source_season VARCHAR(8) NULL,target_season VARCHAR(8) NULL,issuer_id CHAR(36) NOT NULL,created_at BIGINT NOT NULL)`), + table(`CREATE TABLE IF NOT EXISTS jarvis_progression_accounts(account_id CHAR(36) PRIMARY KEY,total_xp BIGINT NOT NULL DEFAULT 0,effective_xp BIGINT NOT NULL DEFAULT 0,level_no INT NOT NULL DEFAULT 1,version INT NOT NULL DEFAULT 1,updated_at BIGINT NOT NULL)`), + table(`CREATE TABLE IF NOT EXISTS jarvis_progression_seasons(season_id VARCHAR(8) PRIMARY KEY,starts_at BIGINT NOT NULL,ends_at BIGINT NOT NULL,level_cap INT NOT NULL,curve_base INT NOT NULL,state VARCHAR(16) NOT NULL,revision INT NOT NULL DEFAULT 1)`), + table(`CREATE TABLE IF NOT EXISTS jarvis_quest_config(definition_id VARCHAR(64) PRIMARY KEY,revision INT NOT NULL,xp INT NULL,reward_json TEXT NULL,updated_by CHAR(36) NOT NULL,updated_at BIGINT NOT NULL)`), + table(`CREATE TABLE IF NOT EXISTS jarvis_quest_states(key_id CHAR(36) PRIMARY KEY,account_id CHAR(36) NOT NULL,definition_id VARCHAR(64) NOT NULL,season_id VARCHAR(8) NOT NULL,state VARCHAR(16) NOT NULL,progress_value BIGINT NOT NULL DEFAULT 0,revision INT NOT NULL DEFAULT 1,started_at BIGINT NOT NULL,completed_at BIGINT NULL,UNIQUE KEY quest_identity(account_id,definition_id,season_id))`), + table(`CREATE TABLE IF NOT EXISTS jarvis_progression_facts(account_id CHAR(36) NOT NULL,season_id VARCHAR(8) NOT NULL,metric VARCHAR(64) NOT NULL,quantity BIGINT NOT NULL,updated_at BIGINT NOT NULL,PRIMARY KEY(account_id,season_id,metric))`), + table(`CREATE TABLE IF NOT EXISTS jarvis_progression_observations(event_id VARCHAR(160) PRIMARY KEY,account_id CHAR(36) NOT NULL,season_id VARCHAR(8) NOT NULL,fingerprint CHAR(64) NOT NULL,source VARCHAR(32) NOT NULL,created_at BIGINT NOT NULL)`), + table(`CREATE TABLE IF NOT EXISTS jarvis_quest_claims(key_id CHAR(36) PRIMARY KEY,request_id CHAR(36) NOT NULL UNIQUE,account_id CHAR(36) NOT NULL,xp INT NOT NULL,reward_json TEXT NULL,claimed_at BIGINT NOT NULL)`), + table(`CREATE TABLE IF NOT EXISTS jarvis_progression_history(id CHAR(36) PRIMARY KEY,account_id CHAR(36) NOT NULL,key_id CHAR(36) NULL,action VARCHAR(32) NOT NULL,details_json TEXT NOT NULL,created_at BIGINT NOT NULL)`), + table(`CREATE TABLE IF NOT EXISTS jarvis_progression_outbox(id CHAR(36) PRIMARY KEY,account_id CHAR(36) NOT NULL,season_id VARCHAR(8) NOT NULL,purpose VARCHAR(32) NOT NULL,payload_json TEXT NOT NULL,state VARCHAR(16) NOT NULL,created_at BIGINT NOT NULL,UNIQUE KEY milestone_once(account_id,season_id,purpose))`) +]); +export async function initializeProgression(db){for(const sql of PROGRESSION_SCHEMA)await db.query(sql);} diff --git a/website/node/progression-xp-instruments.mjs b/website/node/progression-xp-instruments.mjs new file mode 100644 index 00000000..dfe7ffc5 --- /dev/null +++ b/website/node/progression-xp-instruments.mjs @@ -0,0 +1,65 @@ +import {lockXPAccount as account,readActiveXPSeason as activeSeason,saveXPAccount as save} from './progression-xp-store.mjs'; +import {creditXP,transferReservedXP} from './progression-xp-ledger.mjs'; +import {xpAtLevel} from './progression-definitions.mjs'; +const uuid=v=>typeof v==='string'&&/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(v); +const positive=n=>Number.isSafeInteger(n)&&n>0; +const seasonId=v=>/^S\d{2,4}$/.test(v||''); +// Uses the ordinary J.A.R.V.I.S. issue/consume transaction. resolveCase must read +// the authoritative support decision, not browser-provided ticket metadata. +export function createXPInstruments(db,keys,{authorizeIssue,resolveCase,clock=Date.now}){ + if(typeof authorizeIssue!=='function'||typeof resolveCase!=='function')throw TypeError('XP authority and support-case adapters required'); + async function approved(tx,reference,accountId){const source=await resolveCase(tx,reference);if(!source||source.approved!==true||source.accountId!==accountId||!positive(source.maxXP))throw Error('An approved matching support case is required');return source;} + async function insert(tx,{keyId,accountId,kind,amount,reference,from=null,to=null,issuer,now}){ + await tx.query('INSERT INTO jarvis_xp_instruments(key_id,account_id,kind,amount_xp,source_reference,source_season,target_season,issuer_id,created_at) VALUES(?,?,?,?,?,?,?,?,?)',[keyId,accountId,kind,amount,reference,from,to,issuer,now]); + } + return Object.freeze({ + async issueCorrection(actor,{accountId,caseReference,amountXP,requestId}){ + if(!uuid(actor?.id)||!uuid(accountId)||!uuid(requestId)||!positive(amountXP)||!/^[-a-zA-Z0-9_]{1,48}$/.test(caseReference||''))throw TypeError('Invalid XP correction'); + const scopeId='correction:'+caseReference+':'+requestId; + return keys.issue({accountId,keyType:'xp-correction',scopeId,authorize:async(tx,{keyId})=>{ + if(!await authorizeIssue(actor,'xp-correction',tx))throw Error('XP correction permission required'); + await account(tx,accountId,clock());const source=await approved(tx,caseReference,accountId); + const prior=await tx.first('SELECT p.* FROM jarvis_xp_instruments p JOIN organisation_keys k ON k.id=p.key_id WHERE k.account_id=? AND k.key_type=? AND k.scope_id=? FOR UPDATE',[accountId,'xp-correction',scopeId]); + if(prior){if(Number(prior.amount_xp)!==amountXP||prior.issuer_id!==actor.id)throw Error('XP issue reference conflict');return;} + const used=await tx.first("SELECT COALESCE(SUM(p.amount_xp),0) total FROM jarvis_xp_instruments p JOIN organisation_keys k ON k.id=p.key_id WHERE p.account_id=? AND p.kind='correction' AND p.source_reference=? AND k.revoked_at IS NULL",[accountId,caseReference]); + if(amountXP>source.maxXP-Number(used.total))throw Error('XP correction exceeds the uncompensated case amount'); + await insert(tx,{keyId,accountId,kind:'correction',amount:amountXP,reference:caseReference,issuer:actor.id,now:clock()}); + }}); + }, + async issueTransfer(actor,{accountId,fromSeason,toSeason}){ + if(!uuid(actor?.id)||!uuid(accountId)||!seasonId(fromSeason)||!seasonId(toSeason)||fromSeason===toSeason)throw TypeError('Invalid XP season transfer'); + return keys.issue({accountId,keyType:'xp-transfer',scopeId:'transfer:'+fromSeason+':'+toSeason,authorize:async(tx,{keyId})=>{ + if(!await authorizeIssue(actor,'xp-transfer',tx))throw Error('XP transfer permission required'); + const now=clock(),state=await account(tx,accountId,now),source=await tx.first('SELECT * FROM jarvis_progression_seasons WHERE season_id=? FOR UPDATE',[fromSeason]); + if(!source||source.state!=='closed'||Number(source.ends_at)>now)throw Error('Source season is not sealed'); + const target=await activeSeason(tx,now,toSeason); + const between=await tx.first('SELECT COUNT(*) total FROM jarvis_progression_seasons WHERE starts_at>=? AND ends_at<=?',[Number(source.ends_at),Number(target.starts_at)]); + if(Number(source.ends_at)>Number(target.starts_at)||Number(between.total)!==0)throw Error('XP transfers require consecutive seasons'); + const prior=await tx.first('SELECT id FROM organisation_keys WHERE account_id=? AND key_type=? AND scope_id=? FOR UPDATE',[accountId,'xp-transfer','transfer:'+fromSeason+':'+toSeason]);if(prior)return; + if(!positive(state.reserveXP))throw Error('No reserved XP is available'); + await insert(tx,{keyId,accountId,kind:'transfer',amount:state.reserveXP,reference:'season:'+fromSeason,from:fromSeason,to:toSeason,issuer:actor.id,now}); + }}); + }, + async redeem(user,{code,keyType,requestId}){ + if(!uuid(user?.id)||!['xp-correction','xp-transfer'].includes(keyType))throw TypeError('Invalid XP redemption'); + return keys.consume({accountId:user.id,keyType,code,targetId:user.id,requestId,apply:async(tx,{keyId})=>{ + if(typeof user.revalidate==='function'&&(await user.revalidate())?.id!==user.id)throw Error('XP redemption session changed'); + const now=clock(),state=await account(tx,user.id,now),instrument=await tx.first('SELECT * FROM jarvis_xp_instruments WHERE key_id=? AND account_id=? FOR UPDATE',[keyId,user.id]); + if(!instrument||!positive(Number(instrument.amount_xp)))throw Error('XP instrument unavailable'); + const season=await activeSeason(tx,now,keyType==='xp-transfer'?instrument.target_season:null),capXP=xpAtLevel(Number(season.level_cap),Number(season.curve_base));let next; + if(keyType==='xp-correction'){ + if(instrument.kind!=='correction')throw Error('XP instrument purpose mismatch'); + const source=await approved(tx,instrument.source_reference,user.id),used=await tx.first("SELECT COALESCE(SUM(p.amount_xp),0) total FROM jarvis_xp_instruments p JOIN organisation_keys k ON k.id=p.key_id WHERE p.account_id=? AND p.kind='correction' AND p.source_reference=? AND k.used_at IS NOT NULL",[user.id,instrument.source_reference]); + if(Number(instrument.amount_xp)>source.maxXP-Number(used.total))throw Error('XP correction approval changed'); + next=creditXP(state,Number(instrument.amount_xp),{capXP}); + }else{ + if(instrument.kind!=='transfer')throw Error('XP instrument purpose mismatch'); + const source=await tx.first('SELECT state,ends_at FROM jarvis_progression_seasons WHERE season_id=? FOR UPDATE',[instrument.source_season]); + if(source?.state!=='closed'||Number(source.ends_at)>now)throw Error('Source season is not sealed'); + next=transferReservedXP(state,{sealedAmount:Number(instrument.amount_xp),capXP}); + } + await save(tx,user.id,next,season,keyId,keyType,{sourceReference:instrument.source_reference,amountXP:Number(instrument.amount_xp)},now); + }}); + } + }); +} diff --git a/website/node/progression-xp-ledger.mjs b/website/node/progression-xp-ledger.mjs new file mode 100644 index 00000000..9af7ed52 --- /dev/null +++ b/website/node/progression-xp-ledger.mjs @@ -0,0 +1,19 @@ +// Account arithmetic shared by quest rewards, approved corrections and transfer +// instruments. Domain callers own authorisation, once-only keys and transactions. +const whole=n=>Number.isSafeInteger(n)&&n>=0; +function check(state){ + if(!state||![state.totalXP,state.effectiveXP,state.reserveXP].every(whole)||state.totalXP!==state.effectiveXP+state.reserveXP)throw TypeError('Invalid XP account'); +} +export function creditXP(state,amount,{capXP}){ + check(state);if(!whole(amount)||!whole(capXP)||state.effectiveXP>capXP)throw TypeError('Invalid XP credit'); + const totalXP=state.totalXP+amount;if(!whole(totalXP))throw TypeError('XP account overflow'); + const available=Math.min(amount,capXP-state.effectiveXP); + return {...state,totalXP,effectiveXP:state.effectiveXP+available,reserveXP:state.reserveXP+amount-available}; +} +export function transferReservedXP(state,{sealedAmount,capXP}){ + check(state); + if(!whole(sealedAmount)||sealedAmount>state.reserveXP||!whole(capXP)||capXP? FOR UPDATE",[now,now]); + if(rows.length!==1||expected&&rows[0].season_id!==expected)throw Error('A single matching active season is required');return rows[0]; +} +export async function saveXPAccount(tx,id,state,season,keyId,action,details,now){ + const level=levelForXP(state.effectiveXP,{base:Number(season.curve_base),cap:Number(season.level_cap)}); + await tx.query('UPDATE jarvis_progression_accounts SET total_xp=?,effective_xp=?,level_no=?,version=version+1,updated_at=? WHERE account_id=?',[state.totalXP,state.effectiveXP,level,now,id]); + await tx.query('INSERT INTO jarvis_progression_history(id,account_id,key_id,action,details_json,created_at) VALUES(?,?,?,?,?,?)',[randomUUID(),id,keyId,action,JSON.stringify({...details,seasonId:season.season_id,level,totalXP:state.totalXP,effectiveXP:state.effectiveXP,reserveXP:state.reserveXP}),now]); + const purposes=[]; + for(const milestone of [Math.max(1,Math.floor(Number(season.level_cap)/2)),Number(season.level_cap)])if(Number(state.level_no)=milestone)purposes.push(['level-'+milestone,{level:milestone,sourceKey:keyId}]); + if(level>=Number(season.level_cap))purposes.push(['mandatory-completion',{sourceKey:keyId}]); + for(const [purpose,payload]of purposes)await tx.query("INSERT INTO jarvis_progression_outbox(id,account_id,season_id,purpose,payload_json,state,created_at) VALUES(?,?,?,?,?,'queued',?) ON DUPLICATE KEY UPDATE purpose=VALUES(purpose)",[randomUUID(),id,season.season_id,purpose,JSON.stringify(payload),now]); +} diff --git a/website/tests/progression-api.test.mjs b/website/tests/progression-api.test.mjs new file mode 100644 index 00000000..87723a49 --- /dev/null +++ b/website/tests/progression-api.test.mjs @@ -0,0 +1,35 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import {randomUUID} from 'node:crypto'; +import {createProgressionAPI} from '../node/progression-api.mjs'; + +function fixture(){ + const user={id:randomUUID()},calls=[];let signedIn=true; + const quests={list:async actor=>({accountId:actor.id,quests:[]}),start:async(actor,body)=>{calls.push(['start',actor.id,body]);return{id:'instrument',created:true};},claim:async(actor,body)=>{calls.push(['claim',actor.id,body]);return{keyId:'instrument'};},processCompletions:async scope=>calls.push(['complete',scope])}; + const db={query:async(sql,args)=>{calls.push(['query',sql,args]);return[];}}; + const api=createProgressionAPI(db,{quests,authenticate:async()=>signedIn?user:null}); + const call=(path='',body,headers={})=>api(new Request('https://cp.dunerealms.com/api/progression'+path,body===undefined?{}:{method:'POST',headers:{origin:'https://cp.dunerealms.com','Content-Type':'application/json',...headers},body:JSON.stringify(body)})); + return {user,calls,call,logout:()=>{signedIn=false;}}; +} +test('progression reads require identity and history is scoped to the current account',async()=>{ + const f=fixture();assert.equal((await f.call()).headers.get('cache-control'),'private, no-store'); + assert.equal((await (await f.call()).json()).accountId,f.user.id); + assert.equal((await f.call('/history?page=2')).status,200); + const read=f.calls.find(c=>c[0]==='query');assert.deepEqual(read[2],[f.user.id]);assert.match(read[1],/OFFSET 25$/); + assert.equal((await f.call('/history?accountId=other')).status,400); + f.logout();assert.equal((await f.call()).status,401); +}); +test('mission writes reject foreign origins and client supplied XP or account overrides',async()=>{ + const f=fixture(),body={definitionId:'S1-A-01',confirmed:true}; + assert.equal((await f.call('/start',body,{origin:'https://other.example'})).status,403); + assert.equal((await f.call('/start',{...body,accountId:randomUUID()})).status,400); + assert.equal((await f.call('/start',{...body,xp:999999})).status,400); + assert.equal((await f.call('/start',{...body,confirmed:false})).status,400); + assert.equal(f.calls.length,0); + assert.equal((await f.call('/start',body)).status,200);assert.equal(f.calls[0][1],f.user.id); +}); +test('claim completion processing never broadens to another player',async()=>{ + const f=fixture();const response=await f.call('/claim',{definitionId:'S1-A-01',revision:1,requestId:randomUUID(),confirmed:true}); + assert.equal(response.status,200);assert.deepEqual(f.calls.at(-1),['complete',{accountId:f.user.id}]); + assert.equal((await f.call('/xp/redeem',{code:'DEV-forged',requestId:randomUUID(),confirmed:true})).status,400); +}); diff --git a/website/tests/progression-completion-policy.test.mjs b/website/tests/progression-completion-policy.test.mjs new file mode 100644 index 00000000..4fe43eb1 --- /dev/null +++ b/website/tests/progression-completion-policy.test.mjs @@ -0,0 +1,20 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import {QUEST_DEFINITIONS,acquisitionMetric,questAwardXP,completionByXP} from '../node/progression-definitions.mjs'; + +test('acquisitions exclude founding and accept both clan settlement paths',()=>{ + assert.equal(acquisitionMetric('clan','conquest'),'acquired-clan'); + assert.equal(acquisitionMetric('clan','bend-the-knee'),'acquired-clan'); + assert.equal(acquisitionMetric('company','purchase'),'acquired-company'); + for(const kind of ['clan','company'])assert.equal(acquisitionMetric(kind,'creation'),null); + assert.deepEqual(QUEST_DEFINITIONS.filter(d=>d.metric==='acquired-company').map(d=>d.target),[1,3,5]); + assert.deepEqual(QUEST_DEFINITIONS.filter(d=>d.metric==='acquired-clan').map(d=>d.target),[1,5,10]); +}); +test('optional rewards double XP and do not enter mandatory completion',()=>{ + assert.equal(questAwardXP({optional:true},75),150); + assert.equal(questAwardXP({optional:false},75),75); + const definitions=[{id:'required'},{id:'side',optional:true}]; + assert.deepEqual(completionByXP(definitions,{earnedXP:99,thresholdXP:100}),[]); + assert.deepEqual(completionByXP(definitions,{earnedXP:100,thresholdXP:100}),[{definitionId:'required',reason:'xp-threshold'}]); + assert.deepEqual(completionByXP(definitions,{earnedXP:100,thresholdXP:100,completed:new Set(['required'])}),[]); +}); diff --git a/website/tests/progression-policy.test.mjs b/website/tests/progression-policy.test.mjs new file mode 100644 index 00000000..4b8250c4 --- /dev/null +++ b/website/tests/progression-policy.test.mjs @@ -0,0 +1,22 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import {companyFixture} from './company-deed-fixture.mjs'; +import {initializeProgression} from '../node/progression-schema.mjs'; +import {ensureProgressionPolicy,sixMonthsAfter} from '../node/progression-policy.mjs'; +import {QUEST_DEFINITIONS} from '../node/progression-definitions.mjs'; + +test('season installation is recorded once and preserves an existing reward configuration',async()=>{ + const f=await companyFixture();try{ + await initializeProgression(f.db);const definition=QUEST_DEFINITIONS[0]; + await f.db.query('INSERT INTO jarvis_quest_config(definition_id,revision,xp,reward_json,updated_by,updated_at) VALUES(?,8,777,NULL,?,0)',[definition.id,f.people.Owner.id]); + await ensureProgressionPolicy(f.db,f.keys,{clock:()=>Date.UTC(2026,10,18)}); + const config=await f.db.first('SELECT revision,xp FROM jarvis_quest_config WHERE definition_id=?',[definition.id]);assert.deepEqual({...config},{revision:8,xp:777}); + assert.equal((await f.db.query('SELECT definition_id FROM jarvis_quest_config')).length,QUEST_DEFINITIONS.length); + assert.equal((await ensureProgressionPolicy(f.db,f.keys)).replayed,true); + assert.equal((await f.db.query("SELECT id FROM jarvis_progression_history WHERE action='policy-configured'")).length,1); + }finally{f.db.close();} +}); +test('six month seasons clamp month ends without overflowing into another month',()=>{ + assert.equal(new Date(sixMonthsAfter(Date.UTC(2026,7,31,15))).toISOString(),'2027-02-28T15:00:00.000Z'); + assert.equal(new Date(sixMonthsAfter(Date.UTC(2027,7,31))).toISOString(),'2028-02-29T00:00:00.000Z'); +}); diff --git a/website/tests/progression-quests.test.mjs b/website/tests/progression-quests.test.mjs new file mode 100644 index 00000000..b1da1528 --- /dev/null +++ b/website/tests/progression-quests.test.mjs @@ -0,0 +1,45 @@ +import test from 'node:test';import assert from 'node:assert/strict';import {randomUUID} from 'node:crypto'; +import {companyFixture} from './company-deed-fixture.mjs';import {initializeProgression} from '../node/progression-schema.mjs';import {createQuestProgression} from '../node/progression-quests.mjs'; +const definitions=[ + {id:'S1-TEST-01',title:'First objective',branch:'a',season:'S01',metric:'first',target:1,requires:[],requiresAny:[],revision:1,optional:false}, + {id:'S1-TEST-02',title:'Hard objective',branch:'a',season:'S01',metric:'hard',target:1000,requires:['S1-TEST-01'],requiresAny:[],revision:1,optional:false}, + {id:'S1-TEST-03',title:'Side objective',branch:'i',season:'S01',metric:'side',target:1,requires:[],requiresAny:[],revision:1,optional:true}, + {id:'S1-TEST-04',title:'Unfinished side objective',branch:'i',season:'S01',metric:'other',target:100,requires:[],requiresAny:[],revision:1,optional:true} +]; +async function fixture(){const f=await companyFixture();await initializeProgression(f.db); + await f.db.query("INSERT INTO jarvis_progression_seasons(season_id,starts_at,ends_at,level_cap,curve_base,state) VALUES('S01',0,5000,3,25,'active')"); + for(const [i,d]of definitions.entries())await f.db.query('INSERT INTO jarvis_quest_config(definition_id,revision,xp,reward_json,updated_by,updated_at) VALUES(?,1,?,NULL,?,0)',[d.id,i===0?50:25,f.people.Owner.id]); + const token={},service=createQuestProgression(f.db,f.keys,{definitions,clock:()=>2000,authorizePlayer:async actor=>actor.id===f.people.Member.id,authorizeObservation:async actor=>actor===token,verifyAcquisition:async actor=>actor===token,resolvePlayer:async id=>id===f.people.Member.id?f.people.Member:null}); + const observe=(metric,value,eventId=randomUUID())=>service.observe(token,{accountId:f.people.Member.id,seasonId:'S01',metric,value,eventId,source:'verified-test'}); + return {...f,service,observe}; +} +test('verified quest counters are idempotent, prerequisite-bound and cannot be supplied by players',async()=>{ + const f=await fixture();try{ + await assert.rejects(f.service.start(f.people.Member,{definitionId:'S1-TEST-02'}),/prerequisites/); + await assert.rejects(f.service.observe(f.people.Member,{accountId:f.people.Member.id,seasonId:'S01',metric:'first',value:1,eventId:'forged',source:'browser'}),/authority/); + const eventId=randomUUID();await f.observe('first',1,eventId);assert.equal((await f.observe('first',1,eventId)).replayed,true); + await assert.rejects(f.observe('first',2,eventId),/conflict/); + const claim={definitionId:'S1-TEST-01',revision:1,requestId:randomUUID()};await f.service.claim(f.people.Member,claim);assert.equal((await f.service.claim(f.people.Member,claim)).replayed,true); + assert.equal((await f.db.first('SELECT total_xp FROM jarvis_progression_accounts WHERE account_id=?',[f.people.Member.id])).total_xp,50); + assert.equal((await f.service.list(f.people.Member)).quests.find(q=>q.id==='S1-TEST-02').canStart,true); + }finally{f.db.close();} +}); +test('optional double XP can trigger every remaining mandatory reward without completing optionals or inventing gameplay facts',async()=>{ + const f=await fixture();try{ + await f.observe('side',1);await f.service.claim(f.people.Member,{definitionId:'S1-TEST-03',revision:1,requestId:randomUUID()}); + await f.observe('first',1);await f.service.claim(f.people.Member,{definitionId:'S1-TEST-01',revision:1,requestId:randomUUID()}); + assert.deepEqual(await f.service.processCompletions(),{completed:1,failed:0}); + const view=await f.service.list(f.people.Member);assert.equal(view.quests.find(q=>q.id==='S1-TEST-02').state,'claimed');assert.equal(view.quests.find(q=>q.id==='S1-TEST-04').state,'not-started'); + assert.equal(view.profile.totalXP,125);assert.equal(view.profile.effectiveXP,75);assert.equal(view.profile.reserveXP,50); + assert.equal(await f.db.first("SELECT quantity FROM jarvis_progression_facts WHERE metric='hard'"),null); + assert.deepEqual(await f.service.processCompletions(),{completed:0,failed:0}); + assert.equal((await f.db.query('SELECT key_id FROM jarvis_quest_claims')).length,3); + }finally{f.db.close();} +}); +test('changed reward revisions fail before XP or reward delivery is committed',async()=>{ + const f=await fixture();try{await f.observe('first',1); + await assert.rejects(f.service.claim(f.people.Member,{definitionId:'S1-TEST-01',revision:2,requestId:randomUUID()}),/changed/); + assert.equal((await f.db.query('SELECT key_id FROM jarvis_quest_claims')).length,0);assert.equal((await f.db.query('SELECT key_id FROM jarvis_quest_reward_jobs')).length,0); + assert.equal((await f.db.first('SELECT total_xp FROM jarvis_progression_accounts WHERE account_id=?',[f.people.Member.id])).total_xp,0); + }finally{f.db.close();} +}); diff --git a/website/tests/progression-xp-instruments.test.mjs b/website/tests/progression-xp-instruments.test.mjs new file mode 100644 index 00000000..7f59a4cd --- /dev/null +++ b/website/tests/progression-xp-instruments.test.mjs @@ -0,0 +1,39 @@ +import test from 'node:test';import assert from 'node:assert/strict';import {randomUUID} from 'node:crypto'; +import {companyFixture} from './company-deed-fixture.mjs';import {initializeProgression} from '../node/progression-schema.mjs';import {createXPInstruments} from '../node/progression-xp-instruments.mjs'; +async function fixture(){const f=await companyFixture();await initializeProgression(f.db); + await f.db.query("INSERT INTO jarvis_progression_seasons(season_id,starts_at,ends_at,level_cap,curve_base,state) VALUES('S01',0,1000,3,25,'closed'),('S02',1000,5000,4,25,'active')"); + const cases=new Map([['BAN-42',{accountId:f.people.Member.id,approved:true,maxXP:200}]]);let staff=true; + const service=createXPInstruments(f.db,f.keys,{clock:()=>2000,authorizeIssue:async actor=>staff&&actor.id===f.people.Owner.id,resolveCase:async(tx,id)=>cases.get(id)}); + return {...f,cases,service,revokeStaff:()=>{staff=false;},async balance(){return f.db.first('SELECT * FROM jarvis_progression_accounts WHERE account_id=?',[f.people.Member.id]);}}; +} +test('ticket-backed XP correction reserves its approved budget and redeems once into capped balance',async()=>{ + const f=await fixture();try{ + const request={accountId:f.people.Member.id,caseReference:'BAN-42',amountXP:200,requestId:randomUUID()}; + const key=await f.service.issueCorrection(f.people.Owner,request);assert.equal((await f.service.issueCorrection(f.people.Owner,request)).created,false); + await assert.rejects(f.service.issueCorrection(f.people.Owner,{...request,amountXP:1,requestId:randomUUID()}),/uncompensated/); + const claim={code:key.code,keyType:'xp-correction',requestId:randomUUID()}; + await assert.rejects(f.service.redeem(f.people.Other,claim),/unavailable/); + await f.service.redeem(f.people.Member,claim);assert.equal((await f.service.redeem(f.people.Member,claim)).replayed,true); + const balance=await f.balance();assert.equal(balance.total_xp,200);assert.equal(balance.effective_xp,150);assert.equal(balance.level_no,4); + assert.equal((await f.db.query('SELECT id FROM jarvis_progression_history')).length,1); + }finally{f.db.close();} +}); +test('revoked case approval or staff authority cannot issue or consume XP',async()=>{ + const f=await fixture();try{ + const input={accountId:f.people.Member.id,caseReference:'BAN-42',amountXP:100,requestId:randomUUID()},key=await f.service.issueCorrection(f.people.Owner,input); + f.cases.get('BAN-42').approved=false; + await assert.rejects(f.service.redeem(f.people.Member,{code:key.code,keyType:'xp-correction',requestId:randomUUID()}),/approved/); + assert.equal((await f.balance()).total_xp,0);assert.equal((await f.keys.list(f.people.Member.id))[0].status,'available'); + f.revokeStaff();await assert.rejects(f.service.issueCorrection(f.people.Owner,{...input,requestId:randomUUID()}),/permission/); + }finally{f.db.close();} +}); +test('sealed season transfer releases existing reserve once and never credits lifetime XP twice',async()=>{ + const f=await fixture();try{ + await f.db.query('INSERT INTO jarvis_progression_accounts(account_id,total_xp,effective_xp,level_no,version,updated_at) VALUES(?,200,75,3,1,0)',[f.people.Member.id]); + const key=await f.service.issueTransfer(f.people.Owner,{accountId:f.people.Member.id,fromSeason:'S01',toSeason:'S02'}),claim={code:key.code,keyType:'xp-transfer',requestId:randomUUID()}; + await f.service.redeem(f.people.Member,claim);assert.equal((await f.service.redeem(f.people.Member,claim)).replayed,true); + const balance=await f.balance();assert.equal(balance.total_xp,200);assert.equal(balance.effective_xp,150); + assert.equal((await f.service.issueTransfer(f.people.Owner,{accountId:f.people.Member.id,fromSeason:'S01',toSeason:'S02'})).created,false); + await assert.rejects(f.service.issueTransfer(f.people.Owner,{accountId:f.people.Member.id,fromSeason:'S02',toSeason:'S01'}),/sealed/); + }finally{f.db.close();} +}); diff --git a/website/tests/progression-xp-ledger.test.mjs b/website/tests/progression-xp-ledger.test.mjs new file mode 100644 index 00000000..24db1866 --- /dev/null +++ b/website/tests/progression-xp-ledger.test.mjs @@ -0,0 +1,18 @@ +import test from 'node:test';import assert from 'node:assert/strict'; +import {creditXP,transferReservedXP} from '../node/progression-xp-ledger.mjs'; +test('XP credits fill the current cap and reserve every excess point',()=>{ + const original={totalXP:90,effectiveXP:90,reserveXP:0}; + assert.deepEqual(creditXP(original,30,{capXP:100}),{totalXP:120,effectiveXP:100,reserveXP:20}); + assert.equal(original.totalXP,90); + assert.deepEqual(creditXP({totalXP:120,effectiveXP:100,reserveXP:20},10,{capXP:100}),{totalXP:130,effectiveXP:100,reserveXP:30}); +}); +test('sealed reserve transfer moves XP without duplicating lifetime XP',()=>{ + const state={totalXP:180,effectiveXP:100,reserveXP:80}; + assert.deepEqual(transferReservedXP(state,{sealedAmount:80,capXP:150}),{totalXP:180,effectiveXP:150,reserveXP:30}); + assert.throws(()=>transferReservedXP(state,{sealedAmount:81,capXP:150})); +}); +test('corrupt balances, negative credits and unsafe integers are rejected',()=>{ + assert.throws(()=>creditXP({totalXP:100,effectiveXP:99,reserveXP:0},10,{capXP:100})); + assert.throws(()=>creditXP({totalXP:0,effectiveXP:0,reserveXP:0},-1,{capXP:100})); + assert.throws(()=>creditXP({totalXP:Number.MAX_SAFE_INTEGER,effectiveXP:0,reserveXP:Number.MAX_SAFE_INTEGER},1,{capXP:100})); +});