diff --git a/.env.example b/.env.example index 998cfbd..d0234bd 100644 --- a/.env.example +++ b/.env.example @@ -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) @@ -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 diff --git a/prisma/migrations/20260814160000_supabase_api_lockdown/migration.sql b/prisma/migrations/20260814160000_supabase_api_lockdown/migration.sql new file mode 100644 index 0000000..f516284 --- /dev/null +++ b/prisma/migrations/20260814160000_supabase_api_lockdown/migration.sql @@ -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 +$$; diff --git a/prisma/migrations/20260821173000_siwe_nonces/migration.sql b/prisma/migrations/20260821173000_siwe_nonces/migration.sql new file mode 100644 index 0000000..88319d5 --- /dev/null +++ b/prisma/migrations/20260821173000_siwe_nonces/migration.sql @@ -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"); diff --git a/prisma/schema.prisma b/prisma/schema.prisma index 2c18389..147ac23 100644 --- a/prisma/schema.prisma +++ b/prisma/schema.prisma @@ -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 diff --git a/server/api/authSurface.test.ts b/server/api/authSurface.test.ts deleted file mode 100644 index 633c8c1..0000000 --- a/server/api/authSurface.test.ts +++ /dev/null @@ -1,20 +0,0 @@ -import { readFile, readdir } from 'node:fs/promises'; -import { describe, expect, it } from 'vitest'; - -describe('frontend backend surface', () => { - it('has no consumers of the removed wallet-authentication endpoints', async () => { - const sourceRoot = new URL('../../src/', import.meta.url); - const sourceFiles: URL[] = []; - const visit = async (directory: URL): Promise => { - for (const entry of await readdir(directory, { withFileTypes: true })) { - const path = new URL(`${entry.name}${entry.isDirectory() ? '/' : ''}`, directory); - if (entry.isDirectory()) await visit(path); - else if (/\.(?:ts|tsx|js|jsx)$/.test(entry.name)) sourceFiles.push(path); - } - }; - await visit(sourceRoot); - const source = await Promise.all(sourceFiles.map((file) => readFile(file, 'utf8'))); - const joined = source.join('\n'); - expect(joined).not.toMatch(/\/api\/(?:auth|me(?:\/planets|\/mining)?)(?:["'`?]|\b)/); - }); -}); diff --git a/server/api/backendConfig.test.ts b/server/api/backendConfig.test.ts index 2cc07ac..b43c1fd 100644 --- a/server/api/backendConfig.test.ts +++ b/server/api/backendConfig.test.ts @@ -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'); + }); }); diff --git a/server/api/backendConfig.ts b/server/api/backendConfig.ts index de595f1..ca0c3cb 100644 --- a/server/api/backendConfig.ts +++ b/server/api/backendConfig.ts @@ -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 = { @@ -46,6 +48,44 @@ function parseMineralUpgradesEnabled(env: Record): b throw new Error('MINERAL_UPGRADES_ENABLED must be a boolean.'); } +function parseSiweOrigin( + env: Record, + 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, + 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 = process.env, ): MineralEconomyConfig { @@ -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), }; } diff --git a/server/api/backendPlanetRoutes.test.ts b/server/api/backendPlanetRoutes.test.ts index 3dac6d1..f13cfb2 100644 --- a/server/api/backendPlanetRoutes.test.ts +++ b/server/api/backendPlanetRoutes.test.ts @@ -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'), @@ -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(); @@ -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); @@ -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, + }); + }); }); diff --git a/server/api/backendPlanetRoutes.ts b/server/api/backendPlanetRoutes.ts index 4f64ff3..7751b39 100644 --- a/server/api/backendPlanetRoutes.ts +++ b/server/api/backendPlanetRoutes.ts @@ -16,6 +16,12 @@ import { findTicketFromReceipt, parseReceiptReference, type ReceiptReference } f import { saveMegasteraProof } from './prismaTicketPurchase.js'; import { reportBackendError } from './errorDiagnostics.js'; import type { PrismaClient } from './generated/prisma/client.js'; +import { purchasePlanetUpgrade } from './mineralAccounts.js'; +import { + createSiweAuthRoutes, + getSiweSessionAddress, + isExactSiweRequestOrigin, +} from './siweAuth.js'; export type BackendPlanetReference = ReceiptReference; @@ -27,6 +33,7 @@ export type BackendPlanetRouteDependencies = { allows: (key: string) => boolean; now: () => Date; getPrisma?: (config: BackendPlanetConfig) => PrismaClient; + purchaseUpgrade: typeof purchasePlanetUpgrade; }; const MAX_BATCH = 50; @@ -67,6 +74,7 @@ function defaultDependencies(): BackendPlanetRouteDependencies { getPrisma: (config) => getPrismaClient(config.databaseUrl), allows: createRateLimiter(), now: () => new Date(), + purchaseUpgrade: purchasePlanetUpgrade, }; } @@ -91,6 +99,14 @@ export function createBackendPlanetRoutes( const dependencies = { ...defaultDependencies(), ...overrides }; const app = new Hono(); const inFlight = new Map>(); + const getPrisma = (config: BackendPlanetConfig) => + (dependencies.getPrisma ?? ((value) => getPrismaClient(value.databaseUrl)))(config); + + app.route('/auth/siwe', createSiweAuthRoutes({ + getPrisma, + loadConfig: dependencies.loadConfig, + now: dependencies.now, + })); const generate = async (reference: BackendPlanetReference) => { const key = `${reference.transactionHash.toLowerCase()}:${reference.logIndex}`; @@ -246,11 +262,67 @@ export function createBackendPlanetRoutes( return c.json({ error: 'Request body is invalid or too large.' }, 400); } const targetLevel = body && typeof body === 'object' ? (body as { targetLevel?: unknown }).targetLevel : undefined; + const expectedAddress = body && typeof body === 'object' + ? (body as { expectedAddress?: unknown }).expectedAddress + : undefined; if (typeof targetLevel !== 'number' || !Number.isInteger(targetLevel) || targetLevel < 1 || targetLevel > 3) { return c.json({ error: 'targetLevel must be an integer between 1 and 3.' }, 400); } - // ponytail: public upgrades stay off until requests are authenticated to the Planet owner. - return c.json({ error: 'Planet upgrades are disabled.' }, 404); + if (typeof expectedAddress !== 'string' || !isAddress(expectedAddress)) { + return c.json({ error: 'A valid expectedAddress is required.' }, 400); + } + + let config: BackendPlanetConfig; + try { + config = dependencies.loadConfig(); + } catch { + return c.json({ error: 'Planet upgrades are not configured.' }, 503); + } + if (!config.mineralUpgradesEnabled) { + return c.json({ error: 'Planet upgrades are disabled.' }, 404); + } + if (!config.siweOrigin || !isExactSiweRequestOrigin(c, config.siweOrigin)) { + return c.json({ error: 'Request origin is not allowed.' }, 403); + } + + let authenticatedWalletAddress: Awaited>; + try { + authenticatedWalletAddress = await getSiweSessionAddress(c, config, dependencies.now()); + } catch { + return c.json({ error: 'SIWE authentication is not configured.' }, 503); + } + if ( + !authenticatedWalletAddress || + authenticatedWalletAddress.toLowerCase() !== getAddress(expectedAddress).toLowerCase() + ) return c.json({ error: 'Wallet authentication is required.' }, 401); + + try { + const upgrade = await dependencies.purchaseUpgrade(getPrisma(config), { + authenticatedWalletAddress, + cutoverAt: config.mineralEconomyCutoverAt, + planetId: parsedPlanetId.data, + targetLevel, + }); + return c.json({ upgrade }); + } catch (error) { + const message = error instanceof Error ? error.message : ''; + if (message === 'Authenticated wallet does not own this Planet.') { + return c.json({ error: message }, 403); + } + if (message === 'Planet not found.') return c.json({ error: message }, 404); + if ( + message === 'Insufficient mineral balance.' || + message === 'Mineral economy is disabled.' || + message === 'Mineral economy is not active yet.' || + message === 'Planet is not ready for upgrades.' || + message === 'Upgrade target must be the next Planet level.' + ) return c.json({ error: message }, 422); + return c.json( + { error: 'Planet upgrade failed.' }, + 503, + reportBackendError('POST /api/planets/:planetId/upgrade', error), + ); + } }); app.get('/planets/:planetId', async (c) => { diff --git a/server/api/mineralAccounts.ts b/server/api/mineralAccounts.ts index 20af166..87f0265 100644 --- a/server/api/mineralAccounts.ts +++ b/server/api/mineralAccounts.ts @@ -566,6 +566,7 @@ function serializeUpgradeResult(purchase: Parameters[0 export async function purchasePlanetUpgrade( prisma: PrismaClient, input: { + authenticatedWalletAddress: string; planetId: string; targetLevel: number; cutoverAt?: Date | null; @@ -574,12 +575,7 @@ export async function purchasePlanetUpgrade( getMineralUpgradeConfig(input.targetLevel); return prisma.$transaction(async (transaction) => { await acquireMineralEconomySharedBarrier(transaction); - const ownerHint = await transaction.backendPlanet.findUnique({ - where: { id: input.planetId }, - select: { ownerAddress: true }, - }); - if (!ownerHint) throw new Error('Planet not found.'); - const ownerAddress = normalizeOwner(ownerHint.ownerAddress); + const ownerAddress = normalizeOwner(input.authenticatedWalletAddress); await acquireMineralWalletLock(transaction, ownerAddress); const purchasedAt = await getPostgresClockTimestamp(transaction); const resolution = await resolveMineralEconomyForOperation( @@ -593,11 +589,18 @@ export async function purchasePlanetUpgrade( const account = await ensureAndLockMineralAccount(transaction, ownerAddress, cutoverAt); const planet = await lockPlanet(transaction, input.planetId); if (!planet) throw new Error('Planet not found.'); + if (normalizeOwner(planet.ownerAddress) !== ownerAddress) { + throw new Error('Authenticated wallet does not own this Planet.'); + } const existing = await transaction.planetUpgradePurchase.findUnique({ where: { planetId_targetLevel: { planetId: input.planetId, targetLevel: input.targetLevel } }, }); - if (existing) return serializeUpgradeResult(existing); - if (planet.ownerAddress.toLowerCase() !== ownerAddress) throw new Error('Planet owner changed.'); + if (existing) { + if (normalizeOwner(existing.walletAddress) !== ownerAddress) { + throw new Error('Upgrade target must be the next Planet level.'); + } + return serializeUpgradeResult(existing); + } if (planet.status !== 'READY') throw new Error('Planet is not ready for upgrades.'); if (input.targetLevel !== planet.upgradeLevel + 1) { throw new Error('Upgrade target must be the next Planet level.'); diff --git a/server/api/mineralConcurrency.postgres.test.ts b/server/api/mineralConcurrency.postgres.test.ts index a8fa216..dad3099 100644 --- a/server/api/mineralConcurrency.postgres.test.ts +++ b/server/api/mineralConcurrency.postgres.test.ts @@ -1,4 +1,6 @@ import { PrismaPg } from '@prisma/adapter-pg'; +import { Hono } from 'hono'; +import { createSiweMessage } from 'viem/siwe'; import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest'; import { PrismaBackendPlanetStore } from './backendPlanet.js'; import { MEGASTERA_SOURCE } from './config.js'; @@ -14,6 +16,7 @@ import { resolveMineralEconomyCutover, runMineralAccountsBackfill, } from './mineralAccounts.js'; +import { createSiweAuthRoutes } from './siweAuth.js'; const testDatabaseUrl = process.env.MINERAL_ECONOMY_TEST_DATABASE_URL?.trim(); if (!testDatabaseUrl && process.env.MINERAL_ECONOMY_REQUIRE_POSTGRES === '1') { @@ -23,6 +26,7 @@ if (!testDatabaseUrl && process.env.MINERAL_ECONOMY_REQUIRE_POSTGRES === '1') { } const describePostgres = testDatabaseUrl ? describe : describe.skip; const OWNER = '0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'; +const OTHER_OWNER = '0xbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb'; let nextFixtureId = 99_001; function createClient() { @@ -141,6 +145,7 @@ function proofForTicket( } async function clearTestDatabase(prisma: PrismaClient): Promise { + await prisma.siweNonce.deleteMany(); await prisma.leaderboardEntry.deleteMany(); await prisma.leaderboardPeriod.deleteMany(); // Upgrade history is immutable in production; TRUNCATE keeps test cleanup read/write-safe without firing delete triggers. @@ -268,6 +273,7 @@ describePostgres('Mineral upgrade PostgreSQL concurrency', () => { let completed = 0; const firstUpgrade = purchasePlanetUpgrade(first, { + authenticatedWalletAddress: OWNER, planetId: fixture.planet.id, targetLevel: 1, cutoverAt, @@ -276,6 +282,7 @@ describePostgres('Mineral upgrade PostgreSQL concurrency', () => { return result; }); const secondUpgrade = purchasePlanetUpgrade(second, { + authenticatedWalletAddress: OWNER, planetId: fixture.planet.id, targetLevel: 1, cutoverAt, @@ -306,6 +313,91 @@ describePostgres('Mineral upgrade PostgreSQL concurrency', () => { } }); + it('rolls back every economic write when the authenticated wallet is not the locked Planet owner', async () => { + const databaseNow = await postgresNow(first); + const cutoverAt = await ensurePersistedCutover(first, utcMidnightBefore(databaseNow)); + const fixture = await createFixture(first, OWNER, cutoverAt); + const account = await seedAccount(first, OTHER_OWNER, databaseNow); + + await expect(purchasePlanetUpgrade(first, { + authenticatedWalletAddress: OTHER_OWNER, + planetId: fixture.planet.id, + targetLevel: 1, + cutoverAt, + })).rejects.toThrow('Authenticated wallet does not own this Planet'); + + expect((await first.mineralAccount.findUnique({ where: { ownerAddress: OTHER_OWNER } }))?.balanceMicros) + .toBe(account.balanceMicros); + expect((await first.backendPlanet.findUnique({ where: { id: fixture.planet.id } }))?.upgradeLevel) + .toBe(0); + expect(await first.planetUpgradePurchase.count({ where: { planetId: fixture.planet.id } })) + .toBe(0); + }); + + it('lets only one of two parallel SIWE verify requests create a session', async () => { + const origin = 'https://megastera.example'; + const databaseNow = await postgresNow(first); + const nonce = 'c'.repeat(96); + let arrivals = 0; + let release!: () => void; + const bothVerified = new Promise((resolve) => { + release = resolve; + }); + const app = new Hono(); + app.route('/api/auth/siwe', createSiweAuthRoutes({ + generateNonce: () => nonce, + getPrisma: () => first, + loadConfig: () => ({ + chainId: 8453, + confirmations: 6n, + databaseUrl: testDatabaseUrl ?? '', + mineralUpgradesEnabled: true, + rpcUrl: 'https://rpc.example.test', + siweOrigin: origin, + siweSessionSecret: 's'.repeat(32), + }), + now: () => databaseNow, + verifySignature: async () => { + arrivals += 1; + if (arrivals === 2) release(); + await bothVerified; + return true; + }, + })); + const challengeResponse = await app.request(`${origin}/api/auth/siwe/nonce`, { + method: 'POST', + headers: { 'content-type': 'application/json', origin }, + body: JSON.stringify({ address: OWNER }), + }); + const challenge = await challengeResponse.json() as { + address: `0x${string}`; + chainId: number; + domain: string; + expirationTime: string; + issuedAt: string; + nonce: string; + scheme: string; + uri: string; + version: '1'; + }; + const message = createSiweMessage({ + ...challenge, + expirationTime: new Date(challenge.expirationTime), + issuedAt: new Date(challenge.issuedAt), + }); + const verify = () => app.request(`${origin}/api/auth/siwe/verify`, { + method: 'POST', + headers: { 'content-type': 'application/json', origin }, + body: JSON.stringify({ message, signature: '0x12' }), + }); + + const responses = await Promise.all([verify(), verify()]); + + expect(responses.map((response) => response.status).sort()).toEqual([204, 401]); + expect(responses.filter((response) => response.headers.has('set-cookie'))).toHaveLength(1); + expect(await first.siweNonce.count({ where: { nonce } })).toBe(0); + }); + it('serializes different Planet upgrades for one wallet', async () => { const databaseNow = await postgresNow(first); const cutoverAt = await ensurePersistedCutover(first, utcMidnightBefore(databaseNow)); @@ -314,8 +406,14 @@ describePostgres('Mineral upgrade PostgreSQL concurrency', () => { await seedAccount(first, OWNER, databaseNow); const [firstPurchase, secondPurchase] = await Promise.all([ - purchasePlanetUpgrade(first, { planetId: firstFixture.planet.id, targetLevel: 1, cutoverAt }), + purchasePlanetUpgrade(first, { + authenticatedWalletAddress: OWNER, + planetId: firstFixture.planet.id, + targetLevel: 1, + cutoverAt, + }), purchasePlanetUpgrade(second, { + authenticatedWalletAddress: OWNER, planetId: secondFixture.planet.id, targetLevel: 1, cutoverAt, @@ -344,6 +442,7 @@ describePostgres('Mineral upgrade PostgreSQL concurrency', () => { cutoverAt, ).generatePlanet(proofForTicket(generationTicket.ticket, OWNER)); const upgrade = purchasePlanetUpgrade(first, { + authenticatedWalletAddress: OWNER, planetId: existing.planet.id, targetLevel: 1, cutoverAt, diff --git a/server/api/mineralMutations.test.ts b/server/api/mineralMutations.test.ts index b90e4be..a09754c 100644 --- a/server/api/mineralMutations.test.ts +++ b/server/api/mineralMutations.test.ts @@ -3,6 +3,7 @@ import type { PrismaClient } from './generated/prisma/client.js'; import { purchasePlanetUpgrade, settleMineralAccount } from './mineralAccounts.js'; const OWNER = '0x1111111111111111111111111111111111111111'; +const OTHER = '0x2222222222222222222222222222222222222222'; const CUTOVER = new Date('2026-08-20T00:00:00.000Z'); const PURCHASED_AT = new Date('2026-08-21T00:00:00.000Z'); @@ -29,20 +30,33 @@ function makePrisma(overrides: { const lastSettledAt = overrides.account?.lastSettledAt instanceof Date ? overrides.account.lastSettledAt : CUTOVER; const account = { id: 'account-1', - ownerAddress: OWNER, + ownerAddress: typeof overrides.account?.ownerAddress === 'string' ? overrides.account.ownerAddress : OWNER, openingBalanceMicros: 0n, balanceMicros, lastSettledAt, }; const purchase = overrides.existingPurchase ?? null; const clockAt = overrides.clockAt ?? PURCHASED_AT; + const events: string[] = []; + let queryIndex = 0; const tx = { - $queryRaw: vi - .fn() - .mockResolvedValueOnce([{ locked: 1 }]) - .mockResolvedValueOnce([{ locked: 1 }]) - .mockResolvedValueOnce([{ now: clockAt }]) - .mockResolvedValueOnce([{ id: planet.id }]), + $queryRaw: vi.fn().mockImplementation(() => { + queryIndex += 1; + if (queryIndex === 1) { + events.push('economy-lock'); + return [{ locked: 1 }]; + } + if (queryIndex === 2) { + events.push('wallet-lock'); + return [{ locked: 1 }]; + } + if (queryIndex === 3) { + events.push('clock'); + return [{ now: clockAt }]; + } + events.push('planet-lock'); + return [{ id: planet.id }]; + }), mineralEconomyCutover: { findUnique: vi.fn().mockResolvedValue({ id: 1, cutoverAt: CUTOVER }), createMany: vi.fn().mockResolvedValue({ count: 0 }), @@ -56,7 +70,10 @@ function makePrisma(overrides: { }), }, backendPlanet: { - findUnique: vi.fn().mockResolvedValue(planet), + findUnique: vi.fn().mockImplementation(() => { + events.push('planet-read'); + return planet; + }), findMany: vi.fn().mockResolvedValue([planet]), update: vi.fn().mockImplementation(({ data }: { data: Partial }) => { Object.assign(planet, data); @@ -75,6 +92,7 @@ function makePrisma(overrides: { } as unknown as PrismaClient, tx, account, + events, planet, }; } @@ -121,6 +139,7 @@ describe('mineral upgrade mutations', () => { await expect( purchasePlanetUpgrade(fixture.prisma, { + authenticatedWalletAddress: OWNER, planetId: 'planet-1', targetLevel: 1, cutoverAt: CUTOVER, @@ -134,9 +153,30 @@ describe('mineral upgrade mutations', () => { expect(fixture.planet.upgradeLevel).toBe(0); }); + it('checks the authenticated owner only after locking the Planet', async () => { + const fixture = makePrisma({ account: { ownerAddress: OTHER } }); + + await expect( + purchasePlanetUpgrade(fixture.prisma, { + authenticatedWalletAddress: OTHER, + planetId: 'planet-1', + targetLevel: 1, + cutoverAt: CUTOVER, + }), + ).rejects.toThrow('Authenticated wallet does not own this Planet'); + + expect(fixture.tx.backendPlanet.findUnique).toHaveBeenCalledOnce(); + expect(fixture.events.indexOf('planet-lock')).toBeLessThan(fixture.events.indexOf('planet-read')); + expect(fixture.tx.backendPlanet.findMany).not.toHaveBeenCalled(); + expect(fixture.tx.mineralAccount.update).not.toHaveBeenCalled(); + expect(fixture.tx.backendPlanet.update).not.toHaveBeenCalled(); + expect(fixture.tx.planetUpgradePurchase.create).not.toHaveBeenCalled(); + }); + it('returns an existing purchase on retry without debiting again', async () => { const first = makePrisma(); const result = await purchasePlanetUpgrade(first.prisma, { + authenticatedWalletAddress: OWNER, planetId: 'planet-1', targetLevel: 1, cutoverAt: CUTOVER, @@ -156,6 +196,7 @@ describe('mineral upgrade mutations', () => { }, }); const retryResult = await purchasePlanetUpgrade(retry.prisma, { + authenticatedWalletAddress: OWNER, planetId: 'planet-1', targetLevel: 1, cutoverAt: CUTOVER, diff --git a/server/api/siweAuth.test.ts b/server/api/siweAuth.test.ts new file mode 100644 index 0000000..d92ba3b --- /dev/null +++ b/server/api/siweAuth.test.ts @@ -0,0 +1,218 @@ +import { Hono } from 'hono'; +import { createSiweMessage } from 'viem/siwe'; +import { generatePrivateKey, privateKeyToAccount } from 'viem/accounts'; +import { verifyMessage, type Address, type Hex } from 'viem'; +import { beforeEach, describe, expect, it } from 'vitest'; +import type { PrismaClient } from './generated/prisma/client.js'; +import { createSiweAuthRoutes } from './siweAuth.js'; +import { BASE_CHAIN_ID } from './config.js'; + +const ORIGIN = 'https://megastera.example'; +const NOW = new Date('2026-08-21T12:00:00.000Z'); +const NONCE = 'a'.repeat(96); +const SESSION_SECRET = 's'.repeat(32); + +type NonceRow = { + nonce: string; + walletAddress: string; + issuedAt: Date; + expiresAt: Date; +}; + +function makePrisma() { + const rows = new Map(); + const siweNonce = { + create: async ({ data }: { data: NonceRow }) => { + rows.set(data.nonce, data); + return data; + }, + findUnique: async ({ where }: { where: { nonce: string } }) => rows.get(where.nonce) ?? null, + deleteMany: async ({ + where, + }: { + where: { + nonce?: string; + walletAddress?: string; + expiresAt?: { lte?: Date; gt?: Date }; + }; + }) => { + let count = 0; + for (const [nonce, row] of rows) { + if (where.nonce !== undefined && row.nonce !== where.nonce) continue; + if (where.walletAddress !== undefined && row.walletAddress !== where.walletAddress) continue; + if (where.expiresAt?.lte !== undefined && row.expiresAt > where.expiresAt.lte) continue; + if (where.expiresAt?.gt !== undefined && row.expiresAt <= where.expiresAt.gt) continue; + rows.delete(nonce); + count += 1; + } + return { count }; + }, + }; + return { + prisma: { siweNonce } as unknown as PrismaClient, + rows, + }; +} + +type Challenge = { + address: Address; + chainId: number; + domain: string; + expirationTime: string; + issuedAt: string; + nonce: string; + scheme: string; + uri: string; + version: '1'; +}; + +function messageFor(challenge: Challenge, overrides: Partial<{ + chainId: number; + domain: string; + nonce: string; + scheme: string; + statement: string; + uri: string; +}> = {}) { + return createSiweMessage({ + address: challenge.address, + chainId: overrides.chainId ?? challenge.chainId, + domain: overrides.domain ?? challenge.domain, + expirationTime: new Date(challenge.expirationTime), + issuedAt: new Date(challenge.issuedAt), + nonce: overrides.nonce ?? challenge.nonce, + scheme: overrides.scheme ?? challenge.scheme, + statement: overrides.statement, + uri: overrides.uri ?? challenge.uri, + version: '1', + }); +} + +describe('SIWE authentication routes', () => { + let now: Date; + let account: ReturnType; + let otherAccount: ReturnType; + let app: Hono; + + beforeEach(() => { + now = new Date(NOW); + account = privateKeyToAccount(generatePrivateKey()); + otherAccount = privateKeyToAccount(generatePrivateKey()); + const { prisma } = makePrisma(); + app = new Hono(); + app.route('/api/auth/siwe', createSiweAuthRoutes({ + generateNonce: () => NONCE, + getPrisma: () => prisma, + loadConfig: () => ({ + chainId: BASE_CHAIN_ID, + confirmations: 6n, + databaseUrl: 'postgresql://example.test/db', + mineralUpgradesEnabled: true, + rpcUrl: 'https://rpc.example.test', + siweOrigin: ORIGIN, + siweSessionSecret: SESSION_SECRET, + }), + now: () => now, + verifySignature: async (_config, input) => verifyMessage({ + address: input.address, + message: input.message, + signature: input.signature, + }), + })); + }); + + async function issueChallenge(address = account.address): Promise { + const response = await app.request(`${ORIGIN}/api/auth/siwe/nonce`, { + method: 'POST', + headers: { 'content-type': 'application/json', origin: ORIGIN }, + body: JSON.stringify({ address }), + }); + expect(response.status).toBe(201); + return (await response.json()) as Challenge; + } + + async function verify(message: string, signature: Hex) { + return app.request(`${ORIGIN}/api/auth/siwe/verify`, { + method: 'POST', + headers: { 'content-type': 'application/json', origin: ORIGIN }, + body: JSON.stringify({ message, signature }), + }); + } + + it('creates a valid short-lived signed session cookie', async () => { + const challenge = await issueChallenge(); + const message = messageFor(challenge); + const response = await verify(message, await account.signMessage({ message })); + + expect(response.status).toBe(204); + const cookie = response.headers.get('set-cookie'); + expect(cookie).toContain('__Host-megastera-siwe='); + expect(cookie).toContain('Path=/'); + expect(cookie).toContain('Max-Age=900'); + expect(cookie).toContain('HttpOnly'); + expect(cookie).toContain('Secure'); + expect(cookie).toContain('SameSite=Strict'); + expect(cookie).not.toContain('Domain='); + }); + + it('rejects a signature from a different wallet', async () => { + const challenge = await issueChallenge(); + const message = messageFor(challenge); + + expect((await verify(message, await otherAccount.signMessage({ message }))).status).toBe(401); + }); + + it('rejects a wrong nonce and a replayed nonce', async () => { + const challenge = await issueChallenge(); + const wrongMessage = messageFor(challenge, { nonce: 'b'.repeat(96) }); + expect((await verify(wrongMessage, await account.signMessage({ message: wrongMessage }))).status).toBe(401); + + const message = messageFor(challenge); + const signature = await account.signMessage({ message }); + expect((await verify(message, signature)).status).toBe(204); + expect((await verify(message, signature)).status).toBe(401); + }); + + it.each([ + ['domain', { domain: 'evil.example' }], + ['URI', { uri: 'https://megastera.example/other' }], + ['chain ID', { chainId: 1 }], + ] as const)('rejects a signed message with the wrong %s', async (_label, override) => { + const challenge = await issueChallenge(); + const message = messageFor(challenge, override); + + expect((await verify(message, await account.signMessage({ message }))).status).toBe(401); + }); + + it('reconstructs and compares the complete canonical message', async () => { + const challenge = await issueChallenge(); + const message = messageFor(challenge, { statement: 'An extra signed statement.' }); + + expect((await verify(message, await account.signMessage({ message }))).status).toBe(401); + }); + + it('rejects the wrong SIWE version', async () => { + const challenge = await issueChallenge(); + const message = messageFor(challenge).replace('Version: 1', 'Version: 2'); + + expect((await verify(message, await account.signMessage({ message }))).status).toBe(401); + }); + + it('rejects an expired challenge', async () => { + const challenge = await issueChallenge(); + const message = messageFor(challenge); + now = new Date(NOW.getTime() + 5 * 60_000 + 1); + + expect((await verify(message, await account.signMessage({ message }))).status).toBe(401); + }); + + it('requires the exact configured request origin', async () => { + const response = await app.request(`${ORIGIN}/api/auth/siwe/nonce`, { + method: 'POST', + headers: { 'content-type': 'application/json', origin: 'https://evil.example' }, + body: JSON.stringify({ address: account.address }), + }); + + expect(response.status).toBe(403); + }); +}); diff --git a/server/api/siweAuth.ts b/server/api/siweAuth.ts new file mode 100644 index 0000000..d9f322d --- /dev/null +++ b/server/api/siweAuth.ts @@ -0,0 +1,333 @@ +import { Hono, type Context } from 'hono'; +import { getSignedCookie, setSignedCookie } from 'hono/cookie'; +import { + createPublicClient, + getAddress, + http, + isAddress, + isHex, + type Address, + type Hex, +} from 'viem'; +import { base } from 'viem/chains'; +import { + createSiweMessage, + generateSiweNonce, + parseSiweMessage, + validateSiweMessage, +} from 'viem/siwe'; +import { loadBackendPlanetConfig, type BackendPlanetConfig } from './backendConfig.js'; +import { BASE_CHAIN_ID } from './config.js'; +import { getPrismaClient } from './database.js'; +import type { PrismaClient } from './generated/prisma/client.js'; +import { readBoundedJson } from './http.js'; +import { readWithRpcFallback } from './rpc.js'; + +const NONCE_TTL_MS = 5 * 60_000; +const SESSION_TTL_MS = 15 * 60_000; +export const SIWE_SESSION_COOKIE = '__Host-megastera-siwe'; + +type SignatureInput = { + address: Address; + domain: string; + message: string; + nonce: string; + scheme: string; + signature: Hex; + time: Date; +}; + +export type SiweAuthDependencies = { + generateNonce: () => string; + getPrisma: (config: BackendPlanetConfig) => PrismaClient; + loadConfig: () => BackendPlanetConfig; + now: () => Date; + verifySignature: (config: BackendPlanetConfig, input: SignatureInput) => Promise; +}; + +type RequiredSiweConfig = { + origin: string; + secret: string; +}; + +type SiweNonceRow = { + nonce: string; + walletAddress: string; + issuedAt: Date; + expiresAt: Date; +}; + +function requireSiweConfig(config: BackendPlanetConfig): RequiredSiweConfig { + const origin = config.siweOrigin; + const secret = config.siweSessionSecret; + if (!origin || !secret) throw new Error('SIWE is not configured.'); + const parsed = new URL(origin); + if (parsed.protocol !== 'https:' || parsed.origin !== origin) { + throw new Error('SIWE origin is invalid.'); + } + if (new TextEncoder().encode(secret).byteLength < 32) { + throw new Error('SIWE session secret is invalid.'); + } + return { origin, secret }; +} + +export function isExactSiweRequestOrigin(c: Context, configuredOrigin: string): boolean { + return c.req.header('origin') === configuredOrigin && new URL(c.req.url).origin === configuredOrigin; +} + +function challengeFromRow(row: SiweNonceRow, origin: string) { + const parsedOrigin = new URL(origin); + return { + address: getAddress(row.walletAddress), + chainId: BASE_CHAIN_ID, + domain: parsedOrigin.host, + expirationTime: row.expiresAt.toISOString(), + issuedAt: row.issuedAt.toISOString(), + nonce: row.nonce, + scheme: parsedOrigin.protocol.slice(0, -1), + uri: parsedOrigin.origin, + version: '1' as const, + }; +} + +function canonicalMessage(challenge: ReturnType): string { + return createSiweMessage({ + address: challenge.address, + chainId: challenge.chainId, + domain: challenge.domain, + expirationTime: new Date(challenge.expirationTime), + issuedAt: new Date(challenge.issuedAt), + nonce: challenge.nonce, + scheme: challenge.scheme, + uri: challenge.uri, + version: challenge.version, + }); +} + +function isCanonicalParsedMessage( + parsed: ReturnType, + challenge: ReturnType, +): boolean { + return ( + typeof parsed.address === 'string' && + isAddress(parsed.address) && + parsed.address.toLowerCase() === challenge.address.toLowerCase() && + parsed.chainId === challenge.chainId && + parsed.domain === challenge.domain && + parsed.expirationTime?.getTime() === new Date(challenge.expirationTime).getTime() && + parsed.issuedAt?.getTime() === new Date(challenge.issuedAt).getTime() && + parsed.nonce === challenge.nonce && + parsed.scheme === challenge.scheme && + parsed.uri === challenge.uri && + parsed.version === challenge.version + ); +} + +async function verifyWithBaseRpc(config: BackendPlanetConfig, input: SignatureInput): Promise { + const endpoints = [...new Set([config.rpcUrl, ...(config.rpcFallbackUrls ?? [])])].slice(0, 3); + return readWithRpcFallback(endpoints, async (rpcUrl) => { + const client = createPublicClient({ chain: base, transport: http(rpcUrl) }); + if (await client.getChainId() !== BASE_CHAIN_ID) throw new Error('SIWE RPC is not Base mainnet.'); + return client.verifySiweMessage(input); + }); +} + +function defaultDependencies(): SiweAuthDependencies { + return { + generateNonce: generateSiweNonce, + getPrisma: (config) => getPrismaClient(config.databaseUrl), + loadConfig: () => loadBackendPlanetConfig(process.env), + now: () => new Date(), + verifySignature: verifyWithBaseRpc, + }; +} + +function sessionValue(address: Address, issuedAt: Date): string { + return [ + 'v1', + address.toLowerCase(), + issuedAt.getTime().toString(), + (issuedAt.getTime() + SESSION_TTL_MS).toString(), + ].join('.'); +} + +export async function getSiweSessionAddress( + c: Context, + config: BackendPlanetConfig, + now: Date, +): Promise
{ + const { secret } = requireSiweConfig(config); + const value = await getSignedCookie(c, secret, SIWE_SESSION_COOKIE); + if (!value) return undefined; + const [version, rawAddress, rawIssuedAt, rawExpiresAt, extra] = value.split('.'); + if (version !== 'v1' || extra !== undefined || !rawAddress || !isAddress(rawAddress)) return undefined; + const issuedAt = Number(rawIssuedAt); + const expiresAt = Number(rawExpiresAt); + if ( + !Number.isSafeInteger(issuedAt) || + !Number.isSafeInteger(expiresAt) || + expiresAt - issuedAt !== SESSION_TTL_MS || + issuedAt > now.getTime() || + expiresAt <= now.getTime() + ) return undefined; + return getAddress(rawAddress).toLowerCase() as Address; +} + +export function createSiweAuthRoutes( + overrides: Partial = {}, +) { + const dependencies = { ...defaultDependencies(), ...overrides }; + const app = new Hono(); + + app.post('/nonce', async (c) => { + let config: BackendPlanetConfig; + let siwe: RequiredSiweConfig; + try { + config = dependencies.loadConfig(); + if (!config.mineralUpgradesEnabled) return c.json({ error: 'Planet upgrades are disabled.' }, 404); + siwe = requireSiweConfig(config); + } catch { + return c.json({ error: 'SIWE authentication is not configured.' }, 503); + } + if (!isExactSiweRequestOrigin(c, siwe.origin)) { + return c.json({ error: 'Request origin is not allowed.' }, 403); + } + let body: unknown; + try { + body = await readBoundedJson(c.req.raw); + } catch { + return c.json({ error: 'Request body is invalid or too large.' }, 400); + } + const address = body && typeof body === 'object' ? (body as { address?: unknown }).address : undefined; + if (typeof address !== 'string' || !isAddress(address)) { + return c.json({ error: 'A valid wallet address is required.' }, 400); + } + try { + const issuedAt = dependencies.now(); + const nonce = dependencies.generateNonce(); + if (!Number.isFinite(issuedAt.getTime()) || !/^[A-Za-z0-9]{8,96}$/.test(nonce)) { + throw new Error('Invalid SIWE challenge state.'); + } + const row = { + nonce, + walletAddress: getAddress(address).toLowerCase(), + issuedAt, + expiresAt: new Date(issuedAt.getTime() + NONCE_TTL_MS), + }; + const prisma = dependencies.getPrisma(config); + await prisma.siweNonce.deleteMany({ where: { expiresAt: { lte: issuedAt } } }); + await prisma.siweNonce.create({ data: row }); + c.header('cache-control', 'no-store'); + return c.json(challengeFromRow(row, siwe.origin), 201); + } catch { + return c.json({ error: 'SIWE challenge could not be created.' }, 503); + } + }); + + app.post('/verify', async (c) => { + let config: BackendPlanetConfig; + let siwe: RequiredSiweConfig; + try { + config = dependencies.loadConfig(); + if (!config.mineralUpgradesEnabled) return c.json({ error: 'Planet upgrades are disabled.' }, 404); + siwe = requireSiweConfig(config); + } catch { + return c.json({ error: 'SIWE authentication is not configured.' }, 503); + } + if (!isExactSiweRequestOrigin(c, siwe.origin)) { + return c.json({ error: 'Request origin is not allowed.' }, 403); + } + let body: unknown; + try { + body = await readBoundedJson(c.req.raw); + } catch { + return c.json({ error: 'Request body is invalid or too large.' }, 400); + } + const candidate = body && typeof body === 'object' ? body as Record : undefined; + if ( + typeof candidate?.message !== 'string' || + candidate.message.length > 4_096 || + typeof candidate.signature !== 'string' || + !isHex(candidate.signature) + ) return c.json({ error: 'A valid SIWE message and signature are required.' }, 400); + + let parsed: ReturnType; + try { + parsed = parseSiweMessage(candidate.message); + } catch { + return c.json({ error: 'SIWE authentication failed.' }, 401); + } + if (typeof parsed.nonce !== 'string') return c.json({ error: 'SIWE authentication failed.' }, 401); + + const now = dependencies.now(); + let row: SiweNonceRow | null; + try { + row = await dependencies.getPrisma(config).siweNonce.findUnique({ where: { nonce: parsed.nonce } }); + } catch { + return c.json({ error: 'SIWE authentication is unavailable.' }, 503); + } + if (!row || row.issuedAt > now || row.expiresAt <= now) { + return c.json({ error: 'SIWE authentication failed.' }, 401); + } + + const challenge = challengeFromRow(row, siwe.origin); + if ( + candidate.message !== canonicalMessage(challenge) || + !isCanonicalParsedMessage(parsed, challenge) || + !validateSiweMessage({ + address: challenge.address, + domain: challenge.domain, + message: parsed, + nonce: challenge.nonce, + scheme: challenge.scheme, + time: now, + }) + ) return c.json({ error: 'SIWE authentication failed.' }, 401); + + let validSignature: boolean; + try { + validSignature = await dependencies.verifySignature(config, { + address: challenge.address, + domain: challenge.domain, + message: candidate.message, + nonce: challenge.nonce, + scheme: challenge.scheme, + signature: candidate.signature, + time: now, + }); + } catch { + return c.json({ error: 'SIWE authentication is unavailable.' }, 503); + } + if (!validSignature) return c.json({ error: 'SIWE authentication failed.' }, 401); + + try { + const consumed = await dependencies.getPrisma(config).siweNonce.deleteMany({ + where: { + nonce: row.nonce, + walletAddress: row.walletAddress, + expiresAt: { gt: now }, + }, + }); + if (consumed.count !== 1) return c.json({ error: 'SIWE authentication failed.' }, 401); + await setSignedCookie( + c, + SIWE_SESSION_COOKIE, + sessionValue(challenge.address, now), + siwe.secret, + { + httpOnly: true, + maxAge: SESSION_TTL_MS / 1_000, + path: '/', + sameSite: 'Strict', + secure: true, + }, + ); + c.header('cache-control', 'no-store'); + return c.body(null, 204); + } catch { + return c.json({ error: 'SIWE authentication is unavailable.' }, 503); + } + }); + + return app; +} diff --git a/src/hooks/usePlanetUpgrade.test.tsx b/src/hooks/usePlanetUpgrade.test.tsx index 2ef7f46..0f7ad55 100644 --- a/src/hooks/usePlanetUpgrade.test.tsx +++ b/src/hooks/usePlanetUpgrade.test.tsx @@ -5,16 +5,62 @@ import { act, renderHook, waitFor } from '@testing-library/react'; import { afterEach, describe, expect, it, vi } from 'vitest'; import type { ReactNode } from 'react'; -const mocks = vi.hoisted(() => ({ request: vi.fn() })); +const mocks = vi.hoisted(() => ({ + challenge: vi.fn(), + request: vi.fn(), + signMessage: vi.fn(), + verify: vi.fn(), +})); + +vi.mock('wagmi', () => ({ + useSignMessage: () => ({ signMessageAsync: mocks.signMessage }), +})); vi.mock('@/lib/backendApi', async () => { const actual = await vi.importActual('@/lib/backendApi'); - return { ...actual, requestBackendPlanetUpgrade: mocks.request }; + return { + ...actual, + requestBackendPlanetUpgrade: mocks.request, + requestSiweChallenge: mocks.challenge, + verifySiweLogin: mocks.verify, + }; }); +import { BackendApiError } from '@/lib/backendApi'; import { usePlanetUpgrade } from './usePlanetUpgrade'; const ADDRESS = '0x0000000000000000000000000000000000000001' as const; +const CHALLENGE = { + address: ADDRESS, + chainId: 8453, + domain: 'megastera.example', + expirationTime: '2026-08-21T12:05:00.000Z', + issuedAt: '2026-08-21T12:00:00.000Z', + nonce: 'a'.repeat(96), + scheme: 'https', + uri: 'https://megastera.example', + version: '1', +} as const; +const MESSAGE = `https://megastera.example wants you to sign in with your Ethereum account: +${ADDRESS} + + +URI: https://megastera.example +Version: 1 +Chain ID: 8453 +Nonce: ${'a'.repeat(96)} +Issued At: 2026-08-21T12:00:00.000Z +Expiration Time: 2026-08-21T12:05:00.000Z`; + +const receipt = { + purchaseId: 'purchase-1', + planetId: 'planet-1', + ownerAddress: ADDRESS, + targetLevel: 1, + bonusBpsAfter: 1000, + costMicros: '200000', + purchasedAt: '2026-08-13T12:00:00.000Z', +}; function wrapperFor(queryClient: QueryClient) { return ({ children }: { children: ReactNode }) => ( @@ -24,28 +70,27 @@ function wrapperFor(queryClient: QueryClient) { describe('usePlanetUpgrade', () => { afterEach(() => { + mocks.challenge.mockReset(); mocks.request.mockReset(); + mocks.signMessage.mockReset(); + mocks.verify.mockReset(); }); it('invalidates and refetches wallet mining plus both live leaderboard queries after the receipt', async () => { const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } } }); const invalidateQueries = vi.spyOn(queryClient, 'invalidateQueries').mockResolvedValue(); const refetchQueries = vi.spyOn(queryClient, 'refetchQueries').mockResolvedValue(); - mocks.request.mockResolvedValue({ - purchaseId: 'purchase-1', - planetId: 'planet-1', - ownerAddress: ADDRESS, - targetLevel: 1, - bonusBpsAfter: 1000, - costMicros: '200000', - purchasedAt: '2026-08-13T12:00:00.000Z', - }); + mocks.request.mockResolvedValue(receipt); const { result } = renderHook(() => usePlanetUpgrade(ADDRESS), { wrapper: wrapperFor(queryClient) }); act(() => result.current.mutate({ planetId: 'planet-1', targetLevel: 1 })); await waitFor(() => expect(result.current.isSuccess).toBe(true)); - expect(mocks.request).toHaveBeenCalledWith({ planetId: 'planet-1', targetLevel: 1 }); + expect(mocks.request).toHaveBeenCalledWith({ + expectedAddress: ADDRESS, + planetId: 'planet-1', + targetLevel: 1, + }); const invalidatedKeys = invalidateQueries.mock.calls.map(([input]) => input?.queryKey); expect(invalidatedKeys).toEqual(expect.arrayContaining([ @@ -60,4 +105,63 @@ describe('usePlanetUpgrade', () => { ['megastera-backend', expect.any(String), 'leaderboard', 'current-wallet', ADDRESS], ])); }); + + it('signs one canonical SIWE challenge after 401 and retries the upgrade once', async () => { + const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } } }); + mocks.request + .mockRejectedValueOnce(new BackendApiError('Wallet authentication is required.', 401)) + .mockResolvedValueOnce(receipt); + mocks.challenge.mockResolvedValue(CHALLENGE); + mocks.signMessage.mockResolvedValue('0x12'); + mocks.verify.mockResolvedValue(undefined); + + const { result } = renderHook(() => usePlanetUpgrade(ADDRESS), { wrapper: wrapperFor(queryClient) }); + act(() => result.current.mutate({ planetId: 'planet-1', targetLevel: 1 })); + + await waitFor(() => expect(result.current.isSuccess).toBe(true)); + expect(mocks.request).toHaveBeenCalledTimes(2); + expect(mocks.request).toHaveBeenNthCalledWith(1, { + expectedAddress: ADDRESS, + planetId: 'planet-1', + targetLevel: 1, + }); + expect(mocks.request).toHaveBeenNthCalledWith(2, { + expectedAddress: ADDRESS, + planetId: 'planet-1', + targetLevel: 1, + }); + expect(mocks.signMessage).toHaveBeenCalledWith({ account: ADDRESS, message: MESSAGE }); + expect(mocks.verify).toHaveBeenCalledWith({ message: MESSAGE, signature: '0x12' }); + }); + + it('stops after the single authenticated retry', async () => { + const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } } }); + mocks.request.mockRejectedValue(new BackendApiError('Wallet authentication is required.', 401)); + mocks.challenge.mockResolvedValue(CHALLENGE); + mocks.signMessage.mockResolvedValue('0x12'); + mocks.verify.mockResolvedValue(undefined); + + const { result } = renderHook(() => usePlanetUpgrade(ADDRESS), { wrapper: wrapperFor(queryClient) }); + act(() => result.current.mutate({ planetId: 'planet-1', targetLevel: 1 })); + + await waitFor(() => expect(result.current.isError).toBe(true)); + expect(mocks.request).toHaveBeenCalledTimes(2); + expect(mocks.challenge).toHaveBeenCalledOnce(); + expect(mocks.signMessage).toHaveBeenCalledOnce(); + expect(mocks.verify).toHaveBeenCalledOnce(); + }); + + it('does not start SIWE for an authenticated non-owner error', async () => { + const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } } }); + mocks.request.mockRejectedValue(new BackendApiError('Authenticated wallet does not own this Planet.', 403)); + + const { result } = renderHook(() => usePlanetUpgrade(ADDRESS), { wrapper: wrapperFor(queryClient) }); + act(() => result.current.mutate({ planetId: 'planet-1', targetLevel: 1 })); + + await waitFor(() => expect(result.current.isError).toBe(true)); + expect(mocks.request).toHaveBeenCalledOnce(); + expect(mocks.challenge).not.toHaveBeenCalled(); + expect(mocks.signMessage).not.toHaveBeenCalled(); + expect(mocks.verify).not.toHaveBeenCalled(); + }); }); diff --git a/src/hooks/usePlanetUpgrade.ts b/src/hooks/usePlanetUpgrade.ts index a348b37..d48c179 100644 --- a/src/hooks/usePlanetUpgrade.ts +++ b/src/hooks/usePlanetUpgrade.ts @@ -1,6 +1,14 @@ import { useMutation, useQueryClient } from '@tanstack/react-query'; import type { Address } from 'viem'; -import { BACKEND_API_BASE_URL, requestBackendPlanetUpgrade } from '@/lib/backendApi'; +import { createSiweMessage } from 'viem/siwe'; +import { useSignMessage } from 'wagmi'; +import { + BACKEND_API_BASE_URL, + BackendApiError, + requestBackendPlanetUpgrade, + requestSiweChallenge, + verifySiweLogin, +} from '@/lib/backendApi'; export type PlanetUpgradeVariables = { planetId: string; @@ -16,11 +24,36 @@ const currentWalletLeaderboardQueryKey = (address: Address) => export function usePlanetUpgrade(address: Address | undefined) { const queryClient = useQueryClient(); + const { signMessageAsync } = useSignMessage(); return useMutation({ - mutationFn: (variables: PlanetUpgradeVariables) => { + mutationFn: async (variables: PlanetUpgradeVariables) => { if (!address) throw new Error('A connected wallet is required.'); - return requestBackendPlanetUpgrade(variables); + const requestUpgrade = () => requestBackendPlanetUpgrade({ + ...variables, + expectedAddress: address, + }); + try { + return await requestUpgrade(); + } catch (error) { + if (!(error instanceof BackendApiError) || error.status !== 401) throw error; + } + + const challenge = await requestSiweChallenge(address); + const message = createSiweMessage({ + address: challenge.address, + chainId: challenge.chainId, + domain: challenge.domain, + expirationTime: new Date(challenge.expirationTime), + issuedAt: new Date(challenge.issuedAt), + nonce: challenge.nonce, + scheme: challenge.scheme, + uri: challenge.uri, + version: challenge.version, + }); + const signature = await signMessageAsync({ account: address, message }); + await verifySiweLogin({ message, signature }); + return requestUpgrade(); }, onSuccess: async (_receipt) => { if (!address) return; diff --git a/src/lib/backendApi.test.ts b/src/lib/backendApi.test.ts index 7641f9e..e379302 100644 --- a/src/lib/backendApi.test.ts +++ b/src/lib/backendApi.test.ts @@ -1,5 +1,13 @@ import { afterEach, describe, expect, it, vi } from 'vitest'; -import { backendApiUrl, fetchBackendPlanets, requestBackendPlanetGeneration } from './backendApi'; +import { + backendApiUrl, + type BackendApiError, + fetchBackendPlanets, + requestBackendPlanetGeneration, + requestBackendPlanetUpgrade, + requestSiweChallenge, + verifySiweLogin, +} from './backendApi'; const ADDRESS = '0x0000000000000000000000000000000000000001' as const; const TX = `0x${'a'.repeat(64)}` as const; @@ -45,7 +53,11 @@ describe('backendApiUrl', () => { }); describe('backend Planet API', () => { - afterEach(() => vi.restoreAllMocks()); + afterEach(() => { + vi.restoreAllMocks(); + vi.unstubAllEnvs(); + vi.unstubAllGlobals(); + }); it('fetches and validates backend Planet rows', async () => { const fetchMock = vi.spyOn(globalThis, 'fetch').mockResolvedValue( @@ -75,10 +87,6 @@ describe('backend Planet API', () => { }); it('exposes an immutable receipt-only Planet upgrade request', async () => { - const module = await import('./backendApi'); - expect(module.requestBackendPlanetUpgrade).toEqual(expect.any(Function)); - if (typeof module.requestBackendPlanetUpgrade !== 'function') return; - const fetchMock = vi.spyOn(globalThis, 'fetch').mockResolvedValue( new Response(JSON.stringify({ upgrade: { purchaseId: 'purchase-1', @@ -92,7 +100,11 @@ describe('backend Planet API', () => { } }), { status: 200 }), ); - await expect(module.requestBackendPlanetUpgrade({ planetId: 'planet-1', targetLevel: 1 })).resolves.toEqual({ + await expect(requestBackendPlanetUpgrade({ + expectedAddress: ADDRESS, + planetId: 'planet-1', + targetLevel: 1, + })).resolves.toEqual({ purchaseId: 'purchase-1', planetId: 'planet-1', ownerAddress: ADDRESS, @@ -101,6 +113,98 @@ describe('backend Planet API', () => { costMicros: '200000', purchasedAt: '2026-08-13T12:00:00.000Z', }); - expect(fetchMock).toHaveBeenCalledWith('/api/planets/planet-1/upgrade', expect.objectContaining({ method: 'POST' })); + expect(fetchMock).toHaveBeenCalledWith('/api/planets/planet-1/upgrade', expect.objectContaining({ + body: JSON.stringify({ expectedAddress: ADDRESS, targetLevel: 1 }), + credentials: 'same-origin', + method: 'POST', + })); + }); + + it('preserves an upgrade 401 so the caller can start SIWE once', async () => { + vi.spyOn(globalThis, 'fetch').mockResolvedValue( + new Response(JSON.stringify({ error: 'Wallet authentication is required.' }), { status: 401 }), + ); + + await expect(requestBackendPlanetUpgrade({ + expectedAddress: ADDRESS, + planetId: 'planet-1', + targetLevel: 1, + })).rejects.toEqual(expect.objectContaining>({ + message: 'Wallet authentication is required.', + status: 401, + })); + }); + + it('uses same-origin credentials for the minimal SIWE challenge and verification flow', async () => { + const challenge = { + address: ADDRESS, + chainId: 8453, + domain: 'megastera.example', + expirationTime: '2026-08-21T12:05:00.000Z', + issuedAt: '2026-08-21T12:00:00.000Z', + nonce: 'a'.repeat(96), + scheme: 'https', + uri: 'https://megastera.example', + version: '1', + } as const; + const fetchMock = vi.spyOn(globalThis, 'fetch') + .mockResolvedValueOnce(new Response(JSON.stringify(challenge), { status: 201 })) + .mockResolvedValueOnce(new Response(null, { status: 204 })); + + await expect(requestSiweChallenge(ADDRESS)).resolves.toEqual(challenge); + await expect(verifySiweLogin({ message: 'canonical message', signature: '0x12' })).resolves.toBeUndefined(); + + expect(fetchMock).toHaveBeenNthCalledWith(1, '/api/auth/siwe/nonce', expect.objectContaining({ + body: JSON.stringify({ address: ADDRESS }), + credentials: 'same-origin', + method: 'POST', + })); + expect(fetchMock).toHaveBeenNthCalledWith(2, '/api/auth/siwe/verify', expect.objectContaining({ + body: JSON.stringify({ message: 'canonical message', signature: '0x12' }), + credentials: 'same-origin', + method: 'POST', + })); + }); + + it('refuses a cross-origin SIWE backend before requesting a challenge', async () => { + vi.stubGlobal('location', new URL('https://megastera.example')); + vi.stubEnv('VITE_BACKEND_API_BASE_URL', 'https://evil.example'); + vi.resetModules(); + const isolatedApi = await import('./backendApi'); + const fetchMock = vi.spyOn(globalThis, 'fetch').mockResolvedValue( + new Response(JSON.stringify({ + address: ADDRESS, + chainId: 8453, + domain: 'megastera.example', + expirationTime: '2026-08-21T12:05:00.000Z', + issuedAt: '2026-08-21T12:00:00.000Z', + nonce: 'a'.repeat(96), + scheme: 'https', + uri: 'https://megastera.example', + version: '1', + }), { status: 201 }), + ); + + await expect(isolatedApi.requestSiweChallenge(ADDRESS)).rejects.toThrow(/same-origin/i); + expect(fetchMock).not.toHaveBeenCalled(); + }); + + it('refuses a SIWE challenge that is not pinned to the page origin', async () => { + vi.stubGlobal('location', new URL('https://megastera.example')); + vi.spyOn(globalThis, 'fetch').mockResolvedValue( + new Response(JSON.stringify({ + address: ADDRESS, + chainId: 8453, + domain: 'evil.example', + expirationTime: '2026-08-21T12:05:00.000Z', + issuedAt: '2026-08-21T12:00:00.000Z', + nonce: 'a'.repeat(96), + scheme: 'https', + uri: 'https://evil.example', + version: '1', + }), { status: 201 }), + ); + + await expect(requestSiweChallenge(ADDRESS)).rejects.toThrow(/malformed/i); }); }); diff --git a/src/lib/backendApi.ts b/src/lib/backendApi.ts index 057dda8..ad5058d 100644 --- a/src/lib/backendApi.ts +++ b/src/lib/backendApi.ts @@ -19,6 +19,15 @@ export function backendApiFetch(path: string, init?: RequestInit): Promise { + const url = backendApiUrl(path); + if ( + BACKEND_API_BASE_URL && + (!globalThis.location?.origin || new URL(url).origin !== globalThis.location.origin) + ) throw new Error('Wallet authentication requires a same-origin backend.'); + return fetch(url, init); +} + export type BackendPlanet = { planetId: string; chainId: number; @@ -66,6 +75,32 @@ export type BackendPlanetUpgradeReceipt = { purchasedAt: string; }; +export type SiweChallenge = { + address: Address; + chainId: 8453; + domain: string; + expirationTime: string; + issuedAt: string; + nonce: string; + scheme: 'https'; + uri: string; + version: '1'; +}; + +export class BackendApiError extends Error { + constructor(message: string, readonly status: number) { + super(message); + this.name = 'BackendApiError'; + } +} + +function responseError(response: Response, payload: unknown, fallback: string): BackendApiError { + const message = payload && typeof payload === 'object' && typeof (payload as { error?: unknown }).error === 'string' + ? (payload as { error: string }).error + : fallback; + return new BackendApiError(message, response.status); +} + function parseBackendPlanet(value: unknown): BackendPlanet { if (!value || typeof value !== 'object') throw new Error('Backend Planet response is malformed.'); const candidate = value as Partial; @@ -232,20 +267,22 @@ function parseBackendPlanetUpgradeReceipt(value: unknown): BackendPlanetUpgradeR } export async function requestBackendPlanetUpgrade(args: { + expectedAddress: Address; planetId: string; targetLevel: number; }): Promise { - const response = await backendApiFetch(`/api/planets/${encodeURIComponent(args.planetId)}/upgrade`, { + const response = await sameOriginBackendApiFetch(`/api/planets/${encodeURIComponent(args.planetId)}/upgrade`, { method: 'POST', headers: { 'content-type': 'application/json' }, - body: JSON.stringify({ targetLevel: args.targetLevel }), + credentials: 'same-origin', + body: JSON.stringify({ + expectedAddress: getAddress(args.expectedAddress), + targetLevel: args.targetLevel, + }), }); const payload = await response.json().catch(() => undefined); if (!response.ok) { - const message = payload && typeof payload === 'object' && typeof (payload as { error?: unknown }).error === 'string' - ? (payload as { error: string }).error - : `Backend Planet upgrade returned HTTP ${response.status}.`; - throw new Error(message); + throw responseError(response, payload, `Backend Planet upgrade returned HTTP ${response.status}.`); } if (!payload || typeof payload !== 'object' || !('upgrade' in payload)) { throw new Error('Backend Planet upgrade response is malformed.'); @@ -253,6 +290,78 @@ export async function requestBackendPlanetUpgrade(args: { return parseBackendPlanetUpgradeReceipt((payload as { upgrade: unknown }).upgrade); } +function parseSiweChallenge( + value: unknown, + expectedAddress: Address, + expectedOrigin = globalThis.location?.origin, +): SiweChallenge { + if (!value || typeof value !== 'object') throw new Error('SIWE challenge response is malformed.'); + const candidate = value as Partial; + const issuedAt = new Date(candidate.issuedAt ?? ''); + const expirationTime = new Date(candidate.expirationTime ?? ''); + let uri: URL; + try { + uri = new URL(candidate.uri ?? ''); + } catch { + throw new Error('SIWE challenge response is malformed.'); + } + if ( + !isAddress(candidate.address ?? '') || + getAddress(candidate.address as Address) !== getAddress(expectedAddress) || + candidate.chainId !== 8453 || + typeof candidate.domain !== 'string' || + candidate.domain !== uri.host || + !Number.isFinite(issuedAt.getTime()) || + !Number.isFinite(expirationTime.getTime()) || + expirationTime <= issuedAt || + typeof candidate.nonce !== 'string' || + !/^[A-Za-z0-9]{8,96}$/.test(candidate.nonce) || + candidate.scheme !== 'https' || + uri.protocol !== 'https:' || + uri.origin !== candidate.uri || + (expectedOrigin !== undefined && candidate.uri !== expectedOrigin) || + candidate.version !== '1' + ) throw new Error('SIWE challenge response is malformed.'); + return { + address: getAddress(candidate.address as Address), + chainId: 8453, + domain: candidate.domain, + expirationTime: expirationTime.toISOString(), + issuedAt: issuedAt.toISOString(), + nonce: candidate.nonce, + scheme: 'https', + uri: candidate.uri, + version: '1', + }; +} + +export async function requestSiweChallenge(address: Address): Promise { + const expectedAddress = getAddress(address); + const response = await sameOriginBackendApiFetch('/api/auth/siwe/nonce', { + method: 'POST', + headers: { 'content-type': 'application/json' }, + credentials: 'same-origin', + body: JSON.stringify({ address: expectedAddress }), + }); + const payload = await response.json().catch(() => undefined); + if (!response.ok) { + throw responseError(response, payload, `SIWE challenge returned HTTP ${response.status}.`); + } + return parseSiweChallenge(payload, expectedAddress); +} + +export async function verifySiweLogin(args: { message: string; signature: Hex }): Promise { + const response = await sameOriginBackendApiFetch('/api/auth/siwe/verify', { + method: 'POST', + headers: { 'content-type': 'application/json' }, + credentials: 'same-origin', + body: JSON.stringify(args), + }); + if (response.ok) return; + const payload = await response.json().catch(() => undefined); + throw responseError(response, payload, `SIWE verification returned HTTP ${response.status}.`); +} + export async function requestBackendPlanetGenerationBatch(args: { recipient: Address; tickets: readonly PurchasedTicket[];