mirror of
https://github.com/profullstack/logicsrc.git
synced 2026-10-02 20:57:03 +00:00
* Add the LogicSRC OpenCreds specification Leaving a password manager means writing every secret you own to disk in the clear, and losing whatever the spreadsheet had no column for. A CSV is plaintext by construction, lossy by omission, and carries no integrity: nothing in it says which rows were meant to be there, so a truncated import looks exactly like a complete one. The same gap showed up inside LogicSRC. `logicsrc credentials` moves .env secrets and SSH keys through end-to-end-encrypted team vaults, but it can only model a key/value pair. A card, a passport, a login with a TOTP seed, or an OAuth account with a refresh token are all things people already keep in a vault, and none of them are a key/value pair. OpenCreds defines three things: the item, the vault, and the database. - Six item types (login, card, identity, note, key, account) as one record with a type and a named field group, so everything the user typed lives in a single encrypted blob. Codes 1-4 match MarkSyncr's deployed vault and are not renumbered; compatibility is cheaper than elegance. - AES-256-GCM over that record with the item id bound as AAD. Without it, anyone with storage write access could move a low-value login's ciphertext into a high-value row and watch what the user does next. - A key hierarchy where the user key is random, not derived, so a password change re-wraps 32 bytes rather than re-encrypting a vault. The auth hash comes out of a different HKDF label than the wrap key, which is what lets it reach a server at all. - A portable .opencreds file, encrypted by default, whose header is the AAD over the payload -- so the manifest is authenticated by the same tag as the data and a truncated import fails rather than reporting success. The plaintext form exists because people move to products that read nothing else; it is opt-in, confirmed, 0600, and labelled "protected": false in its own header. Namespaces are carried as data, not fixed by the spec: labels are compiled into every ciphertext a vault has written, so editing one does not migrate a vault, it makes it undecryptable. MarkSyncr's deployed vault is conformant by declaring `marksyncr`. Ships: prd/0004, nine spec pages under docs/opencreds/, six JSON Schemas, the @logicsrc/opencreds reference implementation with CSV importers for five products, `logicsrc vault` and the standalone `opencreds` binary, and the spec page at logicsrc.com/opencreds. `vault` rather than `creds` because `creds` is already an alias of `logicsrc credentials`, and the two are different: one moves a pair between providers, the other stores a record. @logicsrc/validators now registers every schema by $id before compiling, so the database schema can $ref the item and manifest schemas rather than restating them. 120 tests, including CLI end-to-end coverage of the masking rules, exit codes, and the manifest-mismatch path. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01QRQrfuwuYKKV5UB9kLHuX5 * Make the OpenCreds conformance claim executable The conformance page described a fixture suite and an `opencreds conformance` command that did not exist. A specification that documents a conformance surface it cannot run is a specification nobody can hold to, including us. `opencreds conformance` now runs the requirement list as code -- one check per C-number, carrying its own id and level -- and emits the report shape the spec publishes. It exits 2 when a MUST does not pass, so it can gate CI directly. The reference implementation reports 29 passed, 0 failed, 1 skipped; the skip is C19, because key management for the team profile lives in @logicsrc/plugin-credential-sharing rather than in this package, and a skipped MAY does not affect conformance. Fixtures are generated (`--emit-fixtures <dir>`) rather than hand-written. A vector produced by an implementation and then verified by it is worth more than a JSON file someone typed: the typed file drifts silently when the format moves, and the generated one cannot. Fourteen files, including an invalid/ set every conforming reader must reject -- a wrong field group, a weak KDF, an unregistered namespace, a short payload and a tampered manifest. The CLI requirements stay with the end-to-end tests that drive the real binary through a child process; a command cannot meaningfully check its own exit codes, and a masked value that is only masked in the library is not masked. conformance.md and cli.md now describe what ships. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01QRQrfuwuYKKV5UB9kLHuX5 * Add @logicsrc/opencreds to the lockfile `npm ci` refuses a lockfile that does not match package.json, and the new workspace package plus the CLI's dependency on it were never recorded: the worktree was bootstrapped by hardlinking node_modules rather than installing, so npm was never asked to update the lock. Adds the workspace link and the package entry. No dependency versions move. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01QRQrfuwuYKKV5UB9kLHuX5 * Register PRD 0004, and stop the fixtures looking like real secrets Two CI failures, both mine. `prd/README.md` is generated by `logicsrc prd index --write` and the scaffold test asserts it is current, so adding a PRD without regenerating it leaves the repo's own conformance check failing. Regenerated. The MCP test asserts the next free PRD id against the live prd/ directory — its comment says it advances with every PRD added — so it moves to 0005. ThreatCrush flagged three of the example strings: a PEM header in the item-model docs and in the conformance fixture, and an `sk_live_` prefixed token. All placeholders, none real, but the finding is the scanner working. A fixture only has to exercise the field, and a real-looking private key header or live-key prefix sitting in the tree trains both the scanner and the people reading its output to shrug at exactly the shape that matters. Replaced with obvious placeholders rather than suppressing the rule. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01QRQrfuwuYKKV5UB9kLHuX5 --------- Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
279 lines
8.7 KiB
TypeScript
279 lines
8.7 KiB
TypeScript
/**
|
|
* Vault creation, unlock, recovery and re-keying.
|
|
*
|
|
* The user key is 32 random bytes, generated once and wrapped. It is not
|
|
* derived from the password, so changing the master password re-wraps 32 bytes
|
|
* instead of re-encrypting every item — and a partial failure during a password
|
|
* change cannot leave half a vault openable by the old password and half by the
|
|
* new.
|
|
*/
|
|
|
|
import {
|
|
aesGcmDecrypt,
|
|
aesGcmEncrypt,
|
|
fromBase64,
|
|
KEY_BYTES,
|
|
randomBytes,
|
|
toBase64,
|
|
} from "./primitives.js";
|
|
import {
|
|
DEFAULT_KDF_PARAMS,
|
|
assertUsableKdfParams,
|
|
assertUsableNamespace,
|
|
deriveAll,
|
|
deriveAuthHash,
|
|
deriveMasterKey,
|
|
deriveRecoveryWrapKey,
|
|
deriveWrapKey,
|
|
} from "./kdf.js";
|
|
import {
|
|
DEFAULT_NAMESPACE,
|
|
OPENCREDS_VERSION,
|
|
type KdfParams,
|
|
type Namespace,
|
|
type Profile,
|
|
type VaultMeta,
|
|
} from "./types.js";
|
|
|
|
export const SALT_BYTES = 16;
|
|
export const RECOVERY_KEY_BYTES = 16;
|
|
|
|
/**
|
|
* Crockford base32: the digits, then the letters without I, L, O or U.
|
|
*
|
|
* I/1, L/1 and O/0 are the pairs people actually confuse, and U is dropped so
|
|
* that no accidental word offends anyone. Crockford also defines how to decode
|
|
* the confusions, which {@link parseRecoveryKey} implements.
|
|
*/
|
|
const RECOVERY_ALPHABET = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
|
|
|
|
/**
|
|
* Render a recovery key for a human to write down.
|
|
*
|
|
* Groups of five, because this value is transcribed by hand exactly once and
|
|
* misread forever after.
|
|
*/
|
|
export function formatRecoveryKey(bytes: Uint8Array): string {
|
|
let bits = 0;
|
|
let value = 0;
|
|
let out = "";
|
|
for (const byte of bytes) {
|
|
value = (value << 8) | byte;
|
|
bits += 8;
|
|
while (bits >= 5) {
|
|
out += RECOVERY_ALPHABET[(value >>> (bits - 5)) & 31];
|
|
bits -= 5;
|
|
}
|
|
}
|
|
if (bits > 0) out += RECOVERY_ALPHABET[(value << (5 - bits)) & 31];
|
|
return (out.match(/.{1,5}/g) ?? []).join("-");
|
|
}
|
|
|
|
/** Parse a recovery key back, tolerating case, spaces and dashes. */
|
|
export function parseRecoveryKey(input: string): Uint8Array {
|
|
const clean = String(input || "")
|
|
.toUpperCase()
|
|
// Dashes, spaces and anything else a person adds while writing it down.
|
|
.replace(/[^0-9A-Z]/g, "")
|
|
// Crockford's decoding rule for the characters the alphabet omits.
|
|
.replace(/O/g, "0")
|
|
.replace(/[IL]/g, "1");
|
|
let bits = 0;
|
|
let value = 0;
|
|
const out: number[] = [];
|
|
for (const char of clean) {
|
|
const index = RECOVERY_ALPHABET.indexOf(char);
|
|
if (index < 0) throw new Error(`Invalid character in recovery key: ${char}`);
|
|
value = (value << 5) | index;
|
|
bits += 5;
|
|
if (bits >= 8) {
|
|
out.push((value >>> (bits - 8)) & 0xff);
|
|
bits -= 8;
|
|
}
|
|
}
|
|
return new Uint8Array(out);
|
|
}
|
|
|
|
export interface CreatedVault {
|
|
meta: VaultMeta;
|
|
userKey: Uint8Array;
|
|
recoveryKey: string;
|
|
}
|
|
|
|
/**
|
|
* Create a `user`-profile vault.
|
|
*
|
|
* Returns the metadata (safe to send to a server), the user key (never), and
|
|
* the recovery key, which is shown to the person exactly once and then is gone
|
|
* from this process.
|
|
*/
|
|
export async function createVault(
|
|
password: string,
|
|
options: { namespace?: Namespace; params?: KdfParams; allowUnregisteredNamespace?: boolean } = {},
|
|
): Promise<CreatedVault> {
|
|
const namespace = assertUsableNamespace(
|
|
options.namespace ?? DEFAULT_NAMESPACE,
|
|
options.allowUnregisteredNamespace,
|
|
);
|
|
const params = assertUsableKdfParams(options.params ?? DEFAULT_KDF_PARAMS);
|
|
|
|
const salt = randomBytes(SALT_BYTES);
|
|
const userKey = randomBytes(KEY_BYTES);
|
|
const { wrapKey, authHash } = await deriveAll(password, salt, params, namespace);
|
|
|
|
const wrapped = await aesGcmEncrypt(wrapKey, userKey);
|
|
|
|
const recoveryBytes = randomBytes(RECOVERY_KEY_BYTES);
|
|
const recoveryWrapKey = await deriveRecoveryWrapKey(recoveryBytes, namespace);
|
|
const recoveryWrapped = await aesGcmEncrypt(recoveryWrapKey, userKey);
|
|
|
|
const now = new Date().toISOString();
|
|
const meta: VaultMeta = {
|
|
opencreds: OPENCREDS_VERSION,
|
|
namespace,
|
|
profile: "user",
|
|
kdf: params.kdf,
|
|
kdfIterations: params.iterations,
|
|
kdfSalt: toBase64(salt),
|
|
protectedUserKey: toBase64(wrapped.ciphertext),
|
|
protectedUserKeyIv: toBase64(wrapped.iv),
|
|
recoveryKeyBlob: toBase64(recoveryWrapped.ciphertext),
|
|
recoveryKeyIv: toBase64(recoveryWrapped.iv),
|
|
authHash,
|
|
createdAt: now,
|
|
updatedAt: now,
|
|
};
|
|
|
|
return { meta, userKey, recoveryKey: formatRecoveryKey(recoveryBytes) };
|
|
}
|
|
|
|
/** Create a `team`-profile vault: a random key, wrapped by the caller's scheme. */
|
|
export function createTeamVault(namespace: Namespace = DEFAULT_NAMESPACE): { meta: VaultMeta; userKey: Uint8Array } {
|
|
const ns = assertUsableNamespace(namespace);
|
|
const now = new Date().toISOString();
|
|
return {
|
|
userKey: randomBytes(KEY_BYTES),
|
|
meta: {
|
|
opencreds: OPENCREDS_VERSION,
|
|
namespace: ns,
|
|
profile: "team",
|
|
kdf: "pbkdf2-sha256",
|
|
kdfIterations: DEFAULT_KDF_PARAMS.iterations,
|
|
kdfSalt: toBase64(randomBytes(SALT_BYTES)),
|
|
// A team vault's key is sealed to member public keys by the caller
|
|
// (see plugins/credential-sharing), so there is no password-wrapped copy.
|
|
protectedUserKey: "",
|
|
protectedUserKeyIv: "",
|
|
wrappedKeys: [],
|
|
createdAt: now,
|
|
updatedAt: now,
|
|
},
|
|
};
|
|
}
|
|
|
|
function paramsOf(meta: VaultMeta): KdfParams {
|
|
return assertUsableKdfParams({ kdf: meta.kdf, iterations: meta.kdfIterations });
|
|
}
|
|
|
|
export function assertProfile(meta: VaultMeta, supported: Profile[]): void {
|
|
if (!supported.includes(meta.profile)) {
|
|
throw new Error(
|
|
`This implementation does not support the "${meta.profile}" profile; refusing to open the vault`,
|
|
);
|
|
}
|
|
}
|
|
|
|
/** Unlock with the master password. Returns the user key. */
|
|
export async function unlockVault(
|
|
meta: VaultMeta,
|
|
password: string,
|
|
options: { allowUnregisteredNamespace?: boolean } = {},
|
|
): Promise<Uint8Array> {
|
|
assertProfile(meta, ["user"]);
|
|
const namespace = assertUsableNamespace(meta.namespace, options.allowUnregisteredNamespace);
|
|
const params = paramsOf(meta);
|
|
|
|
const masterKey = await deriveMasterKey(password, fromBase64(meta.kdfSalt), params);
|
|
const wrapKey = await deriveWrapKey(masterKey, namespace);
|
|
try {
|
|
return await aesGcmDecrypt(
|
|
wrapKey,
|
|
fromBase64(meta.protectedUserKeyIv),
|
|
fromBase64(meta.protectedUserKey),
|
|
);
|
|
} catch {
|
|
throw new Error("Wrong master password");
|
|
}
|
|
}
|
|
|
|
/** Unlock with the recovery key, for the day the password is gone. */
|
|
export async function unlockWithRecoveryKey(
|
|
meta: VaultMeta,
|
|
recoveryKey: string,
|
|
options: { allowUnregisteredNamespace?: boolean } = {},
|
|
): Promise<Uint8Array> {
|
|
assertProfile(meta, ["user"]);
|
|
const namespace = assertUsableNamespace(meta.namespace, options.allowUnregisteredNamespace);
|
|
if (!meta.recoveryKeyBlob || !meta.recoveryKeyIv) {
|
|
throw new Error("This vault has no recovery key");
|
|
}
|
|
const wrapKey = await deriveRecoveryWrapKey(parseRecoveryKey(recoveryKey), namespace);
|
|
try {
|
|
return await aesGcmDecrypt(wrapKey, fromBase64(meta.recoveryKeyIv), fromBase64(meta.recoveryKeyBlob));
|
|
} catch {
|
|
throw new Error("Wrong recovery key");
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Change the master password.
|
|
*
|
|
* Re-wraps the same user key, so not one item is touched. The recovery blob is
|
|
* left alone: it wraps the same key under a value the person still holds.
|
|
*/
|
|
export async function rewrapUserKey(
|
|
meta: VaultMeta,
|
|
userKey: Uint8Array,
|
|
newPassword: string,
|
|
params: KdfParams = DEFAULT_KDF_PARAMS,
|
|
): Promise<VaultMeta> {
|
|
assertProfile(meta, ["user"]);
|
|
const namespace = assertUsableNamespace(meta.namespace, true);
|
|
const usable = assertUsableKdfParams(params);
|
|
const salt = randomBytes(SALT_BYTES);
|
|
const masterKey = await deriveMasterKey(newPassword, salt, usable);
|
|
const wrapKey = await deriveWrapKey(masterKey, namespace);
|
|
const wrapped = await aesGcmEncrypt(wrapKey, userKey);
|
|
|
|
return {
|
|
...meta,
|
|
kdf: usable.kdf,
|
|
kdfIterations: usable.iterations,
|
|
kdfSalt: toBase64(salt),
|
|
protectedUserKey: toBase64(wrapped.ciphertext),
|
|
protectedUserKeyIv: toBase64(wrapped.iv),
|
|
authHash: await deriveAuthHash(masterKey, namespace),
|
|
updatedAt: new Date().toISOString(),
|
|
};
|
|
}
|
|
|
|
/** Issue a fresh recovery key, invalidating the old one. */
|
|
export async function resetRecoveryKey(
|
|
meta: VaultMeta,
|
|
userKey: Uint8Array,
|
|
): Promise<{ meta: VaultMeta; recoveryKey: string }> {
|
|
assertProfile(meta, ["user"]);
|
|
const namespace = assertUsableNamespace(meta.namespace, true);
|
|
const recoveryBytes = randomBytes(RECOVERY_KEY_BYTES);
|
|
const wrapKey = await deriveRecoveryWrapKey(recoveryBytes, namespace);
|
|
const wrapped = await aesGcmEncrypt(wrapKey, userKey);
|
|
return {
|
|
meta: {
|
|
...meta,
|
|
recoveryKeyBlob: toBase64(wrapped.ciphertext),
|
|
recoveryKeyIv: toBase64(wrapped.iv),
|
|
updatedAt: new Date().toISOString(),
|
|
},
|
|
recoveryKey: formatRecoveryKey(recoveryBytes),
|
|
};
|
|
}
|