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
5 changes: 2 additions & 3 deletions apps/docs/lib/integrations/seo-overrides.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
/**
* Hand-authored search titles, descriptions and FAQs for integrations whose pages the previous
* website (`apps/sim/app/(landing)/integrations/data/seo-content.ts`, removed when the website moved
* to simstudioai/site) had tuned. Keyed by catalog slug; any integration absent here, or any field
* left out, uses the generated default in `@/lib/integrations/seo`.
* website had tuned. Keyed by catalog slug; any integration absent here, or any field left out,
* uses the generated default in `@/lib/integrations/seo`.
*/

interface IntegrationSeoOverride {
Expand Down
4 changes: 2 additions & 2 deletions apps/docs/lib/integrations/seo.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { INTEGRATION_TOTALS } from '@sim/deployment-config/integration-totals'
import integrationsJson from '@sim/deployment-config/integrations.json'
import { formatLowerBound } from '@sim/utils/formatting'
import { compareStrings } from '@sim/utils/string'
import { compareStrings, stripVersionSuffix } from '@sim/utils/string'
import type { DocsPage } from '@/lib/content/types'
import { INTEGRATION_SEO_OVERRIDES } from '@/lib/integrations/seo-overrides'

Expand Down Expand Up @@ -255,7 +255,7 @@ export function getIntegrationCatalogContent(): IntegrationCatalogContent {
label: label(id),
integrations: members.map((integration) => ({
name: integration.name,
path: `/integrations/${integration.type.replace(/_v\d+$/, '')}`,
path: `/integrations/${stripVersionSuffix(integration.type)}`,
description: integration.description,
})),
})),
Expand Down
2 changes: 2 additions & 0 deletions apps/docs/scripts/compile-content.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,8 @@ const PIPELINE_FILES = [
path.join(DOCS_ROOT, 'lib/integrations/seo-overrides.ts'),
path.join(DOCS_ROOT, '../../packages/deployment-config/src/integrations.json'),
path.join(DOCS_ROOT, '../../packages/deployment-config/src/integration-totals.ts'),
path.join(DOCS_ROOT, '../../packages/utils/src/formatting.ts'),
path.join(DOCS_ROOT, '../../packages/utils/src/string.ts'),
]
const CONTENT_ROOT = path.join(DOCS_ROOT, 'content/docs')
const OUTPUT_ROOT = path.join(DOCS_ROOT, '.content')
Expand Down
2 changes: 1 addition & 1 deletion apps/sim/app/desktop/connect/page.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'

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

/** Keeps the landing-page barrel the real shell pulls in out of this graph. */
/** Keeps the auth shell the real component pulls in out of this graph. */
vi.mock('@/app/desktop/components/desktop-handoff-shell', () => ({
DesktopHandoffShell: () => null,
}))
Expand Down
49 changes: 48 additions & 1 deletion apps/sim/lib/website/homepage.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,11 @@
import { createServer, type IncomingHttpHeaders, type ServerResponse } from 'node:http'
import type { AddressInfo } from 'node:net'
import { afterEach, beforeAll, describe, expect, it, vi } from 'vitest'
import { fetchWebsiteHomepage, type HomepageFetchLimits } from '@/lib/website/homepage'
import {
fetchWebsiteHomepage,
getWebsiteHomepage,
type HomepageFetchLimits,
} from '@/lib/website/homepage'

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

it.each([
"default-src 'none'; script-src 'self'; frame-ancestors *",
"default-src 'none'; script-src 'self'; frame-ancestors https://example.com",
"default-src 'none'; script-src 'self'; frame-ancestors 'self' https:",
])('refuses a page policy that lets other sites frame the page: %s', async (policy) => {
const upstream = await startUpstream((response) =>
html(response, { 'Content-Security-Policy': policy })
)
expect(await fetchWebsiteHomepage(upstream.origin, 'html', LIMITS)).toEqual({
ok: false,
reason: 'unsafe_policy',
})
})

it('accepts a page policy that lets only this origin frame the page', async () => {
const policy = "default-src 'none'; script-src 'self'; frame-ancestors 'self'"
const upstream = await startUpstream((response) =>
html(response, { 'Content-Security-Policy': policy })
)
expect(await fetchWebsiteHomepage(upstream.origin, 'html', LIMITS)).toMatchObject({
ok: true,
contentSecurityPolicy: policy,
})
})

