Skip to content
Merged
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
22 changes: 22 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -440,6 +440,27 @@ jobs:
- name: Build and probe a real Nuxt app
run: node scripts/framework-consumers.mjs nuxt packed/*.tgz

vite-framework-consumers:
name: Vite framework consumer (${{ matrix.framework }})
needs: pack
runs-on: ubuntu-latest
timeout-minutes: 10
strategy:
fail-fast: false
matrix:
framework: [tanstack-worker, react-router]
steps:
- uses: actions/checkout@v7
- uses: actions/setup-node@v7
with:
node-version: 24.x
- uses: actions/download-artifact@v8
with:
name: packed-tarball
path: packed
- name: Build and probe the app
run: node scripts/framework-consumers.mjs "${{ matrix.framework }}" packed/*.tgz

next-consumers:
name: Next.js ${{ matrix.next }} (${{ matrix.bundler }}) production integration
needs: pack
Expand Down Expand Up @@ -492,6 +513,7 @@ jobs:
- tanstack-consumer
- fastify-startup
- nuxt-consumer
- vite-framework-consumers
runs-on: ubuntu-latest

steps:
Expand Down
26 changes: 26 additions & 0 deletions field-test/hosted-startup.md
Original file line number Diff line number Diff line change
Expand Up @@ -80,3 +80,29 @@ Optionally set `PS_FASTIFY_FALLBACK_RULES_URL` to a second loopback endpoint tha
delivers the sandbox site's unfiltered bundle. The same mismatched build must
then load the rule in detect-only mode and still return 200. Verify the two
recorded matches share a rule revision and only the first was enforced.

## AI builder deployment targets

Select the adapter from the deployed server entry. Build tools listed in
`package.json` can also produce static output. Install protection separately
at any backend the browser calls directly.

| Builder | Documented deployment shape | Connect integration |
| --- | --- | --- |
| GoDaddy Airo AI Builder | Exports code as a ZIP. GoDaddy's separate Node.js Hosting product runs apps on Node 22 using their build and start scripts. [Airo export](https://www.godaddy.com/en-in/help/download-my-airo-ai-builder-files-and-code-42993), [Node.js Hosting requirements](https://www.godaddy.com/help/nodejs-hosting-faq-42915) | Inspect the exported entry. Supported Fastify apps can use the preload on Node hosting when the host controls startup. Managed Airo publishing needs its own deployment verification. |
| Hostinger Horizons | Typically React and Vite with Node.js backend code. Integrated backend projects can also use PocketBase. [Horizons overview](https://www.hostinger.com/support/11004356-hostinger-horizons-creating-and-managing-your-projects/), [Integrated backend](https://www.hostinger.com/changelog) | Use the framework adapter for a supported server-rendered project. A static Vite export supports inventory scanning. PocketBase and separate managed APIs need a separate protection boundary. |
| Lovable | Current TanStack Start apps run on Cloudflare Workers. Earlier React/Vite apps were static and used separate backend functions. [Lovable deployment stack](https://lovable.dev/blog/building-apps-using-tanstack-start) | Use the TanStack Fetch adapter on the Worker. Separate functions and direct Supabase calls need their own coverage. |
| IONOS | MyWebsite Now publishes within IONOS. Momentum AI App & Site Builder can export PHP, Node.js, and static files. [MyWebsite export limits](https://www.ionos.com/help/websites-stores/organize-websites-and-stores/website-builders-overview-of-export-options/), [Momentum export](https://www.ionos.co.uk/help/ai/using-the-ai-app-site-builder/exporting-data-from-the-ai-app-site-builder/) | Select the adapter from the exported Node app's actual entry. PHP and static sites need their own protection coverage. |

Exercise representative builds locally against a packed Connect artifact. The
Worker fixture runs the production bundle in local `workerd`. The React Router
fixture uses the server-rendered framework mode.

```sh
npm run test:frameworks -- tanstack-worker "$tarball"
npm run test:frameworks -- react-router "$tarball"
```

For a managed builder rollout, repeat the check against a sandbox deployed
through the builder itself. Inspect the emitted entry and verify that a
request actually reaches the guard before enabling blocking.
36 changes: 33 additions & 3 deletions scripts/framework-consumers.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,10 @@ const fetchRoute = `async ({ request }) => {
const body = await request.json();
return Response.json(${output});
}`;
const tanstackDependencies = {
'@tanstack/react-start': '1.168.60', '@tanstack/react-router': '1.170.41',
'@vitejs/plugin-react': '6.3.0', react: '19.3.1', 'react-dom': '19.3.1', vite: '8.3.8',
};
const fixtures = {
astro: {
dependencies: { astro: '7.4.12', '@astrojs/node': '11.1.13' },
Expand Down Expand Up @@ -91,8 +95,7 @@ export default function App() { return <Outlet />; }`,
start: ['node_modules/.bin/react-router-serve', './build/server/index.js'],
},
tanstack: {
dependencies: { '@tanstack/react-start': '1.168.60', '@tanstack/react-router': '1.170.41',
'@vitejs/plugin-react': '6.3.0', nitro: '3.0.261103-rc', react: '19.3.1', 'react-dom': '19.3.1', vite: '8.3.8' },
dependencies: { ...tanstackDependencies, nitro: '3.0.261103-rc' },
files: {
'vite.config.ts': `import { defineConfig } from 'vite';
import { tanstackStart } from '@tanstack/react-start/plugin/vite';
Expand Down Expand Up @@ -144,6 +147,32 @@ main();`,
},
};

fixtures['tanstack-worker'] = {
...fixtures.tanstack,
dependencies: {
...tanstackDependencies,
'@cloudflare/vite-plugin': '1.70.0',
wrangler: '4.164.0',
},
files: {
...fixtures.tanstack.files,
'vite.config.ts': `import { defineConfig } from 'vite';
import { cloudflare } from '@cloudflare/vite-plugin';
import { tanstackStart } from '@tanstack/react-start/plugin/vite';
import react from '@vitejs/plugin-react';
export default defineConfig({
plugins: [cloudflare({ viteEnvironment: { name: 'ssr' } }), tanstackStart(), react()],
});`,
'wrangler.jsonc': JSON.stringify({
name: 'framework-fixture',
main: '@tanstack/react-start/server-entry',
compatibility_date: '2026-11-01',
compatibility_flags: ['nodejs_compat'],
}),
},
start: port => ['node_modules/vite/bin/vite.js', 'preview', '--host', '127.0.0.1', '--port', String(port), '--strictPort'],
};

function fastifyFixture(format) {
const commonJs = format === 'cjs';
const entry = commonJs ? 'server.cjs' : 'server.mjs';
Expand Down Expand Up @@ -264,7 +293,8 @@ async function check(protectedApp, liveBuild) {
}
const flags = protectedApp && fixture.preload ? ['--import', '@patchstack/connect/register/fastify'] : [];
if (liveBuild) flags.push('--import', './host/live.mjs');
const app = spawn(process.execPath, [...flags, ...fixture.start], { cwd, env: processEnv, stdio: ['ignore', 'pipe', 'pipe'] });
const entry = typeof fixture.start === 'function' ? fixture.start(port) : fixture.start;
const app = spawn(process.execPath, [...flags, ...entry], { cwd, env: processEnv, stdio: ['ignore', 'pipe', 'pipe'] });
let log = '';
for (const stream of [app.stdout, app.stderr]) stream.on('data', part => { log += part; });
const post = label => fetch(processEnv.ORIGIN + '/fixture', {
Expand Down
53 changes: 37 additions & 16 deletions src/protect/install/adapters/tanstack.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,20 +18,39 @@ const EXTENSIONS = ['ts', 'js', 'mts', 'mjs', 'tsx', 'jsx', 'cts', 'cjs'];
/** TanStack Start's own server entry, which a Cloudflare Worker runs when wrangler's `main` names it. */
const PACKAGE_ENTRY = '@tanstack/react-start/server-entry';
const WRANGLER_CONFIGS = ['wrangler.jsonc', 'wrangler.json', 'wrangler.toml'];
const MAIN = /^(\s*"main"\s*:\s*|main\s*=\s*)"([^"]*)"/m;

