Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ VITE_WALLETCONNECT_PROJECT_ID=
VITE_MEGAPOT_API_KEY=
VITE_API_BASE_URL=

# Backend API base. Empty uses same-origin local development.
# Backend API base. SIWE upgrades require this to be empty or the exact page origin.
VITE_BACKEND_API_BASE_URL=

# Server-only backend Planet configuration (Base mainnet)
Expand All @@ -29,8 +29,12 @@ DATABASE_URL=postgresql://user:password@localhost:5432/megastera
# Optional V2 wallet-mineral cutover. Empty keeps Economy v2 disabled.
# Must be an exact UTC midnight, for example 2026-08-21T00:00:00.000Z.
# MINERAL_ECONOMY_CUTOVER_AT=
# Keep disabled until the upgrade route has owner-bound authentication.
# Keep disabled until the migration, SIWE env, and production smoke test are complete.
# MINERAL_UPGRADES_ENABLED=false
# Required only before enabling upgrades: exact canonical HTTPS origin, without a trailing slash.
# SIWE_ORIGIN=
# Required only before enabling upgrades: server-only random secret containing at least 32 bytes.
# SIWE_SESSION_SECRET=
# Receipt proofs are accepted only after this many newer canonical blocks.
MEGAPLANETS_CONFIRMATIONS=6

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
-- Megastera accesses PostgreSQL only through its server-side Prisma role.
-- Supabase API roles must not receive direct access to these backend tables.
-- Align the original migration's nullable array with the required Prisma field.
ALTER TABLE "ticket_purchases" ALTER COLUMN "normals" SET NOT NULL;

DO $$
BEGIN
IF EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'anon') THEN
EXECUTE 'REVOKE ALL PRIVILEGES ON ALL TABLES IN SCHEMA public FROM anon';
EXECUTE 'REVOKE ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA public FROM anon';
EXECUTE 'REVOKE ALL PRIVILEGES ON ALL FUNCTIONS IN SCHEMA public FROM anon';
EXECUTE 'ALTER DEFAULT PRIVILEGES IN SCHEMA public REVOKE ALL ON TABLES FROM anon';
EXECUTE 'ALTER DEFAULT PRIVILEGES IN SCHEMA public REVOKE ALL ON SEQUENCES FROM anon';
EXECUTE 'ALTER DEFAULT PRIVILEGES IN SCHEMA public REVOKE ALL ON FUNCTIONS FROM anon';
END IF;

IF EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'authenticated') THEN
EXECUTE 'REVOKE ALL PRIVILEGES ON ALL TABLES IN SCHEMA public FROM authenticated';
EXECUTE 'REVOKE ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA public FROM authenticated';
EXECUTE 'REVOKE ALL PRIVILEGES ON ALL FUNCTIONS IN SCHEMA public FROM authenticated';
EXECUTE 'ALTER DEFAULT PRIVILEGES IN SCHEMA public REVOKE ALL ON TABLES FROM authenticated';
EXECUTE 'ALTER DEFAULT PRIVILEGES IN SCHEMA public REVOKE ALL ON SEQUENCES FROM authenticated';
EXECUTE 'ALTER DEFAULT PRIVILEGES IN SCHEMA public REVOKE ALL ON FUNCTIONS FROM authenticated';
END IF;
END
$$;
10 changes: 10 additions & 0 deletions prisma/migrations/20260821173000_siwe_nonces/migration.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
CREATE TABLE "siwe_nonces" (
"nonce" VARCHAR(96) NOT NULL,
"walletAddress" VARCHAR(42) NOT NULL,
"issuedAt" TIMESTAMPTZ(3) NOT NULL,
"expiresAt" TIMESTAMPTZ(3) NOT NULL,

CONSTRAINT "siwe_nonces_pkey" PRIMARY KEY ("nonce")
);

CREATE INDEX "siwe_nonces_expiresAt_idx" ON "siwe_nonces"("expiresAt");
10 changes: 10 additions & 0 deletions prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -174,6 +174,16 @@ model MineralEconomyCutover {
@@map("mineral_economy_cutover")
}

