From c01e4a8c7ae85b2bac8233dea7a869944840e3d8 Mon Sep 17 00:00:00 2001 From: SylvainDruaux Date: Tue, 17 Nov 2026 12:42:18 +0100 Subject: [PATCH 1/2] feat(settings): the Secrets tab edits each dev env file The Secrets tab read and wrote `.env` only, while the dev server also loads `.env.local`, `.env.development` and `.env.development.local`, later files winning. A key set only in `.env.development` did not show, and a key overridden in `.env.local` showed a value dev does not use. A dropdown under the title now picks one of the four files, listed in load order and opening on `.env`. Every `secrets:*` message names its file, and the parser refuses any other name, `.env.production` included. A row whose name a later file sets again says "Dev uses the value in ", worked out in the main process from that file's names alone. Switching files remounts the view, so nothing revealed or typed for one file is shown beside another's names. `.env.development` is usually committed on purpose, for values that are not secret, so the tab offers no .gitignore rule for it and shows no Git warning; `secrets:ignore` refuses it too. The layout keeps every button on one line: the .gitignore offer is the button alone, its explanation in the tooltip, and the tracked warning is shorter. The empty state no longer has a Create button, since adding a secret already creates the file, private; an existing empty file now says it is empty instead of "Adding a secret creates .env". The texts that named `.env` name the chosen file, in the five languages. The MCP tab still stores secrets in `.env`. The Sanity login and the page template env read now share the same file list, so the Sanity login also reads `.env.development.local`. --- docs/contracts.md | 16 +- electron/content/envSecrets.ts | 151 +++++++----- electron/content/projectEnv.ts | 41 ++-- electron/content/sanityLogin.ts | 4 +- electron/handlers/secretsHandlers.ts | 14 +- shared/ipc/ipcPayloads.ts | 12 +- .../properties/i18n/messages/de/settings.ts | 40 ++-- .../properties/i18n/messages/en/settings.ts | 40 ++-- .../properties/i18n/messages/es/settings.ts | 40 ++-- .../properties/i18n/messages/fr/settings.ts | 40 ++-- .../properties/i18n/messages/ptBR/settings.ts | 40 ++-- shared/properties/secrets.ts | 59 ++++- .../projectSettings/McpAddSection.tsx | 6 +- src/features/projectSettings/McpJsonView.tsx | 3 +- src/features/projectSettings/McpTab.tsx | 3 +- src/features/projectSettings/SecretsTab.tsx | 186 ++++++++++----- src/features/projectSettings/mcpFlows.ts | 9 +- .../projectSettings/projectSettings.css | 16 ++ src/features/projectSettings/secretsBridge.ts | 33 ++- src/features/projectSettings/secretsCache.ts | 29 ++- src/features/projectSettings/secretsModel.ts | 8 +- test/electron/content/envSecrets.test.ts | 108 +++++++-- test/electron/content/pageTemplate.test.js | 13 +- .../renderer/projectSettings/mcpPanel.test.js | 10 +- .../projectSettings/secretsPanel.test.js | 214 ++++++++++++++---- test/shared/ipc/ipcPayloads.test.ts | 8 +- test/shared/properties/secrets.test.ts | 74 +++++- 27 files changed, 840 insertions(+), 377 deletions(-) diff --git a/docs/contracts.md b/docs/contracts.md index de2913d51..ade448a64 100644 --- a/docs/contracts.md +++ b/docs/contracts.md @@ -746,16 +746,22 @@ role's UI. It changes only the renderer's active role (`src/lib/currentRole.ts`: The Settings rail button (`projectSettings`, access feature `panel:projectSettings`, admin only until a role is granted it; shortcut ⌥S) sits directly above the AI button and opens a panel with a typed tab registry (`src/features/projectSettings/settingsTabs.ts`). It is the project's settings, apart from the -app's own Settings screen (`src/app/settings`). Its one tab, Secrets, edits the project's `.env`. +app's own Settings screen (`src/app/settings`). Its Secrets tab edits one of the project's dev env files +at a time (`SECRETS_FILE_NAMES`: `.env`, `.env.local`, `.env.development`, `.env.development.local`, the +dev server's load order), picked in a dropdown that opens on `.env`. `.env.production` is not listed. - `shared/properties/envFile.ts` is the codec. It keeps comments, blank lines, quoting, `export` prefixes, spacing, the byte-order mark and line endings: parse then serialize is byte-identical, and an edit rewrites only the line it touches. Bounds: names 128 characters, values 16 KiB, 512 variables, 4000 lines, 256 KiB. Multi-line quoted values are listed but not edited here. -- `secrets:list` returns names only. `secrets:read` returns one value, for a person who revealed or began - editing it. `secrets:apply` applies one change (`add`, `update`, `remove`, `create`) against the revision - (digest of the file's bytes) it was authored on; a file that changed since is refused with `changed`. - `secrets:ignore` appends `.env` to `.gitignore`. A missing `.env` is the ordinary empty list. +- Every `secrets:*` message names its `file`, and the parser refuses any name outside `SECRETS_FILE_NAMES`. + `secrets:list` returns names only; a row whose name a file loading later sets again carries + `overriddenBy` (the last such file, worked out from that file's names alone). `secrets:read` returns one + value, for a person who revealed or began editing it. `secrets:apply` applies one change (`add`, + `update`, `remove`, `create`) against the revision (digest of the file's bytes) it was authored on; a + file that changed since is refused with `changed`. `secrets:ignore` appends the file to `.gitignore`; it + refuses `.env.development`, which is usually committed on purpose and gets no Git warning in the tab. + A missing file is the ordinary empty list. The MCP tab stores secrets in `.env` only. - Writes go through the document actors (atomic, mode kept); a new `.env` is made mode 0600 first. No value appears in a log, an error, a listing or the DOM of a hidden row; failures are fixed text per code. - The list reloads when the window regains focus; there is no file watcher for `.env` yet. diff --git a/electron/content/envSecrets.ts b/electron/content/envSecrets.ts index 7d1ecba1e..508cbbaf7 100644 --- a/electron/content/envSecrets.ts +++ b/electron/content/envSecrets.ts @@ -1,13 +1,14 @@ // i18n-ignore-file: the messages are the English fallback beside each stable failure code; the Secrets tab translates by code (settings.secrets.error.*). -// The Settings panel's Secrets tab, main-process half (shared/properties/secrets.ts): list the -// names in the project's `.env`, hand one value to the renderer when a person reveals or edits -// it, apply one change, and append `.env` to `.gitignore`. +// The Settings panel's Secrets tab, main-process half (shared/properties/secrets.ts): for one of +// the project's dev env files, list its names, hand one value to the renderer when a person +// reveals or edits it, apply one change, and append the file to `.gitignore`. A listing also says +// which names a file loading later sets again, from those files' names alone. // // A value leaves this process only in a `readSecret` reply. Nothing here logs, and no error // value is built from a name, a value or a thrown message: every failure is the fixed text of // its code. A change is written through the document actors (documentWrites.ts), which write a -// temporary file in the project's `.stacki/io`, rename it over `.env`, keep its mode and owner, -// and refuse a write whose base bytes are not the ones on disk. A new `.env` is made private +// temporary file in the project's `.stacki/io`, rename it over the file, keep its mode and owner, +// and refuse a write whose base bytes are not the ones on disk. A new env file is made private // (mode 0600) before anything secret is put in it. Every change names the revision it was authored // against; a file that changed since is refused with `changed`, never overwritten. import fs from 'node:fs'; @@ -17,8 +18,11 @@ import { assert } from '../../shared/core/assert'; import { err, ok } from '../../shared/core/result'; import { ENV_LIMITS, changeEnvFile, envEntries, envInvalidLines, parseEnvFile, serializeEnvFile, type EnvFile } from '../../shared/properties/envFile'; import { - SECRETS_FILE_NAME, + SECRETS_FILE_NAMES, + secretsFileLoadsAfter, + type SecretSummary, type SecretsChange, + type SecretsFileName, type SecretsErrorCode, type SecretsIgnore, type SecretsListing, @@ -32,18 +36,18 @@ import { ignoreState, isTracked, writeIgnoreRule, type Git } from './projectEnv' // Text per code, fixed so a failure can never carry file content. const MESSAGES: Readonly> = { - changed: 'The .env file changed on disk. Reload and try again.', + changed: 'The env file changed on disk. Reload and try again.', 'name-taken': 'A secret with that name already exists.', 'invalid-name': 'That is not a valid secret name.', 'invalid-value': 'That value cannot be saved.', 'not-found': 'That secret is no longer there.', - 'read-only': 'This secret spans several lines. Edit it in the .env file.', - limit: 'The .env file is at its size limit.', - unreadable: 'The .env file could not be read.', - 'too-large': 'The .env file is too large to edit here.', - 'not-text': 'The .env file is not valid UTF-8 text.', - denied: 'Stacki is not allowed to read the .env file.', - filesystem: 'The .env file could not be saved.', + 'read-only': 'This secret spans several lines. Edit it in the env file.', + limit: 'The env file is at its size limit.', + unreadable: 'The env file could not be read.', + 'too-large': 'The env file is too large to edit here.', + 'not-text': 'The env file is not valid UTF-8 text.', + denied: 'Stacki is not allowed to read the env file.', + filesystem: 'The env file could not be saved.', }; const PRIVATE_MODE = 0o600; @@ -53,18 +57,18 @@ interface EnvSource { readonly exists: boolean; } -/** The names in `.env`, how it stands with Git, and the revision a change must name. */ -export async function listSecrets(projectRoot: string, git: Git): Promise> { - const read = readSource(projectRoot); +/** The names in `file`, how it stands with Git, and the revision a change must name. */ +export async function listSecrets(projectRoot: string, file: SecretsFileName, git: Git): Promise> { + const read = readSource(projectRoot, file); if (!read.ok) { return read; } - return listingOf(projectRoot, read.value, git); + return listingOf(projectRoot, file, read.value, git); } /** One value, for a person who revealed or began editing it. */ -export function readSecret(projectRoot: string, revision: Digest, index: number): SecretsResult { - const read = readSource(projectRoot); +export function readSecret(projectRoot: string, file: SecretsFileName, revision: Digest, index: number): SecretsResult { + const read = readSource(projectRoot, file); if (!read.ok) { return read; } @@ -83,8 +87,14 @@ export function readSecret(projectRoot: string, revision: Digest, index: number) } /** Applies `change` to the revision it was authored against and answers with the new listing. */ -export async function applySecretsChange(projectRoot: string, revision: Digest, change: SecretsChange, git: Git): Promise> { - const read = readSource(projectRoot); +export async function applySecretsChange( + projectRoot: string, + file: SecretsFileName, + revision: Digest, + change: SecretsChange, + git: Git, +): Promise> { + const read = readSource(projectRoot, file); if (!read.ok) { return read; } @@ -92,7 +102,7 @@ export async function applySecretsChange(projectRoot: string, revision: Digest, return failure('changed'); } if (change.kind === 'create') { - return createEmpty(projectRoot, read.value, revision, git); + return createEmpty(projectRoot, file, read.value, revision, git); } const parsed = parseEnvFile(read.value.text); if (!parsed.ok) { @@ -102,65 +112,67 @@ export async function applySecretsChange(projectRoot: string, revision: Digest, if (!changed.ok) { return failure(changed.error); } - const written = writeSource(projectRoot, read.value, serializeEnvFile(changed.value), revision); + const written = writeSource(projectRoot, file, read.value, serializeEnvFile(changed.value), revision); if (!written.ok) { return written; } - const after = readSource(projectRoot); + const after = readSource(projectRoot, file); if (!after.ok) { return after; } assertWrote(after.value.text, changed.value); - return listingOf(projectRoot, after.value, git); + return listingOf(projectRoot, file, after.value, git); } -// A project with no `.env` gets an empty private one; one that has it is left as it is. -async function createEmpty(projectRoot: string, source: EnvSource, revision: Digest, git: Git): Promise> { +// A project without the file gets an empty private one; one that has it is left as it is. +async function createEmpty(projectRoot: string, file: SecretsFileName, source: EnvSource, revision: Digest, git: Git): Promise> { if (!source.exists) { - const written = writeSource(projectRoot, source, '', revision); + const written = writeSource(projectRoot, file, source, '', revision); if (!written.ok) { return written; } } - return listSecrets(projectRoot, git); + return listSecrets(projectRoot, file, git); } -/** Appends `.env` to `.gitignore` when no rule ignores it, and answers with the listing's new state. */ -export async function ignoreEnvFile(projectRoot: string, git: Git): Promise> { +/** Appends `file` to `.gitignore` when no rule ignores it, and answers with the listing's new state. */ +export async function ignoreEnvFile(projectRoot: string, file: SecretsFileName, git: Git): Promise> { try { - writeIgnoreRule(projectRoot); + writeIgnoreRule(projectRoot, file); } catch { // The reason is not shown: a thrown message here could name a path the person did not ask about. return failure('filesystem'); } - return listSecrets(projectRoot, git); + return listSecrets(projectRoot, file, git); } function failure(code: SecretsErrorCode): SecretsResult { return err({ code, message: MESSAGES[code] }); } -function envPath(projectRoot: string): string { +function envPath(projectRoot: string, file: SecretsFileName): string { assert(path.isAbsolute(projectRoot), 'A project root is absolute'); - return path.join(projectRoot, SECRETS_FILE_NAME); + const target = path.join(projectRoot, file); + assert(path.dirname(target) === projectRoot, 'An env file sits at the project root'); + return target; } // The file's text, or empty text for a project with none. A file that is too large, not a file, // or not UTF-8 is unreadable: reading it lossily could let a later save destroy it. -function readSource(projectRoot: string): SecretsResult { - const file = envPath(projectRoot); +function readSource(projectRoot: string, file: SecretsFileName): SecretsResult { + const target = envPath(projectRoot, file); let bytes: Buffer; try { - const stats = fs.statSync(file); + const stats = fs.statSync(target); if (!stats.isFile()) { return failure('unreadable'); } if (stats.size > ENV_LIMITS.fileBytesMax) { return failure('too-large'); } - bytes = fs.readFileSync(file); + bytes = fs.readFileSync(target); } catch (error: unknown) { - // A project with no .env is the ordinary case, not a failure. + // A project without the file is the ordinary case, not a failure. return isMissing(error) ? ok({ text: '', exists: false }) : failure(isDenied(error) ? 'denied' : 'unreadable'); } try { @@ -179,47 +191,70 @@ function isMissing(error: unknown): boolean { return typeof error === 'object' && error !== null && 'code' in error && error.code === 'ENOENT'; } -function writeSource(projectRoot: string, before: EnvSource, text: string, revision: Digest): SecretsResult { - const file = envPath(projectRoot); +function writeSource(projectRoot: string, file: SecretsFileName, before: EnvSource, text: string, revision: Digest): SecretsResult { + const target = envPath(projectRoot, file); try { if (before.exists) { - writeProjectText(file, text, before.text); + writeProjectText(target, text, before.text); } else { // Created empty and made private first, so the secret is never in a file others can read. - createProjectText(file, ''); - fs.chmodSync(file, PRIVATE_MODE); - writeProjectText(file, text, ''); + createProjectText(target, ''); + fs.chmodSync(target, PRIVATE_MODE); + writeProjectText(target, text, ''); } return ok(undefined); } catch { // A refused write reads the disk again to say whether another writer got there first. - const now = readSource(projectRoot); + const now = readSource(projectRoot, file); return failure(now.ok && digestOf(now.value.text) !== revision ? 'changed' : 'filesystem'); } } // The read-back holds what was planned: the pair of the plan's assertion and the disk's. function assertWrote(written: string, planned: EnvFile): void { - assert(written === serializeEnvFile(planned), 'The saved .env reads back as planned'); + assert(written === serializeEnvFile(planned), 'The saved env file reads back as planned'); const reparsed = parseEnvFile(written); - assert(reparsed.ok, 'The saved .env parses'); - assert(envEntries(reparsed.value).length === envEntries(planned).length, 'The saved .env holds the planned variables'); + assert(reparsed.ok, 'The saved env file parses'); + assert(envEntries(reparsed.value).length === envEntries(planned).length, 'The saved env file holds the planned variables'); } -async function listingOf(projectRoot: string, source: EnvSource, git: Git): Promise> { +async function listingOf(projectRoot: string, file: SecretsFileName, source: EnvSource, git: Git): Promise> { const parsed = parseEnvFile(source.text); if (!parsed.ok) { return failure('unreadable'); } - const ignore = await ignoreOf(projectRoot, git); - const entries = envEntries(parsed.value).map(({ index, name, duplicate, multiline }) => ({ index, name, duplicate, multiline })); - return ok({ revision: digestOf(source.text), exists: source.exists, entries, invalidLines: envInvalidLines(parsed.value), ignore }); + const ignore = await ignoreOf(projectRoot, file, git); + const overrides = overridesOf(projectRoot, file); + const entries = envEntries(parsed.value).map(({ index, name, duplicate, multiline }): SecretSummary => { + const overriddenBy = overrides.get(name); + return overriddenBy === undefined ? { index, name, duplicate, multiline } : { index, name, duplicate, multiline, overriddenBy }; + }); + return ok({ file, revision: digestOf(source.text), exists: source.exists, entries, invalidLines: envInvalidLines(parsed.value), ignore }); } -async function ignoreOf(projectRoot: string, git: Git): Promise { - if (await isTracked(projectRoot, git)) { +// For each name, the last file loading after `file` that sets it again: the one whose value dev +// uses. Only names are read here, and they stay in this process. A later file that cannot be +// read adds no note rather than failing the listing of the file the person asked for. +function overridesOf(projectRoot: string, file: SecretsFileName): ReadonlyMap { + const later = SECRETS_FILE_NAMES.filter((candidate) => secretsFileLoadsAfter(candidate, file)); + assert(later.length < SECRETS_FILE_NAMES.length, 'overridesOf: the listed file is not one of the later files'); + const overrides = new Map(); + for (const candidate of later) { + const read = readSource(projectRoot, candidate); + const parsed = read.ok ? parseEnvFile(read.value.text) : undefined; + if (parsed?.ok === true) { + for (const entry of envEntries(parsed.value)) { + overrides.set(entry.name, candidate); + } + } + } + return overrides; +} + +async function ignoreOf(projectRoot: string, file: SecretsFileName, git: Git): Promise { + if (await isTracked(projectRoot, git, file)) { return 'tracked'; } - const state = await ignoreState(projectRoot, git); + const state = await ignoreState(projectRoot, git, file); return state === 'no-repository' ? 'unknown' : state; } diff --git a/electron/content/projectEnv.ts b/electron/content/projectEnv.ts index 094fbb763..f2fbfed99 100644 --- a/electron/content/projectEnv.ts +++ b/electron/content/projectEnv.ts @@ -8,11 +8,11 @@ import path from 'node:path'; import { assert } from '../../shared/core/assert'; import { toRecord } from '../../shared/core/record'; +import { SECRETS_FILE_DEFAULT, SECRETS_FILE_NAMES, type SecretsFileName } from '../../shared/properties/secrets'; import { createProjectText, writeProjectText } from '../documents/documentWrites'; -// Vite's order: a later file wins, and every one of these is read in dev. -const ENV_FILES = ['.env', '.env.local', '.env.development', '.env.development.local'] as const; -const ENV_FILE = '.env'; +// A secret saved from a page template's connection goes where the Secrets tab opens. +const ENV_FILE = SECRETS_FILE_DEFAULT; const ENV_BYTES_MAX = 256 * 1024; const ENV_LINES_MAX = 4000; const ASSIGNMENT = /^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/; @@ -25,7 +25,8 @@ export type Git = (projectPath: string, args: readonly string[]) => Promise { const values = new Map(); - for (const name of ENV_FILES) { + // Vite's order: a later file wins, and every one of these is read in dev. + for (const name of SECRETS_FILE_NAMES) { for (const [key, value] of envEntries(readEnvFile(path.join(projectRoot, name)) ?? '')) { values.set(key, value); } @@ -59,15 +60,19 @@ export function withEnvValue(source: string, name: string, value: string): strin return lines.map((candidate, index) => (index === at ? line : candidate)).join('\n'); } -/** The .gitignore text that ignores .env, or undefined when it already does. */ -export function gitignoreWithEnv(source: string | undefined): string | undefined { +/** The .gitignore text that ignores `file`, or undefined when a rule for it is already written. */ +export function gitignoreWithEnv(source: string | undefined, file: SecretsFileName): string | undefined { + // `*.env` matches `.env` alone; `.env*` matches every dev env file. + const rules = file === '.env' ? [file, `/${file}`, '.env*', '*.env'] : [file, `/${file}`, '.env*']; const lines = (source ?? '').split(/\r?\n/).map((line) => line.trim()); - if (lines.some((line) => line === '.env' || line === '/.env' || line === '.env*' || line === '*.env')) { + if (lines.some((line) => rules.includes(line))) { return undefined; } const text = source ?? ''; const lead = text.length === 0 || text.endsWith('\n') ? text : `${text}\n`; - return `${lead}.env\n`; + const next = `${lead}${file}\n`; + assert(next.startsWith(text), 'gitignoreWithEnv: the existing rules are kept as written'); + return next; } /** @@ -76,11 +81,11 @@ export function gitignoreWithEnv(source: string | undefined): string | undefined * missing, before the secret is written. */ export async function writeProjectSecret(projectRoot: string, input: { readonly name: string; readonly value: string }, git: Git): Promise { - if (await isTracked(projectRoot, git)) { + if (await isTracked(projectRoot, git, ENV_FILE)) { throw new Error('.env is tracked by Git, so a secret saved there would be published. Remove it from Git first.'); } - const change = writeIgnoreRule(projectRoot); - if ((await ignoreState(projectRoot, git)) === 'not-ignored') { + const change = writeIgnoreRule(projectRoot, ENV_FILE); + if ((await ignoreState(projectRoot, git, ENV_FILE)) === 'not-ignored') { throw new Error('.gitignore does not ignore .env, so the secret was not saved. Check .gitignore for a rule that brings it back.'); } const file = path.join(projectRoot, ENV_FILE); @@ -95,10 +100,10 @@ export async function writeProjectSecret(projectRoot: string, input: { readonly return change; } -export function writeIgnoreRule(projectRoot: string): IgnoreChange { +export function writeIgnoreRule(projectRoot: string, envFile: SecretsFileName): IgnoreChange { const file = path.join(projectRoot, '.gitignore'); const before = fs.existsSync(file) ? fs.readFileSync(file, 'utf8') : undefined; - const text = gitignoreWithEnv(before); + const text = gitignoreWithEnv(before, envFile); if (text === undefined) { return 'already-ignored'; } @@ -111,10 +116,10 @@ export function writeIgnoreRule(projectRoot: string): IgnoreChange { } // `git ls-files --error-unmatch` fails for a path Git does not track, and in a -// folder that is not a repository, and both mean .env is not tracked. -export async function isTracked(projectRoot: string, git: Git): Promise { +// folder that is not a repository, and both mean the file is not tracked. +export async function isTracked(projectRoot: string, git: Git, file: SecretsFileName): Promise { try { - await git(projectRoot, ['ls-files', '--error-unmatch', '--', ENV_FILE]); + await git(projectRoot, ['ls-files', '--error-unmatch', '--', file]); return true; } catch { return false; @@ -122,9 +127,9 @@ export async function isTracked(projectRoot: string, git: Git): Promise } // `git check-ignore` exits 1 for a path it does not ignore, and 128 outside a repository. -export async function ignoreState(projectRoot: string, git: Git): Promise<'ignored' | 'not-ignored' | 'no-repository'> { +export async function ignoreState(projectRoot: string, git: Git, file: SecretsFileName): Promise<'ignored' | 'not-ignored' | 'no-repository'> { try { - await git(projectRoot, ['check-ignore', '--quiet', '--', ENV_FILE]); + await git(projectRoot, ['check-ignore', '--quiet', '--', file]); return 'ignored'; } catch (error: unknown) { return toRecord(error)?.['code'] === 1 ? 'not-ignored' : 'no-repository'; diff --git a/electron/content/sanityLogin.ts b/electron/content/sanityLogin.ts index a078d345a..7e0ff4769 100644 --- a/electron/content/sanityLogin.ts +++ b/electron/content/sanityLogin.ts @@ -23,12 +23,12 @@ import { assert } from '../../shared/core/assert'; import { DescribedError } from '../../shared/properties/describedError'; import { described, type Described } from '../../shared/properties/i18n/messageRef'; import { SANITY_LOGIN_TIMEOUT_MS, type SanityLoginRequest, type SanityLoginState, type SanityProjectChoice } from '../../shared/properties/cmsConnections'; +import { SECRETS_FILE_NAMES } from '../../shared/properties/secrets'; import type { CmsConnectionStore } from './cmsConnectionStore'; import { SanityRequestError, createSanityEditorKey, sanityLoginURL, sanityLogout, sanityProjects, sanityTokenForSession } from './sanityApi'; const SUCCESS_PAGE = 'https://www.sanity.io/login/success'; // The .env lines read for a suggestion, and the longest file read for them. -const ENV_FILES = ['.env', '.env.local', '.env.development'] as const; const ENV_BYTES_MAX = 64 * 1024; // One sign-in: its state, and what it holds while it runs. Ending it releases @@ -270,7 +270,7 @@ function failureProblem(error: unknown): Described { // of the person's projects has them. function siteSuggestion(projectRoot: string, projects: readonly SanityProjectChoice[]) { const values = new Map(); - for (const name of ENV_FILES) { + for (const name of SECRETS_FILE_NAMES) { for (const [key, value] of envEntries(path.join(projectRoot, name))) { values.set(key, value); } diff --git a/electron/handlers/secretsHandlers.ts b/electron/handlers/secretsHandlers.ts index bbee6a5a8..7989536e3 100644 --- a/electron/handlers/secretsHandlers.ts +++ b/electron/handlers/secretsHandlers.ts @@ -1,6 +1,6 @@ -// The Settings panel's Secrets channels (shared/properties/secrets.ts): list the names in the -// project's `.env`, read one value on request, apply one change against a revision, and add `.env` -// to `.gitignore`. The work is electron/content/envSecrets.ts; this resolves the project and keeps +// The Settings panel's Secrets channels (shared/properties/secrets.ts), for the dev env file each +// message names: list its names, read one value on request, apply one change against a revision, +// and add the file to `.gitignore`. The work is electron/content/envSecrets.ts; this resolves the project and keeps // secrets out of every log: no handler here prints, and the replies hold names and one value at most. import * as fs from 'node:fs'; import * as path from 'node:path'; @@ -17,8 +17,8 @@ export function registerSecretsHandlers(host: Pick listSecrets(root(input.projectPath), git)); - host.ipcMain.handle('secrets:read', (_event, input) => readSecret(root(input.projectPath), input.revision, input.index)); - host.ipcMain.handle('secrets:apply', (_event, input) => applySecretsChange(root(input.projectPath), input.revision, input.change, git)); - host.ipcMain.handle('secrets:ignore', (_event, input) => ignoreEnvFile(root(input.projectPath), git)); + host.ipcMain.handle('secrets:list', (_event, input) => listSecrets(root(input.projectPath), input.file, git)); + host.ipcMain.handle('secrets:read', (_event, input) => readSecret(root(input.projectPath), input.file, input.revision, input.index)); + host.ipcMain.handle('secrets:apply', (_event, input) => applySecretsChange(root(input.projectPath), input.file, input.revision, input.change, git)); + host.ipcMain.handle('secrets:ignore', (_event, input) => ignoreEnvFile(root(input.projectPath), input.file, git)); } diff --git a/shared/ipc/ipcPayloads.ts b/shared/ipc/ipcPayloads.ts index ad1fc1907..2e97e50e2 100644 --- a/shared/ipc/ipcPayloads.ts +++ b/shared/ipc/ipcPayloads.ts @@ -41,7 +41,7 @@ import { parseMediaName, parseMediaOrder, } from '../properties/mediaHosting'; -import { parseSecretReadIndex, parseSecretsChange, parseSecretsRevision } from '../properties/secrets'; +import { parseSecretReadIndex, parseSecretsChange, parseSecretsFileName, parseSecretsIgnorableFile, parseSecretsRevision } from '../properties/secrets'; import { parseMcpChange, parseMcpCodexChange, parseMcpRevision, parseMcpServerName, parseMcpTextInput } from '../properties/mcp'; import { parseConnectionKeyCopy, parseDataSampleRequest, parseEnvPayloadName, parsePageTemplateDraft, parseSecretValue } from '../properties/pageTemplate'; import { parseAstroRemoteEdit, parseAstroRemoteRead } from '../properties/astroContent'; @@ -611,11 +611,11 @@ export const IPC_PAYLOADS = { 'pageTemplate:plan': object({ ...project, draft: parsePageTemplateDraft }), 'pageTemplate:sample': object({ ...project, request: parseDataSampleRequest }), 'project:setEnv': object({ ...project, name: parseEnvPayloadName, value: parseSecretValue }), - // The Settings panel's Secrets tab (shared/properties/secrets.ts): names listed, one value read on request, one change applied against a revision. - 'secrets:list': object({ ...project }), - 'secrets:read': object({ ...project, revision: parseSecretsRevision, index: parseSecretReadIndex }), - 'secrets:apply': object({ ...project, revision: parseSecretsRevision, change: parseSecretsChange }), - 'secrets:ignore': object({ ...project }), + // The Settings panel's Secrets tab (shared/properties/secrets.ts), one dev env file at a time: names listed, one value read on request, one change applied against a revision. + 'secrets:list': object({ ...project, file: parseSecretsFileName }), + 'secrets:read': object({ ...project, file: parseSecretsFileName, revision: parseSecretsRevision, index: parseSecretReadIndex }), + 'secrets:apply': object({ ...project, file: parseSecretsFileName, revision: parseSecretsRevision, change: parseSecretsChange }), + 'secrets:ignore': object({ ...project, file: parseSecretsIgnorableFile }), // The Settings panel's MCP tab (shared/properties/mcp.ts): the project's .mcp.json listed, read as text, one server revealed, a change or the whole text saved against a revision, and Codex's file. 'mcp:read': object({ ...project }), 'mcp:readText': object({ ...project }), diff --git a/shared/properties/i18n/messages/de/settings.ts b/shared/properties/i18n/messages/de/settings.ts index 68ff26045..acf4d75ed 100644 --- a/shared/properties/i18n/messages/de/settings.ts +++ b/shared/properties/i18n/messages/de/settings.ts @@ -255,53 +255,53 @@ export const messages = { 'settings.roles.viewAs.label': 'Ansicht als', 'settings.saved': 'Gespeichert', 'settings.saving': 'Wird gespeichert …', - 'settings.secrets.create': '.env-Datei erstellen', - 'settings.secrets.empty.noFileBody': 'Noch keine .env-Datei.', - 'settings.secrets.error.tooLarge': 'Die .env-Datei ist zu groß, um sie hier zu bearbeiten.', - 'settings.secrets.error.notText': 'Kein gültiges UTF-8, daher lässt Stacki .env unberührt.', - 'settings.secrets.error.denied': '.env nicht lesbar. Prüfe die Rechte.', + 'settings.secrets.empty.noFileBody': 'Noch keine {file}-Datei. Ein Secret anzulegen erstellt sie.', // review + 'settings.secrets.error.tooLarge': 'Die {file}-Datei ist zu groß, um sie hier zu bearbeiten.', + 'settings.secrets.error.notText': 'Kein gültiges UTF-8, daher lässt Stacki {file} unberührt.', + 'settings.secrets.error.denied': '{file} nicht lesbar. Prüfe die Rechte.', 'settings.secrets.unavailable': 'Starte Stacki neu, um Secrets zu nutzen.', 'settings.secrets.add': 'Geheimnis hinzufügen', 'settings.secrets.cancel': 'Abbrechen', 'settings.secrets.delete.action': '{name} löschen', - 'settings.secrets.delete.body': 'Entfernt die Zeile aus .env. Das lässt sich nicht rückgängig machen.', + 'settings.secrets.delete.body': 'Entfernt die Zeile aus {file}. Das lässt sich nicht rückgängig machen.', 'settings.secrets.delete.confirm': 'Löschen', 'settings.secrets.delete.title': '{name} löschen?', - 'settings.secrets.duplicate': 'Zweimal in .env gesetzt. Der letzte gilt.', + 'settings.secrets.duplicate': 'Zweimal in {file} gesetzt. Der letzte gilt.', 'settings.secrets.edit.action': '{name} bearbeiten', - 'settings.secrets.empty.body': 'Ein Secret anzulegen erstellt .env.', + 'settings.secrets.empty.body': '{file} ist leer.', // review 'settings.secrets.empty.title': 'Noch keine Geheimnisse', - 'settings.secrets.error.changed': '.env hat sich geändert. Lade neu.', - 'settings.secrets.error.filesystem': 'Die .env-Datei konnte nicht gespeichert werden.', + 'settings.secrets.error.changed': '{file} hat sich geändert. Lade neu.', + 'settings.secrets.error.filesystem': 'Die {file}-Datei konnte nicht gespeichert werden.', 'settings.secrets.error.invalidName': 'Verwenden Sie Buchstaben, Ziffern und Unterstriche und beginnen Sie nicht mit einer Ziffer.', 'settings.secrets.error.invalidValue': 'Dieser Wert kann nicht gespeichert werden.', - 'settings.secrets.error.limit': 'Die .env-Datei ist voll. Entfernen Sie zuerst ein Geheimnis.', + 'settings.secrets.error.limit': 'Die {file}-Datei ist voll. Entfernen Sie zuerst ein Geheimnis.', 'settings.secrets.error.nameEmpty': 'Geben Sie einen Namen ein.', 'settings.secrets.error.nameTaken': 'Ein Geheimnis mit diesem Namen existiert bereits.', 'settings.secrets.error.nameTooLong': 'Namen dürfen bis zu {max} Zeichen lang sein.', 'settings.secrets.error.notFound': 'Dieses Geheimnis steht nicht mehr in der Datei. Laden Sie neu, um den aktuellen Stand zu sehen.', - 'settings.secrets.error.readOnly': 'Mehrere Zeilen. Bearbeite es in .env.', - 'settings.secrets.error.unreadable': 'Die .env-Datei konnte nicht gelesen werden.', + 'settings.secrets.error.readOnly': 'Mehrere Zeilen. Bearbeite es in {file}.', + 'settings.secrets.error.unreadable': 'Die {file}-Datei konnte nicht gelesen werden.', 'settings.secrets.error.valueTooLong': 'Werte dürfen bis zu {max} KB groß sein.', + 'settings.secrets.file': 'Env-Datei', // review 'settings.secrets.hide.action': '{name} verbergen', 'settings.secrets.hideAll': 'Alle verbergen', 'settings.secrets.ignore.action': 'Zu .gitignore hinzufügen', - 'settings.secrets.ignore.body': 'Fügt .gitignore die Zeile .env hinzu.', + 'settings.secrets.ignore.body': 'Fügt .gitignore die Zeile {file} hinzu.', 'settings.secrets.ignore.confirm': 'Zeile hinzufügen', - 'settings.secrets.ignore.title': '.env zu .gitignore hinzufügen?', - 'settings.secrets.ignore.warning': '.env steht nicht in .gitignore: Geheimnisse könnten committet werden', - 'settings.secrets.intro': 'Gespeichert in .env', + 'settings.secrets.ignore.title': '{file} zu .gitignore hinzufügen?', + 'settings.secrets.ignore.warning': '{file} steht nicht in .gitignore: Geheimnisse könnten committet werden', 'settings.secrets.info': 'Werte bleiben verborgen, bis du sie anzeigst.', - 'settings.secrets.invalidLines': '{count} unlesbare .env-Zeilen bleiben unverändert.', - 'settings.secrets.multiline': 'Mehrere Zeilen. Bearbeite es in .env.', + 'settings.secrets.invalidLines': '{count} unlesbare {file}-Zeilen bleiben unverändert.', + 'settings.secrets.multiline': 'Mehrere Zeilen. Bearbeite es in {file}.', 'settings.secrets.name': 'Name', // same + 'settings.secrets.overridden': 'Im Dev-Modus gilt der Wert aus {file}', // review 'settings.secrets.reload': 'Neu laden', 'settings.secrets.reveal.action': '{name} anzeigen', 'settings.secrets.revealAll': 'Alle anzeigen', 'settings.secrets.save': 'Speichern', 'settings.secrets.tab': 'Geheimnisse', 'settings.secrets.title': 'Geheimnisse', - 'settings.secrets.tracked.warning': '.env wird von Git verfolgt: Die Geheimnisse darin sind committet', + 'settings.secrets.tracked.warning': '{file} ist in Git committet', // review 'settings.secrets.value': 'Wert', 'settings.secrets.valueHidden': 'Verborgener Wert', 'settings.sections': 'Einstellungsbereiche', diff --git a/shared/properties/i18n/messages/en/settings.ts b/shared/properties/i18n/messages/en/settings.ts index 86748a1d2..8ca05924e 100644 --- a/shared/properties/i18n/messages/en/settings.ts +++ b/shared/properties/i18n/messages/en/settings.ts @@ -251,53 +251,53 @@ export const messages = { 'settings.roles.viewAs.label': 'View as', 'settings.saved': 'Saved', 'settings.saving': 'Saving…', - 'settings.secrets.create': 'Create .env file', - 'settings.secrets.empty.noFileBody': 'No .env file yet.', - 'settings.secrets.error.tooLarge': 'The .env file is too large to edit here.', - 'settings.secrets.error.notText': 'Not valid UTF-8, so Stacki leaves .env alone.', - 'settings.secrets.error.denied': 'Cannot read .env. Check its permissions.', + 'settings.secrets.empty.noFileBody': 'No {file} file yet. Adding a secret creates it.', + 'settings.secrets.error.tooLarge': 'The {file} file is too large to edit here.', + 'settings.secrets.error.notText': 'Not valid UTF-8, so Stacki leaves {file} alone.', + 'settings.secrets.error.denied': 'Cannot read {file}. Check its permissions.', 'settings.secrets.unavailable': 'Restart Stacki to use secrets.', 'settings.secrets.add': 'Add secret', 'settings.secrets.cancel': 'Cancel', 'settings.secrets.delete.action': 'Delete {name}', - 'settings.secrets.delete.body': 'Removes the line from .env. This cannot be undone.', + 'settings.secrets.delete.body': 'Removes the line from {file}. This cannot be undone.', 'settings.secrets.delete.confirm': 'Delete', 'settings.secrets.delete.title': 'Delete {name}?', - 'settings.secrets.duplicate': 'Set twice in .env. The last one wins.', + 'settings.secrets.duplicate': 'Set twice in {file}. The last one wins.', 'settings.secrets.edit.action': 'Edit {name}', - 'settings.secrets.empty.body': 'Adding a secret creates .env.', + 'settings.secrets.empty.body': '{file} is empty.', 'settings.secrets.empty.title': 'No secrets yet', - 'settings.secrets.error.changed': '.env changed on disk. Reload to see it.', - 'settings.secrets.error.filesystem': 'The .env file could not be saved.', + 'settings.secrets.error.changed': '{file} changed on disk. Reload to see it.', + 'settings.secrets.error.filesystem': 'The {file} file could not be saved.', 'settings.secrets.error.invalidName': 'Use letters, numbers and underscores, and do not start with a number.', 'settings.secrets.error.invalidValue': 'This value cannot be saved.', - 'settings.secrets.error.limit': 'The .env file is full. Remove a secret first.', + 'settings.secrets.error.limit': 'The {file} file is full. Remove a secret first.', 'settings.secrets.error.nameEmpty': 'Enter a name.', 'settings.secrets.error.nameTaken': 'A secret with this name already exists.', 'settings.secrets.error.nameTooLong': 'Names can be up to {max} characters.', 'settings.secrets.error.notFound': 'That secret is no longer in the file. Reload to see the latest.', - 'settings.secrets.error.readOnly': 'Several lines. Edit it in .env.', - 'settings.secrets.error.unreadable': 'The .env file could not be read.', + 'settings.secrets.error.readOnly': 'Several lines. Edit it in {file}.', + 'settings.secrets.error.unreadable': 'The {file} file could not be read.', 'settings.secrets.error.valueTooLong': 'Values can be up to {max} KB.', + 'settings.secrets.file': 'Env file', 'settings.secrets.hide.action': 'Hide {name}', 'settings.secrets.hideAll': 'Hide all', 'settings.secrets.ignore.action': 'Add to .gitignore', - 'settings.secrets.ignore.body': 'Adds one line, .env, to .gitignore.', + 'settings.secrets.ignore.body': 'Adds one line, {file}, to .gitignore.', 'settings.secrets.ignore.confirm': 'Add line', - 'settings.secrets.ignore.title': 'Add .env to .gitignore?', - 'settings.secrets.ignore.warning': '.env is not in .gitignore: secrets could be committed', - 'settings.secrets.intro': 'Stored in .env', + 'settings.secrets.ignore.title': 'Add {file} to .gitignore?', + 'settings.secrets.ignore.warning': '{file} is not in .gitignore: secrets could be committed', 'settings.secrets.info': 'Values stay hidden until you reveal them.', - 'settings.secrets.invalidLines': '{count} unreadable .env lines are kept as written.', - 'settings.secrets.multiline': 'Several lines. Edit it in .env.', + 'settings.secrets.invalidLines': '{count} unreadable {file} lines are kept as written.', + 'settings.secrets.multiline': 'Several lines. Edit it in {file}.', 'settings.secrets.name': 'Name', + 'settings.secrets.overridden': 'Dev uses the value in {file}', 'settings.secrets.reload': 'Reload', 'settings.secrets.reveal.action': 'Reveal {name}', 'settings.secrets.revealAll': 'Reveal all', 'settings.secrets.save': 'Save', 'settings.secrets.tab': 'Secrets', 'settings.secrets.title': 'Secrets', - 'settings.secrets.tracked.warning': '.env is tracked by Git: its secrets are committed', + 'settings.secrets.tracked.warning': '{file} is committed to Git', 'settings.secrets.value': 'Value', 'settings.secrets.valueHidden': 'Hidden value', 'settings.sections': 'Settings sections', diff --git a/shared/properties/i18n/messages/es/settings.ts b/shared/properties/i18n/messages/es/settings.ts index e1fecd83d..0e85ea4b3 100644 --- a/shared/properties/i18n/messages/es/settings.ts +++ b/shared/properties/i18n/messages/es/settings.ts @@ -253,53 +253,53 @@ export const messages = { 'settings.roles.viewAs.label': 'Ver como', 'settings.saved': 'Guardado', 'settings.saving': 'Guardando…', - 'settings.secrets.create': 'Crear archivo .env', - 'settings.secrets.empty.noFileBody': 'Aún no hay archivo .env.', - 'settings.secrets.error.tooLarge': 'El archivo .env es demasiado grande para editarlo aquí.', - 'settings.secrets.error.notText': 'No es UTF-8 válido, así que Stacki no toca .env.', - 'settings.secrets.error.denied': 'No se puede leer .env. Revisa sus permisos.', + 'settings.secrets.empty.noFileBody': 'Aún no hay archivo {file}. Al añadir un secreto se crea.', // review + 'settings.secrets.error.tooLarge': 'El archivo {file} es demasiado grande para editarlo aquí.', + 'settings.secrets.error.notText': 'No es UTF-8 válido, así que Stacki no toca {file}.', + 'settings.secrets.error.denied': 'No se puede leer {file}. Revisa sus permisos.', 'settings.secrets.unavailable': 'Reinicia Stacki para usar los secretos.', 'settings.secrets.add': 'Añadir secreto', 'settings.secrets.cancel': 'Cancelar', 'settings.secrets.delete.action': 'Eliminar {name}', - 'settings.secrets.delete.body': 'Quita la línea de .env. No se puede deshacer.', + 'settings.secrets.delete.body': 'Quita la línea de {file}. No se puede deshacer.', 'settings.secrets.delete.confirm': 'Eliminar', 'settings.secrets.delete.title': '¿Eliminar {name}?', - 'settings.secrets.duplicate': 'Definido dos veces en .env. Gana el último.', + 'settings.secrets.duplicate': 'Definido dos veces en {file}. Gana el último.', 'settings.secrets.edit.action': 'Editar {name}', - 'settings.secrets.empty.body': 'Al añadir un secreto se crea .env.', + 'settings.secrets.empty.body': '{file} está vacío.', // review 'settings.secrets.empty.title': 'Aún no hay secretos', - 'settings.secrets.error.changed': '.env cambió en el disco. Recarga para verlo.', - 'settings.secrets.error.filesystem': 'No se pudo guardar el archivo .env.', + 'settings.secrets.error.changed': '{file} cambió en el disco. Recarga para verlo.', + 'settings.secrets.error.filesystem': 'No se pudo guardar el archivo {file}.', 'settings.secrets.error.invalidName': 'Usa letras, números y guiones bajos, y no empieces con un número.', 'settings.secrets.error.invalidValue': 'Este valor no se puede guardar.', - 'settings.secrets.error.limit': 'El archivo .env está lleno. Elimina un secreto primero.', + 'settings.secrets.error.limit': 'El archivo {file} está lleno. Elimina un secreto primero.', 'settings.secrets.error.nameEmpty': 'Escribe un nombre.', 'settings.secrets.error.nameTaken': 'Ya existe un secreto con este nombre.', 'settings.secrets.error.nameTooLong': 'Los nombres pueden tener hasta {max} caracteres.', 'settings.secrets.error.notFound': 'Ese secreto ya no está en el archivo. Recarga para ver lo último.', - 'settings.secrets.error.readOnly': 'Varias líneas. Edítalo en .env.', - 'settings.secrets.error.unreadable': 'No se pudo leer el archivo .env.', + 'settings.secrets.error.readOnly': 'Varias líneas. Edítalo en {file}.', + 'settings.secrets.error.unreadable': 'No se pudo leer el archivo {file}.', 'settings.secrets.error.valueTooLong': 'Los valores pueden ocupar hasta {max} KB.', + 'settings.secrets.file': 'Archivo env', // review 'settings.secrets.hide.action': 'Ocultar {name}', 'settings.secrets.hideAll': 'Ocultar todo', 'settings.secrets.ignore.action': 'Añadir a .gitignore', - 'settings.secrets.ignore.body': 'Añade una línea, .env, a .gitignore.', + 'settings.secrets.ignore.body': 'Añade una línea, {file}, a .gitignore.', 'settings.secrets.ignore.confirm': 'Añadir línea', - 'settings.secrets.ignore.title': '¿Añadir .env a .gitignore?', - 'settings.secrets.ignore.warning': '.env no está en .gitignore: los secretos podrían subirse a Git', - 'settings.secrets.intro': 'Guardado en .env', + 'settings.secrets.ignore.title': '¿Añadir {file} a .gitignore?', + 'settings.secrets.ignore.warning': '{file} no está en .gitignore: los secretos podrían subirse a Git', 'settings.secrets.info': 'Los valores permanecen ocultos hasta que los reveles.', - 'settings.secrets.invalidLines': '{count} líneas ilegibles de .env se conservan tal cual.', - 'settings.secrets.multiline': 'Varias líneas. Edítalo en .env.', + 'settings.secrets.invalidLines': '{count} líneas ilegibles de {file} se conservan tal cual.', + 'settings.secrets.multiline': 'Varias líneas. Edítalo en {file}.', 'settings.secrets.name': 'Nombre', + 'settings.secrets.overridden': 'En desarrollo se usa el valor de {file}', // review 'settings.secrets.reload': 'Recargar', 'settings.secrets.reveal.action': 'Revelar {name}', 'settings.secrets.revealAll': 'Revelar todo', 'settings.secrets.save': 'Guardar', 'settings.secrets.tab': 'Secretos', 'settings.secrets.title': 'Secretos', - 'settings.secrets.tracked.warning': '.env está en el seguimiento de Git: sus secretos ya están subidos', + 'settings.secrets.tracked.warning': '{file} está subido a Git', // review 'settings.secrets.value': 'Valor', 'settings.secrets.valueHidden': 'Valor oculto', 'settings.sections': 'Secciones de los ajustes', diff --git a/shared/properties/i18n/messages/fr/settings.ts b/shared/properties/i18n/messages/fr/settings.ts index 3b7916204..6ac785d51 100644 --- a/shared/properties/i18n/messages/fr/settings.ts +++ b/shared/properties/i18n/messages/fr/settings.ts @@ -254,53 +254,53 @@ export const messages = { 'settings.roles.viewAs.label': 'Voir en tant que', 'settings.saved': 'Enregistré', 'settings.saving': 'Enregistrement…', - 'settings.secrets.create': 'Créer le fichier .env', - 'settings.secrets.empty.noFileBody': 'Pas encore de fichier .env.', - 'settings.secrets.error.tooLarge': 'Le fichier .env est trop volumineux pour être modifié ici.', - 'settings.secrets.error.notText': 'UTF-8 invalide : Stacki ne touche pas à .env.', - 'settings.secrets.error.denied': 'Impossible de lire .env. Vérifiez ses droits.', + 'settings.secrets.empty.noFileBody': 'Pas encore de fichier {file}. Ajouter un secret le crée.', // review + 'settings.secrets.error.tooLarge': 'Le fichier {file} est trop volumineux pour être modifié ici.', + 'settings.secrets.error.notText': 'UTF-8 invalide : Stacki ne touche pas à {file}.', + 'settings.secrets.error.denied': 'Impossible de lire {file}. Vérifiez ses droits.', 'settings.secrets.unavailable': 'Redémarrez Stacki pour utiliser les secrets.', 'settings.secrets.add': 'Ajouter un secret', 'settings.secrets.cancel': 'Annuler', 'settings.secrets.delete.action': 'Supprimer {name}', - 'settings.secrets.delete.body': 'Retire la ligne de .env. Action irréversible.', + 'settings.secrets.delete.body': 'Retire la ligne de {file}. Action irréversible.', 'settings.secrets.delete.confirm': 'Supprimer', 'settings.secrets.delete.title': 'Supprimer {name} ?', - 'settings.secrets.duplicate': 'Défini deux fois dans .env. Le dernier l’emporte.', + 'settings.secrets.duplicate': 'Défini deux fois dans {file}. Le dernier l’emporte.', 'settings.secrets.edit.action': 'Modifier {name}', - 'settings.secrets.empty.body': 'Ajouter un secret crée .env.', + 'settings.secrets.empty.body': '{file} est vide.', // review 'settings.secrets.empty.title': 'Aucun secret pour l’instant', - 'settings.secrets.error.changed': '.env a changé sur le disque. Rechargez.', - 'settings.secrets.error.filesystem': 'Le fichier .env n’a pas pu être enregistré.', + 'settings.secrets.error.changed': '{file} a changé sur le disque. Rechargez.', + 'settings.secrets.error.filesystem': 'Le fichier {file} n’a pas pu être enregistré.', 'settings.secrets.error.invalidName': 'Utilisez des lettres, des chiffres et des tirets bas, sans commencer par un chiffre.', 'settings.secrets.error.invalidValue': 'Cette valeur ne peut pas être enregistrée.', - 'settings.secrets.error.limit': 'Le fichier .env est plein. Supprimez d’abord un secret.', + 'settings.secrets.error.limit': 'Le fichier {file} est plein. Supprimez d’abord un secret.', 'settings.secrets.error.nameEmpty': 'Saisissez un nom.', 'settings.secrets.error.nameTaken': 'Un secret portant ce nom existe déjà.', 'settings.secrets.error.nameTooLong': 'Les noms peuvent compter jusqu’à {max} caractères.', 'settings.secrets.error.notFound': 'Ce secret n’est plus dans le fichier. Rechargez pour voir la dernière version.', - 'settings.secrets.error.readOnly': 'Plusieurs lignes. Modifiez-le dans .env.', - 'settings.secrets.error.unreadable': 'Le fichier .env n’a pas pu être lu.', + 'settings.secrets.error.readOnly': 'Plusieurs lignes. Modifiez-le dans {file}.', + 'settings.secrets.error.unreadable': 'Le fichier {file} n’a pas pu être lu.', 'settings.secrets.error.valueTooLong': 'Les valeurs peuvent peser jusqu’à {max} Ko.', + 'settings.secrets.file': 'Fichier env', // review 'settings.secrets.hide.action': 'Masquer {name}', 'settings.secrets.hideAll': 'Tout masquer', 'settings.secrets.ignore.action': 'Ajouter à .gitignore', - 'settings.secrets.ignore.body': 'Ajoute une ligne, .env, à .gitignore.', + 'settings.secrets.ignore.body': 'Ajoute une ligne, {file}, à .gitignore.', 'settings.secrets.ignore.confirm': 'Ajouter la ligne', - 'settings.secrets.ignore.title': 'Ajouter .env à .gitignore ?', - 'settings.secrets.ignore.warning': '.env n’est pas dans .gitignore : les secrets pourraient être commités', - 'settings.secrets.intro': 'Dans .env', + 'settings.secrets.ignore.title': 'Ajouter {file} à .gitignore ?', + 'settings.secrets.ignore.warning': '{file} n’est pas dans .gitignore : les secrets pourraient être commités', 'settings.secrets.info': 'Les valeurs restent masquées tant que vous ne les révélez pas.', - 'settings.secrets.invalidLines': '{count} lignes illisibles de .env sont conservées telles quelles.', - 'settings.secrets.multiline': 'Plusieurs lignes. Modifiez-le dans .env.', + 'settings.secrets.invalidLines': '{count} lignes illisibles de {file} sont conservées telles quelles.', + 'settings.secrets.multiline': 'Plusieurs lignes. Modifiez-le dans {file}.', 'settings.secrets.name': 'Nom', + 'settings.secrets.overridden': 'En dev, la valeur de {file} est utilisée', // review 'settings.secrets.reload': 'Recharger', 'settings.secrets.reveal.action': 'Révéler {name}', 'settings.secrets.revealAll': 'Tout révéler', 'settings.secrets.save': 'Enregistrer', 'settings.secrets.tab': 'Secrets', // same 'settings.secrets.title': 'Secrets', // same - 'settings.secrets.tracked.warning': '.env est suivi par Git : ses secrets sont déjà commités', + 'settings.secrets.tracked.warning': '{file} est commité dans Git', // review 'settings.secrets.value': 'Valeur', 'settings.secrets.valueHidden': 'Valeur masquée', 'settings.sections': 'Sections des réglages', diff --git a/shared/properties/i18n/messages/ptBR/settings.ts b/shared/properties/i18n/messages/ptBR/settings.ts index 462e910c7..773a20651 100644 --- a/shared/properties/i18n/messages/ptBR/settings.ts +++ b/shared/properties/i18n/messages/ptBR/settings.ts @@ -252,53 +252,53 @@ export const messages = { 'settings.roles.viewAs.label': 'Ver como', 'settings.saved': 'Salvo', 'settings.saving': 'Salvando…', - 'settings.secrets.create': 'Criar arquivo .env', - 'settings.secrets.empty.noFileBody': 'Ainda não há arquivo .env.', - 'settings.secrets.error.tooLarge': 'O arquivo .env é grande demais para ser editado aqui.', - 'settings.secrets.error.notText': 'UTF-8 inválido, então o Stacki não mexe no .env.', - 'settings.secrets.error.denied': 'Não foi possível ler o .env. Verifique as permissões.', + 'settings.secrets.empty.noFileBody': 'Ainda não há arquivo {file}. Adicionar um segredo cria o arquivo.', // review + 'settings.secrets.error.tooLarge': 'O arquivo {file} é grande demais para ser editado aqui.', + 'settings.secrets.error.notText': 'UTF-8 inválido, então o Stacki não mexe no {file}.', + 'settings.secrets.error.denied': 'Não foi possível ler o {file}. Verifique as permissões.', 'settings.secrets.unavailable': 'Reinicie o Stacki para usar os segredos.', 'settings.secrets.add': 'Adicionar segredo', 'settings.secrets.cancel': 'Cancelar', 'settings.secrets.delete.action': 'Excluir {name}', - 'settings.secrets.delete.body': 'Remove a linha do .env. Não dá para desfazer.', + 'settings.secrets.delete.body': 'Remove a linha do {file}. Não dá para desfazer.', 'settings.secrets.delete.confirm': 'Excluir', 'settings.secrets.delete.title': 'Excluir {name}?', - 'settings.secrets.duplicate': 'Definido duas vezes no .env. O último vale.', + 'settings.secrets.duplicate': 'Definido duas vezes no {file}. O último vale.', 'settings.secrets.edit.action': 'Editar {name}', - 'settings.secrets.empty.body': 'Adicionar um segredo cria o .env.', + 'settings.secrets.empty.body': 'O {file} está vazio.', // review 'settings.secrets.empty.title': 'Nenhum segredo ainda', - 'settings.secrets.error.changed': 'O .env mudou no disco. Recarregue.', - 'settings.secrets.error.filesystem': 'Não foi possível salvar o arquivo .env.', + 'settings.secrets.error.changed': 'O {file} mudou no disco. Recarregue.', + 'settings.secrets.error.filesystem': 'Não foi possível salvar o arquivo {file}.', 'settings.secrets.error.invalidName': 'Use letras, números e sublinhados, e não comece com um número.', 'settings.secrets.error.invalidValue': 'Este valor não pode ser salvo.', - 'settings.secrets.error.limit': 'O arquivo .env está cheio. Remova um segredo primeiro.', + 'settings.secrets.error.limit': 'O arquivo {file} está cheio. Remova um segredo primeiro.', 'settings.secrets.error.nameEmpty': 'Digite um nome.', 'settings.secrets.error.nameTaken': 'Já existe um segredo com este nome.', 'settings.secrets.error.nameTooLong': 'Os nomes podem ter até {max} caracteres.', 'settings.secrets.error.notFound': 'Esse segredo não está mais no arquivo. Recarregue para ver a versão mais recente.', - 'settings.secrets.error.readOnly': 'Várias linhas. Edite no .env.', - 'settings.secrets.error.unreadable': 'Não foi possível ler o arquivo .env.', + 'settings.secrets.error.readOnly': 'Várias linhas. Edite no {file}.', + 'settings.secrets.error.unreadable': 'Não foi possível ler o arquivo {file}.', 'settings.secrets.error.valueTooLong': 'Os valores podem ter até {max} KB.', + 'settings.secrets.file': 'Arquivo env', // review 'settings.secrets.hide.action': 'Ocultar {name}', 'settings.secrets.hideAll': 'Ocultar todos', 'settings.secrets.ignore.action': 'Adicionar ao .gitignore', - 'settings.secrets.ignore.body': 'Adiciona uma linha, .env, ao .gitignore.', + 'settings.secrets.ignore.body': 'Adiciona uma linha, {file}, ao .gitignore.', 'settings.secrets.ignore.confirm': 'Adicionar linha', - 'settings.secrets.ignore.title': 'Adicionar .env ao .gitignore?', - 'settings.secrets.ignore.warning': '.env não está no .gitignore: os segredos podem ser commitados', - 'settings.secrets.intro': 'Salvo em .env', + 'settings.secrets.ignore.title': 'Adicionar {file} ao .gitignore?', + 'settings.secrets.ignore.warning': '{file} não está no .gitignore: os segredos podem ser commitados', 'settings.secrets.info': 'Os valores ficam ocultos até você revelá-los.', - 'settings.secrets.invalidLines': '{count} linhas ilegíveis do .env são mantidas como estão.', - 'settings.secrets.multiline': 'Várias linhas. Edite no .env.', + 'settings.secrets.invalidLines': '{count} linhas ilegíveis do {file} são mantidas como estão.', + 'settings.secrets.multiline': 'Várias linhas. Edite no {file}.', 'settings.secrets.name': 'Nome', + 'settings.secrets.overridden': 'Em dev, vale o valor de {file}', // review 'settings.secrets.reload': 'Recarregar', 'settings.secrets.reveal.action': 'Revelar {name}', 'settings.secrets.revealAll': 'Revelar todos', 'settings.secrets.save': 'Salvar', 'settings.secrets.tab': 'Segredos', 'settings.secrets.title': 'Segredos', - 'settings.secrets.tracked.warning': '.env é rastreado pelo Git: seus segredos já foram commitados', + 'settings.secrets.tracked.warning': '{file} está commitado no Git', // review 'settings.secrets.value': 'Valor', 'settings.secrets.valueHidden': 'Valor oculto', 'settings.sections': 'Seções das configurações', diff --git a/shared/properties/secrets.ts b/shared/properties/secrets.ts index 33cd7b971..ebac8eedb 100644 --- a/shared/properties/secrets.ts +++ b/shared/properties/secrets.ts @@ -1,5 +1,5 @@ // The Settings panel's Secrets tab: the contract between the renderer and the main -// process for the project's `.env`. The list carries names only. A value crosses once, +// process for the project's env files, one file at a time. The list carries names only. A value crosses once, // in a `secrets:read` reply, when a person reveals or edits it, and is never part of a // listing, an error or a log line. Every change names the revision (a digest of the file's // exact bytes) it was authored against, so a file edited outside Stacki is refused with @@ -13,7 +13,46 @@ import type { Digest } from '../core/brand'; import type { Result } from '../core/result'; import { ENV_LIMITS, envValueProblem, isEnvName, type EnvChange } from './envFile'; -export const SECRETS_FILE_NAME = '.env'; +/** + * The env files the dev server loads, in the order it loads them: a name set in a later file + * wins over the same name in an earlier one. `.env.production` is for builds and is not here. + */ +export const SECRETS_FILE_NAMES = ['.env', '.env.local', '.env.development', '.env.development.local'] as const; +export type SecretsFileName = (typeof SECRETS_FILE_NAMES)[number]; + +/** The file the tab opens on, and the one other features (the MCP tab) write secrets to. */ +export const SECRETS_FILE_DEFAULT: SecretsFileName = '.env'; + +/** + * Whether the tab offers to add a file to `.gitignore`. `.env.development` is left out: it is + * usually committed on purpose, for values that are not secret. + */ +export function secretsFileIgnorable(file: SecretsFileName): boolean { + return file !== '.env.development'; +} + +/** Whether `later` loads after `file`, so a name set in both takes `later`'s value. */ +export function secretsFileLoadsAfter(later: SecretsFileName, file: SecretsFileName): boolean { + return SECRETS_FILE_NAMES.indexOf(later) > SECRETS_FILE_NAMES.indexOf(file); +} + +/** One of the dev env files, from the wire. */ +export function parseSecretsFileName(input: unknown): SecretsFileName { + const file = SECRETS_FILE_NAMES.find((name) => name === input); + if (file === undefined) { + throw new Error('Secrets: expected a dev env file name'); + } + return file; +} + +/** A file the panel may add to `.gitignore`. */ +export function parseSecretsIgnorableFile(input: unknown): SecretsFileName { + const file = parseSecretsFileName(input); + if (!secretsFileIgnorable(file)) { + throw new Error('Secrets: this file is not offered for .gitignore'); + } + return file; +} /** Where `.env` stands with Git: `unknown` outside a repository, where nothing can be committed. */ export const SECRETS_IGNORE_STATES = ['ignored', 'not-ignored', 'tracked', 'unknown'] as const; @@ -49,9 +88,13 @@ export interface SecretSummary { readonly name: string; readonly duplicate: boolean; readonly multiline: boolean; + /** The last file in load order that sets the same name, when one loads after this file: dev uses that value. */ + readonly overriddenBy?: SecretsFileName; } export interface SecretsListing { + /** The file this listing reads. */ + readonly file: SecretsFileName; /** The digest of the file's bytes, or of no bytes when the file does not exist. */ readonly revision: Digest; readonly exists: boolean; @@ -134,11 +177,17 @@ export function parseSecretsListing(input: unknown): SecretsListing { if (typeof exists !== 'boolean') { throw new Error('Secrets: expected a presence flag'); } - const listing: SecretsListing = { revision: digest(fields['revision']), exists, entries: entries.map(parseSummary), invalidLines, ignore }; + const file = parseSecretsFileName(fields['file']); + const listing: SecretsListing = { file, revision: digest(fields['revision']), exists, entries: entries.map(parseSummary), invalidLines, ignore }; assert( listing.entries.every((entry, at) => entry.index === at), 'Secrets are listed in index order', ); + for (const entry of listing.entries) { + if (entry.overriddenBy !== undefined) { + assert(secretsFileLoadsAfter(entry.overriddenBy, file), 'A secret is overridden only by a file that loads after its own'); + } + } return listing; } @@ -176,7 +225,9 @@ function parseSummary(input: unknown): SecretSummary { if (typeof duplicate !== 'boolean' || typeof multiline !== 'boolean') { throw new Error('Secrets: expected entry flags'); } - return { index: parseSecretIndex(fields['index']), name: parseSummaryName(fields['name']), duplicate, multiline }; + const summary = { index: parseSecretIndex(fields['index']), name: parseSummaryName(fields['name']), duplicate, multiline }; + const overriddenBy = optional(parseSecretsFileName)(fields['overriddenBy']); + return overriddenBy === undefined ? summary : { ...summary, overriddenBy }; } // A name read from a file is listed as written; only the editable ones pass `isEnvName`'s length bound. diff --git a/src/features/projectSettings/McpAddSection.tsx b/src/features/projectSettings/McpAddSection.tsx index d2c39ad7b..bd8b3b11b 100644 --- a/src/features/projectSettings/McpAddSection.tsx +++ b/src/features/projectSettings/McpAddSection.tsx @@ -19,7 +19,7 @@ import ProviderLogo from '../../ui/ProviderLogo'; import InfoHint from '../../ui/InfoHint'; import { addServerWithSecrets, type SecretToStore } from './mcpFlows'; import { PASTE_PROBLEM_KEYS, PROVIDER_PROBLEM_KEYS } from './mcpModel'; -import { problemKey } from './secretsModel'; +import { DEFAULT_SECRETS_FILE_PARAMS, problemKey } from './secretsModel'; interface AddProps { readonly projectPath: string; @@ -196,7 +196,7 @@ function ProviderForm({ })} {problem !== undefined && ( - {translate(problem)} + {translate(problem, DEFAULT_SECRETS_FILE_PARAMS)} )}
@@ -338,7 +338,7 @@ function PasteRow({ projectPath, listing, envNames, onAdded, onFailure, onPick } )} {problem !== undefined && ( - {translate(problem)} + {translate(problem, DEFAULT_SECRETS_FILE_PARAMS)} )}
diff --git a/src/features/projectSettings/McpJsonView.tsx b/src/features/projectSettings/McpJsonView.tsx index eaa39821d..dfa954db7 100644 --- a/src/features/projectSettings/McpJsonView.tsx +++ b/src/features/projectSettings/McpJsonView.tsx @@ -9,6 +9,7 @@ import type { McpListing, McpText } from '../../../shared/properties/mcp'; import { mcpJsonIssues } from '../../../shared/properties/mcpJson'; import type { Result } from '../../../shared/core/result'; import type { MessageKey } from '../../lib/i18n/localeContext'; +import { DEFAULT_SECRETS_FILE_PARAMS } from './secretsModel'; import { useTranslate } from '../../lib/i18n/useTranslate'; import CodeEditor from '../../ui/CodeEditor'; import { readMcpText, saveMcpText } from './mcpBridge'; @@ -130,7 +131,7 @@ export default function McpJsonView({ )} {failure !== undefined && (
- {translate(failure)} + {translate(failure, DEFAULT_SECRETS_FILE_PARAMS)}
)} {issues.length > 0 && ( diff --git a/src/features/projectSettings/McpTab.tsx b/src/features/projectSettings/McpTab.tsx index 3fdb0902e..96cf947ee 100644 --- a/src/features/projectSettings/McpTab.tsx +++ b/src/features/projectSettings/McpTab.tsx @@ -13,6 +13,7 @@ import type { McpCodexState, McpListing, McpServerItem } from '../../../shared/p import { MCP_PROVIDERS } from '../../../shared/properties/mcpProviders'; import { moveLiteralsToSecrets } from '../../../shared/properties/mcpSecrets'; import type { MessageKey } from '../../lib/i18n/localeContext'; +import { DEFAULT_SECRETS_FILE_PARAMS } from './secretsModel'; import { useTranslate } from '../../lib/i18n/useTranslate'; import { confirmDialog } from '../../ui/ConfirmDialog'; import { ChevronDownIcon, ChevronRightIcon, CodeIcon, PlugIcon } from '../../ui/Icons'; @@ -299,7 +300,7 @@ export default function McpTab({ projectPath }: { readonly projectPath: string } {header} {failure !== undefined && (
- {translate(failure)} + {translate(failure, DEFAULT_SECRETS_FILE_PARAMS)} {stale && ( +
); } @@ -104,7 +140,7 @@ export default function SecretsTab({ projectPath }: { readonly projectPath: stri const notice = failure ?? state.refreshFailure; const show = async (index: number): Promise => { - const read = await readSecret(projectPath, listing.revision, index); + const read = await readSecret(projectPath, file, listing.revision, index); if (read.ok) { setRevealed((current) => new Map(current).set(index, read.value.value)); } else { @@ -125,7 +161,7 @@ export default function SecretsTab({ projectPath }: { readonly projectPath: stri return; } const reads = await Promise.all( - listing.entries.map(async (entry) => ({ index: entry.index, read: await readSecret(projectPath, listing.revision, entry.index) })), + listing.entries.map(async (entry) => ({ index: entry.index, read: await readSecret(projectPath, file, listing.revision, entry.index) })), ); const next = new Map(); for (const { index, read } of reads) { @@ -141,7 +177,7 @@ export default function SecretsTab({ projectPath }: { readonly projectPath: stri const commit = async (change: SecretsChange): Promise => { setBusy(true); setFailure(undefined); - const applied = await applySecretsChange(projectPath, listing.revision, change); + const applied = await applySecretsChange(projectPath, file, listing.revision, change); setBusy(false); if (applied.ok) { replace(applied.value); @@ -157,7 +193,7 @@ export default function SecretsTab({ projectPath }: { readonly projectPath: stri if (entry.multiline) { return; } - const read = await readSecret(projectPath, listing.revision, entry.index); + const read = await readSecret(projectPath, file, listing.revision, entry.index); if (!read.ok) { setDraft({ kind: 'none' }); setFailure(read.error.code); @@ -176,7 +212,7 @@ export default function SecretsTab({ projectPath }: { readonly projectPath: stri const problem = nameProblem(draft.name, listing.entries, own) ?? (draft.kind === 'edit' && draft.original === undefined ? undefined : valueProblem(draft.value)); if (problem !== undefined) { - setDraft({ ...draft, problem: describe(translate, problem) }); + setDraft({ ...draft, problem: describe(translate, problem, file) }); return; } if (draft.kind === 'add') { @@ -199,7 +235,7 @@ export default function SecretsTab({ projectPath }: { readonly projectPath: stri const remove = async (entry: SecretSummary): Promise => { const confirmed = await confirmDialog({ title: translate('settings.secrets.delete.title', { name: entry.name }), - body: translate('settings.secrets.delete.body'), + body: translate('settings.secrets.delete.body', named), confirmLabel: translate('settings.secrets.delete.confirm'), cancelLabel: translate('settings.secrets.cancel'), danger: true, @@ -211,15 +247,15 @@ export default function SecretsTab({ projectPath }: { readonly projectPath: stri const ignore = async (): Promise => { const confirmed = await confirmDialog({ - title: translate('settings.secrets.ignore.title'), - body: translate('settings.secrets.ignore.body'), + title: translate('settings.secrets.ignore.title', named), + body: translate('settings.secrets.ignore.body', named), confirmLabel: translate('settings.secrets.ignore.confirm'), cancelLabel: translate('settings.secrets.cancel'), }); if (confirmed !== true) { return; } - const result = await ignoreSecretsFile(projectPath); + const result = await ignoreSecretsFile(projectPath, file); if (result.ok) { replace(result.value); } else { @@ -228,10 +264,12 @@ export default function SecretsTab({ projectPath }: { readonly projectPath: stri }; const empty = listing.entries.length === 0 && draft.kind !== 'add'; + // `.env.development` is usually committed on purpose, for values that are not secret: its Git state is no warning. + const warnsAboutGit = secretsFileIgnorable(file); return (
- +
{listing.entries.length > 0 && (
- {listing.ignore === 'not-ignored' && ( -
- {translate('settings.secrets.ignore.warning')} -
)} - {listing.ignore === 'tracked' && ( + {warnsAboutGit && listing.ignore === 'tracked' && (
- {translate('settings.secrets.tracked.warning')} + {translate('settings.secrets.tracked.warning', named)}
)} {notice !== undefined && (
- {translate(problemKey(notice))} + {translate(problemKey(notice), named)} {(failure === undefined || failure === 'changed' || failure === 'not-found') && ( - )} + {translate(listing.exists ? 'settings.secrets.empty.body' : 'settings.secrets.empty.noFileBody', named)}
)}
{draft.kind === 'add' && ( - void submit()} onCancel={() => setDraft({ kind: 'none' })} /> + void submit()} onCancel={() => setDraft({ kind: 'none' })} /> )} {listing.entries.map((entry) => draft.kind === 'edit' && draft.index === entry.index ? ( (revealed.has(entry.index) ? hide(entry.index) : void show(entry.index))} @@ -319,12 +360,13 @@ export default function SecretsTab({ projectPath }: { readonly projectPath: stri ), )}
- {listing.invalidLines > 0 &&

{translate('settings.secrets.invalidLines', { count: listing.invalidLines })}

} + {listing.invalidLines > 0 &&

{translate('settings.secrets.invalidLines', { count: listing.invalidLines, file })}

}
); } -function SecretsHeading() { +// The title, and under it the file the tab shows: the dropdown names the file, so no sentence repeats it. +function SecretsHeading({ file, onFileChange }: { readonly file: SecretsFileName; readonly onFileChange: (file: SecretsFileName) => void }) { const translate = useTranslate(); return (
@@ -332,11 +374,27 @@ function SecretsHeading() { {translate('settings.secrets.title')} -

{translate('settings.secrets.intro')}

+
); } +// The dev env files in the order the dev server loads them, so the list itself shows which one wins. +const FILE_OPTIONS: readonly DropdownOption[] = SECRETS_FILE_NAMES.map((name) => ({ value: name, label: name })); + +function SecretsFilePicker({ file, onChange }: { readonly file: SecretsFileName; readonly onChange: (file: SecretsFileName) => void }) { + const translate = useTranslate(); + return ( + + className="secrets-file" + ariaLabel={translate('settings.secrets.file')} + value={file} + options={FILE_OPTIONS} + onChange={onChange} + /> + ); +} + // A row's shape with nothing in it: the name, the mask and the three icon buttons, in the slots a real row uses so the heights match. function SecretSkeletonRow({ widthPercent }: { readonly widthPercent: number }) { return ( @@ -357,12 +415,14 @@ function SecretSkeletonRow({ widthPercent }: { readonly widthPercent: number }) } function SecretRow({ + file, entry, shown, onToggle, onEdit, onDelete, }: { + readonly file: SecretsFileName; readonly entry: SecretSummary; readonly shown: string | undefined; readonly onToggle: () => void; @@ -371,13 +431,14 @@ function SecretRow({ }) { const translate = useTranslate(); const visible = shown !== undefined; + const named = { file }; return (
- + {entry.name} {entry.multiline ? ( - + {visible ? shown : SECRET_MASK} ) : ( @@ -415,13 +476,15 @@ function SecretRow({ - {entry.duplicate && {translate('settings.secrets.duplicate')}} - {entry.multiline && {translate('settings.secrets.multiline')}} + {entry.duplicate && {translate('settings.secrets.duplicate', named)}} + {entry.multiline && {translate('settings.secrets.multiline', named)}} + {entry.overriddenBy !== undefined && {translate('settings.secrets.overridden', { file: entry.overriddenBy })}}
); } function DraftRow({ + file, draft, busy, valueLocked = false, @@ -429,6 +492,7 @@ function DraftRow({ onSubmit, onCancel, }: { + readonly file: SecretsFileName; readonly draft: Exclude; readonly busy: boolean; readonly valueLocked?: boolean; @@ -490,26 +554,30 @@ function DraftRow({ {draft.problem} )} - {valueLocked && {translate('settings.secrets.multiline')}} + {valueLocked && {translate('settings.secrets.multiline', { file })}} ); } -function describe(translate: Translator, problem: DraftProblem): string { +function describe(translate: Translator, problem: DraftProblem, file: SecretsFileName): string { if (problem === 'nameTooLong') { - return translate(problemKey(problem), { max: ENV_LIMITS.nameCharsMax }); + return translate(problemKey(problem), { max: ENV_LIMITS.nameCharsMax, file }); } if (problem === 'valueTooLong') { - return translate(problemKey(problem), { max: VALUE_KIB_MAX }); + return translate(problemKey(problem), { max: VALUE_KIB_MAX, file }); } - return translate(problemKey(problem)); + return translate(problemKey(problem), { file }); } -// The listing: the cached one at once when this project has been read before, otherwise loading; then a +// The listing: the cached one at once when this file has been read before, otherwise loading; then a // read on mount and whenever the window regains focus (an edit outside Stacki shows then). A reply for a -// project the panel has since left is dropped. A failed read keeps a listing already shown. -function useListing(projectPath: string): { readonly state: ListingState; readonly replace: (listing: SecretsListing) => void; readonly reload: () => void } { - const [state, setState] = useState(() => initialState(projectPath)); +// project the panel has since left is dropped. A failed read keeps a listing already shown. The view is +// remounted for another file (SecretsTab's key), so `file` is fixed for the life of this hook. +function useListing( + projectPath: string, + file: SecretsFileName, +): { readonly state: ListingState; readonly replace: (listing: SecretsListing) => void; readonly reload: () => void } { + const [state, setState] = useState(() => initialState(projectPath, file)); const latest = useRef(0); const seeded = useRef(projectPath); const load = useCallback(() => { @@ -524,7 +592,7 @@ function useListing(projectPath: string): { readonly state: ListingState; readon } else if (result === undefined) { setState((current) => failedState(current, 'unreadable')); } else if (result.ok) { - secretsListingCache.set(projectPath, result.value); + secretsListingCache.set(secretsCacheKey(projectPath, file), result.value); // An unchanged revision keeps the state object, so a refocus does not redraw or hide anything. setState((current) => current.kind === 'ready' && @@ -539,12 +607,12 @@ function useListing(projectPath: string): { readonly state: ListingState; readon } }; // A rejected call is a broken boundary, not an operating failure; the panel says it could not read the file and shows no detail. - void listSecrets(projectPath).then(settle, (error: unknown) => settle(error instanceof SecretsUnavailableError ? 'unavailable' : undefined)); - }, [projectPath]); + void listSecrets(projectPath, file).then(settle, (error: unknown) => settle(error instanceof SecretsUnavailableError ? 'unavailable' : undefined)); + }, [projectPath, file]); useEffect(() => { if (seeded.current !== projectPath) { seeded.current = projectPath; - setState(initialState(projectPath)); + setState(initialState(projectPath, file)); } load(); window.addEventListener('focus', load); @@ -552,21 +620,21 @@ function useListing(projectPath: string): { readonly state: ListingState; readon latest.current += 1; window.removeEventListener('focus', load); }; - }, [load, projectPath]); + }, [load, projectPath, file]); const replace = useCallback( (listing: SecretsListing) => { latest.current += 1; - secretsListingCache.set(projectPath, listing); + secretsListingCache.set(secretsCacheKey(projectPath, file), listing); setState({ kind: 'ready', listing, refreshFailure: undefined }); }, - [projectPath], + [projectPath, file], ); return { state, replace, reload: load }; } // What the tab paints in its first frame: the names it showed last time, or the placeholder when it has none. -function initialState(projectPath: string): ListingState { - const listing = cachedSecretsListing(projectPath); +function initialState(projectPath: string, file: SecretsFileName): ListingState { + const listing = cachedSecretsListing(projectPath, file); return listing === undefined ? { kind: 'loading' } : { kind: 'ready', listing, refreshFailure: undefined }; } diff --git a/src/features/projectSettings/mcpFlows.ts b/src/features/projectSettings/mcpFlows.ts index e0b3c542b..e9fc1a85b 100644 --- a/src/features/projectSettings/mcpFlows.ts +++ b/src/features/projectSettings/mcpFlows.ts @@ -6,6 +6,7 @@ import type { Digest } from '../../../shared/core/brand'; import type { McpChange, McpListing } from '../../../shared/properties/mcp'; import type { McpServerConfig } from '../../../shared/properties/mcpConfig'; +import { SECRETS_FILE_DEFAULT } from '../../../shared/properties/secrets'; import type { MessageKey } from '../../lib/i18n/localeContext'; import { applyMcpChange } from './mcpBridge'; import { MCP_ERROR_KEYS } from './mcpModel'; @@ -23,7 +24,7 @@ export type FlowResult = /** The names in `.env`, or `undefined` when they cannot be read (a card then claims nothing about secrets). */ export async function envNamesOf(projectPath: string): Promise | undefined> { try { - const listed = await listSecrets(projectPath); + const listed = await listSecrets(projectPath, SECRETS_FILE_DEFAULT); return listed.ok ? new Set(listed.value.entries.map((entry) => entry.name)) : undefined; } catch { return undefined; @@ -35,13 +36,13 @@ export async function storeSecrets(projectPath: string, secrets: readonly Secret if (secrets.length === 0) { return undefined; } - const listed = await listSecrets(projectPath); + const listed = await listSecrets(projectPath, SECRETS_FILE_DEFAULT); if (!listed.ok) { return problemKey(listed.error.code); } let listing = listed.value; if (!listing.exists) { - const created = await applySecretsChange(projectPath, listing.revision, { kind: 'create' }); + const created = await applySecretsChange(projectPath, SECRETS_FILE_DEFAULT, listing.revision, { kind: 'create' }); if (!created.ok) { return problemKey(created.error.code); } @@ -51,7 +52,7 @@ export async function storeSecrets(projectPath: string, secrets: readonly Secret if (listing.entries.some((entry) => entry.name === secret.name)) { continue; } - const added = await applySecretsChange(projectPath, listing.revision, { kind: 'add', name: secret.name, value: secret.value }); + const added = await applySecretsChange(projectPath, SECRETS_FILE_DEFAULT, listing.revision, { kind: 'add', name: secret.name, value: secret.value }); if (!added.ok) { return problemKey(added.error.code); } diff --git a/src/features/projectSettings/projectSettings.css b/src/features/projectSettings/projectSettings.css index 9a8b6ce13..deb2b63ae 100644 --- a/src/features/projectSettings/projectSettings.css +++ b/src/features/projectSettings/projectSettings.css @@ -84,6 +84,16 @@ align-items: center; gap: 6px; } +/* A button's text stays on one line however narrow the panel: the row wraps, the label never does. */ +.secrets button { + white-space: nowrap; +} +/* Wide enough for the longest dev env file name, so the dropdown never takes the row from the buttons. */ +.secrets-heading .secrets-file { + width: 190px; + max-width: 100%; + margin-top: 6px; +} .secrets-actions .primary, .secrets-row-actions .primary { display: inline-flex; @@ -105,6 +115,12 @@ .secrets-failure { background: color-mix(in srgb, var(--red) 16%, transparent); } +/* A warning that is only its button: the button says what to do, its tooltip says why. */ +.secrets-warning-action { + justify-content: flex-start; + padding: 0; + background: none; +} .secrets-empty { display: flex; flex-direction: column; diff --git a/src/features/projectSettings/secretsBridge.ts b/src/features/projectSettings/secretsBridge.ts index 8f4745578..288ceec16 100644 --- a/src/features/projectSettings/secretsBridge.ts +++ b/src/features/projectSettings/secretsBridge.ts @@ -1,7 +1,8 @@ -// The Secrets tab's calls to main (shared/properties/secrets.ts): each payload is checked before it +// The Secrets tab's calls to main (shared/properties/secrets.ts), each for the dev env file it names: each payload is checked before it // leaves and each answer is parsed before use. The list carries names only; a value comes back from // `readSecret` alone, for a person who revealed or began editing it. import { parseIpcPayload } from '../../../shared/ipc/ipcPayloads'; +import { assert } from '../../../shared/core/assert'; import type { Digest } from '../../../shared/core/brand'; import { parseSecretValueReply, @@ -9,6 +10,7 @@ import { parseSecretsResult, type SecretValue, type SecretsChange, + type SecretsFileName, type SecretsListing, type SecretsResult, } from '../../../shared/properties/secrets'; @@ -40,22 +42,31 @@ async function call(exposed: unknown, run: () => Promise): Promise> { - const input = parseIpcPayload('secrets:list', { projectPath }); - return parseSecretsResult(await call(window.avb.listSecrets, () => window.avb.listSecrets(input)), parseSecretsListing); +export async function listSecrets(projectPath: string, file: SecretsFileName): Promise> { + const input = parseIpcPayload('secrets:list', { projectPath, file }); + const result = parseSecretsResult(await call(window.avb.listSecrets, () => window.avb.listSecrets(input)), parseSecretsListing); + assert(!result.ok || result.value.file === file, 'A secrets listing is for the file it was asked for'); + return result; } -export async function readSecret(projectPath: string, revision: Digest, index: number): Promise> { - const input = parseIpcPayload('secrets:read', { projectPath, revision, index }); +export async function readSecret(projectPath: string, file: SecretsFileName, revision: Digest, index: number): Promise> { + const input = parseIpcPayload('secrets:read', { projectPath, file, revision, index }); return parseSecretsResult(await call(window.avb.readSecret, () => window.avb.readSecret(input)), parseSecretValueReply); } -export async function applySecretsChange(projectPath: string, revision: Digest, change: SecretsChange): Promise> { - const input = parseIpcPayload('secrets:apply', { projectPath, revision, change }); - return parseSecretsResult(await call(window.avb.applySecretsChange, () => window.avb.applySecretsChange(input)), parseSecretsListing); +export async function applySecretsChange( + projectPath: string, + file: SecretsFileName, + revision: Digest, + change: SecretsChange, +): Promise> { + const input = parseIpcPayload('secrets:apply', { projectPath, file, revision, change }); + const result = parseSecretsResult(await call(window.avb.applySecretsChange, () => window.avb.applySecretsChange(input)), parseSecretsListing); + assert(!result.ok || result.value.file === file, 'A changed secrets listing is for the file that was changed'); + return result; } -export async function ignoreSecretsFile(projectPath: string): Promise> { - const input = parseIpcPayload('secrets:ignore', { projectPath }); +export async function ignoreSecretsFile(projectPath: string, file: SecretsFileName): Promise> { + const input = parseIpcPayload('secrets:ignore', { projectPath, file }); return parseSecretsResult(await call(window.avb.ignoreSecretsFile, () => window.avb.ignoreSecretsFile(input)), parseSecretsListing); } diff --git a/src/features/projectSettings/secretsCache.ts b/src/features/projectSettings/secretsCache.ts index e9087390d..7a81569fb 100644 --- a/src/features/projectSettings/secretsCache.ts +++ b/src/features/projectSettings/secretsCache.ts @@ -1,31 +1,38 @@ -// The last `.env` listing per project, kept in memory so the Secrets tab opens on the names it showed -// before and refreshes in the background (stale-while-revalidate), instead of waiting on a read. +// The last listing per project and env file, kept in memory so the Secrets tab opens on the names it +// showed before and refreshes in the background (stale-while-revalidate), instead of waiting on a read. // // A listing is names, flags and a revision digest: `SecretsListing` has no field for a value, and a value // is only ever read through `readSecret` into a component's own state. So this cache can never hold one. -// It is bounded by `createPanelCache` (the eight most recent projects) and lives for the session only. +// It is bounded by `createPanelCache` (the eight most recent entries) and lives for the session only. +import { assert } from '../../../shared/core/assert'; import type { Result } from '../../../shared/core/result'; -import type { SecretsListing } from '../../../shared/properties/secrets'; +import { SECRETS_FILE_DEFAULT, type SecretsFileName, type SecretsListing } from '../../../shared/properties/secrets'; import { createPanelCache, prewarmPanelCache } from '../../lib/usePanelData'; import { SecretsUnavailableError, listSecrets } from './secretsBridge'; export const secretsListingCache = createPanelCache(); -/** The cached listing for a project, or undefined when the tab has not read one this session. */ -export function cachedSecretsListing(projectPath: string): SecretsListing | undefined { - const entry = secretsListingCache.get(projectPath); +/** The cache key of one file in one project. A newline cannot be in either, so two pairs never share a key. */ +export function secretsCacheKey(projectPath: string, file: SecretsFileName): string { + assert(!projectPath.includes('\n'), 'secretsCacheKey: a project path holds no newline'); + return `${projectPath}\n${file}`; +} + +/** The cached listing for a file, or undefined when the tab has not read it this session. */ +export function cachedSecretsListing(projectPath: string, file: SecretsFileName): SecretsListing | undefined { + const entry = secretsListingCache.get(secretsCacheKey(projectPath, file)); return entry?.kind === 'ready' ? entry.value : undefined; } -/** Reads the listing ahead of the first open (run by the project-open prefetch). A failure leaves the tab to read and report for itself. */ +/** Reads the file the tab opens on ahead of the first open (run by the project-open prefetch). A failure leaves the tab to read and report for itself. */ export function prewarmSecretsListing(projectPath: string): Promise { - return prewarmPanelCache(secretsListingCache, projectPath, readListing(projectPath)); + return prewarmPanelCache(secretsListingCache, secretsCacheKey(projectPath, SECRETS_FILE_DEFAULT), readListing(projectPath, SECRETS_FILE_DEFAULT)); } -function readListing(projectPath: string): () => Promise> { +function readListing(projectPath: string, file: SecretsFileName): () => Promise> { return async () => { try { - const result = await listSecrets(projectPath); + const result = await listSecrets(projectPath, file); return result.ok ? { ok: true, value: result.value } : { ok: false, error: result.error.code }; } catch (error: unknown) { // An app that predates the channels is an expected state (the tab says to restart); anything else is a broken boundary and surfaces. diff --git a/src/features/projectSettings/secretsModel.ts b/src/features/projectSettings/secretsModel.ts index bbf6c86f5..38bc0363d 100644 --- a/src/features/projectSettings/secretsModel.ts +++ b/src/features/projectSettings/secretsModel.ts @@ -2,9 +2,15 @@ // message that says why not. The rules are the main process's (shared/properties/envFile.ts), checked // here first so a person sees the reason beside the field instead of after a round trip. import { ENV_LIMITS, envValueProblem, isEnvName } from '../../../shared/properties/envFile'; -import type { SecretsErrorCode, SecretSummary } from '../../../shared/properties/secrets'; +import { SECRETS_FILE_DEFAULT, type SecretsErrorCode, type SecretSummary } from '../../../shared/properties/secrets'; import type { MessageKey } from '../../lib/i18n/localeContext'; +/** + * The `{file}` a Secrets message names when it comes from the MCP tab, which stores secrets in the + * default file only. A message key from `problemKey` can name the file, so every caller fills it. + */ +export const DEFAULT_SECRETS_FILE_PARAMS = { file: SECRETS_FILE_DEFAULT } as const; + /** What a masked row shows: a fixed run of bullets, so the real length is never visible. */ export const SECRET_MASK = '••••••••'; diff --git a/test/electron/content/envSecrets.test.ts b/test/electron/content/envSecrets.test.ts index 0d02801be..3c2f90d36 100644 --- a/test/electron/content/envSecrets.test.ts +++ b/test/electron/content/envSecrets.test.ts @@ -1,4 +1,5 @@ -// Goal: the main-process half of the Secrets tab reads and writes the project's `.env` safely: a +// Goal: the main-process half of the Secrets tab reads and writes the project's dev env files +// safely, one file at a time, and marks the names a later file sets again: a // missing file is the ordinary empty state; a create makes a private empty file; every change is // written atomically against the revision it was authored on and refused with `changed` when the // file moved; the existing mode is kept; real failures are named by category; no failure text @@ -26,7 +27,7 @@ function project(): string { } async function listed(root: string) { - const result = await listSecrets(root, noGit); + const result = await listSecrets(root, '.env', noGit); assert.ok(result.ok, JSON.stringify(result)); return result.value; } @@ -43,7 +44,7 @@ test('a project with no .env is an empty list, not an error', async () => { test('create makes an empty private .env once, and leaves an existing one alone', async () => { const root = project(); const first = await listed(root); - const created = await applySecretsChange(root, first.revision, { kind: 'create' }, noGit); + const created = await applySecretsChange(root, '.env', first.revision, { kind: 'create' }, noGit); assert.ok(created.ok); assert.equal(created.value.exists, true); assert.equal(fs.readFileSync(path.join(root, '.env'), 'utf8'), ''); @@ -51,7 +52,7 @@ test('create makes an empty private .env once, and leaves an existing one alone' assert.equal(fs.statSync(path.join(root, '.env')).mode & 0o777, 0o600); } fs.writeFileSync(path.join(root, '.env'), 'A=1\n'); - const again = await applySecretsChange(root, digestOf('A=1\n'), { kind: 'create' }, noGit); + const again = await applySecretsChange(root, '.env', digestOf('A=1\n'), { kind: 'create' }, noGit); assert.ok(again.ok); assert.equal(fs.readFileSync(path.join(root, '.env'), 'utf8'), 'A=1\n'); }); @@ -59,13 +60,13 @@ test('create makes an empty private .env once, and leaves an existing one alone' test('adding to a missing file creates it private; later edits keep an existing mode', async () => { const root = project(); const file = path.join(root, '.env'); - const added = await applySecretsChange(root, digestOf(''), { kind: 'add', name: 'A', value: SECRET }, noGit); + const added = await applySecretsChange(root, '.env', digestOf(''), { kind: 'add', name: 'A', value: SECRET }, noGit); assert.ok(added.ok); assert.equal(fs.readFileSync(file, 'utf8'), `A=${SECRET}\n`); if (process.platform !== 'win32') { assert.equal(fs.statSync(file).mode & 0o777, 0o600); fs.chmodSync(file, 0o640); - const updated = await applySecretsChange(root, added.value.revision, { kind: 'update', index: 0, name: 'A', value: 'x' }, noGit); + const updated = await applySecretsChange(root, '.env', added.value.revision, { kind: 'update', index: 0, name: 'A', value: 'x' }, noGit); assert.ok(updated.ok); assert.equal(fs.statSync(file).mode & 0o777, 0o640); } @@ -77,11 +78,11 @@ test('a change authored on an old revision is refused and writes nothing', async fs.writeFileSync(file, '# top\nA=1\n'); const before = await listed(root); fs.writeFileSync(file, '# top\nA=1\nB=2\n'); - const refused = await applySecretsChange(root, before.revision, { kind: 'remove', index: 0 }, noGit); + const refused = await applySecretsChange(root, '.env', before.revision, { kind: 'remove', index: 0 }, noGit); assert.ok(!refused.ok); assert.equal(refused.error.code, 'changed'); assert.equal(fs.readFileSync(file, 'utf8'), '# top\nA=1\nB=2\n'); - const read = readSecret(root, before.revision, 0); + const read = readSecret(root, '.env', before.revision, 0); assert.ok(!read.ok); assert.equal(read.error.code, 'changed'); }); @@ -91,10 +92,10 @@ test('edits change only their line, through BOM and CRLF', async () => { const file = path.join(root, '.env'); fs.writeFileSync(file, '# c\r\nexport A = "1" # n\r\nB=2'); const listing = await listed(root); - const result = await applySecretsChange(root, listing.revision, { kind: 'update', index: 0, name: 'A', value: '9' }, noGit); + const result = await applySecretsChange(root, '.env', listing.revision, { kind: 'update', index: 0, name: 'A', value: '9' }, noGit); assert.ok(result.ok); assert.equal(fs.readFileSync(file, 'utf8'), '# c\r\nexport A = "9" # n\r\nB=2'); - const gone = await applySecretsChange(root, result.value.revision, { kind: 'remove', index: 1 }, noGit); + const gone = await applySecretsChange(root, '.env', result.value.revision, { kind: 'remove', index: 1 }, noGit); assert.ok(gone.ok); assert.equal(fs.readFileSync(file, 'utf8'), '# c\r\nexport A = "9" # n\r\n'); }); @@ -104,10 +105,10 @@ test('values come back only from readSecret', async () => { fs.writeFileSync(path.join(root, '.env'), `A=${SECRET}\n`); const listing = await listed(root); assert.ok(!JSON.stringify(listing).includes(SECRET)); - const read = readSecret(root, listing.revision, 0); + const read = readSecret(root, '.env', listing.revision, 0); assert.ok(read.ok); assert.equal(read.value.value, SECRET); - const missing = readSecret(root, listing.revision, 5); + const missing = readSecret(root, '.env', listing.revision, 5); assert.ok(!missing.ok); assert.equal(missing.error.code, 'not-found'); }); @@ -115,19 +116,19 @@ test('values come back only from readSecret', async () => { test('real read failures are named, and none of them holds a secret', async () => { const directory = project(); fs.mkdirSync(path.join(directory, '.env')); - const asDirectory = await listSecrets(directory, noGit); + const asDirectory = await listSecrets(directory, '.env', noGit); assert.ok(!asDirectory.ok); assert.equal(asDirectory.error.code, 'unreadable'); const binary = project(); fs.writeFileSync(path.join(binary, '.env'), Buffer.from([0x41, 0x3d, 0xff, 0xfe, 0x0a])); - const notText = await listSecrets(binary, noGit); + const notText = await listSecrets(binary, '.env', noGit); assert.ok(!notText.ok); assert.equal(notText.error.code, 'not-text'); const large = project(); fs.writeFileSync(path.join(large, '.env'), `# ${SECRET}${'x'.repeat(300 * 1024)}`); - const tooLarge = await listSecrets(large, noGit); + const tooLarge = await listSecrets(large, '.env', noGit); assert.ok(!tooLarge.ok); assert.equal(tooLarge.error.code, 'too-large'); assert.ok(!tooLarge.error.message.includes(SECRET)); @@ -135,7 +136,7 @@ test('real read failures are named, and none of them holds a secret', async () = if (process.platform !== 'win32' && process.getuid?.() !== 0) { const locked = project(); fs.writeFileSync(path.join(locked, '.env'), `A=${SECRET}\n`, { mode: 0o000 }); - const denied = await listSecrets(locked, noGit); + const denied = await listSecrets(locked, '.env', noGit); assert.ok(!denied.ok); assert.equal(denied.error.code, 'denied'); assert.ok(!denied.error.message.includes(SECRET)); @@ -147,11 +148,11 @@ test('invalid changes come back as codes without touching the file', async () => const file = path.join(root, '.env'); fs.writeFileSync(file, 'A=1\n'); const revision = digestOf('A=1\n'); - const taken = await applySecretsChange(root, revision, { kind: 'add', name: 'A', value: SECRET }, noGit); + const taken = await applySecretsChange(root, '.env', revision, { kind: 'add', name: 'A', value: SECRET }, noGit); assert.ok(!taken.ok); assert.equal(taken.error.code, 'name-taken'); assert.ok(!taken.error.message.includes(SECRET)); - const gone = await applySecretsChange(root, revision, { kind: 'remove', index: 4 }, noGit); + const gone = await applySecretsChange(root, '.env', revision, { kind: 'remove', index: 4 }, noGit); assert.ok(!gone.ok); assert.equal(gone.error.code, 'not-found'); assert.equal(fs.readFileSync(file, 'utf8'), 'A=1\n'); @@ -160,13 +161,78 @@ test('invalid changes come back as codes without touching the file', async () => test('ignore state is reported and .env is appended to .gitignore without rewriting it', async () => { const root = project(); fs.writeFileSync(path.join(root, '.gitignore'), 'node_modules\n# mine'); - const listing = await listSecrets(root, notIgnored); + const listing = await listSecrets(root, '.env', notIgnored); assert.ok(listing.ok); assert.equal(listing.value.ignore, 'not-ignored'); - const result = await ignoreEnvFile(root, notIgnored); + const result = await ignoreEnvFile(root, '.env', notIgnored); assert.ok(result.ok); assert.equal(fs.readFileSync(path.join(root, '.gitignore'), 'utf8'), 'node_modules\n# mine\n.env\n'); - const tracked = await listSecrets(root, async () => undefined); + const tracked = await listSecrets(root, '.env', async () => undefined); assert.ok(tracked.ok); assert.equal(tracked.value.ignore, 'tracked'); }); + +test('each dev env file is listed and changed on its own, and the others are left as they were', async () => { + const root = project(); + fs.writeFileSync(path.join(root, '.env'), 'A=1\n'); + const local = await listSecrets(root, '.env.local', noGit); + assert.ok(local.ok); + assert.equal(local.value.file, '.env.local'); + assert.equal(local.value.exists, false); + const added = await applySecretsChange(root, '.env.local', local.value.revision, { kind: 'add', name: 'B', value: SECRET }, noGit); + assert.ok(added.ok); + assert.equal(fs.readFileSync(path.join(root, '.env.local'), 'utf8'), `B=${SECRET}\n`); + assert.equal(fs.readFileSync(path.join(root, '.env'), 'utf8'), 'A=1\n'); + if (process.platform !== 'win32') { + assert.equal(fs.statSync(path.join(root, '.env.local')).mode & 0o777, 0o600); + } + const read = readSecret(root, '.env.local', added.value.revision, 0); + assert.ok(read.ok); + assert.equal(read.value.value, SECRET); + // A revision names one file's bytes: the other file's revision is refused. + const crossed = readSecret(root, '.env', added.value.revision, 0); + assert.ok(!crossed.ok); + assert.equal(crossed.error.code, 'changed'); +}); + +test('a name a later file sets again is marked with the last such file, from names alone', async () => { + const root = project(); + fs.writeFileSync(path.join(root, '.env'), 'A=1\nB=2\nC=3\n'); + fs.writeFileSync(path.join(root, '.env.local'), `A=${SECRET}\n`); + fs.writeFileSync(path.join(root, '.env.development'), 'A=dev\nB=dev\n'); + const base = await listed(root); + assert.deepEqual( + base.entries.map((entry) => [entry.name, entry.overriddenBy]), + [ + ['A', '.env.development'], + ['B', '.env.development'], + ['C', undefined], + ], + ); + assert.ok(!JSON.stringify(base).includes(SECRET)); + // The last file in load order overrides nothing, and an earlier file never overrides a later one. + const local = await listSecrets(root, '.env.local', noGit); + assert.ok(local.ok); + assert.equal(local.value.entries[0]?.overriddenBy, '.env.development'); + const last = await listSecrets(root, '.env.development', noGit); + assert.ok(last.ok); + assert.ok(last.value.entries.every((entry) => entry.overriddenBy === undefined)); + // A later file that cannot be read adds no note and does not fail the listing. + fs.rmSync(path.join(root, '.env.development')); + fs.mkdirSync(path.join(root, '.env.development')); + const unreadableLater = await listed(root); + assert.equal(unreadableLater.entries[0]?.overriddenBy, '.env.local'); + assert.equal(unreadableLater.entries[1]?.overriddenBy, undefined); +}); + +test('the ignore rule names the file it is asked for', async () => { + const root = project(); + fs.writeFileSync(path.join(root, '.gitignore'), '.env\n'); + const result = await ignoreEnvFile(root, '.env.local', notIgnored); + assert.ok(result.ok); + assert.equal(result.value.file, '.env.local'); + assert.equal(fs.readFileSync(path.join(root, '.gitignore'), 'utf8'), '.env\n.env.local\n'); + const again = await ignoreEnvFile(root, '.env.local', notIgnored); + assert.ok(again.ok); + assert.equal(fs.readFileSync(path.join(root, '.gitignore'), 'utf8'), '.env\n.env.local\n'); +}); diff --git a/test/electron/content/pageTemplate.test.js b/test/electron/content/pageTemplate.test.js index cdb45dd2f..54278a7b9 100644 --- a/test/electron/content/pageTemplate.test.js +++ b/test/electron/content/pageTemplate.test.js @@ -662,10 +662,15 @@ test('env text is read and changed one line at a time', () => { assert.equal(withEnvValue('', 'A', 'q"\\'), 'A="q\\"\\\\"\n'); assert.equal(envEntries(withEnvValue('', 'A', 'q"\\ #x'))[0][1], 'q"\\ #x', 'a value reads back as written'); assert.throws(() => withEnvValue('', 'A', 'two\nlines'), /one line/); - assert.equal(gitignoreWithEnv('.env\n'), undefined); - assert.equal(gitignoreWithEnv('dist\n.env*\n'), undefined); - assert.equal(gitignoreWithEnv('dist'), 'dist\n.env\n'); - assert.equal(gitignoreWithEnv(undefined), '.env\n'); + assert.equal(gitignoreWithEnv('.env\n', '.env'), undefined); + assert.equal(gitignoreWithEnv('dist\n.env*\n', '.env'), undefined); + assert.equal(gitignoreWithEnv('*.env\n', '.env'), undefined); + assert.equal(gitignoreWithEnv('dist', '.env'), 'dist\n.env\n'); + assert.equal(gitignoreWithEnv(undefined, '.env'), '.env\n'); + // Another dev env file gets its own rule: `.env` and `*.env` do not cover it, `.env*` does. + assert.equal(gitignoreWithEnv('.env\n*.env\n', '.env.local'), '.env\n*.env\n.env.local\n'); + assert.equal(gitignoreWithEnv('/.env.local\n', '.env.local'), undefined); + assert.equal(gitignoreWithEnv('.env*\n', '.env.development.local'), undefined); }); const gitRun = (root, args) => execFileSync('git', args, { cwd: root, stdio: 'pipe' }); diff --git a/test/renderer/projectSettings/mcpPanel.test.js b/test/renderer/projectSettings/mcpPanel.test.js index a67e5df1b..345afd9d8 100644 --- a/test/renderer/projectSettings/mcpPanel.test.js +++ b/test/renderer/projectSettings/mcpPanel.test.js @@ -108,7 +108,15 @@ function configOf(text, name) { function envListing() { const parsed = panel.parseEnvFile(envText ?? ''); const entries = panel.envEntries(parsed.value).map(({ index, name, duplicate, multiline }) => ({ index, name, duplicate, multiline })); - return { revision: digest(envText), exists: envText !== undefined, entries, invalidLines: panel.envInvalidLines(parsed.value), ignore: 'ignored' }; + // The MCP tab stores secrets in `.env` only, so main answers for that file. + return { + file: '.env', + revision: digest(envText), + exists: envText !== undefined, + entries, + invalidLines: panel.envInvalidLines(parsed.value), + ignore: 'ignored', + }; } function codexState() { if (codexText === undefined) { diff --git a/test/renderer/projectSettings/secretsPanel.test.js b/test/renderer/projectSettings/secretsPanel.test.js index 6dbfee019..4bb0efef1 100644 --- a/test/renderer/projectSettings/secretsPanel.test.js +++ b/test/renderer/projectSettings/secretsPanel.test.js @@ -1,7 +1,10 @@ -// Goal: the Settings panel's Secrets tab shows the project's `.env` with every value hidden (the real +// Goal: the Settings panel's Secrets tab shows one of the project's dev env files, `.env` first, picked in +// a dropdown that lists the four in load order; every message names the picked file, a name a later file +// sets again says which file dev uses, nothing revealed for one file survives a switch, and `.env.development` +// (usually committed on purpose) gets no Git warning. For the picked file it shows every value hidden (the real // text is in no DOM node until it is revealed), reveals and hides one or all, edits a name and a value // inline (Enter saves, Escape cancels), deletes behind the app's own confirm, adds with validation -// messages, treats a missing `.env` as the normal empty state with a Create button, warns when `.env` +// messages, treats a missing `.env` as the normal empty state where adding a secret creates it, warns when `.env` // is not ignored, refuses a save over an outside change, names real read failures, and tells the person // to restart when the running app lacks the channels. It never shows a plain-text loading line: a first load // paints placeholder rows in the real layout, a reopened tab paints its cached names in its first render and @@ -25,7 +28,7 @@ esbuild.buildSync({ contents: [ "export { default as ProjectSettingsPanel } from './src/features/projectSettings/ProjectSettingsPanel';", "export { default as SecretsTab } from './src/features/projectSettings/SecretsTab';", - "export { secretsListingCache, prewarmSecretsListing } from './src/features/projectSettings/secretsCache';", + "export { secretsCacheKey, secretsListingCache, prewarmSecretsListing } from './src/features/projectSettings/secretsCache';", "export { ConfirmHost } from './src/ui/ConfirmDialog';", "export { changeEnvFile, parseEnvFile, serializeEnvFile, envEntries, envInvalidLines } from './shared/properties/envFile';", ].join('\n'), @@ -44,6 +47,8 @@ esbuild.buildSync({ const dom = new JSDOM('
', { url: 'http://localhost/', pretendToBeVisual: true }); require('../../helpers/popupDom').installPopupDOM(dom.window); +// The DOM here has no layout, so it has no `scrollIntoView`; the file dropdown scrolls its highlighted row into view. +dom.window.HTMLElement.prototype.scrollIntoView ??= () => undefined; global.window = dom.window; for (const name of ['document', 'navigator', 'HTMLElement', 'Element', 'Node', 'Event', 'KeyboardEvent', 'MouseEvent', 'getComputedStyle']) { Object.defineProperty(global, name, { value: dom.window[name], configurable: true, writable: true }); @@ -57,52 +62,72 @@ const React = require('react'); const { act } = React; const { createRoot } = require('react-dom/client'); -// The project as main would answer for it. +// The project as main would answer for it: `.env` in `text`, the other dev env files in `others`. +const FILES = ['.env', '.env.local', '.env.development', '.env.development.local']; let text; // undefined: no .env +let others; // file name → text, for the files after .env let ignore; let applied; let ignored; +let asked; // the file each list call named const digest = (value) => crypto .createHash('sha256') .update(value ?? '') .digest('hex'); const failure = (code) => ({ ok: false, error: { code, message: 'm' } }); -function listing() { - const parsed = panel.parseEnvFile(text ?? ''); - const entries = panel.envEntries(parsed.value).map(({ index, name, duplicate, multiline }) => ({ index, name, duplicate, multiline })); - return { revision: digest(text), exists: text !== undefined, entries, invalidLines: panel.envInvalidLines(parsed.value), ignore }; +const textOf = (file) => (file === '.env' ? text : others.get(file)); +const setText = (file, value) => (file === '.env' ? (text = value) : others.set(file, value)); +const namesOf = (source) => panel.envEntries(panel.parseEnvFile(source ?? '').value).map((entry) => entry.name); +function listing(file = '.env') { + const parsed = panel.parseEnvFile(textOf(file) ?? ''); + // As main does: a name a later file sets again is marked with the last such file. + const later = FILES.slice(FILES.indexOf(file) + 1); + const overrides = new Map(); + for (const candidate of later) { + for (const name of namesOf(textOf(candidate))) { + overrides.set(name, candidate); + } + } + const entries = panel.envEntries(parsed.value).map(({ index, name, duplicate, multiline }) => { + const overriddenBy = overrides.get(name); + return overriddenBy === undefined ? { index, name, duplicate, multiline } : { index, name, duplicate, multiline, overriddenBy }; + }); + return { file, revision: digest(textOf(file)), exists: textOf(file) !== undefined, entries, invalidLines: panel.envInvalidLines(parsed.value), ignore }; } function installMain() { window.avb = { - listSecrets: async () => ({ ok: true, value: listing() }), - readSecret: async ({ revision, index }) => { - if (revision !== digest(text)) { + listSecrets: async ({ file }) => { + asked.push(file); + return { ok: true, value: listing(file) }; + }, + readSecret: async ({ file, revision, index }) => { + if (revision !== digest(textOf(file))) { return failure('changed'); } - const entry = panel.envEntries(panel.parseEnvFile(text ?? '').value)[index]; + const entry = panel.envEntries(panel.parseEnvFile(textOf(file) ?? '').value)[index]; return entry === undefined ? failure('not-found') : { ok: true, value: { value: entry.value } }; }, - applySecretsChange: async ({ revision, change }) => { - if (revision !== digest(text)) { + applySecretsChange: async ({ file, revision, change }) => { + if (revision !== digest(textOf(file))) { return failure('changed'); } - applied.push(change); + applied.push(file === '.env' ? change : { file, ...change }); if (change.kind === 'create') { - text ??= ''; - return { ok: true, value: listing() }; + setText(file, textOf(file) ?? ''); + return { ok: true, value: listing(file) }; } - const next = panel.changeEnvFile(panel.parseEnvFile(text ?? '').value, change); + const next = panel.changeEnvFile(panel.parseEnvFile(textOf(file) ?? '').value, change); if (!next.ok) { return failure(next.error); } - text = panel.serializeEnvFile(next.value); - return { ok: true, value: listing() }; + setText(file, panel.serializeEnvFile(next.value)); + return { ok: true, value: listing(file) }; }, - ignoreSecretsFile: async () => { - ignored.push(true); + ignoreSecretsFile: async ({ file }) => { + ignored.push(file === '.env' ? true : file); ignore = 'ignored'; - return { ok: true, value: listing() }; + return { ok: true, value: listing(file) }; }, }; } @@ -146,11 +171,15 @@ async function unmount() { } function reset(initial, ignoreState = 'ignored') { text = initial; + others = new Map(); ignore = ignoreState; applied = []; ignored = []; + asked = []; installMain(); } +// The cache key of a project's `.env`, the file the tab opens on. +const envKey = (projectPath) => panel.secretsCacheKey(projectPath, '.env'); test('hidden values are in no DOM node; the eye reveals and hides one, and Reveal all hides again', async () => { reset(`API_KEY=${SECRET}\nOTHER=${OTHER}\n`); @@ -254,38 +283,50 @@ test('adding: validation messages, then the new line is appended', async () => { await unmount(); }); -test('no .env is the empty state with a Create button, not an error', async () => { +test('no .env is the empty state, not an error, and Add secret is the one way in', async () => { reset(undefined); await mount(); assert.match(document.body.textContent, /No secrets yet/); - assert.match(document.body.textContent, /No \.env file yet/); + assert.match(document.body.textContent, /No \.env file yet\. Adding a secret creates it\./); assert.ok(!document.body.textContent.includes('could not be read')); - await click(button('Create .env file')); - assert.equal(text, ''); - assert.deepEqual(applied, [{ kind: 'create' }]); - assert.equal(button('Create .env file') ?? undefined, undefined, 'the button goes once the file exists'); - assert.match(document.body.textContent, /Adding a secret creates \.env/); - assert.ok(button('Add secret')); + assert.ok(![...document.querySelectorAll('button')].some((candidate) => /^Create/.test(candidate.textContent.trim())), 'no button offers an empty file'); + await click(button('Add secret')); + await type(byLabel('Name'), 'A'); + await type(byLabel('Value'), 'x'); + await click(button('Save')); + assert.equal(text, 'A=x\n'); + assert.deepEqual(applied, [{ kind: 'add', name: 'A', value: 'x' }]); await unmount(); }); -test('a created file offers the .gitignore flow when it is not ignored', async () => { - reset(undefined, 'not-ignored'); +test('an existing empty .env says it is empty', async () => { + reset(''); await mount(); - await click(button('Create .env file')); - assert.match(document.body.textContent, /\.env is not in \.gitignore: secrets could be committed/); - await click(button('Add to .gitignore')); + assert.match(document.body.textContent, /\.env is empty\./); + assert.ok(!document.body.textContent.includes('creates'), 'an existing file is never said to be created'); + await unmount(); +}); + +test('an existing file offers the .gitignore flow when it is not ignored', async () => { + reset('', 'not-ignored'); + await mount(); + // The button alone is shown; the risk is its tooltip and its description, never a sentence beside it. + const offer = button('Add to .gitignore'); + assert.equal(offer.title, '.env is not in .gitignore: secrets could be committed'); + assert.equal(offer.getAttribute('aria-description'), offer.title); + assert.ok(!document.body.textContent.includes('secrets could be committed')); + await click(offer); assert.match(document.body.textContent, /Add \.env to \.gitignore\?/); await click(button('Add line')); assert.deepEqual(ignored, [true]); - assert.ok(!document.body.textContent.includes('secrets could be committed')); + assert.equal(button('Add to .gitignore') ?? undefined, undefined); await unmount(); }); test('a tracked .env gets a warning with no button', async () => { reset('A=1\n', 'tracked'); await mount(); - assert.match(document.body.textContent, /tracked by Git/); + assert.match(document.body.textContent, /\.env is committed to Git/); assert.equal(button('Add to .gitignore') ?? undefined, undefined); await unmount(); }); @@ -450,7 +491,7 @@ test('the cache holds names only: a revealed or edited value is never in it', as await click(byLabel('Reveal API_KEY')); await click(byLabel('Edit OTHER')); assert.ok(document.body.innerHTML.includes(SECRET)); - const cached = panel.secretsListingCache.get('/names-only'); + const cached = panel.secretsListingCache.get(envKey('/names-only')); assert.equal(cached.kind, 'ready'); const serialized = JSON.stringify(cached); assert.ok(!serialized.includes(SECRET) && !serialized.includes(OTHER), 'no value in the cache'); @@ -467,20 +508,101 @@ test('the cache is bounded to the most recent projects', async () => { await mount(`/bound-${project}`); await unmount(); } - assert.equal(panel.secretsListingCache.get('/bound-0') ?? undefined, undefined, 'the oldest is dropped'); - assert.equal(panel.secretsListingCache.get('/bound-3') ?? undefined, undefined); - assert.equal(panel.secretsListingCache.get('/bound-11').kind, 'ready', 'the newest is kept'); - assert.equal(panel.secretsListingCache.get('/bound-4').kind, 'ready', 'the eighth most recent is kept'); + assert.equal(panel.secretsListingCache.get(envKey('/bound-0')) ?? undefined, undefined, 'the oldest is dropped'); + assert.equal(panel.secretsListingCache.get(envKey('/bound-3')) ?? undefined, undefined); + assert.equal(panel.secretsListingCache.get(envKey('/bound-11')).kind, 'ready', 'the newest is kept'); + assert.equal(panel.secretsListingCache.get(envKey('/bound-4')).kind, 'ready', 'the eighth most recent is kept'); }); test('a prefetch fills the cache so the first open has no placeholder; an app without the channels fills nothing', async () => { reset('A=1\n'); await panel.prewarmSecretsListing('/prefetched'); - assert.equal(panel.secretsListingCache.get('/prefetched').kind, 'ready'); + assert.equal(panel.secretsListingCache.get(envKey('/prefetched')).kind, 'ready'); + assert.deepEqual(asked, ['.env'], 'the prefetch reads the file the tab opens on, and only that one'); delete window.avb.listSecrets; await panel.prewarmSecretsListing('/no-channels'); - assert.equal(panel.secretsListingCache.get('/no-channels') ?? undefined, undefined); + assert.equal(panel.secretsListingCache.get(envKey('/no-channels')) ?? undefined, undefined); window.avb.listSecrets = async () => failure('denied'); await panel.prewarmSecretsListing('/denied'); - assert.equal(panel.secretsListingCache.get('/denied') ?? undefined, undefined, 'a failure is never cached as an empty list'); + assert.equal(panel.secretsListingCache.get(envKey('/denied')) ?? undefined, undefined, 'a failure is never cached as an empty list'); +}); + +// The labels of the open dropdown's options, in the order they are listed. +const optionLabels = () => [...document.querySelectorAll('.dd-option .dd-option-label')].map((label) => label.textContent.trim()); + +// Picks a file in the tab's dropdown, as a person would: open the menu, click the option. +async function pick(file) { + await click(byLabel('Env file')); + const option = [...document.querySelectorAll('.dd-option')].find((candidate) => candidate.querySelector('.dd-option-label')?.textContent.trim() === file); + await click(option); +} + +test('the dropdown lists the four dev files in load order, and opens on .env', async () => { + reset('A=1\n'); + await mount('/files'); + assert.equal(byLabel('Env file').textContent.trim(), '.env'); + await click(byLabel('Env file')); + assert.deepEqual(optionLabels(), FILES); + await click(byLabel('Env file')); + await unmount(); +}); + +test('another file is listed, created and changed on its own, and every message names it', async () => { + reset('A=1\n'); + await mount('/other-file'); + await pick('.env.local'); + assert.equal(asked.at(-1), '.env.local'); + assert.equal(byLabel('Env file').textContent.trim(), '.env.local'); + assert.match(document.body.textContent, /No \.env\.local file yet/); + await click(button('Add secret')); + await type(byLabel('Name'), 'B'); + await type(byLabel('Value'), SECRET); + await click(button('Save')); + assert.equal(others.get('.env.local'), `B=${SECRET}\n`); + assert.equal(text, 'A=1\n', '.env is left as it was'); + assert.deepEqual(applied, [{ file: '.env.local', kind: 'add', name: 'B', value: SECRET }]); + await click(byLabel('Delete B')); + assert.match(document.body.textContent, /Removes the line from \.env\.local/); + await click(button('Cancel')); + await unmount(); +}); + +test('a value revealed in one file is gone when another file is picked', async () => { + reset(`API_KEY=${SECRET}\n`); + await mount('/switch'); + await click(byLabel('Reveal API_KEY')); + assert.ok(document.body.innerHTML.includes(SECRET)); + await pick('.env.local'); + assert.ok(!document.body.innerHTML.includes(SECRET), 'nothing revealed for .env is shown beside .env.local'); + await pick('.env'); + assert.ok(!document.body.innerHTML.includes(SECRET), 'coming back starts hidden'); + await unmount(); +}); + +test('a name a later file sets again says which file dev uses', async () => { + reset('A=1\nB=2\n'); + others.set('.env.local', 'A=local\n'); + others.set('.env.development', 'A=dev\n'); + await mount('/overridden'); + const rows = rowText(); + assert.match(rows[0], /Dev uses the value in \.env\.development/); + assert.ok(!rows[1].includes('Dev uses'), 'a name set only here has no note'); + assert.ok(!document.body.textContent.includes('local'), 'only the last overriding file is named'); + await unmount(); +}); + +test('.env.development is not offered for .gitignore, and its Git state is no warning', async () => { + reset('A=1\n', 'not-ignored'); + others.set('.env.development', 'PUBLIC_URL=x\n'); + await mount('/development'); + assert.ok(button('Add to .gitignore'), '.env still warns'); + await pick('.env.development'); + assert.equal(button('Add to .gitignore') ?? undefined, undefined); + ignore = 'tracked'; + await pick('.env.local'); + await pick('.env.development'); + assert.ok(!document.body.textContent.includes('committed to Git')); + await pick('.env.local'); + assert.match(document.body.textContent, /\.env\.local is committed to Git/); + await unmount(); }); diff --git a/test/shared/ipc/ipcPayloads.test.ts b/test/shared/ipc/ipcPayloads.test.ts index c58be06a2..1b66fb721 100644 --- a/test/shared/ipc/ipcPayloads.test.ts +++ b/test/shared/ipc/ipcPayloads.test.ts @@ -247,10 +247,10 @@ const metadataSamples: Readonly> = { 'emdash:install': { projectPath: '/site', confirmedCommand: 'npm install emdash' }, 'emdash:installCancel': { projectPath: '/site' }, 'emdash:adminUrl': { projectPath: '/site' }, - 'secrets:list': { projectPath: '/site' }, - 'secrets:read': { projectPath: '/site', revision: 'a'.repeat(64), index: 0 }, - 'secrets:apply': { projectPath: '/site', revision: 'a'.repeat(64), change: { kind: 'remove', index: 0 } }, - 'secrets:ignore': { projectPath: '/site' }, + 'secrets:list': { projectPath: '/site', file: '.env' }, + 'secrets:read': { projectPath: '/site', file: '.env', revision: 'a'.repeat(64), index: 0 }, + 'secrets:apply': { projectPath: '/site', file: '.env.local', revision: 'a'.repeat(64), change: { kind: 'remove', index: 0 } }, + 'secrets:ignore': { projectPath: '/site', file: '.env' }, 'mcp:read': { projectPath: '/site' }, 'mcp:readText': { projectPath: '/site' }, 'mcp:reveal': { projectPath: '/site', revision: 'a'.repeat(64), name: 'Sanity' }, diff --git a/test/shared/properties/secrets.test.ts b/test/shared/properties/secrets.test.ts index 41aa7475b..8d40c4f48 100644 --- a/test/shared/properties/secrets.test.ts +++ b/test/shared/properties/secrets.test.ts @@ -6,10 +6,26 @@ import assert from 'node:assert/strict'; import { test } from 'node:test'; import { ENV_LIMITS } from '#dist/shared/properties/envFile.js'; import { parseIpcPayload } from '#dist/shared/ipc/ipcPayloads.js'; -import { parseSecretValueReply, parseSecretsChange, parseSecretsListing, parseSecretsResult } from '#dist/shared/properties/secrets.js'; +import { + SECRETS_FILE_NAMES, + parseSecretValueReply, + parseSecretsChange, + parseSecretsFileName, + parseSecretsListing, + parseSecretsResult, + secretsFileIgnorable, + secretsFileLoadsAfter, +} from '#dist/shared/properties/secrets.js'; const revision = 'a'.repeat(64); -const listing = { revision, exists: true, entries: [{ index: 0, name: 'A', duplicate: false, multiline: false }], invalidLines: 0, ignore: 'ignored' }; +const listing = { + file: '.env', + revision, + exists: true, + entries: [{ index: 0, name: 'A', duplicate: false, multiline: false }], + invalidLines: 0, + ignore: 'ignored', +}; test('changes: known-good shapes parse', () => { assert.deepEqual(parseSecretsChange({ kind: 'add', name: 'A_1', value: '' }), { kind: 'add', name: 'A_1', value: '' }); @@ -69,13 +85,51 @@ test('listing, value and result parsers', () => { assert.throws(() => parseSecretsResult({ ok: 'maybe' }, parseSecretValueReply)); }); -test('channels: payloads for list, read, apply and ignore', () => { - assert.deepEqual(parseIpcPayload('secrets:list', { projectPath: '/site' }), { projectPath: '/site' }); - assert.equal(parseIpcPayload('secrets:read', { projectPath: '/site', revision, index: 0 }).index, 0); - assert.equal(parseIpcPayload('secrets:apply', { projectPath: '/site', revision, change: { kind: 'remove', index: 0 } }).change.kind, 'remove'); - assert.deepEqual(parseIpcPayload('secrets:ignore', { projectPath: '/site' }), { projectPath: '/site' }); - assert.throws(() => parseIpcPayload('secrets:read', { projectPath: '/site', revision: 'short', index: 0 })); - assert.throws(() => parseIpcPayload('secrets:read', { projectPath: '/site', revision, index: -1 })); - assert.throws(() => parseIpcPayload('secrets:apply', { projectPath: '/site', revision, change: { kind: 'add', name: '', value: '' } })); +test('files: the four dev files in load order, and nothing else', () => { + assert.deepEqual(SECRETS_FILE_NAMES, ['.env', '.env.local', '.env.development', '.env.development.local']); + for (const file of SECRETS_FILE_NAMES) { + assert.equal(parseSecretsFileName(file), file); + } + for (const bad of ['.env.production', '.env.test', '../.env', '/etc/passwd', 'env', '', '.ENV', undefined, 3]) { + assert.throws(() => parseSecretsFileName(bad), /expected a dev env file name/); + } + assert.equal(secretsFileLoadsAfter('.env.local', '.env'), true); + assert.equal(secretsFileLoadsAfter('.env.development.local', '.env.development'), true); + assert.equal(secretsFileLoadsAfter('.env', '.env.local'), false); + assert.equal(secretsFileLoadsAfter('.env', '.env'), false); + assert.deepEqual( + SECRETS_FILE_NAMES.filter((file) => !secretsFileIgnorable(file)), + ['.env.development'], + ); +}); + +test('listing: a row is overridden only by a file that loads after the listed one', () => { + const entry = { index: 0, name: 'A', duplicate: false, multiline: false }; + const overridden = parseSecretsListing({ ...listing, entries: [{ ...entry, overriddenBy: '.env.local' }] }); + assert.equal(overridden.entries[0]?.overriddenBy, '.env.local'); + assert.equal('overriddenBy' in (parseSecretsListing(listing).entries[0] ?? {}), false); + assert.throws(() => parseSecretsListing({ ...listing, file: '.env.production' })); + assert.throws(() => parseSecretsListing({ ...listing, file: undefined })); + assert.throws(() => parseSecretsListing({ ...listing, entries: [{ ...entry, overriddenBy: '.env.production' }] })); + assert.throws( + () => parseSecretsListing({ ...listing, file: '.env.local', entries: [{ ...entry, overriddenBy: '.env' }] }), + /overridden only by a file that loads after its own/, + ); + assert.throws(() => parseSecretsListing({ ...listing, entries: [{ ...entry, overriddenBy: '.env' }] }), /overridden only by a file that loads after its own/); +}); + +test('channels: payloads for list, read, apply and ignore name the file', () => { + const site = { projectPath: '/site', file: '.env.local' }; + assert.deepEqual(parseIpcPayload('secrets:list', site), site); + assert.equal(parseIpcPayload('secrets:read', { ...site, revision, index: 0 }).index, 0); + assert.equal(parseIpcPayload('secrets:apply', { ...site, revision, change: { kind: 'remove', index: 0 } }).change.kind, 'remove'); + assert.deepEqual(parseIpcPayload('secrets:ignore', site), site); + assert.throws(() => parseIpcPayload('secrets:read', { ...site, revision: 'short', index: 0 })); + assert.throws(() => parseIpcPayload('secrets:read', { ...site, revision, index: -1 })); + assert.throws(() => parseIpcPayload('secrets:apply', { ...site, revision, change: { kind: 'add', name: '', value: '' } })); assert.throws(() => parseIpcPayload('secrets:list', {})); + assert.throws(() => parseIpcPayload('secrets:list', { projectPath: '/site' })); + assert.throws(() => parseIpcPayload('secrets:list', { projectPath: '/site', file: '../.env' })); + assert.throws(() => parseIpcPayload('secrets:apply', { projectPath: '/site', file: '.env.production', revision, change: { kind: 'create' } })); + assert.throws(() => parseIpcPayload('secrets:ignore', { projectPath: '/site', file: '.env.development' }), /not offered for .gitignore/); }); From 82e7adf465b26c6c045b44eed0432cafe7e8bda9 Mon Sep 17 00:00:00 2001 From: SylvainDruaux Date: Tue, 17 Nov 2026 13:24:04 +0100 Subject: [PATCH 2/2] fix(settings): the .gitignore offer shows Stacki's own tooltip The "Add to .gitignore" button carries its reason only in its tooltip, and that tooltip was the system's: it waited about a second and a half and, on macOS, did not show again on a second hover. The button now uses the app's delayed tip, as the info mark beside the title does, so the reason shows after the shared wait on every hover. Screen readers still read it as the button's description. --- src/features/projectSettings/SecretsTab.tsx | 43 +++++++++++++++---- .../projectSettings/secretsPanel.test.js | 15 ++++++- 2 files changed, 48 insertions(+), 10 deletions(-) diff --git a/src/features/projectSettings/SecretsTab.tsx b/src/features/projectSettings/SecretsTab.tsx index 7c25d6c4b..c63ad01cb 100644 --- a/src/features/projectSettings/SecretsTab.tsx +++ b/src/features/projectSettings/SecretsTab.tsx @@ -10,6 +10,7 @@ // nothing cached it paints placeholder rows, never a word. Choosing another file remounts the file's view, // so nothing revealed or typed for one file is ever shown beside another's names. import { useCallback, useEffect, useRef, useState, type KeyboardEvent } from 'react'; +import { createPortal } from 'react-dom'; import { ENV_LIMITS } from '../../../shared/properties/envFile'; import { SECRETS_FILE_DEFAULT, @@ -26,6 +27,7 @@ import type { Translator } from '../../lib/i18n/localeContext'; import { useTranslate } from '../../lib/i18n/useTranslate'; import { confirmDialog } from '../../ui/ConfirmDialog'; import Dropdown, { type DropdownOption } from '../../ui/Dropdown'; +import { tooltipHost, useDelayedTooltip } from '../../ui/delayedTooltip'; import { HideIcon, LockIcon, PencilIcon, PlusIcon, PreviewIcon, TrashIcon } from '../../ui/Icons'; import { Skeleton, SkeletonRows } from '../../ui/Skeleton'; import InfoHint from '../../ui/InfoHint'; @@ -290,14 +292,7 @@ function SecretsFileView({ {warnsAboutGit && listing.ignore === 'not-ignored' && ( // The button alone, so no sentence wraps beside it; the risk it removes is its tooltip and its description.
- + void ignore()} />
)} {warnsAboutGit && listing.ignore === 'tracked' && ( @@ -379,6 +374,38 @@ function SecretsHeading({ file, onFileChange }: { readonly file: SecretsFileName ); } +// "Add to .gitignore", whose reason is only its tip: Stacki's own tip (the app's dark one, after the shared +// wait, on every hover), not the system's, which waits longer and may not show again on a second hover. +function GitignoreButton({ why, onClick }: { readonly why: string; readonly onClick: () => void }) { + const translate = useTranslate(); + const tooltip = useDelayedTooltip(); + const button = useRef(null); + return ( + <> + + {tooltip.value !== undefined && + createPortal( +
+ {why} +
, + tooltipHost(button.current ?? undefined), + )} + + ); +} + // The dev env files in the order the dev server loads them, so the list itself shows which one wins. const FILE_OPTIONS: readonly DropdownOption[] = SECRETS_FILE_NAMES.map((name) => ({ value: name, label: name })); diff --git a/test/renderer/projectSettings/secretsPanel.test.js b/test/renderer/projectSettings/secretsPanel.test.js index 4bb0efef1..65681b6dd 100644 --- a/test/renderer/projectSettings/secretsPanel.test.js +++ b/test/renderer/projectSettings/secretsPanel.test.js @@ -312,9 +312,20 @@ test('an existing file offers the .gitignore flow when it is not ignored', async await mount(); // The button alone is shown; the risk is its tooltip and its description, never a sentence beside it. const offer = button('Add to .gitignore'); - assert.equal(offer.title, '.env is not in .gitignore: secrets could be committed'); - assert.equal(offer.getAttribute('aria-description'), offer.title); + const why = '.env is not in .gitignore: secrets could be committed'; + assert.equal(offer.getAttribute('aria-description'), why); + assert.equal(offer.title, '', 'no system tooltip, which waits longer and may not show on a second hover'); assert.ok(!document.body.textContent.includes('secrets could be committed')); + // Stacki's own tip: shown after the shared wait, gone when the pointer leaves, and back on every hover. + const tip = () => document.querySelector('.rail-tooltip')?.textContent; + for (const hover of ['first', 'second']) { + await act(async () => offer.dispatchEvent(new window.MouseEvent('mouseover', { bubbles: true, relatedTarget: document.body }))); + assert.equal(tip(), undefined, `the ${hover} hover waits before the tip`); + await act(async () => new Promise((resolve) => setTimeout(resolve, 600))); + assert.equal(tip(), why, `the ${hover} hover shows the reason`); + await act(async () => offer.dispatchEvent(new window.MouseEvent('mouseout', { bubbles: true, relatedTarget: document.body }))); + assert.equal(tip(), undefined, `the tip goes when the pointer leaves after the ${hover} hover`); + } await click(offer); assert.match(document.body.textContent, /Add \.env to \.gitignore\?/); await click(button('Add line'));