Skip to content

Commit 458a31f

Browse files
authored
fix(landing): hold homepage failures briefly, refuse framable website policies, and tidy what the website move left (#10789)
* fix(landing): hold homepage failures briefly, refuse framable website policies, and tidy what the website move left - With no homepage copy to serve, a fetch failure from the last ten seconds answers for itself, so a website that is down does not hold each visitor for the full timeout before the fallback page. - The website's page policy is refused if its frame-ancestors allows any origin but this one, since it would override the route's X-Frame-Options. - AuthLegal requires its Terms and Privacy links; its /terms and /privacy defaults pointed at pages the platform no longer serves. - The integration docs slug uses the shared stripVersionSuffix, and the docs compile cache and --watch also key on the @sim/utils modules the integration pages render from. - Comments that still described the removed landing now describe the root route and auth shell. * test(landing): drop a mock restore the shared Vitest config already makes
1 parent ac30043 commit 458a31f

10 files changed

Lines changed: 95 additions & 27 deletions

File tree

‎apps/docs/lib/integrations/seo-overrides.ts‎

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,7 @@
11
/**
22
* Hand-authored search titles, descriptions and FAQs for integrations whose pages the previous
3-
* website (`apps/sim/app/(landing)/integrations/data/seo-content.ts`, removed when the website moved
4-
* to simstudioai/site) had tuned. Keyed by catalog slug; any integration absent here, or any field
5-
* left out, uses the generated default in `@/lib/integrations/seo`.
3+
* website had tuned. Keyed by catalog slug; any integration absent here, or any field left out,
4+
* uses the generated default in `@/lib/integrations/seo`.
65
*/
76

87
interface IntegrationSeoOverride {

‎apps/docs/lib/integrations/seo.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import { INTEGRATION_TOTALS } from '@sim/deployment-config/integration-totals'
22
import integrationsJson from '@sim/deployment-config/integrations.json'
33
import { formatLowerBound } from '@sim/utils/formatting'
4-
import { compareStrings } from '@sim/utils/string'
4+
import { compareStrings, stripVersionSuffix } from '@sim/utils/string'
55
import type { DocsPage } from '@/lib/content/types'
66
import { INTEGRATION_SEO_OVERRIDES } from '@/lib/integrations/seo-overrides'
77

@@ -255,7 +255,7 @@ export function getIntegrationCatalogContent(): IntegrationCatalogContent {
255255
label: label(id),
256256
integrations: members.map((integration) => ({
257257
name: integration.name,
258-
path: `/integrations/${integration.type.replace(/_v\d+$/, '')}`,
258+
path: `/integrations/${stripVersionSuffix(integration.type)}`,
259259
description: integration.description,
260260
})),
261261
})),

‎apps/docs/scripts/compile-content.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,8 @@ const PIPELINE_FILES = [
4343
path.join(DOCS_ROOT, 'lib/integrations/seo-overrides.ts'),
4444
path.join(DOCS_ROOT, '../../packages/deployment-config/src/integrations.json'),
4545
path.join(DOCS_ROOT, '../../packages/deployment-config/src/integration-totals.ts'),
46+
path.join(DOCS_ROOT, '../../packages/utils/src/formatting.ts'),
47+
path.join(DOCS_ROOT, '../../packages/utils/src/string.ts'),
4648
]
4749
const CONTENT_ROOT = path.join(DOCS_ROOT, 'content/docs')
4850
const OUTPUT_ROOT = path.join(DOCS_ROOT, '.content')

‎apps/sim/app/desktop/connect/page.test.tsx‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'
66

77
vi.mock('@/lib/auth/client', () => authClientMock)
88

9-
/** Keeps the landing-page barrel the real shell pulls in out of this graph. */
9+
/** Keeps the auth shell the real component pulls in out of this graph. */
1010
vi.mock('@/app/desktop/components/desktop-handoff-shell', () => ({
1111
DesktopHandoffShell: () => null,
1212
}))

‎apps/sim/lib/website/homepage.test.ts‎

