forked from unimatrix/web
DUNE-014: deliver isolated Starfall stronghold integration patch
This commit is contained in:
parent
1a6fb6a859
commit
9543817442
4 changed files with 762 additions and 1 deletions
|
|
@ -123,4 +123,13 @@ No task groups have been created yet. Allocate G-001 upon the first actual group
|
|||
- Completed read-only source review at main `2577efefb56aae14da63df725cdf180419563bd1`; announced v0.120.1 source had not yet been pushed when fetched. Report: `docs/STARFALL-EFFICIENCY-REVIEW.md`.
|
||||
- Measured tracked/collector-selected asset bytes and selected gzip sizes; inspected runtime start, caching, polling, full directory reads, auth memoisation and access-audit writes. Distinguished source metrics from live performance hypotheses.
|
||||
- Proposed ordered improvements with measurable goals, privacy/audit/gameplay risks and live/DB verification plan. No Starfall edits, deployment, reset, runtime tests or production loadtest performed.
|
||||
- Not a Dune product patchnote entry. Review needs comparison with v0.120.1 when colleague publishes that source.
|
||||
- Not a Dune product patchnote entry. Review needs comparison with v0.120.1 when colleague publishes that source.
|
||||
## DUNE-014 — P2 — isolated Starfall integration patch (SF-049 / G011)
|
||||
|
||||
- Completed review contribution in `proposals/starfall-stronghold-integration/`: mail-format patch, REVIEW.md and integrity manifest. Base `a33136f55ff4ce06ad93f9768578b08c42ebce49`; isolated detached commit `2a8efcb5818e3381bc58b6acc3b03298d6a08461`.
|
||||
- Authoritative stronghold API, stable identity, trusted permissions, revision CAS and unique indexes, fenced dependent writes, legacy dispute freeze, asset inventory, directory bypass guards and central setFortress wiring.
|
||||
- 234 tests pass (223 baseline plus 11 integration cases); production build succeeds; diagnostic audit covers 100 pages with zero findings. Patch applies cleanly to the exact base index. No live/browser/D1 deployment checks claimed.
|
||||
- No Starfall branch push, deployment, reset, membership move or asset deletion. Only this patch artifact is delivered through mcdune main. Generated runtime output must be rebuilt by integrator.
|
||||
- Explicit remaining scope: G005 special 1:1 slots; transfers containing assets require an approved asset/cost migration; full reward/ticker authority and abandonment lifecycle remain separate integration work. Colleague owns review, merge with newer source and publication.
|
||||
- Colleague reported sidebar-only Starfall v0.120.2 work as orthogonal and explicitly retained a33136f as this patch base.
|
||||
- Assistance artifact only, not a Dune product patchnote entry.
|
||||
46
proposals/starfall-stronghold-integration/REVIEW.md
Normal file
46
proposals/starfall-stronghold-integration/REVIEW.md
Normal file
|
|
@ -0,0 +1,46 @@
|
|||
# SF-049 / G011 — isolated integration patch (DUNE-014)
|
||||
|
||||
Base: `a33136f55ff4ce06ad93f9768578b08c42ebce49`. Prepared in a detached isolated checkout. No Starfall branch pushed, no deployment and no reset. Review before cherry-picking/applying; coordinate migration number 0032 with concurrent work.
|
||||
|
||||
## Included
|
||||
|
||||
- `worker/stronghold-policy.js`: framework-free domain policy, adapted from Dune contribution da7d21e to the current concatenated Worker format.
|
||||
- `worker/strongholds.js` and additive migration `0032_stronghold_claims.sql`: round-generation state, unique live galaxy/alliance claim indexes, operation replay records and audit. The directory revision is the shared compare-and-swap clock. Every dependent write is fenced by a server operation token in the same atomic DB batch. Snapshot predicates also detect alliance permission changes from legacy writers that fail to bump revision.
|
||||
- `/api/strongholds` GET returns claim status/asset counts and server-derived management capabilities. POST requires same origin, generation, revision and unique operationId. Context comes from the signed-in account, owned planet, stored alliance roster and fortress permission; client permission flags are ignored.
|
||||
- Actions: `claim`, `move` (empty claim only, atomic release+new claim), `release`, `offerTransfer`, `transfer`, `dispute`, `resolve`. Admin override requires `staffOverride:true` plus a nonempty reason. Conflict adjudication requires that explicit staff authority.
|
||||
- Stable alliance IDs use the registry first, then existing stored ID; missing legacy identity derives deterministically and is persisted with the first accepted operation. Legacy overlapping claims become disputed, preserving assets. Inactive/disputed reservations continue to block new claims.
|
||||
- Transfer is two-step: source leadership records an offer; target leadership accepts the matching current-revision offer. Source leadership authority is rechecked on acceptance. An admin can explicitly adjudicate an empty transfer. Existing-assets transfer is deliberately blocked rather than guessing ownership/cost migration.
|
||||
- Asset inventory includes accepted alliance active structures, construction queue and global structure directory rows. Release/conflict resolution refuses to discard competing assets. Index uniqueness failure rolls the whole batch back, including state, registry, alliance and audit writes.
|
||||
- Directory GET projects canonical claim status and clears the effective fortress location for disputed/released claims. Directory POST cannot change the claim or stored alliance identity. Existing authorised staff structure editing remains possible only under an active server claim in the owning galaxy, with aligned global slots and alliance reservations. Reserved/disputed/foreign claims cannot be bypassed via this old route. Non-claim fields continue through the existing flow.
|
||||
- `setFortress` uses the API for central players, shows reserved/disputed errors and never changes local ownership optimistically. Empty relocation is confirmed and remains subject to anarchy; member planets and alliance membership are never moved. Browser local resident benefits require an active projected claim. Existing browser-only practice mode keeps its legacy behaviour.
|
||||
- Build wiring and both hand-assembled Worker test harnesses updated. Generated Worker/runtime outputs must be rebuilt; they are intentionally not included as authored patch changes.
|
||||
|
||||
## API example
|
||||
|
||||
Read `/api/strongholds` first. Submit POST as the authenticated session, with same-origin credentials:
|
||||
|
||||
```json
|
||||
{"action":"claim","allianceId":"server-returned-id","galaxy":"07:04","generation":23,"revision":123,"operationId":"unique-client-operation-id"}
|
||||
```
|
||||
|
||||
For release/move/offerTransfer/transfer use claimId; move adds galaxy; transfer actions add targetAllianceId. For dispute supply claimIds and reason; for resolve supply winnerClaimId and winnerStatus (`active` or `inactive`), with explicit admin override and reason. Preserve the exact request body for an identical retry. Reusing an operation ID with a changed body/account is rejected. Offers expire conservatively when the shared directory revision changes.
|
||||
|
||||
## Validation
|
||||
|
||||
- Full suite: `node --test tests/*.test.cjs` — 234 passing (223 baseline + 11 integration tests).
|
||||
- Tests cover trusted rights/origin, replay and forged payloads, exclusive claims, no resource grant or membership changes, stale CAS with no dependent writes, two-party transfer, preserved disputed assets, direct directory bypass, valid structure editing, reset-generation isolation, optimistic concurrent claims, empty relocation, permission revocation without revision bump, and rollback on forced unique-index failure.
|
||||
- Production build: `node scripts/build-worker.cjs`; link/diagnostic audit: 100 pages, zero findings. No live D1/browser/deployment tests claimed. SQLite test adapter serialises atomic batches to model the D1 batch contract; verify on the actual preview backend before publishing.
|
||||
- Rebuild is required after applying: runtime bundlers read authored dist JS. No generated artifacts should be served from the old release accidentally. Preserve public hosting settings and existing bindings/migration history.
|
||||
|
||||
## Explicit limits and reviewer decisions
|
||||
|
||||
1. **G005 / special 1:1 slot expansion is outside this patch.** All existing ordinary 1–10 player / 11–15 structure validation remains. Nothing reassigns, deletes or occupies ghost/tribute slots. Integrate G005 as a separate reviewed occupancy change.
|
||||
2. Existing-asset transfer is blocked with a clear conflict response. A reviewed migration of individual structures, queued costs, treasury ownership and history must precede enabling it. This patch does not silently transfer or delete assets to make a claim fit.
|
||||
3. There is no new structure economy or global server-authoritative reward simulation. Existing staff-edit privileges and browser simulation remain, now claim-gated. Claim actions themselves grant no items/resources. Cursor updates are monotonic and bounded by stored public ticks; full anti-cheat reward ledger, ticker trust and general resource validation remain separate work. Test actual daily reward progression and local-save reconciliation in browser before publication.
|
||||
4. Empty move penalty uses existing seed tick-hour configuration and reported alliance member ticks. Confirm whether a centrally managed round configuration should replace that legacy source before rollout.
|
||||
5. No automatic expiry, conquest, last-resident eviction, alliance reset or active-structure relocation. Inactive legacy records preserve reservations. Lifecycle transitions after later structure destruction/abandonment should be explicitly integrated with a reviewed policy, not inferred from this endpoint.
|
||||
6. Legacy conflicts are frozen; staff chooses a winner. A loser with assets prevents adjudication until an explicit remediation plan is executed. Corrupt identities/malformed legacy coordinates require a staff repair instead of automatic destructive normalisation.
|
||||
7. Request/response replay is per account and exact payload; no client request changes can resurrect ownership. Old-generation records are retained as history and cannot mutate a new round. Retention/archival of operation/audit rows should follow existing staff policy.
|
||||
8. `shLoad` currently inventories the small shared directory; this is correctness-first and not an efficiency implementation. Consider indexing/snapshot optimisation after SF-052 measurements, keeping the revision/permission guards intact.
|
||||
|
||||
The colleague owns review, conflict resolution with newer Starfall edits, final UI/lifecycle completion, integration and publication.
|
||||
|
|
@ -0,0 +1,694 @@
|
|||
From 2a8efcb5818e3381bc58b6acc3b03298d6a08461 Mon Sep 17 00:00:00 2001
|
||||
From: unimatrixgit <95320811+unimatrixgit@users.noreply.github.com>
|
||||
Date: Wed, 14 Oct 2026 16:44:59 +0200
|
||||
Subject: [PATCH] SF-049: integrate authoritative stronghold claims in isolated
|
||||
review patch
|
||||
|
||||
---
|
||||
STRONGHOLD-INTEGRATION-REVIEW.md | 46 +++++++
|
||||
dist/game.js | 4 +-
|
||||
dist/planets.js | 21 +++
|
||||
drizzle/0032_stronghold_claims.sql | 8 ++
|
||||
scripts/build-worker.cjs | 2 +-
|
||||
tests/miday.test.cjs | 2 +-
|
||||
tests/planets.test.cjs | 127 +++++++++++++++++-
|
||||
worker/index.js | 1 +
|
||||
worker/planets.js | 5 +-
|
||||
worker/stronghold-policy.js | 126 ++++++++++++++++++
|
||||
worker/strongholds.js | 207 +++++++++++++++++++++++++++++
|
||||
11 files changed, 542 insertions(+), 7 deletions(-)
|
||||
create mode 100644 STRONGHOLD-INTEGRATION-REVIEW.md
|
||||
create mode 100644 drizzle/0032_stronghold_claims.sql
|
||||
create mode 100644 worker/stronghold-policy.js
|
||||
create mode 100644 worker/strongholds.js
|
||||
|
||||
diff --git a/STRONGHOLD-INTEGRATION-REVIEW.md b/STRONGHOLD-INTEGRATION-REVIEW.md
|
||||
new file mode 100644
|
||||
index 0000000..9e52d39
|
||||
--- /dev/null
|
||||
+++ b/STRONGHOLD-INTEGRATION-REVIEW.md
|
||||
@@ -0,0 +1,46 @@
|
||||
+# SF-049 / G011 — isolated integration patch (DUNE-014)
|
||||
+
|
||||
+Base: `a33136f55ff4ce06ad93f9768578b08c42ebce49`. Prepared in a detached isolated checkout. No Starfall branch pushed, no deployment and no reset. Review before cherry-picking/applying; coordinate migration number 0032 with concurrent work.
|
||||
+
|
||||
+## Included
|
||||
+
|
||||
+- `worker/stronghold-policy.js`: framework-free domain policy, adapted from Dune contribution da7d21e to the current concatenated Worker format.
|
||||
+- `worker/strongholds.js` and additive migration `0032_stronghold_claims.sql`: round-generation state, unique live galaxy/alliance claim indexes, operation replay records and audit. The directory revision is the shared compare-and-swap clock. Every dependent write is fenced by a server operation token in the same atomic DB batch. Snapshot predicates also detect alliance permission changes from legacy writers that fail to bump revision.
|
||||
+- `/api/strongholds` GET returns claim status/asset counts and server-derived management capabilities. POST requires same origin, generation, revision and unique operationId. Context comes from the signed-in account, owned planet, stored alliance roster and fortress permission; client permission flags are ignored.
|
||||
+- Actions: `claim`, `move` (empty claim only, atomic release+new claim), `release`, `offerTransfer`, `transfer`, `dispute`, `resolve`. Admin override requires `staffOverride:true` plus a nonempty reason. Conflict adjudication requires that explicit staff authority.
|
||||
+- Stable alliance IDs use the registry first, then existing stored ID; missing legacy identity derives deterministically and is persisted with the first accepted operation. Legacy overlapping claims become disputed, preserving assets. Inactive/disputed reservations continue to block new claims.
|
||||
+- Transfer is two-step: source leadership records an offer; target leadership accepts the matching current-revision offer. Source leadership authority is rechecked on acceptance. An admin can explicitly adjudicate an empty transfer. Existing-assets transfer is deliberately blocked rather than guessing ownership/cost migration.
|
||||
+- Asset inventory includes accepted alliance active structures, construction queue and global structure directory rows. Release/conflict resolution refuses to discard competing assets. Index uniqueness failure rolls the whole batch back, including state, registry, alliance and audit writes.
|
||||
+- Directory GET projects canonical claim status and clears the effective fortress location for disputed/released claims. Directory POST cannot change the claim or stored alliance identity. Existing authorised staff structure editing remains possible only under an active server claim in the owning galaxy, with aligned global slots and alliance reservations. Reserved/disputed/foreign claims cannot be bypassed via this old route. Non-claim fields continue through the existing flow.
|
||||
+- `setFortress` uses the API for central players, shows reserved/disputed errors and never changes local ownership optimistically. Empty relocation is confirmed and remains subject to anarchy; member planets and alliance membership are never moved. Browser local resident benefits require an active projected claim. Existing browser-only practice mode keeps its legacy behaviour.
|
||||
+- Build wiring and both hand-assembled Worker test harnesses updated. Generated Worker/runtime outputs must be rebuilt; they are intentionally not included as authored patch changes.
|
||||
+
|
||||
+## API example
|
||||
+
|
||||
+Read `/api/strongholds` first. Submit POST as the authenticated session, with same-origin credentials:
|
||||
+
|
||||
+```json
|
||||
+{"action":"claim","allianceId":"server-returned-id","galaxy":"07:04","generation":23,"revision":123,"operationId":"unique-client-operation-id"}
|
||||
+```
|
||||
+
|
||||
+For release/move/offerTransfer/transfer use claimId; move adds galaxy; transfer actions add targetAllianceId. For dispute supply claimIds and reason; for resolve supply winnerClaimId and winnerStatus (`active` or `inactive`), with explicit admin override and reason. Preserve the exact request body for an identical retry. Reusing an operation ID with a changed body/account is rejected. Offers expire conservatively when the shared directory revision changes.
|
||||
+
|
||||
+## Validation
|
||||
+
|
||||
+- Full suite: `node --test tests/*.test.cjs` — 234 passing (223 baseline + 11 integration tests).
|
||||
+- Tests cover trusted rights/origin, replay and forged payloads, exclusive claims, no resource grant or membership changes, stale CAS with no dependent writes, two-party transfer, preserved disputed assets, direct directory bypass, valid structure editing, reset-generation isolation, optimistic concurrent claims, empty relocation, permission revocation without revision bump, and rollback on forced unique-index failure.
|
||||
+- Production build: `node scripts/build-worker.cjs`; link/diagnostic audit: 100 pages, zero findings. No live D1/browser/deployment tests claimed. SQLite test adapter serialises atomic batches to model the D1 batch contract; verify on the actual preview backend before publishing.
|
||||
+- Rebuild is required after applying: runtime bundlers read authored dist JS. No generated artifacts should be served from the old release accidentally. Preserve public hosting settings and existing bindings/migration history.
|
||||
+
|
||||
+## Explicit limits and reviewer decisions
|
||||
+
|
||||
+1. **G005 / special 1:1 slot expansion is outside this patch.** All existing ordinary 1–10 player / 11–15 structure validation remains. Nothing reassigns, deletes or occupies ghost/tribute slots. Integrate G005 as a separate reviewed occupancy change.
|
||||
+2. Existing-asset transfer is blocked with a clear conflict response. A reviewed migration of individual structures, queued costs, treasury ownership and history must precede enabling it. This patch does not silently transfer or delete assets to make a claim fit.
|
||||
+3. There is no new structure economy or global server-authoritative reward simulation. Existing staff-edit privileges and browser simulation remain, now claim-gated. Claim actions themselves grant no items/resources. Cursor updates are monotonic and bounded by stored public ticks; full anti-cheat reward ledger, ticker trust and general resource validation remain separate work. Test actual daily reward progression and local-save reconciliation in browser before publication.
|
||||
+4. Empty move penalty uses existing seed tick-hour configuration and reported alliance member ticks. Confirm whether a centrally managed round configuration should replace that legacy source before rollout.
|
||||
+5. No automatic expiry, conquest, last-resident eviction, alliance reset or active-structure relocation. Inactive legacy records preserve reservations. Lifecycle transitions after later structure destruction/abandonment should be explicitly integrated with a reviewed policy, not inferred from this endpoint.
|
||||
+6. Legacy conflicts are frozen; staff chooses a winner. A loser with assets prevents adjudication until an explicit remediation plan is executed. Corrupt identities/malformed legacy coordinates require a staff repair instead of automatic destructive normalisation.
|
||||
+7. Request/response replay is per account and exact payload; no client request changes can resurrect ownership. Old-generation records are retained as history and cannot mutate a new round. Retention/archival of operation/audit rows should follow existing staff policy.
|
||||
+8. `shLoad` currently inventories the small shared directory; this is correctness-first and not an efficiency implementation. Consider indexing/snapshot optimisation after SF-052 measurements, keeping the revision/permission guards intact.
|
||||
+
|
||||
+The colleague owns review, conflict resolution with newer Starfall edits, final UI/lifecycle completion, integration and publication.
|
||||
diff --git a/dist/game.js b/dist/game.js
|
||||
index 0cb7df2..17fd892 100644
|
||||
--- a/dist/game.js
|
||||
+++ b/dist/game.js
|
||||
@@ -276,7 +276,7 @@ function updateShipPreview(id){const input=document.getElementById('qty-'+id),el
|
||||
function bcalcCopy(kind){const get=(side)=>Object.fromEntries(Object.keys(SHIPS).map(id=>[id,Number(document.querySelector(`[data-cship="${side}"][data-ship="${id}"]`)?.value||0)]));const a=get('a'),d=get('d');if(kind==='attacker')return Object.entries(a).filter(([,n])=>n).map(([id,n])=>`${SHIPS[id].name}: ${n}`).join('\\n')||'No ships';if(kind==='defender')return Object.entries(d).filter(([,n])=>n).map(([id,n])=>`${SHIPS[id].name}: ${n}`).join('\\n')||'No ships';if(kind==='report')return `ATTACKER\\n${Object.entries(a).map(([id,n])=>`${SHIPS[id].name}: ${n}`).join('\\n')}\\n\\nDEFENDER\\n${Object.entries(d).map(([id,n])=>`${SHIPS[id].name}: ${n}`).join('\\n')}`;return document.getElementById('calcResult').innerText;}
|
||||
function copyText(s){if(navigator.clipboard?.writeText)navigator.clipboard.writeText(s).then(()=>notify('Copied to clipboard.')).catch(()=>notify('Clipboard unavailable; select and copy the text.',true));else notify('Clipboard unavailable in this browser.',true);}
|
||||
function calculateBattle(){const a=Object.fromEntries(Object.keys(SHIPS).map(id=>[id,Number(document.querySelector(`[data-cship="a"][data-ship="${id}"]`)?.value||0)])),d=Object.fromEntries(Object.keys(SHIPS).map(id=>[id,Number(document.querySelector(`[data-cship="d"][data-ship="${id}"]`)?.value||0)]));if(![...Object.values(a),...Object.values(d)].every(n=>Number.isSafeInteger(n)&&n>=0&&n<=1000000000))return notify('Use whole ship counts from 0 to 1,000,000,000.',true);const population=Math.max(0,Math.floor(Number(document.getElementById('calcPopulation')?.value??1000))),x=resolveCombat(a,d,undefined,undefined,population,Math.max(0,Math.floor(Number(document.getElementById('calcBiodomes')?.value)||0)),Math.max(0,Math.min(999,Number(document.getElementById('calcBiodomeDamage')?.value)||0))),winner=totalShips(x.attacker)>totalShips(x.defender)?'ATTACKER ADVANTAGE':totalShips(x.defender)>totalShips(x.attacker)?'DEFENDER ADVANTAGE':'MUTUAL / NO CLEAR WINNER';window.bcalc=a?{a,d,population,biodomes:x.habitat.before,biodomeDamage:x.habitat.damageBefore}:null;window.bcalcResult=`<b>${winner}</b><br>Starting ships · attacker ${totalShips(a)} / defender ${totalShips(d)}<br>Ships lost · attacker ${x.aLost} / defender ${x.dLost}<br>Survivors · attacker ${totalShips(x.attacker)} / defender ${totalShips(x.defender)}<br><br>ATTACKER SURVIVORS: ${Object.entries(x.attacker).filter(([,n])=>n).map(([id,n])=>`${SHIPS[id].name} ${n}`).join(' · ')||'none'}<br>DEFENDER SURVIVORS: ${Object.entries(x.defender).filter(([,n])=>n).map(([id,n])=>`${SHIPS[id].name} ${n}`).join(' · ')||'none'}`;const report=recordSimulatedCalculatorReport(x,document.getElementById('calcTitle')?.value||'Calculator engagement');window.bcalcResult+='<h3>SIMULATED NEWS REPORT</h3>'+battleNewsHTML(report);renderAlliance();
}
|
||||
-function allianceAction(action,button){if(state.centralPlayerId&&['accept','decline'].includes(action)&&typeof centralRecruitmentDecision==='function')return centralRecruitmentDecision(action,button);const key=ALLIANCE_ACTION_PERMISSIONS[action];if(key&&!mayAlliance(key))return notify('Your rank cannot use this alliance action.',true);if(action==='exchange')return exchangeAllianceResources();const a=state.alliance;if(action==='setFortress'){if(!mayAlliance('fortress'))return notify('Your rank cannot set the stronghold.',true);const coords=(document.getElementById('fortressGalaxy')?.value||'').trim(),allowedGalaxies=allianceMemberGalaxies();if(!allowedGalaxies.includes(coords))return notify('Choose a galaxy that currently contains alliance members.',true);const normalizedCoords=coords;const old=a.fortress.strongholdGalaxy;if(old===normalizedCoords)return notify('The alliance stronghold is already in that galaxy.');a.fortress.strongholdGalaxy=normalizedCoords;if(!a.fortress.lastDistorterTick)a.fortress.lastDistorterTick=state.tick;if(state.tick>1){a.fortress.anarchyUntilTick=state.tick+allianceHoursToTicks(24)-1;a.fortress.anarchyEnded=false;allianceLogAction(`Stronghold moved from ${old||'unset'} to ${normalizedCoords}. Anarchy Mode: alliance member income reduced by 2% for 24 hours.`,'warn');notify('Stronghold moved. Anarchy Mode is active for 24 hours.',true);}else{allianceLogAction(`Alliance stronghold set to ${normalizedCoords} before the first tick.`,'good');notify('Alliance stronghold established.');}return update();}if(action==='buildStructure'){return queueAllianceStructure(button.dataset.structure,Number(document.getElementById('structureSlot-'+button.dataset.structure)?.value));}if(action==='toggleWar'){if(!mayAlliance('war'))return notify('Your rank cannot change war status.',true);const enemy=button.dataset.war;if(!enemy||enemy===a.name)return;return declareAllianceDiplomacy(enemy,a.wars.includes(enemy)?'peace':'war');}if(action==='message'){a.message=document.getElementById('allianceMessage').value;allianceLog('Commander message updated.');}if(action==='toggleapps')a.applicationsOpen=!a.applicationsOpen;if(action==='accept'&&a.applicants.length){if(a.members.length>=40)return notify('Alliance member limit reached.',true);const i=a.applicants.findIndex(x=>x.id===button.dataset.applicant),x=a.applicants.splice(i<0?0:i,1)[0];a.members.push({id:`member-${Date.now()}`,name:x.name,planet:x.planet,coords:x.coords,rank:'Recruit',online:false});const p=state.galaxy.find(q=>q.name===x.planet);if(p)p.alliance=a.name;allianceLog(`${x.planet} accepted as a Recruit into ${a.name}.`);}if(action==='decline'&&a.applicants.length){const i=a.applicants.findIndex(x=>x.id===button.dataset.applicant),x=a.applicants.splice(i<0?0:i,1)[0];allianceLog(`${x.planet} application declined.`);}if(action==='call'){const p=state.galaxy.find(x=>x.name===document.getElementById('callTarget').value),eta=Math.max(1,Math.min(24,Number(document.getElementById('callEta').value)||1)),c={id:Math.random().toString(36).slice(2),planet:p?.name||'Morrow Wake',coords:p?.coords||'07:04:02',eta,notes:document.getElementById('callNotes').value||'Hostile fleet sighted',attackerCount:'Unknown',age:0};a.calls.push(c);allianceLog(`Defence called for ${c.planet}, hostile ETA ${eta}.`);notify('Alliance defence call sent.');}if(action==='dismiss'){a.calls=a.calls.filter(c=>c.id!==button.dataset.call);allianceLog('A defence call was closed.');}if(action==='donate')return donateAllianceFund();if(action==='tax'){a.tax=Math.max(0,Math.min(5,Number(document.getElementById('allianceTax').value)||0));allianceLog(`Automatic alliance tax set to ${a.tax}%.`);}update();}
|
||||
+function allianceAction(action,button){if(state.centralPlayerId&&['accept','decline'].includes(action)&&typeof centralRecruitmentDecision==='function')return centralRecruitmentDecision(action,button);const key=ALLIANCE_ACTION_PERMISSIONS[action];if(key&&!mayAlliance(key))return notify('Your rank cannot use this alliance action.',true);if(action==='exchange')return exchangeAllianceResources();const a=state.alliance;if(action==='setFortress'&&state.centralPlayerId)return centralSetFortress();if(action==='setFortress'){if(!mayAlliance('fortress'))return notify('Your rank cannot set the stronghold.',true);const coords=(document.getElementById('fortressGalaxy')?.value||'').trim(),allowedGalaxies=allianceMemberGalaxies();if(!allowedGalaxies.includes(coords))return notify('Choose a galaxy that currently contains alliance members.',true);const normalizedCoords=coords;const old=a.fortress.strongholdGalaxy;if(old===normalizedCoords)return notify('The alliance stronghold is already in that galaxy.');a.fortress.strongholdGalaxy=normalizedCoords;if(!a.fortress.lastDistorterTick)a.fortress.lastDistorterTick=state.tick;if(state.tick>1){a.fortress.anarchyUntilTick=state.tick+allianceHoursToTicks(24)-1;a.fortress.anarchyEnded=false;allianceLogAction(`Stronghold moved from ${old||'unset'} to ${normalizedCoords}. Anarchy Mode: alliance member income reduced by 2% for 24 hours.`,'warn');notify('Stronghold moved. Anarchy Mode is active for 24 hours.',true);}else{allianceLogAction(`Alliance stronghold set to ${normalizedCoords} before the first tick.`,'good');notify('Alliance stronghold established.');}return update();}if(action==='buildStructure'){return queueAllianceStructure(button.dataset.structure,Number(document.getElementById('structureSlot-'+button.dataset.structure)?.value));}if(action==='toggleWar'){if(!mayAlliance('war'))return notify('Your rank cannot change war status.',true);const enemy=button.dataset.war;if(!enemy||enemy===a.name)return;return declareAllianceDiplomacy(enemy,a.wars.includes(enemy)?'peace':'war');}if(action==='message'){a.message=document.getElementById('allianceMessage').value;allianceLog('Commander message updated.');}if(action==='toggleapps')a.applicationsOpen=!a.applicationsOpen;if(action==='accept'&&a.applicants.length){if(a.members.length>=40)return notify('Alliance member limit reached.',true);const i=a.applicants.findIndex(x=>x.id===button.dataset.applicant),x=a.applicants.splice(i<0?0:i,1)[0];a.members.push({id:`member-${Date.now()}`,name:x.name,planet:x.planet,coords:x.coords,rank:'Recruit',online:false});const p=state.galaxy.find(q=>q.name===x.planet);if(p)p.alliance=a.name;allianceLog(`${x.planet} accepted as a Recruit into ${a.name}.`);}if(action==='decline'&&a.applicants.length){const i=a.applicants.findIndex(x=>x.id===button.dataset.applicant),x=a.applicants.splice(i<0?0:i,1)[0];allianceLog(`${x.planet} application declined.`);}if(action==='call'){const p=state.galaxy.find(x=>x.name===document.getElementById('callTarget').value),eta=Math.max(1,Math.min(24,Number(document.getElementById('callEta').value)||1)),c={id:Math.random().toString(36).slice(2),planet:p?.name||'Morrow Wake',coords:p?.coords||'07:04:02',eta,notes:document.getElementById('callNotes').value||'Hostile fleet sighted',attackerCount:'Unknown',age:0};a.calls.push(c);allianceLog(`Defence called for ${c.planet}, hostile ETA ${eta}.`);notify('Alliance defence call sent.');}if(action==='dismiss'){a.calls=a.calls.filter(c=>c.id!==button.dataset.call);allianceLog('A defence call was closed.');}if(action==='donate')return donateAllianceFund();if(action==='tax'){a.tax=Math.max(0,Math.min(5,Number(document.getElementById('allianceTax').value)||0));allianceLog(`Automatic alliance tax set to ${a.tax}%.`);}update();}
|
||||
function respondDefence(){const fid=document.getElementById('defenceFleet').value,c=state.alliance.calls.find(x=>x.id===document.getElementById('defenceCall').value);if(!c)return notify('Choose an open defence call.',true);const f=state.fleets[fid];if(!totalShips(f))return notify('Selected fleet has no ships.',true);const composition=copy(f);for(const k of Object.keys(f))f[k]=0;state.missions.push({id:Math.random().toString(36).slice(2),fleet:fid,name:fleetLabel(fid),targetId:'alliance:'+c.id,targetName:c.planet,mission:'Defence',eta:Math.min(4,Math.max(1,c.eta)),phase:'outbound',ships:composition,callId:c.id});allianceLog(`${fleetLabel(fid)} dispatched to defend ${c.planet}.`);update();notify('Defence fleet dispatched.');}
|
||||
function politicsAction(action){if(state.centralPlayerId&&['vote','ministers'].includes(action)&&typeof centralPoliticsAction==='function')return centralPoliticsAction(action);const p=state.politics;if(action==='vote'){const name=document.getElementById('gcVote').value;p.votes=p.votes||{};p.votes[name]=(p.votes[name]||0)+1;p.gc=Object.entries(p.votes).sort((a,b)=>b[1]-a[1])[0][0];addNews(`Galaxy vote cast for ${name}. Current Galactic Commander: ${p.gc}.`,'good');}if(action==='message'){p.banner=document.getElementById('galaxyName').value.slice(0,32)||'Vesper Reach';p.message=document.getElementById('politicsMessage').value.slice(0,500);addNews('Galaxy identity and commanders message updated.');}if(action==='ministers'){p.ministers={};document.querySelectorAll('[data-minister]').forEach(e=>p.ministers[e.dataset.minister]=e.value);addNews('Galaxy minister appointments updated.');}if(action==='policies'){document.querySelectorAll('[data-trust]').forEach(e=>p.trust[e.dataset.trust]=e.value);p.autoExile=document.getElementById('autoExile').checked;addNews('Galaxy wanted, trusted, and auto-exile settings updated.');}if(action==='fund'){document.querySelectorAll('[data-fundallow]').forEach(e=>p.allowedFund[e.dataset.fundallow]=e.checked);addNews('Galaxy fund permissions updated.');}if(action==='exile'){if(p.exileCount>=2)return notify('Two members have already been exiled in this 200-tick window.',true);const target=state.galaxy.find(x=>x.id===document.getElementById('exileTarget').value);if(!target)return;const cost=Math.ceil(planetScore(target)/10*(p.exileCount+2)/2);const bill={metal:cost,crystal:cost,eonium:cost};if(!Object.entries(bill).every(([k,v])=>(state.alliance.fund[k]||0)>=v))return notify(`Galaxy fund requires ${nfmt(cost)} of each resource for this exile vote.`,true);Object.entries(bill).forEach(([k,v])=>state.alliance.fund[k]-=v);p.votesToExile.push({id:Math.random().toString(36).slice(2),planet:target.name,target:target.id,reason:document.getElementById('exileReason').value||'No reason supplied',approvals:[],status:'pending',cost});addNews(`Exile vote opened for ${target.name}.`,'warn');}update();}
|
||||
function approveExile(id){const v=state.politics.votesToExile.find(x=>x.id===id);if(!v||v.status!=='pending')return;const signer=Object.values(state.politics.ministers).find(n=>!v.approvals.includes(n));if(!signer)return notify('Each minister has already voted.',true);v.approvals.push(signer);if(v.approvals.length>=2){v.status='approved';state.politics.exileCount++;state.politics.exiles.push(v.target);const exiledPlanet=state.galaxy.find(p=>p.id===v.target);if(exiledPlanet)exiledPlanet.exiled=true;addNews(`${v.planet} was exiled from the practice galaxy. Reason: ${v.reason}`,'warn');}update();}
|
||||
@@ -329,7 +329,7 @@ document.addEventListener('change',e=>{if(e.target.matches('[data-factoryassign]
|
||||
function galaxyOf(coords){return String(coords||'').split(':').slice(0,2).map(n=>padCoord(Number(n))).join(':');}
|
||||
function homeGalaxy(){return galaxyOf((state.galaxy.find(p=>p.player)||state.galaxy[0]).coords);}
|
||||
function memberCoordinates(name){if(name==='A. Commander'){const home=state.galaxy.find(p=>p.player);if(home&&isAllianceMember(name))return home.coords;}const member=state.alliance.members.find(m=>m.name===name);if(!member)return '';const p=state.galaxy.find(p=>p.ruler===name||p.name===member.planet);return p?.coords||member.coords||'';}
|
||||
-function isStrongholdResident(name){return isAllianceMember(name)&&!!state.alliance.fortress.strongholdGalaxy&&galaxyOf(memberCoordinates(name))===state.alliance.fortress.strongholdGalaxy;}
|
||||
+function isStrongholdResident(name){if(state.centralPlayerId&&state.alliance.fortress.claimStatus!=='active')return false;return isAllianceMember(name)&&!!state.alliance.fortress.strongholdGalaxy&&galaxyOf(memberCoordinates(name))===state.alliance.fortress.strongholdGalaxy;}
|
||||
function galaxyHTML(){const key=homeGalaxy(),planets=state.galaxy.filter(p=>galaxyOf(p.coords)===key),rows=galaxyPlanetHTML().match(/<tr>[\s\S]*?<\/tr>/g)||[],bySlot=new Map(planets.map((p,i)=>[Number(p.coords.split(':')[2]),rows[i]]));return Array.from({length:15},(_,i)=>{const slot=i+1;if(slot<=10&&bySlot.has(slot))return bySlot.get(slot);const structure=slot>10?state.structurePlanets.find(p=>galaxyOf(p.coords)===key&&Number(p.slot)===slot):null;return '<tr data-slot="'+slot+'"><td><b>'+ (structure?esc(structure.name):slot<=10?'Empty':'Empty / Reserved')+'</b><small>'+key+':'+padCoord(slot)+'</small></td><td>'+ (structure?esc(structure.ruler||structure.alliance):'—')+'</td><td colspan="5">'+(slot<=10?'Planet slot':'Alliance stronghold structure')+'</td><td>—</td><td>—</td></tr>';}).join('');}
|
||||
function updateHomeWorldSurvey(){const type=planetTypeFor(state),art=document.getElementById('homePlanetTypeArtwork'),src='/assets/planets/'+type.id+'.svg';if(art?.getAttribute&&art.getAttribute('src')!==src){art.src=src;art.alt=type.name+' orbital survey';}for(const [id,value] of [['homeWorldType',type.name],['homeWorldHabitability',type.habitability+'%'],['homeWorldGrowth',(type.growthPercent>=0?'+':'')+type.growthPercent+'%'],['homeWorldBase',nfmt(type.basePopulation)]]){const e=document.getElementById(id);if(e&&e.textContent!==value)e.textContent=value;}}
|
||||
function updateHomeCoordinates(){updateHomeWorldSurvey();const home=state.galaxy.find(p=>p.player);if(!home)return;for(const [id,value] of [['headerPlanetName',displayPlanetName(home.name)||'Home Planet'],['homeSceneName',displayPlanetName(home.name)||'Home Planet'],['homeSceneRace','COMMAND PLANET · '+(state.race||home.race||'Terran').toUpperCase()],['homeHeroTitle',(displayPlanetName(home.name)||'Home Planet')+', under your command.'],['homeHeroDescription','Ruler: '+(home.ruler||'Unassigned')+(home.username?' · Commander: '+home.username:'')+' · '+home.coords],['headerPlanetCoords',home.coords],['headerPlanetRuler',home.ruler||'Unassigned'],['headerAccountId',state.accountId||'—'],['headerPlanetTick',String(state.tick).padStart(3,'0')],['headerPlanetScore',nfmt(playerScore())],['headerPlanetXP',nfmt(state.xp)],['headerPlanetValue',nfmt(playerValue())],['homeGalaxyLabel','Planetary command · Galaxy '+homeGalaxy()],['homeSceneCoordinates',home.coords.split(':').join(' : ')],['homeRailCoordinates','REALTIME · PLANET '+home.coords],['homeGalaxyStatusLabel','Galaxy '+homeGalaxy()+' · local practice round']]){const el=document.getElementById(id);if(el)el.textContent=value;}}
|
||||
diff --git a/dist/planets.js b/dist/planets.js
|
||||
index 060e17c..64ba913 100644
|
||||
--- a/dist/planets.js
|
||||
+++ b/dist/planets.js
|
||||
@@ -13,3 +13,24 @@ async function refreshSharedPlanets(){if(!planetDirectoryReady||planetDirectoryS
|
||||
initializePlanetDirectory();setInterval(()=>{if(!document.hidden)refreshSharedPlanets();},15000);
|
||||
|
||||
setInterval(async()=>{try{const data=await centralDirectoryRequest('/api/version');const button=document.getElementById('versionReload');if(button&&data.version!=='0.120.1')button.hidden=false;}catch{}},60000);document.addEventListener('click',e=>{if(e.target.id==='versionReload')location.reload();});
|
||||
+
|
||||
+async function centralSetFortress(){
|
||||
+ if(window.strongholdRequestBusy)return;
|
||||
+ window.strongholdRequestBusy=true;
|
||||
+ try{
|
||||
+ const galaxy=(document.getElementById('fortressGalaxy')?.value||'').trim();
|
||||
+ const snapshot=await centralDirectoryRequest('/api/strongholds');
|
||||
+ const alliance=snapshot.alliances.find(a=>a.name===state.alliance.name);
|
||||
+ if(!alliance?.canManage)throw Error('Your rank cannot manage this stronghold.');
|
||||
+ const existing=snapshot.claims.find(c=>c.allianceId===alliance.id&&c.status!=='released');
|
||||
+ if(existing){
|
||||
+ if(existing.status==='disputed')throw Error('This stronghold claim is disputed. Staff must resolve it first.');
|
||||
+ if(existing.galaxy===galaxy.split(':').map(Number).join(':'))return notify('The stronghold is already in that galaxy.');
|
||||
+ if(existing.assetCount)throw Error('Existing structures or reservations must be handled before moving the stronghold.');
|
||||
+ if(!confirm('Move this empty stronghold? Existing anarchy rules still apply.'))return;
|
||||
+ }
|
||||
+ await centralDirectoryRequest('/api/strongholds',{action:existing?'move':'claim',claimId:existing?.id,allianceId:alliance.id,galaxy,revision:snapshot.revision,generation:snapshot.generation,operationId:crypto.randomUUID()});
|
||||
+ await refreshAfterCentralWrite();notify('Stronghold claim established.');
|
||||
+ }catch(error){notify(error.message,true);}
|
||||
+ finally{window.strongholdRequestBusy=false;}
|
||||
+}
|
||||
diff --git a/drizzle/0032_stronghold_claims.sql b/drizzle/0032_stronghold_claims.sql
|
||||
new file mode 100644
|
||||
index 0000000..6e933a3
|
||||
--- /dev/null
|
||||
+++ b/drizzle/0032_stronghold_claims.sql
|
||||
@@ -0,0 +1,8 @@
|
||||
+-- SF-049: additive schema only; no resets, moves or asset deletion.
|
||||
+
|
||||
+CREATE TABLE IF NOT EXISTS stronghold_states(generation INTEGER PRIMARY KEY,data_json TEXT NOT NULL);
|
||||
+CREATE TABLE IF NOT EXISTS stronghold_claims(generation INTEGER NOT NULL,id TEXT NOT NULL,galaxy TEXT NOT NULL,alliance_id TEXT NOT NULL,status TEXT NOT NULL,PRIMARY KEY(generation,id));
|
||||
+CREATE UNIQUE INDEX IF NOT EXISTS stronghold_galaxy_exclusive ON stronghold_claims(generation,galaxy) WHERE status IN ('active','inactive');
|
||||
+CREATE UNIQUE INDEX IF NOT EXISTS stronghold_alliance_exclusive ON stronghold_claims(generation,alliance_id) WHERE status IN ('active','inactive');
|
||||
+CREATE TABLE IF NOT EXISTS stronghold_operations(id TEXT PRIMARY KEY,user_id TEXT NOT NULL,payload TEXT NOT NULL,response_json TEXT NOT NULL);
|
||||
+CREATE TABLE IF NOT EXISTS stronghold_audit(id TEXT PRIMARY KEY,generation INTEGER NOT NULL,user_id TEXT NOT NULL,action TEXT NOT NULL,data_json TEXT NOT NULL,created_at INTEGER NOT NULL);
|
||||
\ No newline at end of file
|
||||
diff --git a/scripts/build-worker.cjs b/scripts/build-worker.cjs
|
||||
index 0cc8d78..8c9a852 100644
|
||||
--- a/scripts/build-worker.cjs
|
||||
+++ b/scripts/build-worker.cjs
|
||||
@@ -8,7 +8,7 @@ function collect(dir){for(const entry of fs.readdirSync(dir,{withFileTypes:true}
|
||||
require('./build-diagnostics.cjs');
|
||||
collect(path.join(root,'dist'));
|
||||
const output=path.join(root,'dist/server');fs.mkdirSync(output,{recursive:true});
|
||||
-const worker=fs.readFileSync(path.join(root,'worker/planet-types.js'),'utf8')+'\n'+'const DEFAULT_ROUND='+fs.readFileSync(path.join(root,'worker/default-round.json'),'utf8')+';\n'+'const ASSETS='+JSON.stringify(assets)+';\n'+fs.readFileSync(path.join(root,'worker/portal.js'),'utf8')+'\n'+fs.readFileSync(path.join(root,'worker/planets.js'),'utf8')+'\n'+fs.readFileSync(path.join(root,'worker/accounts.js'),'utf8')+'\n'+fs.readFileSync(path.join(root,'worker/alliance.js'),'utf8')+'\n'+fs.readFileSync(path.join(root,'worker/attack-operations.js'),'utf8')+'\n'+fs.readFileSync(path.join(root,'worker/forums.js'),'utf8')+'\n'+fs.readFileSync(path.join(root,'worker/access.js'),'utf8')+'\n'+fs.readFileSync(path.join(root,'worker/movement-audit.js'),'utf8')+'\n'+fs.readFileSync(path.join(root,'worker/fleets.js'),'utf8')+'\n'+fs.readFileSync(path.join(root,'worker/tickets.js'),'utf8')+'\n'+fs.readFileSync(path.join(root,'worker/communications.js'),'utf8')+'\n'+fs.readFileSync(path.join(root,'worker/population-development.js'),'utf8')+'\n'+fs.readFileSync(path.join(root,'worker/enrolment.js'),'utf8')+'\n'+fs.readFileSync(path.join(root,'worker/alliance-applications.js'),'utf8')+'\n'+fs.readFileSync(path.join(root,'worker/ship-costs.js'),'utf8')+'\n'+fs.readFileSync(path.join(root,'worker/special-worlds.js'),'utf8')+'\n'+fs.readFileSync(path.join(root,'worker/spacing-bank.js'),'utf8')+'\n'+fs.readFileSync(path.join(root,'worker/round-history.js'),'utf8')+'\n'+fs.readFileSync(path.join(root,'worker/site-management.js'),'utf8')+'\n'+fs.readFileSync(path.join(root,'worker/diagnostics.js'),'utf8')+'\n'+fs.readFileSync(path.join(root,'worker/cache.js'),'utf8')+'\n'+fs.readFileSync(path.join(root,'worker/index.js'),'utf8');
|
||||
+const worker=fs.readFileSync(path.join(root,'worker/planet-types.js'),'utf8')+'\n'+'const DEFAULT_ROUND='+fs.readFileSync(path.join(root,'worker/default-round.json'),'utf8')+';\n'+'const ASSETS='+JSON.stringify(assets)+';\n'+fs.readFileSync(path.join(root,'worker/portal.js'),'utf8')+'\n'+fs.readFileSync(path.join(root,'worker/planets.js'),'utf8')+'\n'+fs.readFileSync(path.join(root,'worker/accounts.js'),'utf8')+'\n'+fs.readFileSync(path.join(root,'worker/alliance.js'),'utf8')+'\n'+fs.readFileSync(path.join(root,'worker/attack-operations.js'),'utf8')+'\n'+fs.readFileSync(path.join(root,'worker/forums.js'),'utf8')+'\n'+fs.readFileSync(path.join(root,'worker/access.js'),'utf8')+'\n'+fs.readFileSync(path.join(root,'worker/movement-audit.js'),'utf8')+'\n'+fs.readFileSync(path.join(root,'worker/fleets.js'),'utf8')+'\n'+fs.readFileSync(path.join(root,'worker/tickets.js'),'utf8')+'\n'+fs.readFileSync(path.join(root,'worker/communications.js'),'utf8')+'\n'+fs.readFileSync(path.join(root,'worker/population-development.js'),'utf8')+'\n'+fs.readFileSync(path.join(root,'worker/enrolment.js'),'utf8')+'\n'+fs.readFileSync(path.join(root,'worker/alliance-applications.js'),'utf8')+'\n'+fs.readFileSync(path.join(root,'worker/ship-costs.js'),'utf8')+'\n'+fs.readFileSync(path.join(root,'worker/special-worlds.js'),'utf8')+'\n'+fs.readFileSync(path.join(root,'worker/spacing-bank.js'),'utf8')+'\n'+fs.readFileSync(path.join(root,'worker/round-history.js'),'utf8')+'\n'+fs.readFileSync(path.join(root,'worker/site-management.js'),'utf8')+'\n'+fs.readFileSync(path.join(root,'worker/diagnostics.js'),'utf8')+'\n'+fs.readFileSync(path.join(root,'worker/cache.js'),'utf8')+'\n'+fs.readFileSync(path.join(root,'worker/stronghold-policy.js'),'utf8')+'\n'+fs.readFileSync(path.join(root,'worker/strongholds.js'),'utf8')+'\n'+fs.readFileSync(path.join(root,'worker/index.js'),'utf8');
|
||||
fs.writeFileSync(path.join(output,'index.js'),worker);
|
||||
fs.mkdirSync(path.join(root,'dist/.openai'),{recursive:true});fs.copyFileSync(path.join(root,'.openai/hosting.json'),path.join(root,'dist/.openai/hosting.json'));
|
||||
fs.cpSync(path.join(root,'drizzle'),path.join(root,'dist/.openai/drizzle'),{recursive:true});
|
||||
diff --git a/tests/miday.test.cjs b/tests/miday.test.cjs
|
||||
index 93b74d0..c30193d 100644
|
||||
--- a/tests/miday.test.cjs
|
||||
+++ b/tests/miday.test.cjs
|
||||
@@ -1,7 +1,7 @@
|
||||
const test=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs'),path=require('node:path');
|
||||
const {DatabaseSync}=require('node:sqlite');
|
||||
const portalSource=fs.readFileSync(path.join(__dirname,'../worker/portal.js'),'utf8');
|
||||
-const source='const DEFAULT_ROUND='+fs.readFileSync(path.join(__dirname,'../worker/default-round.json'),'utf8')+';\n'+'const ASSETS={"/portal.html":{type:"text/html",data:"'+Buffer.from('<h1>Starfall</h1>').toString('base64')+'"}};\n'+portalSource+'\n'+fs.readFileSync(path.join(__dirname,'../worker/accounts.js'),'utf8')+'\n'+fs.readFileSync(path.join(__dirname,'../worker/planets.js'),'utf8')+'\n'+fs.readFileSync(path.join(__dirname,'../worker/access.js'),'utf8')+'\n'+fs.readFileSync(path.join(__dirname,'../worker/cache.js'),'utf8')+'\n'+fs.readFileSync(path.join(__dirname,'../worker/index.js'),'utf8');
|
||||
+const source='const DEFAULT_ROUND='+fs.readFileSync(path.join(__dirname,'../worker/default-round.json'),'utf8')+';\n'+'const ASSETS={"/portal.html":{type:"text/html",data:"'+Buffer.from('<h1>Starfall</h1>').toString('base64')+'"}};\n'+portalSource+'\n'+fs.readFileSync(path.join(__dirname,'../worker/accounts.js'),'utf8')+'\n'+fs.readFileSync(path.join(__dirname,'../worker/planets.js'),'utf8')+'\n'+fs.readFileSync(path.join(__dirname,'../worker/access.js'),'utf8')+'\n'+fs.readFileSync(path.join(__dirname,'../worker/cache.js'),'utf8')+'\n'+fs.readFileSync(path.join(__dirname,'../worker/stronghold-policy.js'),'utf8')+'\n'+fs.readFileSync(path.join(__dirname,'../worker/strongholds.js'),'utf8')+'\n'+fs.readFileSync(path.join(__dirname,'../worker/index.js'),'utf8');
|
||||
const workerPromise=import('data:text/javascript;base64,'+Buffer.from(source).toString('base64'));
|
||||
function database(withUsers=true){const sqlite=new DatabaseSync(':memory:');sqlite.exec(fs.readFileSync(path.join(__dirname,'../drizzle/0000_miday_array.sql'),'utf8'));for(const file of ['0001_planet_directory.sql','0002_intel_affiliations.sql','0003_intel_nicknames.sql','0004_portal_controls.sql'])sqlite.exec(fs.readFileSync(path.join(__dirname,'../drizzle',file),'utf8'));if(withUsers)for(const [id,letter] of [['player-a','a'],['player-b','b']]){sqlite.prepare('INSERT INTO portal_users(id,username,password_hash,password_salt,created_at) VALUES(?,?,?,?,?)').run(id,id,'fixture','fixture',Date.now());sqlite.prepare('INSERT INTO portal_sessions VALUES(?,?,?)').run(require('node:crypto').createHash('sha256').update(letter.repeat(64)).digest('hex'),id,Date.now()+86400000);}return {sqlite,prepare(sql){let values=[];const statement=sqlite.prepare(sql);return {bind(...args){values=args;return this;},async first(){return statement.get(...values)||null;},async all(){return {results:statement.all(...values)};},async run(){return statement.run(...values);}};},async batch(statements){sqlite.exec('BEGIN');try{const results=[];for(const s of statements)results.push(await s.run());sqlite.exec('COMMIT');return results;}catch(error){sqlite.exec('ROLLBACK');throw error;}}};}
|
||||
async function api(db,path,method='GET',body,user='player-a',origin='https://starfall.test'){const {default:worker}=await workerPromise;const headers={};if(user){headers['oai-authenticated-user-id']=user;headers.Cookie='starfall_session='+(user==='player-b'?'b':'a').repeat(64);}if(method!=='GET'){headers.Origin=origin;headers['Content-Type']='application/json';}const response=await worker.fetch(new Request('https://starfall.test'+path,{method,headers,body:method==='GET'?undefined:JSON.stringify(body)}),{DB:db});return {status:response.status,data:await response.json()};}
|
||||
diff --git a/tests/planets.test.cjs b/tests/planets.test.cjs
|
||||
index 7d3d1b8..d565349 100644
|
||||
--- a/tests/planets.test.cjs
|
||||
+++ b/tests/planets.test.cjs
|
||||
@@ -3,7 +3,7 @@ async function enrol(db,user='player-a',values={}){const draft=(await api(db,'/a
|
||||
const test=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs'),path=require('node:path');
|
||||
const {DatabaseSync}=require('node:sqlite');
|
||||
const portalSource=fs.readFileSync(path.join(__dirname,'../worker/portal.js'),'utf8');
|
||||
-const source=fs.readFileSync(path.join(__dirname,'../worker/planet-types.js'),'utf8')+'\n'+'const DEFAULT_ROUND='+fs.readFileSync(path.join(__dirname,'../worker/default-round.json'),'utf8')+';\n'+'const ASSETS={"/portal.html":{type:"text/html",data:"'+Buffer.from('<h1>Starfall</h1>').toString('base64')+'"}};\n'+portalSource+'\n'+fs.readFileSync(path.join(__dirname,'../worker/alliance.js'),'utf8')+'\n'+fs.readFileSync(path.join(__dirname,'../worker/attack-operations.js'),'utf8')+'\n'+fs.readFileSync(path.join(__dirname,'../worker/forums.js'),'utf8')+'\n'+fs.readFileSync(path.join(__dirname,'../worker/access.js'),'utf8')+'\n'+fs.readFileSync(path.join(__dirname,'../worker/movement-audit.js'),'utf8')+'\n'+fs.readFileSync(path.join(__dirname,'../worker/fleets.js'),'utf8')+'\n'+fs.readFileSync(path.join(__dirname,'../worker/tickets.js'),'utf8')+'\n'+fs.readFileSync(path.join(__dirname,'../worker/accounts.js'),'utf8')+'\n'+fs.readFileSync(path.join(__dirname,'../worker/planets.js'),'utf8')+'\n'+fs.readFileSync(path.join(__dirname,'../worker/communications.js'),'utf8')+'\n'+fs.readFileSync(path.join(__dirname,'../worker/population-development.js'),'utf8')+'\n'+fs.readFileSync(path.join(__dirname,'../worker/enrolment.js'),'utf8')+'\n'+fs.readFileSync(path.join(__dirname,'../worker/alliance-applications.js'),'utf8')+'\n'+fs.readFileSync(path.join(__dirname,'../worker/ship-costs.js'),'utf8')+'\n'+fs.readFileSync(path.join(__dirname,'../worker/special-worlds.js'),'utf8')+'\n'+fs.readFileSync(path.join(__dirname,'../worker/spacing-bank.js'),'utf8')+'\n'+fs.readFileSync(path.join(__dirname,'../worker/round-history.js'),'utf8')+'\n'+fs.readFileSync(path.join(__dirname,'../worker/site-management.js'),'utf8')+'\n'+fs.readFileSync(path.join(__dirname,'../worker/diagnostics.js'),'utf8')+'\n'+fs.readFileSync(path.join(__dirname,'../worker/cache.js'),'utf8')+'\n'+fs.readFileSync(path.join(__dirname,'../worker/index.js'),'utf8');
|
||||
+const source=fs.readFileSync(path.join(__dirname,'../worker/planet-types.js'),'utf8')+'\n'+'const DEFAULT_ROUND='+fs.readFileSync(path.join(__dirname,'../worker/default-round.json'),'utf8')+';\n'+'const ASSETS={"/portal.html":{type:"text/html",data:"'+Buffer.from('<h1>Starfall</h1>').toString('base64')+'"}};\n'+portalSource+'\n'+fs.readFileSync(path.join(__dirname,'../worker/alliance.js'),'utf8')+'\n'+fs.readFileSync(path.join(__dirname,'../worker/attack-operations.js'),'utf8')+'\n'+fs.readFileSync(path.join(__dirname,'../worker/forums.js'),'utf8')+'\n'+fs.readFileSync(path.join(__dirname,'../worker/access.js'),'utf8')+'\n'+fs.readFileSync(path.join(__dirname,'../worker/movement-audit.js'),'utf8')+'\n'+fs.readFileSync(path.join(__dirname,'../worker/fleets.js'),'utf8')+'\n'+fs.readFileSync(path.join(__dirname,'../worker/tickets.js'),'utf8')+'\n'+fs.readFileSync(path.join(__dirname,'../worker/accounts.js'),'utf8')+'\n'+fs.readFileSync(path.join(__dirname,'../worker/planets.js'),'utf8')+'\n'+fs.readFileSync(path.join(__dirname,'../worker/communications.js'),'utf8')+'\n'+fs.readFileSync(path.join(__dirname,'../worker/population-development.js'),'utf8')+'\n'+fs.readFileSync(path.join(__dirname,'../worker/enrolment.js'),'utf8')+'\n'+fs.readFileSync(path.join(__dirname,'../worker/alliance-applications.js'),'utf8')+'\n'+fs.readFileSync(path.join(__dirname,'../worker/ship-costs.js'),'utf8')+'\n'+fs.readFileSync(path.join(__dirname,'../worker/special-worlds.js'),'utf8')+'\n'+fs.readFileSync(path.join(__dirname,'../worker/spacing-bank.js'),'utf8')+'\n'+fs.readFileSync(path.join(__dirname,'../worker/round-history.js'),'utf8')+'\n'+fs.readFileSync(path.join(__dirname,'../worker/site-management.js'),'utf8')+'\n'+fs.readFileSync(path.join(__dirname,'../worker/diagnostics.js'),'utf8')+'\n'+fs.readFileSync(path.join(__dirname,'../worker/cache.js'),'utf8')+'\n'+fs.readFileSync(path.join(__dirname,'../worker/stronghold-policy.js'),'utf8')+'\n'+fs.readFileSync(path.join(__dirname,'../worker/strongholds.js'),'utf8')+'\n'+fs.readFileSync(path.join(__dirname,'../worker/index.js'),'utf8');
|
||||
const workerPromise=import('data:text/javascript;base64,'+Buffer.from(source).toString('base64'));
|
||||
function database(withUsers=true){const sqlite=new DatabaseSync(':memory:');sqlite.exec(fs.readFileSync(path.join(__dirname,'../drizzle/0000_miday_array.sql'),'utf8'));sqlite.exec(fs.readFileSync(path.join(__dirname,'../drizzle/0001_planet_directory.sql'),'utf8'));sqlite.exec(fs.readFileSync(path.join(__dirname,'../drizzle/0002_intel_affiliations.sql'),'utf8'));sqlite.exec(fs.readFileSync(path.join(__dirname,'../drizzle/0003_intel_nicknames.sql'),'utf8'));sqlite.exec(fs.readFileSync(path.join(__dirname,'../drizzle/0004_portal_controls.sql'),'utf8'));sqlite.exec(fs.readFileSync(path.join(__dirname,'../drizzle/0005_staff_articles.sql'),'utf8'));if(withUsers)for(const [id,letter] of [['player-a','a'],['player-b','b']]){sqlite.prepare('INSERT INTO portal_users(id,username,password_hash,password_salt,created_at) VALUES(?,?,?,?,?)').run(id,id,'fixture','fixture',Date.now());sqlite.prepare('INSERT INTO portal_sessions VALUES(?,?,?)').run(require('node:crypto').createHash('sha256').update(letter.repeat(64)).digest('hex'),id,Date.now()+86400000);}return {sqlite,prepare(sql){let values=[];const statement=sqlite.prepare(sql);return {bind(...args){values=args;return this;},async first(){return statement.get(...values)||null;},async all(){return {results:statement.all(...values)};},async run(){return statement.run(...values);}};},async batch(statements){sqlite.exec('BEGIN');try{const results=[];for(const s of statements)results.push(await s.run());sqlite.exec('COMMIT');return results;}catch(error){sqlite.exec('ROLLBACK');throw error;}}};}
|
||||
async function api(db,path,method='GET',body,user='player-a',origin='https://starfall.test'){const {default:worker}=await workerPromise;const headers={};if(user){headers['oai-authenticated-user-id']=user;headers.Cookie='starfall_session='+(user==='player-b'?'b':'a').repeat(64);}if(method!=='GET'){headers.Origin=origin;headers['Content-Type']='application/json';}const response=await worker.fetch(new Request('https://starfall.test'+path,{method,headers,body:method==='GET'?undefined:JSON.stringify(body)}),{DB:db,ALLIANCE_KEY_SECRET:Buffer.alloc(32,7).toString('base64')});const raw=await response.text();let data;try{data=JSON.parse(raw);}catch{data={error:raw};}return {status:response.status,data};}
|
||||
@@ -120,3 +120,128 @@ test('legacy target imports preserve claims once without reopening closed operat
|
||||
test('Portal and Game diagnostic reports retain distinct scopes in stored history',async()=>{const db=database();await seed(db);for(const scope of ['portal','game']){const report=await api(db,'/api/staff/diagnostics','POST',{scope,observations:[],sampledPages:scope==='game'?8:6});assert.equal(report.status,200);assert.equal(report.data.report.scope,scope);assert.equal(report.data.report.sampleMode,scope==='game'?'isolated-read-only':'portal-pages');assert.equal((await api(db,'/api/staff/diagnostics?id='+report.data.report.id)).data.report.scope,scope);}const reports=(await api(db,'/api/staff/diagnostics')).data.reports;assert.deepEqual(reports.map(r=>r.scope).sort(),['game','portal']);assert.equal((await api(db,'/api/staff/diagnostics','POST',{scope:'invented'})).status,400);assert.equal((await api(db,'/game-diagnostic.html','GET',null,'player-b')).status,403);});
|
||||
|
||||
test('ordinary enrolment skips galaxy1:1 while staff enrolment may use its free slots',async()=>{const db=database();const first=await enrol(db);assert.equal(first.data.coords,'01:02:01');db.sqlite.prepare("UPDATE portal_users SET role='multihunter' WHERE id='player-b'").run();const second=await enrol(db,'player-b',{ruler:'Staff ruler',planetName:'Staff colony'});assert.equal(second.data.coords,'01:01:01');});
|
||||
+
|
||||
+// SF-049 authoritative integration tests (real SQLite constraints + Worker routing).
|
||||
+async function shRead(db,user='player-a'){return (await api(db,'/api/strongholds','GET',null,user)).data;}
|
||||
+async function shWrite(db,snapshot,fields,user='player-a'){
|
||||
+ return api(db,'/api/strongholds','POST',{generation:snapshot.generation,revision:snapshot.revision,operationId:require('node:crypto').randomUUID(),...fields},user);
|
||||
+}
|
||||
+async function shFixture(){
|
||||
+ const db=database();await seed(db);seedOtherAlliance(db);
|
||||
+ const row=db.sqlite.prepare('SELECT data_json FROM planet_directory WHERE id=?').get('other-home'),p=JSON.parse(row.data_json);p.coords='07:04:02';p.race='Terran';db.sqlite.prepare('UPDATE planet_directory SET coords=?,data_json=? WHERE id=?').run(p.coords,JSON.stringify(p),'other-home');return db;
|
||||
+}
|
||||
+test('stronghold API claims exclusively, checks origin and trusted leadership, and replays one operation',async()=>{
|
||||
+ const db=await shFixture(),snapshot=await shRead(db),a=snapshot.alliances.find(a=>a.name==='Pact');
|
||||
+ assert.equal((await shWrite(db,snapshot,{action:'claim',allianceId:a.id,galaxy:'07:04'},'player-b')).status,403);
|
||||
+ const payload={action:'claim',allianceId:a.id,galaxy:'07:04',generation:snapshot.generation,revision:snapshot.revision,operationId:'claim-operation-one'};
|
||||
+ assert.equal((await api(db,'/api/strongholds','POST',payload,'player-a','https://evil.test')).status,403);
|
||||
+ assert.equal((await api(db,'/api/strongholds','POST',payload)).status,200);
|
||||
+ assert.equal((await api(db,'/api/strongholds','POST',payload)).status,200);
|
||||
+ assert.equal((await api(db,'/api/strongholds','POST',{...payload,galaxy:'7:5'})).status,409);
|
||||
+ const next=await shRead(db,'player-b'),b=next.alliances.find(a=>a.name==='Other');
|
||||
+ assert.equal((await shWrite(db,next,{action:'claim',allianceId:b.id,galaxy:'7:4'},'player-b')).status,409);
|
||||
+ const full=(await api(db,'/api/planets')).data;
|
||||
+ assert.equal(full.alliances.find(a=>a.name==='Pact').fortress.claimStatus,'active');
|
||||
+ assert.equal(full.planets.find(p=>p.id==='other-home').alliance,'Other');
|
||||
+ assert.equal(JSON.parse(db.sqlite.prepare('SELECT data_json FROM planet_directory WHERE id=?').get('home').data_json).resources.metal,123);
|
||||
+});
|
||||
+test('stronghold stale CAS gates every state, index, audit and alliance write',async()=>{
|
||||
+ const db=await shFixture(),snapshot=await shRead(db),id=snapshot.alliances.find(a=>a.name==='Pact').id;
|
||||
+ db.sqlite.prepare('UPDATE planet_directory_meta SET revision=revision+1').run();
|
||||
+ assert.equal((await shWrite(db,snapshot,{action:'claim',allianceId:id,galaxy:'7:4'})).status,409);
|
||||
+ assert.equal(db.sqlite.prepare('SELECT COUNT(*) n FROM stronghold_states').get().n,0);
|
||||
+ assert.equal(db.sqlite.prepare('SELECT COUNT(*) n FROM stronghold_claims').get().n,0);
|
||||
+ assert.equal(db.sqlite.prepare('SELECT COUNT(*) n FROM stronghold_audit').get().n,0);
|
||||
+ assert.equal(JSON.parse(db.sqlite.prepare('SELECT data_json FROM planet_alliances WHERE name=?').get('Pact').data_json).fortress,undefined);
|
||||
+});
|
||||
+test('stronghold empty transfer requires current two-party approval and release retains history',async()=>{
|
||||
+ const db=await shFixture();let s=await shRead(db);const a=s.alliances.find(a=>a.name==='Pact').id,b=s.alliances.find(a=>a.name==='Other').id;
|
||||
+ assert.equal((await shWrite(db,s,{action:'claim',allianceId:a,galaxy:'7:4'})).status,200);
|
||||
+ s=await shRead(db);const claimId=s.claims[0].id;
|
||||
+ assert.equal((await shWrite(db,s,{action:'transfer',claimId,targetAllianceId:b},'player-b')).status,403);
|
||||
+ assert.equal((await shWrite(db,s,{action:'offerTransfer',claimId,targetAllianceId:b})).status,200);
|
||||
+ s=await shRead(db,'player-b');assert.equal((await shWrite(db,s,{action:'transfer',claimId,targetAllianceId:b},'player-b')).status,200);
|
||||
+ s=await shRead(db,'player-b');assert.equal(s.claims[0].allianceId,b);
|
||||
+ assert.equal((await shWrite(db,s,{action:'release',claimId},'player-b')).status,200);
|
||||
+ s=await shRead(db);assert.equal(s.claims[0].status,'released');
|
||||
+ const planets=(await api(db,'/api/planets')).data.planets;assert.equal(planets.find(p=>p.id==='home').alliance,'Pact');
|
||||
+});
|
||||
+test('legacy conflicts freeze bonuses and assets until explicit staff adjudication',async()=>{
|
||||
+ const db=await shFixture();for(const name of ['Pact','Other']){const a=JSON.parse(db.sqlite.prepare('SELECT data_json FROM planet_alliances WHERE name=?').get(name).data_json);a.fortress={strongholdGalaxy:'07:04'};db.sqlite.prepare('UPDATE planet_alliances SET data_json=? WHERE name=?').run(JSON.stringify(a),name);}
|
||||
+ const structure={id:'legacy-s',alliance:'Other',coords:'07:04:11',name:'Legacy asset'};
|
||||
+ db.sqlite.prepare('INSERT INTO planet_directory VALUES(?,?,?,?,?,?)').run(structure.id,'structure',structure.coords,null,JSON.stringify(structure),1);
|
||||
+ let s=await shRead(db);assert.ok(s.claims.every(c=>c.status==='disputed'));
|
||||
+ const projection=(await api(db,'/api/planets')).data;assert.ok(projection.alliances.every(a=>a.fortress.strongholdGalaxy===''));
|
||||
+ const pact=s.claims.find(c=>c.allianceId===s.alliances.find(a=>a.name==='Pact').id);
|
||||
+ assert.equal((await shWrite(db,s,{action:'resolve',winnerClaimId:pact.id,winnerStatus:'active',staffOverride:true,reason:'Reviewed conflict'})).status,409);
|
||||
+ const other=s.claims.find(c=>c.id!==pact.id);
|
||||
+ assert.equal((await shWrite(db,s,{action:'resolve',winnerClaimId:other.id,winnerStatus:'active',staffOverride:true,reason:'Reviewed conflict'})).status,200);
|
||||
+ assert.equal(db.sqlite.prepare('SELECT COUNT(*) n FROM planet_directory WHERE kind=?').get('structure').n,1);
|
||||
+ s=await shRead(db,'player-b');assert.equal((await shWrite(db,s,{action:'release',claimId:other.id},'player-b')).status,409);
|
||||
+});
|
||||
+test('directory POST cannot forge fortress, stable IDs or unclaimed structure assets',async()=>{
|
||||
+ const db=await shFixture();let full=(await api(db,'/api/planets')).data;
|
||||
+ const body={revision:full.revision,planets:full.planets,structures:full.structures,alliances:full.alliances};
|
||||
+ body.alliances.find(a=>a.name==='Pact').fortress.strongholdGalaxy='07:04';assert.equal((await api(db,'/api/planets','POST',body)).status,409);
|
||||
+ full=(await api(db,'/api/planets')).data;
|
||||
+ const forged={revision:full.revision,planets:full.planets,structures:[{id:'forged',alliance:'Pact',name:'Fake',coords:'07:04:11',race:'Terran'}],alliances:full.alliances};
|
||||
+ assert.equal((await api(db,'/api/planets','POST',forged)).status,409);
|
||||
+ assert.equal(db.sqlite.prepare('SELECT COUNT(*) n FROM planet_directory WHERE kind=?').get('structure').n,0);
|
||||
+});
|
||||
+test('claimed staff structure sync preserves valid existing editing and blocks cross-galaxy writes',async()=>{
|
||||
+ const db=await shFixture();let s=await shRead(db),id=s.alliances.find(a=>a.name==='Pact').id;
|
||||
+ await shWrite(db,s,{action:'claim',allianceId:id,galaxy:'7:4'});
|
||||
+ let full=(await api(db,'/api/planets')).data;
|
||||
+ const body={revision:full.revision,planets:full.planets,structures:[{id:'built',alliance:'Pact',name:'Structure',coords:'07:04:11',race:'Terran'}],alliances:full.alliances};
|
||||
+ body.alliances.find(a=>a.name==='Pact').structures={active:[{id:'built',slot:11}],buildQueue:[]};
|
||||
+ assert.equal((await api(db,'/api/planets','POST',body)).status,200);
|
||||
+ s=await shRead(db);assert.equal(s.claims[0].assetCount,2);assert.equal((await shWrite(db,s,{action:'release',claimId:s.claims[0].id})).status,409);
|
||||
+ full=(await api(db,'/api/planets')).data;
|
||||
+ const wrong={revision:full.revision,planets:full.planets,structures:full.structures.map(p=>({...p,coords:'07:05:11'})),alliances:full.alliances};
|
||||
+ assert.equal((await api(db,'/api/planets','POST',wrong)).status,409);
|
||||
+});
|
||||
+test('stronghold generation isolates old claims and SQL uniqueness backs policy',async()=>{
|
||||
+ const db=await shFixture();let s=await shRead(db),id=s.alliances.find(a=>a.name==='Pact').id;
|
||||
+ await shWrite(db,s,{action:'claim',allianceId:id,galaxy:'7:4'});
|
||||
+ assert.throws(()=>db.sqlite.prepare('INSERT INTO stronghold_claims VALUES(?,?,?,?,?)').run(s.generation,'forged','7:4','other','active'),/UNIQUE/);
|
||||
+ await api(db,'/api/portal/reset','POST',{confirmation:'RESET'});
|
||||
+ const fresh=await shRead(db);assert.notEqual(fresh.generation,s.generation);assert.equal(fresh.claims.length,0);
|
||||
+ assert.equal((await shWrite(db,s,{action:'release',claimId:'missing'})).status,409);
|
||||
+});
|
||||
+test('stronghold optimistic concurrent requests choose one winner without side effects',async()=>{
|
||||
+ const db=await shFixture(),snapshot=await shRead(db);let chain=Promise.resolve();const batch=db.batch.bind(db);
|
||||
+ db.batch=statements=>{const result=chain.then(()=>batch(statements));chain=result.catch(()=>{});return result;};
|
||||
+ const make=name=>({action:'claim',allianceId:snapshot.alliances.find(a=>a.name===name).id,galaxy:'7:4'});
|
||||
+ const results=await Promise.all([shWrite(db,snapshot,make('Pact')),shWrite(db,snapshot,make('Other'),'player-b')]);
|
||||
+ assert.deepEqual(results.map(r=>r.status).sort(),[200,409]);
|
||||
+ assert.equal(db.sqlite.prepare('SELECT COUNT(*) n FROM stronghold_claims WHERE status=?').get('active').n,1);
|
||||
+ assert.equal(db.sqlite.prepare('SELECT COUNT(*) n FROM stronghold_audit').get().n,1);
|
||||
+});
|
||||
+
|
||||
+test('empty stronghold move is atomic, retains old claim and never moves residents',async()=>{
|
||||
+ const db=await shFixture();let s=await shRead(db),id=s.alliances.find(a=>a.name==='Pact').id;
|
||||
+ await shWrite(db,s,{action:'claim',allianceId:id,galaxy:'7:4'});
|
||||
+ const p={id:'remote',name:'Remote',alliance:'Pact',coords:'07:06:01',race:'Terran',publicTick:5};
|
||||
+ db.sqlite.prepare('INSERT INTO planet_directory VALUES(?,?,?,?,?,?)').run(p.id,'planet',p.coords,null,JSON.stringify(p),1);
|
||||
+ s=await shRead(db);const original=s.claims[0].id;
|
||||
+ assert.equal((await shWrite(db,s,{action:'move',claimId:original,galaxy:'7:6'})).status,200);
|
||||
+ s=await shRead(db);assert.equal(s.claims.find(c=>c.id===original).status,'released');assert.equal(s.claims.find(c=>c.status==='active').galaxy,'7:6');
|
||||
+ assert.equal(db.sqlite.prepare('SELECT coords FROM planet_directory WHERE id=?').get('home').coords,'07:04:01');
|
||||
+ assert.equal(db.sqlite.prepare('SELECT coords FROM planet_directory WHERE id=?').get('other-home').coords,'07:04:02');
|
||||
+});
|
||||
+test('stronghold CAS rechecks stored permissions even if a legacy writer forgot revision',async()=>{
|
||||
+ const db=await shFixture(),s=await shRead(db),id=s.alliances.find(a=>a.name==='Other').id;
|
||||
+ const batch=db.batch.bind(db);let intercept=true;
|
||||
+ db.batch=async statements=>{if(intercept){intercept=false;const a=JSON.parse(db.sqlite.prepare('SELECT data_json FROM planet_alliances WHERE name=?').get('Other').data_json);a.members[0].rank='Recruit';db.sqlite.prepare('UPDATE planet_alliances SET data_json=? WHERE name=?').run(JSON.stringify(a),'Other');}return batch(statements);};
|
||||
+ assert.equal((await shWrite(db,s,{action:'claim',allianceId:id,galaxy:'7:4'},'player-b')).status,409);
|
||||
+ assert.equal(db.sqlite.prepare('SELECT COUNT(*) n FROM stronghold_audit').get().n,0);
|
||||
+ assert.equal(db.sqlite.prepare('SELECT COUNT(*) n FROM stronghold_states').get().n,0);
|
||||
+});
|
||||
+test('unique constraint failure rolls back every stronghold write in the atomic batch',async()=>{
|
||||
+ const db=await shFixture(),s=await shRead(db),id=s.alliances.find(a=>a.name==='Pact').id;
|
||||
+ const batch=db.batch.bind(db);let intercept=true;
|
||||
+ db.batch=async statements=>{if(intercept){intercept=false;statements.push(db.prepare('INSERT INTO stronghold_claims VALUES(?,?,?,?,?)').bind(s.generation,'collision','7:4','different','active'));}return batch(statements);};
|
||||
+ assert.equal((await shWrite(db,s,{action:'claim',allianceId:id,galaxy:'7:4'})).status,409);
|
||||
+ assert.equal(db.sqlite.prepare('SELECT revision FROM planet_directory_meta WHERE id=1').get().revision,s.revision);
|
||||
+ for(const table of ['stronghold_audit','stronghold_operations','stronghold_states','stronghold_claims'])assert.equal(db.sqlite.prepare('SELECT COUNT(*) n FROM '+table).get().n,0);
|
||||
+});
|
||||
diff --git a/worker/index.js b/worker/index.js
|
||||
index fdfeb6d..dc6a28b 100644
|
||||
--- a/worker/index.js
|
||||
+++ b/worker/index.js
|
||||
@@ -62,6 +62,7 @@ async function api(request,env){
|
||||
}
|
||||
async function serveRequest(request,env){
|
||||
const url=new URL(request.url);
|
||||
+ if(url.pathname==='/api/strongholds')return strongholdAPI(request,env);
|
||||
if(url.pathname==='/api/staff/diagnostics')return diagnosticsAPI(request,env);
|
||||
if(['/diagnostics.html','/game-diagnostic.html'].includes(url.pathname)){const user=await portalUser(request,env);if(!user)return Response.redirect(url.origin+'/login.html',302);if(!portalStaffPermission(user,'diagnostics'))return json({error:'Diagnostics permission required.'},403);}
|
||||
if(url.pathname.startsWith('/botfiles/')){try{return await gameDumpAPI(request,env);}catch{return json({error:'The gamedump is temporarily unavailable.'},503);}}
|
||||
diff --git a/worker/planets.js b/worker/planets.js
|
||||
index f174f73..19bbabb 100644
|
||||
--- a/worker/planets.js
|
||||
+++ b/worker/planets.js
|
||||
@@ -12,7 +12,7 @@ async function planetDirectoryAPI(request,env){
|
||||
if(request.method==='GET'){
|
||||
const meta=await env.DB.prepare('SELECT * FROM planet_directory_meta WHERE id=1').first(),rows=await env.DB.prepare('SELECT * FROM planet_directory ORDER BY coords,id').all(),alliances=await env.DB.prepare('SELECT data_json FROM planet_alliances ORDER BY name').all();
|
||||
const planets=[],structures=[];for(const row of rows.results||[]){const full=JSON.parse(row.data_json),owned=row.owner_id===user.id;const value=portalStaffPermission(user,'planets')||owned?{...full,player:owned}:{id:full.id,name:full.name,ruler:full.ruler,username:full.username||'',race:full.race,planetType:full.planetType,alliance:full.alliance,coords:full.coords,structures:full.structures||0,exiled:!!full.exiled,publicValue:full.publicValue||0,publicScore:full.publicScore||0,publicSize:full.publicSize||0,publicPopulation:full.publicPopulation??full.population??1000,publicXP:full.publicXP||0,publicTick:full.publicTick||0,player:false,directoryReadOnly:true};(row.kind==='planet'?planets:structures).push(value);}
|
||||
- const activeTypes=[...new Set((rows.results||[]).map(r=>JSON.parse(r.data_json).planetType).filter(Boolean))].map(id=>planetTypeFor({planetType:id}));return json({planetTypeSurveys:activeTypes,userId:user.id,accountId:user.accountId,revision:meta.revision,resetGeneration:meta.reset_generation||0,playerOnly:!!meta.player_only,planets,structures,alliances:repairDirectoryMemberships((rows.results||[]).filter(r=>r.kind==='planet').map(r=>JSON.parse(r.data_json)),(alliances.results||[]).map(r=>JSON.parse(r.data_json))),canEdit:portalStaffPermission(user,'planets')});
|
||||
+ const activeTypes=[...new Set((rows.results||[]).map(r=>JSON.parse(r.data_json).planetType).filter(Boolean))].map(id=>planetTypeFor({planetType:id}));return json({planetTypeSurveys:activeTypes,userId:user.id,accountId:user.accountId,revision:meta.revision,resetGeneration:meta.reset_generation||0,playerOnly:!!meta.player_only,planets,structures,alliances:await shDirectoryProjection(env,repairDirectoryMemberships((rows.results||[]).filter(r=>r.kind==='planet').map(r=>JSON.parse(r.data_json)),(alliances.results||[]).map(r=>JSON.parse(r.data_json)))),canEdit:portalStaffPermission(user,'planets')});
|
||||
}
|
||||
if(request.method==='PATCH'){if(request.headers.get('Origin')!==new URL(request.url).origin)return json({error:'Invalid request origin.'},403);const body=await request.json(),updates={};for(const [key,target,max] of [['username','username',32],['planetName','name',60],['rulerName','ruler',60]]){if(body[key]===undefined)continue;const value=String(body[key]).trim();if(value.length<2||value.length>max||!/^['’\p{L}\p{N} _.-]+$/u.test(value))return json({error:key+' must be 2–'+max+' plain characters.'},400);updates[target]=value;}if(!Object.keys(updates).length)return json({error:'Choose an identity field to update.'},400);const row=await env.DB.prepare("SELECT id,data_json FROM planet_directory WHERE owner_id=? AND kind='planet' LIMIT 1").bind(user.id).first();if(!row)return json({error:'No planet assigned to your account yet.'},403);if(updates.ruler&&await env.DB.prepare("SELECT id FROM planet_directory WHERE kind='planet' AND id<>? AND lower(json_extract(data_json,'$.ruler'))=lower(?)").bind(row.id,updates.ruler).first())return json({error:'Ruler name already in use.'},409);const meta=await env.DB.prepare('SELECT revision FROM planet_directory_meta WHERE id=1').first(),data=JSON.parse(row.data_json),operation=crypto.randomUUID();if(updates.name&&await env.DB.prepare("SELECT id FROM planet_directory WHERE kind='planet' AND id<>? AND lower(json_extract(data_json,'$.name'))=lower(?)").bind(row.id,updates.name).first())return json({error:'Planet name already in use.'},409);Object.assign(data,updates);await ensureStaffAuditSchema(env);const audit=staffPlanetAuditStatement(env,user,JSON.parse(row.data_json),data,'Planet identity settings',operation);const results=await env.DB.batch([env.DB.prepare('UPDATE planet_directory_meta SET revision=revision+1,operation_id=? WHERE id=1 AND revision=?').bind(operation,meta.revision),env.DB.prepare('UPDATE planet_directory SET data_json=?,updated_at=? WHERE id=? AND owner_id=? AND EXISTS (SELECT 1 FROM planet_directory_meta WHERE operation_id=?)').bind(JSON.stringify(data),Date.now(),row.id,user.id,operation),...(audit?[audit]:[])]);if((results[0].meta?.changes??results[0].changes)!==1)return json({error:'The directory changed. Retry saving your planet identity.'},409);return json({ok:true,...updates,revision:meta.revision+1});}
|
||||
if(request.method!=='POST')return json({error:'Method not allowed.'},405);
|
||||
@@ -23,11 +23,12 @@ async function planetDirectoryAPI(request,env){
|
||||
const uniqueWorlds=new Set(),planetNames=new Set();for(const p of body.planets){const t=planetTypeFor(p);if(t.uniquePerRound){if(uniqueWorlds.has(t.uniqueKey))return json({error:'A unique world occurs twice.'},409);uniqueWorlds.add(t.uniqueKey);}const name=p.name.toLowerCase();if(planetNames.has(name))return json({error:'Planet names must be unique.'},409);planetNames.add(name);}const entries=[...body.planets.map(p=>[p,'planet']),...body.structures.map(p=>[p,'structure'])],ids=new Set(),coords=new Set();
|
||||
for(const [p,kind] of entries){if(!p||!/^[A-Za-z0-9_.:-]{1,100}$/.test(p.id)||ids.has(p.id)||!validDirectoryCoords(p.coords,kind)||coords.has(p.coords)||!safeDirectoryName(p.name)||!safeDirectoryName(p.alliance,40)||(!['Terran','Cathaar','Xandathrii','Zikonian','Eitraides','Ilyr','Khepri','Drax'].includes(p.race)&&kind==='planet'))return json({error:'Invalid or duplicate planet, coordinate or race.'},400);ids.add(p.id);coords.add(p.coords);}
|
||||
for(const a of body.alliances)if(!safeDirectoryName(a?.name,40)||!Array.isArray(a.members)||a.members.length>40)return json({error:'Invalid alliance directory.'},400);
|
||||
+ const strongholdError=await shGuardDirectory(env,body,user);if(strongholdError)return json({error:strongholdError},409);
|
||||
const old=await env.DB.prepare('SELECT id,owner_id,data_json FROM planet_directory').all(),owners=new Map((old.results||[]).map(r=>[r.id,r.owner_id])),operation=crypto.randomUUID(),now=Date.now();
|
||||
await ensureStaffAuditSchema(env);const oldData=new Map(old.results.map(r=>[r.id,JSON.parse(r.data_json)]));const mode=await env.DB.prepare('SELECT * FROM planet_directory_meta WHERE id=1').first();if(mode.player_only){if(body.planets.some(p=>!owners.get(p.id)))return json({error:'Only account-owned planets are allowed in this round. Create player accounts instead of practice planets.'},400);if(body.alliances.some(a=>!body.planets.some(p=>p.alliance===a.name)))return json({error:'Only alliances with player planets can be active.'},400);}
|
||||
const commands=[env.DB.prepare('UPDATE planet_directory_meta SET revision=revision+1,operation_id=? WHERE id=1 AND revision=?').bind(operation,body.revision),env.DB.prepare('DELETE FROM planet_directory WHERE EXISTS (SELECT 1 FROM planet_directory_meta WHERE operation_id=?)').bind(operation)];
|
||||
for(const [p,kind] of entries){const data={...p};delete data.player;const owner=kind==='planet'?(p.player?user.id:owners.get(p.id)||null):null;commands.push(env.DB.prepare('INSERT INTO planet_directory(id,kind,coords,owner_id,data_json,updated_at) SELECT ?,?,?,?,?,? WHERE EXISTS (SELECT 1 FROM planet_directory_meta WHERE operation_id=?)').bind(p.id,kind,p.coords,owner,JSON.stringify(data),now,operation));const audit=staffPlanetAuditStatement(env,user,oldData.get(p.id)||{},data,body.source==='staff-editor'?'Staff planet editor':body.source==='structure-generator'?'Staff structure generator':'Directory synchronization',operation);if(audit)commands.push(audit);}for(const [id,before] of oldData)if(!ids.has(id)){const audit=staffPlanetAuditStatement(env,user,before,null,'Planet removed',operation);if(audit)commands.push(audit);}
|
||||
- await ensureAllianceRegistry(env);for(const a of repairDirectoryMemberships(body.planets,body.alliances)){const reserved=await env.DB.prepare('SELECT alliance_id FROM alliance_registry WHERE name_key=?').bind(a.name.toLowerCase()).first(),active=await env.DB.prepare('SELECT name FROM planet_alliances WHERE name=?').bind(a.name).first();if(reserved&&!active)return json({error:'Reserved alliance names require an Owner passkey.'},403);const data={...a,registryId:reserved?.alliance_id||a.registryId||crypto.randomUUID()};for(const key of ['intelRecords','intelBrowserCoords','intelTarget','intelSearch','intelGalaxyScans'])delete data[key];commands.push(env.DB.prepare('INSERT INTO planet_alliances(name,data_json,updated_at) SELECT ?,?,? WHERE EXISTS (SELECT 1 FROM planet_directory_meta WHERE operation_id=?) ON CONFLICT(name) DO UPDATE SET data_json=excluded.data_json,updated_at=excluded.updated_at').bind(a.name,JSON.stringify(data),now,operation));}
|
||||
+ await ensureAllianceRegistry(env);for(const a of repairDirectoryMemberships(body.planets,body.alliances)){const reserved=await env.DB.prepare('SELECT alliance_id FROM alliance_registry WHERE name_key=?').bind(a.name.toLowerCase()).first(),active=await env.DB.prepare('SELECT name FROM planet_alliances WHERE name=?').bind(a.name).first();if(reserved&&!active)return json({error:'Reserved alliance names require an Owner passkey.'},403);const data={...a,registryId:reserved?.alliance_id||crypto.randomUUID()};for(const key of ['intelRecords','intelBrowserCoords','intelTarget','intelSearch','intelGalaxyScans'])delete data[key];commands.push(env.DB.prepare('INSERT INTO planet_alliances(name,data_json,updated_at) SELECT ?,?,? WHERE EXISTS (SELECT 1 FROM planet_directory_meta WHERE operation_id=?) ON CONFLICT(name) DO UPDATE SET data_json=excluded.data_json,updated_at=excluded.updated_at').bind(a.name,JSON.stringify(data),now,operation));}
|
||||
const applied=await env.DB.batch(commands);const meta=await env.DB.prepare('SELECT revision,operation_id FROM planet_directory_meta WHERE id=1').first();if((applied[0].meta?.changes??applied[0].changes)!==1)return json({error:'The directory changed in another session. Reload the latest planets before retrying.',revision:meta.revision},409);
|
||||
await archiveAllianceSettings(env);return json({ok:true,revision:body.revision+1});
|
||||
}
|
||||
diff --git a/worker/stronghold-policy.js b/worker/stronghold-policy.js
|
||||
new file mode 100644
|
||||
index 0000000..647f953
|
||||
--- /dev/null
|
||||
+++ b/worker/stronghold-policy.js
|
||||
@@ -0,0 +1,126 @@
|
||||
+const StrongholdPolicy=(()=>{
|
||||
+// Framework-independent proposal for SF-049. Context must come from server policy.
|
||||
+class PolicyError extends Error {
|
||||
+ constructor(code, message) { super(message); this.name = 'PolicyError'; this.code = code; }
|
||||
+}
|
||||
+const fail = (code, message) => { throw new PolicyError(code, message); };
|
||||
+const states = new Set(['active', 'inactive', 'disputed', 'released']);
|
||||
+const reserved = claim => claim.status !== 'released';
|
||||
+const identifier = value => typeof value === 'string' && value.trim() === value && value.length > 0 && value.length <= 120;
|
||||
+function id(value) { if (!identifier(value)) fail('INVALID', 'Invalid identifier.'); return value; }
|
||||
+function normalizeGalaxy(value) {
|
||||
+ if (typeof value !== 'string' || !/^\d{1,3}:\d{1,3}$/.test(value)) fail('INVALID', 'Use galaxy x:y.');
|
||||
+ const [x, y] = value.split(':').map(Number);
|
||||
+ if (x < 1 || y < 1) fail('INVALID', 'Galaxy coordinates must be positive.');
|
||||
+ return `${x}:${y}`;
|
||||
+}
|
||||
+function overlaps(a, b) {
|
||||
+ return a.roundId === b.roundId && (a.galaxy === b.galaxy || a.allianceId === b.allianceId);
|
||||
+}
|
||||
+function checkRows(rows) {
|
||||
+ if (!Array.isArray(rows)) fail('INVALID', 'Claims must be an array.');
|
||||
+ const ids = new Set();
|
||||
+ for (const row of rows) {
|
||||
+ if (!row || !identifier(row.id) || ids.has(row.id)) fail('INVALID', 'Claim IDs must be unique.');
|
||||
+ ids.add(row.id); id(row.roundId); id(row.allianceId);
|
||||
+ if (normalizeGalaxy(row.galaxy) !== row.galaxy || !states.has(row.status)) fail('INVALID', 'Invalid claim state.');
|
||||
+ if (!Array.isArray(row.assetRefs) || row.assetRefs.some(x => !identifier(x)) || new Set(row.assetRefs).size !== row.assetRefs.length) fail('INVALID', 'Invalid asset references.');
|
||||
+ if (row.status === 'released' && row.assetRefs.length) fail('ASSETS_REMAIN', 'Released claims cannot retain assets.');
|
||||
+ }
|
||||
+}
|
||||
+function validateState(state) {
|
||||
+ if (!state || !Number.isSafeInteger(state.revision) || state.revision < 0) fail('INVALID', 'Invalid revision.');
|
||||
+ checkRows(state.claims);
|
||||
+ for (let i = 0; i < state.claims.length; i++) {
|
||||
+ const a = state.claims[i];
|
||||
+ for (const b of state.claims.slice(i + 1)) {
|
||||
+ if (reserved(a) && reserved(b) && overlaps(a, b) && (a.status !== 'disputed' || b.status !== 'disputed')) fail('CONFLICT', 'Overlapping reservations must remain disputed.');
|
||||
+ }
|
||||
+ }
|
||||
+ return true;
|
||||
+}
|
||||
+function start(state, command) {
|
||||
+ validateState(state);
|
||||
+ if (!command || !Number.isSafeInteger(command.expectedRevision) || command.expectedRevision !== state.revision) fail('STALE', 'Refresh before retrying.');
|
||||
+ if (state.revision === Number.MAX_SAFE_INTEGER) fail('INVALID', 'Revision exhausted.');
|
||||
+ return structuredClone(state);
|
||||
+}
|
||||
+function finish(state) { state.revision++; validateState(state); return state; }
|
||||
+function find(state, claimId) {
|
||||
+ id(claimId);
|
||||
+ return state.claims.find(c => c.id === claimId) || fail('NOT_FOUND', 'Claim not found.');
|
||||
+}
|
||||
+function manage(context, allianceId) {
|
||||
+ if (context?.admin === true) return;
|
||||
+ if (!Array.isArray(context?.authorizedAllianceIds) || !context.authorizedAllianceIds.includes(allianceId)) fail('FORBIDDEN', 'Stronghold management permission required.');
|
||||
+}
|
||||
+function admin(context) { if (context?.admin !== true) fail('FORBIDDEN', 'Conflict adjudication requires administrator permission.'); }
|
||||
+function available(state, candidate, excluded = new Set()) {
|
||||
+ if (state.claims.some(c => reserved(c) && !excluded.has(c.id) && overlaps(candidate, c))) fail('CONFLICT', 'Galaxy or alliance already reserved in this round.');
|
||||
+}
|
||||
+function claimStronghold(state, command, context) {
|
||||
+ const next = start(state, command);
|
||||
+ const candidate = {id: id(command.id), roundId: id(command.roundId), allianceId: id(command.allianceId), galaxy: normalizeGalaxy(command.galaxy), status: 'active', assetRefs: []};
|
||||
+ manage(context, candidate.allianceId);
|
||||
+ if (next.claims.some(c => c.id === candidate.id)) fail('DUPLICATE_ID', 'Claim ID already exists.');
|
||||
+ available(next, candidate); next.claims.push(candidate); return finish(next);
|
||||
+}
|
||||
+function releaseStronghold(state, command, context) {
|
||||
+ const next = start(state, command), claim = find(next, command.claimId);
|
||||
+ manage(context, claim.allianceId);
|
||||
+ if (claim.status === 'disputed') fail('DISPUTED', 'Resolve the dispute first.');
|
||||
+ if (claim.status === 'released') fail('RELEASED', 'Claim already released.');
|
||||
+ if (claim.assetRefs.length) fail('ASSETS_REMAIN', 'Handle structures and build reservations before release.');
|
||||
+ claim.status = 'released'; return finish(next);
|
||||
+}
|
||||
+function transferStronghold(state, command, context) {
|
||||
+ const next = start(state, command), claim = find(next, command.claimId), target = id(command.targetAllianceId);
|
||||
+ // Non-admin context represents verified approvals by BOTH alliance leaderships.
|
||||
+ manage(context, claim.allianceId); manage(context, target);
|
||||
+ if (claim.status === 'disputed') fail('DISPUTED', 'Resolve the dispute first.');
|
||||
+ if (claim.status === 'released') fail('RELEASED', 'Released claims cannot transfer.');
|
||||
+ if (target === claim.allianceId) fail('INVALID', 'Choose a different alliance.');
|
||||
+ available(next, {...claim, allianceId: target}, new Set([claim.id]));
|
||||
+ claim.allianceId = target; return finish(next);
|
||||
+}
|
||||
+function markDisputed(state, command, context) {
|
||||
+ const next = start(state, command); admin(context);
|
||||
+ if (!Array.isArray(command.claimIds) || !command.claimIds.length || new Set(command.claimIds).size !== command.claimIds.length || !identifier(command.reason)) fail('INVALID', 'Supply claim IDs and a short reason.');
|
||||
+ for (const claimId of command.claimIds) {
|
||||
+ const claim = find(next, claimId);
|
||||
+ if (!reserved(claim)) fail('RELEASED', 'Released claims cannot be disputed.');
|
||||
+ claim.status = 'disputed'; claim.disputeReason = command.reason;
|
||||
+ }
|
||||
+ return finish(next);
|
||||
+}
|
||||
+function resolveConflict(state, command, context) {
|
||||
+ const next = start(state, command); admin(context);
|
||||
+ const winner = find(next, command.winnerClaimId);
|
||||
+ if (winner.status !== 'disputed') fail('INVALID', 'Winner must be disputed.');
|
||||
+ if (!['active', 'inactive'].includes(command.winnerStatus)) fail('INVALID', 'Choose the adjudicated status.');
|
||||
+ const losers = next.claims.filter(c => c.id !== winner.id && reserved(c) && overlaps(winner, c));
|
||||
+ // Assets must already have an approved and persisted remediation; never discard them.
|
||||
+ if (losers.some(c => c.assetRefs.length)) fail('ASSETS_REMAIN', 'Conflicting assets require an explicit remediation plan.');
|
||||
+ for (const loser of losers) { loser.status = 'released'; loser.resolutionWinnerId = winner.id; }
|
||||
+ winner.status = command.winnerStatus; delete winner.disputeReason;
|
||||
+ return finish(next);
|
||||
+}
|
||||
+function importLegacyClaims(rows) {
|
||||
+ // Trusted snapshot only: preserves IDs, assets, owners and other metadata.
|
||||
+ if (!Array.isArray(rows)) fail('INVALID', 'Claims must be an array.');
|
||||
+ const claims = structuredClone(rows).map(c => ({...c, galaxy: normalizeGalaxy(c.galaxy)}));
|
||||
+ checkRows(claims);
|
||||
+ const conflicting = new Set();
|
||||
+ for (const a of claims) for (const b of claims) {
|
||||
+ if (a.id !== b.id && reserved(a) && reserved(b) && overlaps(a, b)) { conflicting.add(a.id); conflicting.add(b.id); }
|
||||
+ }
|
||||
+ for (const c of claims) if (conflicting.has(c.id)) { c.status = 'disputed'; c.disputeReason = 'Legacy overlapping reservations'; }
|
||||
+ const result = {revision: 0, claims}; validateState(result); return result;
|
||||
+}
|
||||
+function bonusEligible(state, claimId, member) {
|
||||
+ validateState(state); const claim = find(state, claimId);
|
||||
+ return claim.status === 'active' && member?.hasFunctionalStructure === true && member.roundId === claim.roundId && member.allianceId === claim.allianceId && normalizeGalaxy(member.galaxy) === claim.galaxy;
|
||||
+}
|
||||
+
|
||||
+return {PolicyError,normalizeGalaxy,validateState,claimStronghold,releaseStronghold,transferStronghold,markDisputed,resolveConflict,importLegacyClaims,bonusEligible};
|
||||
+})();
|
||||
diff --git a/worker/strongholds.js b/worker/strongholds.js
|
||||
new file mode 100644
|
||||
index 0000000..9083d92
|
||||
--- /dev/null
|
||||
+++ b/worker/strongholds.js
|
||||
@@ -0,0 +1,207 @@
|
||||
+// SF-049: server-owned stronghold claims. Included before the Worker entrypoint.
|
||||
+const strongholdSchema = `
|
||||
+CREATE TABLE IF NOT EXISTS stronghold_states(generation INTEGER PRIMARY KEY,data_json TEXT NOT NULL);
|
||||
+CREATE TABLE IF NOT EXISTS stronghold_claims(generation INTEGER NOT NULL,id TEXT NOT NULL,galaxy TEXT NOT NULL,alliance_id TEXT NOT NULL,status TEXT NOT NULL,PRIMARY KEY(generation,id));
|
||||
+CREATE UNIQUE INDEX IF NOT EXISTS stronghold_galaxy_exclusive ON stronghold_claims(generation,galaxy) WHERE status IN ('active','inactive');
|
||||
+CREATE UNIQUE INDEX IF NOT EXISTS stronghold_alliance_exclusive ON stronghold_claims(generation,alliance_id) WHERE status IN ('active','inactive');
|
||||
+CREATE TABLE IF NOT EXISTS stronghold_operations(id TEXT PRIMARY KEY,user_id TEXT NOT NULL,payload TEXT NOT NULL,response_json TEXT NOT NULL);
|
||||
+CREATE TABLE IF NOT EXISTS stronghold_audit(id TEXT PRIMARY KEY,generation INTEGER NOT NULL,user_id TEXT NOT NULL,action TEXT NOT NULL,data_json TEXT NOT NULL,created_at INTEGER NOT NULL);`;
|
||||
+async function ensureStrongholds(env) {
|
||||
+ // DDL is also in migration 0032. Kept idempotent for existing preview/test adapters.
|
||||
+ for (const sql of strongholdSchema.split(';').map(s=>s.trim()).filter(Boolean)) await env.DB.prepare(sql).run();
|
||||
+}
|
||||
+function shEqual(a,b) {
|
||||
+ function sort(v){return Array.isArray(v)?v.map(sort):v&&typeof v==='object'?Object.fromEntries(Object.keys(v).sort().filter(k=>v[k]!==undefined).map(k=>[k,sort(v[k])])):v;}
|
||||
+ return JSON.stringify(sort(a))===JSON.stringify(sort(b));
|
||||
+}
|
||||
+function shAssetRefs(alliance, directory) {
|
||||
+ const refs=[];
|
||||
+ for(const [kind,items] of [['active',alliance.structures?.active||[]],['queue',alliance.structures?.buildQueue||[]]]) {
|
||||
+ items.forEach((item,i)=>refs.push(kind+':'+String(item.id||i)));
|
||||
+ }
|
||||
+ for(const row of directory) if(row.kind==='structure'&&JSON.parse(row.data_json).alliance===alliance.name) refs.push('directory:'+row.id);
|
||||
+ return [...new Set(refs)];
|
||||
+}
|
||||
+async function shLoad(env) {
|
||||
+ await ensureStrongholds(env); await ensureAllianceRegistry(env); await ensureSpecialWorldSchema(env);
|
||||
+ const meta=await env.DB.prepare('SELECT * FROM planet_directory_meta WHERE id=1').first();
|
||||
+ const generation=meta.reset_generation||0;
|
||||
+ const rows=(await env.DB.prepare('SELECT name,data_json FROM planet_alliances ORDER BY name').all()).results||[];
|
||||
+ const directory=(await env.DB.prepare('SELECT * FROM planet_directory ORDER BY id').all()).results||[];
|
||||
+ const alliances=[];
|
||||
+ for(const row of rows){
|
||||
+ const a=JSON.parse(row.data_json),registered=await env.DB.prepare('SELECT alliance_id FROM alliance_registry WHERE name_key=?').bind(a.name.toLowerCase()).first();
|
||||
+ // Deterministic legacy identity until it can be atomically persisted.
|
||||
+ a.registryId=registered?.alliance_id||a.registryId||('legacy-'+(await digest(a.name.toLowerCase())).slice(0,32));
|
||||
+ alliances.push(a);
|
||||
+ }
|
||||
+ const stored=await env.DB.prepare('SELECT data_json FROM stronghold_states WHERE generation=?').bind(generation).first();
|
||||
+ let state;
|
||||
+ if(stored) state={...JSON.parse(stored.data_json),revision:meta.revision};
|
||||
+ else {
|
||||
+ const legacy=alliances.filter(a=>a.fortress?.strongholdGalaxy).map(a=>({id:'legacy-'+a.registryId,roundId:String(generation),galaxy:StrongholdPolicy.normalizeGalaxy(a.fortress.strongholdGalaxy),allianceId:a.registryId,status:'active',assetRefs:shAssetRefs(a,directory)}));
|
||||
+ state={...StrongholdPolicy.importLegacyClaims(legacy),revision:meta.revision};
|
||||
+ }
|
||||
+ for(const c of state.claims){
|
||||
+ const a=alliances.find(a=>a.registryId===c.allianceId);
|
||||
+ if(c.status!=='released') c.assetRefs=a?shAssetRefs(a,directory):c.assetRefs;
|
||||
+ }
|
||||
+ StrongholdPolicy.validateState(state);
|
||||
+ return {meta,generation,rows,directory,alliances,state};
|
||||
+}
|
||||
+function shCanManage(user,alliance,directory) {
|
||||
+ // Membership comes from the owned planet, rank from the stored alliance roster.
|
||||
+ const owned=directory.filter(r=>r.kind==='planet'&&r.owner_id===user.id).map(r=>({row:r,p:JSON.parse(r.data_json)}));
|
||||
+ return owned.some(({row,p})=>p.alliance===alliance.name&&(alliance.members||[]).some(m=>(m.planetId===row.id||m.planet===p.name)&&(alliance.rankPermissions?.[m.rank]?.fortress??['Owner','HC'].includes(m.rank))));
|
||||
+}
|
||||
+function shContext(user,snapshot,ids,staffOverride=false) {
|
||||
+ if(staffOverride&&user.role==='admin') return {admin:true};
|
||||
+ const authorizedAllianceIds=ids.filter(id=>{const a=snapshot.alliances.find(a=>a.registryId===id);return a&&shCanManage(user,a,snapshot.directory);});
|
||||
+ return {authorizedAllianceIds};
|
||||
+}
|
||||
+function shProject(alliances,state) {
|
||||
+ return alliances.map(a=>{
|
||||
+ const c=state.claims.find(c=>c.allianceId===a.registryId&&c.status!=='released');
|
||||
+ return {...a,fortress:{...(a.fortress||{}),strongholdGalaxy:c?.status==='active'?c.galaxy.split(':').map(n=>n.padStart(2,'0')).join(':'):'',claimId:c?.id||null,claimStatus:c?.status||'unclaimed',reservedGalaxy:c?.galaxy||''}};
|
||||
+ });
|
||||
+}
|
||||
+async function shDirectoryProjection(env,alliances) {
|
||||
+ const snapshot=await shLoad(env);
|
||||
+ // IDs derive from the server registry, never the directory request.
|
||||
+ return shProject(alliances.map(a=>({...a,registryId:snapshot.alliances.find(x=>x.name===a.name)?.registryId||a.registryId})),snapshot.state);
|
||||
+}
|
||||
+async function shGuardDirectory(env,body,user) {
|
||||
+ const snapshot=await shLoad(env);
|
||||
+ const stored=(await env.DB.prepare('SELECT name,data_json FROM planet_alliances ORDER BY name').all()).results||[];
|
||||
+ const previous=stored.map(r=>JSON.parse(r.data_json));
|
||||
+ const structures=(await env.DB.prepare("SELECT data_json FROM planet_directory WHERE kind='structure' ORDER BY id").all()).results.map(r=>JSON.parse(r.data_json));
|
||||
+ // Preserve existing staff editing only under a server-owned, undisputed claim.
|
||||
+ const changedAlliances=new Set();
|
||||
+ for(const a of body.alliances)for(const key of ['active','buildQueue']){
|
||||
+ const items=a.structures?.[key];
|
||||
+ if(items!==undefined&&(!Array.isArray(items)||items.length>200||items.some(x=>!x||typeof x.id!=='string'||!Number.isInteger(x.slot)||x.slot<11||x.slot>15)))return 'Invalid alliance structure reservations.';
|
||||
+ }
|
||||
+ const oldById=new Map(structures.map(p=>[p.id,p])),newById=new Map(body.structures.map(p=>[p.id,p]));
|
||||
+ for(const [id,p] of oldById)if(!shEqual(p,newById.get(id)))changedAlliances.add(p.alliance);
|
||||
+ for(const [id,p] of newById)if(!shEqual(p,oldById.get(id)))changedAlliances.add(p.alliance);
|
||||
+ for(const a of body.alliances){const old=previous.find(x=>x.name===a.name);if(old&&!shEqual(a.structures||{},old.structures||{}))changedAlliances.add(a.name);}
|
||||
+ for(const name of changedAlliances){
|
||||
+ const a=snapshot.alliances.find(a=>a.name===name),claim=a&&snapshot.state.claims.find(c=>c.allianceId===a.registryId&&c.status==='active');
|
||||
+ if(!a||!claim)return 'Structure writes require an active, undisputed stronghold claim.';
|
||||
+ if(user.role!=='admin'&&!shCanManage(user,a,snapshot.directory))return 'Your alliance leadership permission is required to edit these structures.';
|
||||
+ const requested=body.alliances.find(x=>x.name===name);
|
||||
+ if(!requested)return 'Keep the structure owner in the alliance directory.';
|
||||
+ const assets=body.structures.filter(p=>p.alliance===name);
|
||||
+ for(const p of assets)if(StrongholdPolicy.normalizeGalaxy(String(p.coords).split(':').slice(0,2).join(':'))!==claim.galaxy)return 'Structure coordinates must belong to the owning alliance stronghold.';
|
||||
+ for(const kind of ['active','buildQueue'])for(const item of requested.structures?.[kind]||[]){
|
||||
+ const p=assets.find(p=>p.id===item.id);if(!p||Number(p.coords.split(':')[2])!==Number(item.slot))return 'Alliance structures and global slot reservations must match.';
|
||||
+ }
|
||||
+ }
|
||||
+ for(const a of body.alliances){
|
||||
+ const old=previous.find(x=>x.name===a.name);
|
||||
+ if(!old){if(a.fortress?.strongholdGalaxy||(a.structures?.active||[]).length||(a.structures?.buildQueue||[]).length)return 'New alliances cannot import stronghold claims or structures.';continue;}
|
||||
+ if(a.registryId&&old.registryId&&a.registryId!==old.registryId)return 'Stable alliance identity cannot be changed.';
|
||||
+ // Always preserve server-owned fields; clients need not echo diagnostic projection fields.
|
||||
+ const source=a.fortress||{},target=old.fortress||{};
|
||||
+ if((source.strongholdGalaxy||'')!==(target.strongholdGalaxy||''))return 'Use the stronghold API to change a claim.';
|
||||
+ // Preserve the existing daily-cycle cursor monotonically, bounded by reported server state.
|
||||
+ // No buildings/resources are granted by directory synchronization or claim changes.
|
||||
+ const cursor=source.lastDistorterTick,prior=target.lastDistorterTick||0;
|
||||
+ const latestTick=Math.max(1,...snapshot.directory.filter(r=>r.kind==='planet'&&JSON.parse(r.data_json).alliance===a.name).map(r=>JSON.parse(r.data_json).publicTick||1));
|
||||
+ if(Number.isSafeInteger(cursor)&&cursor>=prior&&cursor<=latestTick)target.lastDistorterTick=cursor;
|
||||
+ a.registryId=old.registryId; a.fortress=target;
|
||||
+ }
|
||||
+ return null;
|
||||
+}
|
||||
+async function strongholdAPI(request,env) {
|
||||
+ const user=await portalUser(request,env);if(!user)return json({error:'Sign in first.'},401);
|
||||
+ const url=new URL(request.url);
|
||||
+ if(!['GET','POST'].includes(request.method))return json({error:'Method not allowed.'},405);
|
||||
+ if(request.method==='POST'&&request.headers.get('Origin')!==url.origin)return json({error:'Invalid origin.'},403);
|
||||
+ try{
|
||||
+ const snapshot=await shLoad(env),{state,generation}=snapshot;
|
||||
+ const publicState=()=>({revision:state.revision,generation,claims:state.claims.map(({assetRefs,transferOffer,...c})=>({...c,assetCount:assetRefs.length,transferTarget:transferOffer?.targetAllianceId||null})),alliances:snapshot.alliances.map(a=>({id:a.registryId,name:a.name,canManage:shCanManage(user,a,snapshot.directory)}))});
|
||||
+ if(request.method==='GET')return json(publicState());
|
||||
+ const raw=await request.text();if(raw.length>8000)return json({error:'Request too large.'},413);
|
||||
+ const b=JSON.parse(raw);
|
||||
+ if(!/^[a-zA-Z0-9_.:-]{8,120}$/.test(b.operationId||''))return json({error:'A unique operation ID is required.'},400);
|
||||
+ const replay=await env.DB.prepare('SELECT * FROM stronghold_operations WHERE id=?').bind(b.operationId).first();
|
||||
+ if(replay){if(replay.user_id!==user.id||replay.payload!==raw)return json({error:'Operation ID already used.'},409);return json(JSON.parse(replay.response_json));}
|
||||
+ if(b.generation!==generation)return json({error:'Round changed. Reload.'},409);
|
||||
+ const command={expectedRevision:b.revision,claimId:b.claimId},old=state.claims.find(c=>c.id===b.claimId);
|
||||
+ const ids=[b.allianceId,old?.allianceId,b.targetAllianceId].filter(Boolean);
|
||||
+ const context=shContext(user,snapshot,ids,b.staffOverride===true);
|
||||
+ if(b.staffOverride&&(!context.admin||typeof b.reason!=='string'||!b.reason.trim()))return json({error:'Administrator authority and an audit reason are required.'},403);
|
||||
+ let next;
|
||||
+ if(b.action==='claim'){
|
||||
+ const a=snapshot.alliances.find(a=>a.registryId===b.allianceId);
|
||||
+ if(!a)return json({error:'Alliance not found.'},404);
|
||||
+ const galaxy=StrongholdPolicy.normalizeGalaxy(b.galaxy);
|
||||
+ if(!snapshot.directory.some(r=>r.kind==='planet'&&JSON.parse(r.data_json).alliance===a.name&&StrongholdPolicy.normalizeGalaxy(r.coords.split(':').slice(0,2).join(':'))===galaxy))return json({error:'Choose a galaxy containing an alliance member.'},409);
|
||||
+ next=StrongholdPolicy.claimStronghold(state,{...command,id:crypto.randomUUID(),roundId:String(generation),allianceId:a.registryId,galaxy},context);
|
||||
+ }else if(b.action==='move'){
|
||||
+ if(!old)return json({error:'Claim not found.'},404);
|
||||
+ const a=snapshot.alliances.find(a=>a.registryId===old.allianceId),galaxy=StrongholdPolicy.normalizeGalaxy(b.galaxy);
|
||||
+ if(!snapshot.directory.some(r=>r.kind==='planet'&&JSON.parse(r.data_json).alliance===a.name&&StrongholdPolicy.normalizeGalaxy(r.coords.split(':').slice(0,2).join(':'))===galaxy))return json({error:'Choose a galaxy containing an alliance member.'},409);
|
||||
+ const released=StrongholdPolicy.releaseStronghold(state,command,context);
|
||||
+ next=StrongholdPolicy.claimStronghold(released,{expectedRevision:released.revision,id:crypto.randomUUID(),roundId:String(generation),allianceId:a.registryId,galaxy},context);
|
||||
+ next.revision=b.revision+1; // One atomic directory mutation, retaining the old claim as history.
|
||||
+ }else if(b.action==='release') next=StrongholdPolicy.releaseStronghold(state,command,context);
|
||||
+ else if(b.action==='offerTransfer'){
|
||||
+ if(!old||old.status==='released'||old.status==='disputed')return json({error:'Claim is unavailable or disputed.'},409);
|
||||
+ if(!context.admin&&!context.authorizedAllianceIds.includes(old.allianceId))return json({error:'Stronghold management permission required.'},403);
|
||||
+ if(!snapshot.alliances.some(a=>a.registryId===b.targetAllianceId)||old.allianceId===b.targetAllianceId)return json({error:'Choose an existing other alliance.'},400);
|
||||
+ if(b.revision!==state.revision)return json({error:'Claim changed. Refresh.'},409);
|
||||
+ next=structuredClone(state);next.revision++;next.claims.find(c=>c.id===old.id).transferOffer={targetAllianceId:b.targetAllianceId,approvedBy:user.id,revision:next.revision};
|
||||
+ }else if(b.action==='transfer'){
|
||||
+ if(!context.admin){
|
||||
+ if(!old?.transferOffer||old.transferOffer.targetAllianceId!==b.targetAllianceId||old.transferOffer.revision!==state.revision||!context.authorizedAllianceIds.includes(b.targetAllianceId))return json({error:'Current source approval and target leadership acceptance are required.'},403);
|
||||
+ // Source authority must still exist at acceptance time.
|
||||
+ const sourceUser=await env.DB.prepare('SELECT id,role FROM portal_users WHERE id=?').bind(old.transferOffer.approvedBy).first();
|
||||
+ const source=snapshot.alliances.find(a=>a.registryId===old.allianceId);
|
||||
+ if(!sourceUser||!shCanManage(sourceUser,source,snapshot.directory))return json({error:'Source approval is no longer authorised.'},403);
|
||||
+ context.authorizedAllianceIds.push(old.allianceId);
|
||||
+ }
|
||||
+ // Existing asset transfers need a separately reviewed ownership/cost migration.
|
||||
+ if(old?.assetRefs.length)return json({error:'Existing structures or build reservations require an explicit asset transfer plan.'},409);
|
||||
+ next=StrongholdPolicy.transferStronghold(state,{...command,targetAllianceId:b.targetAllianceId},context);
|
||||
+ delete next.claims.find(c=>c.id===old.id).transferOffer;
|
||||
+ }else if(b.action==='dispute')next=StrongholdPolicy.markDisputed(state,{expectedRevision:b.revision,claimIds:b.claimIds,reason:b.reason},context);
|
||||
+ else if(b.action==='resolve')next=StrongholdPolicy.resolveConflict(state,{expectedRevision:b.revision,winnerClaimId:b.winnerClaimId,winnerStatus:b.winnerStatus},context);
|
||||
+ else return json({error:'Unknown stronghold action.'},400);
|
||||
+ const projected=shProject(snapshot.alliances,next);
|
||||
+ // Retain old move penalty; never move member planets or change membership.
|
||||
+ for(const a of projected){
|
||||
+ const previous=snapshot.alliances.find(x=>x.registryId===a.registryId);
|
||||
+ if(a.fortress.strongholdGalaxy&&a.fortress.strongholdGalaxy!==previous.fortress?.strongholdGalaxy){
|
||||
+ const ticks=snapshot.directory.filter(r=>r.kind==='planet'&&JSON.parse(r.data_json).alliance===a.name).map(r=>JSON.parse(r.data_json).publicTick||1);
|
||||
+ const tick=Math.max(1,...ticks),hours=Number(DEFAULT_ROUND.config?.tickHours)||1;
|
||||
+ a.fortress.lastDistorterTick=tick;
|
||||
+ if(tick>1){a.fortress.anarchyUntilTick=tick+Math.ceil(24/hours)-1;a.fortress.anarchyEnded=false;}
|
||||
+ }
|
||||
+ }
|
||||
+ const op=crypto.randomUUID(),guard='EXISTS(SELECT 1 FROM planet_directory_meta WHERE id=1 AND operation_id=?)';
|
||||
+ // Snapshot predicates protect permissions/legacy data even against older writers that omit revision bumps.
|
||||
+ const predicates=['id=1','revision=?','COALESCE(reset_generation,0)=?','(SELECT COUNT(*) FROM planet_alliances)=?'];
|
||||
+ const args=[op,b.revision,generation,snapshot.rows.length];
|
||||
+ for(const row of snapshot.rows){predicates.push('EXISTS(SELECT 1 FROM planet_alliances WHERE name=? AND data_json=?)');args.push(row.name,row.data_json);}
|
||||
+ for(const row of snapshot.directory.filter(r=>r.owner_id===user.id||r.kind==='structure')){predicates.push('EXISTS(SELECT 1 FROM planet_directory WHERE id=? AND data_json=? AND COALESCE(owner_id,\'\')=?)');args.push(row.id,row.data_json,row.owner_id||'');}
|
||||
+ const response={ok:true,revision:b.revision+1,generation};
|
||||
+ const statements=[env.DB.prepare('UPDATE planet_directory_meta SET revision=revision+1,operation_id=? WHERE '+predicates.join(' AND ')).bind(...args),env.DB.prepare(`INSERT INTO stronghold_states(generation,data_json) SELECT ?,? WHERE ${guard} ON CONFLICT(generation) DO UPDATE SET data_json=excluded.data_json`).bind(generation,JSON.stringify(next),op),env.DB.prepare(`DELETE FROM stronghold_claims WHERE generation=? AND ${guard}`).bind(generation,op)];
|
||||
+ for(const c of next.claims)statements.push(env.DB.prepare(`INSERT INTO stronghold_claims(generation,id,galaxy,alliance_id,status) SELECT ?,?,?,?,? WHERE ${guard}`).bind(generation,c.id,c.galaxy,c.allianceId,c.status,op));
|
||||
+ for(const a of projected){
|
||||
+ statements.push(env.DB.prepare(`UPDATE planet_alliances SET data_json=?,updated_at=? WHERE name=? AND ${guard}`).bind(JSON.stringify(a),Date.now(),a.name,op));
|
||||
+ statements.push(env.DB.prepare(`INSERT INTO alliance_registry(name_key,alliance_id,name,attributes_json,created_by,updated_at) SELECT ?,?,?,?,?,? WHERE ${guard} ON CONFLICT(name_key) DO NOTHING`).bind(a.name.toLowerCase(),a.registryId,a.name,JSON.stringify(allianceAttributes(a)),user.id,Date.now(),op));
|
||||
+ }
|
||||
+ statements.push(env.DB.prepare(`INSERT INTO stronghold_operations SELECT ?,?,?,? WHERE ${guard}`).bind(b.operationId,user.id,raw,JSON.stringify(response),op),env.DB.prepare(`INSERT INTO stronghold_audit SELECT ?,?,?,?,?,? WHERE ${guard}`).bind(op,generation,user.id,b.action,JSON.stringify({claimId:b.claimId||null,reason:b.reason||'',revision:next.revision}),Date.now(),op));
|
||||
+ const results=await env.DB.batch(statements);
|
||||
+ if((results[0].meta?.changes??results[0].changes)!==1)return json({error:'Directory or permissions changed. Refresh before retrying.'},409);
|
||||
+ return json(response);
|
||||
+ }catch(error){
|
||||
+ if(error instanceof StrongholdPolicy.PolicyError)return json({error:error.code==='CONFLICT'?'This galaxy or alliance already has a reserved or disputed stronghold.':error.message,code:error.code},error.code==='FORBIDDEN'?403:error.code==='NOT_FOUND'?404:error.code==='INVALID'?400:409);
|
||||
+ if(error instanceof SyntaxError)return json({error:'Invalid JSON.'},400);
|
||||
+ // A unique index failure rolls the entire D1 batch back.
|
||||
+ if(/UNIQUE constraint/i.test(error.message))return json({error:'Galaxy or alliance was claimed concurrently. Refresh.'},409);
|
||||
+ throw error;
|
||||
+ }
|
||||
+}
|
||||
12
proposals/starfall-stronghold-integration/manifest.json
Normal file
12
proposals/starfall-stronghold-integration/manifest.json
Normal file
|
|
@ -0,0 +1,12 @@
|
|||
{
|
||||
"ticket": "DUNE-014",
|
||||
"upstreamTicket": "SF-049",
|
||||
"upstreamGroup": "G011",
|
||||
"base": "a33136f55ff4ce06ad93f9768578b08c42ebce49",
|
||||
"isolatedCommit": "2a8efcb5818e3381bc58b6acc3b03298d6a08461",
|
||||
"patchSha256": "930b88a703a25e8a6967a7fa230e084fdf0b9ce62db8f646fc1c4e268325f280",
|
||||
"testsPassed": 234,
|
||||
"auditPages": 100,
|
||||
"auditFindings": 0,
|
||||
"deployed": false
|
||||
}
|
||||
Loading…
Reference in a new issue

Staff