Leaving Syncture with your models

Syncture is written and run by one person, and the product is built so that fact never holds your models. Every workspace can be left with every version of every model as ordinary Revit files, on your own machines, with nothing from Syncture. This page says how, for each kind of workspace, and gives the script that rebuilds a workspace from a copy of a bucket you own.

What is on your machines already

Every machine that opened a model holds it as an ordinary Revit file. Syncture hydrates the central into C:\ProgramData\Syncture\Central, and Revit works on a local made from it.

A service that stops leaves every one of those files exactly where it is. Nothing Syncture runs can reach into a machine and take a file back.

Three kinds, three exits

What you do depends on the kind of workspace, chosen when it was made.

Stored by Syncture

From the console on any machine with Revit, Download folder writes every model under a folder to disk as ordinary files. Save a copy writes any older version the same way. Both work for as long as the service is reachable, which the Terms keep for sixty days after a termination, with nothing charged.

With encryption on

The same two doors, on a machine holding the workspace key. In a workspace created with encryption on, the key is the one thing the files need that Syncture never had. Keep a copy of it where no machine on your network can reach.

In your own storage

The bucket is complete in itself. Beside what each save stored, the add-in writes a short description of every version. A script then rebuilds every version of every model from a copy of the bucket, with nothing from Syncture. The credential and the bucket are yours. So is the key, in a workspace created with encryption on as well.

If Syncture stops

There is no second operator, and nothing is deposited with a third party. The Terms say so, and they say what holds instead.

If the service is discontinued, you hear ninety days ahead and nothing further is charged. The export doors stay open for as long as the service is reachable, and for sixty days after a termination.

An insolvency ends neither the contract nor the export. Your data is your property, and we waive any lien over it, or over an export, in advance.

A workspace in your own storage needs none of that. The bucket holds everything, the script below reads it, and both are yours before anything has happened.

The words that bind us are in the Terms, clauses 19 and 20.

What the bucket holds

Two kinds of object under the workspace's prefix, and nothing else.

p/<model>/<pack>/<part>

One part of one pack. A pack is what one save stored. It holds an index and the 4 KiB sectors no earlier version of the model had. A large pack is cut into parts of at most 32 MiB. In a workspace created with encryption on, every sector is encrypted under your key.

v/<model>/<seq>.json

One version, as the service renders it. The model's path and name, the sequence, time, author and note. The key id, for a workspace created with encryption on. For every file, its path, size and root. The pack the version stored, with the size and SHA-256 of each part.

A workspace's prefix is <prefix>w/<workspace>/, which the console's storage dialog shows and lets you copy. Nothing else is ever written under it.

Rebuilding from the bucket

Three steps, on any Windows machine, with nothing signed in.

  1. 1

    Copy the prefix to a disk

    With the tool you already use for the bucket. The commands below copy one workspace's prefix. Copying the whole bucket works the same way, and the script finds every workspace in it.

  2. 2

    Run the script

    Python, PowerShell or C#, whichever your office has. It writes every version of every model under a folder. Every part is checked against its SHA-256, every sector against its fingerprint and every file against its root. The exit status says whether anything was wrong.

  3. 3

    Open the files in Revit

    Each version is a folder of ordinary files: the model and its backup package as they were published. Revit sees a moved central and offers Detach from Central, which makes the copy a model of its own.

Copying the prefix

One line with the tool you already use. Put the bucket, the prefix and the workspace id from the console's storage dialog in place of the angle brackets.

aws s3 sync s3://<bucket>/<prefix>w/<workspace>/ .\bucket\w\<workspace>\

The copy needs list and get rights on the prefix, which the credential the machines use does not have to carry. Use the bucket's own console or an administrator's key for this one step.

The script, in three languages

One command line, three languages. Each reads the folder you copied, needs nothing beyond its runtime, and prints what it rebuilt and what it could not.

python syncture-exit.py --bucket .\bucket --out .\models

Python 3.8 or newer. A workspace created with encryption on also needs pip install cryptography.