model SiweNonce {
nonce String @id @db.VarChar(96)
walletAddress String @db.VarChar(42)
issuedAt DateTime @db.Timestamptz(3)
expiresAt DateTime @db.Timestamptz(3)

@@index([expiresAt])
@@map("siwe_nonces")
}

model PlanetUpgradePurchase {
id String @id @default(uuid()) @db.Uuid
planetId String @db.Uuid
Expand Down
20 changes: 0 additions & 20 deletions server/api/authSurface.test.ts

This file was deleted.

37 changes: 37 additions & 0 deletions server/api/backendConfig.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,4 +36,41 @@ describe('Minerals Economy configuration', () => {
'MINERAL_UPGRADES_ENABLED must be a boolean',
);
});

it('requires exact HTTPS SIWE configuration before upgrades can be enabled', () => {
const config = loadBackendPlanetConfig({
...baseEnv,
MINERAL_UPGRADES_ENABLED: 'true',
SIWE_ORIGIN: 'https://megastera.example',
SIWE_SESSION_SECRET: 's'.repeat(32),
});

expect(config.siweOrigin).toBe('https://megastera.example');
expect(config.siweSessionSecret).toBe('s'.repeat(32));
});

it('fails closed on missing or malformed SIWE configuration', () => {
expect(() => loadBackendPlanetConfig({
...baseEnv,
MINERAL_UPGRADES_ENABLED: 'true',
})).toThrow('SIWE_ORIGIN is required');
expect(() => loadBackendPlanetConfig({
...baseEnv,
MINERAL_UPGRADES_ENABLED: 'true',
SIWE_ORIGIN: 'http://megastera.example',
SIWE_SESSION_SECRET: 's'.repeat(32),
})).toThrow('SIWE_ORIGIN must be an exact HTTPS origin');
expect(() => loadBackendPlanetConfig({
...baseEnv,
MINERAL_UPGRADES_ENABLED: 'true',
SIWE_ORIGIN: 'https://megastera.example/path',
SIWE_SESSION_SECRET: 's'.repeat(32),
})).toThrow('SIWE_ORIGIN must be an exact HTTPS origin');
expect(() => loadBackendPlanetConfig({
...baseEnv,
MINERAL_UPGRADES_ENABLED: 'true',
SIWE_ORIGIN: 'https://megastera.example',
SIWE_SESSION_SECRET: 'too-short',
})).toThrow('SIWE_SESSION_SECRET must contain at least 32 bytes');
});
});
45 changes: 44 additions & 1 deletion server/api/backendConfig.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ export type BackendPlanetConfig = {
/** Optional in dependency overrides so pre-v2 Planet APIs remain source-compatible. */
mineralEconomyCutoverAt?: Date | null;
mineralUpgradesEnabled?: boolean;
siweOrigin?: string;
siweSessionSecret?: string;
};

export type MineralEconomyConfig = {
Expand Down Expand Up @@ -46,6 +48,44 @@ function parseMineralUpgradesEnabled(env: Record<string, string | undefined>): b
throw new Error('MINERAL_UPGRADES_ENABLED must be a boolean.');
}

function parseSiweOrigin(
env: Record<string, string | undefined>,
requiredForUpgrades: boolean,
): string | undefined {
const raw = env.SIWE_ORIGIN?.trim();
if (!raw) {
if (requiredForUpgrades) throw new Error('SIWE_ORIGIN is required when upgrades are enabled.');
return undefined;
}
let origin: URL;
try {
origin = new URL(raw);
} catch {
throw new Error('SIWE_ORIGIN must be an exact HTTPS origin.');
}
if (origin.protocol !== 'https:' || origin.origin !== raw) {
throw new Error('SIWE_ORIGIN must be an exact HTTPS origin.');
}
return raw;
}

function parseSiweSessionSecret(
env: Record<string, string | undefined>,
requiredForUpgrades: boolean,
): string | undefined {
const secret = env.SIWE_SESSION_SECRET?.trim();
if (!secret) {
if (requiredForUpgrades) {
throw new Error('SIWE_SESSION_SECRET is required when upgrades are enabled.');
}
return undefined;
}
if (new TextEncoder().encode(secret).byteLength < 32) {
throw new Error('SIWE_SESSION_SECRET must contain at least 32 bytes.');
}
return secret;
}

