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
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ npm run dev:e2e
npm run auth:e2e:save
```

Reset with `npm run e2e:local:reset` before a full run, then save auth again because reset replaces the local user. See [`docs/agents/local-e2e.md`](./docs/agents/local-e2e.md) for fixture IDs, safety rules, lifecycle commands, and verification.
Reset with `npm run e2e:local:reset` before a full run, then save auth again because reset replaces the local user. To test on a phone, open the Wi-Fi address that `dev:e2e` prints and paste the code from `npm run auth:e2e:copy-code`. Claude has its own local account, which **Sign in as Claude** selects and `npm run auth:e2e:save:claude` saves. See [`docs/agents/local-e2e.md`](./docs/agents/local-e2e.md) for fixture IDs, safety rules, lifecycle commands, and verification.

The existing-account flow below remains available for non-destructive local checks against a configured development project. Do not use it for the resettable browser suite.

Expand Down
20 changes: 17 additions & 3 deletions app/(auth)/login/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import { ClearPrivateBrowserCache } from "@/components/ui/ClearPrivateBrowserCac
import { PageHeader } from "@/components/ui/PageHeader";
import { getCurrentUser } from "@/lib/auth";
import { getLoginAuthError } from "@/lib/server/login-error";
import { getLocalLoginPageState } from "@/lib/server/local-test-login";
import { CLAUDE_LOCAL_LOGIN_ACCOUNT, getLocalLoginPageState } from "@/lib/server/local-test-login";

type LoginPageProps = {
searchParams: Promise<{
Expand All @@ -24,7 +24,7 @@ export default async function LoginPage({ searchParams }: LoginPageProps) {
const user = await getCurrentUser();
const requestHeaders = await headers();
const host = requestHeaders.get("host") || "";
const { requiresPairingCode, showLocalLogin } = getLocalLoginPageState(host);
const { requiresPairingCode, showClaudeLogin, showLocalLogin } = getLocalLoginPageState(host);
const localError =
params.localError === "pairing-code"
? "That local pairing code was not accepted. Copy the current code from your Mac and try again."
Expand Down Expand Up @@ -92,13 +92,27 @@ export default async function LoginPage({ searchParams }: LoginPageProps) {
type="password"
/>
<p className="text-sm text-muted-foreground">
On your Mac, run npm run auth:local:copy-code, then paste the code here.
On your Mac, run npm run{" "}
{process.env.POKENOTES_E2E_LOCAL === "1"
? "auth:e2e:copy-code"
: "auth:local:copy-code"}
, then paste the code here.
</p>
</div>
) : null}
<Button type="submit">
{showLocalLogin ? "Sign in locally" : "Sign in with Google"}
</Button>
{showClaudeLogin ? (
<Button
name="account"
type="submit"
value={CLAUDE_LOCAL_LOGIN_ACCOUNT}
variant="outline"
>
Sign in as Claude
</Button>
) : null}
</form>
</div>
{showLocalLogin ? (
Expand Down
1 change: 1 addition & 0 deletions app/auth/dev-login/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ export async function POST(request: NextRequest) {
}
const pairingCode = String(formData.get("pairingCode") || "");
const validation = validateLocalLoginAttempt({
account: String(formData.get("account") || "") || null,
host: request.headers.get("host"),
origin: request.headers.get("origin"),
pairingCode,
Expand Down
17 changes: 16 additions & 1 deletion docs/agents/local-e2e.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,21 @@ The isolated app runs at `http://localhost:3010`, alongside the normal watchdog-

The setup command writes ignored, mode-`0600` credentials to `.env.e2e.local`. Do not print, copy into documentation, or commit that file.

## Phone, iOS Simulator, and Claude's account

`npm run dev:e2e` listens on every interface and prints the Wi-Fi addresses a phone can use, such as `http://<LocalHostName>.local:3010` or `http://192.168.x.y:3010`. It discovers those addresses each time it starts, adds them to the pairing-login host list and to Next.js `allowedDevOrigins`, and stores nothing, so a new network needs only a restart. The phone must be on the same Wi-Fi as the Mac. On the Mac, run `npm run auth:e2e:copy-code`, then paste into the phone's pairing-code field with Universal Clipboard.

