Isolate store purchase rehearsals from TREK Cloud production [skip ci]

This commit is contained in:
Maurice
2026-12-02 18:38:59 +01:00
parent e54f954f31
commit 0f683b0dee
6 changed files with 189 additions and 23 deletions
+1
View File
@@ -11,3 +11,4 @@ e2e/help/media.env
# The native apps' address screen (npm run build:native), copied into
# android/ and ios/ by `cap sync`
native-dist/
native-sandbox-dist/
+43 -10
View File
@@ -21,7 +21,7 @@ import {
AUTH_PROXY_DOCS_URL,
CLIENT_CERT_DOCS_URL,
CLOUD_TERMS_URL,
CLOUD_URL,
CLOUD_URL as PRODUCTION_CLOUD_URL,
PLAY_SUBSCRIPTIONS_URL,
PRIVACY_URL,
STORE_TERMS_URL,
@@ -57,6 +57,13 @@ document.documentElement.dir = directionOf(locale);
const root = document.getElementById('shell')!;
const PROBE_TIMEOUT_MS = 8000;
const cloudSandbox = typeof __TREK_STORE_SANDBOX_ORIGIN__ === 'string' ? __TREK_STORE_SANDBOX_ORIGIN__ : undefined;
const CLOUD_URL = cloudSandbox ?? PRODUCTION_CLOUD_URL;
const cloudHttpOptions = {
connectTimeout: PROBE_TIMEOUT_MS,
readTimeout: PROBE_TIMEOUT_MS,
...(cloudSandbox ? { disableRedirects: true } : {}),
};
const iap = getIapClient();
/**
@@ -105,6 +112,30 @@ const get: ProbeGet = async (url) => {
}
};
// Keep Cloud sandbox requests on their requested host, including during tenant provisioning.
const cloudGet: ProbeGet = cloudSandbox ? (url) => CapacitorHttp.get({ url, ...cloudHttpOptions }) : get;
function isCloudSandboxTenant(address: string, sandboxOrigin: string): boolean {
let tenant: URL;
try {
tenant = new URL(address);
} catch {
return false;
}
const suffix = `.${new URL(sandboxOrigin).hostname}`;
const slug = tenant.hostname.slice(0, -suffix.length);
return (
tenant.origin === `https://${tenant.hostname}` &&
!tenant.username &&
!tenant.password &&
tenant.hostname.endsWith(suffix) &&
/^[a-z0-9-]+$/.test(slug) &&
tenant.pathname === '/' &&
!tenant.search &&
!tenant.hash
);
}
function failureMessage(reason: ProbeFailure): string {
switch (reason) {
case 'invalid':
@@ -722,7 +753,7 @@ interface CloudPlans {
async function fetchPlans(): Promise<CloudPlans | null> {
try {
const res = await get(`${CLOUD_URL}/api/plans`);
const res = await cloudGet(`${CLOUD_URL}/api/plans`);
const data = typeof res.data === 'string' ? JSON.parse(res.data) : res.data;
const body = (data ?? {}) as { plans?: CloudPlan[]; ordering?: string };
const plans = Array.isArray(body.plans) ? body.plans.filter((plan) => isNewCloudPlan(plan.id)) : [];
@@ -1118,7 +1149,7 @@ type SlugStatus = 'available' | 'taken' | 'invalid' | 'reserved' | 'error';
async function slugStatus(slug: string): Promise<SlugStatus> {
try {
const res = await get(`${CLOUD_URL}/api/slug/check?slug=${encodeURIComponent(slug)}`);
const res = await cloudGet(`${CLOUD_URL}/api/slug/check?slug=${encodeURIComponent(slug)}`);
const data = typeof res.data === 'string' ? JSON.parse(res.data) : res.data;
const status = (data as { status?: string })?.status;
if (status === 'available' || status === 'taken' || status === 'invalid' || status === 'reserved') return status;
@@ -1138,12 +1169,12 @@ async function fetchConsent(): Promise<CloudPurchaseAgreement | null> {
const res = await CapacitorHttp.get({
url: `${CLOUD_URL}/api/iap/consent`,
params: { lang: locale === 'de' ? 'de' : 'en' },
connectTimeout: PROBE_TIMEOUT_MS,
readTimeout: PROBE_TIMEOUT_MS,
...cloudHttpOptions,
});
const data = typeof res.data === 'string' ? JSON.parse(res.data) : res.data;
const body = (data ?? {}) as { version?: unknown; deviations?: unknown };
const body = (data ?? {}) as { version?: unknown; deviations?: unknown; iapEnvironment?: unknown };
if (res.status !== 200 || typeof body.version !== 'string' || typeof body.deviations !== 'string') return null;
if (cloudSandbox && body.iapEnvironment !== 'sandbox') return null;
if (!body.version || !body.deviations) return null;
return { version: body.version, text: body.deviations };
} catch {
@@ -1171,8 +1202,7 @@ async function redeemPurchase(
const res = await CapacitorHttp.post({
url: `${CLOUD_URL}/api/iap/redeem`,
headers: { 'content-type': 'application/json' },
connectTimeout: PROBE_TIMEOUT_MS,
readTimeout: PROBE_TIMEOUT_MS,
...cloudHttpOptions,
// The language of the contract confirmation mail.
data: {
platform: purchase.platform,
@@ -1190,6 +1220,9 @@ async function redeemPurchase(
const data = typeof res.data === 'string' ? JSON.parse(res.data) : res.data;
const body = (data ?? {}) as { instanceUrl?: string; code?: string; welcome?: string };
if ((res.status === 200 || res.status === 201) && typeof body.instanceUrl === 'string') {
if (cloudSandbox && !isCloudSandboxTenant(body.instanceUrl, cloudSandbox)) {
return { ok: false, code: 'redeem-failed' };
}
const welcome =
typeof body.welcome === 'string' && /^[A-Za-z0-9_-]{43}$/.test(body.welcome) ? body.welcome : undefined;
return { ok: true, instanceUrl: body.instanceUrl, ...(welcome ? { welcome } : {}) };
@@ -1687,8 +1720,8 @@ function showProvisioning(instanceUrl: string, welcome?: string): void {
const deadline = Date.now() + 180_000;
const poll = async (): Promise<void> => {
if (!view.screen.node.isConnected) return;
const result = await probeServer(instanceUrl, get);
if (result.ok) {
const result = await probeServer(instanceUrl, cloudGet);
if (result.ok && (!cloudSandbox || new URL(result.url).origin === new URL(instanceUrl).origin)) {
await ready(result.url);
return;
}
@@ -0,0 +1,45 @@
import assert from 'node:assert/strict';
import { basename } from 'node:path';
import { test } from 'node:test';
import config from '../vite.native.config.js';
const variable = 'TREK_CLOUD_SANDBOX_ORIGIN';
function setOrigin(context, origin) {
const previous = process.env[variable];
process.env[variable] = origin;
context.after(() => {
if (previous === undefined) delete process.env[variable];
else process.env[variable] = previous;
});
}
test('isolates the sandbox output and keeps the ordinary app on the production configuration', (context) => {
const origin = 'https://store-sandbox.example.com';
setOrigin(context, origin);
const sandbox = config({ command: 'build', mode: 'store-sandbox' });
assert.deepEqual(sandbox.define, { __TREK_STORE_SANDBOX_ORIGIN__: JSON.stringify(origin) });
assert.equal(basename(sandbox.build.outDir), 'native-sandbox-dist');
for (const input of [
{ command: 'build', mode: 'production' },
{ command: 'serve', mode: 'store-sandbox' },
]) {
const regular = config(input);
assert.deepEqual(regular.define, {});
assert.equal(basename(regular.build.outDir), 'native-dist');
}
});
for (const origin of [
'',
'http://qa.example.com',
'https://qa.example.com/path',
'https://liketrek.com',
'https://www.liketrek.com',
]) {
test(`refuses a sandbox configuration with origin ${JSON.stringify(origin)}`, (context) => {
setOrigin(context, origin);
assert.throws(() => config({ command: 'build', mode: 'store-sandbox' }), { message: new RegExp(variable) });
});
}
+3
View File
@@ -4,6 +4,9 @@
/** The version this bundle was built as (client/package.json), set by `define` in vite.config.js. */
declare const __TREK_UI_VERSION__: string;
/** Defined only for the native store-sandbox build. */
declare const __TREK_STORE_SANDBOX_ORIGIN__: string | undefined;
/**
* Big Shoulders Display's weights, imported for their stylesheets alone
* (components/Studio/bookFontFaces.ts). Its package maps `./*` to `./*.css`
@@ -53,15 +53,22 @@ function element<T extends HTMLElement>(selector: string): T {
return found;
}
function mountShell(): void {
vi.resetModules();
vi.stubGlobal('matchMedia', () => ({ matches: false, addEventListener: vi.fn() }));
vi.stubGlobal('cancelAnimationFrame', vi.fn());
document.body.append(Object.assign(document.createElement('main'), { id: 'shell' }));
mocks.agreement.mockReset();
mocks.purchase.mockClear();
}
afterEach(() => {
vi.unstubAllGlobals();
document.body.replaceChildren();
});
it('keeps the store closed for a withdrawn agreement and asks again when the version changes', async () => {
vi.stubGlobal('matchMedia', () => ({ matches: false, addEventListener: vi.fn() }));
vi.stubGlobal('cancelAnimationFrame', vi.fn());
document.body.append(Object.assign(document.createElement('main'), { id: 'shell' }));
mountShell();
const changed = { status: 200, data: { version: '2026-12-02', deviations: 'Updated agreement' } };
mocks.agreement
.mockResolvedValueOnce(agreement)
@@ -103,3 +110,56 @@ it('keeps the store closed for a withdrawn agreement and asks again when the ver
fireEvent.click(submit);
await waitFor(() => expect(mocks.purchase).toHaveBeenCalledExactlyOnceWith('cloud.plus.monthly', '$11.99'));
});
it('requires a sandbox agreement before presenting a store purchase', async () => {
mountShell();
const sandbox = 'https://store-sandbox.example.com';
vi.stubGlobal('__TREK_STORE_SANDBOX_ORIGIN__', sandbox);
const sandboxAgreement = {
status: 200,
data: { ...agreement.data, iapEnvironment: 'sandbox' },
};
mocks.agreement.mockImplementation(async ({ url }: { url: string }) => {
const path = new URL(url).pathname;
if (path === '/api/plans') {
return {
status: 200,
data: { ordering: 'open', plans: [{ id: 'plus', name: 'Plus', storageGb: 50, aiDocumentLimit: null }] },
};
}
if (path === '/api/slug/check') return { status: 200, data: { status: 'available' } };
return agreement;
});
await import('../../../native-shell/main');
await waitFor(() => expect(element<HTMLElement>('.trial-badge').hidden).toBe(false));
fireEvent.click(element('button.discover'));
await waitFor(() => expect(element<HTMLButtonElement>('.dock button.cta').hidden).toBe(false));
fireEvent.click(element('.dock button.cta'));
const consent = await waitFor(() => {
const input = element<HTMLInputElement>('.consent input');
expect(input.disabled).toBe(true);
return input;
});
const submit = element<HTMLButtonElement>('.dock button.cta');
fireEvent.input(element('.form input[type="text"]'), { target: { value: 'sample-journey' } });
fireEvent.input(element('.form input[type="email"]'), { target: { value: 'buyer@example.invalid' } });
fireEvent.input(element('.form input[type="password"]'), { target: { value: 'Training#Pass123' } });
fireEvent.click(submit);
await waitFor(() => expect(element('.notice').textContent).toBeTruthy());
expect(mocks.purchase).not.toHaveBeenCalled();
mocks.agreement.mockImplementation(async ({ url }: { url: string }) =>
new URL(url).pathname === '/api/slug/check' ? { status: 200, data: { status: 'available' } } : sandboxAgreement
);
fireEvent.click(submit);
await waitFor(() => expect(consent.disabled).toBe(false));
fireEvent.click(consent);
fireEvent.click(submit);
await waitFor(() => expect(mocks.purchase).toHaveBeenCalledExactlyOnceWith('cloud.plus.monthly', '$11.99'));
for (const [options] of mocks.agreement.mock.calls) {
expect(new URL(options.url).origin).toBe(sandbox);
expect(options.disableRedirects).toBe(true);
}
});
+34 -10
View File
@@ -1,16 +1,40 @@
import { defineConfig } from 'vite'
import { defineConfig, loadEnv } from 'vite'
import { fileURLToPath } from 'url'
function sandboxOrigin(mode) {
const envDir = fileURLToPath(new URL('.', import.meta.url))
const { TREK_CLOUD_SANDBOX_ORIGIN: origin } = loadEnv(mode, envDir, 'TREK_CLOUD_SANDBOX_')
const url = URL.canParse(origin) ? new URL(origin) : null
// The host must also support a wildcard certificate for its tenant subdomains.
const dnsName = /^(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z][a-z0-9-]*[a-z0-9]$/
if (
url?.origin !== origin ||
url?.protocol !== 'https:' ||
url.port ||
!dnsName.test(url.hostname) ||
url.hostname === 'liketrek.com' ||
url.hostname === 'www.liketrek.com'
) {
throw new Error('TREK_CLOUD_SANDBOX_ORIGIN must be a dedicated sandbox HTTPS origin without a path or port')
}
return origin
}
// The address screen the native apps ship (native-shell/). Everything past it
// is the UI of the server the user picks, so this build stays tiny and apart
// from the main one: no PWA, no React, only the native strings of each locale.
export default defineConfig({
root: fileURLToPath(new URL('./native-shell', import.meta.url)),
base: './',
publicDir: false,
build: {
outDir: fileURLToPath(new URL('./native-dist', import.meta.url)),
emptyOutDir: true,
target: ['es2020', 'safari15', 'chrome100'],
},
export default defineConfig(({ command, mode }) => {
const sandbox = command === 'build' && mode === 'store-sandbox'
const output = sandbox ? './native-sandbox-dist' : './native-dist'
return {
root: fileURLToPath(new URL('./native-shell', import.meta.url)),
base: './',
publicDir: false,
define: sandbox ? { __TREK_STORE_SANDBOX_ORIGIN__: JSON.stringify(sandboxOrigin(mode)) } : {},
build: {
outDir: fileURLToPath(new URL(output, import.meta.url)),
emptyOutDir: true,
target: ['es2020', 'safari15', 'chrome100'],
},
}
})