harbor0APIBeta

Beta. The harbor0 API is still in beta, so routes and responses may change before it is final. What beta means

Complete examples

Each example is a small command-line client that lists, downloads and uploads files. It works on any account: when the account is end-to-end encrypted it unlocks the keys with your passphrase or recovery key and handles names and contents on your computer.

Both have been checked against the test vectors below and against the harbor0 apps: files they upload open in the apps, and files the apps upload come down byte for byte.

Node.js

Needs Node.js 20 or later. Download harbor0-e2ee.mjs, harbor0.mjs and package.json into one folder, then:

npm install
export HARBOR0_TOKEN='h0_pat_...'
export HARBOR0_PASSPHRASE='your encryption passphrase'   # encrypted accounts only

node harbor0.mjs ls                     # the top of My Drive
node harbor0.mjs ls 9b7d…               # a folder
node harbor0.mjs get 83439bc4-…         # download and decrypt a file
node harbor0.mjs put ./report.pdf 9b7d… # encrypt and upload into a folder

To unlock with the recovery key instead, set HARBOR0_RECOVERY_KEY and leave out HARBOR0_PASSPHRASE.

harbor0-e2ee.mjs: the encryption library

harbor0-e2ee.mjs · Download

// harbor0 end-to-end encryption, format h0e1, for Node.js 20 or later.
//
// Everything here runs on your own computer. The server only ever sees the
// wrapped keys, encrypted names and encrypted file contents.
//
//   npm install hash-wasm      (for Argon2id; everything else is node:crypto)
//
// Format reference: https://api.harbor0.com docs, "End-to-end encryption".
import {
  createCipheriv,
  createDecipheriv,
  createHmac,
  hkdfSync,
  randomBytes,
} from 'node:crypto';
import { Transform } from 'node:stream';
import { argon2id } from 'hash-wasm';

export const NAME_PREFIX = 'h0e1.';
export const HEADER_SIZE = 80;
export const TAG_SIZE = 16;
export const CHUNK_SIZE = 4 * 1024 * 1024;
const MAGIC = Buffer.from('H0E1', 'latin1');
const MASTER_AAD = Buffer.from('harbor0/e2ee/v1/master');
const NAME_AAD = Buffer.from('harbor0/e2ee/v1/name');

// ---------------------------------------------------------------- helpers

export const fromB64url = (s) => Buffer.from(s, 'base64url');
export const toB64url = (b) => Buffer.from(b).toString('base64url');

/** HKDF-SHA256. An empty salt means RFC 5869's default (32 zero bytes). */
const hkdf = (secret, info, length = 32, salt = Buffer.alloc(0)) =>
  Buffer.from(hkdfSync('sha256', secret, salt, Buffer.from(info), length));

/** AES-256-GCM open. `sealed` is ciphertext followed by the 16-byte tag. */
function open(key, iv, sealed, aad) {
  if (sealed.length < TAG_SIZE) throw new Error('Ciphertext is too short.');
  const d = createDecipheriv('aes-256-gcm', key, iv);
  d.setAAD(aad);
  d.setAuthTag(sealed.subarray(sealed.length - TAG_SIZE));
  try {
    return Buffer.concat([d.update(sealed.subarray(0, sealed.length - TAG_SIZE)), d.final()]);
  } catch {
    throw new Error('Wrong key, or the data was changed.');
  }
}

/** AES-256-GCM seal: returns ciphertext followed by the 16-byte tag. */
function seal(key, iv, plain, aad) {
  const c = createCipheriv('aes-256-gcm', key, iv);
  c.setAAD(aad);
  return Buffer.concat([c.update(plain), c.final(), c.getAuthTag()]);
}

// ---------------------------------------------------------- the master key

/** Unwraps the account's 32-byte master key with the encryption passphrase. */
export async function unlockWithPassphrase(envelope, passphrase) {
  const kek = await argon2id({
    password: passphrase.normalize('NFKC'),
    salt: fromB64url(envelope.salt),
    iterations: envelope.iterations,
    memorySize: envelope.memoryKiB,
    parallelism: envelope.parallelism,
    hashLength: 32,
    outputType: 'binary',
  });
  return unwrapMaster(Buffer.from(kek), envelope);
}

/** Unwraps the master key with the recovery key (e.g. "S33W-DHE4-…"). */
export function unlockWithRecovery(envelope, recoveryKey) {
  const recovery = parseRecoveryKey(recoveryKey);
  if (!recovery) throw new Error('That is not a recovery key.');
  const kek = hkdf(recovery, 'harbor0/e2ee/v1/recovery', 32, fromB64url(envelope.salt));
  return unwrapMaster(kek, envelope);
}

function unwrapMaster(kek, envelope) {
  const master = open(kek, fromB64url(envelope.iv), fromB64url(envelope.ciphertext), MASTER_AAD);
  if (master.length !== 32) throw new Error('The stored key is damaged.');
  return master;
}

