From 2a750f620f79ffa95a7f2362333576d1c636b798 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 20:21:15 +0000 Subject: [PATCH 01/10] feat(console): a Mobile App page in the account app that shows the mobile connect QR code Claude-Session: https://claude.ai/code/session_01ADHkmRLqg1PuH8D83b32SV Co-authored-by: Claude --- .../platform-objects/src/apps/account.app.ts | 11 ++ .../src/apps/translations/ar.ts | 1 + .../src/apps/translations/de.ts | 1 + .../src/apps/translations/en.ts | 1 + .../src/apps/translations/es-ES.ts | 1 + .../src/apps/translations/fr.ts | 1 + .../src/apps/translations/ja-JP.ts | 1 + .../src/apps/translations/ko.ts | 1 + .../src/apps/translations/pt-BR.ts | 1 + .../src/apps/translations/ru.ts | 1 + .../src/apps/translations/zh-CN.ts | 1 + .../src/apps/translations/zh-Hant.ts | 1 + .../src/console/connect/deploymentReach.ts | 26 ++- .../console/mobile-app/MobileAppPage.test.tsx | 124 +++++++++++++ .../src/console/mobile-app/MobileAppPage.tsx | 171 ++++++++++++++++++ .../console/mobile-app/mobileConnect.test.ts | 71 ++++++++ .../src/console/mobile-app/mobileConnect.ts | 36 ++++ .../src/services/builtinComponents.tsx | 15 ++ ui/packages/auth/src/types.ts | 9 + ui/packages/i18n/src/locales/ar.ts | 17 ++ ui/packages/i18n/src/locales/de.ts | 17 ++ ui/packages/i18n/src/locales/en.ts | 17 ++ ui/packages/i18n/src/locales/es.ts | 17 ++ ui/packages/i18n/src/locales/fr.ts | 17 ++ ui/packages/i18n/src/locales/ja.ts | 17 ++ ui/packages/i18n/src/locales/ko.ts | 17 ++ ui/packages/i18n/src/locales/pt-BR.ts | 17 ++ ui/packages/i18n/src/locales/ru.ts | 17 ++ ui/packages/i18n/src/locales/zh-Hans.ts | 17 ++ ui/packages/i18n/src/locales/zh-Hant.ts | 17 ++ 30 files changed, 656 insertions(+), 5 deletions(-) create mode 100644 ui/packages/app-shell/src/console/mobile-app/MobileAppPage.test.tsx create mode 100644 ui/packages/app-shell/src/console/mobile-app/MobileAppPage.tsx create mode 100644 ui/packages/app-shell/src/console/mobile-app/mobileConnect.test.ts create mode 100644 ui/packages/app-shell/src/console/mobile-app/mobileConnect.ts diff --git a/packages/platform-objects/src/apps/account.app.ts b/packages/platform-objects/src/apps/account.app.ts index d5675ab082f..39d3765318c 100644 --- a/packages/platform-objects/src/apps/account.app.ts +++ b/packages/platform-objects/src/apps/account.app.ts @@ -73,6 +73,17 @@ export const ACCOUNT_APP: App = { componentRef: 'account:profile_card', icon: 'user-circle', }, + // The QR code and link that connect the ObjectOS mobile app to this + // server, registered by the Console as `account:mobile_app`. Built from + // the server's published public base URL; every signed-in user may + // connect their own phone, so the entry carries no gate. + { + id: 'nav_account_mobile_app', + type: 'component', + label: 'Mobile App', + componentRef: 'account:mobile_app', + icon: 'smartphone', + }, // --- Inbox & work assigned to me ----------------------------------- // Notifications, approvals waiting on me, and the orgs I belong to. diff --git a/packages/platform-objects/src/apps/translations/ar.ts b/packages/platform-objects/src/apps/translations/ar.ts index ceb04780e5a..afdf92accf8 100644 --- a/packages/platform-objects/src/apps/translations/ar.ts +++ b/packages/platform-objects/src/apps/translations/ar.ts @@ -18,6 +18,7 @@ export const ar: TranslationData = { grp_account_developer: { label: 'المطوّر' }, grp_account_ai_assistant: { label: 'مساعد الذكاء الاصطناعي' }, nav_account_profile: { label: 'الملف الشخصي' }, + nav_account_mobile_app: { label: 'تطبيق الجوال' }, nav_account_notifications: { label: 'الإشعارات' }, nav_account_approvals: { label: 'بانتظار موافقتي' }, nav_account_memberships: { label: 'مؤسساتي' }, diff --git a/packages/platform-objects/src/apps/translations/de.ts b/packages/platform-objects/src/apps/translations/de.ts index 26abfc0be14..29da9baf502 100644 --- a/packages/platform-objects/src/apps/translations/de.ts +++ b/packages/platform-objects/src/apps/translations/de.ts @@ -18,6 +18,7 @@ export const de: TranslationData = { grp_account_developer: { label: 'Entwickler' }, grp_account_ai_assistant: { label: 'KI-Assistent' }, nav_account_profile: { label: 'Profil' }, + nav_account_mobile_app: { label: 'Mobile-App' }, nav_account_notifications: { label: 'Benachrichtigungen' }, nav_account_approvals: { label: 'Meine ausstehenden Genehmigungen' }, nav_account_memberships: { label: 'Meine Organisationen' }, diff --git a/packages/platform-objects/src/apps/translations/en.ts b/packages/platform-objects/src/apps/translations/en.ts index 6d400636c17..d3840004000 100644 --- a/packages/platform-objects/src/apps/translations/en.ts +++ b/packages/platform-objects/src/apps/translations/en.ts @@ -33,6 +33,7 @@ export const en: TranslationData = { grp_account_developer: { label: 'Developer' }, grp_account_ai_assistant: { label: 'AI Assistant' }, nav_account_profile: { label: 'Profile' }, + nav_account_mobile_app: { label: 'Mobile App' }, nav_account_notifications: { label: 'Notifications' }, nav_account_approvals: { label: 'Approvals' }, nav_account_memberships: { label: 'My Organizations' }, diff --git a/packages/platform-objects/src/apps/translations/es-ES.ts b/packages/platform-objects/src/apps/translations/es-ES.ts index f403aa3db3f..341a49107d4 100644 --- a/packages/platform-objects/src/apps/translations/es-ES.ts +++ b/packages/platform-objects/src/apps/translations/es-ES.ts @@ -18,6 +18,7 @@ export const esES: TranslationData = { grp_account_developer: { label: 'Desarrollador' }, grp_account_ai_assistant: { label: 'Asistente de IA' }, nav_account_profile: { label: 'Perfil' }, + nav_account_mobile_app: { label: 'Aplicación móvil' }, nav_account_notifications: { label: 'Notificaciones' }, nav_account_approvals: { label: 'Aprobaciones pendientes' }, nav_account_memberships: { label: 'Mis organizaciones' }, diff --git a/packages/platform-objects/src/apps/translations/fr.ts b/packages/platform-objects/src/apps/translations/fr.ts index dda35ac0132..8281ac9297f 100644 --- a/packages/platform-objects/src/apps/translations/fr.ts +++ b/packages/platform-objects/src/apps/translations/fr.ts @@ -18,6 +18,7 @@ export const fr: TranslationData = { grp_account_developer: { label: 'Développeur' }, grp_account_ai_assistant: { label: 'Assistant IA' }, nav_account_profile: { label: 'Profil' }, + nav_account_mobile_app: { label: 'Application mobile' }, nav_account_notifications: { label: 'Notifications' }, nav_account_approvals: { label: 'Mes approbations en attente' }, nav_account_memberships: { label: 'Mes organisations' }, diff --git a/packages/platform-objects/src/apps/translations/ja-JP.ts b/packages/platform-objects/src/apps/translations/ja-JP.ts index 6a5dc62ab9a..4989859a123 100644 --- a/packages/platform-objects/src/apps/translations/ja-JP.ts +++ b/packages/platform-objects/src/apps/translations/ja-JP.ts @@ -18,6 +18,7 @@ export const jaJP: TranslationData = { grp_account_developer: { label: '開発者' }, grp_account_ai_assistant: { label: 'AI アシスタント' }, nav_account_profile: { label: 'プロフィール' }, + nav_account_mobile_app: { label: 'モバイルアプリ' }, nav_account_notifications: { label: '通知' }, nav_account_approvals: { label: '承認待ち' }, nav_account_memberships: { label: '所属組織' }, diff --git a/packages/platform-objects/src/apps/translations/ko.ts b/packages/platform-objects/src/apps/translations/ko.ts index 08c38094e3b..1c510c4db45 100644 --- a/packages/platform-objects/src/apps/translations/ko.ts +++ b/packages/platform-objects/src/apps/translations/ko.ts @@ -18,6 +18,7 @@ export const ko: TranslationData = { grp_account_developer: { label: '개발자' }, grp_account_ai_assistant: { label: 'AI 어시스턴트' }, nav_account_profile: { label: '프로필' }, + nav_account_mobile_app: { label: '모바일 앱' }, nav_account_notifications: { label: '알림' }, nav_account_approvals: { label: '내 승인 대기' }, nav_account_memberships: { label: '내 조직' }, diff --git a/packages/platform-objects/src/apps/translations/pt-BR.ts b/packages/platform-objects/src/apps/translations/pt-BR.ts index d35d29cca15..f59a880f56c 100644 --- a/packages/platform-objects/src/apps/translations/pt-BR.ts +++ b/packages/platform-objects/src/apps/translations/pt-BR.ts @@ -18,6 +18,7 @@ export const ptBR: TranslationData = { grp_account_developer: { label: 'Desenvolvedor' }, grp_account_ai_assistant: { label: 'Assistente de IA' }, nav_account_profile: { label: 'Perfil' }, + nav_account_mobile_app: { label: 'Aplicativo móvel' }, nav_account_notifications: { label: 'Notificações' }, nav_account_approvals: { label: 'Minhas aprovações pendentes' }, nav_account_memberships: { label: 'Minhas organizações' }, diff --git a/packages/platform-objects/src/apps/translations/ru.ts b/packages/platform-objects/src/apps/translations/ru.ts index 1d15139e8cb..b4f43977ada 100644 --- a/packages/platform-objects/src/apps/translations/ru.ts +++ b/packages/platform-objects/src/apps/translations/ru.ts @@ -18,6 +18,7 @@ export const ru: TranslationData = { grp_account_developer: { label: 'Разработчик' }, grp_account_ai_assistant: { label: 'ИИ-ассистент' }, nav_account_profile: { label: 'Профиль' }, + nav_account_mobile_app: { label: 'Мобильное приложение' }, nav_account_notifications: { label: 'Уведомления' }, nav_account_approvals: { label: 'Ждут моего решения' }, nav_account_memberships: { label: 'Мои организации' }, diff --git a/packages/platform-objects/src/apps/translations/zh-CN.ts b/packages/platform-objects/src/apps/translations/zh-CN.ts index c37b406e2ec..bd94da4faa9 100644 --- a/packages/platform-objects/src/apps/translations/zh-CN.ts +++ b/packages/platform-objects/src/apps/translations/zh-CN.ts @@ -18,6 +18,7 @@ export const zhCN: TranslationData = { grp_account_developer: { label: '开发者' }, grp_account_ai_assistant: { label: 'AI 助手' }, nav_account_profile: { label: '个人资料' }, + nav_account_mobile_app: { label: '移动应用' }, nav_account_notifications: { label: '通知' }, nav_account_approvals: { label: '待我审批' }, nav_account_memberships: { label: '我的组织' }, diff --git a/packages/platform-objects/src/apps/translations/zh-Hant.ts b/packages/platform-objects/src/apps/translations/zh-Hant.ts index 2f2d9dfdc7b..387e1ebc926 100644 --- a/packages/platform-objects/src/apps/translations/zh-Hant.ts +++ b/packages/platform-objects/src/apps/translations/zh-Hant.ts @@ -18,6 +18,7 @@ export const zhHant: TranslationData = { grp_account_developer: { label: '開發者' }, grp_account_ai_assistant: { label: 'AI 助理' }, nav_account_profile: { label: '個人資料' }, + nav_account_mobile_app: { label: '移動應用' }, nav_account_notifications: { label: '通知' }, nav_account_approvals: { label: '待我核准' }, nav_account_memberships: { label: '我的組織' }, diff --git a/ui/packages/app-shell/src/console/connect/deploymentReach.ts b/ui/packages/app-shell/src/console/connect/deploymentReach.ts index 19c33aceb13..3bcf03ec6ed 100644 --- a/ui/packages/app-shell/src/console/connect/deploymentReach.ts +++ b/ui/packages/app-shell/src/console/connect/deploymentReach.ts @@ -4,10 +4,8 @@ * Whether a client that connects from its vendor's cloud (claude.ai on the * web, Doubao Work's cloud tasks) can reach this deployment at the address * Connect an Agent shows. Only a public HTTPS address is reachable from - * there: an `http://` address, `localhost`, a single-label or `.local` host - * name, and a loopback, private, link-local or carrier-grade NAT IP literal - * are not. A host name with a dot is taken as public: the page cannot see - * how the reader's DNS resolves it. + * there: an `http://` address, and any address {@link isPublicHostAddress} + * refuses, are not. */ export function isPublicHttpsAddress(address: string): boolean { let url: URL; @@ -16,7 +14,25 @@ export function isPublicHttpsAddress(address: string): boolean { } catch { return false; } - if (url.protocol !== 'https:') return false; + return url.protocol === 'https:' && isPublicHostAddress(address); +} + +/** + * Whether an `http(s)` address names a host a device outside this network + * can open. `localhost`, a single-label or `.local` / `.internal` host name, + * and a loopback, private, link-local or carrier-grade NAT IP literal do + * not; neither does a value that is not an absolute `http(s)` URL. A host + * name with a dot is taken as public: the page cannot see how the reader's + * DNS resolves it. + */ +export function isPublicHostAddress(address: string): boolean { + let url: URL; + try { + url = new URL(address); + } catch { + return false; + } + if (url.protocol !== 'https:' && url.protocol !== 'http:') return false; const host = url.hostname.toLowerCase().replace(/^\[|\]$/g, '').replace(/\.$/, ''); if (!host) return false; if (host.includes(':')) return !isNonPublicIpv6(host); diff --git a/ui/packages/app-shell/src/console/mobile-app/MobileAppPage.test.tsx b/ui/packages/app-shell/src/console/mobile-app/MobileAppPage.test.tsx new file mode 100644 index 00000000000..c124b0a6556 --- /dev/null +++ b/ui/packages/app-shell/src/console/mobile-app/MobileAppPage.test.tsx @@ -0,0 +1,124 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The account app's Mobile App page (objectstack#29314): the QR code encodes + * `objectos://connect?server=` and the same + * link is on the page as copyable text; a loopback or private address, or no + * published address, shows the `OS_AUTH_URL` remedy and no code. + * + * `t` echoes the KEY with any `address` / `setting` option appended, so the + * assertions read which string the page asked for and with which value. The + * QR assertion compares the image against `qrcode`'s own SVG for the expected + * link, so it pins the payload that was actually encoded. + */ + +import '@testing-library/jest-dom/vitest'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'; +import { toString as renderQrSvg } from 'qrcode'; + +vi.mock('@object-ui/i18n', async (importOriginal) => ({ + ...(await importOriginal>()), + useObjectTranslation: () => ({ + t: (key: string, opts?: { address?: string; setting?: string }) => + `«${key}${opts?.address ? `|${opts.address}` : ''}${opts?.setting ? `|${opts.setting}` : ''}»`, + language: 'en', + }), +})); + +let getAuthConfig: ReturnType; +vi.mock('@object-ui/auth', async (importOriginal) => ({ + ...(await importOriginal>()), + useAuth: () => ({ getAuthConfig }), +})); + +import { MobileAppPage } from './MobileAppPage'; +import { builtInLocales } from '@object-ui/i18n/locales'; + +function serving(features: Record | undefined) { + getAuthConfig = vi.fn(async () => ({ features })); +} + +async function expectedQrSrc(link: string): Promise { + const svg = await renderQrSvg(link, { type: 'svg', margin: 1 }); + return `data:image/svg+xml;charset=utf-8,${encodeURIComponent(svg)}`; +} + +beforeEach(() => { + serving({}); +}); +afterEach(() => { + cleanup(); + vi.restoreAllMocks(); +}); + +describe('MobileAppPage: a public base URL renders the code and the copyable link', () => { + it('the QR code and the link carry the published URL, sub-path included', async () => { + serving({ publicBaseUrl: 'https://acme.example/os' }); + render(); + const link = 'objectos://connect?server=https%3A%2F%2Facme.example%2Fos'; + + expect(await screen.findByTestId('mobile-app-link')).toHaveTextContent(link); + const qr = await screen.findByTestId('mobile-app-qr'); + expect(qr).toHaveAttribute('src', await expectedQrSrc(link)); + expect(qr).toHaveAttribute('alt', '«mobileApp.qrAlt»'); + expect(screen.getByTestId('mobile-app-privacy')).toHaveTextContent('«mobileApp.privacy»'); + expect(screen.queryByTestId('mobile-app-refusal')).not.toBeInTheDocument(); + }); + + it('Copy link writes exactly the connect link to the clipboard', async () => { + serving({ publicBaseUrl: 'https://os.acme.example' }); + const writeText = vi.fn(async () => undefined); + Object.defineProperty(navigator, 'clipboard', { value: { writeText }, configurable: true }); + render(); + + fireEvent.click(await screen.findByRole('button', { name: /mobileApp\.copy/ })); + await waitFor(() => expect(writeText).toHaveBeenCalledWith('objectos://connect?server=https%3A%2F%2Fos.acme.example')); + expect(await screen.findByRole('status')).toHaveTextContent('«mobileApp.copied»'); + }); +}); + +describe('MobileAppPage: no code for an address a phone cannot reach', () => { + it.each(['http://localhost:3000', 'http://192.168.1.20'])('%s: the remedy names OS_AUTH_URL and no code renders', async (address) => { + serving({ publicBaseUrl: address }); + render(); + + const refusal = await screen.findByTestId('mobile-app-refusal'); + expect(refusal).toHaveTextContent('«mobileApp.unreachableTitle»'); + expect(refusal).toHaveTextContent(`«mobileApp.unreachableBody|${address}|OS_AUTH_URL»`); + expect(screen.queryByTestId('mobile-app-qr')).not.toBeInTheDocument(); + expect(screen.queryByTestId('mobile-app-link')).not.toBeInTheDocument(); + }); + + it('no published address: the unpublished remedy, and the browser address is never encoded', async () => { + serving({}); + render(); + + const refusal = await screen.findByTestId('mobile-app-refusal'); + expect(refusal).toHaveTextContent('«mobileApp.unpublishedTitle»'); + expect(refusal).toHaveTextContent('«mobileApp.unpublishedBody|OS_AUTH_URL»'); + expect(screen.queryByTestId('mobile-app-qr')).not.toBeInTheDocument(); + expect(document.body.textContent).not.toContain(window.location.host); + }); + + it('a config read that fails says so', async () => { + getAuthConfig = vi.fn(async () => { + throw new Error('offline'); + }); + render(); + expect(await screen.findByTestId('mobile-app-load-failed')).toHaveTextContent('«mobileApp.loadFailed»'); + }); +}); + +describe('the mobileApp pack keys', () => { + it('every built-in locale carries every key the English pack declares, placeholders kept', () => { + const en = (builtInLocales as Record }>).en.mobileApp!; + const placeholders = (s: string) => (s.match(/\{\{\w+\}\}/g) ?? []).sort(); + for (const [locale, pack] of Object.entries(builtInLocales as Record }>)) { + expect(Object.keys(pack.mobileApp ?? {}).sort(), locale).toEqual(Object.keys(en).sort()); + for (const key of Object.keys(en)) { + expect(placeholders(pack.mobileApp![key]), `${locale}.mobileApp.${key}`).toEqual(placeholders(en[key])); + } + } + }); +}); diff --git a/ui/packages/app-shell/src/console/mobile-app/MobileAppPage.tsx b/ui/packages/app-shell/src/console/mobile-app/MobileAppPage.tsx new file mode 100644 index 00000000000..15620c6a7cf --- /dev/null +++ b/ui/packages/app-shell/src/console/mobile-app/MobileAppPage.tsx @@ -0,0 +1,171 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The account app's Mobile App page (`account:mobile_app`): a QR code and a + * copyable link that connect the ObjectOS mobile app to this server. + * + * The server URL is the one the server publishes (`features.publicBaseUrl` on + * the public auth config), never `window.location`, which can be an internal + * or proxied host. A loopback or private address, or no published address, + * gets a refusal naming `OS_AUTH_URL` instead of a code a phone cannot use. + * The code carries the server's address only, never a credential. + */ + +import { useEffect, useState } from 'react'; +import { toString as renderQrSvg } from 'qrcode'; +import { Check, Copy, Smartphone } from 'lucide-react'; +import { useAuth } from '@object-ui/auth'; +import { + Alert, + AlertDescription, + AlertTitle, + Button, + Card, + CardContent, +} from '@object-ui/components'; +import { useObjectTranslation } from '@object-ui/i18n'; +import { PageHeader } from '../../layout/PageHeader.js'; +import { mobileConnectTarget, PUBLIC_ADDRESS_SETTING, type MobileConnectTarget } from './mobileConnect.js'; + +/** An address the remedy shows as the shape `OS_AUTH_URL` takes. */ +const PUBLIC_ADDRESS_EXAMPLE = 'https://os.example.com'; + +type Load = { readonly state: 'loading' } | { readonly state: 'failed' } | { readonly state: 'read'; readonly target: MobileConnectTarget }; + +export function MobileAppPage() { + const { t } = useObjectTranslation(); + const { getAuthConfig } = useAuth(); + const [load, setLoad] = useState({ state: 'loading' }); + + useEffect(() => { + let cancelled = false; + getAuthConfig() + .then((config) => { + if (!cancelled) setLoad({ state: 'read', target: mobileConnectTarget(config?.features?.publicBaseUrl) }); + }) + .catch(() => { + if (!cancelled) setLoad({ state: 'failed' }); + }); + return () => { + cancelled = true; + }; + }, [getAuthConfig]); + + return ( +
+
+ ); +} + +function ConnectCard({ connectLink }: { connectLink: string }) { + const { t } = useObjectTranslation(); + const [svg, setSvg] = useState(null); + const [copied, setCopied] = useState(false); + + // Rendered here, client side: the link never leaves the browser to draw it. + useEffect(() => { + let cancelled = false; + setSvg(null); + renderQrSvg(connectLink, { type: 'svg', margin: 1 }) + .then((markup) => { + if (!cancelled) setSvg(markup); + }) + .catch(() => { + if (!cancelled) setSvg(null); + }); + return () => { + cancelled = true; + }; + }, [connectLink]); + + useEffect(() => { + if (!copied) return; + const id = setTimeout(() => setCopied(false), 1500); + return () => clearTimeout(id); + }, [copied]); + + const copy = async () => { + try { + await navigator.clipboard.writeText(connectLink); + setCopied(true); + } catch { + // Clipboard permission denied: the link stays on screen to copy by hand. + } + }; + + return ( + + +

{t('mobileApp.scanHint')}

+ {/* A QR code needs a light field to scan, in either theme. */} +
+ {svg ? ( + {t('mobileApp.qrAlt')} + ) : ( + +
+ + {t('mobileApp.linkLabel')} + +
+ + {connectLink} + + + + {copied ? t('mobileApp.copied') : ''} + +
+
+

+ {t('mobileApp.privacy')} +

+ + + ); +} diff --git a/ui/packages/app-shell/src/console/mobile-app/mobileConnect.test.ts b/ui/packages/app-shell/src/console/mobile-app/mobileConnect.test.ts new file mode 100644 index 00000000000..b4728180ce0 --- /dev/null +++ b/ui/packages/app-shell/src/console/mobile-app/mobileConnect.test.ts @@ -0,0 +1,71 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The Mobile App page's connect payload is built from the server's published + * public base URL, sub-path mount included, and a loopback or private address + * is refused instead of encoded (objectstack#29314). + */ + +import { describe, expect, it } from 'vitest'; +import { mobileConnectLink, mobileConnectTarget } from './mobileConnect'; + +describe('mobileConnectTarget: the payload is the configured public URL', () => { + it('a public origin becomes objectos://connect?server=', () => { + expect(mobileConnectTarget('https://os.acme.example')).toEqual({ + kind: 'ready', + serverUrl: 'https://os.acme.example', + connectLink: 'objectos://connect?server=https%3A%2F%2Fos.acme.example', + }); + }); + + it('a sub-path mount stays in the encoded server URL', () => { + expect(mobileConnectTarget('https://acme.example/platform/os')).toEqual({ + kind: 'ready', + serverUrl: 'https://acme.example/platform/os', + connectLink: 'objectos://connect?server=https%3A%2F%2Facme.example%2Fplatform%2Fos', + }); + }); + + it('a port is kept, and the encoded URL decodes back to the configured one', () => { + const target = mobileConnectTarget('https://os.acme.example:8443/os'); + expect(target.kind).toBe('ready'); + const link = (target as { connectLink: string }).connectLink; + expect(new URL(link).searchParams.get('server')).toBe('https://os.acme.example:8443/os'); + expect(link).toBe(mobileConnectLink('https://os.acme.example:8443/os')); + }); +}); + +describe('mobileConnectTarget: localhost and private addresses are refused, never encoded', () => { + it.each([ + 'http://localhost:3000', + 'http://app.localhost:3000', + 'http://127.0.0.1:3000', + 'http://10.0.0.5', + 'http://172.16.4.2:8080', + 'http://192.168.1.20/os', + 'http://169.254.10.1', + 'http://100.64.0.1', + 'http://[::1]:3000', + 'http://[fd12::1]', + 'http://intranet', + 'http://os.local', + 'http://os.corp.internal', + ])('%s', (address) => { + expect(mobileConnectTarget(address)).toEqual({ kind: 'unreachable', serverUrl: address }); + }); + + it('a value that is not an absolute http(s) URL is refused too', () => { + expect(mobileConnectTarget('os.acme.example').kind).toBe('unreachable'); + expect(mobileConnectTarget('ftp://os.acme.example').kind).toBe('unreachable'); + }); + + it('CONTROL: a public host on plain http is not a private address, so it is encoded', () => { + expect(mobileConnectTarget('http://os.acme.example').kind).toBe('ready'); + }); +}); + +describe('mobileConnectTarget: no published URL', () => { + it.each([undefined, null, '', ' ', 42])('%s reads as unpublished, never as the browser address', (value) => { + expect(mobileConnectTarget(value)).toEqual({ kind: 'unpublished' }); + }); +}); diff --git a/ui/packages/app-shell/src/console/mobile-app/mobileConnect.ts b/ui/packages/app-shell/src/console/mobile-app/mobileConnect.ts new file mode 100644 index 00000000000..2c9eccbd6e0 --- /dev/null +++ b/ui/packages/app-shell/src/console/mobile-app/mobileConnect.ts @@ -0,0 +1,36 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import { isPublicHostAddress } from '../connect/deploymentReach.js'; + +/** The link the ObjectOS mobile app opens to connect to a server. */ +export const MOBILE_CONNECT_LINK_BASE = 'objectos://connect'; + +/** The server setting that names this deployment's public address. */ +export const PUBLIC_ADDRESS_SETTING = 'OS_AUTH_URL'; + +/** + * What the Mobile App page shows, judged from the server's published public + * base URL (`features.publicBaseUrl` on the public auth config). + * + * - `ready`: a QR code and a copyable link carrying that URL. + * - `unreachable`: the URL names a loopback or private address a phone + * cannot open, so the page refuses with the `OS_AUTH_URL` remedy. + * - `unpublished`: the server published no public URL; the browser's own + * address is never used in its place, because it can be an internal or + * proxied host. + */ +export type MobileConnectTarget = + | { readonly kind: 'ready'; readonly serverUrl: string; readonly connectLink: string } + | { readonly kind: 'unreachable'; readonly serverUrl: string } + | { readonly kind: 'unpublished' }; + +/** The connect link for a server URL: `objectos://connect?server=`. */ +export function mobileConnectLink(serverUrl: string): string { + return `${MOBILE_CONNECT_LINK_BASE}?server=${encodeURIComponent(serverUrl)}`; +} + +export function mobileConnectTarget(publicBaseUrl: unknown): MobileConnectTarget { + if (typeof publicBaseUrl !== 'string' || publicBaseUrl.trim() === '') return { kind: 'unpublished' }; + if (!isPublicHostAddress(publicBaseUrl)) return { kind: 'unreachable', serverUrl: publicBaseUrl }; + return { kind: 'ready', serverUrl: publicBaseUrl, connectLink: mobileConnectLink(publicBaseUrl) }; +} diff --git a/ui/packages/app-shell/src/services/builtinComponents.tsx b/ui/packages/app-shell/src/services/builtinComponents.tsx index 6a6fe76075e..604676ab9ba 100644 --- a/ui/packages/app-shell/src/services/builtinComponents.tsx +++ b/ui/packages/app-shell/src/services/builtinComponents.tsx @@ -116,6 +116,9 @@ const PackagesPage = lazyPage('packages', () => const PermissionMatrixEditPage = lazyPage('permission set', () => import('../views/metadata-admin/PermissionMatrixEditor.js').then((m) => m.PermissionMatrixEditPage), ); +const MobileAppPage = lazyPage('mobile app', () => + import('../console/mobile-app/MobileAppPage.js').then((m) => m.MobileAppPage), +); const PackagedActionsPage = lazyPage('packaged actions', () => import('../views/setup/PackagedActionsPage.js').then((m) => m.PackagedActionsPage), ); @@ -186,6 +189,18 @@ registerAppComponent({ component: PackagesPage, }); +/** + * The account app's Mobile App page: the QR code and link that connect the + * ObjectOS mobile app to this server. The account app's navigation names + * `account:mobile_app`, and `ComponentNavView` resolves it. + */ +registerAppComponent({ + ref: 'account:mobile_app', + label: 'Mobile App', + source: '@object-ui/app-shell', + component: MobileAppPage, +}); + /** * ADR-0126 §7.4 — the Setup page for the actions installed packages ship: * on/off for this deployment. Contributed the way every other framework-owned diff --git a/ui/packages/auth/src/types.ts b/ui/packages/auth/src/types.ts index 578e81370a9..51b61f0d301 100644 --- a/ui/packages/auth/src/types.ts +++ b/ui/packages/auth/src/types.ts @@ -445,6 +445,15 @@ export interface AuthPublicConfig { * form is what it was before the key existed. */ turnstileSiteKey?: string; + /** + * This deployment's public base URL, as the auth layer composes every link + * it hands out: the configured base URL (`OS_AUTH_URL`, then + * `BETTER_AUTH_URL`, then `OS_BASE_URL`) with any sub-path it carries, or + * the loopback fallback when none is set. The account app's Mobile App + * page encodes it in the connect code, never the browser's own address. + * Absent from a server that does not publish it. + */ + publicBaseUrl?: string; }; } diff --git a/ui/packages/i18n/src/locales/ar.ts b/ui/packages/i18n/src/locales/ar.ts index 1a1edcdecdd..41d828a2c40 100644 --- a/ui/packages/i18n/src/locales/ar.ts +++ b/ui/packages/i18n/src/locales/ar.ts @@ -5658,6 +5658,23 @@ const ar = { loading: "جارٍ تحميل بيئة تشغيل React…", error: "خطأ في صفحة React", }, + // The account app's Mobile App page (app-shell `MobileAppPage`): the QR code + // and link that connect the ObjectOS mobile app to this server. + mobileApp: { + title: "تطبيق الجوال", + subtitle: "اربط تطبيق ObjectOS للجوال بهذا الخادم", + scanHint: "افتح تطبيق ObjectOS للجوال وامسح هذا الرمز لربطه بهذا الخادم.", + qrAlt: "رمز QR يربط تطبيق ObjectOS للجوال بهذا الخادم", + linkLabel: "رابط الاتصال", + copy: "نسخ الرابط", + copied: "تم نسخ الرابط", + privacy: "لا يحمل الرمز سوى عنوان هذا الخادم، ولا يحمل حسابك أبدًا.", + loadFailed: "تعذّرت قراءة العنوان العام لهذا الخادم. أعد تحميل الصفحة للمحاولة مرة أخرى.", + unreachableTitle: "لا يستطيع الهاتف الوصول إلى عنوان هذا الخادم", + unreachableBody: "عنوان هذا الخادم هو {{address}}، وهو عنوان محلي أو خاص لا يستطيع الهاتف فتحه، لذلك لا يُعرض أي رمز. اضبط {{setting}} على الخادم على عنوانه العام، مثل {{example}}، ثم أعد تشغيله.", + unpublishedTitle: "لا ينشر هذا الخادم عنوانه العام", + unpublishedBody: "لا يُعرض أي رمز: قد يكون العنوان في متصفحك مضيفًا داخليًا لا يستطيع الهاتف الوصول إليه. اضبط {{setting}} على الخادم على عنوانه العام، مثل {{example}}، ثم أعد تشغيله.", + }, }; export default ar; diff --git a/ui/packages/i18n/src/locales/de.ts b/ui/packages/i18n/src/locales/de.ts index fb5d0156b7f..aef130b2b9c 100644 --- a/ui/packages/i18n/src/locales/de.ts +++ b/ui/packages/i18n/src/locales/de.ts @@ -5088,6 +5088,23 @@ const de = { loading: "React-Laufzeit wird geladen…", error: "Fehler auf der React-Seite", }, + // The account app's Mobile App page (app-shell `MobileAppPage`): the QR code + // and link that connect the ObjectOS mobile app to this server. + mobileApp: { + title: "Mobile-App", + subtitle: "Die ObjectOS-Mobile-App mit diesem Server verbinden", + scanHint: "Öffnen Sie die ObjectOS-Mobile-App und scannen Sie diesen Code, um sie mit diesem Server zu verbinden.", + qrAlt: "QR-Code, der die ObjectOS-Mobile-App mit diesem Server verbindet", + linkLabel: "Verbindungslink", + copy: "Link kopieren", + copied: "Link kopiert", + privacy: "Der Code enthält nur die Adresse dieses Servers, niemals Ihr Konto.", + loadFailed: "Die öffentliche Adresse dieses Servers konnte nicht gelesen werden. Laden Sie die Seite neu, um es erneut zu versuchen.", + unreachableTitle: "Ein Telefon kann die Adresse dieses Servers nicht erreichen", + unreachableBody: "Die Adresse dieses Servers ist {{address}}, eine lokale oder private Adresse, die ein Telefon nicht öffnen kann, daher wird kein Code angezeigt. Setzen Sie {{setting}} auf dem Server auf seine öffentliche Adresse, zum Beispiel {{example}}, und starten Sie ihn neu.", + unpublishedTitle: "Dieser Server veröffentlicht keine öffentliche Adresse", + unpublishedBody: "Es wird kein Code angezeigt: Die Adresse in Ihrem Browser kann ein interner Host sein, den ein Telefon nicht erreicht. Setzen Sie {{setting}} auf dem Server auf seine öffentliche Adresse, zum Beispiel {{example}}, und starten Sie ihn neu.", + }, }; export default de; diff --git a/ui/packages/i18n/src/locales/en.ts b/ui/packages/i18n/src/locales/en.ts index 5af7c5ae8ef..cc6e7b98c45 100644 --- a/ui/packages/i18n/src/locales/en.ts +++ b/ui/packages/i18n/src/locales/en.ts @@ -5992,6 +5992,23 @@ const en = { loading: 'Loading react runtime…', error: 'React page error', }, + // The account app's Mobile App page (app-shell `MobileAppPage`): the QR code + // and link that connect the ObjectOS mobile app to this server. + mobileApp: { + title: "Mobile App", + subtitle: "Connect the ObjectOS mobile app to this server", + scanHint: "Open the ObjectOS mobile app and scan this code to connect it to this server.", + qrAlt: "QR code that connects the ObjectOS mobile app to this server", + linkLabel: "Connection link", + copy: "Copy link", + copied: "Link copied", + privacy: "The code holds only this server's address, never your account.", + loadFailed: "Could not read this server's public address. Reload the page to try again.", + unreachableTitle: "A phone cannot reach this server's address", + unreachableBody: "This server's address is {{address}}, a local or private address a phone cannot open, so no code is shown. Set {{setting}} on the server to its public address, for example {{example}}, and restart it.", + unpublishedTitle: "This server does not publish its public address", + unpublishedBody: "No code is shown: the address in your browser can be an internal host a phone cannot reach. Set {{setting}} on the server to its public address, for example {{example}}, and restart it.", + }, } as const; export default en; diff --git a/ui/packages/i18n/src/locales/es.ts b/ui/packages/i18n/src/locales/es.ts index c687727dbce..469287910d7 100644 --- a/ui/packages/i18n/src/locales/es.ts +++ b/ui/packages/i18n/src/locales/es.ts @@ -5230,6 +5230,23 @@ const es = { loading: "Cargando el entorno de ejecución de React…", error: "Error en la página React", }, + // The account app's Mobile App page (app-shell `MobileAppPage`): the QR code + // and link that connect the ObjectOS mobile app to this server. + mobileApp: { + title: "Aplicación móvil", + subtitle: "Conecta la aplicación móvil de ObjectOS a este servidor", + scanHint: "Abre la aplicación móvil de ObjectOS y escanea este código para conectarla a este servidor.", + qrAlt: "Código QR que conecta la aplicación móvil de ObjectOS a este servidor", + linkLabel: "Enlace de conexión", + copy: "Copiar enlace", + copied: "Enlace copiado", + privacy: "El código solo contiene la dirección de este servidor, nunca tu cuenta.", + loadFailed: "No se pudo leer la dirección pública de este servidor. Recarga la página para volver a intentarlo.", + unreachableTitle: "Un teléfono no puede acceder a la dirección de este servidor", + unreachableBody: "La dirección de este servidor es {{address}}, una dirección local o privada que un teléfono no puede abrir, así que no se muestra ningún código. Establece {{setting}} en el servidor con su dirección pública, por ejemplo {{example}}, y reinícialo.", + unpublishedTitle: "Este servidor no publica su dirección pública", + unpublishedBody: "No se muestra ningún código: la dirección de tu navegador puede ser un host interno al que un teléfono no puede acceder. Establece {{setting}} en el servidor con su dirección pública, por ejemplo {{example}}, y reinícialo.", + }, }; export default es; diff --git a/ui/packages/i18n/src/locales/fr.ts b/ui/packages/i18n/src/locales/fr.ts index 7ae83c77f77..5eaeb11a79c 100644 --- a/ui/packages/i18n/src/locales/fr.ts +++ b/ui/packages/i18n/src/locales/fr.ts @@ -5226,6 +5226,23 @@ const fr = { loading: "Chargement de l'environnement d'exécution React…", error: "Erreur de la page React", }, + // The account app's Mobile App page (app-shell `MobileAppPage`): the QR code + // and link that connect the ObjectOS mobile app to this server. + mobileApp: { + title: "Application mobile", + subtitle: "Connecter l'application mobile ObjectOS à ce serveur", + scanHint: "Ouvrez l'application mobile ObjectOS et scannez ce code pour la connecter à ce serveur.", + qrAlt: "Code QR qui connecte l'application mobile ObjectOS à ce serveur", + linkLabel: "Lien de connexion", + copy: "Copier le lien", + copied: "Lien copié", + privacy: "Le code ne contient que l'adresse de ce serveur, jamais votre compte.", + loadFailed: "Impossible de lire l'adresse publique de ce serveur. Rechargez la page pour réessayer.", + unreachableTitle: "Un téléphone ne peut pas joindre l'adresse de ce serveur", + unreachableBody: "L'adresse de ce serveur est {{address}}, une adresse locale ou privée qu'un téléphone ne peut pas ouvrir : aucun code n'est donc affiché. Définissez {{setting}} sur le serveur avec son adresse publique, par exemple {{example}}, puis redémarrez-le.", + unpublishedTitle: "Ce serveur ne publie pas son adresse publique", + unpublishedBody: "Aucun code n'est affiché : l'adresse de votre navigateur peut être un hôte interne qu'un téléphone ne peut pas joindre. Définissez {{setting}} sur le serveur avec son adresse publique, par exemple {{example}}, puis redémarrez-le.", + }, }; export default fr; diff --git a/ui/packages/i18n/src/locales/ja.ts b/ui/packages/i18n/src/locales/ja.ts index ce4b83d19a1..87db8ee99af 100644 --- a/ui/packages/i18n/src/locales/ja.ts +++ b/ui/packages/i18n/src/locales/ja.ts @@ -5089,6 +5089,23 @@ const ja = { loading: "React ランタイムを読み込んでいます…", error: "React ページのエラー", }, + // The account app's Mobile App page (app-shell `MobileAppPage`): the QR code + // and link that connect the ObjectOS mobile app to this server. + mobileApp: { + title: "モバイルアプリ", + subtitle: "ObjectOS モバイルアプリをこのサーバーに接続します", + scanHint: "ObjectOS モバイルアプリを開き、このコードをスキャンしてこのサーバーに接続します。", + qrAlt: "ObjectOS モバイルアプリをこのサーバーに接続する QR コード", + linkLabel: "接続リンク", + copy: "リンクをコピー", + copied: "リンクをコピーしました", + privacy: "このコードに含まれるのはこのサーバーのアドレスだけで、アカウント情報は含まれません。", + loadFailed: "このサーバーの公開アドレスを読み取れませんでした。ページを再読み込みしてもう一度お試しください。", + unreachableTitle: "スマートフォンからこのサーバーのアドレスに接続できません", + unreachableBody: "このサーバーのアドレスは {{address}} で、スマートフォンから開けないローカルまたはプライベートアドレスのため、コードは表示されません。サーバーの {{setting}} を公開アドレス(例: {{example}})に設定し、サーバーを再起動してください。", + unpublishedTitle: "このサーバーは公開アドレスを公開していません", + unpublishedBody: "コードは表示されません。ブラウザーのアドレスは、スマートフォンから接続できない内部ホストの可能性があります。サーバーの {{setting}} を公開アドレス(例: {{example}})に設定し、サーバーを再起動してください。", + }, }; export default ja; diff --git a/ui/packages/i18n/src/locales/ko.ts b/ui/packages/i18n/src/locales/ko.ts index 03b807cc385..294a75a12d9 100644 --- a/ui/packages/i18n/src/locales/ko.ts +++ b/ui/packages/i18n/src/locales/ko.ts @@ -5086,6 +5086,23 @@ const ko = { loading: "React 런타임을 불러오는 중…", error: "React 페이지 오류", }, + // The account app's Mobile App page (app-shell `MobileAppPage`): the QR code + // and link that connect the ObjectOS mobile app to this server. + mobileApp: { + title: "모바일 앱", + subtitle: "ObjectOS 모바일 앱을 이 서버에 연결합니다", + scanHint: "ObjectOS 모바일 앱을 열고 이 코드를 스캔하면 이 서버에 연결됩니다.", + qrAlt: "ObjectOS 모바일 앱을 이 서버에 연결하는 QR 코드", + linkLabel: "연결 링크", + copy: "링크 복사", + copied: "링크를 복사했습니다", + privacy: "이 코드에는 이 서버의 주소만 들어 있으며 계정 정보는 들어 있지 않습니다.", + loadFailed: "이 서버의 공개 주소를 읽지 못했습니다. 페이지를 새로 고친 후 다시 시도하세요.", + unreachableTitle: "휴대폰에서 이 서버의 주소에 접속할 수 없습니다", + unreachableBody: "이 서버의 주소는 {{address}}이며, 휴대폰에서 열 수 없는 로컬 또는 사설 주소이므로 코드를 표시하지 않습니다. 서버의 {{setting}}을(를) 공개 주소(예: {{example}})로 설정하고 서버를 다시 시작하세요.", + unpublishedTitle: "이 서버는 공개 주소를 게시하지 않습니다", + unpublishedBody: "코드를 표시하지 않습니다. 브라우저의 주소는 휴대폰에서 접속할 수 없는 내부 호스트일 수 있습니다. 서버의 {{setting}}을(를) 공개 주소(예: {{example}})로 설정하고 서버를 다시 시작하세요.", + }, }; export default ko; diff --git a/ui/packages/i18n/src/locales/pt-BR.ts b/ui/packages/i18n/src/locales/pt-BR.ts index 33eaece28e0..0e2678f0d77 100644 --- a/ui/packages/i18n/src/locales/pt-BR.ts +++ b/ui/packages/i18n/src/locales/pt-BR.ts @@ -5225,6 +5225,23 @@ const pt = { loading: "Carregando o runtime do React…", error: "Erro na página React", }, + // The account app's Mobile App page (app-shell `MobileAppPage`): the QR code + // and link that connect the ObjectOS mobile app to this server. + mobileApp: { + title: "Aplicativo móvel", + subtitle: "Conecte o aplicativo móvel ObjectOS a este servidor", + scanHint: "Abra o aplicativo móvel ObjectOS e escaneie este código para conectá-lo a este servidor.", + qrAlt: "Código QR que conecta o aplicativo móvel ObjectOS a este servidor", + linkLabel: "Link de conexão", + copy: "Copiar link", + copied: "Link copiado", + privacy: "O código contém apenas o endereço deste servidor, nunca a sua conta.", + loadFailed: "Não foi possível ler o endereço público deste servidor. Recarregue a página para tentar novamente.", + unreachableTitle: "Um celular não consegue acessar o endereço deste servidor", + unreachableBody: "O endereço deste servidor é {{address}}, um endereço local ou privado que um celular não consegue abrir, então nenhum código é exibido. Defina {{setting}} no servidor com o endereço público dele, por exemplo {{example}}, e reinicie-o.", + unpublishedTitle: "Este servidor não publica seu endereço público", + unpublishedBody: "Nenhum código é exibido: o endereço no seu navegador pode ser um host interno que um celular não consegue acessar. Defina {{setting}} no servidor com o endereço público dele, por exemplo {{example}}, e reinicie-o.", + }, }; export default pt; diff --git a/ui/packages/i18n/src/locales/ru.ts b/ui/packages/i18n/src/locales/ru.ts index 65b946360b6..53db0825744 100644 --- a/ui/packages/i18n/src/locales/ru.ts +++ b/ui/packages/i18n/src/locales/ru.ts @@ -5381,6 +5381,23 @@ const ru = { loading: "Загрузка среды выполнения React…", error: "Ошибка страницы React", }, + // The account app's Mobile App page (app-shell `MobileAppPage`): the QR code + // and link that connect the ObjectOS mobile app to this server. + mobileApp: { + title: "Мобильное приложение", + subtitle: "Подключите мобильное приложение ObjectOS к этому серверу", + scanHint: "Откройте мобильное приложение ObjectOS и отсканируйте этот код, чтобы подключить его к этому серверу.", + qrAlt: "QR-код для подключения мобильного приложения ObjectOS к этому серверу", + linkLabel: "Ссылка для подключения", + copy: "Копировать ссылку", + copied: "Ссылка скопирована", + privacy: "Код содержит только адрес этого сервера и никогда — вашу учётную запись.", + loadFailed: "Не удалось прочитать публичный адрес этого сервера. Перезагрузите страницу, чтобы повторить попытку.", + unreachableTitle: "Телефон не может открыть адрес этого сервера", + unreachableBody: "Адрес этого сервера — {{address}}: это локальный или частный адрес, который телефон не может открыть, поэтому код не показан. Укажите на сервере в {{setting}} его публичный адрес, например {{example}}, и перезапустите сервер.", + unpublishedTitle: "Этот сервер не публикует свой публичный адрес", + unpublishedBody: "Код не показан: адрес в вашем браузере может быть внутренним хостом, недоступным для телефона. Укажите на сервере в {{setting}} его публичный адрес, например {{example}}, и перезапустите сервер.", + }, }; export default ru; diff --git a/ui/packages/i18n/src/locales/zh-Hans.ts b/ui/packages/i18n/src/locales/zh-Hans.ts index ac7bfe94693..7c5ba4055f3 100644 --- a/ui/packages/i18n/src/locales/zh-Hans.ts +++ b/ui/packages/i18n/src/locales/zh-Hans.ts @@ -5147,6 +5147,23 @@ const zh = { loading: '正在加载 React 运行时…', error: 'React 页面错误', }, + // The account app's Mobile App page (app-shell `MobileAppPage`): the QR code + // and link that connect the ObjectOS mobile app to this server. + mobileApp: { + title: "移动应用", + subtitle: "将 ObjectOS 移动应用连接到此服务器", + scanHint: "打开 ObjectOS 移动应用,扫描此二维码即可连接到此服务器。", + qrAlt: "用于将 ObjectOS 移动应用连接到此服务器的二维码", + linkLabel: "连接链接", + copy: "复制链接", + copied: "链接已复制", + privacy: "二维码只包含此服务器的地址,不包含你的账号。", + loadFailed: "无法读取此服务器的公开地址。请刷新页面重试。", + unreachableTitle: "手机无法访问此服务器的地址", + unreachableBody: "此服务器的地址是 {{address}},这是手机无法打开的本机或内网地址,因此不显示二维码。请在服务器上将 {{setting}} 设为它的公开地址(例如 {{example}}),然后重启服务器。", + unpublishedTitle: "此服务器未公布其公开地址", + unpublishedBody: "不显示二维码:浏览器中的地址可能是手机无法访问的内部主机。请在服务器上将 {{setting}} 设为它的公开地址(例如 {{example}}),然后重启服务器。", + }, } as const; export default zh; diff --git a/ui/packages/i18n/src/locales/zh-Hant.ts b/ui/packages/i18n/src/locales/zh-Hant.ts index bf31c0bb579..8f38b2a9b27 100644 --- a/ui/packages/i18n/src/locales/zh-Hant.ts +++ b/ui/packages/i18n/src/locales/zh-Hant.ts @@ -5147,6 +5147,23 @@ const zhHant = { loading: '正在載入 React 執行環境…', error: 'React 頁面錯誤', }, + // The account app's Mobile App page (app-shell `MobileAppPage`): the QR code + // and link that connect the ObjectOS mobile app to this server. + mobileApp: { + title: "移動應用", + subtitle: "將 ObjectOS 移動應用連線到此伺服器", + scanHint: "開啟 ObjectOS 移動應用,掃描此二維碼即可連線到此伺服器。", + qrAlt: "用於將 ObjectOS 移動應用連線到此伺服器的二維碼", + linkLabel: "連線連結", + copy: "複製連結", + copied: "連結已複製", + privacy: "二維碼只包含此伺服器的地址,不包含你的賬號。", + loadFailed: "無法讀取此伺服器的公開地址。請重新整理頁面重試。", + unreachableTitle: "手機無法訪問此伺服器的地址", + unreachableBody: "此伺服器的地址是 {{address}},這是手機無法開啟的本機或內網地址,因此不顯示二維碼。請在伺服器上將 {{setting}} 設為它的公開地址(例如 {{example}}),然後重啟伺服器。", + unpublishedTitle: "此伺服器未公佈其公開地址", + unpublishedBody: "不顯示二維碼:瀏覽器中的地址可能是手機無法訪問的內部主機。請在伺服器上將 {{setting}} 設為它的公開地址(例如 {{example}}),然後重啟伺服器。", + }, } as const; export default zhHant; From 075306ca2f61b121d77512fc2a29e883465e901b Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 20:29:42 +0000 Subject: [PATCH 02/10] test(console): unit pins and a Playwright check for the Mobile App connect code Claude-Session: https://claude.ai/code/session_01ADHkmRLqg1PuH8D83b32SV Co-authored-by: Claude --- ui/e2e/mobile-app-connect-qr.spec.ts | 240 +++++++++++++++++++++++++++ 1 file changed, 240 insertions(+) create mode 100644 ui/e2e/mobile-app-connect-qr.spec.ts diff --git a/ui/e2e/mobile-app-connect-qr.spec.ts b/ui/e2e/mobile-app-connect-qr.spec.ts new file mode 100644 index 00000000000..6040491e652 --- /dev/null +++ b/ui/e2e/mobile-app-connect-qr.spec.ts @@ -0,0 +1,240 @@ +import { test, expect, type Page } from '@playwright/test'; +import { compile } from 'tailwindcss'; +import { build, type Plugin, type Rollup } from 'vite'; +import { readFileSync } from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { uiRoot } from '../scripts/ui-root.mjs'; + +/** + * The account app's Mobile App page (objectstack#29314) in a real browser: the + * QR code renders as an image the browser decodes, beside the copyable + * `objectos://connect?server=…` link built from the server's published public + * base URL; a loopback address gets the `OS_AUTH_URL` remedy and no code. + * + * ## Why a Playwright spec beside the vitest pins + * + * `MobileAppPage.test.tsx` pins the payload: the image's `src` equals + * `qrcode`'s own SVG for the expected link. jsdom decodes no image, so whether + * that `data:` SVG actually renders as a picture with a size, and the link + * stays on screen beside it, is a question only a browser answers. + * + * ## What is real here and what is a fixture + * + * REAL, built from source at run time and running in the page: `MobileAppPage` + * and its `mobileConnect` / `deploymentReach` helpers, `PageHeader`, the Shadcn + * `Alert`, `Button` and `Card` primitives, `qrcode`, `lucide-react`, + * `react-router-dom` (a `MemoryRouter`, for `PageHeader`'s Setup check) and + * React. The copy is the real English pack (`packages/i18n/src/locales/en.ts`), + * interpolated the way i18next does. The stylesheet is real Tailwind, compiled + * from the installed `tailwindcss` for the class strings in those sources. + * + * FIXTURES, declared so nobody reads more into a green run than it says: + * + * - `@object-ui/auth` is a stub whose `getAuthConfig()` answers the + * `features` object each test sets: the public auth config the server + * serves, reduced to the one key this page reads. + * - `@object-ui/i18n` is a stub that looks each key up in the English pack. + * - `@object-ui/components` is a stub re-exporting the four primitives the + * page and its header draw, from their source files. + * - `@object-ui/react` is a stub exporting a `SchemaRenderer` that renders + * nothing; the components' `lib/utils` imports it for helpers this page + * does not call. + * - Theme colour tokens are not compiled, so surfaces are unpainted. + * + * Workspace packages are not imported by name: this lane builds no workspace + * `dist/`, and `scripts/__tests__/e2e-type-check.test.ts` pins that no spec + * under `e2e/` imports one. + */ + +const REPO_ROOT = uiRoot(); +const source = (rel: string) => path.join(REPO_ROOT, rel); + +const PAGE = source('packages/app-shell/src/console/mobile-app/MobileAppPage.tsx'); +const PAGE_HEADER = source('packages/app-shell/src/layout/PageHeader.tsx'); +const EN_PACK = source('packages/i18n/src/locales/en.ts'); +const UI = (name: string) => source(`packages/components/src/ui/${name}.tsx`); +const UTILS = source('packages/components/src/lib/utils.tsx'); + +/** The source files whose class strings the page draws with. */ +const STYLED_SOURCES = [PAGE, PAGE_HEADER, UI('alert'), UI('button'), UI('card')]; + +const STUB_AUTH = '\0mobile-app-qr:auth'; +const STUB_I18N = '\0mobile-app-qr:i18n'; +const STUB_COMPONENTS = '\0mobile-app-qr:components'; +const STUB_REACT = '\0mobile-app-qr:react'; +const ENTRY = '\0mobile-app-qr:entry'; + +function fixtures(): Plugin { + const at = (file: string) => JSON.stringify(file); + const modules: Record = { + [STUB_AUTH]: ` +const getAuthConfig = () => Promise.resolve({ features: window.__features }); +export const useAuth = () => ({ getAuthConfig }); +`, + [STUB_I18N]: ` +import en from ${at(EN_PACK)}; +const t = (key, options) => { + let text = key.split('.').reduce((node, part) => (node == null ? node : node[part]), en); + if (typeof text !== 'string') return key; + for (const [name, value] of Object.entries(options ?? {})) { + text = text.split('{{' + name + '}}').join(String(value)); + } + return text; +}; +export const useObjectTranslation = () => ({ t, language: 'en' }); +`, + [STUB_COMPONENTS]: ` +export { Alert, AlertTitle, AlertDescription } from ${at(UI('alert'))}; +export { Button } from ${at(UI('button'))}; +export { Card, CardContent } from ${at(UI('card'))}; +export { cn } from ${at(UTILS)}; +`, + [STUB_REACT]: 'export const SchemaRenderer = () => null;\n', + [ENTRY]: ` +import * as React from 'react'; +import { createRoot } from 'react-dom/client'; +import { MemoryRouter } from 'react-router-dom'; +import { MobileAppPage } from ${at(PAGE)}; + +createRoot(document.getElementById('root')).render( + React.createElement(MemoryRouter, null, React.createElement(MobileAppPage)), +); +window.__mounted = true; +`, + }; + return { + name: 'mobile-app-qr-fixtures', + enforce: 'pre', + async resolveId(id, importer) { + if (id === '@object-ui/auth') return STUB_AUTH; + if (id === '@object-ui/i18n') return STUB_I18N; + if (id === '@object-ui/components') return STUB_COMPONENTS; + if (id === '@object-ui/react') return STUB_REACT; + if (id === 'mobile-app-qr:entry') return ENTRY; + // The entry's and the stubs' bare imports resolve as the page's own do. + if ((importer === ENTRY || importer === STUB_COMPONENTS) && !path.isAbsolute(id)) { + return this.resolve(id, PAGE, { skipSelf: true }); + } + return null; + }, + load: (id) => modules[id] ?? null, + }; +} + +/** Bundle the entry once, from source, into one classic script. */ +async function bundle(): Promise { + const result = await build({ + configFile: false, + root: REPO_ROOT, + // Out of the tree: this run must leave nothing behind in the checkout. + cacheDir: path.join(os.tmpdir(), 'objectui-mobile-app-qr'), + logLevel: 'error', + publicDir: false, + plugins: [fixtures()], + define: { 'process.env.NODE_ENV': JSON.stringify('production') }, + build: { + write: false, + outDir: path.join(os.tmpdir(), 'objectui-mobile-app-qr-out'), + emptyOutDir: false, + minify: false, + modulePreload: false, + rollupOptions: { + input: 'mobile-app-qr:entry', + output: { format: 'iife', inlineDynamicImports: true }, + }, + }, + }); + const outputs = (Array.isArray(result) ? result : [result]) as Rollup.RollupOutput[]; + const chunks = outputs.flatMap((o) => o.output).filter((o): o is Rollup.OutputChunk => o.type === 'chunk'); + if (chunks.length !== 1) throw new Error(`expected one bundled chunk, got ${chunks.length}`); + return chunks[0].code; +} + +async function tailwind(): Promise { + const twEntry = fileURLToPath(import.meta.resolve('tailwindcss/index.css')); + const compiler = await compile('@import "tailwindcss";', { + base: path.dirname(twEntry), + loadStylesheet: async (id: string, base: string) => { + const file = id === 'tailwindcss' ? twEntry : path.resolve(base, id); + return { path: file, base: path.dirname(file), content: readFileSync(file, 'utf8') }; + }, + }); + const tokens = STYLED_SOURCES.map((f) => readFileSync(f, 'utf8')) + .flatMap((text) => text.split(/[\s'"`]+/)) + .filter(Boolean); + const css = compiler.build(tokens); + // The code's frame is what gives the image its size; without it a 0×0 image could pass for a drawn one. + for (const needle of ['.h-48', '.w-48']) { + if (!css.includes(needle)) throw new Error(`Tailwind emitted no rule for ${needle}; the code would be unsized.`); + } + return css; +} + +/** Never resolved by DNS: every request to it is answered by `page.route`. */ +const HARNESS_ORIGIN = 'http://mobile-app-qr.test'; + +let script = ''; +let css = ''; + +test.beforeAll(async () => { + [script, css] = await Promise.all([bundle(), tailwind()]); +}); + +/** Open the page with the server answering `features` on its public auth config. */ +async function openPage(page: Page, features: Record) { + const errors: string[] = []; + page.on('pageerror', (error) => errors.push(error.message)); + await page.route(`${HARNESS_ORIGIN}/**`, (route) => { + const url = new URL(route.request().url()); + if (url.pathname === '/harness.js') return route.fulfill({ contentType: 'text/javascript', body: script }); + return route.fulfill({ + contentType: 'text/html', + body: + `` + + `` + + `
`, + }); + }); + await page.goto(`${HARNESS_ORIGIN}/`); + try { + await page.waitForFunction(() => '__mounted' in window, null, { timeout: 10_000 }); + } catch (cause) { + throw new Error(`the harness did not mount; page errors: ${JSON.stringify(errors)}`, { cause }); + } +} + +test.describe('Mobile App page: the connect code', () => { + test('a public base URL with a sub-path renders the QR code and the copyable link', async ({ page }) => { + await openPage(page, { publicBaseUrl: 'https://acme.example/os' }); + + const link = page.getByTestId('mobile-app-link'); + await expect(link).toHaveText('objectos://connect?server=https%3A%2F%2Facme.example%2Fos'); + await expect(link).toBeVisible(); + + const qr = page.getByRole('img', { name: 'QR code that connects the ObjectOS mobile app to this server' }); + await expect(qr).toBeVisible(); + // The browser decoded the SVG into a picture: a broken image has no natural size. + await expect.poll(() => qr.evaluate((img: HTMLImageElement) => img.complete && img.naturalWidth > 0)).toBe(true); + const box = await qr.boundingBox(); + expect(box?.width ?? 0).toBeGreaterThanOrEqual(150); + expect(box?.height ?? 0).toBeGreaterThanOrEqual(150); + + await expect(page.getByRole('button', { name: 'Copy link' })).toBeVisible(); + await expect(page.getByText("The code holds only this server's address, never your account.")).toBeVisible(); + await expect(page.getByTestId('mobile-app-refusal')).toHaveCount(0); + }); + + test('CONTROL: a loopback base URL renders the OS_AUTH_URL remedy and no code', async ({ page }) => { + await openPage(page, { publicBaseUrl: 'http://localhost:3000' }); + + const refusal = page.getByTestId('mobile-app-refusal'); + await expect(refusal).toBeVisible(); + await expect(refusal).toContainText("A phone cannot reach this server's address"); + await expect(refusal).toContainText('http://localhost:3000'); + await expect(refusal).toContainText('OS_AUTH_URL'); + await expect(page.getByTestId('mobile-app-qr')).toHaveCount(0); + await expect(page.getByTestId('mobile-app-link')).toHaveCount(0); + }); +}); From 19ce21aa5212604b31c6f8bd157d5a05454dbffe Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 20:30:10 +0000 Subject: [PATCH 03/10] chore: changeset for the Mobile App page Claude-Session: https://claude.ai/code/session_01ADHkmRLqg1PuH8D83b32SV Co-authored-by: Claude --- .changeset/29314-mobile-app-connect-qr.md | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 .changeset/29314-mobile-app-connect-qr.md diff --git a/.changeset/29314-mobile-app-connect-qr.md b/.changeset/29314-mobile-app-connect-qr.md new file mode 100644 index 00000000000..ba8a91d5094 --- /dev/null +++ b/.changeset/29314-mobile-app-connect-qr.md @@ -0,0 +1,17 @@ +--- +'@object-ui/app-shell': patch +'@object-ui/i18n': patch +'@object-ui/auth': patch +'@objectstack/platform-objects': patch +--- + +feat(console): a Mobile App page in the account app shows the code that connects the ObjectOS mobile app to this server + +Clause-②: yes (widening) — a new account-app navigation entry and component (`account:mobile_app`), a new `mobileApp` namespace in the `@object-ui/i18n` packs, and `features.publicBaseUrl` declared on `AuthPublicConfig`; nothing that worked before is refused +Metadata-protocol: none + +The account app (avatar menu → Profile) gains a **Mobile App** entry after Profile. Its page shows a QR code that encodes `objectos://connect?server=`, the same link as copyable text, and one line saying the code holds only the server's address, never the account. + +The server URL is the one the server publishes as `features.publicBaseUrl` on `GET /api/v1/auth/config`: the base URL the auth layer builds every link from (`OS_AUTH_URL`, then `BETTER_AUTH_URL`, then `OS_BASE_URL`), with any sub-path mount. The browser's own address is never used, because it can be an internal or proxied host. When that URL names `localhost` or a private address, or the server publishes none, the page shows no code and says how to fix it: set `OS_AUTH_URL` on the server to its public address and restart it. + +No app-store links are shown: no setting carries them today. From 582808606d32e1eee652830e27d1f3bac49d8a67 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 20:44:23 +0000 Subject: [PATCH 04/10] fix(console): remount the mobile connect card per link instead of resetting state in an effect Claude-Session: https://claude.ai/code/session_01ADHkmRLqg1PuH8D83b32SV Co-authored-by: Claude --- ui/packages/app-shell/src/console/mobile-app/MobileAppPage.tsx | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/ui/packages/app-shell/src/console/mobile-app/MobileAppPage.tsx b/ui/packages/app-shell/src/console/mobile-app/MobileAppPage.tsx index 15620c6a7cf..feebacfe1bc 100644 --- a/ui/packages/app-shell/src/console/mobile-app/MobileAppPage.tsx +++ b/ui/packages/app-shell/src/console/mobile-app/MobileAppPage.tsx @@ -66,7 +66,7 @@ export function MobileAppPage() { {t('mobileApp.loadFailed')} ) : load.target.kind === 'ready' ? ( - + ) : ( @@ -96,7 +96,6 @@ function ConnectCard({ connectLink }: { connectLink: string }) { // Rendered here, client side: the link never leaves the browser to draw it. useEffect(() => { let cancelled = false; - setSvg(null); renderQrSvg(connectLink, { type: 'svg', margin: 1 }) .then((markup) => { if (!cancelled) setSvg(markup); From 9cebce8674bce8d67ce08b8b1e9b81bc8a0277c6 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 22:09:14 +0000 Subject: [PATCH 05/10] test(cli): the account app serves 14 nav ids now that the Mobile App entry joined after Profile Claude-Session: https://claude.ai/code/session_01ADHkmRLqg1PuH8D83b32SV Co-authored-by: Claude --- .../cli/test/connect-agent-both-halves-wire.pin.test.ts | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/packages/cli/test/connect-agent-both-halves-wire.pin.test.ts b/packages/cli/test/connect-agent-both-halves-wire.pin.test.ts index 6777ca00d52..7f5013d1c1a 100644 --- a/packages/cli/test/connect-agent-both-halves-wire.pin.test.ts +++ b/packages/cli/test/connect-agent-both-halves-wire.pin.test.ts @@ -222,9 +222,10 @@ describe('#17647 — Connect-an-Agent visibility: BOTH halves, over the wire', ( .toEqual(['nav_connect_agent']); expect(groupChildren(account.body?.item, 'grp_account_developer')) .toEqual(['nav_account_api_keys', 'nav_account_oauth_apps']); - // The whole served tree, counted: 12 authored ids (the AI Assistant - // slot among them) + the one contributed. - expect(navIds(account.body?.item)).toHaveLength(13); + // The whole served tree, counted: 13 authored ids (the AI Assistant + // slot among them) + the one contributed. (12 authored until the + // Mobile App entry, `nav_account_mobile_app`, joined after Profile.) + expect(navIds(account.body?.item)).toHaveLength(14); // …and the entry's TARGET rode along, so the menu item resolves. expect(JSON.stringify(account.body)).toContain('connect_agent'); From b477713d9a2deec94e6db6750b5489ee82d22d30 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 00:18:01 +0000 Subject: [PATCH 06/10] feat(console): the mobile connect code carries the normalised server address and requires https for a public host Claude-Session: https://claude.ai/code/session_01ADHkmRLqg1PuH8D83b32SV Co-authored-by: Claude --- .changeset/29314-mobile-app-connect-qr.md | 2 +- .../src/apps/account-mobile-app-nav.test.ts | 34 ++++++++ .../console/mobile-app/MobileAppPage.test.tsx | 50 +++++++++++- .../src/console/mobile-app/MobileAppPage.tsx | 22 ++++-- .../console/mobile-app/mobileConnect.test.ts | 77 ++++++++++++++++--- .../src/console/mobile-app/mobileConnect.ts | 47 ++++++++--- ui/packages/i18n/src/locales/ar.ts | 4 +- ui/packages/i18n/src/locales/de.ts | 4 +- ui/packages/i18n/src/locales/en.ts | 4 +- ui/packages/i18n/src/locales/es.ts | 4 +- ui/packages/i18n/src/locales/fr.ts | 4 +- ui/packages/i18n/src/locales/ja.ts | 4 +- ui/packages/i18n/src/locales/ko.ts | 4 +- ui/packages/i18n/src/locales/pt-BR.ts | 4 +- ui/packages/i18n/src/locales/ru.ts | 4 +- ui/packages/i18n/src/locales/zh-Hans.ts | 4 +- ui/packages/i18n/src/locales/zh-Hant.ts | 4 +- 17 files changed, 236 insertions(+), 40 deletions(-) create mode 100644 packages/platform-objects/src/apps/account-mobile-app-nav.test.ts diff --git a/.changeset/29314-mobile-app-connect-qr.md b/.changeset/29314-mobile-app-connect-qr.md index ba8a91d5094..83ad37f0a8e 100644 --- a/.changeset/29314-mobile-app-connect-qr.md +++ b/.changeset/29314-mobile-app-connect-qr.md @@ -12,6 +12,6 @@ Metadata-protocol: none The account app (avatar menu → Profile) gains a **Mobile App** entry after Profile. Its page shows a QR code that encodes `objectos://connect?server=`, the same link as copyable text, and one line saying the code holds only the server's address, never the account. -The server URL is the one the server publishes as `features.publicBaseUrl` on `GET /api/v1/auth/config`: the base URL the auth layer builds every link from (`OS_AUTH_URL`, then `BETTER_AUTH_URL`, then `OS_BASE_URL`), with any sub-path mount. The browser's own address is never used, because it can be an internal or proxied host. When that URL names `localhost` or a private address, or the server publishes none, the page shows no code and says how to fix it: set `OS_AUTH_URL` on the server to its public address and restart it. +The server URL is the one the server publishes as `features.publicBaseUrl` on `GET /api/v1/auth/config`: the base URL the auth layer builds every link from (`OS_AUTH_URL`, then `BETTER_AUTH_URL`, then `OS_BASE_URL`), with any sub-path mount. The code carries that URL normalised to its scheme, host and path: a username, password, query or fragment in the setting never reaches the code, the link or the page. The browser's own address is never used, because it can be an internal or proxied host. When that URL names `localhost` or a private address, or a public host on plain `http:` (the mobile app signs in through it, so it must be HTTPS), the page shows no code and says how to fix it: set `OS_AUTH_URL` on the server to its public `https://` address and restart it. A server that does not publish the field gets a page saying it does not offer this yet. No app-store links are shown: no setting carries them today. diff --git a/packages/platform-objects/src/apps/account-mobile-app-nav.test.ts b/packages/platform-objects/src/apps/account-mobile-app-nav.test.ts new file mode 100644 index 00000000000..bea92663227 --- /dev/null +++ b/packages/platform-objects/src/apps/account-mobile-app-nav.test.ts @@ -0,0 +1,34 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. +// +// The account app's Mobile App entry sits right after Profile and targets the +// component the Console registers as `account:mobile_app` (the app-shell half +// of this pairing is pinned in `MobileAppPage.test.tsx`, which resolves the +// same ref through the component registry). A bare nav-count pin elsewhere +// shows that one id joined; this one shows which, where, and what it opens. +import { describe, it, expect } from 'vitest'; +import { AppSchema } from '@objectstack/spec/ui'; + +import { ACCOUNT_APP } from './account.app.js'; + +type NavItem = { id?: string; type?: string; componentRef?: string; requiredPermissions?: unknown }; + +const topLevel = (): NavItem[] => (ACCOUNT_APP.navigation ?? []) as NavItem[]; + +describe("the account app's Mobile App entry", () => { + it('sits immediately after Profile', () => { + const ids = topLevel().map((item) => item.id); + const profile = ids.indexOf('nav_account_profile'); + expect(profile, 'the account app lost its Profile entry').toBeGreaterThanOrEqual(0); + expect(ids[profile + 1]).toBe('nav_account_mobile_app'); + }); + + it('opens the `account:mobile_app` component, ungated', () => { + const entry = topLevel().find((item) => item.id === 'nav_account_mobile_app'); + expect(entry).toMatchObject({ type: 'component', componentRef: 'account:mobile_app' }); + expect(entry?.requiredPermissions).toBeUndefined(); + }); + + it('CONTROL: the app with the entry still parses as an App', () => { + expect(AppSchema.safeParse(ACCOUNT_APP).success).toBe(true); + }); +}); diff --git a/ui/packages/app-shell/src/console/mobile-app/MobileAppPage.test.tsx b/ui/packages/app-shell/src/console/mobile-app/MobileAppPage.test.tsx index c124b0a6556..4bc0e946de7 100644 --- a/ui/packages/app-shell/src/console/mobile-app/MobileAppPage.test.tsx +++ b/ui/packages/app-shell/src/console/mobile-app/MobileAppPage.test.tsx @@ -34,6 +34,8 @@ vi.mock('@object-ui/auth', async (importOriginal) => ({ import { MobileAppPage } from './MobileAppPage'; import { builtInLocales } from '@object-ui/i18n/locales'; +import { getAppComponent } from '../../services/componentRegistry'; +import '../../services/builtinComponents'; function serving(features: Record | undefined) { getAuthConfig = vi.fn(async () => ({ features })); @@ -66,6 +68,16 @@ describe('MobileAppPage: a public base URL renders the code and the copyable lin expect(screen.queryByTestId('mobile-app-refusal')).not.toBeInTheDocument(); }); + it('a credential, query or fragment in the configured URL never reaches the code or the link', async () => { + serving({ publicBaseUrl: 'https://ops:s3cret@acme.example/os/?token=abc#x' }); + render(); + const link = 'objectos://connect?server=https%3A%2F%2Facme.example%2Fos'; + + expect(await screen.findByTestId('mobile-app-link')).toHaveTextContent(link); + expect(await screen.findByTestId('mobile-app-qr')).toHaveAttribute('src', await expectedQrSrc(link)); + expect(document.body.textContent).not.toMatch(/s3cret|token/); + }); + it('Copy link writes exactly the connect link to the clipboard', async () => { serving({ publicBaseUrl: 'https://os.acme.example' }); const writeText = vi.fn(async () => undefined); @@ -90,13 +102,35 @@ describe('MobileAppPage: no code for an address a phone cannot reach', () => { expect(screen.queryByTestId('mobile-app-link')).not.toBeInTheDocument(); }); + it('a public host on plain http: the HTTPS remedy names the address and OS_AUTH_URL, and no code renders', async () => { + serving({ publicBaseUrl: 'http://os.acme.example/os' }); + render(); + + const refusal = await screen.findByTestId('mobile-app-refusal'); + expect(refusal).toHaveTextContent('«mobileApp.insecureTitle»'); + expect(refusal).toHaveTextContent('«mobileApp.insecureBody|http://os.acme.example/os|OS_AUTH_URL»'); + expect(screen.queryByTestId('mobile-app-qr')).not.toBeInTheDocument(); + expect(screen.queryByTestId('mobile-app-link')).not.toBeInTheDocument(); + }); + + it('a credential in the configured address is shown nowhere on a refusal', async () => { + serving({ publicBaseUrl: 'http://ops:s3cret@192.168.1.20/os' }); + render(); + + const refusal = await screen.findByTestId('mobile-app-refusal'); + expect(refusal).toHaveTextContent('«mobileApp.unreachableBody|http://192.168.1.20/os|OS_AUTH_URL»'); + expect(document.body.textContent).not.toContain('s3cret'); + }); + it('no published address: the unpublished remedy, and the browser address is never encoded', async () => { serving({}); render(); const refusal = await screen.findByTestId('mobile-app-refusal'); expect(refusal).toHaveTextContent('«mobileApp.unpublishedTitle»'); - expect(refusal).toHaveTextContent('«mobileApp.unpublishedBody|OS_AUTH_URL»'); + // The server does not serve the key: no setting can fix that, so none is named. + expect(refusal).toHaveTextContent('«mobileApp.unpublishedBody»'); + expect(refusal).not.toHaveTextContent('OS_AUTH_URL'); expect(screen.queryByTestId('mobile-app-qr')).not.toBeInTheDocument(); expect(document.body.textContent).not.toContain(window.location.host); }); @@ -122,3 +156,17 @@ describe('the mobileApp pack keys', () => { } }); }); + +describe('the account:mobile_app registration', () => { + // The platform-objects half of this pairing pins that the account app's + // `nav_account_mobile_app` entry, right after Profile, names this ref. + it('the ref the account app navigates to resolves to this page', async () => { + serving({ publicBaseUrl: 'https://os.acme.example' }); + const entry = getAppComponent('account:mobile_app'); + expect(entry).toMatchObject({ ref: 'account:mobile_app', source: '@object-ui/app-shell' }); + const Registered = entry!.component; + render(); + expect(await screen.findByTestId('mobile-app-page')).toBeInTheDocument(); + expect(await screen.findByTestId('mobile-app-link')).toHaveTextContent('objectos://connect?server=https%3A%2F%2Fos.acme.example'); + }); +}); diff --git a/ui/packages/app-shell/src/console/mobile-app/MobileAppPage.tsx b/ui/packages/app-shell/src/console/mobile-app/MobileAppPage.tsx index feebacfe1bc..8e3c1136a53 100644 --- a/ui/packages/app-shell/src/console/mobile-app/MobileAppPage.tsx +++ b/ui/packages/app-shell/src/console/mobile-app/MobileAppPage.tsx @@ -6,9 +6,10 @@ * * The server URL is the one the server publishes (`features.publicBaseUrl` on * the public auth config), never `window.location`, which can be an internal - * or proxied host. A loopback or private address, or no published address, - * gets a refusal naming `OS_AUTH_URL` instead of a code a phone cannot use. - * The code carries the server's address only, never a credential. + * or proxied host. A loopback or private address, or a public host on plain + * `http:`, gets a refusal naming `OS_AUTH_URL` instead of a code a phone + * cannot use; a server that does not serve the key gets a refusal saying so. + * The code carries the normalised server address only, never a credential. */ import { useEffect, useState } from 'react'; @@ -69,17 +70,15 @@ export function MobileAppPage() { ) : ( - - {load.target.kind === 'unreachable' ? t('mobileApp.unreachableTitle') : t('mobileApp.unpublishedTitle')} - + {t(refusalKeys(load.target).title)} {load.target.kind === 'unreachable' - ? t('mobileApp.unreachableBody', { + ? t(refusalKeys(load.target).body, { address: load.target.serverUrl, setting: PUBLIC_ADDRESS_SETTING, example: PUBLIC_ADDRESS_EXAMPLE, }) - : t('mobileApp.unpublishedBody', { setting: PUBLIC_ADDRESS_SETTING, example: PUBLIC_ADDRESS_EXAMPLE })} + : t(refusalKeys(load.target).body)} )} @@ -88,6 +87,13 @@ export function MobileAppPage() { ); } +/** The title and body keys for a target that shows no code. */ +function refusalKeys(target: Exclude): { title: string; body: string } { + if (target.kind === 'unpublished') return { title: 'mobileApp.unpublishedTitle', body: 'mobileApp.unpublishedBody' }; + if (target.reason === 'not-https') return { title: 'mobileApp.insecureTitle', body: 'mobileApp.insecureBody' }; + return { title: 'mobileApp.unreachableTitle', body: 'mobileApp.unreachableBody' }; +} + function ConnectCard({ connectLink }: { connectLink: string }) { const { t } = useObjectTranslation(); const [svg, setSvg] = useState(null); diff --git a/ui/packages/app-shell/src/console/mobile-app/mobileConnect.test.ts b/ui/packages/app-shell/src/console/mobile-app/mobileConnect.test.ts index b4728180ce0..e57370c5fa5 100644 --- a/ui/packages/app-shell/src/console/mobile-app/mobileConnect.test.ts +++ b/ui/packages/app-shell/src/console/mobile-app/mobileConnect.test.ts @@ -2,12 +2,13 @@ /** * The Mobile App page's connect payload is built from the server's published - * public base URL, sub-path mount included, and a loopback or private address - * is refused instead of encoded (objectstack#29314). + * public base URL, sub-path mount included, normalised so it carries the + * server's address and nothing else; a loopback or private address, or a + * public host on plain http, is refused instead of encoded (objectstack#29314). */ import { describe, expect, it } from 'vitest'; -import { mobileConnectLink, mobileConnectTarget } from './mobileConnect'; +import { mobileConnectLink, mobileConnectTarget, normalizeServerUrl } from './mobileConnect'; describe('mobileConnectTarget: the payload is the configured public URL', () => { it('a public origin becomes objectos://connect?server=', () => { @@ -51,16 +52,69 @@ describe('mobileConnectTarget: localhost and private addresses are refused, neve 'http://os.local', 'http://os.corp.internal', ])('%s', (address) => { - expect(mobileConnectTarget(address)).toEqual({ kind: 'unreachable', serverUrl: address }); + expect(mobileConnectTarget(address)).toEqual({ kind: 'unreachable', reason: 'not-public', serverUrl: address }); }); - it('a value that is not an absolute http(s) URL is refused too', () => { - expect(mobileConnectTarget('os.acme.example').kind).toBe('unreachable'); - expect(mobileConnectTarget('ftp://os.acme.example').kind).toBe('unreachable'); + it('a scheme other than http(s) is refused, and its credential is not shown', () => { + expect(mobileConnectTarget('ftp://ops:s3cret@os.acme.example')).toEqual({ + kind: 'unreachable', + reason: 'not-public', + serverUrl: 'ftp://os.acme.example', + }); + }); +}); + +describe('mobileConnectTarget: a public host must be HTTPS', () => { + it('a public host on plain http is refused with the HTTPS remedy, never encoded', () => { + expect(mobileConnectTarget('http://os.acme.example/os')).toEqual({ + kind: 'unreachable', + reason: 'not-https', + serverUrl: 'http://os.acme.example/os', + }); + }); + + it('CONTROL: the same host on https is encoded', () => { + expect(mobileConnectTarget('https://os.acme.example/os').kind).toBe('ready'); + }); +}); + +describe('mobileConnectTarget: the payload is the normalised address and nothing else', () => { + it.each([ + ['a username and password', 'https://ops:s3cret@os.acme.example/os', 'https://os.acme.example/os'], + ['a username alone', 'https://ops@os.acme.example', 'https://os.acme.example'], + ['a query', 'https://os.acme.example/os?token=abc&tenant=1', 'https://os.acme.example/os'], + ['a fragment', 'https://os.acme.example/os#session=abc', 'https://os.acme.example/os'], + ['a trailing slash', 'https://os.acme.example/os/', 'https://os.acme.example/os'], + ['surrounding whitespace', ' https://os.acme.example ', 'https://os.acme.example'], + ['an upper-case scheme and host', 'HTTPS://OS.ACME.Example/os', 'https://os.acme.example/os'], + ['the default port', 'https://os.acme.example:443/os', 'https://os.acme.example/os'], + ])('%s is dropped or normalised', (_what, configured, address) => { + expect(mobileConnectTarget(configured)).toEqual({ + kind: 'ready', + serverUrl: address, + connectLink: mobileConnectLink(address), + }); + }); + + it('the decoded server parameter is the only parameter and holds no credential', () => { + const target = mobileConnectTarget('https://ops:s3cret@os.acme.example/os?token=abc#x'); + const link = new URL((target as { connectLink: string }).connectLink); + expect([...link.searchParams.keys()]).toEqual(['server']); + expect(link.searchParams.get('server')).toBe('https://os.acme.example/os'); + expect(link.href).not.toMatch(/s3cret|ops|token|abc/); }); - it('CONTROL: a public host on plain http is not a private address, so it is encoded', () => { - expect(mobileConnectTarget('http://os.acme.example').kind).toBe('ready'); + it('a credential on a refused address is not shown either', () => { + expect(mobileConnectTarget('http://ops:s3cret@192.168.1.20/os')).toEqual({ + kind: 'unreachable', + reason: 'not-public', + serverUrl: 'http://192.168.1.20/os', + }); + }); + + it('normalizeServerUrl answers null for a value that is not an absolute URL', () => { + expect(normalizeServerUrl('os.acme.example')).toBeNull(); + expect(normalizeServerUrl('ops:s3cret@os.acme.example')).toBeNull(); }); }); @@ -68,4 +122,9 @@ describe('mobileConnectTarget: no published URL', () => { it.each([undefined, null, '', ' ', 42])('%s reads as unpublished, never as the browser address', (value) => { expect(mobileConnectTarget(value)).toEqual({ kind: 'unpublished' }); }); + + it('a value that is not an absolute URL reads as unpublished, so the raw value is never shown', () => { + expect(mobileConnectTarget('os.acme.example')).toEqual({ kind: 'unpublished' }); + expect(mobileConnectTarget('ops:s3cret@os.acme.example')).toEqual({ kind: 'unpublished' }); + }); }); diff --git a/ui/packages/app-shell/src/console/mobile-app/mobileConnect.ts b/ui/packages/app-shell/src/console/mobile-app/mobileConnect.ts index 2c9eccbd6e0..05669209245 100644 --- a/ui/packages/app-shell/src/console/mobile-app/mobileConnect.ts +++ b/ui/packages/app-shell/src/console/mobile-app/mobileConnect.ts @@ -12,25 +12,52 @@ export const PUBLIC_ADDRESS_SETTING = 'OS_AUTH_URL'; * What the Mobile App page shows, judged from the server's published public * base URL (`features.publicBaseUrl` on the public auth config). * - * - `ready`: a QR code and a copyable link carrying that URL. - * - `unreachable`: the URL names a loopback or private address a phone - * cannot open, so the page refuses with the `OS_AUTH_URL` remedy. - * - `unpublished`: the server published no public URL; the browser's own - * address is never used in its place, because it can be an internal or - * proxied host. + * - `ready`: a QR code and a copyable link carrying that URL, normalised. + * - `unreachable`, `not-public`: the URL names a loopback or private address + * a phone cannot open, or its scheme is not http(s). + * - `unreachable`, `not-https`: a public host on plain `http:`. The mobile app + * signs in through this address, so it must be HTTPS. + * - `unpublished`: the server does not serve the key, or serves a value that + * is not an absolute URL (never shown: it may hold anything). The + * browser's own address is never used in its place, because it can be an + * internal or proxied host. + * + * `serverUrl` on every arm is the normalised address, so a credential in the + * configured value is never shown or encoded. */ export type MobileConnectTarget = | { readonly kind: 'ready'; readonly serverUrl: string; readonly connectLink: string } - | { readonly kind: 'unreachable'; readonly serverUrl: string } + | { readonly kind: 'unreachable'; readonly reason: 'not-public' | 'not-https'; readonly serverUrl: string } | { readonly kind: 'unpublished' }; -/** The connect link for a server URL: `objectos://connect?server=`. */ +/** + * The address a configured base URL stands for: scheme, host (port included) + * and path, with no trailing slash. A username, password, query or fragment + * in the value is dropped, so the code carries the server's address and + * nothing else. `null` for a value that is not an absolute URL. + */ +export function normalizeServerUrl(value: string): string | null { + let url: URL; + try { + url = new URL(value.trim()); + } catch { + return null; + } + if (!url.host) return null; + return `${url.protocol}//${url.host}${url.pathname.replace(/\/+$/, '')}`; +} + +/** The connect link for a normalised server URL: `objectos://connect?server=`. */ export function mobileConnectLink(serverUrl: string): string { return `${MOBILE_CONNECT_LINK_BASE}?server=${encodeURIComponent(serverUrl)}`; } export function mobileConnectTarget(publicBaseUrl: unknown): MobileConnectTarget { if (typeof publicBaseUrl !== 'string' || publicBaseUrl.trim() === '') return { kind: 'unpublished' }; - if (!isPublicHostAddress(publicBaseUrl)) return { kind: 'unreachable', serverUrl: publicBaseUrl }; - return { kind: 'ready', serverUrl: publicBaseUrl, connectLink: mobileConnectLink(publicBaseUrl) }; + const serverUrl = normalizeServerUrl(publicBaseUrl); + // Not an absolute URL: no address to judge, and the raw value is never shown. + if (serverUrl === null) return { kind: 'unpublished' }; + if (!isPublicHostAddress(serverUrl)) return { kind: 'unreachable', reason: 'not-public', serverUrl }; + if (!serverUrl.startsWith('https://')) return { kind: 'unreachable', reason: 'not-https', serverUrl }; + return { kind: 'ready', serverUrl, connectLink: mobileConnectLink(serverUrl) }; } diff --git a/ui/packages/i18n/src/locales/ar.ts b/ui/packages/i18n/src/locales/ar.ts index 41d828a2c40..8b076dff8f6 100644 --- a/ui/packages/i18n/src/locales/ar.ts +++ b/ui/packages/i18n/src/locales/ar.ts @@ -5672,8 +5672,10 @@ const ar = { loadFailed: "تعذّرت قراءة العنوان العام لهذا الخادم. أعد تحميل الصفحة للمحاولة مرة أخرى.", unreachableTitle: "لا يستطيع الهاتف الوصول إلى عنوان هذا الخادم", unreachableBody: "عنوان هذا الخادم هو {{address}}، وهو عنوان محلي أو خاص لا يستطيع الهاتف فتحه، لذلك لا يُعرض أي رمز. اضبط {{setting}} على الخادم على عنوانه العام، مثل {{example}}، ثم أعد تشغيله.", + insecureTitle: "عنوان هذا الخادم لا يستخدم HTTPS", + insecureBody: "عنوان هذا الخادم هو {{address}}. يسجّل تطبيق الهاتف الدخول عبره، لذا يجب أن يستخدم HTTPS، ولا يُعرض أي رمز. قدّم هذا الخادم عبر HTTPS، واضبط {{setting}} على عنوانه https://، مثل {{example}}، ثم أعد تشغيله.", unpublishedTitle: "لا ينشر هذا الخادم عنوانه العام", - unpublishedBody: "لا يُعرض أي رمز: قد يكون العنوان في متصفحك مضيفًا داخليًا لا يستطيع الهاتف الوصول إليه. اضبط {{setting}} على الخادم على عنوانه العام، مثل {{example}}، ثم أعد تشغيله.", + unpublishedBody: "لا يُعرض أي رمز: لا يوفّر هذا الخادم عنوانه العام لتطبيق الهاتف بعد. حدّث الخادم إلى إصدار يدعم ذلك.", }, }; diff --git a/ui/packages/i18n/src/locales/de.ts b/ui/packages/i18n/src/locales/de.ts index aef130b2b9c..af55be91c7f 100644 --- a/ui/packages/i18n/src/locales/de.ts +++ b/ui/packages/i18n/src/locales/de.ts @@ -5102,8 +5102,10 @@ const de = { loadFailed: "Die öffentliche Adresse dieses Servers konnte nicht gelesen werden. Laden Sie die Seite neu, um es erneut zu versuchen.", unreachableTitle: "Ein Telefon kann die Adresse dieses Servers nicht erreichen", unreachableBody: "Die Adresse dieses Servers ist {{address}}, eine lokale oder private Adresse, die ein Telefon nicht öffnen kann, daher wird kein Code angezeigt. Setzen Sie {{setting}} auf dem Server auf seine öffentliche Adresse, zum Beispiel {{example}}, und starten Sie ihn neu.", + insecureTitle: "Die Adresse dieses Servers verwendet kein HTTPS", + insecureBody: "Die Adresse dieses Servers ist {{address}}. Die mobile App meldet sich darüber an, daher muss sie HTTPS verwenden, und es wird kein Code angezeigt. Stellen Sie den Server über HTTPS bereit, setzen Sie {{setting}} auf seine https://-Adresse, zum Beispiel {{example}}, und starten Sie ihn neu.", unpublishedTitle: "Dieser Server veröffentlicht keine öffentliche Adresse", - unpublishedBody: "Es wird kein Code angezeigt: Die Adresse in Ihrem Browser kann ein interner Host sein, den ein Telefon nicht erreicht. Setzen Sie {{setting}} auf dem Server auf seine öffentliche Adresse, zum Beispiel {{example}}, und starten Sie ihn neu.", + unpublishedBody: "Es wird kein Code angezeigt: Dieser Server stellt der mobilen App seine öffentliche Adresse noch nicht bereit. Aktualisieren Sie den Server auf eine Version, die das unterstützt.", }, }; diff --git a/ui/packages/i18n/src/locales/en.ts b/ui/packages/i18n/src/locales/en.ts index cc6e7b98c45..3d96cc0a959 100644 --- a/ui/packages/i18n/src/locales/en.ts +++ b/ui/packages/i18n/src/locales/en.ts @@ -6006,8 +6006,10 @@ const en = { loadFailed: "Could not read this server's public address. Reload the page to try again.", unreachableTitle: "A phone cannot reach this server's address", unreachableBody: "This server's address is {{address}}, a local or private address a phone cannot open, so no code is shown. Set {{setting}} on the server to its public address, for example {{example}}, and restart it.", + insecureTitle: "This server's address does not use HTTPS", + insecureBody: "This server's address is {{address}}. The mobile app signs in through it, so it must use HTTPS, and no code is shown. Serve this server over HTTPS, set {{setting}} to its https:// address, for example {{example}}, and restart it.", unpublishedTitle: "This server does not publish its public address", - unpublishedBody: "No code is shown: the address in your browser can be an internal host a phone cannot reach. Set {{setting}} on the server to its public address, for example {{example}}, and restart it.", + unpublishedBody: "No code is shown: this server does not offer its public address to the mobile app yet. Update the server to a version that does.", }, } as const; diff --git a/ui/packages/i18n/src/locales/es.ts b/ui/packages/i18n/src/locales/es.ts index 469287910d7..5d082c0c2f5 100644 --- a/ui/packages/i18n/src/locales/es.ts +++ b/ui/packages/i18n/src/locales/es.ts @@ -5244,8 +5244,10 @@ const es = { loadFailed: "No se pudo leer la dirección pública de este servidor. Recarga la página para volver a intentarlo.", unreachableTitle: "Un teléfono no puede acceder a la dirección de este servidor", unreachableBody: "La dirección de este servidor es {{address}}, una dirección local o privada que un teléfono no puede abrir, así que no se muestra ningún código. Establece {{setting}} en el servidor con su dirección pública, por ejemplo {{example}}, y reinícialo.", + insecureTitle: "La dirección de este servidor no usa HTTPS", + insecureBody: "La dirección de este servidor es {{address}}. La aplicación móvil inicia sesión a través de ella, por lo que debe usar HTTPS, y no se muestra ningún código. Sirve este servidor por HTTPS, establece {{setting}} con su dirección https://, por ejemplo {{example}}, y reinícialo.", unpublishedTitle: "Este servidor no publica su dirección pública", - unpublishedBody: "No se muestra ningún código: la dirección de tu navegador puede ser un host interno al que un teléfono no puede acceder. Establece {{setting}} en el servidor con su dirección pública, por ejemplo {{example}}, y reinícialo.", + unpublishedBody: "No se muestra ningún código: este servidor todavía no ofrece su dirección pública a la aplicación móvil. Actualiza el servidor a una versión que lo admita.", }, }; diff --git a/ui/packages/i18n/src/locales/fr.ts b/ui/packages/i18n/src/locales/fr.ts index 5eaeb11a79c..8ff010d1ec7 100644 --- a/ui/packages/i18n/src/locales/fr.ts +++ b/ui/packages/i18n/src/locales/fr.ts @@ -5240,8 +5240,10 @@ const fr = { loadFailed: "Impossible de lire l'adresse publique de ce serveur. Rechargez la page pour réessayer.", unreachableTitle: "Un téléphone ne peut pas joindre l'adresse de ce serveur", unreachableBody: "L'adresse de ce serveur est {{address}}, une adresse locale ou privée qu'un téléphone ne peut pas ouvrir : aucun code n'est donc affiché. Définissez {{setting}} sur le serveur avec son adresse publique, par exemple {{example}}, puis redémarrez-le.", + insecureTitle: "L'adresse de ce serveur n'utilise pas HTTPS", + insecureBody: "L'adresse de ce serveur est {{address}}. L'application mobile s'y connecte pour l'authentification : elle doit donc utiliser HTTPS, et aucun code n'est affiché. Servez ce serveur en HTTPS, définissez {{setting}} avec son adresse https://, par exemple {{example}}, puis redémarrez-le.", unpublishedTitle: "Ce serveur ne publie pas son adresse publique", - unpublishedBody: "Aucun code n'est affiché : l'adresse de votre navigateur peut être un hôte interne qu'un téléphone ne peut pas joindre. Définissez {{setting}} sur le serveur avec son adresse publique, par exemple {{example}}, puis redémarrez-le.", + unpublishedBody: "Aucun code n'est affiché : ce serveur ne fournit pas encore son adresse publique à l'application mobile. Mettez le serveur à jour vers une version qui le prend en charge.", }, }; diff --git a/ui/packages/i18n/src/locales/ja.ts b/ui/packages/i18n/src/locales/ja.ts index 87db8ee99af..a1ff9c7da7e 100644 --- a/ui/packages/i18n/src/locales/ja.ts +++ b/ui/packages/i18n/src/locales/ja.ts @@ -5103,8 +5103,10 @@ const ja = { loadFailed: "このサーバーの公開アドレスを読み取れませんでした。ページを再読み込みしてもう一度お試しください。", unreachableTitle: "スマートフォンからこのサーバーのアドレスに接続できません", unreachableBody: "このサーバーのアドレスは {{address}} で、スマートフォンから開けないローカルまたはプライベートアドレスのため、コードは表示されません。サーバーの {{setting}} を公開アドレス(例: {{example}})に設定し、サーバーを再起動してください。", + insecureTitle: "このサーバーのアドレスは HTTPS を使用していません", + insecureBody: "このサーバーのアドレスは {{address}} です。モバイルアプリはこのアドレスを通じてサインインするため HTTPS が必要で、コードは表示されません。サーバーを HTTPS で提供し、{{setting}} を https:// のアドレス(例: {{example}})に設定して、サーバーを再起動してください。", unpublishedTitle: "このサーバーは公開アドレスを公開していません", - unpublishedBody: "コードは表示されません。ブラウザーのアドレスは、スマートフォンから接続できない内部ホストの可能性があります。サーバーの {{setting}} を公開アドレス(例: {{example}})に設定し、サーバーを再起動してください。", + unpublishedBody: "コードは表示されません。このサーバーはまだ公開アドレスをモバイルアプリに提供していません。対応するバージョンにサーバーを更新してください。", }, }; diff --git a/ui/packages/i18n/src/locales/ko.ts b/ui/packages/i18n/src/locales/ko.ts index 294a75a12d9..1fecd086362 100644 --- a/ui/packages/i18n/src/locales/ko.ts +++ b/ui/packages/i18n/src/locales/ko.ts @@ -5100,8 +5100,10 @@ const ko = { loadFailed: "이 서버의 공개 주소를 읽지 못했습니다. 페이지를 새로 고친 후 다시 시도하세요.", unreachableTitle: "휴대폰에서 이 서버의 주소에 접속할 수 없습니다", unreachableBody: "이 서버의 주소는 {{address}}이며, 휴대폰에서 열 수 없는 로컬 또는 사설 주소이므로 코드를 표시하지 않습니다. 서버의 {{setting}}을(를) 공개 주소(예: {{example}})로 설정하고 서버를 다시 시작하세요.", + insecureTitle: "이 서버의 주소는 HTTPS를 사용하지 않습니다", + insecureBody: "이 서버의 주소는 {{address}}입니다. 모바일 앱은 이 주소로 로그인하므로 HTTPS를 사용해야 하며, 코드를 표시하지 않습니다. 서버를 HTTPS로 제공하고 {{setting}}을(를) https:// 주소(예: {{example}})로 설정한 뒤 서버를 다시 시작하세요.", unpublishedTitle: "이 서버는 공개 주소를 게시하지 않습니다", - unpublishedBody: "코드를 표시하지 않습니다. 브라우저의 주소는 휴대폰에서 접속할 수 없는 내부 호스트일 수 있습니다. 서버의 {{setting}}을(를) 공개 주소(예: {{example}})로 설정하고 서버를 다시 시작하세요.", + unpublishedBody: "코드를 표시하지 않습니다. 이 서버는 아직 모바일 앱에 공개 주소를 제공하지 않습니다. 이를 지원하는 버전으로 서버를 업데이트하세요.", }, }; diff --git a/ui/packages/i18n/src/locales/pt-BR.ts b/ui/packages/i18n/src/locales/pt-BR.ts index 0e2678f0d77..a4abab52cb5 100644 --- a/ui/packages/i18n/src/locales/pt-BR.ts +++ b/ui/packages/i18n/src/locales/pt-BR.ts @@ -5239,8 +5239,10 @@ const pt = { loadFailed: "Não foi possível ler o endereço público deste servidor. Recarregue a página para tentar novamente.", unreachableTitle: "Um celular não consegue acessar o endereço deste servidor", unreachableBody: "O endereço deste servidor é {{address}}, um endereço local ou privado que um celular não consegue abrir, então nenhum código é exibido. Defina {{setting}} no servidor com o endereço público dele, por exemplo {{example}}, e reinicie-o.", + insecureTitle: "O endereço deste servidor não usa HTTPS", + insecureBody: "O endereço deste servidor é {{address}}. O aplicativo móvel faz login por ele, então ele precisa usar HTTPS, e nenhum código é exibido. Sirva este servidor por HTTPS, defina {{setting}} com o endereço https:// dele, por exemplo {{example}}, e reinicie-o.", unpublishedTitle: "Este servidor não publica seu endereço público", - unpublishedBody: "Nenhum código é exibido: o endereço no seu navegador pode ser um host interno que um celular não consegue acessar. Defina {{setting}} no servidor com o endereço público dele, por exemplo {{example}}, e reinicie-o.", + unpublishedBody: "Nenhum código é exibido: este servidor ainda não oferece seu endereço público ao aplicativo móvel. Atualize o servidor para uma versão compatível.", }, }; diff --git a/ui/packages/i18n/src/locales/ru.ts b/ui/packages/i18n/src/locales/ru.ts index 53db0825744..7e66edeab03 100644 --- a/ui/packages/i18n/src/locales/ru.ts +++ b/ui/packages/i18n/src/locales/ru.ts @@ -5395,8 +5395,10 @@ const ru = { loadFailed: "Не удалось прочитать публичный адрес этого сервера. Перезагрузите страницу, чтобы повторить попытку.", unreachableTitle: "Телефон не может открыть адрес этого сервера", unreachableBody: "Адрес этого сервера — {{address}}: это локальный или частный адрес, который телефон не может открыть, поэтому код не показан. Укажите на сервере в {{setting}} его публичный адрес, например {{example}}, и перезапустите сервер.", + insecureTitle: "Адрес этого сервера не использует HTTPS", + insecureBody: "Адрес этого сервера — {{address}}. Мобильное приложение входит через него, поэтому он должен использовать HTTPS, и код не показан. Настройте работу сервера по HTTPS, укажите в {{setting}} его адрес https://, например {{example}}, и перезапустите сервер.", unpublishedTitle: "Этот сервер не публикует свой публичный адрес", - unpublishedBody: "Код не показан: адрес в вашем браузере может быть внутренним хостом, недоступным для телефона. Укажите на сервере в {{setting}} его публичный адрес, например {{example}}, и перезапустите сервер.", + unpublishedBody: "Код не показан: этот сервер пока не сообщает мобильному приложению свой публичный адрес. Обновите сервер до версии, которая это поддерживает.", }, }; diff --git a/ui/packages/i18n/src/locales/zh-Hans.ts b/ui/packages/i18n/src/locales/zh-Hans.ts index 7c5ba4055f3..ce578417b58 100644 --- a/ui/packages/i18n/src/locales/zh-Hans.ts +++ b/ui/packages/i18n/src/locales/zh-Hans.ts @@ -5161,8 +5161,10 @@ const zh = { loadFailed: "无法读取此服务器的公开地址。请刷新页面重试。", unreachableTitle: "手机无法访问此服务器的地址", unreachableBody: "此服务器的地址是 {{address}},这是手机无法打开的本机或内网地址,因此不显示二维码。请在服务器上将 {{setting}} 设为它的公开地址(例如 {{example}}),然后重启服务器。", + insecureTitle: "此服务器的地址未使用 HTTPS", + insecureBody: "此服务器的地址是 {{address}}。移动应用会通过它登录,因此它必须使用 HTTPS,此处不显示二维码。请让此服务器通过 HTTPS 提供服务,将 {{setting}} 设为它的 https:// 地址(例如 {{example}}),然后重启服务器。", unpublishedTitle: "此服务器未公布其公开地址", - unpublishedBody: "不显示二维码:浏览器中的地址可能是手机无法访问的内部主机。请在服务器上将 {{setting}} 设为它的公开地址(例如 {{example}}),然后重启服务器。", + unpublishedBody: "不显示二维码:此服务器尚未向移动应用提供其公开地址。请将服务器升级到支持此功能的版本。", }, } as const; diff --git a/ui/packages/i18n/src/locales/zh-Hant.ts b/ui/packages/i18n/src/locales/zh-Hant.ts index 8f38b2a9b27..36e42979f00 100644 --- a/ui/packages/i18n/src/locales/zh-Hant.ts +++ b/ui/packages/i18n/src/locales/zh-Hant.ts @@ -5161,8 +5161,10 @@ const zhHant = { loadFailed: "無法讀取此伺服器的公開地址。請重新整理頁面重試。", unreachableTitle: "手機無法訪問此伺服器的地址", unreachableBody: "此伺服器的地址是 {{address}},這是手機無法開啟的本機或內網地址,因此不顯示二維碼。請在伺服器上將 {{setting}} 設為它的公開地址(例如 {{example}}),然後重啟伺服器。", + insecureTitle: "此伺服器的地址未使用 HTTPS", + insecureBody: "此伺服器的地址是 {{address}}。移動應用會通過它登入,因此它必須使用 HTTPS,此處不顯示二維碼。請讓此伺服器通過 HTTPS 提供服務,將 {{setting}} 設為它的 https:// 地址(例如 {{example}}),然後重啟伺服器。", unpublishedTitle: "此伺服器未公佈其公開地址", - unpublishedBody: "不顯示二維碼:瀏覽器中的地址可能是手機無法訪問的內部主機。請在伺服器上將 {{setting}} 設為它的公開地址(例如 {{example}}),然後重啟伺服器。", + unpublishedBody: "不顯示二維碼:此伺服器尚未向移動應用提供其公開地址。請將伺服器升級到支援此功能的版本。", }, } as const; From 0a3b4143440f49332d24174ccebbe950e9015d4d Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 00:33:30 +0000 Subject: [PATCH 07/10] feat(auth): GET /auth/config serves the deployment's public base URL as features.publicBaseUrl Claude-Session: https://claude.ai/code/session_01ADHkmRLqg1PuH8D83b32SV Co-authored-by: Claude --- .changeset/29314-mobile-app-connect-qr.md | 6 +- .../docs/references/api/auth-endpoints.mdx | 2 + .../plugins/plugin-auth/src/auth-manager.ts | 7 ++ .../plugin-auth/src/public-base-url.test.ts | 98 +++++++++++++++++++ .../plugin-auth/src/public-base-url.ts | 23 +++++ packages/spec/authorable-surface/api.json | 1 + packages/spec/src/api/auth-endpoints.zod.ts | 7 ++ .../spec/src/kernel/public-auth-features.ts | 7 +- ui/packages/auth/src/types.ts | 7 +- 9 files changed, 152 insertions(+), 6 deletions(-) create mode 100644 packages/plugins/plugin-auth/src/public-base-url.test.ts create mode 100644 packages/plugins/plugin-auth/src/public-base-url.ts diff --git a/.changeset/29314-mobile-app-connect-qr.md b/.changeset/29314-mobile-app-connect-qr.md index 83ad37f0a8e..d9f3b626102 100644 --- a/.changeset/29314-mobile-app-connect-qr.md +++ b/.changeset/29314-mobile-app-connect-qr.md @@ -3,15 +3,17 @@ '@object-ui/i18n': patch '@object-ui/auth': patch '@objectstack/platform-objects': patch +'@objectstack/spec': patch +'@objectstack/plugin-auth': patch --- feat(console): a Mobile App page in the account app shows the code that connects the ObjectOS mobile app to this server -Clause-②: yes (widening) — a new account-app navigation entry and component (`account:mobile_app`), a new `mobileApp` namespace in the `@object-ui/i18n` packs, and `features.publicBaseUrl` declared on `AuthPublicConfig`; nothing that worked before is refused +Clause-②: yes (widening) — a new account-app navigation entry and component (`account:mobile_app`), a new `mobileApp` namespace in the `@object-ui/i18n` packs, and a new optional `features.publicBaseUrl` served on `GET /api/v1/auth/config` (declared in `AuthFeaturesConfigSchema`, registered in `PUBLIC_AUTH_CONFIG_NON_FLAG_KEYS`, typed on `AuthPublicConfig`); nothing that worked before is refused Metadata-protocol: none The account app (avatar menu → Profile) gains a **Mobile App** entry after Profile. Its page shows a QR code that encodes `objectos://connect?server=`, the same link as copyable text, and one line saying the code holds only the server's address, never the account. -The server URL is the one the server publishes as `features.publicBaseUrl` on `GET /api/v1/auth/config`: the base URL the auth layer builds every link from (`OS_AUTH_URL`, then `BETTER_AUTH_URL`, then `OS_BASE_URL`), with any sub-path mount. The code carries that URL normalised to its scheme, host and path: a username, password, query or fragment in the setting never reaches the code, the link or the page. The browser's own address is never used, because it can be an internal or proxied host. When that URL names `localhost` or a private address, or a public host on plain `http:` (the mobile app signs in through it, so it must be HTTPS), the page shows no code and says how to fix it: set `OS_AUTH_URL` on the server to its public `https://` address and restart it. A server that does not publish the field gets a page saying it does not offer this yet. +`GET /api/v1/auth/config` now serves `features.publicBaseUrl`: the base URL the auth layer builds every link from (`OS_AUTH_URL`, then `BETTER_AUTH_URL`, then `OS_BASE_URL`), with any sub-path mount, as an address only (scheme, host and path; a credential, query or fragment in the setting is never served). The page encodes that URL. The page normalises it the same way again before use, so the code carries the server's address and nothing else. The browser's own address is never used, because it can be an internal or proxied host. When that URL names `localhost` or a private address, or a public host on plain `http:` (the mobile app signs in through it, so it must be HTTPS), the page shows no code and says how to fix it: set `OS_AUTH_URL` on the server to its public `https://` address and restart it. A server that does not publish the field gets a page saying it does not offer this yet. No app-store links are shown: no setting carries them today. diff --git a/content/docs/references/api/auth-endpoints.mdx b/content/docs/references/api/auth-endpoints.mdx index e31eff3e7ce..d4a88b7ee65 100644 --- a/content/docs/references/api/auth-endpoints.mdx +++ b/content/docs/references/api/auth-endpoints.mdx @@ -79,6 +79,7 @@ const result = AuthEndpointSchema.parse(data); | **admin** | `boolean` | optional | Admin plugin wired (forced on whenever SCIM is enabled), so creating and impersonating users is available; the console shows those actions only when it is true. Banning, unbanning, unlocking and setting a password answer without it; the console still shows its unlock and set-password actions only when it is true. Absent means not wired | | **termsUrl** | `string` | optional | Terms-of-service link shown beneath the login and register cards: the trimmed OS_TERMS_URL value when set, otherwise the public ObjectStack terms page; absent when the operator set OS_TERMS_URL to an empty or blank (whitespace-only) value to suppress the link | | **privacyUrl** | `string` | optional | Privacy-policy link shown beneath the login and register cards: the trimmed OS_PRIVACY_URL value when set, otherwise the public ObjectStack privacy page; absent when the operator set OS_PRIVACY_URL to an empty or blank (whitespace-only) value to suppress the link | +| **publicBaseUrl** | `string` | optional | This deployment's public base URL, the one the auth layer builds every link it hands out on: the configured baseUrl (OS_AUTH_URL, then BETTER_AUTH_URL, then OS_BASE_URL) with any sub-path it carries, https:// prepended to a bare host, and the loopback fallback when none is set. Served as an address only: scheme, host and path, with no trailing slash, credentials, query or fragment. The console encodes it in the mobile-app connect code, and refuses to when it names a loopback or private address or a public host on plain http. Absent when the configured value is not an absolute URL | ### Nested Shape: `AuthFeaturesConfig.organizationEditions[number]` @@ -230,6 +231,7 @@ This schema accepts one of the following structures: | **admin** | `boolean` | optional | Admin plugin wired (forced on whenever SCIM is enabled), so creating and impersonating users is available; the console shows those actions only when it is true. Banning, unbanning, unlocking and setting a password answer without it; the console still shows its unlock and set-password actions only when it is true. Absent means not wired | | **termsUrl** | `string` | optional | Terms-of-service link shown beneath the login and register cards: the trimmed OS_TERMS_URL value when set, otherwise the public ObjectStack terms page; absent when the operator set OS_TERMS_URL to an empty or blank (whitespace-only) value to suppress the link | | **privacyUrl** | `string` | optional | Privacy-policy link shown beneath the login and register cards: the trimmed OS_PRIVACY_URL value when set, otherwise the public ObjectStack privacy page; absent when the operator set OS_PRIVACY_URL to an empty or blank (whitespace-only) value to suppress the link | +| **publicBaseUrl** | `string` | optional | This deployment's public base URL, the one the auth layer builds every link it hands out on: the configured baseUrl (OS_AUTH_URL, then BETTER_AUTH_URL, then OS_BASE_URL) with any sub-path it carries, https:// prepended to a bare host, and the loopback fallback when none is set. Served as an address only: scheme, host and path, with no trailing slash, credentials, query or fragment. The console encodes it in the mobile-app connect code, and refuses to when it names a loopback or private address or a public host on plain http. Absent when the configured value is not an absolute URL | --- diff --git a/packages/plugins/plugin-auth/src/auth-manager.ts b/packages/plugins/plugin-auth/src/auth-manager.ts index 14c267f6a2a..8e8d59db59d 100644 --- a/packages/plugins/plugin-auth/src/auth-manager.ts +++ b/packages/plugins/plugin-auth/src/auth-manager.ts @@ -319,6 +319,7 @@ import { // with it. import { buildPluginList, type PluginListHost } from './auth-manager-plugin-list.js'; import { resolveTurnstileKeys } from './turnstile-sign-up.js'; +import { publicBaseUrlOf } from './public-base-url.js'; import { assertTrustedAppSchemes, registeredAppSchemesOf } from './one-time-token-handoff.js'; import type { MintScimConnectionCredentialInput, MintedScimConnectionCredential } from './scim-connection-service.js'; import type { OrganizationBoundaryJudge } from './scim-group-projection.js'; @@ -5867,6 +5868,7 @@ export class AuthManager { }; const termsUrl = resolveLegalUrl(rawTermsUrl, DEFAULT_TERMS_URL); const privacyUrl = resolveLegalUrl(rawPrivacyUrl, DEFAULT_PRIVACY_URL); + const publicBaseUrl = publicBaseUrlOf(this.getCanonicalOrigin()); const turnstileKeys = resolveTurnstileKeys(); const organizationEditions = this.resolveOrganizationEditions(request); @@ -5957,6 +5959,11 @@ export class AuthManager { ...(directSignIn.enabled ? { localSignIn: directSignIn.localSignIn } : {}), ...(termsUrl ? { termsUrl } : {}), ...(privacyUrl ? { privacyUrl } : {}), + // The public base URL every emailed / OAuth link is built on + // (`getCanonicalOrigin`), reduced to its address, so the console's + // mobile-app connect code never reads `window.location` for it + // (registered in PUBLIC_AUTH_CONFIG_NON_FLAG_KEYS). + ...(publicBaseUrl ? { publicBaseUrl } : {}), // The PUBLIC Turnstile site key, served only when the sign-up challenge // is wired (both keys set; the resolver `buildPluginList()` mounts the // plugin from). The secret is never part of this payload. diff --git a/packages/plugins/plugin-auth/src/public-base-url.test.ts b/packages/plugins/plugin-auth/src/public-base-url.test.ts new file mode 100644 index 00000000000..1fec111fd0c --- /dev/null +++ b/packages/plugins/plugin-auth/src/public-base-url.test.ts @@ -0,0 +1,98 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * `GET /auth/config` serves `features.publicBaseUrl`: the canonical origin + * every link the auth layer hands out is built on (`getCanonicalOrigin`), sub- + * path included, reduced to its address. The console's mobile-app connect page + * encodes it, so the door being anonymous means a credential in the configured + * base URL must never reach it. + * + * The door case drives the REAL `registerAuthRoutes` on a REAL Hono app over a + * REAL `AuthManager`, as `auth-config-request-language.test.ts` does. + */ + +import { describe, it, expect, vi } from 'vitest'; +import { Hono } from 'hono'; +import type { PluginContext } from '@objectstack/core'; +import { AuthPlugin } from './auth-plugin'; +import { AuthManager } from './auth-manager'; +import { publicBaseUrlOf } from './public-base-url'; + +const SECRET = 'test-secret-at-least-32-chars-long!!'; + +function manager(baseUrl?: string): AuthManager { + const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {}); + try { + return new AuthManager({ secret: SECRET, ...(baseUrl === undefined ? {} : { baseUrl }) }); + } finally { + warnSpy.mockRestore(); + } +} + +function mountDoor(baseUrl: string) { + const app = new Hono(); + const ctx = { + registerService: vi.fn(), + getService: vi.fn(), + getServices: vi.fn(() => new Map()), + hook: vi.fn(), + trigger: vi.fn(), + logger: { info: vi.fn(), warn: vi.fn(), debug: vi.fn(), error: vi.fn() }, + getKernel: vi.fn(), + } as unknown as PluginContext; + const plugin = new AuthPlugin({ secret: SECRET, baseUrl } as any); + (plugin as any).authManager = manager(baseUrl); + (plugin as any).registerAuthRoutes({ getRawApp: () => app, getPort: () => 0 }, ctx); + return app; +} + +describe('GET /api/v1/auth/config serves features.publicBaseUrl over the real door', () => { + it('the configured base URL, sub-path included', async () => { + const app = mountDoor('https://os.acme.example/platform'); + + const res = await app.request('https://os.acme.example/api/v1/auth/config'); + + expect(res.status).toBe(200); + const body = await res.json(); + expect(body.data.features.publicBaseUrl).toBe('https://os.acme.example/platform'); + }); + + it('a credential, query or fragment in the configured base URL is not served', async () => { + const app = mountDoor('https://ops:s3cret@os.acme.example/platform/?token=abc#x'); + + const res = await app.request('https://os.acme.example/api/v1/auth/config'); + + expect(res.status).toBe(200); + const text = await res.text(); + expect(JSON.parse(text).data.features.publicBaseUrl).toBe('https://os.acme.example/platform'); + expect(text).not.toMatch(/s3cret|token=abc/); + }); +}); + +describe('getPublicConfig().features.publicBaseUrl', () => { + it('follows getCanonicalOrigin: a bare host gains https://, a trailing slash goes', () => { + expect(manager('os.acme.example').getPublicConfig().features.publicBaseUrl).toBe('https://os.acme.example'); + expect(manager('https://os.acme.example/').getPublicConfig().features.publicBaseUrl).toBe('https://os.acme.example'); + }); + + it('CONTROL: with no base URL set it is the loopback fallback, which the console refuses to encode', () => { + expect(manager().getPublicConfig().features.publicBaseUrl).toBe('http://localhost:3000'); + }); +}); + +describe('publicBaseUrlOf', () => { + it.each([ + ['https://os.acme.example', 'https://os.acme.example'], + ['https://os.acme.example:8443/os', 'https://os.acme.example:8443/os'], + ['https://os.acme.example:443/os', 'https://os.acme.example/os'], + ['HTTPS://OS.Acme.Example/os/', 'https://os.acme.example/os'], + ['https://ops@os.acme.example', 'https://os.acme.example'], + ])('%s → %s', (origin, served) => { + expect(publicBaseUrlOf(origin)).toBe(served); + }); + + it('a value that is not an absolute URL is not served', () => { + expect(publicBaseUrlOf('https://bad host')).toBeUndefined(); + expect(publicBaseUrlOf('not a url')).toBeUndefined(); + }); +}); diff --git a/packages/plugins/plugin-auth/src/public-base-url.ts b/packages/plugins/plugin-auth/src/public-base-url.ts new file mode 100644 index 00000000000..a8d3aa1a792 --- /dev/null +++ b/packages/plugins/plugin-auth/src/public-base-url.ts @@ -0,0 +1,23 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The public base URL `GET /auth/config` serves as `features.publicBaseUrl`, + * from the canonical origin every link the auth layer hands out is built on. + * + * The door is anonymous, so only the ADDRESS is served: scheme, host (with a + * non-default port) and path, no trailing slash. A username, password, query + * or fragment in the configured base URL is dropped. A value that does not + * parse as an absolute URL is not served at all (`undefined`), so the console + * reads it as "this server does not offer an address" rather than encoding a + * broken one. + */ +export function publicBaseUrlOf(canonicalOrigin: string): string | undefined { + let url: URL; + try { + url = new URL(canonicalOrigin); + } catch { + return undefined; + } + if (!url.host) return undefined; + return `${url.protocol}//${url.host}${url.pathname.replace(/\/+$/, '')}`; +} diff --git a/packages/spec/authorable-surface/api.json b/packages/spec/authorable-surface/api.json index 5430bf051fe..c9e224e9290 100644 --- a/packages/spec/authorable-surface/api.json +++ b/packages/spec/authorable-surface/api.json @@ -227,6 +227,7 @@ "api/AuthFeaturesConfig:phoneNumber", "api/AuthFeaturesConfig:phoneNumberOtp", "api/AuthFeaturesConfig:privacyUrl", + "api/AuthFeaturesConfig:publicBaseUrl", "api/AuthFeaturesConfig:sso", "api/AuthFeaturesConfig:ssoEnforced", "api/AuthFeaturesConfig:tenancyPosture", diff --git a/packages/spec/src/api/auth-endpoints.zod.ts b/packages/spec/src/api/auth-endpoints.zod.ts index 7eaaa47eab3..71243bcd2c5 100644 --- a/packages/spec/src/api/auth-endpoints.zod.ts +++ b/packages/spec/src/api/auth-endpoints.zod.ts @@ -375,6 +375,13 @@ export const AuthFeaturesConfigSchema = lazySchema(() => z.object({ privacyUrl: z.string().optional().describe( 'Privacy-policy link shown beneath the login and register cards: the trimmed OS_PRIVACY_URL value when set, otherwise the public ObjectStack privacy page; absent when the operator set OS_PRIVACY_URL to an empty or blank (whitespace-only) value to suppress the link', ), + publicBaseUrl: z.string().optional().describe( + 'This deployment\'s public base URL, the one the auth layer builds every link it hands out on: the configured baseUrl ' + + '(OS_AUTH_URL, then BETTER_AUTH_URL, then OS_BASE_URL) with any sub-path it carries, https:// prepended to a bare host, ' + + 'and the loopback fallback when none is set. Served as an address only: scheme, host and path, with no trailing slash, ' + + 'credentials, query or fragment. The console encodes it in the mobile-app connect code, and refuses to when it names a ' + + 'loopback or private address or a public host on plain http. Absent when the configured value is not an absolute URL', + ), })); /** diff --git a/packages/spec/src/kernel/public-auth-features.ts b/packages/spec/src/kernel/public-auth-features.ts index 644544c4e24..715011845f3 100644 --- a/packages/spec/src/kernel/public-auth-features.ts +++ b/packages/spec/src/kernel/public-auth-features.ts @@ -406,8 +406,13 @@ export const PUBLIC_AUTH_FEATURE_NAMES = Object.keys(PUBLIC_AUTH_FEATURES) as [ * start, or when the setting was turned on after start-up and the door is not * mounted). It gates no spec input and changes no server door: the server's * password sign-in is the same either way. + * + * `publicBaseUrl` is the deployment's public base URL (the canonical origin + * every link the auth layer hands out is built on, sub-path included), served + * as an address only. Its reader is the console's mobile-app connect page, + * which encodes it in the connect code. It gates no spec input. */ -export const PUBLIC_AUTH_CONFIG_NON_FLAG_KEYS = ['termsUrl', 'privacyUrl', 'tenancyPosture', 'audiencePosture', 'turnstileSiteKey', 'organizationEditions', 'localSignIn'] as const; +export const PUBLIC_AUTH_CONFIG_NON_FLAG_KEYS = ['termsUrl', 'privacyUrl', 'tenancyPosture', 'audiencePosture', 'turnstileSiteKey', 'organizationEditions', 'localSignIn', 'publicBaseUrl'] as const; /** * Capabilities that are RESERVED but deliberately **not advertised** — the diff --git a/ui/packages/auth/src/types.ts b/ui/packages/auth/src/types.ts index 51b61f0d301..32c5bc57503 100644 --- a/ui/packages/auth/src/types.ts +++ b/ui/packages/auth/src/types.ts @@ -449,9 +449,10 @@ export interface AuthPublicConfig { * This deployment's public base URL, as the auth layer composes every link * it hands out: the configured base URL (`OS_AUTH_URL`, then * `BETTER_AUTH_URL`, then `OS_BASE_URL`) with any sub-path it carries, or - * the loopback fallback when none is set. The account app's Mobile App - * page encodes it in the connect code, never the browser's own address. - * Absent from a server that does not publish it. + * the loopback fallback when none is set, served as an address only + * (scheme, host, path). The account app's Mobile App page encodes it in + * the connect code, never the browser's own address. Absent from a server + * that does not publish it. */ publicBaseUrl?: string; }; From e94ccfa2e793636b558ea7326dd455aba1c56c1e Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 00:33:47 +0000 Subject: [PATCH 08/10] chore: grade the changeset for the new auth config key Claude-Session: https://claude.ai/code/session_01ADHkmRLqg1PuH8D83b32SV Co-authored-by: Claude --- .changeset/29314-mobile-app-connect-qr.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/.changeset/29314-mobile-app-connect-qr.md b/.changeset/29314-mobile-app-connect-qr.md index d9f3b626102..c7b7907d91c 100644 --- a/.changeset/29314-mobile-app-connect-qr.md +++ b/.changeset/29314-mobile-app-connect-qr.md @@ -2,15 +2,15 @@ '@object-ui/app-shell': patch '@object-ui/i18n': patch '@object-ui/auth': patch -'@objectstack/platform-objects': patch -'@objectstack/spec': patch -'@objectstack/plugin-auth': patch +'@objectstack/platform-objects': minor +'@objectstack/spec': minor +'@objectstack/plugin-auth': minor --- feat(console): a Mobile App page in the account app shows the code that connects the ObjectOS mobile app to this server Clause-②: yes (widening) — a new account-app navigation entry and component (`account:mobile_app`), a new `mobileApp` namespace in the `@object-ui/i18n` packs, and a new optional `features.publicBaseUrl` served on `GET /api/v1/auth/config` (declared in `AuthFeaturesConfigSchema`, registered in `PUBLIC_AUTH_CONFIG_NON_FLAG_KEYS`, typed on `AuthPublicConfig`); nothing that worked before is refused -Metadata-protocol: none +Metadata-protocol: added The account app (avatar menu → Profile) gains a **Mobile App** entry after Profile. Its page shows a QR code that encodes `objectos://connect?server=`, the same link as copyable text, and one line saying the code holds only the server's address, never the account. From cacb7dd196fd74742b569ff11b02b1724645a0c7 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 00:51:42 +0000 Subject: [PATCH 09/10] test: the served auth config fixtures carry features.publicBaseUrl Claude-Session: https://claude.ai/code/session_01ADHkmRLqg1PuH8D83b32SV Co-authored-by: Claude --- packages/plugins/plugin-auth/src/auth-manager.test.ts | 3 +++ packages/spec/src/api/auth-endpoints.test.ts | 1 + 2 files changed, 4 insertions(+) diff --git a/packages/plugins/plugin-auth/src/auth-manager.test.ts b/packages/plugins/plugin-auth/src/auth-manager.test.ts index bc49d363369..3745f147f25 100644 --- a/packages/plugins/plugin-auth/src/auth-manager.test.ts +++ b/packages/plugins/plugin-auth/src/auth-manager.test.ts @@ -3241,6 +3241,9 @@ describe('AuthManager', () => { developerEditionCreate: false, privacyUrl: 'https://objectstack.ai/privacy', termsUrl: 'https://objectstack.ai/terms', + // The configured base URL as an address, for the console's mobile-app + // connect code (which refuses this loopback one). + publicBaseUrl: 'http://localhost:3000', }); }); diff --git a/packages/spec/src/api/auth-endpoints.test.ts b/packages/spec/src/api/auth-endpoints.test.ts index 0cc9f799e9e..6b534342e9e 100644 --- a/packages/spec/src/api/auth-endpoints.test.ts +++ b/packages/spec/src/api/auth-endpoints.test.ts @@ -244,6 +244,7 @@ describe('AuthFeaturesConfig declares every classified served key', () => { termsUrl: 'https://objectstack.ai/terms', privacyUrl: 'https://objectstack.ai/privacy', turnstileSiteKey: '0x4AAAAAAA', + publicBaseUrl: 'https://os.acme.example/platform', } as const; it('the served fixture names every classified key, so the parse below covers them all', () => { From 7c7c5ba446dca6b4aa6a43349da72d856c8b24ee Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 01:31:44 +0000 Subject: [PATCH 10/10] test(console): pay the lint load at collection in the mobile app page test Claude-Session: https://claude.ai/code/session_01ADHkmRLqg1PuH8D83b32SV Co-authored-by: Claude --- .../app-shell/src/console/mobile-app/MobileAppPage.test.tsx | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/ui/packages/app-shell/src/console/mobile-app/MobileAppPage.test.tsx b/ui/packages/app-shell/src/console/mobile-app/MobileAppPage.test.tsx index 4bc0e946de7..0138de406bb 100644 --- a/ui/packages/app-shell/src/console/mobile-app/MobileAppPage.test.tsx +++ b/ui/packages/app-shell/src/console/mobile-app/MobileAppPage.test.tsx @@ -35,6 +35,10 @@ vi.mock('@object-ui/auth', async (importOriginal) => ({ import { MobileAppPage } from './MobileAppPage'; import { builtInLocales } from '@object-ui/i18n/locales'; import { getAppComponent } from '../../services/componentRegistry'; +// The registry check below loads every built-in page, which reaches the +// metadata admin's dynamic `@objectstack/lint` import: pay that load at +// collection, never inside a test's clocked window. +import '@objectstack/lint'; import '../../services/builtinComponents'; function serving(features: Record | undefined) {