neon 4.15.0 → 4.17.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 CHANGED
@@ -767,27 +767,34 @@ The target directory must be empty unless you pass `--force` (a lone `.git` is i
767
767
 
768
768
  ## Set up a project (`init`)
769
769
 
770
- `neon init` sets up this directory for Neon.
770
+ `neon init` sets up this directory for Neon as one flow: agents, a linked project, and optionally `neon.ts`.
771
771
 
772
- An empty directory (nothing except `.git`) runs `neon bootstrap .` and stops. With `-y` that is `neon bootstrap . --default`. Bootstrap handles scaffolding, agent tooling, and linking. Interactive bootstrap prints a NEON banner, asks every setup question, then runs the work — dependency install last, except when a `neon.ts` needs deps before `link`.
772
+ An empty directory (nothing except `.git`) asks how to set up the directory. Pick a starter template, or skip scaffolding and only install agent tooling, link a project, and optionally write `neon.ts`. That skip is only on `init` — `neon bootstrap` always scaffolds.
773
773
 
774
- An existing app installs agent tooling, then `neon link` unless `.neon` already has a projectId, then `neon config init`. Interactive `config init` opens the services picker; `-y` uses `--services none` (starter policy).
774
+ `-y` in an empty directory scaffolds the default template (`bootstrap --default`) and does not add a later `config init` step. `--skip-template` skips scaffolding even with `-y`. `--template <id>` scaffolds that template; combine it with `-y` to skip the remaining bootstrap pickers.
775
+
776
+ An existing app (or skip-template) installs agent tooling, then `neon link --no-config` unless `.neon` already has a projectId, then asks whether to create `neon.ts`. Saying no skips the services picker and does not write the file. `--no-config` does the same without asking. `-y` writes `config init --services none` unless `--no-config`. `--services` implies creating `neon.ts`.
775
777
 
776
778
  In an interactive terminal it offers one of: the Neon plugin (`neon plugins`), skills and MCP separately (`neon skills`, then `neon mcp`), or skip agent setup. It never runs plugin and skills+MCP together.
777
779
 
778
780
  ```bash
779
781
  $ neon init
782
+ $ neon init --skip-template
780
783
  $ neon init -y
781
784
  $ neon init --agent cursor --agent claude-code
782
785
  ```
783
786
 
784
787
  Without a TTY, pass `-y`. `--agent` skips agent selection but does not replace `-y` for link or templates.
785
788
 
786
- `-y` skips the template picker and the agent-setup offer. Empty dir: `bootstrap --default`. Existing app: plugin when Cursor, Claude Code, or Codex is in project folders, else the host CLI agent; otherwise skills and MCP. If none are found, it exits: pass `--agent <name>`, run from a supported agent, or omit `-y` in a terminal to pick. VS Code, GitHub Copilot CLI, and Grok only take the plugin user-level (`neon plugins --global`), so `-y` uses skills and MCP for those.
789
+ `-y` skips the template picker and the agent-setup offer. Empty dir: `bootstrap --default`. `--skip-template` or an existing app: plugin when Cursor, Claude Code, or Codex is in project folders, else the host CLI agent; otherwise skills and MCP. If none are found, it exits: pass `--agent <name>`, run from a supported agent, or omit `-y` in a terminal to pick. VS Code, GitHub Copilot CLI, and Grok only take the plugin user-level (`neon plugins --global`), so `-y` uses skills and MCP for those.
787
790
 
788
791
  `--agent` / `-a` (repeatable) names coding agents and skips agent selection, interactive or with `-y`. Init forwards those names to `plugins`, or to `skills` and `mcp`, not both.
789
792
 
790
- `-y` forwards `-y` to `plugins` or `skills`/`mcp`, `--default` to `bootstrap`, `--yes` to `link`, and `--services none` to `config init`. `--agent` is forwarded with them. `mcp -y` is the global install. `link --yes` only skips the "already linked" confirmation; it still asks for a project unless one is already linked.
793
+ `--project-id`, `--org-id`, `--project-name`, `--region-id`, and `--branch` are forwarded to `link`, including the link step inside nested bootstrap when a template is scaffolded. They are not filled from `.neon`; a linked directory is not relinked unless you pass one of those flags.
794
+
795
+ `--config`, `--no-config`, and `--services` apply on the existing-app and `--skip-template` path. A template's own `neon.ts` is left as the template shipped it. Passing those flags while scaffolding prints a warning and still copies the template as shipped. After a new `neon.ts` on a pinned branch, init runs `env pull`.
796
+
797
+ `-y` forwards `-y` to `plugins` or `skills`/`mcp`, `--default` to nested bootstrap, `--yes --no-config` to `link`, and `--services none` to `config init`. `--agent` is forwarded with them. `mcp -y` is the global install. `link --yes` only skips the "already linked" confirmation; it still asks for a project unless one is already linked.
791
798
 
792
799
  A failed step stops the rest. `--profile` and `--config-dir` are forwarded to each child. `--output json` and `--output yaml` are refused; the commands init runs print their own output.
793
800
 
@@ -950,6 +957,40 @@ neon snapshots schedule set --branch main --schedule '[{"frequency":"weekly","da
950
957
 
951
958
  All sub-commands honor the [global options](#global-options), including `--output json|yaml|table`.
952
959
 
960
+ ## Function triggers (`triggers`)
961
+
962
+ `neon triggers` (alias `neon trigger`) manages **scheduled function triggers** on a branch — cron jobs that invoke a Neon Function. Beta. The only trigger type is `schedule`; cron is a five-field UTC expression.
963
+
964
+ Every sub-command resolves the project through the standard chain (`--project-id`, then the `.neon` context file, then a single-project auto-detect) and the branch through `--branch <id|name>`, the `.neon` pin, or the project's default branch.
965
+
966
+ ```bash
967
+ neon triggers create --function-slug uptime --name uptime-check --cron '*/15 * * * *'
968
+ neon triggers list
969
+ neon triggers get trigger-test-123
970
+ neon triggers update trigger-test-123 --cron '0 3 * * *'
971
+ neon triggers enable trigger-test-123
972
+ neon triggers disable trigger-test-123
973
+ neon triggers delete trigger-test-123
974
+ ```
975
+
976
+ `enable` / `disable` are wrappers over `update --enabled`. List shows `inherited` when the effective config was authored on an ancestor branch.
977
+
978
+ ## Branch credentials (`credentials`)
979
+
980
+ `neon credentials` (alias `neon credential`) lists, issues, reveals, rotates, and revokes **branch-scoped credentials** — the tokens behind Object Storage (`AWS_*`) and the AI Gateway (`NEON_AI_GATEWAY_TOKEN`). Beta. In regions where those services exist, a new project already has default credentials named `Default AI gateway credential` and `Default object storage credential`; `list` then `reveal` recovers their secrets without minting another token.
981
+
982
+ ```bash
983
+ neon credentials list
984
+ neon credentials create --name app --scope storage:read --scope storage:write
985
+ neon credentials reveal nak_live_…
986
+ neon credentials rotate nak_live_…
987
+ neon credentials revoke nak_live_…
988
+ ```
989
+
990
+ `create` always issues a customer-managed (`user`) credential. `--scope` is repeatable; `--help` lists the values. `reveal` and `rotate` print `api_token` and `s3_secret_access_key`. Rotation keeps the same `token_id` (it is the `AWS_ACCESS_KEY_ID`) and is not idempotent: a retry after a lost response mints another secret.
991
+
992
+ All sub-commands honor the [global options](#global-options), including `--output json|yaml|table`.
993
+
953
994
  ## Database diagnostics (`inspect`)
954
995
 
955
996
  `neon inspect db stalled-queries` takes a read-only snapshot of active queries that have run for more than 30 seconds and groups parallel workers with their leader. Oldest group first. Table output shows duration, wait event, blocking pids, role, query group, and query. `--output json` adds timestamps, query IDs, pids, database, and the rest of the row. A blocking pid can belong to an idle-in-transaction backend this command does not list; `neon inspect db locks` shows lock holders.
@@ -1289,6 +1330,8 @@ Id Name Project Created At Last Used At Last
1289
1330
  | logs | `query`, `fields`, `field-values` | Query branch logs (Beta) |
1290
1331
  | inspect | `db stalled-queries` | Inspect Postgres diagnostics |
1291
1332
  | snapshots | `list`, `get`, `create`, `update`, `delete`, `restore`, `finalize`, `schedule get`, `schedule set` | Manage snapshots |
1333
+ | triggers | `list`, `get`, `create`, `update`, `enable`, `disable`, `delete` | Manage function triggers |
1334
+ | credentials | `list`, `create`, `reveal`, `rotate`, `revoke` | Manage branch credentials |
1292
1335
  | [connection-string](https://neon.com/docs/reference/cli-connection-string) | | Get connection string |
1293
1336
  | [psql](https://neon.com/docs/reference/cli-psql) | | Connect to a database via psql |
1294
1337
  | set-context | | Deprecated; use `link` |
@@ -1,27 +1,26 @@
1
1
  import { log } from "../log.js";
2
2
  import { getCliName } from "../utils/cli_name.js";
3
3
  import { declaredNeonServices } from "../config_services.js";
4
- import { S as toEntries, _ as functionBaseUrlKey, a as envKeysForSelection, b as previewCredentialScopes, d as servicesForEnvKeys, f as NEON_ENV_VAR_KEYS, g as fetchEnvKeysState, h as credentialName, i as ENV_PULL_SERVICES, m as credentialEnvKeys, p as createApiFromOptions, u as serviceForEnvKey, v as isFunctionBaseUrlKey, x as resolveBranchPolicy, y as policyEnvKeys } from "./env_services-CAWrZTWa.js";
4
+ import { C as resolveBranchPolicy, S as policyEnvKeys, _ as defaultStorageCredential, a as envKeysForSelection, b as isFunctionBaseUrlKey, d as servicesForEnvKeys, f as NEON_ENV_VAR_KEYS, g as defaultAiGatewayCredential, h as credentialName, i as ENV_PULL_SERVICES, m as credentialEnvKeys, p as createApiFromOptions, u as serviceForEnvKey, v as fetchEnvKeysState, w as toEntries, x as isLiveCredential, y as functionBaseUrlKey } from "./env_services-CbARRnq9.js";
5
5
  import { formatInstallCommand, resolvePackageManager } from "../utils/package_manager.js";
6
6
  import { credentialScopesSatisfied } from "@neon/config/v1";
7
7
  import { ErrorCode as ErrorCode$1, createNeonApiFromOptions as createNeonApiFromOptions$1, isPlatformError as isPlatformError$1, loadConfigFromFile } from "@neon/config";
8
8
  import { plan, pullConfig } from "@neon/config-runtime";
9
9
  //#region ../../internals/env-core/dist/reuse-secrets.js
10
10
  /**
11
- * Resolve a branch's env while keeping one-time secrets the caller already holds.
11
+ * Resolve a branch's env while keeping secrets the caller already holds.
12
12
  *
13
- * {@link fetchEnvKeys} — and the public `fetchEnv` — only ever *fetch*. The Neon API returns a
14
- * credential's `api_token` / `s3_secret_access_key` exactly once, at mint time, so "fetching"
15
- * them means minting a new credential; a plain `fetchEnv` on every `neon dev` start or `env
16
- * pull` would leave a live credential behind each time. This is the wrapper that avoids that:
17
- * it looks at what the caller already has, decides what is still usable, and asks `fetchEnv`
18
- * for only the rest.
13
+ * {@link fetchEnvKeys} reveals the platform default credentials (or mints a fallback when a
14
+ * region has none). Calling it on every `neon dev` start would rewrite `.env` with freshly
15
+ * revealed secrets each time. This wrapper looks at what the caller already has, keeps a
16
+ * half when it already *is* that default (storage and gateway are independent credentials),
17
+ * and asks `fetchEnv` for only the rest.
19
18
  *
20
19
  * The check is a real verification, not a presence test. A persisted secret is kept only when
21
- * it names a credential that still exists on this branch, is not revoked or expired, and
22
- * carries every scope the policy needs. A `.env.example` placeholder, a credential revoked in
23
- * the console, one copied in from another branch, or one predating a newly-enabled feature all
24
- * fail that check and get replaced.
20
+ * it names a credential that still exists on this branch, is not revoked or expired, and —
21
+ * when defaults exist — *is* that default. A leftover `neon-env ${branch}` credential this
22
+ * tool minted is replaced by the defaults and revoked. A `.env.example` placeholder, a
23
+ * credential revoked in the console, or one copied in from another branch fails that check.
25
24
  *
26
25
  * None of this needs local bookkeeping, because the secrets carry their own credential id:
27
26
  * `AWS_ACCESS_KEY_ID` **is** the credential's `tokenId` (the storage gateway authenticates
@@ -71,47 +70,47 @@ async function fetchEnvReusingSecrets(config, options) {
71
70
  const persisted = readPersistedSecrets(source);
72
71
  const storageCredentialManaged = requested === null || storageCredentialSelected;
73
72
  const gatewayCredentialManaged = requested === null || gatewayCredentialSelected;
74
- const complete = (!storageCredentialSelected || Boolean(persisted.accessKeyId && persisted.secretAccessKey)) && (!gatewayCredentialSelected || Boolean(persisted.apiToken));
75
- const named = storageCredentialManaged && persisted.accessKeyId !== "" || gatewayCredentialManaged && persisted.apiToken !== "" ? namedCredentials(await api.listCredentials(options.projectId, branch.id), persisted) : {
73
+ const storageComplete = Boolean(persisted.accessKeyId && persisted.secretAccessKey);
74
+ const gatewayComplete = Boolean(persisted.apiToken);
75
+ const listed = storageCredentialManaged && persisted.accessKeyId !== "" || gatewayCredentialManaged && persisted.apiToken !== "" ? await api.listCredentials(options.projectId, branch.id) : [];
76
+ const named = listed.length > 0 ? namedCredentials(listed, persisted) : {
76
77
  storage: null,
77
78
  gateway: null
78
79
  };
79
- const reusable = complete ? reusableCredential(named, {
80
- storageEnabled: storageCredentialSelected,
81
- gatewayEnabled: gatewayCredentialSelected
82
- }) : null;
83
- const scopes = previewCredentialScopes(desired.preview, {
84
- storage: storageCredentialSelected,
85
- aiGateway: gatewayCredentialSelected
86
- });
87
- const keep = reusable !== null && credentialScopesSatisfied(reusable.scopes, scopes);
88
- const fetchKeys = requested === null ? null : keep ? selectedPolicyKeys.filter((key) => !secretKeys.includes(key)) : selectedPolicyKeys;
80
+ const now = Date.now();
81
+ const storageDefault = defaultStorageCredential(listed, now);
82
+ const gatewayDefault = defaultAiGatewayCredential(listed, now);
83
+ const keepStorage = !storageCredentialSelected || storageComplete && halfReusable(named.storage, storageDefault, ["storage:read", "storage:write"]);
84
+ const keepGateway = !gatewayCredentialSelected || gatewayComplete && halfReusable(named.gateway, gatewayDefault, ["ai_gateway:invoke"]);
85
+ const keptSecretKeys = credentialEnvKeys({
86
+ storage: storageCredentialSelected && keepStorage,
87
+ aiGateway: gatewayCredentialSelected && keepGateway
88
+ }).filter((key) => selected.has(key));
89
+ const fetchKeys = requested === null ? null : selectedPolicyKeys.filter((key) => !keptSecretKeys.includes(key));
89
90
  const fetched = await fetchEnvKeysState(config, {
90
91
  ...fetchOptions,
91
92
  branchId: branch.id,
92
93
  api,
93
- ...keep && requested === null ? { omitKeys: secretKeys } : {}
94
+ ...keptSecretKeys.length > 0 && requested === null ? { omitKeys: keptSecretKeys } : {}
94
95
  }, fetchKeys);
95
96
  const vars = preferPersisted(toEntries(fetched.env), source);
96
97
  const unavailable = fetched.functionUrlsUnavailable ? { functionUrlsUnavailable: true } : {};
97
- if (keep) {
98
- for (const key of secretKeys) {
99
- const value = source[key];
100
- if (value !== void 0) vars[key] = value;
101
- }
102
- return {
103
- vars,
104
- credential: {
105
- issued: false,
106
- keys: secretKeys,
107
- revoked: [],
108
- superseded: []
109
- },
110
- ...unavailable
111
- };
98
+ for (const key of keptSecretKeys) {
99
+ const value = source[key];
100
+ if (value !== void 0) vars[key] = value;
112
101
  }
102
+ if (!(storageCredentialSelected && !keepStorage || gatewayCredentialSelected && !keepGateway)) return {
103
+ vars,
104
+ credential: {
105
+ issued: false,
106
+ keys: secretKeys,
107
+ revoked: [],
108
+ superseded: []
109
+ },
110
+ ...unavailable
111
+ };
113
112
  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);
113
+ for (const meta of [storageCredentialManaged && !keepStorage ? named.storage : null, gatewayCredentialManaged && !keepGateway ? named.gateway : null]) if (meta !== null && meta.principalType === "user" && meta.name === credentialName(branch.name)) ours.add(meta.tokenId);
115
114
  if (revokeSuperseded) for (const tokenId of ours) await api.revokeCredential(options.projectId, branch.id, tokenId);
116
115
  return {
117
116
  vars,
@@ -162,13 +161,6 @@ function preferPersisted(vars, source) {
162
161
  function gatewayTokenIdShort(apiToken) {
163
162
  return /^nt_live_([^_]+)_.+$/.exec(apiToken)?.[1] ?? null;
164
163
  }
165
- /** Whether an issued credential can still be used: not revoked, not past its expiry. */
166
- function isLiveCredential(meta, now) {
167
- if (meta.revokedAt !== void 0) return false;
168
- if (meta.expiresAt === void 0) return true;
169
- const expiresAt = Date.parse(meta.expiresAt);
170
- return Number.isNaN(expiresAt) || expiresAt > now;
171
- }
172
164
  /**
173
165
  * The live credentials the persisted secrets name — at most one per half. A half that names
174
166
  * nothing contributes nothing, which is what a placeholder, a credential revoked in the
@@ -183,17 +175,17 @@ function namedCredentials(live, persisted) {
183
175
  };
184
176
  }
185
177
  /**
186
- * The credential the persisted secrets can be *reused* as, or `null`.
178
+ * Whether a persisted half can be reused.
187
179
  *
188
- * Strict on purpose: every half the policy enables has to name a live credential, and when both
189
- * features are enabled they must name the *same* one — they share a single credential, so
190
- * halves that disagree came from two different calls and neither can be trusted.
180
+ * When a platform default exists, only that default is reusable — a leftover
181
+ * `neon-env ${branch}` mint is replaced. When no default exists (mint fallback),
182
+ * any live credential the secrets name is reusable if it still carries the
183
+ * scopes that half needs.
191
184
  */
192
- function reusableCredential(named, enabled) {
193
- if (enabled.storageEnabled && enabled.gatewayEnabled) return named.storage && named.gateway && named.storage.tokenId === named.gateway.tokenId ? named.storage : null;
194
- if (enabled.storageEnabled) return named.storage;
195
- if (enabled.gatewayEnabled) return named.gateway;
196
- return null;
185
+ function halfReusable(named, defaultMeta, requiredScopes) {
186
+ if (named === null) return false;
187
+ if (defaultMeta !== null) return named.tokenId === defaultMeta.tokenId;
188
+ return credentialScopesSatisfied(named.scopes, requiredScopes);
197
189
  }
198
190
  //#endregion
199
191
  //#region src/dev/env.ts
@@ -437,16 +429,17 @@ const withAiGateway = (config) => ({
437
429
  *
438
430
  * So the gateway is only added once its credential endpoint has been shown to answer, by
439
431
  * reading the branch's credentials first. A project that does not have them says so on a
440
- * read, before anything is minted — which is the whole question, since the gateway's env is a
441
- * credential and nothing else.
432
+ * read, before anything is revealed or minted — which is the whole question, since the
433
+ * gateway's env is a credential and nothing else.
442
434
  *
443
435
  * Deciding this **before** resolving, rather than by catching and retrying, is what keeps it
444
436
  * honest. A retry re-runs every call the first attempt made, so it would blame the gateway for
445
- * a one-off failure in shared work, and — worse — a first attempt that minted a credential and
446
- * then failed would be papered over by a second that succeeds without one, swallowing the
447
- * error and stranding a secret nobody holds. Once the read succeeds, a later failure is a real
448
- * failure and propagates: the same thing already happens on a branch with object storage,
449
- * whose credential is minted whether or not the gateway is involved.
437
+ * a one-off failure in shared work, and — worse — a first attempt that revealed or minted a
438
+ * credential and then failed would be papered over by a second that succeeds without one,
439
+ * swallowing the error and stranding a secret nobody holds. Once the read succeeds, a later
440
+ * failure is a real failure and propagates: the same thing already happens on a branch with
441
+ * object storage, whose credential is revealed (or minted as a fallback) whether or not the
442
+ * gateway is involved.
450
443
  */
451
444
  const resolveWithImpliedGateway = async (config, ctx, branch) => {
452
445
  const unreachable = await credentialsUnreachable(ctx, branch);
@@ -190,7 +190,7 @@ async function fetchEnvKeysState(config, options, keys) {
190
190
  branchId: branch.id
191
191
  } });
192
192
  }
193
- const secrets = wantsCredential ? await mintBranchCredential({
193
+ const secrets = wantsCredential ? await resolveBranchCredentialSecrets({
194
194
  api,
195
195
  projectId,
196
196
  branchId: branch.id,
@@ -303,9 +303,9 @@ async function resolveBranchPolicy(config, options, api) {
303
303
  };
304
304
  }
305
305
  /**
306
- * Scopes the branch credential should carry for a resolved branch policy and optional key
307
- * selection. Only object storage and the AI Gateway *require* a credential; functions never
308
- * force one, but `functions:invoke` rides along when another selected feature mints one.
306
+ * Scopes a minted fallback credential should carry. Only object storage and the AI Gateway
307
+ * *require* secrets; functions never force a credential. `functions:invoke` rides along only
308
+ * when this path still has to mint (defaults already cover storage and the gateway).
309
309
  */
310
310
  function previewCredentialScopes(preview, selected) {
311
311
  if (!preview) return [];
@@ -348,15 +348,70 @@ function policyEnvKeys(desired) {
348
348
  ...desired.preview?.aiGatewayEnabled ? [K.aiGateway.apiKey, K.aiGateway.baseUrl] : []
349
349
  ];
350
350
  }
351
+ /** Exact `name` values the credentials list endpoint returns for the platform defaults. */
352
+ const DEFAULT_AI_GATEWAY_CREDENTIAL_NAME = "Default AI gateway credential";
353
+ const DEFAULT_OBJECT_STORAGE_CREDENTIAL_NAME = "Default object storage credential";
354
+ /** Whether an issued credential can still be used: not revoked, not past its expiry. */
355
+ function isLiveCredential(meta, now) {
356
+ if (meta.revokedAt !== void 0) return false;
357
+ if (meta.expiresAt === void 0) return true;
358
+ const expiresAt = Date.parse(meta.expiresAt);
359
+ return Number.isNaN(expiresAt) || expiresAt > now;
360
+ }
361
+ function defaultStorageCredential(live, now) {
362
+ return live.find((meta) => meta.name === DEFAULT_OBJECT_STORAGE_CREDENTIAL_NAME && isLiveCredential(meta, now)) ?? null;
363
+ }
364
+ function defaultAiGatewayCredential(live, now) {
365
+ return live.find((meta) => meta.name === DEFAULT_AI_GATEWAY_CREDENTIAL_NAME && isLiveCredential(meta, now)) ?? null;
366
+ }
351
367
  /**
352
- * Mint the branch credential backing object storage / the AI Gateway.
368
+ * Resolve secrets for object storage / the AI Gateway.
353
369
  *
354
- * `api_token` and `s3_secret_access_key` come back **exactly once** — they are not stored
355
- * server-side and the list endpoint returns metadata only — so the caller's copy is the only
356
- * copy. That is why {@link fetchEnv} mints rather than fetches: there is nothing to fetch. A
357
- * caller that already holds a valid copy should leave the secret keys out of `keys` (see
358
- * {@link fetchEnvReusingSecrets}) instead of minting one it will discard.
370
+ * Regions that expose those products already have platform defaults on every branch.
371
+ * Reveal those by exact name instead of minting a combined `neon-env ${branch}` credential.
372
+ * Mint only the half (or both) that has no default — regions without the credentials
373
+ * endpoint still fail at list, same as before.
374
+ *
375
+ * A caller that already holds secrets for those defaults should leave the secret keys out
376
+ * of `keys` (see {@link fetchEnvReusingSecrets}) instead of revealing them again.
359
377
  */
378
+ async function resolveBranchCredentialSecrets(args) {
379
+ const needsStorage = args.scopes.includes("storage:read") || args.scopes.includes("storage:write");
380
+ const needsGateway = args.scopes.includes("ai_gateway:invoke");
381
+ const live = await args.api.listCredentials(args.projectId, args.branchId);
382
+ const now = Date.now();
383
+ const storageDefault = defaultStorageCredential(live, now);
384
+ const gatewayDefault = defaultAiGatewayCredential(live, now);
385
+ const secrets = {
386
+ accessKeyId: "",
387
+ secretAccessKey: "",
388
+ apiToken: ""
389
+ };
390
+ if (needsStorage && storageDefault) {
391
+ const revealed = await args.api.revealCredential(args.projectId, args.branchId, storageDefault.tokenId);
392
+ secrets.accessKeyId = revealed.tokenId;
393
+ secrets.secretAccessKey = revealed.s3SecretAccessKey;
394
+ }
395
+ if (needsGateway && gatewayDefault) secrets.apiToken = (await args.api.revealCredential(args.projectId, args.branchId, gatewayDefault.tokenId)).apiToken;
396
+ const missingStorage = needsStorage && storageDefault === null;
397
+ const missingGateway = needsGateway && gatewayDefault === null;
398
+ if (missingStorage || missingGateway) {
399
+ const minted = await mintBranchCredential({
400
+ ...args,
401
+ scopes: deriveCredentialScopes({
402
+ storage: missingStorage,
403
+ aiGateway: missingGateway,
404
+ functions: args.scopes.includes("functions:invoke")
405
+ })
406
+ });
407
+ if (missingStorage) {
408
+ secrets.accessKeyId = minted.accessKeyId;
409
+ secrets.secretAccessKey = minted.secretAccessKey;
410
+ }
411
+ if (missingGateway) secrets.apiToken = minted.apiToken;
412
+ }
413
+ return secrets;
414
+ }
360
415
  async function mintBranchCredential(args) {
361
416
  const minted = await args.api.createCredential(args.projectId, args.branchId, {
362
417
  scopes: args.scopes,
@@ -625,4 +680,4 @@ const editDistance = (left, right) => {
625
680
  /** Narrow yargs' array option value without accepting any other runtime shape. */
626
681
  const envPullFlagValue = (value) => Array.isArray(value) ? value.map(String) : void 0;
627
682
  //#endregion
628
- export { toEntries as S, functionBaseUrlKey as _, envKeysForSelection as a, previewCredentialScopes as b, ownedEnvServiceKeys as c, servicesForEnvKeys as d, NEON_ENV_VAR_KEYS as f, fetchEnvKeysState as g, credentialName as h, ENV_PULL_SERVICES as i, parseEnvPullKeys as l, credentialEnvKeys as m, ENV_PULL_KEYS as n, envPullFlagValue as o, createApiFromOptions as p, ENV_PULL_KEY_HELP as r, envServiceKeys as s, BRANCH_ENV_KEY as t, serviceForEnvKey as u, isFunctionBaseUrlKey as v, resolveBranchPolicy as x, policyEnvKeys as y };
683
+ export { resolveBranchPolicy as C, policyEnvKeys as S, defaultStorageCredential as _, envKeysForSelection as a, isFunctionBaseUrlKey as b, ownedEnvServiceKeys as c, servicesForEnvKeys as d, NEON_ENV_VAR_KEYS as f, defaultAiGatewayCredential as g, credentialName as h, ENV_PULL_SERVICES as i, parseEnvPullKeys as l, credentialEnvKeys as m, ENV_PULL_KEYS as n, envPullFlagValue as o, createApiFromOptions as p, ENV_PULL_KEY_HELP as r, envServiceKeys as s, BRANCH_ENV_KEY as t, serviceForEnvKey as u, fetchEnvKeysState as v, toEntries as w, isLiveCredential as x, functionBaseUrlKey as y };
package/dist/analytics.js CHANGED
@@ -156,13 +156,20 @@ const closeAnalytics = async (opts) => {
156
156
  log.debug("Flushed CLI analytics");
157
157
  }
158
158
  };
159
+ const getErrorAnalyticsEventContext = (_args) => ({
160
+ version: pkg_default.version,
161
+ ci: isCi(),
162
+ agent: getCliAgent(process.env)
163
+ });
164
+ const CREDENTIAL_TOKEN_ID = /\bnak_live_[0-9a-f]+\b/gi;
165
+ const redactCredentialTokenIds = (text) => text.replace(CREDENTIAL_TOKEN_ID, "nak_live_<redacted>");
159
166
  const getErrorAnalyticsEventProperties = (err, errCode, context) => {
160
167
  const apiError = isNeonApiError(err) ? err : void 0;
161
168
  const requestId = apiError?.headers?.["x-neon-ret-request-id"];
162
169
  return {
163
170
  ...context,
164
- message: err.message,
165
- stack: err.stack,
171
+ message: redactCredentialTokenIds(err.message),
172
+ stack: err.stack ? redactCredentialTokenIds(err.stack) : err.stack,
166
173
  errCode,
167
174
  statusCode: apiError?.status,
168
175
  requestId
@@ -188,15 +195,10 @@ const trackEvent = (event, properties) => {
188
195
  });
189
196
  log.debug("Sent CLI event: %s", event);
190
197
  };
191
- const getErrorAnalyticsEventContext = (_args) => ({
192
- version: pkg_default.version,
193
- ci: isCi(),
194
- agent: getCliAgent(process.env)
195
- });
196
198
  const analyticsCommand = (args) => {
197
199
  const command = args._.join(" ");
198
- if (args._[0] !== "ask" || typeof args.prompt !== "string") return command;
199
- return `${command} ${args.prompt}`;
200
+ const raw = args._[0] !== "ask" || typeof args.prompt !== "string" ? command : `${command} ${args.prompt}`;
201
+ return redactCredentialTokenIds(raw);
200
202
  };
201
203
  const getAnalyticsEventProperties = (args) => ({
202
204
  version: pkg_default.version,
package/dist/api.js CHANGED
@@ -872,6 +872,85 @@ const getApiClient = ({ apiKey, apiHost, requestTimeoutMs = REQUEST_TIMEOUT_MS }
872
872
  auth_user_id: authUserId
873
873
  },
874
874
  body: data
875
+ })),
876
+ listProjectBranchTriggers: (projectId, branchId) => call(() => raw.listProjectBranchTriggers({
877
+ client,
878
+ path: {
879
+ project_id: projectId,
880
+ branch_id: branchId
881
+ }
882
+ })),
883
+ getProjectBranchTrigger: (projectId, branchId, triggerId) => call(() => raw.getProjectBranchTrigger({
884
+ client,
885
+ path: {
886
+ project_id: projectId,
887
+ branch_id: branchId,
888
+ trigger_id: triggerId
889
+ }
890
+ })),
891
+ createProjectBranchTrigger: (projectId, branchId, data) => call(() => raw.createProjectBranchTrigger({
892
+ client,
893
+ path: {
894
+ project_id: projectId,
895
+ branch_id: branchId
896
+ },
897
+ body: data
898
+ })),
899
+ updateProjectBranchTrigger: (projectId, branchId, triggerId, data) => call(() => raw.updateProjectBranchTrigger({
900
+ client,
901
+ path: {
902
+ project_id: projectId,
903
+ branch_id: branchId,
904
+ trigger_id: triggerId
905
+ },
906
+ body: data
907
+ })),
908
+ deleteProjectBranchTrigger: (projectId, branchId, triggerId) => call(() => raw.deleteProjectBranchTrigger({
909
+ client,
910
+ path: {
911
+ project_id: projectId,
912
+ branch_id: branchId,
913
+ trigger_id: triggerId
914
+ }
915
+ })),
916
+ listCredentials: (projectId, branchId) => call(() => raw.listCredentials({
917
+ client,
918
+ path: {
919
+ project_id: projectId,
920
+ branch_id: branchId
921
+ }
922
+ })),
923
+ createCredential: (projectId, branchId, data) => call(() => raw.createCredential({
924
+ client,
925
+ path: {
926
+ project_id: projectId,
927
+ branch_id: branchId
928
+ },
929
+ body: data
930
+ })),
931
+ revokeCredential: (projectId, branchId, tokenId) => call(() => raw.revokeCredential({
932
+ client,
933
+ path: {
934
+ project_id: projectId,
935
+ branch_id: branchId,
936
+ token_id: tokenId
937
+ }
938
+ })),
939
+ revealCredential: (projectId, branchId, tokenId) => call(() => raw.revealCredential({
940
+ client,
941
+ path: {
942
+ project_id: projectId,
943
+ branch_id: branchId,
944
+ token_id: tokenId
945
+ }
946
+ })),
947
+ rotateCredential: (projectId, branchId, tokenId) => call(() => raw.rotateCredential({
948
+ client,
949
+ path: {
950
+ project_id: projectId,
951
+ branch_id: branchId,
952
+ token_id: tokenId
953
+ }
875
954
  }))
876
955
  };
877
956
  };