@xenosystem/primitives 0.0.0-stage → 0.2.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.
Files changed (107) hide show
  1. package/README.md +29 -2
  2. package/dist/cjs/dirs/atomic.d.ts +9 -0
  3. package/dist/cjs/dirs/atomic.js +59 -0
  4. package/dist/cjs/dirs/check-cli.d.ts +2 -0
  5. package/dist/cjs/dirs/check-cli.js +50 -0
  6. package/dist/cjs/dirs/check.d.ts +49 -0
  7. package/dist/cjs/dirs/check.js +158 -0
  8. package/dist/cjs/dirs/cli.d.ts +2 -0
  9. package/dist/cjs/dirs/cli.js +72 -0
  10. package/dist/cjs/dirs/dirs.d.ts +57 -0
  11. package/dist/cjs/dirs/dirs.js +135 -0
  12. package/dist/cjs/dirs/doctor.d.ts +31 -0
  13. package/dist/cjs/dirs/doctor.js +80 -0
  14. package/dist/cjs/dirs/errors.d.ts +8 -0
  15. package/dist/cjs/dirs/errors.js +19 -0
  16. package/dist/cjs/dirs/host.d.ts +4 -0
  17. package/dist/cjs/dirs/host.js +26 -0
  18. package/dist/cjs/dirs/index.d.ts +13 -0
  19. package/dist/cjs/dirs/index.js +55 -0
  20. package/dist/cjs/dirs/inputs.d.ts +14 -0
  21. package/dist/cjs/dirs/inputs.js +14 -0
  22. package/dist/cjs/dirs/layout.d.ts +16 -0
  23. package/dist/cjs/dirs/layout.js +25 -0
  24. package/dist/cjs/dirs/lock.d.ts +38 -0
  25. package/dist/cjs/dirs/lock.js +128 -0
  26. package/dist/cjs/dirs/migrate.d.ts +134 -0
  27. package/dist/cjs/dirs/migrate.js +437 -0
  28. package/dist/cjs/dirs/procinfo.d.ts +10 -0
  29. package/dist/cjs/dirs/procinfo.js +67 -0
  30. package/dist/cjs/dirs/registry.d.ts +27 -0
  31. package/dist/cjs/dirs/registry.js +78 -0
  32. package/dist/cjs/dirs/roots.d.ts +23 -0
  33. package/dist/cjs/dirs/roots.js +114 -0
  34. package/dist/cjs/dirs/segments.d.ts +7 -0
  35. package/dist/cjs/dirs/segments.js +39 -0
  36. package/dist/cjs/generated/contract.d.ts +134 -0
  37. package/dist/cjs/generated/contract.js +233 -0
  38. package/dist/cjs/package.json +1 -0
  39. package/dist/cjs/secrets/envelope.d.ts +37 -0
  40. package/dist/cjs/secrets/envelope.js +90 -0
  41. package/dist/cjs/secrets/errors.d.ts +10 -0
  42. package/dist/cjs/secrets/errors.js +20 -0
  43. package/dist/cjs/secrets/index.d.ts +4 -0
  44. package/dist/cjs/secrets/index.js +17 -0
  45. package/dist/cjs/secrets/keystore.d.ts +37 -0
  46. package/dist/cjs/secrets/keystore.js +41 -0
  47. package/dist/cjs/secrets/os-stores.d.ts +17 -0
  48. package/dist/cjs/secrets/os-stores.js +195 -0
  49. package/dist/cjs/secrets/store.d.ts +32 -0
  50. package/dist/cjs/secrets/store.js +161 -0
  51. package/dist/cjs/secrets/testing.d.ts +5 -0
  52. package/dist/cjs/secrets/testing.js +20 -0
  53. package/dist/cjs/updates/index.d.ts +67 -0
  54. package/dist/cjs/updates/index.js +102 -0
  55. package/dist/esm/dirs/atomic.d.ts +9 -0
  56. package/dist/esm/dirs/atomic.js +56 -0
  57. package/dist/esm/dirs/check-cli.d.ts +2 -0
  58. package/dist/esm/dirs/check-cli.js +48 -0
  59. package/dist/esm/dirs/check.d.ts +49 -0
  60. package/dist/esm/dirs/check.js +152 -0
  61. package/dist/esm/dirs/cli.d.ts +2 -0
  62. package/dist/esm/dirs/cli.js +70 -0
  63. package/dist/esm/dirs/dirs.d.ts +57 -0
  64. package/dist/esm/dirs/dirs.js +129 -0
  65. package/dist/esm/dirs/doctor.d.ts +31 -0
  66. package/dist/esm/dirs/doctor.js +77 -0
  67. package/dist/esm/dirs/errors.d.ts +8 -0
  68. package/dist/esm/dirs/errors.js +14 -0
  69. package/dist/esm/dirs/host.d.ts +4 -0
  70. package/dist/esm/dirs/host.js +21 -0
  71. package/dist/esm/dirs/index.d.ts +13 -0
  72. package/dist/esm/dirs/index.js +13 -0
  73. package/dist/esm/dirs/inputs.d.ts +14 -0
  74. package/dist/esm/dirs/inputs.js +11 -0
  75. package/dist/esm/dirs/layout.d.ts +16 -0
  76. package/dist/esm/dirs/layout.js +21 -0
  77. package/dist/esm/dirs/lock.d.ts +38 -0
  78. package/dist/esm/dirs/lock.js +124 -0
  79. package/dist/esm/dirs/migrate.d.ts +134 -0
  80. package/dist/esm/dirs/migrate.js +428 -0
  81. package/dist/esm/dirs/procinfo.d.ts +10 -0
  82. package/dist/esm/dirs/procinfo.js +62 -0
  83. package/dist/esm/dirs/registry.d.ts +27 -0
  84. package/dist/esm/dirs/registry.js +71 -0
  85. package/dist/esm/dirs/roots.d.ts +23 -0
  86. package/dist/esm/dirs/roots.js +107 -0
  87. package/dist/esm/dirs/segments.d.ts +7 -0
  88. package/dist/esm/dirs/segments.js +35 -0
  89. package/dist/esm/generated/contract.d.ts +134 -0
  90. package/dist/esm/generated/contract.js +230 -0
  91. package/dist/esm/secrets/envelope.d.ts +37 -0
  92. package/dist/esm/secrets/envelope.js +81 -0
  93. package/dist/esm/secrets/errors.d.ts +10 -0
  94. package/dist/esm/secrets/errors.js +15 -0
  95. package/dist/esm/secrets/index.d.ts +4 -0
  96. package/dist/esm/secrets/index.js +4 -0
  97. package/dist/esm/secrets/keystore.d.ts +37 -0
  98. package/dist/esm/secrets/keystore.js +37 -0
  99. package/dist/esm/secrets/os-stores.d.ts +17 -0
  100. package/dist/esm/secrets/os-stores.js +189 -0
  101. package/dist/esm/secrets/store.d.ts +32 -0
  102. package/dist/esm/secrets/store.js +156 -0
  103. package/dist/esm/secrets/testing.d.ts +5 -0
  104. package/dist/esm/secrets/testing.js +12 -0
  105. package/dist/esm/updates/index.d.ts +67 -0
  106. package/dist/esm/updates/index.js +97 -0
  107. package/package.json +42 -4