/** Recovery keys are 20 bytes written as 32 Crockford base32 characters. */
export function parseRecoveryKey(typed) {
  const ALPHABET = '0123456789ABCDEFGHJKMNPQRSTVWXYZ';
  const chars = typed
    .toUpperCase()
    .replace(/[\s-]/g, '')
    .replace(/O/g, '0')
    .replace(/[IL]/g, '1')
    .replace(/U/g, 'V');
  if (!/^[0-9A-HJKMNP-TV-Z]{32}$/.test(chars)) return null;
  const out = Buffer.alloc(20);
  let bits = 0;
  let value = 0;
  let at = 0;
  for (const c of chars) {
    value = ((value << 5) | ALPHABET.indexOf(c)) & 0xffff;
    bits += 5;
    if (bits >= 8) {
      out[at++] = (value >>> (bits - 8)) & 0xff;
      bits -= 8;
    }
  }
  return out;
}

/** The working keys, derived once from the master key. */
export function accountKeys(master) {
  const names = hkdf(master, 'harbor0/e2ee/v1/names', 64);
  return {
    fileWrap: hkdf(master, 'harbor0/e2ee/v1/file-keys'),
    nameEnc: names.subarray(0, 32),
    nameMac: names.subarray(32, 64),
  };
}

// ------------------------------------------------------------------- names

export const isEncryptedName = (name) => /^h0e1\.[A-Za-z0-9_-]+$/.test(name);

/** "h0e1.…" → the real name. */
export function decryptName(keys, token) {
  const bytes = fromB64url(token.slice(NAME_PREFIX.length));
  if (bytes.length < 12 + TAG_SIZE) throw new Error('The name is damaged.');
  return open(keys.nameEnc, bytes.subarray(0, 12), bytes.subarray(12), NAME_AAD).toString('utf8');
}

/**
 * The real name → "h0e1.…". The same name always gives the same token, so you
 * can look an item up by name (GET /v1/drive/folders/:id/lookup?name=…).
 */
export function encryptName(keys, name) {
  const plain = Buffer.from(name.normalize('NFC'), 'utf8');
  if (plain.length > 255) throw new Error('Names on encrypted accounts are at most 255 bytes.');
  const iv = createHmac('sha256', keys.nameMac).update(plain).digest().subarray(0, 12);
  return NAME_PREFIX + toB64url(Buffer.concat([iv, seal(keys.nameEnc, iv, plain, NAME_AAD)]));
}

// ------------------------------------------------------------------- files

/** Size of the original file, from the stored (encrypted) size. */
export function plainSize(stored, chunkSize = CHUNK_SIZE) {
  const body = stored - HEADER_SIZE;
  if (body < TAG_SIZE) return 0;
  return body - TAG_SIZE * Math.ceil(body / (chunkSize + TAG_SIZE));
}
/** Stored (encrypted) size of a file of `plain` bytes. */
export const encryptedSize = (plain, chunkSize = CHUNK_SIZE) =>
  HEADER_SIZE + plain + TAG_SIZE * Math.max(1, Math.ceil(plain / chunkSize));

/** Reads the 80-byte header and unwraps the file's own content key. */
export function openFileCipher(keys, header) {
  if (header.length < HEADER_SIZE || !header.subarray(0, 4).equals(MAGIC) || header[4] !== 1)
    throw new Error('Not an h0e1 encrypted file.');
  const chunkSize = header.readUInt32BE(8);
  if (chunkSize < 4096 || chunkSize > 64 * 1024 * 1024) throw new Error('Damaged header.');
  const bound = Buffer.from(header.subarray(0, 20)); // magic, version, chunk size, nonce prefix
  const contentKey = open(keys.fileWrap, header.subarray(20, 32), header.subarray(32, 80), bound);
  return fileCipher(contentKey, bound, chunkSize);
}

function fileCipher(contentKey, bound, chunkSize) {
  const prefix = bound.subarray(12, 20);
  const nonce = (index) => {
    const n = Buffer.alloc(12);
    prefix.copy(n, 0);
    n.writeUInt32BE(index, 8);
    return n;
  };
  const aad = (last) => Buffer.concat([bound, Buffer.from([last ? 1 : 0])]);
  return {
    chunkSize,
    decryptChunk: (index, sealed, last) => open(contentKey, nonce(index), sealed, aad(last)),
    encryptChunk: (index, plain, last) => seal(contentKey, nonce(index), plain, aad(last)),
  };
}

/**
 * A stream that turns the whole stored file (header included) into the
 * original bytes. `storedSize` is the download's `sizeBytes`.
 */