Lines changed: 48 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,11 @@
55
import { createServer, type IncomingHttpHeaders, type ServerResponse } from 'node:http'
66
import type { AddressInfo } from 'node:net'
77
import { afterEach, beforeAll, describe, expect, it, vi } from 'vitest'
8-
import { fetchWebsiteHomepage, type HomepageFetchLimits } from '@/lib/website/homepage'
8+
import {
9+
fetchWebsiteHomepage,
10+
getWebsiteHomepage,
11+
type HomepageFetchLimits,
12+
} from '@/lib/website/homepage'
913

1014
const PAGE = '<!doctype html><title>Sim</title><h1>Agents for the work that runs itself</h1>'
1115
const LIMITS: HomepageFetchLimits = { timeoutMs: 300, maxBytes: 64 * 1024 }
@@ -152,6 +156,31 @@ describe('fetchWebsiteHomepage', () => {
152156
})
153157
})
154158

159+
it.each([
160+
"default-src 'none'; script-src 'self'; frame-ancestors *",
161+
"default-src 'none'; script-src 'self'; frame-ancestors https://example.com",
162+
"default-src 'none'; script-src 'self'; frame-ancestors 'self' https:",
163+
])('refuses a page policy that lets other sites frame the page: %s', async (policy) => {
164+
const upstream = await startUpstream((response) =>
165+
html(response, { 'Content-Security-Policy': policy })
166+
)
167+
expect(await fetchWebsiteHomepage(upstream.origin, 'html', LIMITS)).toEqual({
168+
ok: false,
169+
reason: 'unsafe_policy',
170+
})
171+
})
172+
173+
it('accepts a page policy that lets only this origin frame the page', async () => {
174+
const policy = "default-src 'none'; script-src 'self'; frame-ancestors 'self'"
175+
const upstream = await startUpstream((response) =>
176+
html(response, { 'Content-Security-Policy': policy })
177+
)
178+
expect(await fetchWebsiteHomepage(upstream.origin, 'html', LIMITS)).toMatchObject({
179+
ok: true,
180+
contentSecurityPolicy: policy,
181+
})
182+
})
183+
155184
it('refuses a response with more than one page policy', async () => {
156185
const upstream = await startUpstream((response) => {
157186
response.setHeader('Content-Type', 'text/html')
@@ -288,3 +317,21 @@ describe('fetchWebsiteHomepage', () => {
288317
})
289318
})
290319
})
320+
321+
describe('getWebsiteHomepage', () => {
322+
it('answers from a recent failure, without asking the website again, while it has no copy', async () => {
323+
const upstream = await startUpstream((response) => {
324+
response.writeHead(500, { 'Content-Type': 'text/html' })
325+
response.end('<p>upstream failure</p>')
326+
})
327+
const failure = { ok: false, reason: 'bad_status' }
328+
expect(await getWebsiteHomepage(upstream.origin, 'html')).toEqual(failure)
329+
expect(await getWebsiteHomepage(upstream.origin, 'html')).toEqual(failure)
330+
expect(upstream.requests).toHaveLength(1)
331+
332+
const later = Date.now() + 11_000
333+
vi.spyOn(Date, 'now').mockReturnValue(later)
334+
expect(await getWebsiteHomepage(upstream.origin, 'html')).toEqual(failure)
335+
expect(upstream.requests).toHaveLength(2)
336+
})
337+
})

‎apps/sim/lib/website/homepage.ts‎

