Optional · Reference
Code sign-in
Some people can't scan: no camera on their computer, or no internet on their phone. They can type the 8-digit code OT Auth shows instead, and your server checks it with OT Auth. Offer it next to the QR code, not in place of it.
How it works
- The person opens OT Auth and taps Show codeThe code has 8 digits and changes every 30 seconds. The phone doesn't need internet to show it. Once the phone is signed out of OT Auth, on the phone itself or from another of the person's phones, its codes stop working.
- They type their phone number and the code on your sign-in pageThe page sends both to your own server, never to OT Auth.
- Your server asks OT AuthOne
POST, signed with your app's Private Key, that says which number and code were typed. - OT Auth answers
loginSuccesswith the person'sUserIDif that is the current code from a phone signed in to that number's OT Auth account, or a reason it isn't. - You sign the person inFind their account by that
UserIDand start a session.
What you need
- Your API Key, the same one your QR codes use.
- Your Private Key, shown once in the console when you generated the API key (Get your keys). Keep it in your server's environment, for example as
OTAUTH_APP_PRIVATE_KEY. - A clock kept in sync (NTP). OT Auth refuses a signed call more than 60 seconds from its own clock.
- Outbound HTTPS from your server to
auth.orvixtech.com.
POST/api/auth/totp/login
Your server checks a code a person typed
Send it to https://auth.orvixtech.com/api/auth/totp/login.
POST https://auth.orvixtech.com/api/auth/totp/login
Content-Type: application/json
Authorization: Bearer 3f1c9a…e07b
X-API-Key: YOUR_API_KEY
X-Timestamp: 1791612255
X-Nonce: Zk3pQ8vR1mT6yW0aB4cN7dE2
X-Signature: MEUCIQCx…
{"PhoneNo":"+919876543210","IP":"203.0.113.7"}| Field | Type | What it is |
|---|---|---|
Authorization | header | Bearer and the lowercase hex SHA-512 of two things joined: the lowercase hex SHA-512 of the phone number, then the 8 digits as typed. |
X-API-Key | header | Your API Key. |
X-Timestamp | header | Now, in Unix seconds. |
X-Nonce | header | 16 to 64 random characters, letters, digits, - and _, new for every call. |
X-Signature | header | Your signature over the call (below). |
PhoneNo | string | The number the person typed, in international format with + and the country code, exactly as you hashed it for Authorization. |
IP | string | The IP address of the visitor who typed the code, as your server saw the connection (behind a proxy, from your own proxy's header only). OT Auth limits wrong codes per visitor, so one visitor can't lock the person out. Without it, all your visitors share one limit for that number. |
Signing the call
It is the same scheme OT Auth uses to sign its calls to you (Checking the signature), the other way round: you sign with your Private Key, and OT Auth checks with the matching public key it keeps for your API key.
The signed text is six lines joined with \n: OTAUTH-V1, POST, /totp/login, the timestamp, the nonce, and the lowercase hex SHA-256 of the body. Sign it with ECDSA P-256 and SHA-256, and send the DER signature in base64 as X-Signature.
import { createHash, createPrivateKey, randomBytes, sign } from "node:crypto";
// Your app's Private Key (base64), shown once when you generated or replaced the API key.
const APP_KEY = createPrivateKey({
key: Buffer.from(process.env.OTAUTH_APP_PRIVATE_KEY, "base64"), format: "der", type: "pkcs8",
});
const sha512 = (text) => createHash("sha512").update(text).digest("hex");
// Asks OT Auth whether `code` is the current code of the OT Auth app for `phoneNo`,
// typed by the visitor at `ip`.
export async function checkCode(phoneNo, code, ip) {
const body = JSON.stringify({ PhoneNo: phoneNo, IP: ip }); // sign these exact bytes, then send them
const ts = String(Math.floor(Date.now() / 1000));
const nonce = randomBytes(18).toString("base64url");
const bodyHash = createHash("sha256").update(body).digest("hex");
const signed = ["OTAUTH-V1", "POST", "/totp/login", ts, nonce, bodyHash].join("\n");
const res = await fetch("https://auth.orvixtech.com/api/auth/totp/login", {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer " + sha512(sha512(phoneNo) + code),
"X-API-Key": process.env.OTAUTH_API_KEY,
"X-Timestamp": ts,
"X-Nonce": nonce,
"X-Signature": sign("sha256", Buffer.from(signed), APP_KEY).toString("base64"),
},
body,
signal: AbortSignal.timeout(5000),
});
const reply = await res.json().catch(() => ({}));
const userId = reply.Data?.UserID; // the same UserID /otlogin sends you
return {
ok: reply.MessageStatus === "loginSuccess" && Number.isSafeInteger(userId),
userId: String(userId),
status: reply.MessageStatus,
retryAfter: res.headers.get("Retry-After"),
};
}Any language with ECDSA P-256 works. The Private Key is base64 of a PKCS#8 DER key; most libraries load it directly or after wrapping it as a PEM PRIVATE KEY.
The reply
Every reply is JSON with Status, MessageStatus and Message. Decide on MessageStatus; Message is English text for your logs and may change.
{
"Status": "Success",
"MessageStatus": "loginSuccess",
"Message": "Signed in",
"Data": { "UserID": 1234567890123456 }
}| HTTP | MessageStatus | What it means | What to do |
|---|---|---|---|
| 200 | loginSuccess | The code is right for this number. Data.UserID names the person. | Find the account by UserID and sign in. |
| 401 | invalidTOTP | The code doesn't match: wrong digits, too old (a code stops working about 30 seconds after the app shows the next one), or from a phone that has been signed out. Or no phone is signed in to OT Auth with this number, or it has no OT Auth account. OT Auth doesn't say which. | Ask for the code the app shows now. |
| 401 | expireTOTP | This code, or a newer one, was already used for this number. Each code works once. | Ask for the next code. |
| 422 | invalidPhoneNoFormat | PhoneNo doesn't start with + and the country code. | Fix the number before you send it. |
| 400 | requiredPhoneNo | The body has no PhoneNo. | Fix your request. |
| 401 | requiredToken, invalidTokenFormat | Authorization is missing, or isn't Bearer followed by the hash. | Fix your request. |
| 429 | tooManyRequests | Too many tries, right or wrong. This visitor tried this number too often at your app; or so many visitors were blocked for this number that it is blocked at every app for a while; or your app checked too many codes overall. It is decided before the code is checked, so it says nothing about the code. | Wait the seconds in the Retry-After header. Without IP in your call, all your visitors count as one. |
| 403 | qrSignInFirst | The code is right, but this person has never signed in to your app with the QR code. | Ask them to scan the QR code once. After that their codes work. |
| 401 | unsigned | Signing headers are missing or malformed. | Send all four, with a valid nonce. |
| 401 | clockSkew | Your timestamp is more than 60 seconds off. | Sync your server's clock. |
| 401 | invalidSignature | The signature doesn't match. | Check the Private Key belongs to this API Key, the /totp/login line, and the body bytes. |
| 401 | replayed | This nonce was already used. | Make a new nonce for every call. |
| 401 | invalidApiKey, inactiveApiKey | Unknown API Key, or switched off in the console. | Check the key on the API Keys page. |
| 401 | appNotEnrolled | This API Key has no Private Key yet. | Choose Replace on the API Keys page to get one. |
| 500 | internalServerError | Our side failed. | Try again shortly. |
| 503 | (none) | OT Auth is busy right now. The body isn't JSON. | Wait the seconds in the Retry-After header, then try again. |
On your server
A sign-in route around checkCode, for Express:
app.post("/api/code-login", express.json(), async (req, res) => {
const { phoneNo, code } = req.body ?? {};
if (!/^\+\d{8,15}$/.test(phoneNo ?? "") || !/^\d{8}$/.test(code ?? "")) {
return res.status(400).json({ error: "Enter your number with its country code, and the 8-digit code." });
}
const result = await checkCode(phoneNo, code, req.ip);
if (result.status === "tooManyRequests") {
return res.status(429).json({ error: "Too many tries. Wait a moment and try again.", retryAfter: result.retryAfter });
}
if (result.status === "qrSignInFirst") {
return res.status(403).json({ error: "Sign in with the QR code once. After that you can use a code." });
}
if (!result.ok) {
// One answer for a wrong code and an unknown number: don't tell visitors who uses OT Auth.
return res.status(401).json({ error: "Wrong phone number or code." });
}
const user = await users.findByOtAuthUserId(result.userId); // never by phone number
if (!user) return res.status(404).json({ error: "No account yet: sign in with the QR code first." });
startSession(res, user);
res.json({ ok: true });
});- Check codes only from your server. The browser sends the number and code to you over HTTPS; only your server talks to OT Auth.
- Give one answer for every refusal, so your sign-in page can't be used to find out who has an account with you.
- Limit attempts on your side too, per account and per visitor, and log refusals:
invalidSignatureorclockSkewin your log means your setup is wrong, not the person.