export function decryptStream(keys, storedSize) {
  let header = null;
  let cipher = null;
  let pending = Buffer.alloc(0);
  let index = 0;
  let total = 0;
  let count = 0;
  const take = (push, final) => {
    const span = cipher.chunkSize + TAG_SIZE;
    while (index < count) {
      const last = index === count - 1;
      const want = last ? total - index * cipher.chunkSize + TAG_SIZE : span;
      if (pending.length < want) break;
      push(cipher.decryptChunk(index, pending.subarray(0, want), last));
      pending = pending.subarray(want);
      index++;
    }
    if (final && index < count) throw new Error('The file ended early.');
  };
  return new Transform({
    transform(data, _encoding, done) {
      try {
        pending = Buffer.concat([pending, data]);
        if (!cipher) {
          if (pending.length < HEADER_SIZE) return done();
          header = pending.subarray(0, HEADER_SIZE);
          cipher = openFileCipher(keys, header);
          total = plainSize(storedSize, cipher.chunkSize);
          count = Math.max(1, Math.ceil(total / cipher.chunkSize));
          pending = pending.subarray(HEADER_SIZE);
        }
        take((b) => this.push(b), false);
        done();
      } catch (error) {
        done(error);
      }
    },
    flush(done) {
      try {
        if (!cipher) throw new Error('The file ended before its header.');
        take((b) => this.push(b), true);
        done();
      } catch (error) {
        done(error);
      }
    },
  });
}

/** Decrypts a whole stored file held in memory. */
export function decryptFile(keys, stored) {
  const cipher = openFileCipher(keys, stored.subarray(0, HEADER_SIZE));
  const total = plainSize(stored.length, cipher.chunkSize);
  const count = Math.max(1, Math.ceil(total / cipher.chunkSize));
  const parts = [];
  let at = HEADER_SIZE;
  for (let i = 0; i < count; i++) {
    const len = Math.min(cipher.chunkSize, total - i * cipher.chunkSize) + TAG_SIZE;
    parts.push(cipher.decryptChunk(i, stored.subarray(at, at + len), i === count - 1));
    at += len;
  }
  return Buffer.concat(parts);
}

/**
 * Encrypts a whole file held in memory, with a new random content key, ready
 * to upload to an encrypted account. Returns the stored bytes.
 */
export function encryptFile(keys, plain) {
  const header = Buffer.alloc(HEADER_SIZE);
  MAGIC.copy(header, 0);
  header[4] = 1;
  header.writeUInt32BE(CHUNK_SIZE, 8);
  randomBytes(8).copy(header, 12);
  const wrapIv = randomBytes(12);
  wrapIv.copy(header, 20);
  const contentKey = randomBytes(32);
  const bound = Buffer.from(header.subarray(0, 20));
  seal(keys.fileWrap, wrapIv, contentKey, bound).copy(header, 32);
  const cipher = fileCipher(contentKey, bound, CHUNK_SIZE);
  const count = Math.max(1, Math.ceil(plain.length / CHUNK_SIZE));
  const chunks = [header];
  for (let i = 0; i < count; i++)
    chunks.push(
      cipher.encryptChunk(i, plain.subarray(i * CHUNK_SIZE, (i + 1) * CHUNK_SIZE), i === count - 1),
    );
  return Buffer.concat(chunks);
}

harbor0.mjs: the command-line client

harbor0.mjs · Download

#!/usr/bin/env node
// A small harbor0 command-line client: list, download and upload files, with
// end-to-end encryption handled on this computer when the account uses it.
//
//   export HARBOR0_TOKEN=h0_pat_...
//   export HARBOR0_PASSPHRASE='...'        # only for encrypted accounts
//   # or HARBOR0_RECOVERY_KEY=XXXX-XXXX-...
//
//   node harbor0.mjs ls [folderId]          # folderId defaults to root
//   node harbor0.mjs get <itemId> [outputPath]
//   node harbor0.mjs put <localFile> [folderId]
import { createHash, randomUUID } from 'node:crypto';
import { createWriteStream } from 'node:fs';
import { readFile } from 'node:fs/promises';
import { basename } from 'node:path';
import { Readable, Transform } from 'node:stream';
import { pipeline } from 'node:stream/promises';
import * as e2ee from './harbor0-e2ee.mjs';

const API = process.env.HARBOR0_API ?? 'https://api.harbor0.com';
const TOKEN = process.env.HARBOR0_TOKEN;
if (!TOKEN) throw new Error('Set HARBOR0_TOKEN to a personal access token (h0_pat_...).');

async function api(method, path, body) {
  for (let attempt = 0; ; attempt++) {
    const res = await fetch(API + path, {
      method,
      headers: {
        Authorization: `Bearer ${TOKEN}`,
        'User-Agent': 'harbor0-example/1.0',
        // This client encrypts and decrypts h0e1 itself, so encrypted accounts let it in.
        'X-Harbor-E2EE': 'h0e1',
        ...(body ? { 'Content-Type': 'application/json' } : {}),
      },
      body: body ? JSON.stringify(body) : undefined,
    });
    if (res.status === 429 && attempt < 5) {
      const wait = Number(res.headers.get('Retry-After') ?? 5);
      await new Promise((r) => setTimeout(r, wait * 1000));
      continue;
    }
    const json = await res.json();
    if (!res.ok) throw new Error(`${json.error.code}: ${json.error.message}`);
    return json;
  }
}

