openapi: 3.1.0 info: title: Okojo Gateway Control API version: "1.0.0" summary: The published interface between an Okojo client and a self-hosted Gateway. description: | This is the interoperability contract required by DEV-010. The Gateway Manager implementation stays proprietary; this document is the narrow, versioned surface published so that another client can be written against a Gateway, and so that the boundary between the proprietary Manager and the GPL traffic process can be reviewed without reading either. ## What this API is not It carries no user traffic. Its read-only traffic observability endpoint returns a bounded, redacted view of the local runtime and never forwards packets. It never returns a Provider URL or an ordinary outbound credential. The one bounded exception is a Home profile returned to the same paired device while its provision/rotation transaction is pending: that response contains only the newly derived credentials for that device's selected service-owned Home listeners. Confirmed profiles are never readable again. A Home invitation QR carries an opaque, short-lived claim token and public Gateway identity binding only; it never carries a Home credential, browser-session credential, or reusable device credential. The API cannot reach the traffic process directly. ## Binding Loopback by default. Serving this on a private network is a separate, explicit decision (ADR 0013), because it changes who can reach a machine that controls a household's traffic. ## Versioning `contractVersion` is returned by `/v1/capabilities` and in the `X-Okojo-Contract` header on every response. Fields may be added without a bump. Anything that would break an existing client bumps the major version and moves the path prefix. A client should read capabilities first and degrade or refuse against a Manager it does not understand, rather than assuming a feature is present. license: name: Contract published for interoperability url: https://okojo.app/contracts servers: - url: http://127.0.0.1:{port}/ description: Loopback, the default and only unconfigured binding. variables: port: default: "48765" tags: - name: discovery description: Reachable without pairing. Reveals nothing about configuration. - name: pairing description: Establishing device authority. - name: configuration description: Reading configuration and driving the apply transaction. - name: activity description: Read-only, redacted local Gateway activity. - name: safety description: Operations that must never be blocked by entitlement. - name: home-invitations description: | One-time Home invitations created through an authenticated WebUI session and redeemed only by an already paired native device. security: - deviceCredential: [] paths: /v1/capabilities: get: tags: [discovery] operationId: getCapabilities security: [] summary: What this Gateway is and what it can do. description: | Deliberately unauthenticated. A device that is not paired yet has to be able to learn whether it is talking to a Manager it understands before it can pair. It returns nothing about how the Gateway is configured. responses: "200": description: Capability description. content: application/json: schema: $ref: "#/components/schemas/Capabilities" /v1/health: get: tags: [discovery] operationId: getHealth summary: Current Gateway state. description: | Reconciles any expired confirmation window before answering, so a deadline that passed while nothing was talking to the Manager is reflected here rather than reported as still pending. responses: "200": description: Health snapshot. content: application/json: schema: $ref: "#/components/schemas/Health" "401": $ref: "#/components/responses/Unauthorized" "503": description: The traffic runtime is unavailable or unhealthy. content: application/json: schema: $ref: "#/components/schemas/Error" /v1/traffic: get: tags: [configuration] operationId: getTrafficSnapshot summary: Read a bounded, redacted traffic dashboard snapshot. description: | Read-only and available to every paired device. The Manager reads Mihomo's local `/traffic` and `/connections` endpoints, keeps trend samples in memory only, and returns only current rates, totals, active destination/node labels, protocol, duration, and aggregate shares. Source addresses, process names, matched rules, Provider URLs, and raw Controller data never cross this boundary. The trend is empty or short after a restart because it is intentionally not persisted. responses: "200": description: Current rates, in-memory trend, and bounded aggregates. content: application/json: schema: $ref: "#/components/schemas/TrafficSnapshot" "401": $ref: "#/components/responses/Unauthorized" "503": $ref: "#/components/responses/RuntimeUnavailable" /v1/providers/health: get: tags: [configuration] operationId: getProviderHealth summary: Read live Provider and node health evidence from Mihomo. description: | Read-only. This returns only the health state and latest delay already held by Mihomo for each Provider node. It does not trigger a health check or return Provider URLs, server addresses, or credentials. A node with no recorded evidence is explicitly `untested`. responses: "200": description: Bounded live Provider health snapshot. content: application/json: schema: $ref: "#/components/schemas/ProviderHealthSnapshot" "401": $ref: "#/components/responses/Unauthorized" "503": $ref: "#/components/responses/RuntimeUnavailable" /v1/providers/refresh: post: tags: [configuration] operationId: refreshProvider summary: Refresh one allowlisted Provider through Mihomo. description: | Pro only. The Provider must already belong to the Manager-owned configuration. The Manager sends only its stable name to Mihomo's local Controller and never fetches or returns the Provider URL itself. A failed fetch leaves configuration unchanged and Mihomo keeps its last good Provider copy. requestBody: required: true content: application/json: schema: type: object additionalProperties: false required: [providerName] properties: providerName: type: string minLength: 1 maxLength: 256 responses: "200": description: Mihomo accepted and completed the refresh. content: application/json: schema: type: object additionalProperties: false required: [providerName, refreshedAt] properties: providerName: type: string refreshedAt: type: string format: date-time "400": $ref: "#/components/responses/Unsupported" "401": $ref: "#/components/responses/Unauthorized" "402": $ref: "#/components/responses/ProRequired" "409": $ref: "#/components/responses/Conflict" "503": $ref: "#/components/responses/RuntimeUnavailable" /v1/providers/structure: post: tags: [configuration] operationId: previewProviderStructure summary: Preview compatible structure in one managed Provider cache. description: | Pro only and read-only. The Provider must already belong to the Manager-owned configuration. The Manager reads only that Provider's bounded cached file from Mihomo's fixed working directory; it does not fetch the Provider URL. The response contains compatible policy-group, referenced rule-set and DNS structure for an adoption review. It never returns the Provider URL, proxy endpoints, credentials or source bytes. Rule-set URLs are returned because accepting a rule set necessarily persists its fetch source in the reviewed configuration transaction. requestBody: required: true content: application/json: schema: type: object additionalProperties: false required: [providerName] properties: providerName: type: string minLength: 1 maxLength: 256 responses: "200": description: Compatible bounded structure ready for user review. content: application/json: schema: $ref: "#/components/schemas/ProviderStructure" "400": $ref: "#/components/responses/BadRequest" "401": $ref: "#/components/responses/Unauthorized" "402": description: Okojo Pro is required to inspect managed Provider structure. "503": $ref: "#/components/responses/RuntimeUnavailable" /v1/pair: post: tags: [pairing] operationId: pairDevice security: [] summary: Exchange a one-time code for a device credential. description: | The code is short lived and single use, generated on the Gateway itself. Every failure returns one identical response. A wrong code, an expired code, a reused code, and a code that hit the attempt limit are not distinguishable, because telling them apart would let the code space be searched with feedback. The credential is returned exactly once, in this response, and is never echoed by any other endpoint. requestBody: required: true content: application/json: schema: $ref: "#/components/schemas/PairRequest" responses: "200": description: Paired. Store the credential in the platform keychain. content: application/json: schema: $ref: "#/components/schemas/PairResponse" "403": description: Refused. Indistinguishable across all pairing failures. content: application/json: schema: $ref: "#/components/schemas/Error" /v1/config: get: tags: [configuration] operationId: getConfig summary: The managed configuration this Gateway will act on. description: | Returns policy groups, their allowlisted members, and the current selection. It does not return Provider sources, node addresses, or any credential. responses: "200": description: Configuration snapshot. content: application/json: schema: $ref: "#/components/schemas/ConfigSnapshot" "401": $ref: "#/components/responses/Unauthorized" /v1/config/adoption-preview: get: tags: [configuration] operationId: getConfigurationAdoptionPreview summary: Assess an existing Mihomo configuration without changing it. description: | This is a read-only inventory for an operator-authored configuration. It returns only a redacted impact summary: counts, Okojo model sections that require re-entry, and stable blockers. It never returns raw YAML, credentials, Provider URLs, node endpoints, rule payloads, or local paths. `ready` means a guided review may begin; it is not an adoption transaction and changes neither files nor runtime. responses: "200": description: Redacted no-write adoption assessment. content: application/json: schema: $ref: "#/components/schemas/ConfigurationAdoptionPreview" "401": $ref: "#/components/responses/Unauthorized" /v1/entitlement: get: tags: [configuration] operationId: getGatewayEntitlement summary: Current offline Gateway feature tier. responses: "200": description: Free or verified Pro state for this Manager identity. content: application/json: schema: $ref: "#/components/schemas/EntitlementStatus" "401": $ref: "#/components/responses/Unauthorized" /v1/config/preview: post: tags: [configuration] operationId: previewSelection summary: Validate and diff a draft selection without mutation. description: | Free and Pro may call this. It writes no file, changes no runtime policy, reloads no service, and creates no durable history entry. requestBody: required: true content: application/json: schema: $ref: "#/components/schemas/SelectRequest" responses: "200": description: Bounded non-mutating diff. content: application/json: schema: $ref: "#/components/schemas/SelectionPreview" "400": $ref: "#/components/responses/BadRequest" "401": $ref: "#/components/responses/Unauthorized" /v1/entitlement/activate: post: tags: [configuration] operationId: activateGatewayEntitlement summary: Install a vendor-signed license already verified from a store purchase. description: | The native App sends only the vendor-signed Gateway license bound to this Manager key. Raw App Store transactions and Google Play purchase tokens never enter the Manager or WebUI. requestBody: required: true content: application/json: schema: $ref: "#/components/schemas/EntitlementActivation" responses: "200": description: Verified and stored locally. content: application/json: schema: $ref: "#/components/schemas/EntitlementStatus" "400": description: Signature, product, time, or Manager binding was invalid. content: application/json: schema: $ref: "#/components/schemas/Error" "401": $ref: "#/components/responses/Unauthorized" /v1/policies/select: post: tags: [configuration] operationId: selectPolicy summary: Change the active member of a policy group at runtime. description: | A runtime change with no persistent write and therefore no confirmation window. The group and member must both be allowlisted by the stored configuration; anything else is refused without touching the runtime. Free on every Gateway (COM-025): it chooses among members the stored configuration already allows and writes no file, and switching away from a failing node is recovery. While the operator still owns Mihomo's configuration (ADR 0022), a group the stored model does not list is also accepted when the live runtime reports it exactly once as a `Selector` whose members include the choice, the same switch a Mihomo dashboard makes. Groups Mihomo chooses itself (url-test, fallback) are not targets there. A signed-in WebUI session reaches this too. Saving a choice as the stored default goes through `/v1/transactions/apply`, a configuration write that needs Gateway Pro. A manual choice also hands the group back from steadier node switching, which stays Pro. requestBody: required: true content: application/json: schema: $ref: "#/components/schemas/SelectRequest" responses: "200": description: Applied. content: application/json: schema: $ref: "#/components/schemas/SelectRequest" "400": $ref: "#/components/responses/BadRequest" "401": $ref: "#/components/responses/Unauthorized" "503": $ref: "#/components/responses/RuntimeUnavailable" /v1/policies/probe: post: tags: [configuration] operationId: probePolicyTarget summary: Measure one allowlisted policy group or proxy through Mihomo. description: | Read-only. The target must be a policy group or proxy name present in the stored Gateway configuration. Mihomo performs the request through that target and returns the delay it observed; the Manager never dials the test URL itself. The test URL is not echoed in the response. requestBody: required: true content: application/json: schema: $ref: "#/components/schemas/ProbeRequest" responses: "200": description: Mihomo completed the latency test. content: application/json: schema: $ref: "#/components/schemas/LatencyProbeResult" "400": $ref: "#/components/responses/BadRequest" "401": $ref: "#/components/responses/Unauthorized" "503": $ref: "#/components/responses/RuntimeUnavailable" /v1/browsers/decide: post: tags: [pairing] operationId: decideBrowserSignIn summary: Approve or refuse a browser that is waiting to sign in. description: | A browser on the Manager's own WebUI asks to sign in and displays six digits. A paired device answers here, and the browser then collects the session it was granted. The code is typed from the browser's own screen rather than chosen from a list of waiting requests: approving whichever request appears would approve one the person is not looking at. Only a paired device may decide, so the code binds an approval to a screen rather than acting as a secret against the network. A refusal is carried rather than left as silence, so a browser that was told no stops asking instead of waiting out its window. Wrong codes are spent against the open requests, and a request whose attempts run out is closed. `404` answers both a code nobody is showing and one whose window has closed, because telling them apart would tell a caller which codes exist. requestBody: required: true content: application/json: schema: $ref: "#/components/schemas/BrowserDecisionRequest" responses: "200": description: Recorded. `approved` echoes the decision that was taken. content: application/json: schema: $ref: "#/components/schemas/BrowserDecisionResponse" "400": $ref: "#/components/responses/BadRequest" "401": $ref: "#/components/responses/Unauthorized" "404": $ref: "#/components/responses/NotFound" /v1/transactions/apply: post: tags: [configuration] operationId: applyChange summary: Write a change and start the confirmation window. description: | The change is validated, backed up, written, and reloaded. It is then live but **not committed**. If `confirm` does not arrive before `confirmBy`, the Gateway rolls itself back. That window is the protection for a user who has just cut their own remote access: they do not have to do anything to recover, and a client that has lost contact cannot leave a Gateway stranded in a state nobody chose. Only one transaction may be in flight. A second is refused rather than queued, because queueing writes to a live traffic configuration is not something a user can reason about. requestBody: required: true content: application/json: schema: $ref: "#/components/schemas/ApplyRequest" responses: "200": description: Applied and awaiting confirmation. content: application/json: schema: $ref: "#/components/schemas/Transaction" "400": $ref: "#/components/responses/BadRequest" "401": $ref: "#/components/responses/Unauthorized" "409": description: Another transaction is already awaiting confirmation. content: application/json: schema: $ref: "#/components/schemas/Error" "503": $ref: "#/components/responses/RuntimeUnavailable" /v1/config/check: post: tags: [configuration] operationId: checkConfiguration summary: Validate and summarize a whole configuration without applying it. description: | Runs the bounded compiler plus both Manager and Mihomo validation paths, then returns only the changed section names and a revision token. It does not persist the draft, reload Mihomo, or change traffic. The token can be sent to `/v1/config/apply` so an intervening edit is refused. Available only when `configurationAuthority.mode` is `manager`. This endpoint never adopts an operator-owned configuration. requestBody: required: true content: application/json: schema: $ref: "#/components/schemas/CheckConfigurationRequest" responses: "200": description: Validated without changing the Gateway. content: application/json: schema: $ref: "#/components/schemas/ConfigurationPreview" "400": $ref: "#/components/responses/BadRequest" "401": $ref: "#/components/responses/Unauthorized" "409": description: Another transaction is awaiting confirmation. content: application/json: schema: $ref: "#/components/schemas/Error" "503": $ref: "#/components/responses/RuntimeUnavailable" /v1/config/adopt: post: tags: [configuration] operationId: adoptConfiguration summary: Adopt the reviewed operator configuration with timed recovery. description: | Requires a paired device, Pro, locally configured compiler inputs and operator-owned configuration. Rebuilds the candidate locally and checks sourceRevision, candidateRevision and the exact reviewed serviceChanges from adoption-preview before starting the normal configuration transaction. No raw configuration or model is accepted. Confirm or roll back using the existing transaction endpoints; an unconfirmed deadline restores the original files and operator ownership. requestBody: required: true content: application/json: schema: type: object additionalProperties: false required: [sourceRevision, candidateRevision, serviceChanges, confirmSeconds] properties: sourceRevision: type: string pattern: '^[a-f0-9]{64}$' candidateRevision: type: string pattern: '^[a-f0-9]{64}$' serviceChanges: type: array uniqueItems: true items: type: string confirmSeconds: type: integer minimum: 1 maximum: 300 responses: "200": description: Transaction outcome; waiting-confirmation requires confirmation after reconnecting. A failed activation may already be rolled back. content: application/json: schema: $ref: "#/components/schemas/Transaction" "400": description: Invalid or unreviewed configuration; raw validator diagnostics are withheld. "401": $ref: "#/components/responses/Unauthorized" "402": description: Pro required. "409": description: Stale review or another pending transaction. "503": description: Runtime validation or reload unavailable. /v1/config/apply: post: tags: [configuration] operationId: applyConfiguration summary: Write a whole configuration and start the confirmation window. description: | The same transaction as `/v1/transactions/apply`, with a different blast radius. That one moves a selection inside an allowlist the operator wrote; this one hands over the file that decides where every packet on the machine goes. Available only where `/v1/capabilities` reports `ownsConfiguration`. A Gateway whose operator kept its configuration refuses this, and that is the correct answer rather than an error to work around. **Credentials the client was never shown come back as the marker it was given.** A configuration read from `/v1/config` is redacted; sending it back with those markers intact means keep the values this Gateway already has. Any other value replaces them. A marker that matches nothing stored — a new entry, or one renamed while asking to keep its password — is refused rather than left empty, because an outbound with no credential saves, compiles and never connects. A refusal carries every fault at once in `faults`, so whoever is fixing one does not discover the next on the following round trip. Clients that first called `/v1/config/check` send its `baseRevision`; a mismatch is refused before either configuration file is written. requestBody: required: true content: application/json: schema: $ref: "#/components/schemas/ApplyConfigurationRequest" responses: "200": description: Applied and awaiting confirmation. content: application/json: schema: $ref: "#/components/schemas/Transaction" "400": description: | The configuration was refused and nothing was changed. `faults` lists every reason. content: application/json: schema: $ref: "#/components/schemas/Error" "401": $ref: "#/components/responses/Unauthorized" "402": description: Okojo Pro is required to change a Gateway's configuration. content: application/json: schema: $ref: "#/components/schemas/Error" "409": description: | Another transaction is awaiting confirmation, or the configuration changed after the supplied preview revision. content: application/json: schema: $ref: "#/components/schemas/Error" "503": $ref: "#/components/responses/RuntimeUnavailable" /v1/home: get: tags: [configuration] operationId: getHomeStatus summary: Report this device's Home access without returning credentials. responses: "200": description: Redacted Home status. content: application/json: schema: $ref: "#/components/schemas/HomeStatus" "401": $ref: "#/components/responses/Unauthorized" /v1/home/provision: post: tags: [configuration] operationId: provisionHome summary: Create this device's selected-transport Home profile. description: | Pro only. The Manager derives separate credentials for each requested Home transport, writes identity and traffic state in one rollback transaction, reloads Mihomo, and returns exactly one or more configured proxies while the transaction is pending. Repeating the same idempotency key returns the same pending profile; a confirmed profile is never readable again. requestBody: required: true content: application/json: schema: $ref: "#/components/schemas/HomeChangeRequest" responses: "200": description: Live, awaiting confirmation through both transports. content: application/json: schema: $ref: "#/components/schemas/HomeProfile" "401": $ref: "#/components/responses/Unauthorized" "402": description: Okojo Pro is required. content: application/json: schema: $ref: "#/components/schemas/Error" "409": description: Home already exists or another transaction is pending. content: application/json: schema: $ref: "#/components/schemas/Error" "503": $ref: "#/components/responses/RuntimeUnavailable" /v1/home/rotate: post: tags: [configuration] operationId: rotateHome summary: Replace this device's selected Home credentials as one pending transaction. requestBody: required: true content: application/json: schema: $ref: "#/components/schemas/HomeChangeRequest" responses: "200": description: Rotated profile, awaiting confirmation through every selected transport. content: application/json: schema: $ref: "#/components/schemas/HomeProfile" "401": $ref: "#/components/responses/Unauthorized" "402": description: Okojo Pro is required. content: application/json: schema: $ref: "#/components/schemas/Error" "409": description: Home is absent or another transaction is pending. content: application/json: schema: $ref: "#/components/schemas/Error" "503": $ref: "#/components/responses/RuntimeUnavailable" /v1/home/confirm: post: tags: [configuration] operationId: confirmHome summary: Confirm that this device used every pending Home transport. requestBody: required: true content: application/json: schema: $ref: "#/components/schemas/HomeConfirmRequest" responses: "200": description: The exact selected transport set was confirmed and the transaction committed. content: application/json: schema: type: object required: [confirmed] properties: confirmed: type: boolean "400": $ref: "#/components/responses/BadRequest" "401": $ref: "#/components/responses/Unauthorized" /v1/home/revoke: post: tags: [safety] operationId: revokeHome summary: Remove all of this device's Home credentials while keeping device control access. description: | Free safety operation. Success is returned only after the listener user maps without this device have reloaded and Mihomo is healthy. Revoking the final user for a listener removes that listener. requestBody: required: true content: application/json: schema: type: object additionalProperties: false responses: "200": description: This device's Home credentials were removed. content: application/json: schema: type: object required: [revoked] properties: revoked: type: boolean "401": $ref: "#/components/responses/Unauthorized" "409": description: Home is absent or another transaction is pending. content: application/json: schema: $ref: "#/components/schemas/Error" /v1/home/invitations: post: tags: [home-invitations] operationId: createHomeInvitation summary: Create a one-time Home invitation for display by the WebUI. description: | Pro only. This route is not available to arbitrary browser code. The WebUI may proxy it only after same-origin, CSRF and its short-lived HttpOnly session checks, then substitutes that session's paired-device credential at the native API boundary. The QR payload contains an opaque claim token, public Gateway identity binding, expiry and the selected transports; it contains no Home profile credentials. Creating an invitation neither provisions a device nor opens a Home listener. It is redeemable only by an already paired native device on this same Gateway. The Manager stores only a hash of the token, expires it without use, and records the selected transport set durably. requestBody: required: true content: application/json: schema: $ref: "#/components/schemas/HomeInvitationCreateRequest" responses: "200": description: A short-lived QR payload ready to render locally. content: application/json: schema: $ref: "#/components/schemas/HomeInvitation" "401": $ref: "#/components/responses/Unauthorized" "402": description: Okojo Pro is required to create a Home invitation. content: application/json: schema: $ref: "#/components/schemas/Error" "409": description: Another Home transaction prevents safe invitation creation. content: application/json: schema: $ref: "#/components/schemas/Error" "503": $ref: "#/components/responses/RuntimeUnavailable" /v1/home/invitations/claim: post: tags: [home-invitations] operationId: claimHomeInvitation summary: Redeem a one-time Home invitation on this paired device. description: | Native paired-device authentication is required. Scanning this QR never pairs a device, grants Gateway management authority, or admits a browser. The first valid redemption binds the invitation to the caller's device identity, creates one rollback-capable pending Home transaction for exactly the QR's transport set, and returns its secret profile only to that same device. If the response is lost, the same bound device may retry the token with the same idempotency key and receives the same still-pending transaction/profile rather than another credential generation. A different device, an expired token, a spent token after completion, or an invalid token receives no oracle that distinguishes those cases. Clients must validate every selected transport and atomically install local nodes before confirming the exact set with `/v1/home/confirm`. Expiry, abort, or missing confirmation rolls the remote transaction back. requestBody: required: true content: application/json: schema: $ref: "#/components/schemas/HomeInvitationClaimRequest" responses: "200": description: The bound device's pending Home profile. Never cache or log it. content: application/json: schema: $ref: "#/components/schemas/HomeProfile" "400": $ref: "#/components/responses/BadRequest" "401": $ref: "#/components/responses/Unauthorized" "402": description: Okojo Pro is required to redeem a Home invitation. content: application/json: schema: $ref: "#/components/schemas/Error" "409": description: The invitation cannot be claimed or its Home transaction is no longer pending. content: application/json: schema: $ref: "#/components/schemas/Error" "503": $ref: "#/components/responses/RuntimeUnavailable" /v1/transactions/confirm: post: tags: [configuration] operationId: confirmChange summary: Commit a change that is awaiting confirmation. requestBody: required: true content: application/json: schema: $ref: "#/components/schemas/ConfirmRequest" responses: "200": description: Committed. content: application/json: schema: type: object properties: confirmed: type: boolean const: true "401": $ref: "#/components/responses/Unauthorized" "409": description: | No longer awaiting confirmation. It may have rolled back already. content: application/json: schema: $ref: "#/components/schemas/Error" /v1/transactions/rollback: post: tags: [safety] operationId: rollbackChange summary: Undo a pending change now, without waiting for the deadline. description: | A **safety operation**. It requires only a paired device and never consults entitlement, so it still works for a device that did not make the change and for one whose licence has lapsed. The automatic deadline covers the user who walked away. This covers the user who is watching, sees the change was wrong, and wants out immediately — the more urgent case, because they may be about to lose the access they are watching through. Omit `transactionId` to roll back whatever is pending, which is what a recovery control needs. Supply it to be certain a stale client does not roll back a newer change it has never seen. requestBody: required: false content: application/json: schema: $ref: "#/components/schemas/RollbackRequest" responses: "200": description: Rolled back. The previous configuration is live again. content: application/json: schema: $ref: "#/components/schemas/Transaction" "401": $ref: "#/components/responses/Unauthorized" "404": description: Nothing is waiting to be rolled back. content: application/json: schema: $ref: "#/components/schemas/Error" /v1/transactions/pending: get: tags: [configuration] operationId: getPendingTransaction summary: The transaction awaiting confirmation, if any. responses: "200": description: | `pending` is null when nothing is awaiting confirmation. A confirmed or rolled-back transaction is not pending. content: application/json: schema: type: object properties: pending: oneOf: - $ref: "#/components/schemas/Transaction" - type: "null" "401": $ref: "#/components/responses/Unauthorized" /v1/history: get: tags: [configuration] operationId: listHistory summary: Recent configuration changes, newest first. description: | Read-only, and not gated on entitlement. Seeing what changed is how a user decides whether they need to recover, and safety and recovery operations are never paywalled. Backup locations and configuration hashes are deliberately not returned, matching the pending-transaction response. Paths are Gateway filesystem detail; hashes are a verifier for configuration content. A client deciding whether to recover needs what changed and how it resolved, not a digest of a file it cannot read. responses: "200": description: | Up to 50 entries. `outcome` is `applied` while a change is live but not yet resolved, then `waiting-confirmation`, `confirmed`, or `rolled-back`. A client must not treat the newest entry as the configuration currently in force without reading its outcome. content: application/json: schema: type: object properties: changes: type: array items: type: object properties: transactionId: { type: string } appliedAt: { type: string, format: date-time } deviceId: type: string description: Which paired device made the change. group: { type: string } member: { type: string } outcome: type: string enum: [applied, waiting-confirmation, confirmed, rolled-back, rollback-failed] "401": $ref: "#/components/responses/Unauthorized" /v1/activity: get: tags: [activity] operationId: listActivity summary: Recent local Gateway activity, newest first. description: | Read-only and available to every paired device. This is a bounded view of the Gateway's local append-only audit log: pairing, browser approval, device administration, entitlement, policy measurements and configuration transaction outcomes. Device identifiers, device names, policy targets, transaction IDs, configuration contents, credentials and pairing codes deliberately do not cross this boundary. The same details remain available only to the operator on the Gateway where they were recorded. responses: "200": description: Up to 50 redacted activity events. content: application/json: schema: type: object properties: events: type: array items: type: object properties: occurredAt: { type: string, format: date-time } action: type: string description: Stable local audit action code. result: type: string description: Outcome recorded for that action. "401": $ref: "#/components/responses/Unauthorized" components: securitySchemes: deviceCredential: type: http scheme: Okojo-Device description: | `Authorization: Okojo-Device :` Issued by `/v1/pair` and stored in the platform keychain. A missing, malformed, or wrong credential all produce the same 401, so a caller cannot learn which part was wrong. responses: Unauthorized: description: | This device is not authorised. Identical for missing, malformed, and wrong credentials. content: application/json: schema: $ref: "#/components/schemas/Error" BadRequest: description: | The request could not be read, or named something this Gateway does not manage. Unknown fields are refused rather than ignored, so a client built against a newer contract fails here instead of having part of its request silently dropped. content: application/json: schema: $ref: "#/components/schemas/Error" NotFound: description: | Nothing here answers to what the request named. Used where saying more would be an oracle: a browser sign-in code that is wrong and one whose window has closed answer identically, because distinguishing them would tell a caller which codes exist. content: application/json: schema: $ref: "#/components/schemas/Error" RuntimeUnavailable: description: | The traffic process is not responding. Nothing was changed. content: application/json: schema: $ref: "#/components/schemas/Error" schemas: Capabilities: type: object required: [contractVersion, runtime, policySelection, configValidation, reload, managerKeyHash, proxyProtocols] properties: contractVersion: type: integer description: Read this first and degrade or refuse rather than assuming. examples: [1] runtime: type: string description: | Identifier of the traffic process behind this Manager. Reported so a client can explain a missing capability, never so it can address the traffic process directly. policySelection: type: boolean configValidation: type: boolean reload: type: boolean providerHealth: type: boolean description: Whether live Provider health evidence can be read. homeAccess: $ref: "#/components/schemas/HomeAccessCapability" dns: $ref: "#/components/schemas/DNSCapability" managerKeyHash: type: string pattern: "^[0-9a-f]{64}$" description: Confirm this identity before requesting a bound Gateway license. proxyProtocols: type: array minItems: 1 uniqueItems: true description: | Credential-free graphical-entry schema exported by the same compiler used for validation and persistence. Clients must render this list instead of maintaining a separate protocol allowlist. items: $ref: "#/components/schemas/ProxyProtocolCapability" ProxyProtocolCapability: type: object additionalProperties: false required: [type, fields] properties: type: type: string fields: type: array items: $ref: "#/components/schemas/ProxyFieldCapability" ProxyFieldCapability: type: object additionalProperties: false required: [key, kind] properties: key: type: string kind: type: string enum: [string, boolean, integer, string-list] required: type: boolean default: false secret: type: boolean default: false HomeAccessCapability: type: object required: [provisioning, transports] description: | Safe, unauthenticated feature negotiation only. This object never contains configured addresses, ports, certificate fingerprints, devices, usernames, or credentials. properties: provisioning: type: boolean description: | True only when this deployment can complete the credential, validation, reload, external confirmation, revocation, and rollback transaction. Schema or compiler support alone leaves this false. transports: type: array minItems: 1 uniqueItems: true items: type: string enum: [anytls, hysteria2] description: | Managed transports available for a Home invitation. An invitation selects a non-empty subset and each selected transport becomes one independently validated client proxy. DNSCapability: type: object required: [enhancedModes, managed] description: | Resolver mode capability. The list is compiler support, not the Gateway's configured nameservers or filters. `managed` is false when an operator-owned system such as OpenClash/UCI retains configuration authority; clients must then keep DNS controls read-only. properties: enhancedModes: type: array minItems: 2 uniqueItems: true items: type: string enum: [fake-ip, redir-host] managed: type: boolean description: Whether `/v1/config/apply` may change this Gateway's DNS. HomeStatus: type: object additionalProperties: false required: [provisioned, transports, proxyCount] properties: provisioned: type: boolean transports: $ref: "#/components/schemas/HomeTransportList" proxyCount: type: integer minimum: 0 description: Number of configured advertised proxies; no addresses are returned. HomeChangeRequest: type: object additionalProperties: false required: [idempotencyKey, confirmSeconds, transports] properties: idempotencyKey: type: string minLength: 16 maxLength: 128 description: Stored only as a hash and valid only for the pending transaction. confirmSeconds: type: integer minimum: 1 maximum: 300 transports: $ref: "#/components/schemas/HomeTransportSet" HomeConfirmRequest: type: object additionalProperties: false required: [transactionId, transports] properties: transactionId: type: string transports: $ref: "#/components/schemas/HomeTransportSet" HomeProfile: type: object additionalProperties: false required: [transactionId, confirmBy, proxies] description: | Secret response returned only to the initiating device while its Home transaction is pending. It must not be logged or cached. properties: transactionId: type: string confirmBy: type: string format: date-time proxies: type: array minItems: 1 items: $ref: "#/components/schemas/HomeProxy" HomeTransport: type: string enum: [anytls, hysteria2] HomeTransportSet: type: array minItems: 1 maxItems: 2 uniqueItems: true items: $ref: "#/components/schemas/HomeTransport" description: | Exact non-empty selected subset. Duplicate, unsupported or omitted transports are invalid. Confirmation must equal the set recorded by the pending transaction; it is not a declaration of partial success. HomeTransportList: type: array uniqueItems: true items: $ref: "#/components/schemas/HomeTransport" description: | The currently provisioned transports for one device. It is empty when Home access has not been provisioned for that device. HomeInvitationCreateRequest: type: object additionalProperties: false required: [transports, expiresInSeconds] properties: transports: $ref: "#/components/schemas/HomeTransportSet" expiresInSeconds: type: integer minimum: 30 maximum: 300 description: | Invitation lifetime. The Manager may choose a shorter configured maximum but never extends this requested deadline. HomeInvitation: type: object additionalProperties: false required: [qrPayload, expiresAt, transports] properties: qrPayload: type: string minLength: 1 maxLength: 256 description: | Exact compact JSON object described by `schemas/home-claim-v1.schema.json`, ready for QR encoding. It has a one-time opaque token but no node password or device credential. expiresAt: type: string format: date-time transports: $ref: "#/components/schemas/HomeTransportSet" HomeInvitationClaimRequest: type: object additionalProperties: false required: [token, idempotencyKey, confirmSeconds] properties: token: type: string pattern: "^[A-Za-z0-9_-]{43}$" description: | The 32-byte URL-safe opaque token read from the QR. It is accepted only over the paired native authenticated channel and must never be logged, cached, or put in a URL. idempotencyKey: type: string minLength: 16 maxLength: 128 description: Stored only as a hash for the pending claim transaction. confirmSeconds: type: integer minimum: 1 maximum: 300 HomeProxy: type: object additionalProperties: false required: [name, type, server, port, options, secrets] properties: name: type: string type: $ref: "#/components/schemas/HomeTransport" server: type: string port: type: integer minimum: 1 maximum: 65535 options: type: object additionalProperties: false required: [sni, fingerprint] properties: sni: type: string fingerprint: type: string pattern: "^[0-9a-f]{64}$" secrets: type: object additionalProperties: false required: [password] properties: password: type: string EntitlementStatus: type: object required: [tier, active, managerKeyHash] properties: tier: type: string enum: [free, pro] active: type: boolean managerKeyHash: type: string pattern: "^[0-9a-f]{64}$" EntitlementActivation: type: object required: [license] properties: license: type: string description: Base64url encoding of the vendor-signed Gateway license JSON. Health: type: object required: [healthy, pendingTransaction, observedAt] properties: healthy: type: boolean pendingTransaction: type: boolean description: True only while a change is awaiting confirmation. observedAt: type: string format: date-time configChangedOutside: type: boolean description: | True when something other than this Manager has edited the traffic configuration — Mihomo's own dashboard, or somebody with an editor. Reported rather than refused. The compiled file says in its own first lines that every apply replaces it in full, so this is the declared arrangement; what was missing was anybody being told it had happened. Absent on a Gateway whose operator kept that file. displayName: type: string maxLength: 80 description: | The operator's label for this Gateway, the same name the WebUI header shows. Present only when one is configured. Given to paired devices here and never in `/v1/capabilities`, because a home or location name can be private. A client keeps the last name it saw, since an unhealthy Gateway answers `503` without it. TrafficSnapshot: type: object additionalProperties: false required: [observedAt, current, trend, connections, nodeShares, destinations] description: | Redacted observability only. This describes the Gateway's current runtime, not user traffic carried through the API. Trend points live in Manager memory and are lost on restart. properties: observedAt: type: string format: date-time current: type: object additionalProperties: false required: [up, down, upTotal, downTotal] properties: up: {type: integer, minimum: 0, description: Bytes per second} down: {type: integer, minimum: 0, description: Bytes per second} upTotal: {type: integer, minimum: 0, description: Cumulative bytes} downTotal: {type: integer, minimum: 0, description: Cumulative bytes} trend: type: array maxItems: 86400 items: type: object additionalProperties: false required: [at, up, down] properties: at: {type: string, format: date-time} up: {type: integer, minimum: 0} down: {type: integer, minimum: 0} connections: type: array maxItems: 64 items: $ref: "#/components/schemas/TrafficConnection" connectionsUnavailable: type: boolean description: | True when current traffic rates were read but the connection inventory could not be read. An empty connections array then means unavailable, not zero active connections. Absent means false. nodeShares: type: array maxItems: 8 items: $ref: "#/components/schemas/TrafficAggregate" destinations: type: array maxItems: 8 items: $ref: "#/components/schemas/TrafficAggregate" TrafficConnection: type: object additionalProperties: false required: [destination, node, protocol, upload, download] properties: destination: {type: string, maxLength: 256} node: {type: string, maxLength: 256} protocol: {type: string, maxLength: 256} upload: {type: integer, minimum: 0} download: {type: integer, minimum: 0} startedAt: {type: string, format: date-time} TrafficAggregate: type: object additionalProperties: false required: [name, bytes, share] properties: name: {type: string, maxLength: 256} bytes: {type: integer, minimum: 0} share: {type: integer, minimum: 0, maximum: 100} PairRequest: type: object required: [code, deviceId] properties: code: type: string description: The one-time code shown on the Gateway. Short lived. deviceId: type: string description: | Stable identifier the client generates for itself. Not a hardware identifier, and never derived from one. PairResponse: type: object required: [deviceId, credential] properties: deviceId: type: string credential: type: string description: | Returned once and never again. Store it in the platform keychain, never in application settings or logs. ConfigSnapshot: type: object required: [syntheticOnly, policies, selections] properties: syntheticOnly: type: boolean description: | True while the Gateway is driving a synthetic fixture rather than a real traffic process. Surfaced so a client can say so plainly instead of presenting fixture data as live. policies: type: object description: Policy group to its allowlisted members. additionalProperties: type: array items: type: string selections: type: object description: Policy group to its currently selected member. additionalProperties: type: string classificationRules: type: array maxItems: 256 description: | Ordered, user-editable rules owned by this Gateway target. Clients use them to preview classification of Provider nodes across all Providers. The Manager transports these patterns but does not classify nodes or silently resolve ambiguous matches. An absent field means an older Gateway or no configured rules. items: $ref: '#/components/schemas/ClassificationRule' configurationAuthority: $ref: '#/components/schemas/ConfigurationAuthority' runtimeConfiguration: $ref: '#/components/schemas/RuntimeConfiguration' ConfigurationAuthority: type: object required: [mode] description: | Who may replace the Mihomo routing configuration on this Gateway. A redacted live snapshot does not change this boundary. Existing operator-authored installations remain `operator` until an explicit, separately confirmed adoption transaction succeeds. properties: mode: type: string enum: [manager, operator] description: | `manager` only after the operator explicitly handed over the complete routing file. `operator` is the safe default; the Manager may show a redacted live view and make supported selections, but must not replace the routing file. ConfigurationAdoptionPreview: type: object required: [verdict, sourceAuthority, preservedSectionCount, requiresService, requiresApp, blockers] description: | A redacted, no-write assessment of an operator-authored Mihomo file. It does not parse or return configuration values. A `ready` verdict permits only guided review; a separately confirmed adoption transaction remains unavailable until the Gateway explicitly advertises it. properties: conversion: type: object description: Optional routing conversion assessment when local compiler inputs exist. Compiled means compiler validation only, not runtime validation or authorization to adopt. No configuration values are returned. required: [status] properties: status: type: string enum: [compiled, blocked] runtimeValidation: type: string enum: [passed, failed, unavailable, stale] description: Validation of temporary logical and traffic candidates; no reload or adoption occurs. Stale means the source changed or became unreadable before/during validation and requires a fresh review. Missing on older Managers. candidateRevision: type: string pattern: '^[a-f0-9]{64}$' description: Digest of the exact privately compiled candidate, binding a later review acknowledgement to local service settings as well as the source. This field alone does not transfer ownership. counts: type: object additionalProperties: type: integer minimum: 0 serviceChanges: type: array items: type: string enum: [mixed-port, socks-port, allow-lan, mode, log-level, external-controller, secret, listeners] findings: type: array items: type: object required: [section, index, code] properties: section: type: string index: type: integer minimum: 0 code: type: string sourceRevision: type: string pattern: '^[a-f0-9]{64}$' description: SHA-256 of the exact source bytes assessed. Absent when the file cannot be read. Identifies this review snapshot only; it grants no write authority. verdict: type: string enum: [ready, blocked, unsupported] sourceAuthority: type: string enum: [manager, operator] preservedSectionCount: type: integer minimum: 0 description: Count of non-modelled top-level sections that would require local preservation. requiresService: type: array description: Safe names of Manager-owned runtime sections that must be deliberately re-entered locally. items: type: string requiresApp: type: array description: Safe names of Okojo model sections that must be deliberately re-entered in the paired App. items: type: string blockers: type: array description: Stable, redacted reasons the guided review cannot proceed yet. items: type: string enum: [already-managed, configuration-file-unavailable, configuration-file-unreadable, configuration-file-not-writable, configuration-shape-unsupported, absolute-path-review-required] RuntimeConfiguration: type: object description: | Redacted snapshot of the configuration and inventory Mihomo is actually running. It is separate from the Okojo editable model. It never contains server addresses, ports for individual nodes, subscription URLs, credentials, or rule payloads. properties: available: type: boolean description: False when the live Controller snapshot is unavailable. port: type: integer socksPort: type: integer mixedPort: type: integer mode: type: string logLevel: type: string allowLan: type: boolean ipv6: type: boolean tunEnabled: type: boolean proxies: type: array items: $ref: '#/components/schemas/RuntimeProxy' groups: type: array items: $ref: '#/components/schemas/RuntimeGroup' providers: type: array items: $ref: '#/components/schemas/RuntimeProvider' ruleCount: type: integer minimum: 0 ruleProviders: type: array items: type: string RuntimeProxy: type: object required: [name, type, alive] properties: name: type: string type: type: string providerName: type: string alive: type: boolean RuntimeGroup: type: object required: [name, type] properties: name: type: string type: type: string now: type: string members: type: array items: type: string RuntimeProvider: type: object required: [name, nodeCount] properties: name: type: string nodeCount: type: integer minimum: 0 ProviderHealthSnapshot: type: object additionalProperties: false required: [observedAt, providers] properties: observedAt: type: string format: date-time providers: type: array items: $ref: "#/components/schemas/ProviderHealth" steadySelection: description: >- The Manager's steadier url-test selection (ADR 0030). Absent until its first pass. A lastPass older than three 30-second intervals means the keeper state is unknown. It does not prove a previously fixed choice has been released or that Mihomo selects automatically. type: object additionalProperties: false required: [groups] properties: lastPass: type: string format: date-time problem: type: string enum: [runtime-unavailable, pro-required, change-pending, fix-failed] groups: type: array items: type: object additionalProperties: false required: [group, mode] properties: group: type: string mode: type: string enum: [balanced, stable] holding: type: string ProviderStructure: type: object additionalProperties: false required: [groups, ruleSets, dnsPolicies, resolvers] properties: groups: type: array items: $ref: "#/components/schemas/ProviderStructureGroup" ruleSets: type: array items: $ref: "#/components/schemas/ProviderStructureRuleSet" dnsPolicies: type: array items: $ref: "#/components/schemas/ProviderStructureDNSPolicy" resolvers: type: array uniqueItems: true items: type: string finalTarget: type: string ProviderStructureGroup: type: object additionalProperties: false required: [name, mode] properties: name: type: string minLength: 1 maxLength: 256 mode: type: string enum: [manual, automaticLowestLatency, automaticFailover, loadBalance] testUrl: type: string format: uri testIntervalSeconds: type: integer minimum: 1 ProviderStructureRuleSet: type: object additionalProperties: false required: [name, url, behavior, format, targetGroupName] properties: name: type: string minLength: 1 maxLength: 256 url: type: string format: uri behavior: type: string enum: [domain, ipcidr, classical] format: type: string enum: [yaml, text, mrs] targetGroupName: type: string minLength: 1 maxLength: 256 intervalSeconds: type: integer minimum: 1 ProviderStructureDNSPolicy: type: object additionalProperties: false required: [domain, nameservers] properties: domain: type: string minLength: 1 nameservers: type: array minItems: 1 uniqueItems: true items: type: string ProviderHealth: type: object additionalProperties: false required: [name, nodeCount, healthyCount, unhealthyCount, untestedCount, nodes] properties: name: type: string maxLength: 256 sourceKind: type: string enum: [provider, configuration] description: Runtime source category; absent when unknown. Configuration inventories can contain nodes, groups and builtins. nodeCount: type: integer minimum: 0 healthyCount: type: integer minimum: 0 unhealthyCount: type: integer minimum: 0 untestedCount: type: integer minimum: 0 nodes: type: array items: $ref: "#/components/schemas/ProviderNodeHealth" ProviderNodeHealth: type: object additionalProperties: false required: [name, state] properties: name: type: string maxLength: 256 kind: type: string enum: [node, group, builtin] description: Runtime object type; absent when unknown. Display names never determine type. state: type: string enum: [healthy, unhealthy, untested] delayMs: type: integer minimum: 0 lastTestedAt: type: string format: date-time ClassificationRule: type: object additionalProperties: false required: [id, axis, label, pattern] properties: id: type: string pattern: '^[A-Za-z0-9._-]{1,64}$' axis: type: string enum: [region, carrier, purpose, multiplier] label: type: string minLength: 1 maxLength: 128 pattern: type: string minLength: 1 maxLength: 1024 description: | A client-side preview pattern. Regex is an aid, never silent truth: invalid or ambiguous matches must be shown rather than guessed. BrowserDecisionResponse: type: object required: [approved] properties: approved: type: boolean BrowserDecisionRequest: type: object required: [code, approve] properties: code: type: string pattern: "^[0-9]{6}$" description: The six digits the waiting browser is displaying. approve: type: boolean description: | True admits the browser. False refuses it, which is a decision the browser is shown rather than an absence of one. SelectRequest: type: object required: [group, member] properties: group: type: string member: type: string ProbeRequest: type: object required: [target, testUrl] properties: target: type: string description: An allowlisted policy group or proxy name. testUrl: type: string format: uri description: An HTTP(S) URL Mihomo fetches through the target. timeoutMs: type: integer minimum: 1000 maximum: 60000 default: 5000 description: Optional timeout. Omitted or zero uses five seconds. LatencyProbeResult: type: object required: [target, delayMs, observedAt] properties: target: type: string delayMs: type: integer minimum: 0 observedAt: type: string format: date-time SelectionPreview: type: object required: [group, current, draft, changed] properties: group: type: string current: type: string draft: type: string changed: type: boolean CheckConfigurationRequest: type: object required: [configuration] properties: configuration: type: object description: The same bounded configuration shape accepted by apply. classificationRules: type: array description: | Target-owned classification metadata checked with the same revision. Omitting the field preserves existing rules; an empty array clears them. items: $ref: '#/components/schemas/ClassificationRule' ConfigurationPreview: type: object required: [validation, baseRevision, changedSections] properties: validation: type: string enum: [passed] baseRevision: type: string pattern: "^[0-9a-f]{64}$" description: Opaque revision for stale-preview protection during apply. changedSections: type: array uniqueItems: true items: type: string enum: [proxies, providers, ruleSets, rules, dns, sniffer, preferences, finalTarget, groups, classificationRules] ApplyConfigurationRequest: type: object required: [configuration, confirmSeconds] properties: configuration: type: object description: | The whole configuration, in the shape `/v1/config` returns under `gateway`. Servers, subscriptions, rule sets, policy groups, rules, resolver settings and the switches a person flips. Deliberately not schema'd field by field here. The Gateway's own allowlist is the authority on what may be written, it refuses anything outside it with a reason, and a second description of the same rules in this document would be a second thing to keep in step. classificationRules: type: array description: | Target-owned classification metadata committed and rolled back with this configuration. Omitting the field preserves existing rules; an empty array clears them. items: $ref: '#/components/schemas/ClassificationRule' confirmSeconds: type: integer minimum: 1 maximum: 300 baseRevision: type: string pattern: "^[0-9a-f]{64}$" description: Optional token returned by the latest configuration check. ApplyRequest: type: object required: [group, member, confirmSeconds] properties: group: type: string member: type: string confirmSeconds: type: integer minimum: 1 maximum: 300 description: | How long the client has to confirm. Bounded at both ends: zero would roll back before a user could react, and an unbounded window would defeat the protection entirely. ConfirmRequest: type: object required: [transactionId] properties: transactionId: type: string RollbackRequest: type: object properties: transactionId: type: string description: | Optional. Omit to roll back whatever is pending; supply it to be certain a stale client does not roll back a newer change. Transaction: type: object required: [id, state, group, member, confirmBy] description: | Deliberately omits backup file names and content hashes. They are of no use to a client and would put Gateway filesystem detail into a mobile device and its logs. properties: id: type: string state: type: string enum: [prepared, waiting-confirmation, confirmed, rolled-back, failed] group: type: string member: type: string confirmBy: type: string format: date-time failure: type: string description: | Present only on a failed or rolled-back transaction. Already safe to display; never a formatted internal error. Error: type: object required: [code, message] properties: code: type: string enum: - unauthorized - bad-request - conflict - not-found - unavailable - internal - unsupported - pairing-refused - pro-required - invalid-license description: | Stable machine code. Branch on this, never on the message. message: type: string faults: type: array items: type: string description: | Every reason a configuration was refused, when there is more than one. Absent otherwise: a single-cause failure says everything it has to say in `message`, and a list of one is noise. description: | Already safe to display. Built from a fixed vocabulary rather than by formatting an internal error, which is how paths, hashes, and credentials leak into a user interface.