Files
smartsecret/ts/smartsecret.backends.file.ts

154 lines
4.4 KiB
TypeScript
Raw Normal View History

import * as plugins from './smartsecret.plugins.js';
import type { ISecretBackend, TBackendType } from './smartsecret.backends.base.js';
interface IVaultEntry {
iv: string; // hex
ciphertext: string; // hex
tag: string; // hex
}
interface IVaultData {
[key: string]: IVaultEntry;
}
export class FileEncryptedBackend implements ISecretBackend {
public readonly backendType: TBackendType = 'file-encrypted';
private service: string;
private vaultPath: string;
private keyfilePath: string;
constructor(service: string, vaultPath?: string) {
this.service = service;
const configDir = vaultPath
? plugins.path.dirname(vaultPath)
: plugins.path.join(plugins.os.homedir(), '.config', 'smartsecret');
this.vaultPath = vaultPath || plugins.path.join(configDir, 'vault.json');
this.keyfilePath = plugins.path.join(configDir, '.keyfile');
}
async isAvailable(): Promise<boolean> {
return true; // File backend is always available
}
async setSecret(account: string, secret: string): Promise<void> {
const key = await this.deriveKey();
const vault = await this.readVault();
const vaultKey = `${this.service}:${account}`;
const iv = plugins.crypto.randomBytes(12);
const cipher = plugins.crypto.createCipheriv('aes-256-gcm', key, iv);
const encrypted = Buffer.concat([cipher.update(secret, 'utf8'), cipher.final()]);
const tag = cipher.getAuthTag();
vault[vaultKey] = {
iv: iv.toString('hex'),
ciphertext: encrypted.toString('hex'),
tag: tag.toString('hex'),
};
await this.writeVault(vault);
}
async getSecret(account: string): Promise<string | null> {
const key = await this.deriveKey();
const vault = await this.readVault();
const vaultKey = `${this.service}:${account}`;
const entry = vault[vaultKey];
if (!entry) return null;
try {
const iv = Buffer.from(entry.iv, 'hex');
const ciphertext = Buffer.from(entry.ciphertext, 'hex');
const tag = Buffer.from(entry.tag, 'hex');
const decipher = plugins.crypto.createDecipheriv('aes-256-gcm', key, iv);
decipher.setAuthTag(tag);
const decrypted = Buffer.concat([decipher.update(ciphertext), decipher.final()]);
return decrypted.toString('utf8');
} catch {
return null;
}
}
async deleteSecret(account: string): Promise<boolean> {
const vault = await this.readVault();
const vaultKey = `${this.service}:${account}`;
if (!(vaultKey in vault)) return false;
delete vault[vaultKey];
await this.writeVault(vault);
return true;
}
async listAccounts(): Promise<string[]> {
const vault = await this.readVault();
const prefix = `${this.service}:`;
return Object.keys(vault)
.filter((k) => k.startsWith(prefix))
.map((k) => k.slice(prefix.length));
}
private async deriveKey(): Promise<Buffer> {
const keyfileContent = await this.ensureKeyfile();
return new Promise((resolve, reject) => {
plugins.crypto.pbkdf2(
keyfileContent,
`smartsecret:${this.service}`,
100_000,
32,
'sha512',
(err, derivedKey) => {
if (err) reject(err);
else resolve(derivedKey);
},
);
});
}
private async ensureKeyfile(): Promise<Buffer> {
const dir = plugins.path.dirname(this.keyfilePath);
try {
await plugins.fs.promises.mkdir(dir, { recursive: true });
} catch {
// Already exists
}
try {
const content = await plugins.fs.promises.readFile(this.keyfilePath);
return content;
} catch {
// Generate new keyfile
const key = plugins.crypto.randomBytes(32);
await plugins.fs.promises.writeFile(this.keyfilePath, key, { mode: 0o600 });
return key;
}
}
private async readVault(): Promise<IVaultData> {
try {
const content = await plugins.fs.promises.readFile(this.vaultPath, 'utf8');
return JSON.parse(content) as IVaultData;
} catch {
return {};
}
}
private async writeVault(vault: IVaultData): Promise<void> {
const dir = plugins.path.dirname(this.vaultPath);
try {
await plugins.fs.promises.mkdir(dir, { recursive: true });
} catch {
// Already exists
}
const tmpPath = this.vaultPath + '.tmp';
await plugins.fs.promises.writeFile(tmpPath, JSON.stringify(vault, null, 2), {
encoding: 'utf8',
mode: 0o600,
});
await plugins.fs.promises.rename(tmpPath, this.vaultPath);
}
}