The iOS Simulator shares the Mac's network, so `http://localhost:3010` works in its Safari. Agents drive it with the T3 device tools (`device_list`, `device_open`, then the returned `agent-device` command) and should use the Wi-Fi address when the check is meant to stand in for a phone.

The reset seeds two accounts:

| Account | Use |
| --- | --- |
| `e2e@pokenotes.local` (E2E Trainer) | The fixture account below. Browser journeys assert on it; **Sign in locally** selects it. |
| `claude@pokenotes.local` (Claude Tester) | Claude's own account. It starts empty, so agent checks create their own state through the UI. **Sign in as Claude** selects it. |

Save Claude's agent-browser state with `npm run auth:e2e:save:claude`; it is written to `.agent-browser/pokenotes-e2e-claude-auth.json`. Both accounts share the pairing code, and a reset recreates both, so save both states again after every reset. Uploaded profile photos load from `127.0.0.1:54321` and do not appear on a physical phone; preset avatars do.

## Routine use

For the complete Battle Log import check, run:
Expand Down Expand Up @@ -116,7 +131,7 @@ npm run e2e:local:stop

## Fixture contract

Each reset creates one confirmed synthetic account, `e2e@pokenotes.local`, with stable application IDs:
Each reset creates one confirmed synthetic fixture account, `e2e@pokenotes.local`, with stable application IDs, plus Claude's empty account described above:

