Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.
Ruby b2b-commercee-commerceecommerceecommerce-apiecommerce-frameworkecommerce-platformheadlessheadless-commerceheadless-ecommercemarketplacemulti-tenantmulti-vendormulti-vendor-ecommerceopen-sourcespree-commerce
Fix: new projects encrypt secrets at rest out of the box (#14710)
Damian Legawiec36df7c72be7b
diff --git a/.changeset/cli-encryption-init.md b/.changeset/cli-encryption-init.mdnew file mode 100644index 0000000000..32f6f14925--- /dev/null+++ b/.changeset/cli-encryption-init.md@@ -0,0 +1,5 @@+---+"@spree/cli": minor+---++New `spree encryption init` command adds Active Record encryption keys (`ACTIVE_RECORD_ENCRYPTION_PRIMARY_KEY`, `_DETERMINISTIC_KEY`, `_KEY_DERIVATION_SALT`) to an existing project's `.env`, so Spree encrypts webhook signing secrets, payment gateway customer IDs and OAuth tokens at rest instead of storing them in plain text. It never overwrites keys that are already set. `spree encryption init --print` only prints a fresh set, for your production host.diff --git a/.changeset/create-spree-app-encryption-keys.md b/.changeset/create-spree-app-encryption-keys.mdnew file mode 100644index 0000000000..df20ff70aa--- /dev/null+++ b/.changeset/create-spree-app-encryption-keys.md@@ -0,0 +1,5 @@+---+"create-spree-app": minor+---++New projects get Active Record encryption keys: the generated `.env` now includes `ACTIVE_RECORD_ENCRYPTION_PRIMARY_KEY`, `ACTIVE_RECORD_ENCRYPTION_DETERMINISTIC_KEY` and `ACTIVE_RECORD_ENCRYPTION_KEY_DERIVATION_SALT`, so webhook signing secrets, payment gateway customer IDs and OAuth tokens are encrypted at rest out of the box instead of being stored in plain text.diff --git a/docs/developer/cli/quickstart.mdx b/docs/developer/cli/quickstart.mdxindex 1307b0b0fd..94dfb5dd70 100644--- a/docs/developer/cli/quickstart.mdx+++ b/docs/developer/cli/quickstart.mdx@@ -195,6 +195,17 @@ spree api-key create --name "Admin" --type secret --scopes read_all # Adminspree api-key revoke <id> # Revoke a key```+### `spree encryption init`++Generate [Active Record encryption](/developer/deployment/environment_variables#active-record-encryption) keys — Spree encrypts webhook signing secrets, payment gateway customer IDs and OAuth tokens with them. New projects already have keys; use this for projects created before they were generated at setup.++```bash+spree encryption init # Add ACTIVE_RECORD_ENCRYPTION_* keys to the project's .env+spree encryption init --print # Print a fresh set without writing anything (e.g. for your hosting provider)+```++It never overwrites keys `.env` already sets, and there is no `--force`: changing the keys makes data encrypted with them unreadable. Afterwards, recreate the containers so they load the new `.env` (`spree update`, or `spree dev` for an ejected project — `spree restart` keeps the old environment), and back the keys up in your secret manager.+### `spree api`Call the Admin API with generic `get`/`post`/`patch`/`delete` commands — zero-config inside a project (a read-only key is minted on first use), env vars or profiles for remote stores. See [Admin API from the CLI](/developer/cli/admin-api) for the full guide.diff --git a/docs/developer/core-concepts/payments.mdx b/docs/developer/core-concepts/payments.mdxindex b3c9ff2587..92a55e7fd4 100644--- a/docs/developer/core-concepts/payments.mdx+++ b/docs/developer/core-concepts/payments.mdx@@ -662,7 +662,7 @@ Maps a Spree customer to their provider-specific customer profile. This enables| `payment_method_id` | The gateway this customer belongs to | `1` || `customer_id` | The Spree customer | `42` |-A customer has at most one record per payment method, and `profile_id` is encrypted with Active Record Encryption where it is configured.+A customer has at most one record per payment method, and `profile_id` is encrypted with [Active Record encryption](/developer/deployment/environment_variables#active-record-encryption) where it is configured.<Note>This one is internal — the API does not expose it. It is listed here becausediff --git a/docs/developer/create-spree-app/quickstart.mdx b/docs/developer/create-spree-app/quickstart.mdxindex c13ab7cf76..8a848fa8b6 100644--- a/docs/developer/create-spree-app/quickstart.mdx+++ b/docs/developer/create-spree-app/quickstart.mdx@@ -67,7 +67,7 @@ my-store/│ ├── seller-dashboard/ # Seller panel, for marketplaces (React)│ └── storefront/ # Next.js storefront (unless --no-storefront)│ └── .env.local # API URL + publishable key-├── .env # SECRET_KEY_BASE, SPREE_PORT, SPREE_VERSION_TAG, SPREE_SAMPLE_DATA+├── .env # SECRET_KEY_BASE, encryption keys, SPREE_PORT, SPREE_VERSION_TAG, SPREE_SAMPLE_DATA├── .spree/ # CLI credentials — gitignored, created on first run├── docker-compose.yml # Spree backend (prebuilt image) + Postgres + Meilisearch├── docker-compose.dev.yml # Alternative: build from local server/diff --git a/docs/developer/deployment/aws.mdx b/docs/developer/deployment/aws.mdxindex 895a2d1b57..855b55a6c0 100644--- a/docs/developer/deployment/aws.mdx+++ b/docs/developer/deployment/aws.mdx@@ -49,6 +49,11 @@ services:environment:DATABASE_URL: postgres://spree:[email protected]:5432/spree_productionSECRET_KEY_BASE: generate-with-openssl-rand-hex-64+ # Active Record encryption — generate with `spree encryption init --print`+ # or `bin/rails db:encryption:init`; never change them once data is encrypted+ ACTIVE_RECORD_ENCRYPTION_PRIMARY_KEY: ...+ ACTIVE_RECORD_ENCRYPTION_DETERMINISTIC_KEY: ...+ ACTIVE_RECORD_ENCRYPTION_KEY_DERIVATION_SALT: ...RAILS_HOST: store.example.com# Uploads to S3 (recommended) — see /developer/deployment/assets# AWS_REGION: eu-west-1diff --git a/docs/developer/deployment/aws_ecs.mdx b/docs/developer/deployment/aws_ecs.mdxindex 8d63b0c4f6..2c9b9166a3 100644--- a/docs/developer/deployment/aws_ecs.mdx+++ b/docs/developer/deployment/aws_ecs.mdx@@ -222,6 +222,9 @@ Create the following secrets in AWS Secrets Manager:|---|---|---|| `spree/database-url` | `DATABASE_URL` | PostgreSQL connection URL || `spree/secret-key-base` | `SECRET_KEY_BASE` | Generate with `bin/rails secret` |+| `spree/ar-encryption-primary-key` | `ACTIVE_RECORD_ENCRYPTION_PRIMARY_KEY` | [Active Record encryption](/developer/deployment/environment_variables#active-record-encryption) keys — generate all three with `bin/rails db:encryption:init` (or `spree encryption init --print`). Never change them once data is encrypted |+| `spree/ar-encryption-deterministic-key` | `ACTIVE_RECORD_ENCRYPTION_DETERMINISTIC_KEY` | Generated together with the primary key |+| `spree/ar-encryption-key-derivation-salt` | `ACTIVE_RECORD_ENCRYPTION_KEY_DERIVATION_SALT` | Generated together with the primary key |Optional secrets for email delivery, file storage, and error tracking:@@ -294,6 +297,18 @@ One task definition runs the whole app — the web server also runs background j{"name": "SECRET_KEY_BASE","valueFrom": "arn:aws:secretsmanager:${AWS_REGION}:${AWS_ACCOUNT_ID}:secret:spree/secret-key-base"+ },+ {+ "name": "ACTIVE_RECORD_ENCRYPTION_PRIMARY_KEY",+ "valueFrom": "arn:aws:secretsmanager:${AWS_REGION}:${AWS_ACCOUNT_ID}:secret:spree/ar-encryption-primary-key"+ },+ {+ "name": "ACTIVE_RECORD_ENCRYPTION_DETERMINISTIC_KEY",+ "valueFrom": "arn:aws:secretsmanager:${AWS_REGION}:${AWS_ACCOUNT_ID}:secret:spree/ar-encryption-deterministic-key"+ },+ {+ "name": "ACTIVE_RECORD_ENCRYPTION_KEY_DERIVATION_SALT",+ "valueFrom": "arn:aws:secretsmanager:${AWS_REGION}:${AWS_ACCOUNT_ID}:secret:spree/ar-encryption-key-derivation-salt"}],"logConfiguration": {@@ -353,6 +368,18 @@ Switches to [split mode](/developer/deployment/quickstart#web-and-worker): backg{"name": "SECRET_KEY_BASE","valueFrom": "arn:aws:secretsmanager:${AWS_REGION}:${AWS_ACCOUNT_ID}:secret:spree/secret-key-base"+ },+ {+ "name": "ACTIVE_RECORD_ENCRYPTION_PRIMARY_KEY",+ "valueFrom": "arn:aws:secretsmanager:${AWS_REGION}:${AWS_ACCOUNT_ID}:secret:spree/ar-encryption-primary-key"+ },+ {+ "name": "ACTIVE_RECORD_ENCRYPTION_DETERMINISTIC_KEY",+ "valueFrom": "arn:aws:secretsmanager:${AWS_REGION}:${AWS_ACCOUNT_ID}:secret:spree/ar-encryption-deterministic-key"+ },+ {+ "name": "ACTIVE_RECORD_ENCRYPTION_KEY_DERIVATION_SALT",+ "valueFrom": "arn:aws:secretsmanager:${AWS_REGION}:${AWS_ACCOUNT_ID}:secret:spree/ar-encryption-key-derivation-salt"}],"logConfiguration": {diff --git a/docs/developer/deployment/docker.mdx b/docs/developer/deployment/docker.mdxindex f33e58fb67..f71d269793 100644--- a/docs/developer/deployment/docker.mdx+++ b/docs/developer/deployment/docker.mdx@@ -54,6 +54,11 @@ services:environment:DATABASE_URL: postgres://postgres@postgres:5432/spree_productionSECRET_KEY_BASE: change-me-to-a-real-secret+ # Active Record encryption — generate with `spree encryption init --print`+ # or `bin/rails db:encryption:init`; never change them once data is encrypted+ ACTIVE_RECORD_ENCRYPTION_PRIMARY_KEY: change-me+ ACTIVE_RECORD_ENCRYPTION_DETERMINISTIC_KEY: change-me+ ACTIVE_RECORD_ENCRYPTION_KEY_DERIVATION_SALT: change-meRAILS_FORCE_SSL: "false"RAILS_ASSUME_SSL: "false"# Public host used in generated URLs (images/attachments in API@@ -93,6 +98,10 @@ Background jobs run inside the web container by default. When job load deservesenvironment:DATABASE_URL: postgres://postgres@postgres:5432/spree_productionSECRET_KEY_BASE: change-me-to-a-real-secret+ # the same encryption keys as web+ ACTIVE_RECORD_ENCRYPTION_PRIMARY_KEY: change-me+ ACTIVE_RECORD_ENCRYPTION_DETERMINISTIC_KEY: change-me+ ACTIVE_RECORD_ENCRYPTION_KEY_DERIVATION_SALT: change-meRAILS_HOST: localhost:3000command: bin/jobs```@@ -103,6 +112,7 @@ Background jobs run inside the web container by default. When job load deserves| --- | --- | --- || `DATABASE_URL` | PostgreSQL connection URL | `postgres://user:pass@host:5432/spree` || `SECRET_KEY_BASE` | Secret key for session encryption | Generate with `bin/rails secret` |+| `ACTIVE_RECORD_ENCRYPTION_PRIMARY_KEY`, `ACTIVE_RECORD_ENCRYPTION_DETERMINISTIC_KEY`, `ACTIVE_RECORD_ENCRYPTION_KEY_DERIVATION_SALT` | Keys Spree encrypts secrets at rest with — see [Active Record encryption](/developer/deployment/environment_variables#active-record-encryption). Never change them once data is encrypted | Generate with `spree encryption init --print` or `bin/rails db:encryption:init` || `RAILS_HOST` | Public host used in generated URLs — image/attachment URLs in API responses, email links | `store.example.com` || `SOLID_QUEUE_IN_PUMA` | Run background jobs inside the web container (default `true`); set `false` when running a dedicated worker | `true` |diff --git a/docs/developer/deployment/environment_variables.mdx b/docs/developer/deployment/environment_variables.mdxindex 1dbda39f85..3da240eb79 100644--- a/docs/developer/deployment/environment_variables.mdx+++ b/docs/developer/deployment/environment_variables.mdx@@ -1,6 +1,6 @@---title: Environment Variables-description: Reference for Spree deployment environment variables — database, web server, background jobs, SMTP, file storage, and application settings.+description: Reference for Spree deployment environment variables — database, secrets and encryption keys, web server, background jobs, SMTP, file storage, and application settings.---Spree uses environment variables for all deployment configuration. No secrets or credentials are stored in the codebase.@@ -14,7 +14,62 @@ These two variables are all a production deployment strictly needs:| `DATABASE_URL` | Database connection URL — see [Database Configuration](/developer/deployment/database) | `postgres://user:pass@localhost:5432/spree` || `SECRET_KEY_BASE` | Secret used to encrypt sessions and cookies. Generate with `openssl rand -hex 64` | `2fad5c0b79d25e4765d3018d8c740f8c3a665f0e5c...` |-You'll almost always want to set [`RAILS_HOST`](#urls-and-hosts) too — without it, generated URLs point at `localhost`.+You'll almost always want to set [`RAILS_HOST`](#urls-and-hosts) too — without it, generated URLs point at `localhost`, and the three [Active Record encryption](#active-record-encryption) keys — without them, secrets Spree stores are kept in plain text.++## Active Record encryption++Spree encrypts sensitive values at rest with [Active Record encryption](https://guides.rubyonrails.org/active_record_encryption.html): webhook endpoint signing secrets, payment gateway customer IDs, and the OAuth tokens stored on user identities. It does so only when encryption keys are configured — without them, these values are stored in plain text and a production app logs a warning at boot.++| Variable | Description |+| --- | --- |+| `ACTIVE_RECORD_ENCRYPTION_PRIMARY_KEY` | Key for (non-deterministic) encrypted attributes |+| `ACTIVE_RECORD_ENCRYPTION_DETERMINISTIC_KEY` | Key for deterministic encrypted attributes — the ones Spree looks records up by, such as webhook signing secrets and gateway customer IDs |+| `ACTIVE_RECORD_ENCRYPTION_KEY_DERIVATION_SALT` | Salt for deriving the encryption keys |++Set all three. Each is a random string — generate a set with any of:++<CodeGroup>++```bash Spree CLI+spree encryption init # writes a set to your project's .env (never overwrites existing keys)+spree encryption init --print # prints a fresh set, e.g. for your hosting provider+```++```bash Without Spree CLI+bin/rails db:encryption:init+```++</CodeGroup>++- **New projects** — `create-spree-app` generates the keys into `.env`, and the [Render Blueprint](/developer/deployment/render) generates them for production.+- **Production** — use a separate set of keys from development and store it in your secret manager as a backup.+- **Rails credentials** — instead of env vars, you can put the values printed by `bin/rails db:encryption:init` under `active_record_encryption` in your encrypted credentials. When both are present, the env vars win.++<Warning>+Never change or lose the keys once data is encrypted — records encrypted with them become unreadable. Rails supports [rotating the primary key](https://guides.rubyonrails.org/active_record_encryption.html#rotating-keys) by adding the new key and keeping the old one, but it doesn't support rotating the deterministic key — and webhook endpoint secrets and gateway customer IDs are encrypted deterministically. Keep `ACTIVE_RECORD_ENCRYPTION_DETERMINISTIC_KEY` and `ACTIVE_RECORD_ENCRYPTION_KEY_DERIVATION_SALT` unchanged unless you plan a migration that re-encrypts those records.+</Warning>++### Enabling encryption on an existing installation++Records written before the keys were set are stored in plain text. OAuth tokens on user identities stay readable and are encrypted on their next write. Webhook endpoint secrets and gateway customer IDs are not readable in plain text once encryption is on, so enable encryption with plaintext support first, then encrypt the existing rows:++1. Allow reading and looking up plaintext rows in `config/application.rb`:++ ```ruby+ config.active_record.encryption.support_unencrypted_data = true+ config.active_record.encryption.extend_queries = true+ ```++2. Set the three keys ([see above](#active-record-encryption)) and deploy.+3. Encrypt the existing rows from a Rails console (`spree console` or `bin/rails console`):++ ```ruby+ [Spree::WebhookEndpoint, Spree::GatewayCustomer, Spree::UserIdentity].each { |model| model.find_each(&:encrypt) }+ ```++4. Remove the two settings from step 1 and deploy again.++Apps created from an older `spree-starter` also need `config/application.rb` to read the env vars — see the [5.6 to 6.0 upgrade guide](/developer/upgrades/5.6-to-6.0#enable-active-record-encryption).## URLs and Hostsdiff --git a/docs/developer/deployment/render.mdx b/docs/developer/deployment/render.mdxindex a29dbf334f..8278a81f0d 100644--- a/docs/developer/deployment/render.mdx+++ b/docs/developer/deployment/render.mdx@@ -39,7 +39,7 @@ The `/jobs` dashboard uses HTTP Basic auth: user `jobs`, with a password the Blu### Environment Variables-Render sets `DATABASE_URL` and `SECRET_KEY_BASE` automatically from the Blueprint. For additional configuration (SMTP, file storage, Sentry, etc.), see [Environment Variables](/developer/deployment/environment_variables).+Render sets `DATABASE_URL`, `SECRET_KEY_BASE` and the three [Active Record encryption](/developer/deployment/environment_variables#active-record-encryption) keys automatically from the Blueprint. Copy the encryption keys from the **Environment** tab into your secret manager as a backup — never change them once data is encrypted. For additional configuration (SMTP, file storage, Sentry, etc.), see [Environment Variables](/developer/deployment/environment_variables).Generated URLs (images and attachments in API responses, email links) automatically use Render's `RENDER_EXTERNAL_HOSTNAME` (`<your-app-name>.onrender.com`). When you attach a custom domain, set [`RAILS_HOST`](/developer/deployment/environment_variables#urls-and-hosts) to it — it takes precedence.diff --git a/docs/developer/security/security_policy.mdx b/docs/developer/security/security_policy.mdxindex 7c19885fed..0cdf14d9b6 100644--- a/docs/developer/security/security_policy.mdx+++ b/docs/developer/security/security_policy.mdx@@ -63,6 +63,7 @@ Spree API is built on **Ruby on Rails** which provides strong security defaultsWe recommend:- Keeping Spree and all dependencies up to date+- Configuring [Active Record encryption](/developer/deployment/environment_variables#active-record-encryption) keys in production — without them, webhook signing secrets, payment gateway customer IDs and OAuth tokens are stored in plain text- Following the [Rails Security Guide](https://guides.rubyonrails.org/security.html)- Using [bundler-audit](https://github.com/rubysec/bundler-audit) to scan for known vulnerabilities in dependencies- Running [brakeman](https://github.com/presidentbeef/brakeman) for static security analysisdiff --git a/docs/developer/upgrades/5.6-to-6.0.mdx b/docs/developer/upgrades/5.6-to-6.0.mdxindex afd394add8..85a26189d4 100644--- a/docs/developer/upgrades/5.6-to-6.0.mdx+++ b/docs/developer/upgrades/5.6-to-6.0.mdx@@ -184,6 +184,45 @@ bundle exec rake spree:upgrade:migrate_country_state_codesCountries and states are no longer database records in 6.0. Addresses, delivery zone members, market countries, stock locations and stores now name them by ISO code (`country_code`, `state_code`), and this task fills those columns from the old `country_id` / `state_id` references. The old `country_iso` / `state_abbr` names still work on addresses for one release.+## Enable Active Record encryption++Spree encrypts webhook endpoint signing secrets, payment gateway customer IDs and the OAuth tokens on user identities with [Active Record encryption](https://guides.rubyonrails.org/active_record_encryption.html) — but only when encryption keys are configured. Without keys these values are stored in plain text. New 6.0 projects get keys at setup; upgraded applications need to add them.++**1. Make the app read the keys.** Projects created from `spree-starter` read them from the `ACTIVE_RECORD_ENCRYPTION_PRIMARY_KEY`, `ACTIVE_RECORD_ENCRYPTION_DETERMINISTIC_KEY` and `ACTIVE_RECORD_ENCRYPTION_KEY_DERIVATION_SALT` env vars, falling back to the `active_record_encryption` entry in Rails credentials. If your `config/application.rb` predates this, add inside the `Application` class:++```ruby config/application.rb+%i[primary_key deterministic_key key_derivation_salt].each do |key|+ value = ENV["ACTIVE_RECORD_ENCRYPTION_#{key.upcase}"].presence ||+ credentials.dig(:active_record_encryption, key).presence+ config.active_record.encryption[key] = value if value+end+```++Setting the keys in `config.active_record.encryption` (rather than only in credentials) matters: Spree checks that configuration when it decides whether to encrypt webhook secrets and gateway customer IDs.++**2. Generate keys for development and production** — a separate set for each environment:++<CodeGroup>++```bash Spree CLI (Docker)+spree encryption init # adds a set to your project's .env (never overwrites existing keys)+spree encryption init --print # prints a set for your production host+```++```bash Without Spree CLI+bin/rails db:encryption:init # prints a set; put it in env vars or encrypted credentials+```++</CodeGroup>++Recreate the containers so they pick up the new `.env` (`spree update`, or `spree dev` for an ejected project — `spree restart` keeps the old environment). Set the keys on your production host **before** deploying, and store them in your secret manager.++<Warning>+Never change or lose the keys once data is encrypted — the encrypted records become unreadable.+</Warning>++**3. Encrypt existing rows.** Rows written before the keys were set are plain text. OAuth tokens on user identities stay readable and are encrypted on their next write. Webhook endpoint secrets and gateway customer IDs can't be read in plain text once encryption is on — follow [Enabling encryption on an existing installation](/developer/deployment/environment_variables#enabling-encryption-on-an-existing-installation): turn on `support_unencrypted_data` and `extend_queries`, deploy with the keys, run `find_each(&:encrypt)` over `Spree::WebhookEndpoint`, `Spree::GatewayCustomer` and `Spree::UserIdentity`, then turn the two settings off again.+## The Cart/Order splitThe single biggest change. What used to be one `Spree::Order` living through checkout and beyond is now two models:diff --git a/packages/cli/README.md b/packages/cli/README.mdindex 31e2f87c57..9ca314b47c 100644--- a/packages/cli/README.md+++ b/packages/cli/README.md@@ -25,6 +25,7 @@ Run from your Spree project directory:| `spree migrate` / `spree seed` / `spree sample-data` | Database tasks || `spree generate …` | Spree generators (models, API resources, subscribers, migrations) || `spree user create` / `spree api-key …` | Admin users and scoped API keys |+| `spree encryption init` | Add Active Record encryption keys to `.env` (`--print` to only print a set) || `spree api get/post/patch/delete <path>` | Call the Admin API directly (`spree api endpoints` lists routes + scopes) || `spree rspec` | Run the backend test suite inside the container |diff --git a/packages/cli/src/commands/encryption.ts b/packages/cli/src/commands/encryption.tsnew file mode 100644index 0000000000..8168f35aa7--- /dev/null+++ b/packages/cli/src/commands/encryption.ts@@ -0,0 +1,130 @@+import crypto from 'node:crypto'+import fs from 'node:fs'+import path from 'node:path'+import * as p from '@clack/prompts'+import type { Command } from 'commander'+import pc from 'picocolors'+import { detectProject, findApiDir, isEjectedProject } from '../context.js'+import {+ APPLICATION_RB_SNIPPET,+ appReadsEncryptionEnv,+ configuredEncryptionVars,+ credentialsFiles,+ formatEncryptionEnv,+ generateEncryptionKeys,+ withEncryptionKeys,+} from '../lib/encryption.js'++const DOCS_URL =+ 'https://spreecommerce.org/docs/developer/deployment/environment_variables#active-record-encryption'++export function registerEncryptionCommand(program: Command): void {+ const encryption = program+ .command('encryption')+ .description('Manage Active Record encryption keys')++ encryption+ .command('init')+ .description(+ 'Generate Active Record encryption keys and add them to .env (never overwrites existing keys)',+ )+ .option('--print', 'only print a fresh set of keys (e.g. for your hosting provider)')+ .addHelpText(+ 'after',+ '\nSpree encrypts webhook signing keys, payment gateway customer ids and OAuth tokens\n' ++ 'at rest only when these keys are set. Once data is encrypted, never change them —\n' ++ 'encrypted rows become unreadable. There is deliberately no --force.',+ )+ .action((flags: { print?: boolean }) => {+ if (flags.print) {+ process.stdout.write(`${formatEncryptionEnv(generateEncryptionKeys())}\n`)+ return+ }++ initEncryption(detectProject().projectDir)+ })+}++export function initEncryption(projectDir: string): void {+ const envPath = path.join(projectDir, '.env')+ const content = fs.existsSync(envPath) ? fs.readFileSync(envPath, 'utf-8') : ''+ const configured = configuredEncryptionVars(content)+ const apiDir = findApiDir(projectDir)+ const ejected = isEjectedProject(projectDir)++ if (ejected && !appReadsEncryptionEnv(path.join(projectDir, apiDir))) {+ p.log.warn(+ `${apiDir}/config doesn't read these env vars yet. Add this inside the Application class in ${apiDir}/config/application.rb:\n\n` ++ pc.dim(APPLICATION_RB_SNIPPET),+ )+ }++ if (configured.length > 0) {+ p.log.warn(+ `.env already sets ${configured.join(', ')} — leaving it unchanged.\n` ++ 'Changing encryption keys makes data encrypted with them unreadable.' ++ (configured.length < 3+ ? '\nAdd the missing values by hand (`spree encryption init --print`).'+ : ''),+ )+ return+ }++ const credentials = credentialsFiles(path.join(projectDir, apiDir))+ if (credentials.length > 0) {+ p.log.warn(+ `${apiDir} has Rails credentials (${credentials.join(', ')}) — leaving .env unchanged.\n` ++ 'If they hold active_record_encryption keys, env vars would take precedence and make\n' ++ 'data encrypted with those keys unreadable. Check with `bin/rails credentials:show`;\n' ++ 'if they hold none, add fresh keys to .env by hand (`spree encryption init --print`).',+ )+ return+ }++ writeEnvAtomically(envPath, withEncryptionKeys(content, generateEncryptionKeys()))+ p.log.success('Added Active Record encryption keys to .env.')++ p.note(+ [+ `1. Recreate the containers to load the new .env: ${pc.cyan(ejected ? 'spree dev' : 'spree update')}`,+ ` (${pc.cyan('spree restart')} keeps the old environment).`,+ '2. Back up the three values in your secret manager —',+ ' losing them makes encrypted data unreadable.',+ '3. Production: set the three env vars on your host before deploying',+ ` (a separate set: ${pc.cyan('spree encryption init --print')}) and never change them.`,+ '',+ DOCS_URL,+ ].join('\n'),+ 'Next steps',+ )+}++/**+ * Writes via a same-directory temp file + rename, so a failed write never+ * truncates the existing .env (and its SECRET_KEY_BASE). A new .env is created+ * owner-only; an existing one keeps its mode. Symlinks are followed.+ */+function writeEnvAtomically(envPath: string, contents: string): void {+ const target = fs.existsSync(envPath) ? fs.realpathSync(envPath) : envPath+ const mode = fs.existsSync(target) ? fs.statSync(target).mode & 0o777 : 0o600+ // Random suffix: a stale file from an earlier crashed run (or a reused PID)+ // can't collide with this one.+ const suffix = crypto.randomBytes(6).toString('hex')+ const tmp = path.join(path.dirname(target), `.${path.basename(target)}.${suffix}.tmp`)+ let created = false+ try {+ const fd = fs.openSync(tmp, 'wx', mode)+ created = true+ try {+ fs.writeFileSync(fd, contents)+ } finally {+ fs.closeSync(fd)+ }+ fs.chmodSync(tmp, mode)+ fs.renameSync(tmp, target)+ } catch (error) {+ // Only remove a temp file this call created.+ if (created) fs.rmSync(tmp, { force: true })+ throw error+ }+}diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.tsindex b896131bdf..9abcc6fb67 100644--- a/packages/cli/src/index.ts+++ b/packages/cli/src/index.ts@@ -11,6 +11,7 @@ import { registerConsoleCommand } from './commands/console.js'import { registerDbCommand } from './commands/db.js'import { registerDevCommand } from './commands/dev.js'import { registerEjectCommand } from './commands/eject.js'+import { registerEncryptionCommand } from './commands/encryption.js'import { registerExecCommand } from './commands/exec.js'import { registerGenerateCommand } from './commands/generate.js'import { registerInitCommand } from './commands/init.js'@@ -92,6 +93,7 @@ registerShellCommand(program)// Spree-specific helpersregisterUserCommand(program)registerApiKeyCommand(program)+registerEncryptionCommand(program)registerOpenCommand(program)registerSeedCommand(program)registerSampleDataCommand(program)diff --git a/packages/cli/src/lib/encryption.ts b/packages/cli/src/lib/encryption.tsnew file mode 100644index 0000000000..1aabe813b9--- /dev/null+++ b/packages/cli/src/lib/encryption.ts@@ -0,0 +1,152 @@+import crypto from 'node:crypto'+import fs from 'node:fs'+import path from 'node:path'++/**+ * The env vars spree-starter reads Active Record encryption keys from (see its+ * config/application.rb). Spree encrypts webhook signing keys, gateway customer+ * ids and OAuth tokens at rest only when all three are configured.+ */+export const ENCRYPTION_ENV_VARS = [+ 'ACTIVE_RECORD_ENCRYPTION_PRIMARY_KEY',+ 'ACTIVE_RECORD_ENCRYPTION_DETERMINISTIC_KEY',+ 'ACTIVE_RECORD_ENCRYPTION_KEY_DERIVATION_SALT',+] as const++export type EncryptionEnvVar = (typeof ENCRYPTION_ENV_VARS)[number]++const ALPHANUMERIC = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'++/**+ * A random alphanumeric string — the format `bin/rails db:encryption:init`+ * prints (`SecureRandom.alphanumeric(32)` per value).+ */+export function randomAlphanumeric(length = 32): string {+ let result = ''+ for (let i = 0; i < length; i++) {+ result += ALPHANUMERIC[crypto.randomInt(ALPHANUMERIC.length)]+ }+ return result+}++/** A fresh set of the three Active Record encryption values. */+export function generateEncryptionKeys(): Record<EncryptionEnvVar, string> {+ return {+ ACTIVE_RECORD_ENCRYPTION_PRIMARY_KEY: randomAlphanumeric(),+ ACTIVE_RECORD_ENCRYPTION_DETERMINISTIC_KEY: randomAlphanumeric(),+ ACTIVE_RECORD_ENCRYPTION_KEY_DERIVATION_SALT: randomAlphanumeric(),+ }+}++export function formatEncryptionEnv(keys: Record<EncryptionEnvVar, string>): string {+ return ENCRYPTION_ENV_VARS.map((name) => `${name}=${keys[name]}`).join('\n')+}++function assignmentPattern(name: string): RegExp {+ return new RegExp(`^[ \\t]*(?:export[ \\t]+)?${name}[ \\t]*=(.*)$`, 'm')+}++/**+ * The effective value of a `.env` assignment, as Docker Compose reads it:+ * surrounding quotes are dropped, and in an unquoted value a `#` preceded by+ * whitespace starts a comment (`KEY= # add later` is empty).+ */+function envValue(raw: string): string {+ const trimmed = raw.trim()+ const quoted = trimmed.match(/^(['"])(.*?)\1/)+ if (quoted) return quoted[2]+ return trimmed.replace(/(^|\s)#.*$/, '').trim()+}++/** The encryption vars `.env` content already assigns a non-empty value. */+export function configuredEncryptionVars(content: string): EncryptionEnvVar[] {+ return ENCRYPTION_ENV_VARS.filter((name) => {+ const match = content.match(assignmentPattern(name))+ if (!match) return false+ return envValue(match[1]).length > 0+ })+}++/**+ * The Rails encrypted credentials files in the app (relative paths). Keys held+ * there can't be read without the master key, and env vars take precedence+ * over them — so generating env keys next to them could shadow keys that+ * already protect data.+ */+export function credentialsFiles(apiDir: string): string[] {+ const configDir = path.join(apiDir, 'config')+ const found: string[] = []+ if (fs.existsSync(path.join(configDir, 'credentials.yml.enc'))) {+ found.push('config/credentials.yml.enc')+ }+ const perEnvDir = path.join(configDir, 'credentials')+ if (fs.existsSync(perEnvDir)) {+ for (const entry of fs.readdirSync(perEnvDir)) {+ if (entry.endsWith('.yml.enc')) found.push(`config/credentials/${entry}`)+ }+ }+ return found+}++/**+ * Returns `.env` content with the given keys set. Empty assignments (e.g.+ * copied from `.env.example`) are filled in place; missing vars are appended.+ * Never call this for vars that already hold a value — see+ * `configuredEncryptionVars`.+ */+export function withEncryptionKeys(+ content: string,+ keys: Record<EncryptionEnvVar, string>,+): string {+ let result = content+ const append: EncryptionEnvVar[] = []++ for (const name of ENCRYPTION_ENV_VARS) {+ const pattern = assignmentPattern(name)+ if (pattern.test(result)) {+ result = result.replace(pattern, `${name}=${keys[name]}`)+ } else {+ append.push(name)+ }+ }++ if (append.length > 0) {+ if (result.length > 0 && !result.endsWith('\n')) result += '\n'+ result +=+ '# Active Record encryption — back these up; never change them once data is encrypted\n'+ result += `${append.map((name) => `${name}=${keys[name]}`).join('\n')}\n`+ }++ return result+}++/**+ * Whether the Rails app's config reads the encryption env vars. Projects+ * scaffolded from an older spree-starter don't, so setting the vars alone+ * would not enable encryption there.+ */+export function appReadsEncryptionEnv(apiDir: string): boolean {+ const configDir = path.join(apiDir, 'config')+ if (!fs.existsSync(configDir)) return false++ const stack = [configDir]+ while (stack.length > 0) {+ const dir = stack.pop() as string+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {+ const full = path.join(dir, entry.name)+ if (entry.isDirectory()) {+ stack.push(full)+ } else if (entry.name.endsWith('.rb')) {+ if (fs.readFileSync(full, 'utf-8').includes('ACTIVE_RECORD_ENCRYPTION_')) return true+ }+ }+ }+ return false+}++/** The snippet to add to config/application.rb in apps that don't read the vars yet. */+export const APPLICATION_RB_SNIPPET = ` %i[primary_key deterministic_key key_derivation_salt].each do |key|+ value = ENV["ACTIVE_RECORD_ENCRYPTION_#{key.upcase}"].presence ||+ credentials.dig(:active_record_encryption, key).presence+ config.active_record.encryption[key] = value if value+ end`diff --git a/packages/cli/tests/encryption.test.ts b/packages/cli/tests/encryption.test.tsnew file mode 100644index 0000000000..c604188829--- /dev/null+++ b/packages/cli/tests/encryption.test.ts@@ -0,0 +1,208 @@+import fs from 'node:fs'+import os from 'node:os'+import path from 'node:path'+import { afterEach, describe, expect, it, vi } from 'vitest'+import { initEncryption } from '../src/commands/encryption'+import {+ appReadsEncryptionEnv,+ configuredEncryptionVars,+ credentialsFiles,+ ENCRYPTION_ENV_VARS,+ formatEncryptionEnv,+ generateEncryptionKeys,+ randomAlphanumeric,+ withEncryptionKeys,+} from '../src/lib/encryption'++vi.mock('@clack/prompts', () => ({+ log: { success: vi.fn(), warn: vi.fn(), info: vi.fn() },+ note: vi.fn(),+}))++const tempDirs: string[] = []++function makeTempDir(): string {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'spree-cli-encryption-test-'))+ tempDirs.push(dir)+ return dir+}++afterEach(() => {+ for (const dir of tempDirs) {+ fs.rmSync(dir, { recursive: true, force: true })+ }+ tempDirs.length = 0+})++const keys = {+ ACTIVE_RECORD_ENCRYPTION_PRIMARY_KEY: 'primary',+ ACTIVE_RECORD_ENCRYPTION_DETERMINISTIC_KEY: 'deterministic',+ ACTIVE_RECORD_ENCRYPTION_KEY_DERIVATION_SALT: 'salt',+}++describe('generateEncryptionKeys', () => {+ it('generates 32-character alphanumeric values like db:encryption:init', () => {+ const generated = generateEncryptionKeys()+ for (const name of ENCRYPTION_ENV_VARS) {+ expect(generated[name]).toMatch(/^[A-Za-z0-9]{32}$/)+ }+ })++ it('generates distinct values', () => {+ const generated = generateEncryptionKeys()+ expect(new Set(Object.values(generated)).size).toBe(3)+ expect(randomAlphanumeric()).not.toBe(randomAlphanumeric())+ })++ it('formats as env assignments', () => {+ expect(formatEncryptionEnv(keys)).toBe(+ 'ACTIVE_RECORD_ENCRYPTION_PRIMARY_KEY=primary\n' ++ 'ACTIVE_RECORD_ENCRYPTION_DETERMINISTIC_KEY=deterministic\n' ++ 'ACTIVE_RECORD_ENCRYPTION_KEY_DERIVATION_SALT=salt',+ )+ })+})++describe('configuredEncryptionVars', () => {+ it('ignores empty, quoted-empty and commented assignments', () => {+ const content =+ 'ACTIVE_RECORD_ENCRYPTION_PRIMARY_KEY=\n' ++ 'ACTIVE_RECORD_ENCRYPTION_DETERMINISTIC_KEY=""\n' ++ '# ACTIVE_RECORD_ENCRYPTION_KEY_DERIVATION_SALT=abc\n'+ expect(configuredEncryptionVars(content)).toEqual([])+ })++ it('treats a whitespace-prefixed inline comment as an empty value', () => {+ const content =+ 'ACTIVE_RECORD_ENCRYPTION_PRIMARY_KEY= # add later\n' ++ 'ACTIVE_RECORD_ENCRYPTION_DETERMINISTIC_KEY=abc # set\n' ++ 'ACTIVE_RECORD_ENCRYPTION_KEY_DERIVATION_SALT="a #b"\n'+ expect(configuredEncryptionVars(content)).toEqual([+ 'ACTIVE_RECORD_ENCRYPTION_DETERMINISTIC_KEY',+ 'ACTIVE_RECORD_ENCRYPTION_KEY_DERIVATION_SALT',+ ])+ })++ it('detects set values, including export-prefixed ones', () => {+ const content =+ 'ACTIVE_RECORD_ENCRYPTION_PRIMARY_KEY=abc\nexport ACTIVE_RECORD_ENCRYPTION_KEY_DERIVATION_SALT=def\n'+ expect(configuredEncryptionVars(content)).toEqual([+ 'ACTIVE_RECORD_ENCRYPTION_PRIMARY_KEY',+ 'ACTIVE_RECORD_ENCRYPTION_KEY_DERIVATION_SALT',+ ])+ })+})++describe('withEncryptionKeys', () => {+ it('appends the keys, keeping existing content', () => {+ const result = withEncryptionKeys('SECRET_KEY_BASE=abc', keys)+ expect(result).toMatch(/^SECRET_KEY_BASE=abc\n# Active Record encryption/)+ expect(result).toContain(`${formatEncryptionEnv(keys)}\n`)+ })++ it('fills empty assignments in place instead of duplicating them', () => {+ const result = withEncryptionKeys(+ 'ACTIVE_RECORD_ENCRYPTION_PRIMARY_KEY=\nSPREE_PORT=3000\n',+ keys,+ )+ expect(result.match(/ACTIVE_RECORD_ENCRYPTION_PRIMARY_KEY=/g)).toHaveLength(1)+ expect(result).toMatch(/^ACTIVE_RECORD_ENCRYPTION_PRIMARY_KEY=primary\nSPREE_PORT=3000\n/)+ expect(result).toContain('ACTIVE_RECORD_ENCRYPTION_KEY_DERIVATION_SALT=salt')+ })+})++describe('initEncryption', () => {+ it('writes generated keys to the project .env', () => {+ const dir = makeTempDir()+ fs.writeFileSync(path.join(dir, '.env'), 'SECRET_KEY_BASE=abc\n')++ initEncryption(dir)++ const env = fs.readFileSync(path.join(dir, '.env'), 'utf-8')+ expect(env).toContain('SECRET_KEY_BASE=abc')+ for (const name of ENCRYPTION_ENV_VARS) {+ expect(env).toMatch(new RegExp(`^${name}=[A-Za-z0-9]{32}$`, 'm'))+ }+ })++ it('creates a missing .env owner-only', () => {+ const dir = makeTempDir()++ initEncryption(dir)++ const env = fs.readFileSync(path.join(dir, '.env'), 'utf-8')+ expect(env).toMatch(/^ACTIVE_RECORD_ENCRYPTION_PRIMARY_KEY=[A-Za-z0-9]{32}$/m)+ if (process.platform !== 'win32') {+ expect(fs.statSync(path.join(dir, '.env')).mode & 0o777).toBe(0o600)+ }+ })++ it('keeps an existing .env mode and leaves no temp file behind', () => {+ const dir = makeTempDir()+ const envPath = path.join(dir, '.env')+ fs.writeFileSync(envPath, 'SECRET_KEY_BASE=abc\n', { mode: 0o640 })+ fs.chmodSync(envPath, 0o640)++ initEncryption(dir)++ expect(fs.readFileSync(envPath, 'utf-8')).toMatch(/^SECRET_KEY_BASE=abc$/m)+ expect(fs.readdirSync(dir)).toEqual(['.env'])+ if (process.platform !== 'win32') {+ expect(fs.statSync(envPath).mode & 0o777).toBe(0o640)+ }+ })++ it('leaves .env unchanged when the app has Rails credentials', () => {+ const dir = makeTempDir()+ fs.mkdirSync(path.join(dir, 'server', 'config'), { recursive: true })+ fs.writeFileSync(path.join(dir, 'server', 'config', 'credentials.yml.enc'), 'x')+ fs.writeFileSync(path.join(dir, '.env'), 'SECRET_KEY_BASE=abc\n')++ initEncryption(dir)++ expect(fs.readFileSync(path.join(dir, '.env'), 'utf-8')).toBe('SECRET_KEY_BASE=abc\n')+ })++ it('never overwrites existing keys', () => {+ const dir = makeTempDir()+ const original = 'SECRET_KEY_BASE=abc\nACTIVE_RECORD_ENCRYPTION_PRIMARY_KEY=keep-me\n'+ fs.writeFileSync(path.join(dir, '.env'), original)++ initEncryption(dir)++ expect(fs.readFileSync(path.join(dir, '.env'), 'utf-8')).toBe(original)+ })+})++describe('credentialsFiles', () => {+ it('lists the app credentials files', () => {+ const dir = makeTempDir()+ fs.mkdirSync(path.join(dir, 'config', 'credentials'), { recursive: true })+ expect(credentialsFiles(dir)).toEqual([])+ fs.writeFileSync(path.join(dir, 'config', 'credentials.yml.enc'), 'x')+ fs.writeFileSync(path.join(dir, 'config', 'credentials', 'production.yml.enc'), 'x')+ expect(credentialsFiles(dir)).toEqual([+ 'config/credentials.yml.enc',+ 'config/credentials/production.yml.enc',+ ])+ })+})++describe('appReadsEncryptionEnv', () => {+ it('is false for an app without the env config', () => {+ const dir = makeTempDir()+ fs.mkdirSync(path.join(dir, 'config', 'initializers'), { recursive: true })+ fs.writeFileSync(path.join(dir, 'config', 'application.rb'), 'module App; end\n')+ expect(appReadsEncryptionEnv(dir)).toBe(false)+ })++ it('is true when any config file reads the env vars', () => {+ const dir = makeTempDir()+ fs.mkdirSync(path.join(dir, 'config', 'initializers'), { recursive: true })+ fs.writeFileSync(+ path.join(dir, 'config', 'initializers', 'encryption.rb'),+ 'ENV["ACTIVE_RECORD_ENCRYPTION_PRIMARY_KEY"]\n',+ )+ expect(appReadsEncryptionEnv(dir)).toBe(true)+ })+})diff --git a/packages/create-spree-app/src/scaffold.ts b/packages/create-spree-app/src/scaffold.tsindex 2626fcf14e..f9df2dae82 100644--- a/packages/create-spree-app/src/scaffold.ts+++ b/packages/create-spree-app/src/scaffold.ts@@ -21,6 +21,7 @@ import { readmeContent } from './templates/readme.js'import type { PackageManager, ScaffoldOptions } from './types.js'import {dlxCommand,+ generateEncryptionKeys,generateSecretKeyBase,installCommand,isDockerRunning,@@ -87,7 +88,15 @@ export async function scaffold(options: ScaffoldOptions): Promise<void> {fs.writeFileSync(path.join(projectDir, '.env'),- envContent(generateSecretKeyBase(), port, options.mailpitSmtpPort, options.mailpitUiPort),+ envContent(+ generateSecretKeyBase(),+ port,+ options.mailpitSmtpPort,+ options.mailpitUiPort,+ generateEncryptionKeys(),+ ),+ // Holds SECRET_KEY_BASE and the encryption keys — owner-only.+ { mode: 0o600 },)fs.writeFileSync(path.join(projectDir, 'package.json'),diff --git a/packages/create-spree-app/src/templates/env.ts b/packages/create-spree-app/src/templates/env.tsindex 0388ecd853..f9be8b87bf 100644--- a/packages/create-spree-app/src/templates/env.ts+++ b/packages/create-spree-app/src/templates/env.ts@@ -1,5 +1,7 @@+import type { EncryptionKeys } from '../utils.js'+/**- * The project root `.env`: Rails secret, ports and image tag. The Mailpit+ * The project root `.env`: Rails secrets, ports and image tag. The Mailpit* ports are written even when they are the defaults, so compose never falls* back to a value the scaffold did not check was free.*/@@ -8,8 +10,15 @@ export function envContent(port: number,mailpitSmtpPort: number,mailpitUiPort: number,+ encryptionKeys: EncryptionKeys,): string {return `SECRET_KEY_BASE=${secretKeyBase}+# Active Record encryption — Spree encrypts webhook signing keys, gateway+# customer ids and OAuth tokens with these. Back them up and never change them+# once data is encrypted; use a separate set in production.+ACTIVE_RECORD_ENCRYPTION_PRIMARY_KEY=${encryptionKeys.primaryKey}+ACTIVE_RECORD_ENCRYPTION_DETERMINISTIC_KEY=${encryptionKeys.deterministicKey}+ACTIVE_RECORD_ENCRYPTION_KEY_DERIVATION_SALT=${encryptionKeys.keyDerivationSalt}SPREE_PORT=${port}SPREE_VERSION_TAG=latestMAILPIT_SMTP_PORT=${mailpitSmtpPort}diff --git a/packages/create-spree-app/src/utils.ts b/packages/create-spree-app/src/utils.tsindex cf03244f6d..7a4c0ae296 100644--- a/packages/create-spree-app/src/utils.ts+++ b/packages/create-spree-app/src/utils.ts@@ -41,6 +41,40 @@ export function generateSecretKeyBase(): string {return crypto.randomBytes(64).toString('hex')}+const ALPHANUMERIC = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'++/**+ * A random alphanumeric string — the format `bin/rails db:encryption:init`+ * prints (`SecureRandom.alphanumeric(32)` per value).+ */+export function randomAlphanumeric(length = 32): string {+ let result = ''+ for (let i = 0; i < length; i++) {+ result += ALPHANUMERIC[crypto.randomInt(ALPHANUMERIC.length)]+ }+ return result+}++export interface EncryptionKeys {+ primaryKey: string+ deterministicKey: string+ keyDerivationSalt: string+}++/**+ * Active Record encryption keys for the scaffolded app. Spree encrypts webhook+ * signing keys, gateway customer ids and OAuth tokens at rest only when these+ * are set; spree-starter reads them from ACTIVE_RECORD_ENCRYPTION_* env vars.+ * Keep the same helper in @spree/cli (`spree encryption init`) in sync.+ */+export function generateEncryptionKeys(): EncryptionKeys {+ return {+ primaryKey: randomAlphanumeric(),+ deterministicKey: randomAlphanumeric(),+ keyDerivationSalt: randomAlphanumeric(),+ }+}+export function installCommand(pm: PackageManager): string {return pm === 'yarn' ? 'yarn' : `${pm} install`}diff --git a/packages/create-spree-app/tests/scaffold.test.ts b/packages/create-spree-app/tests/scaffold.test.tsindex 4344a1a2e0..1374f5de30 100644--- a/packages/create-spree-app/tests/scaffold.test.ts+++ b/packages/create-spree-app/tests/scaffold.test.ts@@ -210,7 +210,7 @@ describe('scaffold (no-start)', () => {expect(compose).toContain('- bundle_cache:/usr/local/bundle')})- it('generates .env with SECRET_KEY_BASE and PORT', async () => {+ it('generates .env with SECRET_KEY_BASE, encryption keys and PORT', async () => {const projectDir = getTempProjectDir()await scaffold({@@ -224,7 +224,13 @@ describe('scaffold (no-start)', () => {const env = fs.readFileSync(path.join(projectDir, '.env'), 'utf-8')expect(env).toMatch(/SECRET_KEY_BASE=.{128}/)+ expect(env).toMatch(/^ACTIVE_RECORD_ENCRYPTION_PRIMARY_KEY=[A-Za-z0-9]{32}$/m)+ expect(env).toMatch(/^ACTIVE_RECORD_ENCRYPTION_DETERMINISTIC_KEY=[A-Za-z0-9]{32}$/m)+ expect(env).toMatch(/^ACTIVE_RECORD_ENCRYPTION_KEY_DERIVATION_SALT=[A-Za-z0-9]{32}$/m)expect(env).toContain('SPREE_PORT=4567')+ if (process.platform !== 'win32') {+ expect(fs.statSync(path.join(projectDir, '.env')).mode & 0o777).toBe(0o600)+ }})it('generates valid package.json with project name', async () => {diff --git a/packages/create-spree-app/tests/templates.test.ts b/packages/create-spree-app/tests/templates.test.tsindex 68e566818a..67810d335b 100644--- a/packages/create-spree-app/tests/templates.test.ts+++ b/packages/create-spree-app/tests/templates.test.ts@@ -6,19 +6,32 @@ import { gitignoreContent } from '../src/templates/gitignore'import { rootPackageJsonContent } from '../src/templates/package-json'import { readmeContent } from '../src/templates/readme'+const keys = {+ primaryKey: 'pk-value',+ deterministicKey: 'dk-value',+ keyDerivationSalt: 'salt-value',+}+describe('envContent', () => {+ it('includes the Active Record encryption keys', () => {+ const content = envContent('any', 3000, 1025, 8025, keys)+ expect(content).toContain('ACTIVE_RECORD_ENCRYPTION_PRIMARY_KEY=pk-value\n')+ expect(content).toContain('ACTIVE_RECORD_ENCRYPTION_DETERMINISTIC_KEY=dk-value\n')+ expect(content).toContain('ACTIVE_RECORD_ENCRYPTION_KEY_DERIVATION_SALT=salt-value\n')+ })+it('includes the provided secret key', () => {- const content = envContent('my-secret-123', 3000, 1025, 8025)+ const content = envContent('my-secret-123', 3000, 1025, 8025, keys)expect(content).toContain('SECRET_KEY_BASE=my-secret-123')})it('includes SPREE_PORT', () => {- const content = envContent('any', 3000, 1025, 8025)+ const content = envContent('any', 3000, 1025, 8025, keys)expect(content).toContain('SPREE_PORT=3000')})it('uses custom port value', () => {- const content = envContent('any', 4567, 1025, 8025)+ const content = envContent('any', 4567, 1025, 8025, keys)expect(content).toContain('SPREE_PORT=4567')})@@ -26,7 +39,7 @@ describe('envContent', () => {// local mail catcher takes them. The scaffold probes them and writes the// result, so compose never falls back to a default nobody checked was free.it('pins the probed Mailpit ports', () => {- const content = envContent('any', 3000, 1026, 8026)+ const content = envContent('any', 3000, 1026, 8026, keys)expect(content).toContain('MAILPIT_SMTP_PORT=1026')expect(content).toContain('MAILPIT_UI_PORT=8026')diff --git a/packages/create-spree-app/tests/utils.test.ts b/packages/create-spree-app/tests/utils.test.tsindex 79379145ef..fd382db5bd 100644--- a/packages/create-spree-app/tests/utils.test.ts+++ b/packages/create-spree-app/tests/utils.test.ts@@ -1,6 +1,7 @@import { beforeEach, describe, expect, it } from 'vitest'import {detectPackageManager,+ generateEncryptionKeys,generateSecretKeyBase,installCommand,runCommand,@@ -51,6 +52,21 @@ describe('generateSecretKeyBase', () => {})})+describe('generateEncryptionKeys', () => {+ it('returns 32-character alphanumeric values like db:encryption:init', () => {+ const keys = generateEncryptionKeys()+ for (const value of Object.values(keys)) {+ expect(value).toMatch(/^[A-Za-z0-9]{32}$/)+ }+ })++ it('generates distinct values', () => {+ const keys = generateEncryptionKeys()+ expect(new Set(Object.values(keys)).size).toBe(3)+ expect(generateEncryptionKeys().primaryKey).not.toBe(keys.primaryKey)+ })+})+describe('installCommand', () => {it('returns "npm install" for npm', () => {expect(installCommand('npm')).toBe('npm install')diff --git a/scripts/server-setup.sh b/scripts/server-setup.shindex bab5143778..e236f5f218 100755--- a/scripts/server-setup.sh+++ b/scripts/server-setup.sh@@ -9,6 +9,7 @@# 2. Clone spree-starter into server/# 3. Write server/.env with SPREE_PATH=.. (for the native bin/dev path —# Docker edge flow overrides via compose env) + a fresh SECRET_KEY_BASE+# and Active Record encryption keys# 4. Build @spree/cli so `pnpm exec spree …` works in server/# 5. Start the edge stack and wait for it to finish booting. The edge web# boot command (scripts/docker-compose.edge.yml) does the heavy lifting@@ -40,8 +41,13 @@ step "Cloning spree-starter into server/${SPREE_STARTER_BRANCH:+ (branch: $SPREEgit clone --depth 1 ${SPREE_STARTER_BRANCH:+--branch "$SPREE_STARTER_BRANCH"} https://github.com/spree/spree-starter.git "$SERVER_DIR"rm -rf "$SERVER_DIR/.git" "$SERVER_DIR/.gitignore"-step "Writing server/.env (SPREE_PATH + SECRET_KEY_BASE)"-printf 'SPREE_PATH=..\nSECRET_KEY_BASE=%s\n' "$(openssl rand -hex 64)" > "$SERVER_DIR/.env"+step "Writing server/.env (SPREE_PATH + SECRET_KEY_BASE + Active Record encryption keys)"+{+ printf 'SPREE_PATH=..\nSECRET_KEY_BASE=%s\n' "$(openssl rand -hex 64)"+ printf 'ACTIVE_RECORD_ENCRYPTION_PRIMARY_KEY=%s\n' "$(openssl rand -hex 16)"+ printf 'ACTIVE_RECORD_ENCRYPTION_DETERMINISTIC_KEY=%s\n' "$(openssl rand -hex 16)"+ printf 'ACTIVE_RECORD_ENCRYPTION_KEY_DERIVATION_SALT=%s\n' "$(openssl rand -hex 16)"+} > "$SERVER_DIR/.env"step "Building @spree/cli (so the spree CLI works in server/)"# Through turbo, which builds workspace deps first (build dependsOn ^build) —diff --git a/scripts/worktree/setup.sh b/scripts/worktree/setup.shindex 60a49d2b01..138c2665af 100755--- a/scripts/worktree/setup.sh+++ b/scripts/worktree/setup.sh@@ -98,6 +98,16 @@ if ! grep -q '^RAILS_PROTOCOL=' server/.env; thenprintf 'RAILS_PROTOCOL=%s\n' 'https' >> server/.envfi+# Active Record encryption keys, so Spree's encrypted columns (webhook signing+# keys, gateway customer ids, OAuth tokens) are encrypted in dev like they are+# in a scaffolded project. Per worktree: the seeded template holds no encrypted+# rows. Only added when missing — changing them makes encrypted rows unreadable.+for key in PRIMARY_KEY DETERMINISTIC_KEY KEY_DERIVATION_SALT; do+ if ! grep -q "^ACTIVE_RECORD_ENCRYPTION_${key}=" server/.env; then+ printf 'ACTIVE_RECORD_ENCRYPTION_%s=%s\n' "$key" "$(openssl rand -hex 16)" >> server/.env+ fi+done+# Mail goes to Mailpit, as it does in the starter's Docker stack. Without# SMTP_HOST the starter falls back to a delivery method that does not exist,# so every email raises rather than being delivered anywhere.