User management: signing in is required before anything is loaded, the sign-in screen is drawn in the same canvas (user name, password as bullets, Enter moves on and submits) and the editor is built only after it; the API gained auth/session, auth/login and auth/logout while every other route answers 401 without a session, projects carry an owner and a foreign one comes back as 404, accounts live in data/users.json with a password hash and sessions as files in data/sessions with a sliding 30 days, so a build under the open tab does not sign anybody out; Logout sits at the far right of the toolbar and, as asked in the issue, does not reload the page: Editor.dispose() takes the editor down while the canvas stays, which is why the autosave, the focus handlers, the window listeners of the tilemap panel, the shortcuts and the plugins all got a way back; the tools sign in as e2e (tools/lib/auth.mjs, password from GAME_MAKER_E2E_PASSWORD or the git-ignored data/e2e-password.txt) and the browser gets the same session by cookie, new e2e module 45 covers the screen, the wrong pair, the bullets, logout without a reload and signing in again, new unit tests for HttpAuthStore and for what a session leaves behind (#177)
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
1 parent
60ea56a2ce
commit
8e4bb6e1f9
38 files changed
+1530
-139
No files matched your search
@@ -14,6 +14,7 @@
|
||||
import { mkdir, writeFile } from 'node:fs/promises';
|
||||
import { dirname, resolve } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { E2E_USER } from '../lib/auth.mjs';
|
||||
import { PROJECTS } from '../lib/projects.mjs';
|
||||
|
||||
const root = resolve(dirname(fileURLToPath(import.meta.url)), '../..');
|
||||
@@ -25,6 +26,9 @@ for (const [name, id] of Object.entries(PROJECTS)) {
|
||||
const doc = {
|
||||
id,
|
||||
name,
|
||||
// The test projects belong to the `e2e` account (#177); a file without an owner is invisible
|
||||
// to everybody, so the shells have to say whose they are.
|
||||
owner: E2E_USER,
|
||||
revision: 0,
|
||||
updatedAt: '1970-01-01T00:00:00Z',
|
||||
project: {},
|
||||
|
||||
+13
-4
@@ -14,8 +14,17 @@ game_maker_serve() {
|
||||
mkdir -p "$root/data/projects" "$root/data/textures"
|
||||
node "$root/tools/ci/project-shells.mjs"
|
||||
|
||||
# A server from an earlier step of the same job is fine to keep.
|
||||
if curl -sf "${GAME_MAKER_BASE_URL}api/index.php?r=projects" >/dev/null 2>&1; then
|
||||
# Since #177 the API needs a session, and the check tools sign in as `e2e`. A fresh checkout has
|
||||
# no accounts at all, so the job makes the one it needs, with a password of its own.
|
||||
if [ ! -f "$root/data/e2e-password.txt" ]; then
|
||||
head -c 24 /dev/urandom | base64 | tr -d '\n' >"$root/data/e2e-password.txt"
|
||||
echo >>"$root/data/e2e-password.txt"
|
||||
fi
|
||||
php "$root/tools/make-user.php" e2e "$(cat "$root/data/e2e-password.txt")"
|
||||
|
||||
# A server from an earlier step of the same job is fine to keep. Asked of the one route that
|
||||
# answers without a session, so "is it up" does not depend on being signed in.
|
||||
if curl -sf "${GAME_MAKER_BASE_URL}api/index.php?r=auth/session" >/dev/null 2>&1; then
|
||||
echo "server already up at $GAME_MAKER_BASE_URL"
|
||||
return 0
|
||||
fi
|
||||
@@ -26,10 +35,10 @@ game_maker_serve() {
|
||||
PHP_CLI_SERVER_WORKERS=8 php -S 0.0.0.0:8080 -t /srv >/tmp/php-server.log 2>&1 &
|
||||
|
||||
for _ in $(seq 60); do
|
||||
curl -sf "${GAME_MAKER_BASE_URL}api/index.php?r=projects" >/dev/null 2>&1 && break
|
||||
curl -sf "${GAME_MAKER_BASE_URL}api/index.php?r=auth/session" >/dev/null 2>&1 && break
|
||||
sleep 0.5
|
||||
done
|
||||
if ! curl -sf "${GAME_MAKER_BASE_URL}api/index.php?r=projects" >/dev/null 2>&1; then
|
||||
if ! curl -sf "${GAME_MAKER_BASE_URL}api/index.php?r=auth/session" >/dev/null 2>&1; then
|
||||
echo "the server never came up" >&2
|
||||
tail -20 /tmp/php-server.log >&2
|
||||
return 1
|
||||
|
||||
@@ -0,0 +1,164 @@
|
||||
import { e2ePassword, E2E_USER } from '../lib/auth.mjs';
|
||||
|
||||
/**
|
||||
* Signing in and out (#177), driven through the real screen: the rest of the suite gets its
|
||||
* session handed to the browser as a cookie, so this is the only step that sees the sign-in
|
||||
* screen at all.
|
||||
*
|
||||
* It runs last and hands the editor back the way it found it: signed in, with the fixture open.
|
||||
*/
|
||||
export async function login(t) {
|
||||
const {
|
||||
check,
|
||||
cdp,
|
||||
sleep,
|
||||
evaluate,
|
||||
json,
|
||||
locate,
|
||||
find,
|
||||
press,
|
||||
typeText,
|
||||
mouse,
|
||||
shot,
|
||||
baseUrl,
|
||||
projectId,
|
||||
} = t;
|
||||
|
||||
const password = await e2ePassword();
|
||||
|
||||
/** Loads the page without handing the browser a session first. */
|
||||
const openSignedOut = async () => {
|
||||
await cdp.send('Network.clearBrowserCookies');
|
||||
await cdp.send('Page.navigate', { url: `${baseUrl}?project=${projectId}` });
|
||||
await sleep(3000);
|
||||
};
|
||||
/**
|
||||
* Waits for the page to be showing one of the two screens. Signing in and out each mean a round
|
||||
* trip to the server – deadlines guessed for that are how a check becomes a coin toss.
|
||||
*/
|
||||
const showing =
|
||||
// The editor counts as up once the project is in it, not when its hook appears: the hook is
|
||||
// installed before the project is fetched, and in a chained run that fetch is long enough for
|
||||
// a check in between to read the empty project the editor starts out with.
|
||||
{
|
||||
editor: `__gm?.state?.project?.id === ${JSON.stringify(projectId)}`,
|
||||
login: 'Boolean(window.__gm?.login)',
|
||||
};
|
||||
const waitForScreen = async (which) => {
|
||||
for (let waited = 0; waited < 15000; waited += 250) {
|
||||
try {
|
||||
if (await evaluate(`Boolean(${showing[which]})`)) return true;
|
||||
} catch {
|
||||
// "Inspected target navigated or closed": only `openSignedOut` navigates here, and asking
|
||||
// across it is not a reason to give up.
|
||||
}
|
||||
await sleep(250);
|
||||
}
|
||||
return false;
|
||||
};
|
||||
|
||||
await openSignedOut();
|
||||
const screenHook = await json(
|
||||
'({ login: Boolean(window.__gm?.login), editor: Boolean(window.__gm?.state) })',
|
||||
);
|
||||
check(
|
||||
'without a session the sign-in screen stands where the editor would',
|
||||
screenHook.login && !screenHook.editor && Boolean(await find('Sign in')),
|
||||
screenHook,
|
||||
);
|
||||
|
||||
// The user name alone: refused by the form itself, before anything is sent.
|
||||
await typeText(E2E_USER);
|
||||
await press('Enter');
|
||||
await press('Enter');
|
||||
check(
|
||||
'an empty password is refused without asking the server',
|
||||
(await json('__gm.login()')).message === 'Enter your password',
|
||||
await json('__gm.login()'),
|
||||
);
|
||||
|
||||
await typeText('not-the-password');
|
||||
await press('Enter');
|
||||
await sleep(600);
|
||||
// What the message says about a *wrong* password is checked in the unit tests: the live server
|
||||
// sits behind a firewall that answers every non-2xx with its own 418 page, so the wording of the
|
||||
// API's 401 only survives where nothing sits in between. That it is refused at all, and that
|
||||
// nobody gets in, holds everywhere – and that is what this check is about.
|
||||
check(
|
||||
'a wrong password is refused and leaves the screen standing',
|
||||
(await json('__gm.login()')).message !== '' &&
|
||||
Boolean(await find('Sign in')) &&
|
||||
!(await evaluate('Boolean(window.__gm?.state)')),
|
||||
await json('__gm.login()'),
|
||||
);
|
||||
|
||||
// Select-all first: the failed attempt left its text in the field.
|
||||
await press('a', { ctrl: true });
|
||||
await typeText(password);
|
||||
const bullets = '•'.repeat(password.length);
|
||||
check(
|
||||
'the password is drawn as bullets, never as itself',
|
||||
Boolean(await find(bullets)) && (await find(password)) === null,
|
||||
{ bullets: bullets.length },
|
||||
);
|
||||
await shot('45-login');
|
||||
|
||||
await press('Enter');
|
||||
await waitForScreen('editor');
|
||||
const loaded = await json(
|
||||
'({ editor: Boolean(window.__gm?.state), project: __gm?.state?.project?.name ?? null, title: document.title })',
|
||||
);
|
||||
check(
|
||||
'the right pair opens the editor, with the account in the window title',
|
||||
loaded.editor && loaded.project === 'E2E fixture' && loaded.title.endsWith(E2E_USER),
|
||||
loaded,
|
||||
);
|
||||
|
||||
// A mark on the window and on the canvas element: both survive a teardown and neither survives a
|
||||
// reload, which is what signing out must not do (#177).
|
||||
await evaluate("window.__stayedUp = 'mark'; document.querySelector('canvas').dataset.stayedUp = 'mark'");
|
||||
|
||||
// Pressed by hand, not with `clickText`: that one waits for a drawn frame afterwards, and the
|
||||
// screen the button brings up is built before that frame is due.
|
||||
const logout = await locate('Logout');
|
||||
await mouse('mouseMoved', logout.x, logout.y);
|
||||
await mouse('mousePressed', logout.x, logout.y);
|
||||
await mouse('mouseReleased', logout.x, logout.y);
|
||||
await waitForScreen('login');
|
||||
check(
|
||||
'Logout ends the session and comes back to the sign-in screen',
|
||||
Boolean(await find('Sign in')) && !(await evaluate('Boolean(window.__gm?.state)')),
|
||||
await json('({ login: Boolean(window.__gm?.login), editor: Boolean(window.__gm?.state) })'),
|
||||
);
|
||||
|
||||
const stayedUp = await json(
|
||||
"({ window: window.__stayedUp ?? null, canvas: document.querySelector('canvas').dataset.stayedUp ?? null })",
|
||||
);
|
||||
check(
|
||||
'signing out does not reload the page: the same canvas stays, only what it draws changes',
|
||||
stayedUp.window === 'mark' && stayedUp.canvas === 'mark',
|
||||
stayedUp,
|
||||
);
|
||||
|
||||
// Back in, so the suite ends on a signed-in editor like every other step leaves it.
|
||||
await locate('Sign in');
|
||||
await typeText(E2E_USER);
|
||||
await press('Enter');
|
||||
await typeText(password);
|
||||
await press('Enter');
|
||||
await waitForScreen('editor');
|
||||
check(
|
||||
'signing in again brings the editor back, with the project in it',
|
||||
(await json('__gm?.state?.project?.name ?? null')) === 'E2E fixture',
|
||||
await json('__gm?.state?.project?.name ?? null'),
|
||||
);
|
||||
// The rebuilt editor has to be laid out, not sitting unlaid-out in the corner: `resize` lays out
|
||||
// only when the size changed, and the sign-in screen has set `root` to the size of the window
|
||||
// already (see `App.ts`). The Logout button is the far right of the toolbar, so it says so.
|
||||
const placed = await json('({ logout: __gm.locate("Logout")?.x ?? null, width: window.innerWidth })');
|
||||
check(
|
||||
'the editor that came back is laid out across the window',
|
||||
placed.logout !== null && placed.logout > placed.width / 2,
|
||||
placed,
|
||||
);
|
||||
}
|
||||
@@ -47,6 +47,7 @@ import { physics } from './41-physics.mjs';
|
||||
import { shapes } from './42-shapes.mjs';
|
||||
import { queries } from './43-queries.mjs';
|
||||
import { documents } from './44-documents.mjs';
|
||||
import { login } from './45-login.mjs';
|
||||
|
||||
export const STEPS = [
|
||||
hierarchy,
|
||||
@@ -93,4 +94,5 @@ export const STEPS = [
|
||||
shapes,
|
||||
queries,
|
||||
documents,
|
||||
login,
|
||||
];
|
||||
@@ -0,0 +1,65 @@
|
||||
/**
|
||||
* Signing the check tools in. Since #177 every API route but `auth/*` needs a session, so every
|
||||
* seed, smoke and e2e run logs in first – as `e2e`, the account that owns the four test projects.
|
||||
*
|
||||
* The password is never in the repo: it comes from `GAME_MAKER_E2E_PASSWORD` or from
|
||||
* `data/e2e-password.txt`, which is git-ignored and written once per server (CI writes its own).
|
||||
*/
|
||||
import { readFile } from 'node:fs/promises';
|
||||
import { dirname, resolve } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
export const E2E_USER = 'e2e';
|
||||
|
||||
const PASSWORD_FILE = resolve(dirname(fileURLToPath(import.meta.url)), '../../data/e2e-password.txt');
|
||||
const COOKIE = 'game_maker_session';
|
||||
|
||||
/** One session per server for the whole process; logging in per request would be pointless load. */
|
||||
const cookies = new Map();
|
||||
|
||||
/** The password of the `e2e` account; the step that drives the sign-in screen types it in. */
|
||||
export async function e2ePassword() {
|
||||
const fromEnv = process.env.GAME_MAKER_E2E_PASSWORD;
|
||||
if (fromEnv) return fromEnv;
|
||||
try {
|
||||
return (await readFile(PASSWORD_FILE, 'utf8')).trim();
|
||||
} catch {
|
||||
throw new Error(
|
||||
`no password for the "${E2E_USER}" account: set GAME_MAKER_E2E_PASSWORD or put it in ${PASSWORD_FILE}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/** `game_maker_session=…` for `Cookie` headers, logging in on first use. */
|
||||
export async function sessionCookie(baseUrl) {
|
||||
const cached = cookies.get(baseUrl);
|
||||
if (cached) return cached;
|
||||
const res = await fetch(`${baseUrl}api/index.php?r=auth/login`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ username: E2E_USER, password: await e2ePassword() }),
|
||||
signal: AbortSignal.timeout(20_000),
|
||||
});
|
||||
if (!res.ok) {
|
||||
throw new Error(`could not sign in as "${E2E_USER}" at ${baseUrl}: HTTP ${res.status}`);
|
||||
}
|
||||
// `getSetCookie` keeps the headers apart; a joined string cannot be split on commas, because a
|
||||
// cookie's own Expires date carries one.
|
||||
const set = res.headers.getSetCookie().find((c) => c.startsWith(`${COOKIE}=`));
|
||||
if (!set) throw new Error(`signing in at ${baseUrl} returned no ${COOKIE} cookie`);
|
||||
const cookie = set.split(';')[0];
|
||||
cookies.set(baseUrl, cookie);
|
||||
return cookie;
|
||||
}
|
||||
|
||||
/** The headers a tool's `fetch` needs on top of its own. */
|
||||
export async function authHeaders(baseUrl) {
|
||||
return { Cookie: await sessionCookie(baseUrl) };
|
||||
}
|
||||
|
||||
/** The session token alone – what the browser gets handed over CDP. */
|
||||
export async function sessionToken(baseUrl) {
|
||||
return (await sessionCookie(baseUrl)).slice(COOKIE.length + 1);
|
||||
}
|
||||
|
||||
export const SESSION_COOKIE = COOKIE;
|
||||
+21
-2
@@ -4,6 +4,7 @@
|
||||
* the summary line is missing, since chromium can die halfway under memory pressure.
|
||||
*/
|
||||
import { writeFileSync } from 'node:fs';
|
||||
import { authHeaders, SESSION_COOKIE, sessionToken } from './auth.mjs';
|
||||
import { launchBrowser } from './browser.mjs';
|
||||
|
||||
/**
|
||||
@@ -391,7 +392,8 @@ function makeTools({ cdp, projectId, baseUrl, consoleLog, check, shotPrefix }) {
|
||||
const api = async (route) => {
|
||||
const url = `${baseUrl}api/index.php?r=${route}`;
|
||||
try {
|
||||
return await (await fetch(url, { signal: AbortSignal.timeout(SERVER_TIMEOUT_MS) })).json();
|
||||
const headers = await authHeaders(baseUrl);
|
||||
return await (await fetch(url, { headers, signal: AbortSignal.timeout(SERVER_TIMEOUT_MS) })).json();
|
||||
} catch (error) {
|
||||
throw new Error(`request to ${route} failed: ${error.message}`, { cause: error });
|
||||
}
|
||||
@@ -399,11 +401,27 @@ function makeTools({ cdp, projectId, baseUrl, consoleLog, check, shotPrefix }) {
|
||||
const sceneOf = (doc) => doc.project.assets.find((a) => a.type === 'scene');
|
||||
const exceptions = () => consoleLog.filter((l) => l.startsWith('EXCEPTION'));
|
||||
/** Opens the project and asserts the page came up cleanly with the test hook installed. */
|
||||
/**
|
||||
* Hands the browser the session the tools log in with (#177). Without it the editor would put
|
||||
* up its sign-in screen instead of the project, and every step after it would find no editor.
|
||||
* The sign-in screen itself is driven by hand in the step that tests it.
|
||||
*/
|
||||
const signIn = async () => {
|
||||
await cdp.send('Network.enable');
|
||||
await cdp.send('Network.setCookie', {
|
||||
name: SESSION_COOKIE,
|
||||
value: await sessionToken(baseUrl),
|
||||
url: baseUrl,
|
||||
});
|
||||
};
|
||||
const navigate = async () => {
|
||||
await signIn();
|
||||
await cdp.send('Page.navigate', { url: `${baseUrl}?project=${projectId}` });
|
||||
await sleep(4000);
|
||||
check('page loaded without exceptions', exceptions().length === 0, exceptions().join(' | '));
|
||||
check('debug hook present', Boolean(await evaluate('Boolean(window.__gm)')));
|
||||
// `state` rather than the bare hook: the sign-in screen installs one of its own, and a run
|
||||
// that stopped there must not look like a loaded editor.
|
||||
check('debug hook present', Boolean(await evaluate('Boolean(window.__gm?.state)')));
|
||||
};
|
||||
|
||||
return {
|
||||
@@ -450,6 +468,7 @@ function makeTools({ cdp, projectId, baseUrl, consoleLog, check, shotPrefix }) {
|
||||
play,
|
||||
stop,
|
||||
api,
|
||||
signIn,
|
||||
sceneOf,
|
||||
navigate,
|
||||
};
|
||||
|
||||
@@ -12,6 +12,7 @@
|
||||
*/
|
||||
import { readFile } from 'node:fs/promises';
|
||||
import { basename, extname } from 'node:path';
|
||||
import { authHeaders } from './auth.mjs';
|
||||
|
||||
export const PROJECTS = {
|
||||
playground: '649188c15414',
|
||||
@@ -61,7 +62,7 @@ export async function uploadTexture(baseUrl, filePath) {
|
||||
}
|
||||
const res = await fetch(`${baseUrl}api/index.php?r=textures`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': type },
|
||||
headers: { 'Content-Type': type, ...(await authHeaders(baseUrl)) },
|
||||
body: bytes,
|
||||
signal: AbortSignal.timeout(20_000),
|
||||
});
|
||||
@@ -95,7 +96,7 @@ export async function uploadFont(baseUrl, filePath) {
|
||||
const name = encodeURIComponent(basename(filePath));
|
||||
const res = await fetch(`${baseUrl}api/index.php?r=fonts&name=${name}`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': type },
|
||||
headers: { 'Content-Type': type, ...(await authHeaders(baseUrl)) },
|
||||
body: bytes,
|
||||
signal: AbortSignal.timeout(20_000),
|
||||
});
|
||||
@@ -116,7 +117,7 @@ export async function uploadFont(baseUrl, filePath) {
|
||||
export async function uploadSound(baseUrl, bytes, fileName, type = 'audio/wav') {
|
||||
const res = await fetch(`${baseUrl}api/index.php?r=sounds&name=${encodeURIComponent(fileName)}`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': type },
|
||||
headers: { 'Content-Type': type, ...(await authHeaders(baseUrl)) },
|
||||
body: bytes,
|
||||
signal: AbortSignal.timeout(20_000),
|
||||
});
|
||||
@@ -134,7 +135,8 @@ export async function writeProject(projectId, baseUrl, project) {
|
||||
// A request without a timeout keeps its socket open, so a stalled server hangs the seed
|
||||
// instead of failing it – and the run that follows never starts.
|
||||
const timeout = () => AbortSignal.timeout(20_000);
|
||||
const current = await fetch(url, { signal: timeout() });
|
||||
const headers = await authHeaders(baseUrl);
|
||||
const current = await fetch(url, { headers, signal: timeout() });
|
||||
if (!current.ok) {
|
||||
console.error(`GET failed: ${current.status} – create the project first (POST ?r=projects)`);
|
||||
process.exit(1);
|
||||
@@ -146,7 +148,7 @@ export async function writeProject(projectId, baseUrl, project) {
|
||||
};
|
||||
const res = await fetch(url, {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
headers: { 'Content-Type': 'application/json', ...headers },
|
||||
body: JSON.stringify(body),
|
||||
signal: timeout(),
|
||||
});
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
/**
|
||||
* Creates an account or sets the password of one that exists. The API has no route for it:
|
||||
* signing up is a follow-up issue, so until then accounts are made here, on the server.
|
||||
*
|
||||
* Usage: php tools/make-user.php <username> <password>
|
||||
* php tools/make-user.php --list
|
||||
*/
|
||||
|
||||
require __DIR__ . '/../api/lib/UserStore.php';
|
||||
|
||||
$file = dirname(__DIR__) . '/data/users.json';
|
||||
$store = new UserStore($file);
|
||||
|
||||
$args = array_slice($argv, 1);
|
||||
if (($args[0] ?? '') === '--list') {
|
||||
foreach ($store->names() as $name) {
|
||||
echo $name, "\n";
|
||||
}
|
||||
exit(0);
|
||||
}
|
||||
if (count($args) !== 2 || $args[0] === '' || $args[1] === '') {
|
||||
fwrite(STDERR, "Usage: php tools/make-user.php <username> <password>\n");
|
||||
exit(2);
|
||||
}
|
||||
|
||||
[$username, $password] = $args;
|
||||
if (!UserStore::isValidName($username)) {
|
||||
fwrite(STDERR, "Invalid user name: {$username}\n");
|
||||
exit(2);
|
||||
}
|
||||
$existed = $store->exists($username);
|
||||
$store->put($username, $password);
|
||||
echo ($existed ? 'password set for ' : 'created '), $username, "\n";
|
||||
Reference in new issue
Block a user