syncture-exit.py
#!/usr/bin/env python3
"""
syncture-exit.py — turn a copy of a Syncture bucket back into Revit models.

Runs against a folder that holds a copy of the bucket your workspace was kept
in, and writes every version of every model as the files that were published.
Needs nothing from Syncture: no account, no service, no network.

    python syncture-exit.py --bucket .\\bucket --out .\\models
    python syncture-exit.py --bucket .\\bucket --out .\\models --key SYNK1-...
    python syncture-exit.py --bucket .\\bucket --out .\\models --latest
    python syncture-exit.py --bucket .\\bucket --verify

--bucket   A folder holding a copy of the bucket, or of the workspace's own
           prefix (the folder that contains `p/` and `v/`). Make the copy with
           the tool you already use: aws s3 sync, rclone sync, mc mirror.
--out      Where the models are written: <out>/<workspace>/<model path>/v0002/...
--key      The workspace key, for a workspace created with encryption on, or
--key-file a file holding it. Never needed for any other workspace.
--latest   Only the newest version of each model.
--model    One model, by its id or its name.
--verify   Check every part, every sector and every file, and write nothing.

Python 3.8 or newer. The standard library does everything except decrypt: a
workspace created with encryption on needs `pip install cryptography`.

The layout and the pack format are documented at
https://syncture.com/docs/exit and in md/EXIT.md of the Syncture repository.
Exit status is 0 when every version was rebuilt and checked, 1 otherwise.
"""

import argparse
import hashlib
import hmac
import json
import os
import struct
import sys
import zlib

FORMAT = "syncture-version/1"
ALPHABET = "0123456789ABCDEFGHJKMNPQRSTVWXYZ"

SECTOR = 4096          # a sector: the grid a file's content is named on
PRINT = 16             # bytes of one fingerprint
FRAME_SECTORS = 64     # sectors in one frame of a pack's payload
HEADER = 64            # bytes of a pack's header


class ExitError(Exception):
    """A reason one version could not be rebuilt. Named, and never silent."""


# ---------------------------------------------------------------------------
# The key: SYNK1- and seven groups of Crockford base32
# ---------------------------------------------------------------------------

def parse_key(text):
    """The 32 key bytes of a SYNK1 key string, or an ExitError naming what is wrong."""
    cleaned = "".join(ch for ch in text.replace("", "") if not ch.isspace()).upper()
    if not cleaned.startswith("SYNK1-"):
        raise ExitError("not a Syncture key: it does not start with SYNK1-")
    folded = cleaned[6:].replace("-", "").replace("I", "1").replace("L", "1").replace("O", "0")
    for ch in folded:
        if ch not in ALPHABET:
            raise ExitError("not a Syncture key: the character %r is not in its alphabet" % ch)
    if len(folded) != 56:
        raise ExitError("not a Syncture key: %d characters after the prefix, not 56" % len(folded))

    key = bytearray()
    accumulator = 0
    bits = 0
    for ch in folded[:52]:
        accumulator = ((accumulator << 5) | ALPHABET.index(ch)) & 0xFFFF
        bits += 5
        if bits >= 8:
            bits -= 8
            if len(key) < 32:
                key.append((accumulator >> bits) & 0xFF)
    if len(key) != 32 or accumulator & ((1 << bits) - 1):
        raise ExitError("not a Syncture key: its padding is not zero")

    digest = hashlib.sha256(b"syncture/key/v1" + bytes(key)).digest()
    check = "".join(format(b, "08b") for b in digest[:3])
    checksum = "".join(ALPHABET[int(check[i:i + 5], 2)] for i in range(0, 20, 5))
    if checksum != folded[52:]:
        raise ExitError("not a Syncture key: it does not check")
    return bytes(key)


def key_id_of(key):
    return hashlib.sha256(b"syncture/kid/v1" + key).digest()[:8].hex()


def subkeys(key, workspace_id):
    """RFC 5869 HKDF-SHA256, written out: one extract, one expand per use."""
    prk = hmac.new(b"syncture/workspace/v1", key, hashlib.sha256).digest()

    def expand(use):
        return hmac.new(prk, ("%s|%s" % (use, workspace_id)).encode("utf-8") + b"\x01", hashlib.sha256).digest()

    return {"enc": expand("enc"), "mac": expand("mac"), "siv": expand("siv"), "file": expand("file")}


def aes_cbc_decrypt(key, iv, data):
    try:
        from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
    except ImportError:
        raise ExitError("this workspace was created with encryption on, and decrypting needs "
                        "`pip install cryptography`")
    decryptor = Cipher(algorithms.AES(key), modes.CBC(iv)).decryptor()
    return decryptor.update(data) + decryptor.finalize()


