logicsrc/packages/opencreds/src/index.ts
Anthony Ettinger d38db62e8b
Some checks are pending
CI / build (push) Waiting to run
Deploy to dev2 / deploy (push) Waiting to run
test / test (push) Waiting to run
vault: autosync the personal vault to the logicsrc account (#226)
`logicsrc vault` (OpenCreds) lived only in ~/.config/logicsrc/opencreds.
Lose the machine and the vault went with it, and a second machine had
no way to get it. It now syncs to the logged-in account.

Server (apps/pwa, /api/opencreds, session or lsk_ bearer):
- opencreds_vaults: one per user. meta (key material already wrapped
  under the master password) + an encrypted folder list, each with a
  revision.
- opencreds_items: one row per item, as the spec asks; envelope NULL is
  a tombstone so purges propagate; seq for incremental pulls.
- Every write names its base revision; a stale one gets 409 with the
  current row. Writes are conditional and read back (each envelope's
  random IV identifies our write), so this needs nothing dialect-specific
  from SQLite or Postgres.
- Stores ciphertext only. The server learns item count and type codes,
  as OpenCreds security.md already accepts.

Client (@logicsrc/opencreds sync.ts, key-free except where noted):
- Pull before every vault command, push after. Offline, the command
  still works and the change goes up next time.
- Conflicts never lose data: the account's edit keeps the id and this
  machine's becomes "<name> (conflict copy)" (needs the unlocked key, so
  it waits otherwise). An edit beats a purge. Byte-identical envelopes
  are adopted, not split, so a lost sync.json is harmless.
- Two different vaults (meta.createdAt differs) are never merged:
  refused, with `vault sync --use-remote` (backs this machine's up to
  .bak-NNN) or `--use-local`.
- Remote item ids must be plain ids; anything else is ignored and never
  becomes a path.
- Folder names are AES-GCM encrypted under the user key before upload.

CLI (0.6.0): `logicsrc vault sync [--status|--use-remote|--use-local]`.
Only the default vault syncs, and only when logged in; a --home or
OPENCREDS_HOME vault stays local unless LOGICSRC_VAULT_SYNC=on;
LOGICSRC_VAULT_SYNC=off disables it. The standalone `opencreds` binary
gets no remote and never syncs. `init` on a machine that just downloaded
the account's vault says to unlock it instead of suggesting --force.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-04 03:45:25 -07:00

250 lines
4.9 KiB
TypeScript