/** Unlocks the account's keys if it is encrypted; null if it isn't. */
async function unlock() {
  const { user } = await api('GET', '/v1/users/me');
  if (!user.e2ee) return null;
  const { e2ee: state } = await api('GET', '/v1/e2ee');
  let master;
  if (process.env.HARBOR0_PASSPHRASE)
    master = await e2ee.unlockWithPassphrase(state.passphrase, process.env.HARBOR0_PASSPHRASE);
  else if (process.env.HARBOR0_RECOVERY_KEY)
    master = e2ee.unlockWithRecovery(state.recovery, process.env.HARBOR0_RECOVERY_KEY);
  else throw new Error('This account is end-to-end encrypted: set HARBOR0_PASSPHRASE.');
  return {
    keys: e2ee.accountKeys(master),
    // While encryption is being turned off, new names and files are stored unencrypted.
    sealNew: !user.e2ee.decryptingSince,
  };
}

const showName = (vault, name) =>
  vault && e2ee.isEncryptedName(name) ? e2ee.decryptName(vault.keys, name) : name;

async function ls(folderId = 'root') {
  const vault = await unlock();
  let cursor = null;
  do {
    const q = new URLSearchParams({ limit: '500', ...(cursor ? { cursor } : {}) });
    const page = await api('GET', `/v1/drive/folders/${folderId}/children?${q}`);
    for (const item of page.items) {
      const size = item.encrypted ? e2ee.plainSize(item.sizeBytes) : item.sizeBytes;
      const kind = item.type === 'FOLDER' ? 'dir ' : String(size).padStart(12);
      console.log(`${item.id}  ${kind}  ${showName(vault, item.name)}`);
    }
    cursor = page.nextCursor;
  } while (cursor);
}

async function get(itemId, output) {
  const vault = await unlock();
  const { item } = await api('GET', `/v1/drive/items/${itemId}`);
  const download = await api('POST', '/v1/downloads', { driveItemId: itemId });
  const res = await fetch(download.downloadUrl); // a signed storage URL: no Authorization header
  if (!res.ok) throw new Error(`Download failed: HTTP ${res.status}`);
  const target = output ?? showName(vault, item.name);
  // The SHA-256 the server keeps is of the stored bytes, so check before decrypting.
  const hash = createHash('sha256');
  const check = new Transform({
    transform(chunk, _e, done) {
      hash.update(chunk);
      done(null, chunk);
    },
  });
  const steps = [Readable.fromWeb(res.body), check];
  if (download.encrypted) {
    if (!vault) throw new Error('This file is encrypted but the account is not unlocked.');
    steps.push(e2ee.decryptStream(vault.keys, download.sizeBytes));
  }
  await pipeline(...steps, createWriteStream(target));
  if (hash.digest('hex') !== download.contentHash)
    throw new Error('The download does not match the SHA-256 the server stored.');
  console.log(`Saved ${target}`);
}

async function put(localFile, folderId = null) {
  const vault = await unlock();
  const plain = await readFile(localFile);
  const encrypt = !!vault?.sealNew;
  // Note: this example holds the file in memory. Stream it for very large files.
  const stored = encrypt ? e2ee.encryptFile(vault.keys, plain) : plain;
  const name = encrypt ? e2ee.encryptName(vault.keys, basename(localFile)) : basename(localFile);
  const contentHash = createHash('sha256').update(stored).digest('hex');

  const { upload } = await api('POST', '/v1/uploads', {
    operationId: randomUUID(),
    parentId: folderId === 'root' ? null : folderId,
    name,
    sizeBytes: stored.length,
    ...(encrypt
      ? { encrypted: true, mimeType: 'application/octet-stream' }
      : { contentHash }),
  });
  const count = Math.max(1, Math.ceil(stored.length / upload.partSizeBytes));
  const parts = [];
  for (let first = 1; first <= count; first += 10) {
    const partNumbers = Array.from({ length: Math.min(10, count - first + 1) }, (_, i) => first + i);
    const signed = await api('POST', `/v1/uploads/${upload.id}/parts`, { partNumbers });
    for (const part of signed.parts) {
      const start = (part.partNumber - 1) * upload.partSizeBytes;
      const res = await fetch(part.uploadUrl, {
        method: 'PUT',
        body: stored.subarray(start, start + upload.partSizeBytes),
      });
      if (!res.ok) throw new Error(`Part ${part.partNumber} failed: HTTP ${res.status}`);
      parts.push({ partNumber: part.partNumber, etag: res.headers.get('ETag') });
    }
  }
  const { item } = await api('POST', `/v1/uploads/${upload.id}/complete`, { parts, contentHash });
  console.log(`Uploaded ${basename(localFile)} as ${item.id}`);
}

const [command, ...args] = process.argv.slice(2);
const commands = { ls, get, put };
if (!commands[command]) {
  console.error('Usage: node harbor0.mjs ls [folderId] | get <itemId> [out] | put <file> [folderId]');
  process.exit(2);
}
await commands[command](...args);

