diff --git a/apps/bear/src/env/env.client.ts b/apps/bear/src/env/env.client.ts index 67ec37c..1ac6b51 100644 --- a/apps/bear/src/env/env.client.ts +++ b/apps/bear/src/env/env.client.ts @@ -1,14 +1,24 @@ import { createClientEnv } from '@lumina/libs/env'; import * as v from 'valibot'; +import { isOrigin } from './is-origin'; + const required = v.pipe(v.string(), v.nonEmpty()); const url = v.pipe(v.string(), v.url()); +/** Scheme and host only: request paths and media URLs are joined to it, so `https://api.lumina.ir/` would give `//v1`. */ +const origin = v.pipe( + url, + v.check( + isOrigin, + 'Must be an origin such as https://api.lumina.ir, with no path or trailing slash.', + ), +); /** Public variables, inlined into the browser bundle. Next.js inlines only literal reads. */ export const clientEnv = createClientEnv({ prefix: 'NEXT_PUBLIC_', schema: { - NEXT_PUBLIC_API_ORIGIN: url, + NEXT_PUBLIC_API_ORIGIN: origin, NEXT_PUBLIC_SITE_URL: url, NEXT_PUBLIC_BALE_HANDLE: required, NEXT_PUBLIC_TELEGRAM_HANDLE: required, diff --git a/apps/bear/src/env/env.server.ts b/apps/bear/src/env/env.server.ts index 1a488a1..f17378e 100644 --- a/apps/bear/src/env/env.server.ts +++ b/apps/bear/src/env/env.server.ts @@ -3,10 +3,20 @@ import 'server-only'; import { createServerEnv } from '@lumina/libs/env/server'; import * as v from 'valibot'; +import { isOrigin } from './is-origin'; + /** Server variables; only server code imports them, through `env/server`. */ export const serverEnv = createServerEnv({ schema: { - API_INTERNAL_ORIGIN: v.pipe(v.string(), v.url()), + // Scheme and host only, as NEXT_PUBLIC_API_ORIGIN: request paths are joined to it. + API_INTERNAL_ORIGIN: v.pipe( + v.string(), + v.url(), + v.check( + isOrigin, + 'Must be an origin such as http://gateway:3000, with no path or trailing slash.', + ), + ), }, runtimeEnv: process.env, skipValidation: process.env.SKIP_ENV_VALIDATION === 'true', diff --git a/apps/bear/src/env/is-origin.ts b/apps/bear/src/env/is-origin.ts new file mode 100644 index 0000000..32ec9ce --- /dev/null +++ b/apps/bear/src/env/is-origin.ts @@ -0,0 +1,8 @@ +/** `https://api.lumina.ir`, not `https://api.lumina.ir/` or `https://api.lumina.ir/v1`. */ +export function isOrigin(value: string): boolean { + try { + return new URL(value).origin === value; + } catch { + return false; + } +} diff --git a/apps/bull/src/env/env.client.ts b/apps/bull/src/env/env.client.ts index 67ec37c..1ac6b51 100644 --- a/apps/bull/src/env/env.client.ts +++ b/apps/bull/src/env/env.client.ts @@ -1,14 +1,24 @@ import { createClientEnv } from '@lumina/libs/env'; import * as v from 'valibot'; +import { isOrigin } from './is-origin'; + const required = v.pipe(v.string(), v.nonEmpty()); const url = v.pipe(v.string(), v.url()); +/** Scheme and host only: request paths and media URLs are joined to it, so `https://api.lumina.ir/` would give `//v1`. */ +const origin = v.pipe( + url, + v.check( + isOrigin, + 'Must be an origin such as https://api.lumina.ir, with no path or trailing slash.', + ), +); /** Public variables, inlined into the browser bundle. Next.js inlines only literal reads. */ export const clientEnv = createClientEnv({ prefix: 'NEXT_PUBLIC_', schema: { - NEXT_PUBLIC_API_ORIGIN: url, + NEXT_PUBLIC_API_ORIGIN: origin, NEXT_PUBLIC_SITE_URL: url, NEXT_PUBLIC_BALE_HANDLE: required, NEXT_PUBLIC_TELEGRAM_HANDLE: required, diff --git a/apps/bull/src/env/env.server.ts b/apps/bull/src/env/env.server.ts index 1a488a1..f17378e 100644 --- a/apps/bull/src/env/env.server.ts +++ b/apps/bull/src/env/env.server.ts @@ -3,10 +3,20 @@ import 'server-only'; import { createServerEnv } from '@lumina/libs/env/server'; import * as v from 'valibot'; +import { isOrigin } from './is-origin'; + /** Server variables; only server code imports them, through `env/server`. */ export const serverEnv = createServerEnv({ schema: { - API_INTERNAL_ORIGIN: v.pipe(v.string(), v.url()), + // Scheme and host only, as NEXT_PUBLIC_API_ORIGIN: request paths are joined to it. + API_INTERNAL_ORIGIN: v.pipe( + v.string(), + v.url(), + v.check( + isOrigin, + 'Must be an origin such as http://gateway:3000, with no path or trailing slash.', + ), + ), }, runtimeEnv: process.env, skipValidation: process.env.SKIP_ENV_VALIDATION === 'true', diff --git a/apps/bull/src/env/is-origin.ts b/apps/bull/src/env/is-origin.ts new file mode 100644 index 0000000..32ec9ce --- /dev/null +++ b/apps/bull/src/env/is-origin.ts @@ -0,0 +1,8 @@ +/** `https://api.lumina.ir`, not `https://api.lumina.ir/` or `https://api.lumina.ir/v1`. */ +export function isOrigin(value: string): boolean { + try { + return new URL(value).origin === value; + } catch { + return false; + } +} diff --git a/packages/libs/src/http/any-signal.ts b/packages/libs/src/http/any-signal.ts new file mode 100644 index 0000000..71b5d9d --- /dev/null +++ b/packages/libs/src/http/any-signal.ts @@ -0,0 +1,27 @@ +const noop = () => undefined; + +/** + * One signal that aborts when any of `signals` does, with that signal's reason. Uses + * `AbortSignal.any` where it exists; Safari < 17.4, Chrome < 116 and Firefox < 124 lack it, so + * there a controller listens to each source. Call `release` once the request settles: it drops + * those listeners, which would otherwise pile up on long-lived signals such as the abort-all one. + */ +export function anySignal( + signals: AbortSignal[], +): [signal: AbortSignal, release: () => void] { + if (typeof AbortSignal.any === 'function') + return [AbortSignal.any(signals), noop]; + const controller = new AbortController(); + const listeners = new AbortController(); + for (const source of signals) { + if (source.aborted) { + controller.abort(source.reason); + break; + } + source.addEventListener('abort', () => controller.abort(source.reason), { + once: true, + signal: listeners.signal, + }); + } + return [controller.signal, () => listeners.abort()]; +} diff --git a/packages/libs/src/http/http-client.ts b/packages/libs/src/http/http-client.ts index 344cb53..f1a6bc8 100644 --- a/packages/libs/src/http/http-client.ts +++ b/packages/libs/src/http/http-client.ts @@ -1,3 +1,4 @@ +import { anySignal } from './any-signal'; import { buildUrl, isAbsoluteUrl, @@ -312,7 +313,7 @@ export class HttpClient { url, requestId: createRequestId(), }; - const signal = AbortSignal.any([ + const [signal, releaseSignal] = anySignal([ ...(options.signal ? [options.signal] : []), ...this.abortSignals(), ]); @@ -332,6 +333,8 @@ export class HttpClient { toHttpError(thrown, context, signal), context, ); + } finally { + releaseSignal(); } try { for (const [onSuccess] of this.responseChain()) { @@ -421,9 +424,10 @@ export class HttpClient { attempt.timeout === false ? undefined : AbortSignal.timeout(attempt.timeout); - const signal = timeoutSignal - ? AbortSignal.any([attempt.signal, timeoutSignal]) - : attempt.signal; + // Both sources live no longer than this request, so their listeners need no release. + const [signal] = timeoutSignal + ? anySignal([attempt.signal, timeoutSignal]) + : [attempt.signal]; // Which signal fired decides the code, never the message. const failure = (cause: unknown) => createHttpError( diff --git a/packages/libs/src/http/http-error.ts b/packages/libs/src/http/http-error.ts index 42664d8..724ff23 100644 --- a/packages/libs/src/http/http-error.ts +++ b/packages/libs/src/http/http-error.ts @@ -147,7 +147,10 @@ function asString(value: unknown): string | undefined { return typeof value === 'string' ? value : undefined; } -function toFieldErrors(value: unknown): Record | undefined { +// { field: ['first message', …] } → { field: 'first message' }; for app error-body mappers too. +export function toFieldErrors( + value: unknown, +): Record | undefined { if (!isRecord(value)) return undefined; const entries = Object.entries(value).flatMap(([field, message]) => { const text: unknown = Array.isArray(message) ? message[0] : message; diff --git a/packages/libs/src/http/index.ts b/packages/libs/src/http/index.ts index b5f73da..86a7ea1 100644 --- a/packages/libs/src/http/index.ts +++ b/packages/libs/src/http/index.ts @@ -1,7 +1,7 @@ export { HTTP_ERROR_CODES } from './constants'; export { HttpClient } from './http-client'; export { createHttpClient, http } from './http'; -export { HttpError, isHttpError } from './http-error'; +export { HttpError, isHttpError, toFieldErrors } from './http-error'; export type { DownloadOptions, DownloadResult, diff --git a/packages/libs/src/http/retry.ts b/packages/libs/src/http/retry.ts index 37bb1b6..7fdb9e8 100644 --- a/packages/libs/src/http/retry.ts +++ b/packages/libs/src/http/retry.ts @@ -13,6 +13,12 @@ export function shouldRetry( if (attempt >= retry.attempts) return false; if (!optIn && !retry.methods.includes(method)) return false; if (error.code === 'ABORTED') return false; + // The server asked for a longer wait than a retry may take: retrying sooner only hits it again. + if ( + error.retryAfter !== undefined && + error.retryAfter * 1000 > retry.maxDelay + ) + return false; if (error.code === 'TIMEOUT') return retry.networkErrors && IDEMPOTENT_METHODS.includes(method); if (error.code === 'NETWORK_ERROR') return retry.networkErrors; @@ -26,14 +32,14 @@ export function shouldRetry( return retry.statuses.includes(error.status); } -// Retry-After wins when present; otherwise exponential backoff with full jitter. +// Retry-After wins when present (shouldRetry already refused one past maxDelay); otherwise +// exponential backoff with full jitter. export function getRetryDelay( error: HttpError, retry: RetryConfig, attempt: number, ): number { - if (error.retryAfter !== undefined) - return Math.min(retry.maxDelay, error.retryAfter * 1000); + if (error.retryAfter !== undefined) return error.retryAfter * 1000; return ( Math.random() * Math.min(retry.maxDelay, retry.baseDelay * 2 ** attempt) ); diff --git a/packages/libs/src/index.ts b/packages/libs/src/index.ts index 505d3d0..4297d99 100644 --- a/packages/libs/src/index.ts +++ b/packages/libs/src/index.ts @@ -44,6 +44,7 @@ export { createHttpClient, http, isHttpError, + toFieldErrors, } from './http'; export type { DownloadOptions, diff --git a/platforms/market/src/app/app-shell/hooks/use-session.ts b/platforms/market/src/app/app-shell/hooks/use-session.ts index 61065b2..b936c01 100644 --- a/platforms/market/src/app/app-shell/hooks/use-session.ts +++ b/platforms/market/src/app/app-shell/hooks/use-session.ts @@ -8,17 +8,29 @@ import { useAuthStore } from '../../../stores/auth'; /** * The browser learns who the viewer is once per page load; auth-dependent parts wait in their - * skeleton until then. When the session ends (sign-out, or a refresh that failed), the store goes - * back to guest and every cached query is dropped: it belonged to the old account. + * skeleton until then. A read that failed offline or on a gateway error leaves the viewer unknown, + * so it runs again when the connection comes back. When the session ends (sign-out, or a refresh + * that failed), the store goes back to guest and every cached query is dropped: it belonged to the + * old account. */ export function useSession(queryClient: QueryClient): void { useEffect(() => { - restoreSession().catch((error: unknown) => - handleError(error, { where: 'app', name: 'restore-session' }), - ); - return eventEmitter.on(AUTH_EVENTS.logout, () => { + const restore = () => + restoreSession().catch((error: unknown) => + handleError(error, { where: 'app', name: 'restore-session' }), + ); + const restoreIfUnknown = () => { + if (useAuthStore.getState().status === 'unknown') void restore(); + }; + void restore(); + window.addEventListener('online', restoreIfUnknown); + const offLogout = eventEmitter.on(AUTH_EVENTS.logout, () => { useAuthStore.getState().clearSession(); queryClient.clear(); }); + return () => { + window.removeEventListener('online', restoreIfUnknown); + offLogout(); + }; }, [queryClient]); } diff --git a/platforms/market/src/app/http/map-error-body.ts b/platforms/market/src/app/http/map-error-body.ts index 5ae43ee..10f31bc 100644 --- a/platforms/market/src/app/http/map-error-body.ts +++ b/platforms/market/src/app/http/map-error-body.ts @@ -1,3 +1,4 @@ +import { toFieldErrors } from '@lumina/libs/http'; import type { HttpErrorShape } from '@lumina/libs/http'; import type { ApiErrorEnvelope } from './types'; @@ -6,28 +7,18 @@ function isRecord(value: unknown): value is Record { return typeof value === 'object' && value !== null && !Array.isArray(value); } -/** `{ field: ['first message', …] }` → `{ field: 'first message' }`. */ -function toFieldErrors( - value: Record, -): Record | undefined { - const entries = Object.entries(value).flatMap(([field, messages]) => { - const message: unknown = Array.isArray(messages) ? messages[0] : messages; - return typeof message === 'string' ? [[field, message] as const] : []; - }); - return entries.length > 0 ? Object.fromEntries(entries) : undefined; -} - /** * Adapts the gateway's error contract to `HttpError`. Two shapes arrive: * - the envelope `{ statusCode, error, message, details }`, where `message` is the server's text - * (already translated), a list, or a field map; + * (already translated), a list, or a field map. A body with `error` but no `statusCode` (from a + * proxy or another service) is read as an envelope too, so its `message` stays a message; * - a bare field map `{ phone_number: ['…'] }` from DTO validation. * Field names stay the server's; each repository's mappers rename them to its `*Args` names. * `details` (a changed price, a frozen unfollow) passes through for the action that handles it. */ export function mapApiErrorBody(body: unknown): Partial { if (!isRecord(body)) return {}; - if (typeof body.statusCode !== 'number') { + if (typeof body.statusCode !== 'number' && typeof body.error !== 'string') { return { fieldErrors: toFieldErrors(body) }; } const { message, details } = body as ApiErrorEnvelope; @@ -38,7 +29,7 @@ export function mapApiErrorBody(body: unknown): Partial { : typeof message === 'string' ? message : undefined, - fieldErrors: isRecord(message) ? toFieldErrors(message) : undefined, + fieldErrors: toFieldErrors(message), retryAfter: typeof retryAfter === 'number' ? retryAfter : undefined, details: isRecord(details) ? details : undefined, }; diff --git a/platforms/market/src/app/navigation/return-path.ts b/platforms/market/src/app/navigation/return-path.ts index 88caec3..59ab3f8 100644 --- a/platforms/market/src/app/navigation/return-path.ts +++ b/platforms/market/src/app/navigation/return-path.ts @@ -1,17 +1,21 @@ import { ROUTES } from './navigation'; +// Never fetched: only resolves a path to see which origin the browser would leave for. +const PROBE_ORIGIN = 'https://return-path.invalid'; + /** * A `?redirect=` value is only followed when it is a path on this site: `/dashboard`, never * `https://evil.example` or `//evil.example`, so login can't be turned into an open redirect. + * The value is resolved the way the browser would resolve it: the URL parser drops tabs and line + * breaks and reads `\` as `/`, so `/\t/evil.example` and `/\evil.example` leave the site too. */ export function safeReturnPath(value: string | null | undefined): string { - if ( - !value || - !value.startsWith('/') || - value.startsWith('//') || - value.startsWith('/\\') - ) { + if (!value?.startsWith('/')) return ROUTES.home; + try { + const url = new URL(value, PROBE_ORIGIN); + if (url.origin !== PROBE_ORIGIN) return ROUTES.home; + return `${url.pathname}${url.search}${url.hash}`; + } catch { return ROUTES.home; } - return value; } diff --git a/platforms/market/src/features/auth/actions/login/actions.ts b/platforms/market/src/features/auth/actions/login/actions.ts index a2fd87c..dac2167 100644 --- a/platforms/market/src/features/auth/actions/login/actions.ts +++ b/platforms/market/src/features/auth/actions/login/actions.ts @@ -1,3 +1,4 @@ +import { handleError } from '@lumina/libs/error-handler'; import { eventEmitter } from '@lumina/libs/event-emitter'; import { useAuthStore } from '../../../../stores/auth'; @@ -10,8 +11,9 @@ import type { LoginOutcome } from './types'; /** * Verifies the login code; the gateway sets the session cookies and the auth store learns the * account, so every auth-dependent part renders its member variant. A suspended account gets no - * session: the gateway still opens one, so it is closed again at once. Emits `auth.login` when - * the person is signed in. + * session: the gateway still opens one, so it is closed again at once. When that close fails the + * person still sees the suspended screen, and the next `restoreSession` closes the session. Emits + * `auth.login` when the person is signed in. */ export async function login( args: VerifyOtpArgs, @@ -19,7 +21,11 @@ export async function login( ): Promise { const { account } = await authRepository.verifyLoginOtp(args); if (account.status === 'suspended') { - await authRepository.logout(); + await authRepository + .logout() + .catch((error: unknown) => + handleError(error, { where: 'action', name: 'logout-suspended' }), + ); useAuthFlowStore.getState().reset(); return { status: 'suspended' }; } diff --git a/platforms/market/src/features/auth/actions/restore-session/actions.ts b/platforms/market/src/features/auth/actions/restore-session/actions.ts index 47500f2..ebd42eb 100644 --- a/platforms/market/src/features/auth/actions/restore-session/actions.ts +++ b/platforms/market/src/features/auth/actions/restore-session/actions.ts @@ -1,3 +1,4 @@ +import { classifyError, handleError } from '@lumina/libs/error-handler'; import { eventEmitter } from '@lumina/libs/event-emitter'; import { useAuthStore } from '../../../../stores/auth'; @@ -5,11 +6,19 @@ import type { ViewerStatus } from '../../../../stores/auth'; import { AUTH_EVENTS } from '../../constants'; import { authRepository } from '../../repositories/auth'; +/** The connection or the gateway failed, so a later read may still succeed. */ +function isTransient(error: unknown): boolean { + const { retry } = classifyError(error); + return retry === 'again' || retry === 'wait'; +} + /** - * Learns who the viewer is, once per page load (the AppShell calls it). A guest is an empty - * session, not an error. An expired access cookie is refreshed by the HTTP client on the way. When - * the read still fails, the viewer is treated as a guest and the error is rethrown for reporting. - * Emits `auth.restore`. + * Learns who the viewer is, once per page load and again when the connection comes back (the + * AppShell calls it). A guest is an empty session, not an error. An expired access cookie is + * refreshed by the HTTP client on the way. A suspended account is no member: its session is closed + * and the viewer is a guest. When the read fails for a reason that may pass (offline, a timeout, + * a 5xx), who the viewer is stays unknown, so a member is never sent to login; any other failure + * makes the viewer a guest. Both rethrow for reporting. Emits `auth.restore`. */ export async function restoreSession({ emit = true, @@ -18,11 +27,23 @@ export async function restoreSession({ let status: ViewerStatus; try { const { account } = await authRepository.getSession(); - if (account) setSession({ account }); - else clearSession(); - status = account ? 'member' : 'guest'; + if (account?.status === 'suspended') { + clearSession(); + void authRepository + .logout() + .catch((error: unknown) => + handleError(error, { where: 'action', name: 'logout-suspended' }), + ); + status = 'guest'; + } else if (account) { + setSession({ account }); + status = 'member'; + } else { + clearSession(); + status = 'guest'; + } } catch (error) { - clearSession(); + if (!isTransient(error)) clearSession(); throw error; } if (emit) eventEmitter.emit(AUTH_EVENTS.restore, { status }); diff --git a/platforms/market/src/features/auth/actions/send-code/actions.ts b/platforms/market/src/features/auth/actions/send-code/actions.ts index 835f0af..01ac560 100644 --- a/platforms/market/src/features/auth/actions/send-code/actions.ts +++ b/platforms/market/src/features/auth/actions/send-code/actions.ts @@ -7,28 +7,33 @@ import { authErrorCode, authRepository, } from '../../repositories/auth'; -import type { SendCodeArgs } from './types'; +import type { SendCodeArgs, SendCodeOptions } from './types'; /** * Sends a sign-in or registration code to the number and starts the resend wait. Also the resend: * a new code replaces the previous one. Asked again for the same number inside the server's - * cooldown, the code already sent still works, so that counts as sent. Emits `auth.code-sent`. + * cooldown, the code already sent still works while it is unused, so that counts as sent; a code + * that already verified the number (registration) does not. The resend button passes + * `acceptPending: false`, so the person learns no new code went out. Emits `auth.code-sent` when a + * code is sent. */ export async function sendCode( { purpose, phone }: SendCodeArgs, - { emit = true }: { emit?: boolean } = {}, + { emit = true, acceptPending = true }: SendCodeOptions = {}, ): Promise<'ok'> { try { if (purpose === 'login') await authRepository.requestLoginOtp({ phone }); else await authRepository.sendRegistrationOtp({ phone }); } catch (error) { const flow = useAuthFlowStore.getState(); - const isSameCode = + const isPendingCode = + acceptPending && authErrorCode(error) === AUTH_ERROR_CODES.cooldown && flow.purpose === purpose && flow.phone === phone && - flow.codeSentAt !== null; - if (!isSameCode) throw error; + flow.codeSentAt !== null && + flow.registration === null; + if (!isPendingCode) throw error; return 'ok'; } useAuthFlowStore.getState().codeSent(purpose, phone, Date.now()); diff --git a/platforms/market/src/features/auth/actions/send-code/index.ts b/platforms/market/src/features/auth/actions/send-code/index.ts index 29246e9..a565916 100644 --- a/platforms/market/src/features/auth/actions/send-code/index.ts +++ b/platforms/market/src/features/auth/actions/send-code/index.ts @@ -1,2 +1,2 @@ export { sendCode } from './actions'; -export type { SendCodeArgs } from './types'; +export type { SendCodeArgs, SendCodeOptions } from './types'; diff --git a/platforms/market/src/features/auth/actions/send-code/types.ts b/platforms/market/src/features/auth/actions/send-code/types.ts index 7a17150..f81bb6d 100644 --- a/platforms/market/src/features/auth/actions/send-code/types.ts +++ b/platforms/market/src/features/auth/actions/send-code/types.ts @@ -5,3 +5,9 @@ export type SendCodeArgs = { /** 09XXXXXXXXX; the repository sends E.164. */ phone: string; }; + +export type SendCodeOptions = { + emit?: boolean; + /** Counts the server's cooldown for the same unused code as sent. Off for the resend button. */ + acceptPending?: boolean; +}; diff --git a/platforms/market/src/features/auth/models/code-step/use-code-step.ts b/platforms/market/src/features/auth/models/code-step/use-code-step.ts index d353dd5..f93d585 100644 --- a/platforms/market/src/features/auth/models/code-step/use-code-step.ts +++ b/platforms/market/src/features/auth/models/code-step/use-code-step.ts @@ -115,7 +115,7 @@ export function useCodeStep({ const onResend = () => { if (!phone || phase === 'sending') return; setPhase('sending'); - sendCode({ purpose, phone }) + sendCode({ purpose, phone }, { acceptPending: false }) .then(() => { restart(); setPhase('sent'); diff --git a/platforms/market/src/features/post/caches/creator-posts.ts b/platforms/market/src/features/post/caches/creator-posts.ts index 73c3896..fc4a978 100644 --- a/platforms/market/src/features/post/caches/creator-posts.ts +++ b/platforms/market/src/features/post/caches/creator-posts.ts @@ -6,9 +6,10 @@ import { POST_PAGE_LIMIT, postRepository } from '../repositories/post'; import type { PostPagePayload } from '../repositories/post'; /** - * A channel's first page for this request's viewer: drafts included for the creator, premium - * posts locked for anyone without a subscription. Later pages load on the client with the same - * `POST_PAGE_LIMIT`. + * A channel's first page as every visitor sees it: server reads carry no session, so drafts are + * left out and premium posts come locked. The creator's drafts and a subscriber's unlocked posts + * load in the browser, in the auth-dependent part that replaces this page. Later pages load on the + * client with the same `POST_PAGE_LIMIT`. */ export const getCreatorPosts = cache( async (creatorId: string): Promise => diff --git a/platforms/market/src/features/post/caches/post.ts b/platforms/market/src/features/post/caches/post.ts index 0718ddd..4c710f0 100644 --- a/platforms/market/src/features/post/caches/post.ts +++ b/platforms/market/src/features/post/caches/post.ts @@ -6,8 +6,10 @@ import { postRepository } from '../repositories/post'; import type { PostPayload } from '../repositories/post'; /** - * One post as this request's viewer may see it: in full, or locked for a premium post without a - * subscription. A missing post or someone else's draft rejects with a 404 for `readOnServer`. + * One post as every visitor sees it: server reads carry no session, so a premium post comes locked + * and the full post loads in the browser for a subscriber. A missing post or any draft, the + * creator's own included, rejects with a 404 for `readOnServer`; the creator opens a draft from a + * page that reads it in the browser. */ export const getPost = cache( async (id: string): Promise => postRepository.get(id), diff --git a/platforms/market/src/features/profile/models/creator-profile/use-profile-autosave.ts b/platforms/market/src/features/profile/models/creator-profile/use-profile-autosave.ts index d0bd2a9..6681ef6 100644 --- a/platforms/market/src/features/profile/models/creator-profile/use-profile-autosave.ts +++ b/platforms/market/src/features/profile/models/creator-profile/use-profile-autosave.ts @@ -11,7 +11,7 @@ import type { AutosaveStatus, CreatorProfileForm } from './types'; /** * Saves the creator's step 5 as a draft about a second after typing stops, at once on request * (a field lost focus), and when the page closes. Saves run one at a time, each from the newest - * values, and a save that would change nothing is skipped. A failure is reported and shown in the + * values, except the one sent as the tab closes, and a save that would change nothing is skipped. A failure is reported and shown in the * status line; it never toasts, because the next change tries again. */ export function useProfileAutosave( @@ -25,36 +25,44 @@ export function useProfileAutosave( const running = useRef | null>(null); const isStopped = useRef(false); + // One request from the newest values, unless they are what the server already has. + const send = useCallback( + async ({ keepalive = false }: { keepalive?: boolean } = {}) => { + if (isStopped.current) return; + const args = toDraftArgs(form.getValues()); + const key = JSON.stringify(args); + if (key === lastSaved.current) return; + + const request = profileRepository + .saveDraft(args, { keepalive }) + .then( + (profile) => { + lastSaved.current = key; + queryClient.setQueryData(profileKeys.mine(), profile); + setStatus({ phase: 'saved', at: Date.now() }); + }, + (error: unknown) => { + const errorClass = handleError(error, { + where: 'action', + name: 'profile-autosave', + }); + if (errorClass.action !== 'silent') setStatus({ phase: 'failed' }); + }, + ) + .finally(() => { + if (running.current === request) running.current = null; + }); + running.current = request; + await request; + }, + [form, queryClient], + ); + const save = useCallback(async (): Promise => { clearTimeout(timer.current); while (running.current) await running.current; - if (isStopped.current) return; - const args = toDraftArgs(form.getValues()); - const key = JSON.stringify(args); - if (key === lastSaved.current) return; - - const request = profileRepository - .saveDraft(args) - .then( - (profile) => { - lastSaved.current = key; - queryClient.setQueryData(profileKeys.mine(), profile); - setStatus({ phase: 'saved', at: Date.now() }); - }, - (error: unknown) => { - const errorClass = handleError(error, { - where: 'action', - name: 'profile-autosave', - }); - if (errorClass.action !== 'silent') setStatus({ phase: 'failed' }); - }, - ) - .finally(() => { - running.current = null; - }); - running.current = request; - await request; - }, [form, queryClient]); + await send(); + }, [send]); useEffect(() => { const unsubscribe = form.subscribe({ @@ -70,15 +78,20 @@ export function useProfileAutosave( }; }, [form, save]); - // Closing the tab or leaving for another page keeps what is pending. + // Closing the tab keeps what is pending: the save goes out at once with keepalive, which the + // browser finishes after the page is gone, instead of waiting for a save in flight that the + // unload would cancel. Leaving for another page of the app saves as usual. useEffect(() => { - const flush = () => void save(); - window.addEventListener('pagehide', flush); - return () => { - window.removeEventListener('pagehide', flush); - flush(); + const flushOnUnload = () => { + clearTimeout(timer.current); + void send({ keepalive: true }); }; - }, [save]); + window.addEventListener('pagehide', flushOnUnload); + return () => { + window.removeEventListener('pagehide', flushOnUnload); + void save(); + }; + }, [send, save]); return { status, diff --git a/platforms/market/src/features/profile/repositories/profile/profile.ts b/platforms/market/src/features/profile/repositories/profile/profile.ts index c88516e..a41c414 100644 --- a/platforms/market/src/features/profile/repositories/profile/profile.ts +++ b/platforms/market/src/features/profile/repositories/profile/profile.ts @@ -43,12 +43,19 @@ export const profileRepository = { /** Registration step 5's autosave: keeps what was typed without completing the profile. */ async saveDraft( args: SaveProfileDraftArgs, - { signal }: { signal?: AbortSignal } = {}, + { + signal, + keepalive = false, + }: { + signal?: AbortSignal; + /** The browser finishes the request after the page closes. */ + keepalive?: boolean; + } = {}, ): Promise { const response = await profileHttp.patch( PROFILE_ENDPOINTS.mine, toSaveProfileDraftDto(args), - { signal }, + { signal, init: keepalive ? { keepalive } : undefined }, ); return toCreatorProfilePayload(response); }, diff --git a/platforms/market/src/shared/locales/fa/errors.json b/platforms/market/src/shared/locales/fa/errors.json index f731186..5043954 100644 --- a/platforms/market/src/shared/locales/fa/errors.json +++ b/platforms/market/src/shared/locales/fa/errors.json @@ -12,6 +12,14 @@ "interceptor-hint": "صفحه را دوباره بارگذاری کنید.", "unknown": "مشکلی پیش آمد.", "unknown-hint": "دوباره تلاش کنید؛ اگر مشکل ادامه داشت، با پشتیبانی تماس بگیرید.", + "validation": "برخی از اطلاعات واردشده درست نیست.", + "bad-request": "درخواست قابل انجام نبود.", + "unauthorized": "برای ادامه وارد حساب خود شوید.", + "forbidden": "اجازه انجام این کار را ندارید.", + "not-found": "موردی که دنبالش بودید پیدا نشد.", + "conflict": "این اطلاعات در این فاصله تغییر کرده است.", + "rate-limited": "تعداد درخواست‌ها زیاد بود.", + "server": "سرور نتوانست درخواست را انجام دهد.", "retry-after": "{{seconds}} ثانیه دیگر دوباره تلاش کنید." }, "fallback": { diff --git a/platforms/market/src/shared/utils/social-links.ts b/platforms/market/src/shared/utils/social-links.ts index 446a771..95ef50c 100644 --- a/platforms/market/src/shared/utils/social-links.ts +++ b/platforms/market/src/shared/utils/social-links.ts @@ -1,4 +1,7 @@ -import { SOCIAL_HANDLE_ADDRESSES } from '../validations/constants'; +import { + SOCIAL_HANDLE_ADDRESSES, + SOCIAL_HANDLE_PATTERN, +} from '../validations/constants'; import type { SocialPlatform } from '../validations/types'; type HandlePlatform = keyof typeof SOCIAL_HANDLE_ADDRESSES; @@ -58,7 +61,9 @@ export function toSocialUrl(platform: SocialPlatform, handle: string): string { /** * A stored link back into a row. The label names the platform for links this form saved; older - * links fall back to their host, and anything else is a website. + * links fall back to their host, and anything else is a website. A platform link whose path is no + * handle (`t.me/s/channel`, `youtube.com/channel/UC…`) stays a website row with its whole address: + * a row that can't be saved would be dropped from the draft, and the server would lose the link. */ export function fromSocialUrl( label: string, @@ -76,7 +81,8 @@ export function fromSocialUrl( : undefined; const platform = byLabel ?? byHost; if (platform && address) { - return { platform, handle: handleFromPath(platform, address.path) }; + const handle = handleFromPath(platform, address.path); + if (SOCIAL_HANDLE_PATTERN.test(handle)) return { platform, handle }; } return { platform: 'website', handle: url }; } diff --git a/platforms/market/src/stores/auth-flow/auth-flow-store.ts b/platforms/market/src/stores/auth-flow/auth-flow-store.ts index 05d556d..47e90c1 100644 --- a/platforms/market/src/stores/auth-flow/auth-flow-store.ts +++ b/platforms/market/src/stores/auth-flow/auth-flow-store.ts @@ -30,11 +30,18 @@ export const useAuthFlowStore = create()( }), carryPhone: (phone) => set((state) => { + // A different number starts clean: the sent code, the block and the misses belong to the + // old one. + if (state.phone !== phone) { + state.codeSentAt = null; + state.blockedUntil = null; + state.misses = 0; + } state.phone = phone; }), codeSent: (purpose, phone, sentAt) => set((state) => { - // A different number starts clean: the block and the misses belong to the old one. + // A different number starts clean: the block belongs to the old one. if (state.phone !== phone) state.blockedUntil = null; state.purpose = purpose; state.phone = phone;