# ---------------------------------------------------------------------------
# The envelope a sealed tail is carried in: SYNK, version 1
# ---------------------------------------------------------------------------

def open_envelope(keys, key_id, envelope):
    """The plaintext of a sealed tail: checked, in order, before one block is decrypted."""
    if len(envelope) < 77:
        raise ExitError("a sealed tail is too short")
    if envelope[:4] != b"SYNK" or envelope[4] != 1:
        raise ExitError("a tail is not in Syncture's sealed format")
    if (len(envelope) - 61) % 16:
        raise ExitError("a sealed tail has an impossible length")
    named = envelope[5:13].hex()
    if named != key_id:
        raise ExitError("a tail was sealed under key %s, and this key is %s" % (named, key_id))
    body, tag = envelope[:-32], envelope[-32:]
    if not hmac.compare_digest(hmac.new(keys["mac"], body, hashlib.sha256).digest(), tag):
        raise ExitError("a sealed tail failed its authentication check")

    padded = aes_cbc_decrypt(keys["enc"], envelope[13:29], envelope[29:-32])
    pad = padded[-1] if padded else 0
    if pad < 1 or pad > 16 or padded[-pad:] != bytes([pad]) * pad:
        raise ExitError("a sealed tail has bad padding")
    return padded[:-pad]


# ---------------------------------------------------------------------------
# How a workspace names and stores a sector
# ---------------------------------------------------------------------------

class Suite:
    """Plain: a fingerprint is a SHA-256 prefix and a sector is stored as it is.
    Sealed: both are keyed, and a sector is AES-256-CBC under its own fingerprint."""

    def __init__(self, keys, key_id):
        self.keys = keys
        self.key_id = key_id

    def fingerprint(self, data):
        if self.keys:
            return hmac.new(self.keys["siv"], b"\xff" * 8 + data, hashlib.sha256).digest()[:PRINT]
        return hashlib.sha256(data).digest()[:PRINT]

    def root(self, length, prints, tail):
        message = b"SYNR1" + struct.pack("<Q", length) + prints
        if tail:
            message += self.fingerprint(tail)
        if self.keys:
            return hmac.new(self.keys["file"], message, hashlib.sha256).hexdigest()
        return hashlib.sha256(message).hexdigest()

    def open_sector(self, stored, fingerprint):
        if not self.keys:
            return stored
        return aes_cbc_decrypt(self.keys["enc"], fingerprint, stored)

    def open_tail(self, stored):
        if not self.keys or not stored:
            return stored
        return open_envelope(self.keys, self.key_id, stored)


# ---------------------------------------------------------------------------
# A pack: header, index, frame table, payload, cut into parts
# ---------------------------------------------------------------------------

def read_varint(data, at):
    value = 0
    for shift in range(0, 56, 7):
        if at >= len(data):
            raise ExitError("a pack's index ends in the middle of a number")
        byte = data[at]
        at += 1
        value |= (byte & 0x7F) << shift
        if byte < 0x80:
            return value, at
    raise ExitError("a pack's index holds a number longer than any it writes")


