A one-of-a-kind resume builder that keeps your privacy in mind. Completely secure, customizable, portable, open-source and free forever. Try it out today!
TypeScript agent-skillsaidsh-pluginhacktoberfestjavascriptmcp-serverreactresume-builderself-hostedtypescript
feat(share): suggest an available .cv domain and show DNS records in a dialog
Amruth Pillaia2bd0c5d9694
diff --git a/.env.example b/.env.exampleindex 05251b134..91f581d41 100644--- a/.env.example+++ b/.env.example@@ -212,7 +212,9 @@ FLAG_DISABLE_API_RATE_LIMIT="false"FLAG_ALLOW_UNSAFE_OAUTH_REDIRECT_URI="false"# Suggests a <username>.cv domain from OlaCV to people who have no custom domain yet.+# With OLACV_API_KEY set, Share checks availability and price first and suggests only a name that's free.FLAG_OLACV_SUGGESTION="false"+# OLACV_API_KEY=# Allows AI providers to be configured with any base URL, including http:// and# private/loopback addresses (e.g. http://localhost:11434 for a local Ollama instance).diff --git a/apps/mobile/src/features/share/custom-domain.tsx b/apps/mobile/src/features/share/custom-domain.tsxnew file mode 100644index 000000000..ba8e8b2a0--- /dev/null+++ b/apps/mobile/src/features/share/custom-domain.tsx@@ -0,0 +1,269 @@+import type { RouterOutput } from "@/api/client";+import { useLingui } from "@lingui/react/macro";+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";+import * as Clipboard from "expo-clipboard";+import { useState } from "react";+import { Linking, View } from "react-native";+import { cvDomainRegistrationUrl, formatTimeSince } from "@reactive-resume/resume/sharing";+import { orpc } from "@/api/client";+import { Banner, Button, Icon, ListGroup, ListRow, Sheet, Text, TextField, haptics, showToast, useTheme } from "@/ui";++const CODE = "RX";++type Domain = NonNullable<RouterOutput["customDomain"]["get"]>;+type Suggestion = NonNullable<RouterOutput["customDomain"]["suggestion"]>;++type CustomDomainProps = {+ offline: boolean;+ /** Suggest a `.cv` domain from OlaCV while none is connected (`FLAG_OLACV_SUGGESTION`). */+ suggest: boolean;+};++/** Connects the account's own domain: the domain, the DNS records to add in a sheet, a check, and the result. */+export function CustomDomain({ offline, suggest }: CustomDomainProps) {+ const { t } = useLingui();+ const { space } = useTheme();+ const queryClient = useQueryClient();+ const domain = useQuery({ ...orpc.customDomain.get.queryOptions(), enabled: !offline });+ const suggestion = useQuery({+ ...orpc.customDomain.suggestion.queryOptions(),+ enabled: suggest && !offline && domain.isSuccess && !domain.data,+ staleTime: 15 * 60_000,+ });+ const [hostname, setHostname] = useState("");+ const [recordsOpen, setRecordsOpen] = useState(false);+ const store = (next: RouterOutput["customDomain"]["get"]) =>+ queryClient.setQueryData(orpc.customDomain.get.queryKey(), next);+ const set = useMutation({+ ...orpc.customDomain.set.mutationOptions(),+ onSuccess: (next) => {+ store(next);+ if (!next.verified) setRecordsOpen(true);+ },+ });+ const verify = useMutation({+ ...orpc.customDomain.verify.mutationOptions(),+ onSuccess: (next) => {+ store(next);+ if (next.verified) setRecordsOpen(false);+ showToast({+ message: next.verified ? t`Domain connected` : t`The records aren't visible yet. Check again later.`,+ });+ },+ });+ const remove = useMutation({ ...orpc.customDomain.remove.mutationOptions(), onSuccess: () => store(null) });+ const error = set.error ?? verify.error ?? remove.error;++ if (domain.isPending) return null;+ const current = domain.data;++ return (+ <View style={{ gap: space.s3 }}>+ {error && <Banner tone="danger" message={error.message} />}+ {!current ? (+ <>+ <TextField+ label={t`Your domain`}+ value={hostname}+ onChangeText={setHostname}+ placeholder="resume.example.com"+ autoCapitalize="none"+ autoCorrect={false}+ keyboardType="url"+ />+ <Button+ variant="secondary"+ label={t`Connect`}+ loading={set.isPending}+ disabled={offline || !hostname.trim()}+ onPress={() => set.mutate({ hostname })}+ />+ {suggest && suggestion.data && (+ <CvDomainCard+ suggestion={suggestion.data}+ connecting={set.isPending}+ disabled={offline}+ onConnect={(hostname) => set.mutate({ hostname })}+ />+ )}+ </>+ ) : (+ <>+ <ListRow+ title={current.hostname}+ subtitle={+ current.verified+ ? t`Connected. Your domain opens your primary resume.`+ : t`Not connected yet. Add its DNS records where you manage the domain, then check.`+ }+ leading={current.verified ? "check-circle" : "warning-circle"}+ />+ {!current.verified && (+ <>+ <Button variant="secondary" label={t`Show DNS records`} onPress={() => setRecordsOpen(true)} />+ <Button+ variant="ghost"+ label={t`Check DNS`}+ loading={verify.isPending}+ disabled={offline}+ onPress={() => verify.mutate({})}+ />+ </>+ )}+ <Button+ variant="ghost"+ label={t`Remove`}+ loading={remove.isPending}+ disabled={offline}+ onPress={() => remove.mutate({})}+ />+ <DnsRecordsSheet+ domain={current}+ open={recordsOpen}+ onClose={() => setRecordsOpen(false)}+ checking={verify.isPending}+ disabled={offline}+ onCheck={() => verify.mutate({})}+ />+ </>+ )}+ </View>+ );+}++const copy = async (value: string, message: string) => {+ await Clipboard.setStringAsync(value);+ haptics.light();+ showToast({ message });+};++type CvDomainCardProps = {+ suggestion: Suggestion;+ connecting: boolean;+ disabled: boolean;+ onConnect: (domain: string) => void;+};++/** A quiet suggestion under the domain field: the account's name as a `.cv` domain, OlaCV's price and its code. */+function CvDomainCard({ suggestion: { domain, checked, price }, connecting, disabled, onConnect }: CvDomainCardProps) {+ const { t, i18n } = useLingui();+ const { colors, radius, space } = useTheme();+ const [visited, setVisited] = useState(false);+ const money = (amount: number, currency: string) =>+ i18n.number(amount, { style: "currency", currency, maximumFractionDigits: Number.isInteger(amount) ? 0 : 2 });+ const cost = price ? money(price.amount, price.currency) : null;+ const yearly = price?.renewal === price?.amount;++ return (+ <View style={{ gap: space.s3, padding: space.s4, borderRadius: radius.rLg, backgroundColor: colors.sunken }}>+ <View style={{ gap: 2 }}>+ <Text variant="title" numberOfLines={1}>+ {domain}+ </Text>+ <Text variant="caption" color="ink3">+ {checked ? (+ <>+ <Text variant="caption" color="accentText">{t`Available`}</Text>+ {cost ? ` · ${yearly ? t`${cost} a year` : t`${cost} the first year`}` : ""}+ </>+ ) : (+ t`May be available`+ )}+ </Text>+ </View>+ <Text variant="callout" color="ink2">+ {t`Your name as your address, from OlaCV, the .cv registry. Code ${CODE} takes 50% off the first year.`}+ </Text>+ <View style={{ flexDirection: "row", flexWrap: "wrap", gap: space.s2 }}>+ <Button+ variant="secondary"+ size="sm"+ icon="arrow-square-out"+ label={t`Register at OlaCV`}+ onPress={() => {+ setVisited(true);+ void Linking.openURL(cvDomainRegistrationUrl(domain));+ }}+ />+ <Button+ variant="ghost"+ size="sm"+ icon="copy"+ label={t`Copy code`}+ onPress={() => void copy(CODE, t`Code copied`)}+ />+ {visited && (+ <Button+ variant="ghost"+ size="sm"+ label={t`Connect ${domain}`}+ loading={connecting}+ disabled={disabled}+ onPress={() => onConnect(domain)}+ />+ )}+ </View>+ </View>+ );+}++type DnsRecordsSheetProps = {+ domain: Domain;+ open: boolean;+ onClose: () => void;+ checking: boolean;+ disabled: boolean;+ onCheck: () => void;+};++/** The records that connect a custom domain, one group each; tapping a name or value copies it. */+function DnsRecordsSheet({ domain, open, onClose, checking, disabled, onCheck }: DnsRecordsSheetProps) {+ const { t, i18n } = useLingui();+ const { space } = useTheme();+ const lastChecked = domain.lastCheckedAt ? formatTimeSince(domain.lastCheckedAt, i18n.locale) : null;++ return (+ <Sheet+ open={open}+ onClose={onClose}+ title={t`Connect ${domain.hostname}`}+ detents={[0.6, 0.95]}+ footer={<Button label={t`Check DNS`} loading={checking} disabled={disabled} onPress={onCheck} />}+ >+ <View style={{ gap: space.s4 }}>+ <Text color="ink2">+ {t`Add these records where you manage the domain, then check. Changes can take a few hours to reach everyone.`}+ </Text>+ {domain.records.map((record) => (+ <ListGroup key={`${record.type}-${record.value}`} title={record.type}>+ <ListRow+ title={record.name}+ subtitle={t({ message: "Name", context: "DNS record" })}+ trailing={<CopyGlyph />}+ accessibilityHint={t`Copies it`}+ onPress={() => void copy(record.name, t`Copied`)}+ />+ <ListRow+ title={record.value}+ subtitle={t`Value`}+ trailing={<CopyGlyph />}+ accessibilityHint={t`Copies it`}+ onPress={() => void copy(record.value, t`Copied`)}+ />+ </ListGroup>+ ))}+ {domain.records.some((record) => record.type === "CNAME") && (+ <Text variant="caption" color="ink3">+ {t`For a root domain such as example.com, use A and AAAA records with ${domain.target}'s addresses instead of the CNAME.`}+ </Text>+ )}+ {lastChecked && <Text variant="caption" color="ink3">{t`Last checked ${lastChecked} ago`}</Text>}+ </View>+ </Sheet>+ );+}++function CopyGlyph() {+ const { colors, size } = useTheme();+ return <Icon name="copy" size={size.icon.meta} color={colors.ink3} />;+}diff --git a/apps/mobile/src/features/share/web-page.tsx b/apps/mobile/src/features/share/web-page.tsxindex 0bfac9cd1..f7944367f 100644--- a/apps/mobile/src/features/share/web-page.tsx+++ b/apps/mobile/src/features/share/web-page.tsx@@ -3,29 +3,18 @@ import type { RouterOutput } from "@/api/client";import type { ResumeDocument } from "@/draft/types";import type { useDocumentOperations } from "@/features/documents/queries";import { useLingui } from "@lingui/react/macro";-import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";+import { useQuery } from "@tanstack/react-query";import * as Clipboard from "expo-clipboard";import { openBrowserAsync } from "expo-web-browser";import { useState } from "react";-import { Linking, View } from "react-native";-import { cvDomainFor, cvDomainRegistrationUrl, publicResumeUrl } from "@reactive-resume/resume/sharing";+import { View } from "react-native";+import { publicResumeUrl } from "@reactive-resume/resume/sharing";+import { CustomDomain } from "./custom-domain";import { flushResume } from "./document";import { client, orpc } from "@/api/client";import { useResumeStore } from "@/draft";import { resume as draftResume } from "@/draft/runtime";-import {- Banner,- Button,- ConfirmDialog,- ListGroup,- ListRow,- Sheet,- Switch,- Text,- TextField,- showToast,- useTheme,-} from "@/ui";+import { Banner, Button, ConfirmDialog, ListGroup, ListRow, Sheet, Switch, TextField, showToast, useTheme } from "@/ui";type WebPageSettingsProps = {resume: ResumeDocument;@@ -126,12 +115,7 @@ export function WebPageSettings({ resume, offline, username, origin, flags, oper/>)}</ListGroup>- {flags?.customDomains && (- <CustomDomain- offline={offline}- suggestion={flags.olacvSuggestion && username ? cvDomainFor(username) : undefined}- />- )}+ {flags?.customDomains && <CustomDomain offline={offline} suggest={flags.olacvSuggestion ?? false} />}<ListGrouptitle={t`Web page`}@@ -287,98 +271,3 @@ export function WebPageSettings({ resume, offline, username, origin, flags, oper</View>);}--type CustomDomainProps = { offline: boolean; suggestion: string | undefined };--/** Connects the account's own domain: the DNS records to add, a check, and the result. */-function CustomDomain({ offline, suggestion }: CustomDomainProps) {- const { t } = useLingui();- const { space } = useTheme();- const queryClient = useQueryClient();- const domain = useQuery({ ...orpc.customDomain.get.queryOptions(), enabled: !offline });- const [hostname, setHostname] = useState("");- const store = (next: RouterOutput["customDomain"]["get"]) =>- queryClient.setQueryData(orpc.customDomain.get.queryKey(), next);- const set = useMutation({ ...orpc.customDomain.set.mutationOptions(), onSuccess: store });- const verify = useMutation({- ...orpc.customDomain.verify.mutationOptions(),- onSuccess: (next) => {- store(next);- showToast({- message: next.verified ? t`Domain connected` : t`The records aren't visible yet. Check again later.`,- });- },- });- const remove = useMutation({ ...orpc.customDomain.remove.mutationOptions(), onSuccess: () => store(null) });- const error = set.error ?? verify.error ?? remove.error;-- if (domain.isPending) return null;- const current = domain.data;-- return (- <View style={{ gap: space.s3 }}>- {error && <Banner tone="danger" message={error.message} />}- {!current ? (- <>- <TextField- label={t`Your domain`}- value={hostname}- onChangeText={setHostname}- placeholder="resume.example.com"- autoCapitalize="none"- autoCorrect={false}- keyboardType="url"- />- <Button- variant="secondary"- label={t`Connect`}- loading={set.isPending}- disabled={offline || !hostname.trim()}- onPress={() => set.mutate({ hostname })}- />- {suggestion && (- <Button- variant="link"- label={t`${suggestion} may be available. Get yours here →`}- onPress={() => void Linking.openURL(cvDomainRegistrationUrl(suggestion))}- />- )}- </>- ) : (- <>- <ListRow- title={current.hostname}- subtitle={current.verified ? t`Connected. Your domain opens your primary resume.` : undefined}- leading={current.verified ? "check-circle" : "warning-circle"}- />- {!current.verified && (- <>- <Text color="ink2">- {t`Add these records where you manage the domain, then check. Changes can take a few hours to reach everyone.`}- </Text>- <Text selectable variant="mono">{`CNAME ${current.hostname} → ${current.target}`}</Text>- <Text selectable variant="mono">{`TXT ${current.txtName} = ${current.txtValue}`}</Text>- <Text variant="caption" color="ink3">- {t`For a root domain such as example.com, use A and AAAA records with ${current.target}'s addresses instead of the CNAME.`}- </Text>- <Button- variant="secondary"- label={t`Check DNS`}- loading={verify.isPending}- disabled={offline}- onPress={() => verify.mutate({})}- />- </>- )}- <Button- variant="ghost"- label={t`Remove`}- loading={remove.isPending}- disabled={offline}- onPress={() => remove.mutate({})}- />- </>- )}- </View>- );-}diff --git a/apps/web/src/features/resume/share/copy-text.tsx b/apps/web/src/features/resume/share/copy-text.tsxnew file mode 100644index 000000000..345aed0a1--- /dev/null+++ b/apps/web/src/features/resume/share/copy-text.tsx@@ -0,0 +1,55 @@+import { t } from "@lingui/core/macro";+import { useEffect, useRef, useState } from "react";+import { useCopyToClipboard } from "usehooks-ts";+import { toast } from "@reactive-resume/ui/components/toast";+import { Tooltip, TooltipContent, TooltipTrigger } from "@reactive-resume/ui/components/tooltip";+import { cn } from "@reactive-resume/utils/style";++const COPIED_MS = 1600;++type CopyTextProps = { value: string; className?: string };++/** Text that copies itself when clicked. The tooltip offers the copy, then confirms it, on touch screens too. */+export function CopyText({ value, className }: CopyTextProps) {+ const [hovered, setHovered] = useState(false);+ const [copied, setCopied] = useState(false);+ const [, copyToClipboard] = useCopyToClipboard();+ const timer = useRef<number>(undefined);++ useEffect(() => () => window.clearTimeout(timer.current), []);++ const copy = async () => {+ if (!(await copyToClipboard(value))) {+ toast.add({ type: "error", description: t`Couldn't copy to the clipboard. Try again.` });+ return;+ }+ setCopied(true);+ window.clearTimeout(timer.current);+ timer.current = window.setTimeout(() => setCopied(false), COPIED_MS);+ };++ return (+ <Tooltip open={hovered || copied} onOpenChange={setHovered}>+ <TooltipTrigger+ closeOnClick={false}+ render={+ <button+ type="button"+ aria-label={t`Copy ${value}`}+ onClick={() => void copy()}+ className={cn(+ "-mx-1 rounded-sm px-1 text-start break-all transition-colors duration-quick hover:bg-hover active:bg-press",+ className,+ )}+ />+ }+ >+ {value}+ </TooltipTrigger>+ <TooltipContent>{copied ? t`Copied` : t`Copy`}</TooltipContent>+ <span className="sr-only" aria-live="polite">+ {copied ? t`Copied` : ""}+ </span>+ </Tooltip>+ );+}diff --git a/apps/web/src/features/resume/share/custom-domain-field.tsx b/apps/web/src/features/resume/share/custom-domain-field.tsxindex 22ce65e1e..a51f76140 100644--- a/apps/web/src/features/resume/share/custom-domain-field.tsx+++ b/apps/web/src/features/resume/share/custom-domain-field.tsx@@ -3,75 +3,103 @@ import { t } from "@lingui/core/macro";import { Trans } from "@lingui/react/macro";import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";import { useId, useState } from "react";-import { cvDomainRegistrationUrl } from "@reactive-resume/resume/sharing";import { Button } from "@reactive-resume/ui/components/button";import { Icon } from "@reactive-resume/ui/components/icon";import { Input } from "@reactive-resume/ui/components/input";import { toast } from "@reactive-resume/ui/components/toast";+import { CvDomainCard } from "./cv-domain-card";+import { DnsRecordsDialog } from "./dns-records-dialog";import { toastError } from "@/libs/error-message";import { orpc } from "@/libs/orpc/client";-type CustomDomainFieldProps = { suggestion: string | undefined };+type CustomDomainFieldProps = {+ /** Suggest a `.cv` domain from OlaCV while none is connected (`FLAG_OLACV_SUGGESTION`). */+ suggest: boolean;+};-/** Connects the account's own domain: the DNS records to add, a check, and the result. */-export function CustomDomainField({ suggestion }: CustomDomainFieldProps) {+/** Connects the account's own domain: the domain, the DNS records to add in a dialog, a check, and the result. */+export function CustomDomainField({ suggest }: CustomDomainFieldProps) {const id = useId();const queryClient = useQueryClient();const { data: domain, isPending: loading } = useQuery(orpc.customDomain.get.queryOptions());+ const { data: suggestion } = useQuery({+ ...orpc.customDomain.suggestion.queryOptions(),+ enabled: suggest && !loading && !domain,+ staleTime: 15 * 60_000,+ });const [hostname, setHostname] = useState("");+ const [recordsOpen, setRecordsOpen] = useState(false);const refresh = (next: RouterOutput["customDomain"]["get"]) =>queryClient.setQueryData(orpc.customDomain.get.queryKey(), next);- const set = useMutation({ ...orpc.customDomain.set.mutationOptions(), onSuccess: refresh });+ const set = useMutation({+ ...orpc.customDomain.set.mutationOptions(),+ onSuccess: (next) => {+ refresh(next);+ if (!next.verified) setRecordsOpen(true);+ },+ });const verify = useMutation({ ...orpc.customDomain.verify.mutationOptions(), onSuccess: refresh });const remove = useMutation({ ...orpc.customDomain.remove.mutationOptions(), onSuccess: () => refresh(null) });const onError = (error: unknown) =>toastError(error, t`Couldn't update sharing. Try again.`, { allowServerMessage: true });+ const check = () =>+ verify.mutate(undefined, {+ onError,+ onSuccess: (next) => {+ if (next.verified) setRecordsOpen(false);+ toast.add(+ next.verified+ ? { description: t`Domain connected` }+ : { type: "error", description: t`The records aren't visible yet. Check again later.` },+ );+ },+ });+if (loading) return null;if (!domain)return (- <form- className="grid gap-1.5"- onSubmit={(event) => {- event.preventDefault();- set.mutate({ hostname }, { onError });- }}- >- <label htmlFor={id} className="text-xs font-medium text-ink-2">- <Trans>Your domain</Trans>- </label>- <div className="flex gap-1.5">- <Input- id={id}- value={hostname}- placeholder="resume.example.com"- spellCheck={false}- autoCapitalize="none"- onChange={(event) => setHostname(event.target.value)}- className="h-[38px] font-mono text-[13px]"+ <>+ <form+ className="grid gap-1.5"+ onSubmit={(event) => {+ event.preventDefault();+ set.mutate({ hostname }, { onError });+ }}+ >+ <label htmlFor={id} className="text-xs font-medium text-ink-2">+ <Trans>Your domain</Trans>+ </label>+ <div className="flex gap-1.5">+ <Input+ id={id}+ value={hostname}+ placeholder="resume.example.com"+ spellCheck={false}+ autoCapitalize="none"+ onChange={(event) => setHostname(event.target.value)}+ className="h-[38px] font-mono text-[13px]"+ />+ <Button+ type="submit"+ variant="secondary"+ className="h-[38px]"+ loading={set.isPending}+ disabled={!hostname.trim()}+ >+ <Trans>Connect</Trans>+ </Button>+ </div>+ </form>+ {suggest && suggestion && (+ <CvDomainCard+ suggestion={suggestion}+ connecting={set.isPending}+ onConnect={() => set.mutate({ hostname: suggestion.domain }, { onError })}/>- <Button- type="submit"- variant="secondary"- className="h-[38px]"- loading={set.isPending}- disabled={!hostname.trim()}- >- <Trans>Connect</Trans>- </Button>- </div>- {suggestion && (- <a- href={cvDomainRegistrationUrl(suggestion)}- target="_blank"- rel="noopener sponsored"- className="text-xs text-ink-2 underline-offset-2 hover:text-ink hover:underline"- >- <Trans>{suggestion} may be available. Get yours here →</Trans>- </a>)}- </form>+ </>);return (@@ -101,46 +129,25 @@ export function CustomDomainField({ suggestion }: CustomDomainFieldProps) {) : (<><p className="text-xs leading-4 text-ink-2">- <Trans>- Add these records where you manage the domain, then check. Changes can take a few hours to reach everyone.- </Trans>- </p>- <dl className="grid grid-cols-[auto_minmax(0,1fr)] gap-x-3 gap-y-1.5 font-mono text-[12px]" dir="ltr">- <dt className="text-ink-3">CNAME</dt>- <dd className="break-all">- {domain.hostname} → {domain.target}- </dd>- <dt className="text-ink-3">TXT</dt>- <dd className="break-all">- {domain.txtName} = {domain.txtValue}- </dd>- </dl>- <p className="text-xs leading-4 text-ink-3">- <Trans>- For a root domain such as example.com, use A and AAAA records with {domain.target}'s addresses instead of- the CNAME.- </Trans>+ <Trans>Not connected yet. Add its DNS records where you manage the domain, then check.</Trans></p>- <Button- variant="secondary"- className="w-fit"- loading={verify.isPending}- onClick={() =>- verify.mutate(undefined, {- onError,- onSuccess: (next) =>- toast.add(- next.verified- ? { description: t`Domain connected` }- : { type: "error", description: t`The records aren't visible yet. Check again later.` },- ),- })- }- >- <Trans>Check DNS</Trans>- </Button>+ <div className="flex flex-wrap gap-2">+ <Button variant="secondary" size="sm" onClick={() => setRecordsOpen(true)}>+ <Trans>Show DNS records</Trans>+ </Button>+ <Button variant="ghost" size="sm" loading={verify.isPending} onClick={check}>+ <Trans>Check DNS</Trans>+ </Button>+ </div></>)}+ <DnsRecordsDialog+ domain={domain}+ open={recordsOpen}+ onOpenChange={setRecordsOpen}+ checking={verify.isPending}+ onCheck={check}+ /></div>);}diff --git a/apps/web/src/features/resume/share/cv-domain-card.tsx b/apps/web/src/features/resume/share/cv-domain-card.tsxnew file mode 100644index 000000000..c84098fe6--- /dev/null+++ b/apps/web/src/features/resume/share/cv-domain-card.tsx@@ -0,0 +1,77 @@+import type { RouterOutput } from "@/libs/orpc/client";+import { Trans, useLingui } from "@lingui/react/macro";+import { useState } from "react";+import { cvDomainRegistrationUrl } from "@reactive-resume/resume/sharing";+import { Button, buttonVariants } from "@reactive-resume/ui/components/button";+import { Icon } from "@reactive-resume/ui/components/icon";+import { CopyText } from "./copy-text";++type CvDomainCardProps = {+ suggestion: NonNullable<RouterOutput["customDomain"]["suggestion"]>;+ connecting: boolean;+ onConnect: () => void;+};++/**+ * A quiet suggestion beside the domain field: the account's own name as a `.cv` domain, with OlaCV's price when it+ * checked, and its code. Once they've gone to register it, connecting it is one click.+ */+export function CvDomainCard({ suggestion: { domain, checked, price }, connecting, onConnect }: CvDomainCardProps) {+ const { i18n } = useLingui();+ const [visited, setVisited] = useState(false);+ const money = (amount: number, currency: string) =>+ i18n.number(amount, { style: "currency", currency, maximumFractionDigits: Number.isInteger(amount) ? 0 : 2 });+ const cost = price ? money(price.amount, price.currency) : null;+ const yearly = price?.renewal === price?.amount;++ return (+ <div className="grid gap-3 rounded-xl bg-sunken p-3.5">+ <div className="grid gap-0.5">+ <p className="truncate font-mono text-[15px] leading-5 font-medium text-ink" dir="ltr">+ {domain}+ </p>+ <p className="text-xs leading-4 text-ink-3">+ {checked ? (+ <>+ <span className="font-medium text-accent-text">+ <Trans>Available</Trans>+ </span>+ {cost && (+ <>+ {" · "}+ {yearly ? <Trans>{cost} a year</Trans> : <Trans>{cost} the first year</Trans>}+ </>+ )}+ </>+ ) : (+ <Trans>May be available</Trans>+ )}+ </p>+ </div>+ <p className="text-xs leading-[18px] text-ink-2">+ <Trans>+ Your name as your address, from OlaCV, the .cv registry. Code{" "}+ <CopyText value="RX" className="mx-0 bg-surface font-mono font-medium text-ink" /> takes 50% off the first+ year.+ </Trans>+ </p>+ <div className="flex flex-wrap items-center gap-2">+ <a+ href={cvDomainRegistrationUrl(domain)}+ target="_blank"+ rel="noopener sponsored"+ onClick={() => setVisited(true)}+ className={buttonVariants({ variant: "secondary", size: "sm" })}+ >+ <Trans>Register at OlaCV</Trans>+ <Icon name="arrow-up-right" size={14} />+ </a>+ {visited && (+ <Button variant="ghost" size="sm" loading={connecting} onClick={onConnect}>+ <Trans>Connect {domain}</Trans>+ </Button>+ )}+ </div>+ </div>+ );+}diff --git a/apps/web/src/features/resume/share/dns-records-dialog.tsx b/apps/web/src/features/resume/share/dns-records-dialog.tsxnew file mode 100644index 000000000..bc38c9209--- /dev/null+++ b/apps/web/src/features/resume/share/dns-records-dialog.tsx@@ -0,0 +1,102 @@+import type { RouterOutput } from "@/libs/orpc/client";+import { t } from "@lingui/core/macro";+import { Trans, useLingui } from "@lingui/react/macro";+import { formatTimeSince } from "@reactive-resume/resume/sharing";+import { Button } from "@reactive-resume/ui/components/button";+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from "@reactive-resume/ui/components/dialog";+import { CopyText } from "./copy-text";++const cellClass =+ "py-2.5 pe-4 last:pe-0 max-sm:grid max-sm:py-0 max-sm:pe-0 max-sm:before:text-xs max-sm:before:text-ink-3 max-sm:before:content-[attr(data-label)]";++type DnsRecordsDialogProps = {+ domain: NonNullable<RouterOutput["customDomain"]["get"]>;+ open: boolean;+ onOpenChange: (open: boolean) => void;+ checking: boolean;+ onCheck: () => void;+};++/** The records that connect a custom domain, each name and value copied with a click, and the DNS check. */+export function DnsRecordsDialog({ domain, open, onOpenChange, checking, onCheck }: DnsRecordsDialogProps) {+ const { i18n } = useLingui();+ const hasCname = domain.records.some((record) => record.type === "CNAME");+ const lastChecked = domain.lastCheckedAt ? formatTimeSince(domain.lastCheckedAt, i18n.locale) : null;++ return (+ <Dialog open={open} onOpenChange={onOpenChange}>+ <DialogContent closeLabel={t`Close`} className="sm:max-w-[680px]">+ <DialogHeader>+ <DialogTitle>+ <Trans>Connect {domain.hostname}</Trans>+ </DialogTitle>+ <DialogDescription>+ <Trans>+ Add these records where you manage the domain, then check. Changes can take a few hours to reach everyone.+ </Trans>+ </DialogDescription>+ </DialogHeader>++ {/* On a phone each record stacks: its type, then its name and value on their own labelled lines. */}+ <table className="w-full text-[13px]" dir="ltr">+ <thead className="max-sm:sr-only">+ <tr className="text-xs text-ink-3">+ <th scope="col" className="w-16 pb-2 text-start font-normal">+ <Trans context="DNS record">Type</Trans>+ </th>+ <th scope="col" className="pe-4 pb-2 text-start font-normal">+ <Trans context="DNS record">Name</Trans>+ </th>+ <th scope="col" className="pb-2 text-start font-normal">+ <Trans>Value</Trans>+ </th>+ </tr>+ </thead>+ <tbody>+ {domain.records.map((record) => (+ <tr+ key={`${record.type}-${record.value}`}+ className="border-t border-line align-top max-sm:grid max-sm:grid-cols-[3.5rem_minmax(0,1fr)] max-sm:gap-y-1 max-sm:py-2.5"+ >+ <td className="py-2.5 font-medium max-sm:row-span-2 max-sm:py-0">{record.type}</td>+ <td data-label={t({ message: "Name", context: "DNS record" })} className={cellClass}>+ <CopyText value={record.name} className="font-mono" />+ </td>+ <td data-label={t`Value`} className={cellClass}>+ <CopyText value={record.value} className="font-mono" />+ </td>+ </tr>+ ))}+ </tbody>+ </table>++ {hasCname && (+ <p className="text-xs leading-4 text-ink-3">+ <Trans>+ For a root domain such as example.com, use A and AAAA records with {domain.target}'s addresses instead of+ the CNAME.+ </Trans>+ </p>+ )}++ <DialogFooter className="items-center">+ {lastChecked && (+ <p className="me-auto text-xs text-ink-3">+ <Trans>Last checked {lastChecked} ago</Trans>+ </p>+ )}+ <Button loading={checking} onClick={onCheck}>+ <Trans>Check DNS</Trans>+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ );+}diff --git a/apps/web/src/features/resume/share/share-panel.tsx b/apps/web/src/features/resume/share/share-panel.tsxindex be403e959..a2d2f7a2b 100644--- a/apps/web/src/features/resume/share/share-panel.tsx+++ b/apps/web/src/features/resume/share/share-panel.tsx@@ -5,7 +5,7 @@ import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";import { useRouteContext } from "@tanstack/react-router";import { QRCodeSVG } from "qrcode.react";import { useState } from "react";-import { cvDomainFor, formatTimeSince, publicResumeUrl, summarizeViews } from "@reactive-resume/resume/sharing";+import { formatTimeSince, publicResumeUrl, summarizeViews } from "@reactive-resume/resume/sharing";import { Button, buttonVariants } from "@reactive-resume/ui/components/button";import { Icon } from "@reactive-resume/ui/components/icon";import { Popover, PopoverContent, PopoverTrigger } from "@reactive-resume/ui/components/popover";@@ -179,9 +179,7 @@ function AddressesSection({ origin, username, setting }: AddressesSectionProps)</span><CopyLinkButton url={shortLink} className="h-8 gap-1.5" /></div>- {flags?.customDomains && (- <CustomDomainField suggestion={flags.olacvSuggestion ? cvDomainFor(username) : undefined} />- )}+ {flags?.customDomains && <CustomDomainField suggest={flags.olacvSuggestion ?? false} />}</section></>);diff --git a/docs/guides/sharing-your-resume-publicly.mdx b/docs/guides/sharing-your-resume-publicly.mdxindex c3a396e33..1b7dd3322 100644--- a/docs/guides/sharing-your-resume-publicly.mdx+++ b/docs/guides/sharing-your-resume-publicly.mdx@@ -96,7 +96,8 @@ One resume can be your **Primary resume**. It opens at your short link, such as- Turn on **Primary resume** in Share. The resume must be published first. If another resume was primary, Reactive Resume asks before moving the role.- **Copy** next to your short link to paste it anywhere. It always leads to your current primary resume.- On rxresu.me, every public address works on both `rx.cv` and `rxresu.me`, so `rxresu.me/dkowalski` opens the same page. Share copies the shorter `rx.cv` one.-- To use your own domain, type it under **Your domain** and select **Connect**. Add the two DNS records shown where you manage the domain, then select **Check DNS**. A subdomain such as `resume.example.com` uses a CNAME record; a root domain such as `example.com` uses A and AAAA records instead. Changes can take a few hours to reach everyone.+- To use your own domain, type it under **Your domain** and select **Connect**. A dialog lists the DNS records to add where you manage the domain; select a name or value to copy it. Then select **Check DNS**. A subdomain such as `resume.example.com` uses a CNAME record; a root domain such as `example.com` uses A and AAAA records instead. Changes can take a few hours to reach everyone. To see the records again, select **Show DNS records**.+- On rxresu.me, Share may suggest a `.cv` domain made from your username or name, such as `dkowalski.cv`, when it's free to register. It's an optional suggestion: OlaCV, the `.cv` registry, sells it, and the code `RX` takes 50% off the first year. After you register it, select **Connect** on the suggestion to add it here.Once connected, your domain shows your primary resume, and search engines are pointed to your domain rather than the rxresu.me address. If your domain's records stop pointing at Reactive Resume for a week, it's disconnected.diff --git a/docs/self-hosting/environment-variables.mdx b/docs/self-hosting/environment-variables.mdxindex 17318d12c..b5db3d5c3 100644--- a/docs/self-hosting/environment-variables.mdx+++ b/docs/self-hosting/environment-variables.mdx@@ -56,6 +56,7 @@ Both are off unless set. Every account's short link, `/<username>`, opens the re| `APP_ALIAS_URL` | unset | A second domain, such as `https://rx.cv`, that serves the same public pages as `APP_URL`: resumes, short links, the home page. Sign-in and the editor redirect to `APP_URL`, and search engines are pointed there. When set, Share copies links on this domain. Point the domain at this server. || `CUSTOM_DOMAIN_TARGET` | unset | The host people point their own domain's CNAME record at, such as `domains.example.com`. It must resolve to this server. || `CUSTOM_DOMAIN_PROVIDER_SECRET` | unset | At least 32 characters. Traefik's HTTP provider sends it in an `X-Provider-Secret` header to read `/api/internal/traefik?service=<service>&entryPoint=<entry point>&certResolver=<resolver>`, which returns a router, and so a certificate, for every verified domain. Custom domains need both this and `CUSTOM_DOMAIN_TARGET`. |+| `OLACV_API_KEY` | unset | An OlaCV API token. With `FLAG_OLACV_SUGGESTION`, Share checks which `.cv` names are free before suggesting one. The server calls `https://ola.cv/api/v1/domains/check` with the account's candidate names only; the token never reaches the browser. |For DNS, HTTPS, alias routing and the custom-domain provider endpoint, see[Sharing domains](/self-hosting/sharing-domains). Setting domain variables doesn't create proxy routes or certificates.@@ -289,7 +290,7 @@ All flags default to `false`.| `FLAG_DISABLE_API_RATE_LIMIT` | Turns off API and authentication rate limiting, including sign-in, sign-up, OAuth, requests made with API keys, PDF export and AI requests. Intended for test installations. || `FLAG_ALLOW_UNSAFE_AI_BASE_URL` | Lets AI providers use `http://` addresses and private or local network addresses, such as an Ollama server on your network. Without it, a provider's base URL must be public `https://`. || `FLAG_ALLOW_UNSAFE_OAUTH_REDIRECT_URI` | Lets MCP and OAuth clients that register themselves use any redirect address, including custom schemes and private hosts. By default a redirect must go to your instance's own address, an `http://` loopback address (`localhost`, `127.0.0.1`, `::1`) or a public `https://` address. |-| `FLAG_OLACV_SUGGESTION` | Suggests registering `<username>.cv` at OlaCV to people who haven't connected a custom domain. Needs custom domains to be on. |+| `FLAG_OLACV_SUGGESTION` | Suggests registering a `.cv` domain made from the account's username or name at OlaCV to people who haven't connected a custom domain. Needs custom domains to be on. With `OLACV_API_KEY`, only a name OlaCV reports as free and not premium is suggested, with its price. |<Warning>Only turn on the two `FLAG_ALLOW_UNSAFE_*` flags on an instance where you trust every user. On a shared instance, andiff --git a/docs/spec.json b/docs/spec.jsonindex f56f2ac5d..c2f57725e 100644--- a/docs/spec.json+++ b/docs/spec.json@@ -54679,6 +54679,36 @@"type": "string","description": "The TXT record's value."},+ "records": {+ "type": "array",+ "items": {+ "type": "object",+ "properties": {+ "type": {+ "enum": [+ "A",+ "AAAA",+ "CNAME",+ "TXT"+ ],+ "type": "string"+ },+ "name": {+ "type": "string",+ "description": "The record's full host name."+ },+ "value": {+ "type": "string"+ }+ },+ "required": [+ "type",+ "name",+ "value"+ ]+ },+ "description": "Every record to add: the TXT record, and a CNAME to the target, or for a root domain A and AAAA records with its addresses."+ },"verified": {"type": "boolean","description": "Whether DNS proved ownership and the domain opens the primary resume."@@ -54702,6 +54732,7 @@"target","txtName","txtValue",+ "records","verified","lastCheckedAt"]@@ -54876,6 +54907,36 @@"type": "string","description": "The TXT record's value."},+ "records": {+ "type": "array",+ "items": {+ "type": "object",+ "properties": {+ "type": {+ "enum": [+ "A",+ "AAAA",+ "CNAME",+ "TXT"+ ],+ "type": "string"+ },+ "name": {+ "type": "string",+ "description": "The record's full host name."+ },+ "value": {+ "type": "string"+ }+ },+ "required": [+ "type",+ "name",+ "value"+ ]+ },+ "description": "Every record to add: the TXT record, and a CNAME to the target, or for a root domain A and AAAA records with its addresses."+ },"verified": {"type": "boolean","description": "Whether DNS proved ownership and the domain opens the primary resume."@@ -54899,6 +54960,7 @@"target","txtName","txtValue",+ "records","verified","lastCheckedAt"]@@ -55252,6 +55314,36 @@"type": "string","description": "The TXT record's value."},+ "records": {+ "type": "array",+ "items": {+ "type": "object",+ "properties": {+ "type": {+ "enum": [+ "A",+ "AAAA",+ "CNAME",+ "TXT"+ ],+ "type": "string"+ },+ "name": {+ "type": "string",+ "description": "The record's full host name."+ },+ "value": {+ "type": "string"+ }+ },+ "required": [+ "type",+ "name",+ "value"+ ]+ },+ "description": "Every record to add: the TXT record, and a CNAME to the target, or for a root domain A and AAAA records with its addresses."+ },"verified": {"type": "boolean","description": "Whether DNS proved ownership and the domain opens the primary resume."@@ -55275,6 +55367,7 @@"target","txtName","txtValue",+ "records","verified","lastCheckedAt"]diff --git a/packages/api/src/features/custom-domain/router.ts b/packages/api/src/features/custom-domain/router.tsindex 3a170b9a9..5d483d2b6 100644--- a/packages/api/src/features/custom-domain/router.ts+++ b/packages/api/src/features/custom-domain/router.ts@@ -2,6 +2,7 @@ import z from "zod";import { protectedProcedure } from "../../context";import { accountRateLimit } from "../../middleware/rate-limit";import { customDomainService } from "./service";+import { suggestCvDomain } from "./suggestion";const route = { tags: ["Custom Domain"] };const errors = {@@ -13,11 +14,43 @@ const status = z.object({target: z.string().describe("The host the domain's CNAME record points at."),txtName: z.string().describe("Where the TXT record that proves ownership goes."),txtValue: z.string().describe("The TXT record's value."),+ records: z+ .array(+ z.object({+ type: z.enum(["A", "AAAA", "CNAME", "TXT"]),+ name: z.string().describe("The record's full host name."),+ value: z.string(),+ }),+ )+ .describe(+ "Every record to add: the TXT record, and a CNAME to the target, or for a root domain A and AAAA records with its addresses.",+ ),verified: z.boolean().describe("Whether DNS proved ownership and the domain opens the primary resume."),lastCheckedAt: z.date().nullable().describe("When DNS was last checked."),});export const customDomainRouter = {+ suggestion: protectedProcedure+ .route({ ...route, tags: ["Internal"], method: "GET", path: "/custom-domain/suggestion" })+ .input(z.object({}).optional())+ .use(accountRateLimit)+ .output(+ z+ .object({+ domain: z.string(),+ checked: z.boolean().describe("Whether OlaCV confirmed the domain is free to register."),+ price: z+ .object({+ amount: z.number().describe("The registration fee, for the first year."),+ renewal: z.number().nullable().describe("Each later year's fee, when OlaCV says."),+ currency: z.string(),+ })+ .nullable(),+ })+ .nullable(),+ )+ .handler(({ context }) => suggestCvDomain(context.user.id)),+get: protectedProcedure.route({...route,diff --git a/packages/api/src/features/custom-domain/service.ts b/packages/api/src/features/custom-domain/service.tsindex 179f4b9b9..c860064c6 100644--- a/packages/api/src/features/custom-domain/service.ts+++ b/packages/api/src/features/custom-domain/service.ts@@ -46,14 +46,39 @@ export function normalizeHostname(input: string): string | null {return ascii;}+const lookup = <T>(query: Promise<T[]>) => query.catch(() => [] as T[]);+const txtValue = (token: string) => `rx-verify=${token}`;-function toStatus(domain: typeof schema.customDomain.$inferSelect) {+export type DnsRecord = { type: "A" | "AAAA" | "CNAME" | "TXT"; name: string; value: string };++/**+ * What to add where the domain's DNS is managed: a TXT record proving ownership, and a CNAME to the target. A root+ * domain can't have a CNAME, so it gets A and AAAA records with the target's addresses instead.+ */+async function connectionRecords(hostname: string, token: string): Promise<DnsRecord[]> {+ const target = env.CUSTOM_DOMAIN_TARGET ?? "";+ const proof: DnsRecord = { type: "TXT", name: `${TXT_PREFIX}.${hostname}`, value: txtValue(token) };+ // ponytail: two labels is a root domain; one under a two-part suffix (example.co.uk) gets the CNAME, and the+ // client's note explains the addresses. A public-suffix list would tell them apart.+ if (hostname.split(".").length === 2) {+ const [v4, v6] = await Promise.all([lookup(resolve4(target)), lookup(resolve6(target))]);+ const addresses = [+ ...v4.map((value): DnsRecord => ({ type: "A", name: hostname, value })),+ ...v6.map((value): DnsRecord => ({ type: "AAAA", name: hostname, value })),+ ];+ if (addresses.length > 0) return [...addresses, proof];+ }+ return [{ type: "CNAME", name: hostname, value: target }, proof];+}++async function toStatus(domain: typeof schema.customDomain.$inferSelect) {return {hostname: domain.hostname,target: env.CUSTOM_DOMAIN_TARGET ?? "",txtName: `${TXT_PREFIX}.${domain.hostname}`,txtValue: txtValue(domain.verificationToken),+ records: await connectionRecords(domain.hostname, domain.verificationToken),verified: domain.verifiedAt !== null,lastCheckedAt: domain.lastCheckedAt,};@@ -67,8 +92,6 @@ const assertEnabled = () => {});};-const lookup = <T>(query: Promise<T[]>) => query.catch(() => [] as T[]);-/** Whether DNS proves `token`'s account owns `hostname` and points it at this server. */async function dnsPointsHere(hostname: string, token: string): Promise<boolean> {const target = env.CUSTOM_DOMAIN_TARGET;diff --git a/packages/api/src/features/custom-domain/suggestion.test.ts b/packages/api/src/features/custom-domain/suggestion.test.tsnew file mode 100644index 000000000..cf3198c14--- /dev/null+++ b/packages/api/src/features/custom-domain/suggestion.test.ts@@ -0,0 +1,71 @@+import { afterEach, describe, expect, it, vi } from "vite-plus/test";++const state = vi.hoisted(() => ({+ user: { username: "", name: "" },+ env: { FLAG_OLACV_SUGGESTION: true, OLACV_API_KEY: "token" as string | undefined },+}));+vi.mock("@reactive-resume/db/client", () => ({+ db: { select: () => ({ from: () => ({ where: async () => [state.user] }) }) },+}));+vi.mock("@reactive-resume/env/server", () => ({ env: state.env }));+vi.mock("./service", () => ({ isCustomDomainsEnabled: () => true }));++const { suggestCvDomain } = await import("./suggestion");++type Answer = {+ available: boolean;+ premium?: boolean;+ registration_fee?: number;+ renewal_fee?: number;+ currency?: string;+};+const olacv = (data: Record<string, Answer>) =>+ vi.stubGlobal("fetch", async () => Response.json({ data, message: "All domain check(s) completed successfully." }));++afterEach(() => {+ vi.unstubAllGlobals();+ state.env.OLACV_API_KEY = "token";+});++describe("suggestCvDomain", () => {+ it("suggests the first of the account's names that is free and not premium, with its price", async () => {+ state.user = { username: "amruth", name: "Amruth Pillai" };+ olacv({+ "amruth.cv": { available: true, premium: true, registration_fee: 67.5, renewal_fee: 10, currency: "USD" },+ "amruthpillai.cv": { available: false, premium: false, registration_fee: 10, currency: "USD" },+ "amruth-pillai.cv": { available: true, premium: false, registration_fee: 10, renewal_fee: 10, currency: "USD" },+ });+ expect(await suggestCvDomain("u1")).toEqual({+ domain: "amruth-pillai.cv",+ checked: true,+ price: { amount: 10, renewal: 10, currency: "USD" },+ });+ });++ it("skips a username that can't be a domain and folds accents out of the name", async () => {+ state.user = { username: "jose.n", name: "José Núñez" };+ olacv({ "josenunez.cv": { available: true }, "jose-nunez.cv": { available: true } });+ expect(await suggestCvDomain("u1")).toEqual({ domain: "josenunez.cv", checked: true, price: null });+ });++ it("suggests nothing when every name is taken", async () => {+ state.user = { username: "taken", name: "Taken" };+ olacv({ "taken.cv": { available: false } });+ expect(await suggestCvDomain("u1")).toBeNull();+ });++ it("suggests nothing when no name can be a domain", async () => {+ state.user = { username: "li_lei", name: "李雷" };+ expect(await suggestCvDomain("u1")).toBeNull();+ });++ it.each([+ ["OlaCV can't be reached", () => vi.stubGlobal("fetch", () => Promise.reject(new TypeError("fetch failed")))],+ ["OlaCV answers with an error", () => vi.stubGlobal("fetch", async () => new Response("", { status: 401 }))],+ ["there's no API key", () => (state.env.OLACV_API_KEY = undefined)],+ ])("suggests the username's domain unchecked when %s", async (_, arrange) => {+ state.user = { username: "unchecked", name: "Somebody Else" };+ arrange();+ expect(await suggestCvDomain("u1")).toEqual({ domain: "unchecked.cv", checked: false, price: null });+ });+});diff --git a/packages/api/src/features/custom-domain/suggestion.ts b/packages/api/src/features/custom-domain/suggestion.tsnew file mode 100644index 000000000..a13442ff8--- /dev/null+++ b/packages/api/src/features/custom-domain/suggestion.ts@@ -0,0 +1,116 @@+import { eq } from "drizzle-orm";+import z from "zod";+import { db } from "@reactive-resume/db/client";+import * as schema from "@reactive-resume/db/schema";+import { env } from "@reactive-resume/env/server";+import { cvDomainFor } from "@reactive-resume/resume/sharing";+import { isCustomDomainsEnabled } from "./service";++const CHECK_URL = "https://ola.cv/api/v1/domains/check";+// Availability changes only when someone registers a name, so a check is reused for a while and shared by accounts.+const CACHE_MS = 15 * 60_000;+const CACHE_LIMIT = 5_000;++const checkResponse = z.object({+ data: z.record(+ z.string(),+ z.object({+ available: z.boolean(),+ premium: z.boolean().optional(),+ registration_fee: z.coerce.number().optional(),+ renewal_fee: z.coerce.number().optional(),+ currency: z.string().optional(),+ }),+ ),+});++/** What registering costs; `renewal` is each later year, when OlaCV says. */+type Price = { amount: number; renewal: number | null; currency: string };+type Check = { available: boolean; premium: boolean; price: Price | null };++const cache = new Map<string, { check: Check; expires: number }>();++export type CvDomainSuggestion = {+ domain: string;+ /** OlaCV confirmed it's free to register. False when it couldn't be checked, so it only may be. */+ checked: boolean;+ price: Price | null;+};++/** The `.cv` names worth suggesting for an account, best first: its username, then its name joined and hyphenated. */+function cvCandidates(user: { username: string; name: string }): string[] {+ const words = user.name+ .normalize("NFKD")+ .replace(/\p{M}/gu, "")+ .toLowerCase()+ .split(/[^a-z0-9]+/)+ .filter(Boolean);+ const names = [user.username, words.join(""), words.join("-")].map(cvDomainFor);+ return [...new Set(names.filter((name): name is string => Boolean(name)))];+}++/** Asks OlaCV about the names not checked recently. `null` when OlaCV can't be reached or answers unexpectedly. */+async function checkDomains(domains: string[], token: string): Promise<Map<string, Check> | null> {+ const now = Date.now();+ const result = new Map<string, Check>();+ for (const domain of domains) {+ const hit = cache.get(domain);+ if (hit && hit.expires > now) result.set(domain, hit.check);+ }+ const missing = domains.filter((domain) => !result.has(domain));+ if (missing.length === 0) return result;++ try {+ const response = await fetch(CHECK_URL, {+ method: "POST",+ headers: { Accept: "application/json", "Content-Type": "application/json", Authorization: `Bearer ${token}` },+ body: JSON.stringify({ domains: missing }),+ signal: AbortSignal.timeout(5_000),+ });+ if (!response.ok) return null;+ const parsed = checkResponse.safeParse(await response.json());+ if (!parsed.success) return null;++ if (cache.size >= CACHE_LIMIT) cache.clear();+ for (const domain of missing) {+ const entry = parsed.data.data[domain];+ const check: Check = {+ available: entry?.available ?? false,+ premium: entry?.premium ?? false,+ price:+ entry?.registration_fee !== undefined && entry.currency+ ? { amount: entry.registration_fee, renewal: entry.renewal_fee ?? null, currency: entry.currency }+ : null,+ };+ cache.set(domain, { check, expires: now + CACHE_MS });+ result.set(domain, check);+ }+ return result;+ } catch {+ return null;+ }+}++/**+ * A `.cv` domain to suggest in Share: the first of the account's names that OlaCV says is free and not premium. Without+ * an API key, or when OlaCV doesn't answer, the username's name is suggested unchecked. `null` when nothing fits.+ */+export async function suggestCvDomain(userId: string): Promise<CvDomainSuggestion | null> {+ if (!env.FLAG_OLACV_SUGGESTION || !isCustomDomainsEnabled()) return null;+ const [user] = await db+ .select({ username: schema.user.username, name: schema.user.name })+ .from(schema.user)+ .where(eq(schema.user.id, userId));+ const candidates = user ? cvCandidates(user) : [];+ const first = candidates[0];+ if (!first) return null;++ const checks = env.OLACV_API_KEY ? await checkDomains(candidates, env.OLACV_API_KEY) : null;+ if (!checks) return { domain: first, checked: false, price: null };++ for (const domain of candidates) {+ const check = checks.get(domain);+ if (check?.available && !check.premium) return { domain, checked: true, price: check.price };+ }+ return null;+}diff --git a/packages/env/src/server.ts b/packages/env/src/server.tsindex 2c70aa56c..1e69d1354 100644--- a/packages/env/src/server.ts+++ b/packages/env/src/server.ts@@ -97,6 +97,8 @@ export const env = createEnv({.optional(),// Sent by Traefik's HTTP provider to read the custom domains' routers; at least 32 characters.CUSTOM_DOMAIN_PROVIDER_SECRET: z.string().min(32).optional(),+ // OlaCV API token: with FLAG_OLACV_SUGGESTION, Share checks which .cv names are free before suggesting one.+ OLACV_API_KEY: z.string().trim().min(1).optional(),SERVER_PORT: z.coerce.number().int().min(1).max(65535).default(3001),TRUSTED_PROXIES: commaList(z.string().refine((range) => {diff --git a/turbo.json b/turbo.jsonindex 9cdea2f41..8dfbff048 100644--- a/turbo.json+++ b/turbo.json@@ -312,6 +312,7 @@"FLAG_ALLOW_UNSAFE_OAUTH_REDIRECT_URI","FLAG_ALLOW_UNSAFE_AI_BASE_URL","FLAG_OLACV_SUGGESTION",+ "OLACV_API_KEY","AI_TEST_TIMEOUT_MS","AI_REQUEST_TIMEOUT_MS","STRICT_SCHEMA_CHECK",