@townco/secret 0.1.49 → 0.1.51

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/dist/index.d.ts CHANGED
@@ -1,15 +1,13 @@
1
- export { EnvFile } from "./env-file";
1
+ export { EnvFile } from "@townco/env";
2
2
  export { type OnePassword, OnePassword as OpItem } from "./onepassword";
3
3
  export type SecretValidation = {
4
- key: string;
5
- value: string;
6
- valid: boolean;
7
- error?: string;
4
+ key: string;
5
+ value: string;
6
+ valid: boolean;
7
+ error?: string;
8
8
  };
9
9
  export declare const listSecrets: () => Promise<Promise<SecretValidation[]>>;
10
- export declare const createSecret: (
11
- name: string,
12
- value: string,
13
- ) => Promise<Promise<void>>;
10
+ export declare const createSecret: (name: string, value: string) => Promise<Promise<void>>;
11
+ export declare const updateSecret: (name: string, value: string) => Promise<Promise<void>>;
14
12
  export declare const deleteSecret: (name: string) => Promise<Promise<void>>;
15
13
  export declare const genenv: () => Promise<Promise<void>>;
package/dist/index.js CHANGED
@@ -1,23 +1,12 @@
1
1
  import * as path from "node:path";
2
- import { EnvFile } from "./env-file";
2
+ import { findRoot } from "@townco/core";
3
+ import { EnvFile } from "@townco/env";
3
4
  import { OnePassword } from "./onepassword";
4
- export { EnvFile } from "./env-file";
5
+ export { EnvFile } from "@townco/env";
5
6
  export { OnePassword as OpItem } from "./onepassword";
6
- const ROOT_MARKER = ".root";
7
7
  const SECRET_FILE = ".env.in";
8
8
  const OP_VAULT = "app";
9
9
  const OP_ITEM = "dev";
10
- const findRoot = async (start = ".") => {
11
- const startResolved = path.resolve(start);
12
- const rootPath = path.join(startResolved, ROOT_MARKER);
13
- if (await Bun.file(rootPath).exists())
14
- return startResolved;
15
- const parent = path.dirname(startResolved);
16
- if (parent === "/") {
17
- throw new Error("No root found");
18
- }
19
- return await findRoot(parent);
20
- };
21
10
  const withOpSignIn = (fn) => async (...args) => {
22
11
  await OnePassword.signin();
23
12
  return fn(...args);
@@ -51,6 +40,7 @@ const withEnvFile = (fn) => async (...args) => {
51
40
  for (const [key, value] of Object.entries(resultSecrets)) {
52
41
  envFile.set(key, value);
53
42
  }
43
+ // Sort the env file before writing
54
44
  await writeEnvFile(filePath, envFile);
55
45
  }
56
46
  }
