feat(export): server-rendered artifacts behind one signed download URL (#160)
CI / changes (push) Successful in 1s
CI / unit (push) Successful in 9s
CI / integration (push) Successful in 15s
CI / ui (push) Successful in 1m2s
CI / conformance (push) Successful in 9s
CI / gate (push) Successful in 0s
CI / deploy (push) Successful in 1m42s

The finished-game export (GCG + a new PNG of the final position) is one
signed, short-lived relative URL (game.export_url; HMAC-SHA256, 10-min
TTL, BACKEND_EXPORT_SIGN_KEY) resolved against the client's own origin
and delivered by the best affordance each platform has (five on-device
review rounds):

- TG Android/desktop: native showPopup chooser -> native downloadFile
  dialog (bridge-only chain, activation-safe).
- TG iOS: app-modal chooser -> OS share sheet with the fetched file
  (a popup callback cannot supply the activation the sheet needs).
- VK iOS: VKWebAppDownloadFile for both formats.
- VK Android: the PNG opens in VK's native image viewer, the GCG copies
  to the clipboard (the VK Android downloader hangs on any download,
  Content-Length/Range notwithstanding).
- VK desktop iframe / desktop browsers: plain anchor downloads.
- Mobile browsers: the OS share sheet (fetch-then-share).
- Legacy TG (< Bot API 8.0): app modal + GCG clipboard, no image option.

The PNG is rasterized on demand by the new internal `renderer` sidecar
(node:22-slim + skia-canvas + baked Liberation/Noto Color Emoji fonts)
executing the SAME ui/src/lib/gameimage.ts the ui project unit-tests;
the backend rebuilds the render payload from the journal +
engine.AlphabetTable, and the device date locale, IANA time zone and
localized non-play labels ride the signed URL. Nothing is stored — the
artifact re-derives from the immutable journal on each GET. The gateway
forwards /dl/* (caddy @gateway matcher extended) behind the per-IP
public rate limiter and serves bytes via http.ServeContent.

Deploy: renderer service in compose + prod overlay + rolling order +
prod push list; TEST_/PROD_EXPORT_SIGN_KEY secrets; the sidecar smoke
runs in the ui CI job. Docs: ARCHITECTURE, FUNCTIONAL(+_ru), UI_DESIGN,
TESTING, deploy/README, renderer/README.
This commit was merged in pull request #160.
This commit is contained in:
2026-07-02 21:58:07 +00:00
parent 16a4431158
commit d5fbaa3034
62 changed files with 2449 additions and 234 deletions
+175 -31
View File
@@ -1,18 +1,31 @@
import { Buffer } from 'node:buffer';
import { expect, test, type Page } from './fixtures';
// The finished-game export: the history header's 📤 button opens the app's own format
// chooser modal — never Telegram's native popup, whose callback runs without user
// activation and so kills navigator.share / clipboard writes (verified on-device).
// The PNG option is offered only outside the in-app WebViews (no working binary
// delivery there until the server-rendered signed-URL path lands); the GCG file is
// always offered. g3 ("vs Rick") is the seeded finished game. Web Share is
// force-disabled per test so both engines deterministically exercise the download
// branch.
// The finished-game export: one signed relative URL (game.export_url) resolved against
// the app's own origin, delivered by the most native affordance per platform — Telegram's
// showPopup chooser + downloadFile dialog (all bridge calls, activation-safe), VK's
// native viewer/download, the OS share sheet with the fetched file on a mobile browser,
// a plain anchor download on desktop. g3 ("vs Rick") is the seeded finished game.
// The mock gateway returns a shape-faithful /dl/... path; the tests intercept that
// route and serve bytes, so the download itself is exercised end to end.
async function disableWebShare(page: Page): Promise<void> {
await page.addInitScript(() => {
Object.defineProperty(navigator, 'canShare', { value: () => false, configurable: true });
Object.defineProperty(navigator, 'share', { value: undefined, configurable: true });
// A minimal valid 1×1 PNG, hex-decoded without node typings (the e2e tsconfig has none).
const PNG_HEX =
'89504e470d0a1a0a0000000d49484452000000010000000108060000001f15c489' +
'0000000a49444154789c6360000000020001e221bc330000000049454e44ae426082';
// Buffer, not Uint8Array: route.fulfill silently hangs a FETCH interception on a
// Uint8Array body (a navigation download tolerates it) — the share test deadlocked.
const PNG_BYTES = Buffer.from(PNG_HEX, 'hex');
async function routeDl(page: Page): Promise<void> {
await page.route('**/dl/**', (route) => {
const png = route.request().url().includes('/png');
return route.fulfill({
status: 200,
contentType: png ? 'image/png' : 'text/plain; charset=utf-8',
headers: { 'Content-Disposition': 'attachment' },
body: png ? PNG_BYTES : '#character-encoding UTF-8\n',
});
});
}
@@ -25,20 +38,18 @@ async function openFinishedHistory(page: Page): Promise<void> {
await expect(page.getByRole('button', { name: 'Export game' })).toBeVisible();
}
test('the export chooser downloads the PNG image on a plain browser', async ({ page }) => {
await disableWebShare(page);
test('the chooser downloads the PNG through the signed URL on a plain browser', async ({ page }) => {
await routeDl(page);
await openFinishedHistory(page);
await page.getByRole('button', { name: 'Export game' }).click();
// The app's own chooser modal offers both formats on the plain web.
await expect(page.getByRole('button', { name: 'GCG file' })).toBeVisible();
const download = page.waitForEvent('download');
await page.getByRole('button', { name: 'Image (PNG)' }).click();
expect((await download).suggestedFilename()).toMatch(/^game-.+\.png$/);
});
test('the export chooser downloads the GCG file on a plain browser', async ({ page }) => {
await disableWebShare(page);
test('the chooser downloads the GCG through the same signed-URL route', async ({ page }) => {
await routeDl(page);
await openFinishedHistory(page);
await page.getByRole('button', { name: 'Export game' }).click();
@@ -47,24 +58,29 @@ test('the export chooser downloads the GCG file on a plain browser', async ({ pa
expect((await download).suggestedFilename()).toMatch(/^game-.+\.gcg$/);
});
test('inside Telegram the chooser is the app modal and withholds the image option', async ({
test('inside Telegram the chooser is the native popup and delivery the native downloadFile', async ({
page,
}) => {
await disableWebShare(page);
// A Telegram WebApp stub with showPopup present: were the chooser still native, it would
// be called — the spy locks the regression (its activation-less callback breaks share and
// clipboard delivery on real devices).
// A Telegram stub with showPopup AND downloadFile (Bot API 8.0): the whole chain stays
// in bridge calls — the popup picks the image, the artifact goes to the native download
// dialog, never an in-webview anchor. (Activation-safe: no gesture-gated Web APIs.)
await page.addInitScript(() => {
Object.assign(window, {
Telegram: {
WebApp: {
initData: 'query_id=test&user=%7B%22id%22%3A1%7D&auth_date=1&hash=deadbeef',
initDataUnsafe: {},
platform: 'android',
ready() {},
expand() {},
showPopup(_params: unknown, cb: (id: string) => void) {
(window as unknown as { __popupCalled?: boolean }).__popupCalled = true;
setTimeout(() => cb(''), 0);
showPopup(params: { buttons?: { id?: string; type?: string }[] }, cb: (id: string) => void) {
const w = window as unknown as { __popup?: unknown };
w.__popup = params;
setTimeout(() => cb('png'), 0);
},
downloadFile(params: { url: string; file_name: string }) {
const w = window as unknown as { __downloads?: { url: string; file_name: string }[] };
(w.__downloads ??= []).push(params);
},
},
},
@@ -77,11 +93,139 @@ test('inside Telegram the chooser is the app modal and withholds the image optio
await page.locator('.scoreboard').click();
await page.getByRole('button', { name: 'Export game' }).click();
// The app's own modal opened with the GCG option only — no PNG in an in-app WebView…
// The native popup carried both formats plus cancel, and no in-app modal was mounted.
const popup = await page.evaluate(
() => (window as unknown as { __popup?: { buttons?: { id?: string; type?: string }[] } }).__popup,
);
expect(popup?.buttons?.map((b) => b.id ?? b.type)).toEqual(['png', 'gcg', 'cancel']);
await expect(page.getByRole('button', { name: 'GCG file' })).toHaveCount(0);
await expect
.poll(() =>
page.evaluate(() => (window as unknown as { __downloads?: { url: string; file_name: string }[] }).__downloads),
)
.toHaveLength(1);
const dl = await page.evaluate(
() => (window as unknown as { __downloads: { url: string; file_name: string }[] }).__downloads[0],
);
// The relative signed path was resolved against the app's own origin — absolute for TG.
expect(dl.url).toMatch(/^http.+\/dl\/.+\/png\?/);
expect(dl.file_name).toMatch(/^game-.+\.png$/);
});
test('a mobile browser gets the OS share sheet with the fetched file', async ({ page }) => {
// Web Share with files present (a mobile browser): the artifact is fetched from the
// signed URL and handed to navigator.share as a File — the sheet opens directly,
// nothing lands in Downloads first.
await page.addInitScript(() => {
const shared: { name: string; type: string }[] = [];
Object.defineProperty(navigator, 'canShare', { value: () => true, configurable: true });
Object.defineProperty(navigator, 'share', {
value: async (data: { files?: File[] }) => {
for (const f of data.files ?? []) shared.push({ name: f.name, type: f.type });
},
configurable: true,
});
(window as unknown as { __shared: typeof shared }).__shared = shared;
});
await routeDl(page);
await openFinishedHistory(page);
await page.getByRole('button', { name: 'Export game' }).click();
await page.getByRole('button', { name: 'Image (PNG)' }).click();
await expect
.poll(() => page.evaluate(() => (window as unknown as { __shared: unknown[] }).__shared))
.toHaveLength(1);
const shared = await page.evaluate(
() => (window as unknown as { __shared: { name: string; type: string }[] }).__shared[0],
);
expect(shared.name).toMatch(/^game-.+\.png$/);
expect(shared.type).toBe('image/png');
});
test('Telegram on iOS keeps the app chooser and opens the OS share sheet', async ({ page }) => {
// TG iOS: WKWebView has navigator.share, and the sheet is the preferred delivery — but
// it needs the user activation a native-popup callback cannot provide, so the chooser
// stays the app modal on this one platform.
await page.addInitScript(() => {
const shared: { name: string; type: string }[] = [];
Object.defineProperty(navigator, 'canShare', { value: () => true, configurable: true });
Object.defineProperty(navigator, 'share', {
value: async (data: { files?: File[] }) => {
for (const f of data.files ?? []) shared.push({ name: f.name, type: f.type });
},
configurable: true,
});
(window as unknown as { __shared: typeof shared }).__shared = shared;
Object.assign(window, {
Telegram: {
WebApp: {
initData: 'query_id=test&user=%7B%22id%22%3A1%7D&auth_date=1&hash=deadbeef',
initDataUnsafe: {},
platform: 'ios',
ready() {},
expand() {},
showPopup() {
(window as unknown as { __popupCalled?: boolean }).__popupCalled = true;
},
downloadFile() {
(window as unknown as { __downloadCalled?: boolean }).__downloadCalled = true;
},
},
},
});
});
await routeDl(page);
await page.goto('/');
await expect(page.getByText('Your turn')).toBeVisible();
await page.getByRole('button', { name: /Rick/ }).click();
await expect(page.locator('[data-cell]').first()).toBeVisible();
await page.locator('.scoreboard').click();
await page.getByRole('button', { name: 'Export game' }).click();
// The app modal opened (both formats) — the native popup was not used…
await expect(page.getByRole('button', { name: 'Image (PNG)' })).toBeVisible();
await page.getByRole('button', { name: 'Image (PNG)' }).click();
// …and the artifact went to the OS share sheet, not TG's download dialog.
await expect
.poll(() => page.evaluate(() => (window as unknown as { __shared: unknown[] }).__shared))
.toHaveLength(1);
const flags = await page.evaluate(() => {
const w = window as unknown as { __popupCalled?: boolean; __downloadCalled?: boolean };
return { popup: !!w.__popupCalled, download: !!w.__downloadCalled };
});
expect(flags).toEqual({ popup: false, download: false });
});
test('a legacy Telegram client (no downloadFile) hides the image and copies the GCG', async ({ page }) => {
await page.addInitScript(() => {
// Headless engines deny the real clipboard; a permissive stub keeps the legacy
// copy path deterministic in both browsers.
Object.defineProperty(navigator, 'clipboard', {
value: { writeText: async () => {} },
configurable: true,
});
Object.assign(window, {
Telegram: {
WebApp: {
initData: 'query_id=test&user=%7B%22id%22%3A1%7D&auth_date=1&hash=deadbeef',
initDataUnsafe: {},
ready() {},
expand() {},
},
},
});
});
await page.goto('/');
await expect(page.getByText('Your turn')).toBeVisible();
await page.getByRole('button', { name: /Rick/ }).click();
await expect(page.locator('[data-cell]').first()).toBeVisible();
await page.locator('.scoreboard').click();
await page.getByRole('button', { name: 'Export game' }).click();
// No image option without the native download; the GCG stays available (clipboard path).
await expect(page.getByRole('button', { name: 'GCG file' })).toBeVisible();
await expect(page.getByRole('button', { name: 'Image (PNG)' })).toHaveCount(0);
// …and the native popup was never used for the chooser.
expect(
await page.evaluate(() => (window as unknown as { __popupCalled?: boolean }).__popupCalled),
).toBeFalsy();
await page.getByRole('button', { name: 'GCG file' }).click();
await expect(page.getByText('GCG copied to the clipboard.')).toBeVisible();
});