Add default-off private API v1 read foundation and migration contracts
This commit is contained in:
parent
6e0f02e19a
commit
f787da9653
10 changed files with 2019 additions and 0 deletions
50
website/api/INVENTORY.md
Normal file
50
website/api/INVENTORY.md
Normal file
|
|
@ -0,0 +1,50 @@
|
|||
# Endpoint and integration inventory
|
||||
|
||||
Inspected 30 October 2026. Source evidence is MC main `6e0f02e19ab88e32ade31d018e6362dbc07bb117`. Other visible branches: `beta`, `cloudpanel-node`, `exchange-completion`, `feature/organic-arrakis-plateaus`. Their trees did not contain the observed banking/quest/kit-market modules. Existing inventory-sharing work is preserved in `unimatrix/MC-inventory-sharing`. A3 and PA are separate projects, not selected API hosts; dune-installer is deployment tooling.
|
||||
|
||||
## Source-confirmed website/control-panel routes
|
||||
|
||||
| Routes | Authentication and authorization | Ownership / reusable implementation |
|
||||
| --- | --- | --- |
|
||||
| `/api/auth/session` GET; `/api/auth/login`, `/register`, `/logout`, `/password` POST | Session cookie SHA-256 lookup and expiry; POST origin check; password scrypt, login limits; registration defaults user | MySQL `site_accounts`, `site_sessions`; `node/auth.mjs` |
|
||||
| `/api/game-link` GET/POST, `/api/game-link/unlink` POST | Session; panel menu gate; origin and cooldown for browser writes | MySQL `site_game_links`, `site_link_challenges`, `site_game_identities`; `node/game-link.mjs` |
|
||||
| `/api/game-link/consume` POST | Private game bearer secret; only the native player command supplies authenticated player UUID | Atomic challenge/link batch, unique account and UUID, 10-minute challenge, persistent first-link identity |
|
||||
| `/api/community/campaigns` GET; campaign/verify-total POST | Public campaign projection; `cp.community.manage` plus origin for staff mutations | MySQL campaigns and `account_audit`; `node/community-rewards.mjs` |
|
||||
| `/api/community/rewards` GET | Session and panel menu check, linked UUID derived server-side | **Has issuance side effects**: creates earned personal codes. Must not be wrapped as a read-only v1 operation |
|
||||
| `/api/community/game/prepare`, `/ack` POST | Private game bearer, validated UUID/code or receipt | MySQL claims unique UUID/month and immutable receipt; prepare replay returns same claim; ack repeat accepted |
|
||||
| `/api/inventory` GET | Session, panel menu, no query; account-derived verified UUID | PostgreSQL `dune_players.inventory_view` snapshot; `control-panel/inventory/inventory-api.mjs` |
|
||||
| `/api/exchange/sales-history?before=…` GET | Session, panel menu; account-derived seller UUID | PostgreSQL native immutable sales IDs, 20 rows plus lookahead; same inventory API module |
|
||||
| `/internal/exchange/listings` GET | Separate constant-time exchange read bearer; no caller parameters | Read-only PostgreSQL listings projection, latest 500; `market-bridge.mjs` |
|
||||
| `/api/exchange/listings` GET | Public gateway, server-only configured upstream token | Worker `exchange-api.mjs`; sanitized projection but converts IDs/prices to Number; v1 reuses bridge directly to preserve precision |
|
||||
| `/api/worlds` GET | Public, fixed operator monitor destination | `node/world-status.mjs`; 15-second cache, 4.5-second timeout, 60-second freshness, honest unknown |
|
||||
| `/api/ranks`, `/api/ranks/create`, `/permissions`, `/assign` | Session, `cp.ranks.manage`, grant ceiling/protected owner/version checks; POST origin | MySQL `cp_ranks` and account role; `node/rank-admin.mjs` |
|
||||
| `/api/game/permissions` GET | Game bearer, no query | Website-managed game node projection and verified memberships; not browser service tokens |
|
||||
| `/api/admin/*`, `/api/servers/*`, `/api/staff/manual` | Existing server-side account, server-control and manual handlers | Preserve untouched; operational logs/console/power are privileged, not v1 public-status reads |
|
||||
| Website `/api/profile`, forums and tickets | Existing Node identity adapter into Worker; ownership/staff checks in Worker | MySQL profiles/forum/support tables; not migrated in this increment |
|
||||
|
||||
The legacy permission resolver only models one account role and registered effective nodes. Some menu gates exist in addition to action permissions. Menu visibility is not sufficient for new operations. The existing Node host also translates a website account-view permission into an internal staff identity consumed by forums/support; do not reuse that bridge as proof of appeal approval or network administration.
|
||||
|
||||
## Native game contracts verified in source
|
||||
|
||||
- `DuneEss/CommunityCodes.java` gets UUID from the actual Bukkit Player, never a website/browser UUID. Linking consumes a challenge over the private service channel. Community redemption prepares remotely, invokes native `grantCommunity`, then acknowledges.
|
||||
- `DuneEss/DuneEconomy.java` owns Vault balances. PostgreSQL mode uses `dune_economy_balances`; a shared-mode failure must not create a second local wallet. Local mode persists `balances.yml`. Website code must not update either ledger.
|
||||
- `grantCommunity` deduplicates by UUID/month and checks immutable receipt **and amount**. PostgreSQL claim insertion and balance credit share one transaction. Local mode writes the ledger and balance together through a temporary snapshot before updating memory. Pending acknowledgements persist and retry; a lost HTTP ack does not authorize a second credit. Existing `CommunityLedgerTest` covers restart, duplicate/mismatched receipt, failed durable write and incomplete shared config. Those Java tests were inspected, not executed here.
|
||||
- `DuneEss/ExchangeStore.java` uses listing row locks, conditional wallet debit, seller credit, stock consumption and a sale reference in one PostgreSQL transaction. Core profile session ownership and Bukkit inventory work remain with the native game. There is no demonstrated external purchase idempotency contract, so no v1 buy wrapper is enabled.
|
||||
- `network/database/README.md` documents single-backend profile ownership and transfer/recovery limitations. Do not make website writes around these leases or concurrently overwrite active inventories.
|
||||
|
||||
## Live-only browser evidence — backend contracts unverified
|
||||
|
||||
The live control panel exposes modules absent from every inspected branch. See `live-consumer-inventory.json` for public browser-code evidence. Browser labels/calls do not prove authorization, table ownership or atomicity.
|
||||
|
||||
| Consumer / observed route family | Evidence / unresolved contract |
|
||||
| --- | --- |
|
||||
| `banking.mjs`, `/api/bank/*` | Native bank UI; require deployed backend, permissions, locks, immutable references and failure/retry rules |
|
||||
| `quests.mjs`, `/api/quests`, `/api/quests/admin`, `/api/quests/admin/definitions` | Player and administrative quest views; versioned definitions; require native quest/reward ownership and event deduplication |
|
||||
| `quest-rewards.mjs`, `/api/quest/rewards` | Reward UI; require issuance/credit/delivery ledger and recovery contract |
|
||||
| `kit-market.mjs`, `/api/kits/*` | Catalogue/orders/redemption calls; UI says code belongs to purchasing UUID, delivery is queued and native-confirmed; seller proceeds 85% / server bank 15% is a UI claim pending backend verification |
|
||||
| `clan-shop.mjs`, `/api/clans/shop`, `/api/clans/shop/price` | Clan designs and bank display; UI officer/owner and pricing controls need backend review |
|
||||
| `imperial-atelier.mjs`, `/api/imperial-atelier` | Office/term/version-sensitive designs; edits must not create repeat kit claims |
|
||||
| `game-ranks.mjs`, `/api/ranks/game`; `luckperms.mjs`, `/api/luckperms/*` | Separate game groups, editor/apply functions; explicit support/appeals separation appears in UI; verify action checks and domain/department/server grants in deployed backend |
|
||||
| Website perks / shop/order integration | Exact deployed source, approval policy, entitlement grant/revoke records and ownership are unresolved; never model these as a native wallet or generic console command |
|
||||
|
||||
Central apidev session was authenticated with rank `user`; DuneGit identity provisioned, zero owned repos before forking, no Git administration. No UUID was linked and no staff/financial/reward actions were tested in production. Only public source, account session and Git workspace metadata were read. No production database access was used.
|
||||
38
website/api/MIGRATION.md
Normal file
38
website/api/MIGRATION.md
Normal file
|
|
@ -0,0 +1,38 @@
|
|||
# Architecture and incremental migration
|
||||
|
||||
## Boundary
|
||||
|
||||
Browser → central website session → same-origin `/api/v1` on control panel → existing identity/permission/link services → narrow native-service adapters. MySQL remains authoritative for website accounts, verified links and website-owned records. Native services remain authoritative for balances, inventory, kit eligibility, game quest progress, charges and delivery. No new wallet, generic console proxy, account privilege, broad service token or alternate UUID-proof mechanism is introduced.
|
||||
|
||||
Initial code is additive in `node/api-v1.mjs`, mounted before legacy dispatch in `control-panel/server.mjs`, behind `API_V1_ENABLED`. Existing handlers and consumers are unchanged. This stage deliberately does not wrap side-effecting legacy rewards GET or unknown live-only handlers.
|
||||
|
||||
## Permission design for subsequent stages
|
||||
|
||||
Obtain the deployed central resolver before extending scope. Use explicit action grants with domain `Website`, `Community`, `Minecraft` or `Network`, plus applicable department and server. Resolve these server-side on every operation; fail closed when scope, verified identity or resolver state is missing. A Website Support grant does not grant Community appeal approval, Minecraft ban management or Network administration. Do not translate rank level, `staff:true`, menu visibility, profile names, a submitted UUID or a stale frontend permission snapshot into authorization.
|
||||
|
||||
For each migrated endpoint record: action permission, domain, department/server context, verified-account ownership, native service permission and whether step-up/owner approval is required. Require review by the permission owner and affected maintainer. Scope-aware privileged endpoints are **deferred**, not provided by the legacy effective-node response. No role-boundary changes may be bundled into API rollout.
|
||||
|
||||
## Order and acceptance gates
|
||||
|
||||
1. **Inventory and reconcile.** Owner/website/Minecraft maintainers confirm deployed commit, uncommitted source and release differences in [coordination issue #2](https://www.dunerealms.com/git/unimatrix/MC/issues/2). Capture server contracts and table ownership without exporting secrets or production player data. Preserve all existing branches and the inventory-sharing fork.
|
||||
2. **Read-only foundation (this increment).** Review OpenAPI, session-only authentication, self ownership, validation, errors, rate budget, correlation and restricted audit collection. Exercise the toggle and rollback in isolated staging. Confirm account, linking, permissions, honest status and native exchange catalogue end to end. Missing bridge configuration returns 503, never demo balances/catalogues.
|
||||
3. **Scoped authorization and native read expansion.** Integrate the deployed role resolver with explicit Website/Community/Minecraft/Network and department/server decisions. Add read adapters for bank, quests, kits and orders only after ownership and native snapshot contracts are known. Keep website entitlement catalogues separate from native game goods. Add independent OpenAPI schemas and contract tests.
|
||||
4. **One mutation at a time.** Prioritize a narrow established native operation. Preserve its transaction boundary and native immutable reference; do not implement balance edits in Node. Test in isolated services before enabling behind an operation-specific flag. Owner and service maintainer approve semantics and recovery.
|
||||
5. **Consumer migration.** Introduce one consumer adapter at a time, compare sanitized read results in staging, then canary with owner-coordinated traffic. Never double-submit a mutation to old and new routes. Keep old request/response shapes working until callers have explicitly migrated. Record usage and agreed deprecation windows before retirement.
|
||||
|
||||
## Mutation contract required before enablement
|
||||
|
||||
- Bind idempotency to authenticated principal, verified UUID, operation, domain/scope and canonical payload hash. Same key/different payload must be 409; same operation/key must retrieve its durable native reference and state. A timeout is unknown outcome, not permission to create a new transaction.
|
||||
- Have the authoritative native owner atomically persist idempotency/reference, conditional debit or reward eligibility, state transition and durable delivery/outbox entry. Use unique constraints and locking/CAS suitable for multi-process concurrency. A Node-only in-memory deduplication map is insufficient.
|
||||
- Service authentication must be independently scoped by service/action/server, private transport, bounded timestamp/nonce or equivalent durable replay prevention, rotation and revocation. Do not pass browser Authorization through or disclose tokens in errors. Preserve the existing game channel until maintainers verify its replacement; do not call it complete replay protection for every future operation.
|
||||
- Model states such as accepted → charged/earned → delivery-pending → delivered and retryable/terminal failures using the actual existing contract. Only native confirmation marks delivery. Preserve receipts through restart and requeue an acknowledgement using the same reference. Do not refund/recredit blindly after a timeout.
|
||||
- Website perks grant only approved permission entitlements with their own approval/revocation audit; in-game purchases retain native redemption and item delivery. A website perk order must not directly credit funds or issue a game item.
|
||||
- Privileged action audits must include principal, explicit permission/scope, target, correlation ID, immutable native reference and outcome, with durable integrity/retention controls. Exclude secret codes and tokens. Pair audit/outbox with mutations so failure cannot silently lose accountability.
|
||||
|
||||
## Required isolated integration scenarios
|
||||
|
||||
Run with independent fixture MySQL/PostgreSQL and native service instances, plus Paper/Velocity staging where applicable. Include anonymous/expired/service-auth rejection; cross-account order/code access; caller UUID spoofing and relink races; department/server mismatch; support denied appeal approval/admin access; duplicate and changed-payload keys; concurrent debits/claims/stock buys; failure before commit, after commit before HTTP response, during native inventory delivery and before/after ack; restart and service outage recovery; rollback with pending deliveries preserved. Assert authoritative balances, stock, receipts and delivery counts, not only HTTP status. Existing Java ledger tests are reusable but do not validate the new website-to-game deployment.
|
||||
|
||||
## Current gaps / dependencies
|
||||
|
||||
Deployed source and scoped permission backend are missing from accessible branches. Banking, current quests, kit market, perks, orders and redemption transaction contracts remain unverified. Maintainer response and isolated environment are pending. This initial stage has fixture integration coverage, not live MySQL/PostgreSQL/Paper/Velocity verification. Legacy routes are retained; no consumers, financial flows, rewards, role definitions, live data or deployments have been changed. Read-only catalogue pagination is bounded by the old bridge's 500 rows; improve that native read contract before claiming full catalogue enumeration.
|
||||
30
website/api/OPERATIONS.md
Normal file
30
website/api/OPERATIONS.md
Normal file
|
|
@ -0,0 +1,30 @@
|
|||
# Deployment and rollback runbook
|
||||
|
||||
**Do not deploy this historical main snapshot over production.** The live panel has newer integrations and a different permission model absent here. Reconcile/cherry-pick the additive changes into the authoritative deployed source with website and Minecraft maintainers first. The API is not deployed by this work.
|
||||
|
||||
## Preparation
|
||||
|
||||
1. Owner confirms maintenance contact, affected maintainers, deployment source/revision and isolated staging. Record current website/control-panel releases, process names, reverse-proxy configuration and rollback targets privately. Do not copy environment secrets into the repository or tickets.
|
||||
2. Review the small code delta: one new module and a panel import/mount, documentation and tests. It needs no DDL, role grants, native balance writes, game binary changes or new ports. Reconcile import paths and the central resolver against the deployed version. Keep native transaction/delivery handlers unchanged.
|
||||
3. Install the existing locked dependencies in a new immutable release directory. Use the host's supported Node version and run the documented tests plus deployed-source regressions. Preserve the existing website build/release process; this API mounts only on the control panel, not on the public Node website host.
|
||||
4. Stage with `API_V1_ENABLED` absent/false, then explicitly true. Reuse the server-owned `EXCHANGE_LISTINGS_URL` and separate `EXCHANGE_READ_TOKEN` only if the maintainer verifies the exact existing bridge contract. Configure `WORLD_STATUS_URL` using the existing monitor. Missing sources intentionally fail closed/unknown. Never expose private environment values in browser configuration or logs.
|
||||
5. Verify restricted durable collection/retention of structured request events, limiter sizing and multi-process edge controls. The included limiter is single-process and resets on restart; a production shared limiter is an operator dependency for scaled rollout.
|
||||
|
||||
## Staging acceptance
|
||||
|
||||
Verify default disabled 404, unauthenticated 401, central ordinary test-account login, own verified link (or unlinked), own effective nodes, unknown vs fresh status, real isolated catalogue, pagination, exact decimals and sanitized outages. Confirm no cross-origin CORS or ownership overrides. Confirm old login, account, inventory, quests, kits, banks, orders/redemption and service bridges continue unchanged using fixtures for writes. Test support/appeals separation against the actual deployed resolver. Do not grant apidev staff, link another player's UUID, spend production funds or create production rewards.
|
||||
|
||||
Record versions and evidence for both service ends. Local tests and HTTP 200 alone do not establish native integration completion. The old community reward GET can issue codes: avoid it in production smoke tests.
|
||||
|
||||
## Owner-coordinated release
|
||||
|
||||
Use the existing release-directory and atomic current-link procedure after owner/maintainer agreement. First deploy with v1 disabled and verify legacy health/sign-in. Enable v1 for the agreed canary using the host's environment/restart procedure. Smoke-test only ordinary account/status reads in production; verify catalogue against staging/native read evidence. Watch latency, error rates, 429s and audit collection. Record the deployed commit and exact prior release. No old routes are retired in this increment.
|
||||
|
||||
## Rollback
|
||||
|
||||
1. Disable `API_V1_ENABLED` and restart/reload the existing control-panel process through its established procedure. Verify `/api/v1/me` now returns 404 while legacy session and health routes still work.
|
||||
2. If the panel is unhealthy, atomically restore the recorded previous control-panel release/current-link and its previous environment, then restart that process. Restore proxy changes only if any were separately introduced during approved rollout; this patch requires none.
|
||||
3. Verify central login, existing inventory/status and native service health. Avoid reward/code issuance or financial smoke tests. Check audit/monitoring for recovery.
|
||||
4. No data rollback, balance rewrite, receipt deletion, schema downgrade or reward reversal is needed or permitted for this read increment. Preserve native pending acknowledgements and delivery queues during any future mutation rollback. Do not delete accounts, links or immutable references.
|
||||
|
||||
If the additive source has not been deployed, rollback simply means leave the toggle disabled. The fork and local changes do not affect production services.
|
||||
49
website/api/README.md
Normal file
49
website/api/README.md
Normal file
|
|
@ -0,0 +1,49 @@
|
|||
# DuneRealms API v1 — initial read increment
|
||||
|
||||
Status: implemented against MC main `6e0f02e19ab88e32ade31d018e6362dbc07bb117`; **not deployed**. Canonical proposed mount: `https://cp.dunerealms.com/api/v1`. Toggle `API_V1_ENABLED=true` explicitly enables it. No schema migration or game binary change is required. The default is disabled.
|
||||
|
||||
- [OpenAPI 3.1 contract](openapi-v1.json)
|
||||
- [Endpoint and integration inventory](INVENTORY.md)
|
||||
- [Architecture and migration](MIGRATION.md)
|
||||
- [Deployment and rollback](OPERATIONS.md)
|
||||
- [Observed live consumer evidence](live-consumer-inventory.json)
|
||||
- [Maintainer coordination](https://www.dunerealms.com/git/unimatrix/MC/issues/2)
|
||||
|
||||
## Implemented requests
|
||||
|
||||
All five endpoints require the existing central website session. Sign in through the current website; this API does not receive passwords, mint independent identities or accept internal service tokens. Use same-origin browser requests with the existing HttpOnly cookie. No CORS access is granted. Ownership selectors and unknown/duplicate query parameters are rejected.
|
||||
|
||||
| GET endpoint | Data |
|
||||
| --- | --- |
|
||||
| `/api/v1/me` | Own account ID, username and display name |
|
||||
| `/api/v1/me/minecraft` | Own verified link joined to the persistent game identity; otherwise `linked:false` |
|
||||
| `/api/v1/me/permissions` | Existing effective permission nodes; informational, not a credential |
|
||||
| `/api/v1/servers` | Public world-status projection, with unavailable/stale checks represented as unknown |
|
||||
| `/api/v1/catalogue?limit=20&before=123` | Existing native exchange listings; excludes kits and website perks |
|
||||
|
||||
Example success: `{"data":{"id":"fixture-account","username":"example","displayName":"Example"},"meta":{"requestId":"server-generated-uuid"}}`.
|
||||
|
||||
Example failure: `{"error":{"code":"unauthenticated","message":"Sign in through the central website.","requestId":"server-generated-uuid"}}` with status 401. Other statuses: 400 invalid query, 403 cross-origin/unsupported authorization, 404 unknown/disabled, 405 unsupported method, 429 throttled, 503 unavailable dependency/audit. Every response is private/no-store and correlated by `X-Request-ID`. The OpenAPI document specifies exact shapes.
|
||||
|
||||
Catalogue IDs and prices remain strings. Follow `pagination.nextCursor` as `before`; default limit 20, maximum 100. Native listings remain mutable, so paging is a live view, not a snapshot. The old bridge exposes only its latest 500 rows: `sourceLimited:true` signals reaching that cap. Do not treat this as a complete catalogue export. No currency conversion, debit or delivery occurs.
|
||||
|
||||
## Security and limits
|
||||
|
||||
Session lookup and permission resolution reuse `node/auth.mjs` and `node/permissions.mjs`. No role definitions, rank assignments, linking challenges, rewards or transaction ledgers are changed. A stored link without the verified identity record is not exposed as verified. Caller UUID, account and scope overrides are rejected. The API has no administrative endpoints, so support access cannot imply appeal approval or administration through v1.
|
||||
|
||||
The initial permission response explicitly says `legacy-effective-nodes`: main lacks the deployed Website/Community/Minecraft/Network and department/server scope model. This is an unresolved deployment dependency, not a substitute scoped policy. Do not use this output to authorize future privileged operations.
|
||||
|
||||
The existing private read bridge is called only from the server using `EXCHANGE_LISTINGS_URL` and `EXCHANGE_READ_TOKEN`. HTTPS, no redirects, timeout, bounded payload, strict response projection and exact decimal validation apply. The fixed configured URL is never caller-controlled. Tokens, bodies, cookies and query values do not enter request audit events. Browser responses contain only allowlisted fields. Existing game bridge service authentication stays in place unchanged.
|
||||
|
||||
Conservative fixed-window limit: 120 requests per process globally and 120 per account per minute; 5,000 maximum buckets, no trusted client IP headers. This deliberately low single-process budget is for the initial staged increment. Agree deployment capacity and shared edge/account limiting before multi-instance rollout; restarting resets the in-memory limiter. Failed audit writes fail the v1 request closed. Default request events go to structured process output; operators must configure restricted durable collection and retention. No new privileged actions exist in this increment; later mutations require transactional privileged audit/outbox records before enablement.
|
||||
|
||||
## Validation
|
||||
|
||||
Use Node 22+ with SQLite support (validated with Node 24), then from `website/`:
|
||||
|
||||
```sh
|
||||
pnpm install --frozen-lockfile --ignore-scripts
|
||||
node --test tests/api-v1.test.mjs tests/account-inventory.test.mjs tests/rank-permissions.test.mjs tests/world-status.test.mjs
|
||||
```
|
||||
|
||||
Tests use isolated SQLite fixtures with real session lookup, verified-link queries, existing permission resolver and the panel router, plus an injected native bridge. They cover expiry, forged headers, cross-account and UUID overrides, support boundaries, pagination, precision, sanitized errors, failure recovery, duplicate/concurrent reads, mutation rejection, rate-window recovery, auditing and old-route compatibility. Financial/delivery concurrency and crash recovery are **not** proven by read-only tests; existing native tests and new isolated service integration tests are required before migrating mutations.
|
||||
26
website/api/REPORT.md
Normal file
26
website/api/REPORT.md
Normal file
|
|
@ -0,0 +1,26 @@
|
|||
# Delivery report — 30 October 2026
|
||||
|
||||
## Completed
|
||||
|
||||
- Signed in through central website authentication and DuneGit SSO as the ordinary `apidev` account. Confirmed its provisioned Git identity and absence of Git administrative access. No credentials were written to project files, commits or documentation.
|
||||
- Inspected visible repositories and branches; selected `unimatrix/MC` because it owns both website/control-panel and native game source. Forked it into `apidev/MC`, preserving upstream history and existing inventory-sharing work.
|
||||
- Posted the source-reconciliation and transaction-contract review request to owner/maintainers in [MC issue #2](https://www.dunerealms.com/git/unimatrix/MC/issues/2). A response/approval is pending; posting a request does not mean maintainers have confirmed it.
|
||||
- Documented source-confirmed routes, authentication, permissions, database ownership, native economy/community transaction contracts and separately labeled live-only consumer evidence.
|
||||
- Implemented a default-off additive session-authenticated `/api/v1` read API for own account, verified Minecraft identity, own effective permissions, sanitized server status and the existing native exchange catalogue. Old routes and consumers remain unchanged.
|
||||
- Added OpenAPI 3.1 request/response/error/pagination definitions, integration tests, migration gates and deployment/rollback instructions.
|
||||
|
||||
## Verification
|
||||
|
||||
29 tests pass: 13 new API tests and 16 existing account-panel, inventory, rank/permission and world-status tests. Run with Node 24.22.1 and the repository's locked dependency versions. Fixtures use real session lookup, SQL link ownership, existing permission resolver and the actual panel router; the native bridge is injected. Coverage includes unauthorized/expired sessions, forged identity, cross-account/UUID overrides, support boundary preservation, duplicate/concurrent reads, rejected mutations, dependency/audit failure recovery, rate limits, exact prices, malformed/oversized native responses, bounded paging and old-route compatibility. `git diff --check` is also part of pre-commit verification.
|
||||
|
||||
No MySQL/PostgreSQL production database was queried directly. Java ledger tests were inspected but not run. No native financial/delivery, Paper/Velocity or new v1 production end-to-end verification has occurred. Full website/build-wide validation was not claimed; this is a targeted additive panel change.
|
||||
|
||||
## Remaining dependencies
|
||||
|
||||
1. Owner/maintainers must identify the actual deployed source. Live banking, quest, kit and permission modules are absent from inspected repository branches. Do not deploy historical main over newer production work.
|
||||
2. Integrate the deployed scoped permission model before privileged API operations. The initial self-permission view explicitly reports legacy effective nodes and grants no new permissions.
|
||||
3. Confirm native bank, quest, kit, shop/order/redemption and website-perk contracts, service authentication, atomicity, durable deduplication, replay protection and recovery. No such mutations were implemented speculatively.
|
||||
4. Provide isolated services and game staging, validate both sides end to end, configure durable audit retention and production limiter capacity, then coordinate canary deployment and rollback with the owner/maintainers.
|
||||
5. Migrate consumers incrementally only after compatibility verification. No legacy routes have been retired.
|
||||
|
||||
Production account privileges, UUID links, funds, balances, rewards, deliveries, services and data are unchanged. The apidev test account remains ordinary and can be reused for future authorized testing. The fork contains the initial implementation, not a claim that all requested integrations are finished.
|
||||
122
website/api/live-consumer-inventory.json
Normal file
122
website/api/live-consumer-inventory.json
Normal file
|
|
@ -0,0 +1,122 @@
|
|||
{
|
||||
"observedAt": "2026-10-30",
|
||||
"evidenceLevel": "Public browser code only; backend authorization and transactional behavior not inferred.",
|
||||
"modules": [
|
||||
{
|
||||
"file": "https://cp.dunerealms.com/banking.mjs",
|
||||
"status": 200,
|
||||
"observedPaths": [
|
||||
"/api/bank/",
|
||||
"/api/auth/session"
|
||||
],
|
||||
"contractEvidence": [
|
||||
"for(const[id,title]of [['personal-bank','Personal bank'],['staff-bank','Staff bank']]){const section=el('section');section.id=id;section.hidden=true;section.className='bank-workspace';const header=el('header'),seal=el('img');seal.src='https://www.dunerealms.com/assets/'+(id==='staff-bank'?'imperial-seal-128.png':'dunemark-icon-64.png');seal.alt='';const copy=el('div');copy.append(el('p',id==='staff-bank'?'THE SERVER TREASURY':'YOUR DUNEMARKS VAULT'),el('h2',title),el('p',id==='staff-bank'?'One central account for authorised server staff.':'Your personal savings, separate from your spending wallet.'));header.append(seal,copy);const status=el('p');status.role='status';const refresh=el('button','Refresh bank');refresh.type='button';refresh.onclick=()=>load(id);const content=el('div');section.append(header,el('p','* A linked Minecraft UUID is required. Bank access follows your linked in-game identity.'),refresh,status,content);dashboard?.append(section);const a=el('a',title+' *');a.href='#",
|
||||
"async function load(id){const v=views[id],staff=id==='staff-bank',g=generation,s=++v.serial;if(!actor||!permissions.includes(staff?'web.bank.staff.view':'web.bank.personal.view'))return;v.refresh.disabled=true;v.status.textContent='Checking the bank…';try{const r=await fetch('/api/bank/'+(staff?'staff':'personal'),{cache:'no-store'}),d=await r.json();if(!r.ok)throw Error(d.message||'Bank unavailable.');if(g!==generation||s!==v.serial)return;v.content.replaceChildren();if(d.linked===false){const link=el('a','Link your Minecraft identity');link.href='#game';v.content.append(el('p','A verified Minecraft identity is needed to access this bank.'),link);v.status.textContent='';return;}",
|
||||
"window.addEventListener('dune:session',e=>session(e.detail));window.addEventListener('dune:page',e=>{if(views[e.detail?.page])load(e.detail.page);});window.addEventListener('hashchange',()=>{if(views[location.hash.slice(1)])load(location.hash.slice(1));});const g=generation;try{const r=await fetch('/api/auth/session',{cache:'no-store'});if(r.ok){const d=await r.json();if(g===generation)session(d.user);}}catch{}"
|
||||
]
|
||||
},
|
||||
{
|
||||
"file": "https://cp.dunerealms.com/quests.mjs",
|
||||
"status": 200,
|
||||
"observedPaths": [
|
||||
"/api/quests/admin/definitions",
|
||||
"/api/quests/admin",
|
||||
"/api/quests",
|
||||
"/api/auth/session"
|
||||
],
|
||||
"contractEvidence": [
|
||||
"async function api(path,body){const r=await fetch(path,{method:body?'POST':'GET',cache:'no-store',headers:body?{'Content-Type':'application/json'}:{},...(body?{body:JSON.stringify(body)}:{})});const data=await r.json();if(!r.ok)throw Error(data.message||'Quest engine unavailable.');return data;}",
|
||||
"window.addEventListener('dune:session',e=>session(e.detail));window.addEventListener('dune:page',e=>{if(views[e.detail?.page])load(e.detail.page);});window.addEventListener('hashchange',()=>{if(views[location.hash.slice(1)])load(location.hash.slice(1));});const g=generation;try{const r=await fetch('/api/auth/session',{cache:'no-store'});if(r.ok){const d=await r.json();if(g===generation)session(d.user);}}catch{}"
|
||||
]
|
||||
},
|
||||
{
|
||||
"file": "https://cp.dunerealms.com/quest-rewards.mjs",
|
||||
"status": 200,
|
||||
"observedPaths": [
|
||||
"/api/quest/rewards",
|
||||
"/api/auth/session"
|
||||
],
|
||||
"contractEvidence": [
|
||||
" async function api(path,body,token){"
|
||||
]
|
||||
},
|
||||
{
|
||||
"file": "https://cp.dunerealms.com/kit-market.mjs",
|
||||
"status": 200,
|
||||
"observedPaths": [
|
||||
"/api/kits/",
|
||||
"/api/auth/session"
|
||||
],
|
||||
"contractEvidence": [
|
||||
"export async function kitApi(path,body){const r=await fetch('/api/kits/'+path,{cache:'no-store',...(body?{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(body)}:{})});const d=await r.json();if(!r.ok)throw Error(d.message||'The kit service is unavailable.');return d;}",
|
||||
"function mountCart(section){const owner=actor?.id;if(!owner)throw Error('Sign in first.');const cart=createKitCart({uuid:()=>crypto.randomUUID(),storage:sessionStorage,key:'dune-kit-cart-v1:'+owner});const box=el('aside',undefined,'kit-cart'),status=el('p');status.role='status';section.append(box);function render(){box.replaceChildren(el('h3','Your Kit Cart'),el('p','Pay with Dunemarks. Purchased kits produce private redeem codes; no real-money payment is taken here.'));const snap=cart.snapshot();for(const line of snap.lines){const row=el('div',undefined,'kit-cart-line'),remove=el('button','Remove');remove.type='button';remove.disabled=cart.busy;remove.onclick=()=>{try{cart.remove(line.orderLineId);render();}catch(e){status.textContent=e.message;}};row.append(el('span',line.name+' · '+(line.priceCents/100).toFixed(2)+' DM'),remove);box.append(row);}if(!snap.lines.length)box.append(el('p','Your cart is empty.'));box.append(el('strong','Total: '+(cart.total()/100).toFixed(2)+' DM'));cons",
|
||||
"async function catalogue(){const section=document.getElementById('kits-exchange');if(!actor||!section)return;const g=generation;section.replaceChildren(el('h2','Kit Exchange'),el('p','Loading published kit designs…'));try{const data=await kitApi('catalogue');if(g!==generation)return;section.replaceChildren();const art=el('img');art.className='kit-market-banner';art.src='https://www.dunerealms.com/assets/clan-atelier-v1.webp';art.alt='Clan stillsuit atelier';section.append(art,el('h2','Kit Exchange'),el('p','Published player designs. Personal kit sales pay 15% to the server bank and 85% to the seller. Rarity is cosmetic; native faction armour rules still apply.'));const search=el('input');search.type='search';search.placeholder='Find a kit or designer';search.setAttribute('aria-label','Find a kit or designer');const sort=el('select');sort.setAttribute('aria-label','Sort kit designs');for(const[value,label]of [['sales','Most Sales'],['new','Newest'],['low','Price: Low to High'],['high','",
|
||||
"async function redemption(){if(!actor)return;const host=document.querySelector('#rewards-codes>.commerce-placeholder-note');if(!host)return;const g=generation;host.replaceChildren(el('h3','Redeem Kit Code'),el('p','A kit code belongs to the purchasing Minecraft UUID. Redeeming queues delivery; it does not immediately place armour in your inventory.'));const form=el('form'),label=el('label','Private kit code'),input=el('input');input.placeholder='DRK-…';input.autocomplete='off';input.required=true;input.maxLength=36;label.append(input);const submit=el('button','Queue Kit Delivery');submit.type='submit';const status=el('p');status.role='status';form.append(label,submit,status);host.append(form);form.onsubmit=async e=>{e.preventDefault();submit.disabled=true;try{const d=await kitApi('redeem',{code:input.value.trim().toUpperCase()});if(g!==generation)return;status.textContent=d.status==='delivered'?'This kit has already been delivered.':'Delivery queued. Join a planetary server, choose a p",
|
||||
"function load(){const page=location.hash;if(page==='#kits-exchange')catalogue();if(['#rewards-redeem','#redeem-code'].includes(page))redemption();}",
|
||||
"if(dashboard){const css=el('link');css.rel='stylesheet';css.href='/kit-market.css';document.head.append(css);window.addEventListener('dune:session',e=>{generation++;actor=e.detail;load();});window.addEventListener('dune:page',load);window.addEventListener('hashchange',load);const initial=generation;fetch('/api/auth/session',{cache:'no-store'}).then(r=>r.json()).then(d=>{if(initial===generation){actor=d.user;load();}}).catch(()=>{});}\r"
|
||||
]
|
||||
},
|
||||
{
|
||||
"file": "https://cp.dunerealms.com/clan-shop.mjs",
|
||||
"status": 200,
|
||||
"observedPaths": [
|
||||
"/api/clans/shop",
|
||||
"/api/clans/shop/price",
|
||||
"/api/auth/session"
|
||||
],
|
||||
"contractEvidence": [
|
||||
"async function api(body){const r=await fetch('/api/clans/shop',{method:body?'POST':'GET',cache:'no-store',headers:body?{'Content-Type':'application/json'}:{},...(body?{body:JSON.stringify(body)}:{})});const d=await r.json();if(!r.ok)throw Error(d.message||'Clan service unavailable.');return d;}",
|
||||
"function priceEditor(view){if(!data.canSetPrice)return;const form=el('form');form.className='clan-form';const label=el('label','Full clan kit price · Dunemarks'),price=el('input');price.type='number';price.min=1;price.max=1000000;price.required=true;price.value=data.priceDunemarks;label.append(price);const save=el('button','Set kit price');save.type='submit';save.dataset.duneAction='admin';form.append(label,save);form.onsubmit=async e=>{e.preventDefault();const g=generation;save.disabled=true;try{const r=await fetch('/api/clans/shop/price',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({priceDunemarks:Number(price.value)})});const d=await r.json();if(!r.ok)throw Error(d.message);if(g===generation)await load();}catch(e){if(g===generation)view.status.textContent=e.message;}finally{if(g===generation)save.disabled=false;}};view.body.append(form);}",
|
||||
"window.addEventListener('dune:session',e=>session(e.detail));window.addEventListener('dune:page',e=>{if(e.detail?.page==='clans'||views[e.detail?.page])load();});window.addEventListener('hashchange',()=>{if(active()==='clans'||views[active()])load();});const g=generation;try{const r=await fetch('/api/auth/session',{cache:'no-store'});if(r.ok){const d=await r.json();if(g===generation)session(d.user);}}catch{}\r"
|
||||
]
|
||||
},
|
||||
{
|
||||
"file": "https://cp.dunerealms.com/commerce-settings.mjs",
|
||||
"status": 200,
|
||||
"observedPaths": [
|
||||
"/api/auth/session"
|
||||
],
|
||||
"contractEvidence": [
|
||||
" let generation=0;const applySession=user=>{for(const[id,,permission]of definitions){const section=document.getElementById(id);if(section)section.hidden=!user?.permissions?.includes(permission);}};window.addEventListener('dune:session',e=>{generation++;applySession(e.detail);});const revision=generation;fetch('/api/auth/session',{cache:'no-store'}).then(r=>r.json()).then(d=>{if(revision===generation)applySession(d.user);}).catch(()=>applySession(null));"
|
||||
]
|
||||
},
|
||||
{
|
||||
"file": "https://cp.dunerealms.com/luckperms.mjs",
|
||||
"status": 200,
|
||||
"observedPaths": [
|
||||
"/api/luckperms/",
|
||||
"/api/auth/session"
|
||||
],
|
||||
"contractEvidence": [
|
||||
"async function api(path,body){const response=await fetch('/api/luckperms/'+path,{cache:'no-store',...(body?{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(body)}:{})});const data=await response.json();if(!response.ok)throw Error(data.message||'LuckPerms is unavailable.');return data;}",
|
||||
" const response=await fetch('/api/auth/session',{cache:'no-store'});if(response.ok)await session((await response.json()).user);"
|
||||
]
|
||||
},
|
||||
{
|
||||
"file": "https://cp.dunerealms.com/game-ranks.mjs",
|
||||
"status": 200,
|
||||
"observedPaths": [
|
||||
"/api/ranks/game",
|
||||
"/api/auth/session"
|
||||
],
|
||||
"contractEvidence": [
|
||||
"const section=el('section');section.id='game-permissions';section.hidden=true;section.className='rank-editor';section.append(el('p','CENTRAL COMMAND · LINKED MINECRAFT ROLES'),el('h2','In-game ranks'),el('p','The same central ranks, with separate Minecraft permissions. * A linked Minecraft UUID is required. Only the website-managed groups are synchronized; unrelated game permissions remain separate.'));",
|
||||
"async function api(payload){const r=await fetch('/api/ranks/game',{cache:'no-store',method:payload?'POST':'GET',headers:payload?{'Content-Type':'application/json'}:{},...(payload?{body:JSON.stringify(payload)}:{})});const d=await r.json();if(!r.ok)throw Error(d.message||'Game permissions unavailable.');return d;}",
|
||||
"window.addEventListener('dune:session',e=>session(e.detail));window.addEventListener('dune:page',e=>{if(e.detail?.page==='game-permissions')load();});window.addEventListener('hashchange',()=>{if(location.hash==='#game-permissions')load();});const g=generation;try{const r=await fetch('/api/auth/session',{cache:'no-store'});if(r.ok){const d=await r.json();if(g===generation)session(d.user);}}catch{}"
|
||||
]
|
||||
},
|
||||
{
|
||||
"file": "https://cp.dunerealms.com/imperial-atelier.mjs",
|
||||
"status": 200,
|
||||
"observedPaths": [
|
||||
"/api/imperial-atelier",
|
||||
"/api/auth/session"
|
||||
],
|
||||
"contractEvidence": [
|
||||
"const dashboard=document.getElementById('dashboard'),section=el('section');section.id='imperial-atelier';section.className='clan-center';section.hidden=true;const hero=el('header');hero.className='imperial-atelier-hero';const img=el('img');img.src='https://www.dunerealms.com/assets/imperial-atelier-v1.webp';img.alt='The Imperial Atelier ceremonial stillsuit workshop';img.className='atelier-banner';const copy=el('div');copy.append(el('p','REGALIA OF THE REALM'),el('h2','The Imperial Atelier'),el('p','Ceremonial stillsuits for the Emperor and current officeholders.'));hero.append(copy);const notice=el('p');notice.role='status';const content=el('div');section.append(hero,img,el('p','* Your linked Minecraft UUID must currently hold the office. Designs apply before the first kit claim of a term. Editing later does not issue another kit or restyle items already claimed.'),notice,content);dashboard?.append(section);let generation=0,actor=null;const link=el('a','The Imperial Atelier *');link.h",
|
||||
"async function api(body){const r=await fetch('/api/imperial-atelier',{method:body?'POST':'GET',cache:'no-store',headers:body?{'Content-Type':'application/json'}:{},...(body?{body:JSON.stringify(body)}:{})});const d=await r.json();if(!r.ok)throw Error(d.message||'Atelier unavailable.');return d;}",
|
||||
"window.addEventListener('dune:session',e=>session(e.detail));window.addEventListener('dune:page',e=>{if(e.detail?.page==='imperial-atelier')load();});window.addEventListener('hashchange',()=>{if(location.hash==='#imperial-atelier')load();});const g=generation;try{const r=await fetch('/api/auth/session',{cache:'no-store'});if(r.ok){const d=await r.json();if(g===generation)session(d.user);}}catch{}"
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
1458
website/api/openapi-v1.json
Normal file
1458
website/api/openapi-v1.json
Normal file
File diff suppressed because it is too large
Load diff
|
|
@ -1,4 +1,5 @@
|
|||
import {createRankAdmin} from '../node/rank-admin.mjs';
|
||||
import {createApiV1} from '../node/api-v1.mjs';
|
||||
import {createStaffManual} from './staff-manual.mjs';
|
||||
import {initializeRanks,can} from '../node/permissions.mjs';
|
||||
import {createServer} from 'node:http';
|
||||
|
|
@ -16,6 +17,7 @@ import {createServerControl} from './server-control.mjs';
|
|||
const types={'.html':'text/html; charset=utf-8','.js':'text/javascript; charset=utf-8','.mjs':'text/javascript; charset=utf-8','.css':'text/css; charset=utf-8'};
|
||||
const sharedAssets=new Set(['ornament.webp','guild.webp','minecraft-hero.webp','menu-0.webp','menu-5.webp','menu-6.webp','menu-9.webp','menu-12.webp','item-23.webp','dunemark-icon-64.png','arrakis-lore-frieze.svg']);
|
||||
export function createPanel(db,settings={},dependencies={}){
|
||||
const apiV1=createApiV1(db,settings,{fetcher:dependencies.fetcher,audit:dependencies.apiAudit});
|
||||
const origin=new URL(settings.CP_ORIGIN||'https://cp.dunerealms.com').origin;
|
||||
const auth=createAuth(db,origin),links=createGameLink(db,settings,origin),rewards=createCommunityRewards(db,settings,origin);
|
||||
const admin=createAccountAdmin(db,origin);
|
||||
|
|
@ -28,6 +30,7 @@ export function createPanel(db,settings={},dependencies={}){
|
|||
const market=(settings.EXCHANGE_READ_TOKEN||'').length>=32?createMarketBridge({pool,readToken:settings.EXCHANGE_READ_TOKEN}):null;
|
||||
return async request=>{
|
||||
const path=new URL(request.url).pathname;
|
||||
if(path==='/api/v1'||path.startsWith('/api/v1/'))return apiV1(request);
|
||||
if(path==='/api/staff/manual')return manual(request);
|
||||
if(path==='/api/game/permissions'||path==='/api/ranks'||path.startsWith('/api/ranks/'))return ranks(request);
|
||||
const menu=path==='/api/inventory'||path==='/api/exchange/sales-history'?'cp.menu.inventory':(path==='/api/game-link'||path.startsWith('/api/game-link/')&&path!=='/api/game-link/consume')?'cp.menu.game':path==='/api/community/rewards'?'cp.menu.rewards':null;
|
||||
|
|
|
|||
103
website/node/api-v1.mjs
Normal file
103
website/node/api-v1.mjs
Normal file
|
|
@ -0,0 +1,103 @@
|
|||
import {randomUUID} from 'node:crypto';
|
||||
import {identity} from './auth.mjs';
|
||||
import {accessFor} from './permissions.mjs';
|
||||
import {createWorldStatus} from './world-status.mjs';
|
||||
|
||||
const uuidPattern=/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/;
|
||||
const idPattern=/^[1-9][0-9]{0,18}$/;
|
||||
const maxId=9223372036854775807n;
|
||||
const routes=new Set(['/api/v1/me','/api/v1/me/minecraft','/api/v1/me/permissions','/api/v1/servers','/api/v1/catalogue']);
|
||||
class Unavailable extends Error {}
|
||||
|
||||
/** Fixed operator-configured destination; browser input never selects a service or token. */
|
||||
export function createCatalogueReader(settings,fetcher=fetch){
|
||||
return async()=>{
|
||||
if(!settings.EXCHANGE_LISTINGS_URL||typeof settings.EXCHANGE_READ_TOKEN!=='string'||settings.EXCHANGE_READ_TOKEN.length<32)throw new Unavailable();
|
||||
const target=new URL(settings.EXCHANGE_LISTINGS_URL);
|
||||
if(target.protocol!=='https:'||target.username||target.password||target.search||target.hash)throw new Unavailable();
|
||||
const response=await fetcher(target.href,{headers:{Authorization:'Bearer '+settings.EXCHANGE_READ_TOKEN},redirect:'error',signal:AbortSignal.timeout(7000)});
|
||||
if(!response.ok)throw new Unavailable();
|
||||
// The existing bridge is bounded to 500 records. Reject oversized/malformed responses.
|
||||
const reader=response.body?.getReader();if(!reader)throw new Unavailable();
|
||||
const chunks=[];let length=0;
|
||||
try{while(true){const {done,value}=await reader.read();if(done)break;length+=value.length;if(length>1048576)throw new Unavailable();chunks.push(value);}}
|
||||
finally{await reader.cancel().catch(()=>{});}
|
||||
const body=JSON.parse(Buffer.concat(chunks).toString('utf8'));
|
||||
if(!Array.isArray(body.listings)||body.listings.length>500)throw new Unavailable();
|
||||
const seen=new Set();
|
||||
return body.listings.map(row=>{
|
||||
const id=String(row.id),price=String(row.price);
|
||||
if(typeof row.id!=='string'||typeof row.price!=='string'||!idPattern.test(id)||BigInt(id)>maxId||seen.has(id)||!Number.isSafeInteger(row.quantity)||row.quantity<1||
|
||||
!/^(?:0|[1-9][0-9]{0,17})(?:\.[0-9]{1,2})?$/.test(price)||!/[1-9]/.test(price))throw new Unavailable();
|
||||
if(['material','category','origin','seller'].some(k=>typeof row[k]!=='string'||row[k].length>({material:80,category:24,origin:48,seller:32}[k])))throw new Unavailable();
|
||||
seen.add(id);
|
||||
return {id,material:row.material,category:row.category,origin:row.origin,seller:row.seller,quantity:row.quantity,unitPrice:price};
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
/** Additive, session-only read API. No reward, entitlement, wallet or delivery writes. */
|
||||
export function createApiV1(db,settings={},dependencies={}){
|
||||
const worldStatus=createWorldStatus(settings,dependencies.fetcher);
|
||||
const readCatalogue=createCatalogueReader(settings,dependencies.fetcher);
|
||||
const now=dependencies.now||Date.now;
|
||||
const audit=dependencies.audit||((event)=>console.info(JSON.stringify(event)));
|
||||
const buckets=new Map();let lastSweep=0;
|
||||
const windowMs=60000,limit=120,maxBuckets=5000;
|
||||
function allow(key){
|
||||
const time=now();
|
||||
if(time-lastSweep>=windowMs){for(const [k,b]of buckets)if(b.until<=time)buckets.delete(k);lastSweep=time;}
|
||||
let bucket=buckets.get(key);
|
||||
if(!bucket||bucket.until<=time){if(!bucket&&buckets.size>=maxBuckets)return false;bucket={until:time+windowMs,count:0};buckets.set(key,bucket);}
|
||||
return ++bucket.count<=limit;
|
||||
}
|
||||
return async request=>{
|
||||
const url=new URL(request.url);
|
||||
if(url.pathname!=='/api/v1'&&!url.pathname.startsWith('/api/v1/'))return null;
|
||||
const requestId=randomUUID();let actor=null;
|
||||
const reply=async(status,data,code,message,extra={})=>{
|
||||
// Fixed fields only: never log cookies, headers, URLs, query values, UUIDs or bodies.
|
||||
try{await audit({event:'api-v1-request',requestId,actorId:actor?.id||null,route:routes.has(url.pathname)?url.pathname:'unmatched',method:['GET','HEAD','POST','PUT','PATCH','DELETE','OPTIONS'].includes(request.method)?request.method:'other',status});}
|
||||
catch{return Response.json({error:{code:'audit_unavailable',message:'The API is temporarily unavailable.',requestId}},{status:503,headers:{'Cache-Control':'private, no-store','Vary':'Cookie','X-Request-ID':requestId,'X-Content-Type-Options':'nosniff'}});}
|
||||
return Response.json(status<400?{data,meta:{requestId}}:{error:{code,message,requestId}},{status,headers:{'Cache-Control':'private, no-store','Vary':'Cookie','X-Request-ID':requestId,'X-Content-Type-Options':'nosniff',...extra}});
|
||||
};
|
||||
try{
|
||||
if(settings.API_V1_ENABLED!=='true')return reply(404,null,'not_found','API v1 is not enabled.');
|
||||
// Bound unauthenticated traffic before database work; do not trust proxy IP headers.
|
||||
if(!allow('global'))return reply(429,null,'rate_limited','Try again later.',{'Retry-After':'60'});
|
||||
actor=await identity(request,db);
|
||||
if(!actor)return reply(401,null,'unauthenticated','Sign in through the central website.');
|
||||
if(!allow('account:'+actor.id))return reply(429,null,'rate_limited','Try again later.',{'Retry-After':'60'});
|
||||
if(request.headers.has('authorization'))return reply(403,null,'credential_not_supported','Use the central website session for this interface.');
|
||||
if(request.headers.get('sec-fetch-site')==='cross-site'||request.headers.has('origin')&&request.headers.get('origin')!==url.origin)return reply(403,null,'origin_rejected','Cross-origin access is not permitted.');
|
||||
if(!routes.has(url.pathname))return reply(404,null,'not_found','Endpoint not found.');
|
||||
if(request.method!=='GET')return reply(405,null,'method_not_allowed','This API increment supports GET only.',{Allow:'GET'});
|
||||
const paged=url.pathname==='/api/v1/catalogue';
|
||||
const keys=[...url.searchParams.keys()];
|
||||
if(keys.some(k=>!paged||!['limit','before'].includes(k))||new Set(keys).size!==keys.length)return reply(400,null,'invalid_query','Unexpected or duplicate query parameter.');
|
||||
if(!paged&&url.search)return reply(400,null,'invalid_query','This endpoint accepts no query parameters.');
|
||||
if(url.pathname==='/api/v1/me')return reply(200,{id:actor.id,username:actor.username,displayName:actor.display_name});
|
||||
if(url.pathname==='/api/v1/me/minecraft'){
|
||||
const link=await db.prepare('SELECT l.minecraft_uuid,l.minecraft_name,l.linked_at,i.first_linked_at FROM site_game_links l JOIN site_game_identities i ON i.minecraft_uuid=l.minecraft_uuid WHERE l.user_id=?').bind(actor.id).first();
|
||||
if(link&&(!uuidPattern.test(link.minecraft_uuid)||!Number.isSafeInteger(Number(link.linked_at))||!Number.isSafeInteger(Number(link.first_linked_at))))throw new Unavailable();
|
||||
return reply(200,{linked:!!link,identity:link?{uuid:link.minecraft_uuid,name:link.minecraft_name,linkedAt:Number(link.linked_at),firstLinkedAt:Number(link.first_linked_at)}:null});
|
||||
}
|
||||
if(url.pathname==='/api/v1/me/permissions'){
|
||||
const access=await accessFor(db,actor);
|
||||
// Report the existing resolver verbatim. Never infer scope or powers from a role label.
|
||||
return reply(200,{rank:access.rank,label:access.label,permissions:[...new Set(access.nodes)].sort(),scopeModel:'legacy-effective-nodes'});
|
||||
}
|
||||
if(url.pathname==='/api/v1/servers'){
|
||||
const response=await worldStatus();if(!response.ok)throw new Unavailable();
|
||||
return reply(200,await response.json());
|
||||
}
|
||||
const pageSize=url.searchParams.get('limit')||'20',before=url.searchParams.get('before');
|
||||
if(!/^(?:[1-9]|[1-9][0-9]|100)$/.test(pageSize)||before!==null&&(!idPattern.test(before)||BigInt(before)>maxId))return reply(400,null,'invalid_query','Use limit 1–100 and a positive decimal before cursor.');
|
||||
const all=await readCatalogue();
|
||||
const sorted=all.sort((a,b)=>BigInt(a.id)>BigInt(b.id)?-1:1);
|
||||
const filtered=before===null?sorted:sorted.filter(r=>BigInt(r.id)<BigInt(before));
|
||||
const items=filtered.slice(0,Number(pageSize)),hasMore=filtered.length>items.length;
|
||||
return reply(200,{kind:'game-exchange',items,pagination:{limit:Number(pageSize),nextCursor:hasMore?items.at(-1).id:null,hasMore,sourceWindow:500,sourceLimited:all.length===500}});
|
||||
}catch{return reply(503,null,'service_unavailable','The API is temporarily unavailable.');}
|
||||
};
|
||||
}
|
||||
140
website/tests/api-v1.test.mjs
Normal file
140
website/tests/api-v1.test.mjs
Normal file
|
|
@ -0,0 +1,140 @@
|
|||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {createHash} from 'node:crypto';
|
||||
import {readFileSync} from 'node:fs';
|
||||
import {LocalD1} from './d1-adapter.mjs';
|
||||
import {createApiV1} from '../node/api-v1.mjs';
|
||||
import {createPanel} from '../control-panel/server.mjs';
|
||||
|
||||
const origin='https://cp.dunerealms.com';
|
||||
const aliceUuid='12345678-1234-4234-9234-123456789012',bobUuid='22345678-1234-4234-9234-123456789012';
|
||||
const schema=`CREATE TABLE site_accounts(id TEXT PRIMARY KEY,username TEXT,display_name TEXT,role TEXT);
|
||||
CREATE TABLE site_sessions(token_hash TEXT PRIMARY KEY,user_id TEXT,expires_at INTEGER);
|
||||
CREATE TABLE site_game_links(user_id TEXT PRIMARY KEY,minecraft_uuid TEXT UNIQUE,minecraft_name TEXT,linked_at INTEGER);
|
||||
CREATE TABLE site_game_identities(minecraft_uuid TEXT PRIMARY KEY,first_linked_at INTEGER,last_name TEXT);
|
||||
CREATE TABLE cp_ranks(rank_key TEXT PRIMARY KEY,label TEXT,rank_level INTEGER,kind TEXT,permissions_json TEXT,version INTEGER);`;
|
||||
function fixture(options={}){
|
||||
const db=new LocalD1(schema),events=[],calls=[];
|
||||
const token='a'.repeat(43),bobToken='b'.repeat(43);
|
||||
for(const [id,name,role,t,uuid]of [['account-a','alice','user',token,aliceUuid],['account-b','bobby','web_support',bobToken,bobUuid]]){
|
||||
db.sqlite.prepare('INSERT INTO site_accounts VALUES(?,?,?,?)').run(id,name,name,role);
|
||||
db.sqlite.prepare('INSERT INTO site_sessions VALUES(?,?,?)').run(createHash('sha256').update(t).digest('hex'),id,Date.now()+600000);
|
||||
db.sqlite.prepare('INSERT INTO site_game_links VALUES(?,?,?,?)').run(id,uuid,name,100);
|
||||
db.sqlite.prepare('INSERT INTO site_game_identities VALUES(?,?,?)').run(uuid,80,name);
|
||||
}
|
||||
db.sqlite.prepare('INSERT INTO cp_ranks VALUES(?,?,?,?,?,?)').run('web_support','Support',30,'access',JSON.stringify(['cp.accounts.view']),1);
|
||||
const settings={API_V1_ENABLED:'true',EXCHANGE_LISTINGS_URL:'https://bridge.test/internal/exchange/listings',EXCHANGE_READ_TOKEN:'fixture-private-token-'.repeat(3),...options.settings};
|
||||
let unavailable=false;
|
||||
const rows=[3,2,1].map(id=>({id:String(id),price:'9007199254740993.12',quantity:2,material:'STONE',category:'blocks',origin:'arrakis',seller:'Trader',internalToken:'must-be-stripped'}));
|
||||
const fetcher=options.fetcher||async function(url,config){calls.push({url,config});if(unavailable)throw Error('private database connection failed');return Response.json({listings:rows});};
|
||||
const deps={fetcher,audit:event=>events.push(event),...options.dependencies};
|
||||
const app=options.panel?createPanel(db,settings,{fetcher,apiAudit:deps.audit}):createApiV1(db,settings,deps);
|
||||
const req=(route='/me',{who='alice',method='GET',headers={},body}={})=>app(new Request(origin+'/api/v1'+route,{method,headers:{...(who?{Cookie:'__Host-dune_session='+(who==='alice'?token:bobToken)}:{}),...headers},...(body?{body:JSON.stringify(body)}:{})}));
|
||||
return {db,req,events,calls,rows,app,settings,fail(value){unavailable=value;},close(){db.close();}};
|
||||
}
|
||||
test('v1 uses real session lookup; anonymous, expired and forged identity are rejected',async()=>{
|
||||
const f=fixture();try{
|
||||
for(const headers of [{},{'oai-authenticated-user-id':'account-a','x-internal-user-id':'account-a'},{Authorization:'Bearer service-secret'}])assert.equal((await f.req('/me',{who:null,headers})).status,401);
|
||||
const response=await f.req(),body=await response.json();assert.deepEqual(body.data,{id:'account-a',username:'alice',displayName:'alice'});
|
||||
assert.equal(response.headers.get('x-request-id'),body.meta.requestId);assert.equal(response.headers.get('cache-control'),'private, no-store');assert.equal(response.headers.get('access-control-allow-origin'),null);
|
||||
f.db.sqlite.exec('UPDATE site_sessions SET expires_at=0');assert.equal((await f.req()).status,401);
|
||||
}finally{f.close();}
|
||||
});
|
||||
test('verified UUID is account-bound and every ownership override is rejected',async()=>{
|
||||
const f=fixture();try{
|
||||
assert.equal((await (await f.req('/me/minecraft')).json()).data.identity.uuid,aliceUuid);
|
||||
assert.equal((await (await f.req('/me/minecraft',{who:'bob'})).json()).data.identity.uuid,bobUuid);
|
||||
for(const suffix of ['?uuid='+bobUuid,'?userId=account-b','?account=account-b','?server=other'])assert.equal((await f.req('/me/minecraft'+suffix)).status,400);
|
||||
assert.equal((await f.req('/accounts/account-b')).status,404);
|
||||
assert.equal((await f.req('/me/minecraft',{method:'POST',body:{uuid:bobUuid}})).status,405);
|
||||
f.db.sqlite.exec("DELETE FROM site_game_identities WHERE minecraft_uuid='"+aliceUuid+"'");
|
||||
assert.deepEqual((await (await f.req('/me/minecraft')).json()).data,{linked:false,identity:null});
|
||||
}finally{f.close();}
|
||||
});
|
||||
test('support permissions do not become appeals, administrative or game powers',async()=>{
|
||||
const f=fixture();try{
|
||||
const data=(await (await f.req('/me/permissions',{who:'bob'})).json()).data;
|
||||
assert.deepEqual(data.permissions,['cp.accounts.view']);assert.equal(data.scopeModel,'legacy-effective-nodes');
|
||||
for(const route of ['/appeals/approve','/admin/accounts','/bank/transfer','/kits/buy','/orders','/redemptions'])assert.equal((await f.req(route,{who:'bob',method:'POST'})).status,404);
|
||||
assert.equal((await f.req('/me',{headers:{Origin:'https://evil.test'}})).status,403);
|
||||
assert.equal((await f.req('/me',{headers:{'Sec-Fetch-Site':'cross-site'}})).status,403);
|
||||
assert.equal((await f.req('/me',{headers:{Authorization:'Bearer internal-token'}})).status,403);
|
||||
}finally{f.close();}
|
||||
});
|
||||
test('catalogue reuses private bridge, preserves decimal precision and projects safe fields',async()=>{
|
||||
const f=fixture();try{
|
||||
const first=await (await f.req('/catalogue?limit=2')).json();assert.deepEqual(first.data.items.map(r=>r.id),['3','2']);assert.equal(first.data.items[0].unitPrice,'9007199254740993.12');assert.equal(first.data.items[0].internalToken,undefined);
|
||||
assert.equal(first.data.pagination.nextCursor,'2');
|
||||
const last=(await (await f.req('/catalogue?limit=2&before=2')).json()).data;assert.deepEqual(last.items.map(r=>r.id),['1']);assert.equal(last.pagination.nextCursor,null);
|
||||
assert.equal(f.calls[0].url,f.settings.EXCHANGE_LISTINGS_URL);assert.equal(f.calls[0].config.redirect,'error');assert.equal(f.calls[0].config.headers.Authorization,'Bearer '+f.settings.EXCHANGE_READ_TOKEN);
|
||||
assert.ok(!JSON.stringify(first).includes(f.settings.EXCHANGE_READ_TOKEN));
|
||||
for(const query of ['limit=0','limit=101','limit=02','limit=1&limit=2','before=0','before=9223372036854775808','before=1e2','uuid='+bobUuid,'url=https://evil.test'])assert.equal((await f.req('/catalogue?'+query)).status,400);
|
||||
}finally{f.close();}
|
||||
});
|
||||
test('upstream failure is sanitized and retry recovers without fabricated catalogue data',async()=>{
|
||||
const f=fixture();try{
|
||||
f.fail(true);const response=await f.req('/catalogue'),body=await response.json();assert.equal(response.status,503);assert.equal(body.error.code,'service_unavailable');assert.ok(!JSON.stringify(body).includes('database'));
|
||||
f.fail(false);assert.equal((await f.req('/catalogue')).status,200);
|
||||
f.rows[0].price=9007199254740992;assert.equal((await f.req('/catalogue')).status,503);
|
||||
}finally{f.close();}
|
||||
});
|
||||
test('unconfigured catalogue fails closed and status honestly reports unknown',async()=>{
|
||||
const f=fixture({settings:{EXCHANGE_READ_TOKEN:''}});try{
|
||||
assert.equal((await f.req('/catalogue')).status,503);assert.equal(f.calls.length,0);
|
||||
const status=(await (await f.req('/servers')).json()).data;assert.equal(status.available,false);assert.ok(status.servers.every(r=>r.state==='unknown'));assert.equal(f.calls.length,0);
|
||||
}finally{f.close();}
|
||||
});
|
||||
test('private bridge configuration, malformed data and oversized payloads fail closed',async()=>{
|
||||
for(const settings of [{EXCHANGE_LISTINGS_URL:'http://bridge.test/listings'},{EXCHANGE_LISTINGS_URL:'https://bridge.test/listings?token=hidden'},{EXCHANGE_LISTINGS_URL:'https://name:password@bridge.test/listings'}]){
|
||||
const f=fixture({settings});try{assert.equal((await f.req('/catalogue')).status,503);assert.equal(f.calls.length,0);}finally{f.close();}
|
||||
}
|
||||
for(const fetcher of [async()=>Response.json({listings:[{id:'1',price:'1.00'}]}),async()=>new Response('x'.repeat(1048577)),async()=>Response.json({listings:Array.from({length:501},()=>({}))}),async()=>Response.json({listings:[]},{status:503})]){
|
||||
const f=fixture({fetcher});try{const r=await f.req('/catalogue');assert.equal(r.status,503);assert.equal((await r.json()).error.code,'service_unavailable');}finally{f.close();}
|
||||
}
|
||||
});
|
||||
test('catalogue source cap is explicit and server status cannot leak monitor fields',async()=>{
|
||||
const f=fixture();try{
|
||||
f.rows.splice(0,f.rows.length,...Array.from({length:500},(_,i)=>({id:String(i+1),price:'1.25',quantity:1,material:'STONE',category:'blocks',origin:'arrakis',seller:'Trader'})));
|
||||
const data=(await (await f.req('/catalogue?limit=100')).json()).data;assert.equal(data.items.length,100);assert.equal(data.pagination.sourceLimited,true);assert.equal(data.pagination.sourceWindow,500);
|
||||
}finally{f.close();}
|
||||
const status=fixture({settings:{WORLD_STATUS_URL:'https://monitor.test/status'},fetcher:async()=>Response.json({checkedAt:Date.now(),servers:Object.fromEntries(['spacing-guild','arrakis','caladan','giedi-prime','kaitain','sigma-draconis-iv','velocity'].map(id=>[id,{online:true,configured:true,players:2,internalAddress:'private',serviceToken:'private'}]))})});
|
||||
try{const data=(await (await status.req('/servers')).json()).data;assert.equal(data.available,true);assert.ok(data.servers.every(row=>row.state==='online'));assert.ok(!JSON.stringify(data).includes('private'));}finally{status.close();}
|
||||
});
|
||||
test('duplicate and concurrent reads cannot change links, balances, rewards or deliveries',async()=>{
|
||||
const f=fixture();try{
|
||||
const before=f.db.sqlite.prepare('SELECT * FROM site_game_links ORDER BY user_id').all();
|
||||
const responses=await Promise.all(Array.from({length:30},()=>f.req('/me/minecraft',{headers:{'Idempotency-Key':'same-request'}})));
|
||||
assert.ok(responses.every(r=>r.status===200));assert.equal(new Set(responses.map(r=>r.headers.get('x-request-id'))).size,30);
|
||||
assert.deepEqual(f.db.sqlite.prepare('SELECT * FROM site_game_links ORDER BY user_id').all(),before);
|
||||
// No economy/reward tables exist: accidental legacy reward calls or wallet SQL fail this test.
|
||||
for(const route of ['/me','/me/minecraft','/me/permissions','/servers','/catalogue'])assert.equal((await f.req(route,{method:'POST',body:{uuid:bobUuid,amount:10}})).status,405);
|
||||
}finally{f.close();}
|
||||
});
|
||||
test('rate limit is bounded, reports retry interval and recovers after its window',async()=>{
|
||||
let time=100000;const f=fixture({dependencies:{now:()=>time}});try{
|
||||
for(let i=0;i<120;i++)assert.equal((await f.req()).status,200);
|
||||
const denied=await f.req();assert.equal(denied.status,429);assert.equal(denied.headers.get('retry-after'),'60');
|
||||
time+=60000;assert.equal((await f.req()).status,200);
|
||||
}finally{f.close();}
|
||||
});
|
||||
test('audit events contain correlation and outcome but no secrets or caller-controlled query',async()=>{
|
||||
const f=fixture();try{
|
||||
const response=await f.req('/me?password=do-not-log',{headers:{'X-Request-ID':'untrusted'}});
|
||||
assert.equal(response.status,400);assert.notEqual(response.headers.get('x-request-id'),'untrusted');
|
||||
assert.deepEqual(Object.keys(f.events[0]).sort(),['actorId','event','method','requestId','route','status']);assert.ok(!JSON.stringify(f.events).includes('do-not-log'));
|
||||
}finally{f.close();}
|
||||
const broken=fixture({dependencies:{audit(){throw Error('log unavailable');}}});try{assert.equal((await broken.req()).status,503);}finally{broken.close();}
|
||||
});
|
||||
test('panel mounts v1 behind default-off toggle and preserves existing auth and linking reads',async()=>{
|
||||
const f=fixture({panel:true});try{
|
||||
assert.equal((await f.req()).status,200);
|
||||
const legacy=await f.app(new Request(origin+'/api/auth/session',{headers:{Cookie:'__Host-dune_session='+'a'.repeat(43)}}));assert.equal(legacy.status,200);assert.equal((await legacy.json()).authenticated,true);
|
||||
const link=await f.app(new Request(origin+'/api/game-link',{headers:{Cookie:'__Host-dune_session='+'a'.repeat(43)}}));assert.equal(link.status,200);assert.equal((await link.json()).link.minecraft_uuid,aliceUuid);
|
||||
}finally{f.close();}
|
||||
const off=fixture({settings:{API_V1_ENABLED:undefined}});try{assert.equal((await off.req()).status,404);}finally{off.close();}
|
||||
});
|
||||
test('OpenAPI describes exactly the implemented read-only paths',()=>{
|
||||
const spec=JSON.parse(readFileSync(new URL('../api/openapi-v1.json',import.meta.url),'utf8'));
|
||||
assert.equal(spec.openapi,'3.1.0');assert.deepEqual(Object.keys(spec.paths).sort(),['/catalogue','/me','/me/minecraft','/me/permissions','/servers']);
|
||||
for(const item of Object.values(spec.paths)){assert.deepEqual(Object.keys(item),['get']);assert.ok(item.get.responses['401']);assert.ok(item.get.responses['503']);}
|
||||
});
|
||||
Loading…
Reference in a new issue

Staff