class Pack:
    """One pack, read from the parts a version object names."""

    def __init__(self, root, model_id, named, suite):
        self.id = named["id"]
        self.suite = suite
        self.paths = []
        self.starts = [0]
        for number, part in enumerate(named["parts"]):
            path = os.path.join(root, "p", model_id, self.id, "%05d" % number)
            if not os.path.isfile(path):
                raise ExitError("part p/%s/%s/%05d is not in the bucket" % (model_id, self.id, number))
            digest = hashlib.sha256()
            size = 0
            with open(path, "rb") as handle:
                while True:
                    block = handle.read(1 << 20)
                    if not block:
                        break
                    digest.update(block)
                    size += len(block)
            if size != part["size"] or digest.hexdigest() != part["sha256"]:
                raise ExitError("part p/%s/%s/%05d is not the bytes its version names; the copy is damaged"
                                % (model_id, self.id, number))
            self.paths.append(path)
            self.starts.append(self.starts[-1] + size)
        if not self.paths:
            raise ExitError("pack %s has no parts" % self.id)

        head = self.read(0, HEADER)
        if head[:4] != b"SYNP":
            raise ExitError("pack %s is not a pack" % self.id)
        if head[4] != 1 or head[6] != 12 or head[7] != 6:
            raise ExitError("pack %s is in a format this script does not read" % self.id)
        self.base = bool(head[5] & 1)
        self.sealed = bool(head[5] & 2)
        index_stored, index_length, self.own, payload = struct.unpack_from("<QQQQ", head, 8)
        (frame_count,) = struct.unpack_from("<I", head, 40)
        if frame_count != (self.own + FRAME_SECTORS - 1) // FRAME_SECTORS:
            raise ExitError("pack %s: its frame count does not match its sectors" % self.id)
        meta_length = HEADER + index_stored + 4 * frame_count
        if meta_length + payload != self.starts[-1]:
            raise ExitError("pack %s is not the size its parts add up to" % self.id)

        if self.sealed != bool(suite.keys):
            if self.sealed:
                raise ExitError("this workspace was created with encryption on; pass its key with --key")
            raise ExitError("pack %s is not encrypted, and its workspace is" % self.id)
        if self.sealed and head[44:52].hex() != suite.key_id:
            raise ExitError("pack %s was sealed under key %s, and the key given has id %s"
                            % (self.id, head[44:52].hex(), suite.key_id))

        try:
            index = zlib.decompress(self.read(HEADER, index_stored), -15)
        except zlib.error:
            raise ExitError("pack %s: its index does not inflate" % self.id)
        if len(index) != index_length:
            raise ExitError("pack %s: its index is not the length its header says" % self.id)
        self.sources, self.files, self.prints = self.parse_index(index)

        table = self.read(HEADER + index_stored, 4 * frame_count)
        self.frames = []
        offset = meta_length
        for number in range(frame_count):
            (entry,) = struct.unpack_from("<I", table, number * 4)
            stored = entry & 0x7FFFFFFF
            self.frames.append((offset, stored, bool(entry & 0x80000000)))
            offset += stored
        if offset != self.starts[-1]:
            raise ExitError("pack %s: its frames do not add up to its payload" % self.id)
        self.opened = {}

    def read(self, offset, count):
        """Bytes [offset, offset + count) of the pack's stream: its parts, end to end."""
        if offset < 0 or offset + count > self.starts[-1]:
            raise ExitError("pack %s is cut short" % self.id)
        out = bytearray()
        part = 0
        while self.starts[part + 1] <= offset and part + 1 < len(self.paths):
            part += 1
        while len(out) < count:
            within = offset + len(out) - self.starts[part]
            take = min(count - len(out), self.starts[part + 1] - self.starts[part] - within)
            with open(self.paths[part], "rb") as handle:
                handle.seek(within)
                out += handle.read(take)
            part += 1
        return bytes(out)

    def parse_index(self, index):
        at = 0
        sources = []
        count, at = read_varint(index, at)
        for _ in range(count):
            length, at = read_varint(index, at)
            sources.append(index[at:at + length].decode("utf-8"))
            at += length

        files = []
        count, at = read_varint(index, at)
        for _ in range(count):
            length, at = read_varint(index, at)
            path = index[at:at + length].decode("utf-8")
            at += length
            size, at = read_varint(index, at)
            runs = []
            covered = 0
            run_count, at = read_varint(index, at)
            for _ in range(run_count):
                head, at = read_varint(index, at)
                kind, sectors = head & 3, head >> 2
                if kind == 0:
                    runs.append((0, sectors, 0, 0))
                elif kind == 1:
                    source, at = read_varint(index, at)
                    sector, at = read_varint(index, at)
                    runs.append((1, sectors, source, sector))
                elif kind == 2:
                    ordinal, at = read_varint(index, at)
                    runs.append((2, sectors, ordinal, 0))
                else:
                    raise ExitError("pack %s: its index holds a run of an unknown kind" % self.id)
                covered += sectors
            if covered != size // SECTOR:
                raise ExitError("pack %s: the runs of %s do not cover it" % (self.id, path))
            tail_length, at = read_varint(index, at)
            if at + tail_length > len(index):
                raise ExitError("pack %s: its index is cut short" % self.id)
            files.append((path, size, runs, index[at:at + tail_length]))
            at += tail_length

        prints = index[at:]
        if len(prints) != self.own * PRINT:
            raise ExitError("pack %s: its index does not end where its fingerprints do" % self.id)
        return sources, files, prints

    def sector(self, ordinal):
        """One of this pack's sectors, as its own bytes, checked against its fingerprint."""
        if ordinal < 0 or ordinal >= self.own:
            raise ExitError("pack %s does not carry sector %d" % (self.id, ordinal))
        number = ordinal // FRAME_SECTORS
        frame = self.opened.get(number)
        if frame is None:
            offset, stored, deflated = self.frames[number]
            sectors = min(FRAME_SECTORS, self.own - number * FRAME_SECTORS)
            frame = self.read(offset, stored)
            if deflated:
                try:
                    frame = zlib.decompress(frame, -15)
                except zlib.error:
                    raise ExitError("pack %s: a frame does not inflate" % self.id)
            if len(frame) != sectors * SECTOR:
                raise ExitError("pack %s: a frame is not the size its sectors say" % self.id)
            if len(self.opened) >= 16:
                self.opened.clear()
            self.opened[number] = frame

        within = (ordinal % FRAME_SECTORS) * SECTOR
        fingerprint = self.prints[ordinal * PRINT:(ordinal + 1) * PRINT]
        data = self.suite.open_sector(frame[within:within + SECTOR], fingerprint)
        if self.suite.fingerprint(data) != fingerprint:
            raise ExitError("pack %s: sector %d is not what its fingerprint says" % (self.id, ordinal))
        return data


