diff --git a/docs/design/PERSONAL-PROGRESSION-SOURCES.md b/docs/design/PERSONAL-PROGRESSION-SOURCES.md index 80f57899..6da72284 100644 --- a/docs/design/PERSONAL-PROGRESSION-SOURCES.md +++ b/docs/design/PERSONAL-PROGRESSION-SOURCES.md @@ -5,21 +5,22 @@ Ticket 404 source audit, 21 November 2026. Definitions and numerical rewards rem | Branch / metrics | Authoritative evidence currently read | Remaining boundary | | --- | --- | --- | | Onboarding: `onboarding`, `faction`, `profile` | Current linked account; completed first-login state; faction choice bound to the current Minecraft UUID; non-empty display name and profile biography of at least ten characters | Browser assertions are not accepted | -| Onboarding: `guild-travel`, `citizen-introduction` | No connected verified reader | Requires the existing travel/introduction domain to publish a verified event; visiting a page is not travel | +| Onboarding: `guild-travel`, `citizen-introduction` | Typed Personal QSM reader; committed domain producer still required | Requires the existing travel/introduction domain to publish a verified event; visiting a page is not travel | | Economy: `bank-transfer` | Posted Postbank standard/instant order from a personal account to a different account/client since season start | Reservations and own-client transfers do not count | | Economy / careers: `earned-minor`, `wage-received` | Posted payroll orders into the player's personal bank entity since season start | The current earned-income reader covers payroll only; other verified income sources remain to be connected | -| Economy: `bank-deposit`, `shop-purchase` | No connected verified reader | Account balances, an open checkout or an unverified purchase are not substituted for a deposit or settled purchase | -| Spice: `spice-harvest` | No connected verified harvest reader | A future game event must prove harvested quantity; owning or buying spice is insufficient | -| Survival: `arrakduin-visit`, `arrakduin-active-minutes`, `sietch-discovery`, `oasis-discovery`, `accessible-planets`, `advanced-survival` | No connected verified game reader | No elapsed browser time, example discoveries or guessed world visits | -| Careers: `jobs-completed`, `employment` | No connected verified reader for these objectives | A political vacancy/application is not silently treated as a completed gameplay job | +| Economy: `bank-deposit`, `shop-purchase` | Typed Personal QSM reader; committed domain producer still required | Account balances, an open checkout or an unverified purchase are not substituted for a deposit or settled purchase | +| Spice: `spice-harvest` | Typed Personal QSM harvest reader; Minecraft producer remains outside this release | A future game event must prove harvested quantity; owning or buying spice is insufficient | +| Survival: `arrakduin-visit`, `arrakduin-active-minutes`, `sietch-discovery`, `oasis-discovery`, `accessible-planets`, `advanced-survival` | Typed Personal QSM reader; Minecraft producer remains outside this release | No elapsed browser time, example discoveries or guessed world visits | +| Careers: `jobs-completed`, `employment` | Typed Personal QSM reader; job/employment producer still required | A political vacancy/application is not silently treated as a completed gameplay job | | Community: `forum-registration`, `forum-contributions` | Central-to-MyBB account mapping and visible native posts in visible threads since season start; at least forty trimmed characters; first qualifying post per thread/day; duplicate normalized message text excluded | The existing reader reports unavailable when native evidence is inaccessible | -| Community: `recognition` | No connected eligible-award reader | A displayed badge alone does not establish an eligible quest award | +| Community: `recognition` | Typed Personal QSM reader; eligible-award producer still required | A displayed badge alone does not establish an eligible quest award | | Civic: `political-interface` | Authenticated server-side political workspace visit recorded through the progression service | The browser cannot submit a counter | | Civic: `civic-activity`, `civic-ballot-equivalent`, `civic-additional` | Allocated positive political ballots linked through the verified voter register since season start | Additional count excludes the first ballot; unrelated civic equivalents are not fabricated | -| Civic: `public-event-equivalent` | No connected verified participation reader | Opening an event page is not event attendance | -| Equipment: `faction-kit`, `starter-kit-repair`, `equipment-use`, `mark-upgrade`, `rarity-enhancement`, `equipment-mark` | No connected verified equipment/delivery reader | Q0 acquisition precedes repair in the existing definitions; ticket 406 owns the four parts, surrender and one replacement entitlement | +| Civic: `public-event-equivalent` | Typed Personal QSM reader; participation producer still required | Opening an event page is not event attendance | +| Equipment: `faction-kit`, `starter-kit-repair` | Original current-player/UUID/season Q0 delivery and repair QSM, including actual 50% durability snapshot, four parts and real surrender proof | Existing QST delivery outbox and native kit acknowledgement; no browser ownership assertion or fabricated physical surrender | +| Equipment: `equipment-use`, `mark-upgrade`, `rarity-enhancement`, `equipment-mark` | Typed Personal QSM reader; committed equipment producer still required | Generic activity cannot replace the dedicated Q0 physical proof | | Kit trade: `kit-design`, `kit-publication` | Active personal-sale blueprint with a meaningful name; active published positive-price listing bound to the blueprint's current version | A stale blueprint/listing does not qualify | -| Kit trade: `eligible-kit-sales` | No connected verified sale reader | Catalogue sales labels or unsettled checkouts are not credited | +| Kit trade: `eligible-kit-sales` | Typed Personal QSM reader; settled-sale producer still required | Catalogue sales labels or unsettled checkouts are not credited | | Optional acquisitions: `acquired-company`, paid `acquired-clan` | Posted deed-purchase job and balanced bank debit/credit, consumed seller XFR, applied dossier and matching buyer/parent/price/payment bindings | Listing publication, reservation, self-founding and a bare parent relation do not count | | Optional acquisitions: conquered `acquired-clan` | Consumed rebellion QST; recorded and unrevoked defender-victory QSM; completed office decision receipt; matching office tenure and immutable `entity-parent-changed` audit | Declaration or capture alone does not count. A lost rebel clan is credited only after the holder executes the existing claim decision. Other conquest producers are not implicitly trusted | @@ -36,3 +37,11 @@ Proof reads reuse the central transaction connection held by the acquisition ope ## Completion and remaining scope The existing level-cap completion operation settles mandatory rewards once through quest claims without inventing underlying facts; optional quests remain separate. Carry-over and Gazette milestone services remain separate existing consumers. The acquisition correction is not completion evidence for missing game/equipment/reward adapters, Council decisions, repeatable POL quests or the gated reset. No production captures or fake payments are used as tests. + +## Shared typed activity keys + +`quest-activity-events.mjs` is shared with Reputation through fixed server-side namespaces, with separate existing season registries, evidence tables and key scopes. The private Personal endpoint is `POST /internal/progression/personal/event`, protected by the existing game-link service authorization. Exact bounded fields: eventId, accountId, minecraftUuid, seasonId, metric, quantity, occurredAt, reference. Original committed domain receipts only; no browser assertion, free-form namespace, arbitrary metric, alternate recipient or reward override. Personal evidence needs no NPC identity; Reputation retains its current SID validation. + +Each domain producer must commit the actual travel/deposit/sale/harvest/job/award/attendance/equipment event before publishing its original unique reference. This release supplies the verified consumer and transport, not a Minecraft producer or a claim that currently absent external events already exist. A zero-event response explicitly lists pending metrics. Existing profile, forum, bank payroll/transfers, elections, acquisitions, atelier and Q0 readers remain authoritative and cannot be overridden through this endpoint. + +Collection reuses the existing observer, facts and QST claim engine. Under the claim transaction, current UUID, season, immutable payload and unrevoked original key are revalidated. A previously cached counter cannot authorize a new reward from revoked, altered or relinked evidence. Namespace isolation prevents Reputation evidence from granting Personal progress. Existing mandatory XP-threshold settlement is still permitted without creating domain facts; optional acquisitions and verified-only Q0 repair retain their requirements. No new quest engine, scheduler or game script is introduced. diff --git a/website/control-panel/public/jarvis-master-keys.mjs b/website/control-panel/public/jarvis-master-keys.mjs index 95628cff..88846ec8 100644 --- a/website/control-panel/public/jarvis-master-keys.mjs +++ b/website/control-panel/public/jarvis-master-keys.mjs @@ -30,6 +30,7 @@ export const MASTER_KEY_TEMPLATES=[ {id:'state',label:'Entity state',actions:[action('state.estate-freeze','Freeze estate from lore-death ESK','entity-state',[field('keyId','Verified lore-death ESK'),reference],{domainAdapter:'PostbankEstates.freeze',executionStatus:'bank-staff-consumer',effect:'Restrict existing personal accounts using a verified lore-death ESK; no balance changes.'}),action('state.estate-unlock','Unlock ESK estate','entity-state',[field('keyId','Existing ESK'),field('revision','Current bank effect revision','number',{min:1}),reference],{domainAdapter:'PostbankEstates.unlock',executionStatus:'bank-staff-consumer',effect:'Bank staff restore only the accounts held by the named ESK. Original death evidence remains unchanged.'}),action('state.record','Entity State Key','entity-state',[field('eventId','Unique source event ID'),field('action','State event'),field('targetUuid','Target entity UUID'),field('targetKind','Player or mob'),field('entityType','Entity type'),field('actorUuid','Killer / actor UUID','text',{required:false}),field('cause','Cause / reason'),field('scope','Server / lore scope'),field('world','World'),field('occurredAt','Event timestamp','number',{min:0}),reference],{recordOnly:true,domainAdapter:'entityStateKeys',executionStatus:'verified-service-record',artwork:'esk-key-v1.png',effect:'Record a verified death, respawn, ban or unban. Shared quest/contract/deed evidence with separate once-only consumer receipts. No Minecraft producer or ban migration in this batch.'})]}, {id:'progression',label:'Progression & XP',actions:[ action('progression.smuggler-institutions','Protected hidden smuggler institutions','staff-parent-link',[],{webIssue:false,domainAdapter:'clandestineInstitutions.provision',executionStatus:'current-owner-server-operator',effect:'Create the fixed protected clan and company under the current Esmar Tuek system identity. A verified introduction QST grants secondary quest affiliations only; never replace a player clan/company or grant PvP, bank, staff or office authority.'}), + action('progression.personal-activity','Verified Personal activity','quest-milestone',[field('eventId','Unique domain event'),field('accountId','Current player account'),field('minecraftUuid','Current linked player UUID'),field('seasonId','Current Personal season'),field('metric','Registered Personal objective metric'),field('quantity','Verified quantity','number',{min:1}),field('reference','Original committed evidence reference')],{webIssue:false,recordOnly:true,domainAdapter:'personalActivityEvents.record',executionStatus:'trusted-domain-producer-only',effect:'Read current immutable QSM evidence through the existing Personal quest engine. Preserve dedicated bank, forum, acquisition and Q0 proof readers. Missing external events remain pending; no browser counters or Minecraft producer are included.'}), action('progression.pol-activity','Verified Reputation activity','quest-milestone',[field('eventId','Unique domain event'),field('accountId','Current player account'),field('minecraftUuid','Current linked player UUID'),field('seasonId','Current season'),field('metric','Registered objective metric'),field('quantity','Verified quantity','number',{min:1}),field('reference','Original evidence reference')],{webIssue:false,recordOnly:true,domainAdapter:'polActivityEvents.record',executionStatus:'trusted-domain-producer-only',effect:'Bind actual committed activity to the current player, season and quest-giver SID. Reuse existing QSM evidence and POL claims; a browser cannot assert progress. PvP, mob and death objectives require original production Minecraft ESK evidence instead.'}), action('progression.pol-repeatables','Ongoing Reputation quest policy','progression-policy',[field('season','Season'),field('policyVersion','Policy version','number',{min:2})],{webIssue:false,recordOnly:true,domainAdapter:'ensurePOLRepeatablePolicy',executionStatus:'recorded-system-policy',effect:'Configure repeating PvP, mob, death, spice and smuggling episodes through existing QST claims. The bonus grows by 2% per completed round to a 5x cap. No default DM is minted; unverified game objectives stay pending.'}), action('xp.correct','Approved XP correction','xp-correction',[field('recipient','Recipient'),field('amountXP','XP amount','number',{min:1}),field('caseReference','Approved support case')]), diff --git a/website/control-panel/server.mjs b/website/control-panel/server.mjs index 4320a6f6..fdc10cef 100644 --- a/website/control-panel/server.mjs +++ b/website/control-panel/server.mjs @@ -1,3 +1,5 @@ +import {initializePersonalActivityEvents} from '../node/personal-activity-events.mjs'; +import {createPersonalActivityAPI} from '../node/personal-activity-api.mjs'; import {initializeSecondaryAffiliations} from '../node/clandestine-institutions.mjs'; import {initializePOLActivityEvents} from '../node/pol-activity-events.mjs'; import {createPOLActivityAPI} from '../node/pol-activity-api.mjs'; @@ -222,6 +224,7 @@ export function createPanel(db,settings={},dependencies={}){ const serverProjects=dependencies.serverProjects||(dependencies.organisationKeys?createServerProjectRuntime(db,dependencies.bankDatabase||null,dependencies.organisationKeys):null); const projectsAPI=createServerProjectAPI(db,serverProjects,{origin}); const starterKitEvents=createStarterKitEventAPI(db,dependencies.organisationKeys,settings); + const personalActivityEvents=createPersonalActivityAPI(db,dependencies.organisationKeys,settings); const polActivityEvents=createPOLActivityAPI(db,dependencies.organisationKeys,settings); const masterKeyGenerator=createMasterKeyGeneratorAPI(db,dependencies.organisationKeys,{origin}); const keyValidation=createKeyValidation(db,dependencies.organisationKeys,{origin}); @@ -377,6 +380,7 @@ export function createPanel(db,settings={},dependencies={}){ if(path==='/api/public/bans'&&request.method==='GET')return banBridge.publicBans(); if(path==='/api/overview'||path==='/api/overview/staff')return overview(request); const sharedError=await sharedErrorResponse(request);if(sharedError)return sharedError; + if(path.startsWith('/internal/progression/personal/'))return personalActivityEvents(request); if(path.startsWith('/internal/progression/pol/'))return polActivityEvents(request); if(path.startsWith('/internal/equipment/'))return starterKitEvents(request); if(path==='/internal/integrations/ban')return banBridge.handle(request); @@ -468,7 +472,7 @@ 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 initializePassiveOrders(db);await initializeJarvisGenerator(db);await initializeEntityState(db);await initializeSystemCharacters(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); /* Passive POL conversion waits for scoped adapters instead of company management. */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 initializeStarterKitEvents(db);db.starterKitEventsEnabled=true;await initializeServerProjects(db);if(bankDatabase)await bankDatabase.query(PROJECT_BANK_SCHEMA);await db.query(GAZETTE_SCHEMA);await ensureProgressionPolicy(db,organisationKeys);await ensureStarterKitRewardPolicy(db,organisationKeys).catch(()=>console.error('Starter kit reward policy requires review; existing custom configuration was preserved'));await initializePOLProgression(db);await initializeSecondaryAffiliations(db);await initializePOLActivityEvents(db);db.polActivityEventsEnabled=true;await initializeRebellionRewards(db);await ensurePOLProgressionPolicy(db,organisationKeys);await ensurePOLRepeatablePolicy(db,organisationKeys);db.polRepeatablesEnabled=true;const progressionRuntime=createProgressionRuntime(db,bankDatabase,organisationKeys);const officeAuctionRuntime=createOfficeAuctionRuntime(db,bankDatabase);const promotionDelivery=bankDatabase?await configurePromotionDelivery(db,bankDatabase,settings):null;const deedPurchases=bankDatabase&&settings.POSTBANK_ENABLED==='true'?createDeedPurchases(db,bankDatabase,organisationKeys,{authority:createPostbankAuthority(db,{bank:bankDatabase})}):null;const starterKitDelivery=await openStarterKitDelivery(db,settings);const boardRuntime=await openBoardKeyRuntime(db,organisationKeys,settings);const handle=createPanel(db,settings,{boardRuntime,inventoryPool,bankDatabase,organisationKeys,deedPurchases,officeAuctionRuntime,promotionDelivery,progressionRuntime}),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 initializePassiveOrders(db);await initializeJarvisGenerator(db);await initializeEntityState(db);await initializeSystemCharacters(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); /* Passive POL conversion waits for scoped adapters instead of company management. */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 initializeStarterKitEvents(db);db.starterKitEventsEnabled=true;await initializeServerProjects(db);if(bankDatabase)await bankDatabase.query(PROJECT_BANK_SCHEMA);await db.query(GAZETTE_SCHEMA);await ensureProgressionPolicy(db,organisationKeys);await ensureStarterKitRewardPolicy(db,organisationKeys).catch(()=>console.error('Starter kit reward policy requires review; existing custom configuration was preserved'));await initializePOLProgression(db);await initializeSecondaryAffiliations(db);await initializePersonalActivityEvents(db);db.personalActivityEventsEnabled=true;await initializePOLActivityEvents(db);db.polActivityEventsEnabled=true;await initializeRebellionRewards(db);await ensurePOLProgressionPolicy(db,organisationKeys);await ensurePOLRepeatablePolicy(db,organisationKeys);db.polRepeatablesEnabled=true;const progressionRuntime=createProgressionRuntime(db,bankDatabase,organisationKeys);const officeAuctionRuntime=createOfficeAuctionRuntime(db,bankDatabase);const promotionDelivery=bankDatabase?await configurePromotionDelivery(db,bankDatabase,settings):null;const deedPurchases=bankDatabase&&settings.POSTBANK_ENABLED==='true'?createDeedPurchases(db,bankDatabase,organisationKeys,{authority:createPostbankAuthority(db,{bank:bankDatabase})}):null;const starterKitDelivery=await openStarterKitDelivery(db,settings);const boardRuntime=await openBoardKeyRuntime(db,organisationKeys,settings);const handle=createPanel(db,settings,{boardRuntime,inventoryPool,bankDatabase,organisationKeys,deedPurchases,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:[{key:'starter_kit_rewards',slot:now=>Math.floor(now/60000)*60000,run:()=>starterKitDelivery.drain()},...(boardRuntime?[{key:'board_keys',slot:now=>Math.floor(now/60000)*60000,run:()=>boardRuntime.drain()}]:[]),...(bankDatabase?[{key:'rebellion_rewards',slot:now=>Math.floor(now/60000)*60000,run:()=>createRebellionRewards(db,bankDatabase,{sourceAccount:settings.REBELLION_REWARD_SOURCE_ACCOUNT,sourceOwnerId:settings.REBELLION_REWARD_SOURCE_OWNER_ID,useWebsiteTreasury:settings.REBELLION_REWARD_FUND==='website-treasury'}).drain()},...(deedPurchases?[{key:'deed_purchases',slot:now=>Math.floor(now/60000)*60000,run:()=>deedPurchases.drain()}]:[]),{key:'server_projects',slot:now=>Math.floor(now/60000)*60000,run:()=>createServerProjectRuntime(db,bankDatabase,organisationKeys).drain()},{key:'progression_completion',slot:now=>Math.floor(now/60000)*60000,run:async()=>{const completed=await progressionRuntime.quests.processCompletions();const news=await progressionRuntime.announcements.drain();return {completed,news};}},{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"}; diff --git a/website/node/personal-activity-api.mjs b/website/node/personal-activity-api.mjs new file mode 100644 index 00000000..2e07694b --- /dev/null +++ b/website/node/personal-activity-api.mjs @@ -0,0 +1,2 @@ +import {createQuestActivityAPI} from './quest-activity-api.mjs'; +export const createPersonalActivityAPI=(db,keys,settings,options)=>createQuestActivityAPI(db,keys,settings,{...options,namespace:'personal'}); diff --git a/website/node/personal-activity-events.mjs b/website/node/personal-activity-events.mjs new file mode 100644 index 00000000..740a0e9a --- /dev/null +++ b/website/node/personal-activity-events.mjs @@ -0,0 +1,6 @@ +import {questActivitySchema,initializeQuestActivityEvents,createQuestActivityEvents,verifiedQuestActivities} from './quest-activity-events.mjs'; +export {PERSONAL_ACTIVITY_METRICS} from './quest-activity-events.mjs'; +export const PERSONAL_ACTIVITY_SCHEMA=questActivitySchema('personal'); +export const initializePersonalActivityEvents=db=>initializeQuestActivityEvents(db,'personal'); +export const createPersonalActivityEvents=(db,keys,options)=>createQuestActivityEvents(db,keys,{...options,namespace:'personal'}); +export const verifiedPersonalActivities=(db,keys,options)=>verifiedQuestActivities(db,keys,{...options,namespace:'personal'}); diff --git a/website/node/pol-activity-api.mjs b/website/node/pol-activity-api.mjs index f7f65bfa..b284ed6a 100644 --- a/website/node/pol-activity-api.mjs +++ b/website/node/pol-activity-api.mjs @@ -1,16 +1,2 @@ -import {gameAuthorized} from './game-link.mjs'; -import {createPOLActivityEvents} from './pol-activity-events.mjs'; -export function createPOLActivityAPI(db,keys,settings,{clock=Date.now}={}){ - const producer={},events=keys?createPOLActivityEvents(db,keys,{clock,authorizeProducer:async actor=>actor===producer}):null; - const reply=(value,status=200)=>Response.json(value,{status,headers:{'Cache-Control':'private, no-store','X-Content-Type-Options':'nosniff'}}); - return async request=>{ - if(!gameAuthorized(request,settings))return reply({message:'Unauthorized'},401); - const url=new URL(request.url);if(url.pathname!=='/internal/progression/pol/event'||request.method!=='POST')return reply({message:'Activity route not found.'},404); - if(url.search)return reply({message:'Activity identity overrides are not accepted.'},400); - if(!events)return reply({message:'Activity keys are unavailable.'},503); - 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:'Activity evidence required.'},400);let size=0;const chunks=[]; - try{while(true){const {done,value}=await reader.read();if(done)break;size+=value.length;if(size>4096){await reader.cancel();return reply({message:'Activity event exceeds its bound.'},413);}chunks.push(value);}return reply(await events.record(producer,JSON.parse(Buffer.concat(chunks).toString('utf8'))));} - catch{return reply({message:'The activity receipt could not be verified. No objective was credited.'},409);}finally{reader.releaseLock();} - }; -} +import {createQuestActivityAPI} from './quest-activity-api.mjs'; +export const createPOLActivityAPI=(db,keys,settings,options)=>createQuestActivityAPI(db,keys,settings,{...options,namespace:'pol'}); diff --git a/website/node/pol-activity-events.mjs b/website/node/pol-activity-events.mjs index b9562cc5..d0ea5730 100644 --- a/website/node/pol-activity-events.mjs +++ b/website/node/pol-activity-events.mjs @@ -1,51 +1,7 @@ -import {POL_REPEATABLES} from './pol-repeatable-quests.mjs'; -import {createHash} from 'node:crypto'; -import {STAFF_OFFICE_ACCOUNT_ID} from './organisation-keys.mjs'; -import {createSystemCharacters} from './system-characters.mjs'; -import {POL_QUEST_DEFINITIONS} from '../control-panel/public/cp-v2/cp-v2-pol-quest-catalogue.mjs'; -const activityDefinition=metric=>POL_QUEST_DEFINITIONS.find(d=>d.metric===metric)||POL_REPEATABLES.find(d=>['SPICE','CARGO'].includes(d.key)&&d.metric===metric); -const uuid=v=>typeof v==='string'&&/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(v); -const hash=v=>createHash('sha256').update(JSON.stringify(v)).digest('hex'); -const first=async(db,sql,args=[])=>(await db.query(sql,args))[0]||null; -export const POL_ACTIVITY_SCHEMA='CREATE TABLE IF NOT EXISTS jarvis_pol_activity_events(key_id CHAR(36) PRIMARY KEY,event_id CHAR(36) NOT NULL UNIQUE,account_id CHAR(36) NOT NULL,minecraft_uuid CHAR(36) NOT NULL,season_id VARCHAR(8) NOT NULL,metric VARCHAR(64) NOT NULL,source_reference VARCHAR(96) NOT NULL,quantity BIGINT NOT NULL,issuer_key_id CHAR(36) NOT NULL,payload_json TEXT NOT NULL,fingerprint CHAR(64) NOT NULL,occurred_at BIGINT NOT NULL,created_at BIGINT NOT NULL,UNIQUE KEY pol_activity_evidence(account_id,season_id,metric,source_reference),INDEX pol_activity_account(account_id,season_id,metric)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4'; -export async function initializePOLActivityEvents(db){await db.query(POL_ACTIVITY_SCHEMA);} -export async function currentPOLPlayer(db,accountId,minecraftUuid,{lock=false}={}){ - const rows=await db.query("SELECT a.id FROM site_accounts a JOIN site_game_links l ON l.user_id=a.id WHERE l.minecraft_uuid=? AND a.password_hash NOT LIKE '!%' AND a.role NOT IN ('system_account','official_account','memorial') AND NOT EXISTS(SELECT 1 FROM site_memorials m WHERE m.user_id=a.id)"+(lock?' FOR UPDATE':''),[minecraftUuid]); - return rows.length===1&&rows[0].id===accountId; -} -async function issuer(store,keys,name,{lock=false}={}){ - const identity=await createSystemCharacters(store,keys,{authorizeOperator:async()=>false}).inspect(name); - if(!identity?.capabilities.includes('quest.issue'))throw Error('Current scoped quest giver required'); - if(lock){const key=await first(store,'SELECT id,revoked_at FROM organisation_keys WHERE id=? FOR UPDATE',[identity.keyId]);if(!key||key.revoked_at!==null)throw Error('Current scoped quest giver required');}return identity; -} -export function createPOLActivityEvents(db,keys,{authorizeProducer,clock=Date.now}={}){ - if(typeof authorizeProducer!=='function')throw TypeError('Trusted activity producer required'); - return Object.freeze({async record(actor,input){ - const fields=['eventId','accountId','minecraftUuid','seasonId','metric','quantity','occurredAt','reference']; - if(!input||typeof input!=='object'||Array.isArray(input)||Object.keys(input).length!==fields.length||fields.some(k=>!Object.hasOwn(input,k))||!uuid(input.eventId)||!uuid(input.accountId)||!uuid(input.minecraftUuid)||input.seasonId!=='S01'||!Number.isSafeInteger(input.quantity)||input.quantity<1||input.quantity>1000000||!Number.isSafeInteger(input.occurredAt)||input.occurredAt>clock()+30000||typeof input.reference!=='string'||input.reference.length<1||input.reference.length>96||/[\x00-\x1f]/.test(input.reference))throw TypeError('Invalid verified activity fields'); - const definition=activityDefinition(input.metric);if(!definition)throw TypeError('Registered POL objective required'); - const payload=Object.fromEntries(fields.map(k=>[k,['eventId','accountId','minecraftUuid'].includes(k)?input[k].toLowerCase():input[k]])),fingerprint=hash(payload); - if(await authorizeProducer(actor,payload,db)!==true)throw Error('Trusted activity producer required'); - const grant=await keys.issue({accountId:STAFF_OFFICE_ACCOUNT_ID,keyType:'quest-milestone',scopeId:payload.seasonId+':POL_ACTIVITY_'+payload.eventId,authorize:async(tx,{keyId})=>{ - if(await authorizeProducer(actor,payload,tx)!==true||!await currentPOLPlayer(tx,payload.accountId,payload.minecraftUuid))throw Error('Current activity identity required'); - const season=await tx.first("SELECT starts_at,ends_at FROM jarvis_pol_progression_seasons WHERE season_id=? AND state='active' AND starts_at<=? AND ends_at>? FOR UPDATE",[payload.seasonId,clock(),clock()]); - if(!season||payload.occurredAt=Number(season.ends_at))throw Error('Current activity season required'); - const current=await issuer(tx,keys,definition.issuer);const identityKey=await tx.first('SELECT id,revoked_at FROM organisation_keys WHERE id=? FOR UPDATE',[current.keyId]);if(!identityKey||identityKey.revoked_at!==null)throw Error('Current scoped quest giver required'); - const prior=await tx.first('SELECT key_id,fingerprint FROM jarvis_pol_activity_events WHERE event_id=? FOR UPDATE',[payload.eventId]); - if(prior){if(prior.fingerprint!==fingerprint)throw Error('Activity event reference conflict');return;} - await tx.query('INSERT INTO jarvis_pol_activity_events(key_id,event_id,account_id,minecraft_uuid,season_id,metric,source_reference,quantity,issuer_key_id,payload_json,fingerprint,occurred_at,created_at) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)',[keyId,payload.eventId,payload.accountId,payload.minecraftUuid,payload.seasonId,payload.metric,payload.reference,payload.quantity,current.keyId,JSON.stringify(payload),fingerprint,payload.occurredAt,clock()]); - }}); - const saved=await first(db,'SELECT fingerprint FROM jarvis_pol_activity_events WHERE key_id=?',[grant.id]);if(saved?.fingerprint!==fingerprint)throw Error('Activity event reference conflict');return {keyId:grant.id,created:grant.created}; - }}); -} -export async function verifiedPOLActivities(db,keys,{accountId,minecraftUuid,seasonId,startsAt,endsAt,now=Date.now(),lock=false}){ - if(!await currentPOLPlayer(db,accountId,minecraftUuid,{lock}))throw Error('Current activity identity required'); - const rows=await db.query("SELECT e.*,k.key_type,k.account_id key_owner,k.scope_id,k.revoked_at FROM jarvis_pol_activity_events e JOIN organisation_keys k ON k.id=e.key_id WHERE e.account_id=? AND e.season_id=? ORDER BY e.occurred_at,e.key_id"+(lock?' FOR UPDATE':''),[accountId,seasonId]),totals=new Map(),seen=new Set(),proofIds=[]; - for(const r of rows){ - const p=JSON.parse(r.payload_json),d=activityDefinition(r.metric); - if(!d||!uuid(p.eventId)||!Number.isSafeInteger(p.quantity)||p.quantity<1||p.quantity>1000000||p.reference!==r.source_reference||r.key_type!=='quest-milestone'||r.key_owner!==STAFF_OFFICE_ACCOUNT_ID||r.revoked_at!==null||hash(p)!==r.fingerprint||r.scope_id!==seasonId+':POL_ACTIVITY_'+p.eventId||p.accountId!==accountId||p.minecraftUuid!==minecraftUuid||p.seasonId!==seasonId||p.metric!==r.metric||p.quantity!==Number(r.quantity)||p.occurredAt!==Number(r.occurred_at)||p.occurredAt=endsAt||p.occurredAt>now+30000||seen.has(p.eventId))continue; - const current=await issuer(db,keys,d.issuer,{lock});if(current.keyId!==r.issuer_key_id)continue; - seen.add(p.eventId);proofIds.push(r.key_id);const total=(totals.get(r.metric)||0)+p.quantity;if(!Number.isSafeInteger(total))throw Error('Activity quantity requires review');totals.set(r.metric,total); - } - return {totals,proofIds}; -} +// Fixed POL namespace of the shared verified activity adapter. +import {questActivitySchema,initializeQuestActivityEvents,createQuestActivityEvents,verifiedQuestActivities,currentActivityPlayer} from './quest-activity-events.mjs'; +export const POL_ACTIVITY_SCHEMA=questActivitySchema('pol'); +export const initializePOLActivityEvents=db=>initializeQuestActivityEvents(db,'pol'); +export const createPOLActivityEvents=(db,keys,options)=>createQuestActivityEvents(db,keys,{...options,namespace:'pol'}); +export const verifiedPOLActivities=(db,keys,options)=>verifiedQuestActivities(db,keys,{...options,namespace:'pol'}); +export const currentPOLPlayer=currentActivityPlayer; diff --git a/website/node/progression-quests.mjs b/website/node/progression-quests.mjs index f470f7fa..b55fc341 100644 --- a/website/node/progression-quests.mjs +++ b/website/node/progression-quests.mjs @@ -80,7 +80,7 @@ export function createQuestProgression(db,keys,{definitions=QUEST_DEFINITIONS,au 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(!await authorizeClaim(actor,d,tx)||scopeId!==d.season+':'+d.id||!e.ready)throw Error('Quest objective is not complete'); + if(!await authorizeClaim(actor,d,tx,{eligibility:e,season,state})||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):{}; diff --git a/website/node/progression-runtime.mjs b/website/node/progression-runtime.mjs index 1c7ab691..6fd5a177 100644 --- a/website/node/progression-runtime.mjs +++ b/website/node/progression-runtime.mjs @@ -1,3 +1,6 @@ +import {PERSONAL_ACTIVITY_METRICS,verifiedPersonalActivities} from './personal-activity-events.mjs'; +import {createHash} from 'node:crypto'; +import {xpAtLevel} from './progression-definitions.mjs'; import {verifiedStarterKitEvidence} from './starter-kit-events.mjs'; import {verifyDeedAcquisition} from './deed-acquisition-proof.mjs'; import {createProgressionMilestoneNews} from './progression-milestone-news.mjs'; @@ -13,12 +16,28 @@ export function createProgressionRuntime(central,bank,keys,{clock=Date.now,resol 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, + async function activityEvidence(actor,store=central,{lock=false}={}){ + if(!central.personalActivityEventsEnabled)return null; + const now=clock(),seasons=await store.query("SELECT season_id,starts_at,ends_at FROM jarvis_progression_seasons WHERE state='active' AND starts_at<=? AND ends_at>?"+(lock?' FOR UPDATE':''),[now,now]);if(seasons.length!==1)throw Error('Current Personal season required'); + const links=await store.query('SELECT minecraft_uuid FROM site_game_links WHERE user_id=?'+(lock?' FOR UPDATE':''),[actor.id]);if(links.length!==1)throw Error('Current activity identity required'); + const season=seasons[0];return {...await verifiedPersonalActivities(store,keys,{accountId:actor.id,minecraftUuid:links[0].minecraft_uuid.toLowerCase(),seasonId:season.season_id,startsAt:Number(season.starts_at),endsAt:Number(season.ends_at),now,lock}),season}; + } + const engine=createQuestProgression(central,keys,{clock,authorizePlayer,resolvePlayer, authorizeObservation:async actor=>actor===observer, + authorizeClaim:async(actor,d,tx,{eligibility})=>{ + if(!PERSONAL_ACTIVITY_METRICS.includes(d.metric)||eligibility.reason==='xp-threshold')return true; + const proof=await activityEvidence(actor,tx,{lock:true});return !!proof&&(proof.totals.get(d.metric)||0)>=d.target; + }, // 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 quests=Object.freeze({...engine,async list(actor){ + const view=await engine.list(actor);if(!central.personalActivityEventsEnabled||view.state!=='active')return view; + let proof=null;try{proof=await activityEvidence(actor);}catch{/* Missing current identity/evidence never supplies objective progress. */} + const bypass=view.season.levelCap!==null&&view.profile.effectiveXP>=xpAtLevel(view.season.levelCap,view.season.curveBase); + return {...view,quests:view.quests.map(q=>{if(!PERSONAL_ACTIVITY_METRICS.includes(q.metric)||q.state==='claimed'||bypass&&!q.optional)return q;const verified=(proof?.totals.get(q.metric)||0)>=q.target;return {...q,canClaim:q.canClaim&&verified,...(q.state==='completed'&&!verified?{state:q.keyId?'active':'not-started'}:{})};})}; + }}); 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'); @@ -72,6 +91,12 @@ export function createProgressionRuntime(central,bank,keys,{clock=Date.now,resol if(rows.length>500)throw Error('The conquest registry requires a larger reviewed window'); for(const row of rows){const receipt=JSON.parse(row.manifest_json).receipt;await quests.recordAcquisition(observer,{accountId:actor.id,kind:'clan',entityId:receipt.clanId,origin:'conquest',sourceKeyId:row.key_id});} }); + if(central.personalActivityEventsEnabled)await source('personal-activity-keys',PERSONAL_ACTIVITY_METRICS,async()=>{ + const proof=await activityEvidence(actor);if(!proof)return {pendingMetrics:PERSONAL_ACTIVITY_METRICS}; + const digest=createHash('sha256').update(JSON.stringify(proof.proofIds)).digest('hex'); + for(const [metric,value]of proof.totals)await quests.observe(observer,{accountId:actor.id,seasonId:proof.season.season_id,metric,value,eventId:'personal-activity:'+actor.id+':'+metric+':'+digest.slice(0,32),source:'verified-activity-key'}); + return {pendingMetrics:PERSONAL_ACTIVITY_METRICS.filter(metric=>!proof.totals.has(metric))}; + }); return {state:'verified',sources}; } async function recordPoliticalVisit(actor){ diff --git a/website/node/quest-activity-api.mjs b/website/node/quest-activity-api.mjs new file mode 100644 index 00000000..e4c22af0 --- /dev/null +++ b/website/node/quest-activity-api.mjs @@ -0,0 +1,17 @@ +import {gameAuthorized} from './game-link.mjs'; +import {createQuestActivityEvents} from './quest-activity-events.mjs'; +export function createQuestActivityAPI(db,keys,settings,{clock=Date.now,namespace}={}){ + if(!['pol','personal'].includes(namespace))throw TypeError('Fixed activity namespace required'); + const producer={},events=keys?createQuestActivityEvents(db,keys,{namespace,clock,authorizeProducer:async actor=>actor===producer}):null; + const reply=(value,status=200)=>Response.json(value,{status,headers:{'Cache-Control':'private, no-store','X-Content-Type-Options':'nosniff'}}); + return async request=>{ + if(!gameAuthorized(request,settings))return reply({message:'Unauthorized'},401); + const url=new URL(request.url);if(url.pathname!=='/internal/progression/'+namespace+'/event'||request.method!=='POST')return reply({message:'Activity route not found.'},404); + if(url.search)return reply({message:'Activity identity overrides are not accepted.'},400); + if(!events)return reply({message:'Activity keys are unavailable.'},503); + 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:'Activity evidence required.'},400);let size=0;const chunks=[]; + try{while(true){const {done,value}=await reader.read();if(done)break;size+=value.length;if(size>4096){await reader.cancel();return reply({message:'Activity event exceeds its bound.'},413);}chunks.push(value);}return reply(await events.record(producer,JSON.parse(Buffer.concat(chunks).toString('utf8'))));} + catch{return reply({message:'The activity receipt could not be verified. No objective was credited.'},409);}finally{reader.releaseLock();} + }; +} diff --git a/website/node/quest-activity-events.mjs b/website/node/quest-activity-events.mjs new file mode 100644 index 00000000..74a9dba6 --- /dev/null +++ b/website/node/quest-activity-events.mjs @@ -0,0 +1,59 @@ +import {QUEST_DEFINITIONS} from './progression-definitions.mjs'; +import {POL_REPEATABLES} from './pol-repeatable-quests.mjs'; +import {createHash} from 'node:crypto'; +import {STAFF_OFFICE_ACCOUNT_ID} from './organisation-keys.mjs'; +import {createSystemCharacters} from './system-characters.mjs'; +import {POL_QUEST_DEFINITIONS} from '../control-panel/public/cp-v2/cp-v2-pol-quest-catalogue.mjs'; +const activityDefinition=metric=>POL_QUEST_DEFINITIONS.find(d=>d.metric===metric)||POL_REPEATABLES.find(d=>['SPICE','CARGO'].includes(d.key)&&d.metric===metric); +const uuid=v=>typeof v==='string'&&/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(v); +const hash=v=>createHash('sha256').update(JSON.stringify(v)).digest('hex'); +const first=async(db,sql,args=[])=>(await db.query(sql,args))[0]||null; +const POL_ACTIVITY_SCHEMA='CREATE TABLE IF NOT EXISTS jarvis_pol_activity_events(key_id CHAR(36) PRIMARY KEY,event_id CHAR(36) NOT NULL UNIQUE,account_id CHAR(36) NOT NULL,minecraft_uuid CHAR(36) NOT NULL,season_id VARCHAR(8) NOT NULL,metric VARCHAR(64) NOT NULL,source_reference VARCHAR(96) NOT NULL,quantity BIGINT NOT NULL,issuer_key_id CHAR(36) NOT NULL,payload_json TEXT NOT NULL,fingerprint CHAR(64) NOT NULL,occurred_at BIGINT NOT NULL,created_at BIGINT NOT NULL,UNIQUE KEY pol_activity_evidence(account_id,season_id,metric,source_reference),INDEX pol_activity_account(account_id,season_id,metric)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4'; +export const PERSONAL_ACTIVITY_METRICS=Object.freeze(['guild-travel','citizen-introduction','bank-deposit','shop-purchase','spice-harvest','arrakduin-visit','arrakduin-active-minutes','sietch-discovery','oasis-discovery','accessible-planets','advanced-survival','jobs-completed','employment','recognition','public-event-equivalent','equipment-use','mark-upgrade','rarity-enhancement','equipment-mark','eligible-kit-sales']); +function namespaceData(namespace){if(!['pol','personal'].includes(namespace))throw TypeError('Fixed quest activity namespace required');return {table:namespace==='pol'?'jarvis_pol_activity_events':'jarvis_personal_activity_events',season:namespace==='pol'?'jarvis_pol_progression_seasons':'jarvis_progression_seasons',prefix:namespace==='pol'?'POL_ACTIVITY_':'PERSONAL_ACTIVITY_'};} +function activityStore(db,namespace){const n=namespaceData(namespace),query=(sql,args=[])=>db.query(sql.replaceAll('jarvis_pol_activity_events',n.table).replaceAll('jarvis_pol_progression_seasons',n.season),args);return {query,first:async(sql,args=[])=>(await query(sql,args))[0]||null};} +export function questActivitySchema(namespace){const n=namespaceData(namespace);return POL_ACTIVITY_SCHEMA.replace('jarvis_pol_activity_events',n.table).replace('issuer_key_id CHAR(36) NOT NULL',namespace==='personal'?'issuer_key_id CHAR(36) NULL':'issuer_key_id CHAR(36) NOT NULL');} +export async function initializeQuestActivityEvents(db,namespace){await db.query(questActivitySchema(namespace));} +const definitionFor=(metric,namespace)=>namespace==='pol'?activityDefinition(metric):PERSONAL_ACTIVITY_METRICS.includes(metric)?QUEST_DEFINITIONS.find(d=>d.metric===metric):null; +export async function currentActivityPlayer(db,accountId,minecraftUuid,{lock=false}={}){ + const rows=await db.query("SELECT a.id FROM site_accounts a JOIN site_game_links l ON l.user_id=a.id WHERE l.minecraft_uuid=? AND a.password_hash NOT LIKE '!%' AND a.role NOT IN ('system_account','official_account','memorial') AND NOT EXISTS(SELECT 1 FROM site_memorials m WHERE m.user_id=a.id)"+(lock?' FOR UPDATE':''),[minecraftUuid]); + return rows.length===1&&rows[0].id===accountId; +} +async function issuer(store,keys,name,{lock=false}={}){ + const identity=await createSystemCharacters(store,keys,{authorizeOperator:async()=>false}).inspect(name); + if(!identity?.capabilities.includes('quest.issue'))throw Error('Current scoped quest giver required'); + if(lock){const key=await first(store,'SELECT id,revoked_at FROM organisation_keys WHERE id=? FOR UPDATE',[identity.keyId]);if(!key||key.revoked_at!==null)throw Error('Current scoped quest giver required');}return identity; +} +export function createQuestActivityEvents(db,keys,{authorizeProducer,clock=Date.now,namespace}={}){ + if(typeof authorizeProducer!=='function')throw TypeError('Trusted activity producer required'); + const n=namespaceData(namespace);db=activityStore(db,namespace); + return Object.freeze({async record(actor,input){ + const fields=['eventId','accountId','minecraftUuid','seasonId','metric','quantity','occurredAt','reference']; + if(!input||typeof input!=='object'||Array.isArray(input)||Object.keys(input).length!==fields.length||fields.some(k=>!Object.hasOwn(input,k))||!uuid(input.eventId)||!uuid(input.accountId)||!uuid(input.minecraftUuid)||input.seasonId!=='S01'||!Number.isSafeInteger(input.quantity)||input.quantity<1||input.quantity>1000000||!Number.isSafeInteger(input.occurredAt)||input.occurredAt>clock()+30000||typeof input.reference!=='string'||input.reference.length<1||input.reference.length>96||/[\x00-\x1f]/.test(input.reference))throw TypeError('Invalid verified activity fields'); + const definition=definitionFor(input.metric,namespace);if(!definition)throw TypeError('Registered quest objective required'); + const payload=Object.fromEntries(fields.map(k=>[k,['eventId','accountId','minecraftUuid'].includes(k)?input[k].toLowerCase():input[k]])),fingerprint=hash(payload); + if(await authorizeProducer(actor,payload,db)!==true)throw Error('Trusted activity producer required'); + const grant=await keys.issue({accountId:STAFF_OFFICE_ACCOUNT_ID,keyType:'quest-milestone',scopeId:payload.seasonId+':'+n.prefix+payload.eventId,authorize:async(rawTx,{keyId})=>{const tx=activityStore(rawTx,namespace); + if(await authorizeProducer(actor,payload,tx)!==true||!await currentActivityPlayer(tx,payload.accountId,payload.minecraftUuid))throw Error('Current activity identity required'); + const season=await tx.first("SELECT starts_at,ends_at FROM jarvis_pol_progression_seasons WHERE season_id=? AND state='active' AND starts_at<=? AND ends_at>? FOR UPDATE",[payload.seasonId,clock(),clock()]); + if(!season||payload.occurredAt=Number(season.ends_at))throw Error('Current activity season required'); + const current=namespace==='pol'?await issuer(tx,keys,definition.issuer):{keyId:null};if(current.keyId){const identityKey=await tx.first('SELECT id,revoked_at FROM organisation_keys WHERE id=? FOR UPDATE',[current.keyId]);if(!identityKey||identityKey.revoked_at!==null)throw Error('Current scoped quest giver required');} + const prior=await tx.first('SELECT key_id,fingerprint FROM jarvis_pol_activity_events WHERE event_id=? FOR UPDATE',[payload.eventId]); + if(prior){if(prior.fingerprint!==fingerprint)throw Error('Activity event reference conflict');return;} + await tx.query('INSERT INTO jarvis_pol_activity_events(key_id,event_id,account_id,minecraft_uuid,season_id,metric,source_reference,quantity,issuer_key_id,payload_json,fingerprint,occurred_at,created_at) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)',[keyId,payload.eventId,payload.accountId,payload.minecraftUuid,payload.seasonId,payload.metric,payload.reference,payload.quantity,current.keyId,JSON.stringify(payload),fingerprint,payload.occurredAt,clock()]); + }}); + const saved=await first(db,'SELECT fingerprint FROM jarvis_pol_activity_events WHERE key_id=?',[grant.id]);if(saved?.fingerprint!==fingerprint)throw Error('Activity event reference conflict');return {keyId:grant.id,created:grant.created}; + }}); +} +export async function verifiedQuestActivities(db,keys,{namespace,accountId,minecraftUuid,seasonId,startsAt,endsAt,now=Date.now(),lock=false}){ + const n=namespaceData(namespace);db=activityStore(db,namespace); + if(!await currentActivityPlayer(db,accountId,minecraftUuid,{lock}))throw Error('Current activity identity required'); + const rows=await db.query("SELECT e.*,k.key_type,k.account_id key_owner,k.scope_id,k.revoked_at FROM jarvis_pol_activity_events e JOIN organisation_keys k ON k.id=e.key_id WHERE e.account_id=? AND e.season_id=? ORDER BY e.occurred_at,e.key_id"+(lock?' FOR UPDATE':''),[accountId,seasonId]),totals=new Map(),seen=new Set(),proofIds=[]; + for(const r of rows){ + const p=JSON.parse(r.payload_json),d=definitionFor(r.metric,namespace); + if(!d||!uuid(p.eventId)||!Number.isSafeInteger(p.quantity)||p.quantity<1||p.quantity>1000000||p.reference!==r.source_reference||r.key_type!=='quest-milestone'||r.key_owner!==STAFF_OFFICE_ACCOUNT_ID||r.revoked_at!==null||hash(p)!==r.fingerprint||r.scope_id!==seasonId+':'+n.prefix+p.eventId||p.accountId!==accountId||p.minecraftUuid!==minecraftUuid||p.seasonId!==seasonId||p.metric!==r.metric||p.quantity!==Number(r.quantity)||p.occurredAt!==Number(r.occurred_at)||p.occurredAt=endsAt||p.occurredAt>now+30000||seen.has(p.eventId))continue; + const current=namespace==='pol'?await issuer(db,keys,d.issuer,{lock}):{keyId:null};if(current.keyId!==r.issuer_key_id)continue; + seen.add(p.eventId);proofIds.push(r.key_id);const total=(totals.get(r.metric)||0)+p.quantity;if(!Number.isSafeInteger(total))throw Error('Activity quantity requires review');totals.set(r.metric,total); + } + return {totals,proofIds}; +} diff --git a/website/tests/personal-activity-events.test.mjs b/website/tests/personal-activity-events.test.mjs new file mode 100644 index 00000000..fea9ce1b --- /dev/null +++ b/website/tests/personal-activity-events.test.mjs @@ -0,0 +1,25 @@ +import test from 'node:test';import assert from 'node:assert/strict';import {randomUUID} from 'node:crypto'; +import {systemCharacterFixture} from './system-character-fixture.mjs'; +import {initializeProgression} from '../node/progression-schema.mjs'; +import {ensureProgressionPolicy} from '../node/progression-policy.mjs'; +import {initializePersonalActivityEvents,createPersonalActivityEvents,verifiedPersonalActivities} from '../node/personal-activity-events.mjs'; +import {initializePOLProgression,ensurePOLProgressionPolicy} from '../node/progression-pol.mjs'; +import {initializePOLActivityEvents,createPOLActivityEvents} from '../node/pol-activity-events.mjs'; +import {createProgressionRuntime} from '../node/progression-runtime.mjs'; +import {createPersonalActivityAPI} from '../node/personal-activity-api.mjs'; +async function setup(){const f=await systemCharacterFixture(),clock=()=>2000;await initializeProgression(f.db);await ensureProgressionPolicy(f.db,f.keys,{clock});await initializePersonalActivityEvents(f.db);f.db.personalActivityEventsEnabled=true;const minecraftUuid=randomUUID();await f.db.query('UPDATE site_game_links SET minecraft_uuid=? WHERE user_id=?',[minecraftUuid,f.people.Member.id]);const producer={},events=createPersonalActivityEvents(f.db,f.keys,{clock,authorizeProducer:async actor=>actor===producer}),runtime=createProgressionRuntime(f.db,null,f.keys,{clock}),input={eventId:randomUUID(),accountId:f.people.Member.id,minecraftUuid,seasonId:'S01',metric:'spice-harvest',quantity:100,occurredAt:2000,reference:randomUUID()};return {...f,clock,producer,events,runtime,input};} +test('Personal activity keys use the existing quest claim once and cannot borrow Reputation evidence or override native readers',async()=>{const f=await setup();try{ + await f.characters.provision(f.people.Owner,'stilgar');await initializePOLProgression(f.db);await ensurePOLProgressionPolicy(f.db,f.keys,{clock:f.clock});await initializePOLActivityEvents(f.db); + const pol=createPOLActivityEvents(f.db,f.keys,{clock:f.clock,authorizeProducer:async actor=>actor===f.producer});await pol.record(f.producer,{...f.input,metric:'pol-repeat-spice'}); + await f.runtime.quests.start(f.people.Member,{definitionId:'S1-C-01'});await f.runtime.collect(f.people.Member);assert.equal((await f.runtime.quests.list(f.people.Member)).quests.find(q=>q.id==='S1-C-01').canClaim,false); + await assert.rejects(f.events.record(f.producer,{...f.input,metric:'earned-minor'}));await assert.rejects(f.events.record(f.people.Member,f.input)); + const receipt=await f.events.record(f.producer,f.input);assert.equal((await f.events.record(f.producer,f.input)).created,false);await f.runtime.collect(f.people.Member); + const claim={definitionId:'S1-C-01',requestId:randomUUID(),revision:1};await f.runtime.quests.claim(f.people.Member,claim);assert.equal((await f.runtime.quests.claim(f.people.Member,claim)).replayed,true); + assert.equal((await f.db.first('SELECT COUNT(*) n FROM jarvis_quest_claims')).n,1);assert.equal((await f.db.first('SELECT COUNT(*) n FROM jarvis_pol_quest_claims')).n,0);assert.equal((await f.db.first('SELECT issuer_key_id FROM jarvis_personal_activity_events WHERE key_id=?',[receipt.keyId])).issuer_key_id,null); +}finally{f.db.close();}}); +test('revoked, altered or relinked Personal proof cannot be claimed from a previously cached counter',async()=>{for(const change of ['revoked','altered','relinked']){const f=await setup();try{const receipt=await f.events.record(f.producer,f.input);await f.runtime.quests.start(f.people.Member,{definitionId:'S1-C-01'});await f.runtime.collect(f.people.Member); + if(change==='revoked')await f.db.query('UPDATE organisation_keys SET revoked_at=1 WHERE id=?',[receipt.keyId]);if(change==='altered')await f.db.query('UPDATE jarvis_personal_activity_events SET quantity=101 WHERE key_id=?',[receipt.keyId]);if(change==='relinked')await f.db.query('UPDATE site_game_links SET minecraft_uuid=? WHERE user_id=?',[randomUUID(),f.people.Member.id]); + assert.equal((await f.runtime.quests.list(f.people.Member)).quests.find(q=>q.id==='S1-C-01').canClaim,false);await assert.rejects(f.runtime.quests.claim(f.people.Member,{definitionId:'S1-C-01',requestId:randomUUID(),revision:1}));assert.equal((await f.db.first('SELECT COUNT(*) n FROM jarvis_quest_claims')).n,0); +}finally{f.db.close();}}}); +test('mandatory XP-threshold settlement records completion without fabricating game proof',async()=>{const f=await setup();try{await f.runtime.quests.start(f.people.Member,{definitionId:'S1-C-01'});await f.db.query('UPDATE jarvis_progression_accounts SET total_xp=60375,effective_xp=60375,level_no=70 WHERE account_id=?',[f.people.Member.id]);await f.runtime.quests.claim(f.people.Member,{definitionId:'S1-C-01',requestId:randomUUID(),revision:1});assert.equal((await f.db.first('SELECT COUNT(*) n FROM jarvis_personal_activity_events')).n,0);assert.equal((await f.db.first('SELECT COUNT(*) n FROM jarvis_progression_facts')).n,0);assert.equal((await f.db.first('SELECT COUNT(*) n FROM jarvis_quest_claims')).n,1);}finally{f.db.close();}}); +test('Personal transport binds its namespace on the server and rejects identity and channel overrides',async()=>{const f=await setup();try{const secret='s'.repeat(32),api=createPersonalActivityAPI(f.db,f.keys,{GAME_LINK_SECRET:secret},{clock:f.clock}),request=(input,path='personal',auth='Bearer '+secret)=>new Request('https://cp.dunerealms.com/internal/progression/'+path+'/event',{method:'POST',headers:{authorization:auth,'content-type':'application/json'},body:JSON.stringify(input)});assert.equal((await api(request(f.input,'pol'))).status,404);assert.equal((await api(request({...f.input,namespace:'pol'}))).status,409);assert.equal((await api(request(f.input,'personal','browser'))).status,401);assert.equal((await api(request(f.input))).status,200);}finally{f.db.close();}});