Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/owner-code-verified-owner.md
Original file line number Diff line number Diff line change
@@ -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.
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 3 additions & 1 deletion src/commands/helpTopics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
69 changes: 68 additions & 1 deletion src/core/ownerCode.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 }),
),
);
Expand All @@ -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/],
Expand Down
81 changes: 64 additions & 17 deletions src/core/ownerCode.ts
Original file line number Diff line number Diff line change
@@ -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";
Expand Down Expand Up @@ -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<string> {
path: string,
init: RequestInit,
): Promise<ApiResponse<Record<string, unknown>>> {
let res;
try {
res = await apiRequest<Record<string, unknown>>(
joinUrl(authUrl, "/registration/register"),
jsonBody("POST", { email }, { [EXTERNAL_DELIVERY_HEADER]: "external" }),
);
res = await apiRequest<Record<string, unknown>>(joinUrl(authUrl, path), init);
} catch {
throw new OwnerCodeError(`Could not reach the auth server at ${authUrl}.`);
}
Expand All @@ -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<string, unknown> | 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<string> {
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.",
Expand Down