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
21 changes: 15 additions & 6 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ shortlink/
│ │ │ │ ├── analytics.ts # Per-link and summary click analytics (D1 batch queries)
│ │ │ │ ├── admin.ts # Admin: user mgmt, link mgmt, settings
│ │ │ │ ├── redirect.ts # /:slug redirect + async click logging
│ │ │ │ └── setup.ts # /setup/:secret — HTTP-triggered DB migration (schema_v1)
│ │ │ │ └── setup.ts # POST /setup — HTTP-triggered DB migration (schema_v1 + schema_v2)
│ │ │ ├── middleware/
│ │ │ │ └── auth.ts # requireAuth and requireAdmin middleware (JWT verification)
│ │ │ └── lib/
Expand Down Expand Up @@ -161,7 +161,11 @@ Stored AES-256-GCM encrypted in D1. The encryption key (`TOTP_ENCRYPTION_KEY`) i
| `link:{slug}` | Short link cache | 21600s (6h) |
| `passkey_challenge:{id}` | WebAuthn challenge | 300s |
| `otp_rate:{email}` | Email OTP rate limit (also used by forgot-password) | 600s |
| `login_attempts:{email}` | Login brute-force rate limit | 900s |
| `login_attempts:{email}` | Login brute-force rate limit (email dimension) | 900s |
| `login_attempts_ip:{ip}` | Login brute-force rate limit (IP dimension) | 900s |
| `register_rate:{ip}` | Registration rate limit (IP) | 3600s |
| `forgot_pw_rate:{ip}` | Forgot-password rate limit (IP) | 3600s |
| `setup_rate:{ip}` | Setup/migration endpoint rate limit (IP) | 900s |
| `2fa_attempts:{jti}` | General 2FA attempt counter | 600s |
| `passkey_opts:{jti}` | Passkey options attempt counter | 600s |
| `totp_confirm:{userId}` | TOTP setup confirm attempt counter | 120s |
Expand Down Expand Up @@ -233,12 +237,14 @@ Email sender config and API keys are managed in the **admin UI settings**, not h
There are two migration paths:

**`wrangler d1 migrations apply` (local dev):**
One file in `apps/worker/migrations/`:
Two files in `apps/worker/migrations/`:
- `0001_init.sql` — canonical schema: all tables (users, passkeys, links, click_logs, verifications, settings, audit_logs, totp_used) + default settings rows
- `0002_token_version.sql` — adds `users.token_version` for session revocation

**HTTP setup route (production):**
`GET /setup/:secret` runs migrations embedded in `routes/setup.ts`. Currently one migration:
`POST /setup` with `X-Setup-Secret` header runs migrations embedded in `routes/setup.ts`. Two migrations:
- `schema_v1` — identical DDL as `0001_init.sql`, but parameterized by `TABLE_PREFIX` and tracked in `_schema_migrations` table
- `schema_v2` — adds `token_version` to `users` (mirrors `0002_token_version.sql`)

Re-visiting the setup URL is safe — already-applied migrations return `"skipped"`.

