Skip to content

Latest commit

 

History

History
378 lines (326 loc) · 28.6 KB

client-api.md

File metadata and controls

378 lines (326 loc) · 28.6 KB

Mistgate Client API, v1 (DRAFT 4, as the panel implements it)

How the client and a Mistgate panel talk once the client knows the user's subscription link. It is meant to be open: another panel may implement it and get the same client. Until a panel answers it, the client works in basic mode (the plain subscription a link gives to any app, see docs/ipc.md).

Status: draft 4. enrol, sync, leave and the settings format are written as the panel implements them (on panel branches, not released yet). The client implements enrol, sync, the block reports and the debug bundle.

Principles

  • The panel is not on the traffic's path. It hands out configuration and takes reports; when it cannot be reached the client keeps working on what it has.
  • The subscription link is enough to enrol. Everything after enrolment is authorised by a device key the client makes itself: 32 random bytes, base64url without padding, sent as Authorization: Bearer <key> over TLS; the panel stores only its SHA-256 and never returns a key. No signatures, timestamps or clocks.
  • The client never calls the subscription page's own self-service (<link>/devices and friends): that is guarded by the page password and stays so.
  • An unknown or malformed token or key gets what the panel answers to any stranger today (the decoy), and counts as a miss (the panel rate-limits misses per client network). Any answer that is not the expected JSON means "unreachable", never "removed".
  • Every request carries X-Mistgate-Caps and User-Agent: Mistgate/<version> (<os>) (the panel takes the app version from the first User-Agent token).
  • The panel's parsers reject unknown body fields: a new field needs a caps or version bump first.

Capabilities

X-Mistgate-Caps: v=1; hysteria2=2; gecko=1; awg=2.0,3.1; vless=1; trusttunnel=1; probe=1

A list of name=version. The panel does not hand out what is not listed (Gecko obfuscation only to clients that announce it, the AmneziaWG version by what is listed, VLESS paths only to vless=1, TrustTunnel paths only to trusttunnel=1), so a new protocol or feature appears without a new format version. v is this API's version.

Discovery

The plain subscription answer carries Mistgate-Client-Api: 1 only when the token is valid AND the request carried X-Mistgate-Caps AND the operator's client-API switch is on. Strangers get the decoy before any header; other apps never see it. The mistgate://add?url=… button on the subscription page stays as a convenience. A basic fetch with X-HWID already makes a device in the panel; enrolling replaces it in the same slot.

Calls

Call Authorised by Purpose
POST <link>/client/enrol the token in the link; the old device key when re-enrolling makes this device with the key the client sends, returns base
GET <base>/sync device key the subscription in the Mistgate format; If-None-Match -> 304
POST <base>/leave device key this device removes itself
POST <link>/probe the token (as today) the detectors' report, v1, announced by Probe-Report: 1
POST <base>/debug device key a debug report, only when sync says debug.intake (VPS edition only)
POST <base>/debug/decline device key the person declines support's request

base is an absolute URL the panel returns from enrol (v1: <subscription prefix>/client, no token in it). The client never builds it. Reasons: rotating the link replaces the token but keeps devices; per-token fetch budgets are shared by all of a person's apps; a token in a path ends up in proxy logs.

enrol

<link> is the public subscription address with the token. Headers: Content-Type: application/json, the User-Agent and caps of every request, and when re-enrolling Authorization: Bearer <old device key>. Body: strict JSON, at most 4 KiB, unknown fields rejected (caps stay a header):

{ "hwid": "…", "platform": "windows", "model": "", "os_version": "11 24H2", "device_key": "<base64url, 32 bytes>" }
  • hwid: [A-Za-z0-9=-]{10,64}, random per install and per operator's panel (the client keys it by the origin of the subscription link: scheme, host and port, so it survives a rotated link), not derived from hardware; the same value basic mode sends as X-HWID. The client keeps it, with the device key, where a reinstall does not erase it.
  • platform: ios | android | windows | macos | linux | other. model: at most 40 characters, no control characters.
  • device_key: generated by the client. A key made by the panel was dropped: a lost answer left the device stuck behind device_exists.

200, with Cache-Control: no-store:

{ "device_id": "…", "base": "https://…/client", "sync_every_s": 3600 }

