Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(infra): deploy the public website from apps/marketing (#7327)
teof8d1725d1920
diff --git a/.github/workflows/deploy_website.yml b/.github/workflows/deploy_website.ymlnew file mode 100644index 0000000000..7d791bad06--- /dev/null+++ b/.github/workflows/deploy_website.yml@@ -0,0 +1,100 @@+# DO NOT EDIT — regenerate with `cargo x workflows` (from the repository root).+# Source: tooling/xtask/crates/xtask_workflows/src/workflows/deploy_website.rs+name: Deploy Website+on:+ push:+ branches:+ - main+ paths:+ - .github/workflows/deploy_website.yml+ - bun.lock+ - apps/marketing/**+ - infra/stacks/website/**+ workflow_call:+ inputs:+ environment:+ required: true+ type: string+ description: The environment to deploy to. e.g. (dev, prod, both)+ secrets:+ AWS_ACCESS_KEY:+ required: true+ AWS_SECRET_ACCESS_KEY:+ required: true+ PULUMI_ACCESS_TOKEN:+ required: true+ workflow_dispatch:+ inputs:+ environment:+ required: true+ type: choice+ default: dev+ options:+ - dev+ - prod+ - both+ description: The environment to deploy to (both deploys dev, then prod)+jobs:+ build-deploy:+ name: Build and Deploy Website+ runs-on: namespace-profile-linux-mid;overrides.cache-tag=web-ci+ concurrency:+ group: deploy-website-${{ matrix.environment }}+ cancel-in-progress: false+ env:+ CI: 'true'+ strategy:+ matrix:+ environment: ${{ fromJSON(inputs.environment == 'both' && '["dev","prod"]' || format('["{0}"]', inputs.environment || 'dev')) }}+ fail-fast: true+ max-parallel: 1+ steps:+ - name: Checkout Repo+ uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10+ with:+ lfs: 'true'+ - name: Verify Git LFS videos were downloaded+ run: |+ if grep -RIl --include='*.mp4' 'version https://git-lfs.github.com/spec/v1' public src; then+ echo "Found Git LFS pointer files instead of real videos."+ exit 1+ fi+ working-directory: apps/marketing+ - name: Mount Namespace cache volume+ uses: namespacelabs/nscloud-cache-action@15799a6b54e5765f85b2aac25b3f0df43ed571c0+ with:+ cache: nix+ path: /home/runner/.bun/install/cache+ continue-on-error: true+ - name: Setup Nix+ uses: ./.github/actions/setup-nix+ - name: Setup+ uses: ./.github/actions/setup-reqs-web+ with:+ playwright: 'true'+ - name: Build+ run: bun run build+ env:+ VITE_APP_BASE_URL: ${{ matrix.environment == 'prod' && 'https://macro.com' || 'https://dev.macro.com' }}+ VITE_GOOGLE_SSO_URL: ${{ matrix.environment == 'prod' && 'https://gateway.macro.com/auth/login/sso?idp_name=google_gmail' || 'https://dev-gateway.macro.com/auth/login/sso?idp_name=google_gmail' }}+ working-directory: apps/marketing+ - name: Install infra dependencies+ run: bun install+ working-directory: infra+ - name: Configure AWS Credentials+ uses: aws-actions/configure-aws-credentials@e7f100cf4c008499ea8adda475de1042d6975c7b+ with:+ aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY }}+ aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}+ aws-region: us-east-1+ - name: Deploy with Pulumi+ uses: pulumi/actions@8e5e406f4007fca908480587cb9893c07090f58d+ with:+ command: up+ stack-name: macro-inc/${{ matrix.environment }}+ work-dir: ./infra/stacks/website+ env:+ PULUMI_ACCESS_TOKEN: ${{ secrets.PULUMI_ACCESS_TOKEN }}+ - name: Teardown Nix+ if: always()+ uses: ./.github/actions/teardown-nixdiff --git a/.github/workflows/release-production.yml b/.github/workflows/release-production.ymlindex 6b8bd13188..425691a641 100644--- a/.github/workflows/release-production.yml+++ b/.github/workflows/release-production.yml@@ -197,6 +197,18 @@ jobs:environment: prodsecrets: inherit+ deploy-website:+ if: github.event_name == 'release'+ name: Deploy Website+ # Also owns the macro.com CloudFront distribution in front of the web app.+ uses: ./.github/workflows/deploy_website.yml+ with:+ environment: prod+ secrets:+ AWS_ACCESS_KEY: ${{ secrets.AWS_ACCESS_KEY }}+ AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }}+ PULUMI_ACCESS_TOKEN: ${{ secrets.PULUMI_ACCESS_TOKEN }}+build:if: github.event_name == 'release'name: Build Web Appdiff --git a/infra/.gitignore b/infra/.gitignoreindex 2a919a25ac..7340747435 100644--- a/infra/.gitignore+++ b/infra/.gitignore@@ -5,6 +5,7 @@!library.js!**/appRouteLambda/**/*.js!**/contentEncodingLambda/**/*.js+!stacks/website/wwwRedirect/handler.jspackage-lock.jsonlocal/generateddiff --git a/infra/biome.jsonc b/infra/biome.jsoncindex b406eafb8e..66e9435b0c 100644--- a/infra/biome.jsonc+++ b/infra/biome.jsonc@@ -17,7 +17,9 @@"**/*.jsx","**/openapi.json",// FusionAuth consumes these as external script templates; keep their source formatting stable.- "!stacks/fusionauth-instance/**/populate_jwt.js"+ "!stacks/fusionauth-instance/**/populate_jwt.js",+ // Uploaded verbatim as CloudFront Function code; reformatting it is a live function update.+ "!stacks/website/wwwRedirect/handler.js"]},"formatter": {diff --git a/infra/bun.lock b/infra/bun.lockindex 1ddcc2426b..7ed1870af7 100644--- a/infra/bun.lock+++ b/infra/bun.lock@@ -234,6 +234,14 @@"@pulumi/synced-folder": "^0.11.1",},},+ "stacks/website": {+ "name": "@macro-inc/infra-website",+ "dependencies": {+ "@pulumi/aws": "^6.83.0",+ "@pulumi/command": "^1.1.0",+ "@pulumi/pulumi": "^3.181.0",+ },+ },},"overrides": {"ts-node": "10.8.0",@@ -313,6 +321,8 @@"@macro-inc/infra-web-app": ["@macro-inc/infra-web-app@workspace:stacks/web-app"],+ "@macro-inc/infra-website": ["@macro-inc/infra-website@workspace:stacks/website"],+"@npmcli/agent": ["@npmcli/[email protected]", "", { "dependencies": { "agent-base": "^7.1.0", "http-proxy-agent": "^7.0.0", "https-proxy-agent": "^7.0.1", "lru-cache": "^11.2.1", "socks-proxy-agent": "^8.0.3" } }, "sha512-EUEuWAxnL07Sp5/iC/1X6Xj+XThUvnbei9zfRWZdEXa7lss9RTHMhAHBeg+MZ5To9s/gGaSI+UwZTPdYMvKSeg=="],"@npmcli/arborist": ["@npmcli/[email protected]", "", { "dependencies": { "@gar/promise-retry": "^1.0.0", "@isaacs/string-locale-compare": "^1.1.0", "@npmcli/fs": "^5.0.0", "@npmcli/installed-package-contents": "^4.0.0", "@npmcli/map-workspaces": "^5.0.0", "@npmcli/metavuln-calculator": "^9.0.2", "@npmcli/name-from-folder": "^4.0.0", "@npmcli/node-gyp": "^5.0.0", "@npmcli/package-json": "^7.0.0", "@npmcli/query": "^5.0.0", "@npmcli/redact": "^4.0.0", "@npmcli/run-script": "^10.0.0", "bin-links": "^6.0.0", "cacache": "^20.0.1", "common-ancestor-path": "^2.0.0", "hosted-git-info": "^9.0.0", "json-stringify-nice": "^1.1.4", "lru-cache": "^11.2.1", "minimatch": "^10.0.3", "nopt": "^9.0.0", "npm-install-checks": "^8.0.0", "npm-package-arg": "^13.0.0", "npm-pick-manifest": "^11.0.1", "npm-registry-fetch": "^19.0.0", "pacote": "^21.0.2", "parse-conflict-json": "^5.0.1", "proc-log": "^6.0.0", "proggy": "^4.0.0", "promise-all-reject-late": "^1.0.0", "promise-call-limit": "^3.0.1", "semver": "^7.3.7", "ssri": "^13.0.0", "treeverse": "^3.0.0", "walk-up-path": "^4.0.0" }, "bin": { "arborist": "bin/index.js" } }, "sha512-tzsb1R8mx0k0drlLDT/9ckEYaQHIaWnUti/ci2IaFoQqdqwfmYrc+90p1+QEZC/ocvqcxBep9P1xKw4FbAGofw=="],@@ -901,6 +911,8 @@"@macro-inc/infra-web-app/@pulumi/aws": ["@pulumi/[email protected]", "", { "dependencies": { "@pulumi/pulumi": "^3.142.0", "mime": "^2.0.0" } }, "sha512-mk3LhRJF6BdOq7VAWtrZpv+loLdaPxvbOVTESommiYXlSX87xXA8mytQCaeIXaivtpdj+xcBOJ8vz0A0Ktmw9g=="],+ "@macro-inc/infra-website/@pulumi/aws": ["@pulumi/[email protected]", "", { "dependencies": { "@pulumi/pulumi": "^3.142.0", "mime": "^2.0.0" } }, "sha512-mk3LhRJF6BdOq7VAWtrZpv+loLdaPxvbOVTESommiYXlSX87xXA8mytQCaeIXaivtpdj+xcBOJ8vz0A0Ktmw9g=="],+"@npmcli/git/ini": ["[email protected]", "", {}, "sha512-IBTdIkzZNOpqm7q3dRqJvMaldXjDHWkEDfrwGEQTs5eaQMWV+djAhR+wahyNNMAa+qpbDUhBMVt4ZKNwpPm7xQ=="],"@npmcli/git/which": ["[email protected]", "", { "dependencies": { "isexe": "^4.0.0" }, "bin": { "node-which": "bin/which.js" } }, "sha512-oGLe46MIrCRqX7ytPUf66EAYvdeMIZYn3WaocqqKZAxrBpkqHfL/qvTyJ/bTk5+AqHCjXmrv3CEWgy368zhRUg=="],diff --git a/infra/stacks/website/Pulumi.dev.yaml b/infra/stacks/website/Pulumi.dev.yamlnew file mode 100644index 0000000000..c04cf5f78c--- /dev/null+++ b/infra/stacks/website/Pulumi.dev.yaml@@ -0,0 +1,8 @@+config:+ aws:region: us-east-1+ aws-native:region: us-east-1+ website-infra:certArn: arn:aws:acm:us-east-1:569036502058:certificate/a75b1b07-534c-44e1-b59b-fa5f74fd8069+ website-infra:domain: macro.com+ website-infra:subdomain: dev+ website-infra:oidcBucketArn: "arn:aws:s3:::macro-oidc-dev"+ website-infra:oidcBucketWebsiteEndpoint: "macro-oidc-dev.s3.us-east-1.amazonaws.com"diff --git a/infra/stacks/website/Pulumi.prod.yaml b/infra/stacks/website/Pulumi.prod.yamlnew file mode 100644index 0000000000..5aa114e9d6--- /dev/null+++ b/infra/stacks/website/Pulumi.prod.yaml@@ -0,0 +1,8 @@+config:+ aws:region: us-east-1+ aws-native:region: us-east-1+ website-infra:certArn: arn:aws:acm:us-east-1:569036502058:certificate/50d917af-65f9-49d6-9505-39f9c01eeb22+ website-infra:domain: macro.com+ website-infra:subdomain: www+ website-infra:oidcBucketArn: "arn:aws:s3:::macro-oidc-prod"+ website-infra:oidcBucketWebsiteEndpoint: "macro-oidc-prod.s3.us-east-1.amazonaws.com"diff --git a/infra/stacks/website/Pulumi.yaml b/infra/stacks/website/Pulumi.yamlnew file mode 100644index 0000000000..2c45ca0bfc--- /dev/null+++ b/infra/stacks/website/Pulumi.yaml@@ -0,0 +1,7 @@+name: website-infra+description: Infra as Code for Website+runtime: nodejs+config:+ pulumi:tags:+ value:+ pulumi:template: aws-typescriptdiff --git a/infra/stacks/website/README.md b/infra/stacks/website/README.mdnew file mode 100644index 0000000000..b26948bb73--- /dev/null+++ b/infra/stacks/website/README.md@@ -0,0 +1,22 @@+# Website++Pulumi project `website-infra` (stacks `macro-inc/dev`, `macro-inc/prod`). It+publishes `apps/marketing/dist` to S3 and owns the macro.com CloudFront+distribution: the public site, `/app` routing to the web-app stack, `/.well-known`+OIDC, `resources*` to Ghost, and the `www`/`chat`/signed-in-root redirects in+`wwwRedirect/handler.js`.++Moved from `macro-inc/solid-site/infra`; project and stack names are unchanged,+so this program manages the existing resources.++## Deploy++`.github/workflows/deploy_website.yml` deploys dev on pushes to `main` that touch+the site or this stack, and prod from `release-production`. Run it manually from+the Actions tab to deploy `dev`, `prod`, or `both` (dev first; prod is cancelled+if dev fails). To preview locally:++```sh+cd apps/marketing && VITE_APP_BASE_URL=https://dev.macro.com bun run build+cd ../../infra/stacks/website && bun run preview:dev+```diff --git a/infra/stacks/website/index.ts b/infra/stacks/website/index.tsnew file mode 100644index 0000000000..ff3dcc0b97--- /dev/null+++ b/infra/stacks/website/index.ts@@ -0,0 +1,455 @@+import * as fs from 'fs';+import * as aws from '@pulumi/aws';+import * as command from '@pulumi/command';+import * as pulumi from '@pulumi/pulumi';+import { hasItems } from '../../packages/utils';++const config = new pulumi.Config();++const certArn = config.require('certArn');+const domain = config.require('domain');+const subdomain = config.require('subdomain');+const domainName = `${subdomain}.${domain}`;+const stack = pulumi.getStack();+const staticSiteDir = '../../../apps/marketing/dist';++// The sync never deletes, so an unbuilt dist would "deploy" nothing and still invalidate.+if (!hasItems(staticSiteDir)) {+ throw new Error(`Website build output is empty: ${staticSiteDir}`);+}++const tags = {+ project: 'website',+ environment: stack,+ owner: 'boswell',+};++const zone = aws.route53.getZoneOutput({ name: domain });++const webAclId = aws.wafv2+ .getWebAcl({+ name: 'macro-global-web-acl',+ scope: 'CLOUDFRONT',+ })+ .then((r) => r.arn);++const websiteAssets = new aws.s3.Bucket(`website-assets-${stack}`, {+ website: {+ indexDocument: 'index.html',+ errorDocument: 'index.html',+ },+ loggings:+ stack === 'prod'+ ? [+ {+ targetBucket: 'macro-logging-bucket',+ targetPrefix: `website-${stack}`,+ },+ ]+ : undefined,+});++const syncAssetsCommand = new command.local.Command(+ 'sync-assets-command',+ {+ create: pulumi.interpolate`aws s3 sync ${staticSiteDir} s3://${websiteAssets.bucket} --exclude "*.br" --exclude "*.gz" --exclude "*.mp4" --acl public-read`,+ triggers: [Date.now()],+ },+ { dependsOn: [websiteAssets], replaceOnChanges: ['*'] }+);++const syncVideoAssetsCommand = new command.local.Command(+ 'sync-video-assets-command',+ {+ create: pulumi.interpolate`aws s3 sync ${staticSiteDir} s3://${websiteAssets.bucket} --exclude "*" --include "*.mp4" --exclude "video/demo-local.mp4" --acl public-read --size-only --cache-control "public,max-age=86400"`,+ triggers: [Date.now()],+ },+ { dependsOn: [websiteAssets], replaceOnChanges: ['*'] }+);++const syncBrAssetsCommand = new command.local.Command(+ 'sync-br-assets-command',+ {+ create: pulumi.interpolate`aws s3 cp ${staticSiteDir} s3://${websiteAssets.bucket} --exclude "*" --include "*.br" --content-encoding br --metadata-directive REPLACE --acl public-read --recursive`,+ triggers: [Date.now()],+ },+ { dependsOn: [websiteAssets], replaceOnChanges: ['*'] }+);++const syncGzAssetsCommand = new command.local.Command(+ 'sync-gz-assets-command',+ {+ create: pulumi.interpolate`aws s3 cp ${staticSiteDir} s3://${websiteAssets.bucket} --exclude "*" --include "*.gz" --content-encoding gzip --metadata-directive REPLACE --acl public-read --recursive`,+ triggers: [Date.now()],+ },+ { dependsOn: [websiteAssets], replaceOnChanges: ['*'] }+);++// Prerendered route HTML (index.html, jobs/index.html, posts/*/index.html, …)+// must never be cached by browsers; CloudFront still caches and is+// invalidated on deploy.+const syncIndexHtmlCommand = new command.local.Command(+ 'sync-index-html-command',+ {+ create: pulumi.interpolate`aws s3 cp ${staticSiteDir} s3://${websiteAssets.bucket} --recursive --exclude "*" --include "*.html" --cache-control no-cache --acl public-read`,+ triggers: [Date.now()],+ },+ { dependsOn: [syncAssetsCommand], replaceOnChanges: ['*'] }+);++const macroWebAppStack = new pulumi.StackReference('macro-web-app', {+ name: `macro-inc/macro-web-app/${stack}`,+});++export const macroWebAppBucketArn: pulumi.Output<string> = macroWebAppStack+ .getOutput('macroWebAppBucketArn')+ .apply((value) => value as string);++export const macroWebAppBucketWebsiteEndpoint: pulumi.Output<string> =+ macroWebAppStack+ .getOutput('macroWebAppBucketWebsiteEndpoint')+ .apply((value) => value as string);++export const macroWebAppRouteLambdaId: pulumi.Output<string> = macroWebAppStack+ .getOutput('appRouteLambdaId')+ .apply((value: string) => value);++export const macroWebAppRouteDomain: pulumi.Output<string> = macroWebAppStack+ .getOutput('appRouteUrl')+ .apply((url: string) => new URL(url).hostname);++export const macroOidcBucketArn: string = config.require('oidcBucketArn');+export const macroOidcBucketWebsiteEndpoint: string = config.require(+ 'oidcBucketWebsiteEndpoint'+);++const wwwRedirectCode = fs+ .readFileSync('./wwwRedirect/handler.js', 'utf-8')+ .replace('__COOKIE_PREFIX__', stack === 'prod' ? '' : 'dev-');++const wwwRedirectFn = new aws.cloudfront.Function(+ `macro-wwww-redirect-fn-${stack}`,+ {+ runtime: 'cloudfront-js-2.0',+ code: wwwRedirectCode,+ }+);++const SHARED_ARRAY_RESPONSE_HEADERS_MAX_AGE_CACHE_CONTROL =+ '78ba335f-4e54-45a3-85d5-1d9933b1363d';+const SHARED_ARRAY_RESPONSE_HEADERS_NO_CACHE_CONTROL =+ 'c9d6f215-ca3d-4c29-8eb4-41ee30fb2129';+const CACHING_DISABLED = '4135ea2d-6df8-44a3-9df3-4b5a84be39ad';++const securityHeadersPolicy = new aws.cloudfront.ResponseHeadersPolicy(+ `security-headers-${stack}`,+ {+ securityHeadersConfig: {+ frameOptions: {+ frameOption: 'DENY',+ override: true,+ },+ contentSecurityPolicy: {+ contentSecurityPolicy: "frame-ancestors 'none'",+ override: true,+ },+ contentTypeOptions: {+ override: true,+ },+ strictTransportSecurity: {+ accessControlMaxAgeSec: 31536000,+ includeSubdomains: false,+ preload: false,+ override: true,+ },+ },+ }+);++const compressibleCachePolicy = new aws.cloudfront.CachePolicy(+ `cache-policy-${stack}`,+ {+ parametersInCacheKeyAndForwardedToOrigin: {+ enableAcceptEncodingGzip: true,+ enableAcceptEncodingBrotli: true,+ cookiesConfig: {+ cookieBehavior: 'none',+ },+ headersConfig: {+ headerBehavior: 'none',+ },+ queryStringsConfig: {+ queryStringBehavior: 'none',+ },+ },+ }+);++const ghostOriginId = `macro.ghost.io-${stack}`;++const cdn = new aws.cloudfront.Distribution(`cdn-${stack}`, {+ enabled: true,+ webAclId,+ tags,+ loggingConfig: {+ bucket: 'macro-cloudfront-logging.s3.amazonaws.com',+ includeCookies: false,+ prefix: `macro-website-${stack}`,+ },+ origins: [+ {+ originId: websiteAssets.arn,+ domainName: websiteAssets.websiteEndpoint,+ customOriginConfig: {+ originProtocolPolicy: 'http-only',+ httpPort: 80,+ httpsPort: 443,+ originSslProtocols: ['TLSv1.2'],+ },+ },+ {+ originId: macroWebAppBucketArn,+ domainName: macroWebAppBucketWebsiteEndpoint,+ customOriginConfig: {+ originProtocolPolicy: 'http-only',+ httpPort: 80,+ httpsPort: 443,+ originSslProtocols: ['TLSv1.2'],+ },+ },+ {+ originId: macroOidcBucketArn,+ domainName: macroOidcBucketWebsiteEndpoint,+ customOriginConfig: {+ originProtocolPolicy: 'http-only',+ httpPort: 80,+ httpsPort: 443,+ originSslProtocols: ['TLSv1.2'],+ },+ },+ {+ originId: ghostOriginId,+ domainName: 'macro-2.ghost.io',+ customHeaders: [+ {+ name: 'X-Forwarded-Host',+ value: stack === 'prod' ? domain : domainName,+ },+ {+ name: 'X-Forwarded-Proto',+ value: 'https',+ },+ ],+ customOriginConfig: {+ originProtocolPolicy: 'https-only',+ httpPort: 80,+ httpsPort: 443,+ originSslProtocols: ['TLSv1.2'],+ },+ },+ {+ originId: macroWebAppRouteLambdaId,+ domainName: macroWebAppRouteDomain,+ customOriginConfig: {+ originProtocolPolicy: 'https-only',+ httpPort: 80,+ httpsPort: 443,+ originSslProtocols: ['TLSv1.2'],+ },+ },+ ],+ defaultCacheBehavior: {+ targetOriginId: websiteAssets.arn,+ viewerProtocolPolicy: 'redirect-to-https',+ allowedMethods: ['GET', 'HEAD'],+ cachedMethods: ['GET', 'HEAD'],+ cachePolicyId: compressibleCachePolicy.id,+ responseHeadersPolicyId: securityHeadersPolicy.id,+ compress: true,+ functionAssociations: [+ {+ eventType: 'viewer-request',+ functionArn: wwwRedirectFn.arn,+ },+ ],+ },+ orderedCacheBehaviors: [+ {+ pathPattern: '/.well-known/*',+ targetOriginId: macroOidcBucketArn,+ cachePolicyId: CACHING_DISABLED,+ viewerProtocolPolicy: 'redirect-to-https',+ allowedMethods: ['GET', 'HEAD', 'OPTIONS'],+ cachedMethods: ['GET', 'HEAD', 'OPTIONS'],+ },+ {+ pathPattern: '/app/*@*',+ targetOriginId: macroWebAppRouteLambdaId,+ cachePolicyId: CACHING_DISABLED,+ responseHeadersPolicyId: SHARED_ARRAY_RESPONSE_HEADERS_NO_CACHE_CONTROL,+ viewerProtocolPolicy: 'redirect-to-https',+ allowedMethods: ['GET', 'HEAD', 'OPTIONS'],+ cachedMethods: ['GET', 'HEAD', 'OPTIONS'],+ },+ {+ pathPattern: '/app/*.*',+ responseHeadersPolicyId:+ SHARED_ARRAY_RESPONSE_HEADERS_MAX_AGE_CACHE_CONTROL,+ targetOriginId: macroWebAppBucketArn,+ viewerProtocolPolicy: 'redirect-to-https',+ allowedMethods: ['GET', 'HEAD', 'OPTIONS'],+ cachedMethods: ['GET', 'HEAD', 'OPTIONS'],+ cachePolicyId: compressibleCachePolicy.id,+ compress: true,+ },+ {+ pathPattern: '/app',+ targetOriginId: macroWebAppBucketArn,+ cachePolicyId: CACHING_DISABLED,+ responseHeadersPolicyId: SHARED_ARRAY_RESPONSE_HEADERS_NO_CACHE_CONTROL,+ viewerProtocolPolicy: 'redirect-to-https',+ allowedMethods: ['GET', 'HEAD', 'OPTIONS'],+ cachedMethods: ['GET', 'HEAD', 'OPTIONS'],+ },+ {+ pathPattern: '/app/*',+ targetOriginId: macroWebAppRouteLambdaId,+ cachePolicyId: CACHING_DISABLED,+ responseHeadersPolicyId: SHARED_ARRAY_RESPONSE_HEADERS_NO_CACHE_CONTROL,+ viewerProtocolPolicy: 'redirect-to-https',+ allowedMethods: ['GET', 'HEAD', 'OPTIONS'],+ cachedMethods: ['GET', 'HEAD', 'OPTIONS'],+ },+ {+ pathPattern: 'resources*',+ targetOriginId: ghostOriginId,+ viewerProtocolPolicy: 'redirect-to-https',+ allowedMethods: [+ 'GET',+ 'HEAD',+ 'OPTIONS',+ 'PUT',+ 'POST',+ 'PATCH',+ 'DELETE',+ ],+ cachedMethods: ['GET', 'HEAD'],+ forwardedValues: {+ queryString: true,+ cookies: {+ forward: 'all',+ },+ headers: ['Origin', 'Referer', 'User-Agent'],+ },+ },+ ],+ restrictions: {+ geoRestriction: {+ restrictionType: 'none',+ },+ },+ priceClass: stack === 'prod' ? 'PriceClass_All' : 'PriceClass_100',+ aliases:+ stack === 'prod'+ ? [domainName, domain, `chat.${domain}`]+ : stack === 'dev'+ ? [domainName, `chat-${domainName}`]+ : [domainName],+ viewerCertificate: {+ cloudfrontDefaultCertificate: false,+ acmCertificateArn: certArn,+ sslSupportMethod: 'sni-only',+ minimumProtocolVersion: 'TLSv1.2_2021',+ },+});++new aws.route53.Record(domainName, {+ name: subdomain,+ zoneId: zone.zoneId,+ type: 'A',+ aliases: [+ {+ name: cdn.domainName,+ zoneId: cdn.hostedZoneId,+ evaluateTargetHealth: true,+ },+ ],+});++if (stack === 'prod') {+ new aws.route53.Record(domain, {+ name: domain,+ zoneId: zone.zoneId,+ type: 'A',+ aliases: [+ {+ name: cdn.domainName,+ zoneId: cdn.hostedZoneId,+ evaluateTargetHealth: true,+ },+ ],+ });++ new aws.route53.Record('chat', {+ name: 'chat',+ zoneId: zone.zoneId,+ type: 'A',+ aliases: [+ {+ name: cdn.domainName,+ zoneId: cdn.hostedZoneId,+ evaluateTargetHealth: true,+ },+ ],+ });+}++if (stack === 'dev') {+ new aws.route53.Record('edge-cname', {+ name: 'edge',+ zoneId: zone.zoneId,+ type: 'CNAME',+ records: ['macro-site-solidify.pages.dev'],+ ttl: 300,+ });++ new aws.route53.Record('chat-dev', {+ name: 'chat-dev',+ zoneId: zone.zoneId,+ type: 'A',+ aliases: [+ {+ name: cdn.domainName,+ zoneId: cdn.hostedZoneId,+ evaluateTargetHealth: true,+ },+ ],+ });+}++const invalidateCache = new command.local.Command(+ 'invalidate-cache',+ {+ create: pulumi.interpolate`aws cloudfront create-invalidation --distribution-id ${cdn.id} --paths "/*"`,+ triggers: [Date.now()],+ },+ {+ dependsOn: [+ cdn,+ websiteAssets,+ syncAssetsCommand,+ syncVideoAssetsCommand,+ syncBrAssetsCommand,+ syncGzAssetsCommand,+ syncIndexHtmlCommand,+ ],+ replaceOnChanges: ['*'],+ }+);++export const cacheInvalidationResult = invalidateCache.stdout;+export const websiteAssetsEndpoint = websiteAssets.websiteEndpoint;+export const websiteAssetsDomain = websiteAssets.bucketDomainName;+export const cdnId = cdn.id;+export const cdnURL = pulumi.interpolate`https://${cdn.domainName}`;+export const domainURL = `https://${domainName}`;diff --git a/infra/stacks/website/package.json b/infra/stacks/website/package.jsonnew file mode 100644index 0000000000..f13e2e2b0a--- /dev/null+++ b/infra/stacks/website/package.json@@ -0,0 +1,14 @@+{+ "name": "@macro-inc/infra-website",+ "packageManager": "bun",+ "private": true,+ "scripts": {+ "preview:dev": "pulumi preview --stack macro-inc/dev",+ "preview:prod": "pulumi preview --stack macro-inc/prod"+ },+ "dependencies": {+ "@pulumi/aws": "^6.83.0",+ "@pulumi/command": "^1.1.0",+ "@pulumi/pulumi": "^3.181.0"+ }+}diff --git a/infra/stacks/website/tsconfig.json b/infra/stacks/website/tsconfig.jsonnew file mode 100644index 0000000000..c8401c9aad--- /dev/null+++ b/infra/stacks/website/tsconfig.json@@ -0,0 +1,18 @@+{+ "compilerOptions": {+ "strict": true,+ "outDir": "bin",+ "target": "es2020",+ "module": "commonjs",+ "moduleResolution": "node",+ "sourceMap": true,+ "experimentalDecorators": true,+ "pretty": true,+ "noFallthroughCasesInSwitch": true,+ "noImplicitReturns": true,+ "forceConsistentCasingInFileNames": true+ },+ "files": [+ "index.ts"+ ]+}diff --git a/infra/stacks/website/wwwRedirect/handler.js b/infra/stacks/website/wwwRedirect/handler.jsnew file mode 100644index 0000000000..09a3a794ff--- /dev/null+++ b/infra/stacks/website/wwwRedirect/handler.js@@ -0,0 +1,90 @@+function handler(event) {+ var request = event.request;+ var headers = request.headers;+ var host = '';+ if (headers.host && headers.host.value) {+ host = headers.host.value;+ }++ if (host.startsWith('chat')) {+ // remove "chat." or "chat-"+ let newHost = host.slice(5);++ // start with original uri+ let redirectUrl = 'https://' + newHost + '/app/?chat=true';++ return {+ statusCode: 302,+ statusDescription: 'Redirecting to chat',+ headers: {+ location: { value: redirectUrl },+ },+ };+ }++ var cookies = request.cookies;++ // Check for auth tokens (HttpOnly cookies are accessible in CloudFront Functions)+ var hasRefreshToken = cookies['__COOKIE_PREFIX__macro-refresh-token'];++ if ((!request.uri || request.uri === '/') && hasRefreshToken) {+ return {+ statusCode: 302,+ statusDescription: 'Redirecting to app',+ headers: {+ location: { value: '/app' },+ },+ };+ }++ // Check if the Host header starts with "www."+ if (host.slice(0, 4) === 'www.') {+ var nakedDomain = host.slice(4); // remove "www."+ var redirectUrl = 'https://' + nakedDomain + request.uri;++ // Process querystring using the provided method+ var qs = [];+ for (var key in request.querystring) {+ if (request.querystring[key].multiValue) {+ request.querystring[key].multiValue.forEach((mv) => {+ qs.push(key + '=' + mv.value);+ });+ } else {+ qs.push(key + '=' + request.querystring[key].value);+ }+ }++ if (qs.length > 0) {+ redirectUrl += '?' + qs.sort().join('&');+ }++ return {+ statusCode: 302,+ statusDescription: 'Found',+ headers: {+ location: { value: redirectUrl },+ },+ };+ }++ // Serve prerendered directory indexes without S3's add-trailing-slash 302.+ // The site is prerendered to `<route>/index.html` and served from the S3+ // *website* endpoint, which 302-redirects an extensionless path (e.g.+ // `/posts/linear-alternative`) to its trailing-slash form before serving the+ // index document. Crawlers, LLM fetchers, and link-preview bots that don't+ // follow redirects then see the redirect stub instead of the page — and our+ // canonical/og:url/sitemap all advertise the no-slash URL. Rewriting the URI+ // to the index.html object here makes S3 return the page directly with a 200,+ // no redirect. Runs only on the default (website-assets) behavior; `/app/*`,+ // `/.well-known/*`, and `resources*` use other origins without this function.+ var uri = request.uri;+ var lastSegment = uri.slice(uri.lastIndexOf('/') + 1);+ if (uri.endsWith('/')) {+ request.uri = uri + 'index.html';+ } else if (lastSegment.indexOf('.') === -1) {+ request.uri = uri + '/index.html';+ }++ // If not "www.", continue as normal+ return request;+}diff --git a/tooling/xtask/crates/xtask_workflows/src/workflows.rs b/tooling/xtask/crates/xtask_workflows/src/workflows.rsindex 99de29f4d6..caf9710bb3 100644--- a/tooling/xtask/crates/xtask_workflows/src/workflows.rs+++ b/tooling/xtask/crates/xtask_workflows/src/workflows.rs@@ -33,6 +33,7 @@ mod deploy_on_push;mod deploy_preview;mod deploy_sync_service;mod deploy_web_app;+mod deploy_website;mod docs_check;mod ensure_daytona_snapshot;mod ios_preview;@@ -244,6 +245,11 @@ const WORKFLOWS: &[WorkflowFile] = &[file_name: "deploy_web_app.yml",render_yaml: || render_patched(deploy_web_app::deploy_web_app, deploy_web_app::patch),},+ WorkflowFile {+ slug: "deploy_website",+ file_name: "deploy_website.yml",+ render_yaml: || render_patched(deploy_website::deploy_website, deploy_website::patch),+ },WorkflowFile {slug: "ensure_daytona_snapshot",file_name: "ensure_daytona_snapshot.yml",diff --git a/tooling/xtask/crates/xtask_workflows/src/workflows/deploy_website.rs b/tooling/xtask/crates/xtask_workflows/src/workflows/deploy_website.rsnew file mode 100644index 0000000000..1477965c16--- /dev/null+++ b/tooling/xtask/crates/xtask_workflows/src/workflows/deploy_website.rs@@ -0,0 +1,195 @@+//! `Deploy Website` — builds the public site (`apps/marketing`) and publishes+//! it through the `website-infra` pulumi stack (`infra/stacks/website`), which+//! also owns the macro.com CloudFront distribution that fronts `/app`.+//! Generated into `deploy_website.yml`.+//!+//! Push to `main` (path-gated) auto-deploys `dev`; prod deploys come through+//! `release-production`, which calls this workflow with `environment: prod` —+//! the same split [`crate::workflows::deploy_ai_editing_worker`] uses. Manual+//! `workflow_dispatch` picks `dev`, `prod`, or `both` (dev, then prod).+//!+//! Replaces the `deploy-dev.yml` / `deploy-prod.yml` workflows in the old+//! `macro-inc/solid-site` repository.++use anyhow::Result;+use gh_workflow::{+ Concurrency, Env, Event, Expression, Job, Push, Run, Step, Strategy, Use, Workflow,+ WorkflowCall, WorkflowDispatch,+};++use crate::workflows::{runners, steps, vars};++#[cfg(test)]+mod test;++/// The environments to deploy, as a JSON list. On push `inputs.environment` is+/// empty, so push runs deploy `dev`; `both` deploys dev before prod.+const ENVIRONMENTS: &str = r#"${{ fromJSON(inputs.environment == 'both' && '["dev","prod"]' || format('["{0}"]', inputs.environment || 'dev')) }}"#;++/// The environment of the current matrix leg.+const ENVIRONMENT: &str = "${{ matrix.environment }}";++/// Build the workflow. The `workflow_dispatch`/`workflow_call` input blocks+/// are filled in by [`patch`].+pub fn deploy_website() -> Workflow {+ Workflow::new("Deploy Website")+ .on(Event::default()+ .push(+ Push::default()+ .add_branch("main")+ .add_path(xtask_paths::repo_glob!(+ ".github/workflows/deploy_website.yml"+ ))+ .add_path(xtask_paths::repo_glob!("bun.lock"))+ .add_path(xtask_paths::repo_glob!("apps/marketing/**"))+ .add_path(xtask_paths::repo_glob!("infra/stacks/website/**")),+ )+ .workflow_dispatch(WorkflowDispatch::default())+ .workflow_call(WorkflowCall::default()))+ .add_job("build-deploy", build_deploy())+}++/// Input blocks `gh_workflow` cannot express: a `choice` dispatch input, and the+/// `workflow_call` contract `release-production` deploys prod through.+pub fn patch(root: &mut serde_yaml::Value) -> Result<()> {+ let on = root+ .get_mut("on")+ .and_then(serde_yaml::Value::as_mapping_mut)+ .ok_or_else(|| anyhow::anyhow!("rendered workflow has no `on` mapping"))?;+ on.insert(+ "workflow_call".into(),+ crate::workflows::yaml_fragment(indoc::indoc! {r#"+ inputs:+ environment:+ required: true+ type: string+ description: The environment to deploy to. e.g. (dev, prod, both)+ secrets:+ AWS_ACCESS_KEY:+ required: true+ AWS_SECRET_ACCESS_KEY:+ required: true+ PULUMI_ACCESS_TOKEN:+ required: true+ "#})?,+ );+ on.insert(+ "workflow_dispatch".into(),+ crate::workflows::yaml_fragment(indoc::indoc! {r#"+ inputs:+ environment:+ required: true+ type: choice+ default: 'dev'+ options:+ - dev+ - prod+ - both+ description: The environment to deploy to (both deploys dev, then prod)+ "#})?,+ );+ Ok(())+}++fn build_deploy() -> Job {+ Job::default()+ .name("Build and Deploy Website")+ .runs_on(runners::Runner::Mid.with_cache_tag(vars::WEB_CI_CACHE_TAG))+ // One leg at a time, in list order: with fail-fast, a failed dev deploy+ // cancels the queued prod leg.+ .strategy(Strategy {+ matrix: Some(serde_json::json!({ "environment": ENVIRONMENTS })),+ fail_fast: Some(true),+ max_parallel: Some(1),+ })+ // Per environment, so a `both` run still serializes with push and+ // release deploys of the same stack. Literal prefix rather than+ // `github.workflow`, which expands to the *caller's* name for+ // workflow_call runs. Never cancel in-progress — that could leave the+ // stack half-applied.+ .concurrency(+ Concurrency::new(Expression::new(format!("deploy-website-{ENVIRONMENT}")))+ .cancel_in_progress(false),+ )+ .add_env(("CI", "true"))+ .add_step(checkout())+ .add_step(verify_lfs_videos())+ .add_step(steps::mount_web_cache_volume(false))+ .add_step(steps::setup_nix())+ // The build prerenders every page and checks homepage hydration in Chromium.+ .add_step(steps::setup_reqs_web("Setup", true))+ .add_step(build())+ .add_step(install_infra_dependencies())+ .add_step(configure_aws_credentials())+ .add_step(pulumi_up())+ .add_step(steps::teardown_nix())+}++fn checkout() -> Step<Use> {+ Step::new("Checkout Repo")+ .uses(+ "actions",+ "checkout",+ "df4cb1c069e1874edd31b4311f1884172cec0e10",+ ) // v6+ .add_with(("lfs", true))+}++/// Without LFS content the site would publish pointer files as its videos.+fn verify_lfs_videos() -> Step<Run> {+ Step::new("Verify Git LFS videos were downloaded")+ .run(indoc::indoc! {r#"+ if grep -RIl --include='*.mp4' 'version https://git-lfs.github.com/spec/v1' public src; then+ echo "Found Git LFS pointer files instead of real videos."+ exit 1+ fi+ "#})+ .working_directory(xtask_paths::repo_dir!("apps/marketing"))+}++fn build() -> Step<Run> {+ Step::new("Build")+ .run("bun run build")+ .working_directory(xtask_paths::repo_dir!("apps/marketing"))+ // Canonical URLs, sitemap and robots are baked in at build time.+ .add_env(Env::new(+ "VITE_APP_BASE_URL",+ "${{ matrix.environment == 'prod' && 'https://macro.com' || 'https://dev.macro.com' }}",+ ))+ .add_env(Env::new(+ "VITE_GOOGLE_SSO_URL",+ "${{ matrix.environment == 'prod' && 'https://gateway.macro.com/auth/login/sso?idp_name=google_gmail' || 'https://dev-gateway.macro.com/auth/login/sso?idp_name=google_gmail' }}",+ ))+}++fn install_infra_dependencies() -> Step<Run> {+ Step::new("Install infra dependencies")+ .run("bun install")+ .working_directory(xtask_paths::repo_dir!("infra"))+}++fn configure_aws_credentials() -> Step<Use> {+ Step::new("Configure AWS Credentials")+ .uses(+ "aws-actions",+ "configure-aws-credentials",+ "e7f100cf4c008499ea8adda475de1042d6975c7b",+ ) // v5+ .add_with(("aws-access-key-id", vars::AWS_ACCESS_KEY))+ .add_with(("aws-secret-access-key", vars::AWS_SECRET_ACCESS_KEY))+ .add_with(("aws-region", "us-east-1"))+}++/// The stack's own `invalidate-cache` command invalidates `/*` after the sync.+fn pulumi_up() -> Step<Use> {+ Step::new("Deploy with Pulumi")+ .uses(+ "pulumi",+ "actions",+ "8e5e406f4007fca908480587cb9893c07090f58d",+ ) // v6+ .add_with(("command", "up"))+ .add_with(("stack-name", format!("macro-inc/{ENVIRONMENT}")))+ .add_with(("work-dir", "./infra/stacks/website"))+ .add_env(Env::new("PULUMI_ACCESS_TOKEN", vars::PULUMI_ACCESS_TOKEN))+}diff --git a/tooling/xtask/crates/xtask_workflows/src/workflows/deploy_website/test.rs b/tooling/xtask/crates/xtask_workflows/src/workflows/deploy_website/test.rsnew file mode 100644index 0000000000..37b95046d9--- /dev/null+++ b/tooling/xtask/crates/xtask_workflows/src/workflows/deploy_website/test.rs@@ -0,0 +1,29 @@+use super::*;++#[test]+fn deploy_publishes_the_marketing_build_through_the_website_stack() {+ let yaml = crate::workflows::render_patched(deploy_website, patch).expect("workflow yaml");+ let check = |needle: &str| assert!(yaml.contains(needle), "missing `{needle}`:\n{yaml}");+ [+ "lfs: 'true'",+ "working-directory: apps/marketing",+ "run: bun run build",+ "'https://macro.com'",+ "work-dir: ./infra/stacks/website",+ "stack-name: macro-inc/${{ matrix.environment }}",+ // Manual dispatch can target dev, prod, or both, one leg at a time.+ "- both",+ r#"inputs.environment == 'both' && '["dev","prod"]'"#,+ "max-parallel: 1",+ "group: deploy-website-${{ matrix.environment }}",+ ]+ .into_iter()+ .for_each(check);++ let build = yaml.find("run: bun run build").expect("build step");+ let deploy = yaml.find("command: up").expect("pulumi up");+ assert!(+ build < deploy,+ "the site must be built before pulumi syncs it"+ );+}