Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
/*
* The Rust core bound to its WebAssembly build, for hosts with a WebAssembly runtime.
*/
/* eslint-disable jsdoc/require-jsdoc */
import initWasm, * as core from '#wasm/aliasvault_core.js';
import { yieldToPaint } from '../utilities/YieldToPaint';
import type { IRustCore, IVaultSyncSession } from './RustCoreBinding';
import type { AccountKeyHierarchy, AvexHeader, FaviconTarget, FilterCredentialsInput, FilterCredentialsOutput, KeyChainOpenResult, MobileLoginApproval, ParsedEmail, PinFailure, ReencryptedAccountKey, RsaKeyPair, SrpEphemeral, SrpSession } from './RustCoreTypes';
/**
* Where the host gets the `.wasm` binary from: bytes, or a fetch response for streaming instantiation.
*/
export type WasmLoader = () => Promise<BufferSource | Response>;
/**
* Bind the Rust core to its WebAssembly build.
* @param loadWasm - provides the WebAssembly binary
*/
export function createWasmRustCore(loadWasm: WasmLoader): IRustCore {
let initPromise: Promise<void> | null = null;
/**
* Instantiate the module.
*/
const init = (): Promise<void> => {
if (!initPromise) {
initPromise = (async (): Promise<void> => {
await initWasm({ module_or_path: await loadWasm() });
})().catch((error: unknown) => {
initPromise = null;
throw error;
});
}
return initPromise;
};
/**
* Run a Rust core function after initialization.
* @param call - the synchronous core call
*/
const ready = async <T>(call: () => T): Promise<T> => {
await init();
return call();
};
return {
init,
extractDomain: (url): Promise<string> => ready(() => core.extractDomain(url)),
extractRootDomain: (domain): Promise<string> => ready(() => core.extractRootDomain(domain)),
isRpIdAllowedForHost: (rpId, host): Promise<boolean> => ready(() => core.isRpIdAllowedForHost(rpId, host)),
isRelatedOriginAllowed: (callerOrigin, origins): Promise<boolean> => ready(() => core.isRelatedOriginAllowed(callerOrigin, origins)),
selectFaviconTarget: (urls): Promise<FaviconTarget | null> => ready(() => (core.selectFaviconTarget(urls) ?? null) as FaviconTarget | null),
filterCredentials: (input: FilterCredentialsInput): Promise<FilterCredentialsOutput> => ready(() => core.filterCredentials(input) as FilterCredentialsOutput),
generateTotpCode: (secret, unixSeconds, algorithm, digits, period): Promise<string | null> => ready(() => core.generateTotpCode(secret, unixSeconds, algorithm, digits, period) ?? null),
generatePassword: (settingsJson): Promise<string> => ready(() => core.generatePassword(settingsJson)),
getDicewareLanguages: (): Promise<string[]> => ready(() => core.getDicewareLanguages()),
generateIdentity: (requestJson): Promise<string> => ready(() => core.generateIdentity(requestJson)),
generateIdentityUsername: (inputJson): Promise<string> => ready(() => core.generateIdentityUsername(inputJson)),
generateIdentityEmailPrefix: (inputJson): Promise<string> => ready(() => core.generateIdentityEmailPrefix(inputJson)),
generateRandomEmailPrefix: (length): Promise<string> => ready(() => core.generateRandomEmailPrefix(length)),
getIdentityLanguages: (): Promise<string[]> => ready(() => core.getIdentityLanguages()),
getIdentityAgeRanges: (): Promise<string[]> => ready(() => core.getIdentityAgeRanges()),
parseEmailSource: (source): Promise<ParsedEmail> => ready(() => core.parseEmailSource(source) as ParsedEmail),
decodeEmailSource: (source): Promise<Uint8Array> => ready(() => core.decodeEmailSource(source)),
extractEmailAttachment: (source, index, detachedBody): Promise<Uint8Array> => ready(() => core.extractEmailAttachment(source, index, detachedBody)),
symmetricDecrypt: (base64Ciphertext, keyBase64): Promise<string> => ready(() => core.symmetricDecrypt(base64Ciphertext, keyBase64)),
symmetricDecryptBytes: (encrypted, keyBase64): Promise<Uint8Array> => ready(() => core.symmetricDecryptBytes(encrypted, keyBase64)),
symmetricEncryptBytes: (plaintext, keyBase64): Promise<Uint8Array> => ready(() => core.symmetricEncryptBytes(plaintext, keyBase64)),
generateRsaKeyPair: (): Promise<RsaKeyPair> => ready(() => core.generateRsaKeyPair() as RsaKeyPair),
rsaDecrypt: (base64Ciphertext, privateKeyJwk): Promise<Uint8Array> => ready(() => core.rsaDecrypt(base64Ciphertext, privateKeyJwk)),
decryptManifestInvitationName: (encryptedName, manifestId, privateKeyJwk): Promise<string> => ready(() => core.decryptManifestInvitationName(encryptedName, manifestId, privateKeyJwk)),
accountSigningKeyFingerprint: (encryptedSigningPrivateKey, accountKeyBase64): Promise<string> => ready(() => core.accountSigningKeyFingerprint(encryptedSigningPrivateKey, accountKeyBase64)),
mobileLoginPublicKeyHash: (publicKeyJwk): Promise<string> => ready(() => core.mobileLoginPublicKeyHash(publicKeyJwk)),
mobileLoginVerificationCode: (publicKeyJwk): Promise<string> => ready(() => core.mobileLoginVerificationCode(publicKeyJwk)),
mobileLoginOpenApproval: (privateKeyJwk, encryptedAccountKey, encryptedPayloadKey, encryptedPayload): Promise<MobileLoginApproval> =>
ready(() => core.mobileLoginOpenApproval(privateKeyJwk, encryptedAccountKey, encryptedPayloadKey, encryptedPayload) as MobileLoginApproval),
/*
* Argon2 (also behind pinEncrypt and pinDecrypt) blocks the thread it runs on for up to a few seconds on slow
* devices, so let the caller's loading indicator paint first before proceeding with the expensive operation.
*/
pinGenerateSalt: (): Promise<Uint8Array> => ready(() => core.pinGenerateSalt()),
pinExtensionSalt: (salt, extensionId): Promise<Uint8Array> => ready(() => core.pinExtensionSalt(salt, extensionId)),
pinEncrypt: async (pin, salt, secret): Promise<Uint8Array> => {
await yieldToPaint();
return ready(() => core.pinEncrypt(pin, salt, secret));
},
pinDecrypt: async (pin, salt, encrypted): Promise<Uint8Array> => {
await yieldToPaint();
return ready(() => core.pinDecrypt(pin, salt, encrypted));
},
pinIsLocked: (failedAttempts): Promise<boolean> => ready(() => core.pinIsLocked(failedAttempts)),
pinRegisterFailure: (failedAttempts): Promise<PinFailure> => ready(() => core.pinRegisterFailure(failedAttempts) as PinFailure),
avexEncrypt: async (avux, password, exportedAt, appVersion): Promise<Uint8Array> => {
await yieldToPaint();
return ready(() => core.avexEncrypt(avux, password, exportedAt, appVersion));
},
avexParseHeader: (avex): Promise<AvexHeader> => ready(() => core.avexParseHeader(avex) as AvexHeader),
avexDecrypt: async (avex, password): Promise<Uint8Array> => {
await yieldToPaint();
return ready(() => core.avexDecrypt(avex, password));
},
argon2DeriveKey: async (password, salt, encryptionSettings): Promise<Uint8Array> => {
await yieldToPaint();
return ready(() => core.argon2DeriveKey(password, salt, encryptionSettings));
},
deriveSrpPasswordHash: (unlockKeyBase64, encryptionType): Promise<string> => ready(() => core.deriveSrpPasswordHash(unlockKeyBase64, encryptionType)),
openKeyChainWithUnlockKey: (unlockKey, encryptedAccountKey, encryptedVek, encryptedAccountPrivateKey): Promise<KeyChainOpenResult> =>
ready(() => core.openKeyChainWithUnlockKey(unlockKey, encryptedAccountKey, encryptedVek, encryptedAccountPrivateKey ?? undefined) as KeyChainOpenResult),
openKeyChainWithAccountKey: (accountKey, encryptedVek, encryptedAccountPrivateKey): Promise<KeyChainOpenResult> =>
ready(() => core.openKeyChainWithAccountKey(accountKey, encryptedVek, encryptedAccountPrivateKey ?? undefined) as KeyChainOpenResult),
createAccountKeyHierarchy: (unlockKeyBase64): Promise<AccountKeyHierarchy> => ready(() => core.createAccountKeyHierarchy(unlockKeyBase64) as AccountKeyHierarchy),
reencryptAccountKey: (encryptedAccountKey, oldUnlockKeyBase64, newUnlockKeyBase64): Promise<ReencryptedAccountKey | null> =>
ready(() => core.reencryptAccountKey(encryptedAccountKey, oldUnlockKeyBase64, newUnlockKeyBase64) as ReencryptedAccountKey | null),
srpGenerateSalt: (): Promise<string> => ready(() => core.srpGenerateSalt()),
srpDerivePrivateKey: (salt, identity, passwordHash): Promise<string> => ready(() => core.srpDerivePrivateKey(salt, identity, passwordHash)),
srpDeriveVerifier: (privateKey): Promise<string> => ready(() => core.srpDeriveVerifier(privateKey)),
srpGenerateEphemeral: (): Promise<SrpEphemeral> => ready(() => core.srpGenerateEphemeral() as SrpEphemeral),
srpDeriveSession: (clientSecret, serverPublic, salt, identity, privateKey): Promise<SrpSession> =>
ready(() => core.srpDeriveSession(clientSecret, serverPublic, salt, identity, privateKey) as SrpSession),
srpVerifySession: (clientPublic, clientProof, sessionKey, serverProof): Promise<boolean> =>
ready(() => core.srpVerifySession(clientPublic, clientProof, sessionKey, serverProof)),
vaultCodecLogoIdFor: (manifestId, kind, source): Promise<string> => ready(() => core.vaultCodecLogoIdFor(manifestId, kind, source)),
vaultCodecLogoContentHash: (bytes): Promise<string> => ready(() => core.vaultCodecLogoContentHash(bytes)),
createVaultSyncSession: (requestJson): Promise<IVaultSyncSession> => ready((): IVaultSyncSession => {
const session = new core.VaultSyncSession(requestJson);
return {
nextCommand: async (): Promise<string> => session.nextCommand(),
commandBytes: async (): Promise<Uint8Array | null> => session.commandBytes() ?? null,
resume: async (responseJson: string, bytes: Uint8Array | null): Promise<void> => session.resume(responseJson, bytes),
free: (): void => session.free(),
};
}),
};
}