@stacksjs/defaults 0.75.629 → 0.75.632
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.
- package/ai/skills/stacks-actions/SKILL.md +1 -1
- package/ai/skills/stacks-email/SKILL.md +7 -4
- package/ai/skills/stacks-env/SKILL.md +19 -8
- package/ai/skills/stacks-models/SKILL.md +10 -1
- package/ai/skills/stacks-native/CATALOG.md +4 -4
- package/app/Actions/Dashboard/Infrastructure/EnvironmentIndexAction.ts +9 -7
- package/app/Actions/Dashboard/Infrastructure/EnvironmentUpdateAction.ts +6 -7
- package/app/Actions/Dashboard/Infrastructure/environment-file.ts +26 -6
- package/app/Actions/Dashboard/Infrastructure/environment-layers.test.ts +129 -0
- package/app/Actions/Dashboard/Infrastructure/environment-layers.ts +235 -0
- package/app/Actions/Dashboard/Infrastructure/environment-page.test.ts +71 -0
- package/app/Actions/Dashboard/Infrastructure/environment-page.ts +69 -0
- package/app/Actions/Dashboard/Settings/mail-settings.test.ts +47 -6
- package/app/Actions/Dashboard/Settings/mail-settings.ts +91 -86
- package/ide/vscode/package.json +1 -1
- package/package.json +5 -5
- package/resources/components/Dashboard/Environment/EnvironmentDashboard.stx +60 -8
- package/resources/components/Dashboard/Settings/MailSettingsDashboard.stx +14 -2
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: stacks-actions
|
|
3
|
-
description: Use when working with Stacks server actions - creating actions in app/Actions/, auto-generated API actions from the useApi model trait, the
|
|
3
|
+
description: Use when working with Stacks server actions - creating actions in app/Actions/, auto-generated API actions from the useApi model trait, the 780 default framework actions (auth, dashboard, commerce, content, deployment, jobs), action request/response handling, or action registration. Covers @stacksjs/actions and storage/framework/defaults/app/Actions/.
|
|
4
4
|
license: MIT
|
|
5
5
|
compatibility: Bun >= 1.3.0, TypeScript
|
|
6
6
|
allowed-tools: Read Edit Write Bash Grep Glob
|
|
@@ -197,10 +197,13 @@ The source of truth for dashboard mail settings is `.env`:
|
|
|
197
197
|
The dashboard endpoints are `GET` and `PUT` at
|
|
198
198
|
`/api/dashboard/mail-settings`. They are guarded outside local development,
|
|
199
199
|
return no stored secret values, preserve a secret when its input is blank, and
|
|
200
|
-
require an explicit clear flag to remove one.
|
|
201
|
-
environment-
|
|
202
|
-
|
|
203
|
-
|
|
200
|
+
require an explicit clear flag to remove one. Reads and writes go through the
|
|
201
|
+
environment-layers service: each value is read from, and saved to, the env
|
|
202
|
+
file the app loads it from, so a key set in `.env.<env>` is edited there and
|
|
203
|
+
not in `.env`. A mail key a later file holds encrypted beyond the server's
|
|
204
|
+
reach is named on the page. Writes are atomic, keep a machine-local backup
|
|
205
|
+
per file under `storage/framework/runtime/dashboard/`, and reject stale
|
|
206
|
+
revisions instead of overwriting concurrent edits.
|
|
204
207
|
|
|
205
208
|
## Driver Interface
|
|
206
209
|
|
|
@@ -190,6 +190,11 @@ import { loadEnv, autoLoadEnv, envPlugin } from '@stacksjs/env'
|
|
|
190
190
|
const loaded = loadEnv({ path: '.env', overload: false }) // { loaded, errors }
|
|
191
191
|
autoLoadEnv() // .env, .env.local, .env.<effectiveEnv>, .env.<effectiveEnv>.local
|
|
192
192
|
|
|
193
|
+
// The files autoLoadEnv reads, in that order, existing ones only. The last
|
|
194
|
+
// one that sets a key (and that this process can decrypt) is where the app's
|
|
195
|
+
// value comes from, so a tool that edits env files writes there.
|
|
196
|
+
environmentFiles(activeEnvName(), projectRoot) // ['.env', '.env.development']
|
|
197
|
+
|
|
193
198
|
// Bun plugin (auto-loads .env before app starts)
|
|
194
199
|
envPlugin()
|
|
195
200
|
```
|
|
@@ -313,21 +318,27 @@ The API is `partitionTenantEnv(values, { self, tenants })` from
|
|
|
313
318
|
|
|
314
319
|
## Dashboard environment editor
|
|
315
320
|
|
|
316
|
-
The dashboard reads and writes
|
|
317
|
-
`/api/dashboard/environment` GET and PUT endpoints
|
|
321
|
+
The dashboard reads and writes the env files the app loads through guarded
|
|
322
|
+
`/api/dashboard/environment` GET and PUT endpoints, which take a `file`:
|
|
323
|
+
`.env` by default, or any other file `environmentFiles()` lists. Any other
|
|
324
|
+
name is answered 404. The GET also lists the files and the keys in the open
|
|
325
|
+
one that a later file sets again (`keysReadElsewhere`), since the app reads
|
|
326
|
+
those from there. The write contract:
|
|
318
327
|
|
|
319
328
|
- validates uppercase environment keys and duplicate definitions
|
|
320
329
|
- limits the file to 1 MB and rejects null bytes
|
|
321
330
|
- requires the SHA-256 revision returned by the latest read
|
|
322
331
|
- writes through a 0600 temporary file and atomic rename
|
|
323
|
-
- stores the previous content under
|
|
324
|
-
`storage/framework/runtime/dashboard
|
|
332
|
+
- stores the previous content per file under
|
|
333
|
+
`storage/framework/runtime/dashboard/`: `environment.backup` for `.env`,
|
|
334
|
+
`environment.<suffix>.backup` for `.env.<suffix>`
|
|
325
335
|
- returns `Cache-Control: no-store` because the response contains secrets
|
|
326
336
|
|
|
327
|
-
Structured settings pages should use `
|
|
328
|
-
dashboard environment-
|
|
329
|
-
|
|
330
|
-
|
|
337
|
+
Structured settings pages should use `updateEnvironmentLayers()` from the
|
|
338
|
+
dashboard environment-layers service. It writes each named key to the env
|
|
339
|
+
file the app reads it from (`.env` when none sets it), keeps an encrypted
|
|
340
|
+
value encrypted under that file's public key, and preserves comments,
|
|
341
|
+
ordering, unrelated values, and the same revision and backup guarantees. Do not implement settings with repeated `writeFileSync`
|
|
331
342
|
calls or raw client-side `fetch`.
|
|
332
343
|
|
|
333
344
|
## Gotchas
|
|
@@ -92,7 +92,8 @@ of forcing a cast. See `orm/tests/inference-attributes.test-d.ts`.
|
|
|
92
92
|
| `nullable` | Explicit nullability override |
|
|
93
93
|
| `default` | Column default (`string \| number \| boolean \| Date`) |
|
|
94
94
|
| `unique` | Unique constraint |
|
|
95
|
-
| `type` | Force the column type instead of inferring from the rule |
|
|
95
|
+
| `type` | Force the column type instead of inferring from the rule. `'number'` is a decimal and wins over the rule (see Gotchas) |
|
|
96
|
+
| `precision` / `scale` | Digits of a decimal column, `decimal(precision, scale)`. Declaring either makes the column a decimal; unset is `decimal(10,2)` |
|
|
96
97
|
| `order` | Column order in the table and in dashboard forms |
|
|
97
98
|
| `fillable` | Allow mass assignment |
|
|
98
99
|
| `guarded` | Block mass assignment |
|
|
@@ -551,6 +552,14 @@ commands, not a project's resolved models.
|
|
|
551
552
|
`database/seeders` are also supported for ordered bootstrap work.
|
|
552
553
|
- **`hidden` is serialization, `guarded` is mass assignment.** They are different
|
|
553
554
|
protections; a password wants both `hidden` and no `fillable`.
|
|
555
|
+
- **A fractional number needs its digits declared.** `type: 'number'` maps to a
|
|
556
|
+
decimal column and wins over the validator, and an undeclared decimal is
|
|
557
|
+
`decimal(10,2)`. With `schema.float()` that silently rounds a probability of
|
|
558
|
+
0.6234 to 0.62. `generate:migrations` warns (`-- qb: ... rounded to 2 decimal
|
|
559
|
+
places`). Declare `precision` / `scale` (`precision: 8, scale: 6` for a 0-1
|
|
560
|
+
probability, `precision: 12, scale: 4` for a price), or `type: 'double'` for a
|
|
561
|
+
floating-point column. Adding them to an existing model emits a `MODIFY
|
|
562
|
+
COLUMN` / `ALTER COLUMN ... TYPE`; widening the scale is lossless.
|
|
554
563
|
- **Declared validation is enforced on ORM writes**, including quiet writes.
|
|
555
564
|
Type inference also accepts explicit types, factories, and defaults; absence
|
|
556
565
|
of a validator is not a promise that an arbitrary request body is safe.
|
|
@@ -21,7 +21,7 @@ Browser runtime bindings are documented separately in `stacks-auto-imports`.
|
|
|
21
21
|
| `@stacksjs/auth` | [`stacks-auth`](../stacks-auth/SKILL.md) | [entrypoint](https://github.com/stacksjs/stacks/blob/main/storage/framework/core/auth/src/index.ts) | 136 |
|
|
22
22
|
| `@stacksjs/browser` | [`stacks-browser`](../stacks-browser/SKILL.md) | [entrypoint](https://github.com/stacksjs/stacks/blob/main/storage/framework/core/browser/src/index.ts) | 10 |
|
|
23
23
|
| `@stacksjs/browser-extension` | [`stacks-browser-extension`](../stacks-browser-extension/SKILL.md) | [entrypoint](https://github.com/stacksjs/stacks/blob/main/storage/framework/core/browser-extension/src/index.ts) | 9 |
|
|
24
|
-
| `@stacksjs/buddy` | [`stacks-buddy`](../stacks-buddy/SKILL.md) | [entrypoint](https://github.com/stacksjs/stacks/blob/main/storage/framework/core/buddy/src/index.ts) |
|
|
24
|
+
| `@stacksjs/buddy` | [`stacks-buddy`](../stacks-buddy/SKILL.md) | [entrypoint](https://github.com/stacksjs/stacks/blob/main/storage/framework/core/buddy/src/index.ts) | 215 |
|
|
25
25
|
| `@stacksjs/build` | [`stacks-build`](../stacks-build/SKILL.md) | [entrypoint](https://github.com/stacksjs/stacks/blob/main/storage/framework/core/build/src/index.ts) | 7 |
|
|
26
26
|
| `@stacksjs/cache` | [`stacks-cache`](../stacks-cache/SKILL.md) | [entrypoint](https://github.com/stacksjs/stacks/blob/main/storage/framework/core/cache/src/index.ts) | 24 |
|
|
27
27
|
| `@stacksjs/calendar-api` | [`stacks-calendar`](../stacks-calendar/SKILL.md) | [entrypoint](https://github.com/stacksjs/stacks/blob/main/storage/framework/core/calendar-api/src/index.ts) | 5 |
|
|
@@ -45,7 +45,7 @@ Browser runtime bindings are documented separately in `stacks-auto-imports`.
|
|
|
45
45
|
| `@stacksjs/docs` | [`stacks-docs`](../stacks-docs/SKILL.md) | [entrypoint](https://github.com/stacksjs/stacks/blob/main/storage/framework/core/docs/src/index.ts) | 5 |
|
|
46
46
|
| `@stacksjs/email` | [`stacks-email`](../stacks-email/SKILL.md) | [entrypoint](https://github.com/stacksjs/stacks/blob/main/storage/framework/core/email/src/index.ts) | 27 |
|
|
47
47
|
| `@stacksjs/enums` | [`stacks-enums`](../stacks-enums/SKILL.md) | [entrypoint](https://github.com/stacksjs/stacks/blob/main/storage/framework/core/enums/src/index.ts) | 3 |
|
|
48
|
-
| `@stacksjs/env` | [`stacks-env`](../stacks-env/SKILL.md) | [entrypoint](https://github.com/stacksjs/stacks/blob/main/storage/framework/core/env/src/index.ts) |
|
|
48
|
+
| `@stacksjs/env` | [`stacks-env`](../stacks-env/SKILL.md) | [entrypoint](https://github.com/stacksjs/stacks/blob/main/storage/framework/core/env/src/index.ts) | 33 |
|
|
49
49
|
| `@stacksjs/error-handling` | [`stacks-error-handling`](../stacks-error-handling/SKILL.md) | [entrypoint](https://github.com/stacksjs/stacks/blob/main/storage/framework/core/error-handling/src/index.ts) | 10 |
|
|
50
50
|
| `@stacksjs/events` | [`stacks-events`](../stacks-events/SKILL.md) | [entrypoint](https://github.com/stacksjs/stacks/blob/main/storage/framework/core/events/src/index.ts) | 13 |
|
|
51
51
|
| `@stacksjs/faker` | [`stacks-faker`](../stacks-faker/SKILL.md) | [entrypoint](https://github.com/stacksjs/stacks/blob/main/storage/framework/core/faker/src/index.ts) | 1 |
|
|
@@ -222,7 +222,7 @@ Read the entrypoint and package export map for re-exported or type-only surfaces
|
|
|
222
222
|
|
|
223
223
|
Local source modules: [src/commands/index.ts](https://github.com/stacksjs/stacks/blob/main/storage/framework/core/buddy/src/commands/index.ts).
|
|
224
224
|
|
|
225
|
-
Evidence directory: [
|
|
225
|
+
Evidence directory: [215 retained tests](https://github.com/stacksjs/stacks/blob/main/storage/framework/core/buddy/tests). These files are evidence pointers, not a claim that all tests were run for this catalog.
|
|
226
226
|
|
|
227
227
|
### @stacksjs/build
|
|
228
228
|
|
|
@@ -452,7 +452,7 @@ Read the entrypoint and package export map for re-exported or type-only surfaces
|
|
|
452
452
|
|
|
453
453
|
Local source modules: [src/cli.ts](https://github.com/stacksjs/stacks/blob/main/storage/framework/core/env/src/cli.ts), [src/crypto.ts](https://github.com/stacksjs/stacks/blob/main/storage/framework/core/env/src/crypto.ts), [src/deployment.ts](https://github.com/stacksjs/stacks/blob/main/storage/framework/core/env/src/deployment.ts), [src/integrations.ts](https://github.com/stacksjs/stacks/blob/main/storage/framework/core/env/src/integrations.ts), [src/numeric-keys.ts](https://github.com/stacksjs/stacks/blob/main/storage/framework/core/env/src/numeric-keys.ts), [src/parser.ts](https://github.com/stacksjs/stacks/blob/main/storage/framework/core/env/src/parser.ts), [src/plaintext.ts](https://github.com/stacksjs/stacks/blob/main/storage/framework/core/env/src/plaintext.ts), [src/plugin.ts](https://github.com/stacksjs/stacks/blob/main/storage/framework/core/env/src/plugin.ts), [src/runtime.ts](https://github.com/stacksjs/stacks/blob/main/storage/framework/core/env/src/runtime.ts), [src/tenants.ts](https://github.com/stacksjs/stacks/blob/main/storage/framework/core/env/src/tenants.ts), [src/types.ts](https://github.com/stacksjs/stacks/blob/main/storage/framework/core/env/src/types.ts), [src/utils.ts](https://github.com/stacksjs/stacks/blob/main/storage/framework/core/env/src/utils.ts), [src/withheld.ts](https://github.com/stacksjs/stacks/blob/main/storage/framework/core/env/src/withheld.ts).
|
|
454
454
|
|
|
455
|
-
Evidence directory: [
|
|
455
|
+
Evidence directory: [33 retained tests](https://github.com/stacksjs/stacks/blob/main/storage/framework/core/env/tests). These files are evidence pointers, not a claim that all tests were run for this catalog.
|
|
456
456
|
|
|
457
457
|
### @stacksjs/error-handling
|
|
458
458
|
|
|
@@ -1,19 +1,21 @@
|
|
|
1
|
+
import type { RequestInstance } from '@stacksjs/types'
|
|
1
2
|
import { Action } from '@stacksjs/actions/runtime'
|
|
3
|
+
import { response } from '@stacksjs/router'
|
|
2
4
|
import { dashboardOperationalError } from '../dashboard-response'
|
|
3
|
-
import {
|
|
5
|
+
import { readEnvironmentPage } from './environment-page'
|
|
4
6
|
|
|
5
7
|
export default new Action({
|
|
6
8
|
name: 'EnvironmentIndexAction',
|
|
7
|
-
description: 'Returns the
|
|
9
|
+
description: 'Returns one of the env files the app loads, its latest dashboard backup, and the keys a later file overrides.',
|
|
8
10
|
method: 'GET',
|
|
9
11
|
apiResponse: true,
|
|
10
12
|
|
|
11
|
-
async handle() {
|
|
13
|
+
async handle(request: RequestInstance) {
|
|
12
14
|
try {
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
)
|
|
15
|
+
const page = await readEnvironmentPage(request.get('file'))
|
|
16
|
+
if (!page)
|
|
17
|
+
return response.json({ message: 'That is not one of the env files this app loads.' }, 404)
|
|
18
|
+
return Response.json(page, { headers: { 'Cache-Control': 'no-store', Pragma: 'no-cache' } })
|
|
17
19
|
}
|
|
18
20
|
catch (error) {
|
|
19
21
|
return dashboardOperationalError(error, 'Environment file could not be loaded.', 'EnvironmentIndexAction')
|
|
@@ -2,11 +2,11 @@ import type { RequestInstance } from '@stacksjs/types'
|
|
|
2
2
|
import { Action } from '@stacksjs/actions/runtime'
|
|
3
3
|
import { response } from '@stacksjs/router'
|
|
4
4
|
import { dashboardOperationalError } from '../dashboard-response'
|
|
5
|
-
import {
|
|
5
|
+
import { saveEnvironmentPage } from './environment-page'
|
|
6
6
|
|
|
7
7
|
export default new Action({
|
|
8
8
|
name: 'EnvironmentUpdateAction',
|
|
9
|
-
description: 'Validates and atomically updates the
|
|
9
|
+
description: 'Validates and atomically updates one of the env files the app loads.',
|
|
10
10
|
method: 'PUT',
|
|
11
11
|
apiResponse: true,
|
|
12
12
|
|
|
@@ -21,11 +21,13 @@ export default new Action({
|
|
|
21
21
|
|
|
22
22
|
let result
|
|
23
23
|
try {
|
|
24
|
-
result = await
|
|
24
|
+
result = await saveEnvironmentPage(request.get('file'), content, revision)
|
|
25
25
|
}
|
|
26
26
|
catch (error) {
|
|
27
27
|
return dashboardOperationalError(error, 'Environment file could not be saved.', 'EnvironmentUpdateAction', 500)
|
|
28
28
|
}
|
|
29
|
+
if (result.unknownFile)
|
|
30
|
+
return response.json({ message: 'That is not one of the env files this app loads.' }, 404)
|
|
29
31
|
if (result.issues?.length) {
|
|
30
32
|
const errors = Object.fromEntries(result.issues.map((issue, index) => [
|
|
31
33
|
issue.line ? String(issue.line) : `file-${index}`,
|
|
@@ -43,10 +45,7 @@ export default new Action({
|
|
|
43
45
|
}
|
|
44
46
|
|
|
45
47
|
return Response.json(
|
|
46
|
-
{
|
|
47
|
-
success: true,
|
|
48
|
-
environment: result.state,
|
|
49
|
-
},
|
|
48
|
+
{ success: true, ...result.page },
|
|
50
49
|
{ headers: { 'Cache-Control': 'no-store', Pragma: 'no-cache' } },
|
|
51
50
|
)
|
|
52
51
|
},
|
|
@@ -20,7 +20,8 @@ export interface EnvironmentFileIssue {
|
|
|
20
20
|
}
|
|
21
21
|
|
|
22
22
|
export interface EnvironmentFileState {
|
|
23
|
-
|
|
23
|
+
/** The file's name in the project directory: `.env`, `.env.development`, ... */
|
|
24
|
+
path: string
|
|
24
25
|
content: string
|
|
25
26
|
revision: string
|
|
26
27
|
exists: boolean
|
|
@@ -33,16 +34,31 @@ export interface EnvironmentFileState {
|
|
|
33
34
|
}
|
|
34
35
|
|
|
35
36
|
export interface EnvironmentFileOptions {
|
|
37
|
+
/** The file's name in the project directory. Default `.env`. */
|
|
38
|
+
name?: string
|
|
39
|
+
/** Where it is. Default: `name` in the project root. */
|
|
36
40
|
envPath?: string
|
|
41
|
+
/** Where the content it replaced is kept. Default: {@link environmentBackupPath}. */
|
|
37
42
|
backupPath?: string
|
|
38
43
|
}
|
|
39
44
|
|
|
45
|
+
/**
|
|
46
|
+
* Where the dashboard keeps the content an env file had before its latest
|
|
47
|
+
* save: one backup per file, so saving `.env.development` does not replace
|
|
48
|
+
* the copy of `.env`. `.env` keeps the location it always had.
|
|
49
|
+
*/
|
|
50
|
+
export function environmentBackupPath(file: string): string {
|
|
51
|
+
return frameworkRuntimePath(file === '.env' ? 'dashboard/environment.backup' : `dashboard/environment${file.slice('.env'.length)}.backup`)
|
|
52
|
+
}
|
|
53
|
+
|
|
40
54
|
export type EnvironmentEntryUpdates = Record<string, string>
|
|
41
55
|
|
|
42
|
-
function resolvedPaths(options: EnvironmentFileOptions = {}): { envPath: string, backupPath: string } {
|
|
56
|
+
function resolvedPaths(options: EnvironmentFileOptions = {}): { name: string, envPath: string, backupPath: string } {
|
|
57
|
+
const name = options.name ?? '.env'
|
|
43
58
|
return {
|
|
44
|
-
|
|
45
|
-
|
|
59
|
+
name,
|
|
60
|
+
envPath: options.envPath ?? projectPath(name),
|
|
61
|
+
backupPath: options.backupPath ?? environmentBackupPath(name),
|
|
46
62
|
}
|
|
47
63
|
}
|
|
48
64
|
|
|
@@ -101,7 +117,11 @@ function serializeEnvironmentValue(value: string): string {
|
|
|
101
117
|
.replace(/\n/g, '\\n')}"`
|
|
102
118
|
}
|
|
103
119
|
|
|
104
|
-
|
|
120
|
+
/**
|
|
121
|
+
* Write a file the way an env file has to be written: whole or not at all
|
|
122
|
+
* (a same-directory rename), and readable by its owner only.
|
|
123
|
+
*/
|
|
124
|
+
export async function atomicWrite(path: string, content: string): Promise<void> {
|
|
105
125
|
await mkdir(dirname(path), { recursive: true })
|
|
106
126
|
const temporaryPath = join(
|
|
107
127
|
dirname(path),
|
|
@@ -232,7 +252,7 @@ export async function readEnvironmentFile(options: EnvironmentFileOptions = {}):
|
|
|
232
252
|
])
|
|
233
253
|
|
|
234
254
|
return {
|
|
235
|
-
path:
|
|
255
|
+
path: paths.name,
|
|
236
256
|
content: environment.content,
|
|
237
257
|
revision: revisionFor(environment.content),
|
|
238
258
|
exists: environment.exists,
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
import { afterEach, describe, expect, test } from 'bun:test'
|
|
2
|
+
import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
|
|
3
|
+
import { tmpdir } from 'node:os'
|
|
4
|
+
import { join } from 'node:path'
|
|
5
|
+
import { decryptValue, encryptValue, generateKeypair } from '@stacksjs/env'
|
|
6
|
+
import { readEnvironmentLayers, updateEnvironmentLayers } from './environment-layers'
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* The env files the app loads, read and written the way it loads them
|
|
10
|
+
* (stacksjs/stacks#3340): a later file wins, an encrypted entry this process
|
|
11
|
+
* cannot decrypt does not, and an encrypted value stays encrypted.
|
|
12
|
+
*/
|
|
13
|
+
const directories: string[] = []
|
|
14
|
+
|
|
15
|
+
/** A project in a temp folder; every backup goes in its own `runtime/`, never the checkout's. */
|
|
16
|
+
function project(files: Record<string, string>): { cwd: string, backupPathFor: (file: string) => string } {
|
|
17
|
+
const cwd = mkdtempSync(join(tmpdir(), 'stacks-env-layers-'))
|
|
18
|
+
directories.push(cwd)
|
|
19
|
+
for (const [name, content] of Object.entries(files))
|
|
20
|
+
writeFileSync(join(cwd, name), content)
|
|
21
|
+
return { cwd, backupPathFor: (file: string) => join(cwd, 'runtime', `${file}.backup`) }
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function text(cwd: string, file: string): string {
|
|
25
|
+
return readFileSync(join(cwd, file), 'utf8')
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
afterEach(() => {
|
|
29
|
+
for (const directory of directories.splice(0))
|
|
30
|
+
rmSync(directory, { recursive: true, force: true })
|
|
31
|
+
})
|
|
32
|
+
|
|
33
|
+
describe('environment layers', () => {
|
|
34
|
+
test('a key set again in a later file comes from that file, and is saved there', async () => {
|
|
35
|
+
const location = project({
|
|
36
|
+
'.env': 'MAIL_HOST=base.test\nMAIL_PORT=25\n',
|
|
37
|
+
'.env.staging': 'MAIL_HOST=staging.test\n',
|
|
38
|
+
})
|
|
39
|
+
const options = { ...location, env: 'staging', privateKey: null }
|
|
40
|
+
|
|
41
|
+
const layers = await readEnvironmentLayers(options)
|
|
42
|
+
expect(layers.layers.map(layer => layer.file)).toEqual(['.env', '.env.staging'])
|
|
43
|
+
expect(layers.entries.MAIL_HOST).toBe('staging.test')
|
|
44
|
+
expect(layers.sources).toMatchObject({ MAIL_HOST: '.env.staging', MAIL_PORT: '.env' })
|
|
45
|
+
|
|
46
|
+
const saved = await updateEnvironmentLayers({ MAIL_HOST: 'saved.test', MAIL_PORT: '2525', MAIL_MAILER: 'smtp' }, layers.revision, options)
|
|
47
|
+
expect(saved.layers?.entries).toMatchObject({ MAIL_HOST: 'saved.test', MAIL_PORT: '2525', MAIL_MAILER: 'smtp' })
|
|
48
|
+
expect(text(location.cwd, '.env.staging')).toBe('MAIL_HOST=saved.test\n')
|
|
49
|
+
// A key no file sets is added to `.env`.
|
|
50
|
+
expect(text(location.cwd, '.env')).toBe('MAIL_HOST=base.test\nMAIL_PORT=2525\n\nMAIL_MAILER=smtp\n')
|
|
51
|
+
// Each file it replaced is kept, under its own name.
|
|
52
|
+
expect(text(location.cwd, 'runtime/.env.backup')).toBe('MAIL_HOST=base.test\nMAIL_PORT=25\n')
|
|
53
|
+
expect(text(location.cwd, 'runtime/.env.staging.backup')).toBe('MAIL_HOST=staging.test\n')
|
|
54
|
+
})
|
|
55
|
+
|
|
56
|
+
test('an encrypted entry with no key to read it does not win, and is named', async () => {
|
|
57
|
+
const { publicKey } = generateKeypair()
|
|
58
|
+
const location = project({
|
|
59
|
+
'.env': 'MAIL_HOST=base.test\n',
|
|
60
|
+
'.env.staging': `DOTENV_PUBLIC_KEY_STAGING=${publicKey}\nMAIL_HOST="${encryptValue('staging.test', publicKey)}"\n`,
|
|
61
|
+
})
|
|
62
|
+
const options = { ...location, env: 'staging', privateKey: null }
|
|
63
|
+
|
|
64
|
+
const layers = await readEnvironmentLayers(options)
|
|
65
|
+
expect(layers.entries.MAIL_HOST).toBe('base.test')
|
|
66
|
+
expect(layers.sources.MAIL_HOST).toBe('.env')
|
|
67
|
+
expect(layers.unreadable).toEqual({ MAIL_HOST: '.env.staging' })
|
|
68
|
+
|
|
69
|
+
const staging = text(location.cwd, '.env.staging')
|
|
70
|
+
await updateEnvironmentLayers({ MAIL_HOST: 'saved.test' }, layers.revision, options)
|
|
71
|
+
expect(text(location.cwd, '.env')).toBe('MAIL_HOST=saved.test\n')
|
|
72
|
+
expect(text(location.cwd, '.env.staging')).toBe(staging)
|
|
73
|
+
})
|
|
74
|
+
|
|
75
|
+
test('an encrypted value is read decrypted and saved encrypted, under its file\'s key', async () => {
|
|
76
|
+
const { publicKey, privateKey } = generateKeypair()
|
|
77
|
+
const location = project({
|
|
78
|
+
'.env': 'MAIL_HOST=base.test\n',
|
|
79
|
+
'.env.staging': `DOTENV_PUBLIC_KEY_STAGING=${publicKey}\nMAIL_HOST="${encryptValue('staging.test', publicKey)}"\nMAIL_PASSWORD=plain-before\n`,
|
|
80
|
+
})
|
|
81
|
+
const options = { ...location, env: 'staging', privateKey, secrets: ['MAIL_PASSWORD'] }
|
|
82
|
+
|
|
83
|
+
const layers = await readEnvironmentLayers(options)
|
|
84
|
+
expect(layers.entries.MAIL_HOST).toBe('staging.test')
|
|
85
|
+
expect(layers.sources.MAIL_HOST).toBe('.env.staging')
|
|
86
|
+
|
|
87
|
+
await updateEnvironmentLayers({ MAIL_HOST: 'saved.test', MAIL_PASSWORD: 'new-secret' }, layers.revision, options)
|
|
88
|
+
const staging = Object.fromEntries(text(location.cwd, '.env.staging').trim().split('\n').map(line => [line.slice(0, line.indexOf('=')), line.slice(line.indexOf('=') + 1).replace(/^"|"$/g, '')]))
|
|
89
|
+
expect(staging.MAIL_HOST).toStartWith('encrypted:')
|
|
90
|
+
expect(decryptValue(staging.MAIL_HOST!, privateKey)).toBe('saved.test')
|
|
91
|
+
// A secret is encrypted in a file that holds ciphertext, even where it was plain.
|
|
92
|
+
expect(staging.MAIL_PASSWORD).toStartWith('encrypted:')
|
|
93
|
+
expect(decryptValue(staging.MAIL_PASSWORD!, privateKey)).toBe('new-secret')
|
|
94
|
+
expect(text(location.cwd, '.env')).toBe('MAIL_HOST=base.test\n')
|
|
95
|
+
expect((await readEnvironmentLayers(options)).entries.MAIL_HOST).toBe('saved.test')
|
|
96
|
+
})
|
|
97
|
+
|
|
98
|
+
test('refuses to write a value that has to be encrypted when its file declares no public key', async () => {
|
|
99
|
+
const { publicKey, privateKey } = generateKeypair()
|
|
100
|
+
const location = project({ '.env.staging': `MAIL_HOST="${encryptValue('staging.test', publicKey)}"\n` })
|
|
101
|
+
const options = { ...location, env: 'staging', privateKey }
|
|
102
|
+
const before = text(location.cwd, '.env.staging')
|
|
103
|
+
|
|
104
|
+
const layers = await readEnvironmentLayers(options)
|
|
105
|
+
const result = await updateEnvironmentLayers({ MAIL_HOST: 'saved.test' }, layers.revision, options)
|
|
106
|
+
expect(result.issues).toEqual([{ key: 'MAIL_HOST', message: '.env.staging holds encrypted values but declares no public key. Repair it before changing MAIL_HOST.' }])
|
|
107
|
+
expect(text(location.cwd, '.env.staging')).toBe(before)
|
|
108
|
+
})
|
|
109
|
+
|
|
110
|
+
test('refuses a write when any file changed since it was read', async () => {
|
|
111
|
+
const location = project({ '.env': 'MAIL_HOST=base.test\n', '.env.staging': 'MAIL_PORT=25\n' })
|
|
112
|
+
const options = { ...location, env: 'staging', privateKey: null }
|
|
113
|
+
const layers = await readEnvironmentLayers(options)
|
|
114
|
+
|
|
115
|
+
writeFileSync(join(location.cwd, '.env.staging'), 'MAIL_PORT=587\n')
|
|
116
|
+
expect(await updateEnvironmentLayers({ MAIL_HOST: 'saved.test' }, layers.revision, options)).toEqual({ conflict: true })
|
|
117
|
+
expect(text(location.cwd, '.env')).toBe('MAIL_HOST=base.test\n')
|
|
118
|
+
})
|
|
119
|
+
|
|
120
|
+
test('writes .env when the project has no env file yet', async () => {
|
|
121
|
+
const location = project({})
|
|
122
|
+
const options = { ...location, env: 'staging', privateKey: null }
|
|
123
|
+
const layers = await readEnvironmentLayers(options)
|
|
124
|
+
expect(layers.layers).toEqual([])
|
|
125
|
+
|
|
126
|
+
await updateEnvironmentLayers({ MAIL_MAILER: 'log' }, layers.revision, options)
|
|
127
|
+
expect(text(location.cwd, '.env')).toBe('MAIL_MAILER=log\n')
|
|
128
|
+
})
|
|
129
|
+
})
|
|
@@ -0,0 +1,235 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto'
|
|
2
|
+
import { readFile } from 'node:fs/promises'
|
|
3
|
+
import { join } from 'node:path'
|
|
4
|
+
import { activeEnvName, declaredEnvPublicKey, encryptValue, environmentFiles, envHasCiphertext, parse, resolvePrivateKey } from '@stacksjs/env'
|
|
5
|
+
import { projectPath } from '@stacksjs/path'
|
|
6
|
+
import { applyEnvironmentEntries, atomicWrite, environmentBackupPath, parseEnvironmentEntries, validateEnvironmentFile } from './environment-file'
|
|
7
|
+
import type { EnvironmentFileIssue } from './environment-file'
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* The env files the app loads, read the way it loads them (stacksjs/stacks#3340).
|
|
11
|
+
*
|
|
12
|
+
* The app reads `.env`, `.env.local`, `.env.<env>` and `.env.<env>.local`
|
|
13
|
+
* (`environmentFiles` in @stacksjs/env), and a later file's value replaces an
|
|
14
|
+
* earlier one's. A page that reads and writes `.env` alone shows values the
|
|
15
|
+
* app is not using as soon as another file sets the same key, and its saves
|
|
16
|
+
* change nothing the app reads.
|
|
17
|
+
*
|
|
18
|
+
* So values are read from every file, each with the loader's own parser and
|
|
19
|
+
* private key, and a write goes to the file a key's value comes from.
|
|
20
|
+
*
|
|
21
|
+
* The parser is the loader's, expansion included: a value written
|
|
22
|
+
* `${OTHER}` or `$(allowed-command)` reads as the app reads it.
|
|
23
|
+
*/
|
|
24
|
+
|
|
25
|
+
export interface EnvironmentLayersOptions {
|
|
26
|
+
/** The project directory. Default: the project root. */
|
|
27
|
+
cwd?: string
|
|
28
|
+
/** The environment whose files are read. Default: the one the app loaded (`activeEnvName`). */
|
|
29
|
+
env?: string
|
|
30
|
+
/** The key encrypted values are decrypted with. Default: the app's (`resolvePrivateKey`); null for none. */
|
|
31
|
+
privateKey?: string | null
|
|
32
|
+
/** Where the content a file had before a save is kept. Default: {@link environmentBackupPath}. */
|
|
33
|
+
backupPathFor?: (file: string) => string
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export interface EnvironmentLayer {
|
|
37
|
+
/** The file's name in the project directory, e.g. `.env.development`. */
|
|
38
|
+
file: string
|
|
39
|
+
content: string
|
|
40
|
+
/** Its entries as written, ciphertext and all. */
|
|
41
|
+
raw: Record<string, string>
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export interface EnvironmentLayers {
|
|
45
|
+
/** A hash of every file's name and content; a write is refused when it changed. */
|
|
46
|
+
revision: string
|
|
47
|
+
/** The files that exist, in the order the app loads them. */
|
|
48
|
+
layers: EnvironmentLayer[]
|
|
49
|
+
/** The values the app reads, decrypted. */
|
|
50
|
+
entries: Record<string, string>
|
|
51
|
+
/** For each key, the file its value comes from. */
|
|
52
|
+
sources: Record<string, string>
|
|
53
|
+
/**
|
|
54
|
+
* Keys a file loaded after the winning one sets with ciphertext this process
|
|
55
|
+
* cannot decrypt. The loader skips such an entry, so it does not win here;
|
|
56
|
+
* wherever its key is present, it does, and replaces what was saved.
|
|
57
|
+
*/
|
|
58
|
+
unreadable: Record<string, string>
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export interface EnvironmentLayersIssue {
|
|
62
|
+
/** The env key the issue is about, or the file for a whole-file problem. */
|
|
63
|
+
key: string
|
|
64
|
+
message: string
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
function resolved(options: EnvironmentLayersOptions): { cwd: string, privateKey: string | undefined, backupPathFor: (file: string) => string, env: string } {
|
|
68
|
+
const cwd = options.cwd ?? projectPath()
|
|
69
|
+
const env = options.env ?? activeEnvName()
|
|
70
|
+
return {
|
|
71
|
+
cwd,
|
|
72
|
+
env,
|
|
73
|
+
privateKey: options.privateKey === null ? undefined : (options.privateKey ?? resolvePrivateKey({ env, cwd })),
|
|
74
|
+
backupPathFor: options.backupPathFor ?? environmentBackupPath,
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function isCiphertext(value: string | undefined): boolean {
|
|
79
|
+
return Boolean(value && (value.startsWith('encrypted:') || value.startsWith('enc:')))
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
function revisionOf(layers: EnvironmentLayer[]): string {
|
|
83
|
+
const hash = createHash('sha256')
|
|
84
|
+
for (const layer of layers)
|
|
85
|
+
hash.update(layer.file).update('\0').update(layer.content).update('\0')
|
|
86
|
+
return hash.digest('hex')
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** Every env file the app loads, and the value it reads for each key. */
|
|
90
|
+
export async function readEnvironmentLayers(options: EnvironmentLayersOptions = {}): Promise<EnvironmentLayers> {
|
|
91
|
+
const { cwd, env, privateKey } = resolved(options)
|
|
92
|
+
const layers: EnvironmentLayer[] = []
|
|
93
|
+
for (const file of environmentFiles(env, cwd)) {
|
|
94
|
+
const content = await readFile(join(cwd, file), 'utf8')
|
|
95
|
+
layers.push({ file, content, raw: parseEnvironmentEntries(content) })
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
const entries: Record<string, string> = {}
|
|
99
|
+
const sources: Record<string, string> = {}
|
|
100
|
+
const unreadable: Record<string, string> = {}
|
|
101
|
+
for (const layer of layers) {
|
|
102
|
+
const { parsed, skippedEncrypted } = parse(layer.content, {
|
|
103
|
+
privateKey,
|
|
104
|
+
processEnv: process.env as Record<string, string>,
|
|
105
|
+
})
|
|
106
|
+
for (const [key, value] of Object.entries(parsed)) {
|
|
107
|
+
entries[key] = value
|
|
108
|
+
sources[key] = layer.file
|
|
109
|
+
delete unreadable[key]
|
|
110
|
+
}
|
|
111
|
+
for (const key of skippedEncrypted)
|
|
112
|
+
unreadable[key] = layer.file
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
return { revision: revisionOf(layers), layers, entries, sources, unreadable }
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** Each layer checked as a file: a malformed one is named, with its line. */
|
|
119
|
+
export function environmentLayerIssues(layers: EnvironmentLayers): Array<EnvironmentFileIssue & { file: string }> {
|
|
120
|
+
return layers.layers.flatMap(layer => validateEnvironmentFile(layer.content).map(issue => ({ ...issue, file: layer.file })))
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/**
|
|
124
|
+
* Write each key to the file the app reads it from, or to `.env` when no file
|
|
125
|
+
* sets it.
|
|
126
|
+
*
|
|
127
|
+
* A value that is encrypted in that file stays encrypted, under the file's own
|
|
128
|
+
* public key, and so does a key named in `secrets` in a file that holds any
|
|
129
|
+
* ciphertext. An empty value is written as it is. Each changed file is
|
|
130
|
+
* replaced atomically, after its old content is kept as its backup.
|
|
131
|
+
*/
|
|
132
|
+
export async function updateEnvironmentLayers(
|
|
133
|
+
updates: Record<string, string>,
|
|
134
|
+
revision: string,
|
|
135
|
+
options: EnvironmentLayersOptions & { secrets?: readonly string[] } = {},
|
|
136
|
+
): Promise<{ layers?: EnvironmentLayers, conflict?: true, issues?: EnvironmentLayersIssue[] }> {
|
|
137
|
+
const current = await readEnvironmentLayers(options)
|
|
138
|
+
if (current.revision !== revision)
|
|
139
|
+
return { conflict: true }
|
|
140
|
+
|
|
141
|
+
const { cwd, backupPathFor } = resolved(options)
|
|
142
|
+
const secrets = new Set(options.secrets ?? [])
|
|
143
|
+
const byFile = new Map<string, Record<string, string>>()
|
|
144
|
+
const issues: EnvironmentLayersIssue[] = []
|
|
145
|
+
|
|
146
|
+
for (const [key, value] of Object.entries(updates)) {
|
|
147
|
+
const file = current.sources[key] ?? '.env'
|
|
148
|
+
const layer = current.layers.find(candidate => candidate.file === file)
|
|
149
|
+
const content = layer?.content ?? ''
|
|
150
|
+
const encrypt = value !== '' && (isCiphertext(layer?.raw[key]) || (secrets.has(key) && envHasCiphertext(content)))
|
|
151
|
+
|
|
152
|
+
let written = value
|
|
153
|
+
if (encrypt) {
|
|
154
|
+
const publicKey = declaredEnvPublicKey(content, file)?.key
|
|
155
|
+
if (!publicKey) {
|
|
156
|
+
issues.push({ key, message: `${file} holds encrypted values but declares no public key. Repair it before changing ${key}.` })
|
|
157
|
+
continue
|
|
158
|
+
}
|
|
159
|
+
try {
|
|
160
|
+
written = encryptValue(value, publicKey)
|
|
161
|
+
}
|
|
162
|
+
catch {
|
|
163
|
+
issues.push({ key, message: `${key} could not be encrypted with the public key ${file} declares.` })
|
|
164
|
+
continue
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
byFile.set(file, { ...byFile.get(file), [key]: written })
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
if (issues.length)
|
|
172
|
+
return { issues }
|
|
173
|
+
|
|
174
|
+
const rewritten = [...byFile].map(([file, fileUpdates]) => {
|
|
175
|
+
const layer = current.layers.find(candidate => candidate.file === file)
|
|
176
|
+
return { file, before: layer?.content, after: applyEnvironmentEntries(layer?.content ?? '', fileUpdates) }
|
|
177
|
+
})
|
|
178
|
+
for (const { file, after } of rewritten) {
|
|
179
|
+
for (const issue of validateEnvironmentFile(after))
|
|
180
|
+
issues.push({ key: file, message: issue.line ? `${file} line ${issue.line}: ${issue.message}` : `${file}: ${issue.message}` })
|
|
181
|
+
}
|
|
182
|
+
if (issues.length)
|
|
183
|
+
return { issues }
|
|
184
|
+
|
|
185
|
+
for (const { file, before, after } of rewritten) {
|
|
186
|
+
if (before !== undefined)
|
|
187
|
+
await atomicWrite(backupPathFor(file), before)
|
|
188
|
+
await atomicWrite(join(cwd, file), after)
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
return { layers: await readEnvironmentLayers(options) }
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/**
|
|
195
|
+
* The env files a person can open on the Environment page: `.env`, which a
|
|
196
|
+
* project always has a place for, and every other file the app loads. A file
|
|
197
|
+
* name from a request is only ever one of these, so it cannot name a path.
|
|
198
|
+
*/
|
|
199
|
+
export function editableEnvironmentFiles(layers: EnvironmentLayers): string[] {
|
|
200
|
+
return ['.env', ...layers.layers.map(layer => layer.file).filter(file => file !== '.env')]
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
export interface KeyReadElsewhere {
|
|
204
|
+
key: string
|
|
205
|
+
/** The later file the app reads the key from instead. */
|
|
206
|
+
file: string
|
|
207
|
+
/**
|
|
208
|
+
* False when that file holds it encrypted and this server cannot decrypt it:
|
|
209
|
+
* the app here still reads this file's value, but wherever that file's key
|
|
210
|
+
* is present, it reads the later one.
|
|
211
|
+
*/
|
|
212
|
+
readable: boolean
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
/**
|
|
216
|
+
* The keys a file sets whose value the app takes from a file it loads later,
|
|
217
|
+
* so editing them in this one changes nothing it reads.
|
|
218
|
+
*/
|
|
219
|
+
export function keysReadElsewhere(layers: EnvironmentLayers, file: string): KeyReadElsewhere[] {
|
|
220
|
+
const order = layers.layers.map(layer => layer.file)
|
|
221
|
+
const position = order.indexOf(file)
|
|
222
|
+
const layer = layers.layers[position]
|
|
223
|
+
if (!layer)
|
|
224
|
+
return []
|
|
225
|
+
|
|
226
|
+
return Object.keys(layer.raw).flatMap((key): KeyReadElsewhere[] => {
|
|
227
|
+
const source = layers.sources[key]
|
|
228
|
+
if (source && order.indexOf(source) > position)
|
|
229
|
+
return [{ key, file: source, readable: true }]
|
|
230
|
+
const unreadable = layers.unreadable[key]
|
|
231
|
+
if (unreadable && order.indexOf(unreadable) > position)
|
|
232
|
+
return [{ key, file: unreadable, readable: false }]
|
|
233
|
+
return []
|
|
234
|
+
})
|
|
235
|
+
}
|