/**
* @logicsrc/opencreds — the OpenCreds reference implementation.
*
* OpenCreds is a LogicSRC OpenSpec for credential records and portable vaults:
* what a credential item is, how a vault is encrypted, and what a vault looks
* like as a file. It exists because leaving a password manager currently means
* writing every secret you own to disk in the clear, and losing whatever the
* spreadsheet had no column for.
*
* Nothing in this package sends anything anywhere. There is no account, no
* server, and no network call — which is what makes "the server cannot read the
* vault" a property of the code rather than a promise in the marketing copy.
*
* Typical use:
*
* const { meta, userKey, recoveryKey } = await createVault(password);
* // show recoveryKey to the person, exactly once
*
* const item = createItem("login", { name: "GitHub", login: { username, password } });
* const envelope = await encryptItem(userKey, item); // ciphertext only
*
* const db = await exportDatabase({ folders, items }, { passphrase });
* // ... hand db to another product ...
* const payload = await openDatabase(db, { passphrase }); // manifest verified
*
* Specification: https://logicsrc.com/opencreds
*/
export {
IV_BYTES,
KEY_BYTES,
MIN_SALT_BYTES,
randomBytes,
utf8Encode,
utf8Decode,
toBase64,
fromBase64,
toHex,
fromHex,
timingSafeEqual,
uuid,
pbkdf2,
hkdf,
sha256,
aesGcmEncrypt,
aesGcmDecrypt,
} from "./primitives.js";
export {
KDF,
DEFAULT_KDF_PARAMS,
MIN_PBKDF2_ITERATIONS,
wrapLabel,
authLabel,
recoveryLabel,
itemLabel,
databaseLabel,
assertUsableNamespace,
assertUsableKdfParams,
deriveMasterKey,
deriveWrapKey,
deriveAuthHash,
deriveRecoveryWrapKey,
deriveExportKey,
deriveAll,
} from "./kdf.js";
export {
SALT_BYTES,
RECOVERY_KEY_BYTES,
formatRecoveryKey,
parseRecoveryKey,
createVault,
createTeamVault,
assertProfile,
unlockVault,
unlockWithRecoveryKey,
rewrapUserKey,
resetRecoveryKey,
type CreatedVault,
} from "./vault-key.js";
export {
isItemType,
createItem,
assertGroupsMatchType,
recordPasswordChange,
updateItem,
encryptItem,
decryptItem,
decryptItems,
maskItem,
readField,
SECRET_FIELDS,
type DecryptResult,
} from "./items.js";
export {
DATABASE_MEDIA_TYPE,
DATABASE_EXTENSION,
buildManifest,
verifyManifest,
exportDatabase,
exportPlaintextDatabase,
isEncryptedDatabase,
readHeader,
openDatabase,
mergePayload,
parseDatabase,
type ExportOptions,
type OpenOptions,
type MergeResult,
} from "./database.js";
export {
IMPORT_SOURCES,
DETECT_ORDER,
CSV_LOSSY_FIELDS,
parseCsv,
rowsToObjects,
detectSource,
parseCsvImport,
toBitwardenCsv,
type ImportSource,
} from "./importers.js";
export { parseBitwardenJson, looksLikeBitwardenJson } from "./bitwarden.js";
export {
parseOnePasswordExport,
looksLikeOnePasswordExport,
stableUuid,
} from "./onepassword.js";
export { looksLikeZip, readZipEntry, zipEntryNames } from "./zip.js";
export {
ALL_SOURCES,
SOURCE_NAMES,
sourceHelp,
isKnownSource,
detectContainer,
routeImport,
type Container,
type SourceInfo,
type RouteResult,
} from "./import-router.js";
export {
validateItem,
validateDatabase,
validateDocument,
hasErrors,
formatDiagnostics,
looksLikeDatabase,
looksLikeItem,
type Diagnostic,
} from "./validate.js";
export { createVaultStore, opencredsHome, type VaultStore } from "./store.js";
export {
DivergedVaultError,
SyncError,
describeSync,
pullVault,
pushVault,
readSyncState,
syncVault,
type Put,
type RemoteItem,
type RemoteVault,
type SyncRemote,
type SyncReport,
type SyncState,
} from "./sync.js";
export { auditEvent, fingerprint, type AuditInput } from "./audit.js";
export {
runConformance,
emitFixtures,
fixturePayload,
formatReport,
type ConformanceLevel,
type ConformanceReport,
type ConformanceResult,
type ConformanceStatus,
} from "./conformance.js";
export {
OPENCREDS_VERSION,
ITEM_TYPE,
ITEM_TYPE_NAME,
ITEM_TYPE_NAMES,
ITEM_SCHEMA_VERSION,
MAX_HISTORY_ENTRIES,
DEFAULT_NAMESPACE,
REGISTERED_NAMESPACES,
NAMESPACE_PATTERN,
} from "./types.js";
export type {
AccountGroup,
AttachmentRef,
AuditAction,
AuditEvent,
CardGroup,
CustomField,
Database,
DatabaseHeader,
DatabaseManifest,
DatabasePayload,
EncryptedDatabase,
Envelope,
FieldKind,
Folder,
HistoryEntry,
IdentityGroup,
ImportOutcome,
Item,
ItemTypeName,
ItemUri,
KdfName,
KdfParams,
KeyGroup,
KeyKind,
LoginGroup,
MergeStrategy,
Namespace,
ParsedImport,
PlaintextDatabase,
Profile,
SkippedRow,
UriMatch,
VaultMeta,
} from "./types.js";
export {
SECRET_CATEGORIES,
SECRET_CATEGORY_IDS,
OTHER_CATEGORY,
categorizeSecret,
categorizeItem,
parseCategories,
csvLine,
toSimpleCsv,
SIMPLE_CSV_COLUMNS,
type SecretCategory,
} from "./categories.js";