@dr-co/dsh-secret-form 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/page.mjs ADDED
@@ -0,0 +1,318 @@
1
+ // The one page a human ever sees.
2
+ //
3
+ // Self-contained by requirement: no assets, no frameworks, no requests beyond
4
+ // the form post itself. The markup is written once and lays out the same on a
5
+ // phone and on a desktop, because the person opening this link is usually
6
+ // holding a phone and already annoyed.
7
+ //
8
+ // Every interpolated string (label, description) comes from the model and is
9
+ // untrusted HTML; the page's own wording comes from the locale table in
10
+ // lib/i18n.mjs and is rendered through the same escaping path.
11
+
12
+ import { FALLBACK_LOCALE, format, messagesFor, normalizeLocale } from './i18n.mjs';
13
+
14
+ /** Headers that apply to every response, form pages and outcome pages alike. */
15
+ export const SECURITY_HEADERS = Object.freeze({
16
+ 'Cache-Control': 'no-store',
17
+ 'Referrer-Policy': 'no-referrer',
18
+ 'X-Content-Type-Options': 'nosniff',
19
+ 'X-Frame-Options': 'DENY',
20
+ 'Content-Security-Policy': "default-src 'none'; style-src 'unsafe-inline'; script-src 'unsafe-inline'; form-action 'self'; base-uri 'none'",
21
+ });
22
+
23
+ const STYLE = `
24
+ :root {
25
+ color-scheme: light dark;
26
+ --bg: #f4f5f7;
27
+ --card: #ffffff;
28
+ --fg: #16181d;
29
+ --muted: #5b6270;
30
+ --line: #d5d9e0;
31
+ --accent: #2a63d4;
32
+ --accent-fg: #ffffff;
33
+ --danger: #b4232a;
34
+ --warn-bg: #fff4e0;
35
+ --warn-fg: #7a4a00;
36
+ }
37
+ @media (prefers-color-scheme: dark) {
38
+ :root {
39
+ --bg: #14161a;
40
+ --card: #1c1f26;
41
+ --fg: #e8eaee;
42
+ --muted: #9aa1ae;
43
+ --line: #333842;
44
+ --accent: #6b9bff;
45
+ --accent-fg: #10141c;
46
+ --danger: #ff8b8b;
47
+ --warn-bg: #3a2d14;
48
+ --warn-fg: #ffd48a;
49
+ }
50
+ }
51
+ * { box-sizing: border-box; }
52
+ html, body { margin: 0; padding: 0; }
53
+ body {
54
+ background: var(--bg);
55
+ color: var(--fg);
56
+ font: 16px/1.5 -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
57
+ -webkit-text-size-adjust: 100%;
58
+ }
59
+ main {
60
+ max-width: 420px;
61
+ margin: 0 auto;
62
+ padding: 24px 16px 40px;
63
+ }
64
+ h1 { font-size: 20px; line-height: 1.3; margin: 0 0 10px; }
65
+ p { margin: 0 0 16px; }
66
+ .hint { color: var(--muted); font-size: 15px; }
67
+ label { display: block; font-size: 14px; font-weight: 600; margin: 0 0 6px; color: var(--muted); }
68
+ input, textarea {
69
+ width: 100%;
70
+ font-size: 16px;
71
+ line-height: 1.4;
72
+ color: var(--fg);
73
+ background: var(--card);
74
+ border: 1px solid var(--line);
75
+ border-radius: 10px;
76
+ padding: 12px;
77
+ min-height: 48px;
78
+ }
79
+ textarea {
80
+ font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
81
+ min-height: 168px;
82
+ resize: vertical;
83
+ }
84
+ .field { position: relative; }
85
+ /* Firefox offers its password manager for input[type=password] and for text
86
+ inputs it heuristically reads as login fields; a textarea is never treated as
87
+ one, so the single-line case is a one-row textarea. The value is hidden by an
88
+ overlay of bullets, which works in every browser without relying on
89
+ -webkit-text-security. */
90
+ .single { min-height: 48px; height: 48px; resize: none; overflow: hidden; white-space: pre; padding-right: 12px; }
91
+ .masked { color: transparent; }
92
+ .mask {
93
+ position: absolute;
94
+ inset: 1px 1px 1px 1px;
95
+ padding: 12px;
96
+ font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
97
+ font-size: 16px;
98
+ line-height: 1.4;
99
+ color: var(--fg);
100
+ background: var(--card);
101
+ border-radius: 10px;
102
+ pointer-events: none;
103
+ overflow: hidden;
104
+ white-space: pre;
105
+ }
106
+ .mask[hidden] { display: none; }
107
+ .reveal { margin: 10px 0 0; }
108
+ .reveal button {
109
+ width: auto;
110
+ min-height: 44px;
111
+ padding: 0 16px;
112
+ font-size: 15px;
113
+ color: var(--muted);
114
+ background: transparent;
115
+ border: 1px solid var(--line);
116
+ border-radius: 10px;
117
+ cursor: pointer;
118
+ }
119
+ .actions { display: flex; gap: 12px; margin: 22px 0 0; }
120
+ button { font: inherit; cursor: pointer; }
121
+ .actions button {
122
+ flex: 1 1 auto;
123
+ min-height: 50px;
124
+ padding: 12px 16px;
125
+ font-size: 16px;
126
+ font-weight: 600;
127
+ border-radius: 10px;
128
+ border: 1px solid transparent;
129
+ }
130
+ .save { background: var(--accent); color: var(--accent-fg); }
131
+ .cancel { background: transparent; color: var(--fg); border-color: var(--line) !important; }
132
+ .notice { border-left: 3px solid var(--accent); padding: 2px 0 2px 12px; }
133
+ .err { color: var(--danger); }
134
+ .warn { background: var(--warn-bg); color: var(--warn-fg); border-radius: 10px; padding: 12px; font-size: 15px; }
135
+ .meta { color: var(--muted); font-size: 13px; margin: 20px 0 0; }
136
+ `.trim();
137
+
138
+ /** Escape text for element content and double-quoted attributes. */
139
+ export function escapeHtml(text) {
140
+ return String(text)
141
+ .replaceAll('&', '&')
142
+ .replaceAll('<', '&lt;')
143
+ .replaceAll('>', '&gt;')
144
+ .replaceAll('"', '&quot;')
145
+ .replaceAll("'", '&#39;');
146
+ }
147
+
148
+ // A regular expression source reaches the page as a JS string literal, so it
149
+ // must not be able to close the script element it lives in.
150
+ function scriptLiteral(text) {
151
+ return JSON.stringify(text).replaceAll('<', '\\u003c');
152
+ }
153
+
154
+ function shell({ title, body, script, locale }) {
155
+ return `<!DOCTYPE html>
156
+ <html lang="${escapeHtml(locale)}">
157
+ <head>
158
+ <meta charset="utf-8">
159
+ <meta name="viewport" content="width=device-width, initial-scale=1">
160
+ <meta name="referrer" content="no-referrer">
161
+ <meta name="robots" content="noindex, nofollow">
162
+ <title>${escapeHtml(title)}</title>
163
+ <style>
164
+ ${STYLE}
165
+ </style>
166
+ </head>
167
+ <body>
168
+ <main>
169
+ ${body}
170
+ </main>
171
+ ${script === undefined ? '' : `<script>\n${script}\n</script>`}
172
+ </body>
173
+ </html>
174
+ `;
175
+ }
176
+
177
+ // The page never renders a locale the table does not have: an unknown tag means
178
+ // the caller passed something odd, and English is always readable.
179
+ function localized(locale) {
180
+ const resolved = normalizeLocale(locale) ?? FALLBACK_LOCALE;
181
+ return { locale: resolved, messages: messagesFor(resolved) };
182
+ }
183
+
184
+ // Minute counts come from the locale's own rule: Russian has three forms, so
185
+ // the plural decision lives in the table next to the words it selects.
186
+ function remainingText(messages, remainingSeconds) {
187
+ if (remainingSeconds === undefined) return '';
188
+ if (remainingSeconds < 60) return messages.remainingSoon;
189
+ return messages.remaining(Math.round(remainingSeconds / 60));
190
+ }
191
+
192
+ /**
193
+ * Render the input page for a pending form.
194
+ * @param form - pending form.
195
+ * @param options - `actionPath` is where the form posts, `remainingSeconds`
196
+ * feeds the expiry line, `error` and `warning` are page-level messages,
197
+ * `locale` picks the wording (English when absent or unsupported).
198
+ */
199
+ export function renderFormView(form, { actionPath, remainingSeconds, error, warning, locale } = {}) {
200
+ const { locale: lang, messages } = localized(locale);
201
+ const name = form.ref;
202
+ const required = form.allowEmpty ? '' : ' required';
203
+ const field = form.kind === 'single'
204
+ ? `<div class="field"><textarea id="value" name="value" rows="1" class="single masked" autocomplete="off" autocapitalize="off" autocorrect="off" spellcheck="false" wrap="off" autofocus${required}></textarea><div class="mask" id="mask" aria-hidden="true" hidden></div></div>`
205
+ : `<textarea id="value" name="value" rows="8" autocomplete="off" autocapitalize="off" autocorrect="off" spellcheck="false" autofocus${required}></textarea>`;
206
+ const reveal = form.kind === 'single'
207
+ ? `<div class="reveal"><button type="button" id="reveal" aria-pressed="false">${escapeHtml(messages.reveal)}</button></div>`
208
+ : '';
209
+ const scripts = [];
210
+ if (form.kind === 'single') {
211
+ scripts.push(`(function () {
212
+ var button = document.getElementById('reveal');
213
+ var field = document.getElementById('value');
214
+ var mask = document.getElementById('mask');
215
+ if (!button || !field || !mask) return;
216
+ var hidden = true;
217
+ var paint = function () {
218
+ mask.hidden = !hidden;
219
+ field.className = hidden ? 'single masked' : 'single';
220
+ if (!hidden) return;
221
+ mask.textContent = new Array(field.value.length + 1).join('\\u2022');
222
+ };
223
+ paint();
224
+ field.addEventListener('input', paint);
225
+ button.addEventListener('click', function () {
226
+ hidden = !hidden;
227
+ button.textContent = hidden ? ${scriptLiteral(messages.reveal)} : ${scriptLiteral(messages.hide)};
228
+ button.setAttribute('aria-pressed', hidden ? 'false' : 'true');
229
+ paint();
230
+ });
231
+ })();`);
232
+ }
233
+ if (form.expect !== undefined) {
234
+ scripts.push(`(function () {
235
+ var pattern = new RegExp(${scriptLiteral(form.expect.source)});
236
+ var field = document.getElementById('value');
237
+ var box = document.getElementById('expect-warning');
238
+ if (!field || !box) return;
239
+ field.addEventListener('input', function () {
240
+ var value = field.value.trim();
241
+ var mismatch = value !== '' && !pattern.test(value);
242
+ box.hidden = !mismatch;
243
+ });
244
+ })();`);
245
+ }
246
+ const remaining = remainingText(messages, remainingSeconds);
247
+ const body = [
248
+ `<h1>${escapeHtml(form.label)}</h1>`,
249
+ form.description === undefined ? '' : `<p class="hint">${escapeHtml(form.description)}</p>`,
250
+ error === undefined ? '' : `<p class="err">${escapeHtml(error)}</p>`,
251
+ warning === undefined ? '' : `<p class="warn">${escapeHtml(warning)}</p>`,
252
+ `<form method="post" action="${escapeHtml(actionPath)}" autocomplete="off">`,
253
+ // The ref is an identifier such as OPENAI_API_KEY: it is shown as is, next
254
+ // to the translated word for the thing being filled in.
255
+ `<label for="value">${escapeHtml(messages.field)} <span class="hint">${escapeHtml(name)}</span></label>`,
256
+ // The locale travels with the post so the outcome page answers in the
257
+ // language the form was read in, whatever the next request's header says.
258
+ `<input type="hidden" name="lang" value="${escapeHtml(lang)}">`,
259
+ field,
260
+ reveal,
261
+ form.expect === undefined
262
+ ? ''
263
+ : `<p class="warn" id="expect-warning" hidden>${escapeHtml(messages.mismatch)}</p>`,
264
+ `<div class="actions">`,
265
+ `<button class="save" type="submit" name="action" value="save">${escapeHtml(messages.save)}</button>`,
266
+ `<button class="cancel" type="submit" name="action" value="cancel" formnovalidate>${escapeHtml(messages.cancel)}</button>`,
267
+ `</div>`,
268
+ `</form>`,
269
+ // Without a remaining time there is no sentence to finish, so the line goes.
270
+ remaining === '' ? '' : `<p class="meta">${escapeHtml(format(messages.note, { time: remaining }))}</p>`,
271
+ ].filter((part) => part !== '');
272
+ return shell({
273
+ title: form.label,
274
+ body: body.join('\n'),
275
+ script: scripts.length === 0 ? undefined : scripts.join('\n'),
276
+ locale: lang,
277
+ });
278
+ }
279
+
280
+ /**
281
+ * Render an outcome page: saved, empty, cancelled, used, expired, unknown.
282
+ * @param kind - key of the notice table.
283
+ * @param note - optional extra sentence, already user-facing.
284
+ * @param options - `locale` picks the wording, English when absent.
285
+ */
286
+ export function renderNotice(kind, note, { locale } = {}) {
287
+ const { locale: lang, messages } = localized(locale);
288
+ const notice = messages.notices[kind] ?? messages.notices.unknown;
289
+ const body = [
290
+ `<h1>${escapeHtml(notice.title)}</h1>`,
291
+ `<p class="notice">${escapeHtml(notice.text)}</p>`,
292
+ note === undefined ? '' : `<p class="warn">${escapeHtml(note)}</p>`,
293
+ ].filter((part) => part !== '');
294
+ return shell({ title: notice.title, body: body.join('\n'), locale: lang });
295
+ }
296
+
297
+ /** Send an HTML response with the security headers and an exact length. */
298
+ export function sendHtml(res, status, html, { head = false } = {}) {
299
+ const body = Buffer.from(html, 'utf8');
300
+ res.writeHead(status, {
301
+ ...SECURITY_HEADERS,
302
+ 'Content-Type': 'text/html; charset=utf-8',
303
+ 'Content-Length': String(body.length),
304
+ });
305
+ res.end(head ? undefined : body);
306
+ }
307
+
308
+ /** Send a short plain-text response (method or body rejections). */
309
+ export function sendText(res, status, text, headers = {}) {
310
+ const body = Buffer.from(`${text}\n`, 'utf8');
311
+ res.writeHead(status, {
312
+ ...SECURITY_HEADERS,
313
+ 'Content-Type': 'text/plain; charset=utf-8',
314
+ 'Content-Length': String(body.length),
315
+ ...headers,
316
+ });
317
+ res.end(body);
318
+ }
@@ -0,0 +1,222 @@
1
+ // Where a submitted secret lands.
2
+ //
3
+ // Two targets: the host credential store (the default, the same one an adapter
4
+ // reads through `apiKeyEnv`) and a document file inside this machine's
5
+ // filesystem. Both refuse rather than guess — an unknown extension, an
6
+ // unparseable document, or a path that would overwrite a non-string value is a
7
+ // validation error, never a best effort.
8
+ import { randomBytes } from 'node:crypto';
9
+ import { chmod, mkdir, open, readFile, rename, rm } from 'node:fs/promises';
10
+ import { basename, dirname, extname, join, resolve } from 'node:path';
11
+
12
+ import { parseYamlMapping, setYamlPath, stringifyYamlMapping } from './yaml.mjs';
13
+
14
+ const ENV_KEY = /^[A-Za-z_][A-Za-z0-9_]*$/;
15
+ const FORMAT_BY_EXTENSION = Object.freeze({
16
+ '.yaml': 'yaml',
17
+ '.yml': 'yaml',
18
+ '.json': 'json',
19
+ '.env': 'env',
20
+ });
21
+ // Dotted paths are also assignment targets, so a segment that reaches a
22
+ // prototype would be a cheap way to poison the process.
23
+ const UNSAFE_SEGMENT = new Set(['__proto__', 'prototype', 'constructor']);
24
+ const DOTENV_PLAIN = /^[A-Za-z0-9_@%+:,./~-]+$/;
25
+
26
+ function invalid(message) {
27
+ const error = new TypeError(message);
28
+ error.code = 'secret-form-target-invalid';
29
+ return error;
30
+ }
31
+
32
+ /**
33
+ * Validate and normalise the `save` argument of `secret_create`.
34
+ * @param save - the model's `save` value, or undefined for the default target.
35
+ * @returns `{ kind: 'credentials' }` or `{ kind: 'file', path, format, given }`.
36
+ */
37
+ export function normalizeTarget(save) {
38
+ if (save === undefined || save === null) return { kind: 'credentials' };
39
+ if (typeof save !== 'object' || Array.isArray(save)) throw invalid('save must be an object');
40
+ if (save.kind === 'credentials') return { kind: 'credentials' };
41
+ if (save.kind !== 'file') {
42
+ throw invalid(`save.kind must be "credentials" or "file", got ${JSON.stringify(save.kind ?? null)}`);
43
+ }
44
+ if (typeof save.path !== 'string' || save.path.trim() === '') {
45
+ throw invalid('save.path must be a non-empty string for a file target');
46
+ }
47
+ if (save.path.includes('\0')) throw invalid('save.path must not contain a NUL byte');
48
+ const extension = extname(save.path).toLowerCase();
49
+ const format = FORMAT_BY_EXTENSION[extension];
50
+ if (format === undefined) {
51
+ throw invalid(`save.path must end in .yaml, .yml, .json or .env, got ${JSON.stringify(extension || save.path)}`);
52
+ }
53
+ return { kind: 'file', path: resolve(save.path), format, given: save.path };
54
+ }
55
+
56
+ /**
57
+ * Validate `ref` against the target's grammar.
58
+ * @param target - normalised target.
59
+ * @param ref - the model's `ref`.
60
+ * @returns the trimmed ref.
61
+ */
62
+ export function assertRefForTarget(target, ref) {
63
+ if (typeof ref !== 'string' || ref.trim() === '') throw invalid('ref must be a non-empty string');
64
+ const text = ref.trim();
65
+ if (target.kind === 'credentials') {
66
+ if (!ENV_KEY.test(text)) {
67
+ throw invalid(`ref ${JSON.stringify(text)} must be a credential reference such as OPENAI_API_KEY`);
68
+ }
69
+ return text;
70
+ }
71
+ if (target.format === 'env') {
72
+ if (!ENV_KEY.test(text)) {
73
+ throw invalid(`ref ${JSON.stringify(text)} must be a variable name such as OPENAI_API_KEY inside a .env file`);
74
+ }
75
+ return text;
76
+ }
77
+ const segments = text.split('.');
78
+ if (segments.length > 1 && segments.some((segment) => segment === '')) {
79
+ throw invalid(`ref ${JSON.stringify(text)} has an empty dotted path segment`);
80
+ }
81
+ for (const segment of segments) {
82
+ if (/\s/.test(segment)) throw invalid(`ref ${JSON.stringify(text)} has whitespace inside a path segment`);
83
+ if (UNSAFE_SEGMENT.has(segment)) throw invalid(`ref ${JSON.stringify(text)} names a prototype member, which is refused`);
84
+ }
85
+ return text;
86
+ }
87
+
88
+ async function readTextIfExists(file) {
89
+ try {
90
+ return await readFile(file, 'utf8');
91
+ } catch (error) {
92
+ if (error.code === 'ENOENT') return undefined;
93
+ throw error;
94
+ }
95
+ }
96
+
97
+ // A half-written credentials document is worse than a failed form: write beside
98
+ // the target, flush it, then rename over it in one step.
99
+ async function writeAtomic(file, text) {
100
+ const temp = join(dirname(file), `.${basename(file)}.${randomBytes(6).toString('hex')}.tmp`);
101
+ let handle;
102
+ try {
103
+ handle = await open(temp, 'wx', 0o600);
104
+ await handle.writeFile(text, 'utf8');
105
+ await handle.sync();
106
+ await handle.close();
107
+ handle = undefined;
108
+ await rename(temp, file);
109
+ } catch (error) {
110
+ if (handle !== undefined) await handle.close().catch(() => {});
111
+ await rm(temp, { force: true }).catch(() => {});
112
+ throw error;
113
+ }
114
+ // The rename carries the temp file's mode, but an existing target may have
115
+ // been group- or world-readable before; the secret is not.
116
+ await chmod(file, 0o600);
117
+ }
118
+
119
+ function dotenvValue(value) {
120
+ if (value === '') return '';
121
+ if (DOTENV_PLAIN.test(value)) return value;
122
+ const escaped = value
123
+ .replaceAll('\\', '\\\\')
124
+ .replaceAll('"', '\\"')
125
+ .replaceAll('\r', '\\r')
126
+ .replaceAll('\n', '\\n');
127
+ return `"${escaped}"`;
128
+ }
129
+
130
+ function upsertEnvLine(existing, ref, value) {
131
+ const text = existing ?? '';
132
+ const eol = text.includes('\r\n') ? '\r\n' : '\n';
133
+ const lines = text.split(/\r?\n/);
134
+ const pattern = new RegExp(`^\\s*(?:export\\s+)?${ref}\\s*=`);
135
+ const line = `${ref}=${dotenvValue(value)}`;
136
+ const index = lines.findIndex((entry) => pattern.test(entry));
137
+ if (index >= 0) lines[index] = line;
138
+ else {
139
+ while (lines.length > 0 && lines[lines.length - 1].trim() === '') lines.pop();
140
+ lines.push(line);
141
+ }
142
+ let out = lines.join(eol);
143
+ if (!out.endsWith(eol)) out += eol;
144
+ return out;
145
+ }
146
+
147
+ function setDocumentPath(document, segments, value, source) {
148
+ let node = document;
149
+ for (const segment of segments.slice(0, -1)) {
150
+ const current = node[segment];
151
+ if (current === undefined) {
152
+ const created = {};
153
+ node[segment] = created;
154
+ node = created;
155
+ continue;
156
+ }
157
+ if (typeof current !== 'object' || current === null || Array.isArray(current)) {
158
+ throw invalid(`${source} already holds a non-object at "${segment}"; refusing to replace it`);
159
+ }
160
+ node = current;
161
+ }
162
+ const last = segments[segments.length - 1];
163
+ const current = node[last];
164
+ if (current !== undefined && typeof current === 'object' && current !== null) {
165
+ throw invalid(`${source} already holds a nested value at "${last}"; refusing to replace it`);
166
+ }
167
+ node[last] = value;
168
+ }
169
+
170
+ function rewriteJson(existing, file, ref, value) {
171
+ let document = {};
172
+ const text = (existing ?? '').trim();
173
+ if (text !== '') {
174
+ try {
175
+ document = JSON.parse(text);
176
+ } catch (error) {
177
+ throw invalid(`${file} is not valid JSON (${error.message}); refusing to rewrite it`);
178
+ }
179
+ if (typeof document !== 'object' || document === null || Array.isArray(document)) {
180
+ throw invalid(`${file} does not hold a JSON object; refusing to rewrite it`);
181
+ }
182
+ }
183
+ setDocumentPath(document, ref.split('.'), value, file);
184
+ return `${JSON.stringify(document, null, 2)}\n`;
185
+ }
186
+
187
+ function rewriteYaml(existing, file, ref, value) {
188
+ const root = (existing ?? '').trim() === ''
189
+ ? { type: 'map', entries: [] }
190
+ : parseYamlMapping(existing, file);
191
+ setYamlPath(root, ref.split('.'), value, file);
192
+ return stringifyYamlMapping(root);
193
+ }
194
+
195
+ /**
196
+ * Store a submitted value.
197
+ * @param target - normalised target.
198
+ * @param ref - validated ref.
199
+ * @param value - normalised submitted value; may be empty only for a file target.
200
+ * @param options - `credentials` is the host service, read lazily by the caller.
201
+ */
202
+ export async function writeSecret(target, ref, value, { credentials } = {}) {
203
+ if (target.kind === 'credentials') {
204
+ // The credential store refuses an empty value, and an empty submit is
205
+ // reported as `empty`: there is nothing to store.
206
+ if (value === '') return;
207
+ if (credentials === undefined || typeof credentials.set !== 'function') {
208
+ throw new Error('dsh-secret-form: the credentials service is not mounted in this host; use save { kind: "file", path } instead');
209
+ }
210
+ await credentials.set(ref, value);
211
+ return;
212
+ }
213
+ const file = target.path;
214
+ await mkdir(dirname(file), { recursive: true, mode: 0o700 });
215
+ const existing = await readTextIfExists(file);
216
+ const text = target.format === 'env'
217
+ ? upsertEnvLine(existing, ref, value)
218
+ : target.format === 'json'
219
+ ? rewriteJson(existing, file, ref, value)
220
+ : rewriteYaml(existing, file, ref, value);
221
+ await writeAtomic(file, text);
222
+ }