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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ pnpm e2e:last-failure # error-context.md of the last failed test, its last fra
- E2E specs import `test` and `expect` from `./test` (`e2e/test.ts`), not from `@playwright/test`: its fixture fails a test when a page throws an uncaught error (known noise goes in its `IGNORED` list), and another stops the game a test leaves playing.
- **Never sleep to wait for a save:** `await saved(page)` (`e2e/helpers.ts`) waits for `data-nf-saved` on the page, set while no layout, panel state, settings write or account push is pending (`SettingsService.pending`; a debounce holds a pending save with `settings.hold()`).
- `/kit` (dev server only, 404 in a build) shows every kit component in both themes, and the floating layers' order over a dialog.
- E2E specs open projects with `openProject(page, path)` (`e2e/helpers.ts`): `/load?path=` asks before opening a folder that is not an exact recent path (a relative path always asks), and the helper answers **Trust and open**. Server and runtime unit tests open projects with `openTrustedProject` (`@nanoforge-dev/editor-server-core/testing`): a fresh data folder trusts nothing.
- E2E specs open projects with `openProject(page, path)` (`e2e/helpers.ts`): `/load?path=` asks before opening a folder that is not an exact recent path (a relative path always asks), and the helper answers **Trust and open**. A folder that can't be opened (missing, outside the root folder) gets its error without the prompt (`projects.locate`): go to `/load?path=` directly for it, not through `openProject`. Server and runtime unit tests open projects with `openTrustedProject` (`@nanoforge-dev/editor-server-core/testing`): a fresh data folder trusts nothing.
- The editor server answers only to loopback host names and `ALLOWED_HOSTS` (DNS rebinding guard): a dev server reached by another name needs it.
- `EDITOR_TOKEN` (off by default; `random` makes one per start): a local editor then answers only to a browser that opened the link it prints (`?token=`, which sets an HttpOnly cookie). Dev server and e2e run without it.
- The editor's page has a Content Security Policy (`packages/server-core/src/http/shell-csp.ts`; inline scripts by hash, read from `index.html`). A local editor allows `'unsafe-eval'` (the engine's ECS is Emscripten WebAssembly, whose bindings compile strings); a hosted one does not. The e2e fixture fails a test on any CSP violation: a new kind of resource (another origin, a worker type) needs the policy changed with it.
Expand Down
55 changes: 55 additions & 0 deletions apps/editor/e2e/load-page.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import { expect, test } from './test';

test('the trust prompt takes focus and reads its warning', async ({ page }) => {
/** A relative path always asks. */
await page.goto('/load?path=pong');
const title = page.getByRole('heading', { name: 'Open pong?', level: 1 });
await expect(title).toBeFocused();
await expect(title).toHaveAccessibleDescription(/lets the editor run its code/);
});

test('an error that replaces the trust prompt takes focus', async ({ page }) => {
await page.route('**/rpc/projects.open', (route) => route.abort());
await page.goto('/load?path=pong');
await page.getByRole('button', { name: 'Open in restricted mode', exact: true }).click();
const title = page.getByRole('heading', { name: 'pong could not be opened' });
await expect(title).toBeFocused();
await expect(title).toHaveAccessibleDescription(/Try again/);
});

test('a missing folder says so without asking to trust it', async ({ page }) => {
await page.goto('/load?path=missing-folder');
const title = page.getByRole('heading', { name: 'No project folder at missing-folder' });
await expect(title).toBeFocused();
await expect(title).toHaveAccessibleDescription(
/Check the path.*No project directory at missing-folder/,
);
await expect(page.getByRole('button', { name: 'Trust and open' })).toHaveCount(0);
});

test('the error of a project page takes focus', async ({ page }) => {
await page.goto('/project/not-a-project');
/** Its wording is the project page's: only the heading is checked. */
await expect(page.getByRole('heading', { level: 1 })).toBeFocused();
});

