@stacksjs/defaults 0.75.630 → 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 +14 -8
- package/ai/skills/stacks-models/SKILL.md +10 -1
- 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 +21 -5
- package/app/Actions/Dashboard/Infrastructure/environment-layers.test.ts +6 -3
- package/app/Actions/Dashboard/Infrastructure/environment-layers.ts +53 -10
- 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 +4 -3
- package/ide/vscode/package.json +1 -1
- package/package.json +5 -5
- package/resources/components/Dashboard/Environment/EnvironmentDashboard.stx +60 -8
|
@@ -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
|
|
|
@@ -318,21 +318,27 @@ The API is `partitionTenantEnv(values, { self, tenants })` from
|
|
|
318
318
|
|
|
319
319
|
## Dashboard environment editor
|
|
320
320
|
|
|
321
|
-
The dashboard reads and writes
|
|
322
|
-
`/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:
|
|
323
327
|
|
|
324
328
|
- validates uppercase environment keys and duplicate definitions
|
|
325
329
|
- limits the file to 1 MB and rejects null bytes
|
|
326
330
|
- requires the SHA-256 revision returned by the latest read
|
|
327
331
|
- writes through a 0600 temporary file and atomic rename
|
|
328
|
-
- stores the previous content under
|
|
329
|
-
`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>`
|
|
330
335
|
- returns `Cache-Control: no-store` because the response contains secrets
|
|
331
336
|
|
|
332
|
-
Structured settings pages should use `
|
|
333
|
-
dashboard environment-
|
|
334
|
-
|
|
335
|
-
|
|
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`
|
|
336
342
|
calls or raw client-side `fetch`.
|
|
337
343
|
|
|
338
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.
|
|
@@ -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
|
|
|
@@ -236,7 +252,7 @@ export async function readEnvironmentFile(options: EnvironmentFileOptions = {}):
|
|
|
236
252
|
])
|
|
237
253
|
|
|
238
254
|
return {
|
|
239
|
-
path:
|
|
255
|
+
path: paths.name,
|
|
240
256
|
content: environment.content,
|
|
241
257
|
revision: revisionFor(environment.content),
|
|
242
258
|
exists: environment.exists,
|
|
@@ -12,12 +12,13 @@ import { readEnvironmentLayers, updateEnvironmentLayers } from './environment-la
|
|
|
12
12
|
*/
|
|
13
13
|
const directories: string[] = []
|
|
14
14
|
|
|
15
|
-
|
|
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 } {
|
|
16
17
|
const cwd = mkdtempSync(join(tmpdir(), 'stacks-env-layers-'))
|
|
17
18
|
directories.push(cwd)
|
|
18
19
|
for (const [name, content] of Object.entries(files))
|
|
19
20
|
writeFileSync(join(cwd, name), content)
|
|
20
|
-
return { cwd,
|
|
21
|
+
return { cwd, backupPathFor: (file: string) => join(cwd, 'runtime', `${file}.backup`) }
|
|
21
22
|
}
|
|
22
23
|
|
|
23
24
|
function text(cwd: string, file: string): string {
|
|
@@ -47,7 +48,9 @@ describe('environment layers', () => {
|
|
|
47
48
|
expect(text(location.cwd, '.env.staging')).toBe('MAIL_HOST=saved.test\n')
|
|
48
49
|
// A key no file sets is added to `.env`.
|
|
49
50
|
expect(text(location.cwd, '.env')).toBe('MAIL_HOST=base.test\nMAIL_PORT=2525\n\nMAIL_MAILER=smtp\n')
|
|
50
|
-
|
|
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')
|
|
51
54
|
})
|
|
52
55
|
|
|
53
56
|
test('an encrypted entry with no key to read it does not win, and is named', async () => {
|
|
@@ -2,8 +2,8 @@ import { createHash } from 'node:crypto'
|
|
|
2
2
|
import { readFile } from 'node:fs/promises'
|
|
3
3
|
import { join } from 'node:path'
|
|
4
4
|
import { activeEnvName, declaredEnvPublicKey, encryptValue, environmentFiles, envHasCiphertext, parse, resolvePrivateKey } from '@stacksjs/env'
|
|
5
|
-
import {
|
|
6
|
-
import { applyEnvironmentEntries, atomicWrite, parseEnvironmentEntries, validateEnvironmentFile } from './environment-file'
|
|
5
|
+
import { projectPath } from '@stacksjs/path'
|
|
6
|
+
import { applyEnvironmentEntries, atomicWrite, environmentBackupPath, parseEnvironmentEntries, validateEnvironmentFile } from './environment-file'
|
|
7
7
|
import type { EnvironmentFileIssue } from './environment-file'
|
|
8
8
|
|
|
9
9
|
/**
|
|
@@ -29,8 +29,8 @@ export interface EnvironmentLayersOptions {
|
|
|
29
29
|
env?: string
|
|
30
30
|
/** The key encrypted values are decrypted with. Default: the app's (`resolvePrivateKey`); null for none. */
|
|
31
31
|
privateKey?: string | null
|
|
32
|
-
/** Where the
|
|
33
|
-
|
|
32
|
+
/** Where the content a file had before a save is kept. Default: {@link environmentBackupPath}. */
|
|
33
|
+
backupPathFor?: (file: string) => string
|
|
34
34
|
}
|
|
35
35
|
|
|
36
36
|
export interface EnvironmentLayer {
|
|
@@ -64,14 +64,14 @@ export interface EnvironmentLayersIssue {
|
|
|
64
64
|
message: string
|
|
65
65
|
}
|
|
66
66
|
|
|
67
|
-
function resolved(options: EnvironmentLayersOptions): { cwd: string, privateKey: string | undefined,
|
|
67
|
+
function resolved(options: EnvironmentLayersOptions): { cwd: string, privateKey: string | undefined, backupPathFor: (file: string) => string, env: string } {
|
|
68
68
|
const cwd = options.cwd ?? projectPath()
|
|
69
69
|
const env = options.env ?? activeEnvName()
|
|
70
70
|
return {
|
|
71
71
|
cwd,
|
|
72
72
|
env,
|
|
73
73
|
privateKey: options.privateKey === null ? undefined : (options.privateKey ?? resolvePrivateKey({ env, cwd })),
|
|
74
|
-
|
|
74
|
+
backupPathFor: options.backupPathFor ?? environmentBackupPath,
|
|
75
75
|
}
|
|
76
76
|
}
|
|
77
77
|
|
|
@@ -127,7 +127,7 @@ export function environmentLayerIssues(layers: EnvironmentLayers): Array<Environ
|
|
|
127
127
|
* A value that is encrypted in that file stays encrypted, under the file's own
|
|
128
128
|
* public key, and so does a key named in `secrets` in a file that holds any
|
|
129
129
|
* ciphertext. An empty value is written as it is. Each changed file is
|
|
130
|
-
* replaced atomically
|
|
130
|
+
* replaced atomically, after its old content is kept as its backup.
|
|
131
131
|
*/
|
|
132
132
|
export async function updateEnvironmentLayers(
|
|
133
133
|
updates: Record<string, string>,
|
|
@@ -138,7 +138,7 @@ export async function updateEnvironmentLayers(
|
|
|
138
138
|
if (current.revision !== revision)
|
|
139
139
|
return { conflict: true }
|
|
140
140
|
|
|
141
|
-
const { cwd,
|
|
141
|
+
const { cwd, backupPathFor } = resolved(options)
|
|
142
142
|
const secrets = new Set(options.secrets ?? [])
|
|
143
143
|
const byFile = new Map<string, Record<string, string>>()
|
|
144
144
|
const issues: EnvironmentLayersIssue[] = []
|
|
@@ -183,10 +183,53 @@ export async function updateEnvironmentLayers(
|
|
|
183
183
|
return { issues }
|
|
184
184
|
|
|
185
185
|
for (const { file, before, after } of rewritten) {
|
|
186
|
-
if (
|
|
187
|
-
await atomicWrite(
|
|
186
|
+
if (before !== undefined)
|
|
187
|
+
await atomicWrite(backupPathFor(file), before)
|
|
188
188
|
await atomicWrite(join(cwd, file), after)
|
|
189
189
|
}
|
|
190
190
|
|
|
191
191
|
return { layers: await readEnvironmentLayers(options) }
|
|
192
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
|
+
}
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import { afterEach, describe, expect, test } from 'bun:test'
|
|
2
|
+
import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
|
|
3
|
+
import { tmpdir } from 'node:os'
|
|
4
|
+
import { join } from 'node:path'
|
|
5
|
+
import { encryptValue, generateKeypair } from '@stacksjs/env'
|
|
6
|
+
import { readEnvironmentPage, saveEnvironmentPage } from './environment-page'
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* The Environment page opens any env file the app loads, says which of its
|
|
10
|
+
* keys the app reads from a later file, and keeps a backup per file
|
|
11
|
+
* (stacksjs/stacks#3341).
|
|
12
|
+
*/
|
|
13
|
+
const directories: string[] = []
|
|
14
|
+
|
|
15
|
+
/** A project in a temp folder, read as `staging`; every backup goes in its own `runtime/`, never the checkout's. */
|
|
16
|
+
function project(files: Record<string, string>) {
|
|
17
|
+
const cwd = mkdtempSync(join(tmpdir(), 'stacks-env-page-'))
|
|
18
|
+
directories.push(cwd)
|
|
19
|
+
for (const [name, content] of Object.entries(files))
|
|
20
|
+
writeFileSync(join(cwd, name), content)
|
|
21
|
+
return { cwd, env: 'staging', privateKey: null, backupPathFor: (file: string) => join(cwd, 'runtime', `${file}.backup`) }
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
afterEach(() => {
|
|
25
|
+
for (const directory of directories.splice(0))
|
|
26
|
+
rmSync(directory, { recursive: true, force: true })
|
|
27
|
+
})
|
|
28
|
+
|
|
29
|
+
describe('the Environment page', () => {
|
|
30
|
+
test('opens .env by default, and lists every env file the app loads', async () => {
|
|
31
|
+
const options = project({ '.env': 'APP_NAME=Base\n', '.env.staging': 'APP_NAME=Staging\n', '.env.production': 'APP_NAME=Production\n' })
|
|
32
|
+
const page = await readEnvironmentPage(undefined, options)
|
|
33
|
+
expect(page?.environment).toMatchObject({ path: '.env', content: 'APP_NAME=Base\n' })
|
|
34
|
+
// `.env.production` is not loaded as staging, so it is not offered.
|
|
35
|
+
expect(page?.files).toEqual(['.env', '.env.staging'])
|
|
36
|
+
})
|
|
37
|
+
|
|
38
|
+
test('names the keys a later file sets again', async () => {
|
|
39
|
+
const { publicKey } = generateKeypair()
|
|
40
|
+
const options = project({
|
|
41
|
+
'.env': 'APP_NAME=Base\nAPP_URL=base.test\nAPP_KEY=base-key\n',
|
|
42
|
+
'.env.local': `APP_URL=local.test\nAPP_KEY="${encryptValue('local-key', publicKey)}"\n`,
|
|
43
|
+
})
|
|
44
|
+
expect((await readEnvironmentPage('.env', options))?.readElsewhere).toEqual([
|
|
45
|
+
{ key: 'APP_URL', file: '.env.local', readable: true },
|
|
46
|
+
{ key: 'APP_KEY', file: '.env.local', readable: false },
|
|
47
|
+
])
|
|
48
|
+
expect((await readEnvironmentPage('.env.local', options))?.readElsewhere).toEqual([])
|
|
49
|
+
})
|
|
50
|
+
|
|
51
|
+
test('opens only an env file the app loads', async () => {
|
|
52
|
+
const options = project({ '.env': 'APP_NAME=Base\n', '.env.production': 'APP_NAME=Production\n' })
|
|
53
|
+
for (const requested of ['.env.production', '../.env', '/etc/passwd', 'config/app.ts', 42])
|
|
54
|
+
expect(await readEnvironmentPage(requested, options)).toBeNull()
|
|
55
|
+
expect(await saveEnvironmentPage('.env.production', 'APP_NAME=Changed\n', '0'.repeat(64), options)).toEqual({ unknownFile: true })
|
|
56
|
+
expect(readFileSync(join(options.cwd, '.env.production'), 'utf8')).toBe('APP_NAME=Production\n')
|
|
57
|
+
})
|
|
58
|
+
|
|
59
|
+
test('saves the file it opened, and keeps that file\'s own backup', async () => {
|
|
60
|
+
const options = project({ '.env': 'APP_NAME=Base\n', '.env.staging': 'APP_NAME=Staging\n' })
|
|
61
|
+
const page = await readEnvironmentPage('.env.staging', options)
|
|
62
|
+
|
|
63
|
+
const saved = await saveEnvironmentPage('.env.staging', 'APP_NAME=Saved\n', page!.environment.revision, options)
|
|
64
|
+
expect(saved.page?.environment).toMatchObject({ path: '.env.staging', content: 'APP_NAME=Saved\n' })
|
|
65
|
+
expect(saved.page?.environment.backup.content).toBe('APP_NAME=Staging\n')
|
|
66
|
+
expect(readFileSync(join(options.cwd, '.env.staging'), 'utf8')).toBe('APP_NAME=Saved\n')
|
|
67
|
+
expect(readFileSync(join(options.cwd, 'runtime/.env.staging.backup'), 'utf8')).toBe('APP_NAME=Staging\n')
|
|
68
|
+
expect(readFileSync(join(options.cwd, '.env'), 'utf8')).toBe('APP_NAME=Base\n')
|
|
69
|
+
expect(existsSync(join(options.cwd, 'runtime/.env.backup'))).toBe(false)
|
|
70
|
+
})
|
|
71
|
+
})
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import { join } from 'node:path'
|
|
2
|
+
import { projectPath } from '@stacksjs/path'
|
|
3
|
+
import { environmentBackupPath, readEnvironmentFile, updateEnvironmentFile } from './environment-file'
|
|
4
|
+
import type { EnvironmentFileIssue, EnvironmentFileState } from './environment-file'
|
|
5
|
+
import { editableEnvironmentFiles, keysReadElsewhere, readEnvironmentLayers } from './environment-layers'
|
|
6
|
+
import type { EnvironmentLayersOptions, KeyReadElsewhere } from './environment-layers'
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* What the Environment page shows: one env file, every env file the app
|
|
10
|
+
* loads, and the keys in this one whose value the app takes from a later
|
|
11
|
+
* file (stacksjs/stacks#3341).
|
|
12
|
+
*
|
|
13
|
+
* The page edited `.env` alone. A key set again in `.env.<env>` kept that
|
|
14
|
+
* file's value, so an edit to it in `.env` was saved and changed nothing the
|
|
15
|
+
* app read, and the file that did set it could not be opened.
|
|
16
|
+
*/
|
|
17
|
+
export interface EnvironmentPage {
|
|
18
|
+
environment: EnvironmentFileState
|
|
19
|
+
/** The files the page can open, in the order the app loads them. */
|
|
20
|
+
files: string[]
|
|
21
|
+
readElsewhere: KeyReadElsewhere[]
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** The file a request names, if it is one of the env files the app loads; `.env` when it names none. */
|
|
25
|
+
function editableFile(requested: unknown, files: string[]): string | null {
|
|
26
|
+
const file = requested === undefined || requested === null || requested === '' ? '.env' : requested
|
|
27
|
+
return typeof file === 'string' && files.includes(file) ? file : null
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function fileOptions(file: string, options: EnvironmentLayersOptions) {
|
|
31
|
+
return {
|
|
32
|
+
name: file,
|
|
33
|
+
envPath: join(options.cwd ?? projectPath(), file),
|
|
34
|
+
backupPath: (options.backupPathFor ?? environmentBackupPath)(file),
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** The page for one env file, or null when the request names a file the app does not load. */
|
|
39
|
+
export async function readEnvironmentPage(requested: unknown, options: EnvironmentLayersOptions = {}): Promise<EnvironmentPage | null> {
|
|
40
|
+
const layers = await readEnvironmentLayers(options)
|
|
41
|
+
const files = editableEnvironmentFiles(layers)
|
|
42
|
+
const file = editableFile(requested, files)
|
|
43
|
+
if (!file)
|
|
44
|
+
return null
|
|
45
|
+
|
|
46
|
+
return {
|
|
47
|
+
environment: await readEnvironmentFile(fileOptions(file, options)),
|
|
48
|
+
files,
|
|
49
|
+
readElsewhere: keysReadElsewhere(layers, file),
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** Replace one env file's content, as `updateEnvironmentFile` does, and return its page. */
|
|
54
|
+
export async function saveEnvironmentPage(
|
|
55
|
+
requested: unknown,
|
|
56
|
+
content: string,
|
|
57
|
+
revision: string,
|
|
58
|
+
options: EnvironmentLayersOptions = {},
|
|
59
|
+
): Promise<{ page?: EnvironmentPage, issues?: EnvironmentFileIssue[], conflict?: boolean, unknownFile?: true }> {
|
|
60
|
+
const file = editableFile(requested, editableEnvironmentFiles(await readEnvironmentLayers(options)))
|
|
61
|
+
if (!file)
|
|
62
|
+
return { unknownFile: true }
|
|
63
|
+
|
|
64
|
+
const result = await updateEnvironmentFile(content, revision, fileOptions(file, options))
|
|
65
|
+
if (result.issues || result.conflict)
|
|
66
|
+
return result
|
|
67
|
+
|
|
68
|
+
return { page: (await readEnvironmentPage(file, options))! }
|
|
69
|
+
}
|
|
@@ -4,7 +4,7 @@ import { join } from 'node:path'
|
|
|
4
4
|
import { describe, expect, test } from 'bun:test'
|
|
5
5
|
import { readMailSettings, updateMailSettings } from './mail-settings'
|
|
6
6
|
|
|
7
|
-
interface Fixture { cwd: string, env: string, privateKey: null,
|
|
7
|
+
interface Fixture { cwd: string, env: string, privateKey: null, backupPathFor: (file: string) => string, envPath: string }
|
|
8
8
|
|
|
9
9
|
/** A project with `.env` and, optionally, more env files, read as the `staging` environment with no private key. */
|
|
10
10
|
async function fixture(content: string, more: Record<string, string> = {}): Promise<Fixture> {
|
|
@@ -13,7 +13,8 @@ async function fixture(content: string, more: Record<string, string> = {}): Prom
|
|
|
13
13
|
cwd,
|
|
14
14
|
env: 'staging',
|
|
15
15
|
privateKey: null,
|
|
16
|
-
|
|
16
|
+
// Every backup in the fixture's own folder, never the checkout's.
|
|
17
|
+
backupPathFor: (file: string) => join(cwd, 'runtime', `${file}.backup`),
|
|
17
18
|
envPath: join(cwd, '.env'),
|
|
18
19
|
}
|
|
19
20
|
await writeFile(options.envPath, content)
|
|
@@ -85,7 +86,7 @@ describe('dashboard mail settings', () => {
|
|
|
85
86
|
expect(content).toContain('MAIL_PASSWORD=keep-this')
|
|
86
87
|
expect(content).toContain('APP_KEY=untouched')
|
|
87
88
|
expect(content).toContain('MAIL_HOST=smtp.example.com')
|
|
88
|
-
expect(await readFile(options.
|
|
89
|
+
expect(await readFile(options.backupPathFor('.env'), 'utf8')).toContain('MAIL_MAILER=log')
|
|
89
90
|
})
|
|
90
91
|
|
|
91
92
|
test('requires provider credentials without returning stored secrets', async () => {
|
package/ide/vscode/package.json
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
"publisher": "Stacks",
|
|
3
3
|
"name": "vscode-stacks",
|
|
4
4
|
"displayName": "Stacks",
|
|
5
|
-
"version": "0.75.
|
|
5
|
+
"version": "0.75.632",
|
|
6
6
|
"description": "Stacks, built into VS Code: stx templates, pickier linting and formatting, encrypted env files, the dev server preview and every buddy command. No other extensions required.",
|
|
7
7
|
"license": "MIT",
|
|
8
8
|
"funding": "https://github.com/sponsors/chrisbbreuer",
|
package/package.json
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
"name": "@stacksjs/defaults",
|
|
3
3
|
"type": "module",
|
|
4
4
|
"sideEffects": false,
|
|
5
|
-
"version": "0.75.
|
|
5
|
+
"version": "0.75.632",
|
|
6
6
|
"repository": {
|
|
7
7
|
"type": "git",
|
|
8
8
|
"url": "git+https://github.com/stacksjs/stacks.git",
|
|
@@ -45,14 +45,14 @@
|
|
|
45
45
|
"dependencies": {
|
|
46
46
|
"@iconify-json/f7": "^1.2.2",
|
|
47
47
|
"@iconify-json/hugeicons": "^1.2.35",
|
|
48
|
-
"@stacksjs/mobile": "0.75.
|
|
48
|
+
"@stacksjs/mobile": "0.75.632",
|
|
49
49
|
"@stacksjs/sanitizer": "^0.2.908",
|
|
50
50
|
"@stacksjs/stx": "^0.2.908",
|
|
51
|
-
"@stacksjs/strings": "0.75.
|
|
51
|
+
"@stacksjs/strings": "0.75.632",
|
|
52
52
|
"@xterm/addon-fit": "^0.11.0",
|
|
53
53
|
"@xterm/xterm": "^6.0.0",
|
|
54
54
|
"ts-qr-codes": "^0.1.8",
|
|
55
|
-
"@stacksjs/support": "0.75.
|
|
56
|
-
"@stacksjs/browser": "0.75.
|
|
55
|
+
"@stacksjs/support": "0.75.632",
|
|
56
|
+
"@stacksjs/browser": "0.75.632"
|
|
57
57
|
}
|
|
58
58
|
}
|
|
@@ -7,7 +7,7 @@ interface EnvironmentFileIssue {
|
|
|
7
7
|
}
|
|
8
8
|
|
|
9
9
|
interface EnvironmentFileState {
|
|
10
|
-
path:
|
|
10
|
+
path: string
|
|
11
11
|
content: string
|
|
12
12
|
revision: string
|
|
13
13
|
exists: boolean
|
|
@@ -19,11 +19,27 @@ interface EnvironmentFileState {
|
|
|
19
19
|
}
|
|
20
20
|
}
|
|
21
21
|
|
|
22
|
+
interface KeyReadElsewhere {
|
|
23
|
+
key: string
|
|
24
|
+
file: string
|
|
25
|
+
readable: boolean
|
|
26
|
+
}
|
|
27
|
+
|
|
22
28
|
interface EnvironmentResponse {
|
|
23
29
|
environment: EnvironmentFileState
|
|
30
|
+
files: string[]
|
|
31
|
+
readElsewhere: KeyReadElsewhere[]
|
|
24
32
|
}
|
|
25
33
|
|
|
26
34
|
const envValues = state('')
|
|
35
|
+
// The env file open in the editor, and every env file the app loads
|
|
36
|
+
// (stacksjs/stacks#3341). A key a later file sets again is read from there.
|
|
37
|
+
const file = state('.env')
|
|
38
|
+
const files = state<string[]>(['.env'])
|
|
39
|
+
const readElsewhere = state<KeyReadElsewhere[]>([])
|
|
40
|
+
const readElsewhereLabel = derived(() => readElsewhere()
|
|
41
|
+
.map(entry => entry.readable ? `${entry.key} (${entry.file})` : `${entry.key} (${entry.file}, encrypted, not readable here)`)
|
|
42
|
+
.join(', '))
|
|
27
43
|
const revision = state('')
|
|
28
44
|
const backupContent = state('')
|
|
29
45
|
const backupUpdatedAt = state<string | null>(null)
|
|
@@ -58,7 +74,11 @@ const variableCount = derived(() => envValues().split('\n').filter((line) => {
|
|
|
58
74
|
}).length)
|
|
59
75
|
const dirty = derived(() => Boolean(revision()) && envValues() !== loadedContent())
|
|
60
76
|
|
|
61
|
-
function applyEnvironment(
|
|
77
|
+
function applyEnvironment(result: EnvironmentResponse): void {
|
|
78
|
+
const { environment } = result
|
|
79
|
+
file.set(environment.path)
|
|
80
|
+
files.set(result.files)
|
|
81
|
+
readElsewhere.set(result.readElsewhere)
|
|
62
82
|
envValues.set(environment.content)
|
|
63
83
|
loadedContent.set(environment.content)
|
|
64
84
|
revision.set(environment.revision)
|
|
@@ -74,8 +94,8 @@ async function loadEnvironment(): Promise<void> {
|
|
|
74
94
|
isLoading.set(true)
|
|
75
95
|
loadError.set('')
|
|
76
96
|
try {
|
|
77
|
-
const result = await dashboardApi<EnvironmentResponse>(
|
|
78
|
-
applyEnvironment(result
|
|
97
|
+
const result = await dashboardApi<EnvironmentResponse>(`/api/dashboard/environment?file=${encodeURIComponent(file())}`)
|
|
98
|
+
applyEnvironment(result)
|
|
79
99
|
}
|
|
80
100
|
catch (error) {
|
|
81
101
|
loadError.set(describeError(error, 'The environment file could not be loaded.'))
|
|
@@ -85,6 +105,17 @@ async function loadEnvironment(): Promise<void> {
|
|
|
85
105
|
}
|
|
86
106
|
}
|
|
87
107
|
|
|
108
|
+
/** Open another env file. Unsaved edits keep the current one open until they are saved. */
|
|
109
|
+
function openFile(name: string): void {
|
|
110
|
+
if (isBusy() || dirty() || name === file())
|
|
111
|
+
return
|
|
112
|
+
successMessage.set('')
|
|
113
|
+
saveError.set('')
|
|
114
|
+
validationIssues.set([])
|
|
115
|
+
file.set(name)
|
|
116
|
+
void loadEnvironment()
|
|
117
|
+
}
|
|
118
|
+
|
|
88
119
|
function openAddModal(): void {
|
|
89
120
|
newVarKey.set('')
|
|
90
121
|
newVarValue.set('')
|
|
@@ -155,11 +186,12 @@ async function handleSave(): Promise<void> {
|
|
|
155
186
|
const result = await dashboardApi<EnvironmentResponse & { success: true }>('/api/dashboard/environment', {
|
|
156
187
|
method: 'PUT',
|
|
157
188
|
body: {
|
|
189
|
+
file: file(),
|
|
158
190
|
content: envValues(),
|
|
159
191
|
revision: revision(),
|
|
160
192
|
},
|
|
161
193
|
})
|
|
162
|
-
applyEnvironment(result
|
|
194
|
+
applyEnvironment(result)
|
|
163
195
|
successMessage.set('Environment file saved. Restart long-running processes to load changed values.')
|
|
164
196
|
}
|
|
165
197
|
catch (error) {
|
|
@@ -198,7 +230,7 @@ onMount(() => void loadEnvironment())
|
|
|
198
230
|
<div class="flex flex-col gap-6 mx-auto pb-12 pt-6 px-4 sm:px-6 lg:px-8 max-w-7xl">
|
|
199
231
|
<PageHeader
|
|
200
232
|
title="Environment Variables"
|
|
201
|
-
description="Edit the
|
|
233
|
+
description="Edit the env files the app loads, with validation, conflict protection, and an automatic backup."
|
|
202
234
|
>
|
|
203
235
|
<template #actions>
|
|
204
236
|
<div class="flex gap-2 items-center">
|
|
@@ -217,7 +249,7 @@ onMount(() => void loadEnvironment())
|
|
|
217
249
|
<div class="grid gap-3 sm:grid-cols-3">
|
|
218
250
|
<div class="p-4 bg-white dark:bg-neutral-900 border border-stone-200 rounded-xl dark:border-neutral-700">
|
|
219
251
|
<p class="font-medium text-stone-500 text-xs tracking-wide uppercase dark:text-neutral-400">File</p>
|
|
220
|
-
<p class="mt-1 font-mono text-sm text-stone-900 dark:text-white"
|
|
252
|
+
<p class="mt-1 font-mono text-sm text-stone-900 dark:text-white" :text="file()"></p>
|
|
221
253
|
</div>
|
|
222
254
|
<div class="p-4 bg-white dark:bg-neutral-900 border border-stone-200 rounded-xl dark:border-neutral-700">
|
|
223
255
|
<p class="font-medium text-stone-500 text-xs tracking-wide uppercase dark:text-neutral-400">Variables</p>
|
|
@@ -229,6 +261,26 @@ onMount(() => void loadEnvironment())
|
|
|
229
261
|
</div>
|
|
230
262
|
</div>
|
|
231
263
|
|
|
264
|
+
<div :if="files().length > 1" class="flex flex-wrap gap-2 items-center" role="group" aria-label="Env file">
|
|
265
|
+
<button
|
|
266
|
+
:for="name in files"
|
|
267
|
+
type="button"
|
|
268
|
+
class="px-3 py-1.5 font-mono text-sm border rounded-lg disabled:opacity-60 transition-colors"
|
|
269
|
+
:class="name === file() ? 'text-white bg-stone-900 border-stone-900 dark:text-neutral-900 dark:bg-white dark:border-white' : 'text-stone-700 bg-white border-stone-200 hover:bg-stone-50 dark:text-neutral-200 dark:bg-neutral-900 dark:border-neutral-700 dark:hover:bg-neutral-800'"
|
|
270
|
+
:aria-pressed="String(name === file())"
|
|
271
|
+
:disabled="isBusy() || (dirty() && name !== file())"
|
|
272
|
+
@click="openFile(name)"
|
|
273
|
+
:text="name"
|
|
274
|
+
></button>
|
|
275
|
+
<span :if="dirty()" class="text-stone-500 text-xs dark:text-neutral-400">Save your edits before opening another file.</span>
|
|
276
|
+
</div>
|
|
277
|
+
|
|
278
|
+
<div :if="readElsewhere().length" class="p-4 text-amber-800 text-sm dark:text-amber-200 bg-amber-50 dark:bg-amber-950/30 border border-amber-200 rounded-xl dark:border-amber-900" role="note" data-env-read-elsewhere>
|
|
279
|
+
<p class="font-medium">Some keys here are set again in a file the app loads later.</p>
|
|
280
|
+
<p class="mt-1">Wherever the app can read that later value, it uses it instead of this file's, so change them there:</p>
|
|
281
|
+
<p class="mt-1 font-mono text-xs" :text="readElsewhereLabel()"></p>
|
|
282
|
+
</div>
|
|
283
|
+
|
|
232
284
|
<div :if="loadError()" class="p-4 text-red-700 text-sm dark:text-red-300 bg-red-50 dark:bg-red-950/30 border border-red-200 rounded-xl dark:border-red-900" role="alert">
|
|
233
285
|
<p :text="loadError()"></p>
|
|
234
286
|
<Button class="mt-3" size="sm" variant="secondary" @click="loadEnvironment">Try again</Button>
|
|
@@ -246,7 +298,7 @@ onMount(() => void loadEnvironment())
|
|
|
246
298
|
<div :if="!loadError()">
|
|
247
299
|
<CodeEditor
|
|
248
300
|
v-model:value="envValues"
|
|
249
|
-
label="
|
|
301
|
+
:label="file()"
|
|
250
302
|
language="env"
|
|
251
303
|
:loading="isLoading()"
|
|
252
304
|
@save="handleSave"
|