class TableFile:
    """One file of a version: its length, its fingerprints, its tail as stored, and where each sector is."""

    def __init__(self, length, prints, tail, places):
        self.length = length
        self.prints = prints
        self.tail = tail
        self.places = places        # per sector: (pack, ordinal)


def apply(parent, pack):
    """The version a pack's index yields from the version before it. A base needs no parent."""
    table = dict(parent) if parent else {}
    for path, size, runs, tail in pack.files:
        prints = bytearray()
        places = []
        at = 0
        for kind, sectors, a, b in runs:
            if kind == 2:
                if a + sectors > pack.own:
                    raise ExitError("%s names sectors pack %s does not carry" % (path, pack.id))
                prints += pack.prints[a * PRINT:(a + sectors) * PRINT]
                places.extend((pack, a + step) for step in range(sectors))
            else:
                if kind == 1 and a >= len(pack.sources):
                    raise ExitError("%s takes sectors from a file pack %s does not name" % (path, pack.id))
                source = path if kind == 0 else pack.sources[a]
                first = at if kind == 0 else b
                held = parent.get(source) if parent else None
                if held is None or first + sectors > len(held.places):
                    raise ExitError("%s takes sectors from %s, which the version before does not have"
                                    % (path, source))
                prints += held.prints[first * PRINT:(first + sectors) * PRINT]
                places.extend(held.places[first:first + sectors])
            at += sectors
        table[path] = TableFile(size, bytes(prints), tail, places)
    return table


# ---------------------------------------------------------------------------
# The bucket
# ---------------------------------------------------------------------------

def workspace_roots(bucket):
    """Every folder under `bucket` that holds a workspace: one with `v/` inside."""
    bucket = os.path.abspath(bucket)
    if os.path.isdir(os.path.join(bucket, "v")):
        return [bucket]
    roots = []
    for dirpath, dirnames, _ in os.walk(bucket):
        if os.path.relpath(dirpath, bucket).count(os.sep) > 4:
            dirnames[:] = []
            continue
        if "v" in dirnames and os.path.basename(os.path.dirname(dirpath)) == "w":
            roots.append(dirpath)
            dirnames[:] = []
    return sorted(roots)


def read_objects(root):
    """Every version object under `v/`, parsed and checked for its format."""
    versions = []
    base = os.path.join(root, "v")
    for model_dir in sorted(os.listdir(base)):
        folder = os.path.join(base, model_dir)
        if not os.path.isdir(folder):
            continue
        for name in sorted(os.listdir(folder)):
            if not name.endswith(".json"):
                continue
            with open(os.path.join(folder, name), "rb") as handle:
                try:
                    obj = json.loads(handle.read().decode("utf-8"))
                except (ValueError, UnicodeDecodeError):
                    raise ExitError("%s is not a version object" % os.path.join(folder, name))
            if obj.get("format") != FORMAT:
                raise ExitError("%s is in format %r, and this script reads %s" % (name, obj.get("format"), FORMAT))
            versions.append(obj)
    return versions