test('a failed new project keeps its dialog and the focus', async ({ page }) => {
await page.goto('/');
/** Slow enough for the old dialog to close while the request runs. */
await page.route('**/rpc/projects.create', async (route) => {
await new Promise((resolve) => setTimeout(resolve, 500));
await route.continue();
});
await page.getByRole('button', { name: 'New project', exact: true }).click();
const dialog = page.getByRole('dialog', { name: 'New project' });
/** The e2e workspace has a pong folder: nf new refuses it. */
await dialog.getByPlaceholder('my-game').fill('pong');
const submit = dialog.getByRole('button', { name: 'Create project' });
await submit.click();
/** Closing while the project is made would leave the request running. */
await page.keyboard.press('Escape');
await expect(dialog).toBeVisible();
await expect(dialog.getByRole('alert')).toContainText('A folder named pong already exists');
await expect(dialog.getByPlaceholder('my-game')).toHaveValue('pong');
await expect(submit).toBeFocused();
});
3 changes: 2 additions & 1 deletion apps/editor/e2e/workbench.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -177,7 +177,8 @@ test('opens a project from a link (nf editor <folder>)', async ({ page }) => {
await page.waitForURL(/\/project\//);
await expect(page.getByRole('tab', { name: 'Files' })).toBeVisible();

await openProject(page, 'missing-folder');
/** A missing folder gets no trust prompt. */
await page.goto('/load?path=missing-folder');
await expect(page.getByText('No project folder at missing-folder')).toBeVisible();
await page.getByRole('button', { name: 'Back to projects' }).click();
await expect(page.getByLabel('Project folder')).toBeVisible();
Expand Down
25 changes: 22 additions & 3 deletions apps/editor/src/lib/editor/Loading.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,16 @@
const { step = '', description, progress = 0, error }: Props = $props();
let running = $state<string>();

/**
* Moves focus to the error's title each time an error replaces what was shown, so it is read
* out (its hint as the description) rather than focus falling to the page body.
*/
const focusOn = (shown: ErrorDescription) => (title: HTMLElement) => {
/** Reading `shown` makes the attachment re-run, and focus again, on each new error. */
void shown;
title.focus();
};

const run = async (label: string, action: () => void | Promise<void>) => {
running = label;
try {
Expand All @@ -25,8 +35,17 @@
<main class="loading" aria-busy={!error}>
<p class="brand">NanoForge</p>
{#if error}
<h1 class="title">{error.title}</h1>
{#if error.hint}<p class="hint">{error.hint}</p>{/if}
<h1
class="title"
tabindex="-1"
aria-describedby={[error.hint && 'loading-hint', error.detail && 'loading-detail']
.filter(Boolean)
.join(' ') || undefined}
{@attach focusOn(error)}
>
{error.title}
</h1>
{#if error.hint}<p class="hint" id="loading-hint">{error.hint}</p>{/if}
{#if error.actions.length}
<div class="actions">
{#each error.actions as action (action.label)}
Expand All @@ -41,7 +60,7 @@
{/each}
</div>
{/if}
{#if error.detail}<p class="detail" role="alert">{error.detail}</p>{/if}
{#if error.detail}<p class="detail" id="loading-detail">{error.detail}</p>{/if}
{:else}
<div
class="bar"
Expand Down
33 changes: 26 additions & 7 deletions apps/editor/src/routes/(editor)/+page.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -93,10 +93,11 @@
error = reason instanceof Error ? reason.message : String(reason);
}
};
/** The dialog stays open until the project is made: a failure shows in it, entries kept. */
const create = () =>
run('Creating project (nf new)', async () => {
creating = false;
const { id } = await projectsApi.create(draft);
creating = false;
return id;
});

Expand Down Expand Up @@ -148,16 +149,24 @@
/>
<Button type="submit" disabled={!path.trim() || !!busy}>Open</Button>
</form>
<Button variant="primary" icon="plus" disabled={!!busy} onclick={() => (creating = true)}
>New project</Button
<Button
variant="primary"
icon="plus"
disabled={!!busy}
onclick={() => {
error = undefined;
creating = true;
}}>New project</Button
>
{/if}
</section>

<Welcome disabled={!!busy} onstart={tutorial} />

{#if busy}<p class="status" role="status">{busy}…</p>{/if}
{#if error}<p class="error" role="alert">{error}</p>{/if}
{#if !creating}
{#if busy}<p class="status" role="status">{busy}…</p>{/if}
{#if error}<p class="error" role="alert">{error}</p>{/if}
{/if}

{#if gateways.length}
<section aria-labelledby="gateways-title">
Expand Down Expand Up @@ -214,14 +223,16 @@

<Dialog
bind:open={creating}
beforeclose={() => !busy}
onclose={() => (error = undefined)}
title="New project"
description="Creates a NanoForge game workspace with nf new."
>
<form
class="create"
onsubmit={(event) => {
event.preventDefault();
if (draft.name && !nameError) void create();
if (draft.name && !nameError && !busy) void create();
}}
>
<label>
Expand Down Expand Up @@ -265,8 +276,16 @@
<span>Multiplayer (adds a server app)</span>
</div>
<Checkbox label="Install dependencies" bind:checked={draft.install} />
{#if busy}<p class="status" role="status">{busy}…</p>{/if}
{#if error}<p class="error" role="alert">{error}</p>{/if}
<div class="buttons">
<Button onclick={() => (creating = false)}>Cancel</Button>
<Button
onclick={() => {
if (busy) return;
creating = false;
error = undefined;
}}>Cancel</Button
>
<Button variant="primary" type="submit" disabled={!draft.name || !!nameError}
>Create project</Button
>
Expand Down
56 changes: 31 additions & 25 deletions apps/editor/src/routes/(editor)/load/+page.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,8 @@
*
* Opening a trusted local folder runs its code (`nanoforge.config.ts`, plugins, builds), and
* any web page can link here: a folder that is not in the recent projects asks first, to trust
* it or to open it in restricted mode (its code off). A hosted editor opens projects by their id
* it or to open it in restricted mode (its code off). A folder that can't be opened (missing,
* outside the root folder) says so without asking. A hosted editor opens projects by their id
* only, never by path.
*/
const editor = getEditor();
Expand Down Expand Up @@ -134,32 +135,37 @@
actions: [{ ...back, primary: true }],
};
} else {
void known(ref.path).then((trusted) => {
if (disposed) return;
if (trusted) return void open();
error = {
title: `Open ${ref.path}?`,
hint: 'Trusting a folder lets the editor run its code on this computer: its nanoforge.config.ts, its plugins, its builds and games. Trust it only if you trust where it comes from; otherwise open it in restricted mode, with its code off.',
actions: [
{
label: 'Trust and open',
primary: true,
run: () => {
error = undefined;
void open(true);
void Promise.all([editor.projects.locate(ref.path), known(ref.path)]).then(
([, trusted]) => {
if (disposed) return;
if (trusted) return void open();
error = {
title: `Open ${ref.path}?`,
hint: 'Trusting a folder lets the editor run its code on this computer: its nanoforge.config.ts, its plugins, its builds and games. Trust it only if you trust where it comes from; otherwise open it in restricted mode, with its code off.',
actions: [
{
label: 'Trust and open',
primary: true,
run: () => {
error = undefined;
void open(true);
},
},
},
{
label: 'Open in restricted mode',
run: () => {
error = undefined;
void open();
{
label: 'Open in restricted mode',
run: () => {
error = undefined;
void open();
},
},
},
back,
],
};
});
back,
],
};
},
(reason: unknown) => {
if (!disposed) error = describe(reason, ref);
},
);
}
return () => {
disposed = true;
Expand Down
5 changes: 5 additions & 0 deletions packages/project/src/service/project-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,11 @@ export class ProjectService implements Disposable {
if (this._current.get() === current) this.close();
}

/** Throws, as `open` would, when a local folder can't be opened: nothing opens, no code runs. */
async locate(path: string): Promise<void> {
await this._rpc.api(ProjectsContract).locate({ path });
}

recent(): Promise<RecentProject[]> {
return this._rpc.api(ProjectsContract).recent(null);
}
Expand Down
5 changes: 5 additions & 0 deletions packages/protocol/src/project/project.contract.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,11 @@ export const ProjectsContract = defineContract('projects', {
input: ProjectRef,
output: OpenedProject,
},
/**
* Local editors: checks that a folder could be opened, without opening it or running its
* code. Throws as `open` does: FORBIDDEN (hosted editor, outside the root folder), NOT_FOUND.
*/
locate: { input: z.object({ path: z.string() }), output: z.null() },
recent: { input: z.null(), output: z.array(RecentProject) },
forget: { input: z.object({ id: ProjectId }), output: z.null() },
/**
Expand Down
19 changes: 16 additions & 3 deletions packages/server-core/src/project/project-registry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -238,7 +238,22 @@ export class ProjectRegistry implements Disposable {
this._onDidClose.dispose();
}

/**
* Checks that a local folder could be opened, without opening it or running its code: throws as
* `open` does (FORBIDDEN on a hosted editor or outside the root folder, NOT_FOUND).
*/
async locate(path: string): Promise<void> {
await this._localFolder(path);
}

private async _openLocal(path: string): Promise<OpenProject> {
const real = await this._localFolder(path);
const trusted = await this.trust.isTrusted(real);
return this._getOrCreate(shortHash(real), real, { path: real }, real, trusted);
}

/** The real path of a local project's folder, inside the root folder. */
private async _localFolder(path: string): Promise<string> {
if (this._env.mode === 'ONLINE') {
throw new RpcError('FORBIDDEN', 'Local projects cannot be opened on a hosted editor');
}
Expand All @@ -249,9 +264,7 @@ export class ProjectRegistry implements Disposable {
}
const info = await stat(target).catch(() => undefined);
if (!info?.isDirectory()) throw new RpcError('NOT_FOUND', `No project directory at ${path}`);
const real = await realpath(target);
const trusted = await this.trust.isTrusted(real);
return this._getOrCreate(shortHash(real), real, { path: real }, real, trusted);
return realpath(target);
}

private async _openGateway(session: Session, gatewayId: string): Promise<OpenProject> {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,10 @@ export const implementProjectsRpc = (
const project = await projects.open(session, ref);
return { id: project.id, name: project.name, trusted: project.trusted };
},
locate: async ({ path }) => {
await projects.locate(path);
return null;
},
isTrusted: ({ id }, { session }) => projects.get(session, id).trusted,
trust: async ({ id }, { session }) => {
await projects.trustProject(projects.get(session, id));
Expand Down
Loading
Loading