Selfie has three deployments, the site and the app in Cloudflare account 0a95e814ccf2b6a95d2dc3bea0a4a2b4:
| What | Where | Source | Deployed by |
|---|---|---|---|
| The landing page | selfie.dev, Pages project selfie-landing |
site/ |
.github/workflows/site.yml, on every push to main that touches site/ |
| The npm package | @diffplug/selfie on npm |
cli/, store/, render/, ui/ |
.github/workflows/npm-release.yml, on a vX.Y.Z tag |
| The app | app.selfie.dev, Worker selfie-app, with built Storybooks on selfieusercontent.com and a redirect from hackathon.selfie.dev |
ui/, store/ |
.github/workflows/app-production.yml, run by hand, then tagged app/YYYY-MM-DD |
lib.selfie.dev, kdoc.selfie.dev, and pydoc.selfie.dev belong to the earlier library (diffplug/selfie-lib), on their own Pages projects. Never move them here.
The app keeps its data in three places:
- D1: one database per project,
selfie-project-<repository id>, bound inui/wrangler.toml. A project sets up its own schema on first use. - R2: bucket
selfie-blobs, one prefix per project (docs/specs/store.md→ R2 adapter). A project's D1 lists the images it holds, so never delete their bytes without their rows (docs/specs/store.md→ Storage). - Postgres on Neon: sign-in only, through pgstencil, reached by the Worker through an uncached Hyperdrive. Its schema is
@pgstencil/auth's migrations, listed inui/pgstencil.json.
-
The site: merge to
main. The workflow tests the site locally, publishessite/public/, and testshttps://selfie.dev. -
The npm package: on a branch, move what's under
## [Unreleased]inCHANGELOG.mdinto a new## [X.Y.Z] - YYYY-MM-DDbelow it, and merge that pull request. Then, as an admin, tag the merge commit and push the tag, which runs npm release:git fetch origin && git tag -a vX.Y.Z -m "@diffplug/selfie X.Y.Z" origin/main && git push origin vX.Y.Z
What it checks before it stages the package is
docs/specs/cli.md→ Package. It only stages it, so to publish, approve it with your 2FA: on the package's page on npmjs.com, or withnpm stage list @diffplug/selfieandnpm stage approve <stage-id>. A failed run publishes nothing: fix it, delete the tag (git push origin :vX.Y.Z, as an admin), and tag again. To build the package on a laptop instead,pnpm build:ui && pnpm npm-package <version> <dir>. -
The app: every push to
mainthat touches the app runs its tests. To release, run App production release from the Actions tab onmain, orgh workflow run app-production.yml --ref main. It checks the Hyperdrive, the Worker's secrets, and that no bucket has a public URL, applies sign-in's migrations, deploys, and then checks the live origins withui/scripts/production.mjs smoke. When they pass, it tags the commit it deployed (docs/specs/cloud.md→ Releases). If only the tag job failed, rerun it alone, and it makes the same tag. Migrations are append-only and run before the new Worker serves, so the Worker that's live during a release must work with the new schema.
From a laptop, the same steps are node ui/scripts/production.mjs preflight|deploy|smoke, with the environment the workflow sets.
A release that changes the store's schema version (docs/specs/renders.md → Schema) changes both D1 and the CLI's SQLite schema, and a store at another version is refused until it's reset. Version 1 held hashes, SHAs, and batch IDs as bytes, and made every table STRICT. Version 2 replaced rejections with undoing an approval, as decisions.undone. To keep published batches and approvals, use a machine that still has their local store and the previous CLI.
- Take the old Worker offline. Run the SQL below on each project D1 database, then deploy the new Worker. The reset discards batch history, decisions, the names they share, and image and built Storybook metadata. The Worker recreates the tables on first use. The image and Storybook bytes in R2 can be reused.
- Once the new Worker is serving, use the previous CLI and its intact local store to run
selfie push <batch-id>for each finished, clean batch you want to republish. Use credentials with decision permission to include decisions. A push made before the D1 reset would be erased by step 1. - After those pushes succeed, stop local Selfie processes and run the same SQL on each affected
$SELFIE_HOME/<slug>/store.db(default~/.config/selfie/<slug>/store.db). Then use the upgraded CLI. To restore published decisions reachable from HEAD, runselfie pull. Runselfie reviewto record a fresh local batch. If all old batch history is disposable, skip step 2.
DROP TABLE IF EXISTS decisions;
DROP TABLE IF EXISTS renders;
DROP TABLE IF EXISTS commit_parents;
DROP TABLE IF EXISTS render_batches;
DROP TABLE IF EXISTS commits;
DROP TABLE IF EXISTS images;
DROP TABLE IF EXISTS built_storybooks;
DROP TABLE IF EXISTS environments;
DROP TABLE IF EXISTS stories;
DROP TABLE IF EXISTS actors;
DROP TABLE IF EXISTS schema_version;
DROP TABLE IF EXISTS note_messages;
DROP TABLE IF EXISTS note_waiters;
DROP TABLE IF EXISTS note_sessions;
DROP TABLE IF EXISTS notes;The notes tables only matter locally, where no CLI reads them any more, and D1 never had them. The table reset preserves render_keys, whose old batch IDs may refer to discarded batches. Deleting the whole store.db also deletes the render keys.
Once, after the app is deployed from a main that includes #120. Until then, each project in R2 holds a diff image and a PixelDiff for every pair a push sent, at projects/<repository id>/diffs/<current>/<golden>.png and .json, which no Worker since reads or writes. Each pair's record is at projects/<repository id>/derived/, and stays. No D1 row refers to anything under diffs/, so its bytes go alone.
-
Check that nothing live reads it. The newest
app/YYYY-MM-DDtag must include #120, and the code it deployed must name nodiffs/key:git fetch origin --tags tag=$(git tag --list 'app/*' --sort=-creatordate | head -1) git merge-base --is-ancestor "$(gh pr view 120 --json mergeCommit -q .mergeCommit.oid)" "$tag" && echo "includes it" git grep -n '"diffs/\|`diffs/' "$tag" -- store/src ui/src
The last command prints nothing. A
selfie pushfrom 0.1.0 still asks fordiffs/needed, which answersnot-found, so it writes nothing there either. -
Signed in to Wrangler as an account admin (
pnpm --dir ui exec wrangler login), since the deploy token only reads R2, add a rule for each project that expires everything under itsdiffs/:for id in $(pnpm --dir ui exec wrangler d1 list --json | jq -r '.[].name | select(startswith("selfie-project-")) | ltrimstr("selfie-project-")'); do pnpm --dir ui exec wrangler r2 bucket lifecycle add selfie-blobs "delete-diffs-$id" "projects/$id/diffs/" --expire-days 1 --force done
The trailing
/keeps each rule todiffs/, and away fromderived/and the images. R2 applies a rule within a day or so of adding it. -
Once R2 → selfie-blobs → Objects in the dashboard shows nothing under any
projects/<id>/diffs/, remove the rules, so none outlives its reason:wrangler r2 bucket lifecycle list selfie-blobsnames them, andpnpm --dir ui exec wrangler r2 bucket lifecycle remove selfie-blobs --name delete-diffs-<id>removes each.
Done once:
- On npmjs.com, the
diffplugorganization holds the package. npm only lets a package that exists trust a workflow, so publish the first version by hand: build it as above, thennpm loginandnpm publish --access publicin that directory. - In the package's settings on npmjs.com, add a trusted publisher: GitHub Actions,
diffplug/selfie, workflownpm-release.yml, environmentnpm-production, with neither Allow npm publish nor Allow npm dist-tag, so it can only stage. - Create the GitHub environment
npm-production, limited to tags matchingv*.
Done once. Only an admin may create, move, or delete a tag, except that the selfie-tagger App may create app/ tags.
-
Create a GitHub App in the
diffplugorganization namedselfie-tagger, with no webhook and only Contents: Read and write on repositories, install it ondiffplug/selfiealone, and generate a private key. -
Create the GitHub environment
app-release-tag, with the App's values in Secrets and settings. Keep the key in the password manager, and delete the downloaded file. -
Set the tag rulesets to these, where admin is the repository role
5, and<APP_ID>is the App's numeric App ID, on its settings page:Ruleset Tags Refuses Except to Tag operationsall but refs/tags/app/**creation, update, deletion an admin App tag creationrefs/tags/app/**creation an admin, and selfie-taggerApp tag historyrefs/tags/app/**update, deletion an admin Tag operationsexists already, as ruleset27667494. Withgh:gh api -X PUT repos/diffplug/selfie/rulesets/27667494 --input - <<< '{"conditions":{"ref_name":{"include":["~ALL"],"exclude":["refs/tags/app/**"]}},"rules":[{"type":"creation"},{"type":"update"},{"type":"deletion"}]}' gh api -X POST repos/diffplug/selfie/rulesets --input - <<< '{"name":"App tag creation","target":"tag","enforcement":"active","conditions":{"ref_name":{"include":["refs/tags/app/**"],"exclude":[]}},"rules":[{"type":"creation"}],"bypass_actors":[{"actor_type":"RepositoryRole","actor_id":5,"bypass_mode":"exempt"},{"actor_type":"Integration","actor_id":<APP_ID>,"bypass_mode":"always"}]}' gh api -X POST repos/diffplug/selfie/rulesets --input - <<< '{"name":"App tag history","target":"tag","enforcement":"active","conditions":{"ref_name":{"include":["refs/tags/app/**"],"exclude":[]}},"rules":[{"type":"update"},{"type":"deletion"}],"bypass_actors":[{"actor_type":"RepositoryRole","actor_id":5,"bypass_mode":"exempt"}]}'
selfie-app keeps what it logs in Workers Logs ([observability] in ui/wrangler.toml), for 3 days on the Workers Free plan and 7 on Paid: in the dashboard, Workers & Pages → selfie-app → Logs. It doesn't keep a line for every request, only what the code logs, which is mostly errors.
Every error a person sees comes with an error code, such as Error code: 7K3MQ9XP, and its log line starts Error 7K3MQ9XP:. To find it, search the logs for the code. A server error's line has the error and its stack. To watch live instead, pnpm --dir ui exec wrangler tail selfie-app.
GitHub environment app-production, limited to the main branch:
| Name | Kind | What |
|---|---|---|
CLOUDFLARE_API_TOKEN |
secret | The deploy token, below |
DATABASE_URL |
secret | The Neon migration role's direct URL (not the pooler, and not Hyperdrive) |
HYPERDRIVE_ID |
variable | The Hyperdrive the Worker reaches Postgres through |
GitHub environment app-release-tag, limited to the main branch, which only the tag job of app-production.yml enters:
| Name | Kind | What |
|---|---|---|
TAGGER_CLIENT_ID |
variable | The selfie-tagger App's Client ID |
TAGGER_PRIVATE_KEY |
secret | The selfie-tagger App's private key |
GitHub environment site-production, limited to the main branch:
| Name | Kind | What |
|---|---|---|
CLOUDFLARE_PAGES_TOKEN |
secret | The Pages token, below |
Repository-wide:
| Name | Kind | What |
|---|---|---|
CLOUDFLARE_ACCOUNT_ID |
variable | 0a95e814ccf2b6a95d2dc3bea0a4a2b4 |
SELFIE_UPLOAD_TOKEN |
secret | What this repository's own CI uploads with, as on every repository the app hosts |
The two Cloudflare tokens are kept nowhere else. To rotate one, create a token with the same permissions, set it with pbpaste | gh secret set <NAME> --env <environment>, and delete the old one. Every repository-wide secret is listed in tend's secrets.allowed in .config/tend.yaml, and uvx tend@latest check flags any other.
The deploy token holds exactly: Workers Scripts Edit, Account Settings Read, Hyperdrive Read, D1 Read, and Workers R2 Storage Read on the account, and Workers Routes Edit, DNS Edit, and Zone Read on selfie.dev and selfieusercontent.com. The Pages token holds Pages Edit on the account, and nothing else.
Worker secrets on selfie-app, set with pnpm --dir ui exec wrangler secret put <NAME>, which preflight checks are all there. Cloudflare can't show them again, so keep each in the password manager:
| Name | What |
|---|---|
AUTH_SECRET |
32 or more random characters, for pgstencil's cookies and keys; changing it signs everyone out |
GITHUB_CLIENT_ID, GITHUB_CLIENT_SECRET |
The GitHub App's OAuth client, for signing in |
GITHUB_APP_ID, GITHUB_APP_PRIVATE_KEY |
The GitHub App itself, for commit statuses and checking that a pushed commit is on GitHub |
SELFIE_UPLOAD_TOKEN |
CI's bearer token: uploads, and can't decide anything |
SELFIE_WRITER_TOKEN |
The writer's bearer token, for SELFIE_TOKEN in their own selfie push, pull, and approve |
Done once, in this order.
-
Rename
diffplug/selfie-hackathontodiffplug/selfie. GitHub then redirects the old name, and the Worker answers it too (docs/specs/cloud.md→ Projects). Update local checkouts withgit remote set-url origin https://github.com/diffplug/selfie, and point other repositories' workflows atdiffplug/selfie/.github/actions/selfie@main. -
In the GitHub App's settings (Selfie.dev,
github.com/apps/selfie-dev, App ID5607634; "Selfie" alone is reserved by GitHub), then under Identifying and authorizing users:- set the Callback URL to exactly
https://app.selfie.dev/api/auth/callback/github - leave Request user authorization (OAuth) during installation off
- generate a client secret; it and the app's Client ID are
GITHUB_CLIENT_SECRETandGITHUB_CLIENT_ID
Its permissions are
statuses: write,contents: read, and Pull requests: Read-only on repositories, Email addresses: Read-only on accounts, and no webhook. A permission added later takes effect only once each installation's owner accepts it, under the organization's Settings → GitHub Apps → Selfie.dev; until then, a project's page lists no pull requests. Without the email permission, GitHub refuses pgstencil's read of/user/emails, and every sign-in fails with a 500. - set the Callback URL to exactly
-
Create the
app-productionandsite-productionenvironments, each limited tomain, and set the secrets and variables above.
-
Create a project
selfieon PostgreSQL 18, with a databaseselfie, and turn on point-in-time restore. Keep it apart from Dormouse's. -
Its owner role is the migration role: put its direct URL in
DATABASE_URL, then apply the schema once:DATABASE_URL=… pnpm --dir ui db:migrate, anddb:validate. -
Create the runtime role,
selfie_app, with only the DML sign-in's tables need, byui/scripts/runtime-role.mjsas the owner. It runs SQL over the encrypted connection, since Neon's console would give the roleneon_superuser. It takes both values from the environment, and running it again sets a new password:DATABASE_URL=… SELFIE_APP_PASSWORD="$(openssl rand -hex 24)" node ui/scripts/runtime-role.mjs
-
Add
selfieusercontent.comas a zone, and point its registrar's nameservers at Cloudflare. -
Create the R2 bucket, with its
r2.devaccess left off (docs/specs/access.md→ Who can do what):pnpm --dir ui exec wrangler r2 bucket create selfie-blobs --location wnam. -
Create the Hyperdrive as
selfie_app, with caching off, since a sign-out must be seen at once:pnpm --dir ui exec wrangler hyperdrive create selfie-auth --caching-disabled --connection-string='postgres://selfie_app:…@<neon host>/selfie?sslmode=require'
Use Neon's direct host, not its
-poolerone, since Hyperdrive pools. Its ID isHYPERDRIVE_ID.ui/wrangler.tomlkeeps a placeholder, whichdeployreplaces. -
Set every Worker secret above on
selfie-app. CopyGITHUB_APP_ID,GITHUB_APP_PRIVATE_KEY, andSELFIE_UPLOAD_TOKENfrom the hackathon's Worker's entries in the password manager. GenerateAUTH_SECRETandSELFIE_WRITER_TOKENfresh, withopenssl rand -hex 32. -
Create the two API tokens above.
The hackathon's Worker, selfie-hackathon, holds hackathon.selfie.dev as a custom domain, and selfie-app claims it.
- In the dashboard, remove
hackathon.selfie.devfromselfie-hackathon's domains. The old URL is down until the next step finishes. - Run App production release. Its smoke checks cover the new origins, the redirect, and starting a sign-in.
- Sign in at
https://app.selfie.dev/sign-in, and check a project page says you can approve. - Push a commit, and check its
selfiestatus links toapp.selfie.dev. - Delete the
selfie-hackathonWorker, but not its D1 databases, which areselfie-app's now.