@inthedark/wb 0.0.6 → 0.0.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -69,3 +69,45 @@ note: have tried to keep dependencies minimal for the most part
69
69
  `/test` — test runner
70
70
  `/scripts` — stuff used by package scripts plus anything i didn't notice an agent left behind :3
71
71
  `/docs` — help agents find things and not break them without eating all their tokens
72
+
73
+ ## .env secrets
74
+
75
+ workbench's npm package `@inthedark/wb` can be used as a dotenv replacement. its `config` is async, so await it before reading your env vars:
76
+
77
+ ```js
78
+ import { config } from "@inthedark/wb";
79
+
80
+ await config();
81
+ ```
82
+
83
+ the following syntax in your .env file can be used to load data from workbench's private store:
84
+
85
+ ```dotenv
86
+ API_KEY=${wb:API_KEY}
87
+ ```
88
+
89
+ configure secrets in workbench at settings > projects & folders > environment > store. select the folder you want to configure.
90
+
91
+ the env loader by default silently acts like dotenv would for loading the .env if workbench is not installed, so it's safe to use in teams where some devs are using other stuff. references it can't resolve stay as literal text. existing env vars still take precedence. pass a `warn` callback to opt into lookup warnings.
92
+
93
+ you can choose what happens when values are missing:
94
+
95
+ ```js
96
+ await config({ required: ["DATABASE_URL"] }); // all others optional
97
+ await config({ optional: ["ANALYTICS_KEY"] }); // all others required
98
+ ```
99
+
100
+ use one list or the other. missing optional vars become empty strings, including the whole value if a store reference fails. missing required vars throw one error listing all their names before changing the environment. explicitly empty values are valid. "all others" means vars in your .env files.
101
+
102
+ you can use wb's env loader to load from other clis too, not just wb store:
103
+
104
+ ```dotenv
105
+ WB_STORES="wb: wb store get {key}; other: my-secret-cli get {key}"
106
+ API_KEY=${other:API_KEY}
107
+ ```
108
+
109
+ replace `my-secret-cli get {key}` with your cli's command. `{key}` is substituted into its arguments, and stdout becomes the value. commands run without a shell.
110
+
111
+ ### security note
112
+
113
+ wb's env secret storage is not built for maximum security. it's built to prevent agents accidentally obtaining secrets. values use aes-256-gcm with a key derived from the device identity, username and project location, not a separate password, so this isn't protection against hostile code running as you.
package/index.d.ts CHANGED
@@ -1,10 +1,10 @@
1
1
  /*
2
2
  * Exports:
3
- * - WorkbenchConfigOptions: dotenv-compatible loading options plus cancellation and warning hooks.
3
+ * - WorkbenchConfigOptions: dotenv loading, mutually exclusive missing-value policies, cancellation and warning hooks.
4
4
  * - WorkbenchConfigOutput: parsed values after store replacement, with the first file read error.
5
- * - config: load dotenv files, then replace resolvable `${store:key}` references through named WB_STORES commands.
5
+ * - config: load dotenv and store values; reject missing required names before writing the environment.
6
6
  */
7
- export interface WorkbenchConfigOptions {
7
+ export type WorkbenchConfigOptions = {
8
8
  /** One file or several; earlier files win unless `override` is set. Defaults to `.env`. */
9
9
  path?: string | readonly string[];
10
10
  encoding?: BufferEncoding;
@@ -13,13 +13,26 @@ export interface WorkbenchConfigOptions {
13
13
  processEnv?: Record<string, string | undefined>;
14
14
  /** Aborting kills running store commands and rejects. */
15
15
  signal?: AbortSignal;
16
- /** Receives bounded messages that never contain command output. Defaults to `process.emitWarning`. */
16
+ /** Opt into bounded lookup warnings that never contain command output. Silent by default. */
17
17
  warn?: (message: string) => void;
18
- }
18
+ } & ({
19
+ /** Only these names are required; all other dotenv variables are optional. Empty values count as supplied. */
20
+ required?: readonly string[];
21
+ optional?: never;
22
+ } | {
23
+ required?: never;
24
+ /** These names are optional; all other dotenv variables are required. Empty values count as supplied. */
25
+ optional?: readonly string[];
26
+ });
19
27
 
20
28
  export interface WorkbenchConfigOutput {
21
29
  parsed: Record<string, string>;
22
30
  error?: Error;
23
31
  }
24
32
 
33
+ /**
34
+ * Without a policy, unresolved references remain literal. With a policy, missing optional
35
+ * variables become empty strings in their entirety. Missing required names reject together
36
+ * before any environment writes. Existing environment values win unless override is set.
37
+ */
25
38
  export function config(options?: WorkbenchConfigOptions): Promise<WorkbenchConfigOutput>;
package/index.mjs CHANGED
@@ -1,6 +1,6 @@
1
1
  /*
2
2
  * Exports:
3
- * - config: load dotenv files, then replace resolvable `${store:key}` references through named WB_STORES commands.
3
+ * - config: load dotenv files, resolve named store references, and enforce an optional missing-variable policy.
4
4
  */
5
5
  import fs from "node:fs/promises";
6
6
  import path from "node:path";
@@ -13,10 +13,6 @@ import {
13
13
  parseStoreDefinitions,
14
14
  } from "./store-definitions.mjs";
15
15
 
16
- function warnDefault(message) {
17
- process.emitWarning(message, "WorkbenchStoreWarning");
18
- }
19
-
20
16
  function stripTerminalLineEnding(value) {
21
17
  return value.endsWith("\r\n") ? value.slice(0, -2) : value.endsWith("\n") ? value.slice(0, -1) : value;
22
18
  }
@@ -37,15 +33,17 @@ async function readParsed(paths, encoding, override) {
37
33
  return { parsed, error };
38
34
  }
39
35
 
40
- async function resolveReferences(parsed, definitions, { runner, signal, warn }) {
36
+ async function resolveReferences(parsed, definitions, { runner, signal, warn, policy }) {
37
+ const references = new Map(Object.entries(parsed).map(([name, value]) => [name, findStoreReferences(value)]));
38
+ const unresolved = new Set();
41
39
  let stores;
42
40
  try {
43
41
  stores = parseStoreDefinitions(definitions);
44
42
  } catch (failure) {
45
- warn(`${failure.message} Store references were left unchanged.`);
46
- return parsed;
43
+ warn(policy ? failure.message : `${failure.message} Store references were left unchanged.`);
44
+ for (const [name, found] of references) if (found.length) unresolved.add(name);
45
+ return { parsed, unresolved };
47
46
  }
48
- const references = new Map(Object.entries(parsed).map(([name, value]) => [name, findStoreReferences(value)]));
49
47
  const lookups = new Map();
50
48
  for (const [name, found] of references) {
51
49
  for (const { key, store } of found) {
@@ -53,25 +51,52 @@ async function resolveReferences(parsed, definitions, { runner, signal, warn })
53
51
  if (stores.has(store) && !lookups.has(id)) lookups.set(id, { argv: expandStoreCommand(stores.get(store), key), owner: name, store });
54
52
  }
55
53
  }
56
- if (!lookups.size) return parsed;
57
54
  const results = new Map(await Promise.all(Array.from(lookups, async ([id, lookup]) => {
58
55
  const result = await runner.run(lookup.argv, { signal });
59
56
  if (!result.ok) {
60
57
  const detail = result.reason === "exit" ? `exited with ${result.exitCode}` : `failed (${result.reason})`;
61
- warn(`The ${lookup.store} store lookup for ${lookup.owner} ${detail}. The reference was left unchanged.`);
58
+ warn(`The ${lookup.store} store lookup for ${lookup.owner} ${detail}.${policy ? "" : " The reference was left unchanged."}`);
62
59
  }
63
60
  return [id, result];
64
61
  })));
65
- return Object.fromEntries(Object.entries(parsed).map(([name, value]) => {
62
+ const resolved = Object.fromEntries(Object.entries(parsed).map(([name, value]) => {
66
63
  let next = "";
67
64
  let cursor = 0;
68
65
  for (const reference of references.get(name)) {
69
66
  const result = results.get(JSON.stringify([reference.store, reference.key]));
67
+ if (!result?.ok) unresolved.add(name);
70
68
  next += value.slice(cursor, reference.start) + (result?.ok ? stripTerminalLineEnding(result.stdout) : reference.text);
71
69
  cursor = reference.end;
72
70
  }
73
71
  return [name, next + value.slice(cursor)];
74
72
  }));
73
+ return { parsed: resolved, unresolved };
74
+ }
75
+
76
+ function missingPolicy(required, optional) {
77
+ if (required !== undefined && optional !== undefined) {
78
+ throw new TypeError("Specify either required or optional, not both.");
79
+ }
80
+ const names = required ?? optional;
81
+ if (required === undefined && optional === undefined) return null;
82
+ if (!Array.isArray(names) || names.some(name => typeof name !== "string" || !name.length)) {
83
+ throw new TypeError("required and optional must be arrays of nonempty environment variable names.");
84
+ }
85
+ return { names: new Set(names), listedRequired: required !== undefined };
86
+ }
87
+
88
+ function applyMissingPolicy(parsed, unresolved, policy, processEnv, override) {
89
+ if (!policy) return;
90
+ const missing = [];
91
+ for (const name of new Set([...Object.keys(parsed), ...policy.names])) {
92
+ const existing = Object.hasOwn(processEnv, name) && processEnv[name] !== undefined;
93
+ const fromFile = Object.hasOwn(parsed, name);
94
+ if (existing && (!override || !fromFile)) continue;
95
+ if (fromFile && !unresolved.has(name)) continue;
96
+ if (policy.names.has(name) === policy.listedRequired) missing.push(name);
97
+ else Object.defineProperty(parsed, name, { value: "", writable: true, enumerable: true, configurable: true });
98
+ }
99
+ if (missing.length) throw new Error(`Missing required environment variables: ${missing.join(", ")}`);
75
100
  }
76
101
 
77
102
  export async function config({
@@ -80,13 +105,20 @@ export async function config({
80
105
  override = false,
81
106
  processEnv = process.env,
82
107
  signal,
83
- warn = warnDefault,
108
+ warn = () => {},
84
109
  runner = new StoreCommandRunner(),
110
+ required,
111
+ optional,
85
112
  } = {}) {
86
113
  signal?.throwIfAborted();
114
+ const policy = missingPolicy(required, optional);
87
115
  const { parsed: raw, error } = await readParsed(Array.isArray(paths) ? paths : [paths], encoding, override);
88
116
  const definitions = raw.WB_STORES?.trim() || processEnv.WB_STORES?.trim() || DEFAULT_STORE_DEFINITIONS;
89
- const parsed = await resolveReferences(raw, definitions, { runner, signal, warn });
90
- dotenv.populate(processEnv, parsed, { override });
117
+ const { parsed, unresolved } = await resolveReferences(raw, definitions, { runner, signal, warn, policy });
118
+ applyMissingPolicy(parsed, unresolved, policy, processEnv, override);
119
+ const values = policy && !override
120
+ ? Object.fromEntries(Object.entries(parsed).filter(([name]) => !Object.hasOwn(processEnv, name) || processEnv[name] === undefined))
121
+ : parsed;
122
+ dotenv.populate(processEnv, values, { override: policy ? true : override });
91
123
  return error ? { parsed, error } : { parsed };
92
124
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@inthedark/wb",
3
- "version": "0.0.6",
3
+ "version": "0.0.7",
4
4
  "type": "module",
5
5
  "repository": {
6
6
  "type": "git",