@@ -70,17 +60,17 @@ export const listSecrets = withOpSignIn(async () => {
70
60
  if (value.startsWith('"') && value.endsWith('"')) {
71
61
  unquotedValue = value.slice(1, -1);
72
62
  }
63
+ // Skip entries that aren't 1Password references
64
+ if (!unquotedValue.startsWith("op://")) {
65
+ continue;
66
+ }
73
67
  const validation = {
74
68
  key,
75
69
  value: unquotedValue,
76
70
  valid: true,
77
71
  };
78
- if (!validation.value.startsWith("op://")) {
79
- validations.push(validation);
80
- continue;
81
- }
82
72
  // Check if field exists in 1Password item
83
- if (opItem.has(key)) {
73
+ if (!opItem.has(key)) {
84
74
  validation.valid = false;
85
75
  validation.error = `Field '${key}' not found in 1Password item`;
86
76
  validations.push(validation);
@@ -110,6 +100,22 @@ export const createSecret = withOpSignIn(async (name, value) => {
110
100
  return secrets;
111
101
  })();
112
102
  });
103
+ export const updateSecret = withOpSignIn(async (name, value) => {
104
+ // Validate that the secret exists in the env file
105
+ const root = await findRoot();
106
+ const filePath = path.join(root, SECRET_FILE);
107
+ const envFile = await readEnvFile(filePath);
108
+ const secrets = envFile.toRecord();
109
+ if (!(name in secrets))
110
+ throw new Error(`Secret '${name}' not found in ${SECRET_FILE}`);
111
+ // Fetch the item and validate it exists in 1Password
112
+ const opItem = await OnePassword.fetch(OP_VAULT, OP_ITEM);
113
+ if (!opItem.has(name))
114
+ throw new Error(`Secret '${name}' not found in 1Password item`);
115
+ // Update the value in 1Password
116
+ opItem.set(name, value);
117
+ await opItem.sync();
118
+ });
113
119
  export const deleteSecret = withOpSignIn(async (name) => {
114
120
  // Fetch the item, delete the field, and sync
115
121
  const opItem = await OnePassword.fetch(OP_VAULT, OP_ITEM);
@@ -2,107 +2,101 @@ import type { FullItem } from "@1password/connect";
2
2
  /**
3
3
  * Represents a change to be made to a 1Password item
4
4
  */
5
- type OnePasswordChange =
6
- | {
7
- type: "add";
8
- key: string;
9
- value: string;
10
- }
11
- | {
12
- type: "update";
13
- key: string;
14
- value: string;
15
- }
16
- | {
17
- type: "delete";
18
- key: string;
19
- };
5
+ type OnePasswordChange = {
6
+ type: "add";
7
+ key: string;
8
+ value: string;
9
+ } | {
10
+ type: "update";
11
+ key: string;
12
+ value: string;
13
+ } | {
14
+ type: "delete";
15
+ key: string;
16
+ };
20
17
  /**
21
18
  * A data structure that represents a 1Password item and provides
22
19
  * methods to detect changes and generate appropriate `op` CLI commands.
23
20
  */
24
21
  export declare class OnePassword {
25
- private vault;
26
- private item;
27
- private fields;
28
- private originalFields;
29
- constructor(vault: string, item: string, fields?: Map<string, string>);
30
- /**
31
- * Create an OpItem from a 1Password FullItem JSON response
32
- */
33
- static fromFullItem(
34
- vault: string,
35
- itemName: string,
36
- fullItem: FullItem,
37
- ): OnePassword;
38
- /**
39
- * Fetch an OpItem from 1Password using the CLI
40
- */
41
- static fetch(vault: string, item: string): Promise<OnePassword>;
42
- /**
43
- * Sign in to 1Password CLI
44
- */
45
- static signin(): Promise<void>;
46
- /**
47
- * Get a field value
48
- */
49
- get(key: string): string | undefined;
50
- /**
51
- * Set a field value (marks as changed)
52
- */
53
- set(key: string, value: string): this;
54
- /**
55
- * Delete a field (marks as deleted)
56
- */
57
- delete(key: string): this;
58
- /**
59
- * Check if a field exists
60
- */
61
- has(key: string): boolean;
62
- /**
63
- * Get all field keys
64
- */
65
- keys(): string[];
66
- /**
67
- * Get all fields as a record
68
- */
69
- toRecord(): Record<string, string>;
70
- /**
71
- * Get all field entries
72
- */
73
- entries(): IterableIterator<[string, string]>;
74
- /**
75
- * Build an op:// reference for a field
76
- */
77
- getReference(key: string): string;
78
- /**
79
- * Detect changes between original and current state
80
- */
81
- detectChanges(): OnePasswordChange[];
82
- /**
83
- * Generate op CLI arguments for a single change
84
- */
85
- private buildEditArgs;
86
- /**
87
- * Apply all changes to 1Password using the op CLI
88
- * Returns the number of changes applied
89
- */
90
- sync(): Promise<number>;
91
- /**
92
- * Inject secrets from a template file to an output file
93
- * This resolves op:// references to actual values
94
- */
95
- static inject(inputPath: string, outputPath: string): Promise<void>;
96
- /**
97
- * Create a clone of this OpItem
98
- */
99
- clone(): OnePassword;
100
- /**
101
- * Reset to original state (discard changes)
102
- */
103
- reset(): this;
104
- /**
105
- * Check if there are unsaved changes
106
- */
107
- hasChanges(): boolean;
22
+ private vault;
23
+ private item;
24
+ private fields;
25
+ private originalFields;
26
+ constructor(vault: string, item: string, fields?: Map<string, string>);
27
+ /**
28
+ * Create an OpItem from a 1Password FullItem JSON response
29
+ */
30
+ static fromFullItem(vault: string, itemName: string, fullItem: FullItem): OnePassword;
31
+ /**
32
+ * Fetch an OpItem from 1Password using the CLI
33
+ */
34
+ static fetch(vault: string, item: string): Promise<OnePassword>;
35
+ /**
36
+ * Sign in to 1Password CLI
37
+ */
38
+ static signin(): Promise<void>;
39
+ /**
40
+ * Get a field value
41
+ */
42
+ get(key: string): string | undefined;
43
+ /**
44
+ * Set a field value (marks as changed)
45
+ */
46
+ set(key: string, value: string): this;
47
+ /**
48
+ * Delete a field (marks as deleted)
49
+ */
50
+ delete(key: string): this;
51
+ /**
52
+ * Check if a field exists
53
+ */
54
+ has(key: string): boolean;
55
+ /**
56
+ * Get all field keys
57
+ */
58
+ keys(): string[];
59
+ /**
60
+ * Get all fields as a record
61
+ */
62
+ toRecord(): Record<string, string>;
63
+ /**
64
+ * Get all field entries
65
+ */
66
+ entries(): IterableIterator<[string, string]>;
67
+ /**
68
+ * Build an op:// reference for a field
69
+ */
70
+ getReference(key: string): string;
71
+ /**
72
+ * Detect changes between original and current state
73
+ */
74
+ detectChanges(): OnePasswordChange[];
75
+ /**
76
+ * Generate op CLI arguments for a single change
77
+ */
78
+ private buildEditArgs;
79
+ /**
80
+ * Apply all changes to 1Password using the op CLI
81
+ * Returns the number of changes applied
82
+ */
83
+ sync(): Promise<number>;
84
+ /**
85
+ * Inject secrets from a template file to an output file
86
+ * This resolves op:// references to actual values
87
+ */
88
+ static inject(inputPath: string, outputPath: string): Promise<void>;
89
+ /**
90
+ * Create a clone of this OpItem
91
+ */
92
+ clone(): OnePassword;
93
+ /**
94
+ * Reset to original state (discard changes)
95
+ */
96
+ reset(): this;
97
+ /**
98
+ * Check if there are unsaved changes
99
+ */
100
+ hasChanges(): boolean;
108
101
  }
102
+ export {};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@townco/secret",
3
- "version": "0.1.49",
3
+ "version": "0.1.51",
4
4
  "type": "module",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",
@@ -20,10 +20,12 @@
20
20
  "check": "tsc --noEmit"
21
21
  },
22
22
  "dependencies": {
23
- "@1password/connect": "^1.4.2"
23
+ "@1password/connect": "^1.4.2",
24
+ "@townco/env": "0.1.1"
24
25
  },
25
26
  "devDependencies": {
26
- "@townco/tsconfig": "0.1.46",
27
+ "@townco/core": "0.0.29",
28
+ "@townco/tsconfig": "0.1.48",
27
29
  "@types/bun": "^1.3.1"
28
30
  }
29
31
  }
@@ -1,107 +0,0 @@
1
- /**
2
- * Represents a line in an .env file
3
- */
4
- type EnvLine =
5
- | {
6
- type: "comment";
7
- content: string;
8
- }
9
- | {
10
- type: "blank";
11
- }
12
- | {
13
- type: "entry";
14
- key: string;
15
- value: string;
16
- raw: string;
17
- };
18
- /**
19
- * A data structure that represents a parsed .env file while preserving
20
- * all original content including comments, blank lines, and order.
21
- */
22
- export declare class EnvFile {
23
- private lines;
24
- constructor(lines?: EnvLine[]);
25
- /**
26
- * Parse a .env file string into an EnvFile structure
27
- */
28
- static parse(content: string): EnvFile;
29
- /**
30
- * Serialize the EnvFile back to a string
31
- */
32
- toString(): string;
33
- /**
34
- * Get all entries as a key-value record
35
- */
36
- toRecord(): Record<string, string>;
37
- /**
38
- * Find an entry line by key
39
- */
40
- private findEntry;
41
- /**
42
- * Find the index of an entry by key
43
- */
44
- private findEntryIndex;
45
- /**
46
- * Create an entry line from key and value
47
- */
48
- private createEntry;
49
- /**
50
- * Normalize a value by ensuring it's properly quoted
51
- */
52
- private normalizeValue;
53
- /**
54
- * Find the insertion index for a new entry (before the final blank line if present)
55
- */
56
- private findInsertionIndex;
57
- /**
58
- * Get the value for a specific key
59
- */
60
- get(key: string): string | undefined;
61
- /**
62
- * Set a value for a key. If the key exists, updates it in place.
63
- * If it doesn't exist, appends it above the final newline (if present).
64
- * Values are always double quoted.
65
- */
66
- set(key: string, value: string): this;
67
- /**
68
- * Delete a key-value entry
69
- */
70
- delete(key: string): this;
71
- /**
72
- * Check if a key exists
73
- */
74
- has(key: string): boolean;
75
- /**
76
- * Get all keys
77
- */
78
- keys(): string[];
79
- /**
80
- * Iterate over all entries
81
- */
82
- entries(): IterableIterator<[string, string]>;
83
- /**
84
- * Apply a function to all entries and return a new EnvFile
85
- */
86
- map(fn: (key: string, value: string) => [string, string]): EnvFile;
87
- /**
88
- * Filter entries based on a predicate
89
- */
90
- filter(fn: (key: string, value: string) => boolean): EnvFile;
91
- /**
92
- * Add a comment line
93
- */
94
- addComment(content: string): this;
95
- /**
96
- * Add a blank line
97
- */
98
- addBlank(): this;
99
- /**
100
- * Get the raw lines array for custom operations
101
- */
102
- getLines(): readonly EnvLine[];
103
- /**
104
- * Create a clone of this EnvFile
105
- */
106
- clone(): EnvFile;
107
- }
package/dist/env-file.js DELETED
@@ -1,205 +0,0 @@
1
- /**
2
- * A data structure that represents a parsed .env file while preserving
3
- * all original content including comments, blank lines, and order.
4
- */
5
- export class EnvFile {
6
- lines;
7
- constructor(lines = []) {
8
- this.lines = lines;
9
- }
10
- /**
11
- * Parse a .env file string into an EnvFile structure
12
- */
13
- static parse(content) {
14
- const lines = content.split("\n").map((line) => {
15
- const trimmed = line.trim();
16
- if (trimmed === "") {
17
- return { type: "blank" };
18
- }
19
- if (trimmed.startsWith("#")) {
20
- return { type: "comment", content: line };
21
- }
22
- const equalsIndex = line.indexOf("=");
23
- if (equalsIndex === -1) {
24
- // Malformed line, treat as comment
25
- return { type: "comment", content: line };
26
- }
27
- const key = line.substring(0, equalsIndex).trim();
28
- const value = line.substring(equalsIndex + 1);
29
- return { type: "entry", key, value, raw: line };
30
- });
31
- return new EnvFile(lines);
32
- }
33
- /**
34
- * Serialize the EnvFile back to a string
35
- */
36
- toString() {
37
- return this.lines
38
- .map((line) => {
39
- switch (line.type) {
40
- case "blank":
41
- return "";
42
- case "comment":
43
- return line.content;
44
- case "entry":
45
- return line.raw;
46
- default:
47
- throw new Error(`Unknown line type`);
48
- }
49
- })
50
- .join("\n");
51
- }
52
- /**
53
- * Get all entries as a key-value record
54
- */
55
- toRecord() {
56
- return Object.fromEntries(this.entries());
57
- }
58
- /**
59
- * Find an entry line by key
60
- */
61
- findEntry(key) {
62
- const line = this.lines.find((l) => l.type === "entry" && l.key === key);
63
- return line;
64
- }
65
- /**
66
- * Find the index of an entry by key
67
- */
68
- findEntryIndex(key) {
69
- return this.lines.findIndex((l) => l.type === "entry" && l.key === key);
70
- }
71
- /**
72
- * Create an entry line from key and value
73
- */
74
- createEntry(key, value) {
75
- const quotedValue = this.normalizeValue(value);
76
- return {
77
- type: "entry",
78
- key,
79
- value: quotedValue,
80
- raw: `${key}=${quotedValue}`,
81
- };
82
- }
83
- /**
84
- * Normalize a value by ensuring it's properly quoted
85
- */
86
- normalizeValue(value) {
87
- // Strip existing quotes if present, then add quotes
88
- const unquoted = value.startsWith('"') && value.endsWith('"') ? value.slice(1, -1) : value;
89
- return `"${unquoted}"`;
90
- }
91
- /**
92
- * Find the insertion index for a new entry (before the final blank line if present)
93
- */
94
- findInsertionIndex() {
95
- const lastLine = this.lines[this.lines.length - 1];
96
- return lastLine?.type === "blank"
97
- ? this.lines.length - 1
98
- : this.lines.length;
99
- }
100
- /**
101
- * Get the value for a specific key
102
- */
103
- get(key) {
104
- return this.findEntry(key)?.value;
105
- }
106
- /**
107
- * Set a value for a key. If the key exists, updates it in place.
108
- * If it doesn't exist, appends it above the final newline (if present).
109
- * Values are always double quoted.
110
- */
111
- set(key, value) {
112
- const index = this.findEntryIndex(key);
113
- const entry = this.createEntry(key, value);
114
- if (index !== -1) {
115
- this.lines[index] = entry;
116
- }
117
- else {
118
- this.lines.splice(this.findInsertionIndex(), 0, entry);
119
- }
120
- return this;
121
- }
122
- /**
123
- * Delete a key-value entry
124
- */
125
- delete(key) {
126
- this.lines = this.lines.filter((l) => !(l.type === "entry" && l.key === key));
127
- return this;
128
- }
129
- /**
130
- * Check if a key exists
131
- */
132
- has(key) {
133
- return this.findEntry(key) !== undefined;
134
- }
135
- /**
136
- * Get all keys
137
- */
138
- keys() {
139
- return this.lines
140
- .filter((l) => l.type === "entry")
141
- .map((l) => l.key);
142
- }
143
- /**
144
- * Iterate over all entries
145
- */
146
- *entries() {
147
- for (const line of this.lines) {
148
- if (line.type === "entry") {
149
- yield [line.key, line.value];
150
- }
151
- }
152
- }
153
- /**
154
- * Apply a function to all entries and return a new EnvFile
155
- */
156
- map(fn) {
157
- const newLines = this.lines.map((line) => {
158
- if (line.type === "entry") {
159
- const [newKey, newValue] = fn(line.key, line.value);
160
- return this.createEntry(newKey, newValue);
161
- }
162
- return line;
163
- });
164
- return new EnvFile(newLines);
165
- }
166
- /**
167
- * Filter entries based on a predicate
168
- */
169
- filter(fn) {
170
- const newLines = this.lines.filter((line) => {
171
- if (line.type === "entry") {
172
- return fn(line.key, line.value);
173
- }
174
- return true; // Keep comments and blank lines
175
- });
176
- return new EnvFile(newLines);
177
- }
178
- /**
179
- * Add a comment line
180
- */
181
- addComment(content) {
182
- const comment = content.startsWith("#") ? content : `# ${content}`;
183
- this.lines.push({ type: "comment", content: comment });
184
- return this;
185
- }
186
- /**
187
- * Add a blank line
188
- */
189
- addBlank() {
190
- this.lines.push({ type: "blank" });
191
- return this;
192
- }
193
- /**
194
- * Get the raw lines array for custom operations
195
- */
196
- getLines() {
197
- return this.lines;
198
- }
199
- /**
200
- * Create a clone of this EnvFile
201
- */
202
- clone() {
203
- return new EnvFile([...this.lines]);
204
- }
205
- }