For security researchers
How Latchway works, in full.
Every Latchway app, and this website, is built to work exactly as described here. It's written for security researchers and engineers. The plain-words version is on our security page.
If you find a mistake or a weakness, please write to support@latchway.app with the subject Security.
Latchway Protocol v1
This document is the single source of truth for every Latchway implementation (Android and iOS apps, the browser sender and receiver on latchway.app, the Go CLI, and the Cloudflare Worker and Go rendezvous servers). If code and this document disagree, the code is wrong.
Latchway moves a file directly between two devices over a WebRTC data channel. A small rendezvous server only relays the encrypted connection handshake; it never carries file bytes. There is no relay for file data: the two devices connect directly (STUN-assisted NAT traversal) or the transfer cannot start. A user who wants to hide their IP address from the other party uses their own VPN together with the client's "Hide my IP" mode (§4.5).
Sender (host) Rendezvous Receiver (joiner)
─────────────── ─────────── ─────────────────
register share ──── WS ────▶ Durable Object ◀──── WS ──── open link
◀── join ──── │ ── joined ──▶
hello ────────────▶ │ ────────────▶
◀──────────── │ ◀──────────── auth proof
enc(meta, go) ────────────▶ │ ────────────▶
◀──────────── │ ◀──────────── enc(offer, ICE)
enc(answer,ICE) ────────────▶ │ ────────────▶
│
══════════════ WebRTC data channel (DTLS, direct) ════════════════════════
AES-GCM chunk 0, 1, 2 … last ─────────────────────────────▶
◀───────────────────────────────────────── progress, done
All multi-byte integers are big-endian. b64url means base64url without
padding (RFC 4648 §5). Strings are UTF-8. JSON messages are objects with a
string field t (type).
1. Identifiers and the link
| Name | Bytes | Encoding | Visibility |
|---|---|---|---|
shareId | 16 | b64url (22) | Public. Seen by the rendezvous. |
secret | 32 | b64url (43) | Private. Lives only in the URL fragment. |
Both are generated with a cryptographically secure RNG when a share is created.
Link forms:
https://<rendezvous-host>/s/<shareId>#<secret> latchway://<rendezvous-host>/s/<shareId>#<secret>
Browsers never send the fragment (#…) to any server, so the secret never
reaches the rendezvous or any web server. Implementations MUST NOT place
the secret anywhere other than the fragment, MUST NOT log it, and MUST set
Referrer-Policy: no-referrer on any page that serves a link.
The https form is the primary one: with Android App Links verified
against /.well-known/assetlinks.json, only the genuine app receives it.
The latchway:// form is a fallback for devices where verification has
not happened; custom schemes are not verified by the OS, so a malicious app
claiming the scheme could intercept such a link. Pages offering the
fallback should say so.
shareId strings are compared byte for byte. Servers MUST reject an id that
does not re-encode to the same 22 characters after decoding (non-canonical
padding bits), so that one share cannot be addressed under two spellings.
The link does not reveal whether a password is set, although the sender's
hello message (§4.1) does, to anyone who connects.
2. Key derivation
pwk = PBKDF2-HMAC-SHA256(NFC(password), salt = "latchway/v1/pw" || shareId, iter = 600000, len = 32)
or 32 zero bytes when no password is set
ikm = secret || pwk (64 bytes)
prk = HKDF-Extract(SHA-256, salt = "latchway/v1" || shareId, ikm)
K_auth = HKDF-Expand(prk, info = "latchway/v1/auth", 32)
K_root = HKDF-Expand(prk, info = "latchway/v1/root", 32)
shareId here means the raw 16 bytes. NFC(password) is the password
normalised to Unicode NFC before UTF-8 encoding; implementations MUST
normalise so that the same password typed on different keyboards derives
the same key.
PBKDF2 rather than a memory-hard KDF is a deliberate trade-off: it is available natively on every target (javax.crypto, WebCrypto, Go) with no extra dependency to audit. The password's protection against offline guessing rests primarily on §3.1, which ensures a receiver's proof can only ever reach the genuine sender, and on the online throttle in §4.1.
Per session (see §4), with hostNonce and joinerNonce of 16 bytes each:
sprk = HKDF-Extract(SHA-256, salt = "latchway/v1/session" || hostNonce || joinerNonce, ikm = K_root) S_sig = HKDF-Expand(sprk, info = "latchway/v1/s/sig", 32) S_file = HKDF-Expand(sprk, info = "latchway/v1/s/file", 32) S_sas = HKDF-Expand(sprk, info = "latchway/v1/s/sas", 32)
Matching code. With sasNonce the 16 random bytes the host puts in
meta (§4.3):
mac = HMAC-SHA256(S_sas, "latchway/v1/sas" || sasNonce) code = (mac[0..4) as u32, big-endian) mod 1000000, as 6 decimal digits with leading zeros
Clients display it as two groups of three, 471 902. The host shows it in
the approval prompt; the joiner shows it while waiting for approval. Both
people compare it over another channel (a call, in person) before the
sender approves. The host draws sasNonce only after it has verified the
joiner's proof, so a party that holds the link and joins with a chosen
joinerNonce cannot steer its session's code towards another session's:
each session's code is uniformly random to everyone, and a guess that
matches succeeds with probability 10⁻⁶ while showing the sender one more
request.
Every session therefore has fresh encryption keys even though the link is reused, which keeps AES-GCM nonces unique by construction.
Test vectors for every step are in testdata/vectors.json (not published
with this page; security reviewers can ask for them) and are checked by the
Go, Kotlin, Swift and JavaScript test suites.
3. Rendezvous protocol
Transport: WebSocket, text frames carrying JSON. The rendezvous is a dumb
router. It parses only t and sid; everything in d is opaque to it.
3.1 Host registration
GET wss://<host>/v1/host?share=<shareId> Authorization: Bearer <token> (only if the server requires one; header only, never a query parameter)
The host's first message is its registration:
{"t":"register","reg":"<b64url 32 bytes>"}
reg is a registration key: 32 random bytes drawn by the sender's
device when the share is created and kept only on that device for the
share's lifetime. It is not derived from the link, so holding the link
gives nobody the ability to pose as the sender. The server stores
SHA-256(reg) against the shareId (never reg itself) and replies
{"t":"ready"}.
- A registration for a
shareIdwhose stored hash matches replaces the live host, if any: the old connection receives{"t":"error","code":"replaced"}and is closed, and its joiners receivehost_gone. This is how a phone that changed networks resumes its share. - A registration whose hash does not match the stored one is refused with
{"t":"error","code":"forbidden"}, whether or not a host is live. - The binding expires 30 days after the most recent registration. A server that loses its bindings (the Go binary keeps them in memory) reopens those ids to whoever registers first; operators who care should keep the binary running or front it with the Worker.
Without this, anyone who learned a shareId (link-preview bots, browser
history, server logs) could register as the host and collect a receiver's
password proof for offline guessing, or simply knock the real host off.
Servers SHOULD rate-limit registrations per IP address.
The host keeps this connection open for the lifetime of the share and
sends the keepalive {"t":"ping"} at least every 30 s; the server answers
{"t":"pong"} (without waking a hibernated Durable Object). Joiners may
use the same keepalive.
3.2 Joiner connection
GET wss://<host>/v1/join/<shareId>
If no host is registered, the upgrade is refused with HTTP 404; if the
joiner caps (§3.4) are reached, with HTTP 429. No socket is opened in
either case. (Browsers cannot read the status of a failed upgrade; a web
client checks /v1/status/<shareId> first to tell the two apart.)
Otherwise the upgrade succeeds and:
- server → joiner:
{"t":"joined","sid":"<b64url 12 bytes>","ice":[…]} - server → host:
{"t":"join","sid":"<same sid>","ice":[…]}
ice is an array of RTCIceServer objects ({"urls":[…]}). Both lists
contain STUN servers only; the Latchway service hands out no TURN
credentials. The host still forwards its list to the joiner in the
encrypted go message (§4.3), and the joiner uses that list, so a
deployment could change the servers without changing clients. Clients
MUST ignore username/credential fields if a server ever sends them and
MUST NOT add TURN servers of their own. Servers MUST filter any configured
extra ICE servers to stun:/stuns: URLs without credentials, so that a
misconfiguration can never hand out a relay.
Servers SHOULD require the WebSocket Origin header, when present, to match
their own origin, so that web pages cannot make visitors' browsers join
shares. Native clients send no Origin. Servers SHOULD also cap concurrent
joiners per IP address.
3.3 Relaying
Either side sends {"t":"sig","sid":"…","d":"<string>"}. The server
forwards it to the other party of that sid unchanged (it MAY add or
overwrite sid on messages from a joiner, who has only one session).
{"t":"leave","sid":"…"} from the host closes that joiner's socket with
{"t":"error","code":"closed"}. When a joiner disconnects the host receives
{"t":"leave","sid":"…"}. When the host disconnects, every joiner receives
{"t":"error","code":"host_gone"} and is closed.
3.4 Limits (normative minimums)
| Limit | Value |
|---|---|
d payload size | ≤ 16 KiB |
sig messages per session per direction | ≤ 256 |
| concurrent joiners per share | ≤ 16 |
joiner lifetime without a sig | ≤ 120 s |
| joiner lifetime total | ≤ 30 min |
Exceeding a size or count limit yields {"t":"error","code":"rate_limited"}
and the lifetime limits yield "timeout", each followed by a close; the
joiner caps are enforced before the upgrade (HTTP 429, above). A sig in
either direction of a session counts as activity for the 120 s limit; a
host holding a proof back (§4.1) sends wait so that the joiner stays
within it. Hosts that send nothing (not even the
keepalive) for 90 s MAY be disconnected. The server MUST NOT persist any
message, MUST NOT log d, and SHOULD NOT log shareId.
3.5 Other HTTP endpoints
| Path | Purpose |
|---|---|
GET /s/<shareId> | Landing page ("Open in Latchway" / get the app) |
GET /v1/status/<shareId> | {"active":true|false} |
GET /.well-known/assetlinks.json | Android App Links verification |
GET /.well-known/apple-app-site-association | iOS universal links (see below) |
GET /.well-known/security.txt | Security contact (RFC 9116), as UTF-8 plain text |
GET /healthz | 200 ok |
/.well-known/assetlinks.json lists the configured SHA-256 signing
certificate fingerprints for the configured Android package. Each
fingerprint is trimmed, upper-cased and must match
^([0-9A-F]{2}:){31}[0-9A-F]{2}$; others are dropped. With no valid
fingerprint (or no package) the body is [].
/.well-known/apple-app-site-association is answered directly (200, no
redirect) with Content-Type: application/json and a short cache
(Cache-Control: public, max-age=300), because Apple's CDN fetches it on
the device's behalf. The configured app ids are trimmed and each must match
^[A-Z0-9]{10}\.[A-Za-z0-9.-]+$ (TEAMID.bundle.id); others are dropped.
With at least one valid id the body is exactly
{"applinks":{"details":[{"appIDs":["TEAMID.app.latchway"],"components":[{"/":"/s/*","comment":"share links"}]}]}}
and with none it is {"applinks":{"details":[]}}.
3.6 Blocked shares (operator)
An operator can stop a share by its shareId, for example after an abuse
report. Servers take a configured list of blocked ids (the Worker's
BLOCKED_SHARES, the Go binary's --blocked-shares; comma-separated,
malformed or non-canonical entries ignored). For a blocked id:
/v1/host?share=<id>is upgraded as usual, but theregistermessage (once it is well formed) is answered with{"t":"error","code":"forbidden"}and the socket is closed. Nothing is stored. Clients already treatforbiddenas "this share cannot be served from here" (§3.1), so they need no change./v1/join/<id>is refused with HTTP 404 before the upgrade, exactly as when no host is registered./v1/status/<id>answers{"active":false}./s/<id>still serves the static landing page.
The list is read at start-up (Worker: on deploy); a host that is live
when the list changes stops being reachable at the next deploy or
restart, and servers need not disconnect it. Servers MUST NOT log the
list, blocked ids or matches. Blocking needs only the public shareId;
the operator never sees the secret, the file or its name.
4. Session protocol
Session messages travel inside the d field of sig messages as JSON
strings. The first two are plaintext; everything after is encrypted.
4.1 Hello and proof (plaintext)
Host → joiner, immediately after join:
{"t":"hello","v":1,"pw":false,"n":"<b64url hostNonce 16 bytes>"}
pw tells the joiner whether to prompt for a password before deriving
keys. hostNonce MUST be freshly drawn for every session; the replay and
nonce-uniqueness arguments below depend on it.
Joiner → host:
{"t":"auth","n":"<b64url joinerNonce 16 bytes>","p":"<b64url proof>"}
proof = HMAC-SHA256(K_auth, "latchway/v1/proof" || v(1 byte) || pw(1 byte: 0x00/0x01) || hostNonce || joinerNonce)
Binding v and pw into the proof means a relay that flips either field
causes a clean bad_auth rather than a misdiagnosed failure, and rules
out version downgrades once a v2 exists.
The host compares in constant time. On failure it replies
{"t":"error","code":"bad_auth"} (plaintext) and sends leave for the
session. Because the proof is bound to both nonces it cannot be replayed.
Guessing throttle. Hosts MUST limit online guessing per share, as follows, without refusing anyone outright:
- Let f be the number of proofs for this share that failed within the last 24 hours, plus the number being checked at once right now (each of which may yet fail, so a burst of parallel joiners cannot slip past the threshold together).
- A proof that arrives while f < 5 is checked at once.
- Otherwise the proof is held. Held proofs are checked one at a time per share (in arrival order where the platform allows), so parallel joiners do not multiply the rate. When a held proof's turn comes, f is recomputed; if it is still at least 5, the proof is checked no sooner than d = min(10 s × 2^(f − 5), 300 s) after the later of its arrival and the moment the previous held proof of the share was answered. (Delays: 10, 20, 40, 80, 160, then 300 s.)
- A correct proof that is held succeeds when its turn comes. It does not reset the count.
- A joiner that leaves while its proof is held is never answered, and its proof is neither checked nor counted.
- When it holds a proof, the host sends the plaintext message
{"t":"wait"}on that session at once and then every 60 s while the proof stays held, so that the joiner can tell its user straight away and the rendezvous does not end the idle session (§3.4). A joiner that receiveswaitbefore its firstencmessage keeps waiting, restarting its own timeout for the host's reply (at least 90 s), and SHOULD tell its user that the sender is slowing down password attempts.waitis unauthenticated, so it may only ever extend a wait, never change an outcome. - The host SHOULD show its user the number of failed proofs since the share was created ("3 wrong-password attempts"), with a way to stop the share.
The joiner authenticates the host implicitly: only a party knowing
K_root can produce the encrypted messages that follow, and §3.1 ensures
only the originating device can be registered as the host. A joiner that
receives an undecryptable message MUST abort with "this link is not valid".
After the joiner has received its first enc message, plaintext messages
on the session carry no meaning and MUST be ignored; before that, the only
meaningful plaintext messages from the host are error and wait.
4.2 Encrypted envelope
After a successful proof both sides derive S_sig and S_file (§2).
Every further signaling message is:
{"t":"enc","c":"<b64url ciphertext>"}
ciphertext = AES-256-GCM(key = S_sig, nonce = dir(1) || 0x00×3 || counter(8), aad = "latchway/v1/sig", plaintext = JSON)
dir is 0x00 for host→joiner and 0x01 for joiner→host. Each direction
keeps its own counter starting at 0 and incrementing by exactly 1 per
message. Receivers MUST reject any message whose counter is not the next
expected value.
4.3 Encrypted messages
| Direction | Message |
|---|---|
| host → joiner | {"t":"meta","name":"…","size":123,"mime":"…","chunk":65536,"from":"Sam","approval":true,"sas":"<b64url sasNonce 16 bytes>","pad":"…"} sas is present in every meta, freshly drawn per session (§2, matching code); a receiver treats a sas that is not 16 bytes of b64url as protocol, and a missing one (older senders) as "no code to show". The name is truncated to 255 bytes and then, if JSON escaping still makes the message exceed 1024 bytes, shortened one character at a time until it fits (never below one character; if that is not enough, from is shortened next). size is -1 when unknown; receivers treat any other negative value, or a non-integer, as protocol. from is optional and truncated to 64 bytes on a character boundary. mime is a bare type/subtype of RFC 6838 restricted-name characters (^[A-Za-z0-9][A-Za-z0-9!#$^_.+-]{0,62}/[A-Za-z0-9][A-Za-z0-9!#$^_.+-]{0,62}$, no parameters); senders replace anything else with application/octet-stream, and receivers treat a non-matching value the same way and never use it to decide how to open the file. Receivers strip control and bidirectional-formatting characters (U+0000–001F, U+007F–009F, U+061C, U+200E–200F, U+202A–202E, U+2066–2069) from name and from before display, and reduce name to a single safe path component before saving. approval means the joiner should show "waiting for the sender to approve". chunk MUST be 65536 in v1; receivers reject other values. pad is spaces, sized so the serialised JSON is exactly 1024 bytes (names longer than fit are truncated to 255 bytes first), so the ciphertext length reveals nothing about the file name or size. files (an integer, 2 to 1000) is present only in a multi-file share and announces the list that follows (§4.6.2). fid (b64url of 16 random bytes) names the file's content for the life of the share: a host of a single-file share sends the same fid in every session (a new one if the file changes), and a host that sends it honours start (§4.7); multi-file shares carry none in this revision. Keys are serialised in the order t, name, size, mime, chunk, from, approval, sas, files, fid, pad (the vectors fix the bytes). |
| host → joiner | {"t":"files","list":[{"name":"…","size":123},…],"more":true,"pad":"…"} — the file list of a multi-file share, in one or more parts sent immediately after meta (§4.6.2). |
| host → joiner | {"t":"go","ice":[…],"net":"open"} — the host is ready to answer an offer (sent immediately when no approval is required). ice is the host's ICE server list from join; the joiner MUST use it in place of the list from joined. net is optional: the host's network check (§4.5); netv, also optional, is that check's version. |
| host → joiner | {"t":"error","code":"denied"|"expired"|"busy"} |
| joiner → host | {"t":"offer","sdp":"…","start":0,"net":"open"} — start is the first chunk index wanted: 0, or, after a meta with fid, the first chunk a continuing receiver lacks (§4.7). A host whose meta had no fid sends from chunk 0 whatever start says. net is optional: the joiner's network check (§4.5); netv as in go. |
| host → joiner | {"t":"answer","sdp":"…"} |
| both | {"t":"ice","cand":"…","mid":"…","mline":0} and {"t":"ice-done"} |
| both | {"t":"error","code":"…"} |
The host sends, in this order: meta; the files parts if meta has
files; then go or an error; then answer and ICE messages. A host
that asks its user to approve each download SHOULD first answer busy or
expired when it could not serve this download anyway, and ask only
otherwise; it still reserves the transfer after the approval, and may still
refuse then. A joiner that checks again on a busy link (some receivers do,
every 15 s) then never prompts the sender in vain. Both
sides MUST ignore encrypted messages whose t they do not know, so that
later revisions can add messages without breaking older peers (a meta
or files out of place is protocol). Receivers written before
this rule treated anything but go or error after meta as
protocol; they cannot receive a multi-file share.
The joiner is always the WebRTC offerer. The SDP (and therefore the DTLS
fingerprint) is authenticated by S_sig, so a hostile rendezvous cannot
substitute its own fingerprint and man-in-the-middle the data channel.
4.4 Data channel
Both sides create the channel with negotiated: true, id: 0, ordered: true,
reliable and label "latchway". A frame is at most 65 557 bytes (header +
64 KiB + tag). Every implementation MUST advertise and accept SCTP messages
of at least 262 144 bytes (a=max-message-size), which is libwebrtc's and
the browsers' default; pion-based implementations must raise their default
of 65 536.
Binary frames (host → joiner) carry one encrypted chunk each:
index u32 chunk index, starting at `start` (0 unless continuing, §4.7), strictly sequential
flags u8 bit0 = last chunk
body … AES-256-GCM(key = S_file,
nonce = 0x00×8 || index(4),
aad = "latchway/v1/chunk" || index(4) || flags(1),
plaintext = up to `chunk` bytes of the file)
Every chunk except the last is exactly chunk bytes of plaintext. The last
chunk may be shorter, including zero bytes for an empty file. The receiver
MUST reject a frame whose index is not the next expected one (the first
expected is start), MUST stop at the first frame with last, and when
size was known MUST verify the total plaintext length (start × chunk
plus what followed) equals size.
Text frames are JSON control messages:
| Direction | Message |
|---|---|
| joiner → host | {"t":"progress","bytes":N} about every MiB |
| joiner → host | {"t":"done"} after the last chunk verified |
| both | {"t":"abort","reason":"…"} |
Abort reasons. An abort ends the transfer for both sides; neither
counts it as a completed download. The sender of an abort stops queueing chunks at once and SHOULD
give the abort up to 3 s to leave (until bufferedAmount is 0) before
closing the peer connection. (Up to 1 MiB of chunks can be queued ahead of
it; on a slow path that takes more than a second to drain, and a receiver
that sees the connection close first reports connection_lost instead of
cancelled.) Once it has left, a sender that stops SHOULD wait up to 1 s
for the other side to close the channel before closing it itself, as a
joiner waits after done; and a receiver whose channel closes while it is
open SHOULD look for an abort still on its way, for up to 0.5 s, before
reporting connection_lost (the channel's state and its messages can
arrive by different paths).
reason | Sent when | The other side reports |
|---|---|---|
cancelled | the person stopped it: the receiver cancelled, or the sender stopped sharing during the transfer | cancelled ("the receiver cancelled" / "the sender cancelled") |
protocol | the peer broke this specification: a chunk that fails to open or arrives out of order, more data than size, a size mismatch at the end, an archive that does not match its list (§4.6.4) | protocol |
paused | the person paused (§4.7): the receiver paused its download, or the sender paused sharing during the transfer | paused ("they paused" / "the sender paused"): not a failure; a receiver keeps the whole chunks it has and may continue, a host keeps the share |
| anything else | a local failure, such as read error or write error | a generic failure; the text is shown, if at all, only after the filtering of §4.3 |
A receiver never reports an abort from the sender, or its own
cancellation, as protocol, and a host never reports a receiver's
cancelled or paused as a failure of its own.
Connection blips. Once the data channel is open, a peer connection
state of disconnected is transient (Wi-Fi hand-overs, a moment without
signal): a client MUST keep the session and wait up to 15 s for the
state to return to connected before giving up, and SHOULD tell its user
the connection is interrupted meanwhile. Only failed, closed, or 15 s
spent in disconnected end the transfer, and the client reports that as
connection_lost (§5), never as protocol. Repeated disconnected events
do not restart the 15 s; a return to connected does. Nothing is re-sent
by Latchway itself: SCTP retransmits what was lost, and v1 uses no ICE
restart. Before the data channel opens, §4.5 applies instead
(disconnected is ignored there; failed or the handshake timeout mean
no direct connection). A joiner that has already sent done treats any
of these states as the end of a completed transfer.
Flow control: the host waits while bufferedAmount exceeds 1 MiB and
resumes below 256 KiB. The host counts a download as completed only on
done, then closes the peer connection. The joiner SHOULD wait for that
close (up to 5 s) before closing its own side, so that done is not lost
to its own teardown.
Once the data channel is open, neither side depends on the rendezvous any
more: a leave, timeout or host_gone on the signaling socket during a
transfer carries no meaning and MUST NOT abort it (a long transfer can
outlive the joiner's 30-minute socket lifetime, §3.4). The joiner's data
channel can open a moment before the host's, and the joiner then leaves at
once; so a host that hears leave while its peer connection is connecting
or connected SHOULD wait a few seconds (latchway.app: 10) for its own
channel before treating the joiner as gone.
4.5 Direct connections and "Hide my IP"
Every connection is direct. ICE has failed when the peer connection
reaches the failed state, or when no data channel has opened within the
handshake timeout (90 s) after the offer and answer were exchanged. Clients
report that as a failure to connect directly and suggest another network (for example Wi-Fi instead
of mobile data) or turning off a VPN that blocks peer-to-peer traffic;
they MUST NOT fall back to any relay.
Network check. Before a transfer a client MAY check how its network
handles direct connections, and each side sends its result as net in
go or offer (with netv, the check's version), so that a failed
connection can say whose network blocked it: open, strict-ordered,
strict-random, strict-scattered, blocked or unknown. Peers MUST
ignore values they do not know.
Finding a path. Clients MAY try further ways to find a direct path between their two networks, using encrypted session messages that other peers ignore (§4.3). Every one of them ends in the same direct, end-to-end encrypted connection: none relays data or involves any server beyond the rendezvous, and none sends anything about the file.
Each side controls only its own candidates, so "Hide my IP" is a client setting with no wire change. When it is on, a client:
- signals only server-reflexive (
typ srflx) candidates, nevertyp hostortyp prflxones, both when trickling and in candidates embedded in the offer or answer SDP; - blanks the related address of each srflx candidate (
raddr 0.0.0.0or::,rport 0), which would otherwise carry the device's LAN address; - in the SDP it sends, also replaces the
c=connection address with0.0.0.0(or::), sets the port of every non-rejectedm=line to 9 and dropsa=rtcp:lines, because WebRTC stacks copy the "default" candidate (possibly a host one) into those places; - on platforms that allow it (Android, iOS), gathers candidates only on VPN network adapters, so the reflexive address is the VPN's exit address;
- before starting, checks that a VPN is active where the platform can tell, and warns the user if not.
A browser cannot choose adapters; there the mode filters candidates and tells the user it relies on a full-tunnel VPN. The rendezvous still sees the address the client connects from (the VPN's, when one is on).
4.6 Several files
A share can carry 2 to 1000 files behind one link. On the wire it is
still one stream over one data channel: the files travel as a single ZIP
archive built on the fly (§4.6.3), which meta describes and the chunks
carry exactly like a single file. In addition the host sends the list of
files before go (§4.6.2), so that a receiver can show it while waiting
for approval and save the files separately (§4.6.4). A single file is
always sent as itself, never as a one-entry archive. Senders MUST refuse
to create a share of more than 1000 files.
4.6.1 Entry names
The sender derives each entry's name from the file's display name, in the order of the list, and uses exactly that name both in the list and in the archive:
- Remove invalid UTF-8 sequences (on UTF-16 platforms: unpaired surrogates).
- Replace every
\with/and keep only the text after the last/. - Remove every code point in the set S: U+0000–001F, U+007F–009F, U+061C, U+200E, U+200F, U+2028, U+2029, U+202A–202E, U+2066–2069, U+FEFF.
- Remove leading and trailing U+0020 SPACE (that character only).
- If the result is empty,
.or.., usefile. - If it is longer than 240 bytes of UTF-8: let ext be the text from
its last
.when that.is not the first character and ext is at most 16 bytes, else empty. Cut the text before ext to at most 240 − len(ext) bytes on a code point boundary, remove trailing U+0020 from the cut part, and append ext. - Deduplicate in list order, comparing with ASCII case folding (A–Z and
a–z only, so every platform agrees): a name equal to an earlier result
becomes stem
(k)ext — that is, stem, a space,(, decimal k,), ext — for the smallest k ≥ 1 whose result is not taken yet, where ext is the text from the last.when that.is not the first character (no length limit here) and stem is the rest.
Every result is 1 to 246 bytes (240 plus at most (999)). Names are not
normalised (NFC or otherwise). Examples are in the entry_names vector:
photo.jpg, photo.jpg, PHOTO.JPG become photo.jpg, photo (1).jpg,
PHOTO (2).JPG; .hidden twice becomes .hidden, .hidden (1).
Receivers do not rely on these rules beyond the checks of §4.6.2; they
apply their own file-name rules when saving (§4.6.4).
4.6.2 meta and files
For a share of N files, meta has name "N files.zip" (N in
decimal), mime "application/zip", size the archive's exact length
(§4.6.3, known from the list before any file is read) and files N.
Everything else about meta (padding to 1024 bytes included) is
unchanged.
Immediately after meta, before go or any error, the host sends the
list as one or more encrypted files messages (consecutive envelope
counters):
{"t":"files","list":[{"name":"photo.jpg","size":65540},{"name":"notes.txt","size":100}],"more":true,"pad":" "}
Their exact bytes matter, because padding depends on their length, so
senders serialise them by this rule (the files vectors fix it): UTF-8;
no white space outside strings; keys in the order t, list, more,
pad; more present (with the value true) on every part except the
last and absent on the last; each entry {"name":…,"size":…} in that
order; size a decimal integer with no sign, leading zero, fraction or
exponent; in name, " written as \" and every other character written
literally (§4.6.1 leaves nothing else that JSON must escape; JSON
encoders that escape <, >, & or non-ASCII characters must not be
used for these messages).
The list is split into parts in order. A part starts with the next entry
and keeps taking entries while the part, serialised with "more":true
and an empty pad, stays at most 8192 bytes. more is then set if
entries remain. Finally pad is filled with spaces so that the part is
exactly the smallest of 1024, 4096 or 8192 bytes that holds it with
an empty pad. The ciphertexts therefore reveal only the number of parts
and the bucket of each. (8192 bytes of plaintext become about 10 962
bytes of d, inside the 16 KiB limit of §3.4 once encrypted and
base64url-encoded; larger buckets would not fit. A list of 1000 files
needs at most about 70 parts.)
A receiver that implements this section, on a meta with files:
- treats
filesthat is not an integer from 2 to 1000 asprotocol; - reads
filesparts until one withoutmore; any other message before that isprotocol(anerrorkeeps its meaning), as is a part with an empty list or more entries in total thanmeta.files; - then MUST check, treating any failure as
protocol: the number of entries equalsmeta.files; everynameis 1 to 255 bytes of UTF-8, contains no/, no\and nothing from S, is not.or.., and neither starts nor ends with U+0020; names are distinct under ASCII case folding; everysizeis an integer from 0 to 2^53 − 1;meta.mimeisapplication/zip; andmeta.sizeequals the archive length that §4.6.3 gives for this list.
A receiver that does not implement it ignores meta.files and the
files messages (unknown type, §4.3) and saves the archive like any
file.
4.6.3 The archive
The byte stream is a ZIP archive that the list determines completely, except for the file data and their CRC-32 values. Multi-byte integers in it are little-endian, as ZIP requires. For entry i (in list order) with n_i name bytes and size_i data bytes:
csize_i = size_i + 5 × max(1, ⌈size_i / 65535⌉)
zip64 = some size_i ≥ 0xFFFFFFFF, or some csize_i ≥ 0xFFFFFFFF, or N ≥ 0xFFFF,
or the archive length computed with zip64 = false is ≥ 0xFFFFFFFF
V = 45 if zip64, else 20
Per entry, in list order:
- Local file header (30 + n + (zip64 ? 20 : 0) bytes): signature
u32
0x04034b50; version needed u16 V; flags u160x0808(bit 3: data descriptor follows; bit 11: UTF-8 name); method u16 8 (DEFLATE); time u16 0; date u160x0021(1980-01-01); CRC-32 u32 0; compressed size u32 csize (0xFFFFFFFFif zip64); uncompressed size u32 size (0xFFFFFFFFif zip64); name length u16 n; extra length u16 (20 if zip64, else 0); the name; if zip64 the extra field: id u16 1, length u16 16, size u64, csize u64. - Data: the file's bytes as DEFLATE stored blocks of at most 65535
bytes each, max(1, ⌈size / 65535⌉) of them, every block but the last
full: a header byte
0x01for the last block and0x00otherwise (BFINAL, BTYPE = 00), LEN u16, NLEN u16 = LEN XOR0xFFFF, then LEN bytes. An empty file is the one block01 00 00 ff ff. - Data descriptor: signature u32
0x08074b50; CRC-32 u32 of the file's bytes (the ZIP CRC, CRC-32/ISO-HDLC); then csize and size, each u64 if zip64, else u32 (24 or 16 bytes in all).
Then the central directory, one record per entry in list order
(46 + n + (zip64 ? 28 : 0) bytes): signature u32 0x02014b50; version
made by u16 V; version needed u16 V; flags u16 0x0808; method u16 8;
time u16 0; date u16 0x0021; CRC-32 u32; compressed size u32 (csize,
or 0xFFFFFFFF if zip64); uncompressed size u32 (size, or 0xFFFFFFFF);
name length u16; extra length u16 (28 if zip64, else 0); comment length
u16 0; disk number u16 0; internal attributes u16 0; external attributes
u32 0; local header offset u32 (the offset, or 0xFFFFFFFF if zip64); the
name; if zip64 the extra field: id u16 1, length u16 24, size u64,
csize u64, offset u64.
If zip64, the zip64 end of central directory record (56 bytes):
signature u32 0x06064b50, record size u64 44, version made by u16 45,
version needed u16 45, disk u32 0, central directory disk u32 0, entries
on this disk u64 N, entries u64 N, central directory size u64, central
directory offset u64; then the zip64 locator (20 bytes): signature
u32 0x07064b50, disk u32 0, offset of the zip64 record u64, disks u32 1.
Last, the end of central directory record (22 bytes): signature u32
0x06054b50, disk u16 0, central directory disk u16 0, entries on this
disk u16 and entries u16 (N, or 0xFFFF if zip64), central directory
size u32 and offset u32 (or 0xFFFFFFFF each if zip64), comment length
u16 0.
The archive's length is therefore Σ(30 + n_i + csize_i + 16) +
Σ(46 + n_i) + 22, or with zip64 Σ(74 + n_i + csize_i) +
Σ(74 + n_i) + 98. Stored blocks inside method 8 keep the length exact
before any file is read (method 0 with data descriptors is not accepted
by every reader), cost 5 bytes per 64 KiB, and every ZIP reader opens the
result. The files vector gives a three-file archive (its SHA-256, first
local header and everything from the central directory on); the
zip64_layout vector gives the length and local headers of a 5 GB
archive.
4.6.4 Receiving several files
A receiver offers Save files (each file separately, into a folder the person chooses; the default) and Save as one .zip.
Save as one .zip stores the stream under meta.name like any single
file. It MAY skip the checks below; any ZIP reader verifies the CRCs
later.
Save files unpacks while the stream arrives. Because every entry's size
is known from the list, the receiver always knows whether the next byte is
structure or data, and of which entry; it needs no ZIP parser. It MUST
compare every byte that is not file data with the byte §4.6.3 prescribes,
where each descriptor's CRC-32 is the one the receiver computed over that
entry's data as received and the offsets follow from the list. (The
simplest implementation runs the same generator the sender does and
compares.) An entry's file is created when its local header has matched
completely, written as its data arrives under a temporary name, and made
final only when its data descriptor has matched. On the first difference,
a CRC that does not match, any byte after the end record, or a last chunk
that ends the stream before the end record, the receiver aborts with
reason protocol (§4.4), reports protocol and deletes the partly written
file. Files already made final MAY be kept, since each has passed its CRC
and every chunk was authenticated; the receiver then says how many were
kept. done is sent only after the end record has matched and every file
has been made final.
Each entry is saved under a name the receiver makes safe by its own rules,
as for meta.name (§4.3): one path component, no control or bidi
characters, no leading dot, no reserved device names. A receiver MUST NOT
overwrite an existing file unless the person asked for that: a name that
is already taken, by a file in the folder or by an earlier entry of this
transfer (compared case-insensitively), becomes stem (k) ext with
the smallest free k ≥ 1, as in §4.6.1 step 7.
4.7 Continuing a download
A transfer that stops part way can continue where it stopped, in a new session on the same link: each session has fresh keys (§2), so sending a chunk index again is safe.
- The receiver keeps the whole chunks it has verified, and nothing after
them, with the share id and the
name,sizeandfidof themetathat started the download. - When it joins again it continues only if the new
metahas the samename,sizeandfid: it asks forstart= the number of chunks it has, keepingstart × chunkbytes. Otherwise it starts over, discarding them, withstart0. A multi-file share (nofid) always starts over. - A host that sent
fidrequires an integer0 ≤ start ≤ max(0, ⌈size ÷ chunk⌉ − 1)(the last chunk's index); anything else, a negative or non-integerstartincluded, isprotocol. A missingstartis 0. It reads the file from bytestart × chunkand sends chunksstartonwards with their own indices; the last carrieslastas always. - Admission is unchanged (§4.3): a continuation is admitted like any
download, counts only on
done, and a host that asks for approval asks again. - Old and new together: a host without
fidsends from chunk 0, and receivers never ask it for more; receivers written before this section always ask for 0.
A receiver SHOULD continue by itself when the connection is lost during a
transfer (§4.4) and the link still works, waiting for the sender as for a
first join when it hears not_found or busy, and SHOULD let its user
pause (stop, keeping what it has) and continue later. A sender SHOULD let
its user pause sharing (leave the rendezvous, keeping the share) and
continue with the same registration key (§3.1), so that receivers waiting
for it continue too.
Pausing. The side that pauses during a transfer aborts with reason
paused (§4.4): the receiver when its user pauses, the sender when its
user pauses sharing. The other side reports paused, never a failure and
never cancelled: a receiver keeps the whole chunks it has and waits for
the sender (and the share) to come back, then continues as above; a host
counts no download and keeps the share. A receiver does not pause once
every byte has arrived or its last chunk is in (it finishes the file
instead), and a host that has sent the last chunk lets that transfer
finish rather than pausing it. A pause ends a session waiting for the
host's approval as paused or by leaving, never as denied. Pausing a
share does not stop its expiry, and a share that no longer takes
receivers (expired or used up) has nothing to pause.
5. Error codes
not_found, host_gone, replaced, forbidden, closed, bad_auth,
denied, expired, busy, rate_limited, timeout, protocol,
internal.
Local-only codes, never sent in an error message, which every client
reports to its user in the same terms:
| Code | Meaning |
|---|---|
connection_lost | the peer connection reached failed or closed, or stayed disconnected for 15 s, after the data channel had opened (§4.4) |
cancelled | the other side aborted with reason cancelled: the person there stopped the transfer (§4.4) |
paused | the other side aborted with reason paused: the person there paused; this side keeps what it has and may continue (§4.4, §4.7) |
6. What each party learns
| Party | Learns | Never learns |
|---|---|---|
| Rendezvous | shareId, both IP addresses, timing, whether a password is set, SHA-256(reg) | secret, keys, file name, size, bytes |
| Receiver | the file; the sender's IP address (the VPN's, with Hide my IP) | — |
| Sender | the receiver's progress; the receiver's IP address (likewise) | — |
For a multi-file share the rendezvous also sees how many files parts
there are and the bucket of each (§4.6.2), a coarse hint of the number of
files; never their names or sizes.
Peer-to-peer means the two devices learn each other's IP address. Someone watching their own traffic (for example with Wireshark) sees the other device's address and port and how much data flows, never the contents, name or exact size. A user who wants to hide their address uses a VPN and Hide my IP (§4.5); the other person then sees only the VPN's address.
7. Why encrypt twice
DTLS already encrypts the data channel hop by hop. The Latchway layer on top exists because (a) it binds the content to the link secret, so a rendezvous that lies about SDP gains nothing, (b) it makes the password a real second factor rather than a server-side check, and (c) the same chunk format is decrypted by WebCrypto in the browser receiver, so one key schedule serves every mode. AES-GCM runs at hundreds of MB/s on phones; the cost is negligible next to the network.
Appendix A. Human-readable sizes
Every client shows byte counts by one rule, so that a sender and a receiver comparing notes read the same text. The units are decimal (1 kB = 1000 bytes), as the file managers on iOS and Android show them, so a size in Latchway matches the size in the Files app:
- A negative count (size unknown) is "unknown size" (localisable).
- Below 1000: the integer and
B, as in0 B,999 B. - Otherwise take the largest k from 1 to 6 with 1000^k ≤ n, so the
unit is
kB,MB,GB,TB,PBorEB(lowercasek, as SI writes it), and let d = 1000^k.- t = ⌊(10·n + d/2) / d⌋ is the value in tenths, rounded half
up. If t < 1000, show ⌊t/10⌋,
., t mod 10, a space and the unit:1.0 kB,1.5 MB,99.9 GB. - Otherwise w = ⌊(n + d/2) / d⌋. If w ≥ 1000 and k < 6,
repeat with k + 1 (which gives
1.0and the next unit: 999 500 000 is1.0 GB). Else show w, a space and the unit:100 MB,999 GB.
- t = ⌊(10·n + d/2) / d⌋ is the value in tenths, rounded half
up. If t < 1000, show ⌊t/10⌋,
- Compute with integers, not floating point, so that values like 1.05 round the same everywhere. 10·n leaves the exact range of a double (2^53) above about 900 TB, and of a signed 64-bit integer above about 0.92 EB; at the largest count, 2^63 − 1, it does not fit in 64 bits at all. Use arbitrary precision (BigInt in JavaScript), a 128-bit product, or split n = q·d + r with 0 ≤ r < d and compute t = 10·q + ⌊10·r / d⌋, plus 1 if 2·(10·r mod d) ≥ d, and w = q, plus 1 if 2·r ≥ d, which stays below 2^64 since 10·r < 10^19.
- The reference uses
.as the decimal separator; a client MAY use its locale's. Rates use the same rule followed by/s(9.4 MB/s). - Protocol constants elsewhere in this document (64 KiB chunks, the
16 KiB
dlimit) are exact binary sizes, not display text.
The human_sizes vector lists inputs and the exact text.