Skip to content

Send files directly between devices over the internet - no cloud storage, no size limits.

Add Pro tier with anonymous account codes (#85)

Denis Lupookov25ca655fb580
diff --git a/apps/desktop/.env.example b/apps/desktop/.env.example
index f8bd1fc..372b044 100644
--- a/apps/desktop/.env.example
+++ b/apps/desktop/.env.example
@@ -12,3 +12,7 @@ VITE_DISCORD_WEBHOOK_URL=
VITE_WEB_URL=
RELAY_CONF_PUBKEY_HEX=
+
+# Base URL for the Pro entitlement API. Leave empty to use the default.
+# A custom origin is added to the renderer CSP automatically at build time.
+VITE_PRO_API_URL=
diff --git a/apps/desktop/src/electron/downloadLocation.ts b/apps/desktop/src/electron/downloadLocation.ts
deleted file mode 100644
index 59587b3..0000000
--- a/apps/desktop/src/electron/downloadLocation.ts
+++ /dev/null
@@ -1,49 +0,0 @@
-import { app } from 'electron'
-import { readFile, stat } from 'fs/promises'
-import path from 'path'
-import { writeFileViaTemp } from './writeFileViaTemp.js'
-
-interface StoredLocation {
- folder?: string
-}
-
-function storePath(): string {
- return path.join(app.getPath('userData'), 'download-location.json')
-}
-
-async function isDirectory(target: string): Promise<boolean> {
- try {
- return (await stat(target)).isDirectory()
- } catch {
- return false
- }
-}
-
-async function readStored(): Promise<string | null> {
- try {
- const parsed = JSON.parse(await readFile(storePath(), 'utf8')) as StoredLocation
- return typeof parsed.folder === 'string' && parsed.folder.length > 0 ? parsed.folder : null
- } catch {
- return null
- }
-}
-
-function osDownloadsDir(): string | null {
- try {
- return app.getPath('downloads')
- } catch {
- return null
- }
-}
-
-export async function getDownloadFolder(): Promise<string | null> {
- const saved = await readStored()
- if (saved && (await isDirectory(saved))) return saved
-
- const fallback = osDownloadsDir()
- return fallback && (await isDirectory(fallback)) ? fallback : null
-}
-
-export async function setDownloadFolder(folder: string): Promise<void> {
- await writeFileViaTemp(storePath(), JSON.stringify({ folder } satisfies StoredLocation))
-}
diff --git a/apps/desktop/src/electron/ipc.ts b/apps/desktop/src/electron/ipc.ts
index 88c8f2f..e74d81d 100644
--- a/apps/desktop/src/electron/ipc.ts
+++ b/apps/desktop/src/electron/ipc.ts
@@ -11,7 +11,16 @@ import { isMac } from 'which-runtime'
import { readdir, stat } from 'fs/promises'
import path from 'path'
import { isPathSafe, type TransferMethod } from '@altersend/core'
-import { getDownloadFolder, setDownloadFolder } from './downloadLocation.js'
+import {
+ clearAccountCode,
+ getDownloadFolder,
+ readAccountCode,
+ readAccountToken,
+ setDownloadFolder,
+ writeAccountCode,
+ writeAccountToken,
+ writeFileViaTemp
+} from './store/index.js'
import { setThemeSource, type ThemeSource } from './theme.js'
import type { DesktopRuntime } from './runtime.js'
import { setReportingEnabled } from './sentry.js'
@@ -209,6 +218,48 @@ export function registerIpcHandlers(runtime: DesktopRuntime) {
ipcMain.handle('app:getDownloadFolder', () => getDownloadFolder())
+ ipcMain.handle('account:getCode', () => readAccountCode())
+
+ ipcMain.handle('account:setCode', (_evt, code: string) => {
+ if (typeof code !== 'string' || !/^\d{16}$/.test(code)) {
+ throw new Error('account:setCode expects a normalised 16-digit code')
+ }
+ return writeAccountCode(code)
+ })
+
+ ipcMain.handle('account:clearCode', () => clearAccountCode())
+
+ ipcMain.handle('account:getToken', () => readAccountToken())
+
+ ipcMain.handle('account:setToken', (_evt, token: unknown) => {
+ if (token !== null && typeof token !== 'string') {
+ throw new Error('account:setToken expects a string or null')
+ }
+ return writeAccountToken(token)
+ })
+
+ ipcMain.handle('account:saveCode', async (evt, contents: string, defaultName: string) => {
+ if (!isPathSafe(defaultName) || path.basename(defaultName) !== defaultName) {
+ throw new Error('Refused: defaultName must be a bare file name')
+ }
+
+ const parentWindow = BrowserWindow.fromWebContents(evt.sender) ?? undefined
+ const startDir = await getDownloadFolder()
+ const dialogOptions = {
+ title: 'Save your Pro code',
+ defaultPath: startDir ? path.join(startDir, defaultName) : defaultName
+ }
+
+ const result = parentWindow
+ ? await dialog.showSaveDialog(parentWindow, dialogOptions)
+ : await dialog.showSaveDialog(dialogOptions)
+
+ if (result.canceled || !result.filePath) return null
+
+ await writeFileViaTemp(result.filePath, contents)
+ return result.filePath
+ })
+
ipcMain.handle('app:chooseDownloadFolder', async (evt) => {
const folder = await pickFolder(evt)
if (folder) await setDownloadFolder(folder)
diff --git a/apps/desktop/src/electron/preload.cjs b/apps/desktop/src/electron/preload.cjs
index d3891df..1bb7e24 100644
--- a/apps/desktop/src/electron/preload.cjs
+++ b/apps/desktop/src/electron/preload.cjs
@@ -30,6 +30,13 @@ contextBridge.exposeInMainWorld('bridge', {
},
getPathForFile: (file) => webUtils.getPathForFile(file),
getDownloadFolder: () => ipcRenderer.invoke('app:getDownloadFolder'),
+ getAccountCode: () => ipcRenderer.invoke('account:getCode'),
+ setAccountCode: (code) => ipcRenderer.invoke('account:setCode', code),
+ clearAccountCode: () => ipcRenderer.invoke('account:clearCode'),
+ getAccountToken: () => ipcRenderer.invoke('account:getToken'),
+ setAccountToken: (token) => ipcRenderer.invoke('account:setToken', token),
+ saveAccountCode: (contents, defaultName) =>
+ ipcRenderer.invoke('account:saveCode', contents, defaultName),
chooseDownloadFolder: () => ipcRenderer.invoke('app:chooseDownloadFolder'),
appRestart: () => ipcRenderer.invoke('app:restart'),
showInFolder: (filePath) => ipcRenderer.invoke('app:showInFolder', filePath),
diff --git a/apps/desktop/src/electron/runtime.ts b/apps/desktop/src/electron/runtime.ts
index cbb0dd2..202e303 100644
--- a/apps/desktop/src/electron/runtime.ts
+++ b/apps/desktop/src/electron/runtime.ts
@@ -10,8 +10,7 @@ import {
type TransferMethod,
type WorkerClient
} from '@altersend/core'
-import { writeFileViaTemp } from './writeFileViaTemp.js'
-import { migrateLegacyStore } from './migrateLegacyStore.js'
+import { migrateLegacyStore, writeFileViaTemp } from './store/index.js'
import { isMac, isLinux, isWindows } from 'which-runtime'
import { command, flag, sloppy } from 'paparam'
import { createRequire } from 'module'
diff --git a/apps/desktop/src/electron/store/accountStore.ts b/apps/desktop/src/electron/store/accountStore.ts
new file mode 100644
index 0000000..97eafa2
--- /dev/null
+++ b/apps/desktop/src/electron/store/accountStore.ts
@@ -0,0 +1,67 @@
+import { app, safeStorage } from 'electron'
+import { readFile, rm } from 'fs/promises'
+import path from 'path'
+import { writeFileViaTemp } from './writeFileViaTemp.js'
+
+function storePath(): string {
+ return path.join(app.getPath('userData'), 'pro-account')
+}
+
+function tokenPath(): string {
+ return path.join(app.getPath('userData'), 'pro-token')
+}
+
+function sealed(): boolean {
+ return app.isPackaged
+}
+
+function readSecret(raw: Buffer): string {
+ return sealed() ? safeStorage.decryptString(raw) : raw.toString('utf8')
+}
+
+function writeSecret(value: string): Buffer {
+ if (!sealed()) return Buffer.from(value, 'utf8')
+
+ if (!safeStorage.isEncryptionAvailable()) {
+ throw new Error('Refusing to store the account code: OS encryption is unavailable')
+ }
+
+ return safeStorage.encryptString(value)
+}
+
+const CODE_PATTERN = /^\d{16}$/
+
+export async function readAccountCode(): Promise<string | null> {
+ try {
+ const code = readSecret(await readFile(storePath())).trim()
+ return CODE_PATTERN.test(code) ? code : null
+ } catch {
+ return null
+ }
+}
+
+export async function writeAccountCode(code: string): Promise<void> {
+ await writeFileViaTemp(storePath(), writeSecret(code))
+}
+
+export async function readAccountToken(): Promise<string | null> {
+ try {
+ return readSecret(await readFile(tokenPath())).trim() || null
+ } catch {
+ return null
+ }
+}
+
+export async function writeAccountToken(token: string | null): Promise<void> {
+ if (!token) {
+ await rm(tokenPath(), { force: true })
+ return
+ }
+
+ await writeFileViaTemp(tokenPath(), writeSecret(token))
+}
+
+export async function clearAccountCode(): Promise<void> {
+ await rm(storePath(), { force: true })
+ await rm(tokenPath(), { force: true })
+}
diff --git a/apps/desktop/src/electron/store/createJsonStore.ts b/apps/desktop/src/electron/store/createJsonStore.ts
new file mode 100644
index 0000000..f49c2e9
--- /dev/null
+++ b/apps/desktop/src/electron/store/createJsonStore.ts
@@ -0,0 +1,34 @@
+import { app } from 'electron'
+import { readFile } from 'fs/promises'
+import path from 'path'
+import { writeFileViaTemp } from './writeFileViaTemp.js'
+
+export interface JsonStore<T> {
+ read(): Promise<T>
+ write(value: T): Promise<void>
+}
+
+export function createJsonStore<T extends object>(filename: string, fallback: T): JsonStore<T> {
+ let pending: Promise<unknown> = Promise.resolve()
+
+ const storePath = () => path.join(app.getPath('userData'), filename)
+
+ return {
+ async read() {
+ try {
+ const parsed = JSON.parse(await readFile(storePath(), 'utf8')) as Partial<T>
+ return { ...fallback, ...parsed }
+ } catch {
+ return fallback
+ }
+ },
+
+ write(value) {
+ const write = pending.then(() => writeFileViaTemp(storePath(), JSON.stringify(value)))
+ pending = write.catch((err) => {
+ console.warn(`[store] could not persist ${filename}`, err)
+ })
+ return write
+ }
+ }
+}
diff --git a/apps/desktop/src/electron/store/downloadLocation.ts b/apps/desktop/src/electron/store/downloadLocation.ts
new file mode 100644
index 0000000..5c7cd4e
--- /dev/null
+++ b/apps/desktop/src/electron/store/downloadLocation.ts
@@ -0,0 +1,37 @@
+import { app } from 'electron'
+import { stat } from 'fs/promises'
+import { createJsonStore } from './createJsonStore.js'
+
+interface StoredLocation {
+ folder: string | null
+}
+
+const store = createJsonStore<StoredLocation>('download-location.json', { folder: null })
+
+async function isDirectory(target: string): Promise<boolean> {
+ try {
+ return (await stat(target)).isDirectory()
+ } catch {
+ return false
+ }
+}
+
+function osDownloadsDir(): string | null {
+ try {
+ return app.getPath('downloads')
+ } catch {
+ return null
+ }
+}
+
+export async function getDownloadFolder(): Promise<string | null> {
+ const { folder } = await store.read()
+ if (folder && (await isDirectory(folder))) return folder
+
+ const fallback = osDownloadsDir()
+ return fallback && (await isDirectory(fallback)) ? fallback : null
+}
+
+export function setDownloadFolder(folder: string): Promise<void> {
+ return store.write({ folder })
+}
diff --git a/apps/desktop/src/electron/store/index.ts b/apps/desktop/src/electron/store/index.ts
new file mode 100644
index 0000000..8a7d43d
--- /dev/null
+++ b/apps/desktop/src/electron/store/index.ts
@@ -0,0 +1,11 @@
+export {
+ clearAccountCode,
+ readAccountCode,
+ readAccountToken,
+ writeAccountCode,
+ writeAccountToken
+} from './accountStore.js'
+export { createJsonStore } from './createJsonStore.js'
+export { getDownloadFolder, setDownloadFolder } from './downloadLocation.js'
+export { migrateLegacyStore } from './migrateLegacyStore.js'
+export { writeFileViaTemp } from './writeFileViaTemp.js'
diff --git a/apps/desktop/src/electron/migrateLegacyStore.ts b/apps/desktop/src/electron/store/migrateLegacyStore.ts
similarity index 100%
rename from apps/desktop/src/electron/migrateLegacyStore.ts
rename to apps/desktop/src/electron/store/migrateLegacyStore.ts
diff --git a/apps/desktop/src/electron/writeFileViaTemp.ts b/apps/desktop/src/electron/store/writeFileViaTemp.ts
similarity index 100%
rename from apps/desktop/src/electron/writeFileViaTemp.ts
rename to apps/desktop/src/electron/store/writeFileViaTemp.ts
diff --git a/apps/desktop/src/electron/theme.ts b/apps/desktop/src/electron/theme.ts
index 41b94fe..8ac6b8e 100644
--- a/apps/desktop/src/electron/theme.ts
+++ b/apps/desktop/src/electron/theme.ts
@@ -1,50 +1,31 @@
-import { app, nativeTheme } from 'electron'
-import { readFile } from 'fs/promises'
-import path from 'path'
+import { nativeTheme } from 'electron'
import { rawTokens } from '@altersend/components/theme/raw'
-import { writeFileViaTemp } from './writeFileViaTemp.js'
+import { createJsonStore } from './store/index.js'
export type ThemeSource = Electron.NativeTheme['themeSource']
interface StoredTheme {
- preference?: string
+ preference: ThemeSource
}
-function storePath(): string {
- return path.join(app.getPath('userData'), 'theme.json')
-}
+const store = createJsonStore<StoredTheme>('theme.json', { preference: 'system' })
function normalize(value: unknown): ThemeSource {
return value === 'light' || value === 'dark' ? value : 'system'
}
export async function loadThemeSource(): Promise<ThemeSource> {
- try {
- const parsed = JSON.parse(await readFile(storePath(), 'utf8')) as StoredTheme
- return normalize(parsed.preference)
- } catch {
- return 'system'
- }
+ return normalize((await store.read()).preference)
}
export function applyThemeSource(preference: ThemeSource): void {
nativeTheme.themeSource = preference
}
-let pendingWrite: Promise<unknown> = Promise.resolve()
-
export function setThemeSource(preference: ThemeSource): Promise<void> {
const normalized = normalize(preference)
applyThemeSource(normalized)
-
- const write = pendingWrite.then(() =>
- writeFileViaTemp(storePath(), JSON.stringify({ preference: normalized } satisfies StoredTheme))
- )
- pendingWrite = write.catch((error) => {
- console.warn('theme: could not persist preference', error)
- })
-
- return write
+ return store.write({ preference: normalized })
}
export function windowBackgroundColor(): string {
diff --git a/apps/desktop/src/renderer/api/bridgeApi.ts b/apps/desktop/src/renderer/api/bridgeApi.ts
index f61dac7..eb0f9c3 100644
--- a/apps/desktop/src/renderer/api/bridgeApi.ts
+++ b/apps/desktop/src/renderer/api/bridgeApi.ts
@@ -64,6 +64,24 @@ export const bridgeApi = {
async chooseDownloadFolder() {
return requireBridge().chooseDownloadFolder()
},
+ getAccountCode() {
+ return requireBridge().getAccountCode()
+ },
+ setAccountCode(code: string) {
+ return requireBridge().setAccountCode(code)
+ },
+ clearAccountCode() {
+ return requireBridge().clearAccountCode()
+ },
+ getAccountToken() {
+ return requireBridge().getAccountToken()
+ },
+ setAccountToken(token: string | null) {
+ return requireBridge().setAccountToken(token)
+ },
+ saveAccountCode(contents: string, defaultName: string) {
+ return requireBridge().saveAccountCode(contents, defaultName)
+ },
appRestart() {
return requireBridge().appRestart()
},
diff --git a/apps/desktop/src/renderer/components/HeroBackdrop/HeroBackdrop.tsx b/apps/desktop/src/renderer/components/HeroBackdrop/HeroBackdrop.tsx
new file mode 100644
index 0000000..2054b96
--- /dev/null
+++ b/apps/desktop/src/renderer/components/HeroBackdrop/HeroBackdrop.tsx
@@ -0,0 +1,41 @@
+import { heroBackdrop, type HeroBackdropStop } from '@altersend/components'
+
+const tint = (alpha: number) =>
+ `color-mix(in oklab, var(--as-color-info) ${alpha * 100}%, transparent)`
+
+const shade = (alpha: number) => `color-mix(in oklab, black ${alpha * 100}%, transparent)`
+
+const stops = (list: HeroBackdropStop[], color: (alpha: number) => string) =>
+ list.map((stop) => `${color(stop.alpha)} ${stop.offset * 100}%`).join(', ')
+
+const { glowCenter, maskCenter, gridSize, gridAlpha } = heroBackdrop
+
+const WASH = `linear-gradient(180deg, ${stops(heroBackdrop.wash, tint)})`
+
+const GLOW = `radial-gradient(${glowCenter.radiusX}% ${glowCenter.radiusY}% at ${glowCenter.x}% ${glowCenter.y}%, ${stops(heroBackdrop.glow, tint)})`
+
+const GRID = `linear-gradient(90deg, ${tint(gridAlpha)} 1px, transparent 1px), linear-gradient(180deg, ${tint(gridAlpha)} 1px, transparent 1px)`
+
+const GRID_MASK = `radial-gradient(${maskCenter.radiusX}% ${maskCenter.radiusY}% at ${maskCenter.x}% ${maskCenter.y}%, ${stops(heroBackdrop.mask, shade)})`
+
+export function HeroBackdrop({ height = heroBackdrop.height }: { height?: number }) {
+ return (
+ <div
+ aria-hidden
+ className='pointer-events-none absolute inset-x-0 top-0 overflow-hidden'
+ style={{ height }}
+ >
+ <div className='absolute inset-0' style={{ background: WASH }} />
+ <div className='absolute inset-0' style={{ background: GLOW }} />
+ <div
+ className='absolute inset-0'
+ style={{
+ backgroundImage: GRID,
+ backgroundSize: `${gridSize}px ${gridSize}px`,
+ maskImage: GRID_MASK,
+ WebkitMaskImage: GRID_MASK
+ }}
+ />
+ </div>
+ )
+}
diff --git a/apps/desktop/src/renderer/components/HeroBackdrop/index.ts b/apps/desktop/src/renderer/components/HeroBackdrop/index.ts
new file mode 100644
index 0000000..7193d4c
--- /dev/null
+++ b/apps/desktop/src/renderer/components/HeroBackdrop/index.ts
@@ -0,0 +1 @@
+export * from './HeroBackdrop'
diff --git a/apps/desktop/src/renderer/components/Settings/index.tsx b/apps/desktop/src/renderer/components/Settings/index.tsx
index 1d1f0bd..89e0afb 100644
--- a/apps/desktop/src/renderer/components/Settings/index.tsx
+++ b/apps/desktop/src/renderer/components/Settings/index.tsx
@@ -5,23 +5,53 @@ import {
LaptopIcon,
MailIcon,
SlidersHorizontalIcon,
+ ArrowUpCircleIcon,
+ UserIcon,
WaypointsIcon,
type IconProps
} from '@altersend/components/icons'
-import { loadPeers } from '@altersend/domain'
+import { loadPeers, useSubscriptionStore } from '@altersend/domain'
import { useTranslation } from '@altersend/locales'
import { ListItem, Modal } from '@altersend/components'
import { DevicesSection } from './sections/DevicesSection'
import { GeneralSection } from './sections/GeneralSection'
import { LanguageSection } from './sections/LanguageSection'
import { ConnectionSection } from './sections/ConnectionSection'
+import { AccountRoute } from './sections/AccountRoute'
import { FeedbackSection } from './sections/FeedbackSection'
import { AboutSection } from './sections/AboutSection'
import { subscribeOpenSettings, type SettingsSection } from './settingsControl'
export { openSettingsPanel } from './settingsControl'
-const NAV: { id: SettingsSection; icon: ComponentType<IconProps>; labelKey: string }[] = [
+function renderSection(section: SettingsSection, version: string) {
+ switch (section) {
+ case 'devices':
+ return <DevicesSection />
+ case 'general':
+ return <GeneralSection />
+ case 'language':
+ return <LanguageSection />
+ case 'connection':
+ return <ConnectionSection />
+ case 'account':
+ return <AccountRoute />
+ case 'feedback':
+ return <FeedbackSection version={version} />
+ case 'about':
+ return <AboutSection version={version} />
+ }
+}
+
+type NavEntry = { id: SettingsSection; icon: ComponentType<IconProps>; labelKey: string }
+
+const ACCOUNT_NAV: NavEntry = {
+ id: 'account',
+ icon: UserIcon,
+ labelKey: 'settings:account.title'
+}
+
+const NAV: NavEntry[] = [
{ id: 'devices', icon: LaptopIcon, labelKey: 'settings:pairing.pairedDevices' },
{ id: 'general', icon: SlidersHorizontalIcon, labelKey: 'settings:sections.general' },
{ id: 'language', icon: GlobeIcon, labelKey: 'settings:languageTitle' },
@@ -34,6 +64,8 @@ export function Settings({ version }: { version: string }) {
const { t } = useTranslation(['settings', 'common'])
const [open, setOpen] = useState(false)
const [section, setSection] = useState<SettingsSection>('devices')
+ const isPro = useSubscriptionStore((state) => state.active)
+ const nav = isPro ? [ACCOUNT_NAV, ...NAV] : NAV
useEffect(() => {
if (open) loadPeers()
@@ -58,7 +90,7 @@ export function Settings({ version }: { version: string }) {
>
<div className='flex h-[560px] border-t border-border-primary'>
<nav className='w-[210px] shrink-0 space-y-1 overflow-y-auto border-r border-border-primary px-2.5 pb-2.5 pt-5'>
- {NAV.map(({ id, icon: Icon, labelKey }) => (
+ {nav.map(({ id, icon: Icon, labelKey }) => (
<ListItem
key={id}
icon={<Icon size={16} />}
@@ -67,22 +99,23 @@ export function Settings({ version }: { version: string }) {
onClick={() => setSection(id)}
/>
))}
+
+ {isPro ? null : (
+ <>
+ <div className='my-2 h-px bg-border-primary' />
+
+ <ListItem
+ icon={<ArrowUpCircleIcon size={16} />}
+ label={t('settings:account.upgradeToPro')}
+ active={section === 'account'}
+ onClick={() => setSection('account')}
+ />
+ </>
+ )}
</nav>
<div className='flex min-h-0 min-w-0 flex-1 flex-col'>
- {section === 'devices' ? (
- <DevicesSection />
- ) : section === 'general' ? (
- <GeneralSection />
- ) : section === 'language' ? (
- <LanguageSection />
- ) : section === 'connection' ? (
- <ConnectionSection />
- ) : section === 'feedback' ? (
- <FeedbackSection version={version} />
- ) : (
- <AboutSection version={version} />
- )}
+ {renderSection(section, version)}
</div>
</div>
</Modal>
diff --git a/apps/desktop/src/renderer/components/Settings/sections/AccountRoute.tsx b/apps/desktop/src/renderer/components/Settings/sections/AccountRoute.tsx
new file mode 100644
index 0000000..c7b5ffe
--- /dev/null
+++ b/apps/desktop/src/renderer/components/Settings/sections/AccountRoute.tsx
@@ -0,0 +1,15 @@
+import { useAccount, useSubscriptionStore } from '@altersend/domain'
+import { accountAdapter } from '../../../lifecycle/account'
+import { AccountSection } from './AccountSection'
+import { ActiveAccountSection } from './ActiveAccountSection'
+
+export function AccountRoute() {
+ const isPro = useSubscriptionStore((state) => state.active)
+ const model = useAccount(accountAdapter)
+
+ const settled = model.phase !== 'paywall'
+
+ if (model.phase === 'active' || (isPro && !settled)) return <ActiveAccountSection model={model} />
+
+ return <AccountSection model={model} />
+}
diff --git a/apps/desktop/src/renderer/components/Settings/sections/AccountSection.tsx b/apps/desktop/src/renderer/components/Settings/sections/AccountSection.tsx
new file mode 100644
index 0000000..4ecbe27
--- /dev/null
+++ b/apps/desktop/src/renderer/components/Settings/sections/AccountSection.tsx
@@ -0,0 +1,30 @@
+import type { ReactElement } from 'react'
+import { useTranslation } from '@altersend/locales'
+import type { AccountModel, AccountPhase } from '@altersend/domain'
+import {
+ CheckoutWaiting,
+ CodeEntry,
+ Paywall,
+ PurchaseSuccess,
+ type AccountPhaseProps
+} from './account'
+
+type PhaseScreen = (props: AccountPhaseProps) => ReactElement | null
+
+const SCREENS: Record<Exclude<AccountPhase, 'active'>, PhaseScreen> = {
+ paywall: Paywall,
+ entering: CodeEntry,
+ approval: CheckoutWaiting,
+ waiting: CheckoutWaiting,
+ success: PurchaseSuccess
+}
+
+export function AccountSection({ model }: { model: AccountModel }) {
+ const { t } = useTranslation(['settings'])
+
+ if (model.phase === 'active') return null
+
+ const Screen = SCREENS[model.phase]
+
+ return <Screen model={model} errorText={model.errorKey && t(model.errorKey)} />
+}
diff --git a/apps/desktop/src/renderer/components/Settings/sections/ActiveAccountSection.tsx b/apps/desktop/src/renderer/components/Settings/sections/ActiveAccountSection.tsx
new file mode 100644
index 0000000..6778f89
--- /dev/null
+++ b/apps/desktop/src/renderer/components/Settings/sections/ActiveAccountSection.tsx
@@ -0,0 +1,121 @@
+import { useState } from 'react'
+import { AccountCodeCard, Button, LinkRow, Spinner } from '@altersend/components'
+import { ChevronRightIcon } from '@altersend/components/icons'
+
+import { useTranslation } from '@altersend/locales'
+import { formatAccountCode, useCopiedFlag } from '@altersend/domain'
+import type { AccountModel } from '@altersend/domain'
+import { ConfirmDialog } from '../../ConfirmDialog'
+import { useToast } from '../../Toast'
+import { SectionShell } from './SectionShell'
+
+const COPY_ID = 'account-code'
+
+export function ActiveAccountSection({ model }: { model: AccountModel }) {
+ const { t, i18n } = useTranslation(['settings', 'common', 'send'])
+ const { copiedId, flashCopied } = useCopiedFlag()
+ const toast = useToast()
+ const [confirmLogOut, setConfirmLogOut] = useState(false)
+
+ const account = model.account
+ const errorText = model.errorKey && t(model.errorKey)
+
+ if (!account) {
+ return (
+ <SectionShell title={t('settings:account.title')}>
+ <div className='mt-2 flex items-center gap-3'>
+ <Spinner size={18} />
+ </div>
+ </SectionShell>
+ )
+ }
+
+ const copyCode = async (): Promise<boolean> => {
+ try {
+ await navigator.clipboard.writeText(formatAccountCode(account.code))
+ } catch {
+ return false
+ }
+
+ flashCopied(COPY_ID)
+ toast.show({ title: t('send:connection.copiedToast') })
+
+ return true
+ }
+
+ const planSummary = account.validUntil
+ ? t('settings:account.subscriptionValue', {
+ plan: t('settings:account.planPro'),
+ date: new Date(account.validUntil).toLocaleDateString(
+ i18n.resolvedLanguage ?? i18n.language,
+ { month: 'short', day: 'numeric', year: 'numeric' }
+ )
+ })
+ : t('settings:account.planPro')
+
+ const footer = (
+ <div className='flex items-center justify-end gap-2'>
+ <Button
+ size='sm'
+ variant='danger'
+ disabled={model.busy}
+ onClick={() => setConfirmLogOut(true)}
+ >
+ {t('settings:account.logOut')}
+ </Button>
+ </div>
+ )
+
+ return (
+ <SectionShell title={t('settings:account.title')} footer={footer}>
+ <div className='mt-1 overflow-hidden rounded-2xl border border-border-primary bg-background-subtle'>
+ <AccountCodeCard
+ attached
+ hidden
+ inline
+ code={account.code}
+ label={t('settings:account.yourCode')}
+ copyLabel={t('common:actions.copy')}
+ copiedLabel={t('settings:account.copied')}
+ revealLabel={t('settings:account.reveal')}
+ hideLabel={t('settings:account.hide')}
+ copied={copiedId === COPY_ID}
+ onCopy={copyCode}
+ />
+
+ <div className='h-px bg-border-primary' />
+
+ <LinkRow
+ isLast
+ label={t('settings:account.subscriptionRow')}
+ trailing={
+ <div className='flex items-center gap-2'>
+ <span className='text-[14px] text-text-muted'>{planSummary}</span>
+ <ChevronRightIcon size={14} />
+ </div>
+ }
+ onPress={model.subscription.manage}
+ />
+ </div>
+
+ {errorText ? <p className='m-0 mt-4 text-[12px] text-text-danger'>{errorText}</p> : null}
+
+ <ConfirmDialog
+ destructive
+ open={confirmLogOut}
+ title={t('settings:account.logOutTitle')}
+ message={t('settings:account.logOutBody', { code: formatAccountCode(account.code) })}
+ confirmLabel={t('settings:account.copyAndLogOut')}
+ cancelLabel={t('common:actions.cancel')}
+ onConfirm={() => {
+ setConfirmLogOut(false)
+ copyCode().then((copied) => {
+ if (copied) model.subscription.logOut()
+ else toast.show({ title: t('settings:account.copyFailed'), variant: 'error' })
+ })
+ }}
+ onCancel={() => setConfirmLogOut(false)}
+ />
+ </SectionShell>
+ )
+}
diff --git a/apps/desktop/src/renderer/components/Settings/sections/SectionShell.tsx b/apps/desktop/src/renderer/components/Settings/sections/SectionShell.tsx
index 2a8b64b..9c49ef5 100644
--- a/apps/desktop/src/renderer/components/Settings/sections/SectionShell.tsx
+++ b/apps/desktop/src/renderer/components/Settings/sections/SectionShell.tsx
@@ -3,21 +3,31 @@ import type { ReactNode } from 'react'
export function SectionShell({
title,
action,
+ backdrop,
+ leading,
children,
footer
}: {
- title: string
+ title?: string
action?: ReactNode
+ backdrop?: ReactNode
+ leading?: ReactNode
children: ReactNode
footer?: ReactNode
}) {
return (
- <div className='flex h-full min-h-0 flex-col'>
- <div className='flex shrink-0 items-center justify-between gap-3 px-6 pb-3 pt-5'>
- <h2 className='m-0 text-[16px] font-semibold text-text-primary'>{title}</h2>
- {action}
- </div>
- <div className='min-h-0 flex-1 overflow-y-auto px-6 pb-6'>{children}</div>
+ <div className='relative flex h-full min-h-0 flex-col'>
+ {backdrop}
+ {(title || action || leading) && (
+ <div className='relative flex shrink-0 items-center justify-between gap-3 px-6 pb-3 pt-5'>
+ <div className='flex min-w-0 items-center gap-2'>
+ {leading}
+ <h2 className='m-0 truncate text-[16px] font-semibold text-text-primary'>{title}</h2>
+ </div>
+ {action}
+ </div>
+ )}
+ <div className='relative min-h-0 flex-1 overflow-y-auto px-6 pb-6'>{children}</div>
{footer && (
<div className='relative shrink-0 border-t border-border-primary px-6 py-4'>{footer}</div>
)}
diff --git a/apps/desktop/src/renderer/components/Settings/sections/account/CheckoutWaiting.tsx b/apps/desktop/src/renderer/components/Settings/sections/account/CheckoutWaiting.tsx
new file mode 100644
index 0000000..16e5f0f
--- /dev/null
+++ b/apps/desktop/src/renderer/components/Settings/sections/account/CheckoutWaiting.tsx
@@ -0,0 +1,40 @@
+import { Button, WaitingState } from '@altersend/components'
+import { GlobeIcon } from '@altersend/components/icons'
+import { useTranslation } from '@altersend/locales'
+import { SectionShell } from '../SectionShell'
+import type { AccountPhaseProps } from './types'
+
+export function CheckoutWaiting({ model, errorText }: AccountPhaseProps) {
+ const { t } = useTranslation(['settings'])
+ const viaStore = Boolean(model.store)
+
+ const footer = (
+ <div className='flex items-center justify-end gap-2'>
+ <Button size='sm' variant='ghost' disabled={model.busy} onClick={model.cancelUpgrade}>
+ {t('settings:account.cancel')}
+ </Button>
+ <Button size='sm' variant='secondary' disabled={model.busy} onClick={model.retryUpgrade}>
+ {t('settings:account.checkAgain')}
+ </Button>
+ </div>
+ )
+
+ return (
+ <SectionShell footer={footer}>
+ <div className='flex h-full min-h-0 flex-col items-center justify-center'>
+ <WaitingState
+ icon={<GlobeIcon size={30} />}
+ title={t(
+ viaStore ? 'settings:account.waitingTitleStore' : 'settings:account.waitingTitle'
+ )}
+ description={t(
+ viaStore ? 'settings:account.waitingBodyStore' : 'settings:account.waitingBody'
+ )}
+ />
+ {errorText ? (
+ <p className='m-0 mt-4 text-center text-[12px] text-text-danger'>{errorText}</p>
+ ) : null}
+ </div>
+ </SectionShell>
+ )
+}
diff --git a/apps/desktop/src/renderer/components/Settings/sections/account/CodeEntry.tsx b/apps/desktop/src/renderer/components/Settings/sections/account/CodeEntry.tsx
new file mode 100644
index 0000000..2f6a19b
--- /dev/null
+++ b/apps/desktop/src/renderer/components/Settings/sections/account/CodeEntry.tsx
@@ -0,0 +1,73 @@
+import { Button, Input } from '@altersend/components'
+import { ArrowLeftIcon, ClipboardIcon } from '@altersend/components/icons'
+import { useTranslation } from '@altersend/locales'
+import { ACCOUNT_CODE_DISPLAY_LENGTH } from '@altersend/domain'
+import { bridgeApi } from '../../../../api/bridgeApi'
+import { SectionShell } from '../SectionShell'
+import type { AccountPhaseProps } from './types'
+
+export function CodeEntry({ model, errorText }: AccountPhaseProps) {
+ const { t } = useTranslation(['settings', 'common'])
+
+ const paste = () => {
+ bridgeApi
+ .clipboardReadText()
+ .then(model.setEntry)
+ .catch((err) => console.warn('[account] clipboard read failed', err))
+ }
+
+ const footer = (
+ <div className='flex items-center justify-end'>
+ <Button
+ size='sm'
+ variant='primary'
+ loading={model.busy}
+ disabled={!model.codeReady}
+ onClick={model.activate}
+ >
+ {t('settings:account.activate')}
+ </Button>
+ </div>
+ )
+
+ const backButton = (
+ <Button
+ size='sm'
+ variant='ghost'
+ iconOnly
+ aria-label={t('settings:account.back')}
+ icon={<ArrowLeftIcon size={16} />}
+ disabled={model.busy}
+ onClick={model.showPaywall}
+ />
+ )
+
+ return (
+ <SectionShell title={t('settings:account.enterCodeTitle')} leading={backButton} footer={footer}>
+ <Input
+ mono
+ aria-label={t('settings:account.enterCodeTitle')}
+ inputMode='numeric'
+ maxLength={ACCOUNT_CODE_DISPLAY_LENGTH}
+ autoComplete='off'
+ spellCheck={false}
+ disabled={model.busy}
+ error={errorText ?? undefined}
+ value={model.entry}
+ placeholder={t('settings:account.codePlaceholder')}
+ trailing={
+ <Button
+ variant='ghost'
+ size='sm'
+ iconOnly
+ aria-label={t('common:actions.paste')}
+ disabled={model.busy}
+ icon={<ClipboardIcon size={16} />}
+ onClick={paste}
+ />
+ }
+ onChange={(e: { target: { value: string } }) => model.setEntry(e.target.value)}
+ />
+ </SectionShell>
+ )
+}
diff --git a/apps/desktop/src/renderer/components/Settings/sections/account/Paywall.tsx b/apps/desktop/src/renderer/components/Settings/sections/account/Paywall.tsx
new file mode 100644
index 0000000..5db9e36
--- /dev/null
+++ b/apps/desktop/src/renderer/components/Settings/sections/account/Paywall.tsx
@@ -0,0 +1,94 @@
+import { Button, Tabs, TabsList, TabsTrigger } from '@altersend/components'
+import { useTranslation } from '@altersend/locales'
+import { BILLING_PLANS, planComparisonRows, planLabel, type BillingPlan } from '@altersend/domain'
+import { HeroBackdrop } from '../../../HeroBackdrop'
+import { SectionShell } from '../SectionShell'
+import { PlanCellValue } from './PlanCellValue'
+import type { AccountPhaseProps } from './types'
+
+const COLUMNS = 'grid grid-cols-[minmax(0,1fr)_72px_104px] items-center gap-x-4'
+const FREE_CHECK_SIZE = 15
+const PRO_CHECK_SIZE = 17
+
+export function Paywall({ model, errorText }: AccountPhaseProps) {
+ const { t } = useTranslation(['settings', 'common'])
+ const rows = planComparisonRows(t)
+
+ const footer = (
+ <div className='flex items-center justify-between gap-3'>
+ <Button size='sm' variant='ghost' disabled={model.busy} onClick={model.showEntry}>
+ {t('settings:account.haveCodeLink')}
+ </Button>
+ <Button size='sm' variant='primary' loading={model.busy} onClick={model.startUpgrade}>
+ {t('settings:account.getPro')}
+ </Button>
+ </div>
+ )
+
+ return (
+ <SectionShell backdrop={<HeroBackdrop />} footer={footer}>
+ <h2 className='m-0 mt-6 text-[30px] font-bold leading-tight tracking-[-0.6px] text-text-primary'>
+ {t('settings:account.paywallTitle')}
+ </h2>
+ <p className='m-0 mt-1.5 text-[15px] leading-[21px] text-text-secondary'>
+ {t('settings:account.paywallLead')}
+ </p>
+
+ <div className='mt-6'>
+ <Tabs
+ size='sm'
+ stretch
+ value={model.plan}
+ onValueChange={(next) => model.choosePlan(next as BillingPlan)}
+ >
+ <TabsList>
+ {BILLING_PLANS.map((option) => (
+ <TabsTrigger key={option} value={option}>
+ {planLabel(option, t, model.prices)}
+ </TabsTrigger>
+ ))}
+ </TabsList>
+ </Tabs>
+ </div>
+
+ <div className='relative mt-7'>
+ <div className='pointer-events-none absolute inset-y-0 right-0 w-[104px] rounded-2xl border border-border-primary bg-background-subtle' />
+
+ <div className={`${COLUMNS} relative py-3`}>
+ <span className='text-[15px] font-semibold text-text-primary'>
+ {t('settings:account.included')}
+ </span>
+ <span className='text-center text-[13px] font-semibold text-text-muted'>
+ {t('settings:account.columnFree')}
+ </span>
+ <span className='justify-self-center rounded-lg bg-surface-primary px-3 py-1.5 text-[13px] font-semibold text-text-primary'>
+ {t('settings:account.columnPro')}
+ </span>
+ </div>
+
+ {rows.map((row, index) => (
+ <div
+ key={row.label}
+ className={`${COLUMNS} relative py-4 ${index === rows.length - 1 ? 'pb-6' : ''}`}
+ >
+ <span className='text-[14px] leading-[19px] text-text-secondary'>{row.label}</span>
+ <PlanCellValue
+ cell={row.free}
+ className='block text-center text-[14px] text-text-muted'
+ size={FREE_CHECK_SIZE}
+ tone='muted'
+ />
+ <PlanCellValue
+ cell={row.pro}
+ className='block text-center text-[16px] font-semibold text-text-primary'
+ size={PRO_CHECK_SIZE}
+ tone='primary'
+ />
+ </div>
+ ))}
+ </div>
+
+ {errorText ? <p className='m-0 mt-4 text-[12px] text-text-danger'>{errorText}</p> : null}
+ </SectionShell>
+ )
+}
diff --git a/apps/desktop/src/renderer/components/Settings/sections/account/PlanCellValue.tsx b/apps/desktop/src/renderer/components/Settings/sections/account/PlanCellValue.tsx
new file mode 100644
index 0000000..277e1c6
--- /dev/null
+++ b/apps/desktop/src/renderer/components/Settings/sections/account/PlanCellValue.tsx
@@ -0,0 +1,25 @@
+import { useTheme } from '@altersend/components'
+import { CheckIcon } from '@altersend/components/icons'
+import type { PlanCell } from '@altersend/domain'
+
+interface Props {
+ cell: PlanCell
+ className: string
+ size: number
+ tone: 'muted' | 'primary'
+}
+
+export function PlanCellValue({ cell, className, size, tone }: Props) {
+ const { theme } = useTheme()
+ const c = theme.colors
+
+ if (cell.type === 'check') {
+ return (
+ <span className='flex justify-center'>
+ <CheckIcon size={size} color={tone === 'muted' ? c.colorTextMuted : c.colorTextPrimary} />
+ </span>
+ )
+ }
+
+ return <span className={className}>{cell.value}</span>
+}
diff --git a/apps/desktop/src/renderer/components/Settings/sections/account/PurchaseSuccess.tsx b/apps/desktop/src/renderer/components/Settings/sections/account/PurchaseSuccess.tsx
new file mode 100644
index 0000000..9934e36
--- /dev/null
+++ b/apps/desktop/src/renderer/components/Settings/sections/account/PurchaseSuccess.tsx
@@ -0,0 +1,113 @@
+import { useState } from 'react'
+import { AccountCodeCard, Button, SuccessBurst, useTheme } from '@altersend/components'
+import { CheckIcon } from '@altersend/components/icons'
+import { useTranslation } from '@altersend/locales'
+import {
+ ACCOUNT_CODE_FILE_NAME,
+ accountCodeFile,
+ formatAccountCode,
+ useCopiedFlag
+} from '@altersend/domain'
+import { bridgeApi } from '../../../../api/bridgeApi'
+import { ConfirmDialog } from '../../../ConfirmDialog'
+import { SectionShell } from '../SectionShell'
+import type { AccountPhaseProps } from './types'
+
+const COPY_ID = 'account-code'
+const SAVE_ID = 'account-code-file'
+const BURST_SIZE = 72
+
+export function PurchaseSuccess({ model }: AccountPhaseProps) {
+ const { t, i18n } = useTranslation(['settings', 'common'])
+ const { copiedId, flashCopied } = useCopiedFlag()
+ const [confirmDone, setConfirmDone] = useState(false)
+ const { theme } = useTheme()
+ const c = theme.colors
+
+ if (!model.account) return null
+
+ const code = model.account.code
+
+ const saveCode = () => {
+ if (!model.account) return
+
+ const contents = accountCodeFile(
+ model.account.code,
+ new Date().toLocaleDateString(i18n.resolvedLanguage ?? i18n.language),
+ {
+ title: t('settings:account.codeFileTitle'),
+ codeLabel: t('settings:account.codeFileCode'),
+ savedLabel: t('settings:account.codeFileSaved'),
+ warning: t('settings:account.codeFileWarning')
+ }
+ )
+
+ bridgeApi
+ .saveAccountCode(contents, ACCOUNT_CODE_FILE_NAME)
+ .then((saved) => {
+ if (saved) flashCopied(SAVE_ID)
+ })
+ .catch((err) => console.warn('[account] saving the code failed', err))
+ }
+
+ const copyCode = () => {
+ if (!code) return
+ navigator.clipboard
+ .writeText(formatAccountCode(code))
+ .then(() => flashCopied(COPY_ID))
+ .catch((err) => console.warn('[account] clipboard write failed', err))
+ }
+
+ const footer = (
+ <div className='flex items-center justify-end'>
+ <Button size='sm' variant='primary' onClick={() => setConfirmDone(true)}>
+ {t('settings:account.done')}
+ </Button>
+ </div>
+ )
+
+ return (
+ <SectionShell footer={footer}>
+ <div className='flex flex-col items-center'>
+ <SuccessBurst
+ size={BURST_SIZE}
+ markColor={c.colorSuccess}
+ tones={[c.colorAccent, c.colorInfo, c.colorSuccess, c.colorWarning]}
+ icon={<CheckIcon size={32} color={c.colorBackground} />}
+ />
+ <h2 className='m-0 -mt-6 text-center text-[28px] font-bold leading-tight tracking-[-0.5px] text-text-primary'>
+ {t('settings:account.successTitle')}
+ </h2>
+ </div>
+
+ <p className='m-0 mx-auto mt-3 max-w-[420px] text-center text-[14px] leading-[20px] text-text-secondary'>
+ {t('settings:account.saveWarning')}
+ </p>
+
+ <div className='mt-6'>
+ <AccountCodeCard
+ code={model.account.code}
+ label={t('settings:account.yourCode')}
+ copyLabel={t('common:actions.copy')}
+ copiedLabel={t('settings:account.copied')}
+ saveLabel={t('settings:account.saveCode')}
+ savedLabel={t('settings:account.codeFileSaved')}
+ copied={copiedId === COPY_ID}
+ saved={copiedId === SAVE_ID}
+ onCopy={copyCode}
+ onSave={saveCode}
+ />
+ </div>
+
+ <ConfirmDialog
+ open={confirmDone}
+ title={t('settings:account.savedCodeTitle')}
+ message={t('settings:account.savedCodeBody')}
+ confirmLabel={t('settings:account.savedCodeConfirm')}
+ cancelLabel={t('common:actions.cancel')}
+ onConfirm={model.acknowledge}
+ onCancel={() => setConfirmDone(false)}
+ />
+ </SectionShell>
+ )
+}
diff --git a/apps/desktop/src/renderer/components/Settings/sections/account/index.ts b/apps/desktop/src/renderer/components/Settings/sections/account/index.ts
new file mode 100644
index 0000000..1d13da8
--- /dev/null
+++ b/apps/desktop/src/renderer/components/Settings/sections/account/index.ts
@@ -0,0 +1,5 @@
+export { CheckoutWaiting } from './CheckoutWaiting'
+export { CodeEntry } from './CodeEntry'
+export { Paywall } from './Paywall'
+export { PurchaseSuccess } from './PurchaseSuccess'
+export type { AccountPhaseProps } from './types'
diff --git a/apps/desktop/src/renderer/components/Settings/sections/account/types.ts b/apps/desktop/src/renderer/components/Settings/sections/account/types.ts
new file mode 100644
index 0000000..c1d54ca
--- /dev/null
+++ b/apps/desktop/src/renderer/components/Settings/sections/account/types.ts
@@ -0,0 +1,6 @@
+import type { AccountModel } from '@altersend/domain'
+
+export interface AccountPhaseProps {
+ model: AccountModel
+ errorText: string | null
+}
diff --git a/apps/desktop/src/renderer/components/Settings/settingsControl.ts b/apps/desktop/src/renderer/components/Settings/settingsControl.ts
index e745174..720bb80 100644
--- a/apps/desktop/src/renderer/components/Settings/settingsControl.ts
+++ b/apps/desktop/src/renderer/components/Settings/settingsControl.ts
@@ -3,6 +3,7 @@ export type SettingsSection =
| 'general'
| 'language'
| 'connection'
+ | 'account'
| 'feedback'
| 'about'
diff --git a/apps/desktop/src/renderer/index.html b/apps/desktop/src/renderer/index.html
index 3d7353a..a4cc495 100644
--- a/apps/desktop/src/renderer/index.html
+++ b/apps/desktop/src/renderer/index.html
@@ -5,7 +5,7 @@
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta
http-equiv="Content-Security-Policy"
- content="default-src 'self'; script-src 'self'; worker-src 'self' blob:; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob: file:; font-src 'self' data:; connect-src 'self' https://*.ingest.sentry.io https://*.ingest.de.sentry.io https://*.ingest.us.sentry.io;"
+ content="default-src 'self'; script-src 'self'; worker-src 'self' blob:; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob: file:; font-src 'self' data:; connect-src 'self' https://api.altersend.com https://*.ingest.sentry.io https://*.ingest.de.sentry.io https://*.ingest.us.sentry.io;"
/>
<title>AlterSend</title>
</head>
diff --git a/apps/desktop/src/renderer/lifecycle/account.ts b/apps/desktop/src/renderer/lifecycle/account.ts
new file mode 100644
index 0000000..58cc2f5
--- /dev/null
+++ b/apps/desktop/src/renderer/lifecycle/account.ts
@@ -0,0 +1,30 @@
+import { accountApiUrl, createAccountRuntime, type AccountStorage } from '@altersend/domain'
+import { bridgeApi } from '../api/bridgeApi'
+import { isRelayEnabled } from './relayStorage'
+
+const accountStorage: AccountStorage = {
+ read: () => bridgeApi.getAccountCode(),
+ write: (code) => bridgeApi.setAccountCode(code),
+ clear: () => bridgeApi.clearAccountCode(),
+ readToken: () => bridgeApi.getAccountToken(),
+ writeToken: (token) => bridgeApi.setAccountToken(token)
+}
+
+const runtime = createAccountRuntime({
+ baseUrl: (import.meta.env.VITE_PRO_API_URL as string | undefined) || accountApiUrl,
+ storage: accountStorage,
+ openUrl: (url) => bridgeApi.openExternalUrl(url),
+ applyToken: async (proToken) => {
+ await bridgeApi.worker.setRelayConfig({ enabled: isRelayEnabled(), proToken })
+ }
+})
+
+export const accountAdapter = runtime.adapter
+const warnSync = (err: unknown) => console.warn('[account] focus sync failed', err)
+
+export function startAccountSync(): void {
+ runtime.startSync()
+ window.addEventListener('focus', () => {
+ runtime.syncTokenIfStale().catch(warnSync)
+ })
+}
diff --git a/apps/desktop/src/renderer/main.tsx b/apps/desktop/src/renderer/main.tsx
index ff45090..c1736f1 100644
--- a/apps/desktop/src/renderer/main.tsx
+++ b/apps/desktop/src/renderer/main.tsx
@@ -27,6 +27,7 @@ import { startDeepLinkHandler } from './lifecycle/deepLinkHandler'
import { initSentry, captureException } from './sentry'
import { isCrashReportingEnabled } from './lifecycle/crashReportingStorage'
import { isRelayEnabled } from './lifecycle/relayStorage'
+import { startAccountSync } from './lifecycle/account'
import { getSavedLocalePreference } from './lifecycle/localePreferenceStorage'
import { getSavedThemePreference, setSavedThemePreference } from './lifecycle/themeStorage'
import { getDesktopSystemLocales } from './lifecycle/systemLocale'
@@ -94,6 +95,7 @@ if (hasBridge()) {
bridgeApi.worker
.setRelayConfig({ enabled: isRelayEnabled() })
.catch((err) => captureException(err, 'setRelayConfig'))
+ startAccountSync()
startPeerWatchdog()
startBackgroundReconnectEffect()
startDeepLinkHandler()
diff --git a/apps/desktop/src/renderer/pages/SendPage/CopyLinkButton.tsx b/apps/desktop/src/renderer/pages/SendPage/CopyLinkButton.tsx
index eaadfd0..e0fa5a2 100644
--- a/apps/desktop/src/renderer/pages/SendPage/CopyLinkButton.tsx
+++ b/apps/desktop/src/renderer/pages/SendPage/CopyLinkButton.tsx
@@ -2,14 +2,16 @@ import { useTranslation } from '@altersend/locales'
import { Button, useTheme } from '@altersend/components'
import { CheckIcon, LinkIcon } from '@altersend/components/icons'
import { WEB_LINK_MAX_LABEL } from '@altersend/domain'
+import { openSettingsPanel } from '../../components/Settings/settingsControl'
interface CopyLinkButtonProps {
topic: string
copied: boolean
+ locked?: boolean
onCopy: () => void
}
-export function CopyLinkButton({ topic, copied, onCopy }: CopyLinkButtonProps) {
+export function CopyLinkButton({ topic, copied, locked = false, onCopy }: CopyLinkButtonProps) {
const { t } = useTranslation(['send', 'common'])
const { theme } = useTheme()
const label = copied ? t('common:actions.copied') : t('send:connection.shareLink')
@@ -23,7 +25,7 @@ export function CopyLinkButton({ topic, copied, onCopy }: CopyLinkButtonProps) {
aria-label={t('send:connection.copyLink')}
tooltip={label}
tooltipDescription={
- copied ? undefined : t('send:connection.linkHint', { limit: WEB_LINK_MAX_LABEL })
+ locked ? t('send:connection.linkHint', { limit: WEB_LINK_MAX_LABEL }) : undefined
}
tooltipSide='left'
disabled={!topic}
@@ -34,7 +36,7 @@ export function CopyLinkButton({ topic, copied, onCopy }: CopyLinkButtonProps) {
<LinkIcon size={18} />
)
}
- onClick={onCopy}
+ onClick={locked ? () => openSettingsPanel('account') : onCopy}
/>
</div>
)
diff --git a/apps/desktop/src/renderer/pages/SendPage/ShareView.tsx b/apps/desktop/src/renderer/pages/SendPage/ShareView.tsx
index 7b1b7f5..b3202da 100644
--- a/apps/desktop/src/renderer/pages/SendPage/ShareView.tsx
+++ b/apps/desktop/src/renderer/pages/SendPage/ShareView.tsx
@@ -3,6 +3,7 @@ import {
buildJoinUrl,
buildWebReceiveUrl,
exceedsWebLinkLimit,
+ useSubscriptionStore,
formatFileSize,
formatItemsCount,
formatTextSnippetPreview,
@@ -52,7 +53,8 @@ export function ShareView() {
const [isQrOpen, setIsQrOpen] = useState(false)
const { copiedId, flashCopied } = useCopiedFlag()
const hasConnectedDevices = vm.connectedCount > 0
- const webLinkTooLarge = exceedsWebLinkLimit(vm.totalSize)
+ const pro = useSubscriptionStore((state) => state.active)
+ const webLinkTooLarge = exceedsWebLinkLimit(vm.totalSize, pro)
const fileRows = groupSelectedFiles(vm.files)
const singleFolder = fileRows.length === 1 && fileRows[0].kind === 'folder' ? fileRows[0] : null
@@ -146,13 +148,12 @@ export function ShareView() {
onCopy={() => void copyTopic()}
placeholder={t('send:connection.placeholder')}
/>
- {!webLinkTooLarge && (
- <CopyLinkButton
- topic={vm.topic}
- copied={copiedId === 'link'}
- onCopy={() => void copyLink()}
- />
- )}
+ <CopyLinkButton
+ topic={vm.topic}
+ copied={copiedId === 'link'}
+ locked={webLinkTooLarge}
+ onCopy={() => void copyLink()}
+ />
<div className='flex h-12 w-12 shrink-0'>
<Button
variant='secondary'
@@ -215,13 +216,12 @@ export function ShareView() {
onCopy={() => void copyTopic()}
placeholder={t('send:connection.placeholder')}
/>
- {!webLinkTooLarge && (
- <CopyLinkButton
- topic={vm.topic}
- copied={copiedId === 'link'}
- onCopy={() => void copyLink()}
- />
- )}
+ <CopyLinkButton
+ topic={vm.topic}
+ copied={copiedId === 'link'}
+ locked={webLinkTooLarge}
+ onCopy={() => void copyLink()}
+ />
</div>
{vm.hasDevices && filesCard}
</div>
diff --git a/apps/desktop/src/types.d.ts b/apps/desktop/src/types.d.ts
index 90f8484..1a7c881 100644
--- a/apps/desktop/src/types.d.ts
+++ b/apps/desktop/src/types.d.ts
@@ -71,6 +71,12 @@ declare global {
getPathForFile: (file: File) => string
getDownloadFolder: () => Promise<string | null>
chooseDownloadFolder: () => Promise<string | null>
+ getAccountCode: () => Promise<string | null>
+ setAccountCode: (code: string) => Promise<void>
+ clearAccountCode: () => Promise<void>
+ getAccountToken: () => Promise<string | null>
+ setAccountToken: (token: string | null) => Promise<void>
+ saveAccountCode: (contents: string, defaultName: string) => Promise<string | null>
appRestart: () => Promise<unknown>
onDeepLink: (cb: (url: string) => void) => () => void
onRuntimeUpdated: (cb: () => void) => () => void
diff --git a/apps/desktop/vite.config.ts b/apps/desktop/vite.config.ts
index 17daea4..03a6347 100644
--- a/apps/desktop/vite.config.ts
+++ b/apps/desktop/vite.config.ts
@@ -1,9 +1,19 @@
-import { defineConfig } from 'vite'
+import { defineConfig, loadEnv } from 'vite'
import react from '@vitejs/plugin-react'
import tailwindcss from '@tailwindcss/vite'
import viteBabel from 'vite-plugin-babel'
import { join, resolve } from 'path'
+function originOf(url: string | undefined): string | null {
+ if (!url) return null
+
+ try {
+ return new URL(url).origin
+ } catch {
+ throw new Error(`VITE_PRO_API_URL is not a valid url: ${url}`)
+ }
+}
+
export default defineConfig(async ({ mode }) => {
const workspaceRoot = resolve(__dirname, '../..')
const dev = mode !== 'production'
@@ -59,8 +69,19 @@ export default defineConfig(async ({ mode }) => {
}
}
+ const apiOrigin = originOf(loadEnv(mode, __dirname, 'VITE_').VITE_PRO_API_URL)
+
+ const cspPlugin = {
+ name: 'csp-api-origin',
+ transformIndexHtml(html: string) {
+ if (!apiOrigin) return html
+ return html.replace('connect-src ', `connect-src ${apiOrigin} `)
+ }
+ }
+
return {
plugins: [
+ cspPlugin,
react({
babel: {
configFile: resolve(__dirname, 'babel.config.cjs')
diff --git a/apps/mobile/.env.example b/apps/mobile/.env.example
index 2c0daf2..8a88431 100644
--- a/apps/mobile/.env.example
+++ b/apps/mobile/.env.example
@@ -4,3 +4,8 @@ EXPO_PUBLIC_SENTRY_DSN=
EXPO_PUBLIC_RELAY_CONF_PUBKEY=
EXPO_PUBLIC_WEB_URL=
+
+EXPO_PUBLIC_PRO_API_URL=
+
+EXPO_PUBLIC_REVENUECAT_IOS_KEY=
+EXPO_PUBLIC_REVENUECAT_ANDROID_KEY=
diff --git a/apps/mobile/app.json b/apps/mobile/app.json
index 678ed5f..d8aba7b 100644
--- a/apps/mobile/app.json
+++ b/apps/mobile/app.json
@@ -53,6 +53,14 @@
"NSPrivacyCollectedDataTypePurposes": [
"NSPrivacyCollectedDataTypePurposeAppFunctionality"
]
+ },
+ {
+ "NSPrivacyCollectedDataType": "NSPrivacyCollectedDataTypePurchaseHistory",
+ "NSPrivacyCollectedDataTypeLinked": false,
+ "NSPrivacyCollectedDataTypeTracking": false,
+ "NSPrivacyCollectedDataTypePurposes": [
+ "NSPrivacyCollectedDataTypePurposeAppFunctionality"
+ ]
}
]
},
diff --git a/apps/mobile/app/(tabs)/send/index.tsx b/apps/mobile/app/(tabs)/send/index.tsx
index 530387e..d3d909b 100644
--- a/apps/mobile/app/(tabs)/send/index.tsx
+++ b/apps/mobile/app/(tabs)/send/index.tsx
@@ -16,6 +16,8 @@ import {
} from '@altersend/domain'
import { continueShare, exceedsFileCountLimit } from '@altersend/domain'
+const SEND_FLOW_PATHS = new Set(['/send', '/send/preparing', '/send/share'])
+
function NavigationController() {
const router = useRouter()
const pathname = usePathname()
@@ -27,6 +29,7 @@ function NavigationController() {
const target =
step === 'preparing' ? '/send/preparing' : isShareStep(step) ? '/send/share' : '/send'
+ if (!SEND_FLOW_PATHS.has(pathname)) return
if (pathname === target) return
if (target === '/send/preparing') {
diff --git a/apps/mobile/app/_layout.tsx b/apps/mobile/app/_layout.tsx
index 848b65f..6703ca7 100644
--- a/apps/mobile/app/_layout.tsx
+++ b/apps/mobile/app/_layout.tsx
@@ -11,7 +11,8 @@ import {
startBackgroundReconnectEffect,
startDownloadRetryEffect,
startPeerWatchdog,
- useSimulatedLoading
+ useSimulatedLoading,
+ useSubscriptionStore
} from '@altersend/domain'
import {
getLocaleFontFamily,
@@ -29,6 +30,7 @@ import { LoadingScreen } from '../src/loading'
import { SafeAreaProvider } from 'react-native-safe-area-context'
import { mobileApi } from '../src/api/mobileApi'
import { ToastProvider } from '../src/components/Toast'
+import { AccountProvider } from '../src/account'
import { UpdateBanner } from '../src/components/UpdateBanner'
import { PairRequestBanner } from '../src/components/PairRequestBanner'
import { InviteBanner } from '../src/components/InviteBanner'
@@ -43,6 +45,9 @@ import {
setSavedThemePreference
} from '../src/lifecycle/themePreferenceStorage'
import { isRelayEnabled } from '../src/lifecycle/relayStorage'
+import { startAccountSync, syncAccountToken } from '../src/lifecycle/account'
+import { watchEntitlement } from '../src/lifecycle/purchases'
+import { UpgradeButton } from '@/src/components'
import { getMobileSystemLocales } from '../src/lifecycle/systemLocale'
import { ShareIntentHandler } from '../src/lifecycle/ShareIntentHandler'
import { startDownloadRoutingEffect } from '../src/transfer/receive'
@@ -57,6 +62,10 @@ bindTransferApi(mobileApi, {
mobileApi.worker
.setRelayConfig({ enabled: isRelayEnabled() })
.catch((err) => captureException(err, 'setRelayConfig'))
+watchEntitlement(() => {
+ syncAccountToken().catch((err) => console.warn('[account] entitlement sync failed', err))
+})
+startAccountSync()
startAppStateBridge()
startPeerWatchdog()
startBackgroundReconnectEffect()
@@ -117,6 +126,7 @@ function ThemedStack() {
const titledScreenOptions = getTitledScreenOptions(theme, fontFamilyName)
const progress = useSimulatedLoading()
const statusBarStyle = themeType === ThemeType.Light ? 'dark' : 'light'
+ const isPro = useSubscriptionStore((state) => state.active)
useEffect(() => {
SystemUI.setBackgroundColorAsync(theme.colors.colorBackground).catch((error) =>
@@ -137,7 +147,11 @@ function ThemedStack() {
<Stack.Screen name='onboarding' options={{ headerShown: false, gestureEnabled: false }} />
<Stack.Screen
name='settings'
- options={{ ...titledScreenOptions, title: t('settings:title') }}
+ options={{
+ ...titledScreenOptions,
+ title: t('settings:title'),
+ headerRight: isPro ? undefined : () => <UpgradeButton />
+ }}
/>
<Stack.Screen
name='language'
@@ -151,6 +165,18 @@ function ThemedStack() {
name='connection'
options={{ ...titledScreenOptions, title: t('settings:rows.connection') }}
/>
+ <Stack.Screen
+ name='account'
+ options={{
+ headerShown: false,
+ presentation: 'fullScreenModal',
+ animation: 'slide_from_bottom'
+ }}
+ />
+ <Stack.Screen
+ name='subscription'
+ options={{ ...titledScreenOptions, title: t('settings:account.title') }}
+ />
<Stack.Screen
name='devices'
options={{ ...titledScreenOptions, title: t('settings:pairing.pairedDevices') }}
@@ -205,11 +231,13 @@ function AppShell() {
}}
>
<ToastProvider>
- <ShareIntentHandler />
- <ThemedStack />
- <UpdateBanner />
- <PairRequestBanner />
- <InviteBanner />
+ <AccountProvider>
+ <ShareIntentHandler />
+ <ThemedStack />
+ <UpdateBanner />
+ <PairRequestBanner />
+ <InviteBanner />
+ </AccountProvider>
</ToastProvider>
</ErrorBoundary>
</ThemeProvider>
diff --git a/apps/mobile/app/account.tsx b/apps/mobile/app/account.tsx
new file mode 100644
index 0000000..e7f0db3
--- /dev/null
+++ b/apps/mobile/app/account.tsx
@@ -0,0 +1,45 @@
+import { useEffect } from 'react'
+import { useTranslation } from '@altersend/locales'
+import type { AccountPhase } from '@altersend/domain'
+import { useRouter } from 'expo-router'
+import {
+ ApprovalWaiting,
+ CheckoutWaiting,
+ CodeEntry,
+ Paywall,
+ PurchaseSuccess,
+ useAccountModel,
+ type AccountPhaseProps
+} from '@/src/account'
+
+type PhaseScreen = (props: AccountPhaseProps) => React.ReactElement | null
+
+const SCREENS: Record<Exclude<AccountPhase, 'active'>, PhaseScreen> = {
+ paywall: Paywall,
+ entering: CodeEntry,
+ approval: ApprovalWaiting,
+ waiting: CheckoutWaiting,
+ success: PurchaseSuccess
+}
+
+export default function AccountScreen() {
+ const { t } = useTranslation(['settings'])
+ const model = useAccountModel()
+ const router = useRouter()
+
+ useEffect(() => {
+ if (model.phase === 'active') router.back()
+ }, [model.phase, router])
+
+ if (model.phase === 'active') return null
+
+ const Screen = SCREENS[model.phase]
+
+ return (
+ <Screen
+ model={model}
+ errorText={model.errorKey && t(model.errorKey)}
+ onDismiss={() => router.back()}
+ />
+ )
+}
diff --git a/apps/mobile/app/settings.tsx b/apps/mobile/app/settings.tsx
index 1e44b55..e210859 100644
--- a/apps/mobile/app/settings.tsx
+++ b/apps/mobile/app/settings.tsx
@@ -2,7 +2,7 @@ import { useCallback, useEffect, useState } from 'react'
import { StyleSheet, View } from 'react-native'
import { useFocusEffect, useRouter } from 'expo-router'
import { LOCALE_OPTIONS, useTranslation, type LocalePreference } from '@altersend/locales'
-import { loadPeers, useTransferStore } from '@altersend/domain'
+import { loadPeers, useSubscriptionStore, useTransferStore } from '@altersend/domain'
import {
AppearancePicker,
MenuGroup,
@@ -17,6 +17,7 @@ import {
MailIcon,
SlidersHorizontalIcon,
SmartphoneIcon,
+ UserIcon,
WaypointsIcon
} from '@altersend/components/icons'
import { Layout } from '@/src/components'
@@ -35,6 +36,7 @@ export default function SettingsScreen() {
getLocalePreferenceSnapshot
)
const peers = useTransferStore((s) => s.peers)
+ const isPro = useSubscriptionStore((s) => s.active)
useEffect(() => {
void loadPeers()
@@ -71,6 +73,17 @@ export default function SettingsScreen() {
return (
<Layout hasNativeHeader>
<View style={styles.container}>
+ {isPro ? (
+ <MenuGroup>
+ <MenuItem
+ isLast
+ label={t('settings:account.title')}
+ icon={<UserIcon size={19} color={c.colorTextSecondary} />}
+ onPress={() => router.push('/subscription')}
+ />
+ </MenuGroup>
+ ) : null}
+
<MenuGroup title={t('settings:sections.general')}>
<MenuItem
label={t('settings:pairing.pairedDevices')}
diff --git a/apps/mobile/app/subscription.tsx b/apps/mobile/app/subscription.tsx
new file mode 100644
index 0000000..27d96c7
--- /dev/null
+++ b/apps/mobile/app/subscription.tsx
@@ -0,0 +1,136 @@
+import { useEffect, useRef, useState } from 'react'
+import { StyleSheet, View } from 'react-native'
+import { AccountCodeCard, Button, MenuItem, Spinner, useTheme } from '@altersend/components'
+import { LogOutIcon } from '@altersend/components/icons'
+import { useTranslation } from '@altersend/locales'
+import { formatAccountCode } from '@altersend/domain'
+import { useRouter } from 'expo-router'
+import { ConfirmDialog, Layout } from '@/src/components'
+import { useToast } from '@/src/components/Toast'
+import { useAccountModel } from '@/src/account'
+import { selectionTap } from '@/src/account/haptics'
+import { useCopyAccountCode } from '@/src/account/useCopyAccountCode'
+
+export default function SubscriptionScreen() {
+ const { t, i18n } = useTranslation(['settings', 'common', 'send'])
+ const { theme } = useTheme()
+ const c = theme.colors
+ const toast = useToast()
+ const router = useRouter()
+ const model = useAccountModel()
+ const { copied, copyCode } = useCopyAccountCode(model.account?.code, () =>
+ toast.show({ title: t('send:connection.copiedToast') })
+ )
+ const [confirmLogOut, setConfirmLogOut] = useState(false)
+ const wasActive = useRef(false)
+
+ const { errorKey, clearError, phase, account } = model
+
+ useEffect(() => {
+ if (!errorKey) return
+ toast.show({ title: t(errorKey), tone: 'error' })
+ clearError()
+ }, [errorKey, clearError, toast, t])
+
+ useEffect(() => {
+ if (phase === 'active') {
+ wasActive.current = true
+ return
+ }
+ if (wasActive.current) router.back()
+ }, [phase, router])
+
+ if (!account) {
+ return (
+ <Layout hasNativeHeader>
+ <View style={styles.loading}>
+ <Spinner size={18} color={c.colorTextMuted} />
+ </View>
+ </Layout>
+ )
+ }
+
+ const footer = (
+ <View style={styles.footer}>
+ <Button
+ size='lg'
+ variant='danger'
+ width='full'
+ icon={<LogOutIcon size={16} />}
+ disabled={model.busy}
+ onClick={() => setConfirmLogOut(true)}
+ >
+ {t('settings:account.logOut')}
+ </Button>
+ </View>
+ )
+
+ const planSummary = account.validUntil
+ ? t('settings:account.subscriptionValue', {
+ plan: t('settings:account.planPro'),
+ date: new Date(account.validUntil).toLocaleDateString(
+ i18n.resolvedLanguage ?? i18n.language,
+ { month: 'short', day: 'numeric' }
+ )
+ })
+ : t('settings:account.planPro')
+
+ return (
+ <Layout hasNativeHeader footer={footer}>
+ <View
+ style={[
+ styles.group,
+ { borderColor: c.colorBorderPrimary, backgroundColor: c.colorBackgroundSubtle }
+ ]}
+ >
+ <AccountCodeCard
+ attached
+ hidden
+ code={account.code}
+ label={t('settings:account.yourCode')}
+ copyLabel={t('common:actions.copy')}
+ copiedLabel={t('settings:account.copied')}
+ revealLabel={t('settings:account.reveal')}
+ hideLabel={t('settings:account.hide')}
+ copied={copied}
+ onCopy={copyCode}
+ onToggleReveal={selectionTap}
+ />
+
+ <View style={[styles.divider, { backgroundColor: c.colorBorderPrimary }]} />
+
+ <MenuItem
+ isLast
+ label={t('settings:account.subscriptionRow')}
+ value={planSummary}
+ disabled={model.busy}
+ onPress={model.subscription.manage}
+ />
+ </View>
+
+ <ConfirmDialog
+ destructive
+ open={confirmLogOut}
+ title={t('settings:account.logOutTitle')}
+ message={t('settings:account.logOutBody', { code: formatAccountCode(account.code) })}
+ confirmLabel={t('settings:account.copyAndLogOut')}
+ cancelLabel={t('common:actions.cancel')}
+ onConfirm={() => {
+ setConfirmLogOut(false)
+ copyCode().then((copied) => {
+ if (copied) model.subscription.logOut()
+ else toast.show({ title: t('settings:account.copyFailed'), tone: 'error' })
+ })
+ }}
+ onCancel={() => setConfirmLogOut(false)}
+ />
+ </Layout>
+ )
+}
+
+const styles = StyleSheet.create({
+ group: { borderWidth: 1, borderRadius: 16, overflow: 'hidden' },
+ divider: { height: StyleSheet.hairlineWidth },
+ loading: { alignItems: 'center', paddingTop: 32 },
+ footer: { gap: 10 }
+})
diff --git a/apps/mobile/package.json b/apps/mobile/package.json
index 5611809..3d14e30 100644
--- a/apps/mobile/package.json
+++ b/apps/mobile/package.json
@@ -39,7 +39,7 @@
"@altersend/core": "1.8.0",
"@altersend/domain": "1.8.0",
"@altersend/locales": "1.8.0",
- "@expo/ui": "~56.0.24",
+ "@expo/ui": "~56.0.25",
"@expo/vector-icons": "^15.0.2",
"@sentry/react-native": "^8.21.0",
"b4a": "^1.6.7",
@@ -48,6 +48,7 @@
"expo-camera": "~56.0.8",
"expo-clipboard": "~56.0.4",
"expo-constants": "~56.0.22",
+ "expo-crypto": "~56.0.4",
"expo-document-picker": "~56.0.4",
"expo-file-system": "~56.0.8",
"expo-font": "~56.0.7",
@@ -68,6 +69,7 @@
"react-native": "0.85.3",
"react-native-b4a": "^0.0.4",
"react-native-bare-kit": "^0.14.0",
+ "react-native-purchases": "^10.7.0",
"react-native-qrcode-svg": "^6.3.1",
"react-native-safe-area-context": "~5.7.0",
"react-native-screens": "~4.26.0",
diff --git a/apps/mobile/src/account/AccountProvider.tsx b/apps/mobile/src/account/AccountProvider.tsx
new file mode 100644
index 0000000..07e68cd
--- /dev/null
+++ b/apps/mobile/src/account/AccountProvider.tsx
@@ -0,0 +1,17 @@
+import { createContext, useContext, type ReactNode } from 'react'
+import { useAccount, type AccountModel } from '@altersend/domain'
+import { accountAdapter } from '@/src/lifecycle/account'
+
+const AccountContext = createContext<AccountModel | null>(null)
+
+export function AccountProvider({ children }: { children: ReactNode }) {
+ const model = useAccount(accountAdapter)
+ return <AccountContext.Provider value={model}>{children}</AccountContext.Provider>
+}
+
+export function useAccountModel(): AccountModel {
+ const model = useContext(AccountContext)
+ if (!model) throw new Error('useAccountModel must be used within AccountProvider')
+
+ return model
+}
diff --git a/apps/mobile/src/account/ApprovalWaiting.tsx b/apps/mobile/src/account/ApprovalWaiting.tsx
new file mode 100644
index 0000000..b3e3b80
--- /dev/null
+++ b/apps/mobile/src/account/ApprovalWaiting.tsx
@@ -0,0 +1,28 @@
+import { StyleSheet, View } from 'react-native'
+import { WaitingState } from '@altersend/components'
+import { ArrowUpCircleIcon } from '@altersend/components/icons'
+import { useTranslation } from '@altersend/locales'
+import { Layout } from '@/src/components'
+import { DismissRow } from './DismissRow'
+import type { AccountPhaseProps } from './types'
+
+export function ApprovalWaiting({ onDismiss }: AccountPhaseProps) {
+ const { t } = useTranslation(['settings'])
+
+ return (
+ <Layout compactTop>
+ <DismissRow onDismiss={onDismiss} />
+ <View style={styles.centre}>
+ <WaitingState
+ icon={<ArrowUpCircleIcon size={30} />}
+ title={t('settings:account.approvalTitle')}
+ description={t('settings:account.approvalBody')}
+ />
+ </View>
+ </Layout>
+ )
+}
+
+const styles = StyleSheet.create({
+ centre: { flex: 1, alignItems: 'center', justifyContent: 'center' }
+})
diff --git a/apps/mobile/src/account/CheckoutWaiting.tsx b/apps/mobile/src/account/CheckoutWaiting.tsx
new file mode 100644
index 0000000..8c8ab82
--- /dev/null
+++ b/apps/mobile/src/account/CheckoutWaiting.tsx
@@ -0,0 +1,74 @@
+import { useEffect, useState } from 'react'
+import { StyleSheet, View } from 'react-native'
+import { Button, useTheme, WaitingState } from '@altersend/components'
+import { ArrowUpCircleIcon, GlobeIcon } from '@altersend/components/icons'
+import { useTranslation } from '@altersend/locales'
+import { Layout } from '@/src/components'
+import { Text } from '@/src/components/ThemedText'
+import { DismissRow } from './DismissRow'
+import type { AccountPhaseProps } from './types'
+
+const RECOVERY_DELAY_MS = 15000
+
+export function CheckoutWaiting({ model, errorText, onDismiss }: AccountPhaseProps) {
+ const { t } = useTranslation(['settings'])
+ const { theme } = useTheme()
+
+ const viaStore = Boolean(model.store)
+ const [recoveryVisible, setRecoveryVisible] = useState(!viaStore)
+
+ useEffect(() => {
+ if (!viaStore) return
+ const timer = setTimeout(() => setRecoveryVisible(true), RECOVERY_DELAY_MS)
+ return () => clearTimeout(timer)
+ }, [viaStore])
+
+ const footer = recoveryVisible ? (
+ <View style={styles.footer}>
+ <Button
+ size='lg'
+ variant='secondary'
+ width='full'
+ disabled={model.busy}
+ onClick={model.retryUpgrade}
+ >
+ {t('settings:account.checkAgain')}
+ </Button>
+ <Button
+ size='sm'
+ variant='ghost'
+ width='full'
+ disabled={model.busy}
+ onClick={model.cancelUpgrade}
+ >
+ {t('settings:account.cancel')}
+ </Button>
+ </View>
+ ) : undefined
+
+ return (
+ <Layout compactTop footer={footer}>
+ <DismissRow onDismiss={onDismiss} />
+ <View style={styles.centre}>
+ <WaitingState
+ icon={viaStore ? <ArrowUpCircleIcon size={30} /> : <GlobeIcon size={30} />}
+ title={t(
+ viaStore ? 'settings:account.waitingTitleStore' : 'settings:account.waitingTitle'
+ )}
+ description={t(
+ viaStore ? 'settings:account.waitingBodyStore' : 'settings:account.waitingBody'
+ )}
+ />
+ {errorText ? (
+ <Text style={[styles.error, { color: theme.colors.colorDanger }]}>{errorText}</Text>
+ ) : null}
+ </View>
+ </Layout>
+ )
+}
+
+const styles = StyleSheet.create({
+ centre: { flex: 1, alignItems: 'center', justifyContent: 'center' },
+ footer: { gap: 10 },
+ error: { fontSize: 13, lineHeight: 18, marginTop: 12, textAlign: 'center' }
+})
diff --git a/apps/mobile/src/account/CodeEntry.tsx b/apps/mobile/src/account/CodeEntry.tsx
new file mode 100644
index 0000000..4671624
--- /dev/null
+++ b/apps/mobile/src/account/CodeEntry.tsx
@@ -0,0 +1,114 @@
+import { StyleSheet, View } from 'react-native'
+import * as Clipboard from 'expo-clipboard'
+import { Button, Input, useTheme } from '@altersend/components'
+import { ClipboardIcon } from '@altersend/components/icons'
+import { useTranslation } from '@altersend/locales'
+import { ACCOUNT_CODE_DISPLAY_LENGTH } from '@altersend/domain'
+import { HeroBackdrop, Layout } from '@/src/components'
+import { IconButton } from '@/src/components/IconButton'
+import { Text } from '@/src/components/ThemedText'
+import { HEADER_TOP } from './constants'
+import { selectionTap, successTap } from './haptics'
+import type { AccountPhaseProps } from './types'
+
+export function CodeEntry({ model, errorText, onDismiss }: AccountPhaseProps) {
+ const { t } = useTranslation(['settings', 'common'])
+ const { theme } = useTheme()
+
+ const paste = () => {
+ Clipboard.getStringAsync()
+ .then((text) => {
+ model.setEntry(text)
+ selectionTap()
+ })
+ .catch((err) => console.warn('[account] clipboard read failed', err))
+ }
+
+ const activate = () => {
+ model.activate().then((ok) => {
+ if (ok) successTap()
+ })
+ }
+
+ return (
+ <Layout compactTop backdrop={<HeroBackdrop />}>
+ <View style={styles.navRow}>
+ <IconButton
+ icon='back'
+ size='large'
+ label={t('settings:account.back')}
+ onPress={model.showPaywall}
+ />
+ <IconButton
+ icon='close'
+ size='large'
+ label={t('common:actions.close')}
+ onPress={onDismiss}
+ />
+ </View>
+
+ <Text style={[styles.title, { color: theme.colors.colorTextPrimary }]}>
+ {t('settings:account.enterCodeTitle')}
+ </Text>
+
+ <View style={styles.field}>
+ <Input
+ mono
+ autoFocus
+ value={model.entry}
+ inputMode='numeric'
+ maxLength={ACCOUNT_CODE_DISPLAY_LENGTH}
+ autoComplete='off'
+ spellCheck={false}
+ disabled={model.busy}
+ aria-label={t('settings:account.enterCodeTitle')}
+ placeholder={t('settings:account.codePlaceholder')}
+ error={errorText ?? undefined}
+ trailing={
+ <Button
+ variant='ghost'
+ size='sm'
+ iconOnly
+ aria-label={t('common:actions.paste')}
+ disabled={model.busy}
+ icon={<ClipboardIcon size={18} />}
+ onClick={paste}
+ />
+ }
+ onChange={(e: { target: { value: string } }) => model.setEntry(e.target.value)}
+ />
+ </View>
+
+ <View style={styles.action}>
+ <Button
+ size='lg'
+ width='full'
+ loading={model.busy}
+ disabled={!model.codeReady}
+ onClick={activate}
+ >
+ {t('settings:account.activate')}
+ </Button>
+ </View>
+ </Layout>
+ )
+}
+
+const styles = StyleSheet.create({
+ navRow: {
+ flexDirection: 'row',
+ alignItems: 'center',
+ justifyContent: 'space-between',
+ paddingTop: HEADER_TOP
+ },
+ title: {
+ flexShrink: 1,
+ fontSize: 30,
+ fontWeight: '700',
+ letterSpacing: -0.6,
+ marginTop: 32,
+ marginBottom: 6
+ },
+ field: { marginTop: 14 },
+ action: { marginTop: 14 }
+})
diff --git a/apps/mobile/src/account/DismissRow.tsx b/apps/mobile/src/account/DismissRow.tsx
new file mode 100644
index 0000000..22e58aa
--- /dev/null
+++ b/apps/mobile/src/account/DismissRow.tsx
@@ -0,0 +1,18 @@
+import { StyleSheet, View } from 'react-native'
+import { useTranslation } from '@altersend/locales'
+import { IconButton } from '@/src/components/IconButton'
+import { HEADER_TOP } from './constants'
+
+export function DismissRow({ onDismiss }: { onDismiss: () => void }) {
+ const { t } = useTranslation(['common'])
+
+ return (
+ <View style={styles.row}>
+ <IconButton icon='close' size='large' label={t('common:actions.close')} onPress={onDismiss} />
+ </View>
+ )
+}
+
+const styles = StyleSheet.create({
+ row: { alignItems: 'flex-end', paddingTop: HEADER_TOP }
+})
diff --git a/apps/mobile/src/account/Paywall.tsx b/apps/mobile/src/account/Paywall.tsx
new file mode 100644
index 0000000..6258613
--- /dev/null
+++ b/apps/mobile/src/account/Paywall.tsx
@@ -0,0 +1,223 @@
+import { useEffect } from 'react'
+import { Linking, StyleSheet, View } from 'react-native'
+import { Button, ExternalLink, LinkRow, useTheme } from '@altersend/components'
+import { useTranslation } from '@altersend/locales'
+import {
+ planComparisonRows,
+ planRows,
+ privacyPolicyUrl,
+ termsOfServiceUrl
+} from '@altersend/domain'
+import { HeroBackdrop, Layout } from '@/src/components'
+import { IconButton } from '@/src/components/IconButton'
+import { Text } from '@/src/components/ThemedText'
+import { purchasesReady } from '@/src/lifecycle/purchases'
+import { HEADER_TOP, SCREEN_PADDING } from './constants'
+import { PlanCellValue } from './PlanCellValue'
+import { successTap } from './haptics'
+import type { AccountPhaseProps } from './types'
+
+const PRO_COLUMN_WIDTH = 80
+const FREE_CHECK_SIZE = 15
+const PRO_CHECK_SIZE = 17
+
+function openExternalUrl(url: string) {
+ Linking.openURL(url).catch((err) => console.warn('[account] could not open url', err))
+}
+
+export function Paywall({ model, errorText, onDismiss }: AccountPhaseProps) {
+ const { t } = useTranslation(['settings', 'common'])
+ const restore = model.store?.restore
+ const { theme } = useTheme()
+ const c = theme.colors
+ const rows = planComparisonRows(t)
+ const { prepareStore } = model
+
+ useEffect(() => prepareStore(), [prepareStore])
+
+ const footer = (
+ <View style={[styles.footer, styles.footerBar, { borderTopColor: c.colorBorderStrong }]}>
+ {errorText ? <Text style={[styles.error, { color: c.colorDanger }]}>{errorText}</Text> : null}
+
+ <Button
+ size='lg'
+ width='full'
+ loading={model.busy}
+ disabled={!purchasesReady || model.storeUnavailable}
+ onClick={model.startUpgrade}
+ >
+ {t('settings:account.getPro')}
+ </Button>
+
+ {model.storeUnavailable ? (
+ <Text style={[styles.note, { color: c.colorTextSecondary }]}>
+ {t('settings:account.storeUnavailable')}
+ </Text>
+ ) : null}
+
+ <Button
+ size='sm'
+ variant='ghost'
+ width='full'
+ disabled={model.busy}
+ onClick={model.showEntry}
+ >
+ {t('settings:account.haveCodeLink')}
+ </Button>
+
+ <View style={styles.legalLinks}>
+ {model.store ? (
+ <ExternalLink onPress={() => restore?.().then((ok) => ok && successTap())}>
+ {t('settings:account.restore')}
+ </ExternalLink>
+ ) : null}
+ <ExternalLink onPress={() => openExternalUrl(termsOfServiceUrl)}>
+ {t('settings:rows.terms')}
+ </ExternalLink>
+ <ExternalLink onPress={() => openExternalUrl(privacyPolicyUrl)}>
+ {t('settings:rows.privacyPolicy')}
+ </ExternalLink>
+ </View>
+ </View>
+ )
+
+ return (
+ <Layout compactTop backdrop={<HeroBackdrop />} footer={footer}>
+ <View style={styles.header}>
+ <Text style={[styles.title, { color: c.colorTextPrimary }]}>
+ {t('settings:account.paywallTitle')}
+ </Text>
+ <IconButton
+ icon='close'
+ size='large'
+ label={t('common:actions.close')}
+ onPress={onDismiss}
+ />
+ </View>
+ <Text style={[styles.lead, { color: c.colorTextSecondary }]}>
+ {t('settings:account.paywallLead')}
+ </Text>
+
+ <View style={styles.plans}>
+ {planRows(t, model.prices).map((row) => (
+ <LinkRow
+ key={row.plan}
+ standalone
+ label={row.title}
+ subtitle={row.caption}
+ selected={row.plan === model.plan}
+ onPress={() => model.choosePlan(row.plan)}
+ trailing={
+ row.price ? (
+ <Text style={[styles.planPrice, { color: c.colorTextPrimary }]}>{row.price}</Text>
+ ) : null
+ }
+ />
+ ))}
+ </View>
+
+ <View style={styles.table}>
+ <View
+ style={[
+ styles.proColumn,
+ { backgroundColor: c.colorBackgroundSubtle, borderColor: c.colorBorderPrimary }
+ ]}
+ />
+
+ <View style={styles.tableHead}>
+ <Text style={[styles.rowLabel, styles.headLabel, { color: c.colorTextPrimary }]}>
+ {t('settings:account.included')}
+ </Text>
+ <Text style={[styles.freeCell, styles.headColumn, { color: c.colorTextMuted }]}>
+ {t('settings:account.columnFree')}
+ </Text>
+ <View style={styles.proHeadCell}>
+ <View style={[styles.proChip, { backgroundColor: c.colorSurfacePrimary }]}>
+ <Text style={[styles.proChipLabel, { color: c.colorTextPrimary }]}>
+ {t('settings:account.columnPro')}
+ </Text>
+ </View>
+ </View>
+ </View>
+
+ {rows.map((row, index) => (
+ <View
+ key={row.label}
+ style={[styles.tableRow, index === rows.length - 1 && styles.tableRowLast]}
+ >
+ <Text style={[styles.rowLabel, { color: c.colorTextSecondary }]}>{row.label}</Text>
+ <View style={styles.freeCell}>
+ <PlanCellValue
+ cell={row.free}
+ color={c.colorTextMuted}
+ size={FREE_CHECK_SIZE}
+ style={styles.freeValue}
+ />
+ </View>
+ <View style={styles.proCell}>
+ <PlanCellValue
+ cell={row.pro}
+ color={c.colorTextPrimary}
+ size={PRO_CHECK_SIZE}
+ style={styles.proValue}
+ />
+ </View>
+ </View>
+ ))}
+ </View>
+ </Layout>
+ )
+}
+
+const styles = StyleSheet.create({
+ header: {
+ flexDirection: 'row',
+ alignItems: 'flex-start',
+ justifyContent: 'space-between',
+ gap: 12,
+ paddingTop: HEADER_TOP
+ },
+ title: { flexShrink: 1, fontSize: 30, fontWeight: '700', letterSpacing: -0.6, marginBottom: 6 },
+ lead: { fontSize: 15, lineHeight: 21 },
+ plans: { marginTop: 24, marginBottom: 8, gap: 10 },
+ planPrice: { fontSize: 16, fontWeight: '600' },
+ table: { position: 'relative', marginTop: 28 },
+ proColumn: {
+ position: 'absolute',
+ right: 0,
+ top: 0,
+ bottom: 0,
+ width: PRO_COLUMN_WIDTH,
+ borderRadius: 16,
+ borderWidth: 1
+ },
+ tableHead: { flexDirection: 'row', alignItems: 'center', paddingVertical: 12 },
+ headLabel: { fontSize: 15, fontWeight: '600' },
+ headColumn: { fontSize: 13, fontWeight: '600', textAlign: 'center' },
+ tableRow: { flexDirection: 'row', alignItems: 'center', paddingVertical: 16 },
+ tableRowLast: { paddingBottom: 24 },
+ rowLabel: { flex: 1, fontSize: 14, lineHeight: 19, paddingRight: 12 },
+ freeCell: { width: 56, marginRight: 16, alignItems: 'center' },
+ freeValue: { fontSize: 14, textAlign: 'center' },
+ proHeadCell: { width: PRO_COLUMN_WIDTH, alignItems: 'center' },
+ proCell: { width: PRO_COLUMN_WIDTH, alignItems: 'center' },
+ proValue: { textAlign: 'center', fontSize: 16, fontWeight: '600' },
+ proChip: { paddingHorizontal: 12, paddingVertical: 6, borderRadius: 8 },
+ proChipLabel: { fontSize: 13, fontWeight: '600' },
+ footer: { gap: 10 },
+ note: { fontSize: 13, lineHeight: 18, textAlign: 'center' },
+ error: { fontSize: 13, lineHeight: 18, marginTop: 12, textAlign: 'center' },
+ legalLinks: {
+ flexDirection: 'row',
+ flexWrap: 'wrap',
+ justifyContent: 'center',
+ columnGap: 16,
+ rowGap: 4
+ },
+ footerBar: {
+ marginHorizontal: -SCREEN_PADDING,
+ paddingHorizontal: SCREEN_PADDING,
+ paddingTop: 16,
+ borderTopWidth: StyleSheet.hairlineWidth
+ }
+})
diff --git a/apps/mobile/src/account/PlanCellValue.tsx b/apps/mobile/src/account/PlanCellValue.tsx
new file mode 100644
index 0000000..f3140a1
--- /dev/null
+++ b/apps/mobile/src/account/PlanCellValue.tsx
@@ -0,0 +1,17 @@
+import type { StyleProp, TextStyle } from 'react-native'
+import { CheckIcon } from '@altersend/components/icons'
+import type { PlanCell } from '@altersend/domain'
+import { Text } from '@/src/components/ThemedText'
+
+interface Props {
+ cell: PlanCell
+ color: string
+ size: number
+ style: StyleProp<TextStyle>
+}
+
+export function PlanCellValue({ cell, color, size, style }: Props) {
+ if (cell.type === 'check') return <CheckIcon size={size} color={color} />
+
+ return <Text style={[style, { color }]}>{cell.value}</Text>
+}
diff --git a/apps/mobile/src/account/PurchaseSuccess.tsx b/apps/mobile/src/account/PurchaseSuccess.tsx
new file mode 100644
index 0000000..15a02a9
--- /dev/null
+++ b/apps/mobile/src/account/PurchaseSuccess.tsx
@@ -0,0 +1,98 @@
+import { useEffect, useState } from 'react'
+import { StyleSheet, View } from 'react-native'
+import { AccountCodeCard, Button, SuccessBurst, useTheme } from '@altersend/components'
+import { CheckIcon } from '@altersend/components/icons'
+import { useTranslation } from '@altersend/locales'
+import { ConfirmDialog, Layout } from '@/src/components'
+import { Text } from '@/src/components/ThemedText'
+import { DismissRow } from './DismissRow'
+import { successTap } from './haptics'
+import { useCopyAccountCode } from './useCopyAccountCode'
+import type { AccountPhaseProps } from './types'
+
+const BURST_SIZE = 84
+
+export function PurchaseSuccess({ model, onDismiss }: AccountPhaseProps) {
+ const { t } = useTranslation(['settings', 'common'])
+ const { theme } = useTheme()
+ const c = theme.colors
+ const { copied, copyCode } = useCopyAccountCode(model.account?.code)
+ const [confirmDone, setConfirmDone] = useState(false)
+
+ useEffect(() => {
+ if (!model.rotated) successTap()
+ }, [model.rotated])
+
+ if (!model.account) return null
+
+ const footer = (
+ <View style={styles.footer}>
+ <Button size='lg' width='full' onClick={() => setConfirmDone(true)}>
+ {t('settings:account.done')}
+ </Button>
+ </View>
+ )
+
+ return (
+ <Layout compactTop footer={footer}>
+ <DismissRow onDismiss={onDismiss} />
+
+ <View style={styles.celebration}>
+ <SuccessBurst
+ size={BURST_SIZE}
+ markColor={c.colorSuccess}
+ tones={[c.colorAccent, c.colorInfo, c.colorSuccess, c.colorWarning]}
+ icon={<CheckIcon size={38} color={c.colorBackground} />}
+ />
+ <Text style={[styles.title, { color: c.colorTextPrimary }]}>
+ {t('settings:account.successTitle')}
+ </Text>
+ </View>
+
+ {model.rotated ? (
+ <Text style={[styles.warning, { color: c.colorWarning }]}>
+ {t('settings:account.codeReplaced')}
+ </Text>
+ ) : null}
+
+ <Text style={[styles.warning, { color: c.colorTextSecondary }]}>
+ {t('settings:account.saveWarning')}
+ </Text>
+
+ <ConfirmDialog
+ open={confirmDone}
+ title={t('settings:account.savedCodeTitle')}
+ message={t('settings:account.savedCodeBody')}
+ confirmLabel={t('settings:account.savedCodeConfirm')}
+ cancelLabel={t('common:actions.cancel')}
+ onConfirm={model.acknowledge}
+ onCancel={() => setConfirmDone(false)}
+ />
+
+ <View style={styles.card}>
+ <AccountCodeCard
+ code={model.account.code}
+ label={t('settings:account.yourCode')}
+ copyLabel={t('common:actions.copy')}
+ copiedLabel={t('settings:account.copied')}
+ copied={copied}
+ onCopy={copyCode}
+ />
+ </View>
+ </Layout>
+ )
+}
+
+const styles = StyleSheet.create({
+ footer: { gap: 10 },
+ celebration: { alignItems: 'center', marginTop: 8 },
+ title: {
+ fontSize: 28,
+ fontWeight: '700',
+ letterSpacing: -0.5,
+ marginTop: -28,
+ textAlign: 'center'
+ },
+ card: { marginTop: 24 },
+ warning: { fontSize: 14, lineHeight: 20, marginTop: 12, textAlign: 'center' }
+})
diff --git a/apps/mobile/src/account/constants.ts b/apps/mobile/src/account/constants.ts
new file mode 100644
index 0000000..ee36ba8
--- /dev/null
+++ b/apps/mobile/src/account/constants.ts
@@ -0,0 +1,2 @@
+export const HEADER_TOP = 24
+export const SCREEN_PADDING = 20
diff --git a/apps/mobile/src/account/haptics.ts b/apps/mobile/src/account/haptics.ts
new file mode 100644
index 0000000..61a8d6f
--- /dev/null
+++ b/apps/mobile/src/account/haptics.ts
@@ -0,0 +1,15 @@
+import * as Haptics from 'expo-haptics'
+
+const warn = (err: unknown) => console.warn('[account] haptic failed', err)
+
+export function selectionTap(): void {
+ Haptics.selectionAsync().catch(warn)
+}
+
+export function impactTap(): Promise<void> {
+ return Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Light)
+}
+
+export function successTap(): void {
+ Haptics.notificationAsync(Haptics.NotificationFeedbackType.Success).catch(warn)
+}
diff --git a/apps/mobile/src/account/index.ts b/apps/mobile/src/account/index.ts
new file mode 100644
index 0000000..529e8ed
--- /dev/null
+++ b/apps/mobile/src/account/index.ts
@@ -0,0 +1,7 @@
+export { AccountProvider, useAccountModel } from './AccountProvider'
+export { ApprovalWaiting } from './ApprovalWaiting'
+export { CheckoutWaiting } from './CheckoutWaiting'
+export { CodeEntry } from './CodeEntry'
+export { Paywall } from './Paywall'
+export { PurchaseSuccess } from './PurchaseSuccess'
+export type { AccountPhaseProps } from './types'
diff --git a/apps/mobile/src/account/types.ts b/apps/mobile/src/account/types.ts
new file mode 100644
index 0000000..28aa21e
--- /dev/null
+++ b/apps/mobile/src/account/types.ts
@@ -0,0 +1,7 @@
+import type { AccountModel } from '@altersend/domain'
+
+export interface AccountPhaseProps {
+ model: AccountModel
+ errorText: string | null
+ onDismiss: () => void
+}
diff --git a/apps/mobile/src/account/useCopyAccountCode.ts b/apps/mobile/src/account/useCopyAccountCode.ts
new file mode 100644
index 0000000..a399c4c
--- /dev/null
+++ b/apps/mobile/src/account/useCopyAccountCode.ts
@@ -0,0 +1,28 @@
+import * as Clipboard from 'expo-clipboard'
+import { formatAccountCode, useCopiedFlag } from '@altersend/domain'
+import { impactTap } from './haptics'
+
+const COPY_ID = 'account-code'
+
+export function useCopyAccountCode(code: string | undefined, onCopied?: () => void) {
+ const { copiedId, flashCopied } = useCopiedFlag()
+
+ const copyCode = async (): Promise<boolean> => {
+ if (!code) return false
+
+ try {
+ await Clipboard.setStringAsync(formatAccountCode(code))
+ } catch (err) {
+ console.warn('[account] clipboard write failed', err)
+ return false
+ }
+
+ flashCopied(COPY_ID)
+ onCopied?.()
+ await impactTap()
+
+ return true
+ }
+
+ return { copied: copiedId === COPY_ID, copyCode }
+}
diff --git a/apps/mobile/src/components/ConfirmDialog/ConfirmDialog.android.tsx b/apps/mobile/src/components/ConfirmDialog/ConfirmDialog.android.tsx
index c982f81..877e2c8 100644
--- a/apps/mobile/src/components/ConfirmDialog/ConfirmDialog.android.tsx
+++ b/apps/mobile/src/components/ConfirmDialog/ConfirmDialog.android.tsx
@@ -38,7 +38,7 @@ export function ConfirmDialog({
) : null}
<AlertDialog.DismissButton>
<TextButton onClick={onCancel} colors={{ contentColor: c.colorTextSecondary }}>
- {cancelLabel}
+ <Text color={c.colorTextSecondary}>{cancelLabel}</Text>
</TextButton>
</AlertDialog.DismissButton>
<AlertDialog.ConfirmButton>
@@ -46,7 +46,7 @@ export function ConfirmDialog({
onClick={onConfirm}
colors={{ contentColor: destructive ? c.colorDanger : c.colorInfo }}
>
- {confirmLabel}
+ <Text color={destructive ? c.colorDanger : c.colorInfo}>{confirmLabel}</Text>
</TextButton>
</AlertDialog.ConfirmButton>
</AlertDialog>
diff --git a/apps/mobile/src/components/HeroBackdrop/HeroBackdrop.tsx b/apps/mobile/src/components/HeroBackdrop/HeroBackdrop.tsx
new file mode 100644
index 0000000..574c1b9
--- /dev/null
+++ b/apps/mobile/src/components/HeroBackdrop/HeroBackdrop.tsx
@@ -0,0 +1,86 @@
+import { useWindowDimensions } from 'react-native'
+import Svg, {
+ Defs,
+ G,
+ Line,
+ LinearGradient,
+ Mask,
+ RadialGradient,
+ Rect,
+ Stop
+} from 'react-native-svg'
+import { heroBackdrop, useTheme, withAlpha, type HeroBackdropStop } from '@altersend/components'
+
+interface HeroBackdropProps {
+ height?: number
+}
+
+const percent = (value: number) => `${value}%`
+
+export function HeroBackdrop({ height = heroBackdrop.height }: HeroBackdropProps) {
+ const { theme } = useTheme()
+ const { width } = useWindowDimensions()
+ const tint = theme.colors.colorInfo
+ const { gridSize, glowCenter, maskCenter } = heroBackdrop
+
+ const columns = Array.from({ length: Math.ceil(width / gridSize) }, (_, i) => (i + 1) * gridSize)
+ const rows = Array.from({ length: Math.ceil(height / gridSize) }, (_, i) => (i + 1) * gridSize)
+
+ const tintStops = (stops: HeroBackdropStop[]) =>
+ stops.map((stop) => (
+ <Stop key={stop.offset} offset={stop.offset} stopColor={tint} stopOpacity={stop.alpha} />
+ ))
+
+ return (
+ <Svg width={width} height={height}>
+ <Defs>
+ <LinearGradient id='wash' x1='0' y1='0' x2='0' y2='1'>
+ {tintStops(heroBackdrop.wash)}
+ </LinearGradient>
+
+ <RadialGradient
+ id='glow'
+ cx={percent(glowCenter.x)}
+ cy={percent(glowCenter.y)}
+ rx={percent(glowCenter.radiusX)}
+ ry={percent(glowCenter.radiusY)}
+ >
+ {tintStops(heroBackdrop.glow)}
+ </RadialGradient>
+
+ <RadialGradient
+ id='gridFade'
+ cx={percent(maskCenter.x)}
+ cy={percent(maskCenter.y)}
+ rx={percent(maskCenter.radiusX)}
+ ry={percent(maskCenter.radiusY)}
+ >
+ {heroBackdrop.mask.map((stop) => (
+ <Stop
+ key={stop.offset}
+ offset={stop.offset}
+ stopColor='white'
+ stopOpacity={stop.alpha}
+ />
+ ))}
+ </RadialGradient>
+
+ <Mask id='gridMask'>
+ <Rect width={width} height={height} fill='url(#gridFade)' />
+ </Mask>
+ </Defs>
+
+ <Rect width={width} height={height} fill='url(#wash)' />
+ <Rect width={width} height={height} fill='url(#glow)' />
+
+ <G mask='url(#gridMask)' stroke={withAlpha(tint, heroBackdrop.gridAlpha)} strokeWidth={1}>
+ {columns.map((x) => (
+ <Line key={`column-${x}`} x1={x} y1={0} x2={x} y2={height} />
+ ))}
+ {rows.map((y) => (
+ <Line key={`row-${y}`} x1={0} y1={y} x2={width} y2={y} />
+ ))}
+ </G>
+ </Svg>
+ )
+}
diff --git a/apps/mobile/src/components/HeroBackdrop/index.ts b/apps/mobile/src/components/HeroBackdrop/index.ts
new file mode 100644
index 0000000..7193d4c
--- /dev/null
+++ b/apps/mobile/src/components/HeroBackdrop/index.ts
@@ -0,0 +1 @@
+export * from './HeroBackdrop'
diff --git a/apps/mobile/src/components/Layout/Layout.tsx b/apps/mobile/src/components/Layout/Layout.tsx
index 69aa7e9..1de2317 100644
--- a/apps/mobile/src/components/Layout/Layout.tsx
+++ b/apps/mobile/src/components/Layout/Layout.tsx
@@ -9,22 +9,28 @@ import { Text } from '@/src/components/ThemedText'
interface LayoutProps {
title?: string
description?: string
+ backdrop?: React.ReactElement
badge?: React.ReactElement
footer?: React.ReactElement
hasNativeHeader?: boolean
compactHeader?: boolean
+ compactTop?: boolean
noScroll?: boolean
onMenuPress?: () => void
}
+const SCREEN_PADDING = 20
+
export const Layout = ({
title,
description,
+ backdrop,
badge,
footer,
children,
hasNativeHeader,
compactHeader,
+ compactTop,
noScroll,
onMenuPress
}: PropsWithChildren<LayoutProps>) => {
@@ -33,8 +39,14 @@ export const Layout = ({
const insets = useSafeAreaInsets()
const showHeader = Boolean(title || description || badge || onMenuPress)
- const nativeHeaderPaddingTop = showHeader ? 8 : 24
- const paddingTop = hasNativeHeader ? nativeHeaderPaddingTop : insets.top + 32
+
+ const resolvePaddingTop = () => {
+ if (hasNativeHeader) return showHeader ? 8 : 24
+ if (compactTop) return insets.top + 8
+ return insets.top + 32
+ }
+
+ const paddingTop = resolvePaddingTop()
const paddingBottom = Platform.OS === 'ios' ? insets.bottom + 8 : 28
return (
@@ -48,6 +60,12 @@ export const Layout = ({
}
]}
>
+ {backdrop ? (
+ <View pointerEvents='none' style={styles.backdrop}>
+ {backdrop}
+ </View>
+ ) : null}
+
{showHeader ? (
<View style={[styles.header, compactHeader && styles.headerCompact]}>
{badge ? <View style={styles.badgeSlot}>{badge}</View> : null}
@@ -70,7 +88,7 @@ export const Layout = ({
) : null}
{noScroll ? (
- <View style={styles.scrollView}>{children}</View>
+ <View style={[styles.scrollView, styles.scrollContent]}>{children}</View>
) : (
<ScrollView style={styles.scrollView} contentContainerStyle={styles.scrollContent}>
{children}
@@ -83,8 +101,13 @@ export const Layout = ({
const styles = StyleSheet.create({
container: {
- flex: 1,
- paddingHorizontal: 20
+ flex: 1
+ },
+ backdrop: {
+ position: 'absolute',
+ top: 0,
+ left: 0,
+ right: 0
},
titleRow: {
flexDirection: 'row',
@@ -94,7 +117,8 @@ const styles = StyleSheet.create({
},
header: {
maxWidth: 720,
- marginBottom: 24
+ marginBottom: 24,
+ paddingHorizontal: SCREEN_PADDING
},
headerCompact: {
marginBottom: 4
@@ -118,10 +142,12 @@ const styles = StyleSheet.create({
},
scrollContent: {
flexGrow: 1,
- paddingBottom: 8
+ paddingBottom: 8,
+ paddingHorizontal: SCREEN_PADDING
},
footer: {
gap: 8,
- paddingTop: 12
+ paddingTop: 12,
+ paddingHorizontal: SCREEN_PADDING
}
})
diff --git a/apps/mobile/src/components/UpgradeButton/UpgradeButton.ios.tsx b/apps/mobile/src/components/UpgradeButton/UpgradeButton.ios.tsx
new file mode 100644
index 0000000..6881db9
--- /dev/null
+++ b/apps/mobile/src/components/UpgradeButton/UpgradeButton.ios.tsx
@@ -0,0 +1,30 @@
+import { useRouter } from 'expo-router'
+import { Button, Host } from '@expo/ui/swift-ui'
+import { buttonStyle, controlSize, font, padding } from '@expo/ui/swift-ui/modifiers'
+import { ThemeType, useTheme } from '@altersend/components'
+import { useTranslation } from '@altersend/locales'
+
+export function UpgradeButton() {
+ const { t } = useTranslation(['settings'])
+ const { themeType } = useTheme()
+ const router = useRouter()
+
+ return (
+ <Host
+ matchContents
+ colorScheme={themeType === ThemeType.Light ? 'light' : 'dark'}
+ style={{ backgroundColor: 'transparent' }}
+ >
+ <Button
+ label={t('settings:account.upgrade')}
+ modifiers={[
+ buttonStyle('plain'),
+ controlSize('small'),
+ font({ textStyle: 'subheadline' }),
+ padding({ horizontal: 4, vertical: 2 })
+ ]}
+ onPress={() => router.push('/account')}
+ />
+ </Host>
+ )
+}
diff --git a/apps/mobile/src/components/UpgradeButton/UpgradeButton.tsx b/apps/mobile/src/components/UpgradeButton/UpgradeButton.tsx
new file mode 100644
index 0000000..4849eef
--- /dev/null
+++ b/apps/mobile/src/components/UpgradeButton/UpgradeButton.tsx
@@ -0,0 +1,18 @@
+import { useRouter } from 'expo-router'
+import { Button, Host } from '@expo/ui'
+import { useTranslation } from '@altersend/locales'
+
+export function UpgradeButton() {
+ const { t } = useTranslation(['settings'])
+ const router = useRouter()
+
+ return (
+ <Host matchContents>
+ <Button
+ variant='filled'
+ label={t('settings:account.upgrade')}
+ onPress={() => router.push('/account')}
+ />
+ </Host>
+ )
+}
diff --git a/apps/mobile/src/components/UpgradeButton/index.ts b/apps/mobile/src/components/UpgradeButton/index.ts
new file mode 100644
index 0000000..3f80e77
--- /dev/null
+++ b/apps/mobile/src/components/UpgradeButton/index.ts
@@ -0,0 +1 @@
+export * from './UpgradeButton'
diff --git a/apps/mobile/src/components/index.ts b/apps/mobile/src/components/index.ts
index 030d866..8c1fb9f 100644
--- a/apps/mobile/src/components/index.ts
+++ b/apps/mobile/src/components/index.ts
@@ -1,3 +1,4 @@
+export * from './HeroBackdrop'
export * from './IllustrationLayout'
export * from './Layout'
export * from './Toast'
@@ -11,3 +12,4 @@ export * from './PairingQrSheet'
export * from './PairingScanSheet'
export * from './PairingManualCodeSheet'
export * from './PairDeviceSheet'
+export * from './UpgradeButton'
diff --git a/apps/mobile/src/lifecycle/account.ts b/apps/mobile/src/lifecycle/account.ts
new file mode 100644
index 0000000..e953381
--- /dev/null
+++ b/apps/mobile/src/lifecycle/account.ts
@@ -0,0 +1,53 @@
+import { AppState, Linking } from 'react-native'
+import * as SecureStore from 'expo-secure-store'
+import { accountApiUrl, createAccountRuntime, type AccountStorage } from '@altersend/domain'
+import { mobileApi } from '@/src/api/mobileApi'
+import { purchaseAdapter, purchasesReady } from './purchases'
+import { isRelayEnabled } from './relayStorage'
+
+const CODE_KEY = 'altersend.account.code'
+const TOKEN_KEY = 'altersend.account.token'
+
+const accountStorage: AccountStorage = {
+ async read() {
+ try {
+ return await SecureStore.getItemAsync(CODE_KEY)
+ } catch (err) {
+ console.warn('[account] could not read stored code', err)
+ return null
+ }
+ },
+ write: (code) => SecureStore.setItemAsync(CODE_KEY, code),
+ clear: () => SecureStore.deleteItemAsync(CODE_KEY),
+ async readToken() {
+ try {
+ return await SecureStore.getItemAsync(TOKEN_KEY)
+ } catch (err) {
+ console.warn('[account] could not read cached token', err)
+ return null
+ }
+ },
+ writeToken: (token) =>
+ token ? SecureStore.setItemAsync(TOKEN_KEY, token) : SecureStore.deleteItemAsync(TOKEN_KEY)
+}
+
+const runtime = createAccountRuntime({
+ baseUrl: process.env.EXPO_PUBLIC_PRO_API_URL || accountApiUrl,
+ storage: accountStorage,
+ openUrl: (url) => Linking.openURL(url),
+ applyToken: async (proToken) => {
+ await mobileApi.worker.setRelayConfig({ enabled: isRelayEnabled(), proToken })
+ },
+ purchases: purchasesReady ? purchaseAdapter : undefined
+})
+
+export const accountAdapter = runtime.adapter
+export const syncAccountToken = runtime.syncToken
+const warnSync = (err: unknown) => console.warn('[account] foreground sync failed', err)
+
+export function startAccountSync(): void {
+ runtime.startSync()
+ AppState.addEventListener('change', (next) => {
+ if (next === 'active') runtime.syncTokenIfStale().catch(warnSync)
+ })
+}
diff --git a/apps/mobile/src/lifecycle/purchases.ts b/apps/mobile/src/lifecycle/purchases.ts
new file mode 100644
index 0000000..6e1bc82
--- /dev/null
+++ b/apps/mobile/src/lifecycle/purchases.ts
@@ -0,0 +1,136 @@
+import { Platform } from 'react-native'
+import * as Crypto from 'expo-crypto'
+import Purchases, {
+ PURCHASES_ERROR_CODE,
+ type CustomerInfo,
+ type PurchasesPackage
+} from 'react-native-purchases'
+import type { BillingPlan, PlanOffer, PurchaseAdapter, PurchaseOutcome } from '@altersend/domain'
+
+const PRO_ENTITLEMENT = 'pro'
+
+const apiKey =
+ Platform.OS === 'ios'
+ ? process.env.EXPO_PUBLIC_REVENUECAT_IOS_KEY
+ : process.env.EXPO_PUBLIC_REVENUECAT_ANDROID_KEY
+
+export const purchasesReady = Boolean(apiKey)
+
+let configured = false
+let onEntitlementChange: (() => void) | null = null
+
+export function watchEntitlement(listener: () => void): void {
+ onEntitlementChange = listener
+}
+
+function ensureConfigured(): boolean {
+ if (!apiKey) return false
+ if (configured) return true
+
+ try {
+ Purchases.configure({ apiKey })
+ Purchases.addCustomerInfoUpdateListener((_info: CustomerInfo) => onEntitlementChange?.())
+ configured = true
+ } catch (err) {
+ console.warn('[purchases] could not configure RevenueCat', err)
+ return false
+ }
+
+ return true
+}
+
+function errorCode(err: unknown): string | null {
+ if (!err || typeof err !== 'object' || !('code' in err)) return null
+ return String((err as { code: unknown }).code)
+}
+
+function isUserCancelled(err: unknown): boolean {
+ if (Boolean(err && typeof err === 'object' && 'userCancelled' in err && err.userCancelled)) {
+ return true
+ }
+ return errorCode(err) === PURCHASES_ERROR_CODE.PURCHASE_CANCELLED_ERROR
+}
+
+function isPro(customerInfo: { entitlements: { active: Record<string, unknown> } }): boolean {
+ return Boolean(customerInfo.entitlements.active[PRO_ENTITLEMENT])
+}
+
+async function packageForPlan(plan: BillingPlan): Promise<PurchasesPackage> {
+ const offerings = await Purchases.getOfferings()
+ const offering = offerings.current
+ const selected = plan === 'yearly' ? offering?.annual : offering?.monthly
+
+ if (!selected) {
+ throw new Error(`[purchases] no ${plan} package in the current RevenueCat offering`)
+ }
+
+ return selected
+}
+
+export const purchaseAdapter: PurchaseAdapter = {
+ async available() {
+ if (!ensureConfigured()) return false
+
+ try {
+ if (!(await Purchases.canMakePayments())) return false
+ return (await Purchases.getOfferings()).current !== null
+ } catch (err) {
+ console.warn('[purchases] store unavailable', err)
+ return false
+ }
+ },
+
+ async offers() {
+ if (!ensureConfigured()) return []
+
+ const offering = (await Purchases.getOfferings()).current
+ if (!offering) return []
+
+ const found: PlanOffer[] = []
+ if (offering.monthly) {
+ found.push({ plan: 'monthly', price: offering.monthly.product.priceString })
+ }
+ if (offering.annual) {
+ found.push({ plan: 'yearly', price: offering.annual.product.priceString })
+ }
+ return found
+ },
+
+ async managementUrl() {
+ if (!ensureConfigured()) return null
+ const info = await Purchases.getCustomerInfo()
+ return info.managementURL ?? null
+ },
+
+ async identify(code) {
+ if (!ensureConfigured()) return
+
+ const hash = await Crypto.digestStringAsync(Crypto.CryptoDigestAlgorithm.SHA256, code)
+ await Purchases.logIn(hash)
+ },
+
+ async buy(plan): Promise<PurchaseOutcome> {
+ if (!ensureConfigured()) return 'cancelled'
+
+ const selected = await packageForPlan(plan)
+
+ try {
+ const { customerInfo } = await Purchases.purchasePackage(selected)
+ return isPro(customerInfo) ? 'bought' : 'pending'
+ } catch (err) {
+ if (isUserCancelled(err)) return 'cancelled'
+
+ const code = errorCode(err)
+ if (code === PURCHASES_ERROR_CODE.PRODUCT_ALREADY_PURCHASED_ERROR) return 'owned'
+ if (code === PURCHASES_ERROR_CODE.PAYMENT_PENDING_ERROR) return 'pending'
+
+ throw err
+ }
+ },
+
+ async restore() {
+ if (!ensureConfigured()) return false
+
+ return isPro(await Purchases.restorePurchases())
+ }
+}
diff --git a/apps/mobile/src/transfer/send/views/ShareView.tsx b/apps/mobile/src/transfer/send/views/ShareView.tsx
index 8f4f419..3ed9693 100644
--- a/apps/mobile/src/transfer/send/views/ShareView.tsx
+++ b/apps/mobile/src/transfer/send/views/ShareView.tsx
@@ -5,6 +5,7 @@ import {
buildShareInvite,
buildWebReceiveUrl,
exceedsWebLinkLimit,
+ useSubscriptionStore,
formatFileSize,
formatItemsCount,
useShareViewModel,
@@ -23,6 +24,7 @@ import {
ShareIcon
} from '@altersend/components/icons'
import { useTranslation } from '@altersend/locales'
+import { useRouter } from 'expo-router'
import { useToast } from '@/src/components/Toast'
import { ConfirmDialog, DeviceActionsSheet, DeviceRenameSheet } from '@/src/components'
import { useDeviceRename } from '@/src/pairing/useDeviceRename'
@@ -39,6 +41,7 @@ export function ShareView() {
const { theme } = useTheme()
const c = theme.colors
const toast = useToast()
+ const router = useRouter()
const vm = useShareViewModel(t, {
onPeerJoined: (peer) =>
toast.show({
@@ -77,13 +80,19 @@ export function ShareView() {
}
}
- const webLinkTooLarge = exceedsWebLinkLimit(vm.totalSize)
- const tileCount = webLinkTooLarge ? 2 : 3
+ const pro = useSubscriptionStore((state) => state.active)
+ const webLinkTooLarge = exceedsWebLinkLimit(vm.totalSize, pro)
+ const tileCount = 3
const tileWidth =
contentWidth > 0 ? (contentWidth - TILE_GAP * (tileCount - 1)) / tileCount : undefined
const shareLink = async () => {
if (!vm.topic) return
+ if (webLinkTooLarge) {
+ router.push('/account')
+ return
+ }
+
try {
const link = buildWebReceiveUrl(vm.topic, process.env.EXPO_PUBLIC_WEB_URL)
await Clipboard.setStringAsync(link)
@@ -97,7 +106,7 @@ export function ShareView() {
})
toast.show({
title: t('send:connection.copiedToast'),
- hint: t('send:connection.linkHint', { limit: WEB_LINK_MAX_LABEL })
+ hint: pro ? undefined : t('send:connection.linkHint', { limit: WEB_LINK_MAX_LABEL })
})
} catch (error) {
console.error(error)
@@ -144,21 +153,19 @@ export function ShareView() {
{vm.isCopied ? t('common:actions.copied') : t('send:connection.copyCode')}
</Button>
</View>
- {!webLinkTooLarge && (
- <View style={[styles.tile, { width: tileWidth }]}>
- <Button
- stack
- size='sm'
- variant='secondary'
- width='full'
- disabled={!vm.topic}
- icon={<LinkIcon size={18} />}
- onClick={() => void shareLink()}
- >
- {t('send:connection.shareLink')}
- </Button>
- </View>
- )}
+ <View style={[styles.tile, { width: tileWidth }]}>
+ <Button
+ stack
+ size='sm'
+ variant='secondary'
+ width='full'
+ disabled={!vm.topic}
+ icon={<LinkIcon size={18} />}
+ onClick={() => void shareLink()}
+ >
+ {t('send:connection.shareLink')}
+ </Button>
+ </View>
<View style={[styles.tile, { width: tileWidth }]}>
<Button
stack
@@ -200,19 +207,17 @@ export function ShareView() {
value={vm.topic}
/>
</View>
- {!webLinkTooLarge && (
- <View style={styles.keyAction}>
- <Button
- variant='secondary'
- width='full'
- iconOnly
- aria-label={t('send:connection.shareLink')}
- disabled={!vm.topic}
- icon={<LinkIcon size={18} />}
- onClick={() => void shareLink()}
- />
- </View>
- )}
+ <View style={styles.keyAction}>
+ <Button
+ variant='secondary'
+ width='full'
+ iconOnly
+ aria-label={t('send:connection.shareLink')}
+ disabled={!vm.topic}
+ icon={<LinkIcon size={18} />}
+ onClick={() => void shareLink()}
+ />
+ </View>
</View>
</View>
)}
diff --git a/apps/web/src/transfer/index.ts b/apps/web/src/transfer/index.ts
index 8ccba8f..c2e1382 100644
--- a/apps/web/src/transfer/index.ts
+++ b/apps/web/src/transfer/index.ts
@@ -8,6 +8,34 @@ import type { ConnectHandlers, Connection } from './types'
export { connectErrorCode } from './relay'
export type { ConnectHandlers, Connection } from './types'
+const LIMIT_RECHECK_MS = [1500, 4000, 9000]
+
+function watchRelayLimit(
+ url: string,
+ cid: string,
+ connection: Connection,
+ handlers: ConnectHandlers,
+ signal?: AbortSignal
+): void {
+ const timers = LIMIT_RECHECK_MS.map((delay) =>
+ setTimeout(() => {
+ if (signal?.aborted) return
+ fetchRelayLimit(url, cid)
+ .then((bytes) => {
+ if (signal?.aborted) return
+ if (bytes === null || bytes <= (connection.maxTransferBytes ?? 0)) return
+ connection.maxTransferBytes = bytes
+ handlers.onLimit?.(bytes)
+ })
+ .catch((err) => console.warn('Relay limit re-check failed', err))
+ }, delay)
+ )
+
+ signal?.addEventListener('abort', () => {
+ for (const timer of timers) clearTimeout(timer)
+ })
+}
+
export async function connect(
code: string,
handlers: ConnectHandlers,
@@ -28,7 +56,7 @@ export async function connect(
throwIfAborted()
handlers.onStatus?.('relay')
const remaining = urls.filter((candidate) => !tried.has(candidate))
- const { dht, teardown, url } = await openRelay(remaining)
+ const { dht, teardown, url, cid } = await openRelay(remaining)
tried.add(url)
const onAbort = () => teardown()
signal?.addEventListener('abort', onAbort, { once: true })
@@ -44,8 +72,13 @@ export async function connect(
throwIfAborted()
if (!peer) throw new Error('senderNotFound')
- const connection = await waitForOffers(dht, peer, topicHex, teardown, handlers)
+ const connection = await waitForOffers(dht, peer, topicHex, teardown, handlers, {
+ cid,
+ host: url
+ })
connection.maxTransferBytes = await limit
+
+ watchRelayLimit(url, cid, connection, handlers, signal)
return connection
} catch (err) {
teardown()
diff --git a/apps/web/src/transfer/relay.ts b/apps/web/src/transfer/relay.ts
index 263f233..688ea4e 100644
--- a/apps/web/src/transfer/relay.ts
+++ b/apps/web/src/transfer/relay.ts
@@ -28,9 +28,18 @@ interface RelayEntry {
socket: WebSocket
}
-function fastestRelay(urls: string[]): Promise<RelayEntry> {
+function connectionId(): string {
+ const bytes = new Uint8Array(16)
+ crypto.getRandomValues(bytes)
+ return Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('')
+}
+
+function fastestRelay(urls: string[], cid: string): Promise<RelayEntry> {
return new Promise((resolve, reject) => {
- const entries = urls.map((url) => ({ url, socket: new WebSocket(url) }))
+ const entries = urls.map((url) => ({
+ url,
+ socket: new WebSocket(`${url.replace(/\/$/, '')}/?cid=${cid}`)
+ }))
if (entries.length === 0) {
reject(new Error('relayUnreachable'))
return
@@ -70,13 +79,15 @@ function withTimeout<T>(promise: Promise<T>, ms: number, code: ConnectErrorCode)
export async function openRelay(
urls: string[]
-): Promise<{ dht: RelayDHT; teardown: () => void; url: string }> {
- const { socket, url } = await fastestRelay(urls)
+): Promise<{ dht: RelayDHT; teardown: () => void; url: string; cid: string }> {
+ const cid = connectionId()
+ const { socket, url } = await fastestRelay(urls, cid)
const dht = new DHT(new Stream(true, socket), { custodial: false }) as unknown as RelayDHT
let torn = false
return {
dht,
url,
+ cid,
teardown: () => {
if (torn) return
torn = true
@@ -86,10 +97,12 @@ export async function openRelay(
}
}
-export async function fetchRelayLimit(wsUrl: string): Promise<number | null> {
+export async function fetchRelayLimit(wsUrl: string, cid?: string): Promise<number | null> {
try {
const base = wsUrl.replace(/^ws/, 'http')
- const res = await fetch(new URL('/limits.json', base), { signal: AbortSignal.timeout(3000) })
+ const url = new URL('/limits.json', base)
+ if (cid) url.searchParams.set('cid', cid)
+ const res = await fetch(url, { signal: AbortSignal.timeout(3000) })
if (!res.ok) return null
const data = (await res.json()) as { maxTransferBytes?: unknown }
const bytes = Number(data.maxTransferBytes)
diff --git a/apps/web/src/transfer/session.ts b/apps/web/src/transfer/session.ts
index cf15898..e09fad6 100644
--- a/apps/web/src/transfer/session.ts
+++ b/apps/web/src/transfer/session.ts
@@ -10,12 +10,18 @@ import type { ConnectHandlers, Connection, Peer, RelayDHT } from './types'
const OFFER_TIMEOUT_MS = 30000
+interface WebRelayConnection {
+ cid: string
+ host: string
+}
+
export function waitForOffers(
dht: RelayDHT,
peer: Peer,
topicHex: string,
teardown: () => void,
- handlers: ConnectHandlers
+ handlers: ConnectHandlers,
+ relay: WebRelayConnection
): Promise<Connection> {
const conn = dht.connect(peer.publicKey)
const transfers = new Map<string, FileTransfer>()
@@ -52,6 +58,7 @@ export function waitForOffers(
if (message.type === 'challenge') {
const nonce = (message as { nonce?: string }).nonce
if (nonce) proto.sendControl({ type: 'auth', proof: topicProof(topicHex, nonce) })
+ proto.sendControl({ type: 'web-relay', cid: relay.cid, host: relay.host })
return
}
if (message.type === 'transfer-start') {
diff --git a/apps/web/src/transfer/types.ts b/apps/web/src/transfer/types.ts
index a49d520..f4b4303 100644
--- a/apps/web/src/transfer/types.ts
+++ b/apps/web/src/transfer/types.ts
@@ -9,6 +9,7 @@ type ConnectStage = 'relay' | 'finding' | 'waiting' | 'preparing'
export interface ConnectHandlers {
onStatus?: (stage: ConnectStage) => void
onClosed?: () => void
+ onLimit?: (maxTransferBytes: number | null) => void
}
export interface DownloadHandlers {
diff --git a/apps/web/src/useReceiveViewModel.ts b/apps/web/src/useReceiveViewModel.ts
index 9322683..c105781 100644
--- a/apps/web/src/useReceiveViewModel.ts
+++ b/apps/web/src/useReceiveViewModel.ts
@@ -103,7 +103,16 @@ export function useReceiveViewModel(): ReceiveViewModel {
putFiles([])
setTexts([])
- connect(trimmed, { onClosed: handlePeerClosed }, controller.signal)
+ connect(
+ trimmed,
+ {
+ onClosed: handlePeerClosed,
+ onLimit: (bytes) => {
+ if (!controller.signal.aborted) setMaxTransferBytes(bytes)
+ }
+ },
+ controller.signal
+ )
.then((connection) => {
if (controller.signal.aborted) {
connection.close()
diff --git a/docs/architecture.md b/docs/architecture.md
index 292a115..707fa3e 100644
--- a/docs/architecture.md
+++ b/docs/architecture.md
@@ -52,6 +52,7 @@ The protocol layer, running entirely inside a **Bare worklet** (a lightweight JS
- `worklet/transfer/sender.ts` / `receiver.ts` — stage files into the writable Hyperdrive (legacy path); receiver picks drive channel per file, else replicated Hyperdrive
- `worklet/transfer/topic-auth.ts` — the join-code proof (see [Topic authentication](#topic-authentication))
- `worklet/relay/config.ts` / `conf.ts` — relay state + `relayThrough`; relay list from a signed DHT record (see [Relay fallback](#relay-fallback))
+- `worklet/relay/announce.ts` / `upgradeWebRelay.ts` — present a signed cap token to a relay (see [Relay fallback](#relay-fallback))
- `worklet/identity/device-identity-store.ts` — the stable device keypair, sealed in the OS keychain (see [Pairing](#remembered-devices--pairing))
- `worklet/peers/*` — `RememberedPeerStore`, `PairingCoordinator`, `DiscoveryCoordinator`, `RecognitionCoordinator`, `RememberCoordinator`
- `worklet/rpc/*` — RPC server + canonical command/reply protocol; `client/worker-client.ts` is the host-side typed client
@@ -107,6 +108,7 @@ Most transfers connect directly via hole-punching. When two peers can't reach ea
- **Engagement** — `relay/config.ts` exposes `relayThrough` in "eager" mode: when enabled it always offers the relay, so hyperdht races a relayed path against a direct punch and upgrades to direct if the punch lands.
- **Discovery** — the relay key isn't baked in. `relay/conf.ts` reads the relay list from a signed DHT **mutable record** (public key injected at build via `--relay-conf-pubkey`), so relays rotate with no app release. Fetched lazily once the relay is enabled, with bounded retry (the worklet wipes its Corestore on startup, so a hypercore won't do).
- **Classification** — `TransferSwarm.classifyConnection` matches a peer's `remoteHost` against known relay hosts and emits a per-peer `connection-type` (`direct` / `relay`), keyed per sender; the UI shows **Connected** vs **Connected via relay**.
+- **Caps** — a relay caps how much a session forwards. A sender raises its own cap with a short-lived token signed by the entitlement service and verified against the relay's public key: `relay/announce.ts` sends it over a protomux `altersend-pro` channel, and `config.ts` releases it only while sending and only to a key from the signed relay list. A browser receiver asks its sender for the upgrade via the `web-relay` control message; `upgradeWebRelay.ts` dials the relay to announce it. Enforced relay-side.
The app is only ever a relay _client_ — it holds the relay's public key and address, never a secret.
diff --git a/package-lock.json b/package-lock.json
index 0c8bb17..00e3b82 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -110,7 +110,7 @@
"@altersend/core": "1.8.0",
"@altersend/domain": "1.8.0",
"@altersend/locales": "1.8.0",
- "@expo/ui": "~56.0.24",
+ "@expo/ui": "~56.0.25",
"@expo/vector-icons": "^15.0.2",
"@sentry/react-native": "^8.21.0",
"b4a": "^1.6.7",
@@ -119,6 +119,7 @@
"expo-camera": "~56.0.8",
"expo-clipboard": "~56.0.4",
"expo-constants": "~56.0.22",
+ "expo-crypto": "~56.0.4",
"expo-document-picker": "~56.0.4",
"expo-file-system": "~56.0.8",
"expo-font": "~56.0.7",
@@ -139,6 +140,7 @@
"react-native": "0.85.3",
"react-native-b4a": "^0.0.4",
"react-native-bare-kit": "^0.14.0",
+ "react-native-purchases": "^10.7.0",
"react-native-qrcode-svg": "^6.3.1",
"react-native-safe-area-context": "~5.7.0",
"react-native-screens": "~4.26.0",
@@ -152,6 +154,35 @@
"typescript": "^5.3.3"
}
},
+ "apps/mobile/node_modules/@expo/ui": {
+ "version": "56.0.25",
+ "resolved": "https://registry.npmjs.org/@expo/ui/-/ui-56.0.25.tgz",
+ "integrity": "sha512-2k1JK2JXzQPzwNNyplav2RD03Rrmd/7BRz2mfqPYLpg6jSGhcOGO3UABYKuGkxU9RFYSEuAmEkeBaL4eF10E8Q==",
+ "license": "MIT",
+ "dependencies": {
+ "sf-symbols-typescript": "^2.1.0",
+ "vaul": "^1.1.2"
+ },
+ "peerDependencies": {
+ "@babel/core": "*",
+ "expo": "*",
+ "react": "*",
+ "react-dom": "*",
+ "react-native": "*",
+ "react-native-worklets": "*"
+ },
+ "peerDependenciesMeta": {
+ "@babel/core": {
+ "optional": true
+ },
+ "react-dom": {
+ "optional": true
+ },
+ "react-native-worklets": {
+ "optional": true
+ }
+ }
+ },
"apps/web": {
"name": "@altersend/web",
"version": "1.8.0",
@@ -4210,6 +4241,7 @@
"cpu": [
"x64"
],
+ "dev": true,
"optional": true,
"os": [
"linux"
@@ -5791,6 +5823,27 @@
}
}
},
+ "node_modules/@revenuecat/purchases-js": {
+ "version": "1.49.1",
+ "resolved": "https://registry.npmjs.org/@revenuecat/purchases-js/-/purchases-js-1.49.1.tgz",
+ "integrity": "sha512-eW5/zT0/Jyp0z2Sq1JTFFdlHrUn31fGLuL099/zee8SemHzszlzKOp1IPCOSolLscTUmFUwlalC65opsa365uw==",
+ "license": "MIT"
+ },
+ "node_modules/@revenuecat/purchases-js-hybrid-mappings": {
+ "version": "18.29.0",
+ "resolved": "https://registry.npmjs.org/@revenuecat/purchases-js-hybrid-mappings/-/purchases-js-hybrid-mappings-18.29.0.tgz",
+ "integrity": "sha512-ABSreDd+SL17GFVkuMydh6EP8AaIqitLYfMeA3k7qfRDLKgvINzW9TH1wt7lCdtMQa6+T/fk1egb6olPK51YCA==",
+ "license": "MIT",
+ "dependencies": {
+ "@revenuecat/purchases-js": "1.49.1"
+ }
+ },
+ "node_modules/@revenuecat/purchases-typescript-internal": {
+ "version": "18.29.0",
+ "resolved": "https://registry.npmjs.org/@revenuecat/purchases-typescript-internal/-/purchases-typescript-internal-18.29.0.tgz",
+ "integrity": "sha512-A+gYvNhSi+Z5r1GdwiyuWq9b3kJYAeAHISGK3R5Ec3tKaF7hwI5LM49paw7YGcyYQalngimjpiVYpBeC/IekBg==",
+ "license": "MIT"
+ },
"node_modules/@rolldown/binding-android-arm64": {
"version": "1.2.2",
"resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.2.2.tgz",
@@ -6068,6 +6121,7 @@
"cpu": [
"arm"
],
+ "dev": true,
"optional": true,
"os": [
"android"
@@ -6080,6 +6134,7 @@
"cpu": [
"arm64"
],
+ "dev": true,
"optional": true,
"os": [
"android"
@@ -6090,6 +6145,7 @@
"cpu": [
"arm64"
],
+ "dev": true,
"license": "MIT",
"optional": true,
"os": [
@@ -6103,6 +6159,7 @@
"cpu": [
"x64"
],
+ "dev": true,
"optional": true,
"os": [
"darwin"
@@ -6115,6 +6172,7 @@
"cpu": [
"arm64"
],
+ "dev": true,
"optional": true,
"os": [
"freebsd"
@@ -6127,6 +6185,7 @@
"cpu": [
"x64"
],
+ "dev": true,
"optional": true,
"os": [
"freebsd"
@@ -6139,6 +6198,7 @@
"cpu": [
"arm"
],
+ "dev": true,
"optional": true,
"os": [
"linux"
@@ -6151,6 +6211,7 @@
"cpu": [
"arm"
],
+ "dev": true,
"optional": true,
"os": [
"linux"
@@ -6163,6 +6224,7 @@
"cpu": [
"arm64"
],
+ "dev": true,
"optional": true,
"os": [
"linux"
@@ -6175,6 +6237,7 @@
"cpu": [
"arm64"
],
+ "dev": true,
"optional": true,
"os": [
"linux"
@@ -6187,6 +6250,7 @@
"cpu": [
"loong64"
],
+ "dev": true,
"optional": true,
"os": [
"linux"
@@ -6199,6 +6263,7 @@
"cpu": [
"loong64"
],
+ "dev": true,
"optional": true,
"os": [
"linux"
@@ -6211,6 +6276,7 @@
"cpu": [
"ppc64"
],
+ "dev": true,
"optional": true,
"os": [
"linux"
@@ -6223,6 +6289,7 @@
"cpu": [
"ppc64"
],
+ "dev": true,
"optional": true,
"os": [
"linux"
@@ -6235,6 +6302,7 @@
"cpu": [
"riscv64"
],
+ "dev": true,
"optional": true,
"os": [
"linux"
@@ -6247,6 +6315,7 @@
"cpu": [
"riscv64"
],
+ "dev": true,
"optional": true,
"os": [
"linux"
@@ -6259,6 +6328,7 @@
"cpu": [
"s390x"
],
+ "dev": true,
"optional": true,
"os": [
"linux"
@@ -6271,6 +6341,7 @@
"cpu": [
"x64"
],
+ "dev": true,
"optional": true,
"os": [
"linux"
@@ -6283,6 +6354,7 @@
"cpu": [
"x64"
],
+ "dev": true,
"optional": true,
"os": [
"linux"
@@ -6295,6 +6367,7 @@
"cpu": [
"x64"
],
+ "dev": true,
"optional": true,
"os": [
"openbsd"
@@ -6307,6 +6380,7 @@
"cpu": [
"arm64"
],
+ "dev": true,
"optional": true,
"os": [
"openharmony"
@@ -6319,6 +6393,7 @@
"cpu": [
"arm64"
],
+ "dev": true,
"optional": true,
"os": [
"win32"
@@ -6331,6 +6406,7 @@
"cpu": [
"ia32"
],
+ "dev": true,
"optional": true,
"os": [
"win32"
@@ -6343,6 +6419,7 @@
"cpu": [
"x64"
],
+ "dev": true,
"optional": true,
"os": [
"win32"
@@ -6355,6 +6432,7 @@
"cpu": [
"x64"
],
+ "dev": true,
"optional": true,
"os": [
"win32"
@@ -13292,6 +13370,15 @@
"node": ">=20.12.0"
}
},
+ "node_modules/expo-crypto": {
+ "version": "56.0.4",
+ "resolved": "https://registry.npmjs.org/expo-crypto/-/expo-crypto-56.0.4.tgz",
+ "integrity": "sha512-fRNEhoXRXgAWBpe3/hq5X+KXTit3OZqdiAGts1YvNEUHQb+H5591mpPac0Yw+sZg9pXcrjRnzo5AxvZaENpc7g==",
+ "license": "MIT",
+ "peerDependencies": {
+ "expo": "*"
+ }
+ },
"node_modules/expo-document-picker": {
"version": "56.0.4",
"license": "MIT",
@@ -14548,6 +14635,7 @@
"version": "2.3.3",
"resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz",
"integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==",
+ "dev": true,
"optional": true,
"os": [
"darwin"
@@ -20106,6 +20194,32 @@
"react-native": "*"
}
},
+ "node_modules/react-native-purchases": {
+ "version": "10.7.0",
+ "resolved": "https://registry.npmjs.org/react-native-purchases/-/react-native-purchases-10.7.0.tgz",
+ "integrity": "sha512-+ow00d8foBDeLiJniXW94P+nUhmyzK91LxKnigwQ2YxAbaBugr/LWpWaSQTDnZ+dL9iJQODvldmIXUiRm9KrXw==",
+ "license": "MIT",
+ "workspaces": [
+ "examples/purchaseTesterTypescript",
+ "react-native-purchases-store-galaxy",
+ "react-native-purchases-ui",
+ "e2e-tests/MaestroTestApp"
+ ],
+ "dependencies": {
+ "@revenuecat/purchases-js-hybrid-mappings": "18.29.0",
+ "@revenuecat/purchases-typescript-internal": "18.29.0"
+ },
+ "peerDependencies": {
+ "react": ">= 16.6.3",
+ "react-native": ">= 0.73.0",
+ "react-native-web": "*"
+ },
+ "peerDependenciesMeta": {
+ "react-native-web": {
+ "optional": true
+ }
+ }
+ },
"node_modules/react-native-qrcode-svg": {
"version": "6.3.21",
"license": "MIT",
@@ -22351,6 +22465,14 @@
"node": ">=4"
}
},
+ "node_modules/string_decoder": {
+ "version": "1.3.0",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "safe-buffer": "~5.2.0"
+ }
+ },
"node_modules/string-argv": {
"version": "0.3.2",
"dev": true,
@@ -22427,14 +22549,6 @@
"url": "https://github.com/chalk/strip-ansi?sponsor=1"
}
},
- "node_modules/string_decoder": {
- "version": "1.3.0",
- "dev": true,
- "license": "MIT",
- "dependencies": {
- "safe-buffer": "~5.2.0"
- }
- },
"node_modules/strip-ansi": {
"version": "6.0.1",
"license": "MIT",
@@ -24909,12 +25023,16 @@
"vitest": "^4.1.8"
},
"peerDependencies": {
+ "@expo/ui": "*",
"lucide-react": "*",
"lucide-react-native": "*",
"react": "^19.0.0",
"react-dom": "^19.0.0"
},
"peerDependenciesMeta": {
+ "@expo/ui": {
+ "optional": true
+ },
"lucide-react": {
"optional": true
},
diff --git a/packages/components/src/components/AccountCodeCard/AccountCodeCard.tsx b/packages/components/src/components/AccountCodeCard/AccountCodeCard.tsx
new file mode 100644
index 0000000..d14c816
--- /dev/null
+++ b/packages/components/src/components/AccountCodeCard/AccountCodeCard.tsx
@@ -0,0 +1,103 @@
+import { useState } from 'react'
+import { html } from 'react-strict-dom'
+import { formatAccountCode, maskAccountCode } from '@altersend/domain'
+import { CheckIcon, CopyIcon, DownloadIcon, EyeIcon, EyeOffIcon } from '../../icons'
+import { Button } from '../Button'
+import { styles } from './styles'
+
+export interface AccountCodeCardProps {
+ code: string
+ label: string
+ copyLabel: string
+ copiedLabel: string
+ copied?: boolean
+ hidden?: boolean
+ inline?: boolean
+ attached?: boolean
+ revealLabel?: string
+ hideLabel?: string
+ saveLabel?: string
+ savedLabel?: string
+ saved?: boolean
+ onCopy: () => void
+ onSave?: () => void
+ onToggleReveal?: (revealed: boolean) => void
+}
+
+export function AccountCodeCard({
+ code,
+ label,
+ copyLabel,
+ copiedLabel,
+ copied = false,
+ hidden = false,
+ inline = false,
+ attached = false,
+ revealLabel,
+ hideLabel,
+ saveLabel,
+ savedLabel,
+ saved = false,
+ onCopy,
+ onSave,
+ onToggleReveal
+}: AccountCodeCardProps) {
+ const [revealed, setRevealed] = useState(false)
+ const masked = hidden && !revealed
+ const value = masked ? maskAccountCode(code) : formatAccountCode(code)
+
+ const actions = (
+ <html.div style={styles.actions}>
+ {hidden ? (
+ <Button
+ size='sm'
+ variant='surface'
+ iconOnly
+ aria-label={revealed ? hideLabel : revealLabel}
+ icon={revealed ? <EyeOffIcon size={16} /> : <EyeIcon size={16} />}
+ onClick={() => {
+ setRevealed((current) => !current)
+ onToggleReveal?.(!revealed)
+ }}
+ />
+ ) : null}
+ <Button
+ size='sm'
+ variant={copied ? 'success' : 'surface'}
+ iconOnly
+ aria-label={copied ? copiedLabel : copyLabel}
+ icon={copied ? <CheckIcon size={16} /> : <CopyIcon size={16} />}
+ onClick={onCopy}
+ />
+ {onSave ? (
+ <Button
+ size='sm'
+ variant={saved ? 'success' : 'surface'}
+ iconOnly
+ aria-label={saved ? savedLabel : saveLabel}
+ icon={saved ? <CheckIcon size={16} /> : <DownloadIcon size={16} />}
+ onClick={onSave}
+ />
+ ) : null}
+ </html.div>
+ )
+
+ return (
+ <html.div style={[styles.card, attached && styles.cardAttached]}>
+ <html.div style={[styles.row, inline && styles.rowInline]}>
+ {inline ? (
+ <>
+ <html.p style={styles.inlineLabel}>{label}</html.p>
+ <html.p style={[styles.code, styles.codeInline]}>{value}</html.p>
+ </>
+ ) : (
+ <html.div style={styles.text}>
+ <html.p style={styles.label}>{label}</html.p>
+ <html.p style={styles.code}>{value}</html.p>
+ </html.div>
+ )}
+ {actions}
+ </html.div>
+ </html.div>
+ )
+}
diff --git a/packages/components/src/components/AccountCodeCard/index.ts b/packages/components/src/components/AccountCodeCard/index.ts
new file mode 100644
index 0000000..b69a57e
--- /dev/null
+++ b/packages/components/src/components/AccountCodeCard/index.ts
@@ -0,0 +1 @@
+export * from './AccountCodeCard'
diff --git a/packages/components/src/components/AccountCodeCard/styles.ts b/packages/components/src/components/AccountCodeCard/styles.ts
new file mode 100644
index 0000000..004b656
--- /dev/null
+++ b/packages/components/src/components/AccountCodeCard/styles.ts
@@ -0,0 +1,74 @@
+import { css } from 'react-strict-dom'
+import { fontTokens, tokens } from '../../theme/tokens.css'
+
+export const styles = css.create({
+ card: {
+ borderWidth: 1,
+ borderStyle: 'solid',
+ borderColor: tokens.colorBorderPrimary,
+ borderRadius: tokens.radiusLg,
+ backgroundColor: tokens.colorBackgroundSubtle
+ },
+ cardAttached: {
+ borderWidth: 0,
+ borderRadius: 0,
+ backgroundColor: 'transparent'
+ },
+ row: {
+ display: 'flex',
+ flexDirection: 'row',
+ alignItems: 'center',
+ justifyContent: 'space-between',
+ gap: tokens.space3,
+ paddingBlock: tokens.space35,
+ paddingInline: tokens.space4
+ },
+ rowInline: {
+ alignItems: 'center',
+ paddingBlock: tokens.space3
+ },
+ inlineLabel: {
+ margin: 0,
+ flexGrow: 1,
+ flexShrink: 1,
+ flexBasis: 0,
+ minWidth: 0,
+ color: tokens.colorTextPrimary,
+ fontFamily: fontTokens.fontFamilySans,
+ fontSize: tokens.fontSizeBase,
+ fontWeight: tokens.fontWeightMedium,
+ lineHeight: tokens.lineHeightNormal
+ },
+ codeInline: {
+ fontSize: tokens.fontSizeBase,
+ color: tokens.colorTextSecondary
+ },
+ actions: {
+ display: 'flex',
+ flexDirection: 'row',
+ alignItems: 'center',
+ gap: tokens.space2
+ },
+ text: {
+ display: 'flex',
+ flexDirection: 'column',
+ gap: tokens.space1,
+ minWidth: 0
+ },
+ label: {
+ margin: 0,
+ color: tokens.colorTextPrimary,
+ fontFamily: fontTokens.fontFamilySans,
+ fontSize: tokens.fontSizeLg,
+ fontWeight: tokens.fontWeightMedium,
+ lineHeight: tokens.lineHeightNormal
+ },
+ code: {
+ margin: 0,
+ color: tokens.colorTextPrimary,
+ fontFamily: fontTokens.fontFamilyMono,
+ fontSize: tokens.fontSizeXl,
+ lineHeight: tokens.lineHeightSnug,
+ letterSpacing: 1
+ }
+})
diff --git a/packages/components/src/components/Button/Button.tsx b/packages/components/src/components/Button/Button.tsx
index ca70c12..113f941 100644
--- a/packages/components/src/components/Button/Button.tsx
+++ b/packages/components/src/components/Button/Button.tsx
@@ -11,6 +11,7 @@ type ButtonElementProps = Parameters<typeof html.button>[0]
export type ButtonVariant =
| 'primary'
| 'secondary'
+ | 'surface'
| 'outline'
| 'ghost'
| 'light'
@@ -36,6 +37,7 @@ export interface ButtonProps extends Omit<ButtonElementProps, 'children' | 'styl
const pressedStyle = {
primary: styles.primaryPressed,
secondary: styles.secondaryPressed,
+ surface: styles.surfacePressed,
outline: styles.outlinePressed,
ghost: styles.ghostPressed,
light: styles.lightPressed,
@@ -52,6 +54,7 @@ const textSize = {
const textVariant = {
primary: styles.textPrimary,
secondary: styles.textSecondary,
+ surface: styles.textSecondary,
outline: styles.textOutline,
ghost: styles.textGhost,
light: styles.textLight,
@@ -68,6 +71,7 @@ const normalIconColor: Record<ButtonVariant, keyof ReturnType<typeof useTheme>['
{
primary: 'colorBackground',
secondary: 'colorTextPrimary',
+ surface: 'colorTextPrimary',
outline: 'colorTextPrimary',
ghost: 'colorTextSecondary',
light: 'colorOnAccent',
diff --git a/packages/components/src/components/Button/styles.ts b/packages/components/src/components/Button/styles.ts
index 1d827d0..abad356 100644
--- a/packages/components/src/components/Button/styles.ts
+++ b/packages/components/src/components/Button/styles.ts
@@ -118,6 +118,23 @@ export const styles = css.create({
secondaryPressed: {
backgroundColor: tokens.colorSurfaceSecondary
},
+ surface: {
+ backgroundColor: tokens.colorSurfacePrimary,
+ borderColor: tokens.colorBorderPrimary,
+ color: tokens.colorTextPrimary,
+ boxShadow: 'none',
+ ':hover': {
+ backgroundColor: tokens.colorSurfaceSecondary,
+ borderColor: tokens.colorBorderStrong
+ },
+ ':focus-visible': {
+ outline: 'none',
+ boxShadow: `0 0 0 2px ${tokens.colorFocusRing}`
+ }
+ },
+ surfacePressed: {
+ backgroundColor: tokens.colorSurfaceSecondary
+ },
outline: {
backgroundColor: tokens.colorBackgroundSubtle,
borderColor: tokens.colorBorderStrong,
diff --git a/packages/components/src/components/LinkRow/LinkRow.tsx b/packages/components/src/components/LinkRow/LinkRow.tsx
index 5dce6a7..cff75c0 100644
--- a/packages/components/src/components/LinkRow/LinkRow.tsx
+++ b/packages/components/src/components/LinkRow/LinkRow.tsx
@@ -28,6 +28,7 @@ interface LinkRowBaseProps {
subtitleWrap?: boolean
description?: string
isActive?: boolean
+ selected?: boolean
isFirst?: boolean
trailing?: ReactNode
onPress?: () => void
@@ -95,6 +96,7 @@ export function LinkRow({
subtitleWrap = false,
description,
isActive,
+ selected,
isFirst = false,
trailing,
onPress,
@@ -183,6 +185,7 @@ export function LinkRow({
alignTop && styles.rowAlignTop,
onPress && !disabled && styles.rowPressable,
isActive && styles.rowActive,
+ selected && styles.rowSelected,
interactive &&
isPressed &&
({ backgroundColor: theme.colors.colorSurfacePrimary } as never)
diff --git a/packages/components/src/components/LinkRow/styles.ts b/packages/components/src/components/LinkRow/styles.ts
index 876c33f..ad5b6ce 100644
--- a/packages/components/src/components/LinkRow/styles.ts
+++ b/packages/components/src/components/LinkRow/styles.ts
@@ -78,6 +78,13 @@ export const styles = css.create({
rowActive: {
backgroundColor: tokens.colorSurfacePrimary
},
+ rowSelected: {
+ borderColor: tokens.colorAccent,
+ backgroundColor: tokens.colorSurfacePrimary,
+ ':hover': {
+ borderColor: tokens.colorAccent
+ }
+ },
iconBox: {
width: tokens.space9,
height: tokens.space9,
diff --git a/packages/components/src/components/SuccessBurst/SuccessBurst.native.tsx b/packages/components/src/components/SuccessBurst/SuccessBurst.native.tsx
new file mode 100644
index 0000000..b1eb8c9
--- /dev/null
+++ b/packages/components/src/components/SuccessBurst/SuccessBurst.native.tsx
@@ -0,0 +1,104 @@
+import { useEffect, useRef, type ReactNode } from 'react'
+import { Animated, Easing, StyleSheet, View } from 'react-native'
+import { BURST_DURATION_MS, PIECES, PIECE_SIZE } from './constants'
+
+export interface SuccessBurstProps {
+ icon: ReactNode
+ markColor: string
+ tones: string[]
+ size?: number
+ play?: boolean
+}
+
+export function SuccessBurst({
+ icon,
+ markColor,
+ tones,
+ size = 96,
+ play = true
+}: SuccessBurstProps) {
+ const mark = useRef(new Animated.Value(0)).current
+ const burst = useRef(new Animated.Value(0)).current
+ const reach = size * 1.9
+
+ useEffect(() => {
+ if (!play) return
+
+ const animation = Animated.parallel([
+ Animated.spring(mark, { toValue: 1, friction: 5, tension: 90, useNativeDriver: true }),
+ Animated.timing(burst, {
+ toValue: 1,
+ duration: BURST_DURATION_MS,
+ easing: Easing.out(Easing.cubic),
+ useNativeDriver: true
+ })
+ ])
+
+ animation.start()
+ return () => animation.stop()
+ }, [burst, mark, play])
+
+ return (
+ <View style={[styles.wrap, { width: size * 3, height: size * 3 }]} pointerEvents='none'>
+ {PIECES.map((piece, i) => (
+ <Animated.View
+ key={i}
+ style={[
+ styles.piece,
+ {
+ backgroundColor: tones[piece.tone % tones.length],
+ opacity: burst.interpolate({ inputRange: [0, 0.75, 1], outputRange: [1, 1, 0] }),
+ transform: [
+ {
+ translateX: burst.interpolate({
+ inputRange: [0, 1],
+ outputRange: [0, piece.x * reach]
+ })
+ },
+ {
+ translateY: burst.interpolate({
+ inputRange: [0, 1],
+ outputRange: [0, piece.y * reach + piece.drift * size]
+ })
+ },
+ {
+ rotate: burst.interpolate({
+ inputRange: [0, 1],
+ outputRange: [`${piece.tilt}deg`, `${piece.tilt + 220}deg`]
+ })
+ }
+ ]
+ }
+ ]}
+ />
+ ))}
+
+ <Animated.View
+ style={[
+ styles.mark,
+ {
+ width: size,
+ height: size,
+ borderRadius: size / 2,
+ backgroundColor: markColor,
+ opacity: mark,
+ transform: [{ scale: mark }]
+ }
+ ]}
+ >
+ {icon}
+ </Animated.View>
+ </View>
+ )
+}
+
+const styles = StyleSheet.create({
+ wrap: { alignItems: 'center', justifyContent: 'center' },
+ piece: {
+ position: 'absolute',
+ width: PIECE_SIZE,
+ height: PIECE_SIZE * 2,
+ borderRadius: PIECE_SIZE / 2
+ },
+ mark: { alignItems: 'center', justifyContent: 'center' }
+})
diff --git a/packages/components/src/components/SuccessBurst/SuccessBurst.tsx b/packages/components/src/components/SuccessBurst/SuccessBurst.tsx
new file mode 100644
index 0000000..1ced551
--- /dev/null
+++ b/packages/components/src/components/SuccessBurst/SuccessBurst.tsx
@@ -0,0 +1,100 @@
+import { useEffect, useState, type ReactNode } from 'react'
+import { css, html } from 'react-strict-dom'
+import { BURST_DURATION_MS, MARK_DURATION_MS, PIECES, PIECE_SIZE } from './constants'
+
+export interface SuccessBurstProps {
+ icon: ReactNode
+ markColor: string
+ tones: string[]
+ size?: number
+ play?: boolean
+}
+
+const pop = css.keyframes({
+ '0%': { transform: 'scale(0.2)', opacity: 0 },
+ '70%': { transform: 'scale(1.08)', opacity: 1 },
+ '100%': { transform: 'scale(1)', opacity: 1 }
+})
+
+const styles = css.create({
+ wrap: {
+ position: 'relative',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center'
+ },
+ piece: {
+ position: 'absolute',
+ transitionProperty: 'transform, opacity',
+ transitionTimingFunction: 'cubic-bezier(0.16, 1, 0.3, 1)'
+ },
+ mark: {
+ position: 'relative',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ animationName: pop,
+ animationTimingFunction: 'cubic-bezier(0.34, 1.56, 0.64, 1)',
+ animationFillMode: 'backwards'
+ }
+})
+
+export function SuccessBurst({
+ icon,
+ markColor,
+ tones,
+ size = 96,
+ play = true
+}: SuccessBurstProps) {
+ const [launched, setLaunched] = useState(false)
+ const reach = size * 1.9
+
+ useEffect(() => {
+ if (!play) return
+ const frame = requestAnimationFrame(() => setLaunched(true))
+ return () => cancelAnimationFrame(frame)
+ }, [play])
+
+ return (
+ <html.div style={[styles.wrap, { width: size * 3, height: size * 3 } as never]}>
+ {play &&
+ PIECES.map((piece, i) => (
+ <html.div
+ key={i}
+ style={[
+ styles.piece,
+ {
+ width: PIECE_SIZE,
+ height: PIECE_SIZE * 2,
+ borderRadius: PIECE_SIZE / 2,
+ backgroundColor: tones[piece.tone % tones.length],
+ transitionDuration: `${BURST_DURATION_MS}ms`,
+ transitionDelay: `${piece.delay}ms`,
+ opacity: launched ? 0 : 1,
+ transform: launched
+ ? `translate(${piece.x * reach}px, ${
+ piece.y * reach + piece.drift * size
+ }px) rotate(220deg)`
+ : 'translate(0px, 0px) rotate(0deg)'
+ } as never
+ ]}
+ />
+ ))}
+
+ <html.div
+ style={[
+ styles.mark,
+ {
+ width: size,
+ height: size,
+ borderRadius: '50%',
+ backgroundColor: markColor,
+ animationDuration: `${MARK_DURATION_MS}ms`
+ } as never
+ ]}
+ >
+ {icon}
+ </html.div>
+ </html.div>
+ )
+}
diff --git a/packages/components/src/components/SuccessBurst/constants.ts b/packages/components/src/components/SuccessBurst/constants.ts
new file mode 100644
index 0000000..fc18236
--- /dev/null
+++ b/packages/components/src/components/SuccessBurst/constants.ts
@@ -0,0 +1,17 @@
+const BURST_PIECES = 22
+export const BURST_DURATION_MS = 1900
+export const MARK_DURATION_MS = 420
+export const PIECE_SIZE = 8
+
+export const PIECES = Array.from({ length: BURST_PIECES }, (_, i) => {
+ const angle = (i / BURST_PIECES) * Math.PI * 2
+ const spread = 0.62 + ((i * 37) % 40) / 100
+ return {
+ x: Math.cos(angle) * spread,
+ y: Math.sin(angle) * spread,
+ drift: ((i * 53) % 30) / 100,
+ delay: ((i * 29) % 22) * 10,
+ tilt: (i * 47) % 360,
+ tone: i % 4
+ }
+})
diff --git a/packages/components/src/components/SuccessBurst/index.ts b/packages/components/src/components/SuccessBurst/index.ts
new file mode 100644
index 0000000..84bd078
--- /dev/null
+++ b/packages/components/src/components/SuccessBurst/index.ts
@@ -0,0 +1,2 @@
+export { SuccessBurst } from './SuccessBurst'
+export type { SuccessBurstProps } from './SuccessBurst'
diff --git a/packages/components/src/components/index.ts b/packages/components/src/components/index.ts
index 19de21e..0cf2e55 100644
--- a/packages/components/src/components/index.ts
+++ b/packages/components/src/components/index.ts
@@ -1,3 +1,4 @@
+export * from './AccountCodeCard/index'
export * from './AppearancePicker/index'
export * from './Badge/index'
export * from './Button/index'
@@ -20,6 +21,7 @@ export * from './PeerListCard/index'
export * from './ReceivedTextRow/index'
export * from './RowGroup/index'
export * from './Spinner/index'
+export * from './SuccessBurst/index'
export * from './Tabs/index'
export * from './Textarea/index'
export * from './ToggleSwitch/index'
diff --git a/packages/components/src/icons/set.tsx b/packages/components/src/icons/set.tsx
index 7245f48..52bb1f4 100644
--- a/packages/components/src/icons/set.tsx
+++ b/packages/components/src/icons/set.tsx
@@ -3,6 +3,7 @@ import {
AppWindow,
Archive,
ArrowLeft,
+ ArrowUpCircle,
ArrowUpRight,
Bell,
Camera,
@@ -50,6 +51,10 @@ import {
Settings,
Share2,
Shield,
+ Eye,
+ EyeOff,
+ LogOut,
+ User,
SlidersHorizontal,
Smartphone,
Sun,
@@ -69,6 +74,7 @@ export { AppleIcon, DiscordIcon, GithubIcon, WindowsIcon, XIcon } from './svgIco
export const AlertCircleIcon = adaptLucide(AlertCircle)
export const ArchiveIcon = adaptLucide(Archive)
export const ArrowLeftIcon = adaptLucide(ArrowLeft)
+export const ArrowUpCircleIcon = adaptLucide(ArrowUpCircle)
export const ArrowUpRightIcon = adaptLucide(ArrowUpRight)
export const AppWindowIcon = adaptLucide(AppWindow)
export const BellIcon = adaptLucide(Bell)
@@ -117,6 +123,10 @@ export const SendIcon = adaptLucide(Send)
export const SettingsIcon = adaptLucide(Settings)
export const ShareIcon = adaptLucide(Share2)
export const ShieldIcon = adaptLucide(Shield)
+export const LogOutIcon = adaptLucide(LogOut)
+export const EyeIcon = adaptLucide(Eye)
+export const EyeOffIcon = adaptLucide(EyeOff)
+export const UserIcon = adaptLucide(User)
export const SlidersHorizontalIcon = adaptLucide(SlidersHorizontal)
export const SmartphoneIcon = adaptLucide(Smartphone)
export const TrashIcon = adaptLucide(Trash2)
diff --git a/packages/components/src/theme/heroBackdrop.ts b/packages/components/src/theme/heroBackdrop.ts
new file mode 100644
index 0000000..c94261e
--- /dev/null
+++ b/packages/components/src/theme/heroBackdrop.ts
@@ -0,0 +1,28 @@
+export interface HeroBackdropStop {
+ offset: number
+ alpha: number
+}
+
+export const heroBackdrop = {
+ height: 300,
+ gridSize: 32,
+ gridAlpha: 0.12,
+ glowCenter: { x: 50, y: 0, radiusX: 72, radiusY: 58 },
+ maskCenter: { x: 50, y: 30, radiusX: 72, radiusY: 62 },
+ wash: [
+ { offset: 0, alpha: 0.16 },
+ { offset: 0.28, alpha: 0.08 },
+ { offset: 0.52, alpha: 0.03 },
+ { offset: 0.78, alpha: 0 }
+ ] as HeroBackdropStop[],
+ glow: [
+ { offset: 0, alpha: 0.18 },
+ { offset: 0.56, alpha: 0.05 },
+ { offset: 1, alpha: 0 }
+ ] as HeroBackdropStop[],
+ mask: [
+ { offset: 0, alpha: 1 },
+ { offset: 0.52, alpha: 0.55 },
+ { offset: 0.84, alpha: 0 }
+ ] as HeroBackdropStop[]
+}
diff --git a/packages/components/src/theme/index.ts b/packages/components/src/theme/index.ts
index e7aa687..d839e39 100644
--- a/packages/components/src/theme/index.ts
+++ b/packages/components/src/theme/index.ts
@@ -12,6 +12,7 @@ export {
export { getSystemTheme } from './useSystemTheme'
export { applyDocumentTheme } from './documentTheme'
export { qrColors } from './qrColors'
+export { heroBackdrop, type HeroBackdropStop } from './heroBackdrop'
export { withAlpha } from './withAlpha'
export { fileTypeColors, type FileTypeColor, type FileTypeKey } from './fileTypeColors'
export { space, radius, fontSize, fontWeight, lineHeight, fontFamily } from './scales'
diff --git a/packages/core/src/types.d.ts b/packages/core/src/types.d.ts
index 7efe310..e6d83e4 100644
--- a/packages/core/src/types.d.ts
+++ b/packages/core/src/types.d.ts
@@ -132,6 +132,9 @@ declare module 'hyperswarm' {
firewall?: (remotePublicKey: Uint8Array) => boolean
relayThrough?: ((force: boolean, swarm: unknown) => Uint8Array[] | null) | Uint8Array[] | null
})
+ readonly dht: {
+ connect(publicKey: Uint8Array, opts?: unknown): unknown
+ }
join(
discoveryKey: Uint8Array,
opts?: { server?: boolean; client?: boolean }
@@ -165,7 +168,7 @@ declare module 'protomux' {
export interface ProtomuxChannel {
addMessage<T = unknown>(opts: {
encoding: unknown
- onmessage: (message: T) => void
+ onmessage?: (message: T) => void
}): ProtomuxMessage<T>
open(): void
close(): void
diff --git a/packages/core/src/worklet/relay/announce.ts b/packages/core/src/worklet/relay/announce.ts
new file mode 100644
index 0000000..204a76b
--- /dev/null
+++ b/packages/core/src/worklet/relay/announce.ts
@@ -0,0 +1,43 @@
+import Protomux from 'protomux'
+import c from 'compact-encoding'
+import { proTokenFor } from './config'
+
+const PROTOCOL = 'altersend-pro'
+
+export function announceProToken(
+ socket: unknown,
+ token: string,
+ cid: string | null = null
+): boolean {
+ try {
+ const mux = Protomux.from(socket)
+ const channel = mux.createChannel({ protocol: PROTOCOL })
+ if (!channel) return false
+
+ const message = channel.addMessage<string>({ encoding: c.string })
+ channel.open()
+ message.send(JSON.stringify({ token, cid }))
+ return true
+ } catch {
+ return false
+ }
+}
+
+interface DialTarget {
+ connect(publicKey: Uint8Array, opts?: unknown): unknown
+}
+
+const attached = new WeakSet<DialTarget>()
+
+export function attachProAnnounce(dht: DialTarget): void {
+ if (attached.has(dht)) return
+ attached.add(dht)
+
+ const connect = dht.connect.bind(dht)
+ dht.connect = (publicKey: Uint8Array, opts?: unknown) => {
+ const socket = connect(publicKey, opts)
+ const token = proTokenFor(publicKey)
+ if (token) announceProToken(socket, token)
+ return socket
+ }
+}
diff --git a/packages/core/src/worklet/relay/conf.ts b/packages/core/src/worklet/relay/conf.ts
index 1da1b30..776c01d 100644
--- a/packages/core/src/worklet/relay/conf.ts
+++ b/packages/core/src/worklet/relay/conf.ts
@@ -102,15 +102,20 @@ async function tryFetch(dht: DHT): Promise<boolean> {
try {
const record = await dht.mutableGet(pubkey, { latest: true })
if (!record?.value) return false
- const parsed = JSON.parse(b4a.toString(record.value, 'utf8')) as { relays?: unknown }
+ const parsed = JSON.parse(b4a.toString(record.value, 'utf8')) as {
+ relays?: unknown
+ web?: unknown
+ }
if (
Array.isArray(parsed.relays) &&
parsed.relays.length > 0 &&
parsed.relays.every(isValidEntry)
) {
const relays = parsed.relays as RelayRecordEntry[]
+ const web = Array.isArray(parsed.web) ? parsed.web.filter(isValidEntry) : []
configureRelay({
- relays: relays.map((r) => ({ keyHex: r.key, host: r.host, utcOffset: recordUtcOffset(r) }))
+ relays: relays.map((r) => ({ keyHex: r.key, host: r.host, utcOffset: recordUtcOffset(r) })),
+ webRelays: web.map((r) => ({ keyHex: r.key, host: r.host }))
})
return true
}
diff --git a/packages/core/src/worklet/relay/config.test.ts b/packages/core/src/worklet/relay/config.test.ts
index 260dec0..603b2cd 100644
--- a/packages/core/src/worklet/relay/config.test.ts
+++ b/packages/core/src/worklet/relay/config.test.ts
@@ -1,6 +1,13 @@
import b4a from 'b4a'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
-import { configureRelay, isRelayHost, relayConfigSummary, relayThrough } from './config'
+import {
+ configureRelay,
+ isRelayHost,
+ proTokenFor,
+ relayConfigSummary,
+ relayThrough,
+ setRelaySending
+} from './config'
const KEY_A = 'a'.repeat(64)
const HOST_A = '1.2.3.4'
@@ -15,7 +22,8 @@ function mockUtcOffset(minutes: number): void {
}
beforeEach(() => {
- configureRelay({ enabled: false, relays: [] })
+ configureRelay({ enabled: false, relays: [], proToken: null })
+ setRelaySending(false)
})
afterEach(() => {
@@ -105,3 +113,45 @@ describe('relay/config', () => {
expect(isRelayHost(HOST_A)).toBe(false)
})
})
+
+const RELAY_KEY = 'aa'.repeat(32)
+const OTHER_KEY = 'bb'.repeat(32)
+const TOKEN = 'signed.token'
+
+function relayKey(): Uint8Array {
+ return b4a.from(RELAY_KEY, 'hex')
+}
+
+describe('proTokenFor', () => {
+ beforeEach(() => {
+ configureRelay({
+ enabled: true,
+ relays: [{ keyHex: RELAY_KEY, host: '1.2.3.4' }],
+ proToken: TOKEN
+ })
+ setRelaySending(true)
+ })
+
+ it('announces to a known relay while sending', () => {
+ expect(proTokenFor(relayKey())).toBe(TOKEN)
+ })
+
+ it('stays silent while receiving', () => {
+ setRelaySending(false)
+ expect(proTokenFor(relayKey())).toBeNull()
+ })
+
+ it('stays silent with no token', () => {
+ configureRelay({ proToken: null })
+ expect(proTokenFor(relayKey())).toBeNull()
+ })
+
+ it('never announces to a key that is not a configured relay', () => {
+ expect(proTokenFor(b4a.from(OTHER_KEY, 'hex'))).toBeNull()
+ })
+
+ it('keeps the token when unrelated config changes', () => {
+ configureRelay({ enabled: true })
+ expect(proTokenFor(relayKey())).toBe(TOKEN)
+ })
+})
diff --git a/packages/core/src/worklet/relay/config.ts b/packages/core/src/worklet/relay/config.ts
index 3e6d7cf..33580b1 100644
--- a/packages/core/src/worklet/relay/config.ts
+++ b/packages/core/src/worklet/relay/config.ts
@@ -6,14 +6,25 @@ interface RelayEntry {
utcOffset: number | null
}
+interface WebRelayEntry {
+ key: Uint8Array
+ host: string
+}
+
interface RelayState {
enabled: boolean
relays: RelayEntry[]
+ webRelays: WebRelayEntry[]
+ proToken: string | null
+ sending: boolean
}
const state: RelayState = {
enabled: false,
- relays: []
+ relays: [],
+ webRelays: [],
+ proToken: null,
+ sending: false
}
let relayLoader: (() => void) | null = null
@@ -28,9 +39,16 @@ interface RelayEntryInput {
utcOffset?: number
}
+interface WebRelayEntryInput {
+ keyHex: string
+ host: string
+}
+
export interface RelayConfigInput {
enabled?: boolean
relays?: readonly RelayEntryInput[]
+ webRelays?: readonly WebRelayEntryInput[]
+ proToken?: string | null
}
function toRelayEntry({ keyHex, host, utcOffset }: RelayEntryInput): RelayEntry {
@@ -46,9 +64,30 @@ export function configureRelay(input: RelayConfigInput): void {
state.relays = input.relays.map(toRelayEntry)
}
+ if (input.webRelays) {
+ state.webRelays = input.webRelays.map(({ keyHex, host }) => ({
+ key: b4a.from(keyHex, 'hex'),
+ host
+ }))
+ }
+
+ if (input.proToken !== undefined) {
+ state.proToken = input.proToken
+ }
+
if (state.enabled) relayLoader?.()
}
+export function setRelaySending(sending: boolean): void {
+ state.sending = sending
+}
+
+export function proTokenFor(key: Uint8Array): string | null {
+ if (!state.proToken || !state.sending) return null
+ if (!state.relays.some((relay) => b4a.equals(relay.key, key))) return null
+ return state.proToken
+}
+
export function relayConfigSummary(): { enabled: boolean; keyCount: number } {
return { enabled: state.enabled, keyCount: state.relays.length }
}
@@ -75,3 +114,21 @@ export function relayThrough(_force: boolean, _swarm?: unknown): Uint8Array[] |
export function isRelayHost(host: string | null | undefined): boolean {
return !!host && state.relays.some((r) => r.host === host)
}
+
+function bareHost(host: string): string {
+ return host
+ .replace(/^wss?:\/\//, '')
+ .replace(/\/.*$/, '')
+ .replace(/:\d+$/, '')
+ .toLowerCase()
+}
+
+export function webRelayKeyForHost(host: string): Uint8Array | null {
+ if (!state.proToken || !state.sending) return null
+ const wanted = bareHost(host)
+ return state.webRelays.find((relay) => bareHost(relay.host) === wanted)?.key ?? null
+}
+
+export function proToken(): string | null {
+ return state.proToken
+}
diff --git a/packages/core/src/worklet/relay/upgradeWebRelay.ts b/packages/core/src/worklet/relay/upgradeWebRelay.ts
new file mode 100644
index 0000000..886b288
--- /dev/null
+++ b/packages/core/src/worklet/relay/upgradeWebRelay.ts
@@ -0,0 +1,40 @@
+import DHT from 'hyperdht'
+import { announceProToken } from './announce'
+import { proToken, webRelayKeyForHost } from './config'
+
+const SETTLE_MS = 1500
+
+interface Dialable {
+ connect(publicKey: Uint8Array, opts?: unknown): unknown
+ destroy(): Promise<void>
+}
+
+interface Closable {
+ destroy(): void
+}
+
+export async function upgradeWebRelay(cid: string, host: string): Promise<boolean> {
+ const token = proToken()
+ const key = webRelayKeyForHost(host)
+ if (!token || !key) return false
+
+ const dht = new DHT() as unknown as Dialable
+
+ try {
+ const socket = dht.connect(key) as Closable
+ const announced = announceProToken(socket, token, cid)
+
+ if (announced) {
+ await new Promise((resolve) => setTimeout(resolve, SETTLE_MS))
+ }
+
+ socket.destroy()
+ return announced
+ } catch {
+ return false
+ } finally {
+ await dht.destroy().catch((err) => {
+ console.warn('[pro] upgrade dht destroy failed', err instanceof Error ? err.message : err)
+ })
+ }
+}
diff --git a/packages/core/src/worklet/rpc/protocol.ts b/packages/core/src/worklet/rpc/protocol.ts
index b963292..dcea316 100644
--- a/packages/core/src/worklet/rpc/protocol.ts
+++ b/packages/core/src/worklet/rpc/protocol.ts
@@ -116,6 +116,7 @@ export interface InitDeviceSecretReply {
export interface SetRelayConfigInput {
enabled: boolean
+ proToken?: string | null
}
export interface SetRelayConfigReply {
diff --git a/packages/core/src/worklet/transfer/control-channel.ts b/packages/core/src/worklet/transfer/control-channel.ts
index 8f37d97..25450c5 100644
--- a/packages/core/src/worklet/transfer/control-channel.ts
+++ b/packages/core/src/worklet/transfer/control-channel.ts
@@ -127,6 +127,12 @@ interface TopicAuth {
proof: string
}
+interface WebRelayConnection {
+ type: 'web-relay'
+ cid: string
+ host: string
+}
+
export type PeerControlMessage =
| TransferStart
| TransferReady
@@ -142,6 +148,7 @@ export type PeerControlMessage =
| ClientHello
| TopicChallenge
| TopicAuth
+ | WebRelayConnection
type PeerControlHandler = (message: PeerControlMessage) => void
diff --git a/packages/core/src/worklet/transfer/control-validation.ts b/packages/core/src/worklet/transfer/control-validation.ts
index a7e0c64..7f9b44f 100644
--- a/packages/core/src/worklet/transfer/control-validation.ts
+++ b/packages/core/src/worklet/transfer/control-validation.ts
@@ -184,6 +184,10 @@ export function isValidControlMessage(x: unknown): x is PeerControlMessage {
return isBoundedHex((x as { nonce?: unknown }).nonce, MAX_ID_LEN)
case 'auth':
return isBoundedHex((x as { proof?: unknown }).proof, MAX_ID_LEN)
+ case 'web-relay': {
+ const v = x as { cid?: unknown; host?: unknown }
+ return isBoundedString(v.cid, MAX_ID_LEN) && isBoundedString(v.host, MAX_ID_LEN)
+ }
default:
return false
}
diff --git a/packages/core/src/worklet/transfer/orchestrator.ts b/packages/core/src/worklet/transfer/orchestrator.ts
index 6065002..edc8327 100644
--- a/packages/core/src/worklet/transfer/orchestrator.ts
+++ b/packages/core/src/worklet/transfer/orchestrator.ts
@@ -72,7 +72,8 @@ import { RememberCoordinator } from '../peers/remember-coordinator'
import { RecognitionCoordinator } from '../peers/recognition-coordinator'
import { DiscoveryCoordinator } from '../peers/discovery'
import { PairingCoordinator } from '../peers/pairing-coordinator'
-import { configureRelay, relayConfigSummary } from '../relay/config'
+import { configureRelay, relayConfigSummary, setRelaySending } from '../relay/config'
+import { upgradeWebRelay } from '../relay/upgradeWebRelay'
function createTransferId(): string {
return crypto.randomBytes(16).toString('hex')
@@ -311,6 +312,14 @@ export class TransferOrchestrator implements TransferRPC {
this.verifyAuth(message.proof, session)
return
}
+ if (message.type === 'web-relay') {
+ if (!this.authedPeers.has(session.peerKey)) return
+
+ upgradeWebRelay(message.cid, message.host).catch((err) => {
+ console.warn('[pro] web relay upgrade rejected', err instanceof Error ? err.message : err)
+ })
+ return
+ }
if (message.type === 'recognition') {
void this.recognition.handleRecognition(message, session.peerKey)
return
@@ -389,6 +398,7 @@ export class TransferOrchestrator implements TransferRPC {
private setRole(role: TransferRole | null): void {
if (this.role === role) return
this.role = role
+ setRelaySending(role === 'sender')
this.emitIPC(createRoleEvent(role))
}
@@ -690,7 +700,7 @@ export class TransferOrchestrator implements TransferRPC {
}
async setRelayConfig(input: SetRelayConfigInput): Promise<SetRelayConfigReply> {
- configureRelay({ enabled: input.enabled })
+ configureRelay({ enabled: input.enabled, proToken: input.proToken })
const { enabled, keyCount } = relayConfigSummary()
return { enabled, keyCount }
}
diff --git a/packages/core/src/worklet/transfer/swarm.ts b/packages/core/src/worklet/transfer/swarm.ts
index 5fa77ad..6f74953 100644
--- a/packages/core/src/worklet/transfer/swarm.ts
+++ b/packages/core/src/worklet/transfer/swarm.ts
@@ -6,6 +6,7 @@ import type { PeerControlMessage } from './control-channel'
import { PeerIdentityStore, type NoiseKeyPair } from './peer-identity-store'
import { PeerDrive } from './drive'
import { relayThrough, isRelayHost } from '../relay/config'
+import { attachProAnnounce } from '../relay/announce'
import { whenRelayConfReady } from '../relay/conf'
type ConnectionType = 'direct' | 'relay'
@@ -60,6 +61,7 @@ export class TransferSwarm {
private createSwarm(keyPair?: NoiseKeyPair): Hyperswarm {
const swarm = new Hyperswarm({ ...(keyPair ? { keyPair } : {}), relayThrough })
+ attachProAnnounce(swarm.dht)
swarm.on('connection', (socket, info) => {
this.handleConnection(socket, info).catch((err) => {
console.error(
diff --git a/packages/domain/src/account/core/billing.ts b/packages/domain/src/account/core/billing.ts
new file mode 100644
index 0000000..8292a03
--- /dev/null
+++ b/packages/domain/src/account/core/billing.ts
@@ -0,0 +1 @@
+export type BillingPlan = 'monthly' | 'yearly'
diff --git a/packages/domain/src/account/core/code.test.ts b/packages/domain/src/account/core/code.test.ts
new file mode 100644
index 0000000..c18e940
--- /dev/null
+++ b/packages/domain/src/account/core/code.test.ts
@@ -0,0 +1,68 @@
+import { describe, expect, it } from 'vitest'
+import {
+ ACCOUNT_CODE_DISPLAY_LENGTH,
+ ACCOUNT_CODE_LENGTH,
+ formatAccountCode,
+ formatAccountCodeInput,
+ isAccountCodeReady,
+ isValidAccountCode,
+ maskAccountCode,
+ normalizeAccountCode
+} from './code'
+
+const CODE = '0239011197318834'
+
+describe('account code', () => {
+ it('is sixteen digits', () => {
+ expect(ACCOUNT_CODE_LENGTH).toBe(16)
+ expect(isValidAccountCode(CODE)).toBe(true)
+ })
+
+ it('rejects the wrong length', () => {
+ expect(isValidAccountCode(CODE.slice(0, 15))).toBe(false)
+ expect(isValidAccountCode(`${CODE}1`)).toBe(false)
+ })
+
+ it('rejects anything that is not a digit', () => {
+ expect(isValidAccountCode('023901119731883A')).toBe(false)
+ })
+
+ it('strips formatting so a pasted code still works', () => {
+ expect(normalizeAccountCode('0239 0111 9731 8834')).toBe(CODE)
+ expect(normalizeAccountCode('0239-0111-9731-8834')).toBe(CODE)
+ expect(normalizeAccountCode(' 0239 0111 9731 8834 ')).toBe(CODE)
+ })
+
+ it('groups the code for display', () => {
+ expect(formatAccountCode(CODE)).toBe('0239 0111 9731 8834')
+ })
+
+ it('round trips through display form', () => {
+ expect(normalizeAccountCode(formatAccountCode(CODE))).toBe(CODE)
+ })
+
+ it('hides every group but the last', () => {
+ expect(maskAccountCode(CODE)).toBe('•••• •••• •••• 8834')
+ })
+
+ it('groups typed input as it grows', () => {
+ expect(formatAccountCodeInput('0')).toBe('0')
+ expect(formatAccountCodeInput('0239')).toBe('0239')
+ expect(formatAccountCodeInput('02390')).toBe('0239 0')
+ })
+
+ it('drops anything that is not a digit while typing', () => {
+ expect(formatAccountCodeInput('02a39-b0111')).toBe('0239 0111')
+ })
+
+ it('is ready only once the display form holds a full code', () => {
+ expect(isAccountCodeReady('0239 0111 9731 883')).toBe(false)
+ expect(isAccountCodeReady('0239 0111 9731 8834')).toBe(true)
+ })
+
+ it('stops at the full code length', () => {
+ expect(formatAccountCodeInput(`${CODE}9999`)).toBe('0239 0111 9731 8834')
+ expect(ACCOUNT_CODE_DISPLAY_LENGTH).toBe(19)
+ expect(formatAccountCode(CODE)).toHaveLength(ACCOUNT_CODE_DISPLAY_LENGTH)
+ })
+})
diff --git a/packages/domain/src/account/core/code.ts b/packages/domain/src/account/core/code.ts
new file mode 100644
index 0000000..f914ac7
--- /dev/null
+++ b/packages/domain/src/account/core/code.ts
@@ -0,0 +1,30 @@
+export const ACCOUNT_CODE_LENGTH = 16
+const GROUP_SIZE = 4
+
+export const ACCOUNT_CODE_DISPLAY_LENGTH =
+ ACCOUNT_CODE_LENGTH + Math.ceil(ACCOUNT_CODE_LENGTH / GROUP_SIZE) - 1
+
+export function normalizeAccountCode(input: string): string {
+ return input.replace(/\D/g, '')
+}
+
+export function formatAccountCode(code: string): string {
+ return (code.match(new RegExp(`.{1,${GROUP_SIZE}}`, 'g')) ?? []).join(' ')
+}
+
+export function formatAccountCodeInput(input: string): string {
+ return formatAccountCode(normalizeAccountCode(input).slice(0, ACCOUNT_CODE_LENGTH))
+}
+
+export function isValidAccountCode(code: string): boolean {
+ return code.length === ACCOUNT_CODE_LENGTH && /^\d+$/.test(code)
+}
+
+export function isAccountCodeReady(input: string): boolean {
+ return isValidAccountCode(normalizeAccountCode(input))
+}
+
+export function maskAccountCode(code: string): string {
+ const groups = formatAccountCode(code).split(' ')
+ return groups.map((group, index) => (index === groups.length - 1 ? group : '••••')).join(' ')
+}
diff --git a/packages/domain/src/account/core/codeFile.ts b/packages/domain/src/account/core/codeFile.ts
new file mode 100644
index 0000000..707b57e
--- /dev/null
+++ b/packages/domain/src/account/core/codeFile.ts
@@ -0,0 +1,22 @@
+import { formatAccountCode } from './code'
+
+export interface CodeFileLabels {
+ title: string
+ codeLabel: string
+ savedLabel: string
+ warning: string
+}
+
+export const ACCOUNT_CODE_FILE_NAME = 'altersend-pro-code.txt'
+
+export function accountCodeFile(code: string, savedOn: string, labels: CodeFileLabels): string {
+ return [
+ labels.title,
+ '',
+ `${labels.codeLabel}: ${formatAccountCode(code)}`,
+ `${labels.savedLabel}: ${savedOn}`,
+ '',
+ labels.warning,
+ ''
+ ].join('\n')
+}
diff --git a/packages/domain/src/account/core/index.ts b/packages/domain/src/account/core/index.ts
new file mode 100644
index 0000000..2c9f4ad
--- /dev/null
+++ b/packages/domain/src/account/core/index.ts
@@ -0,0 +1,5 @@
+export * from './billing'
+export * from './code'
+export * from './codeFile'
+export * from './plans'
+export * from './state'
diff --git a/packages/domain/src/account/core/plans.ts b/packages/domain/src/account/core/plans.ts
new file mode 100644
index 0000000..dc62973
--- /dev/null
+++ b/packages/domain/src/account/core/plans.ts
@@ -0,0 +1,93 @@
+import { NATIVE_RELAY_MAX_LABEL, WEB_LINK_MAX_LABEL } from '../../constants/transfer'
+import type { BillingPlan } from './billing'
+
+export type TranslateFn = (key: string, values?: Record<string, string | number>) => string
+
+export interface PlanOffer {
+ plan: BillingPlan
+ price: string
+}
+
+export type PlanPrices = Partial<Record<BillingPlan, string>>
+
+export function pricesFrom(offers: PlanOffer[]): PlanPrices {
+ const prices: PlanPrices = {}
+ for (const offer of offers) prices[offer.plan] = offer.price
+ return prices
+}
+
+export type PlanCell = { type: 'text'; value: string } | { type: 'check' }
+
+const cellText = (value: string): PlanCell => ({ type: 'text', value })
+
+const UNLIMITED = cellText('∞')
+const INCLUDED: PlanCell = { type: 'check' }
+
+export const BILLING_PLANS: BillingPlan[] = ['monthly', 'yearly']
+
+const PLAN_LABEL_KEY: Record<BillingPlan, string> = {
+ monthly: 'settings:account.planMonthly',
+ yearly: 'settings:account.planYearly'
+}
+
+export interface PlanComparisonRow {
+ label: string
+ free: PlanCell
+ pro: PlanCell
+}
+
+const PLAN_PRICE_KEY: Record<BillingPlan, string> = {
+ monthly: 'settings:account.pricePerMonth',
+ yearly: 'settings:account.pricePerYear'
+}
+
+export function planLabel(plan: BillingPlan, t: TranslateFn, prices?: PlanPrices): string {
+ const price = prices?.[plan]
+ return price ? t(PLAN_PRICE_KEY[plan], { price }) : t(PLAN_LABEL_KEY[plan])
+}
+
+const PLAN_CAPTION_KEY: Record<BillingPlan, string> = {
+ monthly: 'settings:account.billedMonthly',
+ yearly: 'settings:account.billedYearly'
+}
+
+export interface PlanRow {
+ plan: BillingPlan
+ title: string
+ caption: string
+ price: string | null
+}
+
+export function planRows(t: TranslateFn, prices?: PlanPrices): PlanRow[] {
+ return BILLING_PLANS.map((plan) => ({
+ plan,
+ title: t(PLAN_LABEL_KEY[plan]),
+ caption: t(PLAN_CAPTION_KEY[plan]),
+ price: prices?.[plan] ?? null
+ }))
+}
+
+export function planComparisonRows(t: TranslateFn): PlanComparisonRow[] {
+ return [
+ {
+ label: t('settings:account.featureDirect'),
+ free: UNLIMITED,
+ pro: UNLIMITED
+ },
+ {
+ label: t('settings:account.featurePriority'),
+ free: cellText(t('settings:account.none')),
+ pro: INCLUDED
+ },
+ {
+ label: t('settings:account.featureWebCap'),
+ free: cellText(WEB_LINK_MAX_LABEL),
+ pro: UNLIMITED
+ },
+ {
+ label: t('settings:account.featureAppCap'),
+ free: cellText(NATIVE_RELAY_MAX_LABEL),
+ pro: UNLIMITED
+ }
+ ]
+}
diff --git a/packages/domain/src/account/core/state.ts b/packages/domain/src/account/core/state.ts
new file mode 100644
index 0000000..c813ffa
--- /dev/null
+++ b/packages/domain/src/account/core/state.ts
@@ -0,0 +1,108 @@
+import type { BillingPlan } from './billing'
+
+export type AccountPhase = 'paywall' | 'entering' | 'waiting' | 'approval' | 'success' | 'active'
+
+export type AccountError =
+ | 'failed'
+ | 'unknownCode'
+ | 'offline'
+ | 'server'
+ | 'timedOut'
+ | 'nothingToRestore'
+ | 'restoreNotMoved'
+ | 'expiredCode'
+
+const ERROR_KEY: Record<AccountError, string> = {
+ failed: 'settings:account.failed',
+ unknownCode: 'settings:account.unknownCode',
+ offline: 'settings:account.offline',
+ server: 'settings:account.serverError',
+ timedOut: 'settings:account.timedOut',
+ nothingToRestore: 'settings:account.nothingToRestore',
+ restoreNotMoved: 'settings:account.restoreNotMoved',
+ expiredCode: 'settings:account.expiredCode'
+}
+
+export function accountErrorKey(error: AccountError | null): string | null {
+ return error ? ERROR_KEY[error] : null
+}
+
+export interface AccountState {
+ code: string
+ validUntil: string | null
+}
+
+export interface AccountSession {
+ phase: AccountPhase
+ account: AccountState | null
+ busy: boolean
+ error: AccountError | null
+ entry: string
+ plan: BillingPlan
+ rotated: boolean
+}
+
+export type AccountAction =
+ | { type: 'entryChanged'; entry: string }
+ | { type: 'planChosen'; plan: BillingPlan }
+ | { type: 'started' }
+ | { type: 'settled' }
+ | { type: 'failed'; error: AccountError }
+ | { type: 'errorCleared' }
+ | { type: 'showEntry' }
+ | { type: 'showPaywall' }
+ | { type: 'upgrading'; account: AccountState }
+ | { type: 'awaitingApproval'; account: AccountState }
+ | { type: 'purchased'; account: AccountState; rotated?: boolean }
+ | { type: 'activated'; account: AccountState }
+ | { type: 'acknowledged' }
+ | { type: 'forgotten' }
+
+export const initialAccountSession: AccountSession = {
+ phase: 'paywall',
+ account: null,
+ busy: false,
+ error: null,
+ entry: '',
+ plan: 'monthly',
+ rotated: false
+}
+
+export function accountReducer(state: AccountSession, action: AccountAction): AccountSession {
+ switch (action.type) {
+ case 'entryChanged':
+ return { ...state, entry: action.entry, error: null }
+ case 'planChosen':
+ return { ...state, plan: action.plan }
+ case 'started':
+ return { ...state, busy: true, error: null }
+ case 'settled':
+ return { ...state, busy: false }
+ case 'failed':
+ return { ...state, busy: false, error: action.error }
+ case 'errorCleared':
+ return { ...state, error: null }
+ case 'showEntry':
+ return { ...state, phase: 'entering', error: null, entry: '' }
+ case 'showPaywall':
+ return { ...state, phase: 'paywall', error: null }
+ case 'upgrading':
+ return { ...state, phase: 'waiting', account: action.account, error: null }
+ case 'awaitingApproval':
+ return { ...state, phase: 'approval', account: action.account, error: null }
+ case 'purchased':
+ return {
+ ...state,
+ phase: state.phase === 'active' ? 'active' : 'success',
+ account: action.account,
+ rotated: Boolean(action.rotated),
+ error: null
+ }
+ case 'activated':
+ return { ...state, phase: 'active', account: action.account, entry: '', error: null }
+ case 'acknowledged':
+ return { ...state, phase: 'active' }
+ case 'forgotten':
+ return { ...initialAccountSession, plan: state.plan }
+ }
+}
diff --git a/packages/domain/src/account/index.ts b/packages/domain/src/account/index.ts
new file mode 100644
index 0000000..3074a71
--- /dev/null
+++ b/packages/domain/src/account/index.ts
@@ -0,0 +1,25 @@
+export {
+ ACCOUNT_CODE_DISPLAY_LENGTH,
+ ACCOUNT_CODE_FILE_NAME,
+ accountCodeFile,
+ BILLING_PLANS,
+ formatAccountCode,
+ maskAccountCode,
+ planComparisonRows,
+ planLabel,
+ planRows,
+ type AccountPhase,
+ type BillingPlan,
+ type PlanCell,
+ type PlanOffer,
+ type PlanRow
+} from './core'
+
+export type { AccountStorage, PurchaseAdapter, PurchaseOutcome } from './ports'
+
+export {
+ createAccountRuntime,
+ useAccount,
+ useSubscriptionStore,
+ type AccountModel
+} from './runtime'
diff --git a/packages/domain/src/account/ports/index.ts b/packages/domain/src/account/ports/index.ts
new file mode 100644
index 0000000..4d205e7
--- /dev/null
+++ b/packages/domain/src/account/ports/index.ts
@@ -0,0 +1,2 @@
+export * from './purchases'
+export * from './storage'
diff --git a/packages/domain/src/account/ports/purchases.ts b/packages/domain/src/account/ports/purchases.ts
new file mode 100644
index 0000000..6a06876
--- /dev/null
+++ b/packages/domain/src/account/ports/purchases.ts
@@ -0,0 +1,12 @@
+import type { BillingPlan, PlanOffer } from '../core'
+
+export type PurchaseOutcome = 'bought' | 'owned' | 'pending' | 'cancelled'
+
+export interface PurchaseAdapter {
+ available(): Promise<boolean>
+ offers(): Promise<PlanOffer[]>
+ managementUrl(): Promise<string | null>
+ identify(code: string): Promise<void>
+ buy(plan: BillingPlan): Promise<PurchaseOutcome>
+ restore(): Promise<boolean>
+}
diff --git a/packages/domain/src/account/ports/storage.ts b/packages/domain/src/account/ports/storage.ts
new file mode 100644
index 0000000..a318979
--- /dev/null
+++ b/packages/domain/src/account/ports/storage.ts
@@ -0,0 +1,7 @@
+export interface AccountStorage {
+ read(): Promise<string | null>
+ write(code: string): Promise<void>
+ clear(): Promise<void>
+ readToken?(): Promise<string | null>
+ writeToken?(token: string | null): Promise<void>
+}
diff --git a/packages/domain/src/account/runtime/createAccountRuntime.ts b/packages/domain/src/account/runtime/createAccountRuntime.ts
new file mode 100644
index 0000000..07aa02d
--- /dev/null
+++ b/packages/domain/src/account/runtime/createAccountRuntime.ts
@@ -0,0 +1,51 @@
+import type { AccountStorage, PurchaseAdapter } from '../ports'
+import { createAccountClient } from '../transport'
+import { createTokenSync } from './tokenSync'
+import type { AccountAdapter } from './useAccount'
+
+export interface AccountRuntimeOptions {
+ baseUrl: string
+ storage: AccountStorage
+ openUrl(url: string): Promise<void>
+ applyToken(token: string | null): Promise<void>
+ purchases?: PurchaseAdapter
+}
+
+export interface AccountRuntime {
+ adapter: AccountAdapter
+ syncToken(): Promise<boolean>
+ syncTokenIfStale(): Promise<boolean>
+ startSync(): void
+ stopSync(): void
+}
+
+export function createAccountRuntime({
+ baseUrl,
+ storage,
+ openUrl,
+ applyToken,
+ purchases
+}: AccountRuntimeOptions): AccountRuntime {
+ const client = createAccountClient(baseUrl)
+ const tokenSync = createTokenSync({
+ client,
+ readCode: storage.read,
+ applyToken,
+ readCachedToken: storage.readToken?.bind(storage),
+ cacheToken: storage.writeToken?.bind(storage)
+ })
+
+ return {
+ adapter: {
+ client,
+ storage,
+ openUrl,
+ syncToken: tokenSync.sync,
+ purchases
+ },
+ syncToken: tokenSync.sync,
+ syncTokenIfStale: tokenSync.syncIfStale,
+ startSync: tokenSync.start,
+ stopSync: tokenSync.stop
+ }
+}
diff --git a/packages/domain/src/account/runtime/index.ts b/packages/domain/src/account/runtime/index.ts
new file mode 100644
index 0000000..4f9de94
--- /dev/null
+++ b/packages/domain/src/account/runtime/index.ts
@@ -0,0 +1,6 @@
+export * from './createAccountRuntime'
+export * from './store'
+export * from './tokenSync'
+export * from './useAccount'
+export * from './useEntitlementPoll'
+export * from './usePlanPrices'
diff --git a/packages/domain/src/account/runtime/purchaseFlow.test.ts b/packages/domain/src/account/runtime/purchaseFlow.test.ts
new file mode 100644
index 0000000..4f2f3b0
--- /dev/null
+++ b/packages/domain/src/account/runtime/purchaseFlow.test.ts
@@ -0,0 +1,155 @@
+import { describe, expect, it } from 'vitest'
+import type { AccountAction } from '../core'
+import {
+ abandon,
+ assertHttpsUrl,
+ buyFromStore,
+ restoreFromStore,
+ type PurchaseContext
+} from './purchaseFlow'
+
+interface Options {
+ stored?: string | null
+ storedExists?: boolean
+ restored?: boolean
+ active?: boolean
+ alreadyPaid?: boolean
+}
+
+function makeContext({
+ stored = null,
+ storedExists = true,
+ restored = true,
+ active = true,
+ alreadyPaid = false
+}: Options) {
+ const actions: AccountAction[] = []
+ const discarded: string[] = []
+ const polled: string[] = []
+ let written = stored
+
+ const ctx = {
+ client: {
+ status: async () => ({
+ exists: storedExists,
+ active: alreadyPaid,
+ validUntil: alreadyPaid ? '2030-01-01' : null
+ }),
+ create: async () => ({ code: 'new-code' }),
+ syncStore: async () => ({ exists: true, active, validUntil: active ? '2030-01-01' : null })
+ },
+ storage: {
+ read: async () => written,
+ write: async (code: string) => {
+ written = code
+ },
+ clear: async () => {
+ written = null
+ }
+ },
+ purchases: {
+ identify: async () => {},
+ restore: async () => restored,
+ buy: async () => 'bought'
+ },
+ openUrl: async () => {},
+ syncToken: async () => true,
+ dispatch: (action: AccountAction) => actions.push(action),
+ poll: (code: string) => {
+ polled.push(code)
+ },
+ discard: async (code: string) => {
+ discarded.push(code)
+ }
+ } as unknown as PurchaseContext
+
+ return { ctx, actions, discarded, polled, code: () => written }
+}
+
+describe('restoreFromStore', () => {
+ it('flags a restore that had to mint a new code', async () => {
+ const { ctx, actions } = makeContext({ stored: null })
+
+ expect(await restoreFromStore(ctx)).toBe('restored')
+ expect(actions).toEqual([
+ { type: 'purchased', account: { code: 'new-code', validUntil: '2030-01-01' }, rotated: true }
+ ])
+ })
+
+ it('keeps a stored code and activates without flagging a rotation', async () => {
+ const { ctx, actions } = makeContext({ stored: 'kept-code' })
+
+ expect(await restoreFromStore(ctx)).toBe('restored')
+ expect(actions).toEqual([
+ { type: 'activated', account: { code: 'kept-code', validUntil: '2030-01-01' } }
+ ])
+ })
+
+ it('discards a minted code when the store has nothing to restore', async () => {
+ const { ctx, actions, discarded } = makeContext({ stored: null, restored: false })
+
+ expect(await restoreFromStore(ctx)).toBe('nothingToRestore')
+ expect(discarded).toEqual(['new-code'])
+ expect(actions).toEqual([])
+ })
+
+ it('discards a minted code when the purchase did not move', async () => {
+ const { ctx, discarded } = makeContext({ stored: null, active: false })
+
+ expect(await restoreFromStore(ctx)).toBe('notMoved')
+ expect(discarded).toEqual(['new-code'])
+ })
+})
+
+describe('buyFromStore', () => {
+ it('waits for the entitlement instead of claiming success', async () => {
+ const { ctx, actions, polled } = makeContext({ stored: 'kept-code', active: false })
+
+ expect(await buyFromStore(ctx, { code: 'kept-code', fresh: false }, 'monthly')).toBe(true)
+ expect(actions.map((a) => a.type)).toEqual(['awaitingApproval'])
+ expect(polled).toEqual(['kept-code'])
+ })
+
+ it('reports success once the entitlement is confirmed', async () => {
+ const { ctx, actions, polled } = makeContext({ stored: 'kept-code' })
+
+ expect(await buyFromStore(ctx, { code: 'kept-code', fresh: false }, 'monthly')).toBe(true)
+ expect(actions.map((a) => a.type)).toEqual(['purchased'])
+ expect(polled).toEqual([])
+ })
+})
+
+describe('assertHttpsUrl', () => {
+ it('passes https urls through', () => {
+ expect(assertHttpsUrl('https://checkout.stripe.com/c/pay/x', 'checkout')).toBe(
+ 'https://checkout.stripe.com/c/pay/x'
+ )
+ })
+
+ it('rejects any other scheme', () => {
+ expect(() => assertHttpsUrl('file:///etc/passwd', 'checkout')).toThrow()
+ expect(() => assertHttpsUrl('javascript:alert(1)', 'checkout')).toThrow()
+ expect(() => assertHttpsUrl('http://example.com', 'checkout')).toThrow()
+ })
+})
+
+describe('abandon', () => {
+ it('keeps a code the payment already activated instead of deleting it', async () => {
+ const { ctx, actions, discarded } = makeContext({ stored: null, alreadyPaid: true })
+
+ await abandon(ctx, { code: 'paid-code', fresh: true })
+
+ expect(discarded).toEqual([])
+ expect(actions).toEqual([
+ { type: 'purchased', account: { code: 'paid-code', validUntil: '2030-01-01' } }
+ ])
+ })
+
+ it('discards a freshly minted code that was never paid for', async () => {
+ const { ctx, discarded } = makeContext({ stored: null })
+
+ await abandon(ctx, { code: 'new-code', fresh: true })
+
+ expect(discarded).toEqual(['new-code'])
+ })
+})
diff --git a/packages/domain/src/account/runtime/purchaseFlow.ts b/packages/domain/src/account/runtime/purchaseFlow.ts
new file mode 100644
index 0000000..24013b2
--- /dev/null
+++ b/packages/domain/src/account/runtime/purchaseFlow.ts
@@ -0,0 +1,153 @@
+import type { AccountAction, BillingPlan } from '../core'
+import type { AccountStorage, PurchaseAdapter } from '../ports'
+import type { AccountClient, AccountStatus } from '../transport'
+
+export interface PurchaseContext {
+ client: AccountClient
+ storage: AccountStorage
+ purchases?: PurchaseAdapter
+ openUrl(url: string): Promise<void>
+ syncToken(): Promise<unknown>
+ dispatch(action: AccountAction): void
+ poll(code: string): void
+ discard(code: string): Promise<void>
+}
+
+export interface ReservedCode {
+ code: string
+ fresh: boolean
+}
+
+const warn = (context: string, err: unknown) => console.warn(`[account] ${context}`, err)
+
+export function assertHttpsUrl(url: string, context: string): string {
+ if (!/^https:\/\//i.test(url)) throw new Error(`[account] ${context} returned a non-https url`)
+ return url
+}
+
+export async function reserveCode(ctx: PurchaseContext): Promise<ReservedCode> {
+ const stored = await ctx.storage.read()
+
+ if (stored) {
+ const existing = await ctx.client.status(stored)
+ if (existing.exists) return { code: stored, fresh: false }
+ }
+
+ const created = await ctx.client.create()
+ await ctx.storage.write(created.code)
+ return { code: created.code, fresh: true }
+}
+
+export async function abandon(ctx: PurchaseContext, reserved: ReservedCode): Promise<void> {
+ if (!reserved.fresh) return
+
+ const status = await ctx.client.status(reserved.code).catch((err) => {
+ warn('status check before discard failed', err)
+ return null
+ })
+
+ if (status?.active) {
+ ctx.dispatch({
+ type: 'purchased',
+ account: { code: reserved.code, validUntil: status.validUntil ?? null }
+ })
+ await ctx.syncToken()
+ return
+ }
+
+ await ctx.discard(reserved.code)
+}
+
+async function creditFromStore(ctx: PurchaseContext, code: string): Promise<AccountStatus | null> {
+ try {
+ return await ctx.client.syncStore(code)
+ } catch (err) {
+ warn('store sync failed, falling back to polling', err)
+ return null
+ }
+}
+
+async function settle(ctx: PurchaseContext, code: string): Promise<void> {
+ const credited = await creditFromStore(ctx, code)
+ const account = { code, validUntil: credited?.validUntil ?? null }
+
+ if (!credited?.active) {
+ ctx.dispatch({ type: 'awaitingApproval', account })
+ ctx.poll(code)
+ return
+ }
+
+ ctx.dispatch({ type: 'purchased', account })
+ await ctx.syncToken()
+}
+
+export async function buyFromStore(
+ ctx: PurchaseContext,
+ reserved: ReservedCode,
+ plan: BillingPlan
+): Promise<boolean> {
+ const { purchases } = ctx
+ if (!purchases) return false
+
+ const { code } = reserved
+ await purchases.identify(code)
+ const outcome = await purchases.buy(plan)
+
+ if (outcome === 'cancelled') {
+ await abandon(ctx, reserved)
+ return false
+ }
+
+ if (outcome === 'pending') {
+ ctx.dispatch({ type: 'awaitingApproval', account: { code, validUntil: null } })
+ ctx.poll(code)
+ return true
+ }
+
+ await settle(ctx, code)
+ return true
+}
+
+export async function buyWithCard(
+ ctx: PurchaseContext,
+ reserved: ReservedCode,
+ plan: BillingPlan
+): Promise<boolean> {
+ const { code } = reserved
+
+ ctx.dispatch({ type: 'upgrading', account: { code, validUntil: null } })
+ const url = assertHttpsUrl(await ctx.client.checkout(code, plan), 'checkout')
+ await ctx.openUrl(url)
+ ctx.poll(code)
+ return true
+}
+
+export type RestoreOutcome = 'restored' | 'nothingToRestore' | 'notMoved'
+
+export async function restoreFromStore(ctx: PurchaseContext): Promise<RestoreOutcome> {
+ const { purchases } = ctx
+ if (!purchases) return 'nothingToRestore'
+
+ const reserved = await reserveCode(ctx)
+ await purchases.identify(reserved.code)
+
+ if (!(await purchases.restore())) {
+ await abandon(ctx, reserved)
+ return 'nothingToRestore'
+ }
+
+ const status = await ctx.client.syncStore(reserved.code)
+ if (!status.active) {
+ await abandon(ctx, reserved)
+ return 'notMoved'
+ }
+
+ const account = { code: reserved.code, validUntil: status.validUntil ?? null }
+
+ ctx.dispatch(
+ reserved.fresh ? { type: 'purchased', account, rotated: true } : { type: 'activated', account }
+ )
+ await ctx.syncToken()
+
+ return 'restored'
+}
diff --git a/packages/domain/src/account/runtime/store.ts b/packages/domain/src/account/runtime/store.ts
new file mode 100644
index 0000000..9fa5936
--- /dev/null
+++ b/packages/domain/src/account/runtime/store.ts
@@ -0,0 +1,17 @@
+import { create } from 'zustand'
+
+interface SubscriptionState {
+ active: boolean
+}
+
+const subscriptionStore = create<SubscriptionState>()(() => ({ active: false }))
+
+export const useSubscriptionStore = subscriptionStore
+
+export function setSubscriptionActive(active: boolean): void {
+ subscriptionStore.setState({ active })
+}
+
+export function isSubscriptionActive(): boolean {
+ return subscriptionStore.getState().active
+}
diff --git a/packages/domain/src/account/runtime/tokenSync.ts b/packages/domain/src/account/runtime/tokenSync.ts
new file mode 100644
index 0000000..fc516c3
--- /dev/null
+++ b/packages/domain/src/account/runtime/tokenSync.ts
@@ -0,0 +1,133 @@
+import type { AccountClient } from '../transport'
+import { setSubscriptionActive } from './store'
+
+const REFRESH_MS = 12 * 60 * 60 * 1000
+const STALE_AFTER_MS = 5 * 60 * 1000
+
+export interface TokenSyncOptions {
+ client: AccountClient
+ readCode(): Promise<string | null>
+ applyToken(token: string | null): Promise<void>
+ readCachedToken?(): Promise<string | null>
+ cacheToken?(token: string | null): Promise<void>
+}
+
+export interface TokenSync {
+ sync(): Promise<boolean>
+ syncIfStale(minAgeMs?: number): Promise<boolean>
+ start(): void
+ stop(): void
+}
+
+function proTokenExpiry(token: string): number | null {
+ try {
+ const [body] = token.split('.')
+ if (!body) return null
+
+ const json = atob(body.replace(/-/g, '+').replace(/_/g, '/'))
+ const expiry = (JSON.parse(json) as { e?: unknown }).e
+
+ return typeof expiry === 'number' ? expiry * 1000 : null
+ } catch {
+ return null
+ }
+}
+
+export function createTokenSync({
+ client,
+ readCode,
+ applyToken,
+ readCachedToken,
+ cacheToken
+}: TokenSyncOptions): TokenSync {
+ let token: string | null = null
+ let timer: ReturnType<typeof setInterval> | null = null
+ let lastSyncAt = 0
+ let running: Promise<boolean> | null = null
+ let generation = 0
+
+ const report = (err: unknown) =>
+ console.warn('[account] token sync failed:', err instanceof Error ? err.message : String(err))
+
+ async function push(): Promise<void> {
+ setSubscriptionActive(token !== null)
+ await applyToken(token)
+ await cacheToken?.(token)
+ }
+
+ async function seed(): Promise<void> {
+ if (!readCachedToken) return
+
+ const cached = await readCachedToken().catch(report)
+ if (!cached || token) return
+
+ const expiresAt = proTokenExpiry(cached)
+ if (expiresAt === null || expiresAt <= Date.now()) return
+
+ token = cached
+ setSubscriptionActive(true)
+ await applyToken(token)
+ }
+
+ async function run(): Promise<boolean> {
+ const attempt = ++generation
+ const code = await readCode()
+
+ if (!code) {
+ if (attempt !== generation) return token !== null
+ token = null
+ await push()
+ return false
+ }
+
+ let fresh: string | null
+ try {
+ const result = await client.token(code)
+ fresh = result?.token ?? null
+ } catch (err) {
+ report(err)
+ return token !== null
+ }
+
+ if (attempt !== generation) return token !== null
+
+ token = fresh
+ lastSyncAt = Date.now()
+ await push()
+
+ return token !== null
+ }
+
+ function sync(): Promise<boolean> {
+ if (running) return running
+ running = run().finally(() => {
+ running = null
+ })
+ return running
+ }
+
+ async function syncIfStale(minAgeMs = STALE_AFTER_MS): Promise<boolean> {
+ if (Date.now() - lastSyncAt < minAgeMs) return token !== null
+ return sync()
+ }
+
+ return {
+ sync,
+ syncIfStale,
+ start() {
+ if (timer) return
+ seed()
+ .catch(report)
+ .then(() => sync())
+ .catch(report)
+ timer = setInterval(() => {
+ sync().catch(report)
+ }, REFRESH_MS)
+ },
+ stop() {
+ if (!timer) return
+ clearInterval(timer)
+ timer = null
+ }
+ }
+}
diff --git a/packages/domain/src/account/runtime/useAccount.ts b/packages/domain/src/account/runtime/useAccount.ts
new file mode 100644
index 0000000..094be26
--- /dev/null
+++ b/packages/domain/src/account/runtime/useAccount.ts
@@ -0,0 +1,381 @@
+import { useCallback, useEffect, useMemo, useReducer, useRef, useState } from 'react'
+import {
+ accountErrorKey,
+ accountReducer,
+ formatAccountCodeInput,
+ initialAccountSession,
+ isAccountCodeReady,
+ isValidAccountCode,
+ normalizeAccountCode,
+ type AccountPhase,
+ type AccountState,
+ type BillingPlan,
+ type PlanPrices
+} from '../core'
+import type { AccountStorage, PurchaseAdapter } from '../ports'
+import { classifyAccountError, type AccountClient, type AccountStatus } from '../transport'
+import {
+ abandon,
+ assertHttpsUrl,
+ buyFromStore,
+ buyWithCard,
+ reserveCode,
+ restoreFromStore,
+ type PurchaseContext,
+ type ReservedCode
+} from './purchaseFlow'
+import { isSubscriptionActive, useSubscriptionStore } from './store'
+import { useEntitlementPoll } from './useEntitlementPoll'
+import { usePlanPrices } from './usePlanPrices'
+import { useStoreAvailability } from './useStoreAvailability'
+
+export interface AccountAdapter {
+ client: AccountClient
+ storage: AccountStorage
+ openUrl(url: string): Promise<void>
+ syncToken(): Promise<unknown>
+ purchases?: PurchaseAdapter
+}
+
+interface AccountStoreActions {
+ restore(): Promise<boolean>
+}
+
+interface AccountSubscriptionActions {
+ logOut(): void
+ manage(): void
+}
+
+export interface AccountModel {
+ phase: AccountPhase
+ account: AccountState | null
+ busy: boolean
+ errorKey: string | null
+ entry: string
+ codeReady: boolean
+ rotated: boolean
+ storeUnavailable: boolean
+ plan: BillingPlan
+ prices: PlanPrices
+ store?: AccountStoreActions
+ subscription: AccountSubscriptionActions
+ clearError(): void
+ setEntry(input: string): void
+ choosePlan(plan: BillingPlan): void
+ prepareStore(): void
+ showEntry(): void
+ showPaywall(): void
+ startUpgrade(): void
+ retryUpgrade(): void
+ cancelUpgrade(): void
+ activate(): Promise<boolean>
+ acknowledge(): void
+}
+
+const warn = (context: string, err: unknown) => console.warn(`[account] ${context}`, err)
+
+export function useAccount(adapter: AccountAdapter): AccountModel {
+ const { client, storage, openUrl, syncToken, purchases } = adapter
+ const [session, dispatch] = useReducer(accountReducer, initialAccountSession)
+ const [storeRequested, setStoreRequested] = useState(false)
+ const storeUnavailable = useStoreAvailability(storeRequested ? purchases : undefined)
+ const prices = usePlanPrices(client, purchases, storeRequested)
+ const inFlight = useRef(false)
+ const pending = useRef<ReservedCode | null>(null)
+
+ const creditPurchase = useCallback(
+ async (code: string, status: AccountStatus) => {
+ pending.current = null
+ dispatch({ type: 'purchased', account: { code, validUntil: status.validUntil ?? null } })
+ await syncToken()
+ },
+ [syncToken]
+ )
+
+ const reportTimeout = useCallback(() => dispatch({ type: 'failed', error: 'timedOut' }), [])
+
+ const { start: pollUntilActive, stop: stopPolling } = useEntitlementPoll({
+ client,
+ onActive: creditPurchase,
+ onTimeout: reportTimeout
+ })
+
+ const run = useCallback(async (action: () => Promise<boolean>): Promise<boolean> => {
+ if (inFlight.current) return false
+
+ inFlight.current = true
+ dispatch({ type: 'started' })
+
+ try {
+ const ok = await action()
+ dispatch({ type: 'settled' })
+ return ok
+ } catch (err) {
+ warn('action failed', err)
+ dispatch({ type: 'failed', error: classifyAccountError(err) })
+ return false
+ } finally {
+ inFlight.current = false
+ }
+ }, [])
+
+ const forget = useCallback(async () => {
+ pending.current = null
+ stopPolling()
+ await storage.clear()
+ dispatch({ type: 'forgotten' })
+
+ await syncToken()
+ }, [stopPolling, storage, syncToken])
+
+ const discard = useCallback(
+ async (code: string) => {
+ await client.remove(code).catch((err) => warn('orphan cleanup failed', err))
+ await forget()
+ },
+ [client, forget]
+ )
+
+ useEffect(() => {
+ let cancelled = false
+
+ storage
+ .read()
+ .then(async (code) => {
+ if (!code || cancelled) return
+
+ if (isSubscriptionActive()) {
+ dispatch({ type: 'activated', account: { code, validUntil: null } })
+ }
+
+ const status = await client.status(code)
+ if (cancelled) return
+
+ if (!status.exists) {
+ await storage.clear()
+ dispatch({ type: 'forgotten' })
+ return
+ }
+
+ if (status.active) {
+ dispatch({ type: 'activated', account: { code, validUntil: status.validUntil ?? null } })
+ return
+ }
+
+ dispatch({ type: 'showPaywall' })
+ })
+ .catch((err) => warn('status lookup failed', err))
+
+ return () => {
+ cancelled = true
+ }
+ }, [client, storage])
+
+ const subscriptionActive = useSubscriptionStore((state) => state.active)
+
+ useEffect(() => {
+ if (!subscriptionActive || session.phase !== 'paywall' || session.account) return
+
+ let cancelled = false
+ storage
+ .read()
+ .then((code) => {
+ if (code && !cancelled) dispatch({ type: 'activated', account: { code, validUntil: null } })
+ })
+ .catch((err) => warn('cached entitlement lookup failed', err))
+
+ return () => {
+ cancelled = true
+ }
+ }, [session.account, session.phase, storage, subscriptionActive])
+
+ const context = useMemo<PurchaseContext>(
+ () => ({
+ client,
+ storage,
+ purchases,
+ openUrl,
+ syncToken,
+ dispatch,
+ poll: pollUntilActive,
+ discard
+ }),
+ [client, discard, openUrl, pollUntilActive, purchases, storage, syncToken]
+ )
+
+ const startUpgrade = useCallback(() => {
+ if (storeUnavailable) return
+
+ run(async () => {
+ const reserved = await reserveCode(context)
+ pending.current = reserved
+
+ try {
+ return context.purchases
+ ? await buyFromStore(context, reserved, session.plan)
+ : await buyWithCard(context, reserved, session.plan)
+ } catch (err) {
+ await abandon(context, reserved)
+ throw err
+ }
+ })
+ }, [context, run, session.plan, storeUnavailable])
+
+ const restore = useCallback(() => {
+ return run(async () => {
+ const outcome = await restoreFromStore(context)
+
+ if (outcome === 'nothingToRestore') {
+ dispatch({ type: 'failed', error: 'nothingToRestore' })
+ return false
+ }
+
+ if (outcome === 'notMoved') {
+ dispatch({ type: 'failed', error: 'restoreNotMoved' })
+ return false
+ }
+
+ return true
+ })
+ }, [context, run])
+
+ const store = useMemo<AccountStoreActions | undefined>(
+ () => (purchases && !storeUnavailable ? { restore } : undefined),
+ [purchases, restore, storeUnavailable]
+ )
+
+ const retryUpgrade = useCallback(() => {
+ if (!session.account) return
+
+ dispatch({ type: 'upgrading', account: session.account })
+ pollUntilActive(session.account.code)
+ }, [pollUntilActive, session.account])
+
+ const cancelUpgrade = useCallback(() => {
+ const reserved = pending.current
+ run(async () => {
+ stopPolling()
+ pending.current = null
+
+ if (reserved?.fresh) await abandon(context, reserved)
+ else if (!reserved) await forget()
+ else dispatch({ type: 'showPaywall' })
+
+ return true
+ })
+ }, [context, forget, run, stopPolling])
+
+ const activate = useCallback(
+ () =>
+ run(async () => {
+ const code = normalizeAccountCode(session.entry)
+ if (!isValidAccountCode(code)) {
+ dispatch({ type: 'failed', error: 'unknownCode' })
+ return false
+ }
+
+ const status = await client.status(code)
+ if (!status.exists) {
+ dispatch({ type: 'failed', error: 'unknownCode' })
+ return false
+ }
+
+ if (!status.active) {
+ dispatch({ type: 'failed', error: 'expiredCode' })
+ return false
+ }
+
+ await storage.write(code)
+ dispatch({ type: 'activated', account: { code, validUntil: status.validUntil ?? null } })
+ await syncToken()
+
+ return true
+ }),
+ [client, run, session.entry, storage, syncToken]
+ )
+
+ const manage = useCallback(() => {
+ run(async () => {
+ if (!session.account) return false
+
+ const storeUrl = purchases ? await purchases.managementUrl() : null
+ const url = storeUrl ?? (await client.portal(session.account.code))
+
+ if (!url) return false
+ await openUrl(assertHttpsUrl(url, 'manage'))
+
+ return true
+ })
+ }, [client, openUrl, purchases, run, session.account])
+
+ const logOut = useCallback(() => {
+ run(async () => {
+ await forget()
+
+ return true
+ })
+ }, [forget, run])
+
+ const subscription = useMemo<AccountSubscriptionActions>(
+ () => ({ logOut, manage }),
+ [logOut, manage]
+ )
+
+ const setEntry = useCallback(
+ (input: string) => dispatch({ type: 'entryChanged', entry: formatAccountCodeInput(input) }),
+ []
+ )
+
+ const choosePlan = useCallback((plan: BillingPlan) => dispatch({ type: 'planChosen', plan }), [])
+ const clearError = useCallback(() => dispatch({ type: 'errorCleared' }), [])
+ const showEntry = useCallback(() => dispatch({ type: 'showEntry' }), [])
+ const showPaywall = useCallback(() => dispatch({ type: 'showPaywall' }), [])
+ const acknowledge = useCallback(() => dispatch({ type: 'acknowledged' }), [])
+ const prepareStore = useCallback(() => setStoreRequested(true), [])
+
+ return useMemo(
+ () => ({
+ phase: session.phase,
+ account: session.account,
+ busy: session.busy,
+ errorKey: accountErrorKey(session.error),
+ entry: session.entry,
+ codeReady: isAccountCodeReady(session.entry),
+ rotated: session.rotated,
+ storeUnavailable,
+ plan: session.plan,
+ prices,
+ store,
+ subscription,
+ clearError,
+ setEntry,
+ choosePlan,
+ prepareStore,
+ showEntry,
+ showPaywall,
+ startUpgrade,
+ retryUpgrade,
+ cancelUpgrade,
+ activate,
+ acknowledge
+ }),
+ [
+ acknowledge,
+ activate,
+ cancelUpgrade,
+ choosePlan,
+ clearError,
+ prepareStore,
+ prices,
+ retryUpgrade,
+ session,
+ setEntry,
+ showEntry,
+ showPaywall,
+ startUpgrade,
+ store,
+ storeUnavailable,
+ subscription
+ ]
+ )
+}
diff --git a/packages/domain/src/account/runtime/useEntitlementPoll.ts b/packages/domain/src/account/runtime/useEntitlementPoll.ts
new file mode 100644
index 0000000..49338d9
--- /dev/null
+++ b/packages/domain/src/account/runtime/useEntitlementPoll.ts
@@ -0,0 +1,82 @@
+import { useCallback, useEffect, useRef } from 'react'
+import type { AccountClient, AccountStatus } from '../transport'
+
+const FAST_MS = 3000
+const SLOW_MS = 10000
+const FAST_WINDOW_MS = 60 * 1000
+const TIMEOUT_MS = 15 * 60 * 1000
+
+export interface EntitlementPollOptions {
+ client: AccountClient
+ onActive(code: string, status: AccountStatus): void | Promise<void>
+ onTimeout(): void
+}
+
+export interface EntitlementPoll {
+ start(code: string): void
+ stop(): void
+}
+
+const warn = (err: unknown) => console.warn('[account] entitlement poll failed', err)
+
+export function useEntitlementPoll({
+ client,
+ onActive,
+ onTimeout
+}: EntitlementPollOptions): EntitlementPoll {
+ const timer = useRef<ReturnType<typeof setTimeout> | null>(null)
+ const attempt = useRef(0)
+
+ const stop = useCallback(() => {
+ attempt.current += 1
+ if (!timer.current) return
+ clearTimeout(timer.current)
+ timer.current = null
+ }, [])
+
+ useEffect(() => stop, [stop])
+
+ const start = useCallback(
+ (code: string) => {
+ stop()
+ const run = attempt.current
+ const startedAt = Date.now()
+
+ const schedule = () => {
+ if (run !== attempt.current) return
+ const elapsed = Date.now() - startedAt
+
+ if (elapsed > TIMEOUT_MS) {
+ onTimeout()
+ return
+ }
+
+ timer.current = setTimeout(tick, elapsed < FAST_WINDOW_MS ? FAST_MS : SLOW_MS)
+ }
+
+ const tick = () => {
+ client
+ .status(code)
+ .then(async (status) => {
+ if (run !== attempt.current) return
+ if (!status.active) {
+ schedule()
+ return
+ }
+
+ stop()
+ await onActive(code, status)
+ })
+ .catch((err) => {
+ warn(err)
+ schedule()
+ })
+ }
+
+ schedule()
+ },
+ [client, onActive, onTimeout, stop]
+ )
+
+ return { start, stop }
+}
diff --git a/packages/domain/src/account/runtime/usePlanPrices.ts b/packages/domain/src/account/runtime/usePlanPrices.ts
new file mode 100644
index 0000000..cf480ff
--- /dev/null
+++ b/packages/domain/src/account/runtime/usePlanPrices.ts
@@ -0,0 +1,37 @@
+import { useEffect, useState } from 'react'
+import { pricesFrom, type PlanOffer, type PlanPrices } from '../core'
+import type { PurchaseAdapter } from '../ports'
+import type { AccountClient } from '../transport'
+
+export function usePlanPrices(
+ client: AccountClient,
+ purchases?: PurchaseAdapter,
+ storeRequested = true
+): PlanPrices {
+ const [prices, setPrices] = useState<PlanPrices>({})
+
+ useEffect(() => {
+ if (purchases && !storeRequested) return
+
+ let cancelled = false
+
+ const load = async (): Promise<PlanOffer[]> => {
+ if (purchases) return purchases.offers()
+
+ const listed = await client.prices()
+ return listed.map((price) => ({ plan: price.plan, price: price.formatted }))
+ }
+
+ load()
+ .then((offers) => {
+ if (!cancelled) setPrices(pricesFrom(offers))
+ })
+ .catch((err) => console.warn('[account] loading prices failed', err))
+
+ return () => {
+ cancelled = true
+ }
+ }, [client, purchases, storeRequested])
+
+ return prices
+}
diff --git a/packages/domain/src/account/runtime/useStoreAvailability.ts b/packages/domain/src/account/runtime/useStoreAvailability.ts
new file mode 100644
index 0000000..2fa69f3
--- /dev/null
+++ b/packages/domain/src/account/runtime/useStoreAvailability.ts
@@ -0,0 +1,27 @@
+import { useEffect, useState } from 'react'
+import type { PurchaseAdapter } from '../ports'
+
+export function useStoreAvailability(purchases?: PurchaseAdapter): boolean {
+ const [unavailable, setUnavailable] = useState(false)
+
+ useEffect(() => {
+ if (!purchases) return
+
+ let cancelled = false
+
+ purchases
+ .available()
+ .then((ok) => {
+ if (!cancelled) setUnavailable(!ok)
+ })
+ .catch(() => {
+ if (!cancelled) setUnavailable(true)
+ })
+
+ return () => {
+ cancelled = true
+ }
+ }, [purchases])
+
+ return unavailable
+}
diff --git a/packages/domain/src/account/transport/AccountApiError.ts b/packages/domain/src/account/transport/AccountApiError.ts
new file mode 100644
index 0000000..67fa699
--- /dev/null
+++ b/packages/domain/src/account/transport/AccountApiError.ts
@@ -0,0 +1,13 @@
+export const NETWORK_ERROR_STATUS = 0
+export const TIMEOUT_ERROR_STATUS = -1
+export const SERVER_ERROR_STATUS = 500
+
+export class AccountApiError extends Error {
+ readonly status: number
+
+ constructor(status: number, message: string, cause?: unknown) {
+ super(message, { cause })
+ this.name = 'AccountApiError'
+ this.status = status
+ }
+}
diff --git a/packages/domain/src/account/transport/classifyAccountError.ts b/packages/domain/src/account/transport/classifyAccountError.ts
new file mode 100644
index 0000000..6a012dc
--- /dev/null
+++ b/packages/domain/src/account/transport/classifyAccountError.ts
@@ -0,0 +1,9 @@
+import type { AccountError } from '../core'
+import { AccountApiError, NETWORK_ERROR_STATUS, TIMEOUT_ERROR_STATUS } from './AccountApiError'
+
+export function classifyAccountError(err: unknown): AccountError {
+ if (!(err instanceof AccountApiError)) return 'failed'
+ if (err.status === NETWORK_ERROR_STATUS) return 'offline'
+ if (err.status === TIMEOUT_ERROR_STATUS || err.status >= 500) return 'server'
+ return 'failed'
+}
diff --git a/packages/domain/src/account/transport/client.ts b/packages/domain/src/account/transport/client.ts
new file mode 100644
index 0000000..22788cf
--- /dev/null
+++ b/packages/domain/src/account/transport/client.ts
@@ -0,0 +1,144 @@
+import type { BillingPlan } from '../core'
+import {
+ AccountApiError,
+ NETWORK_ERROR_STATUS,
+ SERVER_ERROR_STATUS,
+ TIMEOUT_ERROR_STATUS
+} from './AccountApiError'
+
+const REQUEST_TIMEOUT_MS = 15000
+
+interface NewAccount {
+ code: string
+ validUntil: string
+ active: boolean
+}
+
+export interface AccountStatus {
+ exists: boolean
+ active: boolean
+ validUntil?: string
+}
+
+interface AccountToken {
+ token: string
+ expiresAt: number
+}
+
+interface AccountDeletion {
+ deleted: boolean
+ subscriptionCancelled: boolean
+ customerDeleted: boolean
+}
+
+interface PlanPriceResponse {
+ plan: BillingPlan
+ formatted: string
+}
+
+export interface AccountClient {
+ prices(): Promise<PlanPriceResponse[]>
+ create(): Promise<NewAccount>
+ status(code: string): Promise<AccountStatus>
+ syncStore(code: string): Promise<AccountStatus>
+ checkout(code: string, plan: BillingPlan): Promise<string>
+ portal(code: string): Promise<string>
+ remove(code: string): Promise<AccountDeletion>
+ token(code: string): Promise<AccountToken | null>
+}
+
+async function send<T>(
+ baseUrl: string,
+ path: string,
+ method: 'GET' | 'POST' | 'DELETE',
+ body?: unknown
+): Promise<T> {
+ const controller = new AbortController()
+ const expiry = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS)
+ let response: Response
+
+ try {
+ response = await fetch(`${baseUrl}${path}`, {
+ method,
+ headers: { 'content-type': 'application/json' },
+ body: method === 'GET' ? undefined : JSON.stringify(body ?? {}),
+ signal: controller.signal
+ })
+ } catch (err) {
+ clearTimeout(expiry)
+ const status = controller.signal.aborted ? TIMEOUT_ERROR_STATUS : NETWORK_ERROR_STATUS
+ throw new AccountApiError(status, `${path} could not be reached`, err)
+ }
+
+ try {
+ if (!response.ok) {
+ throw new AccountApiError(response.status, `${path} failed with ${response.status}`)
+ }
+
+ return (await response.json()) as T
+ } catch (err) {
+ if (err instanceof AccountApiError) throw err
+
+ const status = controller.signal.aborted ? TIMEOUT_ERROR_STATUS : SERVER_ERROR_STATUS
+ throw new AccountApiError(status, `${path} returned an unreadable body`, err)
+ } finally {
+ clearTimeout(expiry)
+ }
+}
+
+export function createAccountClient(baseUrl: string): AccountClient {
+ const post = <T>(path: string, body?: unknown) => send<T>(baseUrl, path, 'POST', body)
+
+ return {
+ async prices() {
+ const { prices } = await send<{ prices: PlanPriceResponse[] }>(
+ baseUrl,
+ '/api/pro/prices',
+ 'GET'
+ )
+ return prices
+ },
+
+ create: () => post<NewAccount>('/api/pro/account'),
+
+ async status(code) {
+ try {
+ return await post<AccountStatus>('/api/pro/status', { code })
+ } catch (err) {
+ if (err instanceof AccountApiError && err.status === 404) {
+ return { exists: false, active: false }
+ }
+ throw err
+ }
+ },
+
+ async syncStore(code) {
+ const result = await post<{ active: boolean; validUntil?: string }>('/api/revenuecat/sync', {
+ code
+ })
+ return { exists: true, active: result.active, validUntil: result.validUntil }
+ },
+
+ async checkout(code, plan) {
+ const { url } = await post<{ url: string }>('/api/pro/checkout', { code, plan })
+ return url
+ },
+
+ async portal(code) {
+ const { url } = await post<{ url: string }>('/api/pro/portal', { code })
+ return url
+ },
+
+ remove: (code) => send<AccountDeletion>(baseUrl, '/api/pro/account', 'DELETE', { code }),
+
+ async token(code) {
+ try {
+ return await post<AccountToken>('/api/pro/token', { code })
+ } catch (err) {
+ if (err instanceof AccountApiError && (err.status === 403 || err.status === 404))
+ return null
+ throw err
+ }
+ }
+ }
+}
diff --git a/packages/domain/src/account/transport/index.ts b/packages/domain/src/account/transport/index.ts
new file mode 100644
index 0000000..caa0c40
--- /dev/null
+++ b/packages/domain/src/account/transport/index.ts
@@ -0,0 +1,3 @@
+export * from './AccountApiError'
+export * from './classifyAccountError'
+export * from './client'
diff --git a/packages/domain/src/constants/links.ts b/packages/domain/src/constants/links.ts
index be4d688..25eaa90 100644
--- a/packages/domain/src/constants/links.ts
+++ b/packages/domain/src/constants/links.ts
@@ -1,4 +1,5 @@
export const websiteUrl = 'https://altersend.com'
+export const accountApiUrl = 'https://api.altersend.com'
export const webAppUrl = 'https://app.altersend.com'
export const downloadUrl = 'https://altersend.com/download'
export const playStoreUrl = 'https://play.google.com/store/apps/details?id=com.altersend.mobile'
diff --git a/packages/domain/src/constants/transfer.test.ts b/packages/domain/src/constants/transfer.test.ts
index 7bfe5e9..3faed5d 100644
--- a/packages/domain/src/constants/transfer.test.ts
+++ b/packages/domain/src/constants/transfer.test.ts
@@ -18,3 +18,14 @@ describe('web link size limit', () => {
expect(exceedsWebLinkLimit(11 * 1024 ** 3)).toBe(true)
})
})
+
+describe('pro senders', () => {
+ it('is not blocked by the free web link ceiling', () => {
+ expect(exceedsWebLinkLimit(WEB_LINK_MAX_BYTES + 1, true)).toBe(false)
+ expect(exceedsWebLinkLimit(WEB_LINK_MAX_BYTES * 50, true)).toBe(false)
+ })
+
+ it('still applies the ceiling without pro', () => {
+ expect(exceedsWebLinkLimit(WEB_LINK_MAX_BYTES + 1, false)).toBe(true)
+ })
+})
diff --git a/packages/domain/src/constants/transfer.ts b/packages/domain/src/constants/transfer.ts
index 72856fe..de77310 100644
--- a/packages/domain/src/constants/transfer.ts
+++ b/packages/domain/src/constants/transfer.ts
@@ -4,8 +4,12 @@ export const WEB_LINK_MAX_BYTES = 10 * 1024 ** 3
export const WEB_LINK_MAX_LABEL = `${WEB_LINK_MAX_BYTES / 1024 ** 3} GB`
-export function exceedsWebLinkLimit(totalSize: number): boolean {
- return totalSize > WEB_LINK_MAX_BYTES
+export const NATIVE_RELAY_MAX_BYTES = 20 * 1024 ** 3
+
+export const NATIVE_RELAY_MAX_LABEL = `${NATIVE_RELAY_MAX_BYTES / 1024 ** 3} GB`
+
+export function exceedsWebLinkLimit(totalSize: number, pro = false): boolean {
+ return !pro && totalSize > WEB_LINK_MAX_BYTES
}
export function exceedsFileCountLimit(fileCount: number): boolean {
diff --git a/packages/domain/src/index.ts b/packages/domain/src/index.ts
index 0159bc3..ed56f40 100644
--- a/packages/domain/src/index.ts
+++ b/packages/domain/src/index.ts
@@ -28,5 +28,6 @@ export * from './constants'
export * from './useSimulatedLoading'
export * from './useCopiedFlag'
export * from './pairing'
+export * from './account'
export * from './feedback'
export * from './receive/useReceiveDownloads'
diff --git a/packages/locales/src/locales/de-DE/settings.json b/packages/locales/src/locales/de-DE/settings.json
index cca7d91..f9b50e4 100644
--- a/packages/locales/src/locales/de-DE/settings.json
+++ b/packages/locales/src/locales/de-DE/settings.json
@@ -108,5 +108,74 @@
"mediaToGalleryDescription": "Wenn deaktiviert, werden sie im Download-Ordner gespeichert.",
"destinationGallery": "Fotos & Videos in die Galerie",
"destinationDownloads": "Fotos & Videos in Downloads"
+ },
+ "account": {
+ "title": "Ihr Abo",
+ "paywallLead": "Größere Übertragungen und Vorrang beim Relay.",
+ "columnFree": "Kostenlos",
+ "columnPro": "Pro",
+ "upgradeToPro": "Auf Pro upgraden",
+ "haveCodeLink": "Sie haben schon Pro? Code eingeben",
+ "restore": "Kauf wiederherstellen",
+ "nothingToRestore": "Für dieses Konto wurde kein Kauf gefunden.",
+ "restoreNotMoved": "Ihr Abo konnte nicht auf dieses Gerät übertragen werden. Geben Sie stattdessen Ihren Code ein.",
+ "enterCodeTitle": "Code eingeben",
+ "codePlaceholder": "0000 0000 0000 0000",
+ "activate": "Aktivieren",
+ "back": "Zurück",
+ "unknownCode": "Code nicht erkannt.",
+ "expiredCode": "Dieses Abo ist abgelaufen. Verlängern Sie es, um Pro weiter zu nutzen.",
+ "failed": "Etwas ist schiefgelaufen. Versuchen Sie es gleich noch einmal.",
+ "offline": "Sie scheinen offline zu sein. Prüfen Sie Ihre Verbindung und versuchen Sie es erneut.",
+ "serverError": "Wir konnten unsere Seite nicht erreichen. Versuchen Sie es in ein paar Minuten erneut.",
+ "timedOut": "Wir sehen noch keine Zahlung. Wenn Sie den Kauf abgeschlossen haben, prüfen Sie erneut.",
+ "checkAgain": "Erneut prüfen",
+ "waitingTitle": "Schließen Sie Ihren Kauf im Browser ab",
+ "waitingBody": "Wir übernehmen ihn automatisch, sobald die Zahlung durchgeht.",
+ "waitingTitleStore": "Kauf wird bestätigt",
+ "waitingBodyStore": "Das dauert nur einen Moment.",
+ "approvalTitle": "Warten auf Freigabe",
+ "approvalBody": "Ihr Kauf muss noch freigegeben werden. Pro wird sofort danach freigeschaltet — Sie können dieses Fenster schließen.",
+ "cancel": "Abbrechen",
+ "successTitle": "Pro ist aktiv",
+ "yourCode": "Ihr Code",
+ "saveWarning": "Er ist Ihr einziger Kaufnachweis. Wir können ihn nicht wiederherstellen, weil wir nicht wissen, wer Sie sind.",
+ "codeReplaced": "Dies ist ein neuer Code – der bisherige funktioniert nicht mehr. Geben Sie ihn auf Ihren anderen Geräten ein.",
+ "savedCodeTitle": "Haben Sie Ihren Code gespeichert?",
+ "savedCodeBody": "Nur damit erhalten Sie Ihr Abo auf einem anderen Gerät zurück. Wir können ihn nicht für Sie wiederherstellen.",
+ "savedCodeConfirm": "Ja, gespeichert",
+ "done": "Fertig",
+ "copied": "Kopiert",
+ "copyFailed": "Ihr Code konnte nicht kopiert werden – kopieren Sie ihn manuell, bevor Sie sich abmelden.",
+ "saveCode": "Code als Datei speichern",
+ "codeFileTitle": "AlterSend Pro",
+ "codeFileCode": "Kontocode",
+ "codeFileSaved": "Gespeichert",
+ "codeFileWarning": "Dieser Code ist Ihr Abo. Geben Sie ihn in AlterSend auf einem beliebigen Gerät ein, um Pro wiederherzustellen. Wir haben ihn nie gespeichert und können ihn nicht für Sie wiederherstellen.",
+ "planPro": "Pro",
+ "subscriptionRow": "Abo",
+ "subscriptionValue": "{{plan}} · bis {{date}}",
+ "logOut": "Von diesem Gerät abmelden",
+ "logOutTitle": "Speichern Sie zuerst Ihren Code",
+ "logOutBody": "Beim Abmelden wird {{code}} von diesem Gerät entfernt. Es ist der einzige Weg zurück zu Pro, und wir können ihn nicht wiederherstellen.",
+ "copyAndLogOut": "Code kopieren und abmelden",
+ "reveal": "Code anzeigen",
+ "hide": "Code verbergen",
+ "upgrade": "Upgrade",
+ "paywallTitle": "Pro freischalten.",
+ "planMonthly": "Monatlich",
+ "planYearly": "Jährlich",
+ "billedMonthly": "Monatliche Abrechnung",
+ "billedYearly": "Jährliche Abrechnung",
+ "pricePerMonth": "{{price}}/Mon.",
+ "pricePerYear": "{{price}}/Jahr",
+ "included": "Enthalten",
+ "getPro": "Pro holen",
+ "storeUnavailable": "In-App-Käufe sind auf diesem Gerät nicht verfügbar. Kaufen Sie AlterSend Pro auf einem anderen Gerät und geben Sie Ihren Code hier ein.",
+ "none": "–",
+ "featureDirect": "Direkte P2P-Übertragung",
+ "featurePriority": "Vorrang, wenn das Relay ausgelastet ist",
+ "featureWebCap": "Übertragung über Relay, Weblink",
+ "featureAppCap": "Übertragung über Relay, App zu App"
}
}
diff --git a/packages/locales/src/locales/en-GB/settings.json b/packages/locales/src/locales/en-GB/settings.json
index b715324..a77d0c8 100644
--- a/packages/locales/src/locales/en-GB/settings.json
+++ b/packages/locales/src/locales/en-GB/settings.json
@@ -108,5 +108,74 @@
"mediaToGalleryDescription": "When off, they're saved to your Downloads folder.",
"destinationGallery": "Photos & videos to Gallery",
"destinationDownloads": "Photos & videos to Downloads"
+ },
+ "account": {
+ "title": "Your subscription",
+ "paywallLead": "Bigger transfers and priority on the relay.",
+ "columnFree": "Free",
+ "columnPro": "Pro",
+ "upgradeToPro": "Upgrade to Pro",
+ "haveCodeLink": "Already have Pro? Enter your code",
+ "restore": "Restore purchase",
+ "nothingToRestore": "No purchase found on this account.",
+ "restoreNotMoved": "Your subscription could not be moved to this device. Enter your code instead.",
+ "enterCodeTitle": "Enter your code",
+ "codePlaceholder": "0000 0000 0000 0000",
+ "activate": "Activate",
+ "back": "Back",
+ "unknownCode": "Code not recognised.",
+ "expiredCode": "That subscription has expired. Renew it to keep using Pro.",
+ "failed": "Something went wrong. Try again in a moment.",
+ "offline": "You appear to be offline. Check your connection and try again.",
+ "serverError": "We couldn't reach our side. Try again in a few minutes.",
+ "timedOut": "We haven't seen a payment yet. If you finished checkout, check again.",
+ "checkAgain": "Check again",
+ "waitingTitle": "Complete your purchase in the browser",
+ "waitingBody": "We'll pick it up automatically once the payment goes through.",
+ "waitingTitleStore": "Confirming your purchase",
+ "waitingBodyStore": "This only takes a moment.",
+ "approvalTitle": "Waiting for approval",
+ "approvalBody": "Your purchase needs approval before it can go through. Pro unlocks as soon as it does — you can close this.",
+ "cancel": "Cancel",
+ "successTitle": "Pro is active",
+ "yourCode": "Your code",
+ "saveWarning": "It's your only proof of purchase. We can't recover it, because we don't know who you are.",
+ "codeReplaced": "This is a new code — your previous one no longer works. Enter this one on your other devices.",
+ "savedCodeTitle": "Did you save your code?",
+ "savedCodeBody": "It's the only way to get your subscription back on another device. We can't recover it for you.",
+ "savedCodeConfirm": "Yes, I saved it",
+ "done": "Done",
+ "copied": "Copied",
+ "copyFailed": "Couldn't copy your code — copy it manually before logging out.",
+ "saveCode": "Save code to a file",
+ "codeFileTitle": "AlterSend Pro",
+ "codeFileCode": "Account code",
+ "codeFileSaved": "Saved",
+ "codeFileWarning": "This code is your subscription. Enter it in AlterSend on any device to restore Pro. We never stored it and cannot recover it for you.",
+ "planPro": "Pro",
+ "subscriptionRow": "Subscription",
+ "subscriptionValue": "{{plan}} · until {{date}}",
+ "logOut": "Log out of this device",
+ "logOutTitle": "Save your code first",
+ "logOutBody": "Logging out removes {{code}} from this device. It is the only way back into Pro, and we cannot recover it.",
+ "copyAndLogOut": "Copy code and log out",
+ "reveal": "Show code",
+ "hide": "Hide code",
+ "upgrade": "Upgrade",
+ "paywallTitle": "Unlock Pro.",
+ "planMonthly": "Monthly",
+ "planYearly": "Yearly",
+ "billedMonthly": "Billed monthly",
+ "billedYearly": "Billed annually",
+ "pricePerMonth": "{{price}}/mo",
+ "pricePerYear": "{{price}}/yr",
+ "included": "What's included",
+ "getPro": "Get Pro",
+ "storeUnavailable": "In-app purchase isn't available on this device. Buy AlterSend Pro on another device and enter your code here.",
+ "none": "–",
+ "featureDirect": "Direct P2P transfer",
+ "featurePriority": "Priority when the relay is busy",
+ "featureWebCap": "Relayed transfer, web link",
+ "featureAppCap": "Relayed transfer, app to app"
}
}
diff --git a/packages/locales/src/locales/en-US/settings.json b/packages/locales/src/locales/en-US/settings.json
index c3c5995..1118506 100644
--- a/packages/locales/src/locales/en-US/settings.json
+++ b/packages/locales/src/locales/en-US/settings.json
@@ -108,5 +108,74 @@
"body": "Pair a device you use often and send to it instantly — no code to scan or type each time.",
"pairButton": "Pair a Device",
"skip": "Skip for now"
+ },
+ "account": {
+ "title": "Your subscription",
+ "paywallLead": "Bigger transfers and priority on the relay.",
+ "columnFree": "Free",
+ "columnPro": "Pro",
+ "upgradeToPro": "Upgrade to Pro",
+ "haveCodeLink": "Already have Pro? Enter your code",
+ "restore": "Restore purchase",
+ "nothingToRestore": "No purchase found on this account.",
+ "restoreNotMoved": "Your subscription could not be moved to this device. Enter your code instead.",
+ "enterCodeTitle": "Enter your code",
+ "codePlaceholder": "0000 0000 0000 0000",
+ "activate": "Activate",
+ "back": "Back",
+ "unknownCode": "Code not recognised.",
+ "expiredCode": "That subscription has expired. Renew it to keep using Pro.",
+ "failed": "Something went wrong. Try again in a moment.",
+ "offline": "You appear to be offline. Check your connection and try again.",
+ "serverError": "We couldn't reach our side. Try again in a few minutes.",
+ "timedOut": "We haven't seen a payment yet. If you finished checkout, check again.",
+ "checkAgain": "Check again",
+ "waitingTitle": "Complete your purchase in the browser",
+ "waitingBody": "We'll pick it up automatically once the payment goes through.",
+ "waitingTitleStore": "Confirming your purchase",
+ "waitingBodyStore": "This only takes a moment.",
+ "approvalTitle": "Waiting for approval",
+ "approvalBody": "Your purchase needs approval before it can go through. Pro unlocks as soon as it does — you can close this.",
+ "cancel": "Cancel",
+ "successTitle": "Pro is active",
+ "yourCode": "Your code",
+ "saveWarning": "It's your only proof of purchase. We can't recover it, because we don't know who you are.",
+ "codeReplaced": "This is a new code — your previous one no longer works. Enter this one on your other devices.",
+ "savedCodeTitle": "Did you save your code?",
+ "savedCodeBody": "It's the only way to get your subscription back on another device. We can't recover it for you.",
+ "savedCodeConfirm": "Yes, I saved it",
+ "done": "Done",
+ "copied": "Copied",
+ "copyFailed": "Couldn't copy your code — copy it manually before logging out.",
+ "saveCode": "Save code to a file",
+ "codeFileTitle": "AlterSend Pro",
+ "codeFileCode": "Account code",
+ "codeFileSaved": "Saved",
+ "codeFileWarning": "This code is your subscription. Enter it in AlterSend on any device to restore Pro. We never stored it and cannot recover it for you.",
+ "planPro": "Pro",
+ "subscriptionRow": "Subscription",
+ "subscriptionValue": "{{plan}} · until {{date}}",
+ "logOut": "Log out of this device",
+ "logOutTitle": "Save your code first",
+ "logOutBody": "Logging out removes {{code}} from this device. It is the only way back into Pro, and we cannot recover it.",
+ "copyAndLogOut": "Copy code and log out",
+ "reveal": "Show code",
+ "hide": "Hide code",
+ "upgrade": "Upgrade",
+ "paywallTitle": "Unlock Pro.",
+ "planMonthly": "Monthly",
+ "planYearly": "Yearly",
+ "billedMonthly": "Billed monthly",
+ "billedYearly": "Billed annually",
+ "pricePerMonth": "{{price}}/mo",
+ "pricePerYear": "{{price}}/yr",
+ "included": "What's included",
+ "getPro": "Get Pro",
+ "storeUnavailable": "In-app purchase isn't available on this device. Buy AlterSend Pro on another device and enter your code here.",
+ "none": "–",
+ "featureDirect": "Direct P2P transfer",
+ "featurePriority": "Priority when the relay is busy",
+ "featureWebCap": "Relayed transfer, web link",
+ "featureAppCap": "Relayed transfer, app to app"
}
}
diff --git a/packages/locales/src/locales/es-419/settings.json b/packages/locales/src/locales/es-419/settings.json
index 38b328a..1880780 100644
--- a/packages/locales/src/locales/es-419/settings.json
+++ b/packages/locales/src/locales/es-419/settings.json
@@ -108,5 +108,74 @@
"mediaToGalleryDescription": "Si está desactivado, se guardan en tu carpeta de Descargas.",
"destinationGallery": "Fotos y videos en la Galería",
"destinationDownloads": "Fotos y videos en Descargas"
+ },
+ "account": {
+ "title": "Tu suscripción",
+ "paywallLead": "Transferencias más grandes y prioridad en el relé.",
+ "columnFree": "Gratis",
+ "columnPro": "Pro",
+ "upgradeToPro": "Cambiar a Pro",
+ "haveCodeLink": "¿Ya tienes Pro? Ingresa tu código",
+ "restore": "Restaurar compra",
+ "nothingToRestore": "No se ha encontrado ninguna compra en esta cuenta.",
+ "restoreNotMoved": "No se ha podido mover tu suscripción a este dispositivo. Introduce tu código.",
+ "enterCodeTitle": "Ingresa tu código",
+ "codePlaceholder": "0000 0000 0000 0000",
+ "activate": "Activar",
+ "back": "Atrás",
+ "unknownCode": "Código no reconocido.",
+ "expiredCode": "Esa suscripción ha caducado. Renuévala para seguir usando Pro.",
+ "failed": "Algo salió mal. Vuelve a intentarlo en un momento.",
+ "offline": "Parece que no tienes conexión. Revísala e inténtalo de nuevo.",
+ "serverError": "No pudimos contactar con nuestro servidor. Inténtalo en unos minutos.",
+ "timedOut": "Todavía no vemos el pago. Si terminaste la compra, vuelve a comprobarlo.",
+ "checkAgain": "Comprobar de nuevo",
+ "waitingTitle": "Completa la compra en el navegador",
+ "waitingBody": "La detectaremos automáticamente en cuanto se procese el pago.",
+ "waitingTitleStore": "Confirmando tu compra",
+ "waitingBodyStore": "Solo tardará un momento.",
+ "approvalTitle": "Esperando aprobación",
+ "approvalBody": "Tu compra necesita aprobación antes de completarse. Pro se activará apenas llegue: puedes cerrar esto.",
+ "cancel": "Cancelar",
+ "successTitle": "Pro está activo",
+ "yourCode": "Tu código",
+ "saveWarning": "Es tu única prueba de compra. No podemos recuperarlo, porque no sabemos quién eres.",
+ "codeReplaced": "Este es un código nuevo: el anterior ya no funciona. Ingrésalo en tus otros dispositivos.",
+ "savedCodeTitle": "¿Guardaste tu código?",
+ "savedCodeBody": "Es la única forma de recuperar tu suscripción en otro dispositivo. No podemos recuperarlo por ti.",
+ "savedCodeConfirm": "Sí, lo guardé",
+ "done": "Hecho",
+ "copied": "Copiado",
+ "copyFailed": "No se pudo copiar tu código: cópialo manualmente antes de cerrar sesión.",
+ "saveCode": "Guardar el código en un archivo",
+ "codeFileTitle": "AlterSend Pro",
+ "codeFileCode": "Código de cuenta",
+ "codeFileSaved": "Guardado",
+ "codeFileWarning": "Este código es tu suscripción. Ingrésalo en AlterSend en cualquier dispositivo para restaurar Pro. Nunca lo guardamos y no podemos recuperarlo por ti.",
+ "planPro": "Pro",
+ "subscriptionRow": "Suscripción",
+ "subscriptionValue": "{{plan}} · hasta {{date}}",
+ "logOut": "Cerrar sesión en este dispositivo",
+ "logOutTitle": "Guarda primero tu código",
+ "logOutBody": "Al cerrar sesión se elimina {{code}} de este dispositivo. Es la única forma de volver a Pro y no podemos recuperarlo.",
+ "copyAndLogOut": "Copiar código y cerrar sesión",
+ "reveal": "Mostrar código",
+ "hide": "Ocultar código",
+ "upgrade": "Mejorar",
+ "paywallTitle": "Activa Pro.",
+ "planMonthly": "Mensual",
+ "planYearly": "Anual",
+ "billedMonthly": "Facturación mensual",
+ "billedYearly": "Facturación anual",
+ "pricePerMonth": "{{price}}/mes",
+ "pricePerYear": "{{price}}/año",
+ "included": "Qué incluye",
+ "getPro": "Obtener Pro",
+ "storeUnavailable": "Las compras dentro de la aplicación no están disponibles en este dispositivo. Compra AlterSend Pro en otro dispositivo e ingresa aquí tu código.",
+ "none": "–",
+ "featureDirect": "Transferencia P2P directa",
+ "featurePriority": "Prioridad cuando el relé está saturado",
+ "featureWebCap": "Transferencia por relé, enlace web",
+ "featureAppCap": "Transferencia por relé, app a app"
}
}
diff --git a/packages/locales/src/locales/es-ES/settings.json b/packages/locales/src/locales/es-ES/settings.json
index bc0dae2..64a3de6 100644
--- a/packages/locales/src/locales/es-ES/settings.json
+++ b/packages/locales/src/locales/es-ES/settings.json
@@ -108,5 +108,74 @@
"mediaToGalleryDescription": "Si está desactivado, se guardan en tu carpeta de Descargas.",
"destinationGallery": "Fotos y vídeos en la Galería",
"destinationDownloads": "Fotos y vídeos en Descargas"
+ },
+ "account": {
+ "title": "Tu suscripción",
+ "paywallLead": "Transferencias más grandes y prioridad en el relé.",
+ "columnFree": "Gratis",
+ "columnPro": "Pro",
+ "upgradeToPro": "Pasar a Pro",
+ "haveCodeLink": "¿Ya tienes Pro? Introduce tu código",
+ "restore": "Restaurar compra",
+ "nothingToRestore": "No se ha encontrado ninguna compra en esta cuenta.",
+ "restoreNotMoved": "No se ha podido mover tu suscripción a este dispositivo. Introduce tu código.",
+ "enterCodeTitle": "Introduce tu código",
+ "codePlaceholder": "0000 0000 0000 0000",
+ "activate": "Activar",
+ "back": "Atrás",
+ "unknownCode": "Código no reconocido.",
+ "expiredCode": "Esa suscripción ha caducado. Renuévala para seguir usando Pro.",
+ "failed": "Algo ha salido mal. Vuelve a intentarlo en un momento.",
+ "offline": "Parece que no tienes conexión. Compruébala e inténtalo de nuevo.",
+ "serverError": "No hemos podido contactar con nuestro servidor. Inténtalo en unos minutos.",
+ "timedOut": "Aún no vemos el pago. Si has terminado la compra, vuelve a comprobarlo.",
+ "checkAgain": "Comprobar de nuevo",
+ "waitingTitle": "Completa la compra en el navegador",
+ "waitingBody": "La detectaremos automáticamente en cuanto se procese el pago.",
+ "waitingTitleStore": "Confirmando tu compra",
+ "waitingBodyStore": "Solo tardará un momento.",
+ "approvalTitle": "Esperando aprobación",
+ "approvalBody": "Tu compra necesita aprobación antes de completarse. Pro se activará en cuanto llegue: puedes cerrar esto.",
+ "cancel": "Cancelar",
+ "successTitle": "Pro está activo",
+ "yourCode": "Tu código",
+ "saveWarning": "Es tu única prueba de compra. No podemos recuperarlo, porque no sabemos quién eres.",
+ "codeReplaced": "Este es un código nuevo: el anterior ya no funciona. Introdúcelo en tus otros dispositivos.",
+ "savedCodeTitle": "¿Has guardado tu código?",
+ "savedCodeBody": "Es la única forma de recuperar tu suscripción en otro dispositivo. No podemos recuperarlo por ti.",
+ "savedCodeConfirm": "Sí, lo he guardado",
+ "done": "Hecho",
+ "copied": "Copiado",
+ "copyFailed": "No se pudo copiar tu código: cópialo manualmente antes de cerrar sesión.",
+ "saveCode": "Guardar el código en un archivo",
+ "codeFileTitle": "AlterSend Pro",
+ "codeFileCode": "Código de cuenta",
+ "codeFileSaved": "Guardado",
+ "codeFileWarning": "Este código es tu suscripción. Introdúcelo en AlterSend en cualquier dispositivo para restaurar Pro. Nunca lo hemos guardado y no podemos recuperarlo por ti.",
+ "planPro": "Pro",
+ "subscriptionRow": "Suscripción",
+ "subscriptionValue": "{{plan}} · hasta {{date}}",
+ "logOut": "Cerrar sesión en este dispositivo",
+ "logOutTitle": "Guarda primero tu código",
+ "logOutBody": "Al cerrar sesión se elimina {{code}} de este dispositivo. Es la única forma de volver a Pro y no podemos recuperarlo.",
+ "copyAndLogOut": "Copiar código y cerrar sesión",
+ "reveal": "Mostrar código",
+ "hide": "Ocultar código",
+ "upgrade": "Mejorar",
+ "paywallTitle": "Activa Pro.",
+ "planMonthly": "Mensual",
+ "planYearly": "Anual",
+ "billedMonthly": "Facturación mensual",
+ "billedYearly": "Facturación anual",
+ "pricePerMonth": "{{price}}/mes",
+ "pricePerYear": "{{price}}/año",
+ "included": "Qué incluye",
+ "getPro": "Obtener Pro",
+ "storeUnavailable": "Las compras dentro de la aplicación no están disponibles en este dispositivo. Compra AlterSend Pro en otro dispositivo e introduce aquí tu código.",
+ "none": "–",
+ "featureDirect": "Transferencia P2P directa",
+ "featurePriority": "Prioridad cuando el relé está saturado",
+ "featureWebCap": "Transferencia por relé, enlace web",
+ "featureAppCap": "Transferencia por relé, app a app"
}
}
diff --git a/packages/locales/src/locales/fr-FR/settings.json b/packages/locales/src/locales/fr-FR/settings.json
index 3b892f9..82ee4e7 100644
--- a/packages/locales/src/locales/fr-FR/settings.json
+++ b/packages/locales/src/locales/fr-FR/settings.json
@@ -108,5 +108,74 @@
"mediaToGalleryDescription": "Si désactivé, elles sont enregistrées dans votre dossier Téléchargements.",
"destinationGallery": "Photos et vidéos vers la Galerie",
"destinationDownloads": "Photos et vidéos vers Téléchargements"
+ },
+ "account": {
+ "title": "Votre abonnement",
+ "paywallLead": "Des transferts plus volumineux et la priorité sur le relais.",
+ "columnFree": "Gratuit",
+ "columnPro": "Pro",
+ "upgradeToPro": "Passer à Pro",
+ "haveCodeLink": "Vous avez déjà Pro ? Saisissez votre code",
+ "restore": "Restaurer l’achat",
+ "nothingToRestore": "Aucun achat trouvé sur ce compte.",
+ "restoreNotMoved": "Votre abonnement n’a pas pu être transféré vers cet appareil. Saisissez plutôt votre code.",
+ "enterCodeTitle": "Saisissez votre code",
+ "codePlaceholder": "0000 0000 0000 0000",
+ "activate": "Activer",
+ "back": "Retour",
+ "unknownCode": "Code non reconnu.",
+ "expiredCode": "Cet abonnement a expiré. Renouvelez-le pour continuer à utiliser Pro.",
+ "failed": "Une erreur est survenue. Réessayez dans un instant.",
+ "offline": "Vous semblez hors ligne. Vérifiez votre connexion et réessayez.",
+ "serverError": "Nous n’avons pas pu joindre notre serveur. Réessayez dans quelques minutes.",
+ "timedOut": "Nous ne voyons pas encore de paiement. Si vous avez terminé, vérifiez à nouveau.",
+ "checkAgain": "Vérifier à nouveau",
+ "waitingTitle": "Terminez votre achat dans le navigateur",
+ "waitingBody": "Nous le détecterons automatiquement dès que le paiement sera passé.",
+ "waitingTitleStore": "Confirmation de votre achat",
+ "waitingBodyStore": "Cela ne prend qu’un instant.",
+ "approvalTitle": "En attente d’approbation",
+ "approvalBody": "Votre achat doit être approuvé avant d’aboutir. Pro sera débloqué dès que ce sera fait — vous pouvez fermer cette fenêtre.",
+ "cancel": "Annuler",
+ "successTitle": "Pro est actif",
+ "yourCode": "Votre code",
+ "saveWarning": "C’est votre seule preuve d’achat. Nous ne pouvons pas le récupérer, car nous ne savons pas qui vous êtes.",
+ "codeReplaced": "Ceci est un nouveau code : le précédent ne fonctionne plus. Saisissez-le sur vos autres appareils.",
+ "savedCodeTitle": "Avez-vous enregistré votre code ?",
+ "savedCodeBody": "C'est le seul moyen de récupérer votre abonnement sur un autre appareil. Nous ne pouvons pas le retrouver pour vous.",
+ "savedCodeConfirm": "Oui, je l'ai enregistré",
+ "done": "Terminé",
+ "copied": "Copié",
+ "copyFailed": "Impossible de copier votre code : copiez-le manuellement avant de vous déconnecter.",
+ "saveCode": "Enregistrer le code dans un fichier",
+ "codeFileTitle": "AlterSend Pro",
+ "codeFileCode": "Code de compte",
+ "codeFileSaved": "Enregistré",
+ "codeFileWarning": "Ce code est votre abonnement. Saisissez-le dans AlterSend sur n’importe quel appareil pour restaurer Pro. Nous ne l’avons jamais conservé et ne pouvons pas le récupérer pour vous.",
+ "planPro": "Pro",
+ "subscriptionRow": "Abonnement",
+ "subscriptionValue": "{{plan}} · jusqu’au {{date}}",
+ "logOut": "Se déconnecter de cet appareil",
+ "logOutTitle": "Enregistrez d’abord votre code",
+ "logOutBody": "La déconnexion supprime {{code}} de cet appareil. C’est le seul moyen de retrouver Pro, et nous ne pouvons pas le récupérer.",
+ "copyAndLogOut": "Copier le code et se déconnecter",
+ "reveal": "Afficher le code",
+ "hide": "Masquer le code",
+ "upgrade": "Passer à Pro",
+ "paywallTitle": "Débloquez Pro.",
+ "planMonthly": "Mensuel",
+ "planYearly": "Annuel",
+ "billedMonthly": "Facturation mensuelle",
+ "billedYearly": "Facturation annuelle",
+ "pricePerMonth": "{{price}}/mois",
+ "pricePerYear": "{{price}}/an",
+ "included": "Ce qui est inclus",
+ "getPro": "Obtenir Pro",
+ "storeUnavailable": "Les achats intégrés ne sont pas disponibles sur cet appareil. Achetez AlterSend Pro sur un autre appareil, puis saisissez votre code ici.",
+ "none": "–",
+ "featureDirect": "Transfert P2P direct",
+ "featurePriority": "Priorité quand le relais est chargé",
+ "featureWebCap": "Transfert via relais, lien web",
+ "featureAppCap": "Transfert via relais, app à app"
}
}
diff --git a/packages/locales/src/locales/it-IT/settings.json b/packages/locales/src/locales/it-IT/settings.json
index 6aa3f9e..7a21b5f 100644
--- a/packages/locales/src/locales/it-IT/settings.json
+++ b/packages/locales/src/locales/it-IT/settings.json
@@ -108,5 +108,74 @@
"mediaToGalleryDescription": "Se disattivato, vengono salvati nella cartella Download.",
"destinationGallery": "Foto e video nella Galleria",
"destinationDownloads": "Foto e video in Download"
+ },
+ "account": {
+ "title": "Il tuo abbonamento",
+ "paywallLead": "Trasferimenti più grandi e priorità sul relay.",
+ "columnFree": "Gratis",
+ "columnPro": "Pro",
+ "upgradeToPro": "Passa a Pro",
+ "haveCodeLink": "Hai già Pro? Inserisci il codice",
+ "restore": "Ripristina acquisto",
+ "nothingToRestore": "Nessun acquisto trovato su questo account.",
+ "restoreNotMoved": "Non è stato possibile spostare il tuo abbonamento su questo dispositivo. Inserisci invece il codice.",
+ "enterCodeTitle": "Inserisci il codice",
+ "codePlaceholder": "0000 0000 0000 0000",
+ "activate": "Attiva",
+ "back": "Indietro",
+ "unknownCode": "Codice non riconosciuto.",
+ "expiredCode": "Questo abbonamento è scaduto. Rinnovalo per continuare a usare Pro.",
+ "failed": "Qualcosa è andato storto. Riprova tra poco.",
+ "offline": "Sembri offline. Controlla la connessione e riprova.",
+ "serverError": "Non siamo riusciti a raggiungere il nostro server. Riprova tra qualche minuto.",
+ "timedOut": "Non vediamo ancora il pagamento. Se hai completato l’acquisto, controlla di nuovo.",
+ "checkAgain": "Controlla di nuovo",
+ "waitingTitle": "Completa l’acquisto nel browser",
+ "waitingBody": "Lo rileveremo automaticamente appena il pagamento va a buon fine.",
+ "waitingTitleStore": "Conferma dell’acquisto",
+ "waitingBodyStore": "Ci vuole solo un attimo.",
+ "approvalTitle": "In attesa di approvazione",
+ "approvalBody": "Il tuo acquisto deve essere approvato prima di andare a buon fine. Pro si attiverà subito dopo: puoi chiudere questa schermata.",
+ "cancel": "Annulla",
+ "successTitle": "Pro è attivo",
+ "yourCode": "Il tuo codice",
+ "saveWarning": "È la tua unica prova d’acquisto. Non possiamo recuperarlo, perché non sappiamo chi sei.",
+ "codeReplaced": "Questo è un codice nuovo: quello precedente non funziona più. Inseriscilo sugli altri tuoi dispositivi.",
+ "savedCodeTitle": "Hai salvato il tuo codice?",
+ "savedCodeBody": "È l'unico modo per riavere l'abbonamento su un altro dispositivo. Non possiamo recuperarlo al posto tuo.",
+ "savedCodeConfirm": "Sì, l'ho salvato",
+ "done": "Fatto",
+ "copied": "Copiato",
+ "copyFailed": "Non è stato possibile copiare il codice: copialo manualmente prima di uscire.",
+ "saveCode": "Salva il codice in un file",
+ "codeFileTitle": "AlterSend Pro",
+ "codeFileCode": "Codice account",
+ "codeFileSaved": "Salvato",
+ "codeFileWarning": "Questo codice è il tuo abbonamento. Inseriscilo in AlterSend su qualsiasi dispositivo per ripristinare Pro. Non lo abbiamo mai conservato e non possiamo recuperarlo per te.",
+ "planPro": "Pro",
+ "subscriptionRow": "Abbonamento",
+ "subscriptionValue": "{{plan}} · fino al {{date}}",
+ "logOut": "Esci da questo dispositivo",
+ "logOutTitle": "Salva prima il codice",
+ "logOutBody": "Uscendo, {{code}} verrà rimosso da questo dispositivo. È l’unico modo per tornare a Pro e non possiamo recuperarlo.",
+ "copyAndLogOut": "Copia il codice ed esci",
+ "reveal": "Mostra codice",
+ "hide": "Nascondi codice",
+ "upgrade": "Passa a Pro",
+ "paywallTitle": "Sblocca Pro.",
+ "planMonthly": "Mensile",
+ "planYearly": "Annuale",
+ "billedMonthly": "Fatturazione mensile",
+ "billedYearly": "Fatturazione annuale",
+ "pricePerMonth": "{{price}}/mese",
+ "pricePerYear": "{{price}}/anno",
+ "included": "Cosa include",
+ "getPro": "Ottieni Pro",
+ "storeUnavailable": "Gli acquisti in-app non sono disponibili su questo dispositivo. Acquista AlterSend Pro su un altro dispositivo e inserisci qui il tuo codice.",
+ "none": "–",
+ "featureDirect": "Trasferimento P2P diretto",
+ "featurePriority": "Priorità quando il relay è occupato",
+ "featureWebCap": "Trasferimento via relay, link web",
+ "featureAppCap": "Trasferimento via relay, app ad app"
}
}
diff --git a/packages/locales/src/locales/ja-JP/settings.json b/packages/locales/src/locales/ja-JP/settings.json
index e606a5d..7cf0651 100644
--- a/packages/locales/src/locales/ja-JP/settings.json
+++ b/packages/locales/src/locales/ja-JP/settings.json
@@ -108,5 +108,74 @@
"mediaToGalleryDescription": "オフの場合、ダウンロードフォルダに保存されます。",
"destinationGallery": "写真と動画をギャラリーへ",
"destinationDownloads": "写真と動画をダウンロードへ"
+ },
+ "account": {
+ "title": "ご利用中のサブスクリプション",
+ "paywallLead": "より大きな転送と、リレー利用時の優先処理。",
+ "columnFree": "無料",
+ "columnPro": "Pro",
+ "upgradeToPro": "Pro にアップグレード",
+ "haveCodeLink": "すでに Pro をお持ちですか?コードを入力",
+ "restore": "購入を復元",
+ "nothingToRestore": "このアカウントで購入が見つかりませんでした。",
+ "restoreNotMoved": "サブスクリプションをこの端末に移行できませんでした。代わりにコードを入力してください。",
+ "enterCodeTitle": "コードを入力",
+ "codePlaceholder": "0000 0000 0000 0000",
+ "activate": "有効にする",
+ "back": "戻る",
+ "unknownCode": "コードを認識できません。",
+ "expiredCode": "このサブスクリプションは期限切れです。Pro を続けるには更新してください。",
+ "failed": "問題が発生しました。少ししてからもう一度お試しください。",
+ "offline": "オフラインのようです。接続を確認してもう一度お試しください。",
+ "serverError": "サーバーに接続できませんでした。数分後にもう一度お試しください。",
+ "timedOut": "まだ支払いを確認できていません。購入が完了している場合は、再確認してください。",
+ "checkAgain": "再確認",
+ "waitingTitle": "ブラウザで購入を完了してください",
+ "waitingBody": "支払いが完了すると自動的に反映されます。",
+ "waitingTitleStore": "購入を確認しています",
+ "waitingBodyStore": "すぐに完了します。",
+ "approvalTitle": "承認待ち",
+ "approvalBody": "この購入には承認が必要です。承認されるとすぐに Pro が有効になります。この画面は閉じてかまいません。",
+ "cancel": "キャンセル",
+ "successTitle": "Pro が有効です",
+ "yourCode": "あなたのコード",
+ "saveWarning": "これが唯一の購入証明です。あなたが誰かを把握していないため、復元することはできません。",
+ "codeReplaced": "これは新しいコードです。以前のコードは使えなくなりました。ほかの端末ではこのコードを入力してください。",
+ "savedCodeTitle": "コードを保存しましたか?",
+ "savedCodeBody": "ほかの端末でサブスクリプションを復元する唯一の方法です。こちらでは復元できません。",
+ "savedCodeConfirm": "保存しました",
+ "done": "完了",
+ "copied": "コピーしました",
+ "copyFailed": "コードをコピーできませんでした。ログアウトする前に手動でコピーしてください。",
+ "saveCode": "コードをファイルに保存",
+ "codeFileTitle": "AlterSend Pro",
+ "codeFileCode": "アカウントコード",
+ "codeFileSaved": "保存済み",
+ "codeFileWarning": "このコードがサブスクリプションそのものです。どの端末でも AlterSend に入力すれば Pro を復元できます。当社は保存しておらず、再発行はできません。",
+ "planPro": "Pro",
+ "subscriptionRow": "サブスクリプション",
+ "subscriptionValue": "{{plan}} · {{date}} まで",
+ "logOut": "この端末からログアウト",
+ "logOutTitle": "先にコードを保存してください",
+ "logOutBody": "ログアウトすると {{code}} がこの端末から削除されます。Pro に戻る唯一の手段であり、復元はできません。",
+ "copyAndLogOut": "コードをコピーしてログアウト",
+ "reveal": "コードを表示",
+ "hide": "コードを隠す",
+ "upgrade": "アップグレード",
+ "paywallTitle": "Pro を解放。",
+ "planMonthly": "月額",
+ "planYearly": "年額",
+ "billedMonthly": "毎月請求",
+ "billedYearly": "年に1回請求",
+ "pricePerMonth": "{{price}}/月",
+ "pricePerYear": "{{price}}/年",
+ "included": "含まれるもの",
+ "getPro": "Pro を購入",
+ "storeUnavailable": "この端末ではアプリ内購入を利用できません。ほかの端末で AlterSend Pro を購入し、コードをここに入力してください。",
+ "none": "–",
+ "featureDirect": "直接 P2P 転送",
+ "featurePriority": "リレー混雑時の優先処理",
+ "featureWebCap": "リレー経由の転送(ウェブリンク)",
+ "featureAppCap": "リレー経由の転送(アプリ間)"
}
}
diff --git a/packages/locales/src/locales/ko-KR/settings.json b/packages/locales/src/locales/ko-KR/settings.json
index e387771..08a0c56 100644
--- a/packages/locales/src/locales/ko-KR/settings.json
+++ b/packages/locales/src/locales/ko-KR/settings.json
@@ -108,5 +108,74 @@
"mediaToGalleryDescription": "끄면 다운로드 폴더에 저장됩니다.",
"destinationGallery": "사진 및 동영상을 갤러리로",
"destinationDownloads": "사진 및 동영상을 다운로드로"
+ },
+ "account": {
+ "title": "내 구독",
+ "paywallLead": "더 큰 전송과 릴레이 우선 처리.",
+ "columnFree": "무료",
+ "columnPro": "Pro",
+ "upgradeToPro": "Pro로 업그레이드",
+ "haveCodeLink": "이미 Pro가 있나요? 코드를 입력하세요",
+ "restore": "구매 복원",
+ "nothingToRestore": "이 계정에서 구매를 찾을 수 없습니다.",
+ "restoreNotMoved": "구독을 이 기기로 옮기지 못했습니다. 대신 코드를 입력하세요.",
+ "enterCodeTitle": "코드 입력",
+ "codePlaceholder": "0000 0000 0000 0000",
+ "activate": "활성화",
+ "back": "뒤로",
+ "unknownCode": "코드를 인식할 수 없습니다.",
+ "expiredCode": "구독이 만료되었습니다. Pro를 계속 사용하려면 갱신하세요.",
+ "failed": "문제가 발생했습니다. 잠시 후 다시 시도하세요.",
+ "offline": "오프라인 상태인 것 같습니다. 연결을 확인하고 다시 시도하세요.",
+ "serverError": "서버에 연결하지 못했습니다. 몇 분 후에 다시 시도하세요.",
+ "timedOut": "아직 결제가 확인되지 않았습니다. 결제를 마쳤다면 다시 확인하세요.",
+ "checkAgain": "다시 확인",
+ "waitingTitle": "브라우저에서 결제를 완료하세요",
+ "waitingBody": "결제가 완료되면 자동으로 반영됩니다.",
+ "waitingTitleStore": "구매 확인 중",
+ "waitingBodyStore": "잠시면 됩니다.",
+ "approvalTitle": "승인 대기 중",
+ "approvalBody": "이 구매는 승인이 필요합니다. 승인되면 바로 Pro가 열립니다. 이 화면은 닫아도 됩니다.",
+ "cancel": "취소",
+ "successTitle": "Pro가 활성화되었습니다",
+ "yourCode": "내 코드",
+ "saveWarning": "유일한 구매 증명입니다. 저희는 회원이 누구인지 모르기 때문에 복구해 드릴 수 없습니다.",
+ "codeReplaced": "새 코드입니다. 이전 코드는 더 이상 사용할 수 없습니다. 다른 기기에는 이 코드를 입력하세요.",
+ "savedCodeTitle": "코드를 저장하셨나요?",
+ "savedCodeBody": "다른 기기에서 구독을 되찾을 수 있는 유일한 방법입니다. 저희가 복구해 드릴 수 없습니다.",
+ "savedCodeConfirm": "네, 저장했습니다",
+ "done": "완료",
+ "copied": "복사됨",
+ "copyFailed": "코드를 복사하지 못했습니다. 로그아웃하기 전에 직접 복사하세요.",
+ "saveCode": "코드를 파일로 저장",
+ "codeFileTitle": "AlterSend Pro",
+ "codeFileCode": "계정 코드",
+ "codeFileSaved": "저장됨",
+ "codeFileWarning": "이 코드가 곧 구독입니다. 어떤 기기에서든 AlterSend에 입력하면 Pro를 복원할 수 있습니다. 저희는 저장하지 않으며 복구해 드릴 수 없습니다.",
+ "planPro": "Pro",
+ "subscriptionRow": "구독",
+ "subscriptionValue": "{{plan}} · {{date}}까지",
+ "logOut": "이 기기에서 로그아웃",
+ "logOutTitle": "코드를 먼저 저장하세요",
+ "logOutBody": "로그아웃하면 {{code}}가 이 기기에서 삭제됩니다. Pro로 돌아갈 유일한 방법이며 복구할 수 없습니다.",
+ "copyAndLogOut": "코드 복사 후 로그아웃",
+ "reveal": "코드 표시",
+ "hide": "코드 숨기기",
+ "upgrade": "업그레이드",
+ "paywallTitle": "Pro 잠금 해제.",
+ "planMonthly": "월간",
+ "planYearly": "연간",
+ "billedMonthly": "매월 청구",
+ "billedYearly": "연 1회 청구",
+ "pricePerMonth": "{{price}}/월",
+ "pricePerYear": "{{price}}/년",
+ "included": "포함 내용",
+ "getPro": "Pro 시작하기",
+ "storeUnavailable": "이 기기에서는 인앱 구매를 사용할 수 없습니다. 다른 기기에서 AlterSend Pro를 구매한 뒤 코드를 여기에 입력하세요.",
+ "none": "–",
+ "featureDirect": "직접 P2P 전송",
+ "featurePriority": "릴레이가 혼잡할 때 우선 처리",
+ "featureWebCap": "릴레이 전송, 웹 링크",
+ "featureAppCap": "릴레이 전송, 앱 간"
}
}
diff --git a/packages/locales/src/locales/pt-BR/settings.json b/packages/locales/src/locales/pt-BR/settings.json
index e44d9ac..dedada5 100644
--- a/packages/locales/src/locales/pt-BR/settings.json
+++ b/packages/locales/src/locales/pt-BR/settings.json
@@ -108,5 +108,74 @@
"mediaToGalleryDescription": "Se desativado, são salvos na sua pasta Downloads.",
"destinationGallery": "Fotos e vídeos na Galeria",
"destinationDownloads": "Fotos e vídeos em Downloads"
+ },
+ "account": {
+ "title": "Sua assinatura",
+ "paywallLead": "Transferências maiores e prioridade no retransmissor.",
+ "columnFree": "Grátis",
+ "columnPro": "Pro",
+ "upgradeToPro": "Mudar para o Pro",
+ "haveCodeLink": "Já tem o Pro? Digite seu código",
+ "restore": "Restaurar compra",
+ "nothingToRestore": "Nenhuma compra encontrada nesta conta.",
+ "restoreNotMoved": "Não foi possível mover sua assinatura para este dispositivo. Digite seu código.",
+ "enterCodeTitle": "Digite seu código",
+ "codePlaceholder": "0000 0000 0000 0000",
+ "activate": "Ativar",
+ "back": "Voltar",
+ "unknownCode": "Código não reconhecido.",
+ "expiredCode": "Essa assinatura expirou. Renove para continuar usando o Pro.",
+ "failed": "Algo deu errado. Tente de novo em instantes.",
+ "offline": "Você parece estar off-line. Verifique a conexão e tente de novo.",
+ "serverError": "Não conseguimos falar com o nosso servidor. Tente em alguns minutos.",
+ "timedOut": "Ainda não vemos o pagamento. Se você concluiu a compra, verifique de novo.",
+ "checkAgain": "Verificar de novo",
+ "waitingTitle": "Conclua a compra no navegador",
+ "waitingBody": "Vamos detectar automaticamente assim que o pagamento for aprovado.",
+ "waitingTitleStore": "Confirmando sua compra",
+ "waitingBodyStore": "Leva só um instante.",
+ "approvalTitle": "Aguardando aprovação",
+ "approvalBody": "Sua compra precisa de aprovação antes de ser concluída. O Pro é liberado assim que isso acontecer — pode fechar esta tela.",
+ "cancel": "Cancelar",
+ "successTitle": "O Pro está ativo",
+ "yourCode": "Seu código",
+ "saveWarning": "É seu único comprovante de compra. Não podemos recuperá-lo, porque não sabemos quem você é.",
+ "codeReplaced": "Este é um código novo: o anterior não funciona mais. Insira este nos seus outros dispositivos.",
+ "savedCodeTitle": "Você salvou seu código?",
+ "savedCodeBody": "É a única forma de recuperar sua assinatura em outro dispositivo. Não podemos recuperá-lo para você.",
+ "savedCodeConfirm": "Sim, salvei",
+ "done": "Concluído",
+ "copied": "Copiado",
+ "copyFailed": "Não foi possível copiar seu código: copie-o manualmente antes de sair.",
+ "saveCode": "Salvar o código em um arquivo",
+ "codeFileTitle": "AlterSend Pro",
+ "codeFileCode": "Código da conta",
+ "codeFileSaved": "Salvo",
+ "codeFileWarning": "Este código é a sua assinatura. Digite-o no AlterSend em qualquer dispositivo para restaurar o Pro. Nunca o armazenamos e não podemos recuperá-lo para você.",
+ "planPro": "Pro",
+ "subscriptionRow": "Assinatura",
+ "subscriptionValue": "{{plan}} · até {{date}}",
+ "logOut": "Sair deste dispositivo",
+ "logOutTitle": "Salve seu código primeiro",
+ "logOutBody": "Sair remove {{code}} deste dispositivo. É a única forma de voltar ao Pro, e não podemos recuperá-lo.",
+ "copyAndLogOut": "Copiar código e sair",
+ "reveal": "Mostrar código",
+ "hide": "Ocultar código",
+ "upgrade": "Fazer upgrade",
+ "paywallTitle": "Ative o Pro.",
+ "planMonthly": "Mensal",
+ "planYearly": "Anual",
+ "billedMonthly": "Cobrança mensal",
+ "billedYearly": "Cobrança anual",
+ "pricePerMonth": "{{price}}/mês",
+ "pricePerYear": "{{price}}/ano",
+ "included": "O que está incluído",
+ "getPro": "Obter o Pro",
+ "storeUnavailable": "As compras no app não estão disponíveis neste dispositivo. Compre o AlterSend Pro em outro dispositivo e insira seu código aqui.",
+ "none": "–",
+ "featureDirect": "Transferência P2P direta",
+ "featurePriority": "Prioridade quando o retransmissor está ocupado",
+ "featureWebCap": "Transferência via retransmissor, link web",
+ "featureAppCap": "Transferência via retransmissor, app para app"
}
}
diff --git a/packages/locales/src/locales/ru-RU/settings.json b/packages/locales/src/locales/ru-RU/settings.json
index 46d95ef..cba4227 100644
--- a/packages/locales/src/locales/ru-RU/settings.json
+++ b/packages/locales/src/locales/ru-RU/settings.json
@@ -108,5 +108,74 @@
"body": "Сопрягите устройство, которым часто пользуетесь, и отправляйте на него файлы мгновенно — без кода для сканирования или ввода каждый раз.",
"pairButton": "Сопрячь устройство",
"skip": "Пропустить"
+ },
+ "account": {
+ "title": "Ваша подписка",
+ "paywallLead": "Больше объём передач и приоритет на ретрансляторе.",
+ "columnFree": "Бесплатно",
+ "columnPro": "Pro",
+ "upgradeToPro": "Перейти на Pro",
+ "haveCodeLink": "Уже есть Pro? Введите код",
+ "restore": "Восстановить покупку",
+ "nothingToRestore": "Для этого аккаунта покупок не найдено.",
+ "restoreNotMoved": "Не удалось перенести подписку на это устройство. Введите код вручную.",
+ "enterCodeTitle": "Введите код",
+ "codePlaceholder": "0000 0000 0000 0000",
+ "activate": "Активировать",
+ "back": "Назад",
+ "unknownCode": "Код не распознан.",
+ "expiredCode": "Срок подписки истёк. Продлите её, чтобы продолжить пользоваться Pro.",
+ "failed": "Что-то пошло не так. Повторите попытку через минуту.",
+ "offline": "Похоже, нет подключения. Проверьте сеть и попробуйте снова.",
+ "serverError": "Не удалось связаться с сервером. Попробуйте через несколько минут.",
+ "timedOut": "Платёж пока не виден. Если вы завершили оплату, проверьте ещё раз.",
+ "checkAgain": "Проверить снова",
+ "waitingTitle": "Завершите покупку в браузере",
+ "waitingBody": "Мы подхватим её автоматически, как только пройдёт оплата.",
+ "waitingTitleStore": "Подтверждаем покупку",
+ "waitingBodyStore": "Это займёт всего мгновение.",
+ "approvalTitle": "Ожидание подтверждения",
+ "approvalBody": "Покупку нужно подтвердить, прежде чем она пройдёт. Pro включится сразу после этого — окно можно закрыть.",
+ "cancel": "Отмена",
+ "successTitle": "Pro активен",
+ "yourCode": "Ваш код",
+ "saveWarning": "Это единственное подтверждение покупки. Мы не сможем его восстановить, потому что не знаем, кто вы.",
+ "codeReplaced": "Это новый код — предыдущий больше не действует. Введите его на других устройствах.",
+ "savedCodeTitle": "Вы сохранили код?",
+ "savedCodeBody": "Только он позволит вернуть подписку на другом устройстве. Мы не сможем его восстановить.",
+ "savedCodeConfirm": "Да, сохранил",
+ "done": "Готово",
+ "copied": "Скопировано",
+ "copyFailed": "Не удалось скопировать код — скопируйте его вручную перед выходом.",
+ "saveCode": "Сохранить код в файл",
+ "codeFileTitle": "AlterSend Pro",
+ "codeFileCode": "Код аккаунта",
+ "codeFileSaved": "Сохранено",
+ "codeFileWarning": "Этот код — ваша подписка. Введите его в AlterSend на любом устройстве, чтобы вернуть Pro. Мы никогда его не хранили и не сможем восстановить.",
+ "planPro": "Pro",
+ "subscriptionRow": "Подписка",
+ "subscriptionValue": "{{plan}} · до {{date}}",
+ "logOut": "Выйти на этом устройстве",
+ "logOutTitle": "Сначала сохраните код",
+ "logOutBody": "При выходе {{code}} будет удалён с этого устройства. Это единственный способ вернуть Pro, и мы не сможем его восстановить.",
+ "copyAndLogOut": "Скопировать код и выйти",
+ "reveal": "Показать код",
+ "hide": "Скрыть код",
+ "upgrade": "Улучшить",
+ "paywallTitle": "Откройте Pro.",
+ "planMonthly": "Ежемесячно",
+ "planYearly": "Ежегодно",
+ "billedMonthly": "Оплата ежемесячно",
+ "billedYearly": "Оплата раз в год",
+ "pricePerMonth": "{{price}}/мес",
+ "pricePerYear": "{{price}}/год",
+ "included": "Что входит",
+ "getPro": "Получить Pro",
+ "storeUnavailable": "Покупки в приложении недоступны на этом устройстве. Оформите AlterSend Pro на другом устройстве и введите код здесь.",
+ "none": "–",
+ "featureDirect": "Прямая P2P-передача",
+ "featurePriority": "Приоритет, когда ретранслятор загружен",
+ "featureWebCap": "Передача через ретранслятор, веб-ссылка",
+ "featureAppCap": "Передача через ретранслятор, между приложениями"
}
}
diff --git a/packages/locales/src/locales/zh-CN/settings.json b/packages/locales/src/locales/zh-CN/settings.json
index ef2ea8e..0fb2dd3 100644
--- a/packages/locales/src/locales/zh-CN/settings.json
+++ b/packages/locales/src/locales/zh-CN/settings.json
@@ -108,5 +108,74 @@
"mediaToGalleryDescription": "关闭后,将保存到下载文件夹。",
"destinationGallery": "照片和视频保存到相册",
"destinationDownloads": "照片和视频保存到下载"
+ },
+ "account": {
+ "title": "我的订阅",
+ "paywallLead": "更大的传输容量,中继繁忙时优先。",
+ "columnFree": "免费",
+ "columnPro": "Pro",
+ "upgradeToPro": "升级到 Pro",
+ "haveCodeLink": "已有 Pro?输入你的代码",
+ "restore": "恢复购买",
+ "nothingToRestore": "此账号未找到任何购买记录。",
+ "restoreNotMoved": "无法将订阅转移到此设备,请改为输入代码。",
+ "enterCodeTitle": "输入代码",
+ "codePlaceholder": "0000 0000 0000 0000",
+ "activate": "激活",
+ "back": "返回",
+ "unknownCode": "无法识别该代码。",
+ "expiredCode": "该订阅已过期。续订后可继续使用 Pro。",
+ "failed": "出了点问题,请稍后再试。",
+ "offline": "你似乎已离线。请检查网络后重试。",
+ "serverError": "无法连接到我们的服务器,请几分钟后重试。",
+ "timedOut": "尚未看到付款。如果你已完成结账,请再次检查。",
+ "checkAgain": "再次检查",
+ "waitingTitle": "请在浏览器中完成购买",
+ "waitingBody": "付款完成后我们会自动识别。",
+ "waitingTitleStore": "正在确认购买",
+ "waitingBodyStore": "只需片刻。",
+ "approvalTitle": "等待批准",
+ "approvalBody": "此次购买需要批准后才能完成。批准后 Pro 会立即开通,你可以关闭此页面。",
+ "cancel": "取消",
+ "successTitle": "Pro 已启用",
+ "yourCode": "你的代码",
+ "saveWarning": "这是你唯一的购买凭证。我们不知道你是谁,因此无法为你找回。",
+ "codeReplaced": "这是一个新代码,之前的代码已失效。请在你的其他设备上输入这个代码。",
+ "savedCodeTitle": "你保存代码了吗?",
+ "savedCodeBody": "这是在其他设备上恢复订阅的唯一方式。我们无法为你找回。",
+ "savedCodeConfirm": "已保存",
+ "done": "完成",
+ "copied": "已复制",
+ "copyFailed": "无法复制你的代码,请在退出前手动复制。",
+ "saveCode": "将代码保存为文件",
+ "codeFileTitle": "AlterSend Pro",
+ "codeFileCode": "账号代码",
+ "codeFileSaved": "已保存",
+ "codeFileWarning": "这个代码就是你的订阅。在任意设备的 AlterSend 中输入即可恢复 Pro。我们从未存储它,也无法为你找回。",
+ "planPro": "Pro",
+ "subscriptionRow": "订阅",
+ "subscriptionValue": "{{plan}} · 至 {{date}}",
+ "logOut": "在此设备上退出登录",
+ "logOutTitle": "请先保存代码",
+ "logOutBody": "退出登录会从此设备移除 {{code}}。这是回到 Pro 的唯一方式,我们无法找回。",
+ "copyAndLogOut": "复制代码并退出",
+ "reveal": "显示代码",
+ "hide": "隐藏代码",
+ "upgrade": "升级",
+ "paywallTitle": "解锁 Pro。",
+ "planMonthly": "按月",
+ "planYearly": "按年",
+ "billedMonthly": "按月扣费",
+ "billedYearly": "按年扣费",
+ "pricePerMonth": "{{price}}/月",
+ "pricePerYear": "{{price}}/年",
+ "included": "包含内容",
+ "getPro": "获取 Pro",
+ "storeUnavailable": "此设备不支持应用内购买。请在其他设备上购买 AlterSend Pro,然后在此输入代码。",
+ "none": "–",
+ "featureDirect": "直接 P2P 传输",
+ "featurePriority": "中继繁忙时优先",
+ "featureWebCap": "经中继传输(网页链接)",
+ "featureAppCap": "经中继传输(应用之间)"
}
}
diff --git a/packages/locales/src/locales/zh-TW/settings.json b/packages/locales/src/locales/zh-TW/settings.json
index e4b3d31..2852408 100644
--- a/packages/locales/src/locales/zh-TW/settings.json
+++ b/packages/locales/src/locales/zh-TW/settings.json
@@ -108,5 +108,74 @@
"mediaToGalleryDescription": "關閉後,將儲存到下載資料夾。",
"destinationGallery": "照片和影片儲存到相簿",
"destinationDownloads": "照片和影片儲存到下載"
+ },
+ "account": {
+ "title": "我的訂閱",
+ "paywallLead": "更大的傳輸容量,中繼忙碌時優先。",
+ "columnFree": "免費",
+ "columnPro": "Pro",
+ "upgradeToPro": "升級到 Pro",
+ "haveCodeLink": "已有 Pro?輸入你的代碼",
+ "restore": "回復購買",
+ "nothingToRestore": "此帳號找不到任何購買紀錄。",
+ "restoreNotMoved": "無法將訂閱轉移到這台裝置,請改為輸入代碼。",
+ "enterCodeTitle": "輸入代碼",
+ "codePlaceholder": "0000 0000 0000 0000",
+ "activate": "啟用",
+ "back": "返回",
+ "unknownCode": "無法辨識這組代碼。",
+ "expiredCode": "此訂閱已到期。續訂後即可繼續使用 Pro。",
+ "failed": "發生問題,請稍後再試。",
+ "offline": "你似乎已離線。請檢查連線後再試。",
+ "serverError": "無法連線到我們的伺服器,請幾分鐘後再試。",
+ "timedOut": "尚未看到付款。如果你已完成結帳,請再次檢查。",
+ "checkAgain": "再次檢查",
+ "waitingTitle": "請在瀏覽器中完成購買",
+ "waitingBody": "付款完成後我們會自動辨識。",
+ "waitingTitleStore": "正在確認購買",
+ "waitingBodyStore": "只需片刻。",
+ "approvalTitle": "等待核准",
+ "approvalBody": "這筆購買需要核准才能完成。核准後 Pro 會立即開通,你可以關閉此畫面。",
+ "cancel": "取消",
+ "successTitle": "Pro 已啟用",
+ "yourCode": "你的代碼",
+ "saveWarning": "這是你唯一的購買憑證。我們不知道你是誰,因此無法為你找回。",
+ "codeReplaced": "這是一組新代碼,之前的代碼已失效。請在你的其他裝置上輸入這組代碼。",
+ "savedCodeTitle": "你儲存代碼了嗎?",
+ "savedCodeBody": "這是在其他裝置上恢復訂閱的唯一方式。我們無法為你找回。",
+ "savedCodeConfirm": "已儲存",
+ "done": "完成",
+ "copied": "已複製",
+ "copyFailed": "無法複製你的代碼,請在登出前手動複製。",
+ "saveCode": "將代碼儲存為檔案",
+ "codeFileTitle": "AlterSend Pro",
+ "codeFileCode": "帳號代碼",
+ "codeFileSaved": "已儲存",
+ "codeFileWarning": "這組代碼就是你的訂閱。在任何裝置的 AlterSend 中輸入即可回復 Pro。我們從未儲存,也無法為你找回。",
+ "planPro": "Pro",
+ "subscriptionRow": "訂閱",
+ "subscriptionValue": "{{plan}} · 至 {{date}}",
+ "logOut": "在這台裝置登出",
+ "logOutTitle": "請先儲存代碼",
+ "logOutBody": "登出會從這台裝置移除 {{code}}。這是回到 Pro 的唯一方式,我們無法找回。",
+ "copyAndLogOut": "複製代碼並登出",
+ "reveal": "顯示代碼",
+ "hide": "隱藏代碼",
+ "upgrade": "升級",
+ "paywallTitle": "解鎖 Pro。",
+ "planMonthly": "每月",
+ "planYearly": "每年",
+ "billedMonthly": "按月扣款",
+ "billedYearly": "按年扣款",
+ "pricePerMonth": "{{price}}/月",
+ "pricePerYear": "{{price}}/年",
+ "included": "包含內容",
+ "getPro": "取得 Pro",
+ "storeUnavailable": "此裝置不支援應用程式內購買。請在其他裝置上購買 AlterSend Pro,然後在此輸入代碼。",
+ "none": "–",
+ "featureDirect": "直接 P2P 傳輸",
+ "featurePriority": "中繼忙碌時優先",
+ "featureWebCap": "經中繼傳輸(網頁連結)",
+ "featureAppCap": "經中繼傳輸(App 之間)"
}
}
diff --git a/packages/locales/src/mobile-font-coverage.test.ts b/packages/locales/src/mobile-font-coverage.test.ts
index 6e8fbfc..e4387a1 100644
--- a/packages/locales/src/mobile-font-coverage.test.ts
+++ b/packages/locales/src/mobile-font-coverage.test.ts
@@ -6,8 +6,12 @@ const repoRoot = new URL('../../..', import.meta.url)
const mobileRoot = new URL('apps/mobile', repoRoot)
const allowedRawTextFiles = new Set(['src/components/ThemedText.tsx'])
+const skippedDirs = new Set(['node_modules', 'ios', 'android', '.expo'])
+
function walk(dir: string): string[] {
return readdirSync(dir).flatMap((entry) => {
+ if (skippedDirs.has(entry)) return []
+
const path = join(dir, entry)
const stat = statSync(path)
if (stat.isDirectory()) return walk(path)
diff --git a/packages/locales/src/resources.test.ts b/packages/locales/src/resources.test.ts
index 29c11e1..a9d6dec 100644
--- a/packages/locales/src/resources.test.ts
+++ b/packages/locales/src/resources.test.ts
@@ -30,12 +30,15 @@ function flattenStringEntries(value: unknown, prefix = ''): StringEntry[] {
function isPlaceholderOnly(value: string): boolean {
const withoutPlaceholders = value.replace(/\{\{[^}]+\}\}/g, '')
- const withoutPunctuation = withoutPlaceholders.replace(/[\s%.,:;!?()[\]{}'"“”‘’…·\-+/#|]+/g, '')
+ const withoutPunctuation = withoutPlaceholders.replace(/[\s%.,:;!?()[\]{}'"“”‘’…·\-–—+/#|]+/g, '')
return withoutPunctuation.length === 0
}
const identicalValueAllowList = new Set([
'AlterSend',
+ 'AlterSend Pro',
+ 'Pro',
+ 'Upgrade',
'Discord',
'Downloads',
'General',
@@ -50,6 +53,7 @@ const identicalValueAllowList = new Set([
const identicalKeyAllowList = new Set([
'common.files.count_one',
+ 'settings.account.codePlaceholder',
'common.files.text',
'common.files.items_one',
'common.labels.desktop',