Expand All @@ -251,14 +257,17 @@ Re-visiting the setup URL is safe — already-applied migrations return `"skippe
- Passkey registration capped at 10 per user
- Forgot-password endpoint never reveals whether an email exists (always returns success)
- Password reset codes: max 3 wrong attempts per code; rate-limited 3 sends per 10 min per email
- Login brute-force limited to 10 attempts per 15-minute window per email (`login_attempts:{email}` KV)
- Login brute-force limited to 10 attempts per 15-minute window per email, plus 20 per IP (`login_attempts:{email}` + `login_attempts_ip:{ip}` KV)
- Registration and forgot-password additionally rate-limited per IP (`register_rate:{ip}`, `forgot_pw_rate:{ip}`)
- Setup/migration endpoint rate-limited per IP (`setup_rate:{ip}`); secret passed via header and compared in constant time
- `cf-connecting-ip` used for IP logging (cannot be forged); `x-forwarded-for` ignored
- User-Agent and Referer headers truncated before storage (512 and 2048 bytes respectively)
- `app_name` setting validated: 1–64 chars, no HTML-special or CR/LF characters
- LIKE queries escape `%`, `_`, `\` metacharacters
- `expiresAt` validated with `Number.isSafeInteger()` to reject NaN/Infinity
- SMTP settings (`smtp_host`, `smtp_user`, `smtp_pass`, `smtp_from`) are validated against CR/LF injection; `smtp_from` validated as a valid email address; `smtp_port` validated as integer 1–65535
- SMTP passwords are stored in plain text in D1 — for production deployments where this is a concern, use Resend with a Worker secret instead
- SMTP STARTTLS failure aborts the send (never falls back to plaintext); SMTP I/O and Resend fetch both carry 10s timeouts
- SMTP passwords are stored in plain text in D1 (but masked in audit logs and never returned by the settings API) — for production deployments where this is a concern, use Resend with a Worker secret instead

---

Expand Down
6 changes: 4 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -94,10 +94,12 @@ This will deploy the code to Cloudflare Workers.

### 6. Run database migrations

After deploying, visit this URL once in your browser (or with `curl`):
After deploying, trigger the migrations once via a `POST` request with the setup
secret in a header (it is no longer accepted in the URL):

```
https://your-worker.workers.dev/setup/<SETUP_SECRET>
curl -X POST https://your-worker.workers.dev/setup \
-H "X-Setup-Secret: <SETUP_SECRET>"
```

Response on success:
Expand Down
5 changes: 3 additions & 2 deletions README.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -97,10 +97,11 @@

### 6. 运行数据库迁移

部署后,在浏览器中访问以下 URL 一次(或使用 `curl`):
部署后,通过 `POST` 请求触发迁移一次,密钥放在请求头中(不再通过 URL 传递):

```
https://your-worker.workers.dev/setup/<SETUP_SECRET>
curl -X POST https://your-worker.workers.dev/setup \
-H "X-Setup-Secret: <SETUP_SECRET>"
```

成功响应:
Expand Down
25 changes: 24 additions & 1 deletion apps/web/src/api/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,11 +75,26 @@ async function request<T>(
// S3: In-flight dedup prevents multiple concurrent 401s from each triggering a refresh call.
// With refresh token rotation, only the first call succeeds; others would see a revoked
// token and force the user back to login unexpectedly.
// FE-S1: The dedup is additionally serialized across tabs via the Web Locks API, so
// sibling tabs refreshing from the same cookie wait for each other instead of
// rotating the refresh token out from under one another.
let refreshPromise: Promise<boolean> | null = null;

function withRefreshLock<T>(fn: () => Promise<T>): Promise<T> {
const locks = typeof navigator !== 'undefined' ? navigator.locks : undefined;
if (locks?.request) {
return locks.request(
'auth-refresh',
{ mode: 'exclusive' },
fn,
) as Promise<T>;
}
return fn();
}

async function tryRefresh(): Promise<boolean> {
if (refreshPromise) return refreshPromise;
refreshPromise = _doRefresh().finally(() => {
refreshPromise = withRefreshLock(_doRefresh).finally(() => {
refreshPromise = null;
});
return refreshPromise;
Expand All @@ -101,6 +116,14 @@ async function _doRefresh(): Promise<boolean> {
}
}

// Serialized silent refresh for the BroadcastChannel 'refresh' handler and the
// initial session restore — returns the new access token, or null when there is
// no valid session.
export async function refreshSession(): Promise<string | null> {
const ok = await tryRefresh();
return ok ? getAccessToken() : null;
}

// ─── Auth API ─────────────────────────────────────────────────────────────────

export interface User {
Expand Down
20 changes: 12 additions & 8 deletions apps/web/src/components/link-table-cells.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import {
copyToClipboard,
expiryLabel,
isExpired,
isSafeUrl,
} from '@/lib/utils';

export function LinkSlugCell({ slug }: { slug: string }) {
Expand All @@ -34,18 +35,21 @@ export function LinkSlugCell({ slug }: { slug: string }) {
}

export function LinkDestinationCell({ url }: { url: string }) {
// FE-S2: Only render the URL as a clickable link when its protocol is http/https.
return (
<td className="px-4 py-3 max-w-xs">
<div className="flex items-center gap-1 truncate">
<span className="truncate text-muted-foreground">{url}</span>
<a
href={url}
target="_blank"
rel="noopener noreferrer"
className="flex-shrink-0 text-muted-foreground hover:text-foreground"
>
<ExternalLink className="h-3 w-3" />
</a>
{isSafeUrl(url) && (
<a
href={url}
target="_blank"
rel="noopener noreferrer"
className="flex-shrink-0 text-muted-foreground hover:text-foreground"
>
<ExternalLink className="h-3 w-3" />
</a>
)}
</div>
</td>
);
Expand Down
52 changes: 28 additions & 24 deletions apps/web/src/contexts/AuthContext.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import {
import {
authApi,
type LoginResult,
refreshSession,
setAccessToken,
type User,
} from '../api/client.ts';
Expand All @@ -21,22 +22,26 @@ interface AuthContextType {
pendingMethods: string[];
login: (email: string, password: string) => Promise<LoginResult>;
logout: () => Promise<void>;
broadcastLogin: (accessToken: string) => void;
broadcastRefresh: () => void;
setPendingState: (token: string, methods: string[]) => void;
clearPendingState: () => void;
refreshUser: () => Promise<void>;
}

const AuthContext = createContext<AuthContextType | null>(null);

type ChannelMsg = { type: 'token'; accessToken: string } | { type: 'logout' };
// FE-S1: The channel carries only a signal, never a token. Any same-origin script
// (XSS, malicious extension) could listen on BroadcastChannel and steal a token
// sent through it, so tokens stay out — each tab fetches its own via the HttpOnly
// refresh cookie.
type ChannelMsg = { type: 'refresh' } | { type: 'logout' };

export function AuthProvider({ children }: { children: React.ReactNode }) {
const [user, setUser] = useState<User | null>(null);
const [isLoading, setIsLoading] = useState(true);
const [pendingToken, setPendingToken] = useState<string | null>(null);
const [pendingMethods, setPendingMethods] = useState<string[]>([]);
// H-1: BroadcastChannel for cross-tab token/logout coordination
// H-1: BroadcastChannel for cross-tab login/logout coordination (signal only)
const channelRef = useRef<BroadcastChannel | null>(null);

const refreshUser = useCallback(async () => {
Expand All @@ -58,12 +63,19 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {
channelRef.current = channel;

channel?.addEventListener('message', (e: MessageEvent<ChannelMsg>) => {
if (e.data?.type === 'token') {
// Another tab refreshed — adopt the new token and fetch the user
setAccessToken(e.data.accessToken);
authApi
.me()
.then((d) => setUser(d.user))
if (e.data?.type === 'refresh') {
// Another tab logged in — obtain our own token via the HttpOnly refresh
// cookie instead of receiving one over the channel. Serialized across
// tabs (Web Locks) so concurrent refreshes don't rotate each other out.
refreshSession()
.then((token) => {
if (!token) return;
setAccessToken(token);
return authApi.me();
})
.then((d) => {
if (d) setUser(d.user);
})
.catch(() => {});
} else if (e.data?.type === 'logout') {
// Another tab logged out — mirror the logout in this tab
Expand All @@ -74,13 +86,9 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {

const init = async () => {
try {
const data = await authApi.refresh();
setAccessToken(data.accessToken);
// Broadcast so sibling tabs avoid their own refresh round-trip
channel?.postMessage({
type: 'token',
accessToken: data.accessToken,
} satisfies ChannelMsg);
const token = await refreshSession();
if (!token) return;
setAccessToken(token);
await refreshUser();
} catch {
// No valid session — user needs to log in
Expand All @@ -104,8 +112,7 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {
// H4: refresh token is set as HttpOnly cookie by the server — no localStorage
setUser(result.user);
channelRef.current?.postMessage({
type: 'token',
accessToken: result.accessToken,
type: 'refresh',
} satisfies ChannelMsg);
}
return result;
Expand All @@ -125,11 +132,8 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {
channelRef.current?.postMessage({ type: 'logout' } satisfies ChannelMsg);
}, []);

const broadcastLogin = useCallback((accessToken: string) => {
channelRef.current?.postMessage({
type: 'token',
accessToken,
} satisfies ChannelMsg);
const broadcastRefresh = useCallback(() => {
channelRef.current?.postMessage({ type: 'refresh' } satisfies ChannelMsg);
}, []);

const setPendingState = useCallback((token: string, methods: string[]) => {
Expand All @@ -151,7 +155,7 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {
pendingMethods,
login,
logout,
broadcastLogin,
broadcastRefresh,
setPendingState,
clearPendingState,
refreshUser,
Expand Down
12 changes: 12 additions & 0 deletions apps/web/src/lib/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,18 @@ export function copyToClipboard(text: string): Promise<void> {
return navigator.clipboard.writeText(text);
}

// FE-S2: Validate that a URL is safe to render as a clickable <a href>. Only
// http/https are allowed — anything else (javascript:, data:, etc.) is rendered
// as plain text to prevent XSS if backend validation is ever bypassed.
export function isSafeUrl(url: string): boolean {
try {
const parsed = new URL(url);
return parsed.protocol === 'http:' || parsed.protocol === 'https:';
} catch {
return false;
}
}

export function buildShortUrl(slug: string): string {
return `${window.location.origin}/${slug}`;
}
Loading
Loading