@@ -0,0 +1,81 @@
1
+ import { createCipheriv, createDecipheriv, createHash, randomBytes } from 'node:crypto';
2
+ import { SecretsError } from "./errors.js";
3
+ export const KEY_BYTES = 32;
4
+ const NONCE_BYTES = 12;
5
+ const TAG_BYTES = 16;
6
+ export const wrapAad = (area, name) => Buffer.from(`xeno-secrets:v1:wrap:${area}:${name}`, 'utf8');
7
+ export const dataAad = (area, name) => Buffer.from(`xeno-secrets:v1:data:${area}:${name}`, 'utf8');
8
+ /** Identifier of a master key: first 8 bytes of its SHA-256, hex. Not secret; lets a wrong key be told from a tampered file. */
9
+ export function keyIdOf(masterKey) {
10
+ return createHash('sha256').update(masterKey).digest('hex').slice(0, 16);
11
+ }
12
+ function seal(key, nonce, plaintext, aad) {
13
+ const c = createCipheriv('aes-256-gcm', key, nonce);
14
+ c.setAAD(aad);
15
+ const ct = Buffer.concat([c.update(plaintext), c.final()]);
16
+ return Buffer.concat([ct, c.getAuthTag()]);
17
+ }
18
+ function open(key, nonce, sealed, aad) {
19
+ if (sealed.length < TAG_BYTES)
20
+ return null;
21
+ try {
22
+ const d = createDecipheriv('aes-256-gcm', key, nonce);
23
+ d.setAAD(aad);
24
+ d.setAuthTag(sealed.subarray(sealed.length - TAG_BYTES));
25
+ return Buffer.concat([d.update(sealed.subarray(0, sealed.length - TAG_BYTES)), d.final()]);
26
+ }
27
+ catch {
28
+ return null;
29
+ }
30
+ }
31
+ export function sealSecret(masterKey, area, name, plaintext, options = {}) {
32
+ if (masterKey.length !== KEY_BYTES)
33
+ throw new SecretsError('invalid-argument', 'the master key must be 32 bytes');
34
+ const dek = options.dek ?? randomBytes(KEY_BYTES);
35
+ const wrapNonce = options.wrapNonce ?? randomBytes(NONCE_BYTES);
36
+ const dataNonce = options.dataNonce ?? randomBytes(NONCE_BYTES);
37
+ const file = {
38
+ v: 1,
39
+ alg: 'AES-256-GCM',
40
+ area,
41
+ name,
42
+ keyId: keyIdOf(masterKey),
43
+ wrap: { nonce: Buffer.from(wrapNonce).toString('base64'), ct: seal(masterKey, wrapNonce, dek, wrapAad(area, name)).toString('base64') },
44
+ data: { nonce: Buffer.from(dataNonce).toString('base64'), ct: seal(dek, dataNonce, plaintext, dataAad(area, name)).toString('base64') },
45
+ createdAt: options.createdAt ?? new Date().toISOString(),
46
+ };
47
+ if (options.dek === undefined)
48
+ dek.fill(0);
49
+ return file;
50
+ }
51
+ /** Parses and shape-checks an envelope file. Throws `malformed`; never echoes file content. */
52
+ export function parseEnvelope(text) {
53
+ let v;
54
+ try {
55
+ v = JSON.parse(text);
56
+ }
57
+ catch {
58
+ throw new SecretsError('malformed', 'the secret file is not valid JSON');
59
+ }
60
+ const o = v;
61
+ const part = (p) => typeof p === 'object' && p !== null && typeof p.nonce === 'string' && typeof p.ct === 'string';
62
+ if (!o || o.v !== 1 || o.alg !== 'AES-256-GCM' || typeof o.area !== 'string' || typeof o.name !== 'string' || typeof o.keyId !== 'string' || !part(o.wrap) || !part(o.data)) {
63
+ throw new SecretsError('malformed', 'the secret file is not a version 1 envelope');
64
+ }
65
+ return o;
66
+ }
67
+ export function openSecret(masterKey, file, area, name) {
68
+ if (file.area !== area || file.name !== name)
69
+ throw new SecretsError('decrypt-failed', `the secret file does not belong at ${area}/${name}`);
70
+ const dek = open(masterKey, Buffer.from(file.wrap.nonce, 'base64'), Buffer.from(file.wrap.ct, 'base64'), wrapAad(area, name));
71
+ if (dek === null) {
72
+ throw keyIdOf(masterKey) !== file.keyId
73
+ ? new SecretsError('key-mismatch', `${area}/${name} was sealed with a different master key`)
74
+ : new SecretsError('decrypt-failed', `${area}/${name} failed authentication (damaged or tampered)`);
75
+ }
76
+ const pt = open(dek, Buffer.from(file.data.nonce, 'base64'), Buffer.from(file.data.ct, 'base64'), dataAad(area, name));
77
+ dek.fill(0);
78
+ if (pt === null)
79
+ throw new SecretsError('decrypt-failed', `${area}/${name} failed authentication (damaged or tampered)`);
80
+ return pt;
81
+ }
@@ -0,0 +1,10 @@
1
+ export type SecretsErrorCode = 'unprotected-store' | 'unsupported-platform' | 'key-unavailable' | 'key-mismatch' | 'decrypt-failed' | 'malformed' | 'invalid-argument';
2
+ /**
3
+ * Every error this family throws. Messages never contain a secret value; they may name the area and the secret's
4
+ * name (names are not secret). `code` is stable and is what callers branch on.
5
+ */
6
+ export declare class SecretsError extends Error {
7
+ readonly code: SecretsErrorCode;
8
+ constructor(code: SecretsErrorCode, message: string);
9
+ }
10
+ export declare function isSecretsError(e: unknown, code?: SecretsErrorCode): e is SecretsError;
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Every error this family throws. Messages never contain a secret value; they may name the area and the secret's
3
+ * name (names are not secret). `code` is stable and is what callers branch on.
4
+ */
5
+ export class SecretsError extends Error {
6
+ code;
7
+ constructor(code, message) {
8
+ super(message);
9
+ this.name = 'SecretsError';
10
+ this.code = code;
11
+ }
12
+ }
13
+ export function isSecretsError(e, code) {
14
+ return e instanceof SecretsError && (code === undefined || e.code === code);
15
+ }
@@ -0,0 +1,4 @@
1
+ export { SecretsError, isSecretsError, type SecretsErrorCode } from './errors.ts';
2
+ export { SecretStore, createSecretStore, type SecretStoreOptions } from './store.ts';
3
+ export { electronSafeStorageKeyStore, unprotectedKeyStore, type BlobLocation, type KeyStore, type SafeStorageLike, } from './keystore.ts';
4
+ export { createLibsecretKeyStore, createMacKeychainKeyStore, createOsKeyStore, createWindowsCredentialKeyStore, type OsStoreOptions, } from './os-stores.ts';
@@ -0,0 +1,4 @@
1
+ export { SecretsError, isSecretsError } from "./errors.js";
2
+ export { SecretStore, createSecretStore } from "./store.js";
3
+ export { electronSafeStorageKeyStore, unprotectedKeyStore, } from "./keystore.js";
4
+ export { createLibsecretKeyStore, createMacKeychainKeyStore, createOsKeyStore, createWindowsCredentialKeyStore, } from "./os-stores.js";
@@ -0,0 +1,37 @@
1
+ /**
2
+ * Where the per-machine master key rests. The OS store holds a KEY, never payloads (a Windows credential blob is
3
+ * capped at 2,560 bytes). `protection` is a statement about the platform backend, not a preference: a store that only
4
+ * offers an unprotected backend declares `unprotected`, and the secret store then refuses (no plaintext fallback).
5
+ */
6
+ export interface KeyStore {
7
+ /** Stable identifier for diagnostics, e.g. `windows-credential-manager`. Never a secret. */
8
+ readonly id: string;
9
+ readonly protection: 'os-protected' | 'unprotected';
10
+ /** Why a store is `unprotected` (shown to the person). */
11
+ readonly reason?: string;
12
+ getKey(): Promise<Uint8Array | null>;
13
+ putKey(key: Uint8Array): Promise<void>;
14
+ /** Removes the key; every secret sealed with it becomes unreadable. Used by tests and by account reset. */
15
+ deleteKey(): Promise<void>;
16
+ }
17
+ /** A store that has no protected backend on this machine. Every secret operation refuses with `reason`. */
18
+ export declare function unprotectedKeyStore(id: string, reason: string): KeyStore;
19
+ export interface SafeStorageLike {
20
+ isEncryptionAvailable(): boolean;
21
+ encryptString(plain: string): Uint8Array;
22
+ decryptString(encrypted: Uint8Array): string;
23
+ /** Linux only: `basic_text` means "no secret store; encrypted with a hardcoded password". */
24
+ getSelectedStorageBackend?(): string;
25
+ }
26
+ /** A way to protect bytes with the OS and a place to keep the protected blob. */
27
+ export interface BlobLocation {
28
+ read(): Promise<Uint8Array | null>;
29
+ write(blob: Uint8Array): Promise<void>;
30
+ remove(): Promise<void>;
31
+ }
32
+ /**
33
+ * A KeyStore for products that already ship Electron's safeStorage. The master key is encrypted with safeStorage and
34
+ * the blob kept at `location` (the caller chooses it, under a `secrets` kind path). `basic_text` and `unknown`
35
+ * backends, and `isEncryptionAvailable() === false`, are refused: that is the spec's hard-fail rule.
36
+ */
37
+ export declare function electronSafeStorageKeyStore(safeStorage: SafeStorageLike, location: BlobLocation): KeyStore;
@@ -0,0 +1,37 @@
1
+ import { SecretsError } from "./errors.js";
2
+ /** A store that has no protected backend on this machine. Every secret operation refuses with `reason`. */
3
+ export function unprotectedKeyStore(id, reason) {
4
+ const refuse = () => { throw new SecretsError('unprotected-store', reason); };
5
+ return { id, protection: 'unprotected', reason, getKey: async () => refuse(), putKey: async () => refuse(), deleteKey: async () => refuse() };
6
+ }
7
+ const UNPROTECTED_BACKENDS = new Set(['basic_text', 'unknown']);
8
+ /**
9
+ * A KeyStore for products that already ship Electron's safeStorage. The master key is encrypted with safeStorage and
10
+ * the blob kept at `location` (the caller chooses it, under a `secrets` kind path). `basic_text` and `unknown`
11
+ * backends, and `isEncryptionAvailable() === false`, are refused: that is the spec's hard-fail rule.
12
+ */
13
+ export function electronSafeStorageKeyStore(safeStorage, location) {
14
+ const backend = safeStorage.getSelectedStorageBackend?.();
15
+ const available = safeStorage.isEncryptionAvailable();
16
+ if (!available || (backend !== undefined && UNPROTECTED_BACKENDS.has(backend))) {
17
+ return unprotectedKeyStore('electron-safe-storage', backend !== undefined && UNPROTECTED_BACKENDS.has(backend)
18
+ ? `this machine offers only an unprotected store (Electron backend "${backend}"); secrets are not saved`
19
+ : 'the operating system encryption service is not available; secrets are not saved');
20
+ }
21
+ return {
22
+ id: `electron-safe-storage${backend ? `:${backend}` : ''}`,
23
+ protection: 'os-protected',
24
+ async getKey() {
25
+ const blob = await location.read();
26
+ if (blob === null)
27
+ return null;
28
+ return Buffer.from(safeStorage.decryptString(blob), 'base64');
29
+ },
30
+ async putKey(key) {
31
+ await location.write(safeStorage.encryptString(Buffer.from(key).toString('base64')));
32
+ },
33
+ async deleteKey() {
34
+ await location.remove();
35
+ },
36
+ };
37
+ }
@@ -0,0 +1,17 @@
1
+ import { type KeyStore } from './keystore.ts';
2
+ export interface OsStoreOptions {
3
+ /** Defaults to the contract's secretsKeyService / secretsKeyAccount. Tests pass unique names. */
4
+ service?: string;
5
+ account?: string;
6
+ }
7
+ /**
8
+ * Windows Credential Manager (generic credential, persisted to this machine only; the system encrypts it with DPAPI).
9
+ * The key travels to PowerShell on stdin, never on the command line, and no PowerShell output is surfaced in errors.
10
+ * Slow (about a second per call: PowerShell + a small compiled P/Invoke); callers cache the key per process, and the
11
+ * Rust crate talks to the same entry directly.
12
+ */
13
+ export declare function createWindowsCredentialKeyStore(options?: OsStoreOptions): KeyStore;
14
+ export declare function createMacKeychainKeyStore(options?: OsStoreOptions): KeyStore;
15
+ export declare function createLibsecretKeyStore(options?: OsStoreOptions): KeyStore;
16
+ /** The key store for this machine's operating system. May be `unprotected`, in which case the secret store refuses. */
17
+ export declare function createOsKeyStore(options?: OsStoreOptions): KeyStore;
@@ -0,0 +1,189 @@
1
+ import { execFile, spawnSync } from 'node:child_process';
2
+ import { INPUTS_JSON } from "../generated/contract.js";
3
+ import { SecretsError } from "./errors.js";
4
+ import { unprotectedKeyStore } from "./keystore.js";
5
+ const names = (o) => ({ service: o.service ?? INPUTS_JSON.secretsKeyService, account: o.account ?? INPUTS_JSON.secretsKeyAccount });
6
+ /** Runs a program with stdin; the output is returned, stderr is never surfaced (it can echo input). */
7
+ function run(file, args, stdin, timeoutMs = 120_000) {
8
+ return new Promise((resolve, reject) => {
9
+ const child = execFile(file, args, { timeout: timeoutMs, windowsHide: true, maxBuffer: 1 << 20 }, (err, stdout) => {
10
+ const code = err ? (typeof err.code === 'number' ? (err.code) : -1) : 0;
11
+ if (err && code === -1)
12
+ return reject(new SecretsError('key-unavailable', `could not run ${file}`));
13
+ resolve({ code, stdout: String(stdout) });
14
+ });
15
+ if (stdin !== null)
16
+ child.stdin?.end(stdin);
17
+ else
18
+ child.stdin?.end();
19
+ });
20
+ }
21
+ const hex = (b) => Buffer.from(b).toString('hex');
22
+ // ---- Windows: Credential Manager (DPAPI-backed) ----------------------------------------------------------------
23
+ const WINDOWS_SCRIPT = String.raw `
24
+ $ErrorActionPreference = 'Stop'
25
+ Add-Type -TypeDefinition @'
26
+ using System;
27
+ using System.ComponentModel;
28
+ using System.Runtime.InteropServices;
29
+ public static class XenoCred {
30
+ [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
31
+ struct CREDENTIAL {
32
+ public uint Flags; public uint Type; public string TargetName; public string Comment;
33
+ public System.Runtime.InteropServices.ComTypes.FILETIME LastWritten;
34
+ public uint CredentialBlobSize; public IntPtr CredentialBlob; public uint Persist;
35
+ public uint AttributeCount; public IntPtr Attributes; public string TargetAlias; public string UserName;
36
+ }
37
+ [DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)] static extern bool CredReadW(string t, uint type, uint flags, out IntPtr cred);
38
+ [DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)] static extern bool CredWriteW(ref CREDENTIAL cred, uint flags);
39
+ [DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)] static extern bool CredDeleteW(string t, uint type, uint flags);
40
+ [DllImport("advapi32.dll")] static extern void CredFree(IntPtr p);
41
+ const int NOT_FOUND = 1168;
42
+ public static byte[] Read(string target) {
43
+ IntPtr p;
44
+ if (!CredReadW(target, 1, 0, out p)) { int e = Marshal.GetLastWin32Error(); if (e == NOT_FOUND) return null; throw new Win32Exception(e); }
45
+ try {
46
+ CREDENTIAL c = (CREDENTIAL)Marshal.PtrToStructure(p, typeof(CREDENTIAL));
47
+ byte[] b = new byte[c.CredentialBlobSize];
48
+ Marshal.Copy(c.CredentialBlob, b, 0, b.Length);
49
+ return b;
50
+ } finally { CredFree(p); }
51
+ }
52
+ public static void Write(string target, string account, byte[] blob) {
53
+ CREDENTIAL c = new CREDENTIAL();
54
+ c.Type = 1; c.TargetName = target; c.UserName = account; c.Persist = 2;
55
+ c.CredentialBlobSize = (uint)blob.Length; c.CredentialBlob = Marshal.AllocHGlobal(blob.Length);
56
+ try {
57
+ Marshal.Copy(blob, 0, c.CredentialBlob, blob.Length);
58
+ if (!CredWriteW(ref c, 0)) throw new Win32Exception(Marshal.GetLastWin32Error());
59
+ } finally {
60
+ for (int i = 0; i < blob.Length; i++) Marshal.WriteByte(c.CredentialBlob, i, 0);
61
+ Marshal.FreeHGlobal(c.CredentialBlob);
62
+ }
63
+ }
64
+ public static void Delete(string target) {
65
+ if (!CredDeleteW(target, 1, 0)) { int e = Marshal.GetLastWin32Error(); if (e != NOT_FOUND) throw new Win32Exception(e); }
66
+ }
67
+ }
68
+ '@
69
+ $req = [Console]::In.ReadToEnd() | ConvertFrom-Json
70
+ $target = $req.target
71
+ switch ($req.op) {
72
+ 'get' {
73
+ $b = [XenoCred]::Read($target)
74
+ if ($null -eq $b) { '{"found":false}' } else { '{"found":true,"key":"' + [Convert]::ToBase64String($b) + '"}' }
75
+ }
76
+ 'put' { [XenoCred]::Write($target, $req.account, [Convert]::FromBase64String($req.key)); '{"ok":true}' }
77
+ 'delete' { [XenoCred]::Delete($target); '{"ok":true}' }
78
+ default { throw 'unknown op' }
79
+ }
80
+ `;
81
+ /**
82
+ * Windows Credential Manager (generic credential, persisted to this machine only; the system encrypts it with DPAPI).
83
+ * The key travels to PowerShell on stdin, never on the command line, and no PowerShell output is surfaced in errors.
84
+ * Slow (about a second per call: PowerShell + a small compiled P/Invoke); callers cache the key per process, and the
85
+ * Rust crate talks to the same entry directly.
86
+ */
87
+ export function createWindowsCredentialKeyStore(options = {}) {
88
+ if (process.platform !== 'win32')
89
+ return unprotectedKeyStore('windows-credential-manager', 'Windows Credential Manager is only available on Windows');
90
+ const { service, account } = names(options);
91
+ const target = `${service}:${account}`;
92
+ const ps = `${process.env['SystemRoot'] ?? 'C:\\Windows'}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`;
93
+ const encoded = Buffer.from(WINDOWS_SCRIPT, 'utf16le').toString('base64');
94
+ const call = async (req) => {
95
+ const r = await run(ps, ['-NoProfile', '-NonInteractive', '-EncodedCommand', encoded], JSON.stringify({ target, account, ...req }));
96
+ if (r.code !== 0)
97
+ throw new SecretsError('key-unavailable', `Windows Credential Manager call failed (exit ${r.code})`);
98
+ try {
99
+ return JSON.parse(r.stdout.trim());
100
+ }
101
+ catch {
102
+ throw new SecretsError('key-unavailable', 'Windows Credential Manager returned an unreadable reply');
103
+ }
104
+ };
105
+ return {
106
+ id: 'windows-credential-manager',
107
+ protection: 'os-protected',
108
+ async getKey() {
109
+ const r = await call({ op: 'get' });
110
+ return r['found'] === true && typeof r['key'] === 'string' ? Buffer.from(r['key'], 'base64') : null;
111
+ },
112
+ async putKey(key) { await call({ op: 'put', key: Buffer.from(key).toString('base64') }); },
113
+ async deleteKey() { await call({ op: 'delete' }); },
114
+ };
115
+ }
116
+ // ---- macOS: Keychain via `security -i` (secret on stdin, never on argv) ----------------------------------------
117
+ // UNVERIFIED on a real Mac in this repository's CI: written to the same interface and reviewed against `man security`.
118
+ export function createMacKeychainKeyStore(options = {}) {
119
+ if (process.platform !== 'darwin')
120
+ return unprotectedKeyStore('macos-keychain', 'the macOS Keychain is only available on macOS');
121
+ const { service, account } = names(options);
122
+ const sec = '/usr/bin/security';
123
+ return {
124
+ id: 'macos-keychain',
125
+ protection: 'os-protected',
126
+ async getKey() {
127
+ const r = await run(sec, ['find-generic-password', '-s', service, '-a', account, '-w'], null);
128
+ if (r.code === 44)
129
+ return null; // errSecItemNotFound
130
+ if (r.code !== 0)
131
+ throw new SecretsError('key-unavailable', `Keychain read failed (exit ${r.code})`);
132
+ return Buffer.from(r.stdout.trim(), 'hex');
133
+ },
134
+ async putKey(key) {
135
+ // `security -i` reads commands from stdin, so the key is not visible in the process list.
136
+ const r = await run(sec, ['-i'], `add-generic-password -U -s ${service} -a ${account} -w ${hex(key)}\n`);
137
+ if (r.code !== 0)
138
+ throw new SecretsError('key-unavailable', `Keychain write failed (exit ${r.code})`);
139
+ },
140
+ async deleteKey() {
141
+ const r = await run(sec, ['delete-generic-password', '-s', service, '-a', account], null);
142
+ if (r.code !== 0 && r.code !== 44)
143
+ throw new SecretsError('key-unavailable', `Keychain delete failed (exit ${r.code})`);
144
+ },
145
+ };
146
+ }
147
+ // ---- Linux: libsecret via `secret-tool` (secret on stdin) ------------------------------------------------------
148
+ // UNVERIFIED against a live Secret Service in this repository's CI. Without a working service it refuses, which is the
149
+ // verified path: there is no plaintext fallback.
150
+ export function createLibsecretKeyStore(options = {}) {
151
+ if (process.platform !== 'linux')
152
+ return unprotectedKeyStore('libsecret', 'libsecret is only available on Linux');
153
+ const { service, account } = names(options);
154
+ const attrs = ['service', service, 'account', account];
155
+ // Probe now: a missing tool or an unreachable Secret Service means this machine has no protected store.
156
+ const probe = spawnSync('secret-tool', ['lookup', ...attrs], { encoding: 'utf8', timeout: 15_000 });
157
+ if (probe.error)
158
+ return unprotectedKeyStore('libsecret', 'secret-tool (libsecret) is not installed; secrets are not saved');
159
+ if (probe.status !== 0 && String(probe.stderr ?? '').trim() !== '') {
160
+ return unprotectedKeyStore('libsecret', 'no Secret Service (GNOME Keyring, KWallet) is reachable; secrets are not saved');
161
+ }
162
+ return {
163
+ id: 'libsecret',
164
+ protection: 'os-protected',
165
+ async getKey() {
166
+ const r = await run('secret-tool', ['lookup', ...attrs], null);
167
+ if (r.code !== 0 || r.stdout.trim() === '')
168
+ return null;
169
+ return Buffer.from(r.stdout.trim(), 'hex');
170
+ },
171
+ async putKey(key) {
172
+ const r = await run('secret-tool', ['store', '--label=XENO secrets key', ...attrs], hex(key));
173
+ if (r.code !== 0)
174
+ throw new SecretsError('key-unavailable', `Secret Service write failed (exit ${r.code})`);
175
+ },
176
+ async deleteKey() {
177
+ await run('secret-tool', ['clear', ...attrs], null);
178
+ },
179
+ };
180
+ }
181
+ /** The key store for this machine's operating system. May be `unprotected`, in which case the secret store refuses. */
182
+ export function createOsKeyStore(options = {}) {
183
+ switch (process.platform) {
184
+ case 'win32': return createWindowsCredentialKeyStore(options);
185
+ case 'darwin': return createMacKeychainKeyStore(options);
186
+ case 'linux': return createLibsecretKeyStore(options);
187
+ default: return unprotectedKeyStore('unsupported', `no protected key store is implemented for ${process.platform}`);
188
+ }
189
+ }
@@ -0,0 +1,32 @@
1
+ import { type XenoDirs } from '../dirs/index.ts';
2
+ import type { KeyStore } from './keystore.ts';
3
+ export interface SecretStoreOptions {
4
+ dirs: XenoDirs;
5
+ keyStore: KeyStore;
6
+ }
7
+ /**
8
+ * Envelope-encrypted secrets at `secrets/<area>/<name>.secret` (XENO LOCAL HOME - SPEC.md section 6).
9
+ * It refuses outright when the key store is not OS-protected: there is no plaintext fallback. It never creates a new
10
+ * master key while secrets sealed with an old one exist, because that would silently orphan them.
11
+ */
12
+ export declare class SecretStore {
13
+ #private;
14
+ constructor(options: SecretStoreOptions);
15
+ /** Whether this machine can keep secrets, and if not, why. Safe to show to a person. */
16
+ status(): {
17
+ available: boolean;
18
+ keyStore: string;
19
+ reason?: string;
20
+ };
21
+ set(area: string, name: string, value: string | Uint8Array): Promise<void>;
22
+ /** The secret's bytes, or null when it does not exist. */
23
+ get(area: string, name: string): Promise<Buffer | null>;
24
+ getString(area: string, name: string): Promise<string | null>;
25
+ has(area: string, name: string): Promise<boolean>;
26
+ delete(area: string, name: string): Promise<boolean>;
27
+ /** Names (never values) stored in an area. */
28
+ list(area: string): Promise<string[]>;
29
+ /** Drops the in-memory copy of the master key. */
30
+ forgetKey(): void;
31
+ }
32
+ export declare function createSecretStore(options: SecretStoreOptions): SecretStore;
@@ -0,0 +1,156 @@
1
+ import { randomBytes } from 'node:crypto';
2
+ import { promises as fsp } from 'node:fs';
3
+ import { AREAS, assertSegment } from "../dirs/index.js";
4
+ import { KEY_BYTES, openSecret, parseEnvelope, sealSecret } from "./envelope.js";
5
+ import { SecretsError } from "./errors.js";
6
+ const SUFFIX = '.secret';
7
+ /**
8
+ * Envelope-encrypted secrets at `secrets/<area>/<name>.secret` (XENO LOCAL HOME - SPEC.md section 6).
9
+ * It refuses outright when the key store is not OS-protected: there is no plaintext fallback. It never creates a new
10
+ * master key while secrets sealed with an old one exist, because that would silently orphan them.
11
+ */
12
+ export class SecretStore {
13
+ #dirs;
14
+ #keyStore;
15
+ #key = null;
16
+ constructor(options) {
17
+ this.#dirs = options.dirs;
18
+ this.#keyStore = options.keyStore;
19
+ }
20
+ /** Whether this machine can keep secrets, and if not, why. Safe to show to a person. */
21
+ status() {
22
+ return this.#keyStore.protection === 'os-protected'
23
+ ? { available: true, keyStore: this.#keyStore.id }
24
+ : { available: false, keyStore: this.#keyStore.id, reason: this.#keyStore.reason ?? 'no protected store is available' };
25
+ }
26
+ #requireProtected() {
27
+ if (this.#keyStore.protection !== 'os-protected') {
28
+ throw new SecretsError('unprotected-store', this.#keyStore.reason ?? 'this machine offers only an unprotected store; secrets are not saved');
29
+ }
30
+ }
31
+ #file(area, name) {
32
+ assertSegment(name, 'secret name');
33
+ return this.#dirs.path('secrets', area, name + SUFFIX);
34
+ }
35
+ async #anySecretExists() {
36
+ for (const a of AREAS) {
37
+ if (!a.uses.includes('secrets') || a.slugPattern !== undefined)
38
+ continue;
39
+ try {
40
+ const names = await fsp.readdir(this.#dirs.path('secrets', a.area));
41
+ if (names.some((n) => n.endsWith(SUFFIX)))
42
+ return true;
43
+ }
44
+ catch (e) {
45
+ if (e.code !== 'ENOENT')
46
+ throw e;
47
+ }
48
+ }
49
+ return false;
50
+ }
51
+ async #masterKey(create) {
52
+ if (this.#key !== null)
53
+ return this.#key;
54
+ this.#requireProtected();
55
+ const found = await this.#keyStore.getKey();
56
+ if (found !== null) {
57
+ if (found.length !== KEY_BYTES)
58
+ throw new SecretsError('key-unavailable', 'the stored master key has the wrong length');
59
+ return (this.#key = Buffer.from(found));
60
+ }
61
+ if (!create)
62
+ return null;
63
+ return this.#dirs.withLock('platform', 'secrets-key', async () => {
64
+ const again = await this.#keyStore.getKey();
65
+ if (again !== null)
66
+ return (this.#key = Buffer.from(again));
67
+ if (await this.#anySecretExists()) {
68
+ throw new SecretsError('key-unavailable', 'secrets exist but the master key is missing from the OS store; refusing to create a new key that would orphan them');
69
+ }
70
+ const fresh = randomBytes(KEY_BYTES);
71
+ await this.#keyStore.putKey(fresh);
72
+ const check = await this.#keyStore.getKey();
73
+ if (check === null || !fresh.equals(Buffer.from(check)))
74
+ throw new SecretsError('key-unavailable', 'the OS store did not keep the master key');
75
+ return (this.#key = fresh);
76
+ }, { owner: 'secrets master key', timeoutMs: 60_000 });
77
+ }
78
+ async set(area, name, value) {
79
+ this.#file(area, name); // validates area, kind and name before anything is created
80
+ this.#requireProtected();
81
+ this.#dirs.assertWritable(); // a newer layout must refuse before a master key is created
82
+ const key = (await this.#masterKey(true));
83
+ const bytes = typeof value === 'string' ? Buffer.from(value, 'utf8') : Buffer.from(value);
84
+ const sealed = sealSecret(key, area, name, bytes);
85
+ bytes.fill(0);
86
+ await this.#dirs.writeFile('secrets', area, [name + SUFFIX], JSON.stringify(sealed) + '\n');
87
+ }
88
+ /** The secret's bytes, or null when it does not exist. */
89
+ async get(area, name) {
90
+ const path = this.#file(area, name);
91
+ this.#requireProtected();
92
+ let text;
93
+ try {
94
+ text = await fsp.readFile(path, 'utf8');
95
+ }
96
+ catch (e) {
97
+ if (e.code === 'ENOENT')
98
+ return null;
99
+ throw e;
100
+ }
101
+ const key = await this.#masterKey(false);
102
+ if (key === null)
103
+ throw new SecretsError('key-unavailable', `${area}/${name} exists but the master key is missing from the OS store`);
104
+ return openSecret(key, parseEnvelope(text), area, name);
105
+ }
106
+ async getString(area, name) {
107
+ const b = await this.get(area, name);
108
+ if (b === null)
109
+ return null;
110
+ const s = b.toString('utf8');
111
+ b.fill(0);
112
+ return s;
113
+ }
114
+ async has(area, name) {
115
+ try {
116
+ await fsp.access(this.#file(area, name));
117
+ return true;
118
+ }
119
+ catch (e) {
120
+ if (e.code === 'ENOENT')
121
+ return false;
122
+ throw e;
123
+ }
124
+ }
125
+ async delete(area, name) {
126
+ try {
127
+ await fsp.unlink(this.#file(area, name));
128
+ return true;
129
+ }
130
+ catch (e) {
131
+ if (e.code === 'ENOENT')
132
+ return false;
133
+ throw e;
134
+ }
135
+ }
136
+ /** Names (never values) stored in an area. */
137
+ async list(area) {
138
+ try {
139
+ const names = await fsp.readdir(this.#dirs.path('secrets', area));
140
+ return names.filter((n) => n.endsWith(SUFFIX)).map((n) => n.slice(0, -SUFFIX.length)).sort();
141
+ }
142
+ catch (e) {
143
+ if (e.code === 'ENOENT')
144
+ return [];
145
+ throw e;
146
+ }
147
+ }
148
+ /** Drops the in-memory copy of the master key. */
149
+ forgetKey() {
150
+ this.#key?.fill(0);
151
+ this.#key = null;
152
+ }
153
+ }
154
+ export function createSecretStore(options) {
155
+ return new SecretStore(options);
156
+ }
@@ -0,0 +1,5 @@
1
+ import type { KeyStore } from './keystore.ts';
2
+ export declare function createMemoryKeyStore(initial?: Uint8Array | null): KeyStore & {
3
+ snapshot(): Uint8Array | null;
4
+ };
5
+ export { sealSecret, openSecret, parseEnvelope, keyIdOf } from './envelope.ts';
@@ -0,0 +1,12 @@
1
+ export function createMemoryKeyStore(initial = null) {
2
+ let key = initial === null ? null : Buffer.from(initial);
3
+ return {
4
+ id: 'memory-test-only',
5
+ protection: 'os-protected',
6
+ async getKey() { return key === null ? null : Buffer.from(key); },
7
+ async putKey(k) { key = Buffer.from(k); },
8
+ async deleteKey() { key = null; },
9
+ snapshot() { return key === null ? null : Buffer.from(key); },
10
+ };
11
+ }
12
+ export { sealSecret, openSecret, parseEnvelope, keyIdOf } from "./envelope.js";