Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Email sign-in codes through the server's own mail server
milind-soni670631b28ad9
diff --git a/deploy/.env.example b/deploy/.env.exampleindex 2ad73b0348..4ead3a93aa 100644--- a/deploy/.env.example+++ b/deploy/.env.example@@ -11,3 +11,9 @@ ENGINES=@anthropic-ai/claude-code# access; members get chat and approvals only.OMB_SIGNIN_EMAILS=OMB_SIGNIN_MEMBER_EMAILS=++# Optional: send those codes through your own mail server instead of the+# OpenMausBot account service, e.g. smtps://user%40example.com:[email protected]:465+# (docs/self-hosting.md). FROM defaults to the user name when it is an address.+OMB_SIGNIN_SMTP_URL=+OMB_SIGNIN_SMTP_FROM=diff --git a/deploy/docker-compose.yml b/deploy/docker-compose.ymlindex 368126534a..ed9b89011e 100644--- a/deploy/docker-compose.yml+++ b/deploy/docker-compose.yml@@ -37,6 +37,9 @@ services:# "Sign in with your email"). Empty means pairing codes only.OMB_SIGNIN_EMAILS: ${OMB_SIGNIN_EMAILS:-}OMB_SIGNIN_MEMBER_EMAILS: ${OMB_SIGNIN_MEMBER_EMAILS:-}+ # Send the codes through your own mail server (same section of the docs).+ OMB_SIGNIN_SMTP_URL: ${OMB_SIGNIN_SMTP_URL:-}+ OMB_SIGNIN_SMTP_FROM: ${OMB_SIGNIN_SMTP_FROM:-}healthcheck:test: ["CMD-SHELL", "curl -sf http://127.0.0.1:8799/api/health | grep -q openmausbot"]interval: 30sdiff --git a/docs/self-hosting.md b/docs/self-hosting.mdindex 7bf3a695df..c0815d3154 100644--- a/docs/self-hosting.md+++ b/docs/self-hosting.md@@ -661,6 +661,24 @@ decided only by your allow-list. Wrong codes count against the same lockoutas pairing codes. Sessions from a sign-in show the email in`openmausbot sessions` and can be revoked the same way.+To send the codes through your own mail server instead, so nobody signs in+through the account service and no MausBot account is made, give the server+an SMTP address:++```sh+OMB_SIGNIN_SMTP_URL="smtps://signin%40yourcompany.com:[email protected]:465"+OMB_SIGNIN_SMTP_FROM="OpenMausBot <[email protected]>" # else the user name, if it is an address+```++`smtps://` uses TLS from the start (port 465); `smtp://` upgrades with+STARTTLS (port 587) and refuses a server that cannot, unless the mail server+is on this machine (`smtp://localhost:25`). Write the user name and password+URL-encoded (`@` is `%40`). Your server then makes each code itself: 8 digits,+single use, ten minutes and five tries, kept only as a hash in memory (a+restart ends the open ones), and at most one every 30 seconds per address.+The allow-list, the lockout and the sessions work as above. Keep the URL in+the service's environment file, never on a command line.+### Inviting people**Settings → People** lists who may sign in, their role, when they were lastdiff --git a/server/account-signin.ts b/server/account-signin.tsindex 6c06527cf6..22aa5cb58b 100644--- a/server/account-signin.ts+++ b/server/account-signin.ts@@ -1,8 +1,10 @@-// Email sign-in through the OpenMausBot control plane: the code exchange is server-side, so a browser only talks to this-// server, and a server with an empty allow-list does not expose the routes. The result is an ordinary local session.+// Email sign-in through the OpenMausBot control plane, or through the server's own mail server when OMB_SIGNIN_SMTP_URL is+// set: the code exchange is server-side, so a browser only talks to this server, and a server with an empty allow-list+// does not expose the routes. The result is an ordinary local session.import { resolveCompanionControlPlaneURL } from "../electron/companion-account-service.mjs";import { ControlPlaneError, createControlPlaneClient, normalizeAccountEmail, type ControlPlaneClient } from "../electron/control-plane-client.mjs";import type { Scope } from "./sessions.ts";+import { createSignInMail, SignInMailError, type MailTransport, type SignInMail } from "./sign-in-mail.ts";import { userError, type UserError } from "./user-errors.ts";/** Who may sign in. `[email protected]` is that address; `@b.com` is everyone at b.com. */@@ -47,9 +49,15 @@ export function createEmailSignIn(options: {env?: NodeJS.ProcessEnv;fetchImpl?: typeof fetch;client?: ControlPlaneClient;+ mailTransport?: MailTransport;}): EmailSignIn {const env = options.env ?? process.env;const allow = () => (typeof options.allow === "function" ? options.allow() : options.allow);+ const smtpUrl = env.OMB_SIGNIN_SMTP_URL?.trim();+ if (smtpUrl) {+ return mailedSignIn(allow, createSignInMail({ url: smtpUrl, from: env.OMB_SIGNIN_SMTP_FROM,+ ...(options.mailTransport ? { transport: options.mailTransport } : {}) }));+ }let client: ControlPlaneClient | null = options.client ?? null;const controlPlane = (): ControlPlaneClient => {if (client) return client;@@ -101,6 +109,34 @@ export function createEmailSignIn(options: {};}+function mailedSignIn(allow: () => SignInAllowList, mail: SignInMail): EmailSignIn {+ return {+ enabled: () => signInEnabled(allow()),+ async start(rawEmail) {+ const email = normalizeAccountEmail(rawEmail);+ if (!email) return { ok: false, status: 400, ...userError("serverError.email.invalid") };+ if (!allowedScopes(email, allow())) return NOT_WELCOME;+ try {+ if ((await mail.send(email)) === "tooSoon") return { ok: false, status: 429, ...userError("serverError.email.tooMany") };+ } catch (error) {+ console.warn(`sign-in code not sent: ${error instanceof Error ? error.message : String(error)}`);+ return { ok: false, status: 502, ...userError("serverError.email.unavailable", { detail: error instanceof SignInMailError ? error.message : "the mail server refused it" }) };+ }+ return { ok: true };+ },+ async verify(rawEmail, code) {+ const email = normalizeAccountEmail(rawEmail);+ if (!email || !allowedScopes(email, allow())) return NOT_WELCOME;+ const checked = mail.check(email, code);+ if (checked === "format") return { ok: false, status: 400, ...userError("serverError.email.codeFormat") };+ if (checked === "tooMany") return { ok: false, status: 429, ...userError("serverError.email.tooMany") };+ if (checked === "wrong") return { ok: false, status: 401, ...userError("serverError.email.codeWrong") };+ const scopes = allowedScopes(email, allow());+ return scopes ? { ok: true, email, userId: `email:${email}`, scopes } : NOT_WELCOME;+ },+ };+}+function unavailable(error: unknown): SignInFailure {const detail = error instanceof ControlPlaneError ? `${error.code}${error.status ? ` (${error.status})` : ""}` : error instanceof Error ? error.message : String(error);return { ok: false, status: 502, ...userError("serverError.email.unavailable", { detail }) };diff --git a/server/sign-in-mail.test.ts b/server/sign-in-mail.test.tsnew file mode 100644index 0000000000..36d8ed77f4--- /dev/null+++ b/server/sign-in-mail.test.ts@@ -0,0 +1,133 @@+import { createServer, type Server } from "node:net";+import type { AddressInfo } from "node:net";+import { afterEach, describe, expect, it } from "vitest";++import { createEmailSignIn } from "./account-signin.ts";+import { createSignInMail, SIGNIN_CODE_RESEND_MS, SIGNIN_CODE_TRIES, SIGNIN_CODE_TTL_MS, smtpOptions, type MailMessage } from "./sign-in-mail.ts";++const URL_ = "smtps://signin%40example.test:p%[email protected]:465";++function mailbox() {+ const sent: MailMessage[] = [];+ return { sent, transport: { sendMail: async (message: MailMessage) => { sent.push(message); } }, code: () => /(\d{4}) (\d{4})/.exec(sent.at(-1)!.text)!.slice(1).join("") };+}++describe("sign-in codes through the server's own mail server", () => {+ it("reads TLS, port and the URL-encoded login from the address, and requires STARTTLS off this machine", () => {+ expect(smtpOptions(URL_)).toMatchObject({ host: "smtp.example.test", port: 465, secure: true, requireTLS: false, auth: { user: "[email protected]", pass: "p@ss" } });+ expect(smtpOptions("smtp://u:[email protected]")).toMatchObject({ port: 587, secure: false, requireTLS: true });+ expect(smtpOptions("smtp://localhost:25")).toMatchObject({ port: 25, requireTLS: false });+ expect(smtpOptions("smtp://localhost:25")).not.toHaveProperty("auth");+ expect(() => smtpOptions("https://smtp.example.test")).toThrow("smtps:// or smtp://");+ expect(() => smtpOptions("not a url")).toThrow("not a URL");+ });++ it("sends an 8-digit code that works once, and never says it in the subject", async () => {+ const box = mailbox();+ const mail = createSignInMail({ url: URL_, transport: box.transport });+ expect(await mail.send("[email protected]")).toBe("sent");+ expect(box.sent[0]).toMatchObject({ from: "[email protected]", to: "[email protected]", subject: "Your OpenMausBot sign-in code" });+ const code = box.code();+ expect(code).toMatch(/^\d{8}$/);+ expect(mail.check("[email protected]", code)).toBe("wrong");+ expect(mail.check("[email protected]", `${code.slice(0, 4)} ${code.slice(4)}`)).toBe("ok");+ expect(mail.check("[email protected]", code)).toBe("wrong");+ expect(mail.check("[email protected]", "12")).toBe("format");+ });++ it("ends a code after ten minutes or five wrong tries, and sends at most one every 30 seconds", async () => {+ let clock = 1_000_000;+ const box = mailbox();+ const mail = createSignInMail({ url: URL_, from: "Sign-in <[email protected]>", now: () => clock, transport: box.transport });+ await mail.send("[email protected]");+ expect(box.sent[0]!.from).toBe("Sign-in <[email protected]>");+ expect(await mail.send("[email protected]")).toBe("tooSoon");+ clock += SIGNIN_CODE_RESEND_MS;+ expect(await mail.send("[email protected]")).toBe("sent");+ const code = box.code();+ const wrong = code === "00000000" ? "11111111" : "00000000";+ for (let attempt = 1; attempt < SIGNIN_CODE_TRIES; attempt++) expect(mail.check("[email protected]", wrong)).toBe("wrong");+ expect(mail.check("[email protected]", wrong)).toBe("tooMany");+ expect(mail.check("[email protected]", code)).toBe("wrong");+ clock += SIGNIN_CODE_RESEND_MS;+ await mail.send("[email protected]");+ clock += SIGNIN_CODE_TTL_MS;+ expect(mail.check("[email protected]", box.code())).toBe("wrong");+ });++ it("forgets a code the mail server refused, and needs a sender address", async () => {+ let refuse = true;+ const sent: MailMessage[] = [];+ const mail = createSignInMail({ url: URL_, transport: { sendMail: async (message) => { if (refuse) throw new Error("550 relay denied"); sent.push(message); } } });+ await expect(mail.send("[email protected]")).rejects.toThrow("550");+ refuse = false;+ expect(await mail.send("[email protected]")).toBe("sent");+ await expect(createSignInMail({ url: "smtp://localhost:25", transport: { sendMail: async () => undefined } }).send("[email protected]"))+ .rejects.toThrow("OMB_SIGNIN_SMTP_FROM");+ });++ it("is what email sign-in uses when OMB_SIGNIN_SMTP_URL is set: no account service, the allow-list as before", async () => {+ const box = mailbox();+ const signIn = createEmailSignIn({+ allow: { admins: ["[email protected]"], members: ["@team.test"] },+ env: { OMB_SIGNIN_SMTP_URL: URL_, OMB_CONTROL_PLANE_URL: "https://control-plane.invalid" },+ fetchImpl: async () => { throw new Error("the account service must not be asked"); },+ mailTransport: box.transport,+ });+ expect(await signIn.start("[email protected]")).toMatchObject({ ok: false, status: 403 });+ expect(box.sent).toEqual([]);+ expect(await signIn.start("[email protected]")).toEqual({ ok: true });+ expect(await signIn.start("[email protected]")).toMatchObject({ ok: false, status: 429 });+ expect(await signIn.verify("[email protected]", "1")).toMatchObject({ ok: false, status: 400 });+ expect(await signIn.verify("[email protected]", box.code() === "00000000" ? "11111111" : "00000000")).toMatchObject({ ok: false, status: 401 });+ expect(await signIn.verify("[email protected]", box.code())).toEqual({ ok: true, email: "[email protected]", userId: "email:[email protected]", scopes: ["admin", "client"] });+ await signIn.start("[email protected]");+ expect(await signIn.verify("[email protected]", box.code())).toMatchObject({ ok: true, scopes: ["client"] });+ });++ it("says why when the mail server cannot be used", async () => {+ const signIn = createEmailSignIn({ allow: { admins: ["[email protected]"], members: [] }, env: { OMB_SIGNIN_SMTP_URL: "smtp://localhost:25" } });+ const refused = await signIn.start("[email protected]");+ expect(refused).toMatchObject({ ok: false, status: 502 });+ expect(refused.ok ? "" : refused.error).toContain("OMB_SIGNIN_SMTP_FROM");+ });+});++describe("a real SMTP conversation", () => {+ let server: Server | undefined;+ afterEach(() => new Promise<void>((done) => (server ? server.close(() => done()) : done())));++ it("delivers the code to a mail server on this machine through nodemailer", async () => {+ const received: string[] = [];+ server = createServer((socket) => {+ let data = false;+ let buffer = "";+ socket.write("220 fake.local ESMTP\r\n");+ socket.on("data", (chunk) => {+ buffer += chunk.toString("utf8");+ let end: number;+ while ((end = buffer.indexOf("\r\n")) >= 0) {+ const line = buffer.slice(0, end);+ buffer = buffer.slice(end + 2);+ if (data) {+ if (line === ".") { data = false; socket.write("250 queued\r\n"); } else received.push(line);+ continue;+ }+ const verb = line.slice(0, 4).toUpperCase();+ if (verb === "EHLO") socket.write("250-fake.local\r\n250 8BITMIME\r\n");+ else if (verb === "DATA") { data = true; socket.write("354 go on\r\n"); }+ else if (verb === "QUIT") socket.end("221 bye\r\n");+ else socket.write("250 ok\r\n");+ }+ });+ });+ await new Promise<void>((ready) => server!.listen(0, "127.0.0.1", ready));+ const port = (server.address() as AddressInfo).port;+ const mail = createSignInMail({ url: `smtp://127.0.0.1:${port}`, from: "[email protected]" });+ expect(await mail.send("[email protected]")).toBe("sent");+ const message = received.join("\n");+ expect(message).toContain("To: [email protected]");+ const code = /(\d{4}) (\d{4})/.exec(message)!.slice(1).join("");+ expect(mail.check("[email protected]", code)).toBe("ok");+ });+});diff --git a/server/sign-in-mail.ts b/server/sign-in-mail.tsnew file mode 100644index 0000000000..76ee012c9c--- /dev/null+++ b/server/sign-in-mail.ts@@ -0,0 +1,105 @@+// Email sign-in codes sent through the server's own mail server (OMB_SIGNIN_SMTP_URL) instead of the OpenMausBot account+// service. A code is 8 digits, works once for ten minutes and for five tries, and only its hash is kept, in memory.+import { createHash, randomInt, timingSafeEqual } from "node:crypto";++export const SIGNIN_CODE_TTL_MS = 10 * 60_000;+export const SIGNIN_CODE_RESEND_MS = 30_000;+export const SIGNIN_CODE_TRIES = 5;+const MAX_PENDING = 1_000;++export interface MailMessage {+ from: string;+ to: string;+ subject: string;+ text: string;+}++export interface MailTransport {+ sendMail(message: MailMessage): Promise<unknown>;+}++export type CodeCheck = "ok" | "format" | "wrong" | "tooMany";++export interface SignInMail {+ /** "tooSoon": a code went to this address moments ago; it still works. */+ send(email: string): Promise<"sent" | "tooSoon">;+ check(email: string, code: string): CodeCheck;+}++export class SignInMailError extends Error {}++const LOOPBACK = /^(?:localhost|127(?:\.\d{1,3}){3}|\[::1\])$/i;++/** `smtps://user:password@host:465` (TLS from the start) or `smtp://user:password@host:587` (STARTTLS, required unless+ * the mail server is on this machine). The user name and password are URL-encoded. */+export function smtpOptions(url: string) {+ let parsed: URL;+ try {+ parsed = new URL(url);+ } catch {+ throw new SignInMailError("OMB_SIGNIN_SMTP_URL is not a URL such as smtps://user:[email protected]:465");+ }+ if (parsed.protocol !== "smtps:" && parsed.protocol !== "smtp:") throw new SignInMailError("OMB_SIGNIN_SMTP_URL must start with smtps:// or smtp://");+ const secure = parsed.protocol === "smtps:";+ const user = decodeURIComponent(parsed.username);+ return {+ host: parsed.hostname.replace(/^\[(.*)\]$/, "$1"), port: Number(parsed.port) || (secure ? 465 : 587), secure,+ requireTLS: !secure && !LOOPBACK.test(parsed.hostname),+ ...(user ? { auth: { user, pass: decodeURIComponent(parsed.password) } } : {}),+ connectionTimeout: 10_000, greetingTimeout: 10_000, socketTimeout: 20_000,+ };+}++const digest = (code: string) => createHash("sha256").update(code).digest();++export function createSignInMail(options: { url: string; from?: string; now?: () => number; transport?: MailTransport }): SignInMail {+ const now = options.now ?? Date.now;+ const pending = new Map<string, { hash: Buffer; sentAt: number; tries: number }>();+ let transport: Promise<MailTransport> | undefined = options.transport ? Promise.resolve(options.transport) : undefined;+ const from = (): string => {+ const named = options.from?.trim() || smtpOptions(options.url).auth?.user || "";+ if (!named.includes("@")) throw new SignInMailError("set OMB_SIGNIN_SMTP_FROM to the address sign-in codes come from");+ return named;+ };+ const prune = () => {+ for (const [email, entry] of pending) if (now() - entry.sentAt >= SIGNIN_CODE_TTL_MS) pending.delete(email);+ };+ return {+ async send(email) {+ prune();+ const open = pending.get(email);+ if (open && now() - open.sentAt < SIGNIN_CODE_RESEND_MS) return "tooSoon";+ if (!open && pending.size >= MAX_PENDING) return "tooSoon";+ const sender = from();+ transport ??= import("nodemailer").then(({ createTransport }) => createTransport(smtpOptions(options.url)));+ const code = String(randomInt(0, 100_000_000)).padStart(8, "0");+ pending.set(email, { hash: digest(code), sentAt: now(), tries: 0 });+ try {+ await (await transport).sendMail({+ from: sender, to: email, subject: "Your OpenMausBot sign-in code",+ text: `Your code to sign in to OpenMausBot is\n\n ${code.slice(0, 4)} ${code.slice(4)}\n\nIt works once, for the next ten minutes.\n`+ + "If you did not ask to sign in, ignore this email: nobody gets in without the code.\n",+ });+ } catch (error) {+ pending.delete(email);+ throw error;+ }+ return "sent";+ },+ check(email, raw) {+ const code = raw.replace(/[\s-]/g, "");+ if (!/^\d{8}$/.test(code)) return "format";+ prune();+ const entry = pending.get(email);+ if (!entry) return "wrong";+ entry.tries += 1;+ if (timingSafeEqual(entry.hash, digest(code))) {+ pending.delete(email);+ return "ok";+ }+ if (entry.tries < SIGNIN_CODE_TRIES) return "wrong";+ pending.delete(email);+ return "tooMany";+ },+ };+}