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 .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ name: CI

on:
push:
branches: [main]
branches: [main, 'tds/**']
pull_request:
branches: [main]
workflow_dispatch:
Expand Down
8 changes: 6 additions & 2 deletions .github/workflows/deploy.yml
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,16 @@ concurrency:
jobs:
deploy:
# workflow_run: only after a successful CI run for a push to this repo's
# main (the `branches` filter alone also matches fork PRs from a branch
# named "main"). workflow_dispatch: only from main.
# main. The `branches: [main]` filter on the trigger already excludes other
# branches (including tds/**), and `head_branch == 'main'` below re-asserts
# it at the job level so a non-main CI run can never reach production.
# `head_repository` also blocks fork PRs whose branch happens to be "main".
# workflow_dispatch: only from main.
if: >-
(github.event_name == 'workflow_dispatch' && github.ref == 'refs/heads/main') ||
(github.event.workflow_run.conclusion == 'success' &&
github.event.workflow_run.event == 'push' &&
github.event.workflow_run.head_branch == 'main' &&
github.event.workflow_run.head_repository.full_name == github.repository)
runs-on: ubuntu-latest
environment:
Expand Down
5 changes: 4 additions & 1 deletion .github/workflows/tag.yml
Original file line number Diff line number Diff line change
Expand Up @@ -59,13 +59,16 @@ jobs:
const sha = stdout.trim();
core.info(`Checking CI status for main@${sha}`);
// Filter by workflow file (not the repo-wide list) so this very tag
// workflow run is not mistaken for CI, and only accept a push run.
// workflow run is not mistaken for CI, and only accept a push run
// on main. `branch: 'main'` pins it to main so a tds/** push run at
// the same commit can never satisfy the check.
const { data } = await github.rest.actions.listWorkflowRuns({
owner: context.repo.owner,
repo: context.repo.repo,
workflow_id: process.env.WORKFLOW_FILE,
head_sha: sha,
event: 'push',
branch: 'main',
});
const ciRun = data.workflow_runs.find(
(run) => run.status === 'completed' && run.conclusion === 'success',
Expand Down
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,10 @@ Navigate to your deployed URL and register — the first account is automaticall
```bash
# 1. Create apps/worker/.dev.vars
cat > apps/worker/.dev.vars << 'EOF'
APP_URL=http://localhost:8787
APP_NAME=ShortLink
RP_ID=localhost
APP_ORIGIN=http://localhost:5173
JWT_SECRET=dev-secret-at-least-32-characters-long
TOTP_ENCRYPTION_KEY=0000000000000000000000000000000000000000000000000000000000000000
SETUP_SECRET=local-setup-secret
Expand Down
4 changes: 4 additions & 0 deletions README.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,10 @@ curl -X POST https://your-worker.workers.dev/setup \
```bash
# 1. 创建 apps/worker/.dev.vars
cat > apps/worker/.dev.vars << 'EOF'
APP_URL=http://localhost:8787
APP_NAME=ShortLink
RP_ID=localhost
APP_ORIGIN=http://localhost:5173
JWT_SECRET=dev-secret-at-least-32-characters-long
TOTP_ENCRYPTION_KEY=0000000000000000000000000000000000000000000000000000000000000000
SETUP_SECRET=local-setup-secret
Expand Down
2 changes: 1 addition & 1 deletion apps/web/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
"dev": "vite",
"build": "tsc --noEmit && vite build",
"typecheck": "tsc --noEmit",
"test": "node --test src/api/client.test.ts src/lib/utils.test.ts",
"test": "node --test src/api/client.test.ts src/lib/utils.test.ts src/lib/apiErrorCodes.test.ts",
"preview": "vite preview"
},
"dependencies": {
Expand Down
9 changes: 6 additions & 3 deletions apps/web/src/api/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,18 +44,21 @@ const BASE = '/api';

interface ApiError {
error: string;
code?: string;
}

// FE-R4: react-query only retries transport failures and server errors. A 4xx
// is the server's final answer (validation, auth, not found); retrying it just
// delays the error the user needs to see.
export class ApiRequestError extends Error {
readonly status: number;
readonly code?: string;

constructor(message: string, status: number) {
constructor(message: string, status: number, code?: string) {
super(message);
this.name = 'ApiRequestError';
this.status = status;
this.code = code;
}
}

Expand Down Expand Up @@ -136,7 +139,7 @@ async function request<T>(
const err = (await retryRes
.json()
.catch(() => ({ error: 'Request failed' }))) as ApiError;
throw new ApiRequestError(err.error, retryRes.status);
throw new ApiRequestError(err.error, retryRes.status, err.code);
}
return retryRes.json() as Promise<T>;
}
Expand All @@ -155,7 +158,7 @@ async function request<T>(
const err = (await res
.json()
.catch(() => ({ error: 'Request failed' }))) as ApiError;
throw new ApiRequestError(err.error, res.status);
throw new ApiRequestError(err.error, res.status, err.code);
}

if (res.status === 204) return undefined as T;
Expand Down
5 changes: 5 additions & 0 deletions apps/web/src/i18n/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,11 @@ type DeepKeys<T, P extends string = ''> = {

export type TranslationKey = DeepKeys<Translations>;

export type TFunction = (
key: TranslationKey,
params?: Record<string, string | number>,
) => string;

function resolve(obj: unknown, path: string): string {
const parts = path.split('.');
let curr = obj;
Expand Down
47 changes: 47 additions & 0 deletions apps/web/src/i18n/locales/en.ts
Original file line number Diff line number Diff line change
Expand Up @@ -261,6 +261,53 @@ export const en = {
appNameUpdated: 'App name updated',
emailSettingsSaved: 'Email settings saved',
},
errors: {
emailOrUsernameTaken: 'This email or username is already taken.',
invalidCredentials: 'Incorrect email or password.',
invalidEmail: 'Please enter a valid email address.',
invalidUsername:
'Username must be 3–32 characters using letters, numbers, dashes, or underscores.',
passwordTooShort: 'Password must be at least 8 characters.',
passwordTooLong: 'Password is too long.',
registrationDisabled: 'Registration is currently disabled.',
tooManyRequests: 'Too many requests. Please try again later.',
tooManyLoginAttempts: 'Too many login attempts. Please try again later.',
tooManyAttempts: 'Too many attempts. Please try again later.',
invalidCode: 'Invalid or incorrect code.',
currentPasswordIncorrect: 'Current password is incorrect.',
totpAlreadyEnabled: 'TOTP is already enabled.',
totpNotConfigured: 'TOTP is not configured for this account.',
accountDisabled: 'This account is disabled.',
codeAlreadyUsed: 'This code was already used. Please use a new one.',
emailSendFailed: 'Failed to send the email. Please try again.',
invalidOrExpiredPendingToken:
'Your sign-in session has expired. Please sign in again.',
invalidOrExpiredChallenge:
'Invalid or expired challenge. Please try again.',
passkeyVerificationFailed: 'Passkey verification failed.',
passkeyNotFound: 'Passkey not found.',
noValidCode: 'No valid code found. Please request a new one.',
emailOtpNotEnabled: 'Email OTP is not enabled for this account.',
invalidOrExpiredVerification: 'Invalid or expired verification.',
invalidOrExpiredCode: 'Invalid or expired code.',
tooManyPasskeys: 'Maximum of 10 passkeys allowed per account.',
passkeyNameTooLong: 'Passkey name must be 64 characters or fewer.',
serviceUnavailable: 'Service temporarily unavailable. Please try again.',
invalidUrl: 'Please enter a valid URL.',
onlyHttpHttpsAllowed: 'Only http and https URLs are allowed.',
invalidSlug:
'Invalid slug. Use 1–50 letters, numbers, dashes, or underscores.',
slugReserved: 'This slug is reserved.',
slugTaken: 'This slug is already taken.',
destinationUrlRequired: 'Please enter a destination URL.',
destinationUrlTooLong: 'Destination URL must be 2048 characters or fewer.',
titleTooLong: 'Title must be 255 characters or fewer.',
linkNotFound: 'Link not found.',
expiresAtInPast: 'Expiry must be in the future.',
failedToCreateLink: 'Failed to create the link.',
notFound: 'Not found.',
internalServerError: 'Internal server error.',
},
} as const;

type DeepString<T> = {
Expand Down
44 changes: 44 additions & 0 deletions apps/web/src/i18n/locales/zh-CN.ts
Original file line number Diff line number Diff line change
Expand Up @@ -251,4 +251,48 @@ export const zhCN: Translations = {
appNameUpdated: '应用名称已更新',
emailSettingsSaved: '邮件设置已保存',
},
errors: {
emailOrUsernameTaken: '该邮箱或用户名已被占用。',
invalidCredentials: '邮箱或密码不正确。',
invalidEmail: '请输入有效的邮箱地址。',
invalidUsername:
'用户名需为 3–32 个字符,可使用字母、数字、短横线或下划线。',
passwordTooShort: '密码至少需要 8 个字符。',
passwordTooLong: '密码过长。',
registrationDisabled: '当前已关闭注册。',
tooManyRequests: '请求过于频繁,请稍后再试。',
tooManyLoginAttempts: '登录尝试次数过多,请稍后再试。',
tooManyAttempts: '尝试次数过多,请稍后再试。',
invalidCode: '验证码无效或错误。',
currentPasswordIncorrect: '当前密码不正确。',
totpAlreadyEnabled: 'TOTP 已启用。',
totpNotConfigured: '该账户未配置 TOTP。',
accountDisabled: '该账户已被禁用。',
codeAlreadyUsed: '该验证码已被使用,请使用新的验证码。',
emailSendFailed: '邮件发送失败,请重试。',
invalidOrExpiredPendingToken: '登录会话已过期,请重新登录。',
invalidOrExpiredChallenge: '验证请求无效或已过期,请重试。',
passkeyVerificationFailed: '通行密钥验证失败。',
passkeyNotFound: '未找到通行密钥。',
noValidCode: '未找到有效验证码,请重新获取。',
emailOtpNotEnabled: '该账户未启用邮件 OTP。',
invalidOrExpiredVerification: '验证无效或已过期。',
invalidOrExpiredCode: '验证码无效或已过期。',
tooManyPasskeys: '每个账户最多 10 个通行密钥。',
passkeyNameTooLong: '通行密钥名称不能超过 64 个字符。',
serviceUnavailable: '服务暂时不可用,请稍后再试。',
invalidUrl: '请输入有效的 URL。',
onlyHttpHttpsAllowed: '仅支持 http 和 https 链接。',
invalidSlug: '别名无效,请使用 1–50 个字母、数字、短横线或下划线。',
slugReserved: '该别名为保留字。',
slugTaken: '该别名已被占用。',
destinationUrlRequired: '请输入目标 URL。',
destinationUrlTooLong: '目标 URL 不能超过 2048 个字符。',
titleTooLong: '标题不能超过 255 个字符。',
linkNotFound: '链接不存在。',
expiresAtInPast: '过期时间必须在将来。',
failedToCreateLink: '创建链接失败。',
notFound: '未找到。',
internalServerError: '服务器内部错误。',
},
};
61 changes: 61 additions & 0 deletions apps/web/src/lib/apiErrorCodes.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import assert from 'node:assert/strict';
import { describe, test } from 'node:test';
import { en } from '../i18n/locales/en.ts';
import { zhCN } from '../i18n/locales/zh-CN.ts';
import { API_ERROR_CODES } from './apiErrorCodes.ts';

// Verifies every backend error code the frontend knows maps to a real,
// non-empty string in both locales, so the "backend error → localized toast"
// path can never silently fall back to English for a known code.

function resolve(obj: unknown, path: string): unknown {
let curr = obj;
for (const p of path.split('.')) {
if (curr == null || typeof curr !== 'object') return undefined;
curr = (curr as Record<string, unknown>)[p];
}
return curr;
}

describe('API_ERROR_CODES', () => {
test('every code maps to a non-empty string in both locales', () => {
for (const [code, key] of Object.entries(API_ERROR_CODES)) {
const enValue = resolve(en, key);
const zhValue = resolve(zhCN, key);
assert.equal(
typeof enValue,
'string',
`${code} → ${key} must resolve to a string in en`,
);
assert.equal(
typeof zhValue,
'string',
`${code} → ${key} must resolve to a string in zh-CN`,
);
assert.ok((enValue as string).length > 0, `${key} (en) is empty`);
assert.ok((zhValue as string).length > 0, `${key} (zh-CN) is empty`);
}
});

test('EMAIL_OR_USERNAME_TAKEN localizes in both languages', () => {
assert.equal(
resolve(en, 'errors.emailOrUsernameTaken'),
'This email or username is already taken.',
);
assert.equal(
resolve(zhCN, 'errors.emailOrUsernameTaken'),
'该邮箱或用户名已被占用。',
);
});

test('INVALID_CREDENTIALS localizes in both languages', () => {
assert.equal(
resolve(en, 'errors.invalidCredentials'),
'Incorrect email or password.',
);
assert.equal(
resolve(zhCN, 'errors.invalidCredentials'),
'邮箱或密码不正确。',
);
});
});
49 changes: 49 additions & 0 deletions apps/web/src/lib/apiErrorCodes.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
// Maps backend error codes to i18n dot-path keys (defined in
// i18n/locales/*.ts). Kept as plain data (no React, no path aliases) so the
// mapping can be unit-tested and cross-checked against both locales.
export const API_ERROR_CODES: Record<string, string> = {
EMAIL_OR_USERNAME_TAKEN: 'errors.emailOrUsernameTaken',
INVALID_CREDENTIALS: 'errors.invalidCredentials',
INVALID_EMAIL: 'errors.invalidEmail',
INVALID_USERNAME: 'errors.invalidUsername',
PASSWORD_TOO_SHORT: 'errors.passwordTooShort',
PASSWORD_TOO_LONG: 'errors.passwordTooLong',
REGISTRATION_DISABLED: 'errors.registrationDisabled',
TOO_MANY_REQUESTS: 'errors.tooManyRequests',
TOO_MANY_LOGIN_ATTEMPTS: 'errors.tooManyLoginAttempts',
TOO_MANY_ATTEMPTS: 'errors.tooManyAttempts',
TOO_MANY_OTP_REQUESTS: 'errors.tooManyRequests',
INVALID_CODE: 'errors.invalidCode',
CURRENT_PASSWORD_INCORRECT: 'errors.currentPasswordIncorrect',
TOTP_ALREADY_ENABLED: 'errors.totpAlreadyEnabled',
TOTP_NOT_CONFIGURED: 'errors.totpNotConfigured',
ACCOUNT_DISABLED: 'errors.accountDisabled',
CODE_ALREADY_USED: 'errors.codeAlreadyUsed',
EMAIL_SEND_FAILED: 'errors.emailSendFailed',
INVALID_OR_EXPIRED_PENDING_TOKEN: 'errors.invalidOrExpiredPendingToken',
INVALID_OR_EXPIRED_CHALLENGE: 'errors.invalidOrExpiredChallenge',
PASSKEY_VERIFICATION_FAILED: 'errors.passkeyVerificationFailed',
PASSKEY_NOT_FOUND: 'errors.passkeyNotFound',
NO_VALID_VERIFICATION_CODE: 'errors.noValidCode',
NO_VALID_OTP: 'errors.noValidCode',
EMAIL_OTP_NOT_ENABLED: 'errors.emailOtpNotEnabled',
INVALID_OR_EXPIRED_VERIFICATION: 'errors.invalidOrExpiredVerification',
INVALID_OR_EXPIRED_VERIFICATION_CODE: 'errors.invalidOrExpiredVerification',
INVALID_OR_EXPIRED_CODE: 'errors.invalidOrExpiredCode',
TOO_MANY_PASSKEYS: 'errors.tooManyPasskeys',
PASSKEY_NAME_TOO_LONG: 'errors.passkeyNameTooLong',
SERVICE_UNAVAILABLE: 'errors.serviceUnavailable',
INVALID_URL: 'errors.invalidUrl',
ONLY_HTTP_HTTPS_ALLOWED: 'errors.onlyHttpHttpsAllowed',
INVALID_SLUG: 'errors.invalidSlug',
SLUG_RESERVED: 'errors.slugReserved',
SLUG_TAKEN: 'errors.slugTaken',
DESTINATION_URL_REQUIRED: 'errors.destinationUrlRequired',
DESTINATION_URL_TOO_LONG: 'errors.destinationUrlTooLong',
TITLE_TOO_LONG: 'errors.titleTooLong',
LINK_NOT_FOUND: 'errors.linkNotFound',
EXPIRES_AT_IN_PAST: 'errors.expiresAtInPast',
FAILED_TO_CREATE_LINK: 'errors.failedToCreateLink',
NOT_FOUND: 'errors.notFound',
INTERNAL_SERVER_ERROR: 'errors.internalServerError',
};
35 changes: 29 additions & 6 deletions apps/web/src/lib/toast.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,35 @@
import { toast } from 'sonner';
import { isSessionExpiredError } from '@/api/client';
import { ApiRequestError, isSessionExpiredError } from '@/api/client';
import type { TFunction, TranslationKey } from '@/i18n';
import { API_ERROR_CODES } from './apiErrorCodes';

// Resolve the message to show for an API error: a localized string when the
// error carries a known code, otherwise the backend's original `error` text, or
// the caller's `fallback` when neither is available. Returns null for a
// session-expired error so callers stay quiet (AuthProvider shows one toast).
export function resolveApiError(
error: unknown,
t: TFunction,
fallback: string,
): string | null {
if (isSessionExpiredError(error)) return null;
const code = error instanceof ApiRequestError ? error.code : undefined;
if (code) {
const key = API_ERROR_CODES[code] as TranslationKey | undefined;
if (key) return t(key);
}
return error instanceof Error && error.message ? error.message : fallback;
}

// #6: an expired session fails every in-flight request at once. AuthProvider
// shows a single "Session expired" toast, so per-request error toasts must stay
// quiet — otherwise the user sees the same message once per request.
export function toastApiError(error: unknown, fallback: string): void {
if (isSessionExpiredError(error)) return;
toast.error(
error instanceof Error && error.message ? error.message : fallback,
);
export function toastApiError(
error: unknown,
fallback: string,
t: TFunction,
): void {
const message = resolveApiError(error, t, fallback);
if (message === null) return;
toast.error(message);
}
2 changes: 1 addition & 1 deletion apps/web/src/pages/admin/AdminLinksPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ export default function AdminLinksPage() {
toast.success(t('toast.linkDeleted'));
setDeleteId(null);
},
onError: (err) => toastApiError(err, t('toast.deleteLinkFailed')),
onError: (err) => toastApiError(err, t('toast.deleteLinkFailed'), t),
});

return (
Expand Down
Loading
Loading