Lines changed: 30 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,11 @@ const HOMEPAGE_FETCH_LIMITS: HomepageFetchLimits = {
3030
const HOMEPAGE_FRESH_MS = 60_000
3131
/** How long a fetched homepage may still be served while the website keeps failing. */
3232
const HOMEPAGE_STALE_LIMIT_MS = 60 * 60_000
33+
/**
34+
* How long a failed fetch answers for itself while there is no copy to serve, so a website that is
35+
* down does not hold each visitor for the full timeout before the fallback page.
36+
*/
37+
const HOMEPAGE_FAILURE_HOLD_MS = 10_000
3338

3439
type HomepageFetchFailure =
3540
| 'invalid_origin'
@@ -156,10 +161,14 @@ function isSafeScriptSource(source: string): boolean {
156161
/** Script directives that override `script-src` for elements and attributes when present. */
157162
const ELEMENT_SCRIPT_DIRECTIVES = ['script-src-elem', 'script-src-attr'] as const
158163

164+
/** Who may frame the page, if the policy says: it overrides the route's `X-Frame-Options: DENY`. */
165+
const SAFE_FRAME_ANCESTORS = new Set(["'none'", "'self'"])
166+
159167
/**
160168
* Whether a page policy restricts script to safe sources: `script-src`, or `default-src` when it
161169
* is absent, must exist, and it and every `script-src-elem` / `script-src-attr` present may name
162-
* no unsafe keyword, bare scheme or wildcard host.
170+
* no unsafe keyword, bare scheme or wildcard host. A `frame-ancestors` it names may allow only
171+
* this origin, or none.
163172
*/
164173
function isSafePolicy(policy: string): boolean {
165174
const directives = new Map<string, string[]>()
@@ -169,6 +178,10 @@ function isSafePolicy(policy: string): boolean {
169178
directives.set(name.toLowerCase(), sources)
170179
}
171180
}
181+
const frameAncestors = directives.get('frame-ancestors')
182+
if (frameAncestors?.some((source) => !SAFE_FRAME_ANCESTORS.has(source.toLowerCase()))) {
183+
return false
184+
}
172185
const scriptSources = directives.get('script-src') ?? directives.get('default-src')
173186
if (!scriptSources) return false
174187
return [
@@ -260,8 +273,10 @@ interface CachedHomepage extends WebsiteHomepage {
260273
fetchedAt: number
261274
}
262275

263-
/** Why the last refresh of each cached format failed, until one succeeds. */
264-
const lastRefreshFailure = new LRUCache<string, HomepageFetchFailure>({ max: 2 })
276+
/** Why and when the last refresh of each cached format failed, until one succeeds. */
277+
const lastRefreshFailure = new LRUCache<string, { reason: HomepageFetchFailure; at: number }>({
278+
max: 2,
279+
})
265280

266281
/**
267282
* The last good homepage, one entry per format of the one configured origin. Concurrent misses
@@ -287,7 +302,7 @@ const homepageCache = new LRUCache<string, CachedHomepage, HomepageCacheContext>
287302
fetchMethod: async (key, _stale, { context }) => {
288303
const result = await fetchWebsiteHomepage(context.origin, context.format)
289304
if (!result.ok) {
290-
lastRefreshFailure.set(key, result.reason)
305+
lastRefreshFailure.set(key, { reason: result.reason, at: Date.now() })
291306
throw new HomepageFetchError(result.reason)
292307
}
293308
lastRefreshFailure.delete(key)
@@ -312,13 +327,21 @@ function failureReason(error: unknown): HomepageFetchFailure {
312327
* The website's homepage for `/` in the requested format: fresh for a minute, then served while
313328
* the next refresh runs in the background. While the website keeps failing, the last good copy is
314329
* served for up to an hour (with the failed refresh's reason); past that, the visitor waits for a
315-
* refresh. Not tied to any visitor's request signal, since one fetch serves every waiting visitor.
330+
* refresh. With no copy to serve, a failure from the last ten seconds is the answer without
331+
* another fetch. Not tied to any visitor's request signal, since one fetch serves every waiting
332+
* visitor.
316333
*/
317334
export async function getWebsiteHomepage(
318335
origin: string,
319336
format: HomepageFormat
320337
): Promise<HomepageResult> {
321338
const key = `${format} ${origin}`
339+
const failure = lastRefreshFailure.get(key)
340+
const copy = homepageCache.peek(key, { allowStale: true })
341+
const usable = copy !== undefined && Date.now() - copy.fetchedAt <= HOMEPAGE_STALE_LIMIT_MS
342+
if (!usable && failure && Date.now() - failure.at < HOMEPAGE_FAILURE_HOLD_MS) {
343+
return { ok: false, reason: failure.reason }
344+
}
322345
const context: HomepageCacheContext = { origin, format }
323346
const status: LRUCache.Status<string, CachedHomepage, HomepageCacheContext> = {}
324347
let cached: CachedHomepage | undefined
@@ -332,9 +355,9 @@ export async function getWebsiteHomepage(
332355
}
333356
if (!cached) return { ok: false, reason: failureReason(status.fetchError) }
334357
if (Date.now() - cached.fetchedAt > HOMEPAGE_STALE_LIMIT_MS) {
335-
return { ok: false, reason: lastRefreshFailure.get(key) ?? 'stale_expired' }
358+
return { ok: false, reason: lastRefreshFailure.get(key)?.reason ?? 'stale_expired' }
336359
}
337-
const refreshFailure = lastRefreshFailure.get(key)
360+
const refreshFailure = lastRefreshFailure.get(key)?.reason
338361
return {
339362
ok: true,
340363
...(refreshFailure ? { refreshFailure } : {}),

‎apps/sim/next.config.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -351,7 +351,7 @@ const nextConfig: NextConfig = {
351351
],
352352
},
353353
// Apply security headers to routes not handled by middleware runtime CSP
354-
// Middleware handles: /, /login, /signup, /workspace/*
354+
// Middleware handles /login, /signup and /workspace/*; the root route sets its own headers
355355
// Exclude chat routes which have their own permissive embed headers
356356
{
357357
source: '/((?!workspace|chat|extension(?:/|$)|login|signup|$).*)',

‎apps/sim/proxy.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -473,7 +473,7 @@ function applyIndexingPolicy(request: NextRequest, response: NextResponse): Next
473473

474474
export const config = {
475475
matcher: [
476-
'/', // Root path for self-hosted redirect logic
476+
'/', // Session hint and self-hosted sign-in redirects; the root route serves the rest
477477
'/w', // Legacy /w redirect
478478
'/w/:path*', // Legacy /w/* redirects
479479
'/workspace/:path*', // New workspace routes

‎packages/auth-ui/src/compositions.tsx‎

Lines changed: 5 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -238,17 +238,13 @@ export function AuthSection({ title, children, className, description }: AuthSec
238238

239239
interface AuthLegalProps {
240240
action: string
241-
/** Terms of Service page; defaults to the host's `/terms`. */
242-
termsHref?: string
243-
/** Privacy Policy page; defaults to the host's `/privacy`. */
244-
privacyHref?: string
241+
/** Terms of Service page. */
242+
termsHref: string
243+
/** Privacy Policy page. */
244+
privacyHref: string
245245
}
246246
/** Links the Terms of Service and Privacy Policy, opening them separately without losing form state. */
247-
export function AuthLegal({
248-
action,
249-
termsHref = '/terms',
250-
privacyHref = '/privacy',
251-
}: AuthLegalProps) {
247+
export function AuthLegal({ action, termsHref, privacyHref }: AuthLegalProps) {
252248
return (
253249
<p className={styles.legal}>
254250
By {action}, you agree to our{' '}

‎packages/deployment-config/src/integration-docs.ts‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import { INTEGRATION_METADATA } from '@sim/deployment-config/integration-metadata'
2+
import { stripVersionSuffix } from '@sim/utils/string'
23

34
/**
45
* Slugs the previous website's integration pages once had, each with the catalog slug that
@@ -23,10 +24,10 @@ const RETIRED_INTEGRATION_SLUGS: Readonly<Record<string, string>> = {
2324
export const INTEGRATION_DOCS_PATHS: ReadonlyMap<string, string> = (() => {
2425
const paths = new Map<string, string>()
2526
for (const integration of INTEGRATION_METADATA) {
26-
paths.set(integration.slug, `/integrations/${integration.type.replace(/_v\d+$/, '')}`)
27+
paths.set(integration.slug, `/integrations/${stripVersionSuffix(integration.type)}`)
2728
}
2829
for (const integration of INTEGRATION_METADATA) {
29-
const docsSlug = integration.type.replace(/_v\d+$/, '')
30+
const docsSlug = stripVersionSuffix(integration.type)
3031
if (!paths.has(docsSlug)) paths.set(docsSlug, `/integrations/${docsSlug}`)
3132
}
3233
for (const [retired, current] of Object.entries(RETIRED_INTEGRATION_SLUGS)) {

0 commit comments

Comments
 (0)