Idempotent: when the live device of this user with this hwid already holds exactly this device_key, the answer is the same device_id and nothing changes. So after a lost answer the client simply repeats the request, with or without Authorization.

  • Without Authorization: makes the device, or takes over the keyless basic-mode device of the same hwid (its old credentials are revoked, no extra slot). Budget: 5 such enrols per link per hour; a refused one (device_exists, device_limit, device_blocked, app_disabled) does not spend it, refusals are bounded by the link's write budget (20 an hour).
  • With the old key and a new device_key: the same device, the new key, credentials kept; the device follows a rotated link. Not counted in the budget. A key that is not a live device of this user with this hwid counts as no key.

Errors are {"error": "<code>"} with an optional "message"; the client branches on the code, not the status: 400 bad_request, 401 device_removed, 401 device_blocked (the key of a blocked device), 403 client_api_off, 403 cross_origin, 403 device_blocked (a blocked hwid, no key), 409 device_exists, 409 device_limit, 409 user_inactive (message: disabled | expired | limited), 409 app_disabled (none of the user's apps takes a link device), 413 too_large, 415 unsupported_media_type, 429 too_many_requests (Retry-After), 503 not_configured, 500 internal.

After enrolment a plain subscription fetch with this device's X-HWID gets a one-entry placeholder without servers. The client therefore does not enrol on a panel that has no sync yet. The operator's switch closes only discovery and new enrolments; enrolled devices keep working.

sync and leave: what they share

Both go to base and are authorised ONLY by Authorization: Bearer <device key>; there is no link token in the path. Besides the User-Agent and caps of every request the client may send X-Ver-OS (stored as the OS version) and X-Mistgate-Direct: 1, the latter only when the call is made OUTSIDE the tunnel. JSON answers carry Cache-Control: no-store. Errors are {"error": "<code>"}; the client branches on the code, not the status.

The panel answers in this order:

  1. A missing or malformed key, a wrong method, or a well-formed key nobody holds: the decoy (not JSON, normally 404). On sync and leave a decoy means "temporary error": the client NEVER forgets the key and never reads it as "removed"; it retries later with backoff. A well-formed key is always looked up, also from a network locked out by misses.
  2. The key is found (live or not): the budget is spent, 30 requests an hour per device (sync, leave and a 304 all count): 429 too_many_requests with Retry-After.
  3. 401 device_removed (removed on the page, by the admin, or by leave) and 401 device_blocked: the client stops and tells the user. Only device_removed means removed.
  4. sync only: 401 link_changed (the person's link was rotated since enrolment). The way out: POST <new link>/client/enrol with the old key as Bearer and a NEW device_key; the device keeps its slot and credentials. leave still works under link_changed.
  5. 403 cross_origin (a browser's Origin or Sec-Fetch-Site: cross-site; native clients send neither).
  6. 503 {"error": "retry"} with Retry-After: the key is valid, repeat after the delay and keep the key. 500 internal.

The operator's switch does not gate sync or leave (only discovery and enrolment).

sync

GET <base>/sync answers 200 with JSON and a strong ETag; a matching If-None-Match gets 304 with no body. The ETag covers the whole body except asn and changes with ANY data, including the used bytes and server load, so a 304 is rare for an active user: a new ETag is not a configuration change. The active tunnel is rebuilt only when the settings of its own path changed.

sync_every_s is the panel's choice (expect about an hour). Sync through the tunnel puts all users of a node behind one exit address: the client adds jitter and honours Retry-After. Side effects on the panel: the device is touched (last seen, the app version from the User-Agent, the OS version) at most once in 10 minutes, and missing credentials are issued (for example the AmneziaWG peer of a new profile).

The body (stable key order; the client ignores fields it does not know):

{
  "v": 1,
  "device_id": "dev_…",
  "status": "active|disabled|expired|limited",
  "sync_every_s": 3600,
  "brand": { "parts": ["Mist", "gate"], "accent": "#rrggbb", "logo_svg": "<svg…>" },
  "support_url": "https://…",
  "notice": { "id": "<sha256 hex of the text>", "text": "…" },
  "plan": { "expires_unix": 0, "quota_bytes": 0, "used_bytes": 0,
            "quota_reset": "none|day|week|month|rolling_month", "next_reset_unix": 0 },
  "probe": { "intake": true, "v": 1 },
  "debug": { "intake": false },
  "asn": 0,
  "dns": { "transport": "plain|dot|doh",
           "servers": [ { "transport": "plain|dot|doh", "address": "…", "ips": ["…"] } ],
           "split": [ { "suffixes": ["ru"], "geo": ["cn"], "servers": [ ] } ],
           "split_direct": false, "block_ads": false, "ipv4_only": false },
  "servers": [
    { "id": "srv_…", "country": "DE", "city": "Frankfurt", "load": "low|medium|high",
      "paths": [
        { "id": "pth_…", "protocol": "hysteria2|awg|vless|trusttunnel", "via": "direct|relay|warp", "ipv6": false, "settings": { } }
      ] }
  ]
}
  • v the client does not know is refused loudly.
  • brand.parts is one or two strings (the name, split for two-tone drawing); logo_svg may be empty and is drawn only as an image.
  • Absent when empty: support_url, notice, a server's load (unknown), asn, dns.
  • plan: expires_unix 0 = never; quota_bytes 0 = unlimited; next_reset_unix 0 = no reset period (only with quota_reset: "none"). The two are independent: a person without a quota still has a reset day, when used_bytes goes back to zero.
  • A server's country and city are empty when the operator set none for the node; the client then shows a number.
  • asn comes only with X-Mistgate-Direct: 1, on the VPS edition, when known. It is not stored by the panel, is not part of the ETag and is not on a 304.
  • dns is one object for the whole subscription. Server addresses: plain ip or ip:port, DoT host[:port], DoH a URL; ips are absent when unknown. split is empty unless split_direct; a rule names domain suffixes (lower-case punycode, no leading dot) and geo (country codes and geosite:<name> lists). A rule sends the questions of the names it names, when they go direct, to its plain resolver; it does not make a name direct. The tunnel's own questions go to the first DoH server of servers (its transport, else the preset's), when the person has set no DNS of their own and the path is not AmneziaWG: over TLS through the VPN, an https URL with no credentials, to the addresses in ips (else the host, if it is an IP, else its name asked once of the tunnel's DNS). When that resolver fails, the question goes through the VPN as before and the resolver rests for 30 s. DoT is not used. ipv4_only makes the client keep IPv6 off the paths. block_ads true makes the client drop the names of geosite:category-ads-all (loaded like any list, from the cache, downloaded when stale) before every other rule and in every route mode: their DNS questions are answered with no address; in smart and selected the name inside a flow is read as well. In all only the DNS questions are checked, so a program that does not ask the system's DNS gets nothing blocked there; AmneziaWG then also runs behind the client's forwarder. dns is absent when the status is not active or the panel has no usable preset.
  • servers is [] unless the status is active. With another status the answer is still 200, with the status, plan, brand, notice, probe and debug.
  • Ids are opaque and stable. A server is one exit node; its IPv6 entry and each relay are more paths of the same server. A server with no path this client can use is not listed.
  • IPv6 addresses in server (hysteria2) and endpoint.host (awg) are bare, without square brackets; the port is a separate field and the client joins them.
  • Never in the body: node names, the link, the token, the page address, other people, the HWID, the device key.

settings, the Mistgate shape per protocol:

  • hysteria2: { "server": "host", "port": 443, "ports": "20000-30000", "hop_interval_s": 30, "auth": "…", "tls": "ca|pin", "pin_sha256": "hex", "sni": "…", "alpn": ["h3"], "obfs": { "type": "salamander|gecko", "password": "…" } }. ports is absent without port hopping (hop_interval_s comes with it); pin_sha256 only with tls: "pin", and then the pin ALONE is the check; sni is absent for nodes known by address only; obfs is absent without obfuscation, and gecko is given only to caps with gecko=1. A relay path has the forwarded port and no ports. tls: "ca" without sni: the certificate must verify for server as dialled (a host name: that name, also as SNI; an address: its IP SAN, no SNI). Verification is never skipped for paths that come from this API. (A plain hysteria2:// link or Mihomo profile that asks for no verification, with no pin, is still taken as it asks.)

  • awg: { "version": "2.0|3.1", "endpoint": { "host": "…", "port": 0 }, "public_key": "…", "private_key": "…", "preshared_key": "…", "address_v4": "a.b.c.d/32", "address_v6": "…/128", "allowed_ips": ["0.0.0.0/0", "::/0"], "dns": ["ip", "ip"], "mtu": 1280, "keepalive_s": 25, "params": { } }. address_v6 is absent without IPv6; allowed_ips ALWAYS has both families: the client routes or blocks IPv6 even without an IPv6 address; keepalive_s is absent when the profile has none. params: jc, jmin, jmax, s1-s4 (integers), h1-h4 (strings, may be ranges), i1-i5 (strings, per device, absent when empty); for 3.1 only: header_protection_key, random_trailers (bool), disable_cookies, and as strings, only when the profile has them: content_padding_addition, rekey_after_time, rekey_timeout, reject_after_time, keepalive_timeout, max_handshake_attempts. A version is given only when caps list it (awg=2.0,3.1). When the operator switched AmneziaWG off for link apps, no awg paths are given.

  • vless (Xray): { "server": "host", "port": 443, "uuid": "…", "flow": "xtls-rprx-vision", "transport": "raw|xhttp|ws", "path": "/…", "host": "…", "mode": "auto|packet-up|stream-up|stream-one", "x_padding_bytes": "100-1000", "security": "reality|tls", "sni": "…", "fingerprint": "chrome", "public_key": "…", "short_id": "…", "spider_x": "/", "alpn": ["h2"] }. flow only with raw and reality; path and host (only when set) with xhttp and ws; mode and x_padding_bytes with xhttp only; public_key, short_id, spider_x with reality; alpn with tls, which is the ordinary certificate check (no pin, never skipped). The panel sends no gRPC and no mux (the client reads those only from other providers' links and profiles). The client reads these fields in one place (profile.ParseVLESS) and checks them: port, UUID form, public_key as 32 bytes of base64url, short_id as at most 8 bytes of hex, paths starting with / and free of spaces and control characters, names of DNS characters only. A transport, security, flow, mode or fingerprint it does not know makes the path unsupported (counted, not an error of the sync). The client gives Xray the server's address, never its name; sni and host are separate fields.

  • A path may carry "purpose": "whitelist" beside via (proposed by the client, not yet settled with the panel): a slow last-resort path for networks that pass only an allowlist. The client keeps it out of every automatic choice and shows it apart; any other value, or none, is an ordinary path.

  • trusttunnel (TrustTunnel, HTTP/2 over TLS): { "server": "address or name to connect to", "port": 443, "sni": "name", "username": "…", "password": "…", "transport": "h2|auto", "tls": "ca|pin", "pin_sha256": "64 hex" }. sni is required: it is the name sent and the name the certificate is checked against (server may be a relay's address). transport h2 and auto both mean HTTP/2 to this client. tls ca (or absent) is the ordinary certificate check; pin checks only the SHA-256 of the leaf certificate's DER against pin_sha256, as for Hysteria2; there is no mode without a check. username and password are opaque strings of the path (the panel issues them per device). Sent only to a client that announces trusttunnel=1. The client reads these fields in one place (profile.ParseTrustTunnelPath); an unknown transport or tls, a missing sni or a bad pin makes the path unsupported. The endpoint may answer a refused request with any status: everything but 200 is a refusal, and the client does not retry against an endpoint that refuses.

AmneziaWG keys. The panel generates the device's key pairs and delivers them in sync (the owner's ruling). A key the client makes itself would be a later capability.

leave

POST <base>/leave, no body. 200 {"ok": true}. Removes exactly this device and its peers; afterwards the key answers 401 device_removed (a second leave too). The client forgets the device key and the subscription.

probe: v1, as the panel takes it today

POST <link>/probe takes a report of the client's network check, and of what its Auto mode learned by itself (see "What Auto sends" below). <link> is the subscription link the person pasted (the token in it is the only authorisation; no page password, no device key). Headers: Content-Type: application/json, Probe-Report: 1, and the User-Agent and caps of every request. At most 128 KiB and 256 servers. The panel's owner has a switch for app reports (off by default, kept 7 days); sync says whether it is on (probe.intake) and which version the panel reads (probe.v). The report never relies on the request's address: the app states the ASN itself and says whether the check ran through the VPN (vpn, direct_checked).

Limits (the panel's): two reports at once, then one in 10 minutes per subscription (429 with Retry-After). The client keeps to one in 10 minutes per subscription and waits out a Retry-After. Answers: 200 {"accepted": N} (the servers the panel matched to the person's subscription by host and port; it drops the rest), 403 probe_off (the owner has not switched it on: the client sets probe.intake to false until the next sync), 403 cross_origin, 409 user_inactive, 413 too_large, 415, 400 bad_request, 429. The client sends nothing without the person's switch (report, off by default, per subscription), except when the person presses send by hand.

What the client sends. Only the fields the check measured; the parser refuses unknown ones, so the body is exactly:

{ "v": 1, "vpn": false, "direct_checked": true,
  "network": { "asn": 64500, "type": "mobile" },
  "servers": [ { "type": "hysteria2", "host": "oslo.example", "port": 443, "verdict": "ok", "delay_ms": 42 } ] }
  • v: 1. vpn: the VPN was up when the check began. direct_checked: true when the report has servers: every server in it was tried from the physical adapter, outside the tunnel (the live tunnel's own AmneziaWG path is not tried that way, so it is left out).
  • network.asn: the asn of the last sync, left out when the panel did not give one. The panel gives it only to a request that says X-Mistgate-Direct: 1, which the client sends only while the VPN is off (state off or error); a sync made through the tunnel brings none and keeps the one the last direct sync gave. network.type is mobile only for a mobile-broadband adapter; Wi-Fi and Ethernet could be a home or an office, so nothing is said. operator, country and region are never sent: the client does not know them.
  • servers: one per path of the subscription that the check could judge, type the path's protocol (hysteria2, awg, vless), host (lower case) and port as the profile of the path has them, as the subscription gave them. delay_ms: the handshake's round trip, only for ok and when it is a millisecond or more. Not sent, because the client has no honest value: flaky, tcp_ok, tcp_tries, tcp_ms, dl_bytes and dns (its DNS check asks about blocked sites, not the servers' names). dl_stalled is not sent from a network check either (its freeze check downloads from foreign sites, not from the servers); only Auto's findings carry it.
The client's check verdict
ok ok
blocked, udp_no_answer (Hysteria2 or AmneziaWG: the host answers on TCP, the handshake gets nothing) handshake_failed
down, no_answer (nothing answers: no handshake, no TCP) no_answer
blocked, no_answer (VLESS: a cut TCP connect and a failed handshake look the same) left out
down, not_found (the client could not resolve the name), config (auth_rejected, bad_config), app left out

A network check never produces freeze or tcp_blocked: it has no per-server freeze test and no TCP-only probe. A path that reaches the node through a relay (via: relay) is left out too: its host and port are the relay's, and the panel would match them to the wrong server. A check older than 24 hours is not sent. The report holds the subscription's paths only; the rest of the check (route hops, UDP and NAT, DNS, foreign sites) stays on the machine. (The network.asn above is the last direct sync's, which may be another network than the check's; Auto's reports below check that.)

What Auto sends. While the tunnel is up on a path that Auto picked (not one the person named), about once an hour (70 to 130 % of an hour, by chance), under the same per-subscription switch and the same panel consent (probe.intake), the client sends what Auto's memory of the current network holds, in the same body. The panel counts reports, not events, so every finding goes once: the client keeps in memory, per path, what it sent and when. Nothing goes when there is no line. One line per path of the subscription (relay and allowlist paths are left out, at most 256):

  • verdict: "freeze", dl_stalled: true: the session's own check downloaded 128 KiB through this server, from the person's network, and the connection started and then carried nothing. Once for each new freeze mark of the path (an older one that was already sent is not sent again, whatever its age under 24 hours; one that a later passed check cancelled is not sent). No dl_bytes (the client does not keep it) and no delay_ms (this check goes through the tunnel).
  • verdict: "ok", delay_ms: the handshake's round trip outside the tunnel, noted by Auto at a success that is under an hour old and followed by no failure. Once for a success newer than the one sent, and at most once in 24 hours for a path (right away after a freeze line). dl_stalled: false is added when the data check of the path passed in this network within 24 hours (and after any freeze mark); when no check was made the field is left out. Both marks come from the same session check as above.
  • A path that failed, or sits in Auto's quarantine, is not sent: Auto makes no TCP probe, so it cannot say honestly whether the host answers (handshake_failed) or nothing does (no_answer). It would take a TCP probe, or a verdict in this contract for "the path failed to carry a connection".
  • vpn: true. direct_checked: true whenever there are lines: it means that the checks were made from the person's own network and not from under someone else's VPN. The handshakes leave from the physical adapter, and the data check goes through the server itself, over the person's network.
  • network.asn only when the panel gave it in this very network: the client notes which network (the same opaque hash that Auto's memory uses) the device was in when a direct sync brought the ASN, and puts it in only when the current network is that one. network.type is mobile or left out, as above.
  • A report the panel did not accept (429 and the rest, with its Retry-After) is not counted as sent; the same line goes at the next tick the limits allow. The client makes no quick retry. A restart of the service forgets what was sent, so the first report after it may repeat ok lines.

The service log gets a fact and a code, never the link, a host, the ASN or the body. The window shows the person the exact body first (report.preview, see ipc.md, "Block reports").

X-Mistgate-Caps does not list probe=1 yet (the panel does not ask for it: it announces reports with the Probe-Report: 1 header and sync's probe).

A v2 with the client's wider check (route hops, UDP and NAT, DNS, foreign sites, the client's verdict names) is deferred: the panel has no storage or admin view for it.

debug

sync carries "debug": {"intake": true, "unasked": true, "request": {"id": "dbr_…", "level": "info|debug", "note": "…", "expires_unix": 0}}. unasked is present only when the person may send on their own; request only while support's request is open. The edge edition answers {"intake": false} and takes nothing. The client offers nothing without intake.

POST <base>/debug: Authorization: Bearer <device key>, Content-Type: application/x-ndjson, Content-Encoding: gzip (required), and X-Mistgate-Debug-Request: dbr_… when it answers a request (absent: the person's own send). The body is one JSON object per line: {"ts": <unix ms>, "lvl": "debug|info|warn|error", "src": "<^[a-z][a-z0-9_-]{0,31}$>", "msg": "…", "kv": {"k": "v"}}. ts, lvl, src and msg are required; kv is optional, string values only, at most 16 keys; an unknown top-level field is a 400. The panel keeps a line of at most 8192 bytes, msg up to 1024 bytes, and of kv only path, server, protocol, via, engine, phase, state, reason, code, err, mode, version, count, ms, bytes, attempt, net, event, status, http (values up to 160 characters). Limits: 1 MiB on the wire, 4 MiB and 20000 lines unpacked, ts within now-30 days..now+1 day. The client builds the bundle (system, checks and log parts and the person's note), scrubs it again, and shows it to the person before sending.

Answers: 200 {"id": "dbr_…", "lines": N, "dropped_kv": M} (200 again for a request already answered); a decoy for an unknown key; 429 too_many_requests; 401 device_removed|device_blocked|link_changed; 403 cross_origin; 403 debug_off; 415; 413 too_large; 409 no_request|user_inactive|app_disabled; 429 with Retry-After (an own send more often than once per 10 minutes, a delivery in progress, or too many attempts); 503 debug_full; 503 with Retry-After: 30; 400 bad_request. Error bodies are the usual {"error": "<code>"}.

POST <base>/debug/decline with the same Authorization and request header and no body: 200 {"id": "dbr_…", "declined": true} or 409 no_request.

What changes in the client meanwhile

  • Basic mode against a Mistgate panel: the client announces itself as a Mihomo client and reads the Mihomo profile (Hysteria2 with Gecko and port ranges, AmneziaWG), see docs/ipc.md. That is the stopgap until this API is live.
  • The ASN for a report comes from sync (X-Mistgate-Direct: 1, outside the tunnel), never from a third-party service. The client sends the header only when the session is off or error (not in connecting, connected, reconnecting or blocked), so the ASN is as old as the last sync made with the VPN off.
  • hwid must become per operator's panel and survive a reinstall (today it is one per install).
  • The client's own network check maps to report v1 only in part (see "probe: v1"); the rest waits for v2.

Not in v1

Client-held AmneziaWG keys, report v2, debug intake on the edge edition, managing the user's other devices from the client (that needs the page password), mirrors of the panel's address, per-network tactics.