Reference implementation
Full example
One Express file with everything from this guide: the sign-in page, its WebSocket, the QR code, the signature check, all four callbacks, and the result pushed back down the socket. Copy it, then swap the in-memory maps for your database.
Run it
npm install express ws qrcode
OTAUTH_API_KEY=your-key OTAUTH_PUBLIC_KEY=MFkwEwYHKoZIzj0CAQYI… node server.jsOTAUTH_API_KEYis your app's API key from the OT Auth console.OTAUTH_PUBLIC_KEYis OT Auth's public key, from the console's API Keys page. Callbacks without a valid signature get401, and the server won't start without it.- Set
https://your-host/apias your key's URL in the console, so OT Auth calls/api/otloginand the rest. It must be public https: use an HTTPS tunnel while you try it on your own machine.
The code
// OT Auth sign-in for an Express app, start to finish. The sign-in page asks
// for a code over a WebSocket; OT Auth calls the four callbacks; the result
// goes back down the socket that asked.
// npm install express ws qrcode
// OTAUTH_API_KEY=… OTAUTH_PUBLIC_KEY=… node server.js
import express from "express";
import QRCode from "qrcode";
import { WebSocketServer } from "ws";
import { createHash, createPublicKey, randomBytes, randomUUID, verify } from "node:crypto";
const API_KEY = process.env.OTAUTH_API_KEY; // from the OT Auth console
const TTL = Number(process.env.QR_TTL ?? 90); // seconds a code lives
// OT Auth's public key (base64), from the OT Auth console's API Keys page. It proves a
// callback came from OT Auth: refuse to start without it.
if (!process.env.OTAUTH_PUBLIC_KEY) throw new Error("Set OTAUTH_PUBLIC_KEY, OT Auth's public key from the OT Auth console");
const OTAUTH_KEY = createPublicKey({ key: Buffer.from(process.env.OTAUTH_PUBLIC_KEY, "base64"), format: "der", type: "spki" });
const app = express();
// Keep each body's exact bytes: OT Auth's signature covers them, not the parsed JSON.
app.use(express.json({ verify: (req, res, bytes) => (req.rawBody = bytes) }));
// Swap these Maps for your database and cache.
const requests = new Map(); // RequestID → { socket, ip, location, expires }
const users = new Map(); // OT Auth UID → your user
const sessions = new Map(); // session token → user
const now = () => Math.floor(Date.now() / 1000);
const locate = (ip) => "Unknown location"; // use your geo-IP lookup; city and country is enough
const send = (socket, message) => socket.readyState === 1 && socket.send(JSON.stringify(message));
const LOOPBACK = ["127.0.0.1", "::1", "::ffff:127.0.0.1"];
// The connection's own address, or the one your local proxy forwards. Never an
// IP the page reports about itself: that is what the person checks before approving.
const clientIp = (req) =>
(LOOPBACK.includes(req.socket.remoteAddress) && req.headers["x-forwarded-for"]?.split(",").at(-1).trim()) ||
req.socket.remoteAddress;
// Browsers send the page's origin with every WebSocket, and a page can't change
// it. Only your own sign-in page may ask for codes: a page on another site could
// open this socket from its visitor's browser, so the phone would show that
// visitor's own IP and city, and that site's script would get the session. If
// your sign-in page is on another host than this server, compare with its origin.
const fromOwnPage = (req) => {
try {
return new URL(req.headers.origin).host === req.headers.host;
} catch {
return false; // no Origin: not a browser page
}
};
// UserID is a 64-bit number: refuse one a JavaScript number can't hold exactly,
// rather than round it onto someone else's.
const uidOf = (body) => (Number.isSafeInteger(body?.UserID) ? String(body.UserID) : null);
// Every pending request of one page.
const dropRequestsOf = (socket) => {
for (const [id, request] of requests) if (request.socket === socket) requests.delete(id);
};
function expire(id) {
const request = requests.get(id);
if (!request) return;
requests.delete(id);
send(request.socket, { message: "requestExpired" });
}
// ---- The sign-in page: one socket per open page --------------------------------
const server = app.listen(process.env.PORT ?? 3000);
const wss = new WebSocketServer({ server, path: "/api/ws", maxPayload: 4096 }); // the page only sends small messages
wss.on("connection", (socket, req) => {
if (!fromOwnPage(req)) return socket.close(1008, "Not this site's sign-in page");
const ip = clientIp(req);
socket.on("message", async (raw) => {
let message;
try {
message = JSON.parse(raw.toString());
} catch {
return;
}
if (message?.MessageType !== "qrLoginRequest") return;
dropRequestsOf(socket); // one live code per page: asking again retires the old one
const id = randomUUID(); // made here, never taken from the page
const expires = now() + TTL;
requests.set(id, { socket, ip, location: locate(ip), expires });
setTimeout(() => expire(id), TTL * 1000);
const token = Buffer.from(JSON.stringify({ apikey: API_KEY, requestId: id })).toString("base64url");
const qrValue = `https://auth.orvixtech.com/qr-login?token=${token}`;
send(socket, {
message: "SessionRequested",
qrValue,
expireTime: expires,
expireDuration: TTL,
qr: await QRCode.toString(qrValue, { type: "svg", margin: 4 }),
});
});
// A closed page can't be signed in.
socket.on("close", () => dropRequestsOf(socket));
});
// The page calls your API with the token it got in loginSuccess.
app.get("/api/me", (req, res) => {
const user = sessions.get(req.headers.authorization?.replace(/^Bearer /, ""));
return user ? res.json(user) : res.sendStatus(401);
});
app.get("/", (req, res) => res.type("html").send(PAGE));
// ---- OT Auth's calls: register https://your-host/api as the callback URL --------
const otauth = express.Router();
// OT Auth signs every call (OTAUTH-V1): check it, and that the call is for your own API
// key, before acting on the body.
const seen = new Map(); // nonce → when it can be forgotten
otauth.use((req, res, next) => {
const ts = req.get("X-Timestamp") ?? "";
const nonce = req.get("X-Nonce") ?? "";
const signature = Buffer.from(req.get("X-Signature") ?? "", "base64");
for (const [n, until] of seen) if (until < Date.now()) seen.delete(n);
const bodyHash = createHash("sha256").update(req.rawBody ?? "").digest("hex");
const signed = Buffer.from(["OTAUTH-V1", "POST", req.path, ts, nonce, bodyHash].join("\n"));
const fresh = Math.abs(now() - Number(ts)) <= 60 && nonce.length >= 16 && nonce.length <= 64 && !seen.has(nonce);
let valid = false;
try {
valid = fresh && verify("sha256", signed, OTAUTH_KEY, signature);
} catch {}
if (!valid) {
console.warn(`Refused OT Auth callback ${req.originalUrl} from ${clientIp(req)}: bad signature`);
return res.status(401).json({ Status: false, MessageStatus: "invalidSignature" });
}
seen.set(nonce, Date.now() + 120_000); // a replay is refused while its timestamp could still pass
// One OT Auth key signs every app's calls, so a genuine call can be about another app's
// QR code (one registered with your URL, or relayed here). APIKey, inside the signed
// body, is the key that was scanned: act only on your own.
if (req.body?.APIKey !== API_KEY) {
console.warn(`Refused OT Auth callback ${req.originalUrl}: it is for another API key`);
return res.status(401).json({ Status: false, MessageStatus: "wrongApiKey" });
}
next();
});
const fail = (res, MessageStatus, extra) => res.json({ Status: false, MessageStatus, ...extra });
// The request named in the body, if it can still be approved; otherwise replies.
function pending(req, res) {
const id = req.body?.RequestID;
const request = requests.get(id);
if (!request) return fail(res, "invalidRequestID"), null;
if (now() >= request.expires) return expire(id), fail(res, "expireRequestID"), null;
return request;
}
// Single use: the request is gone once its page is signed in.
function signIn(req, res, request, user) {
requests.delete(req.body.RequestID);
const token = randomBytes(32).toString("base64url");
sessions.set(token, user);
send(request.socket, { message: "loginSuccess", data: { token, user } });
res.json({ Status: true, MessageStatus: "loginSuccess" });
}
otauth.post("/qrvalidate", (req, res) => {
const request = pending(req, res);
if (!request) return;
res.json({
Status: true,
MessageStatus: "validateSuccess",
Data: { IP: request.ip, Location: request.location, ExpireTime: request.expires, ExpireDuration: TTL },
});
});
otauth.post("/otlogin", (req, res) => {
const request = pending(req, res);
if (!request) return;
const uid = uidOf(req.body);
if (!uid) return fail(res, "invalidUserID");
const user = users.get(uid);
if (!user) {
return fail(res, "userNotFound", {
RegistrationAllowed: true,
PrivacyMessage: "Acme uses your name for your account and your email for receipts.",
FormField: [
{ FieldName: "PhoneNo", Required: true }, // /otregister carries no phone number of its own
{ FieldName: "FirstName", Required: true },
{ FieldName: "Email", Required: false },
],
});
}
user.phone = req.body.PhoneNo; // people can move OT Auth to a new number; the UserID stays
signIn(req, res, request, user);
});
otauth.post("/otregister", (req, res) => {
if (req.body?.MissingFields?.length) {
console.error("OT Auth has no field named", req.body.MissingFields); // fix the FormField list above
return fail(res, "failToRegister");
}
const request = pending(req, res);
if (!request) return;
const uid = uidOf(req.body);
if (!uid) return fail(res, "invalidUserID");
const { FormField = {} } = req.body;
if (users.has(uid)) return fail(res, "alreadyRegistered");
const user = { uid, phone: FormField.PhoneNo ?? "", name: FormField.FirstName ?? "", email: FormField.Email ?? "" };
users.set(user.uid, user);
signIn(req, res, request, user);
});
otauth.post("/otreject", (req, res) => {
const id = req.body?.RequestID;
const request = requests.get(id);
if (request) {
requests.delete(id);
send(request.socket, { message: "requestRejected" });
}
res.json({ Status: true });
});
app.use("/api", otauth);
// ---- The sign-in page ----------------------------------------------------------------
const PAGE = `<!doctype html>
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Sign in</title>
<h1>Sign in to Acme</h1>
<p>Scan with OT Auth on your phone.</p>
<div id="qr" style="width:240px"></div>
<p id="left"></p>
<p><a id="on-phone" hidden>Open OT Auth App</a></p>
<p id="status" aria-live="polite"></p>
<button id="again" hidden>Show a new code</button>
<script>
const $ = (id) => document.getElementById(id);
const socket = new WebSocket(location.origin.replace("http", "ws") + "/api/ws");
const ask = () => socket.send(JSON.stringify({ MessageType: "qrLoginRequest" }));
let timer;
socket.onopen = ask;
socket.onmessage = async ({ data }) => {
const m = JSON.parse(data);
if (m.message === "SessionRequested") {
$("qr").innerHTML = m.qr;
$("on-phone").href = m.qrValue;
$("on-phone").hidden = !/Android|iPhone|iPad/.test(navigator.userAgent);
$("again").hidden = true;
$("status").textContent = "";
clearInterval(timer);
timer = setInterval(() => { $("left").textContent = "Expires in " + Math.max(0, m.expireTime - Math.floor(Date.now() / 1000)) + " s"; }, 1000);
}
if (m.message === "loginSuccess") {
clearInterval(timer);
sessionStorage.setItem("token", m.data.token);
const me = await (await fetch("/api/me", { headers: { Authorization: "Bearer " + m.data.token } })).json();
document.body.textContent = "Signed in as " + me.name;
}
if (m.message === "requestRejected" || m.message === "requestExpired") {
clearInterval(timer);
$("qr").innerHTML = "";
$("left").textContent = "";
$("status").textContent = m.message === "requestRejected" ? "Sign-in was declined on the phone." : "That code expired.";
$("again").hidden = false;
}
};
$("again").onclick = ask;
</script>`;What to change for production
- Storage. Keep users in your user table, with the OT Auth
UserIDas a unique column. A request holds a live socket, so it lives on the server instance that opened it: with several instances, publish each outcome (for example over Redis pub/sub) and let the instance holding the socket deliver it. - Sessions. The example sends the page a random session token; use your own, such as signed access and refresh tokens. The rule that matters: send it only down the socket stored with the request.
- Location. Replace
locate()with a geo-IP lookup. - Fields. Ask only for what you need, and say why in
PrivacyMessage.