mirror of
https://github.com/profullstack/logicsrc.git
synced 2026-10-02 04:43:58 +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>
177 lines
6.2 KiB
TypeScript
177 lines
6.2 KiB
TypeScript
/**
|
|
* Key derivation.
|
|
*
|
|
* The master password is stretched once into a master key, and everything else
|
|
* is derived from that by HKDF under a distinct label. The labels are prefixed
|
|
* by the vault's namespace and versioned, because they are baked into every
|
|
* ciphertext an existing vault has written: a label can be superseded, never
|
|
* edited.
|
|
*/
|
|
|
|
import { pbkdf2, hkdf, toBase64, KEY_BYTES, MIN_SALT_BYTES } from "./primitives.js";
|
|
import {
|
|
DEFAULT_NAMESPACE,
|
|
NAMESPACE_PATTERN,
|
|
REGISTERED_NAMESPACES,
|
|
type KdfName,
|
|
type KdfParams,
|
|
type Namespace,
|
|
} from "./types.js";
|
|
|
|
export const KDF = {
|
|
PBKDF2_SHA256: "pbkdf2-sha256",
|
|
/**
|
|
* Reserved. Argon2id needs WASM in the browser, which means adding
|
|
* 'wasm-unsafe-eval' to an extension CSP — a real cost paid by every user to
|
|
* benefit the KDF. Parameters are carried per vault specifically so this can
|
|
* be adopted later without invalidating a single existing vault.
|
|
*/
|
|
ARGON2ID: "argon2id",
|
|
} as const;
|
|
|
|
/** OWASP's current floor for PBKDF2-HMAC-SHA256. */
|
|
export const DEFAULT_KDF_PARAMS: Readonly<KdfParams> = Object.freeze({
|
|
kdf: KDF.PBKDF2_SHA256 as KdfName,
|
|
iterations: 600_000,
|
|
});
|
|
|
|
/**
|
|
* The lowest iteration count a client will accept.
|
|
*
|
|
* Parameters arrive from a server, which makes them attacker-controlled the
|
|
* moment the server is compromised: serving `iterations: 1` would turn every
|
|
* captured auth hash into an offline guessing exercise with no work factor.
|
|
* Refuse to derive at all below this rather than silently doing weak work.
|
|
*/
|
|
export const MIN_PBKDF2_ITERATIONS = 100_000;
|
|
|
|
/** Domain-separation labels. Append-only — supersede, never edit. */
|
|
export function wrapLabel(namespace: Namespace): string {
|
|
return `${namespace}:vault:wrap:v1`;
|
|
}
|
|
|
|
export function authLabel(namespace: Namespace): string {
|
|
return `${namespace}:vault:auth:v1`;
|
|
}
|
|
|
|
export function recoveryLabel(namespace: Namespace): string {
|
|
return `${namespace}:vault:recovery:v1`;
|
|
}
|
|
|
|
export function itemLabel(namespace: Namespace, version: number, id: string): string {
|
|
return `${namespace}:vault:item:${version}:${id}`;
|
|
}
|
|
|
|
export function databaseLabel(namespace: Namespace): string {
|
|
return `${namespace}:database:v1`;
|
|
}
|
|
|
|
/**
|
|
* Validate a namespace.
|
|
*
|
|
* Accepting an arbitrary prefix is accepting an arbitrary derivation, so an
|
|
* unregistered one needs an explicit opt-in rather than a shrug.
|
|
*/
|
|
export function assertUsableNamespace(namespace: string, allowUnregistered = false): Namespace {
|
|
if (!NAMESPACE_PATTERN.test(namespace)) {
|
|
throw new Error(`Invalid namespace: ${JSON.stringify(namespace)}`);
|
|
}
|
|
if (!allowUnregistered && !REGISTERED_NAMESPACES.includes(namespace)) {
|
|
throw new Error(
|
|
`Unregistered namespace "${namespace}" — registered namespaces are ${REGISTERED_NAMESPACES.join(", ")}. ` +
|
|
"Pass allowUnregistered to open it anyway.",
|
|
);
|
|
}
|
|
return namespace;
|
|
}
|
|
|
|
/** Validate KDF parameters received from a server, or read from a file. */
|
|
export function assertUsableKdfParams(params: Partial<KdfParams> | undefined): KdfParams {
|
|
const kdf = params?.kdf;
|
|
if (kdf !== KDF.PBKDF2_SHA256) {
|
|
throw new Error(
|
|
kdf === KDF.ARGON2ID
|
|
? "argon2id is registered but not implemented; refusing to fall back to a weaker KDF"
|
|
: `Unsupported KDF: ${kdf ?? "missing"}`,
|
|
);
|
|
}
|
|
const iterations = params?.iterations;
|
|
if (!Number.isInteger(iterations) || (iterations as number) < MIN_PBKDF2_ITERATIONS) {
|
|
throw new Error(
|
|
`Refusing to derive a key with ${iterations} iterations — the minimum is ${MIN_PBKDF2_ITERATIONS}`,
|
|
);
|
|
}
|
|
return { kdf, iterations: iterations as number };
|
|
}
|
|
|
|
/**
|
|
* Stretch the master password into the master key.
|
|
*
|
|
* The master key never encrypts anything directly; it exists only to be split
|
|
* by the derivations below.
|
|
*/
|
|
export async function deriveMasterKey(
|
|
password: string,
|
|
salt: Uint8Array,
|
|
params: KdfParams = DEFAULT_KDF_PARAMS,
|
|
): Promise<Uint8Array> {
|
|
if (typeof password !== "string" || password.length === 0) {
|
|
throw new Error("A master password is required");
|
|
}
|
|
if (!(salt instanceof Uint8Array) || salt.length < MIN_SALT_BYTES) {
|
|
throw new Error(`KDF salt must be at least ${MIN_SALT_BYTES} bytes`);
|
|
}
|
|
const { iterations } = assertUsableKdfParams(params);
|
|
return pbkdf2(password, salt, iterations, KEY_BYTES);
|
|
}
|
|
|
|
/** The key that wraps the user key. Never leaves the device. */
|
|
export function deriveWrapKey(masterKey: Uint8Array, namespace: Namespace = DEFAULT_NAMESPACE): Promise<Uint8Array> {
|
|
return hkdf(masterKey, wrapLabel(namespace), KEY_BYTES);
|
|
}
|
|
|
|
/**
|
|
* The only password-derived value that may leave the device. Because it comes
|
|
* out of a different HKDF label than the wrapping key, holding it does not help
|
|
* an attacker decrypt anything. A server storing it hashes it again.
|
|
*/
|
|
export async function deriveAuthHash(
|
|
masterKey: Uint8Array,
|
|
namespace: Namespace = DEFAULT_NAMESPACE,
|
|
): Promise<string> {
|
|
return toBase64(await hkdf(masterKey, authLabel(namespace), KEY_BYTES));
|
|
}
|
|
|
|
/** The key that wraps the recovery copy of the user key. */
|
|
export function deriveRecoveryWrapKey(
|
|
recoveryKey: Uint8Array,
|
|
namespace: Namespace = DEFAULT_NAMESPACE,
|
|
): Promise<Uint8Array> {
|
|
return hkdf(recoveryKey, recoveryLabel(namespace), KEY_BYTES);
|
|
}
|
|
|
|
/** The key an export is encrypted under — derived from the export passphrase, not the vault. */
|
|
export async function deriveExportKey(
|
|
passphrase: string,
|
|
salt: Uint8Array,
|
|
params: KdfParams = DEFAULT_KDF_PARAMS,
|
|
namespace: Namespace = DEFAULT_NAMESPACE,
|
|
): Promise<Uint8Array> {
|
|
const master = await deriveMasterKey(passphrase, salt, params);
|
|
return hkdf(master, databaseLabel(namespace), KEY_BYTES);
|
|
}
|
|
|
|
/** Derive both halves at once — the common path on unlock. */
|
|
export async function deriveAll(
|
|
password: string,
|
|
salt: Uint8Array,
|
|
params: KdfParams = DEFAULT_KDF_PARAMS,
|
|
namespace: Namespace = DEFAULT_NAMESPACE,
|
|
): Promise<{ masterKey: Uint8Array; wrapKey: Uint8Array; authHash: string }> {
|
|
const masterKey = await deriveMasterKey(password, salt, params);
|
|
const [wrapKey, authHash] = await Promise.all([
|
|
deriveWrapKey(masterKey, namespace),
|
|
deriveAuthHash(masterKey, namespace),
|
|
]);
|
|
return { masterKey, wrapKey, authHash };
|
|
}
|