# TIAR Webapp Baseline and Auth v1 Implementation Plan

> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.

**Goal:** Make `tiar-webapp` a runnable 1:1 copy of the old charging UI and migrate its register/login/current-user integration to the new v1 backend.

**Architecture:** Import the old UI source and configuration without Git metadata, dependencies, build output, or environment files. Preserve all browser routes, keep old v1.1 services as temporary fallback for non-Auth features, and route Auth through a server-only v1 client that owns tenant headers and HttpOnly tokens.

**Tech Stack:** Next.js 16 App Router, React 19, TypeScript 5, Tailwind CSS 4, Vitest, Node.js/npm.

**Spec:** `docs/superpowers/specs/2026-08-27-tiar-webapp-baseline-auth-v1-design.md`

## Global Constraints

- Preserve `tiar-webapp/.git`, `.gitignore`, `README.md`, `docs/`, and `local-documents/`.
- Never copy `.git`, `.next`, `node_modules`, `.env`, or `tsconfig.tsbuildinfo`.
- Preserve old browser routes and UI/UX; API differences stay in server adapters.
- Use `https://dev.api.tiar.ai` only for migrated v1 Auth requests.
- Use `https://api-dev.tiar.ai` temporarily for old v1.1 features that have not migrated.
- Never expose access/refresh tokens to browser JSON, logs, or snapshots.
- Do not commit changes unless the user explicitly requests a commit.

---

### Task 1: Import and run the old UI baseline

**Files:**
- Copy: `../tiar-charging-app/src/` to `src/`
- Copy: `../tiar-charging-app/public/` to `public/`
- Copy: `../tiar-charging-app/package.json` to `package.json`
- Copy: `../tiar-charging-app/package-lock.json` to `package-lock.json`
- Copy: `../tiar-charging-app/next.config.ts` to `next.config.ts`
- Copy: `../tiar-charging-app/postcss.config.mjs` to `postcss.config.mjs`
- Copy: `../tiar-charging-app/tsconfig.json` to `tsconfig.json`
- Copy: `../tiar-charging-app/eslint.config.mjs` to `eslint.config.mjs`
- Copy: `../tiar-charging-app/components.json` to `components.json`
- Copy: `../tiar-charging-app/.prettierrc` to `.prettierrc`
- Copy: `../tiar-charging-app/.prettierignore` to `.prettierignore`
- Generate: `.env.local` with target-specific non-secret dev values
- Create: `.env.example`

**Interfaces:**
- Consumes: old frontend repository at `../tiar-charging-app`.
- Produces: independently installable/runnable `tiar-webapp` baseline.

- [ ] **Step 1: Record repository safety baseline**

Run:

```bash
git status --short
test -d .git
test ! -e src
```

Expected: `.gitignore` and `docs/` are the only target changes; `.git` exists and `src` does not.

- [ ] **Step 2: Copy only approved baseline paths**

Use explicit source and destination paths. Do not use a repository-root recursive copy and do not overwrite `.gitignore`, `README.md`, or `docs/`.

- [ ] **Step 3: Verify excluded content was not copied**

Run:

```bash
test ! -e .env
test ! -e node_modules
test ! -e .next
test "$(git rev-parse --show-toplevel)" = "$PWD"
```

Expected: every check exits `0`.

- [ ] **Step 4: Create target-specific local environment configuration**

Create `.env.local` with:

```dotenv
BACKEND_USE_PROD=false
NEXT_PUBLIC_BACKEND_USE_PROD=false
BACKEND_BASE_URL_DEV=https://api-dev.tiar.ai
NEXT_PUBLIC_BACKEND_BASE_URL_DEV=https://api-dev.tiar.ai
ORGANIZATION_CODE=SANDBOX
BASE_DOMAIN=tiar.ai
TIAR_V1_BASE_URL=https://dev.api.tiar.ai
TIAR_V1_TENANT_HOST=parking-plus.dev.tiar.ai
TIAR_V1_APP_NAME=mobile_app
```

Create `.env.example` with the same non-secret keys and explanatory comments.

- [ ] **Step 5: Install dependencies from the copied lockfile**

Run: `npm ci`

Expected: dependencies install in `tiar-webapp/node_modules`; the old repository's `node_modules` is untouched.

- [ ] **Step 6: Run baseline static verification**

Run:

```bash
npm run lint
npm run build
```

