neon 2.47.0 → 3.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 +54 -0
- package/dist/_shared/auth_selection.js +76 -79
- package/dist/_shared/credentials.js +166 -187
- package/dist/_shared/env-core/env.js +395 -0
- package/dist/_shared/env-core/reuse-secrets.js +179 -0
- package/dist/_shared/paths.js +129 -126
- package/dist/_shared/profiles.js +192 -242
- package/dist/_shared/secure_file.js +36 -38
- package/dist/_virtual/_rolldown/runtime.js +13 -0
- package/dist/analytics.js +163 -207
- package/dist/api.js +815 -758
- package/dist/auth.js +121 -141
- package/dist/auth_context.js +39 -53
- package/dist/cli.js +4 -7
- package/dist/commands/api.js +220 -250
- package/dist/commands/api_keys.js +251 -314
- package/dist/commands/auth.js +283 -328
- package/dist/commands/bootstrap.js +372 -437
- package/dist/commands/branches.js +304 -455
- package/dist/commands/bucket.js +374 -514
- package/dist/commands/checkout.js +213 -298
- package/dist/commands/config.js +575 -658
- package/dist/commands/connection_string.js +137 -165
- package/dist/commands/data_api.js +238 -260
- package/dist/commands/databases.js +67 -76
- package/dist/commands/deploy.js +31 -25
- package/dist/commands/dev.js +642 -681
- package/dist/commands/diff.js +156 -200
- package/dist/commands/env.js +243 -303
- package/dist/commands/functions.js +275 -341
- package/dist/commands/index.js +70 -65
- package/dist/commands/init.js +84 -119
- package/dist/commands/inspect.js +55 -55
- package/dist/commands/ip_allow.js +88 -120
- package/dist/commands/link.js +874 -1019
- package/dist/commands/logs.js +291 -0
- package/dist/commands/neon_auth.js +725 -933
- package/dist/commands/operations.js +34 -25
- package/dist/commands/orgs.js +28 -18
- package/dist/commands/profile.js +614 -845
- package/dist/commands/projects.js +313 -373
- package/dist/commands/psql.js +60 -58
- package/dist/commands/roles.js +55 -58
- package/dist/commands/schema_diff.js +87 -131
- package/dist/commands/set_context.js +34 -26
- package/dist/commands/snapshots.js +288 -413
- package/dist/commands/status.js +41 -37
- package/dist/commands/user.js +21 -10
- package/dist/commands/vpc_endpoints.js +85 -113
- package/dist/config.js +7 -6
- package/dist/config_format.js +50 -66
- package/dist/config_template.js +128 -157
- package/dist/context.js +183 -235
- package/dist/current_branch_fast_path.js +40 -49
- package/dist/dev/env.js +313 -394
- package/dist/dev/functions.js +54 -64
- package/dist/dev/inputs.js +46 -58
- package/dist/dev/runtime.js +135 -164
- package/dist/dev/websocket.js +766 -959
- package/dist/env.js +27 -33
- package/dist/env_file.js +118 -132
- package/dist/env_services.js +36 -38
- package/dist/errors.js +57 -68
- package/dist/functions_api.js +45 -43
- package/dist/help.js +189 -140
- package/dist/index.js +182 -257
- package/dist/init/agents.js +137 -118
- package/dist/init/auth.js +58 -68
- package/dist/init/bootstrap.js +325 -396
- package/dist/init/build_config.js +4 -2
- package/dist/init/detect_agent.js +56 -101
- package/dist/init/editors.js +35 -52
- package/dist/init/enrich_output.js +51 -66
- package/dist/init/extension.js +134 -171
- package/dist/init/inspect.js +179 -266
- package/dist/init/interactive.js +510 -622
- package/dist/init/neonctl.js +117 -168
- package/dist/init/orchestrate.js +157 -173
- package/dist/init/phases/auth.js +188 -202
- package/dist/init/phases/cleanup.js +23 -23
- package/dist/init/phases/db.js +251 -277
- package/dist/init/phases/getting_started.js +213 -223
- package/dist/init/phases/mcp.js +174 -224
- package/dist/init/phases/migrations.js +247 -248
- package/dist/init/phases/neon_auth.js +114 -133
- package/dist/init/phases/setup.js +546 -703
- package/dist/init/phases/skills.js +75 -86
- package/dist/init/phases/status.js +72 -67
- package/dist/init/resolve_context.js +102 -99
- package/dist/init/route_command.js +91 -98
- package/dist/init/skills.js +174 -218
- package/dist/init/vsix.js +77 -99
- package/dist/log.js +17 -16
- package/dist/neon_services.js +104 -129
- package/dist/parameters.gen.js +481 -471
- package/dist/pkg.js +17 -19
- package/dist/profile_keys.js +44 -47
- package/dist/psql/cli.js +44 -47
- package/dist/psql/command/cmd_cond.js +231 -406
- package/dist/psql/command/cmd_connect.js +557 -764
- package/dist/psql/command/cmd_copy.js +727 -983
- package/dist/psql/command/cmd_describe.js +1499 -1688
- package/dist/psql/command/cmd_format.js +733 -905
- package/dist/psql/command/cmd_io.js +1293 -2082
- package/dist/psql/command/cmd_lo.js +297 -359
- package/dist/psql/command/cmd_meta.js +727 -878
- package/dist/psql/command/cmd_misc.js +138 -172
- package/dist/psql/command/cmd_pipeline.js +547 -1099
- package/dist/psql/command/cmd_restrict.js +119 -155
- package/dist/psql/command/cmd_show.js +529 -688
- package/dist/psql/command/dispatch.js +261 -325
- package/dist/psql/command/inputQueue.js +35 -33
- package/dist/psql/command/shared.js +49 -63
- package/dist/psql/complete/filenames.js +90 -133
- package/dist/psql/complete/index.js +59 -97
- package/dist/psql/complete/matcher.js +236 -300
- package/dist/psql/complete/psqlVars.js +218 -223
- package/dist/psql/complete/queries.js +159 -177
- package/dist/psql/complete/rules.js +1493 -2299
- package/dist/psql/core/common.js +762 -1180
- package/dist/psql/core/help.js +456 -546
- package/dist/psql/core/mainloop.js +692 -1302
- package/dist/psql/core/prompt.js +391 -408
- package/dist/psql/core/settings.js +429 -644
- package/dist/psql/core/sqlHelp.js +480 -554
- package/dist/psql/core/startup.js +626 -815
- package/dist/psql/core/syncVars.js +67 -110
- package/dist/psql/core/variables.js +156 -278
- package/dist/psql/describe/formatters.js +884 -1285
- package/dist/psql/describe/processNamePattern.js +173 -260
- package/dist/psql/describe/queries.js +1368 -2403
- package/dist/psql/describe/versionGate.js +32 -41
- package/dist/psql/index.js +1414 -1927
- package/dist/psql/io/history.js +232 -271
- package/dist/psql/io/input.js +103 -108
- package/dist/psql/io/lineEditor/buffer.js +238 -319
- package/dist/psql/io/lineEditor/complete.js +135 -213
- package/dist/psql/io/lineEditor/filename.js +139 -148
- package/dist/psql/io/lineEditor/index.js +653 -870
- package/dist/psql/io/lineEditor/keymap.js +544 -702
- package/dist/psql/io/lineEditor/vt100.js +294 -341
- package/dist/psql/io/pgpass.js +158 -187
- package/dist/psql/io/pgservice.js +146 -183
- package/dist/psql/io/psqlrc.js +328 -403
- package/dist/psql/print/aligned.js +1020 -1683
- package/dist/psql/print/asciidoc.js +180 -214
- package/dist/psql/print/crosstab.js +281 -442
- package/dist/psql/print/csv.js +48 -70
- package/dist/psql/print/html.js +195 -226
- package/dist/psql/print/json.js +75 -88
- package/dist/psql/print/latex.js +291 -364
- package/dist/psql/print/pager.js +171 -242
- package/dist/psql/print/troff.js +194 -226
- package/dist/psql/print/unaligned.js +69 -95
- package/dist/psql/print/units.js +167 -169
- package/dist/psql/scanner/slash.js +428 -483
- package/dist/psql/scanner/sql.js +445 -889
- package/dist/psql/scanner/stringutils.js +309 -379
- package/dist/psql/types/index.js +2 -7
- package/dist/psql/types/scanner.js +25 -22
- package/dist/psql/wire/connection.js +2042 -2803
- package/dist/psql/wire/copy.js +84 -100
- package/dist/psql/wire/notify.js +39 -59
- package/dist/psql/wire/pipeline.js +305 -518
- package/dist/psql/wire/protocol.js +349 -417
- package/dist/psql/wire/sasl.js +180 -265
- package/dist/psql/wire/tls.js +400 -561
- package/dist/storage_api.js +115 -129
- package/dist/test_utils/fixtures.js +94 -113
- package/dist/test_utils/oauth_server.js +10 -7
- package/dist/test_utils/project_dir.js +33 -0
- package/dist/utils/ai_gateway_notice.js +131 -162
- package/dist/utils/api_enums.js +21 -28
- package/dist/utils/auth.js +10 -4
- package/dist/utils/branch_notice.js +20 -19
- package/dist/utils/branch_picker.js +83 -89
- package/dist/utils/cli_name.js +15 -12
- package/dist/utils/compute_units.js +20 -27
- package/dist/utils/config_diff.js +127 -158
- package/dist/utils/enrichers.js +95 -148
- package/dist/utils/esbuild.js +133 -147
- package/dist/utils/flags.js +35 -47
- package/dist/utils/formats.js +8 -15
- package/dist/utils/git_diff.js +69 -80
- package/dist/utils/inspect_db.js +101 -143
- package/dist/utils/inspect_queries.js +179 -142
- package/dist/utils/middlewares.js +37 -44
- package/dist/utils/openapi.js +87 -99
- package/dist/utils/package_manager.js +312 -110
- package/dist/utils/point_in_time.js +49 -53
- package/dist/utils/psql.js +89 -106
- package/dist/utils/service_picker.js +55 -58
- package/dist/utils/string.js +5 -5
- package/dist/utils/ui.js +38 -55
- package/dist/utils/write_sync.js +26 -35
- package/dist/utils/zip.js +4 -3
- package/dist/writer.js +67 -87
- package/package.json +9 -7
|
@@ -0,0 +1,395 @@
|
|
|
1
|
+
import { ErrorCode, PlatformError, createNeonApiFromOptions, deriveCredentialScopes, resolveConfig } from "@neon/config/v1";
|
|
2
|
+
//#region src/_shared/env-core/env.ts
|
|
3
|
+
/**
|
|
4
|
+
* The Neon env core — resolving a branch's env from the Neon API, and projecting it into
|
|
5
|
+
* OS-level `{ KEY: value }` pairs.
|
|
6
|
+
*
|
|
7
|
+
* Shared source, not a package: `scripts/sync-shared.mjs` copies it into `@neon/env` (which
|
|
8
|
+
* publishes it as `fetchEnv` / `toEntries`) and into the `neon` CLI (which needs the
|
|
9
|
+
* credential-reuse half in `reuse-secrets.ts`). See `shared/env-core/README.md` for why it is
|
|
10
|
+
* a copy rather than an import.
|
|
11
|
+
*
|
|
12
|
+
* The counterpart that reads `process.env` — `parseEnv` and its zod schemas — is not here. It
|
|
13
|
+
* has no consumer outside `@neon/env`, so it stays in that package and imports this.
|
|
14
|
+
*/
|
|
15
|
+
/**
|
|
16
|
+
* Mapping between the {@link NeonEnv} property paths and the OS-level env-var keys used
|
|
17
|
+
* for cross-process transport (via `.env` files, `env run -- <cmd>`, or anything else
|
|
18
|
+
* that talks to `process.env`).
|
|
19
|
+
*
|
|
20
|
+
* Each top-level key here is a {@link NeonEnv} namespace; the inner record maps the
|
|
21
|
+
* camelCase property names exposed to TypeScript to the UPPER_SNAKE env-var names used
|
|
22
|
+
* by the OS. Keep this in sync with {@link postgresEnvSchema} / {@link authEnvSchema} /
|
|
23
|
+
* {@link dataApiEnvSchema}.
|
|
24
|
+
*/
|
|
25
|
+
/**
|
|
26
|
+
* Neon's default branch owner role, created with every project. This is the role a
|
|
27
|
+
* `DATABASE_URL` should connect as.
|
|
28
|
+
*/
|
|
29
|
+
const NEON_DEFAULT_OWNER_ROLE = "neondb_owner";
|
|
30
|
+
/**
|
|
31
|
+
* Neon's default database, created with every project. When a branch has several databases
|
|
32
|
+
* and none was requested, this is preferred for the `DATABASE_URL` so the common case (a
|
|
33
|
+
* user added a second database next to `neondb`) auto-picks without asking.
|
|
34
|
+
*/
|
|
35
|
+
const NEON_DEFAULT_DATABASE = "neondb";
|
|
36
|
+
/**
|
|
37
|
+
* Roles Neon provisions for the Auth / Data API (PostgREST) stack. They exist to back
|
|
38
|
+
* RLS-scoped Data API requests authenticated by JWT — never to hold a `DATABASE_URL` —
|
|
39
|
+
* so they're skipped when auto-picking the connection role. Enabling Neon Auth or the
|
|
40
|
+
* Data API (`neon config apply`) adds these next to the owner role, which is why a plain
|
|
41
|
+
* branch routinely reports more than one role.
|
|
42
|
+
*/
|
|
43
|
+
const NEON_MANAGED_AUTH_ROLES = /* @__PURE__ */ new Set([
|
|
44
|
+
"authenticator",
|
|
45
|
+
"anonymous",
|
|
46
|
+
"authenticated"
|
|
47
|
+
]);
|
|
48
|
+
const NEON_ENV_VAR_KEYS = {
|
|
49
|
+
/**
|
|
50
|
+
* Branch identity. `NEON_BRANCH` carries the branch **name** and is injected into the
|
|
51
|
+
* Neon Functions runtime on every branch (including the default) by default. `env pull` /
|
|
52
|
+
* `neon dev` / `neon-env run` emit it too so local dev mirrors the deployed runtime.
|
|
53
|
+
*/
|
|
54
|
+
branch: { name: "NEON_BRANCH" },
|
|
55
|
+
postgres: {
|
|
56
|
+
databaseUrl: "DATABASE_URL",
|
|
57
|
+
databaseUrlUnpooled: "DATABASE_URL_UNPOOLED"
|
|
58
|
+
},
|
|
59
|
+
auth: {
|
|
60
|
+
baseUrl: "NEON_AUTH_BASE_URL",
|
|
61
|
+
jwksUrl: "NEON_AUTH_JWKS_URL"
|
|
62
|
+
},
|
|
63
|
+
dataApi: { url: "NEON_DATA_API_URL" },
|
|
64
|
+
/**
|
|
65
|
+
* Object storage (Preview). The S3 SDKs read `AWS_*` from their standard config chain, so
|
|
66
|
+
* a branch credential + `neon dev` / `env pull` makes object storage work from env alone.
|
|
67
|
+
* `region` is injected under the SDK-standard `AWS_REGION`.
|
|
68
|
+
*/
|
|
69
|
+
storage: {
|
|
70
|
+
accessKeyId: "AWS_ACCESS_KEY_ID",
|
|
71
|
+
secretAccessKey: "AWS_SECRET_ACCESS_KEY",
|
|
72
|
+
endpoint: "AWS_ENDPOINT_URL_S3",
|
|
73
|
+
region: "AWS_REGION"
|
|
74
|
+
},
|
|
75
|
+
/**
|
|
76
|
+
* AI Gateway (Preview). Exposed under the Neon-branded env vars the deployed Functions
|
|
77
|
+
* runtime injects: `apiKey` is the minted credential's bearer (`NEON_AI_GATEWAY_TOKEN`)
|
|
78
|
+
* and `baseUrl` is the bare branch gateway host (`NEON_AI_GATEWAY_BASE_URL`,
|
|
79
|
+
* `scheme://host`, no path). Clients like `@neon/ai-sdk-provider` read these and append the
|
|
80
|
+
* dialect route (`/v1`, `/openai/v1`, `/anthropic/v1`) themselves (https://github.com/vercel/ai/pull/15997).
|
|
81
|
+
*/
|
|
82
|
+
aiGateway: {
|
|
83
|
+
apiKey: "NEON_AI_GATEWAY_TOKEN",
|
|
84
|
+
baseUrl: "NEON_AI_GATEWAY_BASE_URL"
|
|
85
|
+
}
|
|
86
|
+
};
|
|
87
|
+
async function fetchEnv(config, options) {
|
|
88
|
+
return fetchEnvKeys(config, options, options.keys ?? null);
|
|
89
|
+
}
|
|
90
|
+
/**
|
|
91
|
+
* The {@link fetchEnv} body, with the key selection as a plain argument and no generic
|
|
92
|
+
* narrowing. Exists for callers that compute the selection at runtime — notably
|
|
93
|
+
* {@link fetchEnvReusingSecrets}, which decides which keys it still needs by checking the
|
|
94
|
+
* branch — since the public overload's `keys` is bound to a literal union those callers cannot
|
|
95
|
+
* produce without asserting.
|
|
96
|
+
*
|
|
97
|
+
* `keys === null` selects everything the policy enables.
|
|
98
|
+
*/
|
|
99
|
+
async function fetchEnvKeys(config, options, keys) {
|
|
100
|
+
const api = options.api ?? createApiFromOptions(options);
|
|
101
|
+
const projectId = options.projectId;
|
|
102
|
+
const { branch, desired } = await resolveBranchPolicy(config, options, api);
|
|
103
|
+
const selection = keys ? new Set(keys) : null;
|
|
104
|
+
const wants = (key) => selection === null || selection.has(key);
|
|
105
|
+
const result = {};
|
|
106
|
+
const [roles, databases] = await Promise.all([api.listBranchRoles(projectId, branch.id), api.listBranchDatabases(projectId, branch.id)]);
|
|
107
|
+
const roleName = pickRoleName(roles, branch, options.roleName);
|
|
108
|
+
const databaseName = pickDatabaseName(databases, branch, options.databaseName);
|
|
109
|
+
const K = NEON_ENV_VAR_KEYS;
|
|
110
|
+
const wantsAuth = desired.authEnabled && (wants(K.auth.baseUrl) || wants(K.auth.jwksUrl));
|
|
111
|
+
const wantsDataApi = desired.dataApiEnabled && wants(K.dataApi.url);
|
|
112
|
+
const [pooled, unpooled, authSnapshot, dataApiSnapshot] = await Promise.all([
|
|
113
|
+
api.getConnectionUri(projectId, {
|
|
114
|
+
branchId: branch.id,
|
|
115
|
+
databaseName,
|
|
116
|
+
roleName,
|
|
117
|
+
pooled: true
|
|
118
|
+
}),
|
|
119
|
+
api.getConnectionUri(projectId, {
|
|
120
|
+
branchId: branch.id,
|
|
121
|
+
databaseName,
|
|
122
|
+
roleName,
|
|
123
|
+
pooled: false
|
|
124
|
+
}),
|
|
125
|
+
wantsAuth ? api.getNeonAuth(projectId, branch.id) : Promise.resolve(null),
|
|
126
|
+
wantsDataApi ? api.getNeonDataApi(projectId, branch.id, databaseName) : Promise.resolve(null)
|
|
127
|
+
]);
|
|
128
|
+
const postgres = {};
|
|
129
|
+
if (wants(K.postgres.databaseUrl)) postgres.databaseUrl = pooled.uri;
|
|
130
|
+
if (wants(K.postgres.databaseUrlUnpooled)) postgres.databaseUrlUnpooled = unpooled.uri;
|
|
131
|
+
if (Object.keys(postgres).length > 0) result.postgres = postgres;
|
|
132
|
+
if (wants(K.branch.name)) result.branch = { name: branch.name };
|
|
133
|
+
if (wantsAuth) {
|
|
134
|
+
if (!authSnapshot) throw new PlatformError(ErrorCode.NotFound, [`fetchEnv: branch policy enables auth but no Neon Auth integration is enabled on branch ${branch.name} (${branch.id}).`, "Enable it via `apply(config, { projectId, branchId })` (or `npx neon …`), in the Neon Console — then re-run fetchEnv. Or return auth.enabled=false."].join(" "), { details: {
|
|
135
|
+
projectId,
|
|
136
|
+
branchId: branch.id
|
|
137
|
+
} });
|
|
138
|
+
const auth = {};
|
|
139
|
+
if (wants(K.auth.baseUrl)) auth.baseUrl = authSnapshot.baseUrl ?? "";
|
|
140
|
+
if (wants(K.auth.jwksUrl)) auth.jwksUrl = authSnapshot.jwksUrl ?? "";
|
|
141
|
+
result.auth = auth;
|
|
142
|
+
}
|
|
143
|
+
if (wantsDataApi) {
|
|
144
|
+
if (!dataApiSnapshot) throw new PlatformError(ErrorCode.NotFound, [`fetchEnv: branch policy enables dataApi but no Data API integration is enabled on branch ${branch.name} (${branch.id}) database ${databaseName}.`, "Enable it via `apply(config, { projectId, branchId })` or in the Neon Console — then re-run fetchEnv. Or return dataApi.enabled=false."].join(" "), { details: {
|
|
145
|
+
projectId,
|
|
146
|
+
branchId: branch.id,
|
|
147
|
+
databaseName
|
|
148
|
+
} });
|
|
149
|
+
result.dataApi = { url: dataApiSnapshot.url };
|
|
150
|
+
}
|
|
151
|
+
const storageEnabled = (desired.preview?.buckets.length ?? 0) > 0;
|
|
152
|
+
const gatewayEnabled = desired.preview?.aiGatewayEnabled ?? false;
|
|
153
|
+
const wantsStorage = storageEnabled && (wants(K.storage.accessKeyId) || wants(K.storage.secretAccessKey) || wants(K.storage.endpoint) || wants(K.storage.region));
|
|
154
|
+
const wantsGateway = gatewayEnabled && (wants(K.aiGateway.apiKey) || wants(K.aiGateway.baseUrl));
|
|
155
|
+
const wantsCredential = storageEnabled && (wants(K.storage.accessKeyId) || wants(K.storage.secretAccessKey)) || gatewayEnabled && wants(K.aiGateway.apiKey);
|
|
156
|
+
if (wantsStorage || wantsGateway) {
|
|
157
|
+
let storage = null;
|
|
158
|
+
if (wantsStorage) {
|
|
159
|
+
storage = await api.getProjectBranchStorage(projectId, branch.id);
|
|
160
|
+
if (!storage) throw new PlatformError(ErrorCode.NotFound, [`fetchEnv: branch policy declares object storage (preview.buckets) but storage is not enabled on branch ${branch.name} (${branch.id}).`, "Enable it via `apply(config, { projectId, branchId })` (or in the Neon Console) — then re-run fetchEnv. Or remove preview.buckets."].join(" "), { details: {
|
|
161
|
+
projectId,
|
|
162
|
+
branchId: branch.id
|
|
163
|
+
} });
|
|
164
|
+
}
|
|
165
|
+
const secrets = wantsCredential ? await mintBranchCredential({
|
|
166
|
+
api,
|
|
167
|
+
projectId,
|
|
168
|
+
branchId: branch.id,
|
|
169
|
+
branchName: branch.name,
|
|
170
|
+
scopes: previewCredentialScopes(desired.preview)
|
|
171
|
+
}) : null;
|
|
172
|
+
if (storage) {
|
|
173
|
+
const storageEnv = {};
|
|
174
|
+
if (secrets && wants(K.storage.accessKeyId)) storageEnv.accessKeyId = secrets.accessKeyId;
|
|
175
|
+
if (secrets && wants(K.storage.secretAccessKey)) storageEnv.secretAccessKey = secrets.secretAccessKey;
|
|
176
|
+
if (wants(K.storage.endpoint)) storageEnv.endpoint = storage.s3Endpoint;
|
|
177
|
+
if (wants(K.storage.region)) storageEnv.region = storage.region;
|
|
178
|
+
result.storage = storageEnv;
|
|
179
|
+
}
|
|
180
|
+
if (wantsGateway) {
|
|
181
|
+
const gateway = {};
|
|
182
|
+
if (secrets && wants(K.aiGateway.apiKey)) gateway.apiKey = secrets.apiToken;
|
|
183
|
+
if (wants(K.aiGateway.baseUrl)) gateway.baseUrl = aiGatewayBaseUrl(branch.id, unpooled.uri);
|
|
184
|
+
result.aiGateway = gateway;
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
return result;
|
|
188
|
+
}
|
|
189
|
+
/**
|
|
190
|
+
* Resolve the target branch and evaluate the policy against it — the first thing any
|
|
191
|
+
* branch-scoped operation needs. Shared by {@link fetchEnv} and {@link fetchEnvReusingSecrets}
|
|
192
|
+
* so the two agree on which branch they're talking about and what it has enabled.
|
|
193
|
+
*/
|
|
194
|
+
async function resolveBranchPolicy(config, options, api) {
|
|
195
|
+
const projectId = options.projectId;
|
|
196
|
+
const branches = await api.listBranches(projectId);
|
|
197
|
+
if (branches.length === 0) throw new PlatformError(ErrorCode.BranchNotFound, [`fetchEnv: project ${projectId} has no branches.`, "Deploy your neon.ts policy (or create a branch) first, or pick a different project id."].join(" "), { details: { projectId } });
|
|
198
|
+
const branchRef = options.branch ?? options.branchId;
|
|
199
|
+
if (!branchRef) throw new PlatformError(ErrorCode.BranchNotFound, ["fetchEnv: no branch provided.", "Pass `branch` with a branch name (e.g. `main`) or id (`br-…`)."].join(" "), { details: { projectId } });
|
|
200
|
+
const branch = resolveBranch(branchRef, branches);
|
|
201
|
+
return {
|
|
202
|
+
branch,
|
|
203
|
+
desired: resolveConfig(config, {
|
|
204
|
+
name: branch.name,
|
|
205
|
+
id: branch.id,
|
|
206
|
+
exists: true,
|
|
207
|
+
...branch.parentId ? { parentId: branch.parentId } : {},
|
|
208
|
+
isDefault: branch.isDefault,
|
|
209
|
+
isProtected: branch.protected,
|
|
210
|
+
...branch.expiresAt ? { expiresAt: branch.expiresAt } : {}
|
|
211
|
+
})
|
|
212
|
+
};
|
|
213
|
+
}
|
|
214
|
+
/**
|
|
215
|
+
* Scopes the branch credential should carry for a resolved branch policy. Only object storage
|
|
216
|
+
* and the AI Gateway *require* a credential; functions never force one (they have no credential
|
|
217
|
+
* of their own), but `functions:invoke` is added to the scope set when a credential is already
|
|
218
|
+
* being minted for storage / the AI Gateway, so the one credential can invoke the branch's
|
|
219
|
+
* functions too. Returns `[]` only when nothing credential-bearing is enabled.
|
|
220
|
+
*/
|
|
221
|
+
function previewCredentialScopes(preview) {
|
|
222
|
+
if (!preview) return [];
|
|
223
|
+
const storage = preview.buckets.length > 0;
|
|
224
|
+
const aiGateway = preview.aiGatewayEnabled;
|
|
225
|
+
if (!storage && !aiGateway) return [];
|
|
226
|
+
return deriveCredentialScopes({
|
|
227
|
+
storage,
|
|
228
|
+
aiGateway,
|
|
229
|
+
functions: preview.functions.length > 0
|
|
230
|
+
});
|
|
231
|
+
}
|
|
232
|
+
/** The `name` this tool stamps on every credential it mints, so it can recognize its own. */
|
|
233
|
+
function credentialName(branchName) {
|
|
234
|
+
return `neon-env ${branchName}`;
|
|
235
|
+
}
|
|
236
|
+
/** The env-var keys a branch credential's secrets surface under, in emit order. */
|
|
237
|
+
function credentialEnvKeys(flags) {
|
|
238
|
+
return [...flags.storage ? [NEON_ENV_VAR_KEYS.storage.accessKeyId, NEON_ENV_VAR_KEYS.storage.secretAccessKey] : [], ...flags.aiGateway ? [NEON_ENV_VAR_KEYS.aiGateway.apiKey] : []];
|
|
239
|
+
}
|
|
240
|
+
/**
|
|
241
|
+
* Every OS-level env var a resolved branch policy produces, in emit order. Lets a caller
|
|
242
|
+
* subtract the ones it already holds and pass the rest as {@link fetchEnv}'s `keys`, without
|
|
243
|
+
* re-deriving which vars a policy implies.
|
|
244
|
+
*/
|
|
245
|
+
function policyEnvKeys(desired) {
|
|
246
|
+
const K = NEON_ENV_VAR_KEYS;
|
|
247
|
+
return [
|
|
248
|
+
K.postgres.databaseUrl,
|
|
249
|
+
K.postgres.databaseUrlUnpooled,
|
|
250
|
+
K.branch.name,
|
|
251
|
+
...desired.authEnabled ? [K.auth.baseUrl, K.auth.jwksUrl] : [],
|
|
252
|
+
...desired.dataApiEnabled ? [K.dataApi.url] : [],
|
|
253
|
+
...(desired.preview?.buckets.length ?? 0) > 0 ? [
|
|
254
|
+
K.storage.accessKeyId,
|
|
255
|
+
K.storage.secretAccessKey,
|
|
256
|
+
K.storage.endpoint,
|
|
257
|
+
K.storage.region
|
|
258
|
+
] : [],
|
|
259
|
+
...desired.preview?.aiGatewayEnabled ? [K.aiGateway.apiKey, K.aiGateway.baseUrl] : []
|
|
260
|
+
];
|
|
261
|
+
}
|
|
262
|
+
/**
|
|
263
|
+
* Mint the branch credential backing object storage / the AI Gateway.
|
|
264
|
+
*
|
|
265
|
+
* `api_token` and `s3_secret_access_key` come back **exactly once** — they are not stored
|
|
266
|
+
* server-side and the list endpoint returns metadata only — so the caller's copy is the only
|
|
267
|
+
* copy. That is why {@link fetchEnv} mints rather than fetches: there is nothing to fetch. A
|
|
268
|
+
* caller that already holds a valid copy should leave the secret keys out of `keys` (see
|
|
269
|
+
* {@link fetchEnvReusingSecrets}) instead of minting one it will discard.
|
|
270
|
+
*/
|
|
271
|
+
async function mintBranchCredential(args) {
|
|
272
|
+
const minted = await args.api.createCredential(args.projectId, args.branchId, {
|
|
273
|
+
scopes: args.scopes,
|
|
274
|
+
principalType: "user",
|
|
275
|
+
name: credentialName(args.branchName)
|
|
276
|
+
});
|
|
277
|
+
return {
|
|
278
|
+
accessKeyId: minted.tokenId,
|
|
279
|
+
secretAccessKey: minted.s3SecretAccessKey,
|
|
280
|
+
apiToken: minted.apiToken
|
|
281
|
+
};
|
|
282
|
+
}
|
|
283
|
+
/**
|
|
284
|
+
* The AI Gateway is a **branch-scoped host** — `<branchId>-api.ai.<host-suffix>` — NOT the
|
|
285
|
+
* control-plane API origin. Derive the suffix from the branch's own Postgres connection host
|
|
286
|
+
* by dropping only the endpoint label (the first segment) and keeping everything after it,
|
|
287
|
+
* including any infra cell prefix (`c-N.`): a connection host of
|
|
288
|
+
* `ep-x.c-3.us-east-2.aws.neon.tech` yields the gateway host
|
|
289
|
+
* `<branchId>-api.ai.c-3.us-east-2.aws.neon.tech`. The cell prefix is **load-bearing** —
|
|
290
|
+
* the gateway is cell-routed, so dropping `c-N.` resolves to the wrong (or no) host.
|
|
291
|
+
*/
|
|
292
|
+
function aiGatewayHost(branchId, connectionUri) {
|
|
293
|
+
let connectionHost = "";
|
|
294
|
+
try {
|
|
295
|
+
connectionHost = new URL(connectionUri).hostname;
|
|
296
|
+
} catch {
|
|
297
|
+
connectionHost = "";
|
|
298
|
+
}
|
|
299
|
+
return `${branchId}-api.ai.${connectionHost.split(".").slice(1).join(".")}`;
|
|
300
|
+
}
|
|
301
|
+
/** The AI Gateway's bare base URL (`NEON_AI_GATEWAY_BASE_URL`) on the branch gateway host. */
|
|
302
|
+
function aiGatewayBaseUrl(branchId, connectionUri) {
|
|
303
|
+
return `https://${aiGatewayHost(branchId, connectionUri)}`;
|
|
304
|
+
}
|
|
305
|
+
function createApiFromOptions(options) {
|
|
306
|
+
return createNeonApiFromOptions("fetchEnv", {
|
|
307
|
+
...options.apiKey ? { apiKey: options.apiKey } : {},
|
|
308
|
+
...options.apiHost ? { apiHost: options.apiHost } : {}
|
|
309
|
+
});
|
|
310
|
+
}
|
|
311
|
+
/**
|
|
312
|
+
* Resolve a branch ref — a name or an id — to a concrete branch. Matches by id first
|
|
313
|
+
* (exact `br-…`), then by name; both are unique within a project, so the lookup is
|
|
314
|
+
* unambiguous. This lets `.neon` files written by `neonctl` (which pin the branch *name*)
|
|
315
|
+
* and explicit `br-…` ids both work.
|
|
316
|
+
*/
|
|
317
|
+
function resolveBranch(branch, branches) {
|
|
318
|
+
const match = branches.find((b) => b.id === branch) ?? branches.find((b) => b.name === branch);
|
|
319
|
+
if (match) return match;
|
|
320
|
+
throw new PlatformError(ErrorCode.BranchNotFound, [`fetchEnv: branch ${JSON.stringify(branch)} not found on project (matched by id or name).`, `Existing branches: ${branches.map((b) => `${b.name} (${b.id})`).join(", ")}.`].join(" "), { details: {
|
|
321
|
+
branch,
|
|
322
|
+
available: branches.map((b) => `${b.name} (${b.id})`)
|
|
323
|
+
} });
|
|
324
|
+
}
|
|
325
|
+
function pickRoleName(roles, branch, requested) {
|
|
326
|
+
if (requested) {
|
|
327
|
+
if (!roles.some((r) => r.name === requested)) throw new PlatformError(ErrorCode.BranchNotFound, [`fetchEnv: role "${requested}" not found on branch ${branch.name} (${branch.id}).`, `Existing roles: ${roles.map((r) => r.name).join(", ") || "(none)"}.`].join(" "), { details: {
|
|
328
|
+
branchId: branch.id,
|
|
329
|
+
roleName: requested,
|
|
330
|
+
availableRoles: roles.map((r) => r.name)
|
|
331
|
+
} });
|
|
332
|
+
return requested;
|
|
333
|
+
}
|
|
334
|
+
if (roles.length === 0) throw new PlatformError(ErrorCode.BranchNotFound, [`fetchEnv: branch ${branch.name} (${branch.id}) has no roles.`, "Create one via the Neon console or pass `roleName` explicitly."].join(" "), { details: { branchId: branch.id } });
|
|
335
|
+
if (roles.length === 1) return roles[0].name;
|
|
336
|
+
const owner = roles.find((r) => r.name === NEON_DEFAULT_OWNER_ROLE);
|
|
337
|
+
if (owner) return owner.name;
|
|
338
|
+
const appRoles = roles.filter((r) => !NEON_MANAGED_AUTH_ROLES.has(r.name));
|
|
339
|
+
if (appRoles.length === 1) return appRoles[0].name;
|
|
340
|
+
throw new PlatformError(ErrorCode.AmbiguousBranchAuth, [`fetchEnv: branch ${branch.name} (${branch.id}) has ${roles.length} roles and none is "${NEON_DEFAULT_OWNER_ROLE}"; cannot auto-pick.`, `Pass \`roleName\` explicitly. Available: ${roles.map((r) => r.name).join(", ")}.`].join(" "), { details: {
|
|
341
|
+
branchId: branch.id,
|
|
342
|
+
availableRoles: roles.map((r) => r.name)
|
|
343
|
+
} });
|
|
344
|
+
}
|
|
345
|
+
function pickDatabaseName(databases, branch, requested) {
|
|
346
|
+
if (requested) {
|
|
347
|
+
if (!databases.some((d) => d.name === requested)) throw new PlatformError(ErrorCode.BranchNotFound, [`fetchEnv: database "${requested}" not found on branch ${branch.name} (${branch.id}).`, `Existing databases: ${databases.map((d) => d.name).join(", ") || "(none)"}.`].join(" "), { details: {
|
|
348
|
+
branchId: branch.id,
|
|
349
|
+
databaseName: requested,
|
|
350
|
+
availableDatabases: databases.map((d) => d.name)
|
|
351
|
+
} });
|
|
352
|
+
return requested;
|
|
353
|
+
}
|
|
354
|
+
if (databases.length === 0) throw new PlatformError(ErrorCode.BranchNotFound, [`fetchEnv: branch ${branch.name} (${branch.id}) has no databases.`, "Create one via the Neon console or pass `databaseName` explicitly."].join(" "), { details: { branchId: branch.id } });
|
|
355
|
+
const neondb = databases.find((d) => d.name === NEON_DEFAULT_DATABASE);
|
|
356
|
+
if (neondb) return neondb.name;
|
|
357
|
+
if (databases.length === 1) return databases[0].name;
|
|
358
|
+
throw new PlatformError(ErrorCode.AmbiguousBranchAuth, [`fetchEnv: branch ${branch.name} (${branch.id}) has ${databases.length} databases and none is named "${NEON_DEFAULT_DATABASE}"; cannot auto-pick.`, `Rename one to "${NEON_DEFAULT_DATABASE}" or keep a single database on the branch (or, when calling fetchEnv directly, pass \`databaseName\`). Available: ${databases.map((d) => d.name).join(", ")}.`].join(" "), { details: {
|
|
359
|
+
branchId: branch.id,
|
|
360
|
+
availableDatabases: databases.map((d) => d.name)
|
|
361
|
+
} });
|
|
362
|
+
}
|
|
363
|
+
/**
|
|
364
|
+
* Project a fully-resolved {@link NeonEnv} into the OS-level `{ KEY: value }` pairs used
|
|
365
|
+
* for cross-process transport. Named after the web-platform `.entries()` convention
|
|
366
|
+
* (`URLSearchParams` / `Headers` / `FormData`); returns a `Record` rather than an
|
|
367
|
+
* iterator of tuples since that's the shape env injection needs (wrap with
|
|
368
|
+
* `Object.entries(...)` if you want literal `[key, value]` pairs). Used by `neon-env run`
|
|
369
|
+
* to inject the vars into a subprocess's `process.env`.
|
|
370
|
+
*
|
|
371
|
+
* Walks the value at runtime so it works for any `NeonEnv<C>` regardless of which
|
|
372
|
+
* conditional namespaces are present.
|
|
373
|
+
*/
|
|
374
|
+
function toEntries(env) {
|
|
375
|
+
const out = {};
|
|
376
|
+
const put = (key, value) => {
|
|
377
|
+
if (value !== void 0) out[key] = value;
|
|
378
|
+
};
|
|
379
|
+
const K = NEON_ENV_VAR_KEYS;
|
|
380
|
+
put(K.postgres.databaseUrl, env.postgres?.databaseUrl);
|
|
381
|
+
put(K.postgres.databaseUrlUnpooled, env.postgres?.databaseUrlUnpooled);
|
|
382
|
+
put(K.branch.name, env.branch?.name);
|
|
383
|
+
put(K.auth.baseUrl, env.auth?.baseUrl);
|
|
384
|
+
put(K.auth.jwksUrl, env.auth?.jwksUrl);
|
|
385
|
+
put(K.dataApi.url, env.dataApi?.url);
|
|
386
|
+
put(K.storage.accessKeyId, env.storage?.accessKeyId);
|
|
387
|
+
put(K.storage.secretAccessKey, env.storage?.secretAccessKey);
|
|
388
|
+
put(K.storage.endpoint, env.storage?.endpoint);
|
|
389
|
+
put(K.storage.region, env.storage?.region);
|
|
390
|
+
put(K.aiGateway.apiKey, env.aiGateway?.apiKey);
|
|
391
|
+
put(K.aiGateway.baseUrl, env.aiGateway?.baseUrl);
|
|
392
|
+
return out;
|
|
393
|
+
}
|
|
394
|
+
//#endregion
|
|
395
|
+
export { NEON_ENV_VAR_KEYS, createApiFromOptions, credentialEnvKeys, credentialName, fetchEnv, fetchEnvKeys, policyEnvKeys, previewCredentialScopes, resolveBranchPolicy, toEntries };
|
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
import { NEON_ENV_VAR_KEYS, createApiFromOptions, credentialEnvKeys, credentialName, fetchEnvKeys, policyEnvKeys, previewCredentialScopes, resolveBranchPolicy, toEntries } from "./env.js";
|
|
2
|
+
import { credentialScopesSatisfied } from "@neon/config/v1";
|
|
3
|
+
//#region src/_shared/env-core/reuse-secrets.ts
|
|
4
|
+
/**
|
|
5
|
+
* Resolve a branch's env while keeping one-time secrets the caller already holds.
|
|
6
|
+
*
|
|
7
|
+
* {@link fetchEnvKeys} — and the public `fetchEnv` — only ever *fetch*. The Neon API returns a
|
|
8
|
+
* credential's `api_token` / `s3_secret_access_key` exactly once, at mint time, so "fetching"
|
|
9
|
+
* them means minting a new credential; a plain `fetchEnv` on every `neon dev` start or `env
|
|
10
|
+
* pull` would leave a live credential behind each time. This is the wrapper that avoids that:
|
|
11
|
+
* it looks at what the caller already has, decides what is still usable, and asks `fetchEnv`
|
|
12
|
+
* for only the rest.
|
|
13
|
+
*
|
|
14
|
+
* The check is a real verification, not a presence test. A persisted secret is kept only when
|
|
15
|
+
* it names a credential that still exists on this branch, is not revoked or expired, and
|
|
16
|
+
* carries every scope the policy needs. A `.env.example` placeholder, a credential revoked in
|
|
17
|
+
* the console, one copied in from another branch, or one predating a newly-enabled feature all
|
|
18
|
+
* fail that check and get replaced.
|
|
19
|
+
*
|
|
20
|
+
* None of this needs local bookkeeping, because the secrets carry their own credential id:
|
|
21
|
+
* `AWS_ACCESS_KEY_ID` **is** the credential's `tokenId` (the storage gateway authenticates
|
|
22
|
+
* against the full id), and the AI Gateway token is minted as `nt_live_<tokenIdShort>_<secret>`,
|
|
23
|
+
* where `tokenIdShort` is what the credentials list reports. The env source being replaced is
|
|
24
|
+
* the record of what the last call issued.
|
|
25
|
+
*
|
|
26
|
+
* ```ts
|
|
27
|
+
* import { fetchEnvReusingSecrets } from "../_shared/env-core/reuse-secrets.js";
|
|
28
|
+
*
|
|
29
|
+
* const { vars, credential } = await fetchEnvReusingSecrets(config, {
|
|
30
|
+
* projectId,
|
|
31
|
+
* branch: "main",
|
|
32
|
+
* env: { ...process.env, ...readEnvFile(".env") },
|
|
33
|
+
* });
|
|
34
|
+
* if (credential.issued) console.log(`new values for ${credential.keys.join(", ")}`);
|
|
35
|
+
* ```
|
|
36
|
+
*/
|
|
37
|
+
async function fetchEnvReusingSecrets(config, options) {
|
|
38
|
+
const { env: source = process.env, revokeSuperseded = true, ...fetchOptions } = options;
|
|
39
|
+
const api = options.api ?? createApiFromOptions(options);
|
|
40
|
+
const { branch, desired } = await resolveBranchPolicy(config, options, api);
|
|
41
|
+
const storageEnabled = (desired.preview?.buckets.length ?? 0) > 0;
|
|
42
|
+
const gatewayEnabled = desired.preview?.aiGatewayEnabled ?? false;
|
|
43
|
+
const secretKeys = credentialEnvKeys({
|
|
44
|
+
storage: storageEnabled,
|
|
45
|
+
aiGateway: gatewayEnabled
|
|
46
|
+
});
|
|
47
|
+
if (secretKeys.length === 0) {
|
|
48
|
+
const fetched = await fetchEnvKeys(config, fetchOptions, null);
|
|
49
|
+
return {
|
|
50
|
+
vars: preferPersisted(toEntries(fetched), source),
|
|
51
|
+
credential: {
|
|
52
|
+
issued: false,
|
|
53
|
+
keys: [],
|
|
54
|
+
revoked: [],
|
|
55
|
+
superseded: []
|
|
56
|
+
}
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
const persisted = readPersistedSecrets(source);
|
|
60
|
+
const complete = (!storageEnabled || Boolean(persisted.accessKeyId && persisted.secretAccessKey)) && (!gatewayEnabled || Boolean(persisted.apiToken));
|
|
61
|
+
const named = persisted.accessKeyId !== "" || persisted.apiToken !== "" ? namedCredentials(await api.listCredentials(options.projectId, branch.id), persisted) : {
|
|
62
|
+
storage: null,
|
|
63
|
+
gateway: null
|
|
64
|
+
};
|
|
65
|
+
const reusable = complete ? reusableCredential(named, {
|
|
66
|
+
storageEnabled,
|
|
67
|
+
gatewayEnabled
|
|
68
|
+
}) : null;
|
|
69
|
+
const scopes = previewCredentialScopes(desired.preview);
|
|
70
|
+
const keep = reusable !== null && credentialScopesSatisfied(reusable.scopes, scopes);
|
|
71
|
+
const allKeys = policyEnvKeys(desired);
|
|
72
|
+
const fetchKeys = keep ? allKeys.filter((key) => !secretKeys.includes(key)) : allKeys;
|
|
73
|
+
const fetched = await fetchEnvKeys(config, {
|
|
74
|
+
...fetchOptions,
|
|
75
|
+
branchId: branch.id,
|
|
76
|
+
api
|
|
77
|
+
}, fetchKeys);
|
|
78
|
+
const vars = preferPersisted(toEntries(fetched), source);
|
|
79
|
+
if (keep) {
|
|
80
|
+
for (const key of secretKeys) {
|
|
81
|
+
const value = source[key];
|
|
82
|
+
if (value !== void 0) vars[key] = value;
|
|
83
|
+
}
|
|
84
|
+
return {
|
|
85
|
+
vars,
|
|
86
|
+
credential: {
|
|
87
|
+
issued: false,
|
|
88
|
+
keys: secretKeys,
|
|
89
|
+
revoked: [],
|
|
90
|
+
superseded: []
|
|
91
|
+
}
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
const ours = /* @__PURE__ */ new Set();
|
|
95
|
+
for (const meta of [named.storage, named.gateway]) if (meta !== null && meta.principalType === "user" && meta.name === credentialName(branch.name)) ours.add(meta.tokenId);
|
|
96
|
+
if (revokeSuperseded) for (const tokenId of ours) await api.revokeCredential(options.projectId, branch.id, tokenId);
|
|
97
|
+
return {
|
|
98
|
+
vars,
|
|
99
|
+
credential: {
|
|
100
|
+
issued: true,
|
|
101
|
+
keys: secretKeys,
|
|
102
|
+
revoked: revokeSuperseded ? [...ours] : [],
|
|
103
|
+
superseded: revokeSuperseded ? [] : [...ours]
|
|
104
|
+
}
|
|
105
|
+
};
|
|
106
|
+
}
|
|
107
|
+
/** Read the branch credential's secrets out of an env source. */
|
|
108
|
+
function readPersistedSecrets(source) {
|
|
109
|
+
const storage = NEON_ENV_VAR_KEYS.storage;
|
|
110
|
+
const gateway = NEON_ENV_VAR_KEYS.aiGateway;
|
|
111
|
+
return {
|
|
112
|
+
accessKeyId: source[storage.accessKeyId] ?? "",
|
|
113
|
+
secretAccessKey: source[storage.secretAccessKey] ?? "",
|
|
114
|
+
apiToken: source[gateway.apiKey] ?? ""
|
|
115
|
+
};
|
|
116
|
+
}
|
|
117
|
+
/**
|
|
118
|
+
* Keep a persisted value rather than overwriting it with an empty fetched one.
|
|
119
|
+
*
|
|
120
|
+
* Neon Auth's `base_url` is the case that needs this: integrations created before the API
|
|
121
|
+
* returned it answer with an empty string, and the persisted copy is the only one left. An
|
|
122
|
+
* empty fetched value never carries more information than a non-empty persisted one, so
|
|
123
|
+
* preferring the latter is safe for every var — and it keeps a pull from blanking a working
|
|
124
|
+
* line in someone's `.env`.
|
|
125
|
+
*/
|
|
126
|
+
function preferPersisted(vars, source) {
|
|
127
|
+
const out = { ...vars };
|
|
128
|
+
for (const [key, value] of Object.entries(out)) {
|
|
129
|
+
if (value !== "") continue;
|
|
130
|
+
const persisted = source[key];
|
|
131
|
+
if (persisted !== void 0 && persisted !== "") out[key] = persisted;
|
|
132
|
+
}
|
|
133
|
+
return out;
|
|
134
|
+
}
|
|
135
|
+
/**
|
|
136
|
+
* The credential id embedded in an AI Gateway token. The API mints them as
|
|
137
|
+
* `nt_live_<tokenIdShort>_<secret>`, and `tokenIdShort` is the public identifier the credentials
|
|
138
|
+
* list reports — so a persisted token names the credential that issued it. Returns `null` for
|
|
139
|
+
* anything not in that shape (a `.env.example` placeholder, a hand-typed value), which callers
|
|
140
|
+
* treat as unverifiable.
|
|
141
|
+
*/
|
|
142
|
+
function gatewayTokenIdShort(apiToken) {
|
|
143
|
+
return /^nt_live_([^_]+)_.+$/.exec(apiToken)?.[1] ?? null;
|
|
144
|
+
}
|
|
145
|
+
/** Whether an issued credential can still be used: not revoked, not past its expiry. */
|
|
146
|
+
function isLiveCredential(meta, now) {
|
|
147
|
+
if (meta.revokedAt !== void 0) return false;
|
|
148
|
+
if (meta.expiresAt === void 0) return true;
|
|
149
|
+
const expiresAt = Date.parse(meta.expiresAt);
|
|
150
|
+
return Number.isNaN(expiresAt) || expiresAt > now;
|
|
151
|
+
}
|
|
152
|
+
/**
|
|
153
|
+
* The live credentials the persisted secrets name — at most one per half. A half that names
|
|
154
|
+
* nothing contributes nothing, which is what a placeholder, a credential revoked in the
|
|
155
|
+
* console, and one copied in from another branch all look like from here.
|
|
156
|
+
*/
|
|
157
|
+
function namedCredentials(live, persisted) {
|
|
158
|
+
const usable = live.filter((meta) => isLiveCredential(meta, Date.now()));
|
|
159
|
+
const shortId = persisted.apiToken ? gatewayTokenIdShort(persisted.apiToken) : null;
|
|
160
|
+
return {
|
|
161
|
+
storage: persisted.accessKeyId ? usable.find((meta) => meta.tokenId === persisted.accessKeyId) ?? null : null,
|
|
162
|
+
gateway: shortId ? usable.find((meta) => meta.tokenIdShort === shortId) ?? null : null
|
|
163
|
+
};
|
|
164
|
+
}
|
|
165
|
+
/**
|
|
166
|
+
* The credential the persisted secrets can be *reused* as, or `null`.
|
|
167
|
+
*
|
|
168
|
+
* Strict on purpose: every half the policy enables has to name a live credential, and when both
|
|
169
|
+
* features are enabled they must name the *same* one — they share a single credential, so
|
|
170
|
+
* halves that disagree came from two different calls and neither can be trusted.
|
|
171
|
+
*/
|
|
172
|
+
function reusableCredential(named, enabled) {
|
|
173
|
+
if (enabled.storageEnabled && enabled.gatewayEnabled) return named.storage && named.gateway && named.storage.tokenId === named.gateway.tokenId ? named.storage : null;
|
|
174
|
+
if (enabled.storageEnabled) return named.storage;
|
|
175
|
+
if (enabled.gatewayEnabled) return named.gateway;
|
|
176
|
+
return null;
|
|
177
|
+
}
|
|
178
|
+
//#endregion
|
|
179
|
+
export { fetchEnvReusingSecrets };
|