belt 0.6.10 → 0.6.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: b3fc587d6980e4a754477a032f264e7f36de83898b451b0134741e7ccbe46706
4
- data.tar.gz: 34797d0fa6c1e05d3873a57ec3d2219c9c9fcea4cc13c443ed17c5d1b509b550
3
+ metadata.gz: 5c14e759e93bb681bd3a6731e88b373a27fe7b31a16a2da03de2e481d1e45be5
4
+ data.tar.gz: a6e7fbbc0c17f3f5fe25b79683d95831468fe6b24e2869b86ea82c7d27b5ce03
5
5
  SHA512:
6
- metadata.gz: 52ef8567694bcae88ca060b71f04e8ba4deb9766c1e99971bdb52ba3bcbdc66f9e54abc7fc888681bd37d90b2d7ada71de602484929c8dadfa97a58a3456bf15
7
- data.tar.gz: 6ff546e948f0dd67b25d9386e7db16c10a7b4fb7387594c608dfb898d567ee947cf0c50e6999275fe8a170b15944d77a45a40f6a56d7f763a8235b41b41a3a7f
6
+ metadata.gz: '039b10e91eeb5c05b14f04e3f1cf1869f184ad91639363d2c03f66d6c0a40da305da07052789a030c805f8070e680ec5652bafed0fcd755755a24c16a2086b2b'
7
+ data.tar.gz: ffc6d215e223fee7179fe5918f31683de8a90ff0376a0495a0f2041d1f83a12cc6aff5756c62aab6a89b21d0ba8b6a91d083d6e4d0e7f58d4807d4d57a7e436b
data/CHANGELOG.md CHANGED
@@ -1,5 +1,61 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.6.12
4
+
5
+ ### Security
6
+
7
+ - **An unsigned `Authorization: Bearer` token is no longer believed.** On a route
8
+ without an API Gateway authorizer, `Belt::Authentication::Claims.from_event`
9
+ base64-decoded the header token and returned its payload as the caller's
10
+ claims with no signature check, so a made-up token naming any `sub` and the
11
+ admin group made `current_user`, `cognito_admin?` and `authenticate_user!`
12
+ treat the caller as that user (and wrote the forged email, name and role to
13
+ their row). Header tokens are now verified by
14
+ `Belt::Authentication::TokenVerifier`: RS256 only, key by `kid` from the pool's
15
+ JWKS (cached per container), and `exp`, `iss`, `token_use == 'id'` and `aud`
16
+ all required. A token that can't be verified, including when no pool or
17
+ client id is configured, yields no claims. Routes behind `auth: :cognito`
18
+ were not affected and are unchanged. (Fizzy #2002)
19
+
20
+ ### Added
21
+
22
+ - `config.authentication.client_ids` (default: `COGNITO_CLIENT_ID`,
23
+ comma-separated): the app client ids a header token may be issued for.
24
+
25
+ ### Changed
26
+
27
+ - Apps that read `current_user` on a route with no authorizer must set
28
+ `COGNITO_USER_POOL_ID` and `COGNITO_CLIENT_ID` on the Lambda, or those
29
+ requests become anonymous. See UPGRADING.md.
30
+ - `Claims.decode` is unchanged (payload parsing, no signature check) but is no
31
+ longer used to establish identity.
32
+
33
+ ## 0.6.11
34
+
35
+ ### Added
36
+
37
+ - **Frontends answer HTTP 404 for an address that doesn't exist.** A single-page
38
+ app on S3 + CloudFront answered every path with `index.html` and 200, so
39
+ crawlers and agents couldn't tell a missing page from a real one. For a
40
+ frontend with `src/seo.js`, the prerender step now writes `404.html` (the app's
41
+ own "not found" route, `noindex`) and `.belt-routes.json`: the public pages plus
42
+ the app's routes, read from its `<Route path="/...">` declarations and
43
+ `seo.privatePaths`, so there is no second route list to keep in sync.
44
+ `belt deploy frontend` publishes the routes to a CloudFront KeyValueStore, and
45
+ a router function on the distribution serves pages from their prerendered
46
+ files, app routes from `index.html`, and anything else from `404.html` with
47
+ status 404. It fails open: before routes are published, or if the store can't
48
+ be read, every path behaves as before. Generated `frontend.tf` includes the
49
+ store and function; existing apps opt in via UPGRADING.md. (Fizzy #1985)
50
+ - A frontend whose own build prerenders its pages gets real 404s too: belt
51
+ leaves the pages alone and adds the app routes (and `404.html` if the build
52
+ wrote none). The build can write `.belt-routes.json` with `pages` and
53
+ `objects` to say where its pages are stored.
54
+ - `llms-full.txt` is uploaded `no-cache`, like `llms.txt`.
55
+ - **`belt frontend router`** writes or refreshes
56
+ `infrastructure/modules/app/belt_frontend_router.js`.
57
+ - The React template has a `NotFound` page on `<Route path="*">`.
58
+
3
59
  ## 0.6.10
4
60
 
5
61
  ### Changed
@@ -11,13 +11,13 @@ module Belt
11
11
  #
12
12
  # 1. API Gateway Cognito authorizer — claims arrive pre-verified under
13
13
  # requestContext.authorizer.claims, with every value flattened to a String.
14
- # 2. A raw `Authorization: Bearer <id token>` header — the Lambda decodes it.
14
+ # 2. A raw `Authorization: Bearer <id token>` header, on a route with no
15
+ # authorizer — nothing has checked it, so TokenVerifier does: signature
16
+ # against the pool's JWKS, then expiry, issuer, token use and audience.
15
17
  #
16
- # Case 2 is signature-unverified by design: when a Cognito authorizer is attached,
17
- # the gateway has already checked the signature and an unsigned token never reaches
18
- # us. What we can still check cheaply is checked (structure, expiry, issuer, token
19
- # use), which is what stops an expired or foreign token from being waved through on
20
- # routes that read the header directly.
18
+ # A header token that can't be verified — forged, expired, foreign, or the app has
19
+ # no pool configured to verify against — is no identity at all. Unverified claims
20
+ # are never returned from #from_event.
21
21
  module Claims
22
22
  # Cognito sends `cognito:groups` as a JSON array in the raw token, but API
23
23
  # Gateway flattens it to a string — "[admins, members]" or "admins,members".
@@ -27,19 +27,19 @@ module Belt
27
27
 
28
28
  class << self
29
29
  # Claims for this request, or nil if there is no usable Cognito identity.
30
- def from_event(event, issuer: nil)
30
+ def from_event(event, issuer: nil, client_ids: nil)
31
31
  authorizer = event.dig('requestContext', 'authorizer', 'claims')
32
32
  return authorizer if authorizer
33
33
 
34
34
  token = bearer_token(event)
35
35
  return nil unless token
36
36
 
37
- decode(token, issuer: issuer)
37
+ TokenVerifier.verify(token, issuer: issuer, client_ids: client_ids)
38
38
  end
39
39
 
40
40
  # The raw Bearer credential, whatever it is. Callers that only want Cognito
41
- # tokens rely on #decode rejecting anything that isn't one — an app's own API
42
- # key scheme can share the header without special-casing here.
41
+ # tokens rely on TokenVerifier rejecting anything that isn't one — an app's own
42
+ # API key scheme can share the header without special-casing here.
43
43
  def bearer_token(event)
44
44
  header = authorization_header(event)
45
45
  return nil unless header&.start_with?('Bearer ')
@@ -53,9 +53,13 @@ module Belt
53
53
  headers['Authorization'] || headers['authorization']
54
54
  end
55
55
 
56
- # Decode a Cognito ID token's payload, rejecting it unless it is one.
57
- # Returns nil rather than raising: a bad token means "no identity", and every
58
- # caller here is deciding whether an identity exists.
56
+ # Parse a Cognito ID token's payload, rejecting it unless it is shaped like one.
57
+ #
58
+ # NOT an identity: the signature is not checked, so anyone can write a token
59
+ # that decodes. Use it only on a token something else has already verified.
60
+ # #from_event does not call this — it goes through TokenVerifier.
61
+ #
62
+ # Returns nil rather than raising for a token that doesn't parse.
59
63
  def decode(token, issuer: nil)
60
64
  payload = payload_segment(token)
61
65
  return nil unless payload
@@ -22,9 +22,12 @@ module Belt
22
22
  @user_class = nil
23
23
  @admin_groups = nil
24
24
  @issuer = nil
25
+ @client_ids = nil
25
26
  end
26
27
 
27
- attr_writer :admin_groups, :issuer
28
+ attr_writer :admin_groups, :issuer, :client_ids
29
+
30
+ alias client_id= client_ids=
28
31
 
29
32
  # Accepts a class or a name. Stored as a name and resolved on demand so the
30
33
  # setting can be declared before the model file is loaded.
@@ -52,9 +55,10 @@ module Belt
52
55
  configured.empty? ? DEFAULT_ADMIN_GROUPS : configured
53
56
  end
54
57
 
55
- # Expected `iss` claim. Derived from the Cognito env vars Belt's Terraform module
56
- # already exports, so apps don't restate it. Nil disables the issuer check —
57
- # which is the right behaviour locally and in tests, where there is no pool.
58
+ # Expected `iss` claim, and where the pool's signing keys are fetched from.
59
+ # Derived from COGNITO_USER_POOL_ID. Nil means there is no pool to verify a
60
+ # Bearer header token against, so such a token is never an identity. Routes
61
+ # behind an API Gateway authorizer don't need it.
58
62
  def issuer
59
63
  return @issuer if @issuer
60
64
 
@@ -64,6 +68,15 @@ module Belt
64
68
  region = ENV['COGNITO_REGION'] || ENV['AWS_REGION'] || 'us-east-1'
65
69
  "https://cognito-idp.#{region}.amazonaws.com/#{pool_id}"
66
70
  end
71
+
72
+ # App client ids a Bearer header token may be issued for (its `aud` claim).
73
+ # From COGNITO_CLIENT_ID, comma-separated when the pool has several clients
74
+ # (web and mobile, say). Empty means header tokens are never an identity.
75
+ def client_ids
76
+ return Array(@client_ids).map(&:to_s) if @client_ids
77
+
78
+ ENV.fetch('COGNITO_CLIENT_ID', '').to_s.split(',').map(&:strip).reject(&:empty?)
79
+ end
67
80
  end
68
81
  end
69
82
  end
@@ -31,12 +31,15 @@ module Belt
31
31
  Claims.bearer_token(event)
32
32
  end
33
33
 
34
- # The Cognito claims on this request, or nil if there aren't any. Memoized
35
- # including the nil, so a request decodes at most once.
34
+ # The Cognito claims on this request, or nil if there aren't any. Always
35
+ # verified: by the API Gateway authorizer, or — for a Bearer header on a route
36
+ # without one — by TokenVerifier against the pool's keys. Memoized including the
37
+ # nil, so a request verifies at most once.
36
38
  def cognito_claims
37
39
  return @cognito_claims if defined?(@cognito_claims)
38
40
 
39
- @cognito_claims = Claims.from_event(event, issuer: belt_authentication_config.issuer)
41
+ config = belt_authentication_config
42
+ @cognito_claims = Claims.from_event(event, issuer: config.issuer, client_ids: config.client_ids)
40
43
  end
41
44
 
42
45
  def cognito_sub
@@ -0,0 +1,136 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'base64'
4
+ require 'json'
5
+ require 'net/http'
6
+ require 'openssl'
7
+ require 'uri'
8
+
9
+ module Belt
10
+ module Authentication
11
+ # Verifies a Cognito ID token taken from an `Authorization: Bearer` header.
12
+ #
13
+ # A route with an API Gateway authorizer never needs this: the gateway checked the
14
+ # token and handed over the claims. A route without one has nothing in front of it,
15
+ # so a token there counts only if it was signed by the app's own pool, for one of
16
+ # the app's own clients. Everything is required — signature (RS256, key looked up
17
+ # by `kid` in the pool's JWKS), `exp`, `iss`, `token_use == 'id'` and `aud`.
18
+ #
19
+ # The key set is fetched once per Lambda container. An unknown `kid` triggers a
20
+ # refetch (Cognito rotates rarely), but at most once per REFETCH_INTERVAL, so a
21
+ # caller inventing key ids cannot make every request pay for an outbound call.
22
+ module TokenVerifier
23
+ ALGORITHM = 'RS256'
24
+ JWKS_TIMEOUT = 2
25
+ # Seconds before an unknown `kid` may trigger another fetch of a key set we hold.
26
+ REFETCH_INTERVAL = 60
27
+ # Seconds before retrying a fetch that failed outright.
28
+ RETRY_INTERVAL = 5
29
+
30
+ @key_sets = {}
31
+ @mutex = Mutex.new
32
+
33
+ class << self
34
+ # The verified claims, or nil. Never raises: a token that can't be verified
35
+ # means "no identity". Nil too when the issuer or client ids are unknown —
36
+ # without them there is nothing to verify against.
37
+ def verify(token, issuer:, client_ids:)
38
+ audiences = Array(client_ids).map(&:to_s).reject(&:empty?)
39
+ return nil if token.to_s.empty? || issuer.to_s.empty? || audiences.empty?
40
+
41
+ segments = token.to_s.split('.')
42
+ return nil unless segments.length == 3
43
+ return nil unless signed_by_pool?(segments, issuer)
44
+
45
+ claims = JSON.parse(decode_segment(segments[1]))
46
+ valid_claims?(claims, issuer, audiences) ? claims : nil
47
+ rescue StandardError
48
+ nil
49
+ end
50
+
51
+ # Test seam: supply a pool's keys ({ kid => OpenSSL::PKey::RSA }) so nothing
52
+ # is fetched.
53
+ def store_keys(issuer, keys)
54
+ @mutex.synchronize { @key_sets[issuer] = { keys: keys, fetch_after: monotonic_now + REFETCH_INTERVAL } }
55
+ end
56
+
57
+ def reset!
58
+ @mutex.synchronize { @key_sets = {} }
59
+ end
60
+
61
+ private
62
+
63
+ def signed_by_pool?(segments, issuer)
64
+ header = JSON.parse(decode_segment(segments[0]))
65
+ return false unless header.is_a?(Hash) && header['alg'] == ALGORITHM
66
+
67
+ key = key_for(header['kid'], issuer)
68
+ return false unless key
69
+
70
+ key.verify('SHA256', decode_segment(segments[2]), "#{segments[0]}.#{segments[1]}")
71
+ end
72
+
73
+ def valid_claims?(claims, issuer, audiences)
74
+ return false unless claims.is_a?(Hash)
75
+ return false unless claims['exp'].is_a?(Numeric) && claims['exp'] > Time.now.to_i
76
+ return false unless claims['iss'] == issuer
77
+ return false unless claims['token_use'] == 'id'
78
+
79
+ audiences.intersect?(Array(claims['aud']).map(&:to_s))
80
+ end
81
+
82
+ def key_for(kid, issuer)
83
+ return nil if kid.to_s.empty?
84
+
85
+ @mutex.synchronize do
86
+ set = @key_sets[issuer]
87
+ set = @key_sets[issuer] = fetch_key_set(issuer) if refetch?(set, kid)
88
+ set[:keys][kid]
89
+ end
90
+ end
91
+
92
+ def refetch?(set, kid)
93
+ return true if set.nil?
94
+
95
+ !set[:keys].key?(kid) && monotonic_now >= set[:fetch_after]
96
+ end
97
+
98
+ def fetch_key_set(issuer)
99
+ keys = fetch_keys(issuer)
100
+ { keys: keys || {}, fetch_after: monotonic_now + (keys ? REFETCH_INTERVAL : RETRY_INTERVAL) }
101
+ end
102
+
103
+ # The JWKS URL comes from the configured issuer, never from the token.
104
+ # Returns nil when the key set could not be fetched.
105
+ def fetch_keys(issuer)
106
+ uri = URI("#{issuer}/.well-known/jwks.json")
107
+ options = { use_ssl: uri.scheme == 'https', open_timeout: JWKS_TIMEOUT, read_timeout: JWKS_TIMEOUT }
108
+ response = Net::HTTP.start(uri.host, uri.port, **options) { |http| http.get(uri.request_uri) }
109
+ return nil unless response.is_a?(Net::HTTPSuccess)
110
+
111
+ JSON.parse(response.body).fetch('keys', []).each_with_object({}) do |jwk, keys|
112
+ keys[jwk['kid']] = rsa_key(jwk) if jwk['kty'] == 'RSA'
113
+ end
114
+ rescue StandardError
115
+ nil
116
+ end
117
+
118
+ # OpenSSL 3 keys are immutable, so build the PKCS#1 DER instead of setting n/e.
119
+ def rsa_key(jwk)
120
+ modulus = OpenSSL::BN.new(decode_segment(jwk['n']), 2)
121
+ exponent = OpenSSL::BN.new(decode_segment(jwk['e']), 2)
122
+ der = OpenSSL::ASN1::Sequence([OpenSSL::ASN1::Integer(modulus), OpenSSL::ASN1::Integer(exponent)]).to_der
123
+ OpenSSL::PKey::RSA.new(der)
124
+ end
125
+
126
+ def decode_segment(segment)
127
+ Base64.urlsafe_decode64(segment + ('=' * ((4 - (segment.length % 4)) % 4)))
128
+ end
129
+
130
+ def monotonic_now
131
+ Process.clock_gettime(Process::CLOCK_MONOTONIC)
132
+ end
133
+ end
134
+ end
135
+ end
136
+ end
@@ -3,6 +3,7 @@
3
3
  require_relative 'errors'
4
4
  require_relative 'configuration'
5
5
  require_relative 'authentication/configuration'
6
+ require_relative 'authentication/token_verifier'
6
7
  require_relative 'authentication/claims'
7
8
  require_relative 'authentication/cognito_authenticatable'
8
9
  require_relative 'authentication/model_macro'
@@ -9,6 +9,7 @@ require_relative 'environment_config'
9
9
  require_relative 'frontend_env_map'
10
10
  require_relative 'frontend_prerender'
11
11
  require_relative 'frontend_registry'
12
+ require_relative 'frontend_routes'
12
13
  require_relative 'terraform_command'
13
14
 
14
15
  module Belt
@@ -18,7 +19,7 @@ module Belt
18
19
 
19
20
  PAGES_MANIFEST = FrontendPrerender::PAGES_MANIFEST
20
21
  # Uploaded with no-cache instead of the immutable header hashed assets get
21
- REVALIDATED_FILES = %w[*.html robots.txt sitemap.xml llms.txt].freeze
22
+ REVALIDATED_FILES = %w[*.html robots.txt sitemap.xml llms.txt llms-full.txt].freeze
22
23
 
23
24
  def self.run(args)
24
25
  frontend_name = FrontendRegistry.extract_flag!(args, '--frontend')
@@ -73,6 +74,7 @@ module Belt
73
74
  puts "━━━ #{@frontend.label} (#{@frontend.path}/) ━━━"
74
75
  build_frontend
75
76
  sync_to_s3
77
+ publish_routes
76
78
  invalidate_cloudfront
77
79
  url = fetch_frontend_url
78
80
  puts "\n✅ #{@frontend.label.capitalize} deployed to #{@env}!"
@@ -150,7 +152,7 @@ module Belt
150
152
  # excluded so --delete doesn't remove them before they're re-uploaded.
151
153
  run!('aws', 's3', 'sync', dist_prefix, "s3://#{bucket}", '--delete',
152
154
  '--size-only', '--cache-control', 'public, max-age=31536000, immutable',
153
- *[*REVALIDATED_FILES, PAGES_MANIFEST].flat_map { |f| ['--exclude', f] },
155
+ *[*REVALIDATED_FILES, PAGES_MANIFEST, FrontendRoutes::MANIFEST].flat_map { |f| ['--exclude', f] },
154
156
  *pages.keys.flat_map { |key| ['--exclude', key] })
155
157
 
156
158
  index = File.join(dist, 'index.html')
@@ -189,8 +191,23 @@ module Belt
189
191
  end
190
192
  end
191
193
 
194
+ # Tells CloudFront which addresses exist, so anything else answers 404
195
+ # (FrontendRoutes). Before the invalidation, so the first uncached request
196
+ # already sees the new routes.
197
+ def publish_routes
198
+ return unless File.file?(File.join(@frontend.dist_dir, FrontendRoutes::MANIFEST))
199
+
200
+ FrontendRoutes.new(dist_dir: @frontend.dist_dir, distribution_id: distribution_id).publish
201
+ end
202
+
203
+ def distribution_id
204
+ return @distribution_id if defined?(@distribution_id)
205
+
206
+ @distribution_id = fetch_distribution_id
207
+ end
208
+
192
209
  def invalidate_cloudfront
193
- dist_id = fetch_distribution_id
210
+ dist_id = distribution_id
194
211
  unless dist_id
195
212
  puts '⚠️ No CloudFront distribution found (skipping cache invalidation)'
196
213
  return
@@ -6,6 +6,7 @@ require_relative 'environment_config'
6
6
  require_relative 'frontend_env_map'
7
7
  require_relative 'frontend_prerender'
8
8
  require_relative 'frontend_registry'
9
+ require_relative 'frontend_routes'
9
10
  require_relative 'terraform_command'
10
11
 
11
12
  module Belt
@@ -13,6 +14,7 @@ module Belt
13
14
  # belt frontend env <environment> [--frontend NAME]
14
15
  # belt frontend list
15
16
  # belt frontend prerender [--frontend NAME]
17
+ # belt frontend router
16
18
  #
17
19
  # Smart-merges terraform outputs into <frontend>/.env using the declarative map
18
20
  # (<frontend>/env.yml or .belt/frontend_env.yml for the default frontend).
@@ -29,6 +31,8 @@ module Belt
29
31
  run_list
30
32
  when 'prerender'
31
33
  run_prerender(args)
34
+ when 'router'
35
+ run_router
32
36
  when nil, '-h', '--help', 'help'
33
37
  puts usage
34
38
  exit(subcommand.nil? ? 1 : 0)
@@ -67,6 +71,18 @@ module Belt
67
71
  prerender.run
68
72
  end
69
73
 
74
+ # Writes (or refreshes) the CloudFront router function next to the frontend
75
+ # terraform that loads it. For apps adopting real 404s, and after a belt
76
+ # upgrade that changes the function.
77
+ def self.run_router
78
+ module_dir = FrontendRoutes::MODULE_DIR
79
+ abort "Error: Module directory not found at #{module_dir}/." unless Dir.exist?(module_dir)
80
+
81
+ dest = FrontendRoutes.install_router(module_dir)
82
+ puts dest ? " write #{dest}" : " current #{File.join(module_dir, FrontendRoutes::ROUTER_FILE)}"
83
+ puts "\nApply it with `belt deploy <environment>`. See `belt explain seo`, \"Real 404s\"."
84
+ end
85
+
70
86
  def self.run_env(args)
71
87
  frontend_name = FrontendRegistry.extract_flag!(args, '--frontend')
72
88
  env = EnvResolver.resolve(args)
@@ -106,6 +122,7 @@ module Belt
106
122
  belt frontend env <environment> [--frontend NAME]
107
123
  belt frontend list
108
124
  belt frontend prerender [--frontend NAME] Build + SEO prerender locally (src/seo.js)
125
+ belt frontend router Write the CloudFront router function (real 404s)
109
126
  belt frontend --help
110
127
 
111
128
  Env map (optional, per frontend):
@@ -21,6 +21,7 @@ module Belt
21
21
  # existing apps don't grow an untracked build directory.
22
22
  SSR_OUT_DIR = 'node_modules/.cache/belt-ssr'
23
23
  PAGES_MANIFEST = '.belt-pages.json'
24
+ ROUTES_MANIFEST = '.belt-routes.json'
24
25
 
25
26
  def initialize(frontend, env: {})
26
27
  @frontend = frontend
@@ -32,34 +33,41 @@ module Belt
32
33
  end
33
34
 
34
35
  # Frontends scaffolded by belt 0.6.6–0.6.9 run their own scripts/prerender.js
35
- # inside `npm run build`; their output is already in dist.
36
+ # inside `npm run build`, and an app can prerender its own way and say where
37
+ # its pages are in .belt-routes.json; either way the pages are already in dist.
36
38
  def prerendered_by_build?
37
- File.file?(File.join(@frontend.dist_dir, PAGES_MANIFEST))
39
+ [PAGES_MANIFEST, ROUTES_MANIFEST].any? { |file| File.file?(File.join(@frontend.dist_dir, file)) }
38
40
  end
39
41
 
40
42
  # Returns true when it prerendered, false when the frontend didn't opt in.
41
- def run
43
+ def run # rubocop:disable Naming/PredicateMethod
42
44
  return false unless manifest
43
45
 
44
46
  if prerendered_by_build?
45
- puts '🔎 SEO: prerendered by the app build (scripts/prerender.js) — skipping belt prerender'
47
+ puts '🔎 SEO: prerendered by the app build — skipping belt prerender, adding the app routes for 404s'
48
+ run_script('--routes-only')
46
49
  return false
47
50
  end
48
51
 
49
52
  puts "🔎 SEO: prerendering pages from #{manifest}"
50
53
  ssr = build_ssr_bundle
54
+ run_script(*(ssr ? ['--ssr', ssr] : []))
55
+ true
56
+ end
57
+
58
+ private
59
+
60
+ def run_script(*extra)
51
61
  cmd = ['node', SCRIPT,
52
62
  '--manifest', File.expand_path(manifest, @frontend.path),
53
63
  '--dist', File.expand_path(@frontend.dist_dir),
54
- '--public', File.expand_path('public', @frontend.path)]
55
- cmd.push('--ssr', ssr) if ssr
56
- return true if system(@env, *cmd, chdir: @frontend.path)
64
+ '--public', File.expand_path('public', @frontend.path),
65
+ '--src', File.expand_path('src', @frontend.path), *extra]
66
+ return if system(@env, *cmd, chdir: @frontend.path)
57
67
 
58
68
  abort "\n✗ SEO prerender failed: #{cmd.shelljoin}"
59
69
  end
60
70
 
61
- private
62
-
63
71
  # Builds the SSR bundle and returns its entry path, or nil when there's no
64
72
  # entry or it doesn't build (typically a module touching window/document at
65
73
  # import time). Without it, pages still get their tags, sitemap and robots.
@@ -0,0 +1,129 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'fileutils'
4
+ require 'json'
5
+ require 'open3'
6
+
7
+ module Belt
8
+ module CLI
9
+ # Real 404s for a single-page frontend.
10
+ #
11
+ # CloudFront can't tell which addresses an SPA has, so the classic setup
12
+ # answers every path with index.html and 200. Belt's router function
13
+ # (lib/belt/frontend/router.js) fixes that at the edge, and this class keeps
14
+ # it informed: after each deploy it publishes the routes the prerender step
15
+ # wrote to <dist>/.belt-routes.json (from src/seo.js: `pages` and
16
+ # `privatePaths`) into the CloudFront KeyValueStore the function reads.
17
+ #
18
+ # Nothing here is required for a deploy to work. No manifest, no router on the
19
+ # distribution, or a failed publish all leave the site serving as it did.
20
+ class FrontendRoutes
21
+ ROUTER_SOURCE = File.expand_path('../frontend/router.js', __dir__)
22
+ ROUTER_FILE = 'belt_frontend_router.js'
23
+ MODULE_DIR = 'infrastructure/modules/app'
24
+ MANIFEST = '.belt-routes.json'
25
+ KEY = 'belt:routes'
26
+ # A KeyValueStore value holds 1 KB.
27
+ CHUNK_SIZE = 1000
28
+
29
+ # Copies the router function next to the terraform that loads it with
30
+ # file(). Returns the path when the file was written or refreshed.
31
+ def self.install_router(module_dir = MODULE_DIR)
32
+ dest = File.join(module_dir, ROUTER_FILE)
33
+ source = File.read(ROUTER_SOURCE)
34
+ return nil if File.file?(dest) && File.read(dest) == source
35
+
36
+ FileUtils.mkdir_p(module_dir)
37
+ File.write(dest, source)
38
+ dest
39
+ end
40
+
41
+ # The KeyValueStore entries for a manifest: the chunk count under KEY and
42
+ # the JSON split across KEY:0, KEY:1, ...
43
+ def self.entries(manifest)
44
+ routes = { 'app' => Array(manifest['app']), 'pages' => Array(manifest['pages']) }
45
+ routes['objects'] = manifest['objects'] if manifest['objects'].is_a?(Hash) && manifest['objects'].any?
46
+ json = JSON.generate(routes, ascii_only: true)
47
+ chunks = json.scan(/.{1,#{CHUNK_SIZE}}/m)
48
+ chunks.each_with_index.to_h { |chunk, i| ["#{KEY}:#{i}", chunk] }.merge(KEY => chunks.size.to_s)
49
+ end
50
+
51
+ def initialize(dist_dir:, distribution_id:)
52
+ @dist_dir = dist_dir
53
+ @distribution_id = distribution_id
54
+ end
55
+
56
+ def manifest
57
+ path = File.join(@dist_dir, MANIFEST)
58
+ return nil unless File.file?(path)
59
+
60
+ data = JSON.parse(File.read(path))
61
+ data.is_a?(Hash) ? data : nil
62
+ rescue JSON::ParserError
63
+ nil
64
+ end
65
+
66
+ # Returns :published, or the reason nothing was published.
67
+ def publish
68
+ routes = manifest
69
+ return :no_manifest unless routes
70
+ return :no_distribution unless @distribution_id
71
+
72
+ store = key_value_store_arn
73
+ unless store
74
+ puts 'ℹ️ Unknown paths still answer 200: this CloudFront distribution has no belt router. ' \
75
+ 'See "Real 404s" in `belt explain seo`.'
76
+ return :no_router
77
+ end
78
+
79
+ write(store, self.class.entries(routes))
80
+ puts "🧭 Published routes: #{Array(routes['pages']).size} page(s), " \
81
+ "#{Array(routes['app']).size} app path(s); anything else answers 404"
82
+ :published
83
+ rescue StandardError => e
84
+ warn "⚠️ Could not publish routes (#{e.message.lines.first&.strip}). " \
85
+ 'The site keeps serving with the routes from the last deploy.'
86
+ :failed
87
+ end
88
+
89
+ private
90
+
91
+ # The store is whichever KeyValueStore the distribution's default-behavior
92
+ # functions are associated with, so no extra terraform output is needed.
93
+ def key_value_store_arn
94
+ functions = aws_json('cloudfront', 'get-distribution-config', '--id', @distribution_id)
95
+ .dig('DistributionConfig', 'DefaultCacheBehavior', 'FunctionAssociations', 'Items') || []
96
+ functions.each do |association|
97
+ name = association['FunctionARN'].to_s.split('/').last
98
+ next if name.to_s.empty?
99
+
100
+ stores = aws_json('cloudfront', 'describe-function', '--name', name, '--stage', 'LIVE')
101
+ .dig('FunctionSummary', 'FunctionConfig', 'KeyValueStoreAssociations', 'Items') || []
102
+ arn = stores.first&.fetch('KeyValueStoreARN', nil)
103
+ return arn if arn
104
+ end
105
+ nil
106
+ end
107
+
108
+ # One atomic update: new entries in, chunks left over from a longer list out.
109
+ def write(store, entries)
110
+ etag = aws_json('cloudfront-keyvaluestore', 'describe-key-value-store', '--kvs-arn', store).fetch('ETag')
111
+ existing = (aws_json('cloudfront-keyvaluestore', 'list-keys', '--kvs-arn', store)['Items'] || [])
112
+ .map { |item| item['Key'] }
113
+ stale = existing.select { |key| key.start_with?(KEY) } - entries.keys
114
+
115
+ cmd = ['cloudfront-keyvaluestore', 'update-keys', '--kvs-arn', store, '--if-match', etag,
116
+ '--puts', JSON.generate(entries.map { |key, value| { 'Key' => key, 'Value' => value } })]
117
+ cmd.push('--deletes', JSON.generate(stale.map { |key| { 'Key' => key } })) if stale.any?
118
+ aws_json(*cmd)
119
+ end
120
+
121
+ def aws_json(*args)
122
+ out, err, status = Open3.capture3('aws', *args, '--output', 'json')
123
+ raise err.strip.empty? ? "aws #{args.first(2).join(' ')} failed" : err.strip unless status.success?
124
+
125
+ out.strip.empty? ? {} : JSON.parse(out)
126
+ end
127
+ end
128
+ end
129
+ end
@@ -5,6 +5,7 @@ require 'erb'
5
5
  require_relative 'app_detection'
6
6
  require_relative 'env_resolver'
7
7
  require_relative 'frontend_registry'
8
+ require_relative 'frontend_routes'
8
9
 
9
10
  module Belt
10
11
  module CLI
@@ -70,6 +71,7 @@ module Belt
70
71
  def run
71
72
  validate!
72
73
  generate_frontend_tf
74
+ install_router
73
75
  ensure_cloudfront_cors
74
76
  append_env_outputs
75
77
  return if @quiet
@@ -96,6 +98,12 @@ module Belt
96
98
  puts " create #{dest}" unless @quiet
97
99
  end
98
100
 
101
+ # The CloudFront function frontend.tf loads with file().
102
+ def install_router
103
+ dest = FrontendRoutes.install_router(MODULE_DIR)
104
+ puts " create #{dest}" if dest && !@quiet
105
+ end
106
+
99
107
  def append_env_outputs
100
108
  Dir.glob('infrastructure/*/outputs.tf').reject { |f| f.include?('modules') }.each do |file|
101
109
  before = File.read(file)
data/lib/belt/cli.rb CHANGED
@@ -167,6 +167,7 @@ module Belt
167
167
  frontend env <env> [--frontend NAME] Write <frontend>/.env from terraform outputs
168
168
  frontend list List configured frontends
169
169
  frontend prerender [--frontend NAME] Build + SEO prerender a frontend locally
170
+ frontend router Write the CloudFront router function (real 404s)
170
171
  routes [-g PATTERN] [-f json] Show route definitions
171
172
  contracts [-g PATTERN] [-f json] Show API request/response contracts
172
173
  lambda-config [-e ENV] [-f json|terraform] Show merged lambda configuration
@@ -150,6 +150,7 @@ Belt.configure do |config|
150
150
  config.authentication.user_class = 'Account' # default: 'User'
151
151
  config.authentication.admin_groups = %w[staff] # default: ['admins'], or ADMIN_COGNITO_GROUPS
152
152
  config.authentication.issuer = '...' # default: derived from COGNITO_USER_POOL_ID
153
+ config.authentication.client_ids = %w[...] # default: COGNITO_CLIENT_ID (comma-separated)
153
154
  end
154
155
  ```
155
156
 
@@ -168,12 +169,46 @@ A route can be authenticated either way, and both are handled:
168
169
  1. **API Gateway Cognito authorizer** — claims arrive pre-verified under
169
170
  `requestContext.authorizer.claims`, with every value flattened to a string
170
171
  (`"true"`, `"[admins, members]"`).
171
- 2. **A raw `Authorization: Bearer <id token>` header** — the Lambda decodes it.
172
+ 2. **A raw `Authorization: Bearer <id token>` header**, on a route with no
173
+ authorizer — nothing has checked it, so Belt does.
172
174
 
173
- Case 2 is signature-unverified by design: where an authorizer is attached, the gateway
174
- already checked the signature and an unsigned token never reaches your code. What can
175
- still be checked cheaply is checked — structure, expiry, issuer, and `token_use` (an
176
- access token is rejected; it carries no email or name).
175
+ For case 2 Belt verifies the token itself and returns no claims unless every check
176
+ passes:
177
+
178
+ - signed with RS256 by a key in your pool's JWKS (looked up by `kid`, fetched once per
179
+ Lambda container)
180
+ - `exp` present and in the future
181
+ - `iss` is your pool
182
+ - `token_use` is `id` (an access token carries no email or name)
183
+ - `aud` is one of your app client ids
184
+
185
+ So a token someone made up is not an identity: `current_user` is nil,
186
+ `cognito_admin?` is false and `authenticate_user!` answers 401.
187
+
188
+ The Lambda needs to know the pool and the client to verify against. Add both to the
189
+ function's environment (`config/lambda/api.yml`):
190
+
191
+ ```yaml
192
+ env_vars:
193
+ COGNITO_USER_POOL_ID: ref(cognito_user_pool_id)
194
+ COGNITO_CLIENT_ID: ref(cognito_client_id) # comma-separated for several clients
195
+ ```
196
+
197
+ and supply the refs in `infrastructure/modules/app/main.tf`:
198
+
199
+ ```hcl
200
+ lambda_env_refs = merge(var.lambda_env_refs, {
201
+ cognito_user_pool_id = aws_cognito_user_pool.main.id
202
+ cognito_client_id = aws_cognito_user_pool_client.main.id
203
+ })
204
+ ```
205
+
206
+ Without them a header token is never believed — Belt fails closed rather than return
207
+ claims it could not verify. Routes declared `auth: :cognito` need neither variable:
208
+ the gateway has already done the checking.
209
+
210
+ `Belt::Authentication::Claims.decode` still parses a token's payload without checking
211
+ its signature. It is not an identity check; don't use it as one.
177
212
 
178
213
  Anything that isn't a Cognito ID token — including your own API key scheme sharing the
179
214
  same header — reads as "no Cognito identity" rather than an error, so
@@ -140,6 +140,56 @@ the build; set `SEO_INDEXABLE=true|false` to override.
140
140
  After the first prod deploy, submit `https://<domain>/sitemap.xml` to Google
141
141
  Search Console and Bing Webmaster Tools.
142
142
 
143
+ ### Real 404s
144
+
145
+ A single-page app on S3 + CloudFront classically answers every path with
146
+ `index.html` and HTTP 200, because CloudFront can't tell which addresses the app
147
+ has. Crawlers and agents then can't tell a missing page from a real one. A
148
+ frontend with `src/seo.js` answers a real 404 instead:
149
+
150
+ - **A public page** (`seo.pages`) is served from its prerendered file.
151
+ - **A route of the app** is served `index.html`, as before.
152
+ - **Anything else** gets `404.html` with HTTP 404. That page is the app's own
153
+ "not found" route (`<Route path="*">`) prerendered, with `noindex`.
154
+
155
+ You don't keep a route list. The prerender step reads the app's routes from its
156
+ `<Route path="/...">` declarations under `src/` (test files are skipped), adds
157
+ `seo.privatePaths` as prefixes, and writes them to `dist/.belt-routes.json`.
158
+ `belt deploy frontend` publishes that to a CloudFront KeyValueStore, and belt's
159
+ router function (`infrastructure/modules/app/belt_frontend_router.js`, on the
160
+ distribution's viewer-request and viewer-response events) reads it at the edge.
161
+ The deploy prints what it published:
162
+
163
+ ```
164
+ SEO: 14 app route(s) and 6 page(s) answer; any other address is a 404
165
+ 🧭 Published routes: 5 page(s), 14 app path(s); anything else answers 404
166
+ ```
167
+
168
+ Belt only sees a route written as `<Route path="/literal/or/:param">`. A route
169
+ declared another way — a nested `<Route path="settings">`, a `createBrowserRouter`
170
+ config object, a path built at runtime — needs its prefix in `privatePaths`
171
+ (`'/account'` covers `/account` and everything under it). If one is missed,
172
+ nothing breaks in a browser: `404.html` loads the app, which routes to the real
173
+ page. Only the HTTP status is wrong, so check `dist/.belt-routes.json` after
174
+ adding a route in an unusual way.
175
+
176
+ A frontend that prerenders its own way (its `npm run build` writes the pages, as
177
+ the 0.6.6–0.6.9 templates did) still gets this: belt leaves its pages alone and
178
+ only adds the app routes and, if the build wrote none, `404.html`. Such a build
179
+ can write `dist/.belt-routes.json` itself to say where its pages are:
180
+ `{ "pages": ["/docs"], "objects": { "/": "/_pages/index.html", "/docs": "/_pages/docs.html" } }`.
181
+ `objects` is only needed for a page that isn't stored at its own extensionless
182
+ key.
183
+
184
+ Published routes reach the edge within about a minute of the deploy. Check with
185
+ `curl -s -o /dev/null -w '%{http_code}\n' https://<site>/no-such-page` (404) and
186
+ the same for a route of the app (200).
187
+
188
+ It fails open. Until a deploy has published routes, or if the store can't be
189
+ read or written, every path behaves as it did before (index.html, 200). Paths
190
+ with a file extension are never rewritten. Customize the 404 page's metadata
191
+ with `seo.notFound: { title, description }`.
192
+
143
193
  ## Infrastructure
144
194
 
145
195
  `belt setup frontend` (and `belt generate frontend`) writes S3 + CloudFront into
@@ -147,6 +197,9 @@ Search Console and Bing Webmaster Tools.
147
197
  `{name}_frontend.tf` with unique resource names and outputs
148
198
  (`ops_frontend_bucket_name`, …). Extra frontends get a CloudFront URL only —
149
199
  custom DNS stays on the default frontend unless you add records yourself.
200
+ The generated distribution includes the router function and KeyValueStore for
201
+ real 404s (above); `belt frontend router` rewrites `belt_frontend_router.js`
202
+ after a belt upgrade changes it.
150
203
 
151
204
  CORS: each CloudFront domain is added to `frontend_urls` on the conveyor-belt
152
205
  resource so SPA → API calls work.
@@ -16,15 +16,27 @@
16
16
  * llms.txt — plain-text site summary for LLMs (https://llmstxt.org)
17
17
  * .belt-pages.json — S3 key → file map; `belt deploy frontend` uploads each page
18
18
  * to its extensionless key (/about → about.html) as text/html
19
+ * 404.html — what an address with no page gets, with HTTP 404: the app's
20
+ * own "not found" route when it has one, never indexed
21
+ * .belt-routes.json — the public pages, plus the app's own routes (every
22
+ * <Route path="/..."> under --src and seo.privatePaths);
23
+ * `belt deploy frontend` publishes them to CloudFront so it can
24
+ * tell a real address from a missing one (see `belt explain
25
+ * seo`, "Real 404s")
19
26
  *
20
- * Usage: node prerender.mjs --manifest src/seo.js --dist dist [--ssr entry-server.js] [--public public]
27
+ * With --routes-only (a frontend whose own build already prerendered its pages) nothing
28
+ * above is touched except what real 404s need: .belt-routes.json gains the app's routes
29
+ * (keeping any `pages`/`objects` the build wrote, else taking pages from .belt-pages.json),
30
+ * and 404.html is written only if the build didn't write one.
31
+ *
32
+ * Usage: node prerender.mjs --manifest src/seo.js --dist dist [--ssr entry-server.js] [--public public] [--src src]
21
33
  *
22
34
  * Environment:
23
35
  * VITE_SITE_URL canonical origin (belt deploy injects the frontend URL)
24
36
  * BELT_ENV environment being built (belt deploy injects it)
25
37
  * SEO_INDEXABLE "true"/"false" to override seo.indexableEnvironments
26
38
  */
27
- import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
39
+ import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs'
28
40
  import { dirname, join, resolve } from 'node:path'
29
41
  import { pathToFileURL } from 'node:url'
30
42
  import { parseArgs } from 'node:util'
@@ -34,17 +46,20 @@ const { values: args } = parseArgs({
34
46
  manifest: { type: 'string' },
35
47
  dist: { type: 'string' },
36
48
  ssr: { type: 'string' },
37
- public: { type: 'string' }
49
+ public: { type: 'string' },
50
+ src: { type: 'string' },
51
+ 'routes-only': { type: 'boolean' }
38
52
  }
39
53
  })
40
54
  if (!args.manifest || !args.dist) {
41
- console.error('Usage: node prerender.mjs --manifest src/seo.js --dist dist [--ssr entry-server.js] [--public public]')
55
+ console.error('Usage: node prerender.mjs --manifest src/seo.js --dist dist [--ssr entry-server.js] [--public public] [--src src]')
42
56
  process.exit(1)
43
57
  }
44
58
 
45
59
  const DIST = resolve(args.dist)
46
60
  const SSR_ENTRY = args.ssr ? resolve(args.ssr) : null
47
61
  const PROJECT_ROBOTS = args.public ? join(resolve(args.public), 'robots.txt') : null
62
+ const SRC = args.src ? resolve(args.src) : null
48
63
  const seo = (await import(pathToFileURL(resolve(args.manifest)).href)).default
49
64
 
50
65
  const siteUrl = (process.env.VITE_SITE_URL || seo.siteUrl || '').replace(/\/+$/, '')
@@ -135,6 +150,63 @@ function pageHtml(template, page, body) {
135
150
  )
136
151
  }
137
152
 
153
+ // The addresses the single-page app routes itself, as patterns for belt's
154
+ // CloudFront router: `*` is one segment, a trailing `**` is the rest. They come
155
+ // from the app's own <Route path="/..."> declarations, so adding a route needs no
156
+ // second list, plus seo.privatePaths for anything declared another way (nested
157
+ // relative routes, a router config object, a path built at runtime).
158
+ const ROUTE_PATH = /<Route\b[^>]*?\bpath=\{?["'`](\/[^"'`]*)["'`]/g
159
+ const SOURCE_FILE = /\.(jsx?|tsx?)$/
160
+ const TEST_FILE = /\.(test|spec)\.|__tests__/
161
+
162
+ function sourceFiles(dir) {
163
+ return readdirSync(dir, { withFileTypes: true }).flatMap((entry) => {
164
+ const path = join(dir, entry.name)
165
+ if (entry.isDirectory()) return entry.name === 'node_modules' ? [] : sourceFiles(path)
166
+ return SOURCE_FILE.test(entry.name) && !TEST_FILE.test(path) ? [path] : []
167
+ })
168
+ }
169
+
170
+ function routePattern(path) {
171
+ const segments = []
172
+ for (const segment of normalize(path).split('/').slice(1)) {
173
+ if (segment === '*' || segment.endsWith('?')) return ['', ...segments, '**'].join('/')
174
+ segments.push(segment.startsWith(':') ? '*' : segment)
175
+ }
176
+ return ['', ...segments].join('/')
177
+ }
178
+
179
+ function appRoutes(pagePaths) {
180
+ const declared = SRC && existsSync(SRC)
181
+ ? sourceFiles(SRC).flatMap((file) => [...readFileSync(file, 'utf-8').matchAll(ROUTE_PATH)].map((match) => match[1]))
182
+ : []
183
+ const patterns = [...declared.map(routePattern), ...privatePaths.map((path) => `${path}/**`)]
184
+ return [...new Set(patterns)].filter((pattern) => pattern !== '/' && !pagePaths.includes(pattern)).sort()
185
+ }
186
+
187
+ // Served for every address that is neither a page nor an app route. It keeps the
188
+ // app's scripts, so a route belt couldn't see still boots the app in a browser.
189
+ const NOT_FOUND_PATH = '/404'
190
+
191
+ function notFoundHtml(template, body) {
192
+ const title = seo.notFound?.title || `Page not found | ${seo.siteName}`
193
+ const description = seo.notFound?.description || `There is no page at this address on ${seo.siteName}.`
194
+ const fallback = `<main><h1>Page not found</h1><p>${escapeHtml(description)}</p><p><a href="/">${escapeHtml(seo.siteName)}</a></p></main>`
195
+ return template
196
+ .replace(/<title>[\s\S]*?<\/title>/, () => `<title>${escapeHtml(title)}</title>`)
197
+ .replace(/\s*<meta name="description"[^>]*>/, '')
198
+ .replace(
199
+ '</head>',
200
+ () =>
201
+ ` <meta name="description" content="${escapeHtml(description)}" />\n` +
202
+ ' <meta name="robots" content="noindex" />\n </head>'
203
+ )
204
+ .replace(
205
+ '<div id="root"></div>',
206
+ () => (body ? `<div id="root" data-prerendered="${NOT_FOUND_PATH}">${body}</div>` : `<div id="root">${fallback}</div>`)
207
+ )
208
+ }
209
+
138
210
  function robotsTxt() {
139
211
  if (!indexable) return 'User-agent: *\nDisallow: /\n'
140
212
  if (PROJECT_ROBOTS && existsSync(PROJECT_ROBOTS)) return readFileSync(PROJECT_ROBOTS, 'utf-8')
@@ -154,12 +226,29 @@ function llmsTxt() {
154
226
  return `${lines.join('\n')}\n`
155
227
  }
156
228
 
229
+ const readJson = (file) => (existsSync(file) ? JSON.parse(readFileSync(file, 'utf-8')) : null)
230
+
231
+ // The app's build prerendered its own pages. Fill in what real 404s still need.
232
+ function completeRoutes(indexFile) {
233
+ const routesFile = join(DIST, '.belt-routes.json')
234
+ const built = readJson(routesFile) || {}
235
+ const pagePaths = built.pages || Object.keys(readJson(join(DIST, '.belt-pages.json')) || {}).map(normalize)
236
+ const routes = { ...built, pages: pagePaths, app: appRoutes(pagePaths) }
237
+
238
+ writeFileSync(routesFile, `${JSON.stringify(routes, null, 2)}\n`)
239
+ if (!existsSync(join(DIST, '404.html'))) {
240
+ writeFileSync(join(DIST, '404.html'), notFoundHtml(readFileSync(indexFile, 'utf-8'), ''))
241
+ }
242
+ console.log(`SEO: ${routes.app.length} app route(s) and ${pagePaths.length + 1} page(s) answer; any other address is a 404`)
243
+ }
244
+
157
245
  async function main() {
158
246
  const indexFile = join(DIST, 'index.html')
159
247
  if (!existsSync(indexFile)) {
160
248
  console.error(`${indexFile} not found — run \`vite build\` first`)
161
249
  process.exit(1)
162
250
  }
251
+ if (args['routes-only']) return completeRoutes(indexFile)
163
252
  if (!pages.some((page) => page.path === '/')) pages.unshift({ path: '/', title: seo.siteName })
164
253
  for (const page of pages) {
165
254
  page.title ||= seo.siteName
@@ -179,13 +268,19 @@ async function main() {
179
268
  if (key) manifest[key] = file
180
269
  }
181
270
 
271
+ writeFileSync(join(DIST, '404.html'), notFoundHtml(template, renderBody(render, NOT_FOUND_PATH)))
272
+ const pagePaths = pages.map((page) => page.path).filter((path) => path !== '/')
273
+ const routes = { pages: pagePaths, app: appRoutes(pagePaths) }
274
+
182
275
  writeFileSync(join(DIST, '.belt-pages.json'), `${JSON.stringify(manifest, null, 2)}\n`)
276
+ writeFileSync(join(DIST, '.belt-routes.json'), `${JSON.stringify(routes, null, 2)}\n`)
183
277
  writeFileSync(join(DIST, 'robots.txt'), robotsTxt())
184
278
  writeFileSync(join(DIST, 'llms.txt'), llmsTxt())
185
279
  if (siteUrl) writeFileSync(join(DIST, 'sitemap.xml'), sitemapXml())
186
280
 
187
281
  if (PROJECT_ROBOTS && indexable && existsSync(PROJECT_ROBOTS)) console.log('SEO: robots.txt from public/robots.txt')
188
282
  if (!siteUrl) console.warn('⚠️ No site URL (VITE_SITE_URL or seo.siteUrl) — skipped canonical URLs and sitemap.xml')
283
+ console.log(`SEO: ${routes.app.length} app route(s) and ${pagePaths.length + 1} page(s) answer; any other address is a 404`)
189
284
  console.log(
190
285
  `SEO: prerendered ${pages.length} page(s), ${indexable ? 'indexable' : 'noindex'}` +
191
286
  `${process.env.BELT_ENV ? ` (${process.env.BELT_ENV})` : ''}`
@@ -0,0 +1,112 @@
1
+ // Belt frontend router — a CloudFront Function (cloudfront-js-2.0), associated
2
+ // with the distribution's default behavior for both viewer-request and
3
+ // viewer-response. It makes an address with no page answer HTTP 404 instead of
4
+ // the app shell with 200, so crawlers and agents can tell a missing page from a
5
+ // real one.
6
+ //
7
+ // `belt deploy frontend` publishes the app's routes (src/seo.js) to the
8
+ // KeyValueStore associated with this function:
9
+ //
10
+ // belt:routes number of chunks
11
+ // belt:routes:N chunk N of the JSON { "app": [...], "pages": [...], "objects": {...} }
12
+ // (a KeyValueStore value holds 1 KB, so the JSON is split)
13
+ //
14
+ // `pages` are prerendered public pages, stored in S3 at their extensionless key
15
+ // unless `objects` names another object for that path ("/" included).
16
+ // `app` are patterns for the addresses the single-page app routes itself, read
17
+ // from its <Route path> declarations and seo.privatePaths: `*` is any one
18
+ // segment, a trailing `**` is anything from there on.
19
+ //
20
+ // a page → served from its own object
21
+ // an app route → /index.html
22
+ // anything else → /404.html, with status 404
23
+ // a path with a file extension (/assets/x.js, /robots.txt) → untouched
24
+ //
25
+ // CloudFront's JavaScript engine is not Node: among other gaps it rejects `await`
26
+ // inside a call's arguments or a condition. Keep every await as its own
27
+ // `const x = await ...` statement (spec/belt/frontend/router_spec.rb checks).
28
+ //
29
+ // Until routes have been published, or if the store can't be read, every request
30
+ // passes through untouched and the distribution's custom error responses serve
31
+ // index.html, exactly as before this function existed.
32
+ import cf from 'cloudfront';
33
+
34
+ const NOT_FOUND = '/404.html';
35
+
36
+ async function loadRoutes() {
37
+ try {
38
+ const kvs = cf.kvs();
39
+ const header = await kvs.get('belt:routes');
40
+ const count = parseInt(header, 10);
41
+ const reads = [];
42
+ for (let i = 0; i < count; i++) reads.push(kvs.get('belt:routes:' + i));
43
+ const chunks = await Promise.all(reads);
44
+ return JSON.parse(chunks.join(''));
45
+ } catch (error) {
46
+ return null;
47
+ }
48
+ }
49
+
50
+ function hasExtension(uri) {
51
+ return uri.substring(uri.lastIndexOf('/') + 1).indexOf('.') !== -1;
52
+ }
53
+
54
+ // Where a request goes: null to leave it alone, or the object to serve.
55
+ async function resolve(uri) {
56
+ if (hasExtension(uri)) return null;
57
+ const path = uri.replace(/\/+$/, '');
58
+ const routes = await loadRoutes();
59
+ if (!routes) return null;
60
+
61
+ const objects = routes.objects || {};
62
+ if (path === '') return objects['/'] || null;
63
+ if (routes.pages.indexOf(path) !== -1) return objects[path] || path;
64
+ for (let i = 0; i < routes.app.length; i++) {
65
+ if (matches(routes.app[i], path)) return '/index.html';
66
+ }
67
+ return NOT_FOUND;
68
+ }
69
+
70
+ function matches(pattern, path) {
71
+ const want = pattern.split('/');
72
+ const have = path.split('/');
73
+ for (let i = 0; i < want.length; i++) {
74
+ if (want[i] === '**') return true;
75
+ if (i >= have.length) return false;
76
+ if (want[i] !== '*' && want[i] !== have[i]) return false;
77
+ }
78
+ return want.length === have.length;
79
+ }
80
+
81
+ // An error thrown from a CloudFront Function is a 503 for the visitor, so
82
+ // anything unexpected leaves the request or response as it came.
83
+ async function handler(event) {
84
+ const request = event.request;
85
+
86
+ if (event.context.eventType === 'viewer-request') {
87
+ try {
88
+ const target = await resolve(request.uri);
89
+ if (target) request.uri = target;
90
+ } catch (error) {
91
+ console.log('belt router: ' + error);
92
+ }
93
+ return request;
94
+ }
95
+
96
+ // viewer-response. The request here may carry the original address or the one
97
+ // the viewer-request run rewrote, so both are checked. Only a 200 is changed:
98
+ // a 304 revalidation of the 404 page has to stay a 304.
99
+ const response = event.response;
100
+ try {
101
+ if (response.statusCode !== 200) return response;
102
+ let target = request.uri;
103
+ if (target !== NOT_FOUND) target = await resolve(request.uri);
104
+ if (target === NOT_FOUND) {
105
+ response.statusCode = 404;
106
+ response.statusDescription = 'Not Found';
107
+ }
108
+ } catch (error) {
109
+ console.log('belt router: ' + error);
110
+ }
111
+ return response;
112
+ }
data/lib/belt/version.rb CHANGED
@@ -1,7 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Belt
4
- VERSION = '0.6.10'
4
+ VERSION = '0.6.12'
5
5
 
6
6
  # Ruby version new apps run on in Lambda. Rendered into the conveyor-belt
7
7
  # provider block (`ruby_version`) by `belt new` / `belt generate environment`.
@@ -1,11 +1,13 @@
1
1
  import { Routes, Route } from 'react-router-dom'
2
2
  import Home from './pages/Home'
3
+ import NotFound from './pages/NotFound'
3
4
 
4
5
  // The router lives in main.jsx (browser) and entry-server.jsx (prerender).
5
6
  function App() {
6
7
  return (
7
8
  <Routes>
8
9
  <Route path="/" element={<Home />} />
10
+ <Route path="*" element={<NotFound />} />
9
11
  </Routes>
10
12
  )
11
13
  }
@@ -0,0 +1,18 @@
1
+ import { Link } from 'react-router-dom'
2
+
3
+ // Shown for any address the app has no route for. `belt deploy frontend`
4
+ // prerenders it to 404.html, which CloudFront serves with HTTP 404, so crawlers
5
+ // and agents can tell a missing page from a real one.
6
+ function NotFound() {
7
+ return (
8
+ <main style={{ maxWidth: '36rem', margin: '4rem auto', padding: '0 1.5rem', fontFamily: 'system-ui, sans-serif' }}>
9
+ <h1>Page not found</h1>
10
+ <p>There is no page at this address.</p>
11
+ <p>
12
+ <Link to="/">Back to the home page</Link>
13
+ </p>
14
+ </main>
15
+ )
16
+ }
17
+
18
+ export default NotFound
@@ -11,6 +11,10 @@
11
11
  // - Every public route gets an entry in `pages` with a specific title and a
12
12
  // one- or two-sentence description that says plainly what the page is.
13
13
  // - Login-gated or app-only routes go in `privatePaths` (disallowed in robots.txt).
14
+ // - An address that is neither a page here nor a route of the app answers HTTP
15
+ // 404 with the app's "not found" page. The app's routes are read from its
16
+ // <Route path="/..."> declarations; a route declared any other way needs its
17
+ // prefix in `privatePaths` too, or a fresh load of it answers 404.
14
18
  // - Only `indexableEnvironments` are indexable. Every other environment, and
15
19
  // local builds, ship `Disallow: /` and <meta name="robots" content="noindex">
16
20
  // so dev and ephemeral environments never end up in search results.
@@ -79,9 +79,22 @@ resource "aws_cloudfront_distribution" "<%= @tf_name %>" {
79
79
  forward = "none"
80
80
  }
81
81
  }
82
+
83
+ # Real 404s — see the router resources below.
84
+ function_association {
85
+ event_type = "viewer-request"
86
+ function_arn = aws_cloudfront_function.<%= @tf_name %>_route_request.arn
87
+ }
88
+
89
+ function_association {
90
+ event_type = "viewer-response"
91
+ function_arn = aws_cloudfront_function.<%= @tf_name %>_route_response.arn
92
+ }
82
93
  }
83
94
 
84
- # SPA routing — serve index.html for 404/403
95
+ # SPA fallback — serve index.html for a missing object. The router function
96
+ # sends unknown addresses to /404.html itself; this is what a path gets before
97
+ # routes have been published, and what a missing file (/assets/gone.js) gets.
85
98
  custom_error_response {
86
99
  error_code = 404
87
100
  response_code = 200
@@ -114,6 +127,35 @@ resource "aws_cloudfront_distribution" "<%= @tf_name %>" {
114
127
  }
115
128
  }
116
129
 
130
+ # Real 404s. `belt deploy frontend` publishes the app's routes (frontend
131
+ # src/seo.js: `pages` and `privatePaths`) to this KeyValueStore, and the router
132
+ # function serves a page from its prerendered object, an app route from
133
+ # index.html, and anything else from /404.html with status 404. The same code
134
+ # runs on both events; <%= Belt::CLI::FrontendRoutes::ROUTER_FILE %> is belt's (refresh it with
135
+ # `belt frontend router`).
136
+ resource "aws_cloudfront_key_value_store" "<%= @tf_name %>_routes" {
137
+ name = "${var.app_name}-${var.environment}-<%= @bucket_slug %>-routes"
138
+ comment = "Routes published by belt deploy frontend"
139
+ }
140
+
141
+ resource "aws_cloudfront_function" "<%= @tf_name %>_route_request" {
142
+ name = "${var.app_name}-${var.environment}-<%= @bucket_slug %>-route-req"
143
+ runtime = "cloudfront-js-2.0"
144
+ comment = "Send each address to its page, the app, or the 404 page"
145
+ publish = true
146
+ key_value_store_associations = [aws_cloudfront_key_value_store.<%= @tf_name %>_routes.arn]
147
+ code = file("${path.module}/<%= Belt::CLI::FrontendRoutes::ROUTER_FILE %>")
148
+ }
149
+
150
+ resource "aws_cloudfront_function" "<%= @tf_name %>_route_response" {
151
+ name = "${var.app_name}-${var.environment}-<%= @bucket_slug %>-route-res"
152
+ runtime = "cloudfront-js-2.0"
153
+ comment = "Answer 404 for the 404 page"
154
+ publish = true
155
+ key_value_store_associations = [aws_cloudfront_key_value_store.<%= @tf_name %>_routes.arn]
156
+ code = file("${path.module}/<%= Belt::CLI::FrontendRoutes::ROUTER_FILE %>")
157
+ }
158
+
117
159
  # S3 bucket policy — CloudFront OAC access only
118
160
  resource "aws_s3_bucket_policy" "<%= @tf_name %>" {
119
161
  bucket = aws_s3_bucket.<%= @tf_name %>.id
@@ -272,6 +272,11 @@ answer engines (`belt explain frontend`). When you add or change a public page:
272
272
  - Add it to `frontend/src/seo.js` → `pages` with a specific `title` and a one- or
273
273
  two-sentence `description` that names what the page is and who it's for.
274
274
  - Put login-gated routes in `privatePaths` (they're disallowed in `robots.txt`).
275
+ - An address that is neither a page nor a route of the app answers HTTP 404. Belt
276
+ reads the app's routes from `<Route path="/...">` in `frontend/src`, so a normal
277
+ new route needs nothing. A route declared another way (nested relative path,
278
+ router config object) needs its prefix in `privatePaths`, or a fresh load of it
279
+ answers 404; `frontend/dist/.belt-routes.json` shows what belt found.
275
280
  - Keep the page's content in the rendered markup — no `window`/`document`/
276
281
  `localStorage` during render (use `useEffect`), and no content that only appears
277
282
  after an API call if crawlers need to see it.
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: belt
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.6.10
4
+ version: 0.6.12
5
5
  platform: ruby
6
6
  authors:
7
7
  - Stowzilla
@@ -110,6 +110,7 @@ files:
110
110
  - lib/belt/authentication/configuration.rb
111
111
  - lib/belt/authentication/controller.rb
112
112
  - lib/belt/authentication/model_macro.rb
113
+ - lib/belt/authentication/token_verifier.rb
113
114
  - lib/belt/cli.rb
114
115
  - lib/belt/cli/apex_dns_sync.rb
115
116
  - lib/belt/cli/app_detection.rb
@@ -139,6 +140,7 @@ files:
139
140
  - lib/belt/cli/frontend_env_map.rb
140
141
  - lib/belt/cli/frontend_prerender.rb
141
142
  - lib/belt/cli/frontend_registry.rb
143
+ - lib/belt/cli/frontend_routes.rb
142
144
  - lib/belt/cli/frontend_setup_command.rb
143
145
  - lib/belt/cli/generate_command.rb
144
146
  - lib/belt/cli/generator_registry.rb
@@ -181,6 +183,7 @@ files:
181
183
  - lib/belt/docs/testing.md
182
184
  - lib/belt/errors.rb
183
185
  - lib/belt/frontend/prerender.mjs
186
+ - lib/belt/frontend/router.js
184
187
  - lib/belt/helpers/cors_origin.rb
185
188
  - lib/belt/helpers/error_logging.rb
186
189
  - lib/belt/helpers/response.rb
@@ -222,6 +225,7 @@ files:
222
225
  - lib/templates/frontend/react/src/lib/apiClient.js.erb
223
226
  - lib/templates/frontend/react/src/main.jsx
224
227
  - lib/templates/frontend/react/src/pages/Home.jsx.erb
228
+ - lib/templates/frontend/react/src/pages/NotFound.jsx
225
229
  - lib/templates/frontend/react/src/seo.js.erb
226
230
  - lib/templates/frontend/react/vite.config.js
227
231
  - lib/templates/frontend_infra/frontend.tf.erb