| Area | Stable fixtures |
| --- | --- |
Expand Down
7 changes: 7 additions & 0 deletions eslint.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,13 @@ export default [
"react-hooks/set-state-in-effect": "off"
}
},
{
// CommonJS files can only load their dependencies with require().
files: ["**/*.cjs", "next.config.js"],
rules: {
"@typescript-eslint/no-require-imports": "off"
}
},
{
ignores: [
"node_modules/**",
Expand Down
32 changes: 27 additions & 5 deletions lib/server/local-test-login.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,13 @@ type LocalLoginEnvironment = {
POKE_NOTES_LOCAL_LOGIN_HOSTS?: string;
POKE_NOTES_TEST_LOGIN_EMAIL?: string;
POKE_NOTES_TEST_LOGIN_PASSWORD?: string;
POKE_NOTES_CLAUDE_LOGIN_EMAIL?: string;
POKE_NOTES_CLAUDE_LOGIN_PASSWORD?: string;
};

/** Form value that selects Claude's own local test account instead of the default one. */
export const CLAUDE_LOCAL_LOGIN_ACCOUNT = "claude";

const LOOPBACK_HOSTS = new Set(["localhost:3000", "127.0.0.1:3000", "[::1]:3000"]);

function normalizeHost(value: string | null | undefined) {
Expand All @@ -31,12 +36,23 @@ export function isAllowedLocalLoginHost(
return getAllowedLocalLoginHosts(environment).has(normalizeHost(host));
}

function getLocalLoginConfig(environment: LocalLoginEnvironment = process.env) {
function getLocalLoginConfig(
environment: LocalLoginEnvironment = process.env,
account?: string | null
) {
const enabled =
environment.NODE_ENV === "development" &&
environment.POKE_NOTES_ENABLE_TEST_LOGIN === "1";
const email = String(environment.POKE_NOTES_TEST_LOGIN_EMAIL || "");
const password = String(environment.POKE_NOTES_TEST_LOGIN_PASSWORD || "");
const claude = account === CLAUDE_LOCAL_LOGIN_ACCOUNT;
const email = String(
(claude ? environment.POKE_NOTES_CLAUDE_LOGIN_EMAIL : environment.POKE_NOTES_TEST_LOGIN_EMAIL) ||
""
);
const password = String(
(claude
? environment.POKE_NOTES_CLAUDE_LOGIN_PASSWORD
: environment.POKE_NOTES_TEST_LOGIN_PASSWORD) || ""
);
const pairingCode = String(environment.POKE_NOTES_LOCAL_LOGIN_CODE || "");

return {
Expand All @@ -55,21 +71,26 @@ export function getLocalLoginPageState(
const allowedHost = isAllowedLocalLoginHost(host, environment);
const requiresPairingCode = allowedHost;

const showLocalLogin = Boolean(config.configured && allowedHost);

return {
showLocalLogin: Boolean(config.configured && allowedHost),
showLocalLogin,
showClaudeLogin:
showLocalLogin && getLocalLoginConfig(environment, CLAUDE_LOCAL_LOGIN_ACCOUNT).configured,
requiresPairingCode
};
}

export function validateLocalLoginRequest(
input: {
account?: string | null | undefined;
host: string | null | undefined;
origin: string | null | undefined;
secFetchSite?: string | null | undefined;
},
environment: LocalLoginEnvironment = process.env
) {
const config = getLocalLoginConfig(environment);
const config = getLocalLoginConfig(environment, input.account);
const host = normalizeHost(input.host);

if (!config.configured || !isAllowedLocalLoginHost(host, environment)) {
Expand Down Expand Up @@ -100,6 +121,7 @@ export function validateLocalLoginRequest(

export function validateLocalLoginAttempt(
input: {
account?: string | null | undefined;
host: string | null | undefined;
origin: string | null | undefined;
pairingCode: string;
Expand Down
5 changes: 4 additions & 1 deletion next.config.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
const { localNetworkHostnames } = require("./scripts/local-network-hosts.cjs");

const baselineSecurityHeaders = [
{
key: "Permissions-Policy",
Expand All @@ -20,7 +22,8 @@ const baselineSecurityHeaders = [
/** @type {import('next').NextConfig} */
const nextConfig = {
distDir: process.env.POKENOTES_E2E_LOCAL === "1" ? ".next-e2e" : ".next",
allowedDevOrigins: ["192.168.1.195", "Jamess-MacBook-Pro-2.local"],
// Lets a phone on the same Wi-Fi load dev assets from whatever address this Mac has today.
allowedDevOrigins: process.env.NODE_ENV === "production" ? [] : localNetworkHostnames(),
async headers() {
return [
{
Expand Down
2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,8 @@
"auth:local:setup": "node scripts/setup-local-test-login.mjs",
"auth:local:save": "node scripts/save-local-auth-state.mjs",
"auth:e2e:save": "node scripts/local-e2e.mjs save-auth",
"auth:e2e:save:claude": "node scripts/local-e2e.mjs save-auth --account=claude",
"auth:e2e:copy-code": "node scripts/local-e2e.mjs copy-code",
"e2e:local:setup": "node scripts/local-e2e.mjs setup",
"e2e:local:reset": "node scripts/local-e2e.mjs reset",
"e2e:local:start": "node scripts/local-e2e.mjs start",
Expand Down
48 changes: 42 additions & 6 deletions scripts/local-e2e.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import { delimiter, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { config as loadDotenv, parse as parseDotenv } from "dotenv";
import { waitForLocalSchema } from "./local-e2e-readiness.mjs";
import localNetworkHosts from "./local-network-hosts.cjs";

const rootDir = resolve(fileURLToPath(new URL("..", import.meta.url)));
const e2eDir = resolve(rootDir, "tests/e2e");
Expand All @@ -26,6 +27,8 @@ const tsxBin = resolve(rootDir, "node_modules/.bin/tsx");
const nextBin = resolve(rootDir, "node_modules/.bin/next");
const dockerBinDir = "/Applications/Docker.app/Contents/Resources/bin";
const command = process.argv[2] || "status";
const appPort = 3010;
const claudeEmail = "claude@pokenotes.local";
const localSupabaseArgs = ["--workdir", "tests/e2e"];
const excludedServices = [
"realtime",
Expand Down Expand Up @@ -73,11 +76,12 @@ const commands = {
stop,
status,
dev,
"save-auth": saveAuth
"save-auth": saveAuth,
"copy-code": copyCode
};

if (!commands[command]) {
throw new Error(`Unknown command ${JSON.stringify(command)}. Use setup, reset, start, stop, status, dev, or save-auth.`);
throw new Error(`Unknown command ${JSON.stringify(command)}. Use setup, reset, start, stop, status, dev, save-auth, or copy-code.`);
}

await commands[command]();
Expand Down Expand Up @@ -277,6 +281,8 @@ async function reset() {
const previousEnvironment = readExistingE2eEnvironment();
const password = previousEnvironment.POKE_NOTES_TEST_LOGIN_PASSWORD
|| `Local-${randomBytes(18).toString("base64url")}!9`;
const claudePassword = previousEnvironment.POKE_NOTES_CLAUDE_LOGIN_PASSWORD
|| `Local-${randomBytes(18).toString("base64url")}!9`;
const pairingCode = previousEnvironment.POKE_NOTES_LOCAL_LOGIN_CODE
|| randomBytes(18).toString("base64url");
const authClaimsSecret = previousEnvironment.POKENOTES_AUTH_CLAIMS_SECRET
Expand All @@ -286,7 +292,9 @@ async function reset() {
NEXT_PUBLIC_SUPABASE_URL: apiUrl,
SUPABASE_SERVICE_ROLE_KEY: serviceRoleKey,
POKE_NOTES_TEST_LOGIN_EMAIL: "e2e@pokenotes.local",
POKE_NOTES_TEST_LOGIN_PASSWORD: password
POKE_NOTES_TEST_LOGIN_PASSWORD: password,
POKE_NOTES_CLAUDE_LOGIN_EMAIL: claudeEmail,
POKE_NOTES_CLAUDE_LOGIN_PASSWORD: claudePassword
});

console.log("Waiting for the recreated local schema to become readable through PostgREST.");
Expand All @@ -309,6 +317,8 @@ async function reset() {
"POKE_NOTES_LOCAL_LOGIN_HOSTS=localhost:3010,127.0.0.1:3010,[::1]:3010",
"POKE_NOTES_TEST_LOGIN_EMAIL=e2e@pokenotes.local",
`POKE_NOTES_TEST_LOGIN_PASSWORD=${password}`,
`POKE_NOTES_CLAUDE_LOGIN_EMAIL=${claudeEmail}`,
`POKE_NOTES_CLAUDE_LOGIN_PASSWORD=${claudePassword}`,
""
].join("\n");

Expand Down Expand Up @@ -351,19 +361,45 @@ async function dev() {
throw new Error("Refusing to start: the E2E local-only marker is missing.");
}
assertLocalUrl(String(process.env.NEXT_PUBLIC_SUPABASE_URL || ""));
await spawnAndForward(nextBin, ["dev", "-H", "0.0.0.0", "--port", "3010"], localEnvironment());
// Discovered at start, not stored, because the Mac's Wi-Fi address changes between networks.
const lanHosts = localNetworkHosts.localNetworkHostnames();
const loginHosts = new Set([
...String(process.env.POKE_NOTES_LOCAL_LOGIN_HOSTS || "").split(",").filter(Boolean),
...lanHosts.map((hostname) => `${hostname}:${appPort}`)
]);
if (lanHosts.length > 0) {
console.log(`On a phone on the same Wi-Fi, open ${lanHosts.map((hostname) => `http://${hostname}:${appPort}`).join(" or ")}.`);
console.log("Run npm run auth:e2e:copy-code on this Mac and paste the code on the phone (Universal Clipboard).");
}
await spawnAndForward(
nextBin,
["dev", "-H", "0.0.0.0", "--port", String(appPort)],
localEnvironment({ POKE_NOTES_LOCAL_LOGIN_HOSTS: Array.from(loginHosts).join(",") })
);
}

async function copyCode() {
const pairingCode = readExistingE2eEnvironment().POKE_NOTES_LOCAL_LOGIN_CODE;
if (!pairingCode) {
throw new Error("Missing .env.e2e.local. Run npm run e2e:local:setup first.");
}
run("pbcopy", [], { capture: true, input: pairingCode });
console.log("Local E2E pairing code copied to the macOS clipboard; its value was not printed.");
}

async function saveAuth() {
if (!existsSync(envFile)) {
throw new Error("Missing .env.e2e.local. Run npm run e2e:local:setup first.");
}
const claude = process.argv.slice(3).includes("--account=claude");
await spawnAndForward(
process.execPath,
[
"scripts/save-local-auth-state.mjs",
"--base-url=http://localhost:3010",
"--state=.agent-browser/pokenotes-e2e-auth.json"
`--base-url=http://localhost:${appPort}`,
...(claude
? ["--account=claude", "--state=.agent-browser/pokenotes-e2e-claude-auth.json"]
: ["--state=.agent-browser/pokenotes-e2e-auth.json"])
],
localEnvironment({ POKENOTES_ENV_FILE: ".env.e2e.local" })
);
Expand Down
50 changes: 50 additions & 0 deletions scripts/local-network-hosts.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
// Hostnames a phone on the same Wi-Fi can use to reach this Mac's dev server.
// CommonJS so next.config.js can require it as well as the .mjs scripts.

const { execFileSync } = require("node:child_process");
const { networkInterfaces } = require("node:os");

function isPrivateIpv4(address) {
const octets = address.split(".").map(Number);
if (octets.length !== 4 || octets.some((octet) => !Number.isInteger(octet))) {
return false;
}

return (
octets[0] === 10 ||
(octets[0] === 172 && octets[1] >= 16 && octets[1] <= 31) ||
(octets[0] === 192 && octets[1] === 168) ||
(octets[0] === 169 && octets[1] === 254)
);
}

/** Private IPv4 addresses plus the macOS Bonjour name (`<LocalHostName>.local`), without ports. */
function localNetworkHostnames() {
const hosts = new Set();

for (const addresses of Object.values(networkInterfaces())) {
for (const address of addresses ?? []) {
if (address.family === "IPv4" && !address.internal && isPrivateIpv4(address.address)) {
hosts.add(address.address);
}
}
}

if (process.platform === "darwin") {
try {
const localHostName = execFileSync("scutil", ["--get", "LocalHostName"], {
encoding: "utf8",
stdio: ["ignore", "pipe", "ignore"]
}).trim();
if (localHostName) {
hosts.add(`${localHostName}.local`);
}
} catch {
// The private IP remains available when the Bonjour name cannot be read.
}
}

return Array.from(hosts);
}

module.exports = { localNetworkHostnames };
12 changes: 11 additions & 1 deletion scripts/save-local-auth-state.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,14 @@ const baseUrlParts = new URL(baseUrl);
const statePath = resolve(String(args.get("--state") || ".agent-browser/pokenotes-local-auth.json"));
const session = String(args.get("--session") || `pokenotes-local-auth-${Date.now()}`);
const pairingCode = String(process.env.POKE_NOTES_LOCAL_LOGIN_CODE || "");
const account = String(args.get("--account") || "");

if (account && account !== "claude") {
throw new Error(`Unknown local account "${account}". Use --account=claude or omit it.`);
}
if (account === "claude" && !process.env.POKE_NOTES_CLAUDE_LOGIN_EMAIL) {
throw new Error("Claude's local account is not configured. Run npm run e2e:local:reset first.");
}

if (!existsSync(agentBrowserBin)) {
throw new Error("agent-browser is not installed. Run npm install first.");
Expand All @@ -67,7 +75,9 @@ if (currentUrl.pathname === "/login") {
]);
runAgentBrowser([
"click",
'form[action="/auth/dev-login"] button[type="submit"]'
account
? `form[action="/auth/dev-login"] button[name="account"][value="${account}"]`
: 'form[action="/auth/dev-login"] button[type="submit"]:not([name])'
]);
}
runAgentBrowser([
Expand Down
Loading
Loading