Python

Needs Python 3.11 or later. Download harbor0_e2ee.py and harbor0.py into one folder, then:

python3 -m pip install cryptography argon2-cffi
export HARBOR0_TOKEN='h0_pat_...'
export HARBOR0_PASSPHRASE='your encryption passphrase'   # encrypted accounts only

python3 harbor0.py ls
python3 harbor0.py get 83439bc4-…
python3 harbor0.py put ./report.pdf 9b7d…

harbor0_e2ee.py: the encryption library

harbor0_e2ee.py · Download

"""harbor0 end-to-end encryption, format h0e1, for Python 3.9+.

Everything here runs on your own computer. The server only ever sees the
wrapped keys, encrypted names and encrypted file contents.

    pip install cryptography argon2-cffi
"""
from __future__ import annotations

import base64
import hashlib
import hmac
import math
import os
import re
import struct
import unicodedata
from typing import BinaryIO, Iterator

from argon2.low_level import Type, hash_secret_raw
from cryptography.exceptions import InvalidTag
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
from cryptography.hazmat.primitives.kdf.hkdf import HKDF

NAME_PREFIX = "h0e1."
HEADER_SIZE = 80
TAG_SIZE = 16
CHUNK_SIZE = 4 * 1024 * 1024
MAGIC = b"H0E1"
MASTER_AAD = b"harbor0/e2ee/v1/master"
NAME_AAD = b"harbor0/e2ee/v1/name"


class E2eeError(Exception):
    pass


# ------------------------------------------------------------------ helpers

def from_b64url(s: str) -> bytes:
    return base64.urlsafe_b64decode(s + "=" * (-len(s) % 4))


def to_b64url(b: bytes) -> str:
    return base64.urlsafe_b64encode(b).rstrip(b"=").decode("ascii")


def hkdf(secret: bytes, info: str, length: int = 32, salt: bytes = b"") -> bytes:
    """HKDF-SHA256. An empty salt means RFC 5869's default (32 zero bytes)."""
    return HKDF(
        algorithm=hashes.SHA256(), length=length, salt=salt or None, info=info.encode()
    ).derive(secret)


def _open(key: bytes, iv: bytes, sealed: bytes, aad: bytes) -> bytes:
    """AES-256-GCM open; `sealed` is the ciphertext followed by the 16-byte tag."""
    try:
        return AESGCM(key).decrypt(iv, sealed, aad)
    except InvalidTag:
        raise E2eeError("Wrong key, or the data was changed.") from None


def _seal(key: bytes, iv: bytes, plain: bytes, aad: bytes) -> bytes:
    return AESGCM(key).encrypt(iv, plain, aad)


# ----------------------------------------------------------- the master key

def unlock_with_passphrase(envelope: dict, passphrase: str) -> bytes:
    """Unwraps the account's 32-byte master key with the encryption passphrase."""
    kek = hash_secret_raw(
        secret=unicodedata.normalize("NFKC", passphrase).encode("utf-8"),
        salt=from_b64url(envelope["salt"]),
        time_cost=envelope["iterations"],
        memory_cost=envelope["memoryKiB"],
        parallelism=envelope["parallelism"],
        hash_len=32,
        type=Type.ID,
    )
    return _unwrap_master(kek, envelope)


def unlock_with_recovery(envelope: dict, recovery_key: str) -> bytes:
    """Unwraps the master key with the recovery key (e.g. "S33W-DHE4-...")."""
    recovery = parse_recovery_key(recovery_key)
    if recovery is None:
        raise E2eeError("That is not a recovery key.")
    kek = hkdf(recovery, "harbor0/e2ee/v1/recovery", 32, from_b64url(envelope["salt"]))
    return _unwrap_master(kek, envelope)


def _unwrap_master(kek: bytes, envelope: dict) -> bytes:
    master = _open(kek, from_b64url(envelope["iv"]), from_b64url(envelope["ciphertext"]), MASTER_AAD)
    if len(master) != 32:
        raise E2eeError("The stored key is damaged.")
    return master


def parse_recovery_key(typed: str) -> bytes | None:
    """Recovery keys are 20 bytes written as 32 Crockford base32 characters."""
    alphabet = "0123456789ABCDEFGHJKMNPQRSTVWXYZ"
    chars = re.sub(r"[\s-]", "", typed.upper()).replace("O", "0").replace("I", "1")
    chars = chars.replace("L", "1").replace("U", "V")
    if not re.fullmatch(r"[0-9A-HJKMNP-TV-Z]{32}", chars):
        return None
    value = int("".join(f"{alphabet.index(c):05b}" for c in chars), 2)
    return value.to_bytes(20, "big")


class AccountKeys:
    """The working keys, derived once from the master key."""

    def __init__(self, master: bytes):
        names = hkdf(master, "harbor0/e2ee/v1/names", 64)
        self.file_wrap = hkdf(master, "harbor0/e2ee/v1/file-keys")
        self.name_enc = names[:32]
        self.name_mac = names[32:]


