Skip to content

armgit / ente

Public Imported from GitHub
0

πŸ’š End-to-end encrypted cloud for everything.

2.2 KB
Raw Blame
import type { Remote } from "comlink";
import { inWorker } from "ente-base/env";
import { ComlinkWorker } from "ente-base/worker/comlink-worker";
import * as kdf from "./kdf";
import type { KDFWorker } from "./kdf.worker";
export { decryptBox } from "ente-prelogin-wasm";

const b64ToBinary = (b64: string) => atob(b64);

const fromB64 = (b64String: string): Promise<Uint8Array> => {
    const binary = b64ToBinary(b64String);
    const bytes = new Uint8Array(binary.length);
    for (let i = 0; i < binary.length; i++) {
        bytes[i] = binary.charCodeAt(i);
    }
    return Promise.resolve(bytes);
};

export const fromB64URLSafeNoPadding = async (b64String: string) => {
    let normalized = b64String.replace(/-/g, "+").replace(/_/g, "/");
    while (normalized.length % 4) normalized += "=";
    return fromB64(normalized);
};

const withKDFWorker = async <T>(
    callback: (worker: Remote<KDFWorker>) => Promise<T>,
): Promise<T> => {
    const worker = new ComlinkWorker<typeof KDFWorker>(
        "kdf",
        new Worker(new URL("kdf.worker.ts", import.meta.url)),
    );
    try {
        return await callback(await worker.remote);
    } finally {
        worker.terminate();
    }
};

export const deriveKey = (
    password: string,
    saltB64: string,
    opsLimit: number,
    memLimit: number,
): Promise<string> =>
    inWorker()
        ? kdf.deriveKey(password, saltB64, opsLimit, memLimit)
        : withKDFWorker((worker) =>
              worker.deriveKey(password, saltB64, opsLimit, memLimit),
          );

export const generateSignupKeys = (password: string, srpUserID: string) =>
    inWorker()
        ? kdf.generateSignupKeys(password, srpUserID)
        : withKDFWorker((worker) =>
              worker.generateSignupKeys(password, srpUserID),
          );

export const generateInteractiveKeyAttributes = (
    password: string,
    attributes: unknown,
    masterKey: string,
): Promise<unknown> =>
    inWorker()
        ? kdf.generateInteractiveKeyAttributes(password, attributes, masterKey)
        : withKDFWorker((worker) =>
              worker.generateInteractiveKeyAttributes(
                  password,
                  attributes,
                  masterKey,
              ),
          );