def safe_name(segment):
    """A folder or file name Windows and POSIX both accept."""
    cleaned = "".join("_" if ch in '<>:"/\\|?*' or ord(ch) < 32 else ch for ch in segment).rstrip(". ")
    return cleaned or "_"


class Rebuilder:
    """One model's versions, read in order, each from the one before it or from a base."""

    def __init__(self, root, key_text):
        self.root = root
        self.key = parse_key(key_text) if key_text else None
        self.key_id = key_id_of(self.key) if self.key else ""
        self.suites = {}
        self.packs = {}
        self.at = None          # the sequence `self.table` is the table of
        self.table = None

    def suite_for(self, obj):
        if not obj.get("encryption"):
            return Suite(None, "")
        if not self.key:
            raise ExitError("this workspace was created with encryption on; pass its key with --key")
        wanted = obj["encryption"]["keyId"]
        if wanted != self.key_id:
            raise ExitError("this workspace's key has id %s, and the key given has id %s" % (wanted, self.key_id))
        workspace_id = obj["workspace"]["id"]
        if workspace_id not in self.suites:
            self.suites[workspace_id] = Suite(subkeys(self.key, workspace_id), self.key_id)
        return self.suites[workspace_id]

    def pack(self, obj, named, suite):
        if named["id"] not in self.packs:
            self.packs[named["id"]] = Pack(self.root, obj["model"]["id"], named, suite)
        return self.packs[named["id"]]

    def table_of(self, by_seq, seq, suite):
        """The table of version `seq`: from the version before when that is at hand, else from the nearest base."""
        obj = by_seq[seq]
        if self.at == seq:
            return self.table
        if self.at == seq - 1 and self.table is not None and obj["pack"]["kind"] == "delta":
            self.table = apply(self.table, self.pack(obj, obj["pack"], suite))
            self.at = seq
            return self.table

        # Walk down to the newest version at or below this one that stands
        # alone: one published as a base, or one a base was written for.
        start = seq
        while True:
            if start not in by_seq:
                raise ExitError("version %d is read from version %d, whose object is not in the bucket"
                                % (seq, start))
            if by_seq[start].get("base") or by_seq[start]["pack"]["kind"] == "base":
                break
            start -= 1

        first = by_seq[start]
        table = apply(None, self.pack(first, first.get("base") or first["pack"], suite))
        if not self.pack(first, first.get("base") or first["pack"], suite).base:
            raise ExitError("version %d is named as a base and its pack is not one" % start)
        for step in range(start + 1, seq + 1):
            table = apply(table, self.pack(by_seq[step], by_seq[step]["pack"], suite))
        self.table = table
        self.at = seq
        return table

    def rebuild(self, by_seq, seq, folder):
        """Writes, or only checks, every file of one version. Answers (files, bytes)."""
        obj = by_seq[seq]
        suite = self.suite_for(obj)
        table = self.table_of(by_seq, seq, suite)

        # The tree root names the file table: path, size and root of every
        # file, in path order, a line feed after each.
        lines = "".join("%s\n%d\n%s\n" % (entry["path"], entry["size"], entry["root"])
                        for entry in sorted(obj["files"], key=lambda entry: entry["path"].encode("utf-16-be")))
        if obj.get("root") and hashlib.sha256(lines.encode("utf-8")).hexdigest() != obj["root"]:
            raise ExitError("the version's file table is not the one its root names")

        total = 0
        for entry in obj["files"]:
            held = table.get(entry["path"])
            if held is None or held.length != entry["size"]:
                raise ExitError("%s: the packs of this version do not yield it" % entry["path"])
            tail = suite.open_tail(held.tail)
            if len(tail) != held.length % SECTOR:
                raise ExitError("%s: its tail is not the length the file says" % entry["path"])
            if suite.root(held.length, held.prints, tail) != entry["root"]:
                raise ExitError("%s: the file is not what its root says" % entry["path"])

            target = None
            handle = None
            if folder:
                target = os.path.join(folder, *[safe_name(part) for part in entry["path"].split("/")])
                os.makedirs(os.path.dirname(target), exist_ok=True)
                handle = open(target + ".partial", "wb")
            try:
                for number, (pack, ordinal) in enumerate(held.places):
                    data = pack.sector(ordinal)
                    if pack.prints[ordinal * PRINT:(ordinal + 1) * PRINT] != held.prints[number * PRINT:(number + 1) * PRINT]:
                        raise ExitError("%s: sector %d is not the one the version names" % (entry["path"], number))
                    if handle:
                        handle.write(data)
                if handle:
                    handle.write(tail)
            finally:
                if handle:
                    handle.close()
            if target:
                os.replace(target + ".partial", target)
            total += held.length
        return len(obj["files"]), total


