appstash 0.7.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -251,6 +251,50 @@ const dirs = appstash('myapp', {
251
251
  console.log(dirs.config); // /opt/myapp/.myapp/config
252
252
  ```
253
253
 
254
+ ## Config store
255
+
256
+ `createConfigStore(tool, options?)` layers a context + credential store on top of the
257
+ directories above: named contexts (each with an endpoint and optional per-target
258
+ endpoints), credentials per context, per-context vars, and `getClientConfig(target)`
259
+ resolution (store → env vars → actionable error).
260
+
261
+ Every file it writes is atomic (temp file + `rename`) and mode `0600`. A stored file
262
+ that exists but does not parse throws with its path — it is never silently replaced
263
+ with defaults.
264
+
265
+ ### One signed-in state across several tools
266
+
267
+ Pass `stashName` when multiple binaries are really one product. They then share
268
+ contexts and credentials, while `tool` still drives env-var prefixes (`CSDK_TOKEN`)
269
+ and the command names in error messages:
270
+
271
+ ```typescript
272
+ // A generated SDK CLI, an agent CLI and a desktop app, one login:
273
+ createConfigStore('csdk', { stashName: 'constructive' });
274
+ createConfigStore('agent', { stashName: 'constructive' });
275
+ createConfigStore('desktop', { stashName: 'constructive' });
276
+ ```
277
+
278
+ ### Encrypting secrets at rest
279
+
280
+ Supply a `SecretCodec` to transform the secret-bearing fields (`token`,
281
+ `refreshToken`, `apiKey`) on the way to disk; everything else stays readable. The
282
+ codec name is recorded in `credentials.json`, so a file written by a different codec
283
+ is reported instead of decoded into garbage:
284
+
285
+ ```typescript
286
+ import { safeStorage } from 'electron';
287
+
288
+ createConfigStore('desktop', {
289
+ stashName: 'constructive',
290
+ codec: {
291
+ name: 'electron-safeStorage',
292
+ encode: (s) => safeStorage.encryptString(s).toString('base64'),
293
+ decode: (s) => safeStorage.decryptString(Buffer.from(s, 'base64'))
294
+ }
295
+ });
296
+ ```
297
+
254
298
  ## Design Philosophy
255
299
 
256
300
  - **Simple**: One function, clear structure
package/config-store.d.ts CHANGED
@@ -12,15 +12,48 @@ export interface ContextCredentials {
12
12
  token: string;
13
13
  expiresAt?: string;
14
14
  refreshToken?: string;
15
+ /** Identity the token belongs to. */
16
+ userId?: string;
17
+ email?: string;
18
+ /** Long-lived API key minted for this context, and its server-side id. */
19
+ apiKey?: string;
20
+ keyId?: string;
21
+ apiKeyExpiresAt?: string;
22
+ /** Epoch millis of the sign-in that produced these credentials. */
23
+ signedInAt?: number;
24
+ }
25
+ /**
26
+ * At-rest transform for the secret-bearing fields of stored credentials
27
+ * (`token`, `refreshToken`, `apiKey`). Hosts with a keychain supply one — e.g.
28
+ * Electron `safeStorage` — so the same on-disk layout can be encrypted without
29
+ * the store knowing how. `decode` receives exactly what `encode` produced.
30
+ */
31
+ export interface SecretCodec {
32
+ /** Recorded on disk, so a file written by a different codec is detected. */
33
+ name: string;
34
+ encode(plaintext: string): string;
35
+ decode(encoded: string): string;
15
36
  }
16
37
  export interface Credentials {
17
38
  tokens: Record<string, ContextCredentials>;
39
+ /** Name of the codec that encoded the secret fields. */
40
+ codec?: string;
18
41
  }
19
42
  export interface GlobalSettings {
20
43
  currentContext?: string;
21
44
  }
22
45
  export interface ConfigStoreOptions {
23
46
  baseDir?: string;
47
+ /**
48
+ * Directory identity to store under, when it differs from the tool name.
49
+ * Several CLIs that are one product — a generated SDK CLI, an agent CLI, a
50
+ * desktop app — pass the same `stashName`, so signing in through one signs
51
+ * you in everywhere, while `toolName` still drives env-var prefixes and the
52
+ * commands named in error messages. Defaults to `toolName`.
53
+ */
54
+ stashName?: string;
55
+ /** At-rest transform for secret fields. Defaults to plaintext. */
56
+ codec?: SecretCodec;
24
57
  }
25
58
  export interface ClientConfig {
26
59
  endpoint: string;
package/config-store.js CHANGED
@@ -37,27 +37,61 @@ exports.createConfigStore = createConfigStore;
37
37
  const fs = __importStar(require("fs"));
38
38
  const path = __importStar(require("path"));
39
39
  const index_1 = require("./index");
40
+ const SECRET_FIELDS = ['token', 'refreshToken', 'apiKey'];
41
+ const PLAINTEXT_CODEC = 'plaintext';
42
+ /**
43
+ * Read stored JSON, or `fallback` when the file does not exist. A file that
44
+ * exists but does not parse is a real problem — a half-written credential file,
45
+ * a hand-edit gone wrong — so it throws with the path instead of quietly
46
+ * resetting the caller's configuration.
47
+ */
40
48
  function readJson(filePath, fallback) {
41
- if (fs.existsSync(filePath)) {
42
- try {
43
- return JSON.parse(fs.readFileSync(filePath, 'utf8'));
44
- }
45
- catch {
49
+ let raw;
50
+ try {
51
+ raw = fs.readFileSync(filePath, 'utf8');
52
+ }
53
+ catch (err) {
54
+ if (err.code === 'ENOENT') {
46
55
  return JSON.parse(JSON.stringify(fallback));
47
56
  }
57
+ throw err;
58
+ }
59
+ try {
60
+ return JSON.parse(raw);
61
+ }
62
+ catch (err) {
63
+ throw new Error(`Malformed JSON in ${filePath}: ${err.message}`);
48
64
  }
49
- return JSON.parse(JSON.stringify(fallback));
50
65
  }
51
- function writeJson(filePath, data, mode) {
66
+ /**
67
+ * Write JSON atomically: a temp file in the destination directory, then
68
+ * `rename`. A crash or a concurrent reader mid-write can never observe a
69
+ * truncated file. `mode` is applied to the temp file before the rename so the
70
+ * contents are never briefly world-readable.
71
+ */
72
+ function writeJson(filePath, data, mode = 0o600) {
52
73
  const dir = path.dirname(filePath);
53
- if (!fs.existsSync(dir)) {
54
- fs.mkdirSync(dir, { recursive: true });
74
+ fs.mkdirSync(dir, { recursive: true });
75
+ const tmp = path.join(dir, `.${path.basename(filePath)}.${process.pid}.tmp`);
76
+ try {
77
+ fs.writeFileSync(tmp, JSON.stringify(data, null, 2) + '\n', { mode });
78
+ fs.renameSync(tmp, filePath);
79
+ }
80
+ catch (err) {
81
+ try {
82
+ fs.unlinkSync(tmp);
83
+ }
84
+ catch {
85
+ // the temp file may not exist; the original error is what matters
86
+ }
87
+ throw err;
55
88
  }
56
- const options = mode ? { mode } : {};
57
- fs.writeFileSync(filePath, JSON.stringify(data, null, 2), options);
58
89
  }
59
90
  function createConfigStore(toolName, options) {
60
- const dirs = (0, index_1.appstash)(toolName, { ensure: true, baseDir: options?.baseDir });
91
+ const stashName = options?.stashName ?? toolName;
92
+ const codec = options?.codec;
93
+ const codecName = codec?.name ?? PLAINTEXT_CODEC;
94
+ const dirs = (0, index_1.appstash)(stashName, { ensure: true, baseDir: options?.baseDir });
61
95
  function settingsPath() {
62
96
  return (0, index_1.resolve)(dirs, 'config', 'settings.json');
63
97
  }
@@ -99,18 +133,11 @@ function createConfigStore(toolName, options) {
99
133
  if (!fs.existsSync(contextsDir)) {
100
134
  return [];
101
135
  }
102
- const files = fs.readdirSync(contextsDir).filter(f => f.endsWith('.json'));
103
- const contexts = [];
104
- for (const file of files) {
105
- try {
106
- const content = fs.readFileSync(path.join(contextsDir, file), 'utf8');
107
- contexts.push(JSON.parse(content));
108
- }
109
- catch {
110
- // skip invalid files
111
- }
112
- }
113
- return contexts;
136
+ return fs
137
+ .readdirSync(contextsDir)
138
+ .filter(f => f.endsWith('.json'))
139
+ .map(f => readJson(path.join(contextsDir, f), null))
140
+ .filter((ctx) => ctx !== null);
114
141
  }
115
142
  function deleteContext(name) {
116
143
  const p = contextPath(name);
@@ -142,20 +169,40 @@ function createConfigStore(toolName, options) {
142
169
  saveSettings(settings);
143
170
  return true;
144
171
  }
172
+ /** Map the secret fields of one entry through `transform`. */
173
+ function mapSecrets(creds, transform) {
174
+ const mapped = { ...creds };
175
+ for (const field of SECRET_FIELDS) {
176
+ const value = mapped[field];
177
+ if (typeof value === 'string')
178
+ mapped[field] = transform(value);
179
+ }
180
+ return mapped;
181
+ }
182
+ /** Stored credentials, still encoded. */
145
183
  function loadCredentials() {
146
- return readJson(credentialsPath(), { tokens: {} });
184
+ const credentials = readJson(credentialsPath(), { tokens: {} });
185
+ const fileCodec = credentials.codec ?? PLAINTEXT_CODEC;
186
+ if (Object.keys(credentials.tokens).length > 0 && fileCodec !== codecName) {
187
+ throw new Error(`Credentials in ${credentialsPath()} were written with the "${fileCodec}" codec, ` +
188
+ `but this store uses "${codecName}". Sign in again to rewrite them.`);
189
+ }
190
+ return credentials;
147
191
  }
148
192
  function saveCredentials(credentials) {
149
- writeJson(credentialsPath(), credentials, 0o600);
193
+ writeJson(credentialsPath(), { ...credentials, codec: codecName }, 0o600);
150
194
  }
151
195
  function setCredentials(contextName, creds) {
152
196
  const credentials = loadCredentials();
153
- credentials.tokens[contextName] = creds;
197
+ credentials.tokens[contextName] = codec ? mapSecrets(creds, codec.encode) : creds;
154
198
  saveCredentials(credentials);
155
199
  }
156
200
  function getCredentials(contextName) {
157
201
  const credentials = loadCredentials();
158
- return credentials.tokens[contextName] || null;
202
+ const stored = credentials.tokens[contextName];
203
+ if (!stored)
204
+ return null;
205
+ return codec ? mapSecrets(stored, codec.decode) : stored;
159
206
  }
160
207
  function removeCredentials(contextName) {
161
208
  const credentials = loadCredentials();
@@ -12,15 +12,48 @@ export interface ContextCredentials {
12
12
  token: string;
13
13
  expiresAt?: string;
14
14
  refreshToken?: string;
15
+ /** Identity the token belongs to. */
16
+ userId?: string;
17
+ email?: string;
18
+ /** Long-lived API key minted for this context, and its server-side id. */
19
+ apiKey?: string;
20
+ keyId?: string;
21
+ apiKeyExpiresAt?: string;
22
+ /** Epoch millis of the sign-in that produced these credentials. */
23
+ signedInAt?: number;
24
+ }
25
+ /**
26
+ * At-rest transform for the secret-bearing fields of stored credentials
27
+ * (`token`, `refreshToken`, `apiKey`). Hosts with a keychain supply one — e.g.
28
+ * Electron `safeStorage` — so the same on-disk layout can be encrypted without
29
+ * the store knowing how. `decode` receives exactly what `encode` produced.
30
+ */
31
+ export interface SecretCodec {
32
+ /** Recorded on disk, so a file written by a different codec is detected. */
33
+ name: string;
34
+ encode(plaintext: string): string;
35
+ decode(encoded: string): string;
15
36
  }
16
37
  export interface Credentials {
17
38
  tokens: Record<string, ContextCredentials>;
39
+ /** Name of the codec that encoded the secret fields. */
40
+ codec?: string;
18
41
  }
19
42
  export interface GlobalSettings {
20
43
  currentContext?: string;
21
44
  }
22
45
  export interface ConfigStoreOptions {
23
46
  baseDir?: string;
47
+ /**
48
+ * Directory identity to store under, when it differs from the tool name.
49
+ * Several CLIs that are one product — a generated SDK CLI, an agent CLI, a
50
+ * desktop app — pass the same `stashName`, so signing in through one signs
51
+ * you in everywhere, while `toolName` still drives env-var prefixes and the
52
+ * commands named in error messages. Defaults to `toolName`.
53
+ */
54
+ stashName?: string;
55
+ /** At-rest transform for secret fields. Defaults to plaintext. */
56
+ codec?: SecretCodec;
24
57
  }
25
58
  export interface ClientConfig {
26
59
  endpoint: string;
@@ -1,27 +1,61 @@
1
1
  import * as fs from 'fs';
2
2
  import * as path from 'path';
3
3
  import { appstash, resolve } from './index';
4
+ const SECRET_FIELDS = ['token', 'refreshToken', 'apiKey'];
5
+ const PLAINTEXT_CODEC = 'plaintext';
6
+ /**
7
+ * Read stored JSON, or `fallback` when the file does not exist. A file that
8
+ * exists but does not parse is a real problem — a half-written credential file,
9
+ * a hand-edit gone wrong — so it throws with the path instead of quietly
10
+ * resetting the caller's configuration.
11
+ */
4
12
  function readJson(filePath, fallback) {
5
- if (fs.existsSync(filePath)) {
6
- try {
7
- return JSON.parse(fs.readFileSync(filePath, 'utf8'));
8
- }
9
- catch {
13
+ let raw;
14
+ try {
15
+ raw = fs.readFileSync(filePath, 'utf8');
16
+ }
17
+ catch (err) {
18
+ if (err.code === 'ENOENT') {
10
19
  return JSON.parse(JSON.stringify(fallback));
11
20
  }
21
+ throw err;
22
+ }
23
+ try {
24
+ return JSON.parse(raw);
25
+ }
26
+ catch (err) {
27
+ throw new Error(`Malformed JSON in ${filePath}: ${err.message}`);
12
28
  }
13
- return JSON.parse(JSON.stringify(fallback));
14
29
  }
15
- function writeJson(filePath, data, mode) {
30
+ /**
31
+ * Write JSON atomically: a temp file in the destination directory, then
32
+ * `rename`. A crash or a concurrent reader mid-write can never observe a
33
+ * truncated file. `mode` is applied to the temp file before the rename so the
34
+ * contents are never briefly world-readable.
35
+ */
36
+ function writeJson(filePath, data, mode = 0o600) {
16
37
  const dir = path.dirname(filePath);
17
- if (!fs.existsSync(dir)) {
18
- fs.mkdirSync(dir, { recursive: true });
38
+ fs.mkdirSync(dir, { recursive: true });
39
+ const tmp = path.join(dir, `.${path.basename(filePath)}.${process.pid}.tmp`);
40
+ try {
41
+ fs.writeFileSync(tmp, JSON.stringify(data, null, 2) + '\n', { mode });
42
+ fs.renameSync(tmp, filePath);
43
+ }
44
+ catch (err) {
45
+ try {
46
+ fs.unlinkSync(tmp);
47
+ }
48
+ catch {
49
+ // the temp file may not exist; the original error is what matters
50
+ }
51
+ throw err;
19
52
  }
20
- const options = mode ? { mode } : {};
21
- fs.writeFileSync(filePath, JSON.stringify(data, null, 2), options);
22
53
  }
23
54
  export function createConfigStore(toolName, options) {
24
- const dirs = appstash(toolName, { ensure: true, baseDir: options?.baseDir });
55
+ const stashName = options?.stashName ?? toolName;
56
+ const codec = options?.codec;
57
+ const codecName = codec?.name ?? PLAINTEXT_CODEC;
58
+ const dirs = appstash(stashName, { ensure: true, baseDir: options?.baseDir });
25
59
  function settingsPath() {
26
60
  return resolve(dirs, 'config', 'settings.json');
27
61
  }
@@ -63,18 +97,11 @@ export function createConfigStore(toolName, options) {
63
97
  if (!fs.existsSync(contextsDir)) {
64
98
  return [];
65
99
  }
66
- const files = fs.readdirSync(contextsDir).filter(f => f.endsWith('.json'));
67
- const contexts = [];
68
- for (const file of files) {
69
- try {
70
- const content = fs.readFileSync(path.join(contextsDir, file), 'utf8');
71
- contexts.push(JSON.parse(content));
72
- }
73
- catch {
74
- // skip invalid files
75
- }
76
- }
77
- return contexts;
100
+ return fs
101
+ .readdirSync(contextsDir)
102
+ .filter(f => f.endsWith('.json'))
103
+ .map(f => readJson(path.join(contextsDir, f), null))
104
+ .filter((ctx) => ctx !== null);
78
105
  }
79
106
  function deleteContext(name) {
80
107
  const p = contextPath(name);
@@ -106,20 +133,40 @@ export function createConfigStore(toolName, options) {
106
133
  saveSettings(settings);
107
134
  return true;
108
135
  }
136
+ /** Map the secret fields of one entry through `transform`. */
137
+ function mapSecrets(creds, transform) {
138
+ const mapped = { ...creds };
139
+ for (const field of SECRET_FIELDS) {
140
+ const value = mapped[field];
141
+ if (typeof value === 'string')
142
+ mapped[field] = transform(value);
143
+ }
144
+ return mapped;
145
+ }
146
+ /** Stored credentials, still encoded. */
109
147
  function loadCredentials() {
110
- return readJson(credentialsPath(), { tokens: {} });
148
+ const credentials = readJson(credentialsPath(), { tokens: {} });
149
+ const fileCodec = credentials.codec ?? PLAINTEXT_CODEC;
150
+ if (Object.keys(credentials.tokens).length > 0 && fileCodec !== codecName) {
151
+ throw new Error(`Credentials in ${credentialsPath()} were written with the "${fileCodec}" codec, ` +
152
+ `but this store uses "${codecName}". Sign in again to rewrite them.`);
153
+ }
154
+ return credentials;
111
155
  }
112
156
  function saveCredentials(credentials) {
113
- writeJson(credentialsPath(), credentials, 0o600);
157
+ writeJson(credentialsPath(), { ...credentials, codec: codecName }, 0o600);
114
158
  }
115
159
  function setCredentials(contextName, creds) {
116
160
  const credentials = loadCredentials();
117
- credentials.tokens[contextName] = creds;
161
+ credentials.tokens[contextName] = codec ? mapSecrets(creds, codec.encode) : creds;
118
162
  saveCredentials(credentials);
119
163
  }
120
164
  function getCredentials(contextName) {
121
165
  const credentials = loadCredentials();
122
- return credentials.tokens[contextName] || null;
166
+ const stored = credentials.tokens[contextName];
167
+ if (!stored)
168
+ return null;
169
+ return codec ? mapSecrets(stored, codec.decode) : stored;
123
170
  }
124
171
  function removeCredentials(contextName) {
125
172
  const credentials = loadCredentials();
package/esm/index.d.ts CHANGED
@@ -97,5 +97,5 @@ export declare function ensure(dirs: AppStashResult): EnsureResult;
97
97
  * ```
98
98
  */
99
99
  export declare function resolve(dirs: AppStashResult, kind: 'config' | 'cache' | 'data' | 'logs' | 'tmp', ...parts: string[]): string;
100
+ export type { ClientConfig, ConfigStore, ConfigStoreOptions, ContextConfig, ContextCredentials, ContextTargetEndpoint, Credentials, GlobalSettings, SecretCodec, } from './config-store';
100
101
  export { createConfigStore } from './config-store';
101
- export type { ClientConfig, ConfigStore, ConfigStoreOptions, ContextConfig, ContextCredentials, ContextTargetEndpoint, Credentials, GlobalSettings, } from './config-store';
package/esm/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import * as fs from 'fs';
2
- import * as path from 'path';
3
2
  import * as os from 'os';
3
+ import * as path from 'path';
4
4
  /**
5
5
  * Get home directory with fallback
6
6
  */
@@ -12,6 +12,7 @@ function getHomeDir() {
12
12
  }
13
13
  }
14
14
  catch {
15
+ // ignore
15
16
  }
16
17
  return null;
17
18
  }
