@neondatabase/env 1.0.0 → 1.1.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/README.md +21 -1
- package/dist/cli.js +1304 -6
- package/dist/cli.js.map +1 -1
- package/dist/{_shared/env-core/env.js → env.js} +62 -41
- package/dist/env.js.map +1 -0
- package/dist/index.d.ts +528 -3
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +197 -2
- package/dist/{lib/parse-env.js.map → index.js.map} +1 -1
- package/package.json +12 -7
- package/dist/_shared/auth_selection.d.ts +0 -95
- package/dist/_shared/auth_selection.d.ts.map +0 -1
- package/dist/_shared/auth_selection.js +0 -85
- package/dist/_shared/auth_selection.js.map +0 -1
- package/dist/_shared/credentials.d.ts +0 -186
- package/dist/_shared/credentials.d.ts.map +0 -1
- package/dist/_shared/credentials.js +0 -190
- package/dist/_shared/credentials.js.map +0 -1
- package/dist/_shared/env-core/env.d.ts +0 -424
- package/dist/_shared/env-core/env.d.ts.map +0 -1
- package/dist/_shared/env-core/env.js.map +0 -1
- package/dist/_shared/env-core/reuse-secrets.d.ts +0 -95
- package/dist/_shared/env-core/reuse-secrets.d.ts.map +0 -1
- package/dist/_shared/env-core/reuse-secrets.js +0 -181
- package/dist/_shared/env-core/reuse-secrets.js.map +0 -1
- package/dist/_shared/paths.d.ts +0 -116
- package/dist/_shared/paths.d.ts.map +0 -1
- package/dist/_shared/paths.js +0 -153
- package/dist/_shared/paths.js.map +0 -1
- package/dist/_shared/profiles.d.ts +0 -145
- package/dist/_shared/profiles.d.ts.map +0 -1
- package/dist/_shared/profiles.js +0 -228
- package/dist/_shared/profiles.js.map +0 -1
- package/dist/_shared/secure_file.d.ts +0 -25
- package/dist/_shared/secure_file.d.ts.map +0 -1
- package/dist/_shared/secure_file.js +0 -43
- package/dist/_shared/secure_file.js.map +0 -1
- package/dist/config/dist/lib/define-config.d.ts +0 -20
- package/dist/config/dist/lib/define-config.d.ts.map +0 -1
- package/dist/config/dist/lib/neon-api.d.ts +0 -375
- package/dist/config/dist/lib/neon-api.d.ts.map +0 -1
- package/dist/config/dist/lib/types.d.ts +0 -603
- package/dist/config/dist/lib/types.d.ts.map +0 -1
- package/dist/config/dist/v1.d.ts +0 -5
- package/dist/lib/cli/commands.d.ts +0 -68
- package/dist/lib/cli/commands.d.ts.map +0 -1
- package/dist/lib/cli/commands.js +0 -233
- package/dist/lib/cli/commands.js.map +0 -1
- package/dist/lib/cli/resolve-api-key.d.ts +0 -29
- package/dist/lib/cli/resolve-api-key.d.ts.map +0 -1
- package/dist/lib/cli/resolve-api-key.js +0 -74
- package/dist/lib/cli/resolve-api-key.js.map +0 -1
- package/dist/lib/cli/resolve-context.d.ts +0 -34
- package/dist/lib/cli/resolve-context.d.ts.map +0 -1
- package/dist/lib/cli/resolve-context.js +0 -88
- package/dist/lib/cli/resolve-context.js.map +0 -1
- package/dist/lib/parse-env.d.ts +0 -95
- package/dist/lib/parse-env.d.ts.map +0 -1
- package/dist/lib/parse-env.js +0 -198
package/dist/cli.js
CHANGED
|
@@ -1,9 +1,1309 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
2
|
+
import { c as previewCredentialScopes, i as credentialName, l as resolveBranchPolicy, n as createApiFromOptions, o as fetchEnvKeys, r as credentialEnvKeys, s as policyEnvKeys, t as NEON_ENV_VAR_KEYS, u as toEntries } from "./env.js";
|
|
3
|
+
import { createRequire } from "node:module";
|
|
4
|
+
import { existsSync, readFileSync, renameSync, rmSync, statSync, unlinkSync, writeFileSync } from "node:fs";
|
|
4
5
|
import { fileURLToPath } from "node:url";
|
|
5
6
|
import yargs from "yargs";
|
|
6
7
|
import { hideBin } from "yargs/helpers";
|
|
8
|
+
import { spawn } from "node:child_process";
|
|
9
|
+
import { basename, dirname, isAbsolute, join, resolve } from "node:path";
|
|
10
|
+
import { ConfigLoadError, ErrorCode, MissingContextError, PlatformError, credentialScopesSatisfied, loadConfigFromFile } from "@neon/config/v1";
|
|
11
|
+
import { createHash } from "node:crypto";
|
|
12
|
+
import { homedir } from "node:os";
|
|
13
|
+
//#region ../../internals/env-core/dist/reuse-secrets.js
|
|
14
|
+
/**
|
|
15
|
+
* Resolve a branch's env while keeping one-time secrets the caller already holds.
|
|
16
|
+
*
|
|
17
|
+
* {@link fetchEnvKeys} — and the public `fetchEnv` — only ever *fetch*. The Neon API returns a
|
|
18
|
+
* credential's `api_token` / `s3_secret_access_key` exactly once, at mint time, so "fetching"
|
|
19
|
+
* them means minting a new credential; a plain `fetchEnv` on every `neon dev` start or `env
|
|
20
|
+
* pull` would leave a live credential behind each time. This is the wrapper that avoids that:
|
|
21
|
+
* it looks at what the caller already has, decides what is still usable, and asks `fetchEnv`
|
|
22
|
+
* for only the rest.
|
|
23
|
+
*
|
|
24
|
+
* The check is a real verification, not a presence test. A persisted secret is kept only when
|
|
25
|
+
* it names a credential that still exists on this branch, is not revoked or expired, and
|
|
26
|
+
* carries every scope the policy needs. A `.env.example` placeholder, a credential revoked in
|
|
27
|
+
* the console, one copied in from another branch, or one predating a newly-enabled feature all
|
|
28
|
+
* fail that check and get replaced.
|
|
29
|
+
*
|
|
30
|
+
* None of this needs local bookkeeping, because the secrets carry their own credential id:
|
|
31
|
+
* `AWS_ACCESS_KEY_ID` **is** the credential's `tokenId` (the storage gateway authenticates
|
|
32
|
+
* against the full id), and the AI Gateway token is minted as `nt_live_<tokenIdShort>_<secret>`,
|
|
33
|
+
* where `tokenIdShort` is what the credentials list reports. The env source being replaced is
|
|
34
|
+
* the record of what the last call issued.
|
|
35
|
+
*
|
|
36
|
+
* ```ts
|
|
37
|
+
* import { fetchEnvReusingSecrets } from "@neon-internals/env-core/reuse-secrets";
|
|
38
|
+
*
|
|
39
|
+
* const { vars, credential } = await fetchEnvReusingSecrets(config, {
|
|
40
|
+
* projectId,
|
|
41
|
+
* branch: "main",
|
|
42
|
+
* env: { ...process.env, ...readEnvFile(".env") },
|
|
43
|
+
* });
|
|
44
|
+
* if (credential.issued) console.log(`new values for ${credential.keys.join(", ")}`);
|
|
45
|
+
* ```
|
|
46
|
+
*/
|
|
47
|
+
async function fetchEnvReusingSecrets(config, options) {
|
|
48
|
+
const { env: source = process.env, keys: requestedKeys, revokeSuperseded = true, ...fetchOptions } = options;
|
|
49
|
+
const api = options.api ?? createApiFromOptions(options);
|
|
50
|
+
const { branch, desired } = await resolveBranchPolicy(config, options, api);
|
|
51
|
+
const allPolicyKeys = policyEnvKeys(desired);
|
|
52
|
+
const requested = requestedKeys ? new Set(requestedKeys) : null;
|
|
53
|
+
const selectedPolicyKeys = requested === null ? allPolicyKeys : allPolicyKeys.filter((key) => requested.has(key));
|
|
54
|
+
const selected = new Set(selectedPolicyKeys);
|
|
55
|
+
const K = NEON_ENV_VAR_KEYS;
|
|
56
|
+
const storageCredentialSelected = (desired.preview?.buckets.length ?? 0) > 0 && (selected.has(K.storage.accessKeyId) || selected.has(K.storage.secretAccessKey));
|
|
57
|
+
const gatewayCredentialSelected = (desired.preview?.aiGatewayEnabled ?? false) && selected.has(K.aiGateway.apiKey);
|
|
58
|
+
const secretKeys = credentialEnvKeys({
|
|
59
|
+
storage: storageCredentialSelected,
|
|
60
|
+
aiGateway: gatewayCredentialSelected
|
|
61
|
+
}).filter((key) => selected.has(key));
|
|
62
|
+
if (secretKeys.length === 0) {
|
|
63
|
+
const fetched = await fetchEnvKeys(config, fetchOptions, requested === null ? null : selectedPolicyKeys);
|
|
64
|
+
return {
|
|
65
|
+
vars: preferPersisted(toEntries(fetched), source),
|
|
66
|
+
credential: {
|
|
67
|
+
issued: false,
|
|
68
|
+
keys: [],
|
|
69
|
+
revoked: [],
|
|
70
|
+
superseded: []
|
|
71
|
+
}
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
const persisted = readPersistedSecrets(source);
|
|
75
|
+
const storageCredentialManaged = requested === null || storageCredentialSelected;
|
|
76
|
+
const gatewayCredentialManaged = requested === null || gatewayCredentialSelected;
|
|
77
|
+
const complete = (!storageCredentialSelected || Boolean(persisted.accessKeyId && persisted.secretAccessKey)) && (!gatewayCredentialSelected || Boolean(persisted.apiToken));
|
|
78
|
+
const named = storageCredentialManaged && persisted.accessKeyId !== "" || gatewayCredentialManaged && persisted.apiToken !== "" ? namedCredentials(await api.listCredentials(options.projectId, branch.id), persisted) : {
|
|
79
|
+
storage: null,
|
|
80
|
+
gateway: null
|
|
81
|
+
};
|
|
82
|
+
const reusable = complete ? reusableCredential(named, {
|
|
83
|
+
storageEnabled: storageCredentialSelected,
|
|
84
|
+
gatewayEnabled: gatewayCredentialSelected
|
|
85
|
+
}) : null;
|
|
86
|
+
const scopes = previewCredentialScopes(desired.preview, {
|
|
87
|
+
storage: storageCredentialSelected,
|
|
88
|
+
aiGateway: gatewayCredentialSelected
|
|
89
|
+
});
|
|
90
|
+
const keep = reusable !== null && credentialScopesSatisfied(reusable.scopes, scopes);
|
|
91
|
+
const fetchKeys = keep ? selectedPolicyKeys.filter((key) => !secretKeys.includes(key)) : selectedPolicyKeys;
|
|
92
|
+
const fetched = await fetchEnvKeys(config, {
|
|
93
|
+
...fetchOptions,
|
|
94
|
+
branchId: branch.id,
|
|
95
|
+
api
|
|
96
|
+
}, fetchKeys);
|
|
97
|
+
const vars = preferPersisted(toEntries(fetched), source);
|
|
98
|
+
if (keep) {
|
|
99
|
+
for (const key of secretKeys) {
|
|
100
|
+
const value = source[key];
|
|
101
|
+
if (value !== void 0) vars[key] = value;
|
|
102
|
+
}
|
|
103
|
+
return {
|
|
104
|
+
vars,
|
|
105
|
+
credential: {
|
|
106
|
+
issued: false,
|
|
107
|
+
keys: secretKeys,
|
|
108
|
+
revoked: [],
|
|
109
|
+
superseded: []
|
|
110
|
+
}
|
|
111
|
+
};
|
|
112
|
+
}
|
|
113
|
+
const ours = /* @__PURE__ */ new Set();
|
|
114
|
+
for (const meta of [storageCredentialManaged ? named.storage : null, gatewayCredentialManaged ? named.gateway : null]) if (meta !== null && meta.principalType === "user" && meta.name === credentialName(branch.name)) ours.add(meta.tokenId);
|
|
115
|
+
if (revokeSuperseded) for (const tokenId of ours) await api.revokeCredential(options.projectId, branch.id, tokenId);
|
|
116
|
+
return {
|
|
117
|
+
vars,
|
|
118
|
+
credential: {
|
|
119
|
+
issued: true,
|
|
120
|
+
keys: secretKeys,
|
|
121
|
+
revoked: revokeSuperseded ? [...ours] : [],
|
|
122
|
+
superseded: revokeSuperseded ? [] : [...ours]
|
|
123
|
+
}
|
|
124
|
+
};
|
|
125
|
+
}
|
|
126
|
+
/** Read the branch credential's secrets out of an env source. */
|
|
127
|
+
function readPersistedSecrets(source) {
|
|
128
|
+
const storage = NEON_ENV_VAR_KEYS.storage;
|
|
129
|
+
const gateway = NEON_ENV_VAR_KEYS.aiGateway;
|
|
130
|
+
return {
|
|
131
|
+
accessKeyId: source[storage.accessKeyId] ?? "",
|
|
132
|
+
secretAccessKey: source[storage.secretAccessKey] ?? "",
|
|
133
|
+
apiToken: source[gateway.apiKey] ?? ""
|
|
134
|
+
};
|
|
135
|
+
}
|
|
136
|
+
/**
|
|
137
|
+
* Keep a persisted value rather than overwriting it with an empty fetched one.
|
|
138
|
+
*
|
|
139
|
+
* Neon Auth's `base_url` is the case that needs this: integrations created before the API
|
|
140
|
+
* returned it answer with an empty string, and the persisted copy is the only one left. An
|
|
141
|
+
* empty fetched value never carries more information than a non-empty persisted one, so
|
|
142
|
+
* preferring the latter is safe for every var — and it keeps a pull from blanking a working
|
|
143
|
+
* line in someone's `.env`.
|
|
144
|
+
*/
|
|
145
|
+
function preferPersisted(vars, source) {
|
|
146
|
+
const out = { ...vars };
|
|
147
|
+
for (const [key, value] of Object.entries(out)) {
|
|
148
|
+
if (value !== "") continue;
|
|
149
|
+
const persisted = source[key];
|
|
150
|
+
if (persisted !== void 0 && persisted !== "") out[key] = persisted;
|
|
151
|
+
}
|
|
152
|
+
return out;
|
|
153
|
+
}
|
|
154
|
+
/**
|
|
155
|
+
* The credential id embedded in an AI Gateway token. The API mints them as
|
|
156
|
+
* `nt_live_<tokenIdShort>_<secret>`, and `tokenIdShort` is the public identifier the credentials
|
|
157
|
+
* list reports — so a persisted token names the credential that issued it. Returns `null` for
|
|
158
|
+
* anything not in that shape (a `.env.example` placeholder, a hand-typed value), which callers
|
|
159
|
+
* treat as unverifiable.
|
|
160
|
+
*/
|
|
161
|
+
function gatewayTokenIdShort(apiToken) {
|
|
162
|
+
return /^nt_live_([^_]+)_.+$/.exec(apiToken)?.[1] ?? null;
|
|
163
|
+
}
|
|
164
|
+
/** Whether an issued credential can still be used: not revoked, not past its expiry. */
|
|
165
|
+
function isLiveCredential(meta, now) {
|
|
166
|
+
if (meta.revokedAt !== void 0) return false;
|
|
167
|
+
if (meta.expiresAt === void 0) return true;
|
|
168
|
+
const expiresAt = Date.parse(meta.expiresAt);
|
|
169
|
+
return Number.isNaN(expiresAt) || expiresAt > now;
|
|
170
|
+
}
|
|
171
|
+
/**
|
|
172
|
+
* The live credentials the persisted secrets name — at most one per half. A half that names
|
|
173
|
+
* nothing contributes nothing, which is what a placeholder, a credential revoked in the
|
|
174
|
+
* console, and one copied in from another branch all look like from here.
|
|
175
|
+
*/
|
|
176
|
+
function namedCredentials(live, persisted) {
|
|
177
|
+
const usable = live.filter((meta) => isLiveCredential(meta, Date.now()));
|
|
178
|
+
const shortId = persisted.apiToken ? gatewayTokenIdShort(persisted.apiToken) : null;
|
|
179
|
+
return {
|
|
180
|
+
storage: persisted.accessKeyId ? usable.find((meta) => meta.tokenId === persisted.accessKeyId) ?? null : null,
|
|
181
|
+
gateway: shortId ? usable.find((meta) => meta.tokenIdShort === shortId) ?? null : null
|
|
182
|
+
};
|
|
183
|
+
}
|
|
184
|
+
/**
|
|
185
|
+
* The credential the persisted secrets can be *reused* as, or `null`.
|
|
186
|
+
*
|
|
187
|
+
* Strict on purpose: every half the policy enables has to name a live credential, and when both
|
|
188
|
+
* features are enabled they must name the *same* one — they share a single credential, so
|
|
189
|
+
* halves that disagree came from two different calls and neither can be trusted.
|
|
190
|
+
*/
|
|
191
|
+
function reusableCredential(named, enabled) {
|
|
192
|
+
if (enabled.storageEnabled && enabled.gatewayEnabled) return named.storage && named.gateway && named.storage.tokenId === named.gateway.tokenId ? named.storage : null;
|
|
193
|
+
if (enabled.storageEnabled) return named.storage;
|
|
194
|
+
if (enabled.gatewayEnabled) return named.gateway;
|
|
195
|
+
return null;
|
|
196
|
+
}
|
|
197
|
+
//#endregion
|
|
198
|
+
//#region ../../internals/cli-core/dist/cli_config.js
|
|
199
|
+
const CRED_STORAGE_FILE = "file";
|
|
200
|
+
const CRED_STORAGE_KEYRING = "keyring";
|
|
201
|
+
//#endregion
|
|
202
|
+
//#region ../../internals/cli-core/dist/paths.js
|
|
203
|
+
/**
|
|
204
|
+
* # Where the Neon CLIs keep their files on disk
|
|
205
|
+
*
|
|
206
|
+
**Deliberately impure.** It reads environment variables and touches the filesystem, which
|
|
207
|
+
* `@neon/config` — the package this used to be a subpath of — must never do from its root
|
|
208
|
+
* export. It lives here instead of there precisely so that a policy-facing package does not
|
|
209
|
+
* carry implementor-only code.
|
|
210
|
+
*
|
|
211
|
+
* It exists because three separate readers each grew their own answer to "where is the
|
|
212
|
+
* config directory", and all three disagreed: `packages/cli` honoured `XDG_CONFIG_HOME` but
|
|
213
|
+
* not `NEONCTL_CONFIG_DIR`, `packages/env` honoured the env var but not XDG, and the init
|
|
214
|
+
* flow hardcoded `~/.config/neonctl`. With `XDG_CONFIG_HOME` set, the CLI wrote
|
|
215
|
+
* credentials somewhere the other two never looked.
|
|
216
|
+
*
|
|
217
|
+
* ## The directory
|
|
218
|
+
*
|
|
219
|
+
* `neon` is the current name; `neonctl` is the legacy one, kept readable forever. Resolution,
|
|
220
|
+
* each entry winning over the next:
|
|
221
|
+
*
|
|
222
|
+
* 1. An explicit directory (a `--config-dir` flag) — **exact**, no legacy fallback.
|
|
223
|
+
* 2. `NEON_CONFIG_DIR` — exact.
|
|
224
|
+
* 3. `NEONCTL_CONFIG_DIR` (legacy name) — exact.
|
|
225
|
+
* 4. `$XDG_CONFIG_HOME/neon`, else `<home>/.config/neon`.
|
|
226
|
+
*
|
|
227
|
+
* An explicitly chosen directory is never paired with a fallback: `--config-dir /tmp/ci` that
|
|
228
|
+
* quietly read `~/.config/neonctl` would defeat the point of passing it.
|
|
229
|
+
*
|
|
230
|
+
* ## The files
|
|
231
|
+
*
|
|
232
|
+
* {@link resolveConfigFile} answers "which path should I use for this file", and it is the
|
|
233
|
+
* same answer for reading and writing:
|
|
234
|
+
*
|
|
235
|
+
* - Present in `neon/` → use it.
|
|
236
|
+
* - Present only in `neonctl/` → **use it there, in place.** An existing credentials file is
|
|
237
|
+
* never copied or moved, so nothing is left behind to go stale and no other tool starts
|
|
238
|
+
* reading an abandoned token.
|
|
239
|
+
* - Present in neither → the new location. New files only ever appear under `neon/`.
|
|
240
|
+
*/
|
|
241
|
+
/** Current directory name. New files are created here. */
|
|
242
|
+
const CONFIG_DIR_NAME = "neon";
|
|
243
|
+
/** Legacy directory name, read forever so existing installs keep working untouched. */
|
|
244
|
+
const LEGACY_CONFIG_DIR_NAME = "neonctl";
|
|
245
|
+
/** Where files are created. See the module docs for the precedence. */
|
|
246
|
+
function configDir(options = {}) {
|
|
247
|
+
const explicit = explicitDir(options);
|
|
248
|
+
if (explicit) return explicit;
|
|
249
|
+
return join(configHome(options.env ?? process.env), CONFIG_DIR_NAME);
|
|
250
|
+
}
|
|
251
|
+
/**
|
|
252
|
+
* The legacy directory, or `undefined` when the location was chosen explicitly (in which
|
|
253
|
+
* case there is no legacy counterpart to fall back to).
|
|
254
|
+
*/
|
|
255
|
+
function legacyConfigDir(options = {}) {
|
|
256
|
+
if (explicitDir(options)) return void 0;
|
|
257
|
+
return join(configHome(options.env ?? process.env), LEGACY_CONFIG_DIR_NAME);
|
|
258
|
+
}
|
|
259
|
+
/**
|
|
260
|
+
* Resolve one file inside the config directory. Prefers the current location, falls back to
|
|
261
|
+
* an existing legacy file **in place**, and otherwise points at the current location so new
|
|
262
|
+
* files are created there.
|
|
263
|
+
*/
|
|
264
|
+
function resolveConfigFile(fileName, options = {}) {
|
|
265
|
+
const dir = configDir(options);
|
|
266
|
+
const current = resolve(dir, fileName);
|
|
267
|
+
if (existsSync(current)) return {
|
|
268
|
+
path: current,
|
|
269
|
+
dir,
|
|
270
|
+
isLegacy: false,
|
|
271
|
+
exists: true
|
|
272
|
+
};
|
|
273
|
+
const legacyDir = legacyConfigDir(options);
|
|
274
|
+
if (legacyDir) {
|
|
275
|
+
const legacy = resolve(legacyDir, fileName);
|
|
276
|
+
if (existsSync(legacy)) return {
|
|
277
|
+
path: legacy,
|
|
278
|
+
dir: legacyDir,
|
|
279
|
+
isLegacy: true,
|
|
280
|
+
exists: true
|
|
281
|
+
};
|
|
282
|
+
}
|
|
283
|
+
return {
|
|
284
|
+
path: current,
|
|
285
|
+
dir,
|
|
286
|
+
isLegacy: false,
|
|
287
|
+
exists: false
|
|
288
|
+
};
|
|
289
|
+
}
|
|
290
|
+
/** `$XDG_CONFIG_HOME`, else `<home>/.config`. Falls back to a relative `.config` with no home. */
|
|
291
|
+
function configHome(env) {
|
|
292
|
+
const xdg = nonEmpty$3(env.XDG_CONFIG_HOME);
|
|
293
|
+
if (xdg) return xdg;
|
|
294
|
+
const home = nonEmpty$3(env.HOME) ?? nonEmpty$3(env.USERPROFILE);
|
|
295
|
+
return home ? join(home, ".config") : ".config";
|
|
296
|
+
}
|
|
297
|
+
function explicitDir(options) {
|
|
298
|
+
const env = options.env ?? process.env;
|
|
299
|
+
return nonEmpty$3(options.dir) ?? nonEmpty$3(env.NEON_CONFIG_DIR) ?? nonEmpty$3(env.NEONCTL_CONFIG_DIR);
|
|
300
|
+
}
|
|
301
|
+
function nonEmpty$3(value) {
|
|
302
|
+
if (typeof value !== "string") return void 0;
|
|
303
|
+
const trimmed = value.trim();
|
|
304
|
+
return trimmed === "" ? void 0 : trimmed;
|
|
305
|
+
}
|
|
306
|
+
const CREDENTIALS_FILE = "credentials.json";
|
|
307
|
+
/**
|
|
308
|
+
* Default for `--config-dir`: `$XDG_CONFIG_HOME/neon`, else `~/.config/neon`.
|
|
309
|
+
*
|
|
310
|
+
* The directory was called `neonctl` until the CLI was renamed. An existing one is still read —
|
|
311
|
+
* see {@link credentialsPath} — but it is never written to, moved, or deleted.
|
|
312
|
+
*/
|
|
313
|
+
const defaultDir = configDir();
|
|
314
|
+
/**
|
|
315
|
+
* Where this invocation's `credentials.json` lives.
|
|
316
|
+
*
|
|
317
|
+
* When `--config-dir` was left at its default, an existing file in the legacy `neonctl`
|
|
318
|
+
* directory is used **in place**: an install that predates the rename keeps working, and its
|
|
319
|
+
* credentials are never duplicated into a second location where one copy could go stale while
|
|
320
|
+
* another tool still reads it.
|
|
321
|
+
*
|
|
322
|
+
* A `--config-dir` the user actually passed is used exactly as given. Falling back out of an
|
|
323
|
+
* explicitly chosen directory would defeat the reason for choosing it — a CI run pointed at a
|
|
324
|
+
* scratch directory must never pick up a developer's real credentials.
|
|
325
|
+
*/
|
|
326
|
+
const credentialsPath = (dir) => resolveConfigFile(CREDENTIALS_FILE, dir === defaultDir ? {} : { dir }).path;
|
|
327
|
+
/**
|
|
328
|
+
* Whether a credentials file is one the CLI created, rather than a path a profile adopted.
|
|
329
|
+
*
|
|
330
|
+
* Anything that deletes a credential has to ask this first. A profile entry may point anywhere —
|
|
331
|
+
* that is what makes adopting an existing directory a one-line edit — and a file we did not
|
|
332
|
+
* create is not ours to remove.
|
|
333
|
+
*/
|
|
334
|
+
const isInsideConfigDir = (configDirectory, file) => `${resolve(file)}/`.startsWith(`${resolve(configDirectory)}/`);
|
|
335
|
+
/**
|
|
336
|
+
* Whether a credentials file is one the CLI owns, counting the legacy `neonctl` directory.
|
|
337
|
+
*
|
|
338
|
+
* {@link credentialsPath} deliberately reads an existing legacy file in place rather than
|
|
339
|
+
* migrating it, so for a default config directory that file is ours even though it sits outside
|
|
340
|
+
* `neon/`. Judging ownership on the current directory alone would call an install that predates
|
|
341
|
+
* the rename "adopted".
|
|
342
|
+
*/
|
|
343
|
+
const isOwnedCredentialPath = (configDirectory, file) => {
|
|
344
|
+
if (isInsideConfigDir(configDirectory, file)) return true;
|
|
345
|
+
if (configDirectory !== defaultDir) return false;
|
|
346
|
+
const legacy = legacyConfigDir();
|
|
347
|
+
return legacy !== void 0 && isInsideConfigDir(legacy, file);
|
|
348
|
+
};
|
|
349
|
+
//#endregion
|
|
350
|
+
//#region ../../internals/cli-core/dist/secure_file.js
|
|
351
|
+
/**
|
|
352
|
+
* Write a secret to disk owner-only, by creating a temporary file in the same directory and
|
|
353
|
+
* renaming it over the target.
|
|
354
|
+
*
|
|
355
|
+
* The rename is what makes this correct rather than merely tidy. `writeFileSync`'s `mode`
|
|
356
|
+
* applies only when it *creates* the file, so writing over an existing credentials file
|
|
357
|
+
* leaves whatever permissions it already had — a file created `0700` by an older release
|
|
358
|
+
* stays `0700` forever, and one created before a umask change stays world-readable. Renaming
|
|
359
|
+
* a fresh inode into place means every write lands at {@link SECRET_FILE_MODE}, so the
|
|
360
|
+
* permissions repair themselves instead of being inherited.
|
|
361
|
+
*
|
|
362
|
+
* It also closes the window where a reader could see the file at default permissions: the
|
|
363
|
+
* temporary file is created `0600` *before* it holds the secret's final name, and `rename`
|
|
364
|
+
* is atomic within a directory, so there is no moment at which the target is readable by
|
|
365
|
+
* anyone else and no moment at which it is half-written.
|
|
366
|
+
*
|
|
367
|
+
* The temporary name carries the pid so two processes writing at once cannot collide on it.
|
|
368
|
+
*/
|
|
369
|
+
const writeSecretFile = (path, contents) => {
|
|
370
|
+
const directory = dirname(path);
|
|
371
|
+
const temporary = join(directory, `.${basename(path)}.${process.pid}.${Date.now()}.tmp`);
|
|
372
|
+
try {
|
|
373
|
+
writeFileSync(temporary, contents, {
|
|
374
|
+
encoding: "utf8",
|
|
375
|
+
mode: 384
|
|
376
|
+
});
|
|
377
|
+
renameSync(temporary, path);
|
|
378
|
+
} catch (err) {
|
|
379
|
+
try {
|
|
380
|
+
unlinkSync(temporary);
|
|
381
|
+
} catch {}
|
|
382
|
+
throw err;
|
|
383
|
+
}
|
|
384
|
+
};
|
|
385
|
+
//#endregion
|
|
386
|
+
//#region ../../internals/cli-core/dist/profiles.js
|
|
387
|
+
/**
|
|
388
|
+
* Pointer-only profiles avoid mirrored credentials and persistent active-profile
|
|
389
|
+
* state while preserving existing single-account and legacy-directory installs.
|
|
390
|
+
*/
|
|
391
|
+
const PROFILES_FILE = "profiles.json";
|
|
392
|
+
const KEYRING_CREDENTIALS = "keyring";
|
|
393
|
+
const isKeyringPointer = (credentials) => credentials === KEYRING_CREDENTIALS;
|
|
394
|
+
/** The implicit profile. Backed by plain `credentials.json`, with or without a profiles file. */
|
|
395
|
+
const DEFAULT_PROFILE = "DEFAULT";
|
|
396
|
+
/** Profile names become part of a filename, so keep them boring. */
|
|
397
|
+
const NAME_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
|
|
398
|
+
const locationOf = (profile) => profile.storage === "keyring" ? {
|
|
399
|
+
profile: profile.name,
|
|
400
|
+
storage: CRED_STORAGE_KEYRING
|
|
401
|
+
} : {
|
|
402
|
+
profile: profile.name,
|
|
403
|
+
storage: CRED_STORAGE_FILE,
|
|
404
|
+
path: profile.credentialsPath
|
|
405
|
+
};
|
|
406
|
+
/** Where `profiles.json` lives for this config directory (whether or not it exists yet). */
|
|
407
|
+
const profilesFilePath = (dir) => resolveConfigFile(PROFILES_FILE, dir === defaultDir ? {} : { dir }).path;
|
|
408
|
+
/**
|
|
409
|
+
* Read and classify `profiles.json` without deciding what to do about it.
|
|
410
|
+
*
|
|
411
|
+
* Entry keys and shapes are validated here rather than at each use. A key is a profile name,
|
|
412
|
+
* and a name that `assertValidProfileName` would reject cannot have been written by this CLI —
|
|
413
|
+
* it would travel into error messages as a recovery command nobody can run, and into a
|
|
414
|
+
* `credentials.<name>.json` filename.
|
|
415
|
+
*/
|
|
416
|
+
const inspectProfiles = (dir) => {
|
|
417
|
+
const path = profilesFilePath(dir);
|
|
418
|
+
if (!existsSync(path)) return { kind: "absent" };
|
|
419
|
+
const broken = (why) => ({
|
|
420
|
+
kind: "unusable",
|
|
421
|
+
reason: `${path} could not be read as a profiles file: ${why}`
|
|
422
|
+
});
|
|
423
|
+
let contents;
|
|
424
|
+
try {
|
|
425
|
+
contents = readFileSync(path, "utf8");
|
|
426
|
+
} catch (err) {
|
|
427
|
+
const code = err.code;
|
|
428
|
+
return broken(code ? `reading it failed with ${code}` : "reading it failed");
|
|
429
|
+
}
|
|
430
|
+
let parsed;
|
|
431
|
+
try {
|
|
432
|
+
parsed = JSON.parse(contents);
|
|
433
|
+
} catch {
|
|
434
|
+
return broken("it is not valid JSON");
|
|
435
|
+
}
|
|
436
|
+
if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) return broken("it does not contain an object");
|
|
437
|
+
const profiles = parsed.profiles;
|
|
438
|
+
if (profiles === null || typeof profiles !== "object" || Array.isArray(profiles)) return broken("it has no `profiles` object");
|
|
439
|
+
for (const [name, entry] of Object.entries(profiles)) {
|
|
440
|
+
if (!NAME_PATTERN.test(name)) return broken(`"${name}" is not a valid profile name`);
|
|
441
|
+
if (entry === null || typeof entry !== "object" || typeof entry.credentials !== "string" || entry.credentials.trim() === "") return broken(`profile "${name}" has no \`credentials\` pointer`);
|
|
442
|
+
}
|
|
443
|
+
return {
|
|
444
|
+
kind: "ok",
|
|
445
|
+
file: {
|
|
446
|
+
version: 1,
|
|
447
|
+
profiles
|
|
448
|
+
}
|
|
449
|
+
};
|
|
450
|
+
};
|
|
451
|
+
/**
|
|
452
|
+
* Read `profiles.json`, or `null` when there is nothing usable there.
|
|
453
|
+
*
|
|
454
|
+
* A malformed file is reported through `onWarn` and treated as absent, because for a *read* the
|
|
455
|
+
* worst case is a named profile turning up missing, which is recoverable — whereas throwing
|
|
456
|
+
* would lock the user out of `neon auth` itself. Writing is the opposite: see
|
|
457
|
+
* {@link upsertProfile}, which refuses rather than rebuilding a file it cannot read.
|
|
458
|
+
*/
|
|
459
|
+
const readProfiles = (dir, onWarn = () => {}) => {
|
|
460
|
+
const read = inspectProfiles(dir);
|
|
461
|
+
if (read.kind === "ok") return read.file;
|
|
462
|
+
if (read.kind === "unusable") onWarn(read.reason);
|
|
463
|
+
return null;
|
|
464
|
+
};
|
|
465
|
+
/** Resolve a profile to an absolute credentials path. Throws when a named profile is unknown. */
|
|
466
|
+
const resolveProfile = (dir, name) => {
|
|
467
|
+
const read = inspectProfiles(dir);
|
|
468
|
+
if (read.kind === "unusable") throw new Error(`${read.reason}. Fix or delete the file — every profile is defined in it.`);
|
|
469
|
+
const file = read.kind === "ok" ? read.file : null;
|
|
470
|
+
const entry = file?.profiles[name];
|
|
471
|
+
if (entry) {
|
|
472
|
+
if (isKeyringPointer(entry.credentials)) return {
|
|
473
|
+
name,
|
|
474
|
+
storage: CRED_STORAGE_KEYRING,
|
|
475
|
+
...entry.label ? { label: entry.label } : {},
|
|
476
|
+
...entry.userId ? { userId: entry.userId } : {},
|
|
477
|
+
declared: true
|
|
478
|
+
};
|
|
479
|
+
return {
|
|
480
|
+
name,
|
|
481
|
+
storage: CRED_STORAGE_FILE,
|
|
482
|
+
credentialsPath: resolveEntryPath(dir, entry.credentials),
|
|
483
|
+
...entry.label ? { label: entry.label } : {},
|
|
484
|
+
...entry.userId ? { userId: entry.userId } : {},
|
|
485
|
+
declared: true
|
|
486
|
+
};
|
|
487
|
+
}
|
|
488
|
+
if (name === "DEFAULT") return {
|
|
489
|
+
name,
|
|
490
|
+
storage: CRED_STORAGE_FILE,
|
|
491
|
+
credentialsPath: credentialsPath(dir),
|
|
492
|
+
declared: false
|
|
493
|
+
};
|
|
494
|
+
const known = file ? Object.keys(file.profiles).join(", ") : DEFAULT_PROFILE;
|
|
495
|
+
throw new Error(`Unknown profile "${name}". Known profiles: ${known}. Create it with \`neon profile create ${name}\`.`);
|
|
496
|
+
};
|
|
497
|
+
const locationForName = (dir, name) => locationOf(resolveProfile(dir, name));
|
|
498
|
+
const resolveEntryPath = (dir, entry) => isAbsolute(entry) ? entry : resolve(profilesDir(dir), entry);
|
|
499
|
+
/** `profiles.json` may sit in the legacy directory, so entries resolve against its own dir. */
|
|
500
|
+
const profilesDir = (dir) => resolve(profilesFilePath(dir), "..");
|
|
501
|
+
//#endregion
|
|
502
|
+
//#region ../../internals/cli-core/dist/auth_selection.js
|
|
503
|
+
const selectCredential = ({ apiKeyFlag, profileFlag, apiKeyEnv, profileEnv }) => {
|
|
504
|
+
const flagKey = nonEmpty$2(apiKeyFlag);
|
|
505
|
+
const flagProfile = nonEmpty$2(profileFlag);
|
|
506
|
+
if (flagKey !== void 0 && flagProfile !== void 0) throw new Error("Pass either --api-key or --profile, not both. --api-key supplies a credential directly; --profile selects a stored one.");
|
|
507
|
+
if (flagKey !== void 0) return {
|
|
508
|
+
source: "explicit-api-key",
|
|
509
|
+
apiKey: flagKey
|
|
510
|
+
};
|
|
511
|
+
if (flagProfile !== void 0) return {
|
|
512
|
+
source: "profile",
|
|
513
|
+
profile: flagProfile,
|
|
514
|
+
explicit: true
|
|
515
|
+
};
|
|
516
|
+
const envKey = nonEmpty$2(apiKeyEnv);
|
|
517
|
+
const envProfile = nonEmpty$2(profileEnv);
|
|
518
|
+
if (envKey !== void 0) return {
|
|
519
|
+
source: "ambient-api-key",
|
|
520
|
+
apiKey: envKey,
|
|
521
|
+
...envProfile !== void 0 ? { ignoredProfile: envProfile } : {}
|
|
522
|
+
};
|
|
523
|
+
return {
|
|
524
|
+
source: "profile",
|
|
525
|
+
profile: envProfile ?? "DEFAULT",
|
|
526
|
+
explicit: envProfile !== void 0
|
|
527
|
+
};
|
|
528
|
+
};
|
|
529
|
+
/** The warning for an ambient key that displaced an ambient profile, or `null`. */
|
|
530
|
+
const displacedProfileWarning = (selection) => selection.source === "ambient-api-key" && selection.ignoredProfile !== void 0 ? `NEON_API_KEY is set, so profile "${selection.ignoredProfile}" from NEON_PROFILE was ignored. Pass --profile ${selection.ignoredProfile} to use it instead.` : null;
|
|
531
|
+
function nonEmpty$2(value) {
|
|
532
|
+
if (typeof value !== "string") return void 0;
|
|
533
|
+
const trimmed = value.trim();
|
|
534
|
+
return trimmed === "" ? void 0 : trimmed;
|
|
535
|
+
}
|
|
536
|
+
//#endregion
|
|
537
|
+
//#region ../../internals/cli-core/dist/credentials.js
|
|
538
|
+
/**
|
|
539
|
+
* # Stored credentials — one file per account, two kinds
|
|
540
|
+
*
|
|
541
|
+
* A profile points at exactly one credentials file (see `./profiles.ts`), and that file says
|
|
542
|
+
* what kind of credential it holds. Adding API-key support this way rather than adding a
|
|
543
|
+
* second pointer to `profiles.json` keeps a profile what it already was — one name, one path
|
|
544
|
+
* — and means `profiles.json` needs no schema change at all.
|
|
545
|
+
*
|
|
546
|
+
* ```json
|
|
547
|
+
* // oauth: every file written before this existed. An absent `type` means this.
|
|
548
|
+
* { "access_token": "…", "refresh_token": "…", "expires_at": 1786…, "user_id": "…" }
|
|
549
|
+
*
|
|
550
|
+
* // api_key, stored by `neon profile create --api-key`
|
|
551
|
+
* { "type": "api_key", "api_key": "napi_…", "user_id": "…" }
|
|
552
|
+
*
|
|
553
|
+
* // api_key minted by `--mint --org-id`, which records the scope it was issued at
|
|
554
|
+
* { "type": "api_key", "api_key": "napi_…", "key_id": 123, "org_id": "org-…" }
|
|
555
|
+
* ```
|
|
556
|
+
*
|
|
557
|
+
* ## One profile, one kind
|
|
558
|
+
*
|
|
559
|
+
* A credentials file holds an API key or an OAuth session, never both, and `type` states
|
|
560
|
+
* which. An earlier draft let the two coexist — the idea being that a key could keep the
|
|
561
|
+
* session it was minted from and so rotate without a browser. It did not survive review, for
|
|
562
|
+
* two reasons that are worth recording so nobody rebuilds it:
|
|
563
|
+
*
|
|
564
|
+
* 1. **It never worked.** The resolver returned the key without testing it, so a revoked key
|
|
565
|
+
* failed to mint and never fell back to the session sitting beside it.
|
|
566
|
+
* 2. **It could mix accounts.** Nothing compared the identity of the credential being written
|
|
567
|
+
* with the one already there, so a profile could hold one account's session and another's
|
|
568
|
+
* key, told apart only by a single string. Flip or lose `type` and the profile silently
|
|
569
|
+
* becomes a different person.
|
|
570
|
+
*
|
|
571
|
+
* Recovery from a dead key is therefore one browser login — `neon profile create <name>
|
|
572
|
+
* --mint` — which is what the retained session was supposed to save and never did.
|
|
573
|
+
*
|
|
574
|
+
* ## Older releases
|
|
575
|
+
*
|
|
576
|
+
* A CLI predating this reads the pointer, finds no `type` it understands, ignores it, and
|
|
577
|
+
* looks for `access_token`. An `api_key` profile has none, so an older release falls through
|
|
578
|
+
* to its browser login rather than crashing. That it does not crash is why `credentials`
|
|
579
|
+
* stays a required pointer: an entry without one makes 2.41 and 2.42 throw
|
|
580
|
+
* `ERR_INVALID_ARG_TYPE` from `resolveEntryPath`.
|
|
581
|
+
*/
|
|
582
|
+
const OAUTH = "oauth";
|
|
583
|
+
const API_KEY = "api_key";
|
|
584
|
+
const credentialLabel = (at) => at.storage === "keyring" ? `the OS keyring item for profile "${at.profile}"` : at.path;
|
|
585
|
+
/**
|
|
586
|
+
* Which credential in this file authenticates, by declaration alone.
|
|
587
|
+
*
|
|
588
|
+
* An unrecognised `type` throws rather than falling back to `oauth`. A file we cannot
|
|
589
|
+
* interpret is a misconfiguration the user has to see: treating it as OAuth would send them
|
|
590
|
+
* to a browser login that silently replaces a credential they meant to keep, and treating it
|
|
591
|
+
* as an API key would authenticate with whatever `api_key` happened to be there.
|
|
592
|
+
*
|
|
593
|
+
* This deliberately does not check that an `api_key` file has a key — `neon profile list`
|
|
594
|
+
* needs the kind of a file it is not about to authenticate with, and must be able to report a
|
|
595
|
+
* broken one rather than throwing halfway through a table.
|
|
596
|
+
*/
|
|
597
|
+
const credentialKind = (credentials, at, store = "file") => {
|
|
598
|
+
const declared = credentials.type;
|
|
599
|
+
if (declared === void 0 || declared === "oauth") return OAUTH;
|
|
600
|
+
if (declared === "api_key") return API_KEY;
|
|
601
|
+
throw new Error(`${credentialLabel(at)} declares a "type" this version does not understand. Expected "${OAUTH}" or "${API_KEY}". ${credentialsRepairHint(at, store)}`);
|
|
602
|
+
};
|
|
603
|
+
const credentialsRepairHint = (at, store = "file") => store === "keyring" ? `Replace it deliberately with \`neon profile create ${at.profile}\`, or remove the profile with \`neon profile remove ${at.profile}\`.` : `Replace it deliberately with \`neon profile create ${at.profile}\`, or delete the file.`;
|
|
604
|
+
/**
|
|
605
|
+
* Resolve what to authenticate with, validating that the declared kind is actually usable.
|
|
606
|
+
*
|
|
607
|
+
* An `api_key` file with no key is a hard error rather than a fall-through to OAuth: the user
|
|
608
|
+
* asked for a key, and quietly opening a browser instead would replace the credential they
|
|
609
|
+
* were trying to fix.
|
|
610
|
+
*/
|
|
611
|
+
const interpretCredentials = (credentials, at, store = "file") => {
|
|
612
|
+
if (credentialKind(credentials, at, store) === "oauth") return { kind: OAUTH };
|
|
613
|
+
const apiKey = nonEmpty$1(credentials.api_key);
|
|
614
|
+
if (apiKey === void 0) throw new Error(`${credentialLabel(at)} declares "type": "${API_KEY}" but has no "api_key" value. ${credentialsRepairHint(at, store)}`);
|
|
615
|
+
return {
|
|
616
|
+
kind: API_KEY,
|
|
617
|
+
apiKey
|
|
618
|
+
};
|
|
619
|
+
};
|
|
620
|
+
/**
|
|
621
|
+
* Read and classify a credentials file, without deciding what to do about it.
|
|
622
|
+
*
|
|
623
|
+
* A permission or I/O error still throws: there may be a perfectly good credential here that
|
|
624
|
+
* we cannot see, and treating that as absent would send the user to a browser login that
|
|
625
|
+
* overwrites it.
|
|
626
|
+
*/
|
|
627
|
+
/** Discard parser details because V8 may quote secret material near a syntax error. */
|
|
628
|
+
const parseCredentialsJson = (contents, label) => {
|
|
629
|
+
let parsed;
|
|
630
|
+
try {
|
|
631
|
+
parsed = JSON.parse(contents);
|
|
632
|
+
} catch {
|
|
633
|
+
return {
|
|
634
|
+
kind: "unusable",
|
|
635
|
+
reason: `${label} is not valid JSON, so the credential in it cannot be read`
|
|
636
|
+
};
|
|
637
|
+
}
|
|
638
|
+
if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) return {
|
|
639
|
+
kind: "unusable",
|
|
640
|
+
reason: `${label} does not contain a credentials object`
|
|
641
|
+
};
|
|
642
|
+
return {
|
|
643
|
+
kind: "ok",
|
|
644
|
+
credentials: parsed
|
|
645
|
+
};
|
|
646
|
+
};
|
|
647
|
+
const inspectCredentials = (path) => {
|
|
648
|
+
let contents;
|
|
649
|
+
try {
|
|
650
|
+
contents = readFileSync(path, "utf8");
|
|
651
|
+
} catch (err) {
|
|
652
|
+
if (err.code === "ENOENT") return { kind: "absent" };
|
|
653
|
+
throw err;
|
|
654
|
+
}
|
|
655
|
+
return parseCredentialsJson(contents, path);
|
|
656
|
+
};
|
|
657
|
+
/**
|
|
658
|
+
* The credential at `path`, or `null` when the file is not there.
|
|
659
|
+
*
|
|
660
|
+
* A damaged file is an error, not an absence. Treating it as absent — which is what this used to
|
|
661
|
+
* do — meant any read-only command could repair it by starting a browser sign-in and overwriting
|
|
662
|
+
* it, **possibly as a different account**, with the user never having asked for a repair and no
|
|
663
|
+
* way back to whatever was in the file. Failing here costs one deliberate command; the message
|
|
664
|
+
* names it.
|
|
665
|
+
*
|
|
666
|
+
* `profile list` and telemetry use {@link inspectCredentials} instead, because describing a
|
|
667
|
+
* broken credential is not the same as using one.
|
|
668
|
+
*/
|
|
669
|
+
const readCredentials = (at) => {
|
|
670
|
+
const read = inspectCredentials(at.path);
|
|
671
|
+
if (read.kind === "unusable") throw new Error(`${read.reason}. ${credentialsRepairHint(at)}`);
|
|
672
|
+
return read.kind === "ok" ? read.credentials : null;
|
|
673
|
+
};
|
|
674
|
+
const writeCredentials = (path, credentials) => {
|
|
675
|
+
writeSecretFile(path, JSON.stringify(credentials));
|
|
676
|
+
};
|
|
677
|
+
function nonEmpty$1(value) {
|
|
678
|
+
if (typeof value !== "string") return void 0;
|
|
679
|
+
const trimmed = value.trim();
|
|
680
|
+
return trimmed === "" ? void 0 : trimmed;
|
|
681
|
+
}
|
|
682
|
+
//#endregion
|
|
683
|
+
//#region ../../internals/cli-core/dist/credential_store.js
|
|
684
|
+
const KEYRING_SERVICE = "com.neon.neon-cli";
|
|
685
|
+
/** Hashing the resolved profiles directory isolates config roots while keeping profile names visible. */
|
|
686
|
+
const keyringAccount = (configDir, profile) => `cli:${createHash("sha256").update(dirname(profilesFilePath(configDir))).digest("hex")}:${profile}`;
|
|
687
|
+
var KeyringUnavailableError = class extends Error {
|
|
688
|
+
constructor(profile, kind = "read") {
|
|
689
|
+
const loaded = "This CLI cannot use the OS keyring.";
|
|
690
|
+
super(profile === void 0 ? `${loaded} Drop \`--keyring\` to keep the credential in a file.` : kind === "write" ? `${loaded} Remove the profile with \`neon profile remove ${profile} --yes\`.` : `${loaded} Use --api-key or NEON_API_KEY. If this is a standalone neon binary, use the npm-installed neon instead. To reset the profile: \`neon profile remove ${profile} --yes\`.`);
|
|
691
|
+
this.name = "KeyringUnavailableError";
|
|
692
|
+
}
|
|
693
|
+
};
|
|
694
|
+
var KeyringUnreadableError = class extends Error {
|
|
695
|
+
constructor(profile) {
|
|
696
|
+
const replace = `\`neon auth --profile ${profile}\``;
|
|
697
|
+
super(`Could not read the OS keyring item for profile "${profile}". Unlock the keyring and retry, or run ${replace}. To reset the profile: \`neon profile remove ${profile} --yes\`.`);
|
|
698
|
+
this.name = "KeyringUnreadableError";
|
|
699
|
+
}
|
|
700
|
+
};
|
|
701
|
+
var KeyringClearError = class extends Error {
|
|
702
|
+
constructor(profile, kind = "visible") {
|
|
703
|
+
const recovery = `\`neon profile remove ${profile} --yes\``;
|
|
704
|
+
super(kind === "unconfirmed" ? `Could not confirm the OS keyring item for profile "${profile}" is gone. The OS store does not distinguish a missing item from denied access. Unlock the OS keyring and retry, or reset the profile with ${recovery} (a leftover may remain; it is unused once the profile is gone).` : `Could not clear the OS keyring item for profile "${profile}". Unlock the OS keyring and retry, or reset the profile with ${recovery} (a leftover may remain; it is unused once the profile is gone).`);
|
|
705
|
+
this.name = "KeyringClearError";
|
|
706
|
+
}
|
|
707
|
+
};
|
|
708
|
+
const deleteFileIfPresent = (path) => {
|
|
709
|
+
if (!existsSync(path)) return false;
|
|
710
|
+
rmSync(path);
|
|
711
|
+
return true;
|
|
712
|
+
};
|
|
713
|
+
const inspectKeyringItem = (keyring, account, label) => {
|
|
714
|
+
if (keyring === null) return { kind: "absent" };
|
|
715
|
+
let raw;
|
|
716
|
+
try {
|
|
717
|
+
raw = keyring.get(KEYRING_SERVICE, account);
|
|
718
|
+
} catch {
|
|
719
|
+
return { kind: "absent" };
|
|
720
|
+
}
|
|
721
|
+
if (raw === null) return { kind: "absent" };
|
|
722
|
+
return parseCredentialsJson(raw, label);
|
|
723
|
+
};
|
|
724
|
+
const createCredentialStore = (dir, options = {}) => {
|
|
725
|
+
const keyring = options.keyring ?? null;
|
|
726
|
+
const accountFor = (profile) => keyringAccount(dir, profile);
|
|
727
|
+
const assertKeyringWritable = (profile) => {
|
|
728
|
+
if (keyring === null) throw new KeyringUnavailableError(profile, "write");
|
|
729
|
+
};
|
|
730
|
+
const setKeyringOrRollback = (profile, credentials) => {
|
|
731
|
+
assertKeyringWritable(profile);
|
|
732
|
+
const kr = keyring;
|
|
733
|
+
if (kr === null) throw new KeyringUnavailableError(profile, "write");
|
|
734
|
+
const account = accountFor(profile);
|
|
735
|
+
const label = `profile "${profile}"`;
|
|
736
|
+
let previous = null;
|
|
737
|
+
try {
|
|
738
|
+
previous = kr.get(KEYRING_SERVICE, account);
|
|
739
|
+
} catch {
|
|
740
|
+
previous = null;
|
|
741
|
+
}
|
|
742
|
+
try {
|
|
743
|
+
kr.set(KEYRING_SERVICE, account, JSON.stringify(credentials));
|
|
744
|
+
} catch {
|
|
745
|
+
throw new KeyringUnavailableError();
|
|
746
|
+
}
|
|
747
|
+
try {
|
|
748
|
+
if (kr.get("com.neon.neon-cli", account) === null) throw new Error(`Wrote credentials to the OS keyring for ${label} but could not read them back.`);
|
|
749
|
+
} catch (err) {
|
|
750
|
+
if (previous !== null) {
|
|
751
|
+
try {
|
|
752
|
+
kr.set(KEYRING_SERVICE, account, previous);
|
|
753
|
+
} catch {
|
|
754
|
+
throw new KeyringClearError(profile, "visible");
|
|
755
|
+
}
|
|
756
|
+
let restored = null;
|
|
757
|
+
try {
|
|
758
|
+
restored = kr.get(KEYRING_SERVICE, account);
|
|
759
|
+
} catch {
|
|
760
|
+
restored = null;
|
|
761
|
+
}
|
|
762
|
+
if (restored === null) throw new KeyringClearError(profile, "visible");
|
|
763
|
+
}
|
|
764
|
+
throw err instanceof Error ? err : new Error(String(err));
|
|
765
|
+
}
|
|
766
|
+
};
|
|
767
|
+
const removeKeyringItem = (profile, required, account = accountFor(profile)) => {
|
|
768
|
+
if (keyring === null) {
|
|
769
|
+
if (required) throw new KeyringUnavailableError(profile, "write");
|
|
770
|
+
return "unconfirmed";
|
|
771
|
+
}
|
|
772
|
+
let raw;
|
|
773
|
+
try {
|
|
774
|
+
raw = keyring.get(KEYRING_SERVICE, account);
|
|
775
|
+
} catch (err) {
|
|
776
|
+
if (!required) return "unconfirmed";
|
|
777
|
+
throw err instanceof Error ? err : new Error(String(err));
|
|
778
|
+
}
|
|
779
|
+
if (raw === null) {
|
|
780
|
+
if (required) throw new KeyringClearError(profile, "unconfirmed");
|
|
781
|
+
return "unconfirmed";
|
|
782
|
+
}
|
|
783
|
+
let deleted;
|
|
784
|
+
try {
|
|
785
|
+
deleted = keyring.delete(KEYRING_SERVICE, account);
|
|
786
|
+
} catch (err) {
|
|
787
|
+
if (!required) return "unconfirmed";
|
|
788
|
+
throw err instanceof Error ? err : new Error(String(err));
|
|
789
|
+
}
|
|
790
|
+
let still;
|
|
791
|
+
try {
|
|
792
|
+
still = keyring.get(KEYRING_SERVICE, account);
|
|
793
|
+
} catch (err) {
|
|
794
|
+
if (!required) return "unconfirmed";
|
|
795
|
+
throw err instanceof Error ? err : new Error(String(err));
|
|
796
|
+
}
|
|
797
|
+
if (!deleted || still !== null) {
|
|
798
|
+
if (required) throw new KeyringClearError(profile, "visible");
|
|
799
|
+
return "left";
|
|
800
|
+
}
|
|
801
|
+
return "cleared";
|
|
802
|
+
};
|
|
803
|
+
const inspect = (at) => {
|
|
804
|
+
if (at.storage === "keyring") {
|
|
805
|
+
if (keyring === null) return {
|
|
806
|
+
file: "unreadable",
|
|
807
|
+
storage: CRED_STORAGE_KEYRING,
|
|
808
|
+
credentials: null,
|
|
809
|
+
reason: new KeyringUnavailableError(at.profile).message
|
|
810
|
+
};
|
|
811
|
+
const keyringRead = inspectKeyringItem(keyring, accountFor(at.profile), credentialLabel(at));
|
|
812
|
+
if (keyringRead.kind === "ok") return {
|
|
813
|
+
file: "ok",
|
|
814
|
+
storage: CRED_STORAGE_KEYRING,
|
|
815
|
+
credentials: keyringRead.credentials
|
|
816
|
+
};
|
|
817
|
+
if (keyringRead.kind === "unusable") return {
|
|
818
|
+
file: "unreadable",
|
|
819
|
+
storage: CRED_STORAGE_KEYRING,
|
|
820
|
+
credentials: null,
|
|
821
|
+
reason: keyringRead.reason
|
|
822
|
+
};
|
|
823
|
+
return {
|
|
824
|
+
file: "unreadable",
|
|
825
|
+
storage: CRED_STORAGE_KEYRING,
|
|
826
|
+
credentials: null,
|
|
827
|
+
reason: new KeyringUnreadableError(at.profile).message
|
|
828
|
+
};
|
|
829
|
+
}
|
|
830
|
+
const fileRead = inspectCredentials(at.path);
|
|
831
|
+
return {
|
|
832
|
+
file: fileRead.kind === "ok" ? "ok" : fileRead.kind === "absent" ? "missing" : "invalid",
|
|
833
|
+
storage: CRED_STORAGE_FILE,
|
|
834
|
+
credentials: fileRead.kind === "ok" ? fileRead.credentials : null,
|
|
835
|
+
...fileRead.kind === "unusable" ? { reason: fileRead.reason } : {}
|
|
836
|
+
};
|
|
837
|
+
};
|
|
838
|
+
const read = (at) => {
|
|
839
|
+
if (at.storage === "keyring") {
|
|
840
|
+
if (keyring === null) throw new KeyringUnavailableError(at.profile);
|
|
841
|
+
let raw;
|
|
842
|
+
try {
|
|
843
|
+
raw = keyring.get(KEYRING_SERVICE, accountFor(at.profile));
|
|
844
|
+
} catch {
|
|
845
|
+
throw new KeyringUnreadableError(at.profile);
|
|
846
|
+
}
|
|
847
|
+
if (raw === null) throw new KeyringUnreadableError(at.profile);
|
|
848
|
+
const parsed = parseCredentialsJson(raw, credentialLabel(at));
|
|
849
|
+
if (parsed.kind === "unusable") throw new Error(parsed.reason);
|
|
850
|
+
if (parsed.kind !== "ok") throw new KeyringUnreadableError(at.profile);
|
|
851
|
+
return {
|
|
852
|
+
credentials: parsed.credentials,
|
|
853
|
+
backend: CRED_STORAGE_KEYRING,
|
|
854
|
+
profile: at.profile
|
|
855
|
+
};
|
|
856
|
+
}
|
|
857
|
+
const credentials = readCredentials(at);
|
|
858
|
+
if (credentials === null) return null;
|
|
859
|
+
return {
|
|
860
|
+
credentials,
|
|
861
|
+
backend: CRED_STORAGE_FILE,
|
|
862
|
+
path: at.path,
|
|
863
|
+
profile: at.profile
|
|
864
|
+
};
|
|
865
|
+
};
|
|
866
|
+
const write = (at, credentials) => {
|
|
867
|
+
if (at.storage === "keyring") {
|
|
868
|
+
setKeyringOrRollback(at.profile, credentials);
|
|
869
|
+
return {
|
|
870
|
+
credentials,
|
|
871
|
+
backend: CRED_STORAGE_KEYRING,
|
|
872
|
+
profile: at.profile
|
|
873
|
+
};
|
|
874
|
+
}
|
|
875
|
+
writeCredentials(at.path, credentials);
|
|
876
|
+
return {
|
|
877
|
+
credentials,
|
|
878
|
+
backend: CRED_STORAGE_FILE,
|
|
879
|
+
path: at.path,
|
|
880
|
+
profile: at.profile
|
|
881
|
+
};
|
|
882
|
+
};
|
|
883
|
+
const del = (at, deleteOptions) => {
|
|
884
|
+
const required = deleteOptions?.required !== false;
|
|
885
|
+
if (at.storage === "keyring") return removeKeyringItem(at.profile, required, deleteOptions?.account);
|
|
886
|
+
if (!isOwnedCredentialPath(dir, at.path)) return "skipped";
|
|
887
|
+
return deleteFileIfPresent(at.path) ? "cleared" : "absent";
|
|
888
|
+
};
|
|
889
|
+
return {
|
|
890
|
+
inspect,
|
|
891
|
+
read,
|
|
892
|
+
write,
|
|
893
|
+
delete: del,
|
|
894
|
+
assertKeyringWritable
|
|
895
|
+
};
|
|
896
|
+
};
|
|
897
|
+
//#endregion
|
|
898
|
+
//#region src/lib/cli/keyring.ts
|
|
899
|
+
const isPackaged = () => process.pkg !== void 0;
|
|
900
|
+
const isMissingItem = (err) => {
|
|
901
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
902
|
+
return /no matching entry|not found|password not found/i.test(message);
|
|
903
|
+
};
|
|
904
|
+
const tryLoadKeyring = () => {
|
|
905
|
+
if (isPackaged()) return null;
|
|
906
|
+
try {
|
|
907
|
+
const { Entry } = createRequire(import.meta.url)(["@napi-rs", "keyring"].join("/"));
|
|
908
|
+
return {
|
|
909
|
+
get(service, account) {
|
|
910
|
+
try {
|
|
911
|
+
return new Entry(service, account).getPassword();
|
|
912
|
+
} catch (err) {
|
|
913
|
+
if (isMissingItem(err)) return null;
|
|
914
|
+
throw err;
|
|
915
|
+
}
|
|
916
|
+
},
|
|
917
|
+
set(service, account, password) {
|
|
918
|
+
new Entry(service, account).setPassword(password);
|
|
919
|
+
},
|
|
920
|
+
delete(service, account) {
|
|
921
|
+
try {
|
|
922
|
+
return new Entry(service, account).deletePassword();
|
|
923
|
+
} catch (err) {
|
|
924
|
+
if (isMissingItem(err)) return false;
|
|
925
|
+
throw err;
|
|
926
|
+
}
|
|
927
|
+
}
|
|
928
|
+
};
|
|
929
|
+
} catch {
|
|
930
|
+
return null;
|
|
931
|
+
}
|
|
932
|
+
};
|
|
933
|
+
//#endregion
|
|
934
|
+
//#region src/lib/cli/resolve-api-key.ts
|
|
935
|
+
/**
|
|
936
|
+
* Resolve the Neon API key for a `neon-env` CLI invocation.
|
|
937
|
+
*
|
|
938
|
+
* Precedence is the `neon` CLI's, from the same module: **an explicit flag beats an ambient
|
|
939
|
+
* environment variable.** `--api-key` and `--profile` together is an error; `--profile` beats
|
|
940
|
+
* `NEON_API_KEY`; `--api-key` beats `NEON_PROFILE`; two ambient sources resolve to the key.
|
|
941
|
+
*
|
|
942
|
+
* Sharing that decision rather than restating it is the point. An earlier version of this file
|
|
943
|
+
* checked `NEON_API_KEY` before the selected profile, so `NEON_API_KEY=… neon-env run --profile
|
|
944
|
+
* work` silently used the wrong account — the very bug this feature fixes in `neon`.
|
|
945
|
+
*
|
|
946
|
+
* The CLI owns the resolution because `@neon/config` and `@neon/env`'s root export are
|
|
947
|
+
* deliberately environment- and filesystem-agnostic: they accept an explicit `apiKey` and
|
|
948
|
+
* nothing else, so the ambient sources a *user* expects have to be read out here.
|
|
949
|
+
*/
|
|
950
|
+
function resolveApiKey(options) {
|
|
951
|
+
const env = options.env ?? process.env;
|
|
952
|
+
const selection = selectCredential({
|
|
953
|
+
...options.apiKey !== void 0 ? { apiKeyFlag: options.apiKey } : {},
|
|
954
|
+
...options.profile !== void 0 ? { profileFlag: options.profile } : {},
|
|
955
|
+
...env.NEON_API_KEY !== void 0 ? { apiKeyEnv: env.NEON_API_KEY } : {},
|
|
956
|
+
...env.NEON_PROFILE !== void 0 ? { profileEnv: env.NEON_PROFILE } : {}
|
|
957
|
+
});
|
|
958
|
+
const displaced = displacedProfileWarning(selection);
|
|
959
|
+
if (displaced !== null) (options.warn ?? ((message) => process.stderr.write(`${message}\n`)))(displaced);
|
|
960
|
+
if (selection.source !== "profile") return selection.apiKey;
|
|
961
|
+
return readStoredCredential(selection, env);
|
|
962
|
+
}
|
|
963
|
+
/**
|
|
964
|
+
* The credential stored for the selected profile.
|
|
965
|
+
*
|
|
966
|
+
* Two different situations, deliberately not merged. A **missing** credential under `DEFAULT` is
|
|
967
|
+
* the ordinary not-signed-in state and resolves to no key; under a profile the user named it is
|
|
968
|
+
* an error, because reporting a missing credential would hide that the real problem is the name
|
|
969
|
+
* they typed. A **damaged** credential is always an error: the file is there, it is not an
|
|
970
|
+
* absence, and no amount of signing in elsewhere explains it.
|
|
971
|
+
*/
|
|
972
|
+
function readStoredCredential(selection, env) {
|
|
973
|
+
const { profile, explicit } = selection;
|
|
974
|
+
/**
|
|
975
|
+
* An *absence* is only an error when the user named the profile. Not being signed in under
|
|
976
|
+
* `DEFAULT` is the ordinary state, and the library's `PLATFORM_MISSING_API_KEY` says it
|
|
977
|
+
* better than a stack trace.
|
|
978
|
+
*/
|
|
979
|
+
const absent = (reason) => {
|
|
980
|
+
if (explicit) throw new Error(reason);
|
|
981
|
+
};
|
|
982
|
+
const dir = configDir({ env });
|
|
983
|
+
let at;
|
|
984
|
+
try {
|
|
985
|
+
at = locationForName(dir, profile);
|
|
986
|
+
} catch (err) {
|
|
987
|
+
throw err instanceof Error ? err : new Error(String(err));
|
|
988
|
+
}
|
|
989
|
+
if (at.storage === "file" && profile === "DEFAULT" && readProfiles(dir)?.profiles["DEFAULT"] === void 0) at = {
|
|
990
|
+
...at,
|
|
991
|
+
path: resolveConfigFile("credentials.json", { env }).path
|
|
992
|
+
};
|
|
993
|
+
const loaded = createCredentialStore(configDir({ env }), { keyring: tryLoadKeyring() }).read(at);
|
|
994
|
+
if (loaded === null) return absent(`Profile "${profile}" has no stored credential at ${credentialLabel(at)}. Sign in with \`neon profile create ${profile}\`.`);
|
|
995
|
+
const credential = interpretCredentials(loaded.credentials, at, loaded.backend);
|
|
996
|
+
if (credential.kind === "api_key") return credential.apiKey;
|
|
997
|
+
const token = loaded.credentials.access_token;
|
|
998
|
+
if (typeof token === "string" && token.trim() !== "") return token.trim();
|
|
999
|
+
throw new Error(`Profile "${profile}" holds a browser sign-in with no usable token at ${credentialLabel(at)}. Sign in again with \`neon auth --profile ${profile}\`.`);
|
|
1000
|
+
}
|
|
1001
|
+
//#endregion
|
|
1002
|
+
//#region src/lib/cli/resolve-context.ts
|
|
1003
|
+
/**
|
|
1004
|
+
* Resolve `projectId` and `branch` for a CLI invocation. Precedence (each wins over the
|
|
1005
|
+
* next): explicit flag → `NEON_*` env var → `.neon[/project.json]` walked up from `cwd`.
|
|
1006
|
+
*
|
|
1007
|
+
* Returns the resolved values plus a list of human-readable reasons for any field that
|
|
1008
|
+
* could not be resolved (so the caller can render one combined error).
|
|
1009
|
+
*/
|
|
1010
|
+
function resolveContext(options) {
|
|
1011
|
+
const env = options.env ?? process.env;
|
|
1012
|
+
const file = findNeonFile(options.cwd);
|
|
1013
|
+
const projectId = nonEmpty(options.projectId) ?? nonEmpty(env.NEON_PROJECT_ID) ?? file?.projectId;
|
|
1014
|
+
const branch = nonEmpty(options.branch) ?? nonEmpty(env.NEON_BRANCH) ?? nonEmpty(env.NEON_BRANCH_ID) ?? file?.branch;
|
|
1015
|
+
const missing = [];
|
|
1016
|
+
if (!projectId) missing.push("project id — pass `--project-id`, set `NEON_PROJECT_ID`, or add `projectId` to `.neon` (run `npx neon link`).");
|
|
1017
|
+
if (!branch) missing.push("branch — pass `--branch`, set `NEON_BRANCH`/`NEON_BRANCH_ID`, or add `branch` to `.neon` (run `npx neon link` / `neon checkout <branch>`).");
|
|
1018
|
+
if (!projectId || !branch) return {
|
|
1019
|
+
ok: false,
|
|
1020
|
+
missing
|
|
1021
|
+
};
|
|
1022
|
+
return {
|
|
1023
|
+
ok: true,
|
|
1024
|
+
context: {
|
|
1025
|
+
projectId,
|
|
1026
|
+
branch
|
|
1027
|
+
}
|
|
1028
|
+
};
|
|
1029
|
+
}
|
|
1030
|
+
/**
|
|
1031
|
+
* Walk up from `cwd` looking for `.neon/project.json` (preferred) or `.neon` (neonctl
|
|
1032
|
+
* convention). Stops at the first `.git` directory or the home directory. Read-only.
|
|
1033
|
+
*/
|
|
1034
|
+
function findNeonFile(cwd) {
|
|
1035
|
+
let current = resolve(cwd);
|
|
1036
|
+
const stop = resolve(homedir());
|
|
1037
|
+
let lastSeen = null;
|
|
1038
|
+
while (true) {
|
|
1039
|
+
const parsed = readNeonFileAt(resolve(current, ".neon", "project.json")) ?? readNeonFileAt(resolve(current, ".neon"));
|
|
1040
|
+
if (parsed) return parsed;
|
|
1041
|
+
if (current === stop) return null;
|
|
1042
|
+
if (existsSync(resolve(current, ".git"))) return null;
|
|
1043
|
+
const parent = dirname(current);
|
|
1044
|
+
if (parent === current || parent === lastSeen) return null;
|
|
1045
|
+
lastSeen = current;
|
|
1046
|
+
current = parent;
|
|
1047
|
+
}
|
|
1048
|
+
}
|
|
1049
|
+
function readNeonFileAt(path) {
|
|
1050
|
+
if (!isFile(path)) return null;
|
|
1051
|
+
let raw;
|
|
1052
|
+
try {
|
|
1053
|
+
raw = readFileSync(path, "utf-8");
|
|
1054
|
+
} catch {
|
|
1055
|
+
return null;
|
|
1056
|
+
}
|
|
1057
|
+
let parsed;
|
|
1058
|
+
try {
|
|
1059
|
+
parsed = JSON.parse(raw);
|
|
1060
|
+
} catch {
|
|
1061
|
+
return null;
|
|
1062
|
+
}
|
|
1063
|
+
if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) return null;
|
|
1064
|
+
const obj = parsed;
|
|
1065
|
+
const out = {};
|
|
1066
|
+
if (typeof obj.projectId === "string" && obj.projectId !== "") out.projectId = obj.projectId;
|
|
1067
|
+
const branch = typeof obj.branch === "string" && obj.branch !== "" ? obj.branch : typeof obj.branchId === "string" && obj.branchId !== "" ? obj.branchId : void 0;
|
|
1068
|
+
if (branch) out.branch = branch;
|
|
1069
|
+
return out;
|
|
1070
|
+
}
|
|
1071
|
+
function isFile(path) {
|
|
1072
|
+
try {
|
|
1073
|
+
return statSync(path).isFile();
|
|
1074
|
+
} catch {
|
|
1075
|
+
return false;
|
|
1076
|
+
}
|
|
1077
|
+
}
|
|
1078
|
+
function nonEmpty(value) {
|
|
1079
|
+
if (typeof value !== "string") return void 0;
|
|
1080
|
+
const trimmed = value.trim();
|
|
1081
|
+
return trimmed === "" ? void 0 : trimmed;
|
|
1082
|
+
}
|
|
1083
|
+
//#endregion
|
|
1084
|
+
//#region src/lib/cli/commands.ts
|
|
1085
|
+
/** File `env run` reads to layer one-time auth keys. Matches the Vercel/Next.js convention. */
|
|
1086
|
+
const DEFAULT_ENV_FILE = ".env.local";
|
|
1087
|
+
/**
|
|
1088
|
+
* Implementation of `neon-env run -- <cmd...>`. Loads `neon.ts`, fetches the env from
|
|
1089
|
+
* Neon, then spawns the user-supplied command with the env vars injected on top of the
|
|
1090
|
+
* inherited `process.env`. Stdio is inherited so interactive dev servers keep working.
|
|
1091
|
+
* The parent process exits with the child's exit code.
|
|
1092
|
+
*/
|
|
1093
|
+
async function runEnvRun(options, ctx) {
|
|
1094
|
+
if (options.command.length === 0) return failure([
|
|
1095
|
+
"`env run` requires a command to spawn.",
|
|
1096
|
+
"Usage: neon-env run -- <command> [args...]",
|
|
1097
|
+
"Example: neon-env run -- npm run dev"
|
|
1098
|
+
].join("\n"));
|
|
1099
|
+
const resolved = resolveContext({
|
|
1100
|
+
cwd: ctx.cwd,
|
|
1101
|
+
...options.projectId ? { projectId: options.projectId } : {},
|
|
1102
|
+
...options.branch ? { branch: options.branch } : {}
|
|
1103
|
+
});
|
|
1104
|
+
if (!resolved.ok) return failure(["`env run` could not resolve the Neon project and branch:", ...resolved.missing.map((m) => ` - ${m}`)].join("\n"), 3);
|
|
1105
|
+
let injected;
|
|
1106
|
+
try {
|
|
1107
|
+
injected = await loadConfigAndFetchEnv(options, ctx, resolved.context);
|
|
1108
|
+
} catch (err) {
|
|
1109
|
+
return handleError(err);
|
|
1110
|
+
}
|
|
1111
|
+
const [executable, ...args] = options.command;
|
|
1112
|
+
return {
|
|
1113
|
+
exitCode: await spawnAndWait(executable, args, {
|
|
1114
|
+
cwd: ctx.cwd,
|
|
1115
|
+
env: {
|
|
1116
|
+
...process.env,
|
|
1117
|
+
...injected
|
|
1118
|
+
}
|
|
1119
|
+
}),
|
|
1120
|
+
stdout: "",
|
|
1121
|
+
stderr: ""
|
|
1122
|
+
};
|
|
1123
|
+
}
|
|
1124
|
+
/**
|
|
1125
|
+
* Implementation of `neon-env export`. Resolves the branch's Neon env the same way `run`
|
|
1126
|
+
* does (neon.ts policy + linked branch), then writes it to stdout — as dotenv lines or JSON —
|
|
1127
|
+
* instead of spawning a process, so other env tools can consume it. For example, varlock can
|
|
1128
|
+
* bulk-load it with `@setValuesBulk(exec("neon-env export --format json"), format=json)`.
|
|
1129
|
+
*/
|
|
1130
|
+
async function runEnvExport(options, ctx) {
|
|
1131
|
+
const resolved = resolveContext({
|
|
1132
|
+
cwd: ctx.cwd,
|
|
1133
|
+
...options.projectId ? { projectId: options.projectId } : {},
|
|
1134
|
+
...options.branch ? { branch: options.branch } : {}
|
|
1135
|
+
});
|
|
1136
|
+
if (!resolved.ok) return failure(["`env export` could not resolve the Neon project and branch:", ...resolved.missing.map((m) => ` - ${m}`)].join("\n"), 3);
|
|
1137
|
+
let entries;
|
|
1138
|
+
try {
|
|
1139
|
+
entries = await loadConfigAndFetchEnv(options, ctx, resolved.context);
|
|
1140
|
+
} catch (err) {
|
|
1141
|
+
return handleError(err);
|
|
1142
|
+
}
|
|
1143
|
+
return {
|
|
1144
|
+
exitCode: 0,
|
|
1145
|
+
stdout: options.format === "json" ? `${JSON.stringify(entries, null, 2)}\n` : toDotenv(entries),
|
|
1146
|
+
stderr: ""
|
|
1147
|
+
};
|
|
1148
|
+
}
|
|
1149
|
+
/** Render an env map as dotenv `KEY=value` lines, quoting values that need it. */
|
|
1150
|
+
function toDotenv(entries) {
|
|
1151
|
+
const lines = Object.entries(entries).map(([key, value]) => formatDotenvLine(key, value));
|
|
1152
|
+
return lines.length > 0 ? `${lines.join("\n")}\n` : "";
|
|
1153
|
+
}
|
|
1154
|
+
/**
|
|
1155
|
+
* Render a single `KEY=value` dotenv line, double-quoting (and escaping) values that contain
|
|
1156
|
+
* whitespace, `#`, quotes, or `=` so connection strings round-trip through dotenv parsers.
|
|
1157
|
+
*/
|
|
1158
|
+
function formatDotenvLine(key, value) {
|
|
1159
|
+
if (!/[\s#"'=]/.test(value)) return `${key}=${value}`;
|
|
1160
|
+
return `${key}="${value.replace(/\\/g, "\\\\").replace(/"/g, "\\\"")}"`;
|
|
1161
|
+
}
|
|
1162
|
+
/**
|
|
1163
|
+
* Load `neon.ts`, then resolve the branch env for the explicitly-resolved project + branch.
|
|
1164
|
+
* Layers `.env.local` (next to the config file) into the env source so re-runs keep the
|
|
1165
|
+
* one-time secrets the Neon API only returns once — the branch credential's, and any Auth
|
|
1166
|
+
* values a pre-`base_url` integration can no longer report. Uses
|
|
1167
|
+
* {@link fetchEnvReusingSecrets} rather than a bare `fetchEnv` so a run that already has a
|
|
1168
|
+
* working credential verifies and keeps it instead of minting another one per invocation.
|
|
1169
|
+
*/
|
|
1170
|
+
async function loadConfigAndFetchEnv(options, ctx, resolved) {
|
|
1171
|
+
const { config, resolvedPath } = await loadConfigFromFile({
|
|
1172
|
+
...options.configPath ? { path: options.configPath } : {},
|
|
1173
|
+
cwd: ctx.cwd
|
|
1174
|
+
});
|
|
1175
|
+
const envFileSource = join(dirname(resolvedPath), DEFAULT_ENV_FILE);
|
|
1176
|
+
const fileEnv = existsSync(envFileSource) ? parseEnvFile(readFileSync(envFileSource, "utf-8")) : {};
|
|
1177
|
+
const apiKey = resolveApiKey({
|
|
1178
|
+
...options.apiKey ? { apiKey: options.apiKey } : {},
|
|
1179
|
+
...options.profile ? { profile: options.profile } : {}
|
|
1180
|
+
});
|
|
1181
|
+
const { vars } = await fetchEnvReusingSecrets(config, {
|
|
1182
|
+
projectId: resolved.projectId,
|
|
1183
|
+
branch: resolved.branch,
|
|
1184
|
+
env: {
|
|
1185
|
+
...process.env,
|
|
1186
|
+
...fileEnv
|
|
1187
|
+
},
|
|
1188
|
+
...ctx.api ? { api: ctx.api } : {},
|
|
1189
|
+
...apiKey ? { apiKey } : {}
|
|
1190
|
+
});
|
|
1191
|
+
return vars;
|
|
1192
|
+
}
|
|
1193
|
+
/**
|
|
1194
|
+
* Spawn a child process with stdio inherited so dev servers stay interactive. Resolves
|
|
1195
|
+
* with the child's exit code (treating signal terminations as code 1 so the CLI surfaces
|
|
1196
|
+
* a non-zero exit consistently).
|
|
1197
|
+
*/
|
|
1198
|
+
function spawnAndWait(command, args, options) {
|
|
1199
|
+
return new Promise((resolve) => {
|
|
1200
|
+
const child = spawn(command, args, {
|
|
1201
|
+
cwd: options.cwd,
|
|
1202
|
+
env: options.env,
|
|
1203
|
+
stdio: "inherit"
|
|
1204
|
+
});
|
|
1205
|
+
child.on("error", (err) => {
|
|
1206
|
+
process.stderr.write(`neon-env run: failed to spawn '${command}': ${err.message}\n`);
|
|
1207
|
+
resolve(1);
|
|
1208
|
+
});
|
|
1209
|
+
child.on("exit", (code, signal) => {
|
|
1210
|
+
if (typeof code === "number") {
|
|
1211
|
+
resolve(code);
|
|
1212
|
+
return;
|
|
1213
|
+
}
|
|
1214
|
+
if (signal) {
|
|
1215
|
+
process.stderr.write(`neon-env run: child terminated by signal ${signal}\n`);
|
|
1216
|
+
resolve(1);
|
|
1217
|
+
return;
|
|
1218
|
+
}
|
|
1219
|
+
resolve(1);
|
|
1220
|
+
});
|
|
1221
|
+
});
|
|
1222
|
+
}
|
|
1223
|
+
function parseEnvFile(body) {
|
|
1224
|
+
const out = {};
|
|
1225
|
+
for (const line of body.split("\n")) {
|
|
1226
|
+
const parsed = parseEnvLine(line);
|
|
1227
|
+
if (parsed) out[parsed.key] = parsed.value;
|
|
1228
|
+
}
|
|
1229
|
+
return out;
|
|
1230
|
+
}
|
|
1231
|
+
function parseEnvLine(line) {
|
|
1232
|
+
const match = line.match(/^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/);
|
|
1233
|
+
const key = match?.[1];
|
|
1234
|
+
const rawValue = match?.[2];
|
|
1235
|
+
if (key === void 0 || rawValue === void 0) return null;
|
|
1236
|
+
return {
|
|
1237
|
+
key,
|
|
1238
|
+
value: unescapeEnvValue(rawValue.trim())
|
|
1239
|
+
};
|
|
1240
|
+
}
|
|
1241
|
+
function unescapeEnvValue(value) {
|
|
1242
|
+
if (value.length >= 2 && value.startsWith("\"") && value.endsWith("\"")) return value.slice(1, -1).replace(/\\"/g, "\"").replace(/\\\\/g, "\\");
|
|
1243
|
+
if (value.length >= 2 && value.startsWith("'") && value.endsWith("'")) return value.slice(1, -1);
|
|
1244
|
+
return value;
|
|
1245
|
+
}
|
|
1246
|
+
/**
|
|
1247
|
+
* Stable exit code per `PlatformError` code. Mirrors the table in the config package so
|
|
1248
|
+
* shell pipelines can branch on the specific failure mode without parsing free text.
|
|
1249
|
+
*/
|
|
1250
|
+
const EXIT_CODE_BY_PLATFORM_ERROR_CODE = {
|
|
1251
|
+
[ErrorCode.MissingApiKey]: 1,
|
|
1252
|
+
[ErrorCode.Unauthorized]: 6,
|
|
1253
|
+
[ErrorCode.Forbidden]: 7,
|
|
1254
|
+
[ErrorCode.NotFound]: 8,
|
|
1255
|
+
[ErrorCode.RateLimited]: 9,
|
|
1256
|
+
[ErrorCode.NetworkError]: 10,
|
|
1257
|
+
[ErrorCode.ServerError]: 11,
|
|
1258
|
+
[ErrorCode.Locked]: 11,
|
|
1259
|
+
[ErrorCode.InternalError]: 99
|
|
1260
|
+
};
|
|
1261
|
+
function handleError(err) {
|
|
1262
|
+
if (err instanceof MissingContextError) return errorResult(err, `Missing context: ${err.message}`, 3);
|
|
1263
|
+
if (err instanceof ConfigLoadError) return errorResult(err, `Failed to load config: ${err.message}`, 4);
|
|
1264
|
+
if (err instanceof PlatformError && err.code === ErrorCode.MissingApiKey) return errorResult(err, [
|
|
1265
|
+
"No Neon API key. `neon-env` looks for one in this order:",
|
|
1266
|
+
" - the `--api-key` flag",
|
|
1267
|
+
" - the `NEON_API_KEY` environment variable",
|
|
1268
|
+
" - `credentials.json` in `NEONCTL_CONFIG_DIR` (else `~/.config/neonctl`) — run `neon auth` to create it"
|
|
1269
|
+
].join("\n"), EXIT_CODE_BY_PLATFORM_ERROR_CODE[ErrorCode.MissingApiKey] ?? 1);
|
|
1270
|
+
if (err instanceof PlatformError) {
|
|
1271
|
+
const exitCode = EXIT_CODE_BY_PLATFORM_ERROR_CODE[err.code];
|
|
1272
|
+
if (exitCode !== void 0) return errorResult(err, err.message, exitCode);
|
|
1273
|
+
return errorResult(err, `[${err.code}] ${err.message}`, 5);
|
|
1274
|
+
}
|
|
1275
|
+
if (err instanceof Error) return errorResult(err, err.message, 1);
|
|
1276
|
+
return failure(String(err), 1);
|
|
1277
|
+
}
|
|
1278
|
+
function errorResult(err, message, exitCode) {
|
|
1279
|
+
const result = {
|
|
1280
|
+
exitCode,
|
|
1281
|
+
stdout: "",
|
|
1282
|
+
stderr: `${message}\n`
|
|
1283
|
+
};
|
|
1284
|
+
const debug = buildDebugInfo(err);
|
|
1285
|
+
if (debug) result.debugInfo = debug;
|
|
1286
|
+
return result;
|
|
1287
|
+
}
|
|
1288
|
+
function buildDebugInfo(err) {
|
|
1289
|
+
if (!(err instanceof Error)) return void 0;
|
|
1290
|
+
const lines = [];
|
|
1291
|
+
if (err instanceof PlatformError) {
|
|
1292
|
+
lines.push(`code : ${err.code}`);
|
|
1293
|
+
if (Object.keys(err.details).length > 0) lines.push(`details : ${JSON.stringify(err.details, null, 2)}`);
|
|
1294
|
+
}
|
|
1295
|
+
if (err.cause instanceof Error) lines.push(`cause : ${err.cause.name}: ${err.cause.message}`);
|
|
1296
|
+
if (err.stack) lines.push(err.stack);
|
|
1297
|
+
return lines.length > 0 ? lines.join("\n") : void 0;
|
|
1298
|
+
}
|
|
1299
|
+
function failure(message, exitCode = 1) {
|
|
1300
|
+
return {
|
|
1301
|
+
exitCode,
|
|
1302
|
+
stdout: "",
|
|
1303
|
+
stderr: `${message}\n`
|
|
1304
|
+
};
|
|
1305
|
+
}
|
|
1306
|
+
//#endregion
|
|
7
1307
|
//#region src/cli.ts
|
|
8
1308
|
const pkgVersion = readPackageVersion();
|
|
9
1309
|
const argv = yargs(hideBin(process.argv)).scriptName("neon-env").usage("$0 <command> [options]").parserConfiguration({ "populate--": true }).option("debug", {
|
|
@@ -49,10 +1349,9 @@ const command = String(argv._[0]);
|
|
|
49
1349
|
const cwd = process.cwd();
|
|
50
1350
|
let result;
|
|
51
1351
|
switch (command) {
|
|
52
|
-
case "run":
|
|
53
|
-
const passthrough = Array.isArray(argv["--"]) ? argv["--"].map(String) : [];
|
|
1352
|
+
case "run":
|
|
54
1353
|
result = await runEnvRun({
|
|
55
|
-
command:
|
|
1354
|
+
command: Array.isArray(argv["--"]) ? argv["--"].map(String) : [],
|
|
56
1355
|
...typeof argv.config === "string" ? { configPath: argv.config } : {},
|
|
57
1356
|
...typeof argv["project-id"] === "string" ? { projectId: argv["project-id"] } : {},
|
|
58
1357
|
...typeof argv.branch === "string" ? { branch: argv.branch } : {},
|
|
@@ -60,7 +1359,6 @@ switch (command) {
|
|
|
60
1359
|
...typeof argv.profile === "string" ? { profile: argv.profile } : {}
|
|
61
1360
|
}, { cwd });
|
|
62
1361
|
break;
|
|
63
|
-
}
|
|
64
1362
|
case "export":
|
|
65
1363
|
result = await runEnvExport({
|
|
66
1364
|
format: argv.format === "json" ? "json" : "dotenv",
|