# -------------------------------------------------------------------- names

def is_encrypted_name(name: str) -> bool:
    return re.fullmatch(r"h0e1\.[A-Za-z0-9_-]+", name) is not None


def decrypt_name(keys: AccountKeys, token: str) -> str:
    """"h0e1.…" → the real name."""
    data = from_b64url(token[len(NAME_PREFIX):])
    if len(data) < 12 + TAG_SIZE:
        raise E2eeError("The name is damaged.")
    return _open(keys.name_enc, data[:12], data[12:], NAME_AAD).decode("utf-8")


def encrypt_name(keys: AccountKeys, name: str) -> str:
    """The real name → "h0e1.…". The same name always gives the same token."""
    plain = unicodedata.normalize("NFC", name).encode("utf-8")
    if len(plain) > 255:
        raise E2eeError("Names on encrypted accounts are at most 255 bytes.")
    iv = hmac.new(keys.name_mac, plain, hashlib.sha256).digest()[:12]
    return NAME_PREFIX + to_b64url(iv + _seal(keys.name_enc, iv, plain, NAME_AAD))


# -------------------------------------------------------------------- files

def plain_size(stored: int, chunk_size: int = CHUNK_SIZE) -> int:
    """Size of the original file, from the stored (encrypted) size."""
    body = stored - HEADER_SIZE
    if body < TAG_SIZE:
        return 0
    return body - TAG_SIZE * math.ceil(body / (chunk_size + TAG_SIZE))


def encrypted_size(plain: int, chunk_size: int = CHUNK_SIZE) -> int:
    """Stored (encrypted) size of a file of `plain` bytes."""
    return HEADER_SIZE + plain + TAG_SIZE * max(1, math.ceil(plain / chunk_size))


class FileCipher:
    """One file version's content key, read from or written into its 80-byte header."""

    def __init__(self, content_key: bytes, bound: bytes):
        self.key = content_key
        self.bound = bound  # header[0:20]: magic, version, chunk size, nonce prefix
        self.chunk_size = struct.unpack(">I", bound[8:12])[0]

    @classmethod
    def open(cls, keys: AccountKeys, header: bytes) -> "FileCipher":
        if len(header) < HEADER_SIZE or header[:4] != MAGIC or header[4] != 1:
            raise E2eeError("Not an h0e1 encrypted file.")
        chunk = struct.unpack(">I", header[8:12])[0]
        if not 4096 <= chunk <= 64 * 1024 * 1024:
            raise E2eeError("Damaged header.")
        bound = bytes(header[:20])
        return cls(_open(keys.file_wrap, header[20:32], header[32:80], bound), bound)

    @classmethod
    def create(cls, keys: AccountKeys) -> tuple["FileCipher", bytes]:
        """A new random content key; returns the cipher and the 80-byte header to store first."""
        bound = MAGIC + bytes([1, 0, 0, 0]) + struct.pack(">I", CHUNK_SIZE) + os.urandom(8)
        content_key, wrap_iv = os.urandom(32), os.urandom(12)
        header = bound + wrap_iv + _seal(keys.file_wrap, wrap_iv, content_key, bound)
        return cls(content_key, bound), header

    def _nonce(self, index: int) -> bytes:
        return self.bound[12:20] + struct.pack(">I", index)

    def _aad(self, last: bool) -> bytes:
        return self.bound + (b"\x01" if last else b"\x00")

    def decrypt_chunk(self, index: int, sealed: bytes, last: bool) -> bytes:
        return _open(self.key, self._nonce(index), sealed, self._aad(last))

    def encrypt_chunk(self, index: int, plain: bytes, last: bool) -> bytes:
        return _seal(self.key, self._nonce(index), plain, self._aad(last))


def decrypt_stream(keys: AccountKeys, stored: BinaryIO, stored_size: int) -> Iterator[bytes]:
    """Reads a whole stored file (header first) and yields the original bytes, chunk by chunk."""
    cipher = FileCipher.open(keys, _read_exactly(stored, HEADER_SIZE))
    total = plain_size(stored_size, cipher.chunk_size)
    count = max(1, math.ceil(total / cipher.chunk_size))
    for i in range(count):
        length = min(cipher.chunk_size, total - i * cipher.chunk_size) + TAG_SIZE
        yield cipher.decrypt_chunk(i, _read_exactly(stored, length), i == count - 1)


def decrypt_file(keys: AccountKeys, stored: bytes) -> bytes:
    """Decrypts a whole stored file held in memory."""
    import io

    return b"".join(decrypt_stream(keys, io.BytesIO(stored), len(stored)))


def encrypt_stream(keys: AccountKeys, plain: BinaryIO, size: int) -> Iterator[bytes]:
    """Yields the stored bytes for a file of `size` bytes: the header, then each sealed chunk."""
    cipher, header = FileCipher.create(keys)
    yield header
    count = max(1, math.ceil(size / CHUNK_SIZE))
    for i in range(count):
        chunk = _read_exactly(plain, min(CHUNK_SIZE, size - i * CHUNK_SIZE))
        yield cipher.encrypt_chunk(i, chunk, i == count - 1)


