feat(core): initial release with 3-tier secret storage
Implements SmartSecret with macOS Keychain, Linux secret-tool, and AES-256-GCM encrypted file fallback backends. Zero runtime dependencies.
This commit is contained in:
@@ -0,0 +1,8 @@
|
||||
/**
|
||||
* autocreated commitinfo by @pushrocks/commitinfo
|
||||
*/
|
||||
export const commitinfo = {
|
||||
name: '@push.rocks/smartsecret',
|
||||
version: '1.0.0',
|
||||
description: 'OS keychain-based secret storage with encrypted-file fallback for Node.js.',
|
||||
};
|
||||
@@ -0,0 +1,5 @@
|
||||
export * from './smartsecret.classes.smartsecret.js';
|
||||
export type { ISecretBackend, TBackendType } from './smartsecret.backends.base.js';
|
||||
export { MacosKeychainBackend } from './smartsecret.backends.macos.js';
|
||||
export { LinuxSecretServiceBackend } from './smartsecret.backends.linux.js';
|
||||
export { FileEncryptedBackend } from './smartsecret.backends.file.js';
|
||||
@@ -0,0 +1,10 @@
|
||||
export type TBackendType = 'macos-keychain' | 'linux-secret-service' | 'file-encrypted';
|
||||
|
||||
export interface ISecretBackend {
|
||||
readonly backendType: TBackendType;
|
||||
isAvailable(): Promise<boolean>;
|
||||
setSecret(account: string, secret: string): Promise<void>;
|
||||
getSecret(account: string): Promise<string | null>;
|
||||
deleteSecret(account: string): Promise<boolean>;
|
||||
listAccounts(): Promise<string[]>;
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
import * as plugins from './smartsecret.plugins.js';
|
||||
import type { ISecretBackend, TBackendType } from './smartsecret.backends.base.js';
|
||||
|
||||
function execFile(cmd: string, args: string[]): Promise<{ stdout: string; stderr: string }> {
|
||||
return new Promise((resolve, reject) => {
|
||||
plugins.childProcess.execFile(cmd, args, { encoding: 'utf8' }, (err, stdout, stderr) => {
|
||||
if (err) {
|
||||
reject(Object.assign(err, { stdout, stderr }));
|
||||
} else {
|
||||
resolve({ stdout: stdout as string, stderr: stderr as string });
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function spawnWithStdin(cmd: string, args: string[], stdinData: string): Promise<{ stdout: string; stderr: string }> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const child = plugins.childProcess.spawn(cmd, args, { stdio: ['pipe', 'pipe', 'pipe'] });
|
||||
let stdout = '';
|
||||
let stderr = '';
|
||||
child.stdout!.on('data', (chunk: Buffer) => { stdout += chunk.toString(); });
|
||||
child.stderr!.on('data', (chunk: Buffer) => { stderr += chunk.toString(); });
|
||||
child.on('error', reject);
|
||||
child.on('close', (code) => {
|
||||
if (code === 0) {
|
||||
resolve({ stdout, stderr });
|
||||
} else {
|
||||
reject(Object.assign(new Error(`secret-tool exited with code ${code}`), { stdout, stderr }));
|
||||
}
|
||||
});
|
||||
child.stdin!.write(stdinData);
|
||||
child.stdin!.end();
|
||||
});
|
||||
}
|
||||
|
||||
export class LinuxSecretServiceBackend implements ISecretBackend {
|
||||
public readonly backendType: TBackendType = 'linux-secret-service';
|
||||
private service: string;
|
||||
|
||||
constructor(service: string) {
|
||||
this.service = service;
|
||||
}
|
||||
|
||||
async isAvailable(): Promise<boolean> {
|
||||
if (process.platform !== 'linux') return false;
|
||||
try {
|
||||
await execFile('which', ['secret-tool']);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
async setSecret(account: string, secret: string): Promise<void> {
|
||||
// secret-tool store reads password from stdin
|
||||
await spawnWithStdin('secret-tool', [
|
||||
'store',
|
||||
'--label', `${this.service}:${account}`,
|
||||
'service', this.service,
|
||||
'account', account,
|
||||
], secret);
|
||||
}
|
||||
|
||||
async getSecret(account: string): Promise<string | null> {
|
||||
try {
|
||||
const { stdout } = await execFile('secret-tool', [
|
||||
'lookup',
|
||||
'service', this.service,
|
||||
'account', account,
|
||||
]);
|
||||
// secret-tool returns empty string if not found (exit 0) or exits non-zero
|
||||
return stdout.length > 0 ? stdout : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
async deleteSecret(account: string): Promise<boolean> {
|
||||
try {
|
||||
await execFile('secret-tool', [
|
||||
'clear',
|
||||
'service', this.service,
|
||||
'account', account,
|
||||
]);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
async listAccounts(): Promise<string[]> {
|
||||
try {
|
||||
const { stdout } = await execFile('secret-tool', [
|
||||
'search',
|
||||
'--all',
|
||||
'service', this.service,
|
||||
]);
|
||||
const accounts: string[] = [];
|
||||
const regex = /attribute\.account = (.+)/g;
|
||||
let match: RegExpExecArray | null;
|
||||
while ((match = regex.exec(stdout)) !== null) {
|
||||
accounts.push(match[1].trim());
|
||||
}
|
||||
return [...new Set(accounts)];
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
import * as plugins from './smartsecret.plugins.js';
|
||||
import type { ISecretBackend, TBackendType } from './smartsecret.backends.base.js';
|
||||
|
||||
function execFile(cmd: string, args: string[]): Promise<{ stdout: string; stderr: string }> {
|
||||
return new Promise((resolve, reject) => {
|
||||
plugins.childProcess.execFile(cmd, args, { encoding: 'utf8' }, (err, stdout, stderr) => {
|
||||
if (err) {
|
||||
reject(Object.assign(err, { stdout, stderr }));
|
||||
} else {
|
||||
resolve({ stdout: stdout as string, stderr: stderr as string });
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
export class MacosKeychainBackend implements ISecretBackend {
|
||||
public readonly backendType: TBackendType = 'macos-keychain';
|
||||
private service: string;
|
||||
|
||||
constructor(service: string) {
|
||||
this.service = service;
|
||||
}
|
||||
|
||||
async isAvailable(): Promise<boolean> {
|
||||
if (process.platform !== 'darwin') return false;
|
||||
try {
|
||||
await execFile('which', ['security']);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
async setSecret(account: string, secret: string): Promise<void> {
|
||||
// Delete existing entry first (ignore errors if not found)
|
||||
try {
|
||||
await execFile('security', [
|
||||
'delete-generic-password',
|
||||
'-s', this.service,
|
||||
'-a', account,
|
||||
]);
|
||||
} catch {
|
||||
// Not found — fine
|
||||
}
|
||||
|
||||
await execFile('security', [
|
||||
'add-generic-password',
|
||||
'-s', this.service,
|
||||
'-a', account,
|
||||
'-w', secret,
|
||||
'-U',
|
||||
]);
|
||||
}
|
||||
|
||||
async getSecret(account: string): Promise<string | null> {
|
||||
try {
|
||||
const { stdout } = await execFile('security', [
|
||||
'find-generic-password',
|
||||
'-s', this.service,
|
||||
'-a', account,
|
||||
'-w',
|
||||
]);
|
||||
return stdout.trim();
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
async deleteSecret(account: string): Promise<boolean> {
|
||||
try {
|
||||
await execFile('security', [
|
||||
'delete-generic-password',
|
||||
'-s', this.service,
|
||||
'-a', account,
|
||||
]);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
async listAccounts(): Promise<string[]> {
|
||||
try {
|
||||
const { stdout } = await execFile('security', [
|
||||
'dump-keychain',
|
||||
]);
|
||||
const accounts: string[] = [];
|
||||
const serviceRegex = new RegExp(`"svce"<blob>="${this.service.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}"`);
|
||||
const lines = stdout.split('\n');
|
||||
for (let i = 0; i < lines.length; i++) {
|
||||
if (serviceRegex.test(lines[i])) {
|
||||
// Look for the account line nearby
|
||||
for (let j = Math.max(0, i - 5); j < Math.min(lines.length, i + 5); j++) {
|
||||
const match = lines[j].match(/"acct"<blob>="([^"]+)"/);
|
||||
if (match) {
|
||||
accounts.push(match[1]);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return [...new Set(accounts)];
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
import type { ISecretBackend, TBackendType } from './smartsecret.backends.base.js';
|
||||
import { MacosKeychainBackend } from './smartsecret.backends.macos.js';
|
||||
import { LinuxSecretServiceBackend } from './smartsecret.backends.linux.js';
|
||||
import { FileEncryptedBackend } from './smartsecret.backends.file.js';
|
||||
|
||||
export interface ISmartSecretOptions {
|
||||
service?: string;
|
||||
vaultPath?: string;
|
||||
}
|
||||
|
||||
export class SmartSecret {
|
||||
private service: string;
|
||||
private vaultPath?: string;
|
||||
private backend: ISecretBackend | null = null;
|
||||
|
||||
constructor(options?: ISmartSecretOptions) {
|
||||
this.service = options?.service ?? 'smartsecret';
|
||||
this.vaultPath = options?.vaultPath;
|
||||
}
|
||||
|
||||
private async getBackend(): Promise<ISecretBackend> {
|
||||
if (this.backend) return this.backend;
|
||||
|
||||
const candidates: ISecretBackend[] = [
|
||||
new MacosKeychainBackend(this.service),
|
||||
new LinuxSecretServiceBackend(this.service),
|
||||
new FileEncryptedBackend(this.service, this.vaultPath),
|
||||
];
|
||||
|
||||
for (const candidate of candidates) {
|
||||
if (await candidate.isAvailable()) {
|
||||
this.backend = candidate;
|
||||
return this.backend;
|
||||
}
|
||||
}
|
||||
|
||||
// File backend is always available, so we should never reach here
|
||||
this.backend = candidates[candidates.length - 1];
|
||||
return this.backend;
|
||||
}
|
||||
|
||||
async setSecret(account: string, secret: string): Promise<void> {
|
||||
const backend = await this.getBackend();
|
||||
await backend.setSecret(account, secret);
|
||||
}
|
||||
|
||||
async getSecret(account: string): Promise<string | null> {
|
||||
const backend = await this.getBackend();
|
||||
return backend.getSecret(account);
|
||||
}
|
||||
|
||||
async deleteSecret(account: string): Promise<boolean> {
|
||||
const backend = await this.getBackend();
|
||||
return backend.deleteSecret(account);
|
||||
}
|
||||
|
||||
async listAccounts(): Promise<string[]> {
|
||||
const backend = await this.getBackend();
|
||||
return backend.listAccounts();
|
||||
}
|
||||
|
||||
async getBackendType(): Promise<TBackendType> {
|
||||
const backend = await this.getBackend();
|
||||
return backend.backendType;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
// node native scope
|
||||
import * as childProcess from 'child_process';
|
||||
import * as crypto from 'crypto';
|
||||
import * as fs from 'fs';
|
||||
import * as os from 'os';
|
||||
import * as path from 'path';
|
||||
|
||||
export { childProcess, crypto, fs, os, path };
|
||||
Reference in New Issue
Block a user