def main(argv):
    parser = argparse.ArgumentParser(description="Turn a copy of a Syncture bucket back into Revit models.")
    parser.add_argument("--bucket", required=True, help="a folder holding a copy of the bucket, or of the workspace's prefix")
    parser.add_argument("--out", help="where the models are written")
    parser.add_argument("--key", help="the workspace key, for a workspace created with encryption on")
    parser.add_argument("--key-file", help="a file holding the workspace key")
    parser.add_argument("--latest", action="store_true", help="only the newest version of each model")
    parser.add_argument("--model", help="one model, by id or name")
    parser.add_argument("--verify", action="store_true", help="check everything and write nothing")
    args = parser.parse_args(argv)

    if not args.verify and not args.out:
        parser.error("--out is needed unless --verify is given")
    key_text = args.key
    if args.key_file:
        with open(args.key_file, "r", encoding="utf-8-sig") as handle:
            key_text = handle.read()

    roots = workspace_roots(args.bucket)
    if not roots:
        print("No workspace found under %s: no folder holding v/ and p/." % args.bucket)
        return 1

    failures = 0
    rebuilt = 0
    files = 0
    total = 0
    for root in roots:
        try:
            versions = read_objects(root)
        except ExitError as error:
            print("x  %s: %s" % (root, error))
            failures += 1
            continue
        if not versions:
            print("-  %s holds no versions" % root)
            continue

        by_model = {}
        for obj in versions:
            by_model.setdefault(obj["model"]["id"], []).append(obj)
        for model_id, objs in sorted(by_model.items()):
            objs.sort(key=lambda o: o["version"]["seq"])
            newest = objs[-1]
            if args.model and args.model not in (model_id, newest["model"]["name"]):
                continue
            chosen = objs[-1:] if args.latest else objs
            by_seq = {obj["version"]["seq"]: obj for obj in objs}
            workspace_name = safe_name(newest["workspace"]["name"] or newest["workspace"]["id"])
            model_folder = [safe_name(part) for part in newest["model"]["path"].split("/") if part]
            print("%s  (%s), %d of %d versions" % (newest["model"]["path"], model_id, len(chosen), len(objs)))

            try:
                worker = Rebuilder(root, key_text)
            except ExitError as error:
                failures += len(chosen)
                print("   x  %s" % error)
                continue

            for obj in chosen:
                seq = obj["version"]["seq"]
                try:
                    folder = None
                    if not args.verify:
                        folder = os.path.join(args.out, workspace_name, *model_folder, "v%04d" % seq)
                    count, size = worker.rebuild(by_seq, seq, folder)
                    files += count
                    total += size
                    rebuilt += 1
                    print("   +  v%d  %s  %s  %d files" % (seq, obj["version"]["createdAt"][:10], obj["version"]["author"], count))
                except ExitError as error:
                    failures += 1
                    worker.at = None
                    worker.table = None
                    print("   x  v%d: %s" % (seq, error))

    verb = "checked" if args.verify else "rebuilt"
    print("%d versions %s, %d files, %d bytes, %d failures." % (rebuilt, verb, files, total, failures))
    return 1 if failures else 0


if __name__ == "__main__":
    sys.exit(main(sys.argv[1:]))

Add --latest for the newest version of each model only, or --model for one model. Add --verify to check everything and write nothing, and --key for a workspace created with encryption on.

The byte formats

Everything a script needs to read the bucket, so that anybody can write one. Integers are little-endian and digests are lowercase hex.

The version object

format

syncture-version/1. A script refuses any other value.

workspace

id and name. The id is what the key is bound to in a workspace created with encryption on.

model

