From 86b27df68eec27ac3e26e34207bbb9870b3ce744 Mon Sep 17 00:00:00 2001 From: Brandon Corbett Date: Fri, 4 Dec 2026 12:13:22 -0500 Subject: [PATCH] fix(owner-code): sign in for the code when the owner is already verified Auth API 0.24.0 answers registration for a verified address as a new sign-up with no code, so owner-code now falls back to /login and the sign-in code route when registration returns none. --- .changeset/owner-code-verified-owner.md | 5 ++ README.md | 3 +- src/commands/helpTopics.ts | 4 +- src/core/ownerCode.test.ts | 69 ++++++++++++++++++++- src/core/ownerCode.ts | 81 +++++++++++++++++++------ 5 files changed, 142 insertions(+), 20 deletions(-) create mode 100644 .changeset/owner-code-verified-owner.md diff --git a/.changeset/owner-code-verified-owner.md b/.changeset/owner-code-verified-owner.md new file mode 100644 index 0000000..f0eab01 --- /dev/null +++ b/.changeset/owner-code-verified-owner.md @@ -0,0 +1,5 @@ +--- +"seamless-cli": patch +--- + +`seamless owner-code` prints a code for an owner whose account is already verified, so the owner of a local stack can sign in again without reading container logs. Auth API 0.24.0 stopped returning a code from registration for a verified address, so the command now falls back to the sign-in code route when registration returns none. The first registration is unchanged. diff --git a/README.md b/README.md index 6dbf9fc..ae616fb 100644 --- a/README.md +++ b/README.md @@ -496,7 +496,8 @@ seamless owner-code The local stack sends no email, so when the page asks for a code, `seamless owner-code` prints one for the owner. It waits for the auth server, defaults to the project's `OWNER_EMAIL`, and only talks to a local auth server (`--url`, default `http://localhost:5312`). The code replaces any code sent -before, so run it after the page asks, and enter it within 5 minutes. +before, so run it after the page asks, and enter it within 5 minutes. It also works when the owner +signs in again later: for an address that has already registered, it prints a sign-in code. The owner gets `admin:write` (or `admin` on an instance whose available roles list only that). Email OTP registration creates the account before the address is verified, but an unverified account diff --git a/src/commands/helpTopics.ts b/src/commands/helpTopics.ts index e3c08bd..d848045 100644 --- a/src/commands/helpTopics.ts +++ b/src/commands/helpTopics.ts @@ -228,7 +228,9 @@ can finish registering without reading container logs. Register in the browser with the owner address first. When the page asks for a code, run this from the project directory and enter what it prints. -The code replaces any code sent before and expires in 5 minutes. +The code replaces any code sent before and expires in 5 minutes. Signing +in again later works the same way: for an owner who has already +registered, the code is a sign-in code. [email] • Defaults to OWNER_EMAIL from auth/.env or docker-compose.yml diff --git a/src/core/ownerCode.test.ts b/src/core/ownerCode.test.ts index 999e749..92a12cb 100644 --- a/src/core/ownerCode.test.ts +++ b/src/core/ownerCode.test.ts @@ -150,10 +150,49 @@ describe("requestOwnerCode", () => { expect(JSON.parse(init.body)).toEqual({ email: "owner@example.com" }); }); + it("signs in for the code when registration returns none for a verified owner", async () => { + const fetchMock = vi + .fn() + .mockResolvedValueOnce( + jsonResponse(200, { message: "Success", sub: "other", token: "decoy", ttl: 300 }), + ) + .mockResolvedValueOnce( + jsonResponse(200, { + message: "Success", + token: "pre-auth", + identifierType: "email", + loginMethods: ["email_otp"], + }), + ) + .mockResolvedValueOnce( + jsonResponse(200, { + message: "success", + token: "pre-auth-2", + delivery: { kind: "otp_email", to: "owner@example.com", token: "XYZ789" }, + }), + ); + vi.stubGlobal("fetch", fetchMock); + + await expect( + requestOwnerCode("http://localhost:5312", "owner@example.com"), + ).resolves.toBe("XYZ789"); + + const [loginUrl, loginInit] = fetchMock.mock.calls[1]; + expect(loginUrl).toBe("http://localhost:5312/login"); + expect(loginInit.method).toBe("POST"); + expect(JSON.parse(loginInit.body)).toEqual({ identifier: "owner@example.com" }); + + const [sendUrl, sendInit] = fetchMock.mock.calls[2]; + expect(sendUrl).toBe("http://localhost:5312/otp/generate-login-email-otp"); + expect(sendInit.method).toBe("POST"); + expect(sendInit.headers.Authorization).toBe("Bearer pre-auth"); + expect(sendInit.headers["x-seamless-auth-delivery-mode"]).toBe("external"); + }); + it("explains the dev setting when the server withholds the code", async () => { vi.stubGlobal( "fetch", - vi.fn().mockResolvedValue( + vi.fn().mockImplementation(async () => jsonResponse(200, { message: "Success", sub: "u1", token: "e", ttl: 300 }), ), ); @@ -163,6 +202,34 @@ describe("requestOwnerCode", () => { ).rejects.toThrow(/ALLOW_UNCREDENTIALED_DELIVERY_SECRETS/); }); + it("does not ask for a sign-in code when the login answer carries no token", async () => { + const fetchMock = vi + .fn() + .mockResolvedValueOnce(jsonResponse(200, { message: "Success" })) + .mockResolvedValueOnce(jsonResponse(200, { message: "Success" })); + vi.stubGlobal("fetch", fetchMock); + + await expect( + requestOwnerCode("http://localhost:5312", "owner@example.com"), + ).rejects.toThrow(/did not return the code/); + expect(fetchMock).toHaveBeenCalledTimes(2); + }); + + it("names a refusal from the sign-in code route", async () => { + vi.stubGlobal( + "fetch", + vi + .fn() + .mockResolvedValueOnce(jsonResponse(200, { message: "Success", token: "decoy" })) + .mockResolvedValueOnce(jsonResponse(200, { message: "Success", token: "pre-auth" })) + .mockResolvedValueOnce(jsonResponse(403, { error: "login_method_disabled" })), + ); + + await expect( + requestOwnerCode("http://localhost:5312", "owner@example.com"), + ).rejects.toThrow(/refused the request \(403\)/); + }); + it.each([ [429, /rate limiting/], [400, /not a valid email/], diff --git a/src/core/ownerCode.ts b/src/core/ownerCode.ts index eb819b0..c727d24 100644 --- a/src/core/ownerCode.ts +++ b/src/core/ownerCode.ts @@ -1,7 +1,13 @@ import fs from "fs"; import path from "path"; import { parseEnv } from "./env.js"; -import { apiRequest, isRateLimited, joinUrl, jsonBody } from "./http.js"; +import { + apiRequest, + type ApiResponse, + isRateLimited, + joinUrl, + jsonBody, +} from "./http.js"; import { deliveryCode } from "./loginFlow.js"; export const LOCAL_AUTH_URL = "http://localhost:5312"; @@ -98,25 +104,15 @@ export async function waitForAuthServer( ); } -/** - * Issues a fresh email code for the address through registration, with external - * delivery so it comes back in the response. - * - * The auth server keeps one email code per account, so this code replaces whatever - * the browser's own registration or sign-in sent and is accepted on that page. For an - * address with no account yet, registration creates it, which is what grants the - * owner its admin role. - */ -export async function requestOwnerCode( +async function send( authUrl: string, email: string, -): Promise { + path: string, + init: RequestInit, +): Promise>> { let res; try { - res = await apiRequest>( - joinUrl(authUrl, "/registration/register"), - jsonBody("POST", { email }, { [EXTERNAL_DELIVERY_HEADER]: "external" }), - ); + res = await apiRequest>(joinUrl(authUrl, path), init); } catch { throw new OwnerCodeError(`Could not reach the auth server at ${authUrl}.`); } @@ -132,8 +128,59 @@ export async function requestOwnerCode( if (!res.ok) { throw new OwnerCodeError(`The auth server refused the request (${res.status}).`); } + return res; +} + +function preAuthToken(data: Record | null): string | undefined { + const token = data?.token; + return typeof token === "string" && token ? token : undefined; +} + +/** + * Issues a fresh email code for the address, with external delivery so it comes back + * in the response. + * + * The auth server keeps one email code per account, so this code replaces whatever + * the browser's own registration or sign-in sent and is accepted on that page. For an + * address with no account yet, or one not yet verified, registration issues it and + * creates the account, which is what grants the owner its admin role. + * + * From auth API 0.24.0, registration answers an address whose account is already + * verified as a new sign-up with no code, so the same email is then signed in instead + * and the code comes from the sign-in code route. + */ +export async function requestOwnerCode( + authUrl: string, + email: string, +): Promise { + const external = { [EXTERNAL_DELIVERY_HEADER]: "external" }; - const code = deliveryCode(res.data); + const registered = await send( + authUrl, + email, + "/registration/register", + jsonBody("POST", { email }, external), + ); + const registrationCode = deliveryCode(registered.data); + if (registrationCode) return registrationCode; + + // `/login` answers every address with a pre-auth token, a decoy one when there is no + // verified account, and a decoy is sent no code. So a missing code below means the + // server withheld it or there is no account to sign in, never a wrong guess at which. + const started = await send( + authUrl, + email, + "/login", + jsonBody("POST", { identifier: email }), + ); + const token = preAuthToken(started.data); + const sent = token + ? await send(authUrl, email, "/otp/generate-login-email-otp", { + method: "POST", + headers: { ...external, Authorization: `Bearer ${token}` }, + }) + : undefined; + const code = sent ? deliveryCode(sent.data) : undefined; if (!code) { throw new OwnerCodeError( "The auth server did not return the code. It returns codes only outside production with ALLOW_UNCREDENTIALED_DELIVERY_SECRETS=true, which seamless init sets.",