Versi server 0.6.0 · apiVersion 1 · diterbitkan 5 Oktober 2026. Versi lain: tidak ada.
References to docs/operations.md in this document mean the install guide and the operations guide at /docs/install and /docs/operations.
WiraTalk server API
The public contract of a WiraTalk company server. Sections 1 to 10 cover accounts, sessions and people, section 11 is chat, section 12 files (with the media parts of section 11: 11.2, 11.16 to 11.18, 11.25 to 11.28) and section 13 push notifications. Installing, updating and rolling back: docs/operations.md. Every account belongs to the company that runs the server: an admin creates it, or a person's first sign-in through the company's single sign-on creates it. Nobody signs up on their own. A password is kept only as an Argon2id hash.
Changes for clients
What a client written for the 0.5.1 server must change: the sign-in routes of the old identity service and /v1/auth/password/reset/* are gone, and so are the old single sign-on routes; people sign in with POST /v1/auth/password (an email or a username, 3.2), a link an admin made (3.8 to 3.10) or a provider the admin configured (3.11 to 3.13). GET /v1/auth/providers answers { "methods": [ { "id": "password" }, { "id": "oidc:<id>", "name": "..." } ] } (3.1). ACCOUNT_SUSPENDED is now ACCOUNT_DISABLED. A sign-in answer carries a deviceToken the app stores and sends back (3.2). Admin work has its own section (14) and /.well-known/wiratalk (10.9) says which server this is.
A web signs in only by linking from a phone (7.6): the phone makes a code, the web exchanges it (3.14) and keeps its session with Authorization: Bearer wta_... and a refresh token (3.15). The server answers CORS for the WiraTalk web (section 1).
1. Conventions
- Transport. HTTPS only. Request and response bodies are JSON, UTF-8 (
Content-Type: application/json) unless a section says otherwise. - Base path. Every API path below starts with
/v1. - Body size. Every request body is limited to 131,072 bytes (128 KiB). A larger
Content-Lengthis refused before reading; a chunked or lying body is cut off as soon as it passes the limit. Result: HTTP 413PAYLOAD_TOO_LARGE. The one exception isPOST /v1/files(12.1): its body is the file itself, up to 99,614,720 bytes (95 MiB), under its own per-kind cap. - Malformed JSON. A body that is missing, not valid JSON, or not a JSON object is treated as
{}. The endpoint then fails its own field validation (usuallyINVALID_REQUEST). - Session.
Authorization: Bearer <sessionId>(Android;sessionIdis 64 lowercase hex characters), or the cookie__Host-wt_sid(web, HttpOnly, Secure, SameSite=Strict,Path=/). A cookie session on an unsafe method (POST,PUT,PATCH,DELETE) also needs the headerX-WiraTalk: 1and, when the browser sends one, a matchingOrigin; otherwise 403CSRF_REJECTED. A Bearer session never needs either (there is no ambient cookie for another site to ride on). A linked web (7.6) sendsAuthorization: Bearer wta_..., its access token, and never a cookie; it works on every route below except the ones for a phone's own sessions and grants (7.1 to 7.3, 7.7, 7.9, 7.10), which answer it 403PHONE_ONLY. - Login CSRF. Any request to
POST /v1/auth/password(3.2) orPOST /v1/auth/exchange(3.13) carrying anOriginheader that is not exactly the server's own public origin (WT_PUBLIC_ORIGIN) is refused (403CSRF_REJECTED) before the body is even read, whateverclientthe body eventually names: this is what stops a cross-site page from firing anenctype="text/plain"form post with a body of its own choosing (no CORS preflight needed for that trick). On top of that, aclient: "web"sign-in, which answers with the webSet-Cookie, also needsX-WiraTalk: 1, exactly like an authenticated cookie request; without it, 403CSRF_REJECTEDand no cookie is set. The exchange of awebsign-in (3.13) follows the same rule, checked before its code is spent. An Android answer (Bearer, no cookie) never needs either check. - User-Agent. The app SHOULD send
WiraTalk/<version> (<platform>), for exampleWiraTalk/0.1.0 (Android); the server uses it for the session label only (src/sessions/label.ts), never to gate a request. - Timestamps. ISO 8601 in UTC with milliseconds and
Z(2026-09-28T10:00:00.000Z). - Language. Human text in
erroris Indonesian by default and English when the request'sAccept-Languageprefersen(primary tagen). The text is not part of the contract: clients MUST branch oncodeonly. - Caching. Every API response carries
Cache-Control: private, no-store, except the public documents and files of section 10, and the files, thumbnails and group photos of 12.2, 12.3 and 11.28 (private, max-age=86400with a strongETag: cached by the reader's own browser or app only, never by Cloudflare). - Client IP. The address of the TCP peer, used for rate limits and the audit log. When the peer is one of the addresses or IPv4 ranges in
TRUSTED_PROXIES(empty by default, so no header is believed; set it to the reverse proxy or tunnel in front of the server), the client is the address in itsCF-Connecting-IPheader.X-Forwarded-Foris never read. - Unknown fields in requests are ignored. Clients MUST ignore unknown fields in responses.
- CORS. The one origin allowed is
WT_HUB_URL(the WiraTalk web, which the Hub serves), on/v1/*and/.well-known/wiratalk; no other origin is ever allowed or reflected. Its preflight (OPTIONSwithAccess-Control-Request-Method) is 204 withAccess-Control-Allow-Originset to that origin,Access-Control-Allow-Methods: GET, HEAD, POST, PUT, PATCH, DELETE,Access-Control-Allow-Headers: Authorization, Content-Type, Range, If-None-Match, X-WiraTalk-Client, X-WiraTalkandAccess-Control-Max-Age: 7200(the last two names are the ones the app's web client sends). Every answer to a request from that origin, errors included, carriesAccess-Control-Allow-OriginandAccess-Control-Expose-Headers: Content-Range, Content-Length, ETag, Retry-After. No credentials are allowed (there is noAccess-Control-Allow-Credentials), and a cookie on a request from that origin is ignored: the web is authenticated byAuthorizationalone. The web reads media withfetchplusAuthorizationand makes blob URLs (there are no signed URLs), and reads the event stream (9.1) with a streamedfetch, notEventSource, which cannot sendAuthorization. Every answer on those paths carriesVary: Origin. Other paths send no CORS headers.
2. Error model
One response shape for every error:
HTTP 4xx/5xx
{ "error": "<human text>", "code": "PAYLOAD_TOO_LARGE" }
Extra fields MAY appear next to code (for example retryAfterSec on RATE_LIMITED and ACCOUNT_LOCKED, which also set the Retry-After header). On an endpoint that requires a session, 401 UNAUTHENTICATED means only one thing: the session is missing, expired, forged, revoked, or its user no longer exists or is disabled (see wiratalk.users.suspended_at, docs/schema.md). It is never reused for a sign-in refusal; sign-in endpoints have their own codes (below). ACCESS_TOKEN_EXPIRED is answered only to a linked web's access token and means "refresh, then retry"; it never means the session is dead.
| HTTP | code | When |
|---|---|---|
| 400 | INVALID_REQUEST | A request field is missing or malformed |
| 400 | INVALID_LINK | An account link (3.8, 3.9) that is unknown, malformed, already used, replaced by a newer one or expired: ask the company admin for a new one |
| 400 | INVALID_EXCHANGE_CODE | 3.13: the sign-in code is unknown, expired, already used, or the verifier does not match (the code is spent either way) |
| 400 | INVALID_PAIRING_CODE | /v1/auth/linked/exchange: the linking code is unknown, expired, already used, or its phone session has ended (7.6): scan the QR code again |
| 400 | WEAK_PASSWORD | A new password is under 12 characters |
| 400 | INVALID_USERNAME | The requested username is missing, malformed, or reserved |
| 400 | CONFIRMATION_REQUIRED | Account deletion: confirmUsername/confirmEmail does not match |
| 400 | MESSAGE_TOO_LONG | A message text over 4000 characters after cleaning (11.1) |
| 401 | UNAUTHENTICATED | The session is missing, dead, forged, revoked, or the user is suspended |
| 401 | ACCESS_TOKEN_EXPIRED | A linked web's access token (7.6) is unknown or past its 15 minutes: refresh it (/v1/auth/linked/refresh), then retry |
| 401 | INVALID_CREDENTIALS | Wrong username, email or password; also an unknown login and an account without a password, with the same body |
| 403 | CSRF_REJECTED | A cookie-authenticated unsafe request without the CSRF header, or with a foreign Origin |
| 403 | ACCOUNT_DISABLED | The password is correct, or an account link is being completed, but the account is disabled by the company's admin |
| 403 | PHONE_ONLY | A linked web called /v1/sessions (7.1 to 7.3), or anything but the phone (a linked web, the same-origin cookie web) called /v1/linked-devices (7.7, 7.9, 7.10) |
| 403 | ADMIN_ONLY | Any /v1/admin route (section 14) called by a session whose person is not an admin; the role is read from the database on every request |
| 403 | RECENT_AUTH_REQUIRED | Account deletion: the calling session is older than 15 minutes |
| 403 | NOT_A_MEMBER | A former member (left or removed) tried something only a current member may do (11.1) |
| 403 | BLOCKED | Sending or forwarding in a direct conversation where either person has blocked the other (11.1) |
| 403 | ADMIN_REQUIRED | A group action only admins may take (11.7 to 11.10) |
| 403 | NOT_SENDER | Deleting for everyone a message the caller did not send (11.18) |
| 403 | DELETE_WINDOW_EXPIRED | Deleting for everyone more than 5 minutes after sending (11.18) |
| 404 | NOT_FOUND | The thing a request names does not exist (or is hidden from this caller) |
| 404 | ROUTE_NOT_FOUND | Unknown path |
| 404 | NO_RELEASE | /v1/app/version or /v1/app/apk: RELEASES_DIR holds no valid manifest or APK yet (10.7) |
| 409 | NOT_LISTED | POST /v1/linked-devices (7.6): the stored directory entry does not name this server and its origin as active with at least an hour left, or the Hub licence is refused or off: no web can be linked yet |
| 409 | LINKED_DEVICE_LIMIT | The account already has 5 linked webs, pending ones included (7.6) |
| 409 | PROVIDER_EXISTS | An admin adding a sign-in provider with an id that is taken |
| 409 | PROVIDER_LIMIT | 10 sign-in providers already exist |
| 409 | CANNOT_CHANGE_SELF | An admin disabling, enabling or changing the role of their own account (14.2) |
| 409 | USER_DISABLED | Making a link for an account that is disabled (14.2): enable it first |
| 409 | LAST_COMPANY_ADMIN | Disabling, demoting or deleting (8.1) the only active admin of the company |
| 409 | USERNAME_TAKEN | That username already belongs to another account |
| 409 | EMAIL_TAKEN | That email already belongs to another account (an admin creating an account) |
| 409 | USERNAME_REQUIRED | The caller has no username yet and the action needs one: starting a conversation, sending or forwarding (11.1) |
| 409 | PEER_DELETED | Sending in a direct conversation whose other person deleted their account (11.1) |
| 409 | LAST_ADMIN | Demoting the only admin of a group (11.10) |
| 409 | GROUP_FULL | A group would have more than 64 members (11.5, 11.8) |
| 409 | FILE_UNAVAILABLE | A message (11.16), a forward (11.17) or a group photo (11.28) names a file that is unknown, not the caller's own upload, still uploading, never linked and uploaded more than 24 hours ago, linked once but no longer linked to any message, or already collected (12.5): upload it again |
| 405 | METHOD_NOT_ALLOWED | Known path, wrong method (the Allow header lists the right ones) |
| 413 | PAYLOAD_TOO_LARGE | Body over 128 KiB, or an upload whose size is over its kind's cap (12.1; with limitBytes), or an upload body longer than its size |
| 415 | UNSUPPORTED_FILE_TYPE | An image or voice upload whose bytes are not a format 12.1 accepts, or an image that cannot be decoded |
| 422 | OIDC_DISCOVERY_FAILED | An admin saving a sign-in provider whose issuer cannot be reached, answers too slowly, too much or something invalid |
| 429 | RATE_LIMITED | Too many attempts; retryAfterSec when the window is known |
| 429 | ACCOUNT_LOCKED | Ten failed password sign-ins in a row for one login string: that login is locked for 15 minutes, even for the right password, for real and invented logins alike (3.2); retryAfterSec and Retry-After |
| 429 | UPLOAD_QUOTA_EXCEEDED | 100 unsent uploads already, or the 2 GiB a day are used up (12.6); retryAfterSec and Retry-After for the daily volume |
| 500 | INTERNAL_ERROR | Unexpected error. Details go to the server log only, never to the client |
| 503 | SERVICE_UNAVAILABLE | Postgres, Redis, the file store or the encryption key is not available; or the server is busy hashing passwords (more sign-ins at once than the 2 hashing slots and the queue of 16 hold); or (12.1) the server is busy with other uploads, with retryAfterSec and Retry-After |
3. Auth
Every method below issues the same kind of session (src/sessions/sessions.ts): idle expiry 90 days sliding, capped at 365 days from creation. The client field (or the caller's own choice of transport) decides the answer shape: Android gets a bearer sessionId in the body, web gets the __Host-wt_sid cookie and no sessionId in the body. The cookie's Max-Age is the absolute cap, 365 days: the browser never slides a cookie, so the server enforces the 90-day idle limit itself (a cookie naming a session that went idle is simply 401 UNAUTHENTICATED).
Every account is a wiratalk.users row reached through a row of wiratalk.identities (docs/schema.md): local for an account with a password, oidc:<id> for one that signs in through a single sign-on provider. There is no sign-up: an account exists only because an admin made it, or because a person's first sign-in passed a provider the admin configured for an allowed email domain (3.12).
3.1 GET /v1/auth/providers
Public. The sign-in methods this server offers, so a client shows only what works:
{ "methods": [{ "id": "password" }, { "id": "oidc:acme", "name": "Acme" }] }
password is always listed. Every enabled single sign-on provider the admin configured follows as oidc:<id> with the name to show on its button, in name order; its sign-in starts at 3.11. A disabled provider is not listed. Never cached (Cache-Control: private, no-store).
3.2 POST /v1/auth/password
{ "login": "rina", "password": "correct horse battery staple", "client": "android" }
login is the person's username (a leading @ is allowed) or email, compared without case: anything with an @ after its first character is an email, the rest a username of 3 to 30 characters of a-z0-9._. 1 to 320 characters, otherwise 400 INVALID_REQUEST. The older field name email is read when login is absent. password is 1 to 1024 characters. client: android or web, default android. client: "web" also needs X-WiraTalk: 1 (login CSRF, section 1); a foreign Origin is refused for either client.
Success, client: "android" (HTTP 200):
{ "sessionId": "<64 hex>", "user": { "...": "MeView, see 3.6" }, "deviceToken": "<token>" }
Success, client: "web" (HTTP 200, plus Set-Cookie: __Host-wt_sid=... and Set-Cookie: __Host-wt_device=...):
{ "user": { "...": "MeView" } }
Device token. Every success also issues a signed device token that says "this phone or browser signed in with the password the account has now". It lasts 180 days. The app keeps it in secure storage, does not delete it when the person signs out, and sends it back as deviceToken in the body of every later sign-in; the browser gets it as the __Host-wt_device cookie (HttpOnly; Secure; SameSite=Strict; Path=/) and sends it back by itself. A valid token is bound to its account: a token for another account, a broken or expired one, or one issued before the password last changed is simply ignored. A holder of a valid token is not held by the per-login lock-out and the per-login limit below (it has a small limit of its own, 10 failures per 15 minutes per account and token), so a stranger who keeps a login locked cannot keep its owner out of the phone they already use. The per-address limit applies to everyone.
Refusals:
- 401
INVALID_CREDENTIALS: a wrong password, a login nobody has, an account that has no password and a password longer than allowed all answer with the same body, and an unknown login costs the same time as a known one (a password is checked against a throwaway hash and the same counters are written), so neither the message nor the timing says which login exists. - 429
ACCOUNT_LOCKED: ten failed attempts in a row for one login string lock that login for 15 minutes, withretryAfterSecandRetry-After. The counters and the lock are kept for every login string a stranger types, real or invented, and the answer is the same for both, so being locked reveals nothing. An account's email and its username are two login strings with a counter each. While a login is locked even the right password is refused and nothing is counted, so the lock never grows. A failure counts for an hour from the latest one (every failure renews the window), and a success clears the count. The lock is audited asaccount_locked, the owner is told by email when the server can send mail, and an admin can lift it. Without a valid device token a person on a new phone waits out an attack on their login: this is what the device token is for. - 403
ACCOUNT_DISABLED: said only after the right password, so it tells nothing to someone guessing. A wrong password for a disabled account is the same 401 as for any other. - 429
RATE_LIMITED: 10 failed attempts per minute per address and 5 per minute per login string. Only failures use these up: a successful sign-in gives its attempt back, so a company behind one address can all sign in at once. - 503
SERVICE_UNAVAILABLEwithRetry-After: 2: the server hashes at most 2 passwords at once and lets 16 wait, so a flood of attempts cannot starve everything else; the next ones are turned away at once.
A person who signs in with a local account that has no username yet gets MeView.needsUsername: true and a suggestedUsername (the email's local part, cleaned, with 1 to 99 appended if needed; null when nothing in that range is free); the app picks one with PUT /v1/me/username (4.3). Every sign-in is audited as sign_in with detail.method.
3.6 GET /v1/auth/session
Requires a session. Returns the caller's own view of themselves:
{ "user": {
"id": "uuid",
"role": "member",
"email": "rina@example.com",
"name": "Rina" ,
"username": null,
"about": "",
"emailDiscoverable": true,
"locale": "id",
"avatarEtag": null,
"needsUsername": true,
"suggestedUsername": "rina1"
} }
401 UNAUTHENTICATED when the session is dead.
3.7 POST /v1/auth/logout
Requires a session (a cookie session also needs the CSRF header, section 1). Revokes the current session only (not the person's other devices), deletes its device row (7.4) with it, clears the cookie when the session was a cookie one, and answers { "ok": true }. From a linked web (7.6) it ends that web's grant instead (no cookie is involved, so no Set-Cookie; audited sign_out {linked: true}); from a phone it also ends every web that phone linked.
3.8 POST /v1/auth/links/inspect
Public, rate limited with 3.9 (20 calls per minute per IP, 429 RATE_LIMITED). The token of an account link goes in the body, never in a path or query string:
{ "token": "<43 characters of base64url>" }
Answers what the set-password screen shows and changes nothing:
{ "purpose": "invite", "name": "Rina Maharani", "username": "rina", "email": "rina@contoh.test", "expiresAt": "2026-10-12T03:00:00.000Z", "company": "PT Contoh Uji" }
purpose is invite (the account has no password yet, valid 7 days) or reset (valid 24 hours). name and username can be null. A token that is malformed, unknown, used, replaced or expired is 400 INVALID_LINK, one answer for all of them. Never cached.
3.9 POST /v1/auth/links/complete
Public, same rate limit as 3.8.
{ "token": "<43 characters>", "password": "kata-sandi-baru-1", "client": "android" }
password follows the rules of the sign-in (12 to 128 characters counted as code points: under 12 is 400 WEAK_PASSWORD, over 128 or not a string 400 INVALID_REQUEST). client and the login CSRF rules are those of 3.2 (web needs X-WiraTalk: 1; a foreign Origin is refused for either), and the answers have the shapes of 3.2: a session starts, as after a sign-in (audited password_set {purpose}, then sign_in).
The link is spent by one conditional delete, so of any number of concurrent calls with the same token exactly one succeeds and the rest get 400 INVALID_LINK. A refusal that is the caller's to fix leaves the link usable: a weak password, a bad client, a failed CSRF check, and 403 ACCOUNT_DISABLED for a disabled account (answered before any password hashing). Completing also stores the password hash (replacing an older one), makes sure the local identity exists, lifts the lock-out of 3.2 for the person's email and username, and answers a new deviceToken; every device token of the old password stops working. After a reset, every session of the person made before the call ends (audited other_sessions_revoked {trigger: "password_reset"}), inside the same transaction as the new password: if the sessions cannot be ended, nothing is changed and the link is still usable. A sign-in that was checking the old password while the reset committed is refused, or its session ended, so the session this call starts is the only one left.
3.10 The link format
https://talk.wiracode.com/i/<serverId>#<token> invitation
https://talk.wiracode.com/r/<serverId>#<token> reset
The host is the Hub's (WT_HUB_URL), the path says which kind it is and serverId is the company server's id. Why the Hub's host and not the company server's own:
- The app declares Android App Links only for hosts known when it is built;
talk.wiracode.comis already its link host, so the link opens the app for any company's server. - Without the app the same URL lands on the universal web the Hub serves.
- The client resolves
serverIdthrough the signed directory, so a link can only lead to a registered, active server, and a suspended company's links stop working. - The token sits in the fragment, which a browser never sends: no request carries it to the Hub, Cloudflare or any access log. The Hub's own page script can read it on
/i/and/r/, so the universal web must remove it from the address withhistory.replaceStateas soon as it has read it. The client sends it only to the company server, in the POST body of 3.8 and 3.9.
The token is 32 random bytes in base64url (43 characters, 256 bits). The database keeps only its SHA-256 (docs/schema.md, account_links); a person has at most one live link, a new one replaces the older. A link is shown in exactly three places: the admin API's answer that made it, the email to its owner, and the output of the command in section 16. It is never logged and never written to the audit log.
3.11 GET /v1/auth/oidc/:id/start
Public. Starts a sign-in through the provider :id (the part after oidc: in 3.1). A browser navigates here; the answer is a 302 to the provider's authorization endpoint with response_type=code, the client id, redirect_uri=<WT_PUBLIC_ORIGIN>/v1/auth/oidc/callback, scope=openid email profile, a state and a nonce the server made, and the server's own PKCE code_challenge (S256). Query parameters:
| Parameter | Value |
|---|---|
challenge | The app's PKCE challenge: base64url(SHA-256(verifier)), 43 characters of A-Za-z0-9_-. The matching verifier is sent at 3.13 |
app_state | An opaque string of 16 to 128 characters of A-Za-z0-9_-, handed back unchanged at the end |
client | android or web |
Errors, as JSON: 400 INVALID_REQUEST for a malformed parameter; 404 NOT_FOUND for an unknown or disabled provider; 503 SERVICE_UNAVAILABLE when the provider's metadata cannot be fetched; 429 RATE_LIMITED past 30 starts a minute per IP. The flow is kept in Redis for 10 minutes and is read once (docs/schema.md).
3.12 GET /v1/auth/oidc/callback
The provider's redirect back (?code=&state= or ?error=&state=); the same address for every provider. The server spends the state, exchanges the code at the provider's token endpoint (with the client secret and the PKCE verifier), and checks the id token: RS256 or ES256 only, signature against the provider's published keys, iss, aud (and azp), exp, iat, nbf, nonce, sub, and at_hash / c_hash when present. Then:
- A person who signed in through this provider before is the same person (suspended:
disabled). An email whose domain is no longer on the provider's list isnot_allowedfor them too, and so is a token that carries no email at all (the domain cannot be checked). - A new identity needs an
emailwithemail_verifiedtrue (or, for a provider the admin markedtrustEmailbecause it omits the claim, such as Microsoft Entra, anemail_verifiedthat is absent; an explicitfalseis never accepted) and the part after its@, lowercased, equal to one of the provider's allowed domains.a@sub.contoh.co.idanda@contoh.co.id.evil.testdo not matchcontoh.co.id. The domain must be written in its plain ASCII form: an address with invisible, soft-hyphen or full-width characters in the domain isnot_allowed. - That email then joins the account an admin made for it (the account has a
localidentity, and none from this provider yet), auditedidentity_linked {method}, but only when the provider vouches for the address:email_verifiedis true, or the token carries Microsoft Entra'sxms_edov: true(the directory verified that the tenant owns the email's domain; an optional claim the admin enables on the app registration). UndertrustEmailanemail_verifiedthat is merely absent may create a new account but never joins an existing one, because an unverified address (Entra'smailattribute can be edited by tenant staff) must not hand over an account, an admin's least of all. An account that came from a sign-in and no admin is never joined by email. A disabled account isdisabled. - With no account for the email, one is made:
role: "member", no username yet (needsUsername: true), the name the provider gave (cleaned) or the email's local part, auditedaccount_created {method: "oidc:<id>"}. This is the only way an account appears other than an admin making it. The name and email of an existing account are never overwritten.
When the provider names itself in the redirect (iss, RFC 9207) it must be this attempt's provider; another issuer is unavailable. A refused sign-in is logged (provider and reason, never the address).
Google: an address on a company domain stays email_verified at Google even after the mailbox is gone, and a company may later give that address to someone else. Prefer a Google Workspace issuer setup where the company controls the accounts, and remove people from the provider's list of allowed domains or disable it when in doubt.
The answer is always a 302 to the app's own address, never to anything the provider or the caller supplied: wiratalk://auth for client=android, /auth/return for client=web, with state=<app_state> and either code=<exchange code> (43 characters, good for 2 minutes and one use) or error=:
error | Meaning |
|---|---|
cancelled | The person refused at the provider (access_denied) |
unavailable | The provider answered wrongly: a failed token call, an id token that does not check out (the reason goes to the server log, never the token), a missing code, a provider disabled meanwhile |
not_allowed | The email is missing, unverified, outside the allowed domains, or its account cannot take this identity |
disabled | The account is disabled |
An unknown, used, expired or missing state is not a redirect: 400 with a small HTML page, "Sesi masuk sudah kedaluwarsa. Tutup halaman ini dan coba lagi." ("This sign-in session has expired. Close this page and try again." when Accept-Language prefers en).
3.13 POST /v1/auth/exchange
{ "code": "<43 characters>", "verifier": "<the app's PKCE verifier>" }
Redeems the code of 3.12. The code is spent first, so a wrong verifier (400 INVALID_EXCHANGE_CODE) also burns it; a second call with the same code is the same 400. A code whose account was disabled in the meantime gets 403 ACCOUNT_DISABLED. The call needs no session. Login CSRF (section 1): a foreign Origin is 403 CSRF_REJECTED, and a code of a web sign-in also needs X-WiraTalk: 1, checked on a plain read of the code so a refused call does not spend it. Rate limited to 20 calls a minute per IP.
The answer follows the client chosen at 3.11: android gets { "sessionId": "...", "user": <MeView> }; web gets the __Host-wt_sid cookie and { "user": <MeView> }. The session is audited sign_in {method: "oidc:<id>"}.
3.14 POST /v1/auth/linked/exchange
{ "code": "wtc_<43 characters>" }
The web trades the single-use code it took out of the envelope (7.8) for its session. No session is needed. The call must carry no Origin header or exactly the web's origin (WT_HUB_URL); any other Origin is 403 CSRF_REJECTED, refused before the body is read and without spending the code. Answer:
{
"accessToken": "wta_<43>",
"accessExpiresAt": "<ISO, 15 minutes ahead>",
"refreshToken": "wtr_<43>",
"linkedDevice": { "id": "uuid", "label": null, "browser": "Chrome · Windows", "place": "Bandung, Indonesia", "linkedAt": "...", "lastUsedAt": "..." },
"user": "<MeView, 3.6>"
}
browser comes from this request's User-Agent and place from the location headers Cloudflare adds (shown in the request's language), so the app, which cannot know the browser, still shows what was linked. 400 INVALID_PAIRING_CODE: the code is malformed, unknown, expired (it lives 120 seconds), already used, or the phone session that made it has signed out. 403 ACCOUNT_DISABLED. Failures count per address, 20 a minute (a successful call gives its hit back); the 21st is 429 RATE_LIMITED.
3.15 POST /v1/auth/linked/refresh
{ "refreshToken": "wtr_<43>" }
Answers { "accessToken", "accessExpiresAt", "refreshToken" } like 3.14 (without linkedDevice and user). Every refresh replaces both tokens: the old access token stops working at once and the old refresh token is spent. Same Origin rule as 3.14 (403 CSRF_REJECTED, nothing spent). Failures count per address, 60 a minute (429 RATE_LIMITED).
401 UNAUTHENTICATED means the web is signed out for good: the token is unknown, was used before, belongs to a grant not used for 30 days, or its account is gone or disabled. The reuse rule is strict: a refresh token presented a second time ends the grant, whichever of the two calls came first, and is audited linked_device_reuse. So the web refreshes one call at a time across all its tabs (the Web Locks API) and before accessExpiresAt. An answer lost in transit leaves the web holding a spent token: the grant ends and the web shows the QR again.
4. Me, username and avatar
A person edits their own name, @username, about text and profile photo. The email and the role are the admin's. The profile photo is kept as the server's own 512 x 512 WebP made from one of the person's image uploads (4.5). Every change of it publishes user.changed (9.1).
4.1 GET /v1/me
Requires a session. The caller's own profile, the same shape as MeView in 3.6:
{
"id": "uuid",
"role": "member",
"email": "rina@example.com",
"name": "Rina",
"username": null,
"about": "",
"emailDiscoverable": true,
"locale": "id",
"avatarEtag": null,
"needsUsername": true,
"suggestedUsername": "rina1"
}
role is member or admin. avatarEtag is the etag of the stored photo (wiratalk.user_avatars.etag), null when there is none. 401 UNAUTHENTICATED when the session is dead.
4.2 PATCH /v1/me
{ "name": "Rina Maharani", "about": "Suka kopi dan hiking.", "emailDiscoverable": false, "locale": "en" }
Every field is optional; only the fields present are changed. name is cleaned the same way, composed (NFC) and stripped of invisible format characters; it must keep something visible, be at most 100 code points (also as sent) and not be the label of a deleted account ("Akun terhapus", "Deleted account") or "WiraTalk" (400 INVALID_REQUEST otherwise). about is cleaned with the same control-character and whitespace rules as everywhere else, at most 140 characters; a request whose about is over 140 characters before cleaning is refused outright (400 INVALID_REQUEST), never silently truncated. locale must be "id" or "en".
Answers the updated MeView (4.1's shape). When at least one field actually changed, publishes user.changed { "userId": "<id>" } to the caller's own live-update stream (GET /v1/events) and audits profile_update.
4.3 PUT /v1/me/username
{ "username": "@RinaP" }
The leading @ is optional and stripped either way. A username is 3 to 30 characters of a-z0-9._, lowercased, starting and ending with a letter or digit, never containing .., __, ._ or _., and not one of a fixed list of reserved words (admin, wiratalk, wira, system, and similar; src/account/username.ts RESERVED_USERNAMES is the source of truth). Anything else is 400 INVALID_USERNAME.
Setting an account's first username (needsUsername: true) is unlimited. Changing an existing one is rate limited to 5 per day (username-change); over that, 429 RATE_LIMITED. A name already held by another account is 409 USERNAME_TAKEN (including the rare case where two requests race for the same free name: the database's own unique constraint is the final word, and the loser also gets 409). Setting it to the name it already is answers 200 with no change, no event and no rate-limit charge.
On success, answers the updated MeView, publishes user.changed and audits username_changed.
4.4 GET /v1/usernames/:name
Requires a session. Availability check for a username someone is considering, from that person's own point of view (their current username, if any, reads as available to them):
{ "available": true }
{ "available": false, "reason": "invalid" }
reason: "invalid" covers anything normalizeUsername would reject (malformed or reserved); a merely taken name is { "available": false } with no reason. Rate limited: 60 per minute per user (username-check).
4.5 Profile photo
GET /v1/users/:id/avatar requires a session (a plain <img> load carries the cookie; no CSRF header is needed for a GET). The bytes of that user's photo, image/webp, with ETag and Cache-Control: private, max-age=86400; a request with a matching If-None-Match gets 304 with no body. 404 NOT_FOUND when the user does not exist or has no photo (never a fallback image; the app decides what to show for that).
PUT /v1/me/avatar sets the caller's own photo from an image they uploaded (12.1):
{ "fileId": "<uuid of an own image upload>" }
The server keeps a 512 x 512 WebP of the centre of the image (the same pipeline as a group photo, 11.28), so the upload may expire. Answers { "avatarEtag": "<16 hex>" }. A missing or malformed fileId is 400 INVALID_REQUEST; a file that is unknown, someone else's, not an image or no longer usable is 409 FILE_UNAVAILABLE; bytes that cannot be decoded are 415 UNSUPPORTED_FILE_TYPE. Sending the picture the person already has changes nothing. A change publishes user.changed and audits avatar_changed.
DELETE /v1/me/avatar removes the photo and answers { "ok": true }; having none changes nothing.
Both are rate limited to 20 per hour per person.
5. People
WiraTalk never lets anyone browse other users. The only ways to find someone are an exact @username or exact email match (5.1), a personal contact link someone shares with you (5.6 to 5.9), or already having them as a contact. Every route below requires a session. The shared shape, PublicProfile:
{
"id": "uuid",
"name": "Rina",
"username": "rina",
"about": "",
"avatarEtag": null,
"email": null,
"isContact": false,
"blockedByMe": false
}
email is null in every view of a profile except one: the answer to a lookup (5.1) that matched by that exact email, which can only happen when the target's emailDiscoverable is true (PATCH /v1/me, 4.2). The searcher typed the address, so echoing it reveals nothing; a lookup by @username, 5.2, contacts, contact links and blocks never show it. emailDiscoverable means "findable by email", nothing more. isContact and blockedByMe are always from the caller's own point of view.
5.1 GET /v1/users/lookup?q=
q is either an @username (the leading @ is optional; a bare username works too) or a full email address, matched case-insensitively. Whichever the string looks like decides which lookup runs (a username never contains @; an email always has one with something before and after it and a . in the domain): there is no combined free-text search.
Privacy: looking up the exact email of an account with email discoverability off answers 404 NOT_FOUND, byte for byte the same body as looking up an email nobody has. A caller can never tell "exists but hidden" apart from "does not exist". The same 404 covers looking up yourself and looking up a suspended account (an account without a username is simply never matched by the username path: the column is unique but nullable, and no query matches a null against a name). A missing q is 400 INVALID_REQUEST. Rate limited: 30 per 10 minutes per user (lookup).
5.2 GET /v1/users/:id
Anyone's public profile by id (5's shape). 404 NOT_FOUND for an unknown id or a suspended account. Unlike 5.1, this one does not exclude looking up yourself.
5.3 GET /v1/contacts
Your own contacts, each a PublicProfile plus nickname (string | null), sorted by nickname, falling back to name then username, case-insensitively.
5.4 PUT /v1/contacts/:userId
{ "nickname": "Ri" }
nickname is optional; absent or null clears it, otherwise it is cleaned the same way as about (4.2), at most 80 characters. Adding yourself is 400 INVALID_REQUEST. An unknown or suspended user is 404 NOT_FOUND (suspended users behave as nonexistent for adding a contact, the same as 5.1's suspended case). Calling this again on an existing contact just retitles it. Answers the contact's PublicProfile plus nickname and publishes contacts.changed {} (GET /v1/events) to yourself.
5.5 DELETE /v1/contacts/:userId
Idempotent: removing someone who is not a contact still answers { "ok": true }. Publishes contacts.changed {}.
5.6 GET /v1/me/contact-link
Your personal contact link, the thing a QR code or invite link encodes, created the first time this is called and stable after that:
{ "token": "<22 chars of A-Za-z0-9_->", "url": "https://talk.wiracode.com/c/<token>" }
5.7 POST /v1/me/contact-link/rotate
Replaces the token outright, no grace period: the old one starts answering 404 the moment this call returns (any QR code or link printed with it stops working; a fresh one has to be shared). Same answer shape as 5.6. Rate limited: 5 per hour per user (contact-link-rotate).
5.8 GET /v1/contact-links/:token
The link owner's PublicProfile. 404 NOT_FOUND for an unknown or rotated-away token, or one whose owner is now suspended.
5.9 POST /v1/contact-links/:token/accept
Adds the link's owner to your own contacts, with no nickname, and answers their PublicProfile, publishing contacts.changed {} to you. Accepting your own link is 400 INVALID_REQUEST.
6. Moderation
Blocking and reporting: what Google Play's user-generated-content policy requires, alongside an admin-only account suspension (wiratalk.users.suspended_at, src/cli/reports.ts).
6.1 GET /v1/blocks
Everyone you have blocked, newest first (a PublicProfile each, no nickname).
6.2 PUT /v1/blocks/:userId
Blocking yourself is 400 INVALID_REQUEST; an unknown user is 404 NOT_FOUND. Unlike adding a contact, blocking a suspended account is allowed: there is no reason to refuse it, and a report against a suspended user (6.5) may still want to block them too. Idempotent: blocking someone already blocked changes nothing. Publishes blocks.changed {}.
6.3 DELETE /v1/blocks/:userId
Idempotent, publishes blocks.changed {}.
Blocking is stored one-directionally (A can block B without B ever being told), but messaging refuses new messages when either side has blocked the other (isBlockedEitherWay, src/people/blocks.ts).
6.4 GET /v1/reports/reasons
{ "reasons": ["spam", "harassment", "hate", "sexual", "violence", "dangerous", "impersonation", "privacy", "other"] }
6.5 POST /v1/reports
{
"targetUserId": "uuid",
"reason": "spam",
"note": "optional, up to 500 characters",
"conversationId": null,
"seq": null,
"alsoBlock": false
}
Only targetUserId and reason are required. reason must be one of 6.4's list; anything else is 400 INVALID_REQUEST. conversationId (a uuid) and seq (a positive integer) report one message and are given together (one without the other is 400 INVALID_REQUEST). They must name a message the reporter can see (11.1); anything else, including a conversation the reporter is not a member of and a message deleted for everyone, is 404 NOT_FOUND. The message must be a text or media message (11.2) sent by targetUserId (400 INVALID_REQUEST otherwise). The report then keeps a copy as evidence: that message and up to 5 earlier text or media messages of the same sender in the same conversation that the reporter can see (never anyone else's messages, never a deleted one). A media message is copied as its caption (body) plus an attachment preview (11.2):
{
"conversationId": "uuid",
"conversationKind": "group",
"copiedAt": "2026-09-30T10:00:00.000Z",
"messages": [
{ "seq": 3, "body": "...", "createdAt": "...", "reported": false, "attachment": null },
{ "seq": 9, "body": "", "createdAt": "...", "reported": true, "attachment": { "fileId": "uuid", "kind": "image", "name": "WiraTalk-20261001-104200.jpg", "durationMs": null } }
]
}
The files named in the evidence (the reported message's own and every earlier one's) are kept for 90 days from the report (REPORT_FILE_HOLD_DAYS), even when the message is deleted for everyone in the meantime: for moderation only (12.4: once a deletion for everyone unlinks a file, it is unreadable through this API for anyone, the hold notwithstanding, until src/cli/reports.ts file <reportId> <fileId> --out <dir> writes it into a directory you name; it refuses any file that is not in that report's evidence, and never writes to stdout).
The copy is kept with the report: deleting the message for everyone or deleting the sender's account later does not remove it. src/cli/reports.ts show prints it. A report without a message has evidence: null. alsoBlock: true also blocks the target (6.2, best effort: a block that already existed is not an error), publishing blocks.changed {} alongside the report. A target whose account is deleted after the report was stored is not an error either: the stored report's id is answered, and nothing is blocked or published (there is nobody left to block, and a retry would only file a second report). Reporting yourself is 400 INVALID_REQUEST; an unknown target is 404 NOT_FOUND, and so is a target whose account is deleted while the report is being filed (nothing is stored then). Rate limited: 20 per hour per user (reports).
{ "id": "uuid" }
Audits account_report_filed. The report survives its reporter's account being deleted later (reporter_id turns null; the row itself is kept) and is otherwise invisible through this API: only src/cli/reports.ts, run inside the server container, lists, shows, dismisses or actions a report, or suspends an account:
node dist/src/cli/reports.js list [--all]
node dist/src/cli/reports.js show <id>
node dist/src/cli/reports.js dismiss <id> ["note"]
node dist/src/cli/reports.js action <id> ["note"]
node dist/src/cli/reports.js suspend <userId>
node dist/src/cli/reports.js suspend --report <reportId>
node dist/src/cli/reports.js unsuspend <userId>
node dist/src/cli/reports.js file <reportId> <fileId> --out <dir>
list without --all shows only open reports; dismiss/action only work on one that is still open. suspend sets suspended_at and revokes every one of that account's live sessions immediately (rather than waiting for its next request to hit requireSession's own self-heal); suspend --report <reportId> suspends that report's target the same way and marks the report actioned. unsuspend only clears suspended_at. The tool never prints an email: list and show print the reporter's and the reported user's ids (what suspend takes) with their name and username, or "(deleted)" once an account is gone.
file writes <fileId>-<name> (the name shortened, its extension kept, when the whole would pass a filesystem's 255-byte limit) into --out, mode 0600, and refuses when that file is already there. The bytes go to a hidden temporary name in the same directory first (.<fileId>-<12 hex>.part) and take the final name only once all of them are written. A run that fails with an error, or is stopped by Ctrl-C (SIGINT), docker stop (SIGTERM) or a closed terminal (SIGHUP), removes its temporary file and exits (130, 143 or 129 for the signals), so it leaves no partial copy and a rerun is never refused because of one. A run killed outright (SIGKILL, the kernel's out-of-memory killer included) cannot clean up: it can leave that hidden .part file, which ls does not show. In production the server container is read-only, with only a tmpfs at /tmp, so a moderator writes there, copies the file out, and removes it, together with any such leftover. The container of an installed server is <instance>-server (WT_INSTANCE, docs/operations.md):
docker exec <instance>-server node dist/src/cli/reports.js file <reportId> <fileId> --out /tmp
docker cp <instance>-server:/tmp/<written file> <a path on your own machine>
docker exec <instance>-server rm /tmp/<written file>
docker exec <instance>-server sh -c 'rm -f /tmp/.*.part'
Nothing removes them otherwise: a tmpfs file is memory, counted against the container's memory limit for as long as it exists.
7. Sessions & devices
Every route below requires a session. 7.1 to 7.3 work for a phone and for the same-origin cookie web, and a linked web gets 403 PHONE_ONLY. 7.7, 7.9 and 7.10 are the phone's alone: anything but the phone (a linked web, the same-origin cookie web) gets 403 PHONE_ONLY. 7.4 and 7.5 work for a phone and for a linked web.
7.1 GET /v1/sessions
Every live session of the caller, newest first:
[
{ "id": "<16 hex, public>", "label": "WiraTalk 0.1.0 · Android", "client": "android", "createdAt": "...", "lastUsedAt": "...", "current": true }
]
A linked web calling this is 403 PHONE_ONLY; its own grants are listed at 7.9.
id is the session's public id (publicSessionId, src/sessions/sessions.ts), a one-way hash of the real session id: it names a session without ever handing back something a client could authenticate with. current is true for the session the request itself used.
7.2 DELETE /v1/sessions/:id
Revokes one session by its public id (7.1). Idempotent and leaks nothing: an unknown id, or one belonging to someone else, is a silent no-op, answering { "ok": true } either way, exactly like removing someone who was never a contact (5.5). Revoking the session that authenticated this very request also clears the __Host-wt_sid cookie, when that session was a cookie one. The revoked session's device row (7.4) goes with it, and so do the linked webs (7.6) that session made. Audits session_revoked. A linked web calling this is 403 PHONE_ONLY.
7.3 POST /v1/sessions/revoke-others
Ends every one of the caller's sessions except the one making this call ("sign out everywhere else"), and their device rows (7.4):
{ "revoked": 2 }
It also ends every linked web (7.6) of the account, and counts them in revoked: a person who suspects a lost device expects every other way in to close. Audits other_sessions_revoked. A linked web calling this is 403 PHONE_ONLY.
7.4 PUT /v1/devices/current
{ "platform": "android", "fcmToken": "<FCM token, or null>", "appVersion": "0.1.0" }
One device row per session (session_public_id, unique), for push notifications and the "your devices" account screen. platform is android, web or ios; fcmToken and appVersion are optional (null/absent clears them). The web app registers the FCM token of its service worker once the browser allows notifications (13.4); until then it registers with no fcmToken. Calling this again for the same session updates the one row in place, never a duplicate. fcmToken is globally unique: a token already held by another of this device's rows (a reinstall, or the same push registration seen from a different session) moves to this row, leaving the old row's token null. Answers { "id": "<device row uuid>" } and audits device_registered. A malformed platform is 400 INVALID_REQUEST; a call already under way when the account is deleted is 401 UNAUTHENTICATED, as every later call of that session is.
A device row never outlives its session: signing out (3.7), revoking a session (7.2, 7.3), disabling the account and account deletion all delete the rows of the sessions they end, and a housekeeping job (every 10 minutes) removes the rows of sessions that expired while idle. A signed-out phone therefore stops receiving push at once. A linked web (7.6) registers its row like any session, with its own access token, and the row goes when the web ends (the phone removes it, the phone's session ends, or the web is unused for 30 days); until then the sweep keeps it.
The server clears a row's fcmToken when FCM says that token is dead (13.6); the row and its session stay. The app registers its current token again at every start and whenever Firebase hands it a new one, which puts it back. Only android and web tokens are pushed to (section 13); an ios token is kept but not used until the iOS app.
7.5 DELETE /v1/devices/current
Removes this session's device row (signing out of push without ending the session). Idempotent: a session with no device row still answers { "ok": true }.
7.6 Linked devices
A linked device is a web the phone signed in by scan. Its grant lives in wiratalk.linked_devices and has two states: pending (the phone made a code, 7.7; it waits up to 120 seconds for the exchange, 3.14) and active (exchanged). Only SHA-256 hashes of codes and tokens are stored.
Tokens, each wtc_, wta_ or wtr_ followed by 32 random bytes in base64url:
| token | for | lifetime |
|---|---|---|
wtc_ code | the exchange (3.14), inside the envelope (7.8) | 120 seconds, one use, only while the phone session that made it is signed in |
wta_ access token | every route, as Authorization: Bearer wta_... | 15 minutes; one live token per grant, a refresh replaces it |
wtr_ refresh token | POST /v1/auth/linked/refresh (3.15) | replaced on every use; a second use ends the grant |
An access token that is unknown or past its 15 minutes is 401 ACCESS_TOKEN_EXPIRED: refresh, then retry. A header that starts Bearer wta_ but is malformed (wrong length or characters) is no session at all: 401 UNAUTHENTICATED, and neither a phone bearer nor a cookie is consulted. 401 UNAUTHENTICATED keeps its one meaning, the session is dead; a linked web gets it from the refresh once the grant is gone.
A linked web ends when the person removes it on the phone, the phone session that linked it ends (including its idle expiry), the person chooses "sign out everywhere else", the account is disabled, its password is reset, the account is deleted, or it goes 30 days without use. It also ends when the web signs out (3.7) or its refresh token is used twice (3.15). Each end deletes the grant, closes its event streams with session.revoked (9.1), removes its device row (7.4) and tells the phone with linked_devices.changed. An account has at most 5 grants, pending ones included (409 LINKED_DEVICE_LIMIT).
A linked web acts as a session of its own on every route that is not phone-only. The server gives it an internal session id derived from the grant (never handed out and no bearer), which is why its device row (7.4), its viewing presence (11.24) and session.revoked (9.1) work as for any session. For account deletion (8.1) the 15 minutes count from linking.
The web's duties:
- keep the refresh token in IndexedDB, wrapped with a non-extractable WebCrypto key; never in
localStorageor a cookie; - keep one stored token pair for all tabs: both the access token and the refresh token are shared, never copied per tab (a tab that refreshes with its own copy of the refresh token presents a spent one, which ends the grant);
- refresh one tab at a time (the Web Locks API) and before
accessExpiresAt; each tab re-reads both stored tokens inside the lock before it refreshes, and refreshes only when the stored access token is the one that just failed, otherwise it retries with the stored one; - on
ACCESS_TOKEN_EXPIRED, refresh and retry the call once; - send no request headers beyond the ones CORS allows (section 1);
- on
UNAUTHENTICATED, drop its tokens and show the QR again.
7.7 POST /v1/linked-devices
The phone, after scanning the QR (7.8):
{ "webPublicKey": "<87 base64url characters>", "label": "Laptop kantor" }
label is optional, 1 to 60 visible characters, the phone's own name for the web. webPublicKey must be a point on P-256. Answers
{ "id": "uuid", "codeExpiresAt": "<ISO, 120 seconds ahead>", "envelope": { "v": 1, "epk": "...", "iv": "...", "ct": "..." } }
and the app posts envelope to the Hub (15.2). Errors: 400 INVALID_REQUEST (a missing, malformed or off-curve key, a bad label); 403 PHONE_ONLY; 409 NOT_LISTED; 409 LINKED_DEVICE_LIMIT; 429 RATE_LIMITED (10 a 10 minutes per account; every call counts, refusals included). When the Hub refuses the envelope (404 or 409), the app deletes the pending grant with 7.10.
7.8 The pairing envelope
src/linked/envelope.ts. To sign a browser in, the web shows a QR code and the phone answers it with one envelope that only that browser can open. The QR text is
wiratalk-pair:v1:<pairingId>:<webPublicKey>
pairingId is 22 base64url characters (made by the Hub, 15.2). webPublicKey is 87 base64url characters: the 65-byte uncompressed P-256 point 0x04 || X || Y (WebCrypto exportKey('raw')) of a fresh, non-extractable key pair the web makes for every pairing. The QR is replaced every 2 minutes. All base64url here is unpadded and canonical.
Envelope = { "v": 1, "epk": "<87 chars: the server's ephemeral 65-byte point>", "iv": "<16 chars: 12 bytes>", "ct": "<ciphertext || 16-byte tag, 17 to 4096 bytes>" }
The sealed plaintext is UTF-8 JSON:
{ "v": 1, "apiBase": "<this server's origin>", "serverEntry": "<its signed directory entry, a JWS>", "code": "wtc_<43 characters>", "codeExpiresAt": "<ISO time>" }
serverEntry is the entry the Hub signed for this server (section 15); a server that is not listed yet cannot link a web (NOT_LISTED, section 2).
Three ASCII strings fix the construction:
| name | value |
|---|---|
| salt | wiratalk-pairing-v1 |
| info prefix | wiratalk-pairing-v1 key |
| additional data | wiratalk-pairing-v1 envelope |
The server makes a fresh P-256 key pair and a random 12-byte iv, then:
Z= ECDH(server private key, web public key): the 32-byte X coordinate.K= HKDF-SHA-256 with inputZ, the salt above,info= the info prefix followed byepk(65 bytes) and the web public key (65 bytes), 32 bytes out.ct= AES-256-GCM(K,iv, additional data above) over the plaintext, with the 16-byte tag appended.
Both public keys are inside info, so K belongs to this one exchange.
The web opens it with WebCrypto:
importKey('raw', epk, { name: 'ECDH', namedCurve: 'P-256' }, false, []).deriveBits({ name: 'ECDH', public: epkKey }, webPrivateKey, 256)givesZ.importKey('raw', Z, 'HKDF', false, ['deriveKey']), thenderiveKey({ name: 'HKDF', hash: 'SHA-256', salt, info }, hkdfKey, { name: 'AES-GCM', length: 256 }, false, ['decrypt']).decrypt({ name: 'AES-GCM', iv, additionalData, tagLength: 128 }, key, ct)(the tag is the last 16 bytes ofct).
After opening, the web checks: v is 1; serverEntry verifies (EdDSA, typ wiratalk-directory+jws, a key id it has pinned); the entry's apiBase equals the plaintext's apiBase, its status is active and its expiresAt is in the future; codeExpiresAt is in the future. Only then does it exchange the code at <apiBase>.
Known-answer vector (the web private key, the server's ephemeral private key and the iv are fixed here only so that an implementation can be checked without a server; z and key are hex):
{
"webPrivateKeyHex": "027670925797df7bbd543142183236920974eee19b122f91c60072b2ddfe6397",
"webPublicKey": "BMqhEEsgXUtC9YbDS5_htT6UdfZB8VvMTNzC4Pnr3d9lYgPTPPnF2N_Tza2pWm0SJ1caB-TKzM45-YEvAHtwzkk",
"ephemeralPrivateKeyHex": "c83fe16ff97d3b497ab59a4b7d050fef9f678a718f1cd82d56c969c35691be66",
"ivHex": "000102030405060708090a0b",
"plaintext": "{\"v\":1,\"apiBase\":\"https://chat.contoh.test\",\"serverEntry\":\"e30.e30.c2ln\",\"code\":\"wtc_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\",\"codeExpiresAt\":\"2026-10-05T02:02:00.000Z\"}",
"z": "77a639581cc63a332e4116357b221f9748c9a39c19f4b248941827c135d5631d",
"key": "1f32b33248fba4e7b5cff6e4613d034737b56125798a309dd49e8ac04663313e",
"envelope": {
"v": 1,
"epk": "BJst5TF7czPGS2k8adfK413vPNjq1SW7-VDyQY6tjCE3L4WrAEors-n22uOpZWP_wmeav1foCpzp424LL4-DmP4",
"iv": "AAECAwQFBgcICQoL",
"ct": "j3yaZvP5WIWuJPRSnQyH74BN2GRCndcmGS7bri53YAVlAeSu8hEUJsw2UnvObl-72dJHiCVcosTqdBmOKocuFmIjrx3d8RlZOnshp8E61MX6WzeCEMTfQ2SnryHf9XndouuxbEMChNa5VXMrklYDvBqiczkQfFFjDyT7PScYiw6IXBw8_4x4ZzEFSqxURdm8JOM7Rib_5U-FkUDhPdB3-TC8tFz4r4VsJZ7fYL74aZty5ho2C4mGu64Eftf_"
}
}
7.9 GET /v1/linked-devices
The phone's active grants, newest first, at most 5:
[ { "id": "uuid", "label": null, "browser": "Chrome · Windows", "place": "Bandung, Indonesia", "linkedAt": "...", "lastUsedAt": "..." } ]
browser and place are null when the exchange did not carry them (place needs the location headers of the proxy in front of the server); place is "Kota, Negara" in the request's language. lastUsedAt is written at most once a minute. The app refetches on linked_devices.changed (9.1). 403 PHONE_ONLY.
7.10 DELETE /v1/linked-devices/:id
Ends one grant of the caller, pending ones included, and answers { "ok": true }. Like 7.2 it leaks nothing: an unknown id, someone else's, one already gone or one that is not a uuid all answer { "ok": true } and remove nothing. The web's access token is 401 ACCESS_TOKEN_EXPIRED at once and its refresh 401 UNAUTHENTICATED. Audits linked_device_removed for a grant that existed. 403 PHONE_ONLY.
8. Account
8.1 POST /v1/account/delete
{ "confirmUsername": "rina" }
Deletes the caller's account outright, immediately, no grace period (the recent-auth check and the typed confirmation below already prove intent). Three checks, in order:
- The last admin. The only active admin of the company cannot delete their own account: 409
LAST_COMPANY_ADMIN, nothing is changed and the session stays. Make another person an admin first (14.2). - Recent auth. The session making this call must be at most 15 minutes old (
createdAt, notlastUsedAt; from a linked web, 7.6, the 15 minutes count from linking, which the phone's approval made a fresh sign-in); otherwise 403RECENT_AUTH_REQUIRED. There is no step-up sign-in flow yet: the client's own remedy is to sign the person in again and retry. - Typed confirmation.
confirmUsernamemust equal the account's ownusername; an account with no username yet (needsUsername: true) instead requiresconfirmEmailto equal itsemail, case-insensitive. Anything else (including a missing field) is 400CONFIRMATION_REQUIRED.
On success: every session is revoked, the wiratalk.users row is deleted (cascading to the identities, password, avatar, devices, contacts, blocks and the contact link; wiratalk.reports rows naming this user keep their row with reporter_id/target_user_id set null, docs/schema.md), the cookie is cleared when the calling session was a cookie one, and the deletion is audited account_deleted (detail: {"reason": "user"}; the audit row has no foreign key on the user it named, so it survives the account it explains). Answers { "ok": true }.
Chat (section 11): the account's memberships, stars, "deleted for me" marks and per-conversation settings go with it. Messages it already sent stay: each gets senderId: null and a new rev (so every other member's changes sync, 11.15, turns them into "Akun terhapus"), and every message quoting one of them, whoever sent it, also gets a new rev (its reply preview's senderId changes to null too, even though the quoting message itself is otherwise untouched). A group whose only current admin this was gets its earliest-joined remaining member as admin. A conversation nobody is a member of any more is deleted with its messages. The remaining current members of every conversation it was in get conversation.changed. No system message is written.
Files (section 12): uploads the account made but never sent are collected at the next round (12.5). Files attached to its messages stay with those messages (the recipients already received them) and simply lose their uploader. Group photos it set stay. Reports keep their evidence (6.5).
8.2 GET /v1/account/export
Everything WiraTalk itself holds about the caller: profile, contacts, blocks, devices, sessions, linked webs, the reports they filed, their conversations and every message they sent. Never includes another user's email, even one that user has made discoverable (5), and never another person's message: contacts, blocks, reported users and direct-conversation partners are named only by id (plus name and username where the profile endpoints already do).
{
"exportedAt": "2026-09-28T10:00:00.000Z",
"profile": { "...": "MeView (4.1) plus createdAt and lastSignInAt" },
"contacts": [{ "id": "uuid", "name": "Rina", "username": "rina", "nickname": "Ri", "createdAt": "..." }],
"blocks": [{ "id": "uuid", "name": "...", "username": "...", "createdAt": "..." }],
"devices": [{ "id": "uuid", "platform": "android", "appVersion": "0.1.0", "label": "...", "createdAt": "...", "lastSeenAt": "..." }],
"signIn": { "identities": [{ "provider": "local", "createdAt": "...", "lastUsedAt": "..." }], "passwordSetAt": "..." },
"sessions": [{ "id": "<16 hex>", "label": "...", "client": "android", "createdAt": "...", "lastUsedAt": "..." }],
"linkedDevices": [{ "id": "uuid", "label": null, "browser": "Chrome · Windows", "city": null, "country": null, "linkedAt": "...", "lastUsedAt": "..." }],
"reports": [{ "id": "uuid", "targetUserId": "uuid", "reason": "spam", "note": null, "status": "open", "createdAt": "..." }],
"conversations": [{ "id": "uuid", "kind": "group", "title": "Tim Desain", "peerId": null, "role": "admin", "isMember": true, "joinedAt": "..." }],
"files": [{ "id": "uuid", "kind": "image", "name": "WiraTalk-20261001-104200.jpg", "mime": "image/jpeg", "size": 482113, "createdAt": "...", "attached": true }],
"filesTruncated": false,
"messages": [{ "conversationId": "uuid", "seq": 12, "kind": "media", "body": "caption or text", "attachments": [{ "fileId": "uuid", "kind": "image", "name": "...", "mime": "image/jpeg", "size": 482113, "durationMs": null }], "replyToSeq": null, "forwarded": false, "createdAt": "..." }],
"messagesTruncated": false
}
messages: every message the caller sent that still exists (not deleted for everyone), regardless of the caller having since left the conversation, cleared it or hidden the message for themselves, ordered by conversation then seq, at most 100,000 (messagesTruncated: true when there are more). Because of that, a message's conversationId can name a conversation absent from conversations above (a group left and then cleared deletes the membership row, 8.1, but not the messages already sent into it); conversations itself has no such cap, every membership row the caller has or had. The answer is streamed (chunked), still one JSON document, with messages and messagesTruncated last.
files: every upload of the caller that still exists AND is still readable (12.4: unsent, or still linked), oldest first, at most 10,000 (filesTruncated: true when there are more). attached says whether it is currently attached to a message (false for one never sent). A file that was once attached and has since lost its last link is left out of this list entirely, not merely marked: since 12.4 already answers 404 to its own uploader once that happens, even while the file is held for a report, listing it here would be the one remaining way for the export to tell a reported sender that one of their files had been unlinked. The bytes are not in the JSON: the caller downloads any of them with 12.2 while it is still linked or unsent (12.4). Each own message carries its attachments (null for a text message).
Rate limited: 5 per hour per user (export). Audits account_exported.
9. Live events
9.1 GET /v1/events (Server-Sent Events)
A session (Bearer, or the __Host-wt_sid cookie: GET is a safe method, so no CSRF header is needed) with Accept: text/event-stream. A dead session answers 401 UNAUTHENTICATED before any byte. HEAD answers the same headers with an empty body (a proxy health check); any other method is 405.
On success the server sends, in order:
retry: 5000(the reconnect delay a well-behavedEventSourcehonors).event: hellowith{}, right after the stream subscribes to this user's and this session's channels: a client that missed changes made before it connected refetches its state onhello.- One
event:per change concerning this user (the table below), for as long as the stream stays open. event: hbwith{}every 25 seconds while nothing else is happening. This is a real named event, not a:comment: the browser'sEventSourcecannot see comments, so a client watchdog needshbto tell a silent-but-alive connection from a dead one.
Every frame is one event: line and one single-line JSON data: line, followed by a blank line:
event: user.changed
data: {"userId":"<uuid>"}
Events published on a change (src/events/events.ts):
| event | data | sent when |
|---|---|---|
user.changed | {"userId":"<uuid>"} | the caller's own profile, name or username changed, or the stored photo changed (section 4) |
contacts.changed | {} | a contact was added, removed, or a contact link was accepted |
blocks.changed | {} | a block was added or removed |
sessions.changed | {} | a session of this user was created or revoked |
linked_devices.changed | {} | a linked web of this user was added, removed or ended: refetch 7.9 |
session.revoked | {} | THIS session or linked web was revoked; the server closes the stream right after sending it |
message.new | {"conversationId": "<uuid>", "message": Message, "users": [UserRef]} | a message this user can see was written: a send (11.16), a forward (11.17), a group event (kind: "system"). A conversationId the client does not know means a new conversation: fetch 11.6 |
message.changed | {"conversationId": "<uuid>", "seq": 12, "rev": 57, "change": "deleted"} | change is deleted (to everyone who can see the message, 11.18), hidden, starred or unstarred (to the user who did it, for their other devices, 11.18 and 11.19) |
conversation.changed | {"conversationId": "<uuid>"} | the title, the group photo (11.28), the members, a role or the pinned message changed (current members), or the user's own settings, clear or membership changed (that user): refetch 11.6 |
conversation.removed | {"conversationId": "<uuid>"} | the user forgot a group they had left (11.13): drop it |
receipt.changed | {"conversationId": "<uuid>", "userId": "<uuid>", "readSeq": 12, "deliveredSeq": 12} | a read or delivered position moved (11.22): to that user, and in a direct conversation also to the other person |
typing | {"conversationId": "<uuid>", "userId": "<uuid>"} | another current member is typing (11.23) |
Chat events never carry anything the receiving user may not see: a message.new whose quoted message (replyTo) predates the receiver's joinedSeq arrives with that quote as available: false (11.2). Live events are a fast path only; the changes sync of 11.15 is the source of truth, and a client never advances its stored rev from an event.
The server ends every stream after 10 minutes of age regardless of activity; the client is expected to reconnect (retry: 5000 above), at which point it gets a fresh hello and refetches.
Limits, enforced per server process: at most 3 open streams per session (opening a 4th closes the oldest of that session) and 20 per user (opening a 21st closes the oldest of that user); at most 30 stream openings per minute per user (429 RATE_LIMITED beyond that). Closing a stream for any reason (the client disconnects, the age limit, a limit above, the session being revoked) releases its Redis subscriptions.
10. Public
Everything here is public: no session, no CSRF header. Pages are HTML under a strict CSP, the rest is JSON or a file. src/http/routes/public.ts.
10.1 Pages
| Path | What |
|---|---|
/privacy, /terms, /delete-account | The legal documents (10.2) as HTML: a petrol title band, contents, the text, the contact |
/credits | The typeface licence (Roboto, SIL OFL 1.1) |
/download | The Android APK of 10.7 with version, size, date and the signing certificate fingerprint (from ANDROID_CERT_SHA256); without a release, a link to the web app |
/c/:token | The invite page of a contact link (10.4) |
Indonesian by default, English with ?lang=en (any other value is Indonesian); Content-Language says which. Every page: Content-Type: text/html; charset=UTF-8, Cache-Control: public, max-age=300 (the invite page: private, no-store), and
Content-Security-Policy: default-src 'self'; script-src 'none'; object-src 'none'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'
No scripts, no inline styles, nothing from a third party: the stylesheet, the Roboto fonts and the favicon are served by this server under /site-assets/<name>?v=<content hash> (Cache-Control: public, max-age=31536000, immutable; the prefix is not /assets/ because the web app has its own assets/ folder). The look is design direction A ("Petrol Keluarga"): band #0A4C60, primary #0D6478, ground #F4F6F8, white cards with a 22 px radius. The WiraTalk logo is a placeholder drawn in src/site/svg.ts only (header, footer, favicon), so the real logo is one edit away. The pages name the developer ("WiraTalk dikembangkan oleh WIRA Code Indonesia"), the company running this server (WT_LEGAL_NAME, default the company name) and its contact address (WT_PRIVACY_EMAIL), never a personal name; the footer ends with © 2026 WIRA Code Indonesia.
10.2 GET /v1/legal/:doc
:doc is privacy, terms or delete-account; anything else is 404 NOT_FOUND. ?lang=en for English. The same document the HTML page is rendered from, so the app's native screens and the web pages can never differ:
{
"id": "privacy",
"lang": "id",
"title": "Kebijakan Privasi WiraTalk",
"description": "...",
"updated": "2026-09-29",
"url": "https://talk.wiracode.com/privacy",
"intro": [Block],
"sections": [{ "id": "data", "heading": "2. Data yang Kami Proses", "blocks": [Block] }],
"footer": [Block]
}
Block is {"type":"paragraph","spans":[Span]}, {"type":"list","ordered":bool,"items":[[Span]]} or {"type":"table","header":[string,string],"rows":[[[Span],[Span]]]}. Span is {"type":"text"|"bold"|"number","text":...} or {"type":"link","text":...,"link":Link}, where Link is {"kind":"doc","doc":"terms","section":"rules"} (navigate natively), {"kind":"mailto","email":...,"subject"?:...} or {"kind":"external","url":"https://..."}. A client renders an unknown span type as its plain text and skips an unknown block type. Section ids are stable anchors (the app links to delete-account#deleted-data and terms#rules). Cache-Control: public, max-age=300 with a strong ETag; If-None-Match (also weak W/"...", a list, or *) answers 304. Every number in the documents (retention, backups, sessions, minimum age, request and report handling times) comes from src/config/constants.ts.
The documents are built from the operator profile of the configuration: the company running the server is the controller (WT_LEGAL_NAME, contact WT_PRIVACY_EMAIL), the country the server is in comes from WT_DATA_COUNTRY, the provider rows of the privacy policy from WT_PROCESSORS (role=name pairs separated by ;; roles hosting, cdn, storage, email, backup), and the file-version sentence from WT_FILES_VERSION_DAYS (omitted at 0). The brand line names the developer.
10.3 The web app and the coming-soon page
Every GET or HEAD that no route answers and that is not under /v1, /.well-known/ or /site-assets/ is the web app (the Flutter web build in WEB_DIR):
- A file in
WEB_DIRanswers as itself withCache-Control: no-cacheand a contentETag(304 onIf-None-Match). - A missing path whose last segment does not end in a static-file extension (
.js,.wasm,.json,.png,.otf,.frag, ...) is a page of the app:WEB_DIR/index.html(history routing:/chats/abc,/auth/return?code=...,/?invite=<token>). Without a build inWEB_DIR, the coming-soon page ("WiraTalk Segera Hadir", links to the legal pages and the download;noindexon any path but/). - Anything else is a 404: never
index.html, so the app never parses HTML as a missing script or font. A browser (Accept: text/html) gets the HTML 404 page (noindex), anything else JSONROUTE_NOT_FOUND.
Refused with a 404 whatever exists on disk: a path segment that is .., starts with a dot, or contains /, \ or NUL after decoding; source maps (*.map); and anything whose real path (symlinks resolved) is outside WEB_DIR. Every response from WEB_DIR carries
Content-Security-Policy: default-src 'self'; script-src 'self' 'wasm-unsafe-eval'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; font-src 'self'; connect-src 'self' https://firebaseinstallations.googleapis.com https://fcmregistrations.googleapis.com; media-src 'self' blob:; worker-src 'self' blob:; frame-ancestors 'none'; base-uri 'self'; form-action 'self'
Permissions-Policy: camera=(self), microphone=(self), display-capture=(self), geolocation=()
(every other response keeps camera=(), microphone=()).
Files, thumbnails and group photos (12.2, 12.3, 11.28) are same-origin /v1/... URLs: img-src 'self' and media-src 'self' already allow them, and the __Host-wt_sid cookie authorizes them like any other GET.
The policy means the web build must ship its own CanvasKit (no gstatic.com script CDN). base-uri is 'self' (it was 'none' until 2026-09-29): the build's <base href="/"> must apply, or a reload of any nested page such as /auth/return loads /auth/flutter_bootstrap.js and the app never starts. font-src is 'self' only: the engine's fallback fonts come through the same-origin proxy of 10.8 (https://fonts.gstatic.com was dropped from font-src on 2026-09-29, nothing used it). connect-src adds exactly the two hosts the Firebase JS SDK calls to get and refresh the browser's FCM token, from the page and from its service worker (13.4): https://firebaseinstallations.googleapis.com and https://fcmregistrations.googleapis.com. The SDK is bundled with the web build (script-src 'self'): the service worker never loads it from gstatic.com. Unknown API paths never reach the web app: /v1/nope is JSON ROUTE_NOT_FOUND even for a browser, and any other method than GET or HEAD on an unknown path is JSON ROUTE_NOT_FOUND too.
10.4 GET /c/:token
The public page of a contact link (5.6), mobile first. A valid token whose owner is not suspended shows "<Nama> mengajak Anda ngobrol di WiraTalk" (English: "<Name> invites you to chat on WiraTalk"; no name: the @username), initials in a circle (never the photo), the @username (never the email), and three buttons:
- Buka di aplikasi: on an Android User-Agent the Chrome intent link
intent://<host>/c/<token>#Intent;scheme=https;package=com.wiraapps.talk;end(Chrome rebuildshttps://<host>/c/<token>from it and hands it to the installed app; App Links, 10.5), elsewhere the https link itself; - Unduh untuk Android:
/download; - Buka di web:
/?invite=<token>.
An unknown, malformed or rotated token, or a suspended owner, answers an HTML 404 in the same look. Both carry <meta name="robots" content="noindex"> and Cache-Control: private, no-store, so a rotated link or a suspension takes the page down at once.
10.5 GET /.well-known/assetlinks.json
Android App Links for https://<host>/c/*, from ANDROID_CERT_SHA256 (a comma list of certificate SHA-256 fingerprints: upload key and Play app signing key):
[{
"relation": ["delegate_permission/common.handle_all_urls"],
"target": { "namespace": "android_app", "package_name": "com.wiraapps.talk",
"sha256_cert_fingerprints": ["0F:0F:...:0F"] }
}]
Fingerprints as Android tools print them (uppercase hex pairs joined by colons). ANDROID_CERT_SHA256 unset: []. Content-Type: application/json; charset=utf-8, Cache-Control: public, max-age=300. Any other /.well-known/ path is JSON ROUTE_NOT_FOUND.
10.6 GET /v1/health
{ "ok": true, "db": true, "redis": true, "push": "ready", "version": "0.6.0" }
ok is db && redis; HTTP 503 when either is down (same body shape). push (section 13) is off (no WT_LICENCE_KEY, or the Hub has refused the licence, section 15), unknown (the Hub has not answered a credential check yet: the one at start, then again 30 seconds after one that got no answer, doubling to every 5 minutes, until it answers; a check without an answer never turns it failing, so a blip of the network, the Hub or FCM at start shows as unknown, not as a failure), ready (the Hub accepted the licence at the last check or send; with nothing sent for 30 minutes it is checked again) or failing (the Hub refused the licence key, reason credential, or three worker turns in a row had a failure and no success; a check without an answer counts as such a turn only once the Hub has answered one; checked again every 5 minutes and after every send). Every check is a validate-only call: nothing is delivered. push never makes ok false: chat works without push. version is the server's package.json version.
10.7 App release
RELEASES_DIR (default <root>/releases, read only) holds latest.json (at most 1 MiB, written by the app's release script) and the APK it names:
{ "latestVersion": "0.1.0", "minSupportedVersion": "0.1.0", "notes": "...",
"releasedAt": "2026-09-29", "fileName": "wiratalk-0.1.0.apk", "size": 31457280,
"sha256": "<64 lowercase hex>" }
Only a fileName of the form wiratalk-<version>.apk inside RELEASES_DIR is ever served; anything else counts as no release. sha256 is the APK's SHA-256 (the release script computes it); a missing or malformed value is answered as "". The app's self-updater (internal flavor) downloads the APK and installs it only when its SHA-256 equals this value, so it never offers a release that has none.
GET /v1/app/version answers the manifest plus "apkUrl": "<WT_PUBLIC_ORIGIN>/v1/app/apk" (Cache-Control: private, no-store), or 404 NO_RELEASE.
GET /v1/app/apk streams the APK (Content-Type: application/vnd.android.package-archive, Content-Disposition: attachment; filename="wiratalk-<version>.apk", Accept-Ranges: bytes). One Range: bytes=... range answers 206 with Content-Range; an unsatisfiable one 416 with Content-Range: bytes */<size>; HEAD answers the headers only. No release: 404 NO_RELEASE.
10.8 GET /fonts/fallback/<path>
The web app's font fallback, same origin. Flutter's web engine downloads a Noto font the first time a page shows a character its bundled fonts lack (an emoji, Chinese or Japanese text, a check mark), with fetch() from fontFallbackBaseUrl. The web build sets that to /fonts/fallback/ (the app's web/flutter_bootstrap.js) instead of the engine's default https://fonts.gstatic.com/s/, which the SPA CSP's connect-src 'self' refuses; the server fetches the same file from https://fonts.gstatic.com/s/<path> itself, so the reader's browser never contacts Google. src/site/font-fallback.ts.
<path>must look like the paths Flutter 3.44.8's engine requests (itsfont_fallback_data.dart, 694 files, plus Roboto):<family>/v<N>/<name>[.<chunk>].woff2, matched on the raw (still percent-encoded) path with^[a-z0-9]{1,40}/v[0-9]{1,3}/[A-Za-z0-9_-]{1,128}(\.[0-9]{1,3})?\.woff2$. Anything else (other extensions,%escapes, extra segments) is 404NOT_FOUNDwith no outbound call, and so is any request with a query string, even an empty?(the engine never sends one, and every?xvariant would miss the Cloudflare edge cache).- The upstream call sends no cookie and no client header, follows no redirect, and is bounded by 10 s and 2 MiB (the largest file of 3.44.8's set is 709,292 bytes).
- At most 16 downloads from Google at once, server-wide; one more is answered 503
SERVICE_UNAVAILABLEat once, with no outbound call. - 200: the font,
Content-Type: font/woff2,Cache-Control: public, max-age=31536000, immutable. Upstream 404: 404NOT_FOUND. Any other upstream status, a redirect, a timeout, a network error, an empty or oversized body, or a body that does not start with the WOFF2 signaturewOF2: 503SERVICE_UNAVAILABLE. Failures carryCache-Control: no-store. - No session needed and none set.
GET/HEADonly (405 otherwise). Rate limited: 300 per 10 minutes per IP (font-fallback-ip), counted only for paths that pass the check above.
10.9 GET /.well-known/wiratalk
The company's identity. No session; HEAD answers the headers only, other methods 405 METHOD_NOT_ALLOWED, any other /.well-known/ path 404 ROUTE_NOT_FOUND. 200, Content-Type: application/json, Cache-Control: no-store:
{
"serverId": "srv_abcdefghijklmnop",
"name": "PT Contoh",
"apiVersion": 1,
"minAppVersion": "0.1.0",
"authMethods": ["password"],
"licenceKeyId": null
}
serverId:WT_SERVER_ID, the id WiraTalk Hub issued (^[a-z0-9][a-z0-9_-]{5,63}$). The Hub fetches this document before it lists the server and requires the sameserverId.name: the company name (WT_COMPANY_NAME, 1 to 100 characters).apiVersion: the API version this server speaks (1).minAppVersion: the oldest app version the server serves; the app refuses to talk to a server that asks for a newer one than it is.authMethods: the ids of the sign-in methods (GET /v1/auth/providers):passwordandoidc:<id>for each enabled provider.licenceKeyId: the first 16 base64url characters of the SHA-256 ofWT_LICENCE_KEY, ornullwhile no key is set. The Hub compares it with the id of the key a company registers with. It is a one-way hash prefix; the key itself is never served, logged or put in an error.
Versions
apiVersionis an integer (1). It changes only when a change would break a client written for the previous value, and the app refuses a server whoseapiVersionit does not speak. Additions (a new field, a new route) keep it.minAppVersionis the oldest app the server serves. It is raised only when a client must update, and the app refuses to talk to a server that asks for a newer app than it is.- The server's own version (
versioninGET /v1/health, andpackage.json) is the release a company installs. It is also the image tagtalk.wiracode.com/wiratalk/server:<version>. - Every release publishes this document as the WiraTalk Server API of that version on the Hub (
/business/docs/api/<version>), so a company reads the contract of the version it runs.
The document stays far under the Hub's 8 KiB cap. The Hub lists only an https address on port 443, so a server is registrable (key set, https, no port) or it runs for local use only.
10.10 GET /v1/company and GET /v1/company/logo
The company's name and logo for the sign-in and invitation screens. No session needed; GET and HEAD only.
GET /v1/company: 200 { "name": "PT Contoh", "logoEtag": "0123456789abcdef" } (logoEtag is null while there is no logo), Cache-Control: public, max-age=60. The name is the one an admin saved (14.4), else WT_COMPANY_NAME.
GET /v1/company/logo: the logo as image/webp, 512 x 512, with a strong ETag ("<logoEtag>"), Cache-Control: public, max-age=300 and Cross-Origin-Resource-Policy: cross-origin (the one answer that allows other sites to embed it). A matching If-None-Match is 304. No logo: 404 NOT_FOUND.
11. Chat
Direct and group conversations with text messages. Photos, voice notes and files as media messages (11.16), the media gallery (11.27), group photos (11.28), the files themselves (section 12) and push notifications (section 13). Reactions, stickers, threads, mentions and message info come later; their message kinds already exist in the data model. Every route requires a session (a cookie session on an unsafe method also needs the CSRF header, section 1). src/chat/, src/http/routes/conversations.ts, src/http/routes/messages.ts.
11.1 Rules every chat route follows
- Conversations.
kindisdirect(exactly two people, one conversation per pair, created on first use by 11.4) orgroup(a title, up to 64 current members, admins and members, 11.5 to 11.11). - seq. Every message has a
seq: 1, 2, 3, ... per conversation, allocated in the sending transaction, never skipped and never reused (a refused or duplicate send allocates nothing). Group events (created, members added, removed, left, renamed) are messages too (kind: "system") and take a seq like any other. - rev. Every conversation has a
revcounter that moves whenever a message a client may have cached changes: a new message, a deletion for everyone, a star or unstar (the starred message itself changes), a sender deleting their account, or one member hiding a message for themselves (11.18). Every change has arevof its own. A message carries therevof its last change. Clients catch up with 11.15. - Visibility. A member sees a message when its
seqis abovejoinedSeq, aboveclearedSeq, (after leaving or being removed) at mostleftSeq, and they have not deleted it for themselves.joinedSeqis the conversation's last seq when they joined (0 for the creator and the first members), so a member added later sees the "added" message and everything after it, never the history before it. Every answer below (history, changes, list previews, the pinned message, starred messages, search, live events, report evidence) follows this one rule. - Non-members. Any route naming a conversation the caller is not a member of (never was, or forgot it with 11.13) answers 404
NOT_FOUND, exactly like a conversation that does not exist, never 403. A malformed id or seq in the path is also 404. Answers that depend only on the request or the caller, never on the conversation (a malformed body: 400; no username yet: 409USERNAME_REQUIRED; a rate limit: 429), may come before the membership check; otherwise a non-member always gets 404. - Former members. After leaving (11.11) or being removed (11.9) a person stays a former member: read routes keep working within their visible range (history up to
leftSeq, changes, starred and starring, search, read receipts, hiding, 11.12, 11.13), but a route that needs current membership (sending, being a forward target, typing, pinning, group management) answers 403NOT_A_MEMBER. A former member sees the title the group had when they left, no member list, no member count and no pinned message. - Username. Starting a conversation (11.4, 11.5), sending (11.16) and forwarding (11.17) need the caller to have a username: 409
USERNAME_REQUIREDotherwise. - Blocks (6.2). In a direct conversation where either person has blocked the other, sending and forwarding into it answer 403
BLOCKED(the same answer to both sides: nobody learns who blocked), typing is not relayed, and read/delivered receipts do not cross the block either: a move still reaches the reader's own other devices (11.22), but never the other person's, and both sides' summaries (11.2, 11.3, 11.6) answerreceipts: nullfor the conversation, the same asBLOCKEDitself, for as long as the block stands. The conversation, its history and 11.4 keep working. Once neither side has the other blocked any more, receipts (and typing) resume normally, with no special catch-up: the positions were moving the whole time, only unannounced. Groups are unaffected (a blocked person's group messages are still delivered and visible, receipts included), except that two people where one has blocked the other can never add each other to a group (11.5, 11.8), and a person gets no push notification for group messages from someone they blocked. - Deleted accounts. Messages a deleted account sent stay, with
senderId: nulland a newreveach; clients show them as "Akun terhapus" / "Deleted account". A direct conversation whose other person deleted their account stays readable; sending answers 409PEER_DELETED. A user id insidesystem(11.2) that is missing fromusersis also a deleted account. - Kinds. The server writes
textandsystemmessages andmediamessages (a caption inbodyplusattachments, 11.2).stickerandcallarrive in later versions: a client that meets akindit does not know MUST show a neutral "update WiraTalk to see this message" bubble, never drop the message (itsseqstill counts). - Message text.
bodyis 1 to 4000 characters (Unicode code points) after cleaning:\r\nand\rbecome\n; control characters other than\nand\t, and the bidi override and isolate characters (U+202A to U+202E, U+2066 to U+2069), are removed; leading and trailing whitespace is trimmed. Line breaks inside are kept. An empty result is 400INVALID_REQUEST; over 4000 characters is 400MESSAGE_TOO_LONG. - Users. Answers that carry messages or conversations also carry
users: aUserReffor every user id they mention that still exists (senders, the other person of a direct conversation, quoted senders, ids insidesystem). A client overlays its own contact nicknames (5.3). - Clock. Time windows (the 5-minute delete) use the database clock.
11.2 Shapes
UserRef:
{ "id": "uuid", "name": "Rina Maharani", "username": "rina.m", "avatarEtag": null }
Message:
{
"conversationId": "uuid",
"seq": 12,
"rev": 31,
"senderId": "uuid",
"kind": "text",
"body": "Oke, nanti aku kirim filenya ya",
"system": null,
"attachments": null,
"replyTo": null,
"forwarded": false,
"clientId": "k3J9x0aQ2mZpW8vB",
"createdAt": "2026-09-30T10:42:00.000Z",
"deletedAt": null,
"starredByMe": false
}
senderId:nullfor asystemmessage and for a message whose sender deleted their account.body:""forsystemmessages and for a message deleted for everyone (deletedAtset).bodyof amediamessage is its caption:""when there is none.attachments:nullfor every kind butmedia, and after a deletion for everyone; formedia, an array ofAttachment(exactly one today; clients MUST accept more, for albums later). It is a snapshot taken when the message was sent: the same file forwarded elsewhere carries the samefileId.
Attachment:
{
"fileId": "uuid",
"kind": "image",
"mime": "image/jpeg",
"size": 482113,
"name": "WiraTalk-20261001-104200.jpg",
"width": 1920,
"height": 1440,
"durationMs": null,
"waveform": null,
"blur": "UklGRkAAAABXRUJQVlA4IDQAAADwAQCdASoYABIAPm0u..."
}
kind:image(a photo, re-encoded by the server:mimeisimage/jpeg, orimage/webpwhen the image has an alpha channel, which every GIF has),voice(a voice note:audio/mp4,audio/webmoraudio/ogg) orfile(anything sent as a document;mimeis what the bytes, then the name, look like, for the icon only: a file is always downloaded, never shown inline).size: bytes of what is stored (for an image, the re-encoded one).name: images and voice notes get one from the server (WiraTalk-<yyyymmdd>-<hhmmss>.<jpg|webp|m4a|webm|ogg>, UTC); a file keeps its cleaned client name (12.1).width,height: images only (at most 2560), elsenull.durationMs: voice only (1 to 1,800,000), elsenull.waveform: voice only, 0 to 64 integers 0 to 255 (the bars of the voice bubble, as the sender's client measured them), elsenull.blur: images only: base64 of a WebP of at most 24 px on its long side (at most 2048 characters), drawn blurred while the image loads (F-Media: "Media belum diunduh ditampilkan buram");nullwhen none could be made that small.- The bytes:
GET /v1/files/<fileId>(12.2), the thumbnail of an imageGET /v1/files/<fileId>/thumb(12.3). clientId: the sender's idempotency key (11.16), echoed to every member so the sending device can match the live event to its outbox before the HTTP answer arrives.nullforsystemmessages.replyTo:null, or aReplyPreviewof the message it answers (same conversation):
{ "seq": 7, "senderId": "uuid", "kind": "text", "body": "Pagi! Laporan minggu ini sudah jadi?", "deleted": false, "available": true, "attachment": null }
body is at most 160 characters. deleted: true (and body: "") when that message was deleted for everyone. available: false (with body: "", senderId: null, kind: "text") when the reader joined after that message: a quote never reveals history from before joining. attachment (also in MessagePreview below): null, or for a media message that is not deleted and available, an AttachmentPreview of its first attachment, { "fileId": "uuid", "kind": "voice", "name": "WiraTalk-20261001-104000.m4a", "durationMs": 14000 }: what a client needs to write "Foto", "Pesan suara 0:14" or the file name next to the quote or the list preview (A-Conversation, F-WebTwoPane), and the thumbnail URL of an image (12.3). That thumbnail may answer 404 when the reader can no longer see the quoted message (12.4); clients draw the kind icon then.
starredByMe: whether the reader starred it (alwaysfalsein live events).system(only whenkindissystem) is rendered by the client in the reader's language; every id in it is a user id:
type | fields | Indonesian rendering, for reference |
|---|---|---|
group_created | actorId, title, userIds (the first members, without the creator) | Rina membuat grup "Tim Desain" |
members_added | actorId, userIds | Rina menambahkan Bayu, Dewi |
member_removed | actorId, userId | Rina mengeluarkan Bayu |
member_left | actorId | Bayu keluar |
title_changed | actorId, title | Rina mengganti nama grup menjadi "Tim Q4" |
photo_changed | actorId | Rina mengganti foto grup |
photo_removed | actorId | Rina menghapus foto grup |
A client hides a system message whose type it does not know.
MessagePreview (a list's last message, the pinned message):
{ "seq": 12, "senderId": "uuid", "kind": "text", "body": "at most 160 characters", "system": null, "deleted": false, "createdAt": "...", "attachment": null }
ConversationSummary:
{
"id": "uuid",
"kind": "direct",
"title": null,
"peerId": "uuid",
"photoEtag": null,
"memberCount": 2,
"role": null,
"isMember": true,
"joinedSeq": 0,
"clearedSeq": 0,
"leftSeq": null,
"lastSeq": 12,
"rev": 31,
"lastReadSeq": 10,
"unread": 2,
"markedUnread": false,
"mutedUntil": null,
"pinnedAt": null,
"lastMessage": { "...": "MessagePreview, or null" },
"lastActivityAt": "...",
"pinnedMessage": null,
"receipts": { "readSeq": 11, "deliveredSeq": 12 },
"createdAt": "..."
}
title: groups only (nullfor direct); a former member gets the title as it was when they left.peerId: direct only: the other person, ornullonce they deleted their account.photoEtag: groups only: the etag of the group photo (11.28),nullwhen there is none, for a direct conversation, and always for a former member. A client fetchesGET /v1/conversations/<id>/photowhen it changes, else draws the initials.memberCount: current members;nullfor a former member.role:"admin"or"member"for a current group member,nullotherwise.lastSeq: the last seq the caller can know about: the conversation's last seq, orleftSeqfor a former member.unread:max(0, lastSeq - max(lastReadSeq, joinedSeq, clearedSeq)). It counts every seq,systemmessages included.mutedUntil:null(not muted) or when the mute ends; a year-9999 value means "until unmuted" (11.12). A client compares it with the current time for the muted icon; push honours it.lastMessage: the last message the caller can see, ornull.lastActivityAt:lastMessage.createdAt, or the conversation'screatedAtwhen there is none.pinnedMessage:null, or aMessagePreviewplus"pinnedBy": "uuid or null"and"pinnedAt": "..."(11.21);nullwhen the caller cannot see that message, and always for a former member.receipts: direct only: the other person'sreadSeqanddeliveredSeq(delivered is never below read). A client draws the ticks of its own messages from it:seq <= readSeqread (blue double tick),seq <= deliveredSeqdelivered (grey double tick), otherwise sent (one tick).nullfor groups (a group message shows the single "sent" tick, as in other messengers; per-member positions are stored for a later message info view), for a direct conversation whose other person deleted their account, and for a direct conversation with a block either way (11.1): both sides then see single ticks, the same answer to both, for as long as the block stands.
Member (11.6): { "userId": "uuid", "role": "admin", "joinedAt": "..." }.
ConversationRef (starred and search results): { "id": "uuid", "kind": "group", "title": "Tim Desain", "peerId": null } (title and peerId as in ConversationSummary).
11.3 GET /v1/conversations
{ "conversations": [ConversationSummary], "users": [UserRef] }
Every conversation the caller is a current or former member of that holds at least one message they can see: a new direct conversation without a message is not listed, and neither is one they cleared (11.13) until a new message arrives. Pinned conversations first (pinnedAt, newest first), then by lastActivityAt, newest first. At most 1000. The "Semua / Belum dibaca / Grup" tabs and searching conversation names are done by the client on this list.
11.4 POST /v1/conversations/direct
{ "userId": "uuid" }
Gets or creates the one direct conversation between the caller and userId. Calling it again, from either side, or twice at once, returns the same conversation. Answers { "conversation": ConversationSummary, "users": [UserRef] } (a new one has lastMessage: null). The other person sees it only after the first message. Works even when a block is in place (sending then answers BLOCKED). Errors: 400 INVALID_REQUEST (userId missing, malformed, or the caller's own), 404 NOT_FOUND (unknown or suspended user), 409 USERNAME_REQUIRED, 429 (chat-direct).
11.5 POST /v1/conversations/group
{ "title": "Tim Desain", "memberIds": ["uuid", "uuid"], "clientId": "k3J9x0aQ2mZpW8vB" }
Creates a group with the caller as its only admin. title: cleaned with the same control-character and whitespace rules as about (4.2), at most 80 characters after cleaning, and never empty after cleaning either (400 otherwise). Unlike about, this limit is checked only after cleaning, not on the raw input: raw input is accepted up to 1000 characters before cleaning (400 past that), then cleaned and measured. memberIds: 1 to 64 uuids (400 otherwise); duplicates and the caller's own id are dropped; what is left must be 1 to 63 ids (none left: 400; more: 409 GROUP_FULL). An id that is unknown, suspended, or blocked either way with the caller is not added and comes back in notAdded (the client can say "Tidak bisa menambahkan Bayu" without learning why). Writes the first message, system.type: "group_created". clientId (optional): 8 to 64 characters of A-Za-z0-9_-, the same format as a message's (11.16), generated once per attempt by the client and reused on every retry; unique per creator, not per conversation (there is none yet). A retry with a clientId the caller already used answers the group it made the first time, with duplicate: true, notAdded: [], and creates nothing (no new conversation, members, group_created message or audit row); this includes two concurrent creates with the same clientId, which make one group between them, the same idempotent-retry shape as a duplicate send (11.16), at the same status, 200. Omitting clientId behaves exactly as before: every call makes a new group. Answers { "conversation": ConversationSummary, "users": [UserRef], "notAdded": ["uuid"], "duplicate": false }. Errors: 400, 409 GROUP_FULL, 409 USERNAME_REQUIRED, 429 (group-create). Audits group_created (not on a duplicate answer).
11.6 GET /v1/conversations/:id
{ "conversation": ConversationSummary, "members": [Member], "users": [UserRef] }
Answers for a conversation without messages too. members: the current members, admins first, then by joinedSeq, then joinedAt, then id as further tiebreakers (both people of a direct conversation, role member); [] for a former member. joinedSeq and joinedAt normally agree; the rare case they do not (two adds racing the conversation lock) is src/chat/groups.ts's promoteIfNoAdmin. A client fetches this when a live event names a conversation it does not know or says it changed.
11.7 PATCH /v1/conversations/:id
{ "title": "Tim Desain Q4" }
Renames a group. Admins only (403 ADMIN_REQUIRED); a direct conversation is 400. Title rules as in 11.5; the same title again changes nothing and writes nothing. Writes title_changed. Answers like 11.6. Audits group_renamed. 429 (group-admin).
11.8 POST /v1/conversations/:id/members
{ "userIds": ["uuid"] }
Adds members. Admins only. 1 to 64 uuids (400 otherwise); ids that are already current members, and the caller's own, are ignored; ids that cannot be added (11.5's rules) come back in notAdded. When the group would pass 64 current members, 409 GROUP_FULL and nothing is added. A former member added again starts over: they see the new "added" message and what follows, not their earlier history. Writes one members_added naming everyone added. Answers { "added": ["uuid"], "notAdded": ["uuid"] }. Audits group_members_added. 429 (group-admin).
11.9 DELETE /v1/conversations/:id/members/:userId
Removes a current member (any role). Admins only. Removing yourself is 400 (use 11.11); a user who is not a current member is 404. Writes member_removed; its seq becomes the removed person's leftSeq, so they see that message and nothing after it. { "ok": true }. Audits group_member_removed. 429 (group-admin).
11.10 PUT /v1/conversations/:id/members/:userId/role
{ "role": "admin" }
Admins only; role is admin or member; the target must be a current member (404 otherwise). Demoting the only admin (which can only be yourself) is 409 LAST_ADMIN. Setting the role it already has changes nothing. No system message. { "ok": true }. Audits group_role_changed. 429 (group-admin).
11.11 POST /v1/conversations/:id/leave
Groups only (a direct conversation is 400; to take it off the list, 11.13). Writes member_left; its seq becomes the caller's leftSeq. When the last admin leaves and current members remain, the member who joined earliest (ties by id) becomes admin. Leaving again is a no-op. { "ok": true }. 429 (group-admin).
11.12 PUT /v1/conversations/:id/prefs
{ "mutedUntil": "always", "pinned": true, "markedUnread": false }
The caller's own settings for this conversation; every field is optional. mutedUntil: null (unmute), "always" (stored as 9999-12-31T00:00:00.000Z), or a future RFC 3339 timestamp (up to 9 fractional digits, as the Dart VM sends microseconds; anything past milliseconds is dropped); a past or malformed one is 400. pinned: true sets pinnedAt to now (again: refreshes it), false clears it. markedUnread: the "mark as unread" dot; reading (11.22) clears it. Former members may change these too. Answers { "mutedUntil": null, "pinnedAt": "...", "markedUnread": false } and sends conversation.changed to the caller's own streams. 429 (chat-action). While mutedUntil is in the future the caller gets no push notification from the conversation (13.1; mentions will get through a mute later).
11.13 POST /v1/conversations/:id/clear
"Hapus chat", for the caller only. A current member: clearedSeq becomes the conversation's last seq; everything up to it disappears from every answer to them, their stars and "deleted for me" marks at or below it are dropped, and the conversation leaves their list until a new message arrives: { "removed": false, "clearedSeq": 42 }. A former member of a group: the membership is removed for good (the conversation then answers 404 to them like to any non-member), conversation.removed goes to their streams: { "removed": true, "clearedSeq": null }. Other members are not affected. 429 (chat-action).
11.14 GET /v1/conversations/:id/messages
Query: at most one of before=<seq> (older than), after=<seq> (newer than), around=<seq> (centred on it, inclusive); none = the latest page. limit 1 to 100, default 50. Anything else (two cursors, a value that is not a non-negative integer) is 400.
{ "messages": [Message], "users": [UserRef], "hasMoreBefore": true, "hasMoreAfter": false }
messages is ascending by seq and holds only what the caller can see (11.1): a gap in seq is a message hidden from them. around=S returns up to ceil(limit / 2) messages at or below S and the rest above S. hasMoreBefore/hasMoreAfter say whether a page in that direction may exist (it can come back empty when everything left there is hidden).
11.15 GET /v1/conversations/:id/changes?sinceRev=<rev>
sinceRev is required (a non-negative integer); limit 1 to 500, default 200.
{ "rev": 57, "messages": [Message], "hiddenSeqs": [9], "users": [UserRef], "hasMore": false }
Every message the caller can see whose rev is above sinceRev (new, deleted for everyone, starred or unstarred, sender deleted), ascending by rev, and the seqs the caller deleted for themselves since then (on another device). Store rev and pass it as the next sinceRev; while hasMore is true, call again right away. The client upserts messages by seq and drops hiddenSeqs. A message can come back unchanged for this caller (another member starred it: the star is private, the new rev is not); upserting handles that. sinceRev=0 pages through the whole visible history.
Sync recipe: on hello (9.1) refetch 11.3; page 11.15 for each conversation whose rev is above the stored one; drop cached messages at or below clearedSeq or joinedSeq, and above leftSeq.
A former member calls this the same way and keeps getting real answers (11.1): messages and hiddenSeqs never include a seq above leftSeq, no matter how far the conversation moves afterwards. But rev (11.1) is one counter for the whole conversation, so it keeps climbing from activity the former member can no longer see (a current member's new messages); the rev this call answers with, once caught up, tracks that same counter. Seeing rev advance again later (here or in 11.3) is therefore not a promise of anything new for a former member, only that the conversation moved; the next 11.15 call for it can legitimately answer messages: [], hiddenSeqs: [], hasMore: false. That answer is still the signal to stop: store the rev it gives back and do not call again until it is asked to (the next time 11.3 reports a higher one for this conversation), the same rule as for a current member. A star or a deletion for everyone on a message at or below leftSeq still reaches a former member this way, since it is within what they can see.
11.16 POST /v1/conversations/:id/messages
{ "clientId": "k3J9x0aQ2mZpW8vB", "body": "Ini foto papan tulis tadi", "replyToSeq": null, "attachments": [{ "fileId": "uuid" }] }
clientId: 8 to 64 characters of A-Za-z0-9_-, generated once per message by the client (its outbox) and reused on every retry. replyToSeq: optional; a message of this conversation the caller can see (404 otherwise; one deleted for everyone is fine, its preview says so). attachments: optional; absent or null sends a text message (body required, 11.1). Otherwise exactly one { "fileId": "uuid" } (none, more, a duplicate or a malformed id: 400): the message is kind: "media" and body is an optional caption (missing, null or empty after the 11.1 cleaning means none, ""; over 4000 characters 400 MESSAGE_TOO_LONG). The file must be one the caller uploaded (12.1) and still usable: stored, not collected, and either currently linked to a message already or never linked and uploaded less than 24 hours ago (database clock); a file that was linked once and later lost its last link (a deletion for everyone, or its conversation deleted) is never usable again, however young it still is. Anything else, including someone else's upload (which answers exactly like an unknown id), is 409 FILE_UNAVAILABLE, and nothing is written (no seq is taken). Sending the same upload again, here or in another conversation, links the same file: nothing is copied. Current members only.
{ "message": Message, "users": [UserRef], "duplicate": false }
A retry with a clientId this conversation already holds from the caller answers that message with duplicate: true and changes nothing (no new seq, no event); the same clientId from another member is 400. This answer keeps working for the caller even after they stop being a current member (leave or removal): the message already exists and is unaffected by that, and an outbox retrying after a restart must not mark it failed. The duplicate check comes before every file check: retrying a media message that was already sent answers duplicate: true even after its upload would have expired. A brand new clientId from a former member is 403 NOT_A_MEMBER, like any other write. A send also moves the caller's own lastReadSeq and delivered position to the new seq and clears their markedUnread, and announces that implicit move with the same receipt.changed a POST read (11.22) would (the caller's own streams and, in a direct conversation, the other person). Everyone who can see the message gets message.new. Errors: 400 INVALID_REQUEST, 400 MESSAGE_TOO_LONG, 403 NOT_A_MEMBER, 403 BLOCKED, 404 (also a send that was already under way when the caller's own account was deleted: nothing is stored), 409 FILE_UNAVAILABLE, 409 PEER_DELETED, 409 USERNAME_REQUIRED, 429 (chat-send).
11.17 POST /v1/conversations/:id/messages/:seq/forward
{ "clientId": "f8Qm2LpA9x0zR1sT", "targets": [{ "conversationId": "uuid" }, { "userId": "uuid" }] }
Copies a text or media message the caller can see (not deleted: 404; any other kind: 400) into 1 to 5 distinct targets (400 otherwise): a conversation (the caller must be a current member) or a person (their direct conversation, created if needed). Each copy is an ordinary send (11.16) with forwarded: true and no reply, and every target reuses the one clientId (it is unique per conversation), so retrying the whole call duplicates nothing. A media copy links the same files (its attachments carry the same `fileId`s): nothing is copied in the store, and the copy keeps the files alive after the original is deleted (12.5). One target failing does not stop the others:
{
"results": [
{ "conversationId": "uuid", "message": Message, "duplicate": false },
{ "userId": "uuid", "conversationId": "uuid", "code": "BLOCKED" }
],
"users": [UserRef]
}
results has one entry per target, in the order of targets (results[i] answers targets[i]); a successful result for a userId target carries the direct conversationId but no userId, so clients match results to targets by position. A failed result echoes its target (conversationId, or userId plus the conversationId it would have gone to when that is known, else null) and the code 11.4 or 11.16 would have answered (NOT_FOUND, NOT_A_MEMBER, BLOCKED, PEER_DELETED, FILE_UNAVAILABLE, INVALID_REQUEST). Errors of the call itself: 400, 404 (the source), 409 USERNAME_REQUIRED, 429 (chat-forward).
11.18 DELETE /v1/conversations/:id/messages/:seq?scope=me|everyone
scope=me: hides the message from the caller only (current and former members; any message they can see,systemincluded). Idempotent. Their other devices getmessage.changedwithchange: "hidden", and 11.15 lists it inhiddenSeqs. Hiding the current pinned message also sends the caller's own devicesconversation.changed(theirpinnedMessage, 11.2, now answersnull; nobody else's does).scope=everyone: the sender only (403NOT_SENDER, also for asystemmessage), within 5 minutes ofcreatedAt(403DELETE_WINDOW_EXPIRED), current members only. The text is erased for good (body: "",deletedAtset,replyTo: nulleven if the message itself was a reply; a report filed earlier keeps its own copy, 6.5), stars on it are removed, its attachments go too (unlinking them: once no other message links the file any more, it stops being readable for everyone, its uploader included, 12.4, and is deleted from the store at the next collection, 12.5), it stops being the pinned message, and everyone who can still see it (11.1'sVISIBLE_SQL: not someone who already hid it or cleared past it) getsmessage.changedwithchange: "deleted". Every message that quoted it gets a newrevin the same change (its ownreplyTopreview is now{ deleted: true, body: "" }, 11.2), without amessage.changedof its own: the tombstone's event already tells an affected client to sync 11.15, which returns the re-revved quote too. Already deleted: 404. Group admins cannot delete other people's messages. A push notification that still shows the message is replaced (13.5).
Any other scope is 400. { "ok": true }. 429 (chat-action).
11.19 PUT /v1/conversations/:id/messages/:seq/star and DELETE (same path)
Stars or unstars a message for the caller only. Starring needs a non-system message (400) the caller can see and not deleted (404). Both are idempotent and answer { "starred": true } / { "starred": false }; a real change gives the message a new rev and sends message.changed (starred or unstarred) to the caller's own streams. 429 (chat-action).
11.20 GET /v1/starred
Optional conversationId=<uuid> (404 when the caller is not a member, or the value is not a uuid).
{ "items": [{ "conversation": ConversationRef, "message": Message, "starredAt": "..." }], "users": [UserRef] }
The caller's starred messages they can still see (not deleted, not hidden, not cleared), newest star first, at most 500.
11.21 PUT /v1/conversations/:id/pin and DELETE (same path)
PUT with { "seq": 4 } pins a message as the conversation's banner, for every member (one per conversation: pinning another replaces it). Any current member; a message they can see, not deleted (404), not system (400). Answers { "pinnedMessage": PinnedMessage } (11.2's pinnedMessage shape). DELETE unpins, idempotent, { "ok": true }. A real change sends conversation.changed to the current members. 429 (chat-action).
11.22 POST /v1/conversations/:id/read and POST /v1/conversations/:id/delivered
{ "seq": 12 }
Moves the caller's read position (which also moves delivered, and clears markedUnread) or delivered position forward to seq (a non-negative integer, 400 otherwise), capped at the last seq they can see, never backwards. Answers { "lastReadSeq": 12, "deliveredSeq": 12 }. Clients post delivered when a message reaches the device (live event or sync) and read when it is on screen. When a position moves, receipt.changed goes to the caller's own streams and, in a direct conversation, to the other person (groups: the caller only) unless a block stands either way between them, in which case it goes only to the caller's own streams (11.1). A group action that moves the actor's own position (11.5 to 11.11: creating, renaming, adding, removing, a role change, leaving) announces it the same way, to the actor's own streams only. Former members may post these too. 429 (chat-receipt).
11.23 POST /v1/conversations/:id/typing
No body. Tells the other current members "typing" (the typing event). A client shows it for 5 seconds after the last event, and hides it at once when a message from that person arrives; it may post as often as every keystroke: the server relays at most one per 3 seconds per person and conversation. Current members only (403 NOT_A_MEMBER). Not relayed in a direct conversation with a block either way (still { "ok": true }). { "ok": true }. 429 (chat-typing).
11.24 PUT /v1/presence/viewing
{ "conversationId": "uuid" }
"This session has this conversation open on screen", or { "conversationId": null } when none. It lasts 75 seconds: a client repeats it every 30 seconds while the conversation stays open and sends null when it closes. Push notifications (13.1) skip a person who has a session viewing that conversation, on every device of theirs; only a live session counts (a linked web is one), and a session that signs out or is revoked (7.3) stops viewing at once. 404 when the caller is not a member (current or former); 400 for a malformed or missing conversationId. { "ok": true }. 429 (chat-presence).
11.25 GET /v1/search/messages
Query: q (2 to 100 characters after trimming, a case-insensitive substring; %, _ and \ match themselves), optional conversationId (404 when not a member or not a uuid), optional filter, limit 1 to 100, default 30. filter:
- absent: text messages and media captions matching
q(qrequired); links: messages whose text or caption containshttp://orhttps://;images: media messages with an image (the "Foto" tab of F-Search);files: media messages with a file (the "Dokumen" tab);qalso matches the file name.
With a filter, q may be absent or shorter (absent: every such message); any other filter value is 400.
{ "results": [{ "conversation": ConversationRef, "message": Message }], "users": [UserRef] }
Messages the caller can see (11.1), not deleted, newest first, across all their conversations (or the one named). 429 (chat-search).
11.26 Rate limits
| bucket | limit | used by |
|---|---|---|
chat-direct | 60 per minute per user | 11.4 |
group-create | 20 per hour per user | 11.5 |
group-admin | 60 per minute per user | 11.7 to 11.11 |
chat-send | 60 per minute per user | 11.16 |
chat-forward | 20 per minute per user | 11.17 |
chat-action | 120 per minute per user | 11.12, 11.13, 11.18, 11.19, 11.21 |
chat-receipt | 600 per minute per user | 11.22 |
chat-typing | 40 per minute per user | 11.23 |
chat-presence | 60 per minute per user | 11.24 |
chat-search | 30 per minute per user | 11.25 |
file-upload | 100 per 10 minutes per user | 12.1 |
file-download | 1200 per minute per user | 12.2, 12.3, 11.28 GET |
push-user | 60 per minute per user | 13.1: new notifications an account receives, one hit per account and conversation per worker turn however many of its devices the coalesced push reaches; a retry of the same job and a deletion's replacement (13.5) are exempt and never count against it, because a replacement must never be dropped; past the limit a new one is dropped, the request that caused it is never refused |
Reads (11.3, 11.6, 11.14, 11.15, 11.20, 11.27) are not rate limited. 11.28's PUT and DELETE use group-admin.
11.27 GET /v1/conversations/:id/media
The media gallery of one conversation ("Media, file, dan tautan", F-Media). Query: kind = image, voice or file (required), optional before=<seq> (older than), limit 1 to 100, default 50; anything else is 400.
{ "messages": [Message], "users": [UserRef], "hasMore": true }
The media messages of that kind the caller can see (11.1), not deleted, newest first. Next page: before = the smallest seq of this page, while hasMore. The "Tautan" tab is 11.25 with filter=links and conversationId. A non-member gets 404.
11.28 PUT /v1/conversations/:id/photo, DELETE and GET (same path)
The group photo (F-GroupName, F-GroupInfo). Groups only: on a direct conversation PUT and DELETE answer 400 and GET 404.
PUTwith{ "fileId": "uuid" }: admins only (403ADMIN_REQUIRED), current members only (403NOT_A_MEMBER). The file must be an image the caller uploaded that is still usable (11.16's rule; anything else 409FILE_UNAVAILABLE). The server keeps its own 512 x 512 WebP crop (the centre of the image), so the upload itself may expire afterwards. If the square crop still exceeds 262,144 bytes (256 KiB) after its quality steps down, and, for an image with an alpha channel, after that alpha is flattened onto white and quality steps down again, the request fails with 415UNSUPPORTED_FILE_TYPErather than ever storing an oversized crop. Writes the system messagephoto_changedand sendsconversation.changedto the current members; setting the same picture again changes nothing. Answers{ "photoEtag": "16 hex" }. Auditsgroup_photo_changed. 429 (group-admin).DELETE: admins only; writesphoto_removedand sendsconversation.changedwhen there was a photo, else changes nothing.{ "ok": true }. Auditsgroup_photo_changed(detail: {"removed": true}). 429 (group-admin).GET: current members only; the WebP itself (Content-Type: image/webp,ETag: "<photoEtag>",Cache-Control: private, max-age=86400; 304 on a matchingIf-None-Match). No photo, a former member, a non-member: 404. 429 (file-download).
12. Files
Photos, voice notes and documents. A client uploads the bytes first (12.1), then sends a message naming the file (11.16). Every byte goes through this server, same origin: there are no presigned URLs. The store is the company's own S3 bucket or the package's bundled MinIO, reached by the server only, under the key prefix FILES_S3_PREFIX. src/files/, src/http/routes/files.ts.
12.1 POST /v1/files
Query: kind = image, voice or file (required); size = the exact number of bytes in the body (required, at least 1); for file, name (the file's name, URL-encoded, optional); for voice, durationMs (required, 1 to 1,800,000) and waveform (optional: 0 to 64 comma-separated integers 0 to 255, for example waveform=3,40,255,12). Body: the raw bytes of the file (no multipart form); Content-Type is ignored. A Content-Length, when sent, must equal size (400 otherwise). A cookie session also needs the CSRF header (section 1). The caller needs a username (409 USERNAME_REQUIRED).
Caps by kind (decided from size before a byte is read, 413 PAYLOAD_TOO_LARGE with limitBytes): image 16,777,216 bytes (16 MiB), voice 8,388,608 (8 MiB), file 99,614,720 (95 MiB, under Cloudflare's 100 MB). A body longer than size is cut off at once (413); a shorter one, or one that stops sending for 60 seconds, is 400 INVALID_REQUEST. A refused upload's connection is closed.
The type comes from the bytes, never from the client:
image: JPEG, PNG, WebP or GIF (its first frame), at most 40 megapixels; anything else (HEIC included: convert to JPEG first), or bytes that cannot be decoded, is 415UNSUPPORTED_FILE_TYPE. The server turns it upright (EXIF orientation), scales it to at most 2560 px on its long side and re-encodes it (JPEG, or WebP when it has an alpha channel) WITHOUT any metadata: no EXIF, no GPS position, no camera details. The original is never stored. A thumbnail (WebP, at most 480 px) and theblur(11.2) are made from the result.voice: MP4/M4A (AAC), WebM (Opus) or Ogg (Opus); anything else is 415. Stored as sent.file: anything, stored byte for byte (a photo sent as a document keeps its metadata: the app says so). Itsnameis cleaned: control and bidi characters and/\become_, spaces collapse, leading and trailing dots and spaces go, at most 255 characters (the extension kept); missing or empty:berkas.
{ "file": Attachment, "expiresAt": "2026-10-02T10:42:00.000Z" }
file is the Attachment (11.2) a message will carry. expiresAt: the upload must be sent (11.16) before then, else it is collected (12.5). Errors: 400, 401, 409 USERNAME_REQUIRED, 413, 415, 429 RATE_LIMITED (file-upload, or more than 3 uploads at once from this user, then retryAfterSec: 1), 429 UPLOAD_QUOTA_EXCEEDED (12.6), 503 SERVICE_UNAVAILABLE (the store cannot be reached, or the server already handles its maximum of uploads: retryAfterSec).
12.2 GET /v1/files/:id (and HEAD)
The stored bytes, to whoever may read them (12.4); anyone else, and a malformed id, gets 404 NOT_FOUND, the same answer as an unknown id.
Content-Type: the image or voice type;application/octet-streamfor everyfile.Content-Disposition:inlinefor images and voice notes,attachmentfor files, always withfilename="<ASCII fallback>"andfilename*=UTF-8''<the name>.Content-Security-Policy: default-src 'none'; frame-ancestors 'none'; sandbox(nothing served here can run).ETag: "<first 32 hex of SHA-256 of the bytes>";If-None-Matchanswers 304 (after the read check).Cache-Control: private, max-age=86400.Accept-Ranges: bytes. One range (bytes=a-b,bytes=a-,bytes=-n) answers 206 withContent-Range; a start past the end 416 withContent-Range: bytes */<size>and no body; several ranges or anything malformed are ignored (200, the whole file).HEADanswers the same headers withContent-Lengthand no body.
Streaming: the bytes come from the store as the reader takes them, so each download holds a store connection for as long as its body is being sent. Hence, for a download that reaches the store (a HEAD, a 304 and a 416 never do, and never count):
- at most 8 at once per user (429
RATE_LIMITED,retryAfterSec: 1) and 128 at once on the server (503SERVICE_UNAVAILABLE,retryAfterSec: 5); thumbnails (12.3) have counters of their own, 32 per user and 128 on the server, so a gallery's burst of thumbnails never refuses a document and slow document downloads never refuse a thumbnail; - a download whose reader takes no byte for 5 minutes is ended: the connection is closed mid-body. A reader that keeps taking bytes, however slowly, is never cut (the server sees the bytes its operating system has taken for sending, which it takes in steps;
src/files/download.tssays what that means on a very slow link). A client resumes with a range (bytes=<what it has>-).
The counters are released the moment a download ends, however it ends. Errors: 404, 429 RATE_LIMITED (file-download, or this user's concurrent downloads, retryAfterSec), 503 SERVICE_UNAVAILABLE (the store, or the server's concurrent downloads: retryAfterSec).
12.3 GET /v1/files/:id/thumb
An image's thumbnail (WebP, at most 480 px), with 12.2's rules, headers and answers (Content-Type: image/webp, its own ETag), counted against the thumbnail caps of 12.2 and 12.6. Not an image: 404.
12.4 Who can read a file
Exactly two kinds of people, everyone else gets 404:
- Its uploader, while the file is unsent (before it is sent: an outbox retry too) or while at least one message still links it (sending it again, a forward, the account export, 8.2). Once a file that was once attached has no link left, its uploader gets 404 too, the same instant as everyone else: this holds even while the file is held for a report (6.5), which only keeps the collector from erasing it so
src/cli/reports.ts filecan still read it; a hold never reopens a file to its uploader or to anyone else, since that would tell a reported sender they had been reported. - Anyone who can see (11.1: joined before it, not cleared past it, not after leaving, not hidden for themselves) a message that links the file and is not deleted for everyone. A forwarded copy is such a message too.
So a non-member, a member added after the message, someone who cleared the chat or hid the message, a former member for a message after they left, and everyone, uploader included, once the file's last link is gone, get 404.
12.5 How long a file lives
- Unsent. An upload nobody attached can be sent for 24 hours (
expiresAt); after that 11.16 answersFILE_UNAVAILABLE, and the next collection after 25 hours deletes it. An upload that never finished is deleted after an hour. - Sent. A file lives as long as one message (or forwarded copy) links it. When the last link goes (a deletion for everyone, a conversation nobody belongs to any more), it is deleted at the next collection.
- Collection runs every 15 minutes. It deletes the object (and the thumbnail) from the store, then its record. A store with versioning keeps a deleted object's previous version as long as its own rule says;
WT_FILES_VERSION_DAYSdeclares that to the privacy policy. - Held. A file named in a report's evidence (6.5) is not collected for 90 days from the report, even once its last ordinary link is gone, so that it still exists for
src/cli/reports.ts fileto read; 12.4 already closes it to everyone else's ordinary read at that point, its uploader included. - Account deletion (8.1): its unsent uploads are collected at the next round; files in its messages stay with the messages.
12.6 Limits
| What | Limit |
|---|---|
| Upload size | image 16 MiB, voice 8 MiB, file 95 MiB (12.1) |
| Image | at most 40 megapixels in; stored at most 2560 px, thumbnail 480 px |
| Voice note | at most 30 minutes (durationMs), at most 64 waveform bars |
| Uploads per user | 100 per 10 minutes (file-upload, 429 RATE_LIMITED); 3 at once (429 RATE_LIMITED, retryAfterSec: 1) |
| Unsent uploads per user | 100 (429 UPLOAD_QUOTA_EXCEEDED) |
| Volume per user | 2 GiB per 24-hour window from the first upload in it (429 UPLOAD_QUOTA_EXCEEDED, retryAfterSec) |
| File reads per user | 1200 per minute (file-download) |
| Downloads streaming at once | per user: 8 files, photos at full size and voice notes, plus 32 thumbnails (429 RATE_LIMITED, retryAfterSec: 1); per server: 128 of each (503 SERVICE_UNAVAILABLE, retryAfterSec: 5) (12.2) |
| A download's reader idle | 5 minutes without taking a byte, then the connection is closed (12.2) |
| Attachments per message | 1 (11.16) |
12.7 What clients send
Not enforced, but what the limits above assume:
- Photos are compressed before upload: JPEG, at most 2560 px on the long side, quality about 80 (F-AttachSheet: "Foto dikecilkan otomatis sebelum dikirim").
- Voice notes: Android records AAC in M4A (mono, 32 kbit/s is plenty); the web records what its browser's
MediaRecorderoffers (WebM Opus in Chrome and Firefox, MP4 AAC in Safari). The client measures the duration and up to 64 waveform bars itself. - A failed upload is retried with the same bytes; a send that answers
FILE_UNAVAILABLEuploads again, then sends with the newfileIdand the SAMEclientId.
13. Push notifications
The server hands every notification to WiraTalk Hub (15.1), which sends it through Firebase Cloud Messaging (project wira-apps) to the Android app and to the web app's service worker; no Firebase key is kept on the server. The server sends them only while it has a licence key and the Hub has not refused it (10.6 "push"); chat works the same without push. src/push/; the Redis keys are in docs/schema.md section 5.
13.1 Who is notified
A new text or media message (11.16, 11.17) is queued for push right after it is stored; a system message never is. When the push is sent (normally within a second; a push not sent within 15 minutes is dropped, never shown late; the one exception is a deletion's replacement, 13.5, which lives 24 hours), the server decides from the state at THAT moment who gets it:
- every current member who can see the message (11.1), except the sender: no device of the sender, phone or web, is notified of their own message;
- not a member while their mute lasts (11.12; a mention will get through a mute later);
- not a member who has blocked the sender (6.2);
- not a member who has already read it (
lastReadSeqat or past it, 11.22: read on another device, or by sending into the conversation in any way, a reply, a forward into it or a group admin's own change, all of which move the sender's read position, or by clearing it): a push that waited, a retry and a push taken up again after a crash never ring for a message already read; - not a member with any live session viewing the conversation (11.24): one open screen, phone or web (a linked web too), silences every device of that account;
- not a suspended account, and never a device whose session has ended (signed out, revoked, expired, or a linked web that ended), even before its device row is removed;
- at most 60 notifications a minute per account (
push-user, 11.26), counting only new pushes, one hit per account and conversation per worker turn however many of its devices the coalesced push reaches; past that they are dropped (the request that caused them is never refused). A retry of the same job and a deletion's replacement (13.5) are never counted against it and are never dropped by it, because a replacement must never be lost (a retry is a job that has already been sent to, or that waited out a refused key or an unfetchable access token: it names its devices); - on every device of those accounts that registered an FCM token (7.4),
androidorweb(aniostoken is kept but not used until the iOS app); - a device gets each message at most once, and never an older message of a conversation after a newer one; when several messages of one conversation wait for the same device, only the newest is sent, and its title says how many are unread.
A message deleted for everyone before its push went out is never shown.
Queuing is one Redis call made right after the message is stored. When it fails (a Redis error or timeout at that moment) or the server stops between the two, that push is lost, never retried: the message itself never is (the app syncs it on open), the send is never refused or delayed for it, and the loss is counted (enqueue_failed, 13.7) and logged. The same holds for a deletion's replacement (13.5).
A send FCM neither confirmed nor refused within its deadline ("maybe", 13.6) is sent again, so a device may alert once per such send for a message that is still unread (at most the 9 sends of 13.6); never for one already read.
13.2 What it says
The text is in the RECIPIENT's language (locale, 4.2; Indonesian unless en): the OS shows it while the app is not running.
title: the sender as the recipient knows them (the recipient's own contact nickname for them, 5.4; else the sender's name; else@username); in a group"<sender> @ <group title>". When more than one message of the conversation is unread for the recipient (theunreadof 11.2),(3 pesan)/(3 messages)is appended. At most 100 code points; the names are cut, never the count.body: a text message's text (or a photo's caption) on one line, at most 100 code points, the last one…when cut; for mediaFotoorFoto: <caption>,Pesan suara,Dokumen: <file name>(EnglishPhoto,Voice message,Document).- The replacement of a message deleted for everyone (13.5): another message that device may be showing, re-rendered with these rules but without the count; or, when there is none, the deleted message's title without the count and the body
Pesan ini telah dihapus/This message was deleted.
The title and body pass through Google's servers, as the privacy policy says ("Firebase Cloud Messaging").
13.3 Android
{
"token": "<the device's FCM token>",
"data": { "type": "chat_message", "conversationId": "<uuid>", "seq": "12" },
"notification": { "title": "Rina @ Tim Desain", "body": "Rapat jam 3 ya" },
"android": {
"priority": "high",
"restrictedPackageName": "com.wiraapps.talk",
"notification": { "channelId": "wiratalk_messages", "tag": "<conversation uuid>", "sound": "default" }
}
}
- Always priority high WITH a notification block: Android shows it itself while the app is killed or dozing, and no app code runs. With the app in the foreground Android does not show it; the app's
onMessagedoes. tagis the conversation id: a conversation has at most one notification, and the next one replaces it.- Never a
ttlor acollapseKey. - The app creates two channels:
wiratalk_messages(high importance, default sound) andwiratalk_updates(low importance, no sound: the replacement of 13.5). datacarries onlytype,conversationIdandseq(strings, as FCM requires). A tap opens/chats/<conversationId>(fromgetInitialMessageoronMessageOpenedApp),seqbeing the message to show.typeischat_message,chat_deletedortest(13.7); a client ignores atypeit does not know (call types, data-only with no notification block at all, will be added).
13.4 Web
{
"token": "<the browser's FCM token>",
"data": { "type": "chat_message", "conversationId": "<uuid>", "seq": "12" },
"webpush": {
"headers": { "TTL": "86400", "Urgency": "high" },
"notification": {
"title": "Rina @ Tim Desain", "body": "Rapat jam 3 ya", "tag": "<conversation uuid>",
"icon": "https://talk.wiracode.com/icons/Icon-192.png", "renotify": true, "silent": false
},
"fcmOptions": { "link": "https://talk.wiracode.com/chats/<conversation uuid>" }
}
}
The app's service worker (firebase-messaging-sw.js, with the Firebase SDK bundled, 10.3) lets the SDK show it; a click opens link. The browser token comes from the SDK's getToken with the project's VAPID public key BAzbn9pQ48k-ciLeRQ7CjVM2O-7tl0wrEVsP15NiZ7Qw6NWWCKBd9DXKfHrwiVKUcv3ZpVOXwLMv5ABwEWVCeT8 and is registered with 7.4 (platform: "web"). While the browser is closed the push waits up to TTL (one day).
13.5 A message deleted for everyone
When a message is deleted for everyone (11.18), its text must not stay readable in any notification. The server keeps two marks per device and conversation (docs/schema.md section 5): push-last, the newest seq sent to that device with an answer of success or "maybe" (13.6), and push-ok, the newest seq FCM confirmed (0 when there is none). That device's notification of the conversation may be showing ANY seq from push-ok to push-last: a "maybe" may or may not have arrived, and an earlier replacement (below) may have put a message of that range back.
- Who. A deletion of seq S goes to every device of the conversation's members, current and former (never the sender), with
push-ok <= S <= push-last. A device whose push-ok is past S certainly shows a newer message, and one whose push-last is below S was never notified of S: neither gets anything. A member who left a group and then deleted it from their list (11.13) has no membership left: the server also remembers which devices it pushed in each conversation (noted before each send, so a send cut short still counts; each kept for 24 hours and 20 minutes after its last push there, as long as a replacement can still need it, and at most the 512 most recent per conversation), and their owners count as former members (they get the deletion text, never a re-render: they can see nothing of it any more). Only a live session's device is ever pushed (a linked web's included): one whose session ended, or whose token has since been cleared or moved to another account (another account signing in on the same phone, 7.4), gets nothing. The server cannot replace those notifications any more, so the app cancels all of its notifications when it signs out and when another account signs in on it. - How. A replacement with the same tag:
data.type: "chat_deleted"(sameconversationId,seq= S), on Android thewiratalk_updateschannel without a sound, on the web"renotify": false, "silent": true. The OS swaps it in place; nothing alerts. - What it shows. The newest message with
push-ok <= seq <= push-last, other than S, that still exists (not deleted for everyone, text or media, not sent by a deleted account), that this recipient can see now (11.1: not hidden for them, after their clear, within their membership), that is not their own, and whose sender they have not blocked (13.1: a blocker is never pushed that sender's messages, though they can still read them in the app), re-rendered with 13.2's title (without the count) and body. A device that showed a later message keeps it, and one that still showed S loses it. With no such message: S's title without the count and the 13.2 deletion text. Nothing below push-ok is ever re-rendered (a later deletion of it could no longer find the device), and a replacement moves neither mark (what it shows lies in the range already). - A former member's replacement names only the sender, never the group (its title may have changed since they left, 11.1).
- The notification of a
chat_deletedmay therefore show another message than itsseq. (No push can remove a notification while the app is not running; a replacement can.) A running app may simply drop that conversation's notification when achat_deletedarrives. - A send whose deadline fired, or whose connection failed after FCM may already have the request, moves push-last exactly as a delivered one (13.6): a replacement sent shortly after still finds it, rather than leaving the original text showing because our own bookkeeping was never sure it arrived.
- Marks not written yet. A send that may have reached a device but whose marks could not be written (a Redis error) owes them: they are written later, without sending it again, for up to 24 hours. While a new-message push of the conversation is still being sent (claimed by the worker and not settled) or owes marks, its deletions wait: they look again every 2 seconds, for at most 15 minutes after the deletion, and then go out anyway (never dropped). The deletions of the same worker turn read the marks it owes as if written. A push that holds its conversation's deletions this way (owing marks, or taken up again after a crash, below) waits apart and is taken up before any other job, so it never waits behind a backlog while its deletion's 15 minutes run out. Both that 15-minute bound and the hold itself count from the worker's start at the earliest: after the server was down, a push still owing marks holds its conversation's deletions until it is taken up again. When the worker dies between a send and its bookkeeping, that push is taken up again once its claim runs out (5 minutes, or whenever the server is back): first, every device it may have reached without a mark is marked as a "maybe" (even if the message was deleted for everyone meanwhile: that deletion waited for this; even if the push is too old to send by then; and a failure to read its state retries this without ever giving up for up to 24 hours), then it is sent again if it still exists and is not too old. That marking is generous: it may include a member the original push left out (muted, blocking the sender, joined since), who may then get a silent re-render of a message they were never pushed, or the deletion text naming a sender they blocked. A deletion can still miss a device when Redis keeps refusing these writes past the 15-minute wait, for a push in flight when this version was first deployed (its claim was made without this bookkeeping), and when its replacement is never queued: the one Redis call after the deletion is stored fails, or the server stops between the two (13.1: counted
enqueue_failedand logged as an error; a deletion retried by the client then answers 404 and queues nothing).
The replacement is the one push that is not allowed to be lost to an outage once it is queued: it may live 24 hours (a new message's push, 15 minutes), it is not ended by the 9-send limit of 13.6 (its sends are bounded by the 24 hours and the 60-second backoff cap, so about 1,440 at most), a failure to read its state does not use up an attempt, and the queue's limit (PUSH_QUEUE_MAX, docs/schema.md section 5) does not refuse it: a replacement is refused only past a hard ceiling of twice that limit (20,000 jobs in all), and counted dropped_queue_full. Replacements wait apart from new messages: each worker turn takes up to half of its jobs from each, so a pile of replacements retrying through a long FCM outage never keeps new messages from being sent, and the other way round.
13.6 Tokens
- 7.4 registers a token: one per session (device row), moved to the newest session that registers it (another account signing in on the same phone), removed with its session (sign-out, revocation, expiry, account deletion) and by 7.5.
- The Hub's answer
unregisteredclears that row'sfcmToken(the row and its session stay). The Hub probesINVALID_ARGUMENTitself with a validate-only send of a minimal message to that token alone (carrying the samerestrictedPackageNameas every Android message) and answersunregisteredonly when the token is dead; otherwise the message, not the token, was at fault and the answer isrejected. A token of another Firebase project (SENDER_ID_MISMATCH) is never cleared. A clear only happens while the row still holds that token. The app registers its current token at every start and whenever Firebase hands it a new one. - A
retryis tried again for the devices that got it: after 2 s, doubling with jitter, at most 60 s apart (or the Hub's wait), at most 9 sends (without a wait they span about 4 minutes, so an outage of a minute or two loses nothing), never past the 15-minute limit (a deletion's replacement, 13.5: no send limit, 24 hours; a job whose own state could not be read also counts here, and is treated as a retry forpush-user). One gateway call carries up to 500 messages and has ONE deadline (45 s) for all it waits on, the request and its answer's body. A call that answers after it, or whose connection failed once the request may already have left (any failure that is not known to happen before anything was written: when unsure, this), and aretrythe Hub marksmaybeDelivered(the "may have reached FCM" case), count as neither success nor failure: the device is marked as having been sent to (so a deletion's replacement still finds it, 13.5) and is retried anyway, since FCM may or may not have taken it. - The licence being refused (15.1:
INVALID_LICENCE,COMPANY_SUSPENDED): nothing was sent, and it never counts toward the 9-send limit above: that job waits a steady interval instead (so a short outage or a rotation never gives up on a push within seconds), bounded only by the job's age (15 minutes, 24 hours for a replacement). Such a wait is still a retry for thepush-userlimit of 13.1.
13.7 Operations
GET /v1/healthanswers"push"(10.6).- The server logs
push statsonce a minute when anything happened: what was queued, sent, retried, given up, held (held: a deletion waiting for a new-message push of its conversation to settle, 13.5), dropped (queue full:dropped_full, ordropped_queue_fullfor a replacement past the hard ceiling; too old), not queued at all (enqueue_failed: Redis refused or timed out at that moment; the push is lost, 13.1), the tokens cleared, and each reason a push was not sent (muted, blocked, read, viewing, no device, session ended, platform, already sent, rate limited);push readyandpush failing(with a reason,credentialwhen the Hub refused the licence key anywhere in those turns, elseunreachable; only after three worker turns in a row that had a failure and no successful send, a credential check without an answer counting as one once the Hub has answered one (whileunknownit counts for nothing: a blip at start is not an outage), never on one slow answer; a refused licence found by a check flips it at once) only when the state changes. The licence is checked (validate-only, nothing delivered) at start, again whileunknownafter a check without an answer (30 s, doubling to 5 minutes), every 5 minutes whilefailing, and after 30 minutes without a success whileready. Never a token, a user id or message text. src/cli/push-test.ts, in the server container (docker exec <instance>-server node dist/src/cli/push-test.js ...):--check(a validate-only call through the Hub with a token no device has:PUSH_CHECK_OK WiraTalk Hub accepted the licence and reached FCM, nothing is delivered;PUSH_OFF: no WT_LICENCE_KEY, push goes through WiraTalk Hubwithout a key;PUSH_CHECK_FAILED: WiraTalk Hub refused the licence key,... WiraTalk Hub or FCM could not be reachedor... WiraTalk Hub refused the check requestotherwise),--status(jobs waiting and claimed),<userId|@username> [--dry-run](a test push,data.type: "test", tagwiratalk-test, no chat content, to every device of that account; one line per device, never a token; auditedpush_test_sent).
14. Admin
Everything an admin of the company does through the API. Every route needs a session whose person is an admin: the role is read from the database on each request (never kept in the session), so a demoted admin is refused at once. A person who is not an admin gets 403 ADMIN_ONLY on every route here, no session is 401. A cookie session needs the CSRF header on writes as everywhere (section 1). Each admin may make 120 calls a minute (admin, 429 RATE_LIMITED). Every answer is Cache-Control: private, no-store.
Every change is written to the audit log (docs/schema.md) with the admin as the actor and the person or provider it concerns in detail; a detail never holds a token, a link, a password or a secret. One server serves one company, so an admin may act on every account of it; an id that names no account is 404 NOT_FOUND.
14.1 GET /v1/admin/users?q=&limit=50&offset=0
{ "users": [ { "id": "...", "name": "Budi", "username": "budi", "email": "budi@contoh.co.id",
"role": "member", "disabled": false, "activated": true, "methods": ["password", "oidc:acme"],
"linkExpiresAt": null, "createdAt": "2026-10-05T03:00:00.000Z", "lastSignInAt": null } ],
"total": 1 }
Ordered by name (email when there is none). q (at most 100 characters; a leading @ is ignored) matches a piece of the name, username or email without regard to case; % and _ in it mean themselves. limit 1 to 100, offset 0 or more, else 400 INVALID_REQUEST. total counts every match. methods lists password when the account has one and oidc:<id> for every provider identity; activated is true when methods is not empty. linkExpiresAt is the expiry of the person's live invitation or reset link.
14.2 People
POST /v1/admin/users
{ "name": "Budi", "username": "budi", "email": "budi@contoh.co.id", "role": "member", "sendEmail": false }
name is cleaned like a profile name (1 to 100 characters), username is required and follows 4.3, email is an address of at most 320 characters, role is member (default) or admin, sendEmail defaults to false. 201:
{ "user": { "...": "as in 14.1" }, "link": { "purpose": "invite", "url": "https://talk.wiracode.com/i/srv_...#...", "expiresAt": "...", "emailed": false } }
The link is the invitation of 3.10, valid 7 days; the person sets a password on it. With sendEmail true and SMTP configured (section 14.6) the link is also mailed to the person, after the answer: emailed is true when the mail was handed to the server's mail queue and false when mail is off or was not asked for. A mail that cannot be sent later is only logged and never fails or delays the call (the admin can pass the link on). email is a plain address (letters, digits and .!#$%&'*+/=?^_`{|}~- before the @, a dotted host after it, at most 320 characters); a comma, semicolon, quote, bracket or space is 400 INVALID_REQUEST. Refusals create nothing: 400 INVALID_REQUEST, 400 INVALID_USERNAME, 409 EMAIL_TAKEN (compared without case), 409 USERNAME_TAKEN. Audited admin_user_created {targetId, role, via: "api"}.
POST /v1/admin/users/:id/link, body { "sendEmail": false }: a new link for an existing account, an invitation until it has a password and a reset after, replacing the person's older link. 200 { "link": { "purpose", "url", "expiresAt", "emailed" } }. A disabled account: 409 USER_DISABLED. Audited admin_link_issued {targetId, purpose, emailed, via: "api"}. At most 60 links an hour per admin and 10 an hour per person (admin-link, admin-link-target).
POST /v1/admin/users/:id/disable and /enable: 200 { "user" }. Disabling ends every session of the person at once, deletes their live link and refuses their sign-in (403 ACCOUNT_DISABLED); enabling brings the account back. Doing either to the caller's own account is 409 CANNOT_CHANGE_SELF; disabling the only active admin is 409 LAST_COMPANY_ADMIN. Audited admin_user_disabled and admin_user_enabled (only when the state changes). The host command that suspends an account (16) does the same.
PUT /v1/admin/users/:id/role, body { "role": "admin" } (admin or member, else 400): 200 { "user" }, effective on the person's next request. Own account: 409 CANNOT_CHANGE_SELF; demoting the only active admin: 409 LAST_COMPANY_ADMIN. Audited admin_role_changed {targetId, from, to}.
POST /v1/admin/users/:id/unlock: lifts the sign-in lock-out of the person's logins (3.2). 200 { "ok": true }. Audited admin_account_unlocked {targetId}.
When ten wrong passwords lock a sign-in and SMTP is configured, the person gets a short mail saying so, at most one a day per account. Without SMTP nothing is sent and the audit log holds account_locked.
14.3 Sign-in providers
GET /v1/admin/oidc-providers: { "providers": [ { "id", "name", "issuer", "clientId", "allowedDomains", "trustEmail", "enabled", "redirectUri", "createdAt" } ] }. redirectUri is <WT_PUBLIC_ORIGIN>/v1/auth/oidc/callback, the address to register at the provider. The client secret is never returned by any route.
POST /v1/admin/oidc-providers with { "id", "name", "issuer", "clientId", "clientSecret", "allowedDomains", "trustEmail"?, "enabled"? } (the rules of 3.11 to 3.13 and docs/schema.md): 201 { "provider" }. PATCH /v1/admin/oidc-providers/:id takes any of those fields but id (and the issuer, which cannot change): 200 { "provider" }. DELETE /v1/admin/oidc-providers/:id: 200 { "ok": true }, 404 when there is no such provider; the identities that came through it go too and the people keep their accounts. Errors: 400 INVALID_REQUEST, 409 PROVIDER_EXISTS, 409 PROVIDER_LIMIT, 422 OIDC_DISCOVERY_FAILED. Audited admin_oidc_changed {providerId, change: "created" | "updated" | "deleted", fields?} (fields names the fields a patch changed, never their values).
Set trustEmail only for a provider whose email claim the company can trust. Microsoft Entra does not verify the email claim: use trustEmail with Entra only for a single-tenant issuer of the company's own directory. With trustEmail, a new person can appear on an unverified claim but an existing account is joined only by a verified email (or xms_edov), so tenant staff who can edit a mail attribute cannot take over an account. Deleting a provider deletes the identities it created; disabling it (enabled: false) keeps them.
14.4 Company name and logo
GET /v1/admin/company: { "name", "logoEtag" }. PATCH /v1/admin/company with { "name": "PT Baru" } (cleaned, 1 to 100 characters, else 400 INVALID_REQUEST): the same answer. The name is what /.well-known/wiratalk (10.9), GET /v1/company (10.10), the set-password screen and the mails say. Audited admin_company_changed {change: "name"}.
PUT /v1/admin/company/logo with { "fileId": "<uuid>" }: the admin's own image upload (12.1) becomes the logo, with the same safety as a profile photo (4.5): decoded by an image library, cropped square, stored as a 512 x 512 WebP of at most 256 KiB with no metadata, so EXIF and GPS are gone. 200 { "logoEtag" }; 409 FILE_UNAVAILABLE for a file that is not the caller's own image, 400 INVALID_REQUEST for a bad id. DELETE /v1/admin/company/logo: 200 { "ok": true } (also when there is none). Audited admin_company_changed {change: "logo_set" | "logo_removed"}.
14.5 GET /v1/admin/status
{ "version": "0.6.0", "serverId": "srv_...", "publicOrigin": "https://talk.example.co.id",
"push": "ready", "mail": "off",
"hub": { "state": "ok", "code": null, "registeredAt": "2026-10-05T08:00:00.000Z",
"lastHeartbeatAt": "2026-10-05T09:00:00.000Z", "entryExpiresAt": "2026-11-04T09:00:00.000Z" },
"users": { "total": 12, "admins": 2, "disabled": 1, "notActivated": 3 },
"storage": { "files": 340, "fileBytes": 523456789 } }
push is the state of 10.6 (off while the licence is refused); hub is the Hub state of section 15, with its reason in code and the times as ISO strings or null; mail is on when SMTP is configured; notActivated counts accounts with neither a password nor a provider identity; storage counts stored files that are not collected (12.5).
14.6 Email for links
Mail is optional. With SMTP_HOST set (and SMTP_FROM, SMTP_PORT default 587, SMTP_SECURE 0 or 1 default 0, SMTP_USER and SMTP_PASS together) the server sends plain Indonesian text mails for the links an admin makes and for a locked sign-in; the sender's name is the company name. STARTTLS is required unless SMTP_SECURE=1. A mail holds the link and a short text and nothing else about the account; the SMTP password is never logged. Without SMTP_HOST the admin copies the link from the answer.
15. The Hub
A server with a licence key (WT_LICENCE_KEY) and a public origin that is an https address on the default port registers with the WiraTalk Hub (WT_HUB_URL, default https://talk.wiracode.com) and reports to it every hour. Without a key, or on any other origin, the state is off and the Hub is never called. src/hub/.
Calls (POST /hub/v1/servers/register and /heartbeat): Authorization: Bearer <licence key>, Content-Type: application/json, User-Agent: WiraTalk-Server/<version>; no redirect is followed, a call lasts at most 10 seconds and an answer is read up to 16 KiB. The key is never logged.
- Register body
{ "serverId", "apiBase": <public origin> }. Before it answers, the Hub fetches/.well-known/wiratalk(section 10.9) and requires the sameserverIdandlicenceKeyId. Sent at start-up when the stored registration is not for this origin and this key, so also after a change ofWT_LICENCE_KEYorWT_PUBLIC_ORIGIN, and again whenever a heartbeat answersSERVER_NOT_REGISTERED. - Heartbeat body
{ "serverId", "version", "userCount", "health" }:userCountis the accounts that are not disabled;healthisokwhen the database and Redis both answer, elsedegraded. - Both answer 200 with a signed directory
entry(a JWS; itsexpiresAtis kept asentryExpiresAt).
Schedule: a run at start-up, then every hour after a good run; while runs fail, the next one after 30 seconds, 1, 2 and 5 minutes, then every 10 minutes until one is good (the first registration of a new server often fails while its first certificate is being issued). Every delay gets up to a tenth of jitter, and an hour never holds more than 10 tries, the Hub's limit of registrations an hour per key, also when the server is restarted in between: the failing streak and the earliest time of the next try are stored with the Hub state, and a restart waits for that time instead of starting the steps over. A 429 or 503 with Retry-After waits that long when it is longer than the step (at most an hour). Chat never waits for the Hub and the Hub is never needed to start or stop.
States, in GET /v1/admin/status (14.5) as hub.state with the reason in hub.code:
| state | meaning | push |
|---|---|---|
off | no licence key or not a registrable origin | as without the Hub |
pending | nothing stored yet | as without the Hub |
ok | the last run was accepted | on |
refused | the Hub answered INVALID_LICENCE or COMPANY_SUSPENDED | paused |
failing | any other trouble: network, timeout, rate_limited, unavailable, redirect, bad_answer, WELL_KNOWN_FAILED:<reason>, SERVER_NOT_REGISTERED, or a Hub refusal such as SERVER_ID_MISMATCH, LICENCE_MISMATCH, SERVER_ID_TAKEN, API_BASE_TAKEN, SERVER_LIMIT, INVALID_URL | unchanged |
What the registration refusals mean:
WELL_KNOWN_FAILED:<reason>: the Hub could not read/.well-known/wiratalkat the public origin (unreachable,timeout,redirect,status,too_large,not_json,private_address, ormismatchwhen it answers for another server id). Right after an install it is often the first certificate still being issued; the next tries come within minutes.SERVER_ID_MISMATCH:WT_SERVER_IDis not the server id the licence key was issued for.LICENCE_MISMATCH: the public origin answers with this server id but with another licence key'slicenceKeyId: the address points at another server.SERVER_ID_TAKEN,API_BASE_TAKEN: another company holds that id or address.SERVER_LIMIT: the company has no room for another server.INVALID_URL: the origin is not one the Hub lists.
While refused, no new push is queued (GET /v1/health shows "push":"off"; jobs already queued are still sent); chat is unaffected. The state is stored (wiratalk.server_settings, key hub_state) and applied before the first call at start-up, so a restart does not reopen push. A failing run never changes a stored refused: only an accepted heartbeat does, and push then resumes by itself.
15.1 Push through the Hub
src/push/hub-transport.ts. Every notification goes to the Hub as POST /hub/v1/push/send with Authorization: Bearer <licence key>, Content-Type: application/json and User-Agent: WiraTalk-Server/<version>; no redirect is followed, a call lasts at most 45 seconds and an answer is read up to 128 KiB.
{ "messages": [ 1 to 500 messages, the shapes of 13.3 and 13.4 ], "validateOnly": true }
validateOnly is optional: the Hub has FCM validate the messages and delivers none (the credential check, the probe of a token and --dry-run). A batch of more than 500 messages is split into several calls. The Hub rebuilds each message from the allowed fields only, forces our app id and web origin, sends it with WiraTalk's Firebase project and answers 200 with { "results": [ ... ] }, one result per message in the same order:
| Hub answer | outcome on the server |
|---|---|
{ "status": "ok" } | ok |
{ "status": "unregistered" } | unregistered: the token is cleared (13.6) |
{ "status": "rejected", "code": ... } | rejected: dropped and logged, the token kept |
{ "status": "retry", "retryAfter": n } (a token over its limit, a skipped probe, FCM busy) | retry after n seconds, at most 60; the Hub answered, so no verdict on health |
{ "status": "retry", "maybeDelivered": true } | maybe |
| 200 unreadable, or with the wrong number of results | maybe for every message |
401 or 403 with INVALID_LICENCE or COMPANY_SUSPENDED | credential (the licence is refused: health failing, reason credential) |
429 RATE_LIMITED with Retry-After (too many open calls, Retry-After: 1; the company's minute used up; or the per-address limit, shared by every server behind one address) | retry after Retry-After, no verdict on health |
503 UNAVAILABLE with Retry-After (credentials not loaded: 30; the Hub busy as a whole: 1) | retry after Retry-After; counts towards health like any failure to get an answer |
408 REQUEST_TIMEOUT | retry, no wait given |
400 INVALID_REQUEST, 413 PAYLOAD_TOO_LARGE | rejected with that code |
| other 5xx | maybe |
| a deadline, or a connection that failed once the request may have left | maybe |
| connection refused, name not found, TLS or unsafe address; a redirect | retry, no wait given |
| a proxy page, a missing route, or a 401 or 403 without a licence code | retry, no wait given |
rejected codes are INVALID_MESSAGE (a field the Hub does not allow), INVALID_ARGUMENT (the message, not the token, was bad), SENDER_ID_MISMATCH, an FCM error code, or http_<status>. The Hub keeps no message text and no token: only a keyed fingerprint of the token for a minute and per-day counts.
15.2 Pairing through the Hub
The web and the phone never talk to each other; the Hub passes one envelope (7.8) between them. It is the Hub's own API, at WT_HUB_URL (default https://talk.wiracode.com), and its errors have the Hub's shape { "error": { "code": "..." } }.
| Call | Who | Answer |
|---|---|---|
POST /hub/v1/pairing | the web | 200 { "pairingId", "expiresAt" } (120 seconds); 403 CSRF_REJECTED when a browser Origin is not the Hub's own; 429 RATE_LIMITED with Retry-After (30 a minute per address, and 50 live pairings per IPv4 address or 5 per IPv6 /64); 503 UNAVAILABLE with Retry-After: 10 |
GET /hub/v1/pairing/<pairingId>/events | the web | 200 text/event-stream; 404 PAIRING_NOT_FOUND; 409 PAIRING_BUSY (another browser already waits on it) |
POST /hub/v1/pairing/<pairingId> with { "envelope": Envelope } (at most 8 KiB) | the phone | 204; 400 INVALID_REQUEST; 404 PAIRING_NOT_FOUND; 409 PAIRING_USED; 413 PAYLOAD_TOO_LARGE; 408 REQUEST_TIMEOUT; 429 RATE_LIMITED |
The wait is a list of frames, event: <name> then a one-line JSON data::
| event | data | meaning |
|---|---|---|
ready | { "expiresAt" } | first, once this browser is attached: show the QR now |
hb | {} | every 25 seconds |
envelope | { "envelope": Envelope } | then the stream ends |
expired | {} | then the stream ends: make a new pairing and a new QR |
A pairing that no browser attaches to within 15 seconds ends as expired.
The web's duties:
- attach to the wait at once after creating the pairing, before it shows the QR code;
- stop making new pairings after 5 QR codes in a row that nobody scanned, and while the tab is hidden, and then show a button that loads a new code (a tab left open must not hold a place at the Hub for ever);
- a wait that ends without
envelopeorexpired(a dropped connection, a Hub restart) is reopened on the same pairing; a 404 there means a new pairing; - 404 or 409 on the wait: make a new pairing;
- 429 or 503 on create: wait
Retry-Afterseconds, then try again.
The Hub cannot read an envelope: it is sealed to the browser's key. It checks only its shape, keeps it in memory until one browser has it (or the pairing ends, 2 minutes at most), and never writes it to disk or a log.
While the Hub is down, the webs already linked keep working with their server (nothing on a linked web's way needs the Hub), but no new web can be linked.
16. Commands
Run on the host of the server, in the server container (docker exec <instance>-server node dist/src/cli/admin.js ..., or ./wiratalk compose exec -T server node dist/src/cli/admin.js ... from the package folder). They need the database; only admin.js password also needs Redis (REDIS_URL). Exit codes: 0 done, 1 failed, 2 usage (hub-status.js uses 0, 1 and 3, below).
node dist/src/cli/admin.js create --name "<nama>" --username <username> --email <email> [--another] [--password-stdin]
node dist/src/cli/admin.js link <@username | email>
node dist/src/cli/admin.js password <@username | email> --password-stdin
create makes an admin account with no password (the first way into a new server). While an active admin exists it refuses with Sudah ada admin aktif. Tambahkan --another untuk membuat admin lagi. (exit 1) unless --another is given; the people of the company are made through 14.2. It prints exactly two lines on stdout: Akun admin @<username> dibuat. Buka tautan ini untuk membuat kata sandi (berlaku 24 jam, sekali pakai): and the invitation link of 3.10. Refusals print one line and exit 1: Email ini sudah dipakai akun lain., Nama pengguna ini tidak bisa dipakai., Nama pengguna sudah dipakai., Email tidak sah., Nama tidak sah.. Audited admin_user_created (no user, {targetId, role: "admin", via: "cli"}).
create --password-stdin reads the password from stdin instead (all of it, at most 4096 bytes, one trailing newline removed; the installer pipes it in) and makes no link: it checks the password before anything is made (Kata sandi terlalu pendek: paling sedikit 12 karakter. or Kata sandi terlalu panjang: paling banyak 128 karakter., exit 1), stores it, audits password_set {purpose: "cli"} for the new account and prints one line, Akun admin @<username> dibuat. Masuk dengan nama pengguna atau email dan kata sandi yang Anda masukkan. stdin is read only with the flag, and the password is never printed or logged.
password replaces the password of an existing account with the one read from stdin (the same checks and lines), removes its open link, ends all its sessions and lifts its sign-in lock: Kata sandi @<username> diganti. Semua sesi akun ini diakhiri. (the email when the account has no username). Unknown account Akun tidak ditemukan., disabled Akun ini dinonaktifkan. (exit 1); without --password-stdin the usage line (exit 2). Audited password_set {purpose: "cli"} and other_sessions_revoked {trigger: "cli_password", revoked} on the account.
link prints a new link for an existing account, an invitation until the account has a password and a reset after, valid 24 hours, replacing the account's older link: Tautan undangan untuk <@username, or the email when the account has no username yet> (berlaku 24 jam, sekali pakai): or Tautan atur ulang kata sandi untuk @<username> (berlaku 24 jam, sekali pakai):, then the URL. An unknown login is Akun tidak ditemukan. and a disabled account Akun ini dinonaktifkan. (exit 1). Audited admin_link_issued {targetId, purpose, via: "cli"} with no actor.
Any other failure prints Gagal: periksa koneksi database dan konfigurasi. and nothing about its cause. The link is printed once and kept nowhere.
node dist/src/cli/hub-status.js
prints one line for the link to WiraTalk Hub, from the state the server stored (it does not call the Hub; ./wiratalk status shows it): HUB_OK (exit 0); HUB_OFF (no licence key, or an address the Hub does not list), HUB_PENDING, HUB_FAILING <code> or HUB_REFUSED <code> (exit 3, the code is the Hub's error code or the reason of the failed try); HUB_STATUS_FAILED (exit 1, the database or the configuration did not answer, and nothing else is printed).
node dist/src/cli/origin-check.js
checks that the public origin answers for this server, as the Hub will: it fetches <WT_PUBLIC_ORIGIN>/.well-known/wiratalk over HTTPS with the certificate checked (no redirect followed, 10 seconds, 16 KiB at most) and compares serverId and licenceKeyId with its own. ORIGIN_OK (exit 0); ORIGIN_WAITING <reason> (exit 3) with dns, tls, unreachable, timeout, redirect, status_<code>, too_large, not_json, mismatch (another server id) or key_mismatch (another licence key); ORIGIN_CHECK_FAILED (exit 1, the configuration could not be read). The installer runs it with Caddy in front before it waits for the Hub.
node dist/src/cli/files-probe.js [--create-bucket]
proves the file store (one object written, read, read by range and deleted under FILES_S3_PREFIX; PROBE_OK ... exit 0, PROBE_FAILED: <what> exit 1, 2 when the store is not configured). With --create-bucket the bucket is made first, an existing one being fine, and BUCKET_OK is printed before the probe: the installer uses it for the bundled MinIO.
The backup commands run from the server image (the host needs only Docker):
node dist/src/cli/backup-settings.js
node dist/src/cli/backup-offsite.js <wiratalk-YYYYMMDD.dump.gpg> [wiratalk-key-YYYYMMDD.env.gpg]
node dist/src/cli/backup-files.js [--restore]
backup-settings.js prints the retention numbers of src/config/constants.ts as HOURLY_KEEP=48, DAILY_KEEP=30, OFFSITE_KEEP_DAYS=90 and AUDIT_RETENTION_DAYS=180, one per line. backup-offsite.js uploads the (already encrypted) files to the off-site store named by OFFSITE_S3_ENDPOINT, OFFSITE_S3_BUCKET, OFFSITE_S3_ACCESS_KEY, OFFSITE_S3_SECRET_KEY and the optional OFFSITE_S3_REGION and OFFSITE_S3_PREFIX (default wiratalk-backups/), checks each size, removes copies older than 90 days by the date in their name, and prints uploaded <key> (<n> bytes) lines, then OFFSITE_OK (exit 0) or OFFSITE_FAILED: <what> (1 failed, 2 refused: missing settings, a name outside the pattern, or an off-site prefix that overlaps FILES_S3_PREFIX on the same bucket). backup-files.js copies the chat files (S3_*, FILES_S3_PREFIX) to <OFFSITE_S3_PREFIX>files/, copying what is new or changed and deleting there what the file store no longer has; with --restore it copies the other way and deletes nothing. It prints FILES_COPY_OK copied <n> deleted <m> kept <k>, FILES_COPY_FAILED: <what> (exit 1 failed, 2 refused for the same reasons) or FILES_COPY_REFUSED <reason> (exit 1): the copy still adds what is new but deletes nothing when the file store lists no objects (source-empty) or when the deletions would remove more than half of a copy that holds more than 20 objects (too-many-deletions <n>/<total>). No command prints a key.