Expected: both commands pass, or any inherited baseline failure is isolated and documented before Auth changes.

---

### Task 2: Add the v1 client with test-first configuration and error behavior

**Files:**
- Modify: `package.json`
- Modify: `package-lock.json`
- Create: `src/services/v1/config.ts`
- Create: `src/services/v1/client.ts`
- Test: `src/services/v1/config.test.ts`
- Test: `src/services/v1/client.test.ts`

**Interfaces:**
- Produces: `getV1Config(env?)`, `buildV1Headers(config, headers?)`, `requestV1(path, init, dependencies?)`, and `V1ApiError`.
- Consumes: server-only environment variables defined in Task 1.

- [ ] **Step 1: Install and configure Vitest**

Run: `npm install --save-dev vitest`

Add scripts:

```json
"test": "vitest run",
"test:watch": "vitest"
```

- [ ] **Step 2: Write failing config tests**

Test that `getV1Config` defaults to the approved dev URL/tenant/app name and trims trailing slashes. Test that `buildV1Headers` adds JSON content type, `X-Forwarded-Host`, and `X-App-Name` without accepting browser-provided tenant values.

- [ ] **Step 3: Run config tests and confirm RED**

Run: `npm test -- src/services/v1/config.test.ts`

Expected: FAIL because `config.ts` does not exist.

- [ ] **Step 4: Implement minimal v1 configuration**

Implement:

```ts
export type V1Config = {
  baseUrl: string;
  tenantHost: string;
  appName: string;
};

export function getV1Config(env: NodeJS.ProcessEnv = process.env): V1Config;
export function buildV1Headers(config: V1Config, headers?: HeadersInit): Headers;
```

- [ ] **Step 5: Run config tests and confirm GREEN**

Run: `npm test -- src/services/v1/config.test.ts`

Expected: PASS.

- [ ] **Step 6: Write failing client tests**

Use an injected in-memory `fetch` function. Assert URL construction, JSON parsing, network-error mapping, non-2xx status preservation, and that tokens are never logged.

- [ ] **Step 7: Run client tests and confirm RED**

Run: `npm test -- src/services/v1/client.test.ts`

Expected: FAIL because `client.ts` does not exist.

- [ ] **Step 8: Implement the minimal generic client**

Implement:

```ts
export class V1ApiError extends Error {
  constructor(
    message: string,
    public readonly status: number,
    public readonly payload?: unknown,
  );
}

export async function requestV1<T>(
  path: string,
  init?: RequestInit,
  dependencies?: { fetchImpl?: typeof fetch; config?: V1Config },
): Promise<T>;
```

- [ ] **Step 9: Run all v1 client tests**

Run: `npm test -- src/services/v1`

Expected: PASS.

---

### Task 3: Add the Auth v1 adapter using TDD

**Files:**
- Create: `src/services/v1/authAdapter.ts`
- Test: `src/services/v1/authAdapter.test.ts`

**Interfaces:**
- Consumes: `requestV1` from Task 2.
- Produces: `normalizeAuthEmail`, `checkEmailV1`, `signUpV1`, `loginV1`, `getCurrentUserV1`, and Auth response/token types.

- [ ] **Step 1: Write failing email and request-contract tests**

Assert that emails are trimmed/lowercased and that check-email, sign-up, and login call these exact paths:

```text
/v1/auth/check-email
/v1/auth/sign-up
/v1/auth/login
```

- [ ] **Step 2: Run tests and confirm RED**

Run: `npm test -- src/services/v1/authAdapter.test.ts`

Expected: FAIL because the adapter does not exist.

- [ ] **Step 3: Implement request methods**

Implement injected requester support so tests use real adapter behavior without network calls:

```ts
export type V1Requester = <T>(path: string, init?: RequestInit) => Promise<T>;
export function normalizeAuthEmail(email: string): string;
export function checkEmailV1(email: string, requester?: V1Requester): Promise<unknown>;
export function signUpV1(email: string, requester?: V1Requester): Promise<unknown>;
export function loginV1(email: string, password: string, requester?: V1Requester): Promise<V1LoginResponse>;
```

- [ ] **Step 4: Run request tests and confirm GREEN**

Run: `npm test -- src/services/v1/authAdapter.test.ts`

Expected: PASS.

- [ ] **Step 5: Add failing response-normalization tests**