id, name and path, the path being where the model was filed when the object was written.

version

id, seq, createdAt, author, note and hostRelease. The sequence is the number in the object's name.

encryption

null, or { keyId } in a workspace created with encryption on, naming the key every sealed pack carries.

files

One entry per file: path, size and root. The root names the file's whole content, from its size, the fingerprint of each sector and the fingerprint of its tail.

root

The SHA-256 of the file table: for every file in path order, its path, its size in decimal and its root, a line feed after each.

pack

id, kind and parts. A base describes the version completely. A delta is read against the version before. Each part has its size and sha256 as it lies in the bucket.

base

null, or a pack that describes this version completely, written for it afterwards. A script may start reading there.

SYNP, a pack

stream

A pack's parts joined in order: a 64-byte header, the index (raw deflate, RFC 1951), the frame table, the payload.

0 · 4

SYNP, then at offset 4 one byte of version, 01.

5 · 1

Bit 0 is set in a base. Bit 1 is set in a pack from a workspace created with encryption on.

6 · 2

12 and 6: a sector is 4,096 bytes and a frame holds up to 64 sectors.

8 · 32

Four 64-bit integers: the index's stored length, its length once inflated, the number of sectors the pack carries, the payload's stored length.

40 · 4

The frame count. In a workspace created with encryption on, the 8-byte key id follows at offset 44. The payload begins at 64 + the index's stored length + 4 × the frame count.

index

A varint count of source paths, each a varint length and UTF-8. Then a varint count of files.

per file

Path, varint size, varint run count, the runs, varint tail length, the tail. The runs cover the file's whole sectors in order.

a run

A varint: the sector count shifted left by two, plus a kind. Kind 0 takes the same sectors of the same file in the version before. Kind 1 takes them from a source file there, and is followed by the source's number and its first sector. Kind 2 takes this pack's own sectors, and is followed by the first one's ordinal.

then

16 bytes per sector the pack carries: their fingerprints, in order. Nothing follows.

frame table

One 32-bit integer per frame: its stored length, with the top bit set when the frame is raw deflate.

payload

The pack's own sectors in order, 64 to a frame. A sector's fingerprint is the first 16 bytes of its SHA-256.

check

A file's root is SHA-256("SYNR1" + size as 64 bits + every sector's fingerprint + the tail's fingerprint), the last left out when there is no tail. It must be the root the version object names.

With encryption on

the key

SYNK1- and seven groups of Crockford base32. Remove spaces and hyphens, uppercase, fold I and L to 1 and O to 0. 52 characters carry the 32 bytes and 4 carry a checksum, the first 20 bits of SHA-256("syncture/key/v1" + K).

subkeys

PRK = HMAC-SHA256(key "syncture/workspace/v1", K). Each subkey is HMAC-SHA256(PRK, "<use>|<workspace id>" + 0x01), for enc, mac, siv and file.

fingerprint

The first 16 bytes of HMAC-SHA256 under the siv subkey over eight FF bytes and then the sector.

a sector

AES-256-CBC under the enc subkey with the sector's fingerprint as the vector and no padding. Exactly 4,096 bytes. Frames are never deflated.

a root

The same bytes as without encryption, under HMAC-SHA256 with the file subkey.

a tail · 0

A tail is carried as an envelope. SYNK, then at offset 4 one byte of version, 01.

5 · 8

The key id, the first 8 bytes of SHA-256("syncture/kid/v1" + K). Checked against the key you hold before anything else.

13 · 16

The AES initialisation vector.

29 · n

AES-256-CBC under the enc subkey, PKCS7 padded, so n is a multiple of 16.

29+n · 32

HMAC-SHA256 under the mac subkey over everything before it. Checked in constant time before one block is decrypted.

In a workspace created with encryption on, a sector is stored as exactly 4,096 encrypted bytes and a file's tail as an envelope. The same sector always encrypts to the same bytes, so a repeated sector is still stored once.

What proves it

The three scripts are run against a fixture bucket before every release, and so is the add-in's own reader. Python, Windows PowerShell 5.1 and the .NET SDK each rebuild the same forty-two files byte for byte. Each refuses a workspace created with encryption on until it is given the key.

The fixture and the checker ship with the product's source. This page is held to the same test as every other page, where a claim the software does not implement fails the build.

10 October 2026