it('refuses a response with more than one page policy', async () => {
const upstream = await startUpstream((response) => {
response.setHeader('Content-Type', 'text/html')
Expand Down Expand Up @@ -288,3 +317,21 @@ describe('fetchWebsiteHomepage', () => {
})
})
})

describe('getWebsiteHomepage', () => {
it('answers from a recent failure, without asking the website again, while it has no copy', async () => {
const upstream = await startUpstream((response) => {
response.writeHead(500, { 'Content-Type': 'text/html' })
response.end('<p>upstream failure</p>')
})
const failure = { ok: false, reason: 'bad_status' }
expect(await getWebsiteHomepage(upstream.origin, 'html')).toEqual(failure)
expect(await getWebsiteHomepage(upstream.origin, 'html')).toEqual(failure)
expect(upstream.requests).toHaveLength(1)

const later = Date.now() + 11_000
vi.spyOn(Date, 'now').mockReturnValue(later)
expect(await getWebsiteHomepage(upstream.origin, 'html')).toEqual(failure)
expect(upstream.requests).toHaveLength(2)
})
})
37 changes: 30 additions & 7 deletions apps/sim/lib/website/homepage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,11 @@ const HOMEPAGE_FETCH_LIMITS: HomepageFetchLimits = {
const HOMEPAGE_FRESH_MS = 60_000
/** How long a fetched homepage may still be served while the website keeps failing. */
const HOMEPAGE_STALE_LIMIT_MS = 60 * 60_000
/**
* How long a failed fetch answers for itself while there is no copy to serve, so a website that is
* down does not hold each visitor for the full timeout before the fallback page.
*/
const HOMEPAGE_FAILURE_HOLD_MS = 10_000

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

/** Who may frame the page, if the policy says: it overrides the route's `X-Frame-Options: DENY`. */
const SAFE_FRAME_ANCESTORS = new Set(["'none'", "'self'"])

/**
* Whether a page policy restricts script to safe sources: `script-src`, or `default-src` when it
* is absent, must exist, and it and every `script-src-elem` / `script-src-attr` present may name
* no unsafe keyword, bare scheme or wildcard host.
* no unsafe keyword, bare scheme or wildcard host. A `frame-ancestors` it names may allow only
* this origin, or none.
*/
function isSafePolicy(policy: string): boolean {
const directives = new Map<string, string[]>()
Expand All @@ -169,6 +178,10 @@ function isSafePolicy(policy: string): boolean {
directives.set(name.toLowerCase(), sources)
}
}
const frameAncestors = directives.get('frame-ancestors')
if (frameAncestors?.some((source) => !SAFE_FRAME_ANCESTORS.has(source.toLowerCase()))) {
return false
}
const scriptSources = directives.get('script-src') ?? directives.get('default-src')
if (!scriptSources) return false
return [
Expand Down Expand Up @@ -260,8 +273,10 @@ interface CachedHomepage extends WebsiteHomepage {
fetchedAt: number
}

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

/**
* The last good homepage, one entry per format of the one configured origin. Concurrent misses
Expand All @@ -287,7 +302,7 @@ const homepageCache = new LRUCache<string, CachedHomepage, HomepageCacheContext>
fetchMethod: async (key, _stale, { context }) => {
const result = await fetchWebsiteHomepage(context.origin, context.format)
if (!result.ok) {
lastRefreshFailure.set(key, result.reason)
lastRefreshFailure.set(key, { reason: result.reason, at: Date.now() })
throw new HomepageFetchError(result.reason)
}
lastRefreshFailure.delete(key)
Expand All @@ -312,13 +327,21 @@ function failureReason(error: unknown): HomepageFetchFailure {
* The website's homepage for `/` in the requested format: fresh for a minute, then served while
* the next refresh runs in the background. While the website keeps failing, the last good copy is
* served for up to an hour (with the failed refresh's reason); past that, the visitor waits for a
* refresh. Not tied to any visitor's request signal, since one fetch serves every waiting visitor.
* refresh. With no copy to serve, a failure from the last ten seconds is the answer without
* another fetch. Not tied to any visitor's request signal, since one fetch serves every waiting
* visitor.
*/
export async function getWebsiteHomepage(
origin: string,
format: HomepageFormat
): Promise<HomepageResult> {
const key = `${format} ${origin}`
const failure = lastRefreshFailure.get(key)
const copy = homepageCache.peek(key, { allowStale: true })
const usable = copy !== undefined && Date.now() - copy.fetchedAt <= HOMEPAGE_STALE_LIMIT_MS
if (!usable && failure && Date.now() - failure.at < HOMEPAGE_FAILURE_HOLD_MS) {
return { ok: false, reason: failure.reason }
}
const context: HomepageCacheContext = { origin, format }
const status: LRUCache.Status<string, CachedHomepage, HomepageCacheContext> = {}
let cached: CachedHomepage | undefined
Expand All @@ -332,9 +355,9 @@ export async function getWebsiteHomepage(
}
if (!cached) return { ok: false, reason: failureReason(status.fetchError) }
if (Date.now() - cached.fetchedAt > HOMEPAGE_STALE_LIMIT_MS) {
return { ok: false, reason: lastRefreshFailure.get(key) ?? 'stale_expired' }
return { ok: false, reason: lastRefreshFailure.get(key)?.reason ?? 'stale_expired' }
}
const refreshFailure = lastRefreshFailure.get(key)
const refreshFailure = lastRefreshFailure.get(key)?.reason
return {
ok: true,
...(refreshFailure ? { refreshFailure } : {}),
Expand Down
2 changes: 1 addition & 1 deletion apps/sim/next.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -351,7 +351,7 @@ const nextConfig: NextConfig = {
],
},
// Apply security headers to routes not handled by middleware runtime CSP
// Middleware handles: /, /login, /signup, /workspace/*
// Middleware handles /login, /signup and /workspace/*; the root route sets its own headers
// Exclude chat routes which have their own permissive embed headers
{
source: '/((?!workspace|chat|extension(?:/|$)|login|signup|$).*)',
Expand Down
2 changes: 1 addition & 1 deletion apps/sim/proxy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -473,7 +473,7 @@ function applyIndexingPolicy(request: NextRequest, response: NextResponse): Next

export const config = {
matcher: [
'/', // Root path for self-hosted redirect logic
'/', // Session hint and self-hosted sign-in redirects; the root route serves the rest
'/w', // Legacy /w redirect
'/w/:path*', // Legacy /w/* redirects
'/workspace/:path*', // New workspace routes
Expand Down
14 changes: 5 additions & 9 deletions packages/auth-ui/src/compositions.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -238,17 +238,13 @@ export function AuthSection({ title, children, className, description }: AuthSec

interface AuthLegalProps {
action: string
/** Terms of Service page; defaults to the host's `/terms`. */
termsHref?: string
/** Privacy Policy page; defaults to the host's `/privacy`. */
privacyHref?: string
/** Terms of Service page. */
termsHref: string
/** Privacy Policy page. */
privacyHref: string
}
/** Links the Terms of Service and Privacy Policy, opening them separately without losing form state. */
export function AuthLegal({
action,
termsHref = '/terms',
privacyHref = '/privacy',
}: AuthLegalProps) {
export function AuthLegal({ action, termsHref, privacyHref }: AuthLegalProps) {
return (
<p className={styles.legal}>
By {action}, you agree to our{' '}
Expand Down
5 changes: 3 additions & 2 deletions packages/deployment-config/src/integration-docs.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { INTEGRATION_METADATA } from '@sim/deployment-config/integration-metadata'
import { stripVersionSuffix } from '@sim/utils/string'

/**
* Slugs the previous website's integration pages once had, each with the catalog slug that
Expand All @@ -23,10 +24,10 @@ const RETIRED_INTEGRATION_SLUGS: Readonly<Record<string, string>> = {
export const INTEGRATION_DOCS_PATHS: ReadonlyMap<string, string> = (() => {
const paths = new Map<string, string>()
for (const integration of INTEGRATION_METADATA) {
paths.set(integration.slug, `/integrations/${integration.type.replace(/_v\d+$/, '')}`)
paths.set(integration.slug, `/integrations/${stripVersionSuffix(integration.type)}`)
}
for (const integration of INTEGRATION_METADATA) {
const docsSlug = integration.type.replace(/_v\d+$/, '')
const docsSlug = stripVersionSuffix(integration.type)
if (!paths.has(docsSlug)) paths.set(docsSlug, `/integrations/${docsSlug}`)
}
for (const [retired, current] of Object.entries(RETIRED_INTEGRATION_SLUGS)) {
Expand Down
Loading