@kindgi/secrets-dotenv 0.0.0-bootstrap.0 → 0.1.1
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/LICENSE +201 -0
- package/README.md +67 -1
- package/dist/index.d.ts +19 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +225 -0
- package/dist/index.js.map +1 -0
- package/dist/pack-env.d.ts +54 -0
- package/dist/pack-env.d.ts.map +1 -0
- package/dist/pack-env.js +81 -0
- package/dist/pack-env.js.map +1 -0
- package/package.json +50 -4
- package/src/index.ts +324 -0
- package/src/pack-env.ts +134 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for describing the origin of the Work and
|
|
141
|
+
reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright 2026 Kindgi Inc.
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
package/README.md
CHANGED
|
@@ -1,3 +1,69 @@
|
|
|
1
1
|
# @kindgi/secrets-dotenv
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
The dev-mode `SecretBinding` — secrets for `kindgi dev`, straight from the
|
|
4
|
+
project's env files — plus the one definition of which env files belong
|
|
5
|
+
to a pack environment.
|
|
6
|
+
|
|
7
|
+
Not for production: plaintext on disk, no audit events, no versioning.
|
|
8
|
+
Deployed environments use a durable, encrypted `SecretBinding` or an
|
|
9
|
+
external secrets provider.
|
|
10
|
+
|
|
11
|
+
## Which files
|
|
12
|
+
|
|
13
|
+
| Environment | Files read (lowest precedence first) | Writes go to |
|
|
14
|
+
|---|---|---|
|
|
15
|
+
| `local` (`kindgi dev`) | `.env`, `.env.local` — or `dev.envFiles` from `kindgi.config.ts` | the last file (`.env.local`) |
|
|
16
|
+
| anything else | `.env.<envName>` | the same file |
|
|
17
|
+
|
|
18
|
+
Paths are relative to the pack root. For `local` these are the same files,
|
|
19
|
+
parsed the same way (`@kindgi/dotenv-file`: dotenv grammar, `${VAR}`
|
|
20
|
+
expansion), as the application beside the pack — Kindgi embedded in a
|
|
21
|
+
Next.js app sees exactly what `next dev` sees. A key already in the app's
|
|
22
|
+
`.env` is available to the pack without copying it anywhere.
|
|
23
|
+
|
|
24
|
+
```ts
|
|
25
|
+
import { readPackEnv, resolvePackEnvFiles } from '@kindgi/secrets-dotenv';
|
|
26
|
+
|
|
27
|
+
resolvePackEnvFiles({ packDir, envName: 'local' });
|
|
28
|
+
// → { read: ['<pack>/.env', '<pack>/.env.local'], write: '<pack>/.env.local' }
|
|
29
|
+
|
|
30
|
+
const env = await readPackEnv({ packDir, envName: 'local', env: process.env });
|
|
31
|
+
env.values; // merged + expanded; env.origin says which file supplied each name
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
## Runtime config vs. the pack's secrets
|
|
35
|
+
|
|
36
|
+
One file can hold both. The `KINDGI_` prefix is the line
|
|
37
|
+
(`isRuntimeKey`, `runtimeValues`, `packValues`):
|
|
38
|
+
|
|
39
|
+
- `KINDGI_*` — Kindgi's own runtime config (`KINDGI_DATABASE_URL`, …).
|
|
40
|
+
Never visible through the binding, never written by it.
|
|
41
|
+
- everything else — the pack's. An app's own `DATABASE_URL` is just a name
|
|
42
|
+
the pack could reference; it never configures Kindgi.
|
|
43
|
+
|
|
44
|
+
## The binding
|
|
45
|
+
|
|
46
|
+
```ts
|
|
47
|
+
import { createDotenvSecretBinding } from '@kindgi/secrets-dotenv';
|
|
48
|
+
|
|
49
|
+
const binding = createDotenvSecretBinding({
|
|
50
|
+
packDir,
|
|
51
|
+
localEnvFiles: ['.env', '.env.local'], // optional — dev.envFiles
|
|
52
|
+
env: process.env, // optional — fallback for ${VAR} no file defines
|
|
53
|
+
});
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
- **Reads** (`list`, `get`, `resolve`, `getVersion`, `listVersions`): the
|
|
57
|
+
merged, expanded view without `KINDGI_*`. Versions are synthetic
|
|
58
|
+
(`versionId: 1`).
|
|
59
|
+
- **`set`**: `setKey` on the write target — one line changes, every other
|
|
60
|
+
byte stays; atomic write, mode 0600. `create-new` reports
|
|
61
|
+
`already-exists` if ANY of the files defines the name. Refuses
|
|
62
|
+
`KINDGI_*`, the reserved `kindgi.` prefix, non-POSIX names, and values
|
|
63
|
+
no dotenv quoting can hold.
|
|
64
|
+
- **`rotate` / `revoke`**: unsupported — the error names the files to
|
|
65
|
+
edit.
|
|
66
|
+
- **Scope-blind**: dotenv files are flat; `Scope` is ignored.
|
|
67
|
+
- **`${VAR}`**: resolved across the files; `env` only fills names no file
|
|
68
|
+
defines and never overrides a file's value. Nothing reads `process.env`
|
|
69
|
+
unless you pass it.
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import type { SecretBinding } from '@kindgi/api';
|
|
2
|
+
export { DEFAULT_LOCAL_ENV_FILES, LOCAL_ENV_NAME, type PackEnv, type PackEnvFiles, type PackEnvFilesInput, RUNTIME_KEY_PREFIX, type ReadPackEnvInput, displayEnvPath, isRuntimeKey, packValues, readFileOrNull, readPackEnv, resolvePackEnvFiles, runtimeValues, } from './pack-env.js';
|
|
3
|
+
export interface CreateDotenvSecretBindingOptions {
|
|
4
|
+
/** Pack root — the directory holding `kindgi.config.ts`. */
|
|
5
|
+
readonly packDir: string;
|
|
6
|
+
/**
|
|
7
|
+
* Files read for `local`, lowest precedence first (relative to
|
|
8
|
+
* `packDir`). Defaults to `.env`, `.env.local`. Set it from
|
|
9
|
+
* `dev.envFiles` in `kindgi.config.ts`.
|
|
10
|
+
*/
|
|
11
|
+
readonly localEnvFiles?: readonly string[];
|
|
12
|
+
/**
|
|
13
|
+
* Fallback for `${VAR}` references no file defines — typically the
|
|
14
|
+
* process environment. Never overrides a file's own value.
|
|
15
|
+
*/
|
|
16
|
+
readonly env?: Readonly<Record<string, string | undefined>>;
|
|
17
|
+
}
|
|
18
|
+
export declare function createDotenvSecretBinding(options: CreateDotenvSecretBindingOptions): SecretBinding;
|
|
19
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAgDA,OAAO,KAAK,EACV,aAAa,EAkBd,MAAM,aAAa,CAAC;AAcrB,OAAO,EACL,uBAAuB,EACvB,cAAc,EACd,KAAK,OAAO,EACZ,KAAK,YAAY,EACjB,KAAK,iBAAiB,EACtB,kBAAkB,EAClB,KAAK,gBAAgB,EACrB,cAAc,EACd,YAAY,EACZ,UAAU,EACV,cAAc,EACd,WAAW,EACX,mBAAmB,EACnB,aAAa,GACd,MAAM,eAAe,CAAC;AAEvB,MAAM,WAAW,gCAAgC;IAC/C,4DAA4D;IAC5D,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IACzB;;;;OAIG;IACH,QAAQ,CAAC,aAAa,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IAC3C;;;OAGG;IACH,QAAQ,CAAC,GAAG,CAAC,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,CAAC,CAAC,CAAC;CAC7D;AAID,wBAAgB,yBAAyB,CACvC,OAAO,EAAE,gCAAgC,GACxC,aAAa,CAgJf"}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,225 @@
|
|
|
1
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
// Copyright (C) 2026 Kindgi Inc.
|
|
3
|
+
/**
|
|
4
|
+
* `@kindgi/secrets-dotenv` — dev-mode `SecretBinding` backed by the
|
|
5
|
+
* pack's env files.
|
|
6
|
+
*
|
|
7
|
+
* In local development (`kindgi dev`) the Kindgi runtime uses this binding
|
|
8
|
+
* for two roles: model adapters (Anthropic, OpenAI-compat, …) `resolve`
|
|
9
|
+
* their API key at agent-turn time, and the `/v1/secrets/*` routes
|
|
10
|
+
* (`@kindgi/api`) read and write through it.
|
|
11
|
+
*
|
|
12
|
+
* ## Which files
|
|
13
|
+
*
|
|
14
|
+
* See `pack-env.ts`. For `local` (the environment `kindgi dev` runs as)
|
|
15
|
+
* the binding reads the project's own env files — `.env`, then
|
|
16
|
+
* `.env.local` on top, overridable via `dev.envFiles` — the same files,
|
|
17
|
+
* parsed the same way, as the application beside the pack. A key added
|
|
18
|
+
* to `.env` by hand is a secret the pack can resolve; nothing needs to be
|
|
19
|
+
* copied anywhere. Other environments read `.env.<envName>`.
|
|
20
|
+
*
|
|
21
|
+
* ## Semantics
|
|
22
|
+
*
|
|
23
|
+
* - **Reads** (`list`, `get`, `resolve`, `getVersion`, `listVersions`):
|
|
24
|
+
* the merged, `${VAR}`-expanded view. `KINDGI_*` names are Kindgi
|
|
25
|
+
* runtime config and are invisible here. Version metadata is
|
|
26
|
+
* synthetic (`versionId: 1`) — dotenv files don't version.
|
|
27
|
+
* - **`set`**: writes the highest-precedence file (`.env.local` by
|
|
28
|
+
* default) via `@kindgi/dotenv-file`'s `setKey` — one line changes,
|
|
29
|
+
* every other byte stays. `create-new` returns `already-exists` when
|
|
30
|
+
* the name is defined in ANY of the files. Refuses `KINDGI_*` and the
|
|
31
|
+
* reserved `kindgi.` prefix. Files are written atomically, mode 0600.
|
|
32
|
+
* - **`rotate` / `revoke`**: not supported — the answer is "edit the
|
|
33
|
+
* env file", and the error says which files.
|
|
34
|
+
* - **Scope-blind**: dotenv files are flat, so the `Scope` on every
|
|
35
|
+
* input is ignored. Durable secret stores honor scope.
|
|
36
|
+
*
|
|
37
|
+
* ## NOT for production
|
|
38
|
+
*
|
|
39
|
+
* Plaintext on disk, no audit events, no versioning, no concurrent-write
|
|
40
|
+
* safety, a filesystem read on every `resolve`. Deployments use a
|
|
41
|
+
* durable, encrypted `SecretBinding` or an external secrets provider.
|
|
42
|
+
*/
|
|
43
|
+
import { randomUUID } from 'node:crypto';
|
|
44
|
+
import { chmod, mkdir, rename, writeFile } from 'node:fs/promises';
|
|
45
|
+
import { dirname } from 'node:path';
|
|
46
|
+
import { RESERVED_SECRET_NAME_PREFIX } from '@kindgi/api';
|
|
47
|
+
import { ENV_KEY_REGEX, EnvValueNotRepresentableError, setKey } from '@kindgi/dotenv-file';
|
|
48
|
+
import { displayEnvPath, isRuntimeKey, packValues, readFileOrNull, readPackEnv, } from './pack-env.js';
|
|
49
|
+
export { DEFAULT_LOCAL_ENV_FILES, LOCAL_ENV_NAME, RUNTIME_KEY_PREFIX, displayEnvPath, isRuntimeKey, packValues, readFileOrNull, readPackEnv, resolvePackEnvFiles, runtimeValues, } from './pack-env.js';
|
|
50
|
+
const FILE_MODE = 0o600;
|
|
51
|
+
export function createDotenvSecretBinding(options) {
|
|
52
|
+
const { packDir } = options;
|
|
53
|
+
const load = (envName) => readPackEnv({
|
|
54
|
+
packDir,
|
|
55
|
+
envName: envName,
|
|
56
|
+
...(options.localEnvFiles !== undefined && { localEnvFiles: options.localEnvFiles }),
|
|
57
|
+
...(options.env !== undefined && { env: options.env }),
|
|
58
|
+
});
|
|
59
|
+
const secretsOf = async (envName) => packValues((await load(envName)).values);
|
|
60
|
+
const filesLabel = (env) => env.files.read.map((p) => displayEnvPath(packDir, p)).join(', ');
|
|
61
|
+
async function get(input) {
|
|
62
|
+
return Object.hasOwn(await secretsOf(input.envName), input.name) ? toRecord(input) : null;
|
|
63
|
+
}
|
|
64
|
+
async function list(input) {
|
|
65
|
+
const prefix = input.namePrefix;
|
|
66
|
+
const names = Object.keys(await secretsOf(input.envName))
|
|
67
|
+
.filter((k) => prefix === undefined || k.startsWith(prefix))
|
|
68
|
+
.sort();
|
|
69
|
+
return {
|
|
70
|
+
data: names
|
|
71
|
+
.slice(0, input.limit)
|
|
72
|
+
.map((name) => toRecord({ scope: input.scope, envName: input.envName, name })),
|
|
73
|
+
};
|
|
74
|
+
}
|
|
75
|
+
async function resolve(input) {
|
|
76
|
+
// Attribution context is a no-op here — durable stores use it for
|
|
77
|
+
// the compliance-evidence audit event (see `@kindgi/compliance`).
|
|
78
|
+
void input.resolveContext;
|
|
79
|
+
const env = await load(input.envName);
|
|
80
|
+
const secrets = packValues(env.values);
|
|
81
|
+
if (!Object.hasOwn(secrets, input.name)) {
|
|
82
|
+
return {
|
|
83
|
+
kind: 'err',
|
|
84
|
+
error: {
|
|
85
|
+
code: 'secret-not-found',
|
|
86
|
+
message: `No secret "${input.name}" for env "${input.envName}" in ${filesLabel(env)} at ${packDir}`,
|
|
87
|
+
name: input.name,
|
|
88
|
+
},
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
return {
|
|
92
|
+
kind: 'ok',
|
|
93
|
+
value: { name: input.name, versionId: 1, value: secrets[input.name] ?? '' },
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
async function getVersion(input) {
|
|
97
|
+
if (input.versionId !== 1)
|
|
98
|
+
return null;
|
|
99
|
+
return Object.hasOwn(await secretsOf(input.envName), input.name) ? toVersion(input) : null;
|
|
100
|
+
}
|
|
101
|
+
async function listVersions(input) {
|
|
102
|
+
return Object.hasOwn(await secretsOf(input.envName), input.name)
|
|
103
|
+
? { data: [toVersion(input)] }
|
|
104
|
+
: { data: [] };
|
|
105
|
+
}
|
|
106
|
+
async function set(input) {
|
|
107
|
+
const refused = refusedName(input.name);
|
|
108
|
+
if (refused !== undefined)
|
|
109
|
+
return storeError(refused);
|
|
110
|
+
// dotenv only ever exposes version 1, so any other ifVersion is stale.
|
|
111
|
+
if (input.ifVersion !== undefined && input.ifVersion !== 1) {
|
|
112
|
+
return { kind: 'version-conflict', currentVersion: 1 };
|
|
113
|
+
}
|
|
114
|
+
let env;
|
|
115
|
+
try {
|
|
116
|
+
env = await load(input.envName);
|
|
117
|
+
}
|
|
118
|
+
catch (err) {
|
|
119
|
+
return storeError(`Failed to read env files: ${err.message}`);
|
|
120
|
+
}
|
|
121
|
+
const existing = Object.hasOwn(env.values, input.name);
|
|
122
|
+
if (input.writeMode === 'create-new' && existing) {
|
|
123
|
+
return { kind: 'already-exists', record: toRecord(input) };
|
|
124
|
+
}
|
|
125
|
+
const failure = await writeKey(env.files.write, input.name, input.value);
|
|
126
|
+
if (failure !== undefined)
|
|
127
|
+
return storeError(failure);
|
|
128
|
+
// Authorization-tuple hook (`enqueueTuples`) — invoked ONLY on fresh
|
|
129
|
+
// insert per the SecretBinding contract. Dev mode has no transaction
|
|
130
|
+
// or outbox to persist to, but the hook runs so the caller's
|
|
131
|
+
// side-effects (if any) still happen.
|
|
132
|
+
if (!existing)
|
|
133
|
+
void input.enqueueTuples(randomUUID());
|
|
134
|
+
return { kind: 'ok', record: toRecord(input), versionId: 1 };
|
|
135
|
+
}
|
|
136
|
+
/** `setKey` into `file` and write it back atomically; the error message on failure. */
|
|
137
|
+
async function writeKey(file, name, value) {
|
|
138
|
+
const label = displayEnvPath(packDir, file);
|
|
139
|
+
let contents;
|
|
140
|
+
try {
|
|
141
|
+
contents = setKey((await readFileOrNull(file)) ?? '', name, value).contents;
|
|
142
|
+
}
|
|
143
|
+
catch (err) {
|
|
144
|
+
if (err instanceof EnvValueNotRepresentableError)
|
|
145
|
+
return err.message;
|
|
146
|
+
return `Failed to read ${label}: ${err.message}`;
|
|
147
|
+
}
|
|
148
|
+
try {
|
|
149
|
+
await writeAtomic(file, contents);
|
|
150
|
+
return undefined;
|
|
151
|
+
}
|
|
152
|
+
catch (err) {
|
|
153
|
+
return `Failed to write ${label}: ${err.message}`;
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
async function rotate(input) {
|
|
157
|
+
const env = await load(input.envName);
|
|
158
|
+
return {
|
|
159
|
+
kind: 'err',
|
|
160
|
+
error: {
|
|
161
|
+
code: 'secret-store-error',
|
|
162
|
+
message: `Dev secrets live in your env files (${filesLabel(env)}) and have no versions to rotate. Edit the value there, or run \`kindgi secrets set ${input.name} --write-mode=add-version\`.`,
|
|
163
|
+
},
|
|
164
|
+
};
|
|
165
|
+
}
|
|
166
|
+
async function revoke(input) {
|
|
167
|
+
const env = await load(input.envName);
|
|
168
|
+
return {
|
|
169
|
+
kind: 'err',
|
|
170
|
+
error: {
|
|
171
|
+
code: 'secret-store-error',
|
|
172
|
+
message: `Dev secrets live in your env files (${filesLabel(env)}) and have no revocation. Remove ${input.name} from those files.`,
|
|
173
|
+
},
|
|
174
|
+
};
|
|
175
|
+
}
|
|
176
|
+
return { list, get, resolve, getVersion, listVersions, set, rotate, revoke };
|
|
177
|
+
}
|
|
178
|
+
// ---------------------------------------------------------------------
|
|
179
|
+
// Helpers
|
|
180
|
+
// ---------------------------------------------------------------------
|
|
181
|
+
function refusedName(name) {
|
|
182
|
+
if (isRuntimeKey(name)) {
|
|
183
|
+
return `"${name}" is Kindgi runtime config (KINDGI_*), not a pack secret. Set it in your shell or env file directly.`;
|
|
184
|
+
}
|
|
185
|
+
if (name.startsWith(RESERVED_SECRET_NAME_PREFIX)) {
|
|
186
|
+
return `Name "${name}" uses the reserved "${RESERVED_SECRET_NAME_PREFIX}" prefix; framework-internal only.`;
|
|
187
|
+
}
|
|
188
|
+
if (!ENV_KEY_REGEX.test(name)) {
|
|
189
|
+
return `Invalid secret name "${name}" for an env file — must match ${ENV_KEY_REGEX.source}.`;
|
|
190
|
+
}
|
|
191
|
+
return undefined;
|
|
192
|
+
}
|
|
193
|
+
function storeError(message) {
|
|
194
|
+
return { kind: 'error', code: 'secret-store-error', message };
|
|
195
|
+
}
|
|
196
|
+
function toRecord(input) {
|
|
197
|
+
const iso = new Date(0).toISOString();
|
|
198
|
+
return {
|
|
199
|
+
scope: input.scope,
|
|
200
|
+
envName: input.envName,
|
|
201
|
+
name: input.name,
|
|
202
|
+
currentVersion: 1,
|
|
203
|
+
createdAt: iso,
|
|
204
|
+
updatedAt: iso,
|
|
205
|
+
};
|
|
206
|
+
}
|
|
207
|
+
function toVersion(input) {
|
|
208
|
+
return {
|
|
209
|
+
scope: input.scope,
|
|
210
|
+
envName: input.envName,
|
|
211
|
+
name: input.name,
|
|
212
|
+
versionId: 1,
|
|
213
|
+
value: null,
|
|
214
|
+
createdAt: new Date(0).toISOString(),
|
|
215
|
+
};
|
|
216
|
+
}
|
|
217
|
+
/** Write-tmp + rename, mode 0600 (chmod again: rename can keep a looser mode). */
|
|
218
|
+
async function writeAtomic(target, contents) {
|
|
219
|
+
await mkdir(dirname(target), { recursive: true });
|
|
220
|
+
const tmp = `${target}.${process.pid}.${Date.now()}.tmp`;
|
|
221
|
+
await writeFile(tmp, contents, { mode: FILE_MODE });
|
|
222
|
+
await rename(tmp, target);
|
|
223
|
+
await chmod(target, FILE_MODE);
|
|
224
|
+
}
|
|
225
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,sCAAsC;AACtC,iCAAiC;AAEjC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAuCG;AAEH,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,KAAK,EAAE,KAAK,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AACnE,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAsBpC,OAAO,EAAE,2BAA2B,EAAE,MAAM,aAAa,CAAC;AAC1D,OAAO,EAAE,aAAa,EAAE,6BAA6B,EAAE,MAAM,EAAE,MAAM,qBAAqB,CAAC;AAG3F,OAAO,EAEL,cAAc,EACd,YAAY,EACZ,UAAU,EACV,cAAc,EACd,WAAW,GACZ,MAAM,eAAe,CAAC;AAEvB,OAAO,EACL,uBAAuB,EACvB,cAAc,EAId,kBAAkB,EAElB,cAAc,EACd,YAAY,EACZ,UAAU,EACV,cAAc,EACd,WAAW,EACX,mBAAmB,EACnB,aAAa,GACd,MAAM,eAAe,CAAC;AAkBvB,MAAM,SAAS,GAAG,KAAK,CAAC;AAExB,MAAM,UAAU,yBAAy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,MAAM,CAAC,CAAC;IAC1B,MAAM,KAAK,CAAC,MAAM,EAAE,SAAS,CAAC,CAAC;AACjC,CAAC"}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import { type EnvDiagnostic } from '@kindgi/dotenv-file';
|
|
2
|
+
/** The environment `kindgi dev` runs as. */
|
|
3
|
+
export declare const LOCAL_ENV_NAME = "local";
|
|
4
|
+
/** Files read for `local`, lowest precedence first. */
|
|
5
|
+
export declare const DEFAULT_LOCAL_ENV_FILES: readonly string[];
|
|
6
|
+
/** Names with this prefix are Kindgi runtime config, never pack secrets. */
|
|
7
|
+
export declare const RUNTIME_KEY_PREFIX = "KINDGI_";
|
|
8
|
+
export declare function isRuntimeKey(name: string): boolean;
|
|
9
|
+
export interface PackEnvFilesInput {
|
|
10
|
+
/** Pack root — the directory holding `kindgi.config.ts`. */
|
|
11
|
+
readonly packDir: string;
|
|
12
|
+
readonly envName: string;
|
|
13
|
+
/**
|
|
14
|
+
* Files read for `local`, lowest precedence first; relative paths
|
|
15
|
+
* resolve against `packDir`. Defaults to `DEFAULT_LOCAL_ENV_FILES`.
|
|
16
|
+
* Ignored for every other environment.
|
|
17
|
+
*/
|
|
18
|
+
readonly localEnvFiles?: readonly string[];
|
|
19
|
+
}
|
|
20
|
+
export interface PackEnvFiles {
|
|
21
|
+
/** Absolute paths, lowest precedence first. */
|
|
22
|
+
readonly read: readonly string[];
|
|
23
|
+
/** Where a write lands — the highest-precedence file. */
|
|
24
|
+
readonly write: string;
|
|
25
|
+
}
|
|
26
|
+
export declare function resolvePackEnvFiles(input: PackEnvFilesInput): PackEnvFiles;
|
|
27
|
+
/** Display form of a pack env file path (relative to the pack when inside it). */
|
|
28
|
+
export declare function displayEnvPath(packDir: string, path: string): string;
|
|
29
|
+
export interface ReadPackEnvInput extends PackEnvFilesInput {
|
|
30
|
+
/**
|
|
31
|
+
* Fallback for `${VAR}` references no file defines — typically the
|
|
32
|
+
* process environment. Never overrides a file's own value.
|
|
33
|
+
*/
|
|
34
|
+
readonly env?: Readonly<Record<string, string | undefined>>;
|
|
35
|
+
/** File reader: contents, or `null` when the file does not exist. */
|
|
36
|
+
readonly readFile?: (path: string) => Promise<string | null>;
|
|
37
|
+
}
|
|
38
|
+
export interface PackEnv {
|
|
39
|
+
readonly files: PackEnvFiles;
|
|
40
|
+
/** Files that exist, lowest precedence first. */
|
|
41
|
+
readonly present: readonly string[];
|
|
42
|
+
/** Every name the files define — runtime and pack — merged and expanded. */
|
|
43
|
+
readonly values: Readonly<Record<string, string>>;
|
|
44
|
+
/** For each name, the file that supplied it. */
|
|
45
|
+
readonly origin: Readonly<Record<string, string>>;
|
|
46
|
+
readonly diagnostics: readonly EnvDiagnostic[];
|
|
47
|
+
}
|
|
48
|
+
export declare function readPackEnv(input: ReadPackEnvInput): Promise<PackEnv>;
|
|
49
|
+
/** The pack's names only (`KINDGI_*` removed). */
|
|
50
|
+
export declare function packValues(values: Readonly<Record<string, string>>): Record<string, string>;
|
|
51
|
+
/** Kindgi's runtime config only (`KINDGI_*`). */
|
|
52
|
+
export declare function runtimeValues(values: Readonly<Record<string, string>>): Record<string, string>;
|
|
53
|
+
export declare function readFileOrNull(path: string): Promise<string | null>;
|
|
54
|
+
//# sourceMappingURL=pack-env.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"pack-env.d.ts","sourceRoot":"","sources":["../src/pack-env.ts"],"names":[],"mappings":"AA2BA,OAAO,EAAE,KAAK,aAAa,EAAiB,MAAM,qBAAqB,CAAC;AAExE,4CAA4C;AAC5C,eAAO,MAAM,cAAc,UAAU,CAAC;AAEtC,uDAAuD;AACvD,eAAO,MAAM,uBAAuB,EAAE,SAAS,MAAM,EAA2B,CAAC;AAEjF,4EAA4E;AAC5E,eAAO,MAAM,kBAAkB,YAAY,CAAC;AAE5C,wBAAgB,YAAY,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAElD;AAED,MAAM,WAAW,iBAAiB;IAChC,4DAA4D;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AC,KAAK,EAAE,gBAAgB,GAAG,OAAO,CAAC,OAAO,CAAC,CAc3E;AAED,kDAAkD;AAClD,wBAAgB,UAAU,CAAC,MAAM,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAE3F;AAED,iDAAiD;AACjD,wBAAgB,aAAa,CAAC,MAAM,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAE9F;AAED,wBAAsB,cAAc,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,CAOzE"}
|
package/dist/pack-env.js
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
// Copyright (C) 2026 Kindgi Inc.
|
|
3
|
+
/**
|
|
4
|
+
* Which env files belong to a pack environment, and what they hold.
|
|
5
|
+
*
|
|
6
|
+
* **`local` — `kindgi dev`.** The project's own env files, read the way
|
|
7
|
+
* the application beside the pack reads them: `.env`, then `.env.local`
|
|
8
|
+
* on top (override per pack with `dev.envFiles` in `kindgi.config.ts`).
|
|
9
|
+
* Kindgi reads them; it writes only when asked (an explicit secret or
|
|
10
|
+
* env `set`), and then to the highest-precedence file so the new value
|
|
11
|
+
* wins.
|
|
12
|
+
*
|
|
13
|
+
* **Any other environment** (`staging`, `production`, …) — one file,
|
|
14
|
+
* `.env.<envName>`, read and written as-is. Deployed environments keep
|
|
15
|
+
* their real secrets in the runtime's secret store; these files carry
|
|
16
|
+
* per-environment values to push there.
|
|
17
|
+
*
|
|
18
|
+
* **Runtime vs. agents.** One file can hold both Kindgi's own runtime
|
|
19
|
+
* config and the values the pack's agents use. The `KINDGI_` prefix is
|
|
20
|
+
* the line: `KINDGI_*` names configure Kindgi and are never exposed as
|
|
21
|
+
* secrets; every other name belongs to the pack.
|
|
22
|
+
*/
|
|
23
|
+
import { readFile as fsReadFile } from 'node:fs/promises';
|
|
24
|
+
import { isAbsolute, join, relative } from 'node:path';
|
|
25
|
+
import { readEnvLayers } from '@kindgi/dotenv-file';
|
|
26
|
+
/** The environment `kindgi dev` runs as. */
|
|
27
|
+
export const LOCAL_ENV_NAME = 'local';
|
|
28
|
+
/** Files read for `local`, lowest precedence first. */
|
|
29
|
+
export const DEFAULT_LOCAL_ENV_FILES = ['.env', '.env.local'];
|
|
30
|
+
/** Names with this prefix are Kindgi runtime config, never pack secrets. */
|
|
31
|
+
export const RUNTIME_KEY_PREFIX = 'KINDGI_';
|
|
32
|
+
export function isRuntimeKey(name) {
|
|
33
|
+
return name.startsWith(RUNTIME_KEY_PREFIX);
|
|
34
|
+
}
|
|
35
|
+
export function resolvePackEnvFiles(input) {
|
|
36
|
+
const names = input.envName === LOCAL_ENV_NAME
|
|
37
|
+
? (input.localEnvFiles ?? DEFAULT_LOCAL_ENV_FILES)
|
|
38
|
+
: [`.env.${input.envName}`];
|
|
39
|
+
if (names.length === 0) {
|
|
40
|
+
throw new TypeError('localEnvFiles must list at least one file.');
|
|
41
|
+
}
|
|
42
|
+
const read = names.map((n) => (isAbsolute(n) ? n : join(input.packDir, n)));
|
|
43
|
+
return { read, write: read[read.length - 1] };
|
|
44
|
+
}
|
|
45
|
+
/** Display form of a pack env file path (relative to the pack when inside it). */
|
|
46
|
+
export function displayEnvPath(packDir, path) {
|
|
47
|
+
const rel = relative(packDir, path);
|
|
48
|
+
return rel !== '' && !rel.startsWith('..') && !isAbsolute(rel) ? rel : path;
|
|
49
|
+
}
|
|
50
|
+
export async function readPackEnv(input) {
|
|
51
|
+
const files = resolvePackEnvFiles(input);
|
|
52
|
+
const read = input.readFile ?? readFileOrNull;
|
|
53
|
+
const layers = await Promise.all(files.read.map(async (source) => ({ source, contents: await read(source) })));
|
|
54
|
+
const view = readEnvLayers(layers, input.env !== undefined ? { env: input.env } : {});
|
|
55
|
+
return {
|
|
56
|
+
files,
|
|
57
|
+
present: view.present,
|
|
58
|
+
values: view.values,
|
|
59
|
+
origin: view.origin,
|
|
60
|
+
diagnostics: view.diagnostics,
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
/** The pack's names only (`KINDGI_*` removed). */
|
|
64
|
+
export function packValues(values) {
|
|
65
|
+
return Object.fromEntries(Object.entries(values).filter(([name]) => !isRuntimeKey(name)));
|
|
66
|
+
}
|
|
67
|
+
/** Kindgi's runtime config only (`KINDGI_*`). */
|
|
68
|
+
export function runtimeValues(values) {
|
|
69
|
+
return Object.fromEntries(Object.entries(values).filter(([name]) => isRuntimeKey(name)));
|
|
70
|
+
}
|
|
71
|
+
export async function readFileOrNull(path) {
|
|
72
|
+
try {
|
|
73
|
+
return await fsReadFile(path, 'utf8');
|
|
74
|
+
}
|
|
75
|
+
catch (err) {
|
|
76
|
+
if (err.code === 'ENOENT')
|
|
77
|
+
return null;
|
|
78
|
+
throw err;
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
//# sourceMappingURL=pack-env.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"pack-env.js","sourceRoot":"","sources":["../src/pack-env.ts"],"names":[],"mappings":"AAAA,sCAAsC;AACtC,iCAAiC;AAEjC;;;;;;;;;;;;;;;;;;;GAmBG;AAEH,OAAO,EAAE,QAAQ,IAAI,UAAU,EAAE,MAAM,kBAAkB,CAAC;AAC1D,OAAO,EAAE,UAAU,EAAE,IAAI,EAAE,QAAQ,EAAE,MAAM,WAAW,CAAC;AAEvD,OAAO,EAAsB,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAExE,4CAA4C;AAC5C,MAAM,CAAC,MAAM,cAAc,GAAG,OAAO,CAAC;AAEtC,uDAAuD;AACvD,MAAM,CAAC,MAAM,uBAAuB,GAAsB,CAAC,MAAM,EAAE,YAAY,CAAC,CAAC;AAEjF,4EAA4E;AAC5E,MAAM,CAAC,MAAM,k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AAE,MAAM,CAAC,CAAC;IACxC,CAAC;IAAC,OAAO,GAAG,EAAE,CAAC;QACb,IAAK,GAA6B,CAAC,IAAI,KAAK,QAAQ;YAAE,OAAO,IAAI,CAAC;QAClE,MAAM,GAAG,CAAC;IACZ,CAAC;AACH,CAAC"}
|
package/package.json
CHANGED
|
@@ -1,7 +1,53 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@kindgi/secrets-dotenv",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"description": "Dev-mode `SecretBinding` over the project's own env files (`.env`, then `.env.local`, or `dev.envFiles`) — the same files, parsed the same way, as the app beside the pack — plus the one definition of which env files belong to a pack environment. `KINDGI_*` names are runtime config, never secrets. Not for production — no encryption, no audit, no versioning.",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
|
-
"repository": {
|
|
7
|
-
|
|
6
|
+
"repository": {
|
|
7
|
+
"type": "git",
|
|
8
|
+
"url": "git+https://github.com/kindgi/kindgi-sdk.git",
|
|
9
|
+
"directory": "packages/secrets-dotenv"
|
|
10
|
+
},
|
|
11
|
+
"homepage": "https://github.com/kindgi/kindgi-sdk/tree/main/packages/secrets-dotenv#readme",
|
|
12
|
+
"bugs": {
|
|
13
|
+
"url": "https://github.com/kindgi/kindgi-sdk/issues"
|
|
14
|
+
},
|
|
15
|
+
"type": "module",
|
|
16
|
+
"main": "./dist/index.js",
|
|
17
|
+
"types": "./dist/index.d.ts",
|
|
18
|
+
"exports": {
|
|
19
|
+
".": {
|
|
20
|
+
"types": "./dist/index.d.ts",
|
|
21
|
+
"import": "./dist/index.js"
|
|
22
|
+
}
|
|
23
|
+
},
|
|
24
|
+
"files": [
|
|
25
|
+
"dist",
|
|
26
|
+
"src",
|
|
27
|
+
"README.md"
|
|
28
|
+
],
|
|
29
|
+
"dependencies": {
|
|
30
|
+
"@kindgi/api": "0.1.1",
|
|
31
|
+
"@kindgi/dotenv-file": "0.1.1",
|
|
32
|
+
"@kindgi/platform": "0.1.1",
|
|
33
|
+
"@kindgi/types": "0.1.1"
|
|
34
|
+
},
|
|
35
|
+
"devDependencies": {
|
|
36
|
+
"@types/node": "^22.10.5",
|
|
37
|
+
"typescript": "^5.7.3",
|
|
38
|
+
"vitest": "^2.1.8"
|
|
39
|
+
},
|
|
40
|
+
"engines": {
|
|
41
|
+
"node": ">=22.0.0"
|
|
42
|
+
},
|
|
43
|
+
"publishConfig": {
|
|
44
|
+
"access": "public",
|
|
45
|
+
"provenance": true
|
|
46
|
+
},
|
|
47
|
+
"scripts": {
|
|
48
|
+
"build": "tsc -p tsconfig.build.json",
|
|
49
|
+
"typecheck": "tsc --noEmit",
|
|
50
|
+
"test": "vitest run --passWithNoTests",
|
|
51
|
+
"clean": "rm -rf dist *.tsbuildinfo"
|
|
52
|
+
}
|
|
53
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,324 @@
|
|
|
1
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
// Copyright (C) 2026 Kindgi Inc.
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* `@kindgi/secrets-dotenv` — dev-mode `SecretBinding` backed by the
|
|
6
|
+
* pack's env files.
|
|
7
|
+
*
|
|
8
|
+
* In local development (`kindgi dev`) the Kindgi runtime uses this binding
|
|
9
|
+
* for two roles: model adapters (Anthropic, OpenAI-compat, …) `resolve`
|
|
10
|
+
* their API key at agent-turn time, and the `/v1/secrets/*` routes
|
|
11
|
+
* (`@kindgi/api`) read and write through it.
|
|
12
|
+
*
|
|
13
|
+
* ## Which files
|
|
14
|
+
*
|
|
15
|
+
* See `pack-env.ts`. For `local` (the environment `kindgi dev` runs as)
|
|
16
|
+
* the binding reads the project's own env files — `.env`, then
|
|
17
|
+
* `.env.local` on top, overridable via `dev.envFiles` — the same files,
|
|
18
|
+
* parsed the same way, as the application beside the pack. A key added
|
|
19
|
+
* to `.env` by hand is a secret the pack can resolve; nothing needs to be
|
|
20
|
+
* copied anywhere. Other environments read `.env.<envName>`.
|
|
21
|
+
*
|
|
22
|
+
* ## Semantics
|
|
23
|
+
*
|
|
24
|
+
* - **Reads** (`list`, `get`, `resolve`, `getVersion`, `listVersions`):
|
|
25
|
+
* the merged, `${VAR}`-expanded view. `KINDGI_*` names are Kindgi
|
|
26
|
+
* runtime config and are invisible here. Version metadata is
|
|
27
|
+
* synthetic (`versionId: 1`) — dotenv files don't version.
|
|
28
|
+
* - **`set`**: writes the highest-precedence file (`.env.local` by
|
|
29
|
+
* default) via `@kindgi/dotenv-file`'s `setKey` — one line changes,
|
|
30
|
+
* every other byte stays. `create-new` returns `already-exists` when
|
|
31
|
+
* the name is defined in ANY of the files. Refuses `KINDGI_*` and the
|
|
32
|
+
* reserved `kindgi.` prefix. Files are written atomically, mode 0600.
|
|
33
|
+
* - **`rotate` / `revoke`**: not supported — the answer is "edit the
|
|
34
|
+
* env file", and the error says which files.
|
|
35
|
+
* - **Scope-blind**: dotenv files are flat, so the `Scope` on every
|
|
36
|
+
* input is ignored. Durable secret stores honor scope.
|
|
37
|
+
*
|
|
38
|
+
* ## NOT for production
|
|
39
|
+
*
|
|
40
|
+
* Plaintext on disk, no audit events, no versioning, no concurrent-write
|
|
41
|
+
* safety, a filesystem read on every `resolve`. Deployments use a
|
|
42
|
+
* durable, encrypted `SecretBinding` or an external secrets provider.
|
|
43
|
+
*/
|
|
44
|
+
|
|
45
|
+
import { randomUUID } from 'node:crypto';
|
|
46
|
+
import { chmod, mkdir, rename, writeFile } from 'node:fs/promises';
|
|
47
|
+
import { dirname } from 'node:path';
|
|
48
|
+
|
|
49
|
+
import type {
|
|
50
|
+
SecretBinding,
|
|
51
|
+
SecretError,
|
|
52
|
+
SecretGetInput,
|
|
53
|
+
SecretGetVersionInput,
|
|
54
|
+
SecretListInput,
|
|
55
|
+
SecretListPage,
|
|
56
|
+
SecretListVersionsInput,
|
|
57
|
+
SecretRecord,
|
|
58
|
+
SecretResolveInput,
|
|
59
|
+
SecretResolveOutcome,
|
|
60
|
+
SecretRevokeInput,
|
|
61
|
+
SecretRevokeOutcome,
|
|
62
|
+
SecretRotateInput,
|
|
63
|
+
SecretRotateOutcome,
|
|
64
|
+
SecretSetInput,
|
|
65
|
+
SecretSetOutcome,
|
|
66
|
+
SecretVersionPage,
|
|
67
|
+
SecretVersionRecord,
|
|
68
|
+
} from '@kindgi/api';
|
|
69
|
+
import { RESERVED_SECRET_NAME_PREFIX } from '@kindgi/api';
|
|
70
|
+
import { ENV_KEY_REGEX, EnvValueNotRepresentableError, setKey } from '@kindgi/dotenv-file';
|
|
71
|
+
import type { Result } from '@kindgi/types';
|
|
72
|
+
|
|
73
|
+
import {
|
|
74
|
+
type PackEnv,
|
|
75
|
+
displayEnvPath,
|
|
76
|
+
isRuntimeKey,
|
|
77
|
+
packValues,
|
|
78
|
+
readFileOrNull,
|
|
79
|
+
readPackEnv,
|
|
80
|
+
} from './pack-env.js';
|
|
81
|
+
|
|
82
|
+
export {
|
|
83
|
+
DEFAULT_LOCAL_ENV_FILES,
|
|
84
|
+
LOCAL_ENV_NAME,
|
|
85
|
+
type PackEnv,
|
|
86
|
+
type PackEnvFiles,
|
|
87
|
+
type PackEnvFilesInput,
|
|
88
|
+
RUNTIME_KEY_PREFIX,
|
|
89
|
+
type ReadPackEnvInput,
|
|
90
|
+
displayEnvPath,
|
|
91
|
+
isRuntimeKey,
|
|
92
|
+
packValues,
|
|
93
|
+
readFileOrNull,
|
|
94
|
+
readPackEnv,
|
|
95
|
+
resolvePackEnvFiles,
|
|
96
|
+
runtimeValues,
|
|
97
|
+
} from './pack-env.js';
|
|
98
|
+
|
|
99
|
+
export interface CreateDotenvSecretBindingOptions {
|
|
100
|
+
/** Pack root — the directory holding `kindgi.config.ts`. */
|
|
101
|
+
readonly packDir: string;
|
|
102
|
+
/**
|
|
103
|
+
* Files read for `local`, lowest precedence first (relative to
|
|
104
|
+
* `packDir`). Defaults to `.env`, `.env.local`. Set it from
|
|
105
|
+
* `dev.envFiles` in `kindgi.config.ts`.
|
|
106
|
+
*/
|
|
107
|
+
readonly localEnvFiles?: readonly string[];
|
|
108
|
+
/**
|
|
109
|
+
* Fallback for `${VAR}` references no file defines — typically the
|
|
110
|
+
* process environment. Never overrides a file's own value.
|
|
111
|
+
*/
|
|
112
|
+
readonly env?: Readonly<Record<string, string | undefined>>;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
const FILE_MODE = 0o600;
|
|
116
|
+
|
|
117
|
+
export function createDotenvSecretBinding(
|
|
118
|
+
options: CreateDotenvSecretBindingOptions,
|
|
119
|
+
): SecretBinding {
|
|
120
|
+
const { packDir } = options;
|
|
121
|
+
|
|
122
|
+
const load = (envName: SecretRecord['envName']): Promise<PackEnv> =>
|
|
123
|
+
readPackEnv({
|
|
124
|
+
packDir,
|
|
125
|
+
envName: envName as unknown as string,
|
|
126
|
+
...(options.localEnvFiles !== undefined && { localEnvFiles: options.localEnvFiles }),
|
|
127
|
+
...(options.env !== undefined && { env: options.env }),
|
|
128
|
+
});
|
|
129
|
+
|
|
130
|
+
const secretsOf = async (envName: SecretRecord['envName']): Promise<Record<string, string>> =>
|
|
131
|
+
packValues((await load(envName)).values);
|
|
132
|
+
|
|
133
|
+
const filesLabel = (env: PackEnv): string =>
|
|
134
|
+
env.files.read.map((p) => displayEnvPath(packDir, p)).join(', ');
|
|
135
|
+
|
|
136
|
+
async function get(input: SecretGetInput): Promise<SecretRecord | null> {
|
|
137
|
+
return Object.hasOwn(await secretsOf(input.envName), input.name) ? toRecord(input) : null;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
async function list(input: SecretListInput): Promise<SecretListPage> {
|
|
141
|
+
const prefix = input.namePrefix;
|
|
142
|
+
const names = Object.keys(await secretsOf(input.envName))
|
|
143
|
+
.filter((k) => prefix === undefined || k.startsWith(prefix))
|
|
144
|
+
.sort();
|
|
145
|
+
return {
|
|
146
|
+
data: names
|
|
147
|
+
.slice(0, input.limit)
|
|
148
|
+
.map((name) => toRecord({ scope: input.scope, envName: input.envName, name })),
|
|
149
|
+
};
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
async function resolve(
|
|
153
|
+
input: SecretResolveInput,
|
|
154
|
+
): Promise<Result<SecretResolveOutcome, SecretError>> {
|
|
155
|
+
// Attribution context is a no-op here — durable stores use it for
|
|
156
|
+
// the compliance-evidence audit event (see `@kindgi/compliance`).
|
|
157
|
+
void input.resolveContext;
|
|
158
|
+
const env = await load(input.envName);
|
|
159
|
+
const secrets = packValues(env.values);
|
|
160
|
+
if (!Object.hasOwn(secrets, input.name)) {
|
|
161
|
+
return {
|
|
162
|
+
kind: 'err',
|
|
163
|
+
error: {
|
|
164
|
+
code: 'secret-not-found',
|
|
165
|
+
message: `No secret "${input.name}" for env "${input.envName as unknown as string}" in ${filesLabel(env)} at ${packDir}`,
|
|
166
|
+
name: input.name,
|
|
167
|
+
},
|
|
168
|
+
};
|
|
169
|
+
}
|
|
170
|
+
return {
|
|
171
|
+
kind: 'ok',
|
|
172
|
+
value: { name: input.name, versionId: 1, value: secrets[input.name] ?? '' },
|
|
173
|
+
};
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
async function getVersion(input: SecretGetVersionInput): Promise<SecretVersionRecord | null> {
|
|
177
|
+
if (input.versionId !== 1) return null;
|
|
178
|
+
return Object.hasOwn(await secretsOf(input.envName), input.name) ? toVersion(input) : null;
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
async function listVersions(input: SecretListVersionsInput): Promise<SecretVersionPage> {
|
|
182
|
+
return Object.hasOwn(await secretsOf(input.envName), input.name)
|
|
183
|
+
? { data: [toVersion(input)] }
|
|
184
|
+
: { data: [] };
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
async function set(input: SecretSetInput): Promise<SecretSetOutcome> {
|
|
188
|
+
const refused = refusedName(input.name);
|
|
189
|
+
if (refused !== undefined) return storeError(refused);
|
|
190
|
+
// dotenv only ever exposes version 1, so any other ifVersion is stale.
|
|
191
|
+
if (input.ifVersion !== undefined && input.ifVersion !== 1) {
|
|
192
|
+
return { kind: 'version-conflict', currentVersion: 1 };
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
let env: PackEnv;
|
|
196
|
+
try {
|
|
197
|
+
env = await load(input.envName);
|
|
198
|
+
} catch (err) {
|
|
199
|
+
return storeError(`Failed to read env files: ${(err as Error).message}`);
|
|
200
|
+
}
|
|
201
|
+
const existing = Object.hasOwn(env.values, input.name);
|
|
202
|
+
if (input.writeMode === 'create-new' && existing) {
|
|
203
|
+
return { kind: 'already-exists', record: toRecord(input) };
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
const failure = await writeKey(env.files.write, input.name, input.value);
|
|
207
|
+
if (failure !== undefined) return storeError(failure);
|
|
208
|
+
|
|
209
|
+
// Authorization-tuple hook (`enqueueTuples`) — invoked ONLY on fresh
|
|
210
|
+
// insert per the SecretBinding contract. Dev mode has no transaction
|
|
211
|
+
// or outbox to persist to, but the hook runs so the caller's
|
|
212
|
+
// side-effects (if any) still happen.
|
|
213
|
+
if (!existing) void input.enqueueTuples(randomUUID());
|
|
214
|
+
|
|
215
|
+
return { kind: 'ok', record: toRecord(input), versionId: 1 };
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
/** `setKey` into `file` and write it back atomically; the error message on failure. */
|
|
219
|
+
async function writeKey(file: string, name: string, value: string): Promise<string | undefined> {
|
|
220
|
+
const label = displayEnvPath(packDir, file);
|
|
221
|
+
let contents: string;
|
|
222
|
+
try {
|
|
223
|
+
contents = setKey((await readFileOrNull(file)) ?? '', name, value).contents;
|
|
224
|
+
} catch (err) {
|
|
225
|
+
if (err instanceof EnvValueNotRepresentableError) return err.message;
|
|
226
|
+
return `Failed to read ${label}: ${(err as Error).message}`;
|
|
227
|
+
}
|
|
228
|
+
try {
|
|
229
|
+
await writeAtomic(file, contents);
|
|
230
|
+
return undefined;
|
|
231
|
+
} catch (err) {
|
|
232
|
+
return `Failed to write ${label}: ${(err as Error).message}`;
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
async function rotate(
|
|
237
|
+
input: SecretRotateInput,
|
|
238
|
+
): Promise<Result<SecretRotateOutcome, SecretError>> {
|
|
239
|
+
const env = await load(input.envName);
|
|
240
|
+
return {
|
|
241
|
+
kind: 'err',
|
|
242
|
+
error: {
|
|
243
|
+
code: 'secret-store-error',
|
|
244
|
+
message: `Dev secrets live in your env files (${filesLabel(env)}) and have no versions to rotate. Edit the value there, or run \`kindgi secrets set ${input.name} --write-mode=add-version\`.`,
|
|
245
|
+
},
|
|
246
|
+
};
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
async function revoke(
|
|
250
|
+
input: SecretRevokeInput,
|
|
251
|
+
): Promise<Result<SecretRevokeOutcome, SecretError>> {
|
|
252
|
+
const env = await load(input.envName);
|
|
253
|
+
return {
|
|
254
|
+
kind: 'err',
|
|
255
|
+
error: {
|
|
256
|
+
code: 'secret-store-error',
|
|
257
|
+
message: `Dev secrets live in your env files (${filesLabel(env)}) and have no revocation. Remove ${input.name} from those files.`,
|
|
258
|
+
},
|
|
259
|
+
};
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
return { list, get, resolve, getVersion, listVersions, set, rotate, revoke };
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
// ---------------------------------------------------------------------
|
|
266
|
+
// Helpers
|
|
267
|
+
// ---------------------------------------------------------------------
|
|
268
|
+
|
|
269
|
+
function refusedName(name: string): string | undefined {
|
|
270
|
+
if (isRuntimeKey(name)) {
|
|
271
|
+
return `"${name}" is Kindgi runtime config (KINDGI_*), not a pack secret. Set it in your shell or env file directly.`;
|
|
272
|
+
}
|
|
273
|
+
if (name.startsWith(RESERVED_SECRET_NAME_PREFIX)) {
|
|
274
|
+
return `Name "${name}" uses the reserved "${RESERVED_SECRET_NAME_PREFIX}" prefix; framework-internal only.`;
|
|
275
|
+
}
|
|
276
|
+
if (!ENV_KEY_REGEX.test(name)) {
|
|
277
|
+
return `Invalid secret name "${name}" for an env file — must match ${ENV_KEY_REGEX.source}.`;
|
|
278
|
+
}
|
|
279
|
+
return undefined;
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
function storeError(message: string): SecretSetOutcome {
|
|
283
|
+
return { kind: 'error', code: 'secret-store-error', message };
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
function toRecord(input: {
|
|
287
|
+
readonly scope: SecretRecord['scope'];
|
|
288
|
+
readonly envName: SecretRecord['envName'];
|
|
289
|
+
readonly name: string;
|
|
290
|
+
}): SecretRecord {
|
|
291
|
+
const iso = new Date(0).toISOString();
|
|
292
|
+
return {
|
|
293
|
+
scope: input.scope,
|
|
294
|
+
envName: input.envName,
|
|
295
|
+
name: input.name,
|
|
296
|
+
currentVersion: 1,
|
|
297
|
+
createdAt: iso,
|
|
298
|
+
updatedAt: iso,
|
|
299
|
+
};
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
function toVersion(input: {
|
|
303
|
+
readonly scope: SecretRecord['scope'];
|
|
304
|
+
readonly envName: SecretRecord['envName'];
|
|
305
|
+
readonly name: string;
|
|
306
|
+
}): SecretVersionRecord {
|
|
307
|
+
return {
|
|
308
|
+
scope: input.scope,
|
|
309
|
+
envName: input.envName,
|
|
310
|
+
name: input.name,
|
|
311
|
+
versionId: 1,
|
|
312
|
+
value: null,
|
|
313
|
+
createdAt: new Date(0).toISOString(),
|
|
314
|
+
};
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
/** Write-tmp + rename, mode 0600 (chmod again: rename can keep a looser mode). */
|
|
318
|
+
async function writeAtomic(target: string, contents: string): Promise<void> {
|
|
319
|
+
await mkdir(dirname(target), { recursive: true });
|
|
320
|
+
const tmp = `${target}.${process.pid}.${Date.now()}.tmp`;
|
|
321
|
+
await writeFile(tmp, contents, { mode: FILE_MODE });
|
|
322
|
+
await rename(tmp, target);
|
|
323
|
+
await chmod(target, FILE_MODE);
|
|
324
|
+
}
|
package/src/pack-env.ts
ADDED
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
// Copyright (C) 2026 Kindgi Inc.
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Which env files belong to a pack environment, and what they hold.
|
|
6
|
+
*
|
|
7
|
+
* **`local` — `kindgi dev`.** The project's own env files, read the way
|
|
8
|
+
* the application beside the pack reads them: `.env`, then `.env.local`
|
|
9
|
+
* on top (override per pack with `dev.envFiles` in `kindgi.config.ts`).
|
|
10
|
+
* Kindgi reads them; it writes only when asked (an explicit secret or
|
|
11
|
+
* env `set`), and then to the highest-precedence file so the new value
|
|
12
|
+
* wins.
|
|
13
|
+
*
|
|
14
|
+
* **Any other environment** (`staging`, `production`, …) — one file,
|
|
15
|
+
* `.env.<envName>`, read and written as-is. Deployed environments keep
|
|
16
|
+
* their real secrets in the runtime's secret store; these files carry
|
|
17
|
+
* per-environment values to push there.
|
|
18
|
+
*
|
|
19
|
+
* **Runtime vs. agents.** One file can hold both Kindgi's own runtime
|
|
20
|
+
* config and the values the pack's agents use. The `KINDGI_` prefix is
|
|
21
|
+
* the line: `KINDGI_*` names configure Kindgi and are never exposed as
|
|
22
|
+
* secrets; every other name belongs to the pack.
|
|
23
|
+
*/
|
|
24
|
+
|
|
25
|
+
import { readFile as fsReadFile } from 'node:fs/promises';
|
|
26
|
+
import { isAbsolute, join, relative } from 'node:path';
|
|
27
|
+
|
|
28
|
+
import { type EnvDiagnostic, readEnvLayers } from '@kindgi/dotenv-file';
|
|
29
|
+
|
|
30
|
+
/** The environment `kindgi dev` runs as. */
|
|
31
|
+
export const LOCAL_ENV_NAME = 'local';
|
|
32
|
+
|
|
33
|
+
/** Files read for `local`, lowest precedence first. */
|
|
34
|
+
export const DEFAULT_LOCAL_ENV_FILES: readonly string[] = ['.env', '.env.local'];
|
|
35
|
+
|
|
36
|
+
/** Names with this prefix are Kindgi runtime config, never pack secrets. */
|
|
37
|
+
export const RUNTIME_KEY_PREFIX = 'KINDGI_';
|
|
38
|
+
|
|
39
|
+
export function isRuntimeKey(name: string): boolean {
|
|
40
|
+
return name.startsWith(RUNTIME_KEY_PREFIX);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export interface PackEnvFilesInput {
|
|
44
|
+
/** Pack root — the directory holding `kindgi.config.ts`. */
|
|
45
|
+
readonly packDir: string;
|
|
46
|
+
readonly envName: string;
|
|
47
|
+
/**
|
|
48
|
+
* Files read for `local`, lowest precedence first; relative paths
|
|
49
|
+
* resolve against `packDir`. Defaults to `DEFAULT_LOCAL_ENV_FILES`.
|
|
50
|
+
* Ignored for every other environment.
|
|
51
|
+
*/
|
|
52
|
+
readonly localEnvFiles?: readonly string[];
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export interface PackEnvFiles {
|
|
56
|
+
/** Absolute paths, lowest precedence first. */
|
|
57
|
+
readonly read: readonly string[];
|
|
58
|
+
/** Where a write lands — the highest-precedence file. */
|
|
59
|
+
readonly write: string;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export function resolvePackEnvFiles(input: PackEnvFilesInput): PackEnvFiles {
|
|
63
|
+
const names =
|
|
64
|
+
input.envName === LOCAL_ENV_NAME
|
|
65
|
+
? (input.localEnvFiles ?? DEFAULT_LOCAL_ENV_FILES)
|
|
66
|
+
: [`.env.${input.envName}`];
|
|
67
|
+
if (names.length === 0) {
|
|
68
|
+
throw new TypeError('localEnvFiles must list at least one file.');
|
|
69
|
+
}
|
|
70
|
+
const read = names.map((n) => (isAbsolute(n) ? n : join(input.packDir, n)));
|
|
71
|
+
return { read, write: read[read.length - 1] as string };
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** Display form of a pack env file path (relative to the pack when inside it). */
|
|
75
|
+
export function displayEnvPath(packDir: string, path: string): string {
|
|
76
|
+
const rel = relative(packDir, path);
|
|
77
|
+
return rel !== '' && !rel.startsWith('..') && !isAbsolute(rel) ? rel : path;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
export interface ReadPackEnvInput extends PackEnvFilesInput {
|
|
81
|
+
/**
|
|
82
|
+
* Fallback for `${VAR}` references no file defines — typically the
|
|
83
|
+
* process environment. Never overrides a file's own value.
|
|
84
|
+
*/
|
|
85
|
+
readonly env?: Readonly<Record<string, string | undefined>>;
|
|
86
|
+
/** File reader: contents, or `null` when the file does not exist. */
|
|
87
|
+
readonly readFile?: (path: string) => Promise<string | null>;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
export interface PackEnv {
|
|
91
|
+
readonly files: PackEnvFiles;
|
|
92
|
+
/** Files that exist, lowest precedence first. */
|
|
93
|
+
readonly present: readonly string[];
|
|
94
|
+
/** Every name the files define — runtime and pack — merged and expanded. */
|
|
95
|
+
readonly values: Readonly<Record<string, string>>;
|
|
96
|
+
/** For each name, the file that supplied it. */
|
|
97
|
+
readonly origin: Readonly<Record<string, string>>;
|
|
98
|
+
readonly diagnostics: readonly EnvDiagnostic[];
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
export async function readPackEnv(input: ReadPackEnvInput): Promise<PackEnv> {
|
|
102
|
+
const files = resolvePackEnvFiles(input);
|
|
103
|
+
const read = input.readFile ?? readFileOrNull;
|
|
104
|
+
const layers = await Promise.all(
|
|
105
|
+
files.read.map(async (source) => ({ source, contents: await read(source) })),
|
|
106
|
+
);
|
|
107
|
+
const view = readEnvLayers(layers, input.env !== undefined ? { env: input.env } : {});
|
|
108
|
+
return {
|
|
109
|
+
files,
|
|
110
|
+
present: view.present,
|
|
111
|
+
values: view.values,
|
|
112
|
+
origin: view.origin,
|
|
113
|
+
diagnostics: view.diagnostics,
|
|
114
|
+
};
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** The pack's names only (`KINDGI_*` removed). */
|
|
118
|
+
export function packValues(values: Readonly<Record<string, string>>): Record<string, string> {
|
|
119
|
+
return Object.fromEntries(Object.entries(values).filter(([name]) => !isRuntimeKey(name)));
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/** Kindgi's runtime config only (`KINDGI_*`). */
|
|
123
|
+
export function runtimeValues(values: Readonly<Record<string, string>>): Record<string, string> {
|
|
124
|
+
return Object.fromEntries(Object.entries(values).filter(([name]) => isRuntimeKey(name)));
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
export async function readFileOrNull(path: string): Promise<string | null> {
|
|
128
|
+
try {
|
|
129
|
+
return await fsReadFile(path, 'utf8');
|
|
130
|
+
} catch (err) {
|
|
131
|
+
if ((err as NodeJS.ErrnoException).code === 'ENOENT') return null;
|
|
132
|
+
throw err;
|
|
133
|
+
}
|
|
134
|
+
}
|