export function loadMineralEconomyConfig(
env: Record<string, string | undefined> = process.env,
): MineralEconomyConfig {
Expand Down Expand Up @@ -77,12 +117,15 @@ export function loadBackendPlanetConfig(
.filter(Boolean)
.filter((value, index, values) => value !== rpcUrl && values.indexOf(value) === index)
.slice(0, 3);
const mineralEconomy = loadMineralEconomyConfig(env);
return {
chainId: BASE_CHAIN_ID,
rpcUrl,
rpcFallbackUrls,
databaseUrl,
confirmations,
...loadMineralEconomyConfig(env),
...mineralEconomy,
siweOrigin: parseSiweOrigin(env, mineralEconomy.mineralUpgradesEnabled),
siweSessionSecret: parseSiweSessionSecret(env, mineralEconomy.mineralUpgradesEnabled),
};
}
143 changes: 124 additions & 19 deletions server/api/backendPlanetRoutes.test.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
import { describe, expect, it, vi } from 'vitest';
import { Hono } from 'hono';
import { generateSignedCookie } from 'hono/cookie';
import { getAddress, stringToHex, type Hex } from 'viem';
import { BASE_CHAIN_ID, MEGASTERA_SOURCE } from './config.js';
import { BASE_JACKPOT, type MegasteraProof } from './eligibility.js';
import { MemoryBackendPlanetStore } from './backendPlanet.js';
import { createBackendPlanetRoutes } from './backendPlanetRoutes.js';
import { SIWE_SESSION_COOKIE } from './siweAuth.js';

const proof: MegasteraProof = {
recipient: getAddress('0x1111111111111111111111111111111111111111'),
Expand All @@ -23,6 +25,52 @@ const proof: MegasteraProof = {
};

const config = { chainId: BASE_CHAIN_ID, rpcUrl: 'https://rpc.example.test', databaseUrl: 'postgres://example', confirmations: 6n } as const;
const SIWE_ORIGIN = 'https://megastera.example';
const SIWE_SECRET = 's'.repeat(32);
const NOW = new Date('2026-08-21T00:00:00.000Z');

const upgradeConfig = {
...config,
mineralEconomyCutoverAt: new Date('2026-08-20T00:00:00.000Z'),
mineralUpgradesEnabled: true,
siweOrigin: SIWE_ORIGIN,
siweSessionSecret: SIWE_SECRET,
} as const;

async function sessionCookie(address = proof.recipient, issuedAt = NOW) {
const value = [
'v1',
address.toLowerCase(),
issuedAt.getTime(),
issuedAt.getTime() + 15 * 60_000,
].join('.');
return (await generateSignedCookie(SIWE_SESSION_COOKIE, value, SIWE_SECRET, {
path: '/',
secure: true,
})).split(';')[0];
}

function makeUpgradeApp() {
const purchaseUpgrade = vi.fn().mockResolvedValue({
purchaseId: 'purchase-1',
planetId: 'planet-1',
ownerAddress: proof.recipient.toLowerCase(),
targetLevel: 1,
bonusBpsAfter: 1_000,
costMicros: '200000',
purchasedAt: NOW.toISOString(),
});
const getPrisma = vi.fn(() => ({} as never));
const app = new Hono();
app.route('/api', createBackendPlanetRoutes({
...makeAppDependencies(),
getPrisma,
loadConfig: () => upgradeConfig,
now: () => NOW,
purchaseUpgrade,
}));
return { app, getPrisma, purchaseUpgrade };
}

function makeAppDependencies() {
const store = new MemoryBackendPlanetStore();
Expand Down Expand Up @@ -108,7 +156,20 @@ describe('backend Planet routes', () => {
const response = await app.request('/api/planets/planet-1/upgrade', {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ targetLevel: 0 }),
body: JSON.stringify({ targetLevel: 0, expectedAddress: proof.recipient }),
});

expect(response.status).toBe(400);
expect(getPrisma).not.toHaveBeenCalled();
});

it('requires expectedAddress before touching the database', async () => {
const { app, getPrisma } = makeUpgradeApp();

const response = await app.request(`${SIWE_ORIGIN}/api/planets/planet-1/upgrade`, {
method: 'POST',
headers: { 'content-type': 'application/json', origin: SIWE_ORIGIN },
body: JSON.stringify({ targetLevel: 1 }),
});

expect(response.status).toBe(400);
Expand All @@ -132,34 +193,78 @@ describe('backend Planet routes', () => {
const response = await app.request('/api/planets/planet-1/upgrade', {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ targetLevel: 1 }),
body: JSON.stringify({ targetLevel: 1, expectedAddress: proof.recipient }),
});

expect(response.status).toBe(404);
expect(getPrisma).not.toHaveBeenCalled();
});

it('keeps the unauthenticated upgrade route server-disabled even when configured', async () => {
const getPrisma = vi.fn();
const app = new Hono();
app.route('/api', createBackendPlanetRoutes({
...makeAppDependencies(),
getPrisma,
loadConfig: () => ({
...config,
mineralEconomyCutoverAt: new Date('2026-08-22T00:00:00.000Z'),
mineralUpgradesEnabled: true,
}),
now: () => new Date('2026-08-21T00:00:00.000Z'),
}));
it('rejects an unauthenticated upgrade when the kill switch is enabled', async () => {
const { app, getPrisma } = makeUpgradeApp();

const response = await app.request('/api/planets/planet-1/upgrade', {
const response = await app.request(`${SIWE_ORIGIN}/api/planets/planet-1/upgrade`, {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ targetLevel: 1 }),
headers: { 'content-type': 'application/json', origin: SIWE_ORIGIN },
body: JSON.stringify({ targetLevel: 1, expectedAddress: proof.recipient }),
});

expect(response.status).toBe(404);
expect(response.status).toBe(401);
expect(getPrisma).not.toHaveBeenCalled();
});

it('rejects an expired session and a session for another connected wallet', async () => {
const { app, getPrisma } = makeUpgradeApp();
const expired = await sessionCookie(proof.recipient, new Date(NOW.getTime() - 16 * 60_000));
const wrongWallet = await sessionCookie('0x2222222222222222222222222222222222222222');
const request = (cookie: string) => app.request(`${SIWE_ORIGIN}/api/planets/planet-1/upgrade`, {
method: 'POST',
headers: { 'content-type': 'application/json', cookie, origin: SIWE_ORIGIN },
body: JSON.stringify({ targetLevel: 1, expectedAddress: proof.recipient }),
});

expect((await request(expired)).status).toBe(401);
expect((await request(wrongWallet)).status).toBe(401);
expect(getPrisma).not.toHaveBeenCalled();
});

it('returns 403 when the locked Planet belongs to another wallet', async () => {
const { app, purchaseUpgrade } = makeUpgradeApp();
purchaseUpgrade.mockRejectedValue(new Error('Authenticated wallet does not own this Planet.'));

const response = await app.request(`${SIWE_ORIGIN}/api/planets/planet-1/upgrade`, {
method: 'POST',
headers: {
'content-type': 'application/json',
cookie: await sessionCookie(),
origin: SIWE_ORIGIN,
},
body: JSON.stringify({ targetLevel: 1, expectedAddress: proof.recipient }),
});

expect(response.status).toBe(403);
});

it('passes only the authenticated session wallet into an owner upgrade', async () => {
const { app, purchaseUpgrade } = makeUpgradeApp();

const response = await app.request(`${SIWE_ORIGIN}/api/planets/planet-1/upgrade`, {
method: 'POST',
headers: {
'content-type': 'application/json',
cookie: await sessionCookie(),
origin: SIWE_ORIGIN,
},
body: JSON.stringify({ targetLevel: 1, expectedAddress: proof.recipient }),
});

expect(response.status).toBe(200);
expect(await response.json()).toMatchObject({ upgrade: { purchaseId: 'purchase-1' } });
expect(purchaseUpgrade).toHaveBeenCalledWith(expect.anything(), {
authenticatedWalletAddress: proof.recipient.toLowerCase(),
cutoverAt: upgradeConfig.mineralEconomyCutoverAt,
planetId: 'planet-1',
targetLevel: 1,
});
});
});
Loading
Loading