Documentation
Client SDK
Download from a link

Download from a link

The secrecyClient.cloud.downloadDataFromLink method downloads the data behind a link and decrypts it on the device. It takes the dataLinkSlug — the public part of the URL — and a crypto object holding the encrypted data key and the password, both returned by uploadData in its sharing property when the link was created. It resolves with the decrypted bytes as a Uint8Array.

The crypto object is what makes the data readable. Without it the download returns an encrypted payload that cannot be opened.

share.ts
const downloadFromLink = async ({
  dataLinkSlug,
  key,
  password,
}: {
  dataLinkSlug: string;
  key: string;
  password: string;
}): Promise<Uint8Array | null> => {
  // First we need to check if the secrecyClient is available
  if (!secrecyClient) {
    return null;
  }
 
  try {
    const bytes = await secrecyClient.cloud.downloadDataFromLink({
      dataLinkSlug,
      // key is the encryptedDataKey returned by uploadData
      crypto: { key, password },
    });
 
    return bytes;
  } catch (error) {
    console.error(error);
    return null;
  }
};

A wrong or missing password makes the method throw Unable to decrypt the data! The password is not valid! or Unable to read encrypted data without password!. When the downloaded bytes do not match the expected checksum, it throws Content does not match.

Progress and cancellation

Large files are downloaded then decrypted, and each phase reports its own progress. Pass downloadProgress and decryptProgress callbacks to follow them, and a signal to abort the operation.

share.ts
const bytes = await secrecyClient.cloud.downloadDataFromLink({
  dataLinkSlug,
  crypto: { key, password },
  downloadProgress: (progress) => console.log('download', progress),
  decryptProgress: (progress) => console.log('decrypt', progress),
  // abort the download from an AbortController
  signal: controller.signal,
});

Inspect a link before downloading

The fetchDataLinkMetadata function reads the public description of a link without downloading its content, which is the right way to display the file name, size or type before starting a heavy transfer. It takes the slug alone and requires no client, so it also works for recipients without an account.

share.ts
import { fetchDataLinkMetadata } from '@secrecy/lib';
 
const getLinkMetadata = async (dataLinkSlug: string) => {
  try {
    // No client and no password needed, the metadata is public
    const metadata = await fetchDataLinkMetadata(dataLinkSlug);
 
    // { name, md5, md5Encrypted, size, mime, isEncrypted, ... }
    return metadata;
  } catch (error) {
    console.error(error);
    return null;
  }
};

The returned size is a bigint, and isEncrypted tells whether a password will be required. When the slug does not exist or the response cannot be parsed, the function throws Unable to parse data link json!.