Cover token shapes returned as `result.token.access_token`/`refresh_token` or direct result fields, sanitized user extraction, and missing-token behavior.

- [ ] **Step 6: Implement response normalization and current user**

Add:

```ts
export type AuthTokenPair = { accessToken: string; refreshToken: string };
export function extractTokenPair(response: V1LoginResponse): AuthTokenPair | null;
export function getCurrentUserV1(accessToken: string, requester?: V1Requester): Promise<unknown>;
```

- [ ] **Step 7: Run adapter tests and confirm GREEN**

Run: `npm test -- src/services/v1/authAdapter.test.ts`

Expected: PASS.

---

### Task 4: Wire old Auth UI routes to the new adapter

**Files:**
- Create: `src/app/api/auth/_shared/v1RouteLogic.ts`
- Test: `src/app/api/auth/_shared/v1RouteLogic.test.ts`
- Modify: `src/app/api/auth/check-email/route.ts`
- Modify: `src/app/api/auth/sign-up/route.ts`
- Modify: `src/app/api/auth/login-password/route.ts`
- Modify: `src/app/api/auth/me/route.ts`

**Interfaces:**
- Consumes: Auth adapter functions and existing cookie helpers.
- Produces: old browser-facing response contracts without exposing upstream tokens.

- [ ] **Step 1: Write failing route-logic tests**

Test pure route logic with injected adapter functions. Assert:

- missing email/password returns HTTP `400`;
- sign-up preserves upstream success/error status and message;
- login success returns sanitized user and token pair separately for server cookie writing;
- browser body never contains `access_token` or `refresh_token`;
- Auth upstream errors preserve their safe message/status.

- [ ] **Step 2: Run route-logic tests and confirm RED**

Run: `npm test -- src/app/api/auth/_shared/v1RouteLogic.test.ts`

Expected: FAIL because route logic does not exist.

- [ ] **Step 3: Implement pure route logic**

Create functions returning `{ status, body, tokens? }` for check-email, sign-up, and login. Keep token data outside `body` so only the Next route wrapper can write cookies.

- [ ] **Step 4: Run route-logic tests and confirm GREEN**

Run: `npm test -- src/app/api/auth/_shared/v1RouteLogic.test.ts`

Expected: PASS.

- [ ] **Step 5: Replace old upstream calls in route wrappers**

Keep existing browser route names. Call the new route logic, serialize `body`, and write any returned token pair with the existing HttpOnly cookie helper.

- [ ] **Step 6: Adapt current-user loading**

Read the access-token cookie server-side, call `GET /v1/user` with `Authorization: Bearer ...`, normalize the returned user, and return HTTP `401` while clearing cookies when authentication is invalid.

- [ ] **Step 7: Run Auth and static tests**

Run:

```bash
npm test
npm run lint
```

Expected: all tests pass; no new lint errors.

---

### Task 5: Run the UI and verify register/login behavior

**Files:**
- Modify if evidence requires: Auth route/service files from Tasks 2-4
- Update: `docs/migration/03-auth-api-comparison.md`

**Interfaces:**
- Consumes: runnable baseline and v1 Auth adapter.
- Produces: browser-verified Auth slice and updated migration evidence.

- [ ] **Step 1: Start the target app**

Run: `npm run dev`

Expected: app starts from `tiar-webapp` and redirects local root traffic to the configured Sandbox host.

- [ ] **Step 2: Smoke-test old Auth UI**

Open `/signin` and `/signup`. Confirm old branding/layout, Terms behavior, field validation, navigation links, loading states, and error UI render.

- [ ] **Step 3: Test registration through the UI**

Use a non-production email approved for testing. Confirm the browser calls only `/api/auth/sign-up`, receives the v1 result through the adapter, and routes to `/check-email` on success.

- [ ] **Step 4: Test login through the UI**

Use a verified new-backend test account. Confirm check-email and login pass through the adapter, tokens remain HttpOnly, and `/api/auth/me` loads the user.

- [ ] **Step 5: Run production verification**

Run:

```bash
npm test
npm run lint
npm run build
git diff --check
```

Expected: all commands pass.

- [ ] **Step 6: Update migration evidence**

Record the final new-domain headers, observed statuses, response shape without secrets, working UI routes, and any remaining Auth contract gaps in `docs/migration/03-auth-api-comparison.md`.
