FIX - complete LB custom app compatibility (#11)

* FIX - preserve LB custom app lifecycle

* FIX - reset LB export aliases before startup

* FIX - report competing custom app providers

* FIX - identify LB app frames as live NUI

* FIX - complete LB custom app compatibility

* FIX - provide LB PicChat runtime exports

* FIX - route LB PicChat through Sky Phone

* FIX - return cached LB equipped phone number

* FIX - harden PicChat compatibility migration

* ENH - complete modular phone provider and Creator APIs

* DOC - document the Sky Phone Creator API

---------

Co-authored-by: DerEchteAlec <bycraky@gmail.com>
Co-authored-by: DerEchteAlec <alec.schitzkat@luwan.io>
This commit is contained in:
Leon.Schmidt
2026-08-20 18:19:16 +02:00
committed by GitHub
parent 9aec3eefef
commit 30559048fd
91 changed files with 11860 additions and 2943 deletions
+60 -2
View File
@@ -51,7 +51,7 @@ import { useMarketplaceStore } from '@/stores/marketplace'
import { useAppCatalogStore } from '@/stores/app-catalog'
import { useAppStoreStore } from '@/stores/app-store'
import { useWidgetsStore } from '@/stores/widgets'
import { isPhoneAppId } from '@/config/apps'
import { isPhoneAppId, PHONE_APPS } from '@/config/apps'
import { useNotesStore } from '@/stores/notes'
import { useMemosStore } from '@/stores/memos'
import { useWeatherStore } from '@/stores/weather'
@@ -106,6 +106,7 @@ type AppMessage = {
| PhoneOpenPayload
| CustomAppCatalogEventData
| CustomAppEventData
| NavigationEventData
}
type CustomAppCatalogEventData = {
@@ -118,6 +119,10 @@ type CustomAppEventData = {
payload?: unknown
}
type NavigationEventData = {
appId?: unknown
}
type SimPickerPayload = {
choices: SimPhoneChoice[]
number: string
@@ -494,6 +499,23 @@ function hydratePhone(payload: PhoneOpenPayload): void {
widgets.hydrate(payload.device?.data.widgets?.payload)
}
function getInstalledNavigationAppIds(): string[] {
const installedAppIds: string[] = []
for (const app of PHONE_APPS) {
if (isPhoneAppId(app.id) && appStore.isInstalled(app.id)) {
installedAppIds.push(app.id)
}
}
return installedAppIds
}
function syncNavigationState(): ReturnType<typeof nuiCall> {
return nuiCall('navigation:state', {
currentApp: activeAppId.value || null,
installedApps: getInstalledNavigationAppIds(),
})
}
function cancelUnlockedPhoneDataLoad(): void {
if (unlockedServicesIdle === undefined) return
if (typeof window.cancelIdleCallback === 'function') {
@@ -711,9 +733,33 @@ function onMessage(event: MessageEvent<AppMessage>): void {
if (typeof data?.appId === 'string' && route.params.appId === data.appId) {
void router.push('/')
}
} else if (event.data?.type === 'navigation:open-app') {
const data = event.data.data as NavigationEventData | undefined
if (
typeof data?.appId === 'string' &&
isPhoneAppId(data.appId) &&
appStore.isInstalled(data.appId)
) {
void router.push(`/apps/${data.appId}`)
} else {
console.error('[Navigation] Ignored an unavailable app target.')
}
} else if (event.data?.type === 'navigation:close-app') {
const data = event.data.data as NavigationEventData | undefined
const currentApp = route.params.appId
if (data?.appId === undefined || currentApp === data.appId) {
void router.push('/')
}
} else if (event.data?.type === 'compat:open-messages') {
const data = event.data.data as MessagesEventData | undefined
if (typeof data?.phoneNumber === 'string') {
void messages.openThread(data.phoneNumber).then((opened) => {
if (opened) void router.push('/apps/messages')
})
}
} else if (event.data?.type === 'app:open') {
hydratePhone(event.data.data as PhoneOpenPayload)
void nuiCall('ui:opened')
void syncNavigationState().then(() => nuiCall('ui:opened'))
} else if (event.data?.type === 'device:updated') {
hydratePhone(event.data.data as PhoneOpenPayload)
} else if (event.data?.type === 'app:close') {
@@ -1522,6 +1568,18 @@ watch(
},
)
watch(
() => ({
appIds: getInstalledNavigationAppIds(),
currentApp: activeAppId.value,
open: phone.isOpen,
}),
() => {
if (phone.isOpen && appStore.hydrated) void syncNavigationState()
},
{ deep: true },
)
watch(
() => notifications.requiresAttention,
(requiresAttention) => {
@@ -3,7 +3,7 @@ import { readFileSync } from 'node:fs'
import { describe, expect, it } from 'vitest'
const client = readFileSync(
new URL('../../sky_phone/source/client/main.lua', import.meta.url),
new URL('../../sky_phone/source/client/nui_server_bridge.lua', import.meta.url),
'utf8',
).replace(/\r\n/g, '\n')
const companiesServer = readFileSync(
@@ -32,7 +32,7 @@ function sourceBlock(source: string, startMarker: string, endMarker: string) {
describe('Companies outbound service-line call contract', () => {
it('exposes the dedicated callback through the NUI client bridge', () => {
expect(client).toContain(`${quote}companies:dial-service-line${quote}`)
expect(client).toMatch(/companies\s*=\s*\[\[[^\]]*dial-service-line/)
})
it('accepts only a target number and derives the company from the live server member', () => {
@@ -0,0 +1,28 @@
import { readFileSync } from 'node:fs'
import { describe, expect, it } from 'vitest'
const frame = readFileSync(
new URL('./CustomAppFrame.vue', import.meta.url),
'utf8',
)
const appTypes = readFileSync(
new URL('../types/apps.ts', import.meta.url),
'utf8',
)
describe('Custom app frame context permissions', () => {
it('only exposes locale and theme context when their capabilities are granted', () => {
expect(frame).toContain("capabilities.includes('theme.read')")
expect(frame).toContain("capabilities.includes('locale.read')")
expect(frame).toMatch(
/capabilities\.includes\('theme\.read'\)[\s\S]*colorScheme/,
)
expect(frame).toMatch(
/capabilities\.includes\('locale\.read'\)[\s\S]*language:[\s\S]*locale:/,
)
expect(appTypes).toContain("colorScheme?: 'dark' | 'light'")
expect(appTypes).toContain('language?: string')
expect(appTypes).toContain('locale?: Record<string, unknown>')
})
})
+114 -13
View File
@@ -10,6 +10,8 @@ import { useRouter } from 'vue-router'
import { getPhoneApp, isExternalPhoneApp } from '@/config/apps'
import { useAppCatalogStore } from '@/stores/app-catalog'
import { useCallsStore } from '@/stores/calls'
import { useMessagesStore } from '@/stores/messages'
import { useNotificationsStore } from '@/stores/notifications'
import { usePhoneStore } from '@/stores/phone'
import type {
@@ -33,13 +35,18 @@ import {
getCustomAppSafeArea,
} from '@/utils/customAppLifecycle'
import {
LB_PHONE_STORAGE_MESSAGE_TYPE,
LB_PHONE_ACTION_MESSAGE_TYPE,
createLbPhoneFrameDocument,
createLbPhoneHostSettings,
getLbPhoneCallbackResource,
readLbPhoneStorage,
usesLbPhoneHostRuntime,
writeLbPhoneStorage,
} from '@/utils/lbPhoneAppBridge'
import { cloneJsonData } from '@/utils/clone'
import { nuiCall } from '@/utils/nui'
import type { PhoneCall } from '@/types/phone'
const props = defineProps<{
app: ExternalPhoneAppDefinition
@@ -48,6 +55,8 @@ const props = defineProps<{
const PROTOCOL_VERSION = 1
const catalog = useAppCatalogStore()
const calls = useCallsStore()
const messages = useMessagesStore()
const notifications = useNotificationsStore()
const phone = usePhoneStore()
const router = useRouter()
@@ -128,19 +137,28 @@ const frameReady = computed(
frameLoaded.value &&
(props.app.bridgeMode === 'legacy' || skyBridgeReady.value),
)
const context = computed<SkyPhoneAppContextV1>(() => ({
appId: props.app.id,
capabilities: getSkyPhoneAppCapabilities(props.app.capabilities),
colorScheme: phone.isDarkMode ? 'dark' : 'light',
language: phone.lang,
locale: {
description: props.app.description,
name: props.app.name,
},
phoneScale: phone.preferences.settings.phoneScale / 100,
protocolVersion: PROTOCOL_VERSION,
safeArea: getCustomAppSafeArea(props.app.orientation),
}))
const context = computed<SkyPhoneAppContextV1>(() => {
const capabilities = getSkyPhoneAppCapabilities(props.app.capabilities)
return {
appId: props.app.id,
capabilities,
...(capabilities.includes('theme.read')
? { colorScheme: phone.isDarkMode ? ('dark' as const) : ('light' as const) }
: {}),
...(capabilities.includes('locale.read')
? {
language: phone.lang,
locale: {
description: props.app.description,
name: props.app.name,
},
}
: {}),
phoneScale: phone.preferences.settings.phoneScale / 100,
protocolVersion: PROTOCOL_VERSION,
safeArea: getCustomAppSafeArea(props.app.orientation),
}
})
const lbSettings = computed(() =>
createLbPhoneHostSettings({
deviceName: phone.device?.name ?? '',
@@ -191,6 +209,16 @@ async function prepareLbFrameDocument(): Promise<void> {
const controller = new AbortController()
frameDocumentController = controller
try {
let appStorage = {}
try {
appStorage = readLbPhoneStorage(window.localStorage, props.app.id)
} catch (error) {
console.error(
`[Custom apps] Could not read LB Phone storage for ${props.app.id}.`,
error,
)
}
const response = await fetch(frameUrl.value, {
credentials: 'omit',
signal: controller.signal,
@@ -201,6 +229,7 @@ async function prepareLbFrameDocument(): Promise<void> {
const html = await response.text()
lbFrameDocument.value = createLbPhoneFrameDocument(html, {
appName: props.app.id,
localStorage: appStorage,
resourceName: getLbPhoneCallbackResource(props.app),
settings: lbSettings.value,
ui: props.app.ui,
@@ -282,6 +311,55 @@ async function handleBridgeRequest(
}
}
async function handleLbPhoneAction(message: Record<string, unknown>) {
if (message.action === 'createCall') {
const options = message.options
if (!options || typeof options !== 'object' || Array.isArray(options)) {
console.error(
`[Custom apps] Rejected invalid LB call action from ${props.app.id}.`,
)
return
}
const target = options as Record<string, unknown>
if (
typeof target.number !== 'string' &&
typeof target.company !== 'string'
) {
console.error(
`[Custom apps] Rejected invalid LB call target from ${props.app.id}.`,
)
return
}
const response = await nuiCall<PhoneCall>('calls:dial', {
company: target.company,
phoneNumber: target.number,
})
if (response.success && response.data) calls.applyCallState(response.data)
return
}
if (message.action === 'createSMS') {
const options = message.options
const phoneNumber =
typeof options === 'string'
? options
: options && typeof options === 'object' && !Array.isArray(options)
? ((options as Record<string, unknown>).number ??
(options as Record<string, unknown>).phoneNumber)
: undefined
if (
typeof phoneNumber !== 'string' ||
!(await messages.openThread(phoneNumber))
) {
console.error(
`[Custom apps] Rejected invalid LB SMS target from ${props.app.id}.`,
)
return
}
void router.push('/apps/messages')
}
}
function isTrustedFrameMessage(event: MessageEvent): boolean {
if (event.source !== frame.value?.contentWindow) return false
if (props.app.bundled || lbHostRuntime.value) {
@@ -308,6 +386,29 @@ function onFrameMessage(event: MessageEvent): void {
return
}
if (message.type === LB_PHONE_STORAGE_MESSAGE_TYPE) {
try {
if (
!writeLbPhoneStorage(window.localStorage, props.app.id, message.storage)
) {
console.error(
`[Custom apps] Rejected invalid LB Phone storage for ${props.app.id}.`,
)
}
} catch (error) {
console.error(
`[Custom apps] Could not persist LB Phone storage for ${props.app.id}.`,
error,
)
}
return
}
if (message.type === LB_PHONE_ACTION_MESSAGE_TYPE) {
void handleLbPhoneAction(message)
return
}
if (message.type === 'sky-phone-app:ready') {
if (!skyBridgeReady.value) {
if (loadTimeout !== undefined) clearTimeout(loadTimeout)
@@ -0,0 +1,62 @@
import { readFileSync } from 'node:fs'
import { describe, expect, it } from 'vitest'
const readResourceFile = (path: string) =>
readFileSync(new URL(`../../sky_phone/${path}`, import.meta.url), 'utf8')
describe('LB runtime compatibility contracts', () => {
it('routes legacy call and SMS actions through Sky Phone', () => {
const callsClient = readResourceFile('source/client/calls.lua')
const phoneBridge = readResourceFile('source/bridge/phones/client/lb.lua')
const callsServer = readResourceFile('source/server/calls.lua')
const phoneUi = readFileSync(new URL('./App.vue', import.meta.url), 'utf8')
const customAppFrame = readFileSync(
new URL('./components/CustomAppFrame.vue', import.meta.url),
'utf8',
)
expect(phoneBridge).toContain(
'SkyPhoneCompatibility.RegisterExportAlias("lb-phone", "CreateCall", create_call)',
)
expect(callsClient).toContain(
'Bridge.Callbacks.Trigger("sky_phone:calls:dial"',
)
expect(callsServer).toContain(
'SkyPhoneCompanies.GetServiceLineForCompany(data.company)',
)
expect(phoneBridge).toContain(
'SkyPhoneCompatibility.RegisterExportAlias("lb-phone", "CreateSMS", create_sms)',
)
expect(phoneBridge).toContain('type = "compat:open-messages"')
expect(phoneUi).toContain("event.data?.type === 'compat:open-messages'")
expect(phoneUi).toContain('messages.openThread(data.phoneNumber)')
expect(customAppFrame).toContain("message.action === 'createCall'")
expect(customAppFrame).toContain("message.action === 'createSMS'")
})
it('redirects PicChat phone identity to the Sky SIM table without deleting orphaned data', () => {
const manifest = readResourceFile('fxmanifest.lua')
const migration = readResourceFile(
'source/server/lb_app_compat_migration.lua',
)
expect(manifest).toContain("'source/server/lb_app_compat_migration.lua'")
expect(
manifest.indexOf("'source/server/lb_app_compat_migration.lua'"),
).toBeGreaterThan(manifest.indexOf("'source/server/testdata.lua'"))
expect(migration).toContain('"lbpicchat_logged_in"')
expect(migration).toContain('"phone_phones"')
expect(migration).toContain('"sky_phone_sims"')
expect(migration).toContain('DROP FOREIGN KEY')
expect(migration).toContain('ON DELETE CASCADE ON UPDATE CASCADE')
expect(migration).toContain('Legacy data was preserved')
expect(migration).toContain('FROM `INFORMATION_SCHEMA`.`KEY_COLUMN_USAGE`')
expect(migration).not.toMatch(/KEY_COLUMN_USAGE`\s+keys/i)
expect(migration).toContain(
'xpcall(migrate_picchat_phone_reference, debug.traceback)',
)
expect(migration).toContain('Sky Phone startup will continue')
expect(migration).not.toMatch(/DELETE\s+FROM\s+/i)
})
})
+158 -2
View File
@@ -4,6 +4,8 @@ import { describe, expect, it } from 'vitest'
const readResourceFile = (path: string) =>
readFileSync(new URL(`../../sky_phone/${path}`, import.meta.url), 'utf8')
const readFrontendFile = (path: string) =>
readFileSync(new URL(path, import.meta.url), 'utf8')
const inventoryAdapters = [
['ox', 'source/bridge/server/inventory/ox.lua'],
@@ -52,11 +54,165 @@ describe('phone inventory contracts', () => {
it('provides the LB IsOpen export alias from the authoritative client state', () => {
const phoneClient = readResourceFile('source/client/main.lua')
const phoneBridge = readResourceFile('source/bridge/phones/client/lb.lua')
expect(phoneClient).toContain(
expect(phoneBridge).toContain(
'SkyPhoneCompatibility.RegisterExportAlias("lb-phone", "IsOpen"',
)
expect(phoneClient).toContain('return is_open')
expect(phoneClient).toContain('open = is_open')
expect(phoneBridge).toContain('return get_phone_state_value("open")')
})
it('provides the LB equipped phone number exports from authoritative device state', () => {
const phoneClient = readResourceFile('source/client/main.lua')
const phoneServer = readResourceFile('source/server/phone.lua')
const clientBridge = readResourceFile('source/bridge/phones/client/lb.lua')
const serverBridge = readResourceFile('source/bridge/phones/server/lb.lua')
const serverLifecycle = readResourceFile(
'source/bridge/phones/server/lifecycle.lua',
)
expect(clientBridge).toMatch(
/"GetEquippedPhoneNumber",\s+phone\.GetEquippedPhoneNumber/,
)
expect(phoneClient).toContain('return device_payload.device.sim.number')
expect(phoneClient).toContain(
'Bridge.Callbacks.Trigger("sky_phone:device:equipped-number", {})',
)
expect(phoneServer).toContain(
'Bridge.Callbacks.Register("sky_phone:device:equipped-number", function(source)',
)
expect(phoneServer).toContain(
'function SkyPhone.GetEquippedPhoneNumber(player)',
)
expect(phoneServer).toContain(
'cache_equipped_phone_number(source, identifier, device.phone_number)',
)
expect(phoneServer).toContain(
'equipped_phone_sources[phone_number] = source',
)
const equippedNumberExport = phoneServer.match(
/function SkyPhone\.GetEquippedPhoneNumber\(player\)([\s\S]*?)\nfunction SkyPhone\.GetSourceFromNumber/,
)?.[1]
const equippedNumberResolver = phoneServer.match(
/local function resolve_equipped_phone_number\(source\)([\s\S]*?)\nfunction SkyPhone\.GetEquippedPhoneNumber/,
)?.[1]
expect(equippedNumberExport).toBeDefined()
expect(equippedNumberResolver).toBeDefined()
expect(equippedNumberExport).toContain('type(player) == "number"')
expect(equippedNumberExport).toContain('online_source_for_identifier(player)')
expect(phoneServer).toContain('Bridge.Inventory.GetSlotsWithItem(source, Config.Phone.Item)')
expect(phoneServer).toContain('return resolve_equipped_phone_number(player)')
expect(equippedNumberExport).not.toContain('tonumber(player)')
expect(equippedNumberExport).not.toContain('equipped_phone_numbers[player]')
expect(equippedNumberResolver).not.toContain('return cached_number')
expect(phoneServer).toContain(
'player_source and resolve_equipped_phone_number(player_source) == normalized',
)
expect(serverBridge).toMatch(
/"GetEquippedPhoneNumber",\s+phone\.GetEquippedPhoneNumber/,
)
expect(serverBridge).toMatch(
/"GetSourceFromNumber",\s+phone\.GetSourceFromNumber/,
)
expect(phoneServer).toContain(
'TriggerEvent("sky_phone:server:phoneNumberChanged", source, phone_number)',
)
expect(serverLifecycle).toContain(
'SkyPhoneCompatibility.EmitServerProviderStop(LB_PROVIDER_NAME)',
)
expect(serverLifecycle).toContain(
'SkyPhoneCompatibility.EmitServerProviderStart(LB_PROVIDER_NAME)',
)
})
it('maps LB client lifecycle and state contracts', () => {
const phoneClient = readResourceFile('source/client/main.lua')
const phoneBridge = readResourceFile('source/bridge/phones/client/lb.lua')
expect(phoneBridge).toContain(
'SkyPhoneCompatibility.RegisterExportAlias("lb-phone", "ToggleOpen"',
)
expect(phoneClient).toContain(
'local result = Bridge.Callbacks.Trigger("sky_phone:device:open-request", {})',
)
expect(phoneClient).toMatch(
/result\.success ~= true[\s\S]*open_without_focus = false[\s\S]*return false/,
)
expect(phoneBridge).toContain(
'SkyPhoneCompatibility.RegisterExportAlias("lb-phone", "IsPhoneOnScreen"',
)
expect(phoneBridge).toContain(
'SkyPhoneCompatibility.RegisterExportAlias("lb-phone", "IsInCall"',
)
expect(phoneBridge).toContain(
'SkyPhoneCompatibility.RegisterExportAlias("lb-phone", "FormatNumber", client_bridge.FormatNumber)',
)
expect(phoneClient).toContain(
'TriggerEvent("sky_phone:client:phoneNumberChanged", next_number)',
)
expect(phoneClient).toContain(
'TriggerEvent("sky_phone:client:phoneToggled", true)',
)
expect(phoneClient).toContain(
'TriggerEvent("sky_phone:client:phoneToggled", false)',
)
expect(phoneBridge).toContain('TriggerEvent("lb-phone:numberChanged", phone_number)')
expect(phoneBridge).toContain('TriggerEvent("lb-phone:phoneToggled", open)')
})
it('keeps vendor contracts outside the phone business core', () => {
const corePaths = [
'source/client/main.lua',
'source/client/camera.lua',
'source/client/custom_apps.lua',
'source/server/phone.lua',
'source/server/sim.lua',
'source/server/media.lua',
]
for (const path of corePaths) {
expect(readResourceFile(path)).not.toMatch(
/lb-phone|17mov|high-phone|qs-smartphone|yseries|SkyPhoneCompatibility/,
)
}
})
it('maps the LB custom-app delete lifecycle from the App Store to Lua', () => {
const appStore = readFrontendFile('stores/app-store.ts')
const customApps = readResourceFile('source/client/custom_apps.lua')
const compatibility = readResourceFile('source/bridge/phones/shared/lb.lua')
expect(appStore).toContain("event: 'delete'")
expect(customApps).toContain('and lifecycle_event ~= "delete"')
expect(customApps).toContain(
'invoke_or_defer_hook(app, "onDelete", lifecycle_payload, deferred_hooks)',
)
expect(compatibility).toContain('onDelete = app_data.onDelete')
})
it('emits exact LB observer events after authoritative state changes', () => {
const phonePersistence = readResourceFile(
'source/server/phone_persistence.lua',
)
const simServer = readResourceFile('source/server/sim.lua')
const mediaServer = readResourceFile('source/server/media.lua')
const phoneBridge = readResourceFile(
'source/bridge/phones/server/lifecycle.lua',
)
expect(simServer).toContain(
'TriggerEvent("sky_phone:server:phoneNumberGenerated", source, sim.phone_number)',
)
expect(phonePersistence).toContain(
'TriggerEvent("sky_phone:server:factoryReset", source, phone_number)',
)
expect(mediaServer).toContain(
'TriggerEvent("sky_phone:server:galleryMediaDeleted", src, phone_number, deleted_link)',
)
expect(phoneBridge).toContain('TriggerEvent("lb-phone:phoneNumberGenerated"')
expect(phoneBridge).toContain('TriggerEvent("lb-phone:factoryReset"')
expect(phoneBridge).toContain('TriggerEvent("lb-phone:deletedFromGallery"')
})
it('opens from a configurable F1 mapping without client-provided device identity', () => {
@@ -0,0 +1,32 @@
import { readFileSync } from 'node:fs'
import { join } from 'node:path'
import { describe, expect, it } from 'vitest'
const rootDirectory = join(import.meta.dirname, '..')
const appSource = readFileSync(join(rootDirectory, 'src/App.vue'), 'utf8')
const navigationSource = readFileSync(
join(rootDirectory, '../sky_phone/source/client/navigation.lua'),
'utf8',
)
describe('neutral phone navigation contract', () => {
it('synchronizes installed renderer apps before acknowledging an opened phone', () => {
expect(appSource).toContain("return nuiCall('navigation:state'")
expect(appSource).toContain(
"void syncNavigationState().then(() => nuiCall('ui:opened'))",
)
expect(navigationSource).toContain(
'RegisterNUICallback("navigation:state"',
)
})
it('routes only installed apps and closes only the requested current app', () => {
expect(appSource).toContain("event.data?.type === 'navigation:open-app'")
expect(appSource).toContain('appStore.isInstalled(data.appId)')
expect(appSource).toContain("event.data?.type === 'navigation:close-app'")
expect(appSource).toContain('currentApp === data.appId')
expect(navigationSource).toContain('if not installed_apps[normalized_app_id] then')
expect(navigationSource).toContain('if current_app_id ~= normalized_app_id then')
})
})
+12
View File
@@ -494,6 +494,18 @@ export const useAppStoreStore = defineStore('app-store', {
}
this.homeLayout = removeHomeApp(this.homeLayout, appId)
this.persist()
if (isExternalPhoneApp(app)) {
void nuiCall('custom-app:lifecycle', {
appId,
event: 'delete',
}).then((response) => {
if (!response.success) {
console.error(
`[Custom apps] Delete lifecycle failed for ${appId}: ${response.error ?? 'request_failed'}`,
)
}
})
}
return true
},
+3 -3
View File
@@ -159,9 +159,9 @@ export type SkyPhoneAppBridgeResponse = {
export type SkyPhoneAppContextV1 = {
appId: string
capabilities: SkyPhoneAppCapability[]
colorScheme: 'dark' | 'light'
language: string
locale: Record<string, unknown>
colorScheme?: 'dark' | 'light'
language?: string
locale?: Record<string, unknown>
phoneScale: number
protocolVersion: 1
safeArea: {
+38 -1
View File
@@ -5,7 +5,10 @@ import {
createLbPhoneFrameDocument,
createLbPhoneHostSettings,
getLbPhoneCallbackResource,
getLbPhoneStorageKey,
readLbPhoneStorage,
usesLbPhoneHostRuntime,
writeLbPhoneStorage,
} from '@/utils/lbPhoneAppBridge'
import { DEFAULT_PHONE_PREFERENCES } from '@/utils/preferences'
@@ -90,9 +93,10 @@ describe('LB Phone app bridge', () => {
it('injects the LB runtime and asset base before the vendor bundle', () => {
const html =
'<!doctype html><html><head><script type="module" src="/ui/dist/assets/index.js"></script></head><body></body></html>'
'<!doctype html><html><head><script>globalThis.previewMode = !window.invokeNative</script><script type="module" src="/ui/dist/assets/index.js"></script></head><body></body></html>'
const document = createLbPhoneFrameDocument(html, {
appName: 'snake-game',
localStorage: { theme: 'dark' },
resourceName: 'snake_app',
settings: createLbPhoneHostSettings({
deviceName: '</script><script>window.injected=true</script>',
@@ -109,8 +113,18 @@ describe('LB Phone app bridge', () => {
)
expect(document).toContain('globalThis.fetchNui = async')
expect(document).toContain('globalThis.onNuiEvent = globalThis.useNuiEvent')
expect(document).toContain('globalThis.createCall = globalThis.CreateCall')
expect(document).toContain('globalThis.createSMS = globalThis.CreateSMS')
expect(document).toContain('globalThis.invokeNative = () => undefined')
expect(document).toContain(
"Object.defineProperty(globalThis, 'localStorage'",
)
expect(document).toContain('"localStorage":{"theme":"dark"}')
expect(document).toContain('https://cfx-nui-snake_app/ui/dist/')
expect(document).not.toContain('</script><script>window.injected=true')
expect(document.indexOf('globalThis.invokeNative')).toBeLessThan(
document.indexOf('globalThis.previewMode'),
)
const openingTag = '<script>'
const runtimeStart = document.indexOf(openingTag)
@@ -124,4 +138,27 @@ describe('LB Phone app bridge', () => {
const runtime = document.slice(runtimeStart + openingTag.length, runtimeEnd)
expect(() => new Function(runtime)).not.toThrow()
})
it('persists isolated LB localStorage snapshots without app changes', () => {
const values = new Map<string, string>()
const storage = {
getItem: (key: string) => values.get(key) ?? null,
setItem: (key: string, value: string) => values.set(key, value),
}
expect(
writeLbPhoneStorage(storage, 'snake-game', {
language: 'de',
volume: '0.8',
}),
).toBe(true)
expect(values.has(getLbPhoneStorageKey('snake-game'))).toBe(true)
expect(readLbPhoneStorage(storage, 'snake-game')).toEqual({
language: 'de',
volume: '0.8',
})
expect(writeLbPhoneStorage(storage, 'snake-game', { invalid: 5 })).toBe(
false,
)
})
})
+140
View File
@@ -4,6 +4,15 @@ import type { PhonePreferencesV1 } from '@/utils/preferences'
const LB_PHONE_PROVIDER = 'lb_phone'
const RESOURCE_NAME_PATTERN = /^[A-Za-z0-9][A-Za-z0-9_.-]{0,127}$/
const MAX_FRAME_DOCUMENT_BYTES = 1_048_576
const MAX_STORAGE_BYTES = 65_536
const MAX_STORAGE_ENTRIES = 128
const MAX_STORAGE_KEY_LENGTH = 512
const STORAGE_KEY_PREFIX = 'sky_phone:lb-app-storage:v1:'
export const LB_PHONE_STORAGE_MESSAGE_TYPE = 'sky-phone:lb-storage'
export const LB_PHONE_ACTION_MESSAGE_TYPE = 'sky-phone:lb-action'
export type LbPhoneStorageSnapshot = Record<string, string>
export type LbPhoneHostSettings = {
airplaneMode: boolean
@@ -41,6 +50,7 @@ export type LbPhoneHostSettings = {
type LbPhoneFrameDocumentOptions = {
appName: string
localStorage: LbPhoneStorageSnapshot
resourceName: string
settings: LbPhoneHostSettings
ui: string
@@ -60,6 +70,59 @@ const settingsListeners = new Set();
const resourcePattern = /^[A-Za-z0-9][A-Za-z0-9_.-]{0,127}$/;
const eventPattern = /^[A-Za-z0-9][A-Za-z0-9:._/-]{0,127}$/;
function createStorage(initialValues, onChange) {
const values = new Map(Object.entries(initialValues ?? {}));
const snapshot = () => Object.fromEntries(values);
const storage = {
clear() {
if (values.size === 0) return;
values.clear();
onChange(snapshot());
},
getItem(key) {
const normalizedKey = String(key);
return values.has(normalizedKey) ? values.get(normalizedKey) : null;
},
key(index) {
const normalizedIndex = Number(index);
if (!Number.isInteger(normalizedIndex) || normalizedIndex < 0) return null;
return Array.from(values.keys())[normalizedIndex] ?? null;
},
removeItem(key) {
if (!values.delete(String(key))) return;
onChange(snapshot());
},
setItem(key, value) {
values.set(String(key), String(value));
onChange(snapshot());
}
};
Object.defineProperty(storage, 'length', {
enumerable: true,
get: () => values.size
});
return storage;
}
const localStorageBridge = createStorage(config.localStorage, (storage) => {
globalThis.parent.postMessage({
appId: config.appName,
protocolVersion: 1,
storage,
type: '${LB_PHONE_STORAGE_MESSAGE_TYPE}'
}, '*');
});
Object.defineProperty(globalThis, 'localStorage', {
configurable: true,
enumerable: true,
value: localStorageBridge
});
Object.defineProperty(globalThis, 'sessionStorage', {
configurable: true,
enumerable: true,
value: createStorage({}, () => undefined)
});
function applySettings(nextSettings) {
globalThis.settings = nextSettings;
const theme = nextSettings?.display?.theme === 'dark' ? 'dark' : 'light';
@@ -70,7 +133,22 @@ function applySettings(nextSettings) {
globalThis.resourceName = config.resourceName;
globalThis.appName = config.appName;
globalThis.components = globalThis.components ?? {};
// Official LB app templates use this binding to distinguish live NUI from browser preview mode.
if (typeof globalThis.invokeNative !== 'function') {
globalThis.invokeNative = () => undefined;
}
globalThis.GetParentResourceName = () => config.resourceName;
function requestPhoneAction(action, options) {
globalThis.parent.postMessage({
action,
appId: config.appName,
options,
protocolVersion: 1,
type: '${LB_PHONE_ACTION_MESSAGE_TYPE}'
}, '*');
}
globalThis.createCall = globalThis.CreateCall = (options) => requestPhoneAction('createCall', options);
globalThis.createSMS = globalThis.CreateSMS = (options) => requestPhoneAction('createSMS', options);
globalThis.fetchNui = async (eventName, data, requestedResource) => {
if (typeof eventName !== 'string' || !eventPattern.test(eventName) || eventName.includes('..')) {
throw new TypeError('Invalid NUI callback name');
@@ -150,6 +228,67 @@ function serializeForInlineScript(value: unknown): string {
.replace(/\u2029/g, '\\u2029')
}
function normalizeStorageSnapshot(
value: unknown,
): LbPhoneStorageSnapshot | null {
if (value === null || typeof value !== 'object' || Array.isArray(value)) {
return null
}
const entries = Object.entries(value)
if (entries.length > MAX_STORAGE_ENTRIES) return null
const normalized: LbPhoneStorageSnapshot = {}
for (const [key, item] of entries) {
if (
key.length > MAX_STORAGE_KEY_LENGTH ||
typeof item !== 'string' ||
key === '__proto__' ||
key === 'constructor' ||
key === 'prototype'
) {
return null
}
normalized[key] = item
}
return new TextEncoder().encode(JSON.stringify(normalized)).byteLength <=
MAX_STORAGE_BYTES
? normalized
: null
}
export function getLbPhoneStorageKey(appName: string): string {
if (!RESOURCE_NAME_PATTERN.test(appName)) {
throw new Error('invalid_lb_phone_storage_app')
}
return `${STORAGE_KEY_PREFIX}${appName}`
}
export function readLbPhoneStorage(
storage: Pick<Storage, 'getItem'>,
appName: string,
): LbPhoneStorageSnapshot {
const serialized = storage.getItem(getLbPhoneStorageKey(appName))
if (serialized === null) return {}
const normalized = normalizeStorageSnapshot(JSON.parse(serialized))
if (!normalized) throw new Error('invalid_lb_phone_storage')
return normalized
}
export function writeLbPhoneStorage(
storage: Pick<Storage, 'setItem'>,
appName: string,
value: unknown,
): boolean {
const normalized = normalizeStorageSnapshot(value)
if (!normalized) return false
storage.setItem(getLbPhoneStorageKey(appName), JSON.stringify(normalized))
return true
}
export function usesLbPhoneHostRuntime(
app: ExternalPhoneAppDefinition,
): boolean {
@@ -228,6 +367,7 @@ export function createLbPhoneFrameDocument(
const baseUrl = new URL('.', options.ui).href
const config = serializeForInlineScript({
appName: options.appName,
localStorage: options.localStorage,
resourceName: options.resourceName,
settings: options.settings,
})
@@ -15,7 +15,7 @@ const appSource = readFileSync(
'utf8',
)
const clientSource = readFileSync(
new URL('../../../../sky_phone/source/client/main.lua', import.meta.url),
new URL('../../../../sky_phone/source/client/nui_events.lua', import.meta.url),
'utf8',
)
const serverSource = readFileSync(
@@ -69,7 +69,10 @@ describe('Banking app Sky UI migration', () => {
expect(serverSource).toContain('kind = "transfer_in"')
expect(serverSource).toContain('currency = Config.Banking.Currency')
expect(clientSource).toContain(
'SendNUIMessage({ type = "banking:changed", data = data })',
'["sky_phone:banking:changed"] = "banking:changed"',
)
expect(clientSource).toContain(
'SendNUIMessage({ type = nui_type, data = data })',
)
expect(appSource).toContain("data?.kind === 'transfer_in'")
expect(appSource).toContain("appId: 'banking'")
@@ -4,7 +4,7 @@ import { describe, expect, it } from 'vitest'
const source = readFileSync(new URL('./FlareApp.vue', import.meta.url), 'utf8')
const clientSource = readFileSync(
new URL('../../../../sky_phone/source/client/main.lua', import.meta.url),
new URL('../../../../sky_phone/source/client/nui_server_bridge.lua', import.meta.url),
'utf8',
)
const serverSource = readFileSync(
@@ -210,7 +210,7 @@ describe('FlareApp profile editing contract', () => {
})
it('deletes all account-owned Flare data in one server transaction', () => {
expect(clientSource).toContain('"flare:delete-profile"')
expect(clientSource).toMatch(/flare\s*=\s*\[\[[^\]]*delete-profile/)
expect(serverSource).toContain(
'Bridge.Callbacks.Register("sky_phone:flare:delete-profile"',
)
@@ -19,7 +19,7 @@ const migrationSource = readFileSync(
'utf8',
)
const clientSource = readFileSync(
new URL('../../../../sky_phone/source/client/main.lua', import.meta.url),
new URL('../../../../sky_phone/source/client/nui_server_bridge.lua', import.meta.url),
'utf8',
)
@@ -295,7 +295,10 @@ describe('Mail custom mailbox server contract', () => {
'mail:delete-mailbox',
'mail:move',
]) {
expect(clientSource).toContain(`"${endpoint}"`)
const callback = endpoint.slice('mail:'.length)
expect(clientSource).toMatch(
new RegExp(`mail\\s*=\\s*\\[\\[[^\\]]*(?:^|\\s)${callback}(?:\\s|\\]\\])`),
)
}
})
})
+4 -4
View File
@@ -18,8 +18,8 @@ const clientCalls = readFileSync(
new URL('../../sky_phone/source/bridge/client/calls.lua', import.meta.url),
'utf8',
)
const clientMain = readFileSync(
new URL('../../sky_phone/source/client/main.lua', import.meta.url),
const clientNuiBridge = readFileSync(
new URL('../../sky_phone/source/client/nui_server_bridge.lua', import.meta.url),
'utf8',
)
const phoneApp = readFileSync(
@@ -70,7 +70,7 @@ describe('voice provider contracts', () => {
expect(serverCalls).toMatch(
/call\.speakers\[source\] = data\.enabled\s+send_state\(call, source, "connected", call\.channel\)/,
)
expect(clientMain).toContain('"calls:set-speaker"')
expect(clientNuiBridge).toMatch(/calls\s*=\s*\[\[[^\]]*set-speaker/)
expect(clientCalls).toContain(
'SaltyChat call membership is owned by the server bridge.',
)
@@ -111,7 +111,7 @@ describe('voice provider contracts', () => {
expect(serverCalls).toContain(
'Bridge.Callbacks.Register("sky_phone:calls:set-muted"',
)
expect(clientMain).toContain('"calls:set-muted"')
expect(clientNuiBridge).toMatch(/calls\s*=\s*\[\[[^\]]*set-muted/)
expect(phoneApp).toContain('@click="toggleCallMute"')
expect(phoneApp).not.toContain('callMuted = !callMuted')
})