Repository navigation
239 lines (220 loc) · 10.7 KB
/
Copy pathdeploy.yml
File metadata and controls
239 lines (220 loc) · 10.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
name: Deploy
on:
workflow_run:
workflows: [CI]
branches: [main]
types:
- completed
workflow_dispatch:
permissions:
contents: read
# One production deploy at a time; a newer pending run replaces an older
# pending one, but a running deploy (and its migrations) is never cancelled.
concurrency:
group: deploy-production
cancel-in-progress: false
jobs:
deploy:
# workflow_run: only after a successful CI run for a push to this repo's
# main. The `branches: [main]` filter on the trigger already excludes other
# branches (including tds/**), and `head_branch == 'main'` below re-asserts
# it at the job level so a non-main CI run can never reach production.
# `head_repository` also blocks fork PRs whose branch happens to be "main".
# workflow_dispatch: only from main.
if: >-
(github.event_name == 'workflow_dispatch' && github.ref == 'refs/heads/main') ||
(github.event.workflow_run.conclusion == 'success' &&
github.event.workflow_run.event == 'push' &&
github.event.workflow_run.head_branch == 'main' &&
github.event.workflow_run.head_repository.full_name == github.repository)
runs-on: ubuntu-latest
environment:
name: production
url: ${{ vars.APP_URL }}
env:
TURBO_TELEMETRY_DISABLED: "1"
WRANGLER_SEND_METRICS: "false"
steps:
# Deploy exactly the commit CI verified, not whatever main points to now.
- uses: actions/checkout@v6
with:
ref: ${{ github.event.workflow_run.head_sha || github.sha }}
persist-credentials: false
- uses: pnpm/action-setup@v6
- uses: actions/setup-node@v6
with:
node-version: 24
cache: pnpm
- name: Install dependencies
run: pnpm install --frozen-lockfile
# Runs before Inject so the inject step can write the resolved prefix
# into wrangler.toml: the GitHub variable is the single source of truth
# for the Worker's TABLE_PREFIX binding. Depends only on vars.TABLE_PREFIX.
- name: Resolve TABLE_PREFIX (three-state)
id: prefix
env:
TABLE_PREFIX: ${{ vars.TABLE_PREFIX }}
run: |
resolved="$(node --disable-warning=MODULE_TYPELESS_PACKAGE_JSON .github/scripts/resolve-table-prefix.mjs)"
echo "resolved TABLE_PREFIX: ${resolved:-<empty>}"
echo "table_prefix=${resolved}" >> "$GITHUB_OUTPUT"
- name: Inject resource IDs
env:
D1_DATABASE_ID: ${{ secrets.D1_DATABASE_ID }}
D1_DATABASE_NAME: ${{ vars.D1_DATABASE_NAME }}
KV_NAMESPACE_ID: ${{ secrets.KV_NAMESPACE_ID }}
CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
TABLE_PREFIX: ${{ steps.prefix.outputs.table_prefix }}
run: |
check() {
if ! [[ "${!1}" =~ $2 ]]; then
echo "::error::Variable $1 is missing or malformed (expected $2)"
exit 1
fi
}
check D1_DATABASE_ID '^[0-9a-fA-F-]{32,36}$'
check D1_DATABASE_NAME '^[A-Za-z0-9_-]+$'
check KV_NAMESPACE_ID '^[0-9a-fA-F]{32}$'
check CLOUDFLARE_ACCOUNT_ID '^[0-9a-fA-F]{32}$'
f=apps/worker/wrangler.toml
sed -i "s/D1_DATABASE_ID_PLACEHOLDER/${D1_DATABASE_ID}/g" "$f"
sed -i "s/D1_DATABASE_NAME_PLACEHOLDER/${D1_DATABASE_NAME}/g" "$f"
sed -i "s/KV_NAMESPACE_ID_PLACEHOLDER/${KV_NAMESPACE_ID}/g" "$f"
sed -i "s/CLOUDFLARE_ACCOUNT_ID_PLACEHOLDER/${CLOUDFLARE_ACCOUNT_ID}/g" "$f"
# TABLE_PREFIX is config-managed: the resolved GitHub variable
# (default 'hop', 'none' → empty string) becomes the Worker binding.
sed -i "s/TABLE_PREFIX_PLACEHOLDER/${TABLE_PREFIX}/g" "$f"
if grep -q '_PLACEHOLDER' "$f"; then
echo "::error::Unreplaced placeholders remain in $f"
exit 1
fi
# Build before touching the database so a broken build never leaves a
# migrated schema behind.
- name: Build
run: pnpm build
# Order: migrate first, then deploy code. Migrations must therefore be
# backward compatible with the code currently live (expand → deploy →
# contract: add columns/tables now, drop old ones in a later release).
- name: Prepare D1 migrations
id: d1
working-directory: apps/worker
env:
CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
TABLE_PREFIX: ${{ steps.prefix.outputs.table_prefix }}
run: bash ../../.github/scripts/d1-prepare-migrations.sh
- name: Apply D1 migrations
if: steps.d1.outputs.mode == 'apply'
working-directory: apps/worker
env:
CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
run: pnpm run db:migrate
# TABLE_PREFIX in use: apply the prefix-aware migrations from
# src/lib/migrations.ts (the same ones POST /setup runs).
- name: Apply prefixed D1 migrations
if: steps.d1.outputs.mode == 'prefixed'
working-directory: apps/worker
env:
CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
TABLE_PREFIX: ${{ steps.prefix.outputs.table_prefix }}
run: bash ../../.github/scripts/d1-prefixed-migrations.sh
# Fail-closed: refuse to deploy if a required runtime secret is missing
# or empty, so an empty value can never overwrite a live Cloudflare
# Secret. The JSON lives only in $RUNNER_TEMP (mode 600) and is never
# written to the repository workspace.
#
# WAKER_SIGNING_KEY is optional and mode-free: when the repository Secret
# exists it is injected (the callback receiver is then enabled); when it
# does not, the deploy still succeeds and /_waker/execute fails closed with
# 500 signing_key_missing. The resolved state is handed to the verify step
# so a version that was supposed to carry the key cannot silently ship
# without it. Waker delivers the nightly cleanup, so an absent key means
# that nothing runs it — the verify step warns about exactly that.
- name: Write secrets file
id: secrets
env:
JWT_SECRET: ${{ secrets.JWT_SECRET }}
"SETUP_SECRET": ${{ secrets.SETUP_SECRET }}
TOTP_ENCRYPTION_KEY: ${{ secrets.TOTP_ENCRYPTION_KEY }}
WAKER_SIGNING_KEY: ${{ secrets.WAKER_SIGNING_KEY }}
run: |
set -euo pipefail
for name in JWT_SECRET SETUP_SECRET TOTP_ENCRYPTION_KEY; do
if [ -z "$(printenv "$name" 2>/dev/null || true)" ]; then
echo "::error::GitHub Secret '$name' is empty or missing; aborting deploy (fail-closed)."
exit 1
fi
done
waker_key="$(node --disable-warning=MODULE_TYPELESS_PACKAGE_JSON -e '
const fs = require("node:fs");
const path = require("node:path");
const file = path.join(process.env.RUNNER_TEMP, "secrets.json");
const secrets = {
JWT_SECRET: process.env.JWT_SECRET,
"SETUP_SECRET": process.env["SETUP_SECRET"],
TOTP_ENCRYPTION_KEY: process.env.TOTP_ENCRYPTION_KEY,
};
// The signing key is the only switch of the callback: injected when
// the repository Secret exists, otherwise the callback answers 500
// signing_key_missing and nothing schedules the nightly cleanup.
const key = (process.env.WAKER_SIGNING_KEY ?? "").trim();
if (key.length > 0) {
secrets.WAKER_SIGNING_KEY = key;
} else {
console.warn("WAKER_SIGNING_KEY is not configured — /_waker/execute will answer 500 signing_key_missing until it is set, and nothing else schedules the nightly cleanup.");
}
fs.writeFileSync(
file,
JSON.stringify(secrets, null, 2) + "\n",
{ mode: 0o600 },
);
process.stdout.write(key.length > 0 ? "bound" : "absent");
')"
chmod 600 "$RUNNER_TEMP/secrets.json"
echo "waker_signing_key=${waker_key}"
if [ -n "${GITHUB_OUTPUT:-}" ]; then
echo "waker_signing_key=${waker_key}" >> "$GITHUB_OUTPUT"
fi
# Web and worker were built above; deploy the worker directly so wrangler
# can record the uploaded version ID for the verification step.
#
# Invoke wrangler itself rather than `pnpm run deploy`: pnpm forwards a
# literal `--` to the script, and wrangler's yargs then treats everything
# after it as positional arguments, silently dropping --secrets-file. The
# worker's own `deploy` script is just `wrangler deploy` (the build ran in
# the Build step above), so this drops no pre-step — and the flag now
# reaches wrangler. Verify deployment below asserts the secrets landed.
- name: Deploy
working-directory: apps/worker
env:
CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
WRANGLER_OUTPUT_FILE_PATH: ${{ runner.temp }}/wrangler-output.ndjson
run: pnpm exec wrangler deploy --secrets-file "$RUNNER_TEMP/secrets.json"
# Checked through the Cloudflare API rather than the public hostname, so
# the zone's bot protection can't make it inconclusive.
- name: Verify deployment
id: verify
working-directory: apps/worker
env:
CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
WRANGLER_OUTPUT_FILE_PATH: ${{ runner.temp }}/wrangler-output.ndjson
TABLE_PREFIX: ${{ steps.prefix.outputs.table_prefix }}
WAKER_SIGNING_KEY_EXPECTED: ${{ steps.secrets.outputs.waker_signing_key }}
run: bash ../../.github/scripts/verify-deployment.sh
# Probes vars.APP_URL when it is configured; otherwise resolves the
# Worker's workers.dev address through the Cloudflare API (the account's
# workers.dev subdomain cannot be derived from the account ID), so the
# smoke test no longer needs a configured APP_URL.
- name: Smoke test
id: smoke
env:
APP_URL: ${{ vars.APP_URL }}
ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
CHECK_DB: ${{ steps.d1.outputs.mode == 'apply' || steps.d1.outputs.mode == 'prefixed' }}
run: bash .github/scripts/smoke-test.sh
- name: Rollback hint
if: failure() && (steps.verify.outcome == 'failure' || steps.smoke.outcome == 'failure')
run: |
echo "::error::Post-deploy verification failed. To roll back the Worker to the previous version:"
echo " cd apps/worker && pnpm exec wrangler rollback"
echo "D1 migrations are NOT rolled back automatically; they are designed to stay compatible with the previous code."