def _read_exactly(f: BinaryIO, n: int) -> bytes:
    out = bytearray()
    while len(out) < n:
        data = f.read(n - len(out))
        if not data:
            raise E2eeError("The file ended early.")
        out += data
    return bytes(out)

harbor0.py: the command-line client

harbor0.py · Download

#!/usr/bin/env python3
"""A small harbor0 command-line client (Python 3.11+): list, download and upload files, with
end-to-end encryption handled on this computer when the account uses it.

    pip install cryptography argon2-cffi

    export HARBOR0_TOKEN=h0_pat_...
    export HARBOR0_PASSPHRASE='...'        # only for encrypted accounts
    # or HARBOR0_RECOVERY_KEY=XXXX-XXXX-...

    python3 harbor0.py ls [folderId]
    python3 harbor0.py get <itemId> [outputPath]
    python3 harbor0.py put <localFile> [folderId]
"""
from __future__ import annotations

import hashlib
import io
import json
import os
import sys
import time
import urllib.error
import urllib.parse
import urllib.request
import uuid

import harbor0_e2ee as e2ee

API = os.environ.get("HARBOR0_API", "https://api.harbor0.com")
TOKEN = os.environ.get("HARBOR0_TOKEN") or sys.exit("Set HARBOR0_TOKEN to a personal access token.")


def api(method: str, path: str, body: dict | None = None) -> dict:
    for attempt in range(6):
        request = urllib.request.Request(
            API + path,
            method=method,
            data=json.dumps(body).encode() if body is not None else None,
            headers={
                "Authorization": f"Bearer {TOKEN}",
                "User-Agent": "harbor0-example/1.0",
                # This client encrypts and decrypts h0e1 itself, so encrypted accounts let it in.
                "X-Harbor-E2EE": "h0e1",
                **({"Content-Type": "application/json"} if body is not None else {}),
            },
        )
        try:
            with urllib.request.urlopen(request) as response:
                return json.load(response)
        except urllib.error.HTTPError as error:
            if error.code == 429 and attempt < 5:
                time.sleep(int(error.headers.get("Retry-After", "5")))
                continue
            failure = json.load(error)["error"]
            raise SystemExit(f"{failure['code']}: {failure['message']}") from None
    raise AssertionError("unreachable")


def unlock() -> dict | None:
    """The account's keys if it is encrypted; None if it isn't."""
    user = api("GET", "/v1/users/me")["user"]
    if not user.get("e2ee"):
        return None
    state = api("GET", "/v1/e2ee")["e2ee"]
    if os.environ.get("HARBOR0_PASSPHRASE"):
        master = e2ee.unlock_with_passphrase(state["passphrase"], os.environ["HARBOR0_PASSPHRASE"])
    elif os.environ.get("HARBOR0_RECOVERY_KEY"):
        master = e2ee.unlock_with_recovery(state["recovery"], os.environ["HARBOR0_RECOVERY_KEY"])
    else:
        raise SystemExit("This account is end-to-end encrypted: set HARBOR0_PASSPHRASE.")
    # While encryption is being turned off, new names and files are stored unencrypted.
    return {"keys": e2ee.AccountKeys(master), "seal_new": not user["e2ee"].get("decryptingSince")}


def show_name(vault: dict | None, name: str) -> str:
    if vault and e2ee.is_encrypted_name(name):
        return e2ee.decrypt_name(vault["keys"], name)
    return name


def ls(folder_id: str = "root") -> None:
    vault = unlock()
    cursor = None
    while True:
        query = {"limit": "500", **({"cursor": cursor} if cursor else {})}
        page = api("GET", f"/v1/drive/folders/{folder_id}/children?{urllib.parse.urlencode(query)}")
        for item in page["items"]:
            size = e2ee.plain_size(item["sizeBytes"]) if item.get("encrypted") else item["sizeBytes"]
            kind = "dir " if item["type"] == "FOLDER" else str(size).rjust(12)
            print(f"{item['id']}  {kind}  {show_name(vault, item['name'])}")
        cursor = page["nextCursor"]
        if not cursor:
            break


class HashingReader(io.RawIOBase):
    """Passes reads through, keeping a SHA-256 of everything read."""

    def __init__(self, inner):
        self.inner, self.sha256 = inner, hashlib.sha256()

    def readable(self) -> bool:
        return True

    def read(self, n: int = -1) -> bytes:
        data = self.inner.read(n)
        self.sha256.update(data)
        return data


