Skip to content

One-click character swap for videos: an open-source, local Higgsfield Genjutsu alternative built on ComfyUI and MiniMax H3, with FLUX.3 Klein relighting.

Back off failed sign-ins and require a 12-character password (#13)

mixbag7cf2314eb732
diff --git a/README.md b/README.md
index 1658c6b..4794eac 100644
--- a/README.md
+++ b/README.md
@@ -147,7 +147,7 @@ Not tested yet. The app code does not change, only `.env.local`:
2. Create a deployment from the released Build on the Developer Platform. The workflow has only been run on a 16 GB card with 64 GB of system RAM, so choose at least that.
3. Set `COMFY_BASE_URL` to the deployment URL and `COMFY_API_KEY` to a key from the workspace that owns it. The key stays on the server; never put it in a `NEXT_PUBLIC_` variable.
-4. Before hosting or tunneling the app, set a strong `OPENJUTSU_PASSWORD` and use HTTPS. Without a password, Openjutsu refuses to start on any address but loopback. Open the page and sign in as `openjutsu` with that password; the same browser login protects uploads, job controls, progress and downloads. This is a single-owner app: everyone given the password shares access to its jobs. The start-up check cannot see a tunnel or reverse proxy on the same machine, so never point one at a password-free server.
+4. Before hosting or tunneling the app, set a strong `OPENJUTSU_PASSWORD` and use HTTPS. Without a password, Openjutsu refuses to start on any address but loopback. It also refuses a password shorter than 12 characters. After 5 wrong passwords a client must wait before each try, from 1 second doubling to 5 minutes; clients are told apart by their `X-Forwarded-For` address, which only a proxy or tunnel that sets it makes reliable, so 20 failures spread across clients make everyone wait too. Open the page and sign in as `openjutsu` with that password; the same browser login protects uploads, job controls, progress and downloads. This is a single-owner app: everyone given the password shares access to its jobs. The start-up check cannot see a tunnel or reverse proxy on the same machine, so never point one at a password-free server.
5. Host the Next.js app anywhere that runs Node. `npm start` listens on `127.0.0.1` only; to serve on a network address, build and start Next with the password set (Next uses `PORT` if the host sets it, otherwise 3000):
```sh
diff --git a/instrumentation.ts b/instrumentation.ts
index e6c7c90..9dece20 100644
--- a/instrumentation.ts
+++ b/instrumentation.ts
@@ -2,6 +2,14 @@ import type { Server } from "node:net";
// Next is already listening when register() runs, so check the real bound addresses rather than request headers.
export async function register() {
+ const password = process.env.OPENJUTSU_PASSWORD;
+ if (process.env.NEXT_RUNTIME === "nodejs" && password) {
+ const { MIN_PASSWORD_LENGTH, PASSWORD_TOO_SHORT } = await import("./lib/http.ts");
+ if (password.length < MIN_PASSWORD_LENGTH) {
+ console.error(PASSWORD_TOO_SHORT);
+ process.exit(1);
+ }
+ }
if (process.env.NEXT_RUNTIME === "nodejs" && !process.env.OPENJUTSU_PASSWORD) {
const [{ Server }, { loopbackOnly, PASSWORD_REQUIRED }] = await Promise.all([import("node:net"), import("./lib/http.ts")]);
// _getActiveHandles() is undocumented; if it ever finds no listening server, this fails closed.
diff --git a/lib/http.ts b/lib/http.ts
index 4d33818..50a8053 100644
--- a/lib/http.ts
+++ b/lib/http.ts
@@ -14,13 +14,68 @@ export function validateJobId(id: string) {
if (!/^[A-Za-z0-9_-]+$/.test(id) || id.startsWith("http")) throw new HttpError(400, "Invalid job ID.");
}
+export const MIN_PASSWORD_LENGTH = 12;
+export const PASSWORD_TOO_SHORT = `OPENJUTSU_PASSWORD must be at least ${MIN_PASSWORD_LENGTH} characters. Choose a longer password and start again.`;
+
+// Failed sign-ins back off per client: 5 free tries, then 1 s doubling to 5 min, forgotten after an hour without failures.
+// Next fills X-Forwarded-For with the socket address only when the request has none, so its last entry names the client
+// only behind a proxy or tunnel that appends it. Served directly, a client can forge it, so each client's free tries also
+// count against one shared allowance.
+const FREE_FAILURES = 5;
+const SHARED_FREE_FAILURES = 20;
+const MAX_DELAY = 5 * 60_000;
+const FORGET_AFTER = 60 * 60_000;
+const MAX_CLIENTS = 1000;
+type Failures = { count: number; last: number };
+// Proxy is bundled apart from the route handlers, so both keep their record on globalThis.
+const { failures, shared } = ((globalThis as { [key: symbol]: unknown })[Symbol.for("openjutsu.failures")] ??=
+ { failures: new Map(), shared: { count: 0, last: 0 } }) as { failures: Map<string, Failures>; shared: Failures };
+
+function waitAfter(entry: Failures | undefined, free: number, now: number) {
+ if (!entry || entry.count <= free || now - entry.last > FORGET_AFTER) return 0;
+ return Math.max(0, entry.last + Math.min(1000 * 2 ** (entry.count - free - 1), MAX_DELAY) - now);
+}
+
+function recordFailure(client: string, now: number) {
+ const entry = failures.get(client);
+ const count = entry && now - entry.last <= FORGET_AFTER ? entry.count + 1 : 1;
+ failures.delete(client);
+ failures.set(client, { count, last: now });
+ // Map order is oldest failure first, so expired and excess clients are at the front.
+ for (const [key, { last }] of failures) {
+ if (failures.size <= MAX_CLIENTS && now - last <= FORGET_AFTER) break;
+ failures.delete(key);
+ }
+ if (count <= FREE_FAILURES) {
+ shared.count = now - shared.last <= FORGET_AFTER ? shared.count + 1 : 1;
+ shared.last = now;
+ }
+}
+
export function authorize(request: Request) {
const password = process.env.OPENJUTSU_PASSWORD;
if (password) {
const encoded = request.headers.get("Authorization")?.match(/^Basic\s+(\S+)$/i)?.[1] ?? "";
+ const client = request.headers.get("X-Forwarded-For")?.split(",").at(-1)?.trim() ?? "";
+ const now = performance.now();
+ if (encoded) {
+ // Refuse before comparing, or the answer to a correct guess would still leak at full speed.
+ const wait = Math.max(waitAfter(failures.get(client), FREE_FAILURES, now), waitAfter(shared, SHARED_FREE_FAILURES, now));
+ if (wait > 0) {
+ const seconds = Math.ceil(wait / 1000);
+ return Response.json({ error: `Too many failed sign-ins. Try again in ${seconds} s.` }, {
+ status: 429,
+ headers: { "Retry-After": String(seconds), "Cache-Control": "no-store" },
+ });
+ }
+ }
const supplied = createHash("sha256").update(Buffer.from(encoded, "base64")).digest();
const expected = createHash("sha256").update(`openjutsu:${password}`).digest();
- if (!timingSafeEqual(supplied, expected)) {
+ if (timingSafeEqual(supplied, expected)) {
+ failures.delete(client);
+ } else {
+ // A request without credentials is the browser asking for the sign-in prompt, not a guess.
+ if (encoded) recordFailure(client, now);
return Response.json({ error: "Sign in to Openjutsu." }, {
status: 401,
headers: { "WWW-Authenticate": 'Basic realm="Openjutsu", charset="UTF-8"', "Cache-Control": "no-store" },
diff --git a/test/http.test.ts b/test/http.test.ts
index 6a8b9ff..7ba26b2 100644
--- a/test/http.test.ts
+++ b/test/http.test.ts
@@ -1,7 +1,7 @@
import assert from "node:assert/strict";
import { createServer, type Server } from "node:net";
import test from "node:test";
-import { apiAccess, authorize, HttpError, loopbackOnly, PASSWORD_REQUIRED, readFormData, validateJobId } from "../lib/http.ts";
+import { apiAccess, authorize, HttpError, loopbackOnly, PASSWORD_REQUIRED, PASSWORD_TOO_SHORT, readFormData, validateJobId } from "../lib/http.ts";
import { getJob } from "../lib/comfy.ts";
import { register } from "../instrumentation.ts";
@@ -65,6 +65,12 @@ test("password-free serving starts only on loopback; a network bind needs a pass
process.env.OPENJUTSU_PASSWORD = "review-test-password";
await register();
assert.equal(errors.length, 2);
+ process.env.OPENJUTSU_PASSWORD = "elevenchars";
+ await assert.rejects(register(), /exit 1/, "a short password is refused even on loopback");
+ assert.equal(errors.at(-1), PASSWORD_TOO_SHORT);
+ process.env.OPENJUTSU_PASSWORD = "twelve-chars";
+ await register();
+ assert.equal(errors.length, 3);
});
test("a configured password protects local and hosted access, including media and event requests", (t) => {
@@ -86,6 +92,46 @@ test("a configured password protects local and hosted access, including media an
assert.equal(apiAccess(new Request("https://openjutsu.example/api/jobs", { headers: { Authorization: authorization, Origin: "https://attacker.example" } }))?.status, 403);
});
+test("failed sign-ins back off per client and across forged clients; the right password from a fresh client is never slowed", (t) => {
+ const previous = process.env.OPENJUTSU_PASSWORD;
+ process.env.OPENJUTSU_PASSWORD = "review-test-password";
+ t.after(() => { if (previous === undefined) delete process.env.OPENJUTSU_PASSWORD; else process.env.OPENJUTSU_PASSWORD = previous; });
+ // Start hours after the failures in earlier tests so they are forgotten.
+ let now = performance.now() + 2 * 60 * 60_000;
+ t.mock.method(performance, "now", () => now);
+ const signIn = (password: string | null, client = "203.0.113.7") => {
+ const headers: Record<string, string> = { "X-Forwarded-For": `198.51.100.1, ${client}` };
+ if (password !== null) headers.Authorization = `Basic ${Buffer.from(`openjutsu:${password}`).toString("base64")}`;
+ return authorize(new Request("https://openjutsu.example/api/models", { headers }));
+ };
+ const status = (password: string | null, client?: string) => signIn(password, client)?.status ?? 200;
+
+ for (let i = 0; i < 6; i++) assert.equal(status("wrong"), 401, `failure ${i + 1} is answered`);
+ const refused = signIn("wrong")!;
+ assert.equal(refused.status, 429);
+ assert.equal(refused.headers.get("Retry-After"), "1");
+ assert.equal(status("review-test-password"), 429, "a client in backoff cannot test even the right password");
+ assert.equal(status(null), 401, "asking for the sign-in prompt is never refused");
+ assert.equal(status("review-test-password", "203.0.113.8"), 200, "other clients sign in at once, keyed by the entry nearest the proxy");
+ now += 1000;
+ assert.equal(status("wrong"), 401);
+ now += 1000;
+ assert.equal(status("wrong"), 429, "the delay doubles");
+ now += 1000;
+ assert.equal(status("review-test-password"), 200);
+ assert.equal(status("wrong"), 401, "success clears the client's failures");
+ for (let i = 0; i < 6; i++) status("wrong");
+ now += 60 * 60_000 + 1;
+ assert.equal(status("wrong"), 401, "failures are forgotten after an hour");
+
+ now += 60 * 60_000 + 1;
+ for (let i = 0; i < 21; i++) assert.equal(status("wrong", `forged-${i}`), 401);
+ assert.equal(status("wrong", "forged-new"), 429, "forged client addresses share one allowance");
+ assert.equal(status("review-test-password", "203.0.113.9"), 429);
+ now += 1000;
+ assert.equal(status("review-test-password", "203.0.113.9"), 200);
+});
+
test("bounded multipart parsing preserves video bytes, duplicate pictures and roles", async () => {
const form = new FormData();
form.set("video", new File([new Uint8Array([0, 1, 255])], "clip.mp4", { type: "video/mp4" }));