@hex4c59/pi-ext-config-sync 0.0.0-stage → 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/CHANGELOG.md +30 -0
- package/LICENSE +21 -0
- package/README.md +219 -2
- package/extensions/config-sync.ts +163 -0
- package/package.json +46 -4
- package/src/collect.ts +273 -0
- package/src/crypto.ts +229 -0
- package/src/files.ts +432 -0
- package/src/github.ts +664 -0
- package/src/hash.ts +22 -0
- package/src/operations.ts +829 -0
- package/src/plan.ts +123 -0
- package/src/secret-input.ts +89 -0
- package/src/types.ts +124 -0
package/src/collect.ts
ADDED
|
@@ -0,0 +1,273 @@
|
|
|
1
|
+
import { lstat, readFile } from "node:fs/promises";
|
|
2
|
+
import {
|
|
3
|
+
isRecord,
|
|
4
|
+
localToRemotePath,
|
|
5
|
+
lstatOrUndefined,
|
|
6
|
+
readdirOrUndefined,
|
|
7
|
+
resolveAgentPath,
|
|
8
|
+
} from "./files.ts";
|
|
9
|
+
import { sha256Hex } from "./hash.ts";
|
|
10
|
+
import { SyncError } from "./types.ts";
|
|
11
|
+
|
|
12
|
+
const ROOT_FILES = [
|
|
13
|
+
"settings.json",
|
|
14
|
+
"models.json",
|
|
15
|
+
"mcp.json",
|
|
16
|
+
"keybindings.json",
|
|
17
|
+
"AGENTS.md",
|
|
18
|
+
"SYSTEM.md",
|
|
19
|
+
"APPEND_SYSTEM.md",
|
|
20
|
+
];
|
|
21
|
+
|
|
22
|
+
const ROOT_DIRS = ["themes", "prompts", "skills"];
|
|
23
|
+
const SKIP_NAMES = new Set([".DS_Store", "Thumbs.db", ".git", "node_modules"]);
|
|
24
|
+
const MAX_FILES = 2000;
|
|
25
|
+
const MAX_FILE_BYTES = 10 * 1024 * 1024;
|
|
26
|
+
const MAX_TOTAL_BYTES = 50 * 1024 * 1024;
|
|
27
|
+
const SECRET_NAME = /(authorization|api[-_]?key|access[-_]?token|token|secret|password)/i;
|
|
28
|
+
|
|
29
|
+
export interface CollectOptions {
|
|
30
|
+
localSettingsKeys: string[];
|
|
31
|
+
auditPlaintext?: boolean;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export interface CollectedFile {
|
|
35
|
+
relativePath: string;
|
|
36
|
+
remotePath: string;
|
|
37
|
+
localPath: string;
|
|
38
|
+
bytes: Buffer;
|
|
39
|
+
sha256: string;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export interface CollectResult {
|
|
43
|
+
files: CollectedFile[];
|
|
44
|
+
warnings: string[];
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export class PlaintextSecretError extends SyncError {
|
|
48
|
+
readonly findings: string[];
|
|
49
|
+
|
|
50
|
+
constructor(findings: string[]) {
|
|
51
|
+
super(
|
|
52
|
+
`Plaintext credentials found in synced files: ${findings.join(", ")}. `
|
|
53
|
+
+ "Move them to auth.json or use $ENV/!command references before pushing.",
|
|
54
|
+
);
|
|
55
|
+
this.name = "PlaintextSecretError";
|
|
56
|
+
this.findings = findings;
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export async function collectAgentFiles(
|
|
61
|
+
agentDir: string,
|
|
62
|
+
options: CollectOptions,
|
|
63
|
+
): Promise<CollectResult> {
|
|
64
|
+
const files: CollectedFile[] = [];
|
|
65
|
+
const warnings: string[] = [];
|
|
66
|
+
const budget = { totalBytes: 0 };
|
|
67
|
+
|
|
68
|
+
for (const name of ROOT_FILES) {
|
|
69
|
+
const localPath = resolveAgentPath(agentDir, name);
|
|
70
|
+
const info = await lstatOrUndefined(localPath);
|
|
71
|
+
if (info === undefined) continue;
|
|
72
|
+
if (!info.isFile()) {
|
|
73
|
+
warnings.push(`Skipped ${name}: not a regular file.`);
|
|
74
|
+
continue;
|
|
75
|
+
}
|
|
76
|
+
await addFile(name, localPath, files, warnings, budget, options);
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
for (const dir of ROOT_DIRS) {
|
|
80
|
+
await walkDirectory(agentDir, dir, files, warnings, budget, options);
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
files.sort((left, right) => left.remotePath.localeCompare(right.remotePath));
|
|
84
|
+
return { files, warnings };
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
export async function collectLocalHashes(
|
|
88
|
+
agentDir: string,
|
|
89
|
+
localSettingsKeys: string[],
|
|
90
|
+
): Promise<Record<string, string>> {
|
|
91
|
+
const result = await collectAgentFiles(agentDir, {
|
|
92
|
+
localSettingsKeys,
|
|
93
|
+
auditPlaintext: false,
|
|
94
|
+
});
|
|
95
|
+
const hashes: Record<string, string> = {};
|
|
96
|
+
for (const file of result.files) hashes[file.remotePath] = file.sha256;
|
|
97
|
+
return hashes;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
async function walkDirectory(
|
|
101
|
+
agentDir: string,
|
|
102
|
+
relativeDir: string,
|
|
103
|
+
files: CollectedFile[],
|
|
104
|
+
warnings: string[],
|
|
105
|
+
budget: { totalBytes: number },
|
|
106
|
+
options: CollectOptions,
|
|
107
|
+
): Promise<void> {
|
|
108
|
+
const localDir = resolveAgentPath(agentDir, relativeDir);
|
|
109
|
+
const entries = await readdirOrUndefined(localDir);
|
|
110
|
+
if (entries === undefined) return;
|
|
111
|
+
entries.sort((left, right) => left.name.localeCompare(right.name));
|
|
112
|
+
for (const entry of entries) {
|
|
113
|
+
if (SKIP_NAMES.has(entry.name)) continue;
|
|
114
|
+
if (entry.name.startsWith(".")) continue;
|
|
115
|
+
const relativePath = `${relativeDir}/${entry.name}`;
|
|
116
|
+
const localPath = resolveAgentPath(agentDir, relativePath);
|
|
117
|
+
if (entry.isSymbolicLink()) {
|
|
118
|
+
warnings.push(`Skipped ${relativePath}: symbolic links are not synced.`);
|
|
119
|
+
continue;
|
|
120
|
+
}
|
|
121
|
+
if (entry.isDirectory()) {
|
|
122
|
+
await walkDirectory(agentDir, relativePath, files, warnings, budget, options);
|
|
123
|
+
continue;
|
|
124
|
+
}
|
|
125
|
+
if (!entry.isFile()) continue;
|
|
126
|
+
await addFile(relativePath, localPath, files, warnings, budget, options);
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
async function addFile(
|
|
131
|
+
relativePath: string,
|
|
132
|
+
localPath: string,
|
|
133
|
+
files: CollectedFile[],
|
|
134
|
+
warnings: string[],
|
|
135
|
+
budget: { totalBytes: number },
|
|
136
|
+
options: CollectOptions,
|
|
137
|
+
): Promise<void> {
|
|
138
|
+
if (files.length >= MAX_FILES) {
|
|
139
|
+
throw new SyncError(`config-sync refuses to sync more than ${MAX_FILES} files.`);
|
|
140
|
+
}
|
|
141
|
+
const info = await lstat(localPath);
|
|
142
|
+
if (info.size > MAX_FILE_BYTES) {
|
|
143
|
+
warnings.push(`Skipped ${relativePath}: larger than ${formatMegabytes(MAX_FILE_BYTES)}.`);
|
|
144
|
+
return;
|
|
145
|
+
}
|
|
146
|
+
budget.totalBytes += info.size;
|
|
147
|
+
if (budget.totalBytes > MAX_TOTAL_BYTES) {
|
|
148
|
+
throw new SyncError(`config-sync refuses to sync more than ${formatMegabytes(MAX_TOTAL_BYTES)}.`);
|
|
149
|
+
}
|
|
150
|
+
const bytes = await buildFileBytes(relativePath, localPath, options);
|
|
151
|
+
files.push({
|
|
152
|
+
relativePath,
|
|
153
|
+
remotePath: localToRemotePath(relativePath),
|
|
154
|
+
localPath,
|
|
155
|
+
bytes,
|
|
156
|
+
sha256: sha256Hex(bytes),
|
|
157
|
+
});
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
async function buildFileBytes(
|
|
161
|
+
relativePath: string,
|
|
162
|
+
localPath: string,
|
|
163
|
+
options: CollectOptions,
|
|
164
|
+
): Promise<Buffer> {
|
|
165
|
+
if (relativePath === "settings.json") {
|
|
166
|
+
const text = await readFile(localPath, "utf8");
|
|
167
|
+
const parsed = parseJsonObject(text, "settings.json");
|
|
168
|
+
const stripped = stripLocalSettings(parsed, options.localSettingsKeys);
|
|
169
|
+
return Buffer.from(`${JSON.stringify(stripped, null, 2)}\n`, "utf8");
|
|
170
|
+
}
|
|
171
|
+
if (relativePath === "models.json") {
|
|
172
|
+
const text = await readFile(localPath, "utf8");
|
|
173
|
+
const parsed = parseJsonObject(text, "models.json");
|
|
174
|
+
if (options.auditPlaintext !== false) auditModels(parsed);
|
|
175
|
+
return Buffer.from(text, "utf8");
|
|
176
|
+
}
|
|
177
|
+
if (relativePath === "mcp.json") {
|
|
178
|
+
const text = await readFile(localPath, "utf8");
|
|
179
|
+
const parsed = parseJsonObject(text, "mcp.json");
|
|
180
|
+
if (options.auditPlaintext !== false) auditMcp(parsed);
|
|
181
|
+
return Buffer.from(text, "utf8");
|
|
182
|
+
}
|
|
183
|
+
return readFile(localPath);
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
function parseJsonObject(text: string, name: string): Record<string, unknown> {
|
|
187
|
+
let parsed: unknown;
|
|
188
|
+
try {
|
|
189
|
+
parsed = JSON.parse(text);
|
|
190
|
+
} catch {
|
|
191
|
+
throw new SyncError(`${name} is not valid JSON. Fix it before syncing.`);
|
|
192
|
+
}
|
|
193
|
+
if (!isRecord(parsed)) throw new SyncError(`${name} must contain a JSON object.`);
|
|
194
|
+
return parsed;
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
export function stripLocalSettings(
|
|
198
|
+
settings: Record<string, unknown>,
|
|
199
|
+
localSettingsKeys: string[],
|
|
200
|
+
): Record<string, unknown> {
|
|
201
|
+
const result = { ...settings };
|
|
202
|
+
for (const key of localSettingsKeys) delete result[key];
|
|
203
|
+
return result;
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
export function mergeSettings(
|
|
207
|
+
remoteText: string,
|
|
208
|
+
localText: string | undefined,
|
|
209
|
+
localSettingsKeys: string[],
|
|
210
|
+
): string {
|
|
211
|
+
const remote = parseJsonObject(remoteText, "Remote settings.json");
|
|
212
|
+
const local = localText === undefined ? undefined : parseJsonObject(localText, "Local settings.json");
|
|
213
|
+
const result = { ...remote };
|
|
214
|
+
for (const key of localSettingsKeys) {
|
|
215
|
+
delete result[key];
|
|
216
|
+
if (local !== undefined && key in local) result[key] = local[key];
|
|
217
|
+
}
|
|
218
|
+
return `${JSON.stringify(result, null, 2)}\n`;
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
function auditModels(value: Record<string, unknown>): void {
|
|
222
|
+
const findings: string[] = [];
|
|
223
|
+
visit(value, "models.json", (node, path) => {
|
|
224
|
+
for (const [key, entry] of Object.entries(node)) {
|
|
225
|
+
if ((key === "apiKey" || key === "api_key") && typeof entry === "string") {
|
|
226
|
+
if (!isIndirectValue(entry)) findings.push(`${path}.${key}`);
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
});
|
|
230
|
+
if (findings.length > 0) throw new PlaintextSecretError(findings);
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
function auditMcp(value: Record<string, unknown>): void {
|
|
234
|
+
const findings: string[] = [];
|
|
235
|
+
visit(value, "mcp.json", (node, path) => {
|
|
236
|
+
for (const [key, entry] of Object.entries(node)) {
|
|
237
|
+
if (typeof entry === "string" && hasUrlCredentials(entry)) findings.push(`${path}.${key}`);
|
|
238
|
+
if ((key === "headers" || key === "env") && isRecord(entry)) {
|
|
239
|
+
for (const [name, headerValue] of Object.entries(entry)) {
|
|
240
|
+
if (typeof headerValue !== "string" || !SECRET_NAME.test(name)) continue;
|
|
241
|
+
if (!headerValue.includes("${") && !isIndirectValue(headerValue)) {
|
|
242
|
+
findings.push(`${path}.${key}.${name}`);
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
});
|
|
248
|
+
if (findings.length > 0) throw new PlaintextSecretError(findings);
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
function visit(
|
|
252
|
+
node: Record<string, unknown>,
|
|
253
|
+
path: string,
|
|
254
|
+
inspect: (node: Record<string, unknown>, path: string) => void,
|
|
255
|
+
): void {
|
|
256
|
+
inspect(node, path);
|
|
257
|
+
for (const [key, entry] of Object.entries(node)) {
|
|
258
|
+
if (isRecord(entry)) visit(entry, `${path}.${key}`, inspect);
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
function isIndirectValue(value: string): boolean {
|
|
263
|
+
const trimmed = value.trim();
|
|
264
|
+
return trimmed.startsWith("$") || trimmed.startsWith("!");
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
function hasUrlCredentials(value: string): boolean {
|
|
268
|
+
return /^[a-z][a-z0-9+.-]*:\/\/[^/\s@]+@/i.test(value);
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
function formatMegabytes(bytes: number): string {
|
|
272
|
+
return `${Math.round(bytes / (1024 * 1024))} MB`;
|
|
273
|
+
}
|
package/src/crypto.ts
ADDED
|
@@ -0,0 +1,229 @@
|
|
|
1
|
+
import { createCipheriv, createDecipheriv, randomBytes, scrypt } from "node:crypto";
|
|
2
|
+
import { isRecord } from "./files.ts";
|
|
3
|
+
import { stableStringify } from "./hash.ts";
|
|
4
|
+
import { AUTH_PROVIDER_ID, SyncError } from "./types.ts";
|
|
5
|
+
|
|
6
|
+
const ENCRYPTION_VERSION = 1;
|
|
7
|
+
const KDF_N = 32768;
|
|
8
|
+
const KDF_R = 8;
|
|
9
|
+
const KDF_P = 1;
|
|
10
|
+
const KEY_BYTES = 32;
|
|
11
|
+
const SALT_BYTES = 16;
|
|
12
|
+
const IV_BYTES = 12;
|
|
13
|
+
const TAG_BYTES = 16;
|
|
14
|
+
const MAX_KDF_N = 131072;
|
|
15
|
+
const MAX_KDF_R = 16;
|
|
16
|
+
const MAX_KDF_P = 4;
|
|
17
|
+
const MAX_SCRYPT_MEMORY = 256 * 1024 * 1024;
|
|
18
|
+
const AAD = Buffer.from("pi-config-sync:v1", "utf8");
|
|
19
|
+
|
|
20
|
+
interface EncryptedPayload {
|
|
21
|
+
version: 1;
|
|
22
|
+
kdf: {
|
|
23
|
+
name: "scrypt";
|
|
24
|
+
salt: string;
|
|
25
|
+
n: number;
|
|
26
|
+
r: number;
|
|
27
|
+
p: number;
|
|
28
|
+
};
|
|
29
|
+
cipher: {
|
|
30
|
+
name: "aes-256-gcm";
|
|
31
|
+
iv: string;
|
|
32
|
+
tag: string;
|
|
33
|
+
};
|
|
34
|
+
data: string;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export interface AuthFilter {
|
|
38
|
+
include: string[];
|
|
39
|
+
exclude: string[];
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export function validatePassphrase(passphrase: string): string | null {
|
|
43
|
+
if (passphrase.length < 8) return "Passphrase must be at least 8 characters.";
|
|
44
|
+
return null;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export async function encryptJson(value: unknown, passphrase: string): Promise<string> {
|
|
48
|
+
const salt = randomBytes(SALT_BYTES);
|
|
49
|
+
const iv = randomBytes(IV_BYTES);
|
|
50
|
+
const key = await deriveKey(passphrase, salt, KDF_N, KDF_R, KDF_P);
|
|
51
|
+
const cipher = createCipheriv("aes-256-gcm", key, iv);
|
|
52
|
+
cipher.setAAD(AAD);
|
|
53
|
+
const plaintext = Buffer.from(JSON.stringify(value), "utf8");
|
|
54
|
+
const encrypted = Buffer.concat([cipher.update(plaintext), cipher.final()]);
|
|
55
|
+
const payload: EncryptedPayload = {
|
|
56
|
+
version: ENCRYPTION_VERSION,
|
|
57
|
+
kdf: {
|
|
58
|
+
name: "scrypt",
|
|
59
|
+
salt: salt.toString("base64"),
|
|
60
|
+
n: KDF_N,
|
|
61
|
+
r: KDF_R,
|
|
62
|
+
p: KDF_P,
|
|
63
|
+
},
|
|
64
|
+
cipher: {
|
|
65
|
+
name: "aes-256-gcm",
|
|
66
|
+
iv: iv.toString("base64"),
|
|
67
|
+
tag: cipher.getAuthTag().toString("base64"),
|
|
68
|
+
},
|
|
69
|
+
data: encrypted.toString("base64"),
|
|
70
|
+
};
|
|
71
|
+
return `${JSON.stringify(payload, null, 2)}\n`;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
export async function decryptJson(payloadText: string, passphrase: string): Promise<unknown> {
|
|
75
|
+
const payload = parsePayload(payloadText);
|
|
76
|
+
const salt = decodeBase64(payload.kdf.salt, "salt");
|
|
77
|
+
const iv = decodeBase64(payload.cipher.iv, "iv");
|
|
78
|
+
const tag = decodeBase64(payload.cipher.tag, "tag");
|
|
79
|
+
if (salt.length !== SALT_BYTES || iv.length !== IV_BYTES || tag.length !== TAG_BYTES) {
|
|
80
|
+
throw new SyncError("Synced credentials have an invalid encrypted payload.");
|
|
81
|
+
}
|
|
82
|
+
const key = await deriveKey(passphrase, salt, payload.kdf.n, payload.kdf.r, payload.kdf.p);
|
|
83
|
+
try {
|
|
84
|
+
const decipher = createDecipheriv("aes-256-gcm", key, iv);
|
|
85
|
+
decipher.setAAD(AAD);
|
|
86
|
+
decipher.setAuthTag(tag);
|
|
87
|
+
const plaintext = Buffer.concat([
|
|
88
|
+
decipher.update(decodeBase64(payload.data, "data")),
|
|
89
|
+
decipher.final(),
|
|
90
|
+
]);
|
|
91
|
+
const parsed: unknown = JSON.parse(plaintext.toString("utf8"));
|
|
92
|
+
if (!isRecord(parsed)) throw new Error("not an object");
|
|
93
|
+
return parsed;
|
|
94
|
+
} catch {
|
|
95
|
+
throw new SyncError("Failed to decrypt synced credentials: wrong passphrase or corrupted data.");
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
function parsePayload(text: string): EncryptedPayload {
|
|
100
|
+
let parsed: unknown;
|
|
101
|
+
try {
|
|
102
|
+
parsed = JSON.parse(text);
|
|
103
|
+
} catch {
|
|
104
|
+
throw new SyncError("Synced credentials are not valid JSON.");
|
|
105
|
+
}
|
|
106
|
+
if (!isRecord(parsed) || parsed.version !== ENCRYPTION_VERSION) {
|
|
107
|
+
throw new SyncError("Unsupported synced credential format.");
|
|
108
|
+
}
|
|
109
|
+
if (!isRecord(parsed.kdf) || parsed.kdf.name !== "scrypt") {
|
|
110
|
+
throw new SyncError("Unsupported key derivation in synced credentials.");
|
|
111
|
+
}
|
|
112
|
+
if (!isRecord(parsed.cipher) || parsed.cipher.name !== "aes-256-gcm") {
|
|
113
|
+
throw new SyncError("Unsupported cipher in synced credentials.");
|
|
114
|
+
}
|
|
115
|
+
const n = parsed.kdf.n;
|
|
116
|
+
const r = parsed.kdf.r;
|
|
117
|
+
const p = parsed.kdf.p;
|
|
118
|
+
if (
|
|
119
|
+
typeof n !== "number"
|
|
120
|
+
|| typeof r !== "number"
|
|
121
|
+
|| typeof p !== "number"
|
|
122
|
+
|| !Number.isInteger(n)
|
|
123
|
+
|| !Number.isInteger(r)
|
|
124
|
+
|| !Number.isInteger(p)
|
|
125
|
+
|| n < 2
|
|
126
|
+
|| (n & (n - 1)) !== 0
|
|
127
|
+
|| n > MAX_KDF_N
|
|
128
|
+
|| r < 1
|
|
129
|
+
|| r > MAX_KDF_R
|
|
130
|
+
|| p < 1
|
|
131
|
+
|| p > MAX_KDF_P
|
|
132
|
+
) {
|
|
133
|
+
throw new SyncError("Invalid key derivation parameters in synced credentials.");
|
|
134
|
+
}
|
|
135
|
+
if (
|
|
136
|
+
typeof parsed.kdf.salt !== "string"
|
|
137
|
+
|| typeof parsed.cipher.iv !== "string"
|
|
138
|
+
|| typeof parsed.cipher.tag !== "string"
|
|
139
|
+
|| typeof parsed.data !== "string"
|
|
140
|
+
) {
|
|
141
|
+
throw new SyncError("Incomplete encrypted payload in synced credentials.");
|
|
142
|
+
}
|
|
143
|
+
return {
|
|
144
|
+
version: 1,
|
|
145
|
+
kdf: { name: "scrypt", salt: parsed.kdf.salt, n, r, p },
|
|
146
|
+
cipher: { name: "aes-256-gcm", iv: parsed.cipher.iv, tag: parsed.cipher.tag },
|
|
147
|
+
data: parsed.data,
|
|
148
|
+
};
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
function deriveKey(
|
|
152
|
+
passphrase: string,
|
|
153
|
+
salt: Buffer,
|
|
154
|
+
n: number,
|
|
155
|
+
r: number,
|
|
156
|
+
p: number,
|
|
157
|
+
): Promise<Buffer> {
|
|
158
|
+
return new Promise((resolve, reject) => {
|
|
159
|
+
scrypt(
|
|
160
|
+
passphrase,
|
|
161
|
+
salt,
|
|
162
|
+
KEY_BYTES,
|
|
163
|
+
{ N: n, r, p, maxmem: MAX_SCRYPT_MEMORY },
|
|
164
|
+
(error, key) => {
|
|
165
|
+
if (error) reject(error);
|
|
166
|
+
else resolve(key);
|
|
167
|
+
},
|
|
168
|
+
);
|
|
169
|
+
});
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
function decodeBase64(value: string, field: string): Buffer {
|
|
173
|
+
const decoded = Buffer.from(value, "base64");
|
|
174
|
+
if (decoded.length === 0) {
|
|
175
|
+
throw new SyncError(`Encrypted payload field "${field}" is empty.`);
|
|
176
|
+
}
|
|
177
|
+
return decoded;
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
export function filterAuthEntries(
|
|
181
|
+
auth: Record<string, unknown>,
|
|
182
|
+
filter: AuthFilter,
|
|
183
|
+
): Record<string, unknown> {
|
|
184
|
+
const result: Record<string, unknown> = {};
|
|
185
|
+
const include = new Set(filter.include);
|
|
186
|
+
const exclude = new Set(filter.exclude);
|
|
187
|
+
for (const providerId of Object.keys(auth).sort()) {
|
|
188
|
+
if (providerId === AUTH_PROVIDER_ID) continue;
|
|
189
|
+
const explicitlyIncluded = include.has(providerId);
|
|
190
|
+
if (!explicitlyIncluded && exclude.has(providerId)) continue;
|
|
191
|
+
if (include.size > 0 && !explicitlyIncluded) continue;
|
|
192
|
+
const entry = auth[providerId];
|
|
193
|
+
if (!isValidApiKeyEntry(entry)) continue;
|
|
194
|
+
result[providerId] = entry;
|
|
195
|
+
}
|
|
196
|
+
return result;
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
export function mergeAuthEntries(
|
|
200
|
+
local: Record<string, unknown>,
|
|
201
|
+
remote: Record<string, unknown>,
|
|
202
|
+
): { auth: Record<string, unknown>; applied: number } {
|
|
203
|
+
const auth = { ...local };
|
|
204
|
+
let applied = 0;
|
|
205
|
+
for (const providerId of Object.keys(remote).sort()) {
|
|
206
|
+
if (providerId === AUTH_PROVIDER_ID) continue;
|
|
207
|
+
const entry = remote[providerId];
|
|
208
|
+
if (!isValidApiKeyEntry(entry)) {
|
|
209
|
+
throw new SyncError(`Remote credential entry "${providerId}" has an unsupported shape.`);
|
|
210
|
+
}
|
|
211
|
+
auth[providerId] = entry;
|
|
212
|
+
applied++;
|
|
213
|
+
}
|
|
214
|
+
return { auth, applied };
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
function isValidApiKeyEntry(entry: unknown): entry is Record<string, unknown> {
|
|
218
|
+
if (!isRecord(entry) || entry.type !== "api_key") return false;
|
|
219
|
+
if (typeof entry.key !== "string" || entry.key.length === 0) return false;
|
|
220
|
+
if (entry.env === undefined) return true;
|
|
221
|
+
return isRecord(entry.env) && Object.values(entry.env).every((value) => typeof value === "string");
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
export function authEntriesEqual(
|
|
225
|
+
left: Record<string, unknown>,
|
|
226
|
+
right: Record<string, unknown>,
|
|
227
|
+
): boolean {
|
|
228
|
+
return stableStringify(left) === stableStringify(right);
|
|
229
|
+
}
|