Let a human owner authorize another human in the started room to start a fixed difficulty once within 24 hours. The owner retains the seat, cookie, private hand, recovery setup and takeback control. Consent is explicit even while online; neither host status nor inactivity authorizes a takeover. Activation enters the existing paced private-view AI path without strategic changes. Add additive migration 0006, both exact session fences, owner/delegate-only metadata in the authenticated room snapshot, atomic CAS activation and consumption, expiry and terminal retry receipts. Replacement hides older consent; own AI changes invalidate unused consent. Recovery or handover of either bound seat invalidates the grant. Future-version guards prevent stale computed state from overwriting a racing action. Exact browser retry records retain the original operation/version across refresh and cannot rearm old consent. Shared HTTP continuation preserves coalescing across ordinary and control routes. Independent review found no material remaining issue. Revoke messaging accurately handles activation winning the race. Browser QA exercised grant/revoke, preserved consent after refresh, reciprocal fixed-profile activation, consumed receipts, keyboard takeback and private ownership. The panel now remains expanded after success and action buttons are at least 44px. Responsive screenshot acceptance remains open because the browser viewport override targeted a failed secondary-origin tab; desktop controls and no-overflow width were verified. The QA room is stopped at a genuine human setup decision with both seats taken back. Types, lint, all 4906 offline tests, production build and all 45 HTTP tests pass on the stable source fingerprint. Seven new offline cases cover client consent/retry validation and real SQLite privacy, restart, one-use races, future versions, takeback, expiry and both-seat recovery/handover; two new HTTP cases cover authentication, injection, fixed-profile continuation and takeback. The first broad run exposed 68 legacy VM fixtures missing the new production dependency; their mappings were updated and the real shared continuation remains exercised. The historical 0005 migration test verifies backfill before applying 0006 for current code. All 1174 original rooms, 2456 seats and every prior recovery/entry/handover/migration row remain unchanged. SQLite integrity and foreign keys pass; migration and QA added 88 rooms and 188 seats. No reset, server restart, usage check or automation was performed. The current Sites integration has no supported durable Cron/DO provisioning path. Document this platform blocker rather than adding an inert scheduled export; unattended resumption and broader network-failure acceptance remain unfinished. Full rules, component, AI strength and publication gates remain closed. Verified source tree: 2d86fc611e9ef4f5a10db10f96687a31db1ec238908ecf1e9333c50fac9ccaa8
197 lines
6.3 KiB
TypeScript
197 lines
6.3 KiB
TypeScript
import {
|
|
authenticate,
|
|
createSeatHandover,
|
|
revokeSeatHandover,
|
|
claimSeatHandover,
|
|
recoverSeat,
|
|
SeatControlError,
|
|
setRecoveryKey,
|
|
setSeatAiDelegate,
|
|
revokeSeatAiDelegate,
|
|
useSeatAiDelegate as activateSeatAiDelegate,
|
|
needsAutomaticRoomRecovery,
|
|
} from '@/db/rooms';
|
|
import { RuleError } from '@/game/engine';
|
|
import { validSeatAiDelegateRequest } from '@/lib/seat-ai-delegation';
|
|
import { resumeRoom } from '@/db/room-continuation';
|
|
import { waitUntil } from 'cloudflare:workers';
|
|
const noStore = { 'Cache-Control': 'no-store' };
|
|
export async function POST(req: Request) {
|
|
try {
|
|
const url = new URL(req.url);
|
|
if (req.headers.get('origin') && req.headers.get('origin') !== url.origin)
|
|
throw new SeatControlError(
|
|
'Invalid request origin.',
|
|
'INVALID_ORIGIN',
|
|
403,
|
|
);
|
|
const code = url.pathname.split('/').at(-2)!.toUpperCase();
|
|
if (!/^[A-Z2-9]{8}$/.test(code))
|
|
throw new SeatControlError(
|
|
'Enter the eight-character room code.',
|
|
'INVALID_CONTROL_REQUEST',
|
|
400,
|
|
);
|
|
const raw = await req.text();
|
|
if (raw.length > 4000)
|
|
throw new SeatControlError(
|
|
'Request too large.',
|
|
'REQUEST_TOO_LARGE',
|
|
413,
|
|
);
|
|
const body: unknown = JSON.parse(raw);
|
|
if (!body || typeof body !== 'object' || Array.isArray(body))
|
|
throw new SeatControlError(
|
|
'Choose a recovery operation.',
|
|
'INVALID_CONTROL_REQUEST',
|
|
400,
|
|
);
|
|
const input = body as Record<string, unknown>;
|
|
const token =
|
|
req.headers
|
|
.get('cookie')
|
|
?.split(';')
|
|
.map((part) => part.trim())
|
|
.find((part) => part.startsWith(`dune_${code}=`))
|
|
?.split('=')[1] ?? '';
|
|
if (
|
|
input.type === 'setSeatAiDelegate' ||
|
|
input.type === 'revokeSeatAiDelegate' ||
|
|
input.type === 'useSeatAiDelegate'
|
|
) {
|
|
if (!validSeatAiDelegateRequest(input))
|
|
throw new SeatControlError(
|
|
'The AI permission request is invalid.',
|
|
'INVALID_CONTROL_REQUEST',
|
|
400,
|
|
);
|
|
const auth = await authenticate(code, token);
|
|
const result =
|
|
input.type === 'setSeatAiDelegate'
|
|
? await setSeatAiDelegate(code, auth, input.version, {
|
|
grantId: input.grantId,
|
|
delegateId: input.delegateId,
|
|
difficulty: input.difficulty,
|
|
})
|
|
: input.type === 'revokeSeatAiDelegate'
|
|
? await revokeSeatAiDelegate(
|
|
code,
|
|
auth,
|
|
input.version,
|
|
input.grantId,
|
|
)
|
|
: await activateSeatAiDelegate(code, auth, input.version, {
|
|
ownerId: input.ownerId,
|
|
grantId: input.grantId,
|
|
});
|
|
if (result.view.botsPending || needsAutomaticRoomRecovery(result.view))
|
|
waitUntil(resumeRoom(code));
|
|
return Response.json(result, { headers: noStore });
|
|
}
|
|
if (
|
|
input.type === 'setRecoveryKey' ||
|
|
input.type === 'createSeatHandover' ||
|
|
input.type === 'revokeSeatHandover'
|
|
) {
|
|
const auth = await authenticate(code, token);
|
|
if (input.type === 'createSeatHandover')
|
|
return Response.json(
|
|
await createSeatHandover(code, auth, input.version, {
|
|
offerId: input.offerId,
|
|
handoverSecret: input.handoverSecret,
|
|
}),
|
|
{ headers: noStore },
|
|
);
|
|
if (input.type === 'revokeSeatHandover')
|
|
return Response.json(
|
|
await revokeSeatHandover(code, auth, input.version, input.offerId),
|
|
{ headers: noStore },
|
|
);
|
|
return Response.json(
|
|
await setRecoveryKey(code, auth, input.version, input.recoverySecret),
|
|
{ headers: noStore },
|
|
);
|
|
}
|
|
if (input.type !== 'recoverSeat' && input.type !== 'claimSeatHandover')
|
|
throw new SeatControlError(
|
|
'Choose a recovery operation.',
|
|
'INVALID_CONTROL_REQUEST',
|
|
400,
|
|
);
|
|
if (input.type === 'claimSeatHandover' && token) {
|
|
let existing;
|
|
try {
|
|
existing = await authenticate(code, token);
|
|
} catch (error) {
|
|
if (!(error instanceof RuleError)) throw error;
|
|
}
|
|
if (existing && existing.playerId !== input.playerId)
|
|
throw new SeatControlError(
|
|
'This browser already controls another seat in this room. Use a separate browser profile to accept the handover.',
|
|
'ALREADY_SEATED',
|
|
409,
|
|
);
|
|
}
|
|
const result =
|
|
input.type === 'claimSeatHandover'
|
|
? await claimSeatHandover(code, {
|
|
playerId: input.playerId,
|
|
offerId: input.offerId,
|
|
handoverSecret: input.handoverSecret,
|
|
operationId: input.operationId,
|
|
newSessionToken: input.newSessionToken,
|
|
})
|
|
: await recoverSeat(code, {
|
|
playerId: input.playerId,
|
|
recoverySecret: input.recoverySecret,
|
|
operationId: input.operationId,
|
|
newSessionToken: input.newSessionToken,
|
|
});
|
|
return Response.json(
|
|
{
|
|
view: result.view,
|
|
...('transferred' in result
|
|
? { transferred: result.transferred }
|
|
: { recovered: result.recovered }),
|
|
replayed: result.replayed,
|
|
},
|
|
{
|
|
headers: {
|
|
...noStore,
|
|
'Set-Cookie': `dune_${code}=${result.token}; HttpOnly; SameSite=Strict; Path=/api/rooms/${code}; Max-Age=2592000${url.protocol === 'https:' ? '; Secure' : ''}`,
|
|
},
|
|
},
|
|
);
|
|
} catch (error) {
|
|
return Response.json(
|
|
{
|
|
error:
|
|
error instanceof RuleError
|
|
? error.message
|
|
: error instanceof SyntaxError
|
|
? 'Invalid JSON.'
|
|
: 'The server could not complete this seat request.',
|
|
code:
|
|
error instanceof SeatControlError
|
|
? error.code
|
|
: error instanceof RuleError
|
|
? 'INVALID_SESSION'
|
|
: error instanceof SyntaxError
|
|
? 'INVALID_CONTROL_REQUEST'
|
|
: 'SERVER_ERROR',
|
|
},
|
|
{
|
|
status:
|
|
error instanceof SeatControlError
|
|
? error.status
|
|
: error instanceof RuleError
|
|
? 409
|
|
: error instanceof SyntaxError
|
|
? 400
|
|
: 500,
|
|
headers: noStore,
|
|
},
|
|
);
|
|
}
|
|
}
|