/**
* The Cloudflare Worker this app deploys as, when it builds with `@cloudflare/vite-plugin`: its wrangler
* config and the module that config names as `main`. That module is what the Worker runs, so the vite
* config's own entry setting does not decide it. Null when the app is not a Cloudflare Worker build, or
* its Worker entry cannot be read.
*/
function workerEntry(cwd: string, configs: string[]): { file: string; main: string } | null {
type WorkerMain = { value: string; start: number; end: number };

function readWorkerMain(cwd: string, file: string, source: string): WorkerMain | null {
if (file.endsWith('.toml')) {
const [root] = source.split(/^\s*\[/m, 1);
const matches = [...(root ?? '').matchAll(/^[ \t]*main[ \t]*=[ \t]*("[^"\r\n]*")[ \t]*(?:#.*)?$/gm)];
const match = matches.length === 1 ? matches[0] : undefined;
const quoted = match?.[1];
if (!match || quoted === undefined) return null;
const start = match.index + match[0].indexOf(quoted);
return { value: quoted.slice(1, -1), start, end: start + quoted.length };
}

const ts = sourceCompiler(cwd);
if (!ts) return null;
const tree = ts.parseJsonText(file, source);
if ((tree as typeof tree & { parseDiagnostics: unknown[] }).parseDiagnostics.length) return null;
const statement = tree.statements.length === 1 ? tree.statements[0] : undefined;
if (!statement || !ts.isExpressionStatement(statement) || !ts.isObjectLiteralExpression(statement.expression)) return null;
const properties = statement.expression.properties.filter((property): property is import('typescript').PropertyAssignment =>
ts.isPropertyAssignment(property) && ts.isStringLiteral(property.name) && property.name.text === 'main');
const value = properties.length === 1 ? properties[0]?.initializer : undefined;
return value && ts.isStringLiteral(value)
? { value: value.text, start: value.getStart(tree), end: value.end }
: null;
}

/** Read the entry explicitly configured for the Cloudflare Vite build. */
function workerEntry(cwd: string, configs: string[]): { file: string; main: WorkerMain | null } | null {
if (!configs.some(file => read(join(cwd, file)).includes('@cloudflare/vite-plugin'))) return null;
const file = WRANGLER_CONFIGS.find(name => existsSync(join(cwd, name)));
const main = file ? MAIN.exec(read(join(cwd, file)))?.[2] : undefined;

return file && main !== undefined ? { file, main } : null;
return file ? { file, main: readWorkerMain(cwd, file, read(join(cwd, file))) } : null;
}

/** Whether a wrangler `main` names the managed server entry. */
Expand Down Expand Up @@ -134,7 +153,8 @@ function entryProblem(cwd: string): string | null {
// the managed one (`protect` does that); anything else is the app's own and is left to it.
const worker = workerEntry(cwd, configs);
if (worker) {
return runsManagedEntry(worker.main) || worker.main === PACKAGE_ENTRY
if (!worker.main) return `cannot determine the Cloudflare Worker entry (\`main\` in ${worker.file})`;
return runsManagedEntry(worker.main.value) || worker.main.value === PACKAGE_ENTRY
? null
: `the Cloudflare Worker entry (\`main\` in ${worker.file}) is a custom module; wrap its Fetch handler manually`;
}
Expand Down Expand Up @@ -250,9 +270,10 @@ export const tanstackAdapter: Adapter = {
changed.push(ENTRY);
}
const worker = workerEntry(cwd, viteConfigs(cwd));
if (worker && worker.main === PACKAGE_ENTRY) {
if (worker?.main?.value === PACKAGE_ENTRY) {
const config = read(join(cwd, worker.file));
writeProjectFileSync(cwd, join(cwd, worker.file), config.replace(MAIN, (_, key: string) => `${key}"./${ENTRY}"`));
const { start, end } = worker.main;
writeProjectFileSync(cwd, join(cwd, worker.file), config.slice(0, start) + JSON.stringify(`./${ENTRY}`) + config.slice(end));
changed.push(worker.file);
log(`Cloudflare Worker entry (\`main\` in ${worker.file}) now runs ${ENTRY}.`);
}
Expand All @@ -263,8 +284,8 @@ export const tanstackAdapter: Adapter = {
const ts = sourceCompiler(cwd);
const problem = entryProblem(cwd);
const worker = workerEntry(cwd, viteConfigs(cwd));
const workerProblem = worker && !runsManagedEntry(worker.main)
? `the Cloudflare Worker runs \`${worker.main}\` (\`main\` in ${worker.file}), not ${ENTRY}; run protect`
const workerProblem = worker?.main && !runsManagedEntry(worker.main.value)
? `the Cloudflare Worker runs \`${worker.main.value}\` (\`main\` in ${worker.file}), not ${ENTRY}; run protect`
: null;
const wired = !problem && !workerProblem && !!ts && existsSync(join(cwd,ENTRY)) && wiredEntry(ts,read(join(cwd,ENTRY)))
&& matchesGuardTemplate(cwd,GUARD,'fetch-guard.ts') && existsSync(join(cwd,'src/patchstack/rules.json'));
Expand Down
18 changes: 18 additions & 0 deletions tests/protect/framework-entries.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -338,6 +338,24 @@ export default defineConfig(({ command }) => ({
expect([read(cwd, 'src/server.ts'), read(cwd, 'wrangler.jsonc')]).toEqual(files);
});

it('rewrites only the root entry in compact Worker configuration', () => {
const cwd = worker();
const source = JSON.stringify({ name: 'app', vars: { main: 'example' }, main: '@tanstack/react-start/server-entry' });
put(cwd, 'wrangler.jsonc', source);
expect(runProtect(cwd).status).toBe('wired');
expect(read(cwd, 'wrangler.jsonc')).toBe(source.replace('@tanstack/react-start/server-entry', './src/server.ts'));
expect(runVerify(cwd).wired).toBe(true);
});

it('leaves an entry defined only in a named environment untouched', () => {
const cwd = worker();
const source = JSON.stringify({ env: { preview: { main: '@tanstack/react-start/server-entry' } } });
put(cwd, 'wrangler.jsonc', source);
expect(runProtect(cwd).status).not.toBe('wired');
expect(runVerify(cwd).wired).toBe(false);
expect(read(cwd, 'wrangler.jsonc')).toBe(source);
});

it('accepts a hand-wired entry in another quote style, and names the Worker entry as what is missing', () => {
const cwd = worker();
expect(runProtect(cwd).status).toBe('wired');
Expand Down
2 changes: 1 addition & 1 deletion tests/protect/runtime.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -218,7 +218,7 @@ describe('egress phase — SSRF', () => {
const p = await createProtection({ egress: true, mode: 'block' });
try {
await expect(globalThis.fetch('http://169.254.169.254/latest/meta-data/')).rejects.toThrow();
expect((await (globalThis.fetch as any)('https://api.example.com/')).marker).toBe('stub');
expect((await (globalThis.fetch as any)('https://203.0.113.10/')).marker).toBe('stub');
} finally {
p.uninstallEgress?.();
globalThis.fetch = orig;
Expand Down
3 changes: 1 addition & 2 deletions tests/protect/tier3.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -172,8 +172,7 @@ describe('egress phase — depth', () => {
for (const host of ['127.0.0.1', '10.0.0.5', '192.168.1.1', '172.16.0.9', 'localhost', '[::1]', 'metadata.google.internal']) {
await expect(globalThis.fetch(`http://${host}/`), host).rejects.toThrow();
}
expect((await (globalThis.fetch as any)('https://8.8.8.8/')).marker).toBe('stub');
expect((await (globalThis.fetch as any)('https://api.example.com/')).marker).toBe('stub');
expect((await (globalThis.fetch as any)('https://203.0.113.10/')).marker).toBe('stub');
});
});

Expand Down
Loading