def get(item_id: str, output: str | None = None) -> None:
    vault = unlock()
    item = api("GET", f"/v1/drive/items/{item_id}")["item"]
    download = api("POST", "/v1/downloads", {"driveItemId": item_id})
    target = output or show_name(vault, item["name"])
    # A signed storage URL: no Authorization header.
    with urllib.request.urlopen(download["downloadUrl"]) as response, open(target, "wb") as out:
        stored = HashingReader(response)
        if download.get("encrypted"):
            if not vault:
                raise SystemExit("This file is encrypted but the account is not unlocked.")
            for plain in e2ee.decrypt_stream(vault["keys"], stored, download["sizeBytes"]):
                out.write(plain)
        else:
            while data := stored.read(1 << 20):
                out.write(data)
        # The SHA-256 the server keeps is of the stored bytes.
        if stored.sha256.hexdigest() != download["contentHash"]:
            raise SystemExit("The download does not match the SHA-256 the server stored.")
    print(f"Saved {target}")


def put(local_file: str, folder_id: str | None = None) -> None:
    vault = unlock()
    encrypt = bool(vault and vault["seal_new"])
    size = os.path.getsize(local_file)
    name = os.path.basename(local_file)
    if encrypt:
        name = e2ee.encrypt_name(vault["keys"], name)
    stored_size = e2ee.encrypted_size(size) if encrypt else size

    with open(local_file, "rb") as f:
        # A plain upload declares its SHA-256 up front; an encrypted one only at the end.
        plain_hash = hashlib.file_digest(f, "sha256").hexdigest() if not encrypt else None
        f.seek(0)
        request = {
            "operationId": str(uuid.uuid4()),
            "parentId": None if folder_id in (None, "root") else folder_id,
            "name": name,
            "sizeBytes": stored_size,
        }
        if encrypt:
            request.update(encrypted=True, mimeType="application/octet-stream")
        else:
            request.update(contentHash=plain_hash)
        upload = api("POST", "/v1/uploads", request)["upload"]

        pieces = e2ee.encrypt_stream(vault["keys"], f, size) if encrypt else iter(lambda: f.read(1 << 20), b"")
        part_size, sha256, parts = upload["partSizeBytes"], hashlib.sha256(), []
        buffer, number = bytearray(), 1

        def send(data: bytes, number: int) -> None:
            url = api("POST", f"/v1/uploads/{upload['id']}/parts", {"partNumbers": [number]})["parts"][0]["uploadUrl"]
            with urllib.request.urlopen(urllib.request.Request(url, data=data, method="PUT")) as r:
                parts.append({"partNumber": number, "etag": r.headers["ETag"]})

        for piece in pieces:
            sha256.update(piece)
            buffer += piece
            while len(buffer) >= part_size:
                send(bytes(buffer[:part_size]), number)
                del buffer[:part_size]
                number += 1
        if buffer or number == 1:
            send(bytes(buffer), number)

    item = api("POST", f"/v1/uploads/{upload['id']}/complete", {"parts": parts, "contentHash": sha256.hexdigest()})["item"]
    print(f"Uploaded {os.path.basename(local_file)} as {item['id']}")


if __name__ == "__main__":
    commands = {"ls": ls, "get": get, "put": put}
    if len(sys.argv) < 2 or sys.argv[1] not in commands:
        sys.exit(__doc__)
    commands[sys.argv[1]](*sys.argv[2:])

Test vectors

test-vectors.json holds known values made by the harbor0 apps. If your own implementation reproduces all of them, it will read and write files the apps understand.

FieldWhat to check
masterThe master key: the bytes 1, 2, … 32.
passphrase, passphraseTextUnwrapping the envelope with correct horse fi battery gives master. The fi ligature checks your NFKC normalization.
recoveryEnv, recoveryUnwrapping with the recovery key S33W-DHE4-RF1C-3G5Z-QTYV-SEXT-Q6WB-FDNN gives master.
namesEach real name encrypts to its token, and each token decrypts to the name (in NFC). résumé.pdf and Résumé.txt check Unicode normalization; 日本語.txt checks UTF-8.
small, emptyWhole stored files of 1,000 and 0 bytes. Each decrypts to the pattern below.
bigHeader, bigSize, bigSha256, bigLastChunkEncrypt the pattern of bigSize bytes (3 chunks) using this header: the stored bytes must hash to bigSha256, and the last chunk must equal bigLastChunk.

The plaintext of every vector file is the pattern where byte i is (i × 7) mod 251.

Both example libraries come with a script that checks every vector:

node verify-vectors.mjs ../test-vectors.json
python3 verify_vectors.py ../test-vectors.json
ok  master key: passphrase and recovery key
ok  names: decrypt and encrypt 5
ok  file "small": 1000 bytes
ok  file "empty": 0 bytes
ok  file "big": 8400953 bytes in 3 chunks, stored SHA-256 matches
ok  encryptFile round trip

Get the scripts here: verify-vectors.mjs, verify_vectors.py.

Other ways in

  • rclone. harbor0's build of rclone speaks this API and handles encryption with your passphrase, so you can copy, sync and mount encrypted folders without writing code. See the rclone guide.
  • The harbor0 apps. The web, desktop and mobile apps do all of this for you.