package/index.d.ts CHANGED
@@ -97,5 +97,5 @@ export declare function ensure(dirs: AppStashResult): EnsureResult;
97
97
  * ```
98
98
  */
99
99
  export declare function resolve(dirs: AppStashResult, kind: 'config' | 'cache' | 'data' | 'logs' | 'tmp', ...parts: string[]): string;
100
+ export type { ClientConfig, ConfigStore, ConfigStoreOptions, ContextConfig, ContextCredentials, ContextTargetEndpoint, Credentials, GlobalSettings, SecretCodec, } from './config-store';
100
101
  export { createConfigStore } from './config-store';
101
- export type { ClientConfig, ConfigStore, ConfigStoreOptions, ContextConfig, ContextCredentials, ContextTargetEndpoint, Credentials, GlobalSettings, } from './config-store';
package/index.js CHANGED
@@ -38,8 +38,8 @@ exports.appstash = appstash;
38
38
  exports.ensure = ensure;
39
39
  exports.resolve = resolve;
40
40
  const fs = __importStar(require("fs"));
41
- const path = __importStar(require("path"));
42
41
  const os = __importStar(require("os"));
42
+ const path = __importStar(require("path"));
43
43
  /**
44
44
  * Get home directory with fallback
45
45
  */
@@ -51,6 +51,7 @@ function getHomeDir() {
51
51
  }
52
52
  }
53
53
  catch {
54
+ // ignore
54
55
  }
55
56
  return null;
56
57
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "appstash",
3
- "version": "0.7.0",
3
+ "version": "0.8.0",
4
4
  "author": "Constructive <developers@constructive.io>",
5
5
  "description": "Simple, clean application directory resolution",
6
6
  "main": "index.js",
@@ -40,5 +40,5 @@
40
40
  "xdg",
41
41
  "appdirs"
42
42
  ],
43
- "gitHead": "febc209cbaea97a5976b0554fdb4e1780f6b9618"
43
+ "gitHead": "9ae46e62fa96a289374cff253e3528108d7f4d61"
44
44
  }