From efd6dadeda87344911fb4000fe293c686c678602 Mon Sep 17 00:00:00 2001 From: Jason Morse Date: Thu, 12 Nov 2026 02:08:52 +0000 Subject: [PATCH 01/11] Harden Storybook generated manifest trust handoff Keep bridge and attachment credentials in OS-private records, validate centralized generated contracts, and pin the spawning child's helper to the independent parent handoff. Load runtime identity from a private data-only module. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .changeset/curvy-dragons-fry.md | 6 + .../storybook-desktop-runtime/AGENTS.md | 5 +- .../storybook-desktop-runtime/README.md | 4 + .../config/metro.cjs | 71 +++---- .../config/runtime-instance.cjs | 2 + .../config/runtime-instance.d.cts | 2 + .../references/integration.md | 2 +- .../references/runtime-contract.md | 20 +- .../src/createDesktopStorybookApp.test.tsx | 48 +++++ .../src/createDesktopStorybookApp.tsx | 13 +- .../src/metro.test.ts | 148 ++++++++++++++ packages/agentic/storybook-desktop/AGENTS.md | 3 + packages/agentic/storybook-desktop/README.md | 3 + .../config/generated-contract.cjs | 176 ++++++++++++++++ .../config/generated-contract.d.cts | 6 + .../storybook-desktop/config/server.cjs | 20 +- .../references/contributing.md | 34 ++++ .../src/cli/DesktopStorybookCli.test.ts | 57 ++++-- .../src/cli/DesktopStorybookCli.ts | 70 +++++-- .../StorybookChannelOrchestrator.test.ts | 2 +- .../src/driver/driverManifest.test.ts | 27 ++- .../src/driver/driverManifest.ts | 26 +-- .../src/driver/fixtures/privateStorage.ts | 24 +++ .../src/driver/generatedManifest.test.ts | 192 ++++++++++++++++++ .../src/driver/generatedManifest.ts | 175 ++++++++++++++++ .../src/driver/serverIntegration.test.ts | 81 +++++++- 26 files changed, 1090 insertions(+), 127 deletions(-) create mode 100644 .changeset/curvy-dragons-fry.md create mode 100644 packages/agentic/storybook-desktop-runtime/config/runtime-instance.cjs create mode 100644 packages/agentic/storybook-desktop-runtime/config/runtime-instance.d.cts create mode 100644 packages/agentic/storybook-desktop-runtime/src/createDesktopStorybookApp.test.tsx create mode 100644 packages/agentic/storybook-desktop-runtime/src/metro.test.ts create mode 100644 packages/agentic/storybook-desktop/config/generated-contract.cjs create mode 100644 packages/agentic/storybook-desktop/config/generated-contract.d.cts create mode 100644 packages/agentic/storybook-desktop/src/driver/fixtures/privateStorage.ts create mode 100644 packages/agentic/storybook-desktop/src/driver/generatedManifest.test.ts create mode 100644 packages/agentic/storybook-desktop/src/driver/generatedManifest.ts diff --git a/.changeset/curvy-dragons-fry.md b/.changeset/curvy-dragons-fry.md new file mode 100644 index 0000000000..5f6cf468fb --- /dev/null +++ b/.changeset/curvy-dragons-fry.md @@ -0,0 +1,6 @@ +--- +'@fluentui-react-native/storybook-desktop': patch +'@fluentui-react-native/storybook-desktop-runtime': patch +--- + +Separate Storybook bridge and attachment credentials in owner-private storage, validate versioned generated manifests, and pin native helper provenance through the trusted parent handoff before child processes can spawn helpers. diff --git a/packages/agentic/storybook-desktop-runtime/AGENTS.md b/packages/agentic/storybook-desktop-runtime/AGENTS.md index a7158feac3..127b38eb42 100644 --- a/packages/agentic/storybook-desktop-runtime/AGENTS.md +++ b/packages/agentic/storybook-desktop-runtime/AGENTS.md @@ -21,7 +21,10 @@ authenticated bridge, Metro, theme, and platform chrome. - Keep platform-specific behavior in platform files. Preserve Win32's desktop-only chrome and keep macOS/Windows on upstream LiteUI. - Metro configuration has side effects: loading it can generate the runtime - polyfill. Do not treat config evaluation as a read-only probe. + data module. Do not treat config evaluation as a read-only probe. +- Driver-backed Metro uses the parent's canonical generated-schema locator and + pinned private bridge-only data module. Never copy attachment credentials into + the runtime or trust provenance supplied only by the generated manifest. ## Validation diff --git a/packages/agentic/storybook-desktop-runtime/README.md b/packages/agentic/storybook-desktop-runtime/README.md index 454629bf3d..341197005c 100644 --- a/packages/agentic/storybook-desktop-runtime/README.md +++ b/packages/agentic/storybook-desktop-runtime/README.md @@ -9,6 +9,10 @@ Consumers normally install and invoke `storybook-desktop`; this package is separate so the CLI package stays peer-free and receives the runtime workspace locator. +Driver-backed Metro validates the parent's versioned manifest handoff and +loads its owner-private bridge-only data module; attachment credentials never +enter the app bundle. Test config evaluation only in controlled fixture roots. + Win32 test generations reset the preview subtree and its scroll position while preserving the surrounding desktop chrome preferences. Its scrollable story viewport centers small stories without clipping the start diff --git a/packages/agentic/storybook-desktop-runtime/config/metro.cjs b/packages/agentic/storybook-desktop-runtime/config/metro.cjs index b19ce00ad7..5806d20abb 100644 --- a/packages/agentic/storybook-desktop-runtime/config/metro.cjs +++ b/packages/agentic/storybook-desktop-runtime/config/metro.cjs @@ -1,10 +1,12 @@ const fs = require('node:fs'); const path = require('node:path'); +const { createHash } = require('node:crypto'); const { makeMetroConfig } = require('@rnx-kit/metro-config'); const MetroSymlinksResolver = require('@rnx-kit/metro-resolver-symlinks'); const { withStorybook } = require('@storybook/react-native/withStorybook'); const safeAreaStub = path.resolve(__dirname, 'react-native-safe-area-context.cjs'); +const runtimeInstanceStub = path.resolve(__dirname, 'runtime-instance.cjs'); function resolvePlatformModule(moduleName, platform) { if (platform !== 'win32') { @@ -34,6 +36,9 @@ function createDesktopStorybookMetroConfig({ configPath }) { const config = makeMetroConfig({ resolver: { resolveRequest: (context, moduleName, platform) => { + if (path.resolve(path.dirname(context.originModulePath), moduleName) === runtimeInstanceStub) { + return { type: 'sourceFile', filePath: runtimeModulePath }; + } // Storybook's path-based lite-mode mock does not recognize Yarn's virtual pnpm paths. if (moduleName === '@storybook/react-native-ui' || moduleName.startsWith('@storybook/react-native-ui/')) { return { type: 'empty' }; @@ -57,38 +62,43 @@ function createDesktopStorybookMetroConfig({ configPath }) { configPath, liteMode: true, }); - const getPolyfills = storybookConfig.serializer?.getPolyfills; - - return { - ...storybookConfig, - serializer: { - ...storybookConfig.serializer, - getPolyfills: (...args) => [...(getPolyfills?.(...args) ?? []), runtimeModulePath], - }, - }; + return storybookConfig; } function writeRuntimeInstanceModule(projectRoot) { + if (process.env.STORYBOOK_DRIVER_MANIFEST) { + // The parent publishes this bridge-only module through owner-private OS storage. Metro must never copy the attach + // credential (or trust a helper path) from an editable generated manifest. + if (!process.env.STORYBOOK_GENERATED_CONTRACT || !path.isAbsolute(process.env.STORYBOOK_GENERATED_CONTRACT)) { + throw new Error('Desktop Storybook Metro requires the trusted parent generated-contract locator.'); + } + const { parseDriverManifest, parseHandoff } = require(process.env.STORYBOOK_GENERATED_CONTRACT); + const contents = fs.readFileSync(process.env.STORYBOOK_DRIVER_MANIFEST, 'utf8'); + const manifest = parseDriverManifest(JSON.parse(contents)); + const handoff = parseHandoff(JSON.parse(process.env.STORYBOOK_DRIVER_HANDOFF || 'null')); + if ( + createHash('sha256').update(contents).digest('hex') !== handoff.manifestDigest || + handoff.runtimeModulePath !== path.join(manifest.credentials.root, manifest.credentials.runtimeModule) + ) { + throw new Error('Desktop Storybook manifest does not match the trusted parent handoff.'); + } + if ( + !fs.statSync(handoff.runtimeModulePath).isFile() || + createHash('sha256').update(fs.readFileSync(handoff.runtimeModulePath)).digest('hex') !== handoff.runtimeModuleDigest + ) { + throw new Error('Desktop Storybook runtime module does not match the trusted parent handoff.'); + } + return handoff.runtimeModulePath; + } const generatedDirectory = path.join(projectRoot, 'storybook-desktop.generated'); const runtimeModulePath = path.join(generatedDirectory, 'runtime-instance.js'); const storybookPort = readPort(process.env.STORYBOOK_WS_PORT, 7007); const instanceId = process.env.FURN_STORYBOOK_INSTANCE_ID || 'default'; - const driverManifest = readDriverManifest(process.env.STORYBOOK_DRIVER_MANIFEST); const runtimeInstance = { instanceId, storybookPort, - ...(driverManifest - ? { - bridgeNonce: driverManifest.bridgeNonce, - endpoint: driverManifest.endpoint, - platformManifestDigest: driverManifest.platformManifestDigest, - portablePlanDigest: driverManifest.portablePlanDigest, - targetId: driverManifest.targetId, - testIDPrefix: driverManifest.testIDPrefix, - } - : {}), }; - const content = `globalThis.__FURN_DESKTOP_STORYBOOK_INSTANCE__ = Object.freeze(${JSON.stringify(runtimeInstance)});\n`; + const content = `export default ${JSON.stringify(runtimeInstance)};\n`; fs.mkdirSync(generatedDirectory, { recursive: true }); if (!fs.existsSync(runtimeModulePath) || fs.readFileSync(runtimeModulePath, 'utf8') !== content) { @@ -98,25 +108,6 @@ function writeRuntimeInstanceModule(projectRoot) { return runtimeModulePath; } -function readDriverManifest(manifestPath) { - if (!manifestPath) { - return undefined; - } - if (!fs.existsSync(manifestPath)) { - throw new Error(`Desktop Driver manifest does not exist at ${manifestPath}.`); - } - const manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8')); - if ( - manifest.schemaVersion !== 2 || - !manifest.nativeDriver || - !manifest.application || - typeof manifest.application.leasePath !== 'string' - ) { - throw new Error(`Unsupported Desktop Driver manifest schema "${manifest.schemaVersion}".`); - } - return manifest; -} - function readPort(value, fallback) { const port = Number(value) || fallback; if (!Number.isInteger(port) || port < 1 || port > 65535) { diff --git a/packages/agentic/storybook-desktop-runtime/config/runtime-instance.cjs b/packages/agentic/storybook-desktop-runtime/config/runtime-instance.cjs new file mode 100644 index 0000000000..2b1788e7d0 --- /dev/null +++ b/packages/agentic/storybook-desktop-runtime/config/runtime-instance.cjs @@ -0,0 +1,2 @@ +// Metro resolves this fallback to the parent's data-only instance module when configured. +module.exports = Object.freeze({ instanceId: 'default', storybookPort: 7007 }); diff --git a/packages/agentic/storybook-desktop-runtime/config/runtime-instance.d.cts b/packages/agentic/storybook-desktop-runtime/config/runtime-instance.d.cts new file mode 100644 index 0000000000..928f630f87 --- /dev/null +++ b/packages/agentic/storybook-desktop-runtime/config/runtime-instance.d.cts @@ -0,0 +1,2 @@ +declare const instance: Readonly<{ instanceId: string; storybookPort: number }>; +export = instance; diff --git a/packages/agentic/storybook-desktop-runtime/references/integration.md b/packages/agentic/storybook-desktop-runtime/references/integration.md index 5cbfd72196..a4da3dd067 100644 --- a/packages/agentic/storybook-desktop-runtime/references/integration.md +++ b/packages/agentic/storybook-desktop-runtime/references/integration.md @@ -14,7 +14,7 @@ Storybook integration; do not recreate app identity, native test IDs, or generated runtime config in the consumer. The package exposes its native entry and `./metro` config. The Metro config -may generate a polyfill when loaded. Use the owning app's declared scripts and +may generate a runtime data module when loaded. Use the owning app's declared scripts and do not import this config as a supposedly side-effect-free inspection step. App-specific identity, story package discovery, platform exclusions, and test diff --git a/packages/agentic/storybook-desktop-runtime/references/runtime-contract.md b/packages/agentic/storybook-desktop-runtime/references/runtime-contract.md index fc3df62a00..5afecf34d6 100644 --- a/packages/agentic/storybook-desktop-runtime/references/runtime-contract.md +++ b/packages/agentic/storybook-desktop-runtime/references/runtime-contract.md @@ -79,9 +79,23 @@ overrides higher priority than defaults. ## Metro and source ownership `config/metro.cjs` composes resolver behavior and generates the runtime -polyfill when evaluated. Treat loading it as a write-capable operation. Tests -and diagnostics should use the package's owning app scripts and inspect only -the generated files they need. +data module when evaluated without a driver manifest. Treat loading it as a +write-capable operation; config tests must use controlled fixture roots. +Diagnostics should use the package's owning app scripts and inspect only the +generated files they need. + +Driver-backed Metro does not generate a credential-bearing public file. +The parent supplies `STORYBOOK_DRIVER_HANDOFF` and the canonical schema locator +`STORYBOOK_GENERATED_CONTRACT`; the integration package owns these strict, +versioned contracts without adding runtime/UI peers to the CLI. Metro rejects +unknown generated fields and mismatched manifest/module hashes before using +the owner's private bridge-only module. It never uses the generated helper +path or receives the independent application-attachment nonce. The parent +publishes credentials through OS private storage, not default-mode files. +The generated module's only statement is `export default `; the constant +runtime loader imports it through Metro's resolver instead of embedding values +in executable polyfill source. The old global instance remains a compatibility +fallback for existing app-owned polyfills. React Native platform variations belong in platform-specific files. Build and test through the consuming Storybook workspace for the affected endpoint. diff --git a/packages/agentic/storybook-desktop-runtime/src/createDesktopStorybookApp.test.tsx b/packages/agentic/storybook-desktop-runtime/src/createDesktopStorybookApp.test.tsx new file mode 100644 index 0000000000..182580d4df --- /dev/null +++ b/packages/agentic/storybook-desktop-runtime/src/createDesktopStorybookApp.test.tsx @@ -0,0 +1,48 @@ +import * as React from 'react'; +import { Text } from 'react-native'; +import { render } from '@testing-library/react-native'; +import { createDesktopStorybookApp } from './createDesktopStorybookApp'; +import { useDesktopStorybookConfig, type DesktopStorybookRuntimeInstance } from './DesktopStorybookConfig'; + +let mockRuntimeInstance: DesktopStorybookRuntimeInstance; +jest.mock('../config/runtime-instance.cjs', () => ({ + __esModule: true, + get default() { + return mockRuntimeInstance; + }, +})); +jest.mock('./DesktopDriverBridge', () => ({ DesktopDriverBridge: () => null })); +jest.mock('./StorybookTheme', () => ({ StorybookThemeHost: ({ children }: { children: React.ReactNode }) => children })); +jest.mock('./ThemedStorybookUI', () => ({ ThemedStorybookUI: () => null })); + +const globals = globalThis as typeof globalThis & { __FURN_DESKTOP_STORYBOOK_INSTANCE__?: DesktopStorybookRuntimeInstance }; +const original = globals.__FURN_DESKTOP_STORYBOOK_INSTANCE__; +afterEach(() => { + if (original === undefined) delete globals.__FURN_DESKTOP_STORYBOOK_INSTANCE__; + else globals.__FURN_DESKTOP_STORYBOOK_INSTANCE__ = original; +}); + +function Preview() { + const { runtimeInstance } = useDesktopStorybookConfig(); + return {runtimeInstance?.bridgeNonce}; +} + +test('uses the parent data module rather than a stale legacy global for an authenticated runtime', async () => { + mockRuntimeInstance = { bridgeNonce: 'private-bridge', storybookPort: 7123 }; + globals.__FURN_DESKTOP_STORYBOOK_INSTANCE__ = { bridgeNonce: 'stale-global', storybookPort: 7999 }; + const getStorybookUI = jest.fn(() => Preview); + const App = createDesktopStorybookApp({ getStorybookUI }); + const screen = await render(); + expect(getStorybookUI).toHaveBeenCalledWith(expect.objectContaining({ port: 7123 })); + expect(screen.getByTestId('bridge')).toHaveTextContent('private-bridge'); +}); + +test('preserves app-owned legacy globals when no authenticated data module is configured', async () => { + mockRuntimeInstance = { instanceId: 'default', storybookPort: 7007 }; + globals.__FURN_DESKTOP_STORYBOOK_INSTANCE__ = { bridgeNonce: 'legacy-global', storybookPort: 7999 }; + const getStorybookUI = jest.fn(() => Preview); + const App = createDesktopStorybookApp({ getStorybookUI }); + const screen = await render(); + expect(getStorybookUI).toHaveBeenCalledWith(expect.objectContaining({ port: 7999 })); + expect(screen.getByTestId('bridge')).toHaveTextContent('legacy-global'); +}); diff --git a/packages/agentic/storybook-desktop-runtime/src/createDesktopStorybookApp.tsx b/packages/agentic/storybook-desktop-runtime/src/createDesktopStorybookApp.tsx index fa376208c9..6d2ef6add2 100644 --- a/packages/agentic/storybook-desktop-runtime/src/createDesktopStorybookApp.tsx +++ b/packages/agentic/storybook-desktop-runtime/src/createDesktopStorybookApp.tsx @@ -1,4 +1,5 @@ import type { View } from '@storybook/react-native'; +import generatedRuntimeInstance from '../config/runtime-instance.cjs'; import { DesktopDriverBridge } from './DesktopDriverBridge'; import { DesktopStorybookConfigProvider } from './DesktopStorybookConfig'; @@ -17,11 +18,13 @@ export function createDesktopStorybookApp( view: Pick, { enableWebsockets = true, host = '127.0.0.1', port, testIDPrefix = 'storybook-desktop' }: DesktopStorybookOptions = {}, ) { - const runtimeInstance = ( - globalThis as typeof globalThis & { - __FURN_DESKTOP_STORYBOOK_INSTANCE__?: DesktopStorybookRuntimeInstance; - } - ).__FURN_DESKTOP_STORYBOOK_INSTANCE__; + const generated: DesktopStorybookRuntimeInstance = generatedRuntimeInstance; + const runtimeInstance: DesktopStorybookRuntimeInstance = Object.freeze( + generated.bridgeNonce + ? generated + : ((globalThis as typeof globalThis & { __FURN_DESKTOP_STORYBOOK_INSTANCE__?: DesktopStorybookRuntimeInstance }) + .__FURN_DESKTOP_STORYBOOK_INSTANCE__ ?? generated), + ); const memoryStore: Record = {}; const storage = { getItem: async (key: string) => (key in memoryStore ? memoryStore[key] : null), diff --git a/packages/agentic/storybook-desktop-runtime/src/metro.test.ts b/packages/agentic/storybook-desktop-runtime/src/metro.test.ts new file mode 100644 index 0000000000..ea6507d482 --- /dev/null +++ b/packages/agentic/storybook-desktop-runtime/src/metro.test.ts @@ -0,0 +1,148 @@ +import { createHash } from 'node:crypto'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; + +jest.mock('@rnx-kit/metro-config', () => ({ + makeMetroConfig: (config: object) => ({ ...config, serializer: { getPolyfills: () => ['base-polyfill'] } }), +})); +jest.mock('@rnx-kit/metro-resolver-symlinks', () => () => jest.fn()); +jest.mock('@storybook/react-native/withStorybook', () => ({ withStorybook: (config: unknown) => config })); + +const { createDesktopStorybookMetroConfig } = require('../config/metro.cjs'); +const hash = (contents: string) => createHash('sha256').update(contents).digest('hex'); +const environmentKeys = [ + 'STORYBOOK_DRIVER_MANIFEST', + 'STORYBOOK_DRIVER_HANDOFF', + 'STORYBOOK_GENERATED_CONTRACT', + 'STORYBOOK_WS_PORT', + 'FURN_STORYBOOK_INSTANCE_ID', +]; + +describe('controlled Metro generation fixtures', () => { + let root: string; + let originalEnvironment: (string | undefined)[]; + beforeEach(() => { + root = fs.mkdtempSync(path.join(os.tmpdir(), 'storybook-metro-contract-')); + originalEnvironment = environmentKeys.map((key) => process.env[key]); + for (const key of environmentKeys) delete process.env[key]; + }); + afterEach(() => { + environmentKeys.forEach((key, index) => { + if (originalEnvironment[index] === undefined) delete process.env[key]; + else process.env[key] = originalEnvironment[index]; + }); + fs.rmSync(root, { force: true, recursive: true }); + }); + + function controlledManifest() { + const privateRoot = path.join(root, 'storybook-desktop.generated', '.private'); + const runtimeModulePath = path.join(privateRoot, 'runtime-fixture.js'); + const runtimeContents = 'export default {"bridgeNonce":"bridge-only"};\n'; + const nativeDriver = { + architecture: 'x64', + artifactId: 'artifact', + artifactRoot: root, + buildFingerprint: 'build', + buildId: 'build-id', + compatibilityKey: 'compatibility', + configuration: 'release', + endpoints: ['windows', 'win32'], + executablePath: path.join(root, 'helper.exe'), + features: ['probe'], + origin: 'cache', + provider: 'windows', + schemaVersion: 1, + signing: { mode: 'none' }, + sourceDigest: 'source', + wireProtocol: { major: 1, minor: 0 }, + }; + const manifest = { + application: { leasePath: path.join(privateRoot, 'application-lease.windows.json'), windowTitle: 'Fixture' }, + appName: 'Fixture', + credentials: { name: 'credentials-fixture.json', root: privateRoot, runtimeModule: 'runtime-fixture.js' }, + displayName: 'Fixture', + driverPort: 7010, + endpoint: 'windows', + instanceId: 'fixture', + metroPort: 8081, + nativeDriver, + platformManifestDigest: 'platform', + portablePlanDigest: 'portable', + renderer: 'fabric', + schemaVersion: 3, + storyManifest: { + endpoint: 'windows', + entries: [], + platformManifestDigest: 'platform', + portablePlanDigest: 'portable', + schemaVersion: 1, + }, + storybookPort: 7007, + targetId: 'fixture-windows', + testIDPrefix: 'fixture', + }; + const manifestPath = path.join(root, 'storybook-desktop.generated', 'driver-manifest.json'); + const contents = JSON.stringify(manifest); + fs.mkdirSync(privateRoot, { recursive: true, mode: 0o700 }); + fs.writeFileSync(runtimeModulePath, runtimeContents, { mode: 0o600 }); + fs.writeFileSync(manifestPath, contents); + process.env.STORYBOOK_DRIVER_MANIFEST = manifestPath; + process.env.STORYBOOK_GENERATED_CONTRACT = path.resolve(__dirname, '../../storybook-desktop/config/generated-contract.cjs'); + process.env.STORYBOOK_DRIVER_HANDOFF = JSON.stringify({ + credentialsDigest: 'credentials', + manifestDigest: hash(contents), + nativeDriver, + runtimeModuleDigest: hash(runtimeContents), + runtimeModulePath, + schemaVersion: 1, + }); + return { manifest, manifestPath, runtimeModulePath, runtimeContents }; + } + + test('generates unauthenticated defaults only under the controlled fixture root', () => { + process.env.FURN_STORYBOOK_INSTANCE_ID = 'controlled-fixture'; + process.env.STORYBOOK_WS_PORT = '7123'; + const config = createDesktopStorybookMetroConfig({ configPath: path.join(root, 'src') }); + const generated = path.join(root, 'storybook-desktop.generated', 'runtime-instance.js'); + expect(config.serializer.getPolyfills()).toEqual(['base-polyfill']); + expect( + config.resolver.resolveRequest( + { originModulePath: path.join(__dirname, 'createDesktopStorybookApp.tsx') }, + '../config/runtime-instance.cjs', + 'macos', + ), + ).toEqual({ type: 'sourceFile', filePath: generated }); + expect(fs.readFileSync(generated, 'utf8')).toMatch(/^export default \{[^\n]+\};\n$/); + expect(fs.readFileSync(generated, 'utf8')).toContain('"instanceId":"controlled-fixture","storybookPort":7123'); + }); + + test('uses the parent-published private bridge-only projection without copying it to public generated output', () => { + const fixture = controlledManifest(); + const config = createDesktopStorybookMetroConfig({ configPath: path.join(root, 'src') }); + expect(config.serializer.getPolyfills()).toEqual(['base-polyfill']); + expect( + config.resolver.resolveRequest( + { originModulePath: path.join(__dirname, 'createDesktopStorybookApp.tsx') }, + '../config/runtime-instance.cjs', + 'macos', + ), + ).toEqual({ type: 'sourceFile', filePath: fixture.runtimeModulePath }); + expect(fs.readFileSync(fixture.runtimeModulePath, 'utf8')).toBe(fixture.runtimeContents); + expect(fs.existsSync(path.join(root, 'storybook-desktop.generated', 'runtime-instance.js'))).toBe(false); + }); + + test.each(['missing-handoff', 'missing-contract', 'unknown-field', 'manifest-tamper', 'runtime-tamper'])( + 'fails closed on %s before generating a runtime module', + (failure) => { + const fixture = controlledManifest(); + if (failure === 'missing-handoff') delete process.env.STORYBOOK_DRIVER_HANDOFF; + if (failure === 'missing-contract') delete process.env.STORYBOOK_GENERATED_CONTRACT; + if (failure === 'unknown-field') fs.writeFileSync(fixture.manifestPath, JSON.stringify({ ...fixture.manifest, unknown: true })); + if (failure === 'manifest-tamper') fs.writeFileSync(fixture.manifestPath, JSON.stringify({ ...fixture.manifest, driverPort: 7020 })); + if (failure === 'runtime-tamper') fs.writeFileSync(fixture.runtimeModulePath, 'throw new Error("untrusted polyfill");\n'); + expect(() => createDesktopStorybookMetroConfig({ configPath: path.join(root, 'src') })).toThrow(); + expect(fs.existsSync(path.join(root, 'storybook-desktop.generated', 'runtime-instance.js'))).toBe(false); + }, + ); +}); diff --git a/packages/agentic/storybook-desktop/AGENTS.md b/packages/agentic/storybook-desktop/AGENTS.md index 1e327ec2c6..39c5748214 100644 --- a/packages/agentic/storybook-desktop/AGENTS.md +++ b/packages/agentic/storybook-desktop/AGENTS.md @@ -20,6 +20,9 @@ source ownership and validation. native story-root verification. Never accept uncorrelated channel events. - Treat generated manifests, runtime state, native workspaces, and build products as disposable; fix their owning source. +- Generated manifests never authorize native helpers or expose credentials. + Keep the versioned schema in `config/generated-contract.cjs`, preserve the + independent parent handoff, and publish secrets through OS private storage. - Agent manifests use the controlled transport, never upstream channel relays. Keep args refused and manifest-backed smoke selection on driver sessions. - Keep global output formatting on `--reporter`; the child Node test reporter diff --git a/packages/agentic/storybook-desktop/README.md b/packages/agentic/storybook-desktop/README.md index 58166b772b..f039e62b04 100644 --- a/packages/agentic/storybook-desktop/README.md +++ b/packages/agentic/storybook-desktop/README.md @@ -27,6 +27,9 @@ Agent-served channels reject alternate HTTP mutations and never relay client WebSocket frames; selection/reset go through the session-owning driver grant, and args remain unsupported. Non-agent channels are explicitly legacy unprotected mode; see [integration](references/integration.md). +Generated driver manifests contain no credentials. Owner-private bridge and +attachment records have separate nonces, and child processes require the +parent's independent manifest/helper handoff before starting native services. The [reference index](references/README.md) routes platform, readiness, and troubleshooting tasks. Package agents should start from [AGENTS.md](AGENTS.md). diff --git a/packages/agentic/storybook-desktop/config/generated-contract.cjs b/packages/agentic/storybook-desktop/config/generated-contract.cjs new file mode 100644 index 0000000000..14ae2bf679 --- /dev/null +++ b/packages/agentic/storybook-desktop/config/generated-contract.cjs @@ -0,0 +1,176 @@ +// Shared by the Node integration and Metro through the trusted parent handoff. Keep this contract independent of React. +const driverManifestVersion = 3; +const credentialsVersion = 1; +const handoffVersion = 1; + +const text = (value) => typeof value === 'string' && value.length > 0; +const integer = (value) => Number.isSafeInteger(value) && value >= 0; +const port = (value) => integer(value) && value > 0 && value <= 65535; +const oneOf = + (...values) => + (value) => + values.includes(value); +const optional = (check) => (value) => value === undefined || check(value); +const array = (check) => (value) => Array.isArray(value) && value.every(check); +const record = (check) => (value) => + value !== null && typeof value === 'object' && !Array.isArray(value) && Object.values(value).every(check); +const object = (fields) => (value) => + value !== null && + typeof value === 'object' && + !Array.isArray(value) && + Object.keys(value).every((key) => Object.hasOwn(fields, key)) && + Object.entries(fields).every(([key, check]) => check(value[key])); +const endpoint = oneOf('macos', 'windows', 'win32'); +const filename = (value) => text(value) && /^[a-z][a-z0-9-]{0,100}\.(json|js)$/.test(value); +const applicationFields = { + arguments: optional(array(text)), + aumid: optional(text), + bundleIdentifier: optional(text), + executablePath: optional(text), + windowTitle: optional(text), + workingDirectory: optional(text), +}; +const nativeArtifact = object({ + architecture: oneOf('arm64', 'x64'), + artifactId: text, + artifactRoot: text, + buildFingerprint: text, + buildId: text, + compatibilityKey: text, + configuration: oneOf('debug', 'release'), + endpoints: array(endpoint), + executablePath: text, + features: array(text), + origin: oneOf('built', 'cache', 'explicit-path', 'install-root'), + provider: oneOf('macos', 'windows'), + schemaVersion: oneOf(1), + signing: object({ + certificateHash: optional(text), + designatedRequirement: optional(text), + identity: optional(text), + mode: oneOf('adhoc', 'none', 'signed'), + teamId: optional(text), + }), + sourceDigest: text, + wireProtocol: object({ major: integer, minor: integer }), +}); +const storyManifest = object({ + endpoint, + entries: array( + object({ + id: text, + name: text, + packageName: text, + sourcePath: text, + tags: array(text), + title: text, + // These are externally owned authoring contracts, validated by desktop-driver and the callback extractor. + tests: optional(record(() => true)), + wdio: optional( + object({ + cases: optional(array(object({ name: text, options: record(() => true) }))), + digest: text, + exportName: text, + testNames: optional(array(text)), + }), + ), + }), + ), + platformManifestDigest: text, + portablePlanDigest: text, + schemaVersion: oneOf(1), +}); +const driverManifest = object({ + agent: optional( + object({ + application: optional(object(applicationFields)), + descriptor: text, + readyPath: text, + root: optional(text), + }), + ), + application: object({ ...applicationFields, leasePath: text }), + appName: text, + credentials: object({ name: filename, root: text, runtimeModule: filename }), + displayName: text, + driverPort: port, + endpoint, + instanceId: text, + metroPort: port, + nativeDriver: nativeArtifact, + platformManifestDigest: text, + portablePlanDigest: text, + renderer: oneOf('fabric', 'paper'), + schemaVersion: oneOf(driverManifestVersion), + scope: optional(object({ domains: record(array(text)), values: record(text) })), + storyManifest, + storybookPort: port, + targetId: text, + testIDPrefix: text, + wdio: optional( + object({ + clickMode: optional(oneOf('auto', 'accessibility', 'physical')), + input: optional(oneOf('accessible', 'physical')), + reporter: optional(oneOf('spec', 'tap', 'dot')), + story: optional(text), + tag: optional(text), + test: optional(text), + timeoutMs: optional((value) => integer(value) && value > 0 && value <= 2147483647), + }), + ), +}); +const credentials = object({ + bridgeNonce: text, + leaseNonce: text, + manifestDigest: text, + schemaVersion: oneOf(credentialsVersion), +}); +const handoff = object({ + credentialsDigest: text, + manifestDigest: text, + nativeDriver: nativeArtifact, + runtimeModuleDigest: text, + runtimeModulePath: text, + schemaVersion: oneOf(handoffVersion), +}); + +function parse(check, value, kind) { + if (!check(value)) throw new TypeError(`Invalid or unsupported Desktop Storybook ${kind}.`); + return value; +} + +function parseDriverManifest(value) { + const parsed = parse(driverManifest, value, 'driver manifest'); + if ( + parsed.storyManifest.endpoint !== parsed.endpoint || + parsed.storyManifest.platformManifestDigest !== parsed.platformManifestDigest || + parsed.storyManifest.portablePlanDigest !== parsed.portablePlanDigest || + !parsed.nativeDriver.endpoints.includes(parsed.endpoint) || + parsed.nativeDriver.provider !== (parsed.endpoint === 'macos' ? 'macos' : 'windows') || + (parsed.endpoint === 'win32' && parsed.renderer !== 'paper') || + (parsed.agent?.application && + (!parsed.agent.application.windowTitle || (!parsed.agent.application.aumid && !parsed.agent.application.executablePath))) + ) { + throw new TypeError('Inconsistent Desktop Storybook driver manifest identity.'); + } + return parsed; +} + +function parseCredentials(value) { + const parsed = parse(credentials, value, 'credentials'); + if (parsed.bridgeNonce === parsed.leaseNonce) throw new TypeError('Desktop Storybook credentials must have distinct purposes.'); + return parsed; +} + +function parseHandoff(value) { + return parse(handoff, value, 'helper handoff'); +} + +module.exports = { + credentialsVersion, + driverManifestVersion, + handoffVersion, + parseCredentials, + parseDriverManifest, + parseHandoff, +}; diff --git a/packages/agentic/storybook-desktop/config/generated-contract.d.cts b/packages/agentic/storybook-desktop/config/generated-contract.d.cts new file mode 100644 index 0000000000..5d890792f8 --- /dev/null +++ b/packages/agentic/storybook-desktop/config/generated-contract.d.cts @@ -0,0 +1,6 @@ +export const credentialsVersion: 1; +export const driverManifestVersion: 3; +export const handoffVersion: 1; +export function parseCredentials(value: unknown): unknown; +export function parseDriverManifest(value: unknown): unknown; +export function parseHandoff(value: unknown): unknown; diff --git a/packages/agentic/storybook-desktop/config/server.cjs b/packages/agentic/storybook-desktop/config/server.cjs index 2e1ad31efd..c8cfbb5403 100644 --- a/packages/agentic/storybook-desktop/config/server.cjs +++ b/packages/agentic/storybook-desktop/config/server.cjs @@ -116,16 +116,16 @@ async function startDesktopStorybookServer({ }); try { controller.signal.throwIfAborted(); - const driverManifest = driverManifestPath ? JSON.parse(fs.readFileSync(driverManifestPath, 'utf8')) : undefined; - if ( - driverManifest && - (driverManifest.schemaVersion !== 2 || - !driverManifest.nativeDriver || - !driverManifest.application || - typeof driverManifest.application.leasePath !== 'string' || - typeof driverManifest.application.leaseNonce !== 'string') - ) - throw new Error(`Invalid native Desktop Driver manifest at ${driverManifestPath}.`); + let driverManifest; + if (driverManifestPath) { + const { parseStoredDriverManifest, readDriverManifest } = await import('../lib/driver/generatedManifest.js'); + if (process.env.STORYBOOK_NATIVE_DRIVER_FAKE === '1') { + driverManifest = parseStoredDriverManifest(JSON.parse(fs.readFileSync(driverManifestPath, 'utf8'))); + } else { + if (!process.env.STORYBOOK_DRIVER_HANDOFF) throw new Error('Native Storybook requires its trusted parent helper handoff.'); + driverManifest = await readDriverManifest(driverManifestPath, process.env.STORYBOOK_DRIVER_HANDOFF); + } + } const agent = driverManifest?.agent; if ( agent !== undefined && diff --git a/packages/agentic/storybook-desktop/references/contributing.md b/packages/agentic/storybook-desktop/references/contributing.md index 33f470663d..5635bfaef2 100644 --- a/packages/agentic/storybook-desktop/references/contributing.md +++ b/packages/agentic/storybook-desktop/references/contributing.md @@ -24,6 +24,40 @@ remain socket/epoch authenticated, navigation uses driver-owned settlement, and protected args stay refused. Manifest-backed smoke traversal must acquire and release its driver session before authored test sessions start. +## Generated manifest trust + +`config/generated-contract.cjs` is the dependency-free source of the strict +driver-manifest version 3, private-credential version 1, and parent-handoff +version 1 schemas. Unknown generated fields fail, and authored plans and case +options remain validated by their owning desktop-driver validators. + +The public generated JSON contains credential references, never either nonce. +`src/driver/generatedManifest.ts` publishes a credential record and bridge-only +runtime data module through desktop-driver's owner-private storage adapter: +POSIX directory/file modes `0700`/`0600` with ownership/ACL checks on macOS, +and the native owner/DACL/reparse/root-identity boundary on Windows. +The macOS attachment lease stays in that private namespace. Its random nonce +is independent of the runtime bridge nonce; the lease nonce never reaches Metro. + +The parent resolves the native helper independently and passes its artifact +plus manifest, credential, and runtime-module hashes through inherited +`STORYBOOK_DRIVER_HANDOFF`. The actual channel child rejects a mismatched +manifest before verifying or spawning that helper, including before opening +Windows private storage. A hash inside the editable manifest is not authority. +Metro receives the canonical schema locator through the parent's +`STORYBOOK_GENERATED_CONTRACT`, verifies the manifest and private data module +against the handoff, and never reconstructs credentials from public JSON. +The locator is trusted process configuration, not a manifest-controlled path. +This keeps the integration CLI peer-free; the runtime remains app-owned. + +Do not launch a native channel by copying only a generated manifest or by +inventing a handoff from its fields. Use the owning CLI lifecycle. The explicit +fake-driver fixture mode has no native helper or credentials and is not a +production trust path. Exercise Metro evaluation only under controlled fixture +roots because its legacy, non-driver path still generates a runtime data module. +Generated modules contain only `export default `; executable loader +source stays constant and obtains the data through Metro's resolver. + Input lanes cross these areas. The descriptor schema, merge, and per-case decision belong to `@fluentui-react-native/desktop-driver/authoring`; do not copy them here. `src/cli/inputLane.ts` resolves the requested lane, diff --git a/packages/agentic/storybook-desktop/src/cli/DesktopStorybookCli.test.ts b/packages/agentic/storybook-desktop/src/cli/DesktopStorybookCli.test.ts index f55799763d..7c29b8a5dd 100644 --- a/packages/agentic/storybook-desktop/src/cli/DesktopStorybookCli.test.ts +++ b/packages/agentic/storybook-desktop/src/cli/DesktopStorybookCli.test.ts @@ -13,7 +13,9 @@ import { STORYBOOK_SMOKE_MODE } from '../config/commands'; import { DesktopStorybookConfig, makeDesktopStorybookConfig } from '../config/makeDesktopStorybookConfig'; import { FURN_STORYBOOK_BUNDLE_IDENTIFIER, FURN_STORYBOOK_INSTANCE_ID } from '../config/instance'; import { FURN_STORYBOOK_PLATFORM } from '../config/platforms'; -import { desktopStorybookTargetId } from '../driver/driverManifest'; +import { createDesktopStorybookDriverManifest, writeDesktopStorybookDriverManifest } from '../driver/driverManifest'; +import { createFixturePrivateStorage } from '../driver/fixtures/privateStorage'; +import { readDriverManifest } from '../driver/generatedManifest'; import * as wdioTests from '../testing/runWdioTests'; import type { DesktopCommandRunner, PreparedDesktopCommand, RunningDesktopCommand } from './commandRunner'; import { createDesktopStorybookCommand } from './createDesktopStorybookCommand'; @@ -68,11 +70,17 @@ const nativeDriverArtifact: NativeDriverArtifact = { wireProtocol: { major: 1, minor: 0 }, }; const nativeDriverTestOptions = { + createPrivateStorage: createFixturePrivateStorage, buildNativeDriver: async () => nativeDriverArtifact, - resolveNativeDriver: async () => nativeDriverArtifact, + resolveNativeDriver: async ({ platform }: { platform: string }) => nativeDriverFor(platform), writeMacOSApplicationLease: async () => undefined, connectStoryTraversal: async () => ({ select: async () => undefined, close: async () => null }), }; +function nativeDriverFor(platform: string): NativeDriverArtifact { + return platform === 'macos' + ? { ...nativeDriverArtifact, provider: 'macos', endpoints: ['macos'], signing: { mode: 'adhoc' } } + : { ...nativeDriverArtifact, endpoints: ['windows', 'win32'] }; +} const createEmptyStoryManifest = async (_config: unknown, platform: 'macos' | 'windows' | 'win32') => ({ endpoint: platform, entries: [], @@ -165,11 +173,20 @@ describe('macOS application leases', () => { test('keeps the lease naming the one running application', async () => { const root = fs.mkdtempSync(path.join(os.tmpdir(), 'furn-storybook-macos-lease-')); - const leasePath = path.join(root, 'application.json'); + const leasePath = path.join(root, '.private', 'application-lease.macos.json'); const manifestPath = path.join(root, 'driver-manifest.json'); - fs.writeFileSync( + const config = makeConfig(); + const created = createDesktopStorybookDriverManifest({ + config, + instance: new DesktopStorybookCli(config).instance, + nativeDriver: nativeDriverFor('macos'), + platform: 'macos', + storyManifest: await createEmptyStoryManifest(config, 'macos'), + }); + await writeDesktopStorybookDriverManifest( + { ...created, application: { ...created.application, bundleIdentifier: 'com.example.storybook', leasePath } }, manifestPath, - JSON.stringify({ application: { bundleIdentifier: 'com.example.storybook', leaseNonce: 'nonce', leasePath } }), + createFixturePrivateStorage, ); const running = (processId: number): MacOSRunningApplication => ({ executablePath: '/Applications/Storybook.app/Contents/MacOS/Storybook', @@ -199,6 +216,7 @@ describe('macOS application leases', () => { await expect( maintainMacOSApplicationLease(manifestPath, controller.signal, { intervalMs: 1, + createPrivateStorage: createFixturePrivateStorage, onWarning: (message) => warnings.push(message), queryApplications: async (bundleIdentifier) => { expect(bundleIdentifier).toBe('com.example.storybook'); @@ -487,16 +505,17 @@ describe('DesktopStorybookCli', () => { output: { write: jest.fn() }, }); fs.mkdirSync(path.dirname(manifestPath), { recursive: true }); - fs.writeFileSync( - manifestPath, - JSON.stringify({ - endpoint: 'macos', - instanceId: cli.instance.id, - renderer: 'fabric', - driverPort: 7100, - targetId: desktopStorybookTargetId(config(), 'macos', 'fabric'), + await writeDesktopStorybookDriverManifest( + createDesktopStorybookDriverManifest({ + config: config(), + instance: { ...cli.instance, driverPort: 7100 }, + nativeDriver: nativeDriverFor('macos'), + platform: 'macos', + storyManifest: await createEmptyStoryManifest(config(), 'macos'), wdio: { input: 'accessible' }, }), + manifestPath, + createFixturePrivateStorage, ); try { // The only case needs a physical keyboard, so only the inherited accessible lane can leave it out. @@ -621,15 +640,15 @@ describe('DesktopStorybookCli', () => { try { await expect(new DesktopStorybookCli(makeConfig(), options).driver('macos')).rejects.toThrow('exited unexpectedly'); - const fabricManifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8')); + const fabricManifest = await readDriverManifest(manifestPath, undefined, createFixturePrivateStorage); await expect(new DesktopStorybookCli(makeConfig(), { ...options, paper: true }).driver('macos')).rejects.toThrow( 'exited unexpectedly', ); - const paperManifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8')); + const paperManifest = await readDriverManifest(manifestPath, undefined, createFixturePrivateStorage); await expect(new DesktopStorybookCli(makeConfig(), { ...options, paper: true }).driver('macos')).rejects.toThrow( 'exited unexpectedly', ); - const repeatedPaperManifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8')); + const repeatedPaperManifest = await readDriverManifest(manifestPath, undefined, createFixturePrivateStorage); expect(fabricManifest.renderer).toBe('fabric'); expect(paperManifest.renderer).toBe('paper'); @@ -1195,7 +1214,7 @@ describe('DesktopStorybookCli', () => { test('runs authored tests after traversing the complete story index', async () => { const runner = new RecordingRunner(); - const resolveNativeDriver = jest.fn(async () => nativeDriverArtifact); + const resolveNativeDriver = jest.fn(async () => nativeDriverFor('macos')); const events: string[] = []; const writeMacOSApplicationLease = jest.fn(async () => { events.push('lease'); @@ -1671,7 +1690,7 @@ describe('createDesktopStorybookCommand', () => { args: ['start', '--no-interactive', '--port', expect.any(String)], env: { STORYBOOK_DRIVER_MANIFEST: manifestPath }, }); - const firstManifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8')) as Record; + const firstManifest = await readDriverManifest(manifestPath, undefined, createFixturePrivateStorage); expect(firstManifest).toMatchObject({ endpoint: 'win32', targetId: 'agenticstorybook-win32', @@ -1690,7 +1709,7 @@ describe('createDesktopStorybookCommand', () => { await expect( secondProgram.parseAsync(['node', 'test', 'driver', '--win32', '--host', 'localhost', '--port', '7102']), ).rejects.toThrow('exited unexpectedly'); - const secondManifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8')) as Record; + const secondManifest = await readDriverManifest(manifestPath, undefined, createFixturePrivateStorage); expect(secondManifest.bridgeNonce).toBe(firstManifest.bridgeNonce); } finally { fs.rmSync(manifestPath, { force: true }); diff --git a/packages/agentic/storybook-desktop/src/cli/DesktopStorybookCli.ts b/packages/agentic/storybook-desktop/src/cli/DesktopStorybookCli.ts index 48d478571e..436627b042 100644 --- a/packages/agentic/storybook-desktop/src/cli/DesktopStorybookCli.ts +++ b/packages/agentic/storybook-desktop/src/cli/DesktopStorybookCli.ts @@ -1,4 +1,5 @@ import { spawn } from 'node:child_process'; +import { randomUUID } from 'node:crypto'; import fs from 'node:fs'; import { createServer } from 'node:net'; import path from 'node:path'; @@ -50,6 +51,12 @@ import { type CreateDesktopStorybookDriverManifestOptions, type DesktopStorybookDriverManifest, } from '../driver/driverManifest.js'; +import { + createStorybookPrivateStorage, + parseStoredDriverManifest, + readDriverManifest, + type CreateStorybookPrivateStorage, +} from '../driver/generatedManifest.js'; import { NodeDesktopCommandRunner, STORYBOOK_VERBOSE } from './commandRunner.js'; import type { DesktopCommandRunner, PreparedDesktopCommand, RunningDesktopCommand } from './commandRunner.js'; import { formatDesktopStorybookSmokeTestSummary, runDesktopStorybookSmokeTests } from './smokeTests.js'; @@ -86,6 +93,8 @@ export type DesktopStorybookCliOptions = { runSmokeTests?: typeof runDesktopStorybookSmokeTests; connectStoryTraversal?: typeof connectStoryTraversal; resolveNativeDriver?: typeof resolveNativeDesktopDriver; + /** Trusted OS storage adapter override for controlled fixtures. */ + createPrivateStorage?: CreateStorybookPrivateStorage; /** Resolves a Windows or Win32 desktop target's verified application identity for `driver --agent`. */ resolveDesktopApplication?: typeof resolveDesktopApplication; writeMacOSApplicationLease?: typeof writeMacOSApplicationLease; @@ -139,6 +148,8 @@ export class DesktopStorybookCli { private readonly runSmokeTests: typeof runDesktopStorybookSmokeTests; private readonly connectStoryTraversal: typeof connectStoryTraversal; private readonly resolveNativeDriver: typeof resolveNativeDesktopDriver; + private readonly createPrivateStorage: CreateStorybookPrivateStorage; + private readonly driverHandoffs = new Map(); private readonly resolveDesktopApplication: typeof resolveDesktopApplication; private readonly writeMacOSApplicationLease: typeof writeMacOSApplicationLease; private readonly maintainMacOSApplicationLease: typeof maintainMacOSApplicationLease; @@ -184,6 +195,7 @@ export class DesktopStorybookCli { this.runSmokeTests = options.runSmokeTests ?? runDesktopStorybookSmokeTests; this.connectStoryTraversal = options.connectStoryTraversal ?? connectStoryTraversal; this.resolveNativeDriver = options.resolveNativeDriver ?? resolveNativeDesktopDriver; + this.createPrivateStorage = options.createPrivateStorage ?? createStorybookPrivateStorage; this.resolveDesktopApplication = options.resolveDesktopApplication ?? resolveDesktopApplication; this.writeMacOSApplicationLease = options.writeMacOSApplicationLease ?? writeMacOSApplicationLease; this.maintainMacOSApplicationLease = options.maintainMacOSApplicationLease ?? maintainMacOSApplicationLease; @@ -456,7 +468,7 @@ export class DesktopStorybookCli { if (!fs.existsSync(manifestPath)) { throw new Error(`Start storybook driver --${platform} and launch the app before running storybook test.`); } - const manifest: unknown = JSON.parse(fs.readFileSync(manifestPath, 'utf8')); + const manifest = parseStoredDriverManifest(JSON.parse(fs.readFileSync(manifestPath, 'utf8'))); if ( typeof manifest !== 'object' || manifest === null || @@ -779,7 +791,14 @@ export class DesktopStorybookCli { const renderer = this.renderer(platform); const driverManifest = createDesktopStorybookDriverManifest({ ...(agent ? { agent } : {}), - bridgeNonce: readReusableBridgeNonce(outputPath, instance, storyManifest.platformManifestDigest, renderer), + bridgeNonce: await readReusableBridgeNonce( + outputPath, + instance, + storyManifest.platformManifestDigest, + renderer, + nativeDriver, + this.createPrivateStorage, + ), config: this.config, instance, nativeDriver, @@ -789,7 +808,8 @@ export class DesktopStorybookCli { storyManifest, ...(wdio ? { wdio } : {}), }); - writeDesktopStorybookDriverManifest(driverManifest, outputPath); + const handoff = await writeDesktopStorybookDriverManifest(driverManifest, outputPath, this.createPrivateStorage); + this.driverHandoffs.set(outputPath, handoff); return { manifest: driverManifest, path: outputPath }; } @@ -1057,7 +1077,16 @@ export class DesktopStorybookCli { [FURN_STORYBOOK_BUNDLE_IDENTIFIER]: instance.bundleIdentifier, STORYBOOK_WS_PORT: String(instance.storybookPort), STORYBOOK_DRIVER_PORT: String(instance.driverPort), - ...(instance.driverManifestPath ? { STORYBOOK_DRIVER_MANIFEST: instance.driverManifestPath } : {}), + ...(instance.driverManifestPath + ? { + STORYBOOK_DRIVER_MANIFEST: instance.driverManifestPath, + STORYBOOK_DRIVER_HANDOFF: this.driverHandoffs.get(instance.driverManifestPath) ?? '', + STORYBOOK_GENERATED_CONTRACT: path.join( + this.config.resolvePackage('@fluentui-react-native/storybook-desktop').root, + 'config/generated-contract.cjs', + ), + } + : {}), RCT_METRO_PORT: String(instance.metroPort), ...(instance.macosXcconfigPath ? { XCODE_XCCONFIG_FILE: instance.macosXcconfigPath } : {}), } @@ -1082,17 +1111,19 @@ function reportOutput( }; } -function readReusableBridgeNonce( +async function readReusableBridgeNonce( manifestPath: string, instance: DesktopStorybookInstance, platformManifestDigest: string, renderer: 'fabric' | 'paper', -): string | undefined { + nativeDriver: NativeDriverArtifact, + createStorage: CreateStorybookPrivateStorage, +): Promise { if (!fs.existsSync(manifestPath)) { return undefined; } try { - const current = JSON.parse(fs.readFileSync(manifestPath, 'utf8')) as Record; + const current = await readDriverManifest(manifestPath, undefined, createStorage, nativeDriver); return current.instanceId === instance.id && current.storybookPort === instance.storybookPort && current.driverPort === instance.driverPort && @@ -1139,7 +1170,7 @@ export async function writeMacOSApplicationLease(manifestPath: string, timeoutMs if (process.platform !== 'darwin') { throw new Error('A macOS application lease can only be written on macOS.'); } - const application = readMacOSLeaseApplication(manifestPath); + const application = await readMacOSLeaseApplication(manifestPath); const runningApplication = await waitForMacOSApplication(application.bundleIdentifier, timeoutMs); writeMacOSApplicationLeaseFile(application, runningApplication); } @@ -1150,6 +1181,8 @@ export type MaintainMacOSApplicationLeaseOptions = { queryApplications?: (bundleIdentifier: string) => Promise; /** Receives each distinct query failure once, such as more than one running instance. */ onWarning?: (message: string) => void; + /** Trusted OS storage adapter override for controlled fixtures. */ + createPrivateStorage?: CreateStorybookPrivateStorage; }; /** @@ -1160,13 +1193,13 @@ export type MaintainMacOSApplicationLeaseOptions = { export async function maintainMacOSApplicationLease( manifestPath: string, signal: AbortSignal, - { intervalMs = 2000, queryApplications, onWarning }: MaintainMacOSApplicationLeaseOptions = {}, + { intervalMs = 2000, queryApplications, onWarning, createPrivateStorage }: MaintainMacOSApplicationLeaseOptions = {}, ): Promise { if (!queryApplications && process.platform !== 'darwin') { throw new Error('A macOS application lease can only be written on macOS.'); } const query = queryApplications ?? queryMacOSApplications; - const application = readMacOSLeaseApplication(manifestPath); + const application = await readMacOSLeaseApplication(manifestPath, createPrivateStorage); let leased: string | undefined; let warned: string | undefined; for (;;) { @@ -1194,14 +1227,11 @@ export async function maintainMacOSApplicationLease( } } -function readMacOSLeaseApplication(manifestPath: string): { bundleIdentifier: string; leaseNonce: string; leasePath: string } { - const manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8')) as { - application?: { - bundleIdentifier?: string; - leaseNonce?: string; - leasePath?: string; - }; - }; +async function readMacOSLeaseApplication( + manifestPath: string, + createStorage?: CreateStorybookPrivateStorage, +): Promise<{ bundleIdentifier: string; leaseNonce: string; leasePath: string }> { + const manifest = await readDriverManifest(manifestPath, undefined, createStorage); const application = manifest.application; if (!application?.bundleIdentifier || !application.leaseNonce || !application.leasePath) { throw new Error(`The Desktop Driver manifest at "${manifestPath}" does not contain a complete macOS application descriptor.`); @@ -1215,7 +1245,7 @@ export function writeMacOSApplicationLeaseFile( ): void { validateMacOSRunningApplication(runningApplication); const processStartedAt = new Date(runningApplication.processStartedAt * 1000); - const temporaryPath = `${application.leasePath}.${process.pid}.tmp`; + const temporaryPath = `${application.leasePath}.${randomUUID()}.tmp`; fs.mkdirSync(path.dirname(application.leasePath), { mode: 0o700, recursive: true }); try { fs.writeFileSync( @@ -1233,7 +1263,7 @@ export function writeMacOSApplicationLeaseFile( null, 2, )}\n`, - { mode: 0o600 }, + { flag: 'wx', mode: 0o600 }, ); fs.renameSync(temporaryPath, application.leasePath); fs.chmodSync(application.leasePath, 0o600); diff --git a/packages/agentic/storybook-desktop/src/driver/StorybookChannelOrchestrator.test.ts b/packages/agentic/storybook-desktop/src/driver/StorybookChannelOrchestrator.test.ts index f595c4097b..778b114d46 100644 --- a/packages/agentic/storybook-desktop/src/driver/StorybookChannelOrchestrator.test.ts +++ b/packages/agentic/storybook-desktop/src/driver/StorybookChannelOrchestrator.test.ts @@ -81,7 +81,7 @@ const manifest: DesktopStorybookDriverManifest = { platformManifestDigest: 'platform', portablePlanDigest: 'portable', renderer: 'fabric', - schemaVersion: 2, + schemaVersion: 3, storyManifest: { endpoint: 'windows', entries: [ diff --git a/packages/agentic/storybook-desktop/src/driver/driverManifest.test.ts b/packages/agentic/storybook-desktop/src/driver/driverManifest.test.ts index 769ed9f9d2..bb0ac19487 100644 --- a/packages/agentic/storybook-desktop/src/driver/driverManifest.test.ts +++ b/packages/agentic/storybook-desktop/src/driver/driverManifest.test.ts @@ -7,6 +7,8 @@ import type { DesktopStoryManifest, NativeDriverArtifact } from '@fluentui-react import { createDesktopStorybookInstance } from '../config/instance'; import { makeDesktopStorybookConfig } from '../config/makeDesktopStorybookConfig'; import { createDesktopStorybookDriverManifest, writeDesktopStorybookDriverManifest } from './driverManifest'; +import { createFixturePrivateStorage } from './fixtures/privateStorage'; +import { readDriverManifest } from './generatedManifest'; const storybookRoot = path.resolve(__dirname, '../../../../../apps/storybook'); const storyManifest: DesktopStoryManifest = { @@ -53,14 +55,15 @@ describe('Desktop Storybook driver manifest', () => { expect(manifest).toMatchObject({ application: { - leaseNonce: 'nonce', - leasePath: path.join(storybookRoot, 'storybook-desktop.generated', 'application-lease.windows.json'), + leaseNonce: expect.any(String), + leasePath: path.join(storybookRoot, 'storybook-desktop.generated', '.private', 'application-lease.windows.json'), windowTitle: 'Agentic Components Storybook', }, nativeDriver, - schemaVersion: 2, + schemaVersion: 3, wdio: { timeoutMs: 12_345, tag: 'smoke', reporter: 'tap' }, }); + expect(manifest.application.leaseNonce).not.toBe(manifest.bridgeNonce); const macosManifest = createDesktopStorybookDriverManifest({ bridgeNonce: 'nonce', @@ -78,7 +81,7 @@ describe('Desktop Storybook driver manifest', () => { }); expect(macosManifest.application).toMatchObject({ bundleIdentifier: instance.bundleIdentifier, - leasePath: path.join(storybookRoot, 'storybook-desktop.generated', 'application-lease.macos.json'), + leasePath: path.join(storybookRoot, 'storybook-desktop.generated', '.private', 'application-lease.macos.json'), }); expect(macosManifest.renderer).toBe('fabric'); }); @@ -106,7 +109,7 @@ describe('Desktop Storybook driver manifest', () => { }); }); - test('removes a stale application lease and agent readiness record before writing a new manifest', () => { + test('removes stale readiness and leases, publishing secrets only through private storage', async () => { const temporaryDirectory = fs.mkdtempSync(path.join(os.tmpdir(), 'storybook-driver-manifest-')); try { const config = makeDesktopStorybookConfig({ @@ -134,17 +137,25 @@ describe('Desktop Storybook driver manifest', () => { const manifest = { ...created, agent: { descriptor: 'agent.json', readyPath }, - application: { ...created.application, leasePath: path.join(temporaryDirectory, 'application-lease.windows.json') }, + application: { ...created.application, leasePath: path.join(temporaryDirectory, '.private', 'application-lease.windows.json') }, }; + fs.mkdirSync(path.dirname(manifest.application.leasePath), { recursive: true, mode: 0o700 }); fs.writeFileSync(manifest.application.leasePath, '{}'); fs.writeFileSync(readyPath, '{}'); const outputPath = path.join(temporaryDirectory, 'driver-manifest.json'); - writeDesktopStorybookDriverManifest(manifest, outputPath); + await writeDesktopStorybookDriverManifest(manifest, outputPath, createFixturePrivateStorage); expect(fs.existsSync(manifest.application.leasePath)).toBe(false); expect(fs.existsSync(readyPath)).toBe(false); - expect(JSON.parse(fs.readFileSync(outputPath, 'utf8'))).toMatchObject({ schemaVersion: 2 }); + const serialized = fs.readFileSync(outputPath, 'utf8'); + expect(JSON.parse(serialized)).toMatchObject({ schemaVersion: 3 }); + expect(serialized).not.toContain('"leaseNonce"'); + expect(serialized).not.toContain('"bridgeNonce"'); + await expect(readDriverManifest(outputPath, undefined, createFixturePrivateStorage)).resolves.toMatchObject({ + bridgeNonce: 'nonce', + application: { leaseNonce: created.application.leaseNonce }, + }); } finally { fs.rmSync(temporaryDirectory, { force: true, recursive: true }); } diff --git a/packages/agentic/storybook-desktop/src/driver/driverManifest.ts b/packages/agentic/storybook-desktop/src/driver/driverManifest.ts index 3e4ac5b7a0..388ddca8aa 100644 --- a/packages/agentic/storybook-desktop/src/driver/driverManifest.ts +++ b/packages/agentic/storybook-desktop/src/driver/driverManifest.ts @@ -1,6 +1,6 @@ import { randomBytes } from 'node:crypto'; -import fs from 'node:fs'; import path from 'node:path'; +import { driverManifestVersion } from '../../config/generated-contract.cjs'; import type { DesktopStoryManifest, NativeDesktopApplicationDescriptor, NativeDriverArtifact } from '@fluentui-react-native/desktop-driver'; import type { DesktopInputLane } from '@fluentui-react-native/desktop-driver/authoring'; @@ -11,6 +11,8 @@ import type { DesktopStorybookInstance } from '../config/instance.js'; import type { Platforms } from '../config/platforms.js'; import type { DesktopStorybookWdioOptions } from '../config/wdio.js'; import type { WdioSelectionContext } from '../testing/selection.js'; +import { publishDriverManifest } from './generatedManifest.js'; +import type { CreateStorybookPrivateStorage } from './generatedManifest.js'; /** Asks the channel service to protect its driver with a grant authority and publish one agent's connection. */ export type DesktopStorybookAgentManifest = { @@ -44,7 +46,7 @@ export type DesktopStorybookDriverManifest = { platformManifestDigest: string; portablePlanDigest: string; renderer: 'fabric' | 'paper'; - schemaVersion: 2; + schemaVersion: 3; /** * The scope domains and the values this target holds, which declared test `scope` selection reads. The driver's * CLI resolves them from the full desktop configuration, which a smoke control process does not have. @@ -98,7 +100,7 @@ export function createDesktopStorybookDriverManifest({ throw new Error(`Native Desktop Driver is disabled for ${platform}.`); } const generated = path.join(config.projectRoot, 'storybook-desktop.generated'); - const leasePath = path.join(generated, `application-lease.${platform}.json`); + const leasePath = path.join(generated, '.private', `application-lease.${platform}.json`); return Object.freeze({ ...(agent ? { @@ -113,7 +115,7 @@ export function createDesktopStorybookDriverManifest({ application: Object.freeze({ ...nativeOptions.application, ...(platform === 'macos' ? { bundleIdentifier: instance.bundleIdentifier } : {}), - leaseNonce: bridgeNonce, + leaseNonce: randomBytes(24).toString('base64url'), leasePath, }), appName: config.appName, @@ -127,7 +129,7 @@ export function createDesktopStorybookDriverManifest({ platformManifestDigest: storyManifest.platformManifestDigest, portablePlanDigest: storyManifest.portablePlanDigest, renderer, - schemaVersion: 2, + schemaVersion: driverManifestVersion, ...(scope ? { scope: Object.freeze({ domains: Object.freeze({ ...scope.domains }), values: Object.freeze({ ...scope.values }) }) } : {}), @@ -139,14 +141,12 @@ export function createDesktopStorybookDriverManifest({ }); } -export function writeDesktopStorybookDriverManifest(manifest: DesktopStorybookDriverManifest, outputPath: string): void { - fs.mkdirSync(path.dirname(outputPath), { recursive: true }); - fs.rmSync(manifest.application.leasePath, { force: true }); - if (manifest.agent) fs.rmSync(manifest.agent.readyPath, { force: true }); - const content = `${JSON.stringify(manifest, null, 2)}\n`; - if (!fs.existsSync(outputPath) || fs.readFileSync(outputPath, 'utf8') !== content) { - fs.writeFileSync(outputPath, content); - } +export function writeDesktopStorybookDriverManifest( + manifest: DesktopStorybookDriverManifest, + outputPath: string, + createStorage?: CreateStorybookPrivateStorage, +): Promise { + return publishDriverManifest(manifest, outputPath, createStorage); } /** Where the running driver instance for an endpoint publishes its manifest. */ diff --git a/packages/agentic/storybook-desktop/src/driver/fixtures/privateStorage.ts b/packages/agentic/storybook-desktop/src/driver/fixtures/privateStorage.ts new file mode 100644 index 0000000000..9e36daf636 --- /dev/null +++ b/packages/agentic/storybook-desktop/src/driver/fixtures/privateStorage.ts @@ -0,0 +1,24 @@ +import fs from 'node:fs'; +import path from 'node:path'; + +import type { CreateStorybookPrivateStorage } from '../generatedManifest.js'; + +/** Test-only storage. Real OS ownership qualification uses the shipped private-storage adapters. */ +export const createFixturePrivateStorage: CreateStorybookPrivateStorage = async (root) => { + fs.mkdirSync(root, { recursive: true, mode: 0o700 }); + return { + async read(name) { + const filename = path.join(root, name); + return fs.existsSync(filename) ? fs.readFileSync(filename, 'utf8') : undefined; + }, + async publish(name, contents) { + fs.writeFileSync(path.join(root, name), contents, { flag: 'wx', mode: 0o600 }); + }, + async remove(name, expectedContents) { + const filename = path.join(root, name); + if (!fs.existsSync(filename) || fs.readFileSync(filename, 'utf8') !== expectedContents) return false; + fs.unlinkSync(filename); + return true; + }, + }; +}; diff --git a/packages/agentic/storybook-desktop/src/driver/generatedManifest.test.ts b/packages/agentic/storybook-desktop/src/driver/generatedManifest.test.ts new file mode 100644 index 0000000000..12c83b6ddc --- /dev/null +++ b/packages/agentic/storybook-desktop/src/driver/generatedManifest.test.ts @@ -0,0 +1,192 @@ +import { createHash } from 'node:crypto'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; + +import type { NativeDriverArtifact } from '@fluentui-react-native/desktop-driver'; +import { createDesktopStorybookInstance } from '../config/instance'; +import { makeDesktopStorybookConfig } from '../config/makeDesktopStorybookConfig'; +import { createDesktopStorybookDriverManifest, writeDesktopStorybookDriverManifest } from './driverManifest'; +import { createFixturePrivateStorage } from './fixtures/privateStorage'; +import { parseStoredDriverManifest, readDriverManifest } from './generatedManifest'; + +const appRoot = path.resolve(__dirname, '../../../../../apps/storybook'); +const hash = (contents: string) => createHash('sha256').update(contents).digest('hex'); +const maliciousHelper = "#!/usr/bin/env node\nrequire('node:fs').writeFileSync(process.env.FURN_TEST_SPAWN_MARKER, 'spawned');\n"; + +describe('generated manifest trust handoff', () => { + let root: string; + let manifestPath: string; + let marker: string; + let handoff: string; + + beforeEach(async () => { + root = fs.mkdtempSync(path.join(os.tmpdir(), 'storybook-provenance-')); + manifestPath = path.join(root, 'driver-manifest.json'); + marker = path.join(root, 'unexpected-spawn'); + process.env.FURN_TEST_SPAWN_MARKER = marker; + const executablePath = path.join(root, 'helper'); + fs.writeFileSync(executablePath, '#!/usr/bin/env node\nprocess.exit(0);\n', { mode: 0o700 }); + const nativeDriver: NativeDriverArtifact = { + architecture: 'x64', + artifactId: hash(fs.readFileSync(executablePath, 'utf8')), + artifactRoot: root, + buildFingerprint: 'build', + buildId: 'build-id', + compatibilityKey: 'compatibility', + configuration: 'release', + endpoints: ['windows', 'win32'], + executablePath, + features: ['probe'], + origin: 'cache', + provider: 'windows', + schemaVersion: 1, + signing: { mode: 'none' }, + sourceDigest: 'source', + wireProtocol: { major: 1, minor: 0 }, + }; + const config = makeDesktopStorybookConfig({ projectRoot: appRoot }); + const manifest = createDesktopStorybookDriverManifest({ + config, + instance: createDesktopStorybookInstance({ projectRoot: appRoot, bundleIdentifierPrefix: config.macosBundleIdentifier }), + nativeDriver, + platform: 'windows', + storyManifest: { + endpoint: 'windows', + entries: [], + platformManifestDigest: 'platform', + portablePlanDigest: 'portable', + schemaVersion: 1, + }, + }); + handoff = await writeDesktopStorybookDriverManifest( + { ...manifest, application: { ...manifest.application, leasePath: path.join(root, '.private', 'application-lease.windows.json') } }, + manifestPath, + createFixturePrivateStorage, + ); + }); + afterEach(() => { + delete process.env.FURN_TEST_SPAWN_MARKER; + fs.rmSync(root, { force: true, recursive: true }); + }); + + test.each(['executablePath', 'artifactId', 'sourceDigest', 'signing'] as const)( + 'refuses a substituted %s before the helper can spawn, even with a matching editable hash', + async (field) => { + const manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8')); + const executable = path.join(root, 'untrusted-helper'); + fs.writeFileSync(executable, maliciousHelper, { mode: 0o700 }); + if (field === 'signing') manifest.nativeDriver.signing = { mode: 'signed', identity: 'untrusted' }; + else manifest.nativeDriver[field] = field === 'executablePath' ? executable : 'changed'; + manifest.nativeDriver.artifactId = hash(maliciousHelper); + fs.writeFileSync(manifestPath, JSON.stringify(manifest)); + await expect(readDriverManifest(manifestPath, handoff, createFixturePrivateStorage)).rejects.toThrow('trusted parent handoff'); + expect(fs.existsSync(marker)).toBe(false); + }, + ); + + test('rehashes the independently pinned executable before even the verification handshake can spawn it', async () => { + const manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8')); + fs.writeFileSync(manifest.nativeDriver.executablePath, maliciousHelper); + await expect(readDriverManifest(manifestPath, handoff, createFixturePrivateStorage)).rejects.toThrow('hash does not match'); + expect(fs.existsSync(marker)).toBe(false); + }); + + test.each(['root', 'nativeDriver', 'signing', 'application', 'agent', 'credentials', 'wdio', 'storyManifest'])( + 'rejects unknown %s fields instead of stripping them', + (section) => { + const manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8')); + const object = + section === 'root' + ? manifest + : section === 'signing' + ? manifest.nativeDriver.signing + : section === 'agent' + ? (manifest.agent = { descriptor: 'agent.json', readyPath: path.join(root, 'ready.json') }) + : section === 'wdio' + ? (manifest.wdio = {}) + : manifest[section]; + object.unrecognized = true; + expect(() => parseStoredDriverManifest(manifest)).toThrow('driver manifest'); + }, + ); + + test('rejects unknown schema versions and credential reuse', async () => { + const manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8')); + expect(() => parseStoredDriverManifest({ ...manifest, schemaVersion: 2 })).toThrow('driver manifest'); + const credentialsPath = path.join(manifest.credentials.root, manifest.credentials.name); + const credentials = JSON.parse(fs.readFileSync(credentialsPath, 'utf8')); + credentials.leaseNonce = credentials.bridgeNonce; + fs.writeFileSync(credentialsPath, JSON.stringify(credentials)); + await expect(readDriverManifest(manifestPath, undefined, createFixturePrivateStorage)).rejects.toThrow('distinct purposes'); + }); + + test.each(['credentials', 'handoff'])('rejects unknown %s fields', async (section) => { + if (section === 'handoff') { + await expect( + readDriverManifest(manifestPath, JSON.stringify({ ...JSON.parse(handoff), unknown: true }), createFixturePrivateStorage), + ).rejects.toThrow('helper handoff'); + expect(fs.existsSync(marker)).toBe(false); + } else { + const manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8')); + const credentialsPath = path.join(manifest.credentials.root, manifest.credentials.name); + fs.writeFileSync(credentialsPath, JSON.stringify({ ...JSON.parse(fs.readFileSync(credentialsPath, 'utf8')), unknown: true })); + await expect(readDriverManifest(manifestPath, undefined, createFixturePrivateStorage)).rejects.toThrow('credentials'); + } + }); + + test.each(['tests', 'options'])('delegates unknown authored %s fields to their owning validators', (section) => { + const manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8')); + manifest.storyManifest.entries = [ + { + id: 'fixture--story', + name: 'Story', + packageName: 'fixture', + sourcePath: 'Fixture.stories.tsx', + tags: [], + title: 'Fixture', + ...(section === 'tests' + ? { tests: { version: 1, tests: [], unknown: true } } + : { wdio: { digest: 'digest', exportName: 'Story', cases: [{ name: 'case', options: { unknown: true } }] } }), + }, + ]; + expect(() => parseStoredDriverManifest(manifest)).toThrow('unknown field'); + }); + + (process.platform === 'darwin' ? test : test.skip)( + 'publishes and reads real macOS owner-private records, refusing a permissive credential mode', + async () => { + const fixture = await readDriverManifest(manifestPath, undefined, createFixturePrivateStorage); + fs.rmSync(path.join(root, '.private'), { recursive: true }); + await writeDesktopStorybookDriverManifest(fixture, manifestPath); + const hydrated = await readDriverManifest(manifestPath); + expect(hydrated.bridgeNonce).toBe(fixture.bridgeNonce); + expect(hydrated.application.leaseNonce).toBe(fixture.application.leaseNonce); + const stored = JSON.parse(fs.readFileSync(manifestPath, 'utf8')); + expect(fs.statSync(stored.credentials.root).mode & 0o777).toBe(0o700); + for (const name of [stored.credentials.name, stored.credentials.runtimeModule]) { + expect(fs.statSync(path.join(stored.credentials.root, name)).mode & 0o777).toBe(0o600); + } + fs.chmodSync(path.join(stored.credentials.root, stored.credentials.name), 0o644); + await expect(readDriverManifest(manifestPath)).rejects.toThrow(); + }, + ); + + test('projects only the bridge credential into the runtime, keeping both secrets out of the public manifest', async () => { + const contents = fs.readFileSync(manifestPath, 'utf8'); + const stored = JSON.parse(contents); + const manifest = await readDriverManifest(manifestPath, undefined, createFixturePrivateStorage); + expect(manifest.application.leaseNonce).not.toBe(manifest.bridgeNonce); + expect(contents).not.toContain(manifest.bridgeNonce); + expect(contents).not.toContain(manifest.application.leaseNonce); + const runtimePath = path.join(stored.credentials.root, stored.credentials.runtimeModule); + const runtime = fs.readFileSync(runtimePath, 'utf8'); + expect(runtime).toContain(manifest.bridgeNonce); + expect(runtime).not.toContain(manifest.application.leaseNonce); + if (process.platform !== 'win32') { + expect(fs.statSync(stored.credentials.root).mode & 0o777).toBe(0o700); + expect(fs.statSync(runtimePath).mode & 0o777).toBe(0o600); + expect(fs.statSync(path.join(stored.credentials.root, stored.credentials.name)).mode & 0o777).toBe(0o600); + } + }); +}); diff --git a/packages/agentic/storybook-desktop/src/driver/generatedManifest.ts b/packages/agentic/storybook-desktop/src/driver/generatedManifest.ts new file mode 100644 index 0000000000..28a70007c6 --- /dev/null +++ b/packages/agentic/storybook-desktop/src/driver/generatedManifest.ts @@ -0,0 +1,175 @@ +import { createHash, randomUUID } from 'node:crypto'; +import fs from 'node:fs'; +import path from 'node:path'; + +import { createMacOSPrivateStorage, createWindowsPrivateStorage } from '@fluentui-react-native/desktop-driver/authority'; +import type { PrivateStorage } from '@fluentui-react-native/desktop-driver/authority'; +import { verifyNativeDriverArtifact } from '@fluentui-react-native/desktop-driver/native'; +import type { NativeDriverArtifact } from '@fluentui-react-native/desktop-driver'; +import { validateDesktopCaseOptions, validateDesktopStoryTests } from '@fluentui-react-native/desktop-driver/authoring'; +import { + credentialsVersion, + handoffVersion, + parseCredentials, + parseDriverManifest, + parseHandoff, +} from '../../config/generated-contract.cjs'; + +import type { DesktopStorybookDriverManifest } from './driverManifest.js'; + +export type StoredDriverManifest = Omit & { + application: Omit; + credentials: { name: string; root: string; runtimeModule: string }; +}; + +type Credentials = { schemaVersion: 1; manifestDigest: string; bridgeNonce: string; leaseNonce: string }; +type Handoff = { + schemaVersion: 1; + credentialsDigest: string; + manifestDigest: string; + nativeDriver: NativeDriverArtifact; + runtimeModuleDigest: string; + runtimeModulePath: string; +}; +export type CreateStorybookPrivateStorage = (root: string, artifact: NativeDriverArtifact) => Promise; + +export const createStorybookPrivateStorage: CreateStorybookPrivateStorage = (root, artifact) => { + if (process.platform === 'win32') return createWindowsPrivateStorage({ artifact, root }); + return createMacOSPrivateStorage(root); +}; + +export function parseStoredDriverManifest(value: unknown): StoredDriverManifest { + const manifest = parseDriverManifest(value) as StoredDriverManifest; + for (const entry of manifest.storyManifest.entries) { + if (entry.tests !== undefined) validateDesktopStoryTests(entry.tests, `driver manifest story ${entry.id}`); + for (const test of entry.wdio?.cases ?? []) validateDesktopCaseOptions(test.options, `driver manifest case ${entry.id}/${test.name}`); + } + return manifest; +} + +export function driverManifestDigest(contents: string): string { + return createHash('sha256').update(contents).digest('hex'); +} + +/** Publishes secrets through the OS ownership boundary; the editable generated manifest contains only references. */ +export async function publishDriverManifest( + manifest: DesktopStorybookDriverManifest, + outputPath: string, + createStorage = createStorybookPrivateStorage, +): Promise { + fs.mkdirSync(path.dirname(outputPath), { recursive: true }); + const root = path.join(path.dirname(outputPath), '.private'); + const storage = await createStorage(root, manifest.nativeDriver); + const id = randomUUID(); + const name = `credentials-${id}.json`; + const runtimeModule = `runtime-${id}.js`; + const { bridgeNonce, application, ...rest } = manifest; + const { leaseNonce, ...publicApplication } = application; + const stored = parseStoredDriverManifest({ ...rest, application: publicApplication, credentials: { name, root, runtimeModule } }); + const contents = `${JSON.stringify(stored, null, 2)}\n`; + const manifestDigest = driverManifestDigest(contents); + const credentials = JSON.stringify(parseCredentials({ bridgeNonce, leaseNonce, manifestDigest, schemaVersion: credentialsVersion })); + const runtimeInstance = { + bridgeNonce, + endpoint: manifest.endpoint, + instanceId: manifest.instanceId, + platformManifestDigest: manifest.platformManifestDigest, + portablePlanDigest: manifest.portablePlanDigest, + storybookPort: manifest.storybookPort, + targetId: manifest.targetId, + testIDPrefix: manifest.testIDPrefix, + }; + const runtimeContents = `export default ${JSON.stringify(runtimeInstance)};\n`; + let previous: StoredDriverManifest | undefined; + if (fs.existsSync(outputPath)) { + try { + previous = parseStoredDriverManifest(JSON.parse(fs.readFileSync(outputPath, 'utf8'))); + } catch { + // An obsolete or malformed generated record is replaceable, but never authorizes private-record cleanup. + } + } + await storage.publish(name, credentials); + try { + await storage.publish(runtimeModule, runtimeContents); + fs.rmSync(manifest.application.leasePath, { force: true }); + if (manifest.agent) fs.rmSync(manifest.agent.readyPath, { force: true }); + // No secret is present here; privateStorage owns credential and runtime-module publication. + const pending = `${outputPath}.${id}.pending`; + try { + fs.writeFileSync(pending, contents, { flag: 'wx' }); + fs.renameSync(pending, outputPath); + } finally { + fs.rmSync(pending, { force: true }); + } + } catch (error) { + await storage.remove(name, credentials); + await storage.remove(runtimeModule, runtimeContents); + throw error; + } + if (previous?.credentials.root === root) { + for (const recordName of [previous.credentials.name, previous.credentials.runtimeModule]) { + const previousContents = await storage.read(recordName); + if (previousContents !== undefined) await storage.remove(recordName, previousContents); + } + } + return JSON.stringify({ + credentialsDigest: driverManifestDigest(credentials), + manifestDigest, + nativeDriver: manifest.nativeDriver, + runtimeModuleDigest: driverManifestDigest(runtimeContents), + runtimeModulePath: path.join(root, runtimeModule), + schemaVersion: handoffVersion, + } satisfies Handoff); +} + +/** + * The parent passes its resolved helper and digest separately from generated files. Verify this binding before any + * verification handshake or Windows private-storage helper can execute a path read from the manifest. + */ +export async function readDriverManifest( + manifestPath: string, + handoff?: string, + createStorage = createStorybookPrivateStorage, + trustedArtifact?: NativeDriverArtifact, +): Promise { + const contents = fs.readFileSync(manifestPath, 'utf8'); + const stored = parseStoredDriverManifest(JSON.parse(contents)); + if ( + stored.credentials.root !== path.join(path.dirname(manifestPath), '.private') || + stored.application.leasePath !== path.join(stored.credentials.root, `application-lease.${stored.endpoint}.json`) + ) { + throw new Error('Desktop Storybook private state must use the generated instance namespace.'); + } + let artifact = trustedArtifact ?? stored.nativeDriver; + let trusted: Handoff | undefined; + if (handoff !== undefined) { + trusted = parseHandoff(JSON.parse(handoff)) as Handoff; + if ( + trusted.manifestDigest !== driverManifestDigest(contents) || + JSON.stringify(trusted.nativeDriver) !== JSON.stringify(stored.nativeDriver) || + trusted.runtimeModulePath !== path.join(stored.credentials.root, stored.credentials.runtimeModule) + ) { + throw new Error('Desktop Storybook manifest does not match the trusted parent handoff.'); + } + artifact = await verifyNativeDriverArtifact(trusted.nativeDriver); + } else if (!trustedArtifact && createStorage === createStorybookPrivateStorage && process.platform !== 'darwin') { + // macOS lease writers only read private records, without executing a helper. Windows always needs trusted provenance. + throw new Error('Desktop Storybook requires a trusted parent helper handoff.'); + } + const storage = await createStorage(stored.credentials.root, artifact); + const record = await storage.read(stored.credentials.name); + if (trusted && (record === undefined || trusted.credentialsDigest !== driverManifestDigest(record))) { + throw new Error('Desktop Storybook credentials do not match the trusted parent handoff.'); + } + const credentials = parseCredentials(record === undefined ? undefined : JSON.parse(record)) as Credentials; + if (credentials.manifestDigest !== driverManifestDigest(contents)) { + throw new Error('Desktop Storybook manifest does not match its private credentials.'); + } + const { credentials: _credentials, ...manifest } = stored; + return { + ...manifest, + bridgeNonce: credentials.bridgeNonce, + application: { ...manifest.application, leaseNonce: credentials.leaseNonce }, + nativeDriver: artifact, + }; +} diff --git a/packages/agentic/storybook-desktop/src/driver/serverIntegration.test.ts b/packages/agentic/storybook-desktop/src/driver/serverIntegration.test.ts index d140f24ca9..beda03b2a1 100644 --- a/packages/agentic/storybook-desktop/src/driver/serverIntegration.test.ts +++ b/packages/agentic/storybook-desktop/src/driver/serverIntegration.test.ts @@ -1,4 +1,5 @@ import { spawn } from 'node:child_process'; +import { createHash } from 'node:crypto'; import fs from 'node:fs'; import { createServer, Socket } from 'node:net'; import os from 'node:os'; @@ -9,11 +10,76 @@ import { NodeDesktopCommandRunner } from '@fluentui-react-native/desktop-test/co import { deadline } from '@fluentui-react-native/desktop-test/commands'; import { DesktopRunReporter, startReportTransport } from '@fluentui-react-native/desktop-test/reporting'; -import type { DesktopStorybookDriverManifest } from './driverManifest.js'; +import type { StoredDriverManifest } from './generatedManifest.js'; jest.setTimeout(30_000); describe('desktop Storybook server integration', () => { + test.each(['helper-path-and-hash', 'unknown-field', 'helper-bytes'])( + 'the actual channel process rejects %s before spawning a helper or listening', + async (tamper) => { + const [storybookPort, driverPort] = await Promise.all([getAvailablePort(), getAvailablePort()]); + const root = fs.mkdtempSync(path.join(os.tmpdir(), 'storybook-spawn-trust-')); + const manifestPath = path.join(root, 'driver-manifest.json'); + const marker = path.join(root, 'unexpected-spawn'); + const fixture = createIntegrationManifest(root, storybookPort, driverPort); + const hash = (contents: string) => createHash('sha256').update(contents).digest('hex'); + const originalHelper = '#!/usr/bin/env node\nprocess.exit(0);\n'; + const untrustedHelper = "#!/usr/bin/env node\nrequire('node:fs').writeFileSync(process.env.FURN_TEST_SPAWN_MARKER, 'spawned');\n"; + fs.writeFileSync(fixture.nativeDriver.executablePath, originalHelper, { mode: 0o700 }); + fixture.nativeDriver.artifactId = hash(originalHelper); + const originalContents = JSON.stringify(fixture); + const handoff = { + credentialsDigest: 'unused-before-rejection', + manifestDigest: hash(originalContents), + nativeDriver: { ...fixture.nativeDriver }, + runtimeModuleDigest: 'unused-before-rejection', + runtimeModulePath: path.join(fixture.credentials.root, fixture.credentials.runtimeModule), + schemaVersion: 1, + }; + if (tamper === 'helper-path-and-hash') { + fixture.nativeDriver.executablePath = path.join(root, 'substituted-helper'); + fixture.nativeDriver.artifactId = hash(untrustedHelper); + fs.writeFileSync(fixture.nativeDriver.executablePath, untrustedHelper, { mode: 0o700 }); + } else if (tamper === 'helper-bytes') { + fs.writeFileSync(fixture.nativeDriver.executablePath, untrustedHelper); + } + fs.writeFileSync(manifestPath, JSON.stringify(tamper === 'unknown-field' ? { ...fixture, unexpected: true } : fixture)); + const projectRoot = path.resolve(__dirname, '../../../../../apps/storybook'); + const child = spawn(process.execPath, [path.resolve(__dirname, '../../config/server-runner.cjs')], { + cwd: projectRoot, + env: { + ...process.env, + FURN_TEST_SPAWN_MARKER: marker, + STORYBOOK_CONFIG_PATH: path.join(projectRoot, 'src'), + STORYBOOK_DRIVER_MANIFEST: manifestPath, + STORYBOOK_DRIVER_HANDOFF: JSON.stringify(handoff), + STORYBOOK_NATIVE_DRIVER_FAKE: '0', + STORYBOOK_PROJECT_ROOT: projectRoot, + STORYBOOK_WS_PORT: String(storybookPort), + }, + signal: AbortSignal.timeout(20_000), + stdio: ['ignore', 'pipe', 'pipe'], + }); + const output: string[] = []; + child.stdout.on('data', (data: Buffer) => output.push(data.toString())); + child.stderr.on('data', (data: Buffer) => output.push(data.toString())); + try { + const code = await new Promise((resolve, reject) => { + child.once('error', reject); + child.once('close', resolve); + }); + expect(code).toBe(1); + expect(output.join('')).toMatch(/trusted parent handoff|driver manifest|hash does not match/); + expect(fs.existsSync(marker)).toBe(false); + await expect(fetch(loopbackUrl(driverPort, '/status'))).rejects.toThrow(); + } finally { + if (child.exitCode === null) child.kill(); + fs.rmSync(root, { force: true, recursive: true }); + } + }, + ); + test('hosts the Storybook channel and Stage 1 smoke-test target in one process', async () => { const [storybookPort, driverPort] = await Promise.all([getAvailablePort(), getAvailablePort()]); const temporaryDirectory = fs.mkdtempSync(path.join(os.tmpdir(), 'furn-storybook-driver-')); @@ -332,15 +398,18 @@ describe('desktop Storybook server integration', () => { }); }); -function createIntegrationManifest(temporaryDirectory: string, storybookPort: number, driverPort: number): DesktopStorybookDriverManifest { +function createIntegrationManifest(temporaryDirectory: string, storybookPort: number, driverPort: number): StoredDriverManifest { return { application: { - leaseNonce: 'integration-nonce', - leasePath: path.join(temporaryDirectory, 'application-lease.json'), + leasePath: path.join(temporaryDirectory, '.private', 'application-lease.windows.json'), windowTitle: 'Agentic Components Storybook', }, appName: 'AgenticStorybook', - bridgeNonce: 'integration-nonce', + credentials: { + root: path.join(temporaryDirectory, '.private'), + name: 'credentials-fixture.json', + runtimeModule: 'runtime-fixture.js', + }, displayName: 'Agentic Components Storybook', driverPort, endpoint: 'windows', @@ -367,7 +436,7 @@ function createIntegrationManifest(temporaryDirectory: string, storybookPort: nu platformManifestDigest: 'platform-digest', portablePlanDigest: 'portable-digest', renderer: 'fabric', - schemaVersion: 2, + schemaVersion: 3, storyManifest: { endpoint: 'windows', entries: [ From a5de740f01ca025bf548a923ae4561b36fc9872b Mon Sep 17 00:00:00 2001 From: Jason Morse Date: Thu, 12 Nov 2026 02:10:42 +0000 Subject: [PATCH 02/11] Await the shared workload claim before Storybook startup Prepare the Storybook-owned call site for F10-M's native process identity verification without relocating channel or lease ownership. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../storybook-desktop/src/cli/createDesktopStorybookCommand.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/agentic/storybook-desktop/src/cli/createDesktopStorybookCommand.ts b/packages/agentic/storybook-desktop/src/cli/createDesktopStorybookCommand.ts index bb8d43e5cc..c71ea68992 100644 --- a/packages/agentic/storybook-desktop/src/cli/createDesktopStorybookCommand.ts +++ b/packages/agentic/storybook-desktop/src/cli/createDesktopStorybookCommand.ts @@ -316,7 +316,7 @@ export async function runDesktopStorybookCli(argv: readonly string[] = process.a verbose: program.opts<{ verbose?: boolean }>().verbose, onFatal: (error) => options.services?.fail(error), }); - if (!session.delegated && ['driver', 'smoke'].includes(action.name())) releaseClaim = claimDesktopWorkload(session.reporter.runId); + if (!session.delegated && ['driver', 'smoke'].includes(action.name())) releaseClaim = await claimDesktopWorkload(session.reporter.runId); options.reporter = session.reporter; if (normalized.deprecated) { if (reporterMode === 'json' || reporterMode === 'ndjson') { From fa0681635acca03d878b5bed9307da2ae1824505 Mon Sep 17 00:00:00 2001 From: Jason Morse Date: Thu, 12 Nov 2026 02:17:03 +0000 Subject: [PATCH 03/11] Preserve resolved input metadata in generated manifests Accept the extractor's declared/derived inputSource metadata while keeping authored case options strict. Cover realistic resolved descriptors and reject unsupported metadata; this fixes the consumer smoke's publication failure. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../config/generated-contract.cjs | 9 +++++- .../references/contributing.md | 3 +- .../src/cli/createDesktopStorybookCommand.ts | 3 +- .../src/driver/generatedManifest.test.ts | 28 ++++++++++++++++++- .../src/driver/generatedManifest.ts | 6 +++- 5 files changed, 44 insertions(+), 5 deletions(-) diff --git a/packages/agentic/storybook-desktop/config/generated-contract.cjs b/packages/agentic/storybook-desktop/config/generated-contract.cjs index 14ae2bf679..67aa5ee13d 100644 --- a/packages/agentic/storybook-desktop/config/generated-contract.cjs +++ b/packages/agentic/storybook-desktop/config/generated-contract.cjs @@ -68,7 +68,14 @@ const storyManifest = object({ tests: optional(record(() => true)), wdio: optional( object({ - cases: optional(array(object({ name: text, options: record(() => true) }))), + cases: optional( + array( + object({ + name: text, + options: (value) => record(() => true)(value) && optional(oneOf('declared', 'derived'))(value.inputSource), + }), + ), + ), digest: text, exportName: text, testNames: optional(array(text)), diff --git a/packages/agentic/storybook-desktop/references/contributing.md b/packages/agentic/storybook-desktop/references/contributing.md index 5635bfaef2..2a9d9fea64 100644 --- a/packages/agentic/storybook-desktop/references/contributing.md +++ b/packages/agentic/storybook-desktop/references/contributing.md @@ -29,7 +29,8 @@ and release its driver session before authored test sessions start. `config/generated-contract.cjs` is the dependency-free source of the strict driver-manifest version 3, private-credential version 1, and parent-handoff version 1 schemas. Unknown generated fields fail, and authored plans and case -options remain validated by their owning desktop-driver validators. +options remain validated by their owning desktop-driver validators. Extracted +case options retain their separately validated `inputSource` metadata. The public generated JSON contains credential references, never either nonce. `src/driver/generatedManifest.ts` publishes a credential record and bridge-only diff --git a/packages/agentic/storybook-desktop/src/cli/createDesktopStorybookCommand.ts b/packages/agentic/storybook-desktop/src/cli/createDesktopStorybookCommand.ts index c71ea68992..44793d85ea 100644 --- a/packages/agentic/storybook-desktop/src/cli/createDesktopStorybookCommand.ts +++ b/packages/agentic/storybook-desktop/src/cli/createDesktopStorybookCommand.ts @@ -316,7 +316,8 @@ export async function runDesktopStorybookCli(argv: readonly string[] = process.a verbose: program.opts<{ verbose?: boolean }>().verbose, onFatal: (error) => options.services?.fail(error), }); - if (!session.delegated && ['driver', 'smoke'].includes(action.name())) releaseClaim = await claimDesktopWorkload(session.reporter.runId); + if (!session.delegated && ['driver', 'smoke'].includes(action.name())) + releaseClaim = await claimDesktopWorkload(session.reporter.runId); options.reporter = session.reporter; if (normalized.deprecated) { if (reporterMode === 'json' || reporterMode === 'ndjson') { diff --git a/packages/agentic/storybook-desktop/src/driver/generatedManifest.test.ts b/packages/agentic/storybook-desktop/src/driver/generatedManifest.test.ts index 12c83b6ddc..1317d4b828 100644 --- a/packages/agentic/storybook-desktop/src/driver/generatedManifest.test.ts +++ b/packages/agentic/storybook-desktop/src/driver/generatedManifest.test.ts @@ -4,6 +4,7 @@ import os from 'node:os'; import path from 'node:path'; import type { NativeDriverArtifact } from '@fluentui-react-native/desktop-driver'; +import { validateDesktopCaseOptions } from '@fluentui-react-native/desktop-driver/authoring'; import { createDesktopStorybookInstance } from '../config/instance'; import { makeDesktopStorybookConfig } from '../config/makeDesktopStorybookConfig'; import { createDesktopStorybookDriverManifest, writeDesktopStorybookDriverManifest } from './driverManifest'; @@ -147,12 +148,37 @@ describe('generated manifest trust handoff', () => { title: 'Fixture', ...(section === 'tests' ? { tests: { version: 1, tests: [], unknown: true } } - : { wdio: { digest: 'digest', exportName: 'Story', cases: [{ name: 'case', options: { unknown: true } }] } }), + : { + wdio: { + digest: 'digest', + exportName: 'Story', + cases: [{ name: 'case', options: { input: 'both', inputSource: 'derived', unknown: true } }], + }, + }), }, ]; expect(() => parseStoredDriverManifest(manifest)).toThrow('unknown field'); }); + test.each([undefined, 'physical'] as const)('accepts extracted case options with %s authored input', (input) => { + const manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8')); + const options = validateDesktopCaseOptions({ ...(input === undefined ? {} : { input }), requires: ['keyboard'] }); + manifest.storyManifest.entries = [ + { + id: 'fixture--story', + name: 'Story', + packageName: 'fixture', + sourcePath: 'Fixture.stories.tsx', + tags: [], + title: 'Fixture', + wdio: { digest: 'digest', exportName: 'Story', cases: [{ name: 'case', options }] }, + }, + ]; + expect(parseStoredDriverManifest(manifest).storyManifest.entries[0].wdio?.cases?.[0].options).toEqual(options); + manifest.storyManifest.entries[0].wdio.cases[0].options.inputSource = 'unknown'; + expect(() => parseStoredDriverManifest(manifest)).toThrow('driver manifest'); + }); + (process.platform === 'darwin' ? test : test.skip)( 'publishes and reads real macOS owner-private records, refusing a permissive credential mode', async () => { diff --git a/packages/agentic/storybook-desktop/src/driver/generatedManifest.ts b/packages/agentic/storybook-desktop/src/driver/generatedManifest.ts index 28a70007c6..14b11589a9 100644 --- a/packages/agentic/storybook-desktop/src/driver/generatedManifest.ts +++ b/packages/agentic/storybook-desktop/src/driver/generatedManifest.ts @@ -42,7 +42,11 @@ export function parseStoredDriverManifest(value: unknown): StoredDriverManifest const manifest = parseDriverManifest(value) as StoredDriverManifest; for (const entry of manifest.storyManifest.entries) { if (entry.tests !== undefined) validateDesktopStoryTests(entry.tests, `driver manifest story ${entry.id}`); - for (const test of entry.wdio?.cases ?? []) validateDesktopCaseOptions(test.options, `driver manifest case ${entry.id}/${test.name}`); + for (const test of entry.wdio?.cases ?? []) { + // Extraction adds inputSource to resolved options; the authoring validator accepts only authored fields. + const { inputSource: _inputSource, ...authoredOptions } = test.options; + validateDesktopCaseOptions(authoredOptions, `driver manifest case ${entry.id}/${test.name}`); + } } return manifest; } From e298d7e18ef550c440f1ed287c6aefd2d0246e86 Mon Sep 17 00:00:00 2001 From: Jason Morse Date: Thu, 12 Nov 2026 02:31:14 +0000 Subject: [PATCH 04/11] Record F6 provenance and platform qualification evidence Document portable and signed-native contract coverage, successful Fabric/Paper preparation, explicit Accessibility-blocked consumer outcomes, cleanup, final aggregate validation, and Windows CI sufficiency without claiming unrun native passes. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .changeset/goofy-corners-create.md | 5 + .../desktop-test/references/current-status.md | 97 ++++++++++++++++++- 2 files changed, 101 insertions(+), 1 deletion(-) create mode 100644 .changeset/goofy-corners-create.md diff --git a/.changeset/goofy-corners-create.md b/.changeset/goofy-corners-create.md new file mode 100644 index 0000000000..d90cfcc331 --- /dev/null +++ b/.changeset/goofy-corners-create.md @@ -0,0 +1,5 @@ +--- +'@fluentui-react-native/desktop-test': patch +--- + +Record F6 Storybook manifest provenance, independent credential purposes, and platform qualification evidence in the lifecycle submission ledger. diff --git a/packages/agentic/desktop-test/references/current-status.md b/packages/agentic/desktop-test/references/current-status.md index 5850b32c1d..2c919d709e 100644 --- a/packages/agentic/desktop-test/references/current-status.md +++ b/packages/agentic/desktop-test/references/current-status.md @@ -68,7 +68,7 @@ did not retain a portable raw-report locator; do not imply otherwise. | --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | macOS | Live failed-cleanup and service-restart cases; Paper separately; supervisor death with Metro/channel/helper survivors; exact attached-app preservation. | | Windows / Win32 | Same-branch MCP restart/revocation/dispose/args tests; physical console Ctrl+C requalification of `serve --agent` after the idle-CLI fix; interactive input/capture rerun; naming launched (especially uncontained packaged) apps in the claim. | -| Storybook | Authenticated mutation ingress, context fencing/reconnect, consistent helper build policy, manifest provenance and separate nonces. | +| Storybook | Authenticated mutation ingress, context fencing/reconnect, consistent helper build policy. F6 now implements strict generated provenance and independent nonces; see the F6 evidence below for qualification limits. | | Recovery | Durable uncertainty is wired in both paths; live restart qualification, ledger and exact-resource reconciliation still precede automatic reclaim. The workload claim records a Node.js-clock start time, so it needs a helper-described start time before claim inspection can prove a live owner or a reused PID. | | Concurrency | No physical-input suites in parallel on one interactive desktop. Separate machines may qualify independent endpoints. | | Reliability | Establish the required repeated-run window rather than interpreting aggregate past successes as a pass. | @@ -752,3 +752,98 @@ not physical Ctrl+C. Both owned app/service processes exited, the recorded ports were free, and the per-user claim and default descriptor were absent. The separate `serve --agent` interrupt limitation above is fixed but not yet requalified on Windows. + +## F6 generated manifest provenance — 2026-11-12 + +Implementation source: `efd6dadeda87344911fb4000fe293c686c678602`, with +resolved-case compatibility in `fa0681635` and the awaited shared workload +claim in `a5de740f01ca025bf548a923ae4561b36fc9872b`. +Generated driver manifests are strict version 3 and contain no secrets. +Version-1 private credentials use independent bridge and macOS attachment +nonces. The owner-private runtime module contains only bridge data and a +data-only `export default` statement. The parent's independent handoff pins +manifest/credential/runtime hashes and the resolved helper; the actual channel +child validates that binding and re-verifies the executable before a helper +can spawn. Metro receives the canonical schema locator from trusted process +configuration, not from editable generated files. Channel lifecycle placement +and application lease ownership have not moved. + +**Confirmed portable/local boundary checks:** integration package format, +lint, build, and all 364 tests passed; four Windows-only integration tests +were skipped on macOS. Runtime format, lint, build, and all 33 tests passed. +The ledger-owning desktop-test package passed format, lint, build, and +380 tests with one skip after building the MCP public entry required by its +standalone-consumer fixture; the first test run failed only for that missing +compiled entry. +Controlled Metro fixtures cover missing trust inputs, unknown fields, and +manifest/runtime tampering. Actual channel-child fixtures reject substituted +helper path/hash, helper bytes, and unknown fields before listening or spawning. +The real macOS private-storage adapter round-trips the records with directory +mode `0700` and file mode `0600` and rejects a permissive credential mode. + +**Confirmed native helper checks:** on macOS 27.2.1 arm64, the locked +`FURN_NATIVE_DRIVER_TEST=1 yarn workspace +@fluentui-react-native/desktop-driver test --runInBand` run passed 1,240 tests; +47 platform/capability tests were skipped (75 suites passed, six skipped). +Evidence: `apps/storybook/artifacts/f6/native-contract.log`. The explicitly +built helper uses the stable `FURN Desktop Driver Development` identity; +`doctor --platform macos --permissions` reported ready, unlocked/on-console, +and Screen Recording preflight true, but Accessibility and PostEvent preflight +false. No permission prompts, privacy changes, or TCC resets were requested. +The native consumer runs below must not be interpreted as passed from that +helper readiness result. + +**Native consumer preparation:** Fabric bundle passed +(`apps/storybook/artifacts/f6/bundle-fabric.log`). Initial Fabric prep failed +because CocoaPods called `JSON.fast_generate` after Ruby selected JSON 3.1. +Selecting the already installed JSON 2.18 through a worktree-local Ruby +preload, without installing or modifying shared tools, made prep pass +(`prep-fabric-json2.log`, run `8df5c79a-9618-423d-b65d-e9828644a75b`). +The first Fabric smoke exposed rejection of the extractor's legitimate +resolved `inputSource` metadata; `fa0681635` fixes it and adds declared/derived +descriptor regressions while preserving unknown-field refusal. + +**Fabric native consumer: blocked, not passed.** The corrected smoke built and +launched the app, started the verified channel, and reached authenticated +bridge epoch recording. Native attach then reported Accessibility +`apiDisabled` (`-25211`), and session creation failed because the target exposed +no supported click input mode. No stories or tests executed. +Evidence: `apps/storybook/artifacts/f6/smoke-fabric-resolved-options.log` and +`apps/storybook/artifacts/desktop/65fb216f-89ee-43db-86a6-333b3d91331e/run.json`. +The harness's AppleEvent cleanup also timed out (`-1712`); its leftover app +process was verified against this worktree's executable, terminated by that +exact PID only, and confirmed gone. No privacy workaround was attempted. + +**Paper native consumer: blocked, not passed.** Paper bundle and prep passed +with the same existing-JSON-2 selection (`bundle-paper.log`, run +`3c281fb3-eb3a-4125-a189-86ced929d6ad`; `prep-paper.log`, run +`9b575663-fa72-4625-9f09-b745bfa1e83e`). Paper smoke also built and launched +the app and reached bridge epoch recording, then failed on Accessibility +`apiDisabled` and no supported click input mode. Zero tests executed. +Evidence: `apps/storybook/artifacts/f6/smoke-paper.log` and +`apps/storybook/artifacts/desktop/cfab6e50-9b38-45d3-b114-05b3ea995037/run.json`. +Its AppleEvent cleanup timed out as well; the exact worktree-owned leftover +app PID was verified, terminated, and confirmed gone. Positive Fabric/Paper +traversal and authored-case qualification remain pending an authorized +Accessibility/PostEvent-capable host. + +**Final repository checks:** after `yarn clean-lage-cache`, the locked +`TF_BUILD=1 yarn lage buildci --concurrency 4` passed all 178 tasks. +The existing test wrapper uses `TF_BUILD` only to run Jest in-band; it does not +skip agentic tests. Evidence: +`apps/storybook/artifacts/f6/buildci-serialized-jest.log`. +The first aggregate attempt caught formatting of the awaited claim (fixed +in `fa0681635`). A subsequent default-parallel aggregate passed 103 tasks but +failed the existing bounded-command test with `SIGTERM` rather than the +expected `SIGKILL`; a child startup/deadline race under load is inferred, not +proven. The in-band aggregate was its single justified retry; no unrelated +test or production behavior was changed. + +Windows/Win32 native execution is not available on this Mac. The PR's +`windows-storybook` setup runs the real Windows private-storage contract +(owner/DACL/root identity/reparse/hard-link refusal), and both Windows Fabric +and Win32 Paper smoke jobs exercise publication, child helper verification, +private runtime-module resolution, and live bridge authentication. The +platform-neutral negative provenance/schema fixtures run in the Ubuntu unit +lane. These CI lanes are sufficient for the changed Windows-specific paths; +their same-branch results remain pending, not local passes. From ffb4944db0c5612dd6302ce2a5cbb2c8a0e8ab29 Mon Sep 17 00:00:00 2001 From: Jason Morse Date: Thu, 12 Nov 2026 02:58:36 +0000 Subject: [PATCH 05/11] Fix v3 smoke consumers and canonical private state paths Route Windows smoke lease publication and cleanup through verified private storage, use the shared v3 control schema, and resolve generated directory aliases before creating private records. Cover receipt fencing, stock macOS paths, and symlink replacement; keep Windows qualification explicitly pending. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .changeset/tidy-boats-smile.md | 5 + .../desktop-driver/references/contributing.md | 3 + .../src/authority/macosPrivateStorage.ts | 23 ++- .../src/authority/privateStorage.test.ts | 2 +- .../desktop-test/references/current-status.md | 52 ++++-- .../config/application-lease.cjs | 39 +++++ .../storybook-desktop/config/smoke-win32.ps1 | 54 +++--- .../config/smoke-windows.ps1 | 56 +++---- .../config/storybook-control.cjs | 15 +- .../references/contributing.md | 10 +- .../src/driver/applicationLease.test.ts | 156 ++++++++++++++++++ .../src/driver/applicationLease.ts | 72 ++++++++ .../src/driver/fixtures/storedManifest.cjs | 44 +++++ .../src/driver/fixtures/storedManifest.d.cts | 4 + .../src/driver/generatedManifest.test.ts | 46 +++++- .../src/driver/generatedManifest.ts | 21 ++- .../src/driver/serverIntegration.test.ts | 2 +- .../src/testing/wdioRunner.contract.cjs | 3 +- 18 files changed, 502 insertions(+), 105 deletions(-) create mode 100644 .changeset/tidy-boats-smile.md create mode 100644 packages/agentic/storybook-desktop/config/application-lease.cjs create mode 100644 packages/agentic/storybook-desktop/src/driver/applicationLease.test.ts create mode 100644 packages/agentic/storybook-desktop/src/driver/applicationLease.ts create mode 100644 packages/agentic/storybook-desktop/src/driver/fixtures/storedManifest.cjs create mode 100644 packages/agentic/storybook-desktop/src/driver/fixtures/storedManifest.d.cts diff --git a/.changeset/tidy-boats-smile.md b/.changeset/tidy-boats-smile.md new file mode 100644 index 0000000000..485d1ac07f --- /dev/null +++ b/.changeset/tidy-boats-smile.md @@ -0,0 +1,5 @@ +--- +'@fluentui-react-native/desktop-driver': patch +--- + +Identify the unsafe ancestor when macOS private storage rejects directory aliases, permissions, or ACLs. diff --git a/packages/agentic/desktop-driver/references/contributing.md b/packages/agentic/desktop-driver/references/contributing.md index 5c8e915c77..4232789000 100644 --- a/packages/agentic/desktop-driver/references/contributing.md +++ b/packages/agentic/desktop-driver/references/contributing.md @@ -78,6 +78,9 @@ specifiers, so keep it that way. - Propagate `AbortSignal` to every host operation. - Do not release queues or input locks until a timed-out native command settles. - Preserve attached apps and clean only exact owned resources. +- Callers resolve existing private-storage parent directories before opening them. + macOS storage keeps rejecting symlink ancestors on subsequent operations and + identifies the failing ancestor in ownership/permissions diagnostics. - Keep native events advisory and queries authoritative. - Use opaque public window/element IDs and native liveness checks. - A Storybook preview reset invalidates preview elements, not app chrome or diff --git a/packages/agentic/desktop-driver/src/authority/macosPrivateStorage.ts b/packages/agentic/desktop-driver/src/authority/macosPrivateStorage.ts index 9605e33c8e..c11d07ff30 100644 --- a/packages/agentic/desktop-driver/src/authority/macosPrivateStorage.ts +++ b/packages/agentic/desktop-driver/src/authority/macosPrivateStorage.ts @@ -154,12 +154,16 @@ async function validateRoot(root: string, uid: number): Promise { async function validateAncestors(directory: string, uid: number): Promise { for (let current = directory; ; current = path.dirname(current)) { - const info = await lstat(current); - const rootOwnedSticky = info.uid === 0 && (info.mode & 0o1000) !== 0; - if (!info.isDirectory() || (info.uid !== uid && info.uid !== 0) || ((info.mode & 0o022) !== 0 && !rootOwnedSticky)) { - throw unsafeStorage(); + try { + const info = await lstat(current); + const rootOwnedSticky = info.uid === 0 && (info.mode & 0o1000) !== 0; + if (!info.isDirectory() || (info.uid !== uid && info.uid !== 0) || ((info.mode & 0o022) !== 0 && !rootOwnedSticky)) { + throw unsafeStorage(); + } + await rejectACL(current, true); + } catch { + throw unsafeStorage(current); } - await rejectACL(current, true); if (current === path.dirname(current)) break; } } @@ -194,6 +198,11 @@ function hasCode(error: unknown, code: string): boolean { return typeof error === 'object' && error !== null && 'code' in error && error.code === code; } -function unsafeStorage(): Error { - return new Error('Desktop Driver private storage is unsafe or inaccessible.'); +function unsafeStorage(ancestor?: string): Error { + return new Error( + 'Desktop Driver private storage is unsafe or inaccessible.' + + (ancestor === undefined + ? '' + : ` Check ancestor "${ancestor}": resolve directory aliases and require owner/root ownership without writable shared permissions or ACL grants.`), + ); } diff --git a/packages/agentic/desktop-driver/src/authority/privateStorage.test.ts b/packages/agentic/desktop-driver/src/authority/privateStorage.test.ts index 829f6fdb25..8ffcc35ed3 100644 --- a/packages/agentic/desktop-driver/src/authority/privateStorage.test.ts +++ b/packages/agentic/desktop-driver/src/authority/privateStorage.test.ts @@ -110,7 +110,7 @@ macosDescribe('owner-validated macOS private storage', () => { await mkdir(real, { mode: 0o700 }); await symlink(real, root); await expect(createMacOSPrivateStorage(root)).rejects.toThrow(); - await expect(createMacOSPrivateStorage(path.join(root, 'nested'))).rejects.toThrow(); + await expect(createMacOSPrivateStorage(path.join(root, 'nested'))).rejects.toThrow(`Check ancestor "${root}"`); expect(await readdir(real)).toEqual([]); }); diff --git a/packages/agentic/desktop-test/references/current-status.md b/packages/agentic/desktop-test/references/current-status.md index 2c919d709e..58436a1cff 100644 --- a/packages/agentic/desktop-test/references/current-status.md +++ b/packages/agentic/desktop-test/references/current-status.md @@ -759,7 +759,7 @@ Implementation source: `efd6dadeda87344911fb4000fe293c686c678602`, with resolved-case compatibility in `fa0681635` and the awaited shared workload claim in `a5de740f01ca025bf548a923ae4561b36fc9872b`. Generated driver manifests are strict version 3 and contain no secrets. -Version-1 private credentials use independent bridge and macOS attachment +Version-1 private credentials use independent bridge and application attachment nonces. The owner-private runtime module contains only bridge data and a data-only `export default` statement. The parent's independent handoff pins manifest/credential/runtime hashes and the resolved helper; the actual channel @@ -768,13 +768,30 @@ can spawn. Metro receives the canonical schema locator from trusted process configuration, not from editable generated files. Channel lifecycle placement and application lease ownership have not moved. -**Confirmed portable/local boundary checks:** integration package format, -lint, build, and all 364 tests passed; four Windows-only integration tests -were skipped on macOS. Runtime format, lint, build, and all 33 tests passed. -The ledger-owning desktop-test package passed format, lint, build, and -380 tests with one skip after building the MCP public entry required by its -standalone-consumer fixture; the first test run failed only for that missing -compiled entry. +Review fixes route Windows/Win32 smoke lease publication, replacement, and +cleanup through the trusted Node helper and OS private-storage adapter; +PowerShell receives only a digest receipt. Smoke control now uses the strict +shared version-3 parser. Publication resolves the existing generated directory +once before opening private storage, supporting symlinked projects and macOS +`/var` aliases while retaining later fail-closed ancestor validation and +actionable diagnostics. + +**Portable/local boundary checks:** the initial 364-test integration result +used a project-local temporary directory and did not qualify stock macOS +temporary paths. Review exposed that gap; those counts are superseded by the +default-`TMPDIR` review validation below. Runtime format, lint, build, and all +33 tests pass with the default temporary directory. The driver package passed +format, lint, build, and 1,221 portable tests with 66 skips; focused private +storage tests passed 65 with ten platform skips. +The reviewed integration package passes format, lint, build, and 379 tests +with four Windows-only skips. Its focused generated-manifest, lease, and real +WDIO-runner contract selection passed 38 tests, including the actual v3 smoke +control path. The ledger-owning harness passes format, lint, build, and +380 tests with one skip; its claim-sensitive tests ran under the shared lock. +These review runs used the default macOS `TMPDIR`, without an override. +The channel-child rejection fixture now canonicalizes its temporary parent +too, ensuring it reaches helper/hash refusal instead of an alias-path error. +Evidence: `apps/storybook/artifacts/f6/review-{driver-focused,driver-test,integration-focused,integration-final,runtime,harness}.log`. Controlled Metro fixtures cover missing trust inputs, unknown fields, and manifest/runtime tampering. Actual channel-child fixtures reject substituted helper path/hash, helper bytes, and unknown fields before listening or spawning. @@ -827,7 +844,7 @@ app PID was verified, terminated, and confirmed gone. Positive Fabric/Paper traversal and authored-case qualification remain pending an authorized Accessibility/PostEvent-capable host. -**Final repository checks:** after `yarn clean-lage-cache`, the locked +**Initial repository checks (before review fixes):** after `yarn clean-lage-cache`, the locked `TF_BUILD=1 yarn lage buildci --concurrency 4` passed all 178 tasks. The existing test wrapper uses `TF_BUILD` only to run Jest in-band; it does not skip agentic tests. Evidence: @@ -839,11 +856,12 @@ expected `SIGKILL`; a child startup/deadline race under load is inferred, not proven. The in-band aggregate was its single justified retry; no unrelated test or production behavior was changed. -Windows/Win32 native execution is not available on this Mac. The PR's -`windows-storybook` setup runs the real Windows private-storage contract -(owner/DACL/root identity/reparse/hard-link refusal), and both Windows Fabric -and Win32 Paper smoke jobs exercise publication, child helper verification, -private runtime-module resolution, and live bridge authentication. The -platform-neutral negative provenance/schema fixtures run in the Ubuntu unit -lane. These CI lanes are sufficient for the changed Windows-specific paths; -their same-branch results remain pending, not local passes. +**Windows/Win32 qualification: pending, not sufficient yet.** Native execution +is unavailable on this Mac, and `pwsh` is not installed, so PowerShell parser +validation was not run. The configured private-storage contracts and Windows +Fabric/Win32 Paper smoke jobs are candidate coverage, not observed evidence +that these revised paths work. A passing same-branch run must demonstrate +version-3 smoke control, trusted helper verification, protected-DACL lease +publication/replacement/cleanup, private runtime resolution, and live bridge +authentication. Portable negative fixtures do not qualify Windows ACL +behavior. Keep the PR draft until that coverage is observed. diff --git a/packages/agentic/storybook-desktop/config/application-lease.cjs b/packages/agentic/storybook-desktop/config/application-lease.cjs new file mode 100644 index 0000000000..81c681b61c --- /dev/null +++ b/packages/agentic/storybook-desktop/config/application-lease.cjs @@ -0,0 +1,39 @@ +async function main() { + const [operation, ...args] = process.argv.slice(2); + let update; + if (operation === 'remove' && args.length === 1) { + update = { operation, digest: args[0] }; + } else if (operation === 'publish' && args.length % 2 === 0) { + const fields = new Map(); + const allowed = ['--process-id', '--process-started-at', '--window-title', '--aumid', '--executable-path', '--previous-digest']; + for (let index = 0; index < args.length; index += 2) { + const key = args[index]; + if (!allowed.includes(key) || fields.has(key)) throw new Error('Invalid application lease arguments.'); + fields.set(key, args[index + 1]); + } + update = { + operation, + application: { + processId: Number(fields.get('--process-id')), + processStartedAt: fields.get('--process-started-at'), + windowTitle: fields.get('--window-title'), + ...(fields.has('--aumid') ? { aumid: fields.get('--aumid') } : {}), + ...(fields.has('--executable-path') ? { executablePath: fields.get('--executable-path') } : {}), + }, + ...(fields.has('--previous-digest') ? { previousDigest: fields.get('--previous-digest') } : {}), + }; + } else { + throw new Error('Invalid application lease operation.'); + } + const { STORYBOOK_DRIVER_MANIFEST: manifest, STORYBOOK_DRIVER_HANDOFF: handoff } = process.env; + if (!manifest || !handoff) throw new Error('Application leases require the trusted parent handoff.'); + const { updateWindowsApplicationLease } = await import('../lib/driver/applicationLease.js'); + const digest = await updateWindowsApplicationLease(manifest, handoff, update); + if (digest !== undefined) process.stdout.write(`${digest}\n`); +} + +main().catch(() => { + // Credentials can be malformed; never echo their bytes through a JSON parsing diagnostic. + process.stderr.write('Application lease update failed; verify the parent handoff, private storage, and application identity.\n'); + process.exitCode = 1; +}); diff --git a/packages/agentic/storybook-desktop/config/smoke-win32.ps1 b/packages/agentic/storybook-desktop/config/smoke-win32.ps1 index 4361b014af..92db0cabf3 100644 --- a/packages/agentic/storybook-desktop/config/smoke-win32.ps1 +++ b/packages/agentic/storybook-desktop/config/smoke-win32.ps1 @@ -19,12 +19,13 @@ $storybookPort = if ($env:STORYBOOK_WS_PORT) { [int]$env:STORYBOOK_WS_PORT } els $driverPort = if ($env:STORYBOOK_DRIVER_PORT) { [int]$env:STORYBOOK_DRIVER_PORT } else { 0 } $cliPath = Join-Path $PSScriptRoot 'cli.cjs' $controlPath = Join-Path $PSScriptRoot 'storybook-control.cjs' +$leaseControlPath = Join-Path $PSScriptRoot 'application-lease.cjs' $hostPath = Join-Path $PSScriptRoot 'run-win32.cjs' $requiredStories = @($RequiredStoryIds -split ',' | Where-Object { $_ }) -$applicationLeasePath = $null +$applicationLeaseDigest = $null -if ($SmokeMode -eq 'stories-and-tests' -and (-not $driverPort -or -not $env:STORYBOOK_DRIVER_MANIFEST)) { - throw 'STORYBOOK_DRIVER_PORT and STORYBOOK_DRIVER_MANIFEST are required for stories-and-tests smoke mode.' +if ($SmokeMode -eq 'stories-and-tests' -and (-not $driverPort -or -not $env:STORYBOOK_DRIVER_MANIFEST -or -not $env:STORYBOOK_DRIVER_HANDOFF)) { + throw 'STORYBOOK_DRIVER_PORT, STORYBOOK_DRIVER_MANIFEST, and STORYBOOK_DRIVER_HANDOFF are required for stories-and-tests smoke mode.' } New-Item -ItemType Directory -Path $logRoot -Force | Out-Null @@ -47,29 +48,15 @@ function Write-ApplicationLease { [Microsoft.Management.Infrastructure.CimInstance]$ProcessInfo ) - $driverManifest = Get-Content -LiteralPath $env:STORYBOOK_DRIVER_MANIFEST -Raw | ConvertFrom-Json - if ( - $driverManifest.schemaVersion -ne 2 -or - -not $driverManifest.application.leasePath -or - -not $driverManifest.application.leaseNonce - ) { - throw "Invalid native Desktop Driver manifest at '$($env:STORYBOOK_DRIVER_MANIFEST)'." - } - $leasePath = [string]$driverManifest.application.leasePath - $leaseDirectory = Split-Path -Parent $leasePath - New-Item -ItemType Directory -Path $leaseDirectory -Force | Out-Null - $temporaryPath = "$leasePath.$PID.tmp" - @{ - schemaVersion = 1 - endpoint = 'win32' - nonce = [string]$driverManifest.application.leaseNonce - processId = $Process.Id - processStartedAt = $Process.StartTime.ToUniversalTime().ToString('o') - windowTitle = $WindowTitle - executablePath = [string]$ProcessInfo.ExecutablePath - } | ConvertTo-Json -Depth 4 | Set-Content -LiteralPath $temporaryPath -Encoding utf8NoBOM - Move-Item -LiteralPath $temporaryPath -Destination $leasePath -Force - return $leasePath + $leaseArguments = @($leaseControlPath, 'publish', '--process-id', [string]$Process.Id, + '--process-started-at', $Process.StartTime.ToUniversalTime().ToString('o'), + '--window-title', $WindowTitle, '--executable-path', [string]$ProcessInfo.ExecutablePath) + if ($applicationLeaseDigest) { $leaseArguments += @('--previous-digest', $applicationLeaseDigest) } + $digest = & node @leaseArguments + if ($LASTEXITCODE -ne 0 -or $digest -notmatch '^[0-9a-f]{64}$') { + throw 'Win32 application lease publication failed.' + } + return [string]$digest } function Wait-ForApp { @@ -192,7 +179,7 @@ try { Add-OwnedProcess -Id $appProcessInfo.ParentProcessId Add-OwnedProcess -Id $appProcess.Id if ($SmokeMode -eq 'stories-and-tests') { - $applicationLeasePath = Write-ApplicationLease -Process $appProcess -ProcessInfo $appProcessInfo + $applicationLeaseDigest = Write-ApplicationLease -Process $appProcess -ProcessInfo $appProcessInfo } Wait-ForAutomationId -Process $appProcess -AutomationId (StorybookId 'sidebar-header') @@ -218,8 +205,17 @@ try { } finally { $cleanupFailure = $null try { Stop-OwnedServices } catch { $cleanupFailure = $_.Exception } - if ($applicationLeasePath) { - Remove-Item -LiteralPath $applicationLeasePath -Force -ErrorAction SilentlyContinue + if ($applicationLeaseDigest) { + try { + & node $leaseControlPath remove $applicationLeaseDigest + if ($LASTEXITCODE -ne 0) { throw 'Win32 application lease cleanup failed.' } + } catch { + if ($cleanupFailure) { + $cleanupFailure = [System.AggregateException]::new('Service and application lease cleanup failed.', [System.Exception[]]@($cleanupFailure, $_.Exception)) + } else { + $cleanupFailure = $_.Exception + } + } } for ($index = $ownedProcessIds.Count - 1; $index -ge 0; $index -= 1) { $ownedProcessId = $ownedProcessIds[$index] diff --git a/packages/agentic/storybook-desktop/config/smoke-windows.ps1 b/packages/agentic/storybook-desktop/config/smoke-windows.ps1 index ba3c61e729..1e7eed8587 100644 --- a/packages/agentic/storybook-desktop/config/smoke-windows.ps1 +++ b/packages/agentic/storybook-desktop/config/smoke-windows.ps1 @@ -21,10 +21,11 @@ $metroPort = if ($env:RCT_METRO_PORT) { [int]$env:RCT_METRO_PORT } else { 8081 } $driverPort = if ($env:STORYBOOK_DRIVER_PORT) { [int]$env:STORYBOOK_DRIVER_PORT } else { 0 } $cliPath = Join-Path $PSScriptRoot 'cli.cjs' $controlPath = Join-Path $PSScriptRoot 'storybook-control.cjs' -$applicationLeasePath = $null +$leaseControlPath = Join-Path $PSScriptRoot 'application-lease.cjs' +$applicationLeaseDigest = $null -if ($SmokeMode -eq 'stories-and-tests' -and (-not $driverPort -or -not $env:STORYBOOK_DRIVER_MANIFEST)) { - throw 'STORYBOOK_DRIVER_PORT and STORYBOOK_DRIVER_MANIFEST are required for stories-and-tests smoke mode.' +if ($SmokeMode -eq 'stories-and-tests' -and (-not $driverPort -or -not $env:STORYBOOK_DRIVER_MANIFEST -or -not $env:STORYBOOK_DRIVER_HANDOFF)) { + throw 'STORYBOOK_DRIVER_PORT, STORYBOOK_DRIVER_MANIFEST, and STORYBOOK_DRIVER_HANDOFF are required for stories-and-tests smoke mode.' } New-Item -ItemType Directory -Path $logRoot -Force | Out-Null @@ -80,30 +81,16 @@ function Write-ApplicationLease { [string]$LaunchTarget ) - $driverManifest = Get-Content -LiteralPath $env:STORYBOOK_DRIVER_MANIFEST -Raw | ConvertFrom-Json - if ( - $driverManifest.schemaVersion -ne 2 -or - -not $driverManifest.application.leasePath -or - -not $driverManifest.application.leaseNonce - ) { - throw "Invalid native Desktop Driver manifest at '$($env:STORYBOOK_DRIVER_MANIFEST)'." - } - $leasePath = [string]$driverManifest.application.leasePath - $leaseDirectory = Split-Path -Parent $leasePath - New-Item -ItemType Directory -Path $leaseDirectory -Force | Out-Null - $temporaryPath = "$leasePath.$PID.tmp" $aumid = $LaunchTarget -replace '^shell:AppsFolder\\', '' - @{ - schemaVersion = 1 - endpoint = 'windows' - nonce = [string]$driverManifest.application.leaseNonce - processId = $Process.Id - processStartedAt = $Process.StartTime.ToUniversalTime().ToString('o') - windowTitle = $WindowTitle - aumid = $aumid - } | ConvertTo-Json -Depth 4 | Set-Content -LiteralPath $temporaryPath -Encoding utf8NoBOM - Move-Item -LiteralPath $temporaryPath -Destination $leasePath -Force - return $leasePath + $leaseArguments = @($leaseControlPath, 'publish', '--process-id', [string]$Process.Id, + '--process-started-at', $Process.StartTime.ToUniversalTime().ToString('o'), + '--window-title', $WindowTitle, '--aumid', $aumid) + if ($applicationLeaseDigest) { $leaseArguments += @('--previous-digest', $applicationLeaseDigest) } + $digest = & node @leaseArguments + if ($LASTEXITCODE -ne 0 -or $digest -notmatch '^[0-9a-f]{64}$') { + throw 'Windows application lease publication failed.' + } + return [string]$digest } function Install-WindowsFrameworkPackage { @@ -266,13 +253,13 @@ try { $appProcess = Start-StorybookApp if ($SmokeMode -eq 'stories-and-tests') { - $applicationLeasePath = Write-ApplicationLease -Process $appProcess -LaunchTarget $launchTarget + $applicationLeaseDigest = Write-ApplicationLease -Process $appProcess -LaunchTarget $launchTarget } Invoke-StorybookControl -Phase 'stories' -Process $appProcess if ($SmokeMode -eq 'stories-and-tests') { Stop-StorybookApp -Process $appProcess $appProcess = Start-StorybookApp - $applicationLeasePath = Write-ApplicationLease -Process $appProcess -LaunchTarget $launchTarget + $applicationLeaseDigest = Write-ApplicationLease -Process $appProcess -LaunchTarget $launchTarget Invoke-StorybookControl -Phase 'tests' -Process $appProcess } } catch { @@ -281,8 +268,17 @@ try { } finally { $cleanupFailure = $null try { Stop-OwnedServices } catch { $cleanupFailure = $_.Exception } - if ($applicationLeasePath) { - Remove-Item -LiteralPath $applicationLeasePath -Force -ErrorAction SilentlyContinue + if ($applicationLeaseDigest) { + try { + & node $leaseControlPath remove $applicationLeaseDigest + if ($LASTEXITCODE -ne 0) { throw 'Windows application lease cleanup failed.' } + } catch { + if ($cleanupFailure) { + $cleanupFailure = [System.AggregateException]::new('Service and application lease cleanup failed.', [System.Exception[]]@($cleanupFailure, $_.Exception)) + } else { + $cleanupFailure = $_.Exception + } + } } for ($index = $ownedProcessIds.Count - 1; $index -ge 0; $index -= 1) { $ownedProcessId = $ownedProcessIds[$index] diff --git a/packages/agentic/storybook-desktop/config/storybook-control.cjs b/packages/agentic/storybook-desktop/config/storybook-control.cjs index 1072c3002b..795cf3c33a 100644 --- a/packages/agentic/storybook-desktop/config/storybook-control.cjs +++ b/packages/agentic/storybook-desktop/config/storybook-control.cjs @@ -2,6 +2,7 @@ const fs = require('node:fs'); const path = require('node:path'); const { pathToFileURL } = require('node:url'); const { writeDesktopStorybookFailure } = require('./diagnostics.cjs'); +const { parseDriverManifest } = require('./generated-contract.cjs'); const host = process.env.STORYBOOK_WS_HOST || '127.0.0.1'; const port = Number(process.env.STORYBOOK_WS_PORT) || 7007; @@ -169,19 +170,7 @@ function readDriverManifest() { if (!manifestPath || !fs.existsSync(manifestPath)) { throw new Error('STORYBOOK_DRIVER_MANIFEST must identify the generated driver manifest when running authored tests.'); } - const manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8')); - if ( - manifest.schemaVersion !== 2 || - !['macos', 'win32', 'windows'].includes(manifest.endpoint) || - !Number.isInteger(manifest.driverPort) || - typeof manifest.targetId !== 'string' || - manifest.storyManifest?.schemaVersion !== 1 || - !Array.isArray(manifest.storyManifest.entries) - ) { - throw new Error(`Invalid Desktop Driver manifest at ${manifestPath}.`); - } - - return manifest; + return parseDriverManifest(JSON.parse(fs.readFileSync(manifestPath, 'utf8'))); } async function main() { diff --git a/packages/agentic/storybook-desktop/references/contributing.md b/packages/agentic/storybook-desktop/references/contributing.md index 2a9d9fea64..60cadc1192 100644 --- a/packages/agentic/storybook-desktop/references/contributing.md +++ b/packages/agentic/storybook-desktop/references/contributing.md @@ -37,8 +37,16 @@ The public generated JSON contains credential references, never either nonce. runtime data module through desktop-driver's owner-private storage adapter: POSIX directory/file modes `0700`/`0600` with ownership/ACL checks on macOS, and the native owner/DACL/reparse/root-identity boundary on Windows. -The macOS attachment lease stays in that private namespace. Its random nonce +Application attachment leases stay in that private namespace. Their random nonce is independent of the runtime bridge nonce; the lease nonce never reaches Metro. +Publication resolves the existing generated directory once, so symlinked project +paths and macOS `/var` aliases work without weakening subsequent ancestor checks. +Windows and Win32 smoke scripts pass OS-observed identity to +`config/application-lease.cjs`, which verifies the parent handoff before opening +private storage and publishes/removes leases through its protected DACL boundary. +Scripts retain only a digest receipt; replacement and cleanup cannot overwrite +or remove a different lease. Smoke control reads the shared strict version-3 +public schema, without hydrating credentials. The parent resolves the native helper independently and passes its artifact plus manifest, credential, and runtime-module hashes through inherited diff --git a/packages/agentic/storybook-desktop/src/driver/applicationLease.test.ts b/packages/agentic/storybook-desktop/src/driver/applicationLease.test.ts new file mode 100644 index 0000000000..038218cb2f --- /dev/null +++ b/packages/agentic/storybook-desktop/src/driver/applicationLease.test.ts @@ -0,0 +1,156 @@ +import { spawnSync } from 'node:child_process'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; + +import { verifyNativeDriverArtifact } from '@fluentui-react-native/desktop-driver/native'; +import { updateWindowsApplicationLease } from './applicationLease'; +import { createFixturePrivateStorage } from './fixtures/privateStorage'; +import { createFixtureStoredManifest } from './fixtures/storedManifest.cjs'; +import { driverManifestDigest, publishDriverManifest } from './generatedManifest'; + +jest.mock('@fluentui-react-native/desktop-driver/native', () => ({ + ...jest.requireActual('@fluentui-react-native/desktop-driver/native'), + verifyNativeDriverArtifact: jest.fn(async (artifact) => artifact), +})); + +describe.each(['windows', 'win32'] as const)('%s smoke application lease', (endpoint) => { + let root: string; + let manifestPath: string; + let leasePath: string; + let handoff: string; + const application = () => ({ + processId: 123, + processStartedAt: '2026-11-12T00:00:00.1234567Z', + windowTitle: 'Fixture', + ...(endpoint === 'windows' ? { aumid: 'Fixture!App' } : { executablePath: 'C:\\Fixture\\host.exe' }), + }); + + beforeEach(async () => { + root = fs.mkdtempSync(path.join(fs.realpathSync(os.tmpdir()), 'storybook-lease-')); + manifestPath = path.join(root, 'driver-manifest.json'); + leasePath = path.join(root, '.private', `application-lease.${endpoint}.json`); + const stored = createFixtureStoredManifest(root, { + endpoint, + entries: [], + platformManifestDigest: 'platform', + portablePlanDigest: 'portable', + schemaVersion: 1, + }); + const { credentials: _credentials, ...manifest } = stored; + handoff = await publishDriverManifest( + { ...manifest, bridgeNonce: 'bridge-only', application: { ...manifest.application, leaseNonce: 'attach-only' } }, + manifestPath, + createFixturePrivateStorage, + ); + jest.mocked(verifyNativeDriverArtifact).mockClear(); + }); + afterEach(() => fs.rmSync(root, { force: true, recursive: true })); + + test('publishes, replaces, and removes only the receipted private record through the storage adapter', async () => { + const stored = JSON.parse(fs.readFileSync(manifestPath, 'utf8')); + const storage = await createFixturePrivateStorage(stored.credentials.root, stored.nativeDriver); + const publish = jest.spyOn(storage, 'publish'); + const remove = jest.spyOn(storage, 'remove'); + const createStorage = jest.fn(async () => storage); + const first = await updateWindowsApplicationLease( + manifestPath, + handoff, + { operation: 'publish', application: application() }, + createStorage, + ); + const firstRecord = fs.readFileSync(leasePath, 'utf8'); + expect(first).toBe(driverManifestDigest(firstRecord)); + expect(JSON.parse(firstRecord)).toEqual({ ...application(), endpoint, nonce: 'attach-only', schemaVersion: 1 }); + expect(firstRecord).not.toContain('bridge-only'); + expect(publish).toHaveBeenCalledWith(path.basename(leasePath), firstRecord); + expect(createStorage).toHaveBeenCalledWith(stored.credentials.root, stored.nativeDriver); + expect(verifyNativeDriverArtifact).toHaveBeenCalledWith(stored.nativeDriver); + await expect( + updateWindowsApplicationLease( + manifestPath, + handoff, + { operation: 'publish', application: { ...application(), processId: 456 } }, + createStorage, + ), + ).rejects.toThrow('previous receipt'); + expect(fs.readFileSync(leasePath, 'utf8')).toBe(firstRecord); + const second = await updateWindowsApplicationLease( + manifestPath, + handoff, + { operation: 'publish', application: { ...application(), processId: 456 }, previousDigest: first }, + createStorage, + ); + expect(remove).toHaveBeenCalledWith(path.basename(leasePath), firstRecord); + await updateWindowsApplicationLease(manifestPath, handoff, { operation: 'remove', digest: first! }, createStorage); + expect(JSON.parse(fs.readFileSync(leasePath, 'utf8')).processId).toBe(456); + await updateWindowsApplicationLease(manifestPath, handoff, { operation: 'remove', digest: second! }, createStorage); + expect(fs.existsSync(leasePath)).toBe(false); + expect(fs.existsSync(path.join(stored.credentials.root, stored.credentials.name))).toBe(true); + }); + + test.each(['missing-handoff', 'tampered-manifest', 'unknown-field'])( + 'refuses %s before verifying a helper or opening private storage', + async (kind) => { + if (kind !== 'missing-handoff') { + const stored = JSON.parse(fs.readFileSync(manifestPath, 'utf8')); + if (kind === 'unknown-field') stored.application.leaseNonce = 'public-secret'; + else stored.nativeDriver.executablePath = path.join(root, 'untrusted-helper'); + fs.writeFileSync(manifestPath, JSON.stringify(stored)); + } + const createStorage = jest.fn(createFixturePrivateStorage); + await expect( + updateWindowsApplicationLease( + manifestPath, + kind === 'missing-handoff' ? '' : handoff, + { operation: 'publish', application: application() }, + createStorage, + ), + ).rejects.toThrow(kind === 'unknown-field' ? 'driver manifest' : 'trusted parent handoff'); + expect(verifyNativeDriverArtifact).not.toHaveBeenCalled(); + expect(createStorage).not.toHaveBeenCalled(); + expect(fs.existsSync(leasePath)).toBe(false); + }, + ); + + test('rejects a mismatched app window without publishing an attach credential', async () => { + await expect( + updateWindowsApplicationLease( + manifestPath, + handoff, + { operation: 'publish', application: { ...application(), windowTitle: 'Another application' } }, + createFixturePrivateStorage, + ), + ).rejects.toThrow('lease identity'); + expect(fs.existsSync(leasePath)).toBe(false); + }); + + test('the actual smoke helper refuses an edited manifest without exposing credentials', () => { + const stored = JSON.parse(fs.readFileSync(manifestPath, 'utf8')); + stored.targetId = 'tampered-target'; + fs.writeFileSync(manifestPath, JSON.stringify(stored)); + const result = spawnSync( + process.execPath, + [ + path.resolve(__dirname, '../../config/application-lease.cjs'), + 'publish', + '--process-id', + '123', + '--process-started-at', + application().processStartedAt, + '--window-title', + 'Fixture', + ...(endpoint === 'windows' ? ['--aumid', 'Fixture!App'] : ['--executable-path', 'C:\\Fixture\\host.exe']), + ], + { + encoding: 'utf8', + env: { ...process.env, STORYBOOK_DRIVER_MANIFEST: manifestPath, STORYBOOK_DRIVER_HANDOFF: handoff }, + timeout: 20_000, + }, + ); + expect(result.status).toBe(1); + expect(result.stderr).toContain('Application lease update failed'); + expect(result.stdout + result.stderr).not.toMatch(/bridge-only|attach-only/); + expect(fs.existsSync(leasePath)).toBe(false); + }); +}); diff --git a/packages/agentic/storybook-desktop/src/driver/applicationLease.ts b/packages/agentic/storybook-desktop/src/driver/applicationLease.ts new file mode 100644 index 0000000000..d61fca9ad7 --- /dev/null +++ b/packages/agentic/storybook-desktop/src/driver/applicationLease.ts @@ -0,0 +1,72 @@ +import path from 'node:path'; + +import { createStorybookPrivateStorage, driverManifestDigest, readDriverManifest } from './generatedManifest.js'; +import type { CreateStorybookPrivateStorage } from './generatedManifest.js'; + +type WindowsApplication = { + aumid?: string; + executablePath?: string; + processId: number; + processStartedAt: string; + windowTitle: string; +}; + +type LeaseUpdate = + | { operation: 'publish'; application: WindowsApplication; previousDigest?: string } + | { operation: 'remove'; digest: string }; + +/** Smoke scripts supply OS-observed identity, never credentials or private-storage paths. */ +export async function updateWindowsApplicationLease( + manifestPath: string, + handoff: string, + update: LeaseUpdate, + createStorage: CreateStorybookPrivateStorage = createStorybookPrivateStorage, +): Promise { + if (!handoff) throw new Error('Desktop Storybook application leases require the trusted parent handoff.'); + const manifest = await readDriverManifest(manifestPath, handoff, createStorage); + if (manifest.endpoint === 'macos') throw new Error('Desktop Storybook Windows application leases require a Windows endpoint.'); + const digest = update.operation === 'remove' ? update.digest : update.previousDigest; + if (digest !== undefined && !/^[0-9a-f]{64}$/.test(digest)) throw new TypeError('Invalid application lease receipt.'); + let contents: string | undefined; + if (update.operation === 'publish') { + const application = update.application; + if ( + !Number.isSafeInteger(application.processId) || + application.processId <= 0 || + !boundedText(application.processStartedAt, 64) || + !Number.isFinite(Date.parse(application.processStartedAt)) || + !boundedText(application.windowTitle, 4096) || + application.windowTitle !== manifest.application.windowTitle || + (manifest.endpoint === 'windows' + ? !boundedText(application.aumid, 4096) || application.executablePath !== undefined + : !boundedText(application.executablePath, 4096) || application.aumid !== undefined) + ) { + throw new TypeError('Invalid Desktop Storybook application lease identity.'); + } + contents = JSON.stringify({ + ...application, + endpoint: manifest.endpoint, + nonce: manifest.application.leaseNonce, + schemaVersion: 1, + }); + } + const storage = await createStorage(path.dirname(manifest.application.leasePath), manifest.nativeDriver); + const name = path.basename(manifest.application.leasePath); + const previous = await storage.read(name); + if (update.operation === 'remove') { + if (previous !== undefined && driverManifestDigest(previous) === digest) await storage.remove(name, previous); + return undefined; + } + if (previous === undefined ? digest !== undefined : driverManifestDigest(previous) !== digest) { + throw new Error('Desktop Storybook application lease does not match its previous receipt.'); + } + if (previous !== undefined && !(await storage.remove(name, previous))) { + throw new Error('Desktop Storybook application lease changed during replacement.'); + } + await storage.publish(name, contents!); + return driverManifestDigest(contents!); +} + +function boundedText(value: unknown, maximum: number): value is string { + return typeof value === 'string' && value.length > 0 && value.length <= maximum && !/\p{Cc}/u.test(value); +} diff --git a/packages/agentic/storybook-desktop/src/driver/fixtures/storedManifest.cjs b/packages/agentic/storybook-desktop/src/driver/fixtures/storedManifest.cjs new file mode 100644 index 0000000000..2d510fd807 --- /dev/null +++ b/packages/agentic/storybook-desktop/src/driver/fixtures/storedManifest.cjs @@ -0,0 +1,44 @@ +const path = require('node:path'); +const { driverManifestVersion } = require('../../../config/generated-contract.cjs'); + +function createFixtureStoredManifest(root, storyManifest) { + const { endpoint, platformManifestDigest, portablePlanDigest } = storyManifest; + return { + application: { leasePath: path.join(root, '.private', `application-lease.${endpoint}.json`), windowTitle: 'Fixture' }, + appName: 'Fixture', + credentials: { name: 'credentials-fixture.json', root: path.join(root, '.private'), runtimeModule: 'runtime-fixture.js' }, + displayName: 'Fixture', + driverPort: 4723, + endpoint, + instanceId: 'fixture', + metroPort: 8081, + nativeDriver: { + architecture: 'x64', + artifactId: 'fixture', + artifactRoot: root, + buildFingerprint: 'fixture', + buildId: 'fixture', + compatibilityKey: 'fixture', + configuration: 'release', + endpoints: [endpoint], + executablePath: path.join(root, 'helper'), + features: [], + origin: 'cache', + provider: endpoint === 'macos' ? 'macos' : 'windows', + schemaVersion: 1, + signing: { mode: 'none' }, + sourceDigest: 'fixture', + wireProtocol: { major: 1, minor: 0 }, + }, + platformManifestDigest, + portablePlanDigest, + renderer: endpoint === 'win32' ? 'paper' : 'fabric', + schemaVersion: driverManifestVersion, + storyManifest, + storybookPort: 7007, + targetId: 'fixture', + testIDPrefix: 'fixture', + }; +} + +module.exports = { createFixtureStoredManifest }; diff --git a/packages/agentic/storybook-desktop/src/driver/fixtures/storedManifest.d.cts b/packages/agentic/storybook-desktop/src/driver/fixtures/storedManifest.d.cts new file mode 100644 index 0000000000..e0775049fc --- /dev/null +++ b/packages/agentic/storybook-desktop/src/driver/fixtures/storedManifest.d.cts @@ -0,0 +1,4 @@ +import type { DesktopStoryManifest } from '@fluentui-react-native/desktop-driver'; +import type { StoredDriverManifest } from '../generatedManifest.js'; + +export function createFixtureStoredManifest(root: string, storyManifest: DesktopStoryManifest): StoredDriverManifest; diff --git a/packages/agentic/storybook-desktop/src/driver/generatedManifest.test.ts b/packages/agentic/storybook-desktop/src/driver/generatedManifest.test.ts index 1317d4b828..fcc7d11b9d 100644 --- a/packages/agentic/storybook-desktop/src/driver/generatedManifest.test.ts +++ b/packages/agentic/storybook-desktop/src/driver/generatedManifest.test.ts @@ -22,7 +22,7 @@ describe('generated manifest trust handoff', () => { let handoff: string; beforeEach(async () => { - root = fs.mkdtempSync(path.join(os.tmpdir(), 'storybook-provenance-')); + root = fs.mkdtempSync(path.join(fs.realpathSync(os.tmpdir()), 'storybook-provenance-')); manifestPath = path.join(root, 'driver-manifest.json'); marker = path.join(root, 'unexpected-spawn'); process.env.FURN_TEST_SPAWN_MARKER = marker; @@ -112,6 +112,21 @@ describe('generated manifest trust handoff', () => { }, ); + test.each(['obsolete-version', 'unknown-field'])('the actual smoke control refuses %s through the shared parser', (kind) => { + const manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8')); + if (kind === 'obsolete-version') manifest.schemaVersion = 2; + else manifest.unrecognized = true; + fs.writeFileSync(manifestPath, JSON.stringify(manifest)); + const result = spawnSync(process.execPath, [path.resolve(__dirname, '../../config/storybook-control.cjs'), '--phase', 'tests'], { + cwd: root, + env: { ...process.env, STORYBOOK_DRIVER_MANIFEST: manifestPath, STORYBOOK_SMOKE_MODE: 'stories-and-tests' }, + encoding: 'utf8', + timeout: 20_000, + }); + expect(result.status).toBe(1); + expect(result.stderr).toContain('driver manifest'); + }); + test('rejects unknown schema versions and credential reuse', async () => { const manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8')); expect(() => parseStoredDriverManifest({ ...manifest, schemaVersion: 2 })).toThrow('driver manifest'); @@ -179,6 +194,34 @@ describe('generated manifest trust handoff', () => { expect(() => parseStoredDriverManifest(manifest)).toThrow('driver manifest'); }); + (process.platform === 'darwin' ? test : test.skip)( + 'canonicalizes a symlinked project once and refuses a subsequently replaced canonical ancestor', + async () => { + const fixture = await readDriverManifest(manifestPath, undefined, createFixturePrivateStorage); + const project = path.join(root, 'project'); + const alias = path.join(root, 'project-alias'); + const generated = path.join(project, 'storybook-desktop.generated'); + const aliasedManifest = path.join(alias, 'storybook-desktop.generated', 'driver-manifest.json'); + fs.mkdirSync(generated, { recursive: true, mode: 0o700 }); + fs.symlinkSync(project, alias, 'dir'); + const canonicalRoot = path.join(generated, '.private'); + let storage: Awaited>; + const { createMacOSPrivateStorage } = await import('@fluentui-react-native/desktop-driver/authority'); + await writeDesktopStorybookDriverManifest(fixture, aliasedManifest, async (storageRoot) => { + expect(storageRoot).toBe(canonicalRoot); + storage = await createMacOSPrivateStorage(storageRoot); + return storage; + }); + const stored = JSON.parse(fs.readFileSync(aliasedManifest, 'utf8')); + expect(stored.application.leasePath).toBe(path.join(canonicalRoot, 'application-lease.windows.json')); + expect((await readDriverManifest(aliasedManifest)).bridgeNonce).toBe(fixture.bridgeNonce); + const moved = path.join(root, 'moved-project'); + fs.renameSync(project, moved); + fs.symlinkSync(moved, project, 'dir'); + await expect(storage!.read(stored.credentials.name)).rejects.toThrow(project); + }, + ); + (process.platform === 'darwin' ? test : test.skip)( 'publishes and reads real macOS owner-private records, refusing a permissive credential mode', async () => { @@ -216,3 +259,4 @@ describe('generated manifest trust handoff', () => { } }); }); +import { spawnSync } from 'node:child_process'; diff --git a/packages/agentic/storybook-desktop/src/driver/generatedManifest.ts b/packages/agentic/storybook-desktop/src/driver/generatedManifest.ts index 14b11589a9..29b94c1949 100644 --- a/packages/agentic/storybook-desktop/src/driver/generatedManifest.ts +++ b/packages/agentic/storybook-desktop/src/driver/generatedManifest.ts @@ -62,14 +62,22 @@ export async function publishDriverManifest( createStorage = createStorybookPrivateStorage, ): Promise { fs.mkdirSync(path.dirname(outputPath), { recursive: true }); - const root = path.join(path.dirname(outputPath), '.private'); + // Resolve the existing directory once; storage continues checking the canonical ancestors on every operation. + const directory = fs.realpathSync(path.dirname(outputPath)); + outputPath = path.join(directory, path.basename(outputPath)); + const root = path.join(directory, '.private'); const storage = await createStorage(root, manifest.nativeDriver); const id = randomUUID(); const name = `credentials-${id}.json`; const runtimeModule = `runtime-${id}.js`; const { bridgeNonce, application, ...rest } = manifest; const { leaseNonce, ...publicApplication } = application; - const stored = parseStoredDriverManifest({ ...rest, application: publicApplication, credentials: { name, root, runtimeModule } }); + const leaseName = `application-lease.${manifest.endpoint}.json`; + const stored = parseStoredDriverManifest({ + ...rest, + application: { ...publicApplication, leasePath: path.join(root, leaseName) }, + credentials: { name, root, runtimeModule }, + }); const contents = `${JSON.stringify(stored, null, 2)}\n`; const manifestDigest = driverManifestDigest(contents); const credentials = JSON.stringify(parseCredentials({ bridgeNonce, leaseNonce, manifestDigest, schemaVersion: credentialsVersion })); @@ -95,7 +103,10 @@ export async function publishDriverManifest( await storage.publish(name, credentials); try { await storage.publish(runtimeModule, runtimeContents); - fs.rmSync(manifest.application.leasePath, { force: true }); + const previousLease = await storage.read(leaseName); + if (previousLease !== undefined && !(await storage.remove(leaseName, previousLease))) { + throw new Error('Desktop Storybook application lease changed during publication.'); + } if (manifest.agent) fs.rmSync(manifest.agent.readyPath, { force: true }); // No secret is present here; privateStorage owns credential and runtime-module publication. const pending = `${outputPath}.${id}.pending`; @@ -136,10 +147,12 @@ export async function readDriverManifest( createStorage = createStorybookPrivateStorage, trustedArtifact?: NativeDriverArtifact, ): Promise { + const directory = fs.realpathSync(path.dirname(manifestPath)); + manifestPath = path.join(directory, path.basename(manifestPath)); const contents = fs.readFileSync(manifestPath, 'utf8'); const stored = parseStoredDriverManifest(JSON.parse(contents)); if ( - stored.credentials.root !== path.join(path.dirname(manifestPath), '.private') || + stored.credentials.root !== path.join(directory, '.private') || stored.application.leasePath !== path.join(stored.credentials.root, `application-lease.${stored.endpoint}.json`) ) { throw new Error('Desktop Storybook private state must use the generated instance namespace.'); diff --git a/packages/agentic/storybook-desktop/src/driver/serverIntegration.test.ts b/packages/agentic/storybook-desktop/src/driver/serverIntegration.test.ts index beda03b2a1..9c1c338674 100644 --- a/packages/agentic/storybook-desktop/src/driver/serverIntegration.test.ts +++ b/packages/agentic/storybook-desktop/src/driver/serverIntegration.test.ts @@ -19,7 +19,7 @@ describe('desktop Storybook server integration', () => { 'the actual channel process rejects %s before spawning a helper or listening', async (tamper) => { const [storybookPort, driverPort] = await Promise.all([getAvailablePort(), getAvailablePort()]); - const root = fs.mkdtempSync(path.join(os.tmpdir(), 'storybook-spawn-trust-')); + const root = fs.mkdtempSync(path.join(fs.realpathSync(os.tmpdir()), 'storybook-spawn-trust-')); const manifestPath = path.join(root, 'driver-manifest.json'); const marker = path.join(root, 'unexpected-spawn'); const fixture = createIntegrationManifest(root, storybookPort, driverPort); diff --git a/packages/agentic/storybook-desktop/src/testing/wdioRunner.contract.cjs b/packages/agentic/storybook-desktop/src/testing/wdioRunner.contract.cjs index 44dd1bbb3c..c364a2d321 100644 --- a/packages/agentic/storybook-desktop/src/testing/wdioRunner.contract.cjs +++ b/packages/agentic/storybook-desktop/src/testing/wdioRunner.contract.cjs @@ -5,6 +5,7 @@ const http = require('node:http'); const os = require('node:os'); const path = require('node:path'); const { pathToFileURL } = require('node:url'); +const { createFixtureStoredManifest } = require('../driver/fixtures/storedManifest.cjs'); async function main() { const packageRoot = path.resolve(__dirname, '..', '..'); @@ -273,7 +274,7 @@ async function main() { fs.writeFileSync( smokeManifestPath, JSON.stringify({ - schemaVersion: 2, + ...createFixtureStoredManifest(root, manifest), endpoint: 'windows', driverPort: Number(new URL(harness.server.url).port), targetId: harness.target.id, From 2739349a35c8611f966e532cfac58e4841c17d71 Mon Sep 17 00:00:00 2001 From: Jason Morse Date: Thu, 12 Nov 2026 03:00:58 +0000 Subject: [PATCH 06/11] Record reviewed provenance validation and pending native lanes Replace superseded local temporary-directory qualification with default-TMPDIR package and aggregate evidence. Keep macOS consumer permission blocks and unobserved Windows/Win32 coverage explicit. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../desktop-test/references/current-status.md | 20 ++++++++----------- 1 file changed, 8 insertions(+), 12 deletions(-) diff --git a/packages/agentic/desktop-test/references/current-status.md b/packages/agentic/desktop-test/references/current-status.md index 58436a1cff..396b1d03fe 100644 --- a/packages/agentic/desktop-test/references/current-status.md +++ b/packages/agentic/desktop-test/references/current-status.md @@ -798,7 +798,7 @@ helper path/hash, helper bytes, and unknown fields before listening or spawning. The real macOS private-storage adapter round-trips the records with directory mode `0700` and file mode `0600` and rejects a permissive credential mode. -**Confirmed native helper checks:** on macOS 27.2.1 arm64, the locked +**Pre-review native helper checks:** on macOS 27.2.1 arm64, the locked `FURN_NATIVE_DRIVER_TEST=1 yarn workspace @fluentui-react-native/desktop-driver test --runInBand` run passed 1,240 tests; 47 platform/capability tests were skipped (75 suites passed, six skipped). @@ -844,17 +844,13 @@ app PID was verified, terminated, and confirmed gone. Positive Fabric/Paper traversal and authored-case qualification remain pending an authorized Accessibility/PostEvent-capable host. -**Initial repository checks (before review fixes):** after `yarn clean-lage-cache`, the locked -`TF_BUILD=1 yarn lage buildci --concurrency 4` passed all 178 tasks. -The existing test wrapper uses `TF_BUILD` only to run Jest in-band; it does not -skip agentic tests. Evidence: -`apps/storybook/artifacts/f6/buildci-serialized-jest.log`. -The first aggregate attempt caught formatting of the awaited claim (fixed -in `fa0681635`). A subsequent default-parallel aggregate passed 103 tasks but -failed the existing bounded-command test with `SIGTERM` rather than the -expected `SIGKILL`; a child startup/deadline race under load is inferred, not -proven. The in-band aggregate was its single justified retry; no unrelated -test or production behavior was changed. +**Reviewed repository checks:** source `ffb4944db` passed all 90 +`yarn lage test-links --verbose --grouped` tasks. After `yarn clean-lage-cache`, +the locked `TF_BUILD=1 yarn lage buildci --concurrency 4` passed all 178 tasks +with the default macOS `TMPDIR`. The existing test wrapper uses `TF_BUILD` +only to run Jest in-band; it does not skip agentic tests. Evidence: +`apps/storybook/artifacts/f6/review-links.log` and `review-buildci.log`. +The Accessibility-blocked macOS consumer smoke was not repeated for review. **Windows/Win32 qualification: pending, not sufficient yet.** Native execution is unavailable on this Mac, and `pwsh` is not installed, so PowerShell parser From 17032203bcc832ff358794a7a129be99241b14ab Mon Sep 17 00:00:00 2001 From: Jason Morse Date: Thu, 12 Nov 2026 03:45:56 +0000 Subject: [PATCH 07/11] Fix cross-platform Storybook private storage publication Forward injected storage through the CLI factory and select host adapters explicitly. Derive protected Windows namespaces from the helper-selected per-user root, preserve Metro access outside the workspace, and report bounded refusal reasons without weakening native ACL checks. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .changeset/curvy-dragons-fry.md | 2 + .changeset/tidy-boats-smile.md | 2 + .../desktop-driver/references/security.md | 5 +- .../authority/windowsPrivateStorage.test.ts | 18 +++ .../src/authority/windowsPrivateStorage.ts | 8 +- .../desktop-test/references/current-status.md | 44 ++++++- .../config/metro.cjs | 3 + .../references/runtime-contract.md | 4 + .../src/metro.test.ts | 25 +++- .../references/contributing.md | 13 ++ .../src/cli/DesktopStorybookCli.test.ts | 3 + .../src/cli/createDesktopStorybookCommand.ts | 1 + .../src/driver/generatedManifest.ts | 46 ++++++- .../src/driver/generatedStorage.test.ts | 123 ++++++++++++++++++ 14 files changed, 282 insertions(+), 15 deletions(-) create mode 100644 packages/agentic/storybook-desktop/src/driver/generatedStorage.test.ts diff --git a/.changeset/curvy-dragons-fry.md b/.changeset/curvy-dragons-fry.md index 5f6cf468fb..2c45edb258 100644 --- a/.changeset/curvy-dragons-fry.md +++ b/.changeset/curvy-dragons-fry.md @@ -4,3 +4,5 @@ --- Separate Storybook bridge and attachment credentials in owner-private storage, validate versioned generated manifests, and pin native helper provenance through the trusted parent handoff before child processes can spawn helpers. + +Use helper-selected per-user namespaces on Windows, retain Metro resolution of private projections outside the workspace, and forward private-storage adapters into platform-neutral CLI contracts. diff --git a/.changeset/tidy-boats-smile.md b/.changeset/tidy-boats-smile.md index 485d1ac07f..f4aa7a0472 100644 --- a/.changeset/tidy-boats-smile.md +++ b/.changeset/tidy-boats-smile.md @@ -3,3 +3,5 @@ --- Identify the unsafe ancestor when macOS private storage rejects directory aliases, permissions, or ACLs. + +Expose the Windows helper's validated storage root so consumers can create protected namespaces beneath its OS-selected per-user location. diff --git a/packages/agentic/desktop-driver/references/security.md b/packages/agentic/desktop-driver/references/security.md index 2da943ac3e..74080fffdc 100644 --- a/packages/agentic/desktop-driver/references/security.md +++ b/packages/agentic/desktop-driver/references/security.md @@ -175,7 +175,10 @@ process recovery, automatic discovery, or supervisor wiring. `PrivateStorage` contract through the verified Windows helper's one-shot `--private-storage` mode, so the operating system judges ownership from open handles and Node never trusts a path check. The default root is a per-user -folder under the local application data folder. An override must be a canonical +folder under the local application data folder, resolved through the OS +known-folder API rather than an environment variable. The returned `root` +identifies that validated directory, allowing consumers to open independently +protected child namespaces without guessing the platform location. An override must be a canonical absolute local-drive path of at most 240 characters whose parent exists. A missing root is created atomically with an owner-only protected DACL (one allow entry giving the current user full control); an existing root is validated and diff --git a/packages/agentic/desktop-driver/src/authority/windowsPrivateStorage.test.ts b/packages/agentic/desktop-driver/src/authority/windowsPrivateStorage.test.ts index 433345d4f0..1b75f76ddb 100644 --- a/packages/agentic/desktop-driver/src/authority/windowsPrivateStorage.test.ts +++ b/packages/agentic/desktop-driver/src/authority/windowsPrivateStorage.test.ts @@ -1,3 +1,5 @@ +import path from 'node:path'; + import type { NativeDriverArtifact } from '../native/types'; import { FakeAuthorityHelper } from '../native/windows/fakeAuthorityHelper'; import { createWindowsPrivateStorage } from './windowsPrivateStorage'; @@ -98,6 +100,22 @@ describe('creating Windows private storage', () => { expect(requests()).toEqual([{ operation: 'open' }, { identity, name: 'connection.json', operation: 'read', root: defaultRoot }]); }); + test('opens a protected child namespace beneath the root selected by the helper', async () => { + const defaultRoot = 'C:\\Users\\agent\\AppData\\Local\\com.microsoft.fluentui-react-native.desktop-driver'; + const childRoot = path.win32.join(defaultRoot, 'storybook-fixture'); + helper.answer({ identity, ok: true, root: defaultRoot }).answer({ identity, ok: true, root: childRoot }).answer({ ok: true }); + + const parent = await createWindowsPrivateStorage({ artifact }); + const child = await createWindowsPrivateStorage({ artifact, root: path.win32.join(parent.root, 'storybook-fixture') }); + await child.publish('record', 'protected'); + + expect(requests()).toEqual([ + { operation: 'open' }, + { operation: 'open', root: childRoot }, + { contents: base64('protected'), identity, name: 'record', operation: 'publish', root: childRoot }, + ]); + }); + test('maps a helper refusal to the unsafe-storage failure', async () => { helper.answer({ detail: 'C:\\Users\\agent\\secret', ok: false, reason: 'dacl' }); diff --git a/packages/agentic/desktop-driver/src/authority/windowsPrivateStorage.ts b/packages/agentic/desktop-driver/src/authority/windowsPrivateStorage.ts index 837ef30167..f8fc436418 100644 --- a/packages/agentic/desktop-driver/src/authority/windowsPrivateStorage.ts +++ b/packages/agentic/desktop-driver/src/authority/windowsPrivateStorage.ts @@ -35,9 +35,12 @@ const publicationFailed = (reason: string): Error => /** * Opens the Windows owner-only state root through the Windows helper. The parent must already exist. Existing roots are - * validated, never repaired. Failures carry a fixed message and a non-enumerable `reason` for diagnostics only. + * validated, never repaired. The returned root is the canonical directory validated by the helper, including when the + * helper selected its per-user default. Failures carry a fixed message and a non-enumerable `reason` for diagnostics only. */ -export async function createWindowsPrivateStorage(options: WindowsPrivateStorageOptions): Promise { +export async function createWindowsPrivateStorage( + options: WindowsPrivateStorageOptions, +): Promise { if (process.platform !== 'win32') { throw new Error('Windows private storage is unsupported on this platform; use a validated native ownership adapter.'); } @@ -77,6 +80,7 @@ export async function createWindowsPrivateStorage(options: WindowsPrivateStorage } return { + root, async read(name) { assertPrivateRecordName(name); const answer = await call({ name, operation: 'read' }, readAnswer, unsafeStorage); diff --git a/packages/agentic/desktop-test/references/current-status.md b/packages/agentic/desktop-test/references/current-status.md index 396b1d03fe..5d08c52436 100644 --- a/packages/agentic/desktop-test/references/current-status.md +++ b/packages/agentic/desktop-test/references/current-status.md @@ -852,11 +852,49 @@ only to run Jest in-band; it does not skip agentic tests. Evidence: `apps/storybook/artifacts/f6/review-links.log` and `review-buildci.log`. The Accessibility-blocked macOS consumer smoke was not repeated for review. +**First PR CI follow-up (2026-11-12):** run `43145388693` on +`2739349a3` exposed five Linux CLI fixture failures and both Win32 smoke +lanes refusing private storage before any stories ran. The Linux cause is +confirmed: the command factory dropped the injected `createPrivateStorage` +adapter. It now forwards that option, and platform selection explicitly +supports macOS/Windows while other production credential paths fail closed. +Portable contracts inject storage and simulate all three platform branches. + +The Win32 logs retained only the generic unsafe-storage message, not the +adapter's non-enumerable refusal reason; the exact native refusal category +cannot be recovered from that evidence. Native inspection confirms that the +workspace root was checked before creation and ancestor grants allowing +untrusted child replacement are refused. Unsafe hosted-workspace ancestry +is therefore an inferred cause, not a confirmed refusal category. +Windows publication now asks the verified helper for its OS-selected per-user +known-folder root and opens a deterministic, independently protected child +namespace for the canonical generated directory. Reading rederives that +namespace only after verifying the parent handoff and helper. No environment +path, editable manifest root, relaxed ACL, or root repair chooses authority. +Storybook now surfaces the bounded native refusal token. Metro retains its +workspace roots and also watches the pinned private runtime projection +outside the workspace. + +The separate Windows setup job failed four native build/handshake/UIA +timeout cases, but its existing Windows private-storage native contracts +passed. This branch does not change Windows helper build, resolution, +handshake, C++, UIA, or fixture code; setup runs before Storybook publication. +Runner flakiness is an inference, not a confirmed explanation. The next +same-branch CI run must establish the result; timeouts were not increased. + +**CI-fix portable validation (default `TMPDIR`):** driver format/lint/build/test +passed (1,222 tests; 66 skipped); Storybook integration passed (386; 4 skipped); +runtime passed (34). The new contracts cover OS dispatch, helper-selected +project isolation, trust-before-helper ordering, changed-root and tamper +refusal, protected child calls, and outside-workspace Metro resolution. +Evidence: `apps/storybook/artifacts/f6/ci-fix-{driver,integration,runtime}.log`. +These simulated-platform results are not Windows ACL qualification. + **Windows/Win32 qualification: pending, not sufficient yet.** Native execution is unavailable on this Mac, and `pwsh` is not installed, so PowerShell parser -validation was not run. The configured private-storage contracts and Windows -Fabric/Win32 Paper smoke jobs are candidate coverage, not observed evidence -that these revised paths work. A passing same-branch run must demonstrate +validation was not run. The first CI run confirms that Win32 Paper smoke +reaches the changed protected-storage path, but it does not qualify the +revised namespace or Windows Fabric flow. A passing same-branch run must demonstrate version-3 smoke control, trusted helper verification, protected-DACL lease publication/replacement/cleanup, private runtime resolution, and live bridge authentication. Portable negative fixtures do not qualify Windows ACL diff --git a/packages/agentic/storybook-desktop-runtime/config/metro.cjs b/packages/agentic/storybook-desktop-runtime/config/metro.cjs index 5806d20abb..5829ee0ff8 100644 --- a/packages/agentic/storybook-desktop-runtime/config/metro.cjs +++ b/packages/agentic/storybook-desktop-runtime/config/metro.cjs @@ -57,6 +57,9 @@ function createDesktopStorybookMetroConfig({ configPath }) { unstable_allowRequireContext: true, }, }); + // Windows credentials live outside the workspace in a protected per-user namespace. Metro must watch the pinned + // projection's directory to hash/import that module, without losing the workspace folders chosen by makeMetroConfig. + config.watchFolders = [...new Set([...(config.watchFolders || []), path.dirname(runtimeModulePath)])]; const storybookConfig = withStorybook(config, { configPath, diff --git a/packages/agentic/storybook-desktop-runtime/references/runtime-contract.md b/packages/agentic/storybook-desktop-runtime/references/runtime-contract.md index 5afecf34d6..92c93d880b 100644 --- a/packages/agentic/storybook-desktop-runtime/references/runtime-contract.md +++ b/packages/agentic/storybook-desktop-runtime/references/runtime-contract.md @@ -92,6 +92,10 @@ unknown generated fields and mismatched manifest/module hashes before using the owner's private bridge-only module. It never uses the generated helper path or receives the independent application-attachment nonce. The parent publishes credentials through OS private storage, not default-mode files. +On Windows the projection lives in the helper-selected per-user namespace +outside the workspace. Metro adds that pinned module's directory to its +watch folders without replacing the existing workspace roots; it does not +copy the projection or attachment credentials into public generated output. The generated module's only statement is `export default `; the constant runtime loader imports it through Metro's resolver instead of embedding values in executable polyfill source. The old global instance remains a compatibility diff --git a/packages/agentic/storybook-desktop-runtime/src/metro.test.ts b/packages/agentic/storybook-desktop-runtime/src/metro.test.ts index ea6507d482..4b5a841fd3 100644 --- a/packages/agentic/storybook-desktop-runtime/src/metro.test.ts +++ b/packages/agentic/storybook-desktop-runtime/src/metro.test.ts @@ -4,7 +4,11 @@ import os from 'node:os'; import path from 'node:path'; jest.mock('@rnx-kit/metro-config', () => ({ - makeMetroConfig: (config: object) => ({ ...config, serializer: { getPolyfills: () => ['base-polyfill'] } }), + makeMetroConfig: (config: object) => ({ + ...config, + serializer: { getPolyfills: () => ['base-polyfill'] }, + watchFolders: ['existing-workspace'], + }), })); jest.mock('@rnx-kit/metro-resolver-symlinks', () => () => jest.fn()); jest.mock('@storybook/react-native/withStorybook', () => ({ withStorybook: (config: unknown) => config })); @@ -35,8 +39,7 @@ describe('controlled Metro generation fixtures', () => { fs.rmSync(root, { force: true, recursive: true }); }); - function controlledManifest() { - const privateRoot = path.join(root, 'storybook-desktop.generated', '.private'); + function controlledManifest(privateRoot = path.join(root, 'storybook-desktop.generated', '.private')) { const runtimeModulePath = path.join(privateRoot, 'runtime-fixture.js'); const runtimeContents = 'export default {"bridgeNonce":"bridge-only"};\n'; const nativeDriver = { @@ -84,6 +87,7 @@ describe('controlled Metro generation fixtures', () => { }; const manifestPath = path.join(root, 'storybook-desktop.generated', 'driver-manifest.json'); const contents = JSON.stringify(manifest); + fs.mkdirSync(path.dirname(manifestPath), { recursive: true }); fs.mkdirSync(privateRoot, { recursive: true, mode: 0o700 }); fs.writeFileSync(runtimeModulePath, runtimeContents, { mode: 0o600 }); fs.writeFileSync(manifestPath, contents); @@ -132,6 +136,21 @@ describe('controlled Metro generation fixtures', () => { expect(fs.existsSync(path.join(root, 'storybook-desktop.generated', 'runtime-instance.js'))).toBe(false); }); + test('watches a pinned projection outside the app workspace while preserving existing workspace roots', () => { + const fixture = controlledManifest(path.join(root, 'per-user-state', 'storybook-fixture')); + const project = path.join(root, 'workspace', 'app'); + const config = createDesktopStorybookMetroConfig({ configPath: path.join(project, 'src') }); + expect(config.watchFolders).toEqual(['existing-workspace', path.dirname(fixture.runtimeModulePath)]); + expect( + config.resolver.resolveRequest( + { originModulePath: path.join(__dirname, 'createDesktopStorybookApp.tsx') }, + '../config/runtime-instance.cjs', + 'windows', + ), + ).toEqual({ type: 'sourceFile', filePath: fixture.runtimeModulePath }); + expect(fs.existsSync(path.join(project, 'storybook-desktop.generated'))).toBe(false); + }); + test.each(['missing-handoff', 'missing-contract', 'unknown-field', 'manifest-tamper', 'runtime-tamper'])( 'fails closed on %s before generating a runtime module', (failure) => { diff --git a/packages/agentic/storybook-desktop/references/contributing.md b/packages/agentic/storybook-desktop/references/contributing.md index 60cadc1192..e2e1318f6b 100644 --- a/packages/agentic/storybook-desktop/references/contributing.md +++ b/packages/agentic/storybook-desktop/references/contributing.md @@ -37,6 +37,13 @@ The public generated JSON contains credential references, never either nonce. runtime data module through desktop-driver's owner-private storage adapter: POSIX directory/file modes `0700`/`0600` with ownership/ACL checks on macOS, and the native owner/DACL/reparse/root-identity boundary on Windows. +Windows uses a deterministic, project-specific child of the helper-selected +per-user known-folder root, not the generated workspace directory: a hosted +workspace's ancestors can grant other principals child replacement rights. +Both the parent and child are opened by the existing native adapter; neither +ACL requirements nor reparse/root-identity checks are relaxed. The adapter's +validated root, not `LOCALAPPDATA` or editable manifest fields, chooses the +location. Its closed refusal reason is included in Storybook diagnostics. Application attachment leases stay in that private namespace. Their random nonce is independent of the runtime bridge nonce; the lease nonce never reaches Metro. Publication resolves the existing generated directory once, so symlinked project @@ -58,6 +65,12 @@ Metro receives the canonical schema locator through the parent's against the handoff, and never reconstructs credentials from public JSON. The locator is trusted process configuration, not a manifest-controlled path. This keeps the integration CLI peer-free; the runtime remains app-owned. +Metro explicitly watches the pinned module directory while retaining its +workspace watch roots, so the per-user Windows projection remains resolvable. +The command factory must forward `createPrivateStorage` as well as native +helper adapters. Portable CLI tests inject storage instead of accidentally +depending on their host; production credential publication remains unsupported +on hosts other than macOS and Windows. Do not launch a native channel by copying only a generated manifest or by inventing a handoff from its fields. Use the owning CLI lifecycle. The explicit diff --git a/packages/agentic/storybook-desktop/src/cli/DesktopStorybookCli.test.ts b/packages/agentic/storybook-desktop/src/cli/DesktopStorybookCli.test.ts index 7c29b8a5dd..f4b33b45df 100644 --- a/packages/agentic/storybook-desktop/src/cli/DesktopStorybookCli.test.ts +++ b/packages/agentic/storybook-desktop/src/cli/DesktopStorybookCli.test.ts @@ -1624,8 +1624,10 @@ describe('createDesktopStorybookCommand', () => { test('forwards the selected smoke mode and isolated instance to a package-owned lifecycle', async () => { const runner = new RecordingRunner(); + const createPrivateStorage = jest.fn(createFixturePrivateStorage); const program = createDesktopStorybookCommand({ ...nativeDriverTestOptions, + createPrivateStorage, config: makeConfig({ windows: { smoke: { @@ -1642,6 +1644,7 @@ describe('createDesktopStorybookCommand', () => { try { await program.parseAsync(['node', 'test', 'smoke', '--windows', '--mode', 'stories-and-tests']); + expect(createPrivateStorage).toHaveBeenCalled(); expect(runner.foreground[0]).toMatchObject({ command: 'smoke-windows', env: { diff --git a/packages/agentic/storybook-desktop/src/cli/createDesktopStorybookCommand.ts b/packages/agentic/storybook-desktop/src/cli/createDesktopStorybookCommand.ts index 44793d85ea..baed40f455 100644 --- a/packages/agentic/storybook-desktop/src/cli/createDesktopStorybookCommand.ts +++ b/packages/agentic/storybook-desktop/src/cli/createDesktopStorybookCommand.ts @@ -92,6 +92,7 @@ export function createDesktopStorybookCommand(options: CreateDesktopStorybookCom return new DesktopStorybookCli(config, { buildNativeDriver: options.buildNativeDriver, runner: options.runner, + createPrivateStorage: options.createPrivateStorage, createStoryManifest: options.createStoryManifest, fetch: options.fetch, output: options.output, diff --git a/packages/agentic/storybook-desktop/src/driver/generatedManifest.ts b/packages/agentic/storybook-desktop/src/driver/generatedManifest.ts index 29b94c1949..0169e0b9ed 100644 --- a/packages/agentic/storybook-desktop/src/driver/generatedManifest.ts +++ b/packages/agentic/storybook-desktop/src/driver/generatedManifest.ts @@ -33,11 +33,39 @@ type Handoff = { }; export type CreateStorybookPrivateStorage = (root: string, artifact: NativeDriverArtifact) => Promise; -export const createStorybookPrivateStorage: CreateStorybookPrivateStorage = (root, artifact) => { - if (process.platform === 'win32') return createWindowsPrivateStorage({ artifact, root }); - return createMacOSPrivateStorage(root); +export const createStorybookPrivateStorage: CreateStorybookPrivateStorage = async (root, artifact) => { + if (process.platform === 'win32') return openWindowsPrivateStorage({ artifact, root }); + if (process.platform === 'darwin') return createMacOSPrivateStorage(root); + throw new Error( + `Desktop Storybook private credentials are unsupported on ${process.platform}. Use a macOS or Windows host; portable tests must inject a private-storage adapter.`, + ); }; +async function openWindowsPrivateStorage(options: Parameters[0]) { + try { + return await createWindowsPrivateStorage(options); + } catch (error) { + const reason = error instanceof Error && 'reason' in error ? error.reason : undefined; + if (typeof reason !== 'string' || !/^[a-z]{1,16}$/.test(reason)) throw error; + throw new Error( + `Desktop Storybook Windows private storage was refused (reason: ${reason}). A protected-DACL root with trusted ancestors is required.`, + { cause: error }, + ); + } +} + +function usesWindowsPrivateStorage(createStorage: CreateStorybookPrivateStorage): boolean { + return process.platform === 'win32' && createStorage === createStorybookPrivateStorage; +} + +async function privateStorageRoot(directory: string, artifact: NativeDriverArtifact, createStorage: CreateStorybookPrivateStorage) { + if (!usesWindowsPrivateStorage(createStorage)) return path.join(directory, '.private'); + // Workspace ancestors can grant other users write/delete access. Let the verified helper choose its known-folder + // root, not an environment variable, then create an independently protected namespace for this generated directory. + const parent = await openWindowsPrivateStorage({ artifact }); + return path.join(parent.root, `storybook-${driverManifestDigest(directory)}`); +} + export function parseStoredDriverManifest(value: unknown): StoredDriverManifest { const manifest = parseDriverManifest(value) as StoredDriverManifest; for (const entry of manifest.storyManifest.entries) { @@ -65,7 +93,7 @@ export async function publishDriverManifest( // Resolve the existing directory once; storage continues checking the canonical ancestors on every operation. const directory = fs.realpathSync(path.dirname(outputPath)); outputPath = path.join(directory, path.basename(outputPath)); - const root = path.join(directory, '.private'); + const root = await privateStorageRoot(directory, manifest.nativeDriver, createStorage); const storage = await createStorage(root, manifest.nativeDriver); const id = randomUUID(); const name = `credentials-${id}.json`; @@ -152,7 +180,7 @@ export async function readDriverManifest( const contents = fs.readFileSync(manifestPath, 'utf8'); const stored = parseStoredDriverManifest(JSON.parse(contents)); if ( - stored.credentials.root !== path.join(directory, '.private') || + (!usesWindowsPrivateStorage(createStorage) && stored.credentials.root !== path.join(directory, '.private')) || stored.application.leasePath !== path.join(stored.credentials.root, `application-lease.${stored.endpoint}.json`) ) { throw new Error('Desktop Storybook private state must use the generated instance namespace.'); @@ -173,7 +201,13 @@ export async function readDriverManifest( // macOS lease writers only read private records, without executing a helper. Windows always needs trusted provenance. throw new Error('Desktop Storybook requires a trusted parent helper handoff.'); } - const storage = await createStorage(stored.credentials.root, artifact); + // Resolving the Windows per-user namespace itself launches a helper. Do it only after the parent binding and + // executable verification above; an editable manifest must never authorize even this one-shot helper. + const root = await privateStorageRoot(directory, artifact, createStorage); + if (stored.credentials.root !== root) { + throw new Error('Desktop Storybook private state must use the generated instance namespace.'); + } + const storage = await createStorage(root, artifact); const record = await storage.read(stored.credentials.name); if (trusted && (record === undefined || trusted.credentialsDigest !== driverManifestDigest(record))) { throw new Error('Desktop Storybook credentials do not match the trusted parent handoff.'); diff --git a/packages/agentic/storybook-desktop/src/driver/generatedStorage.test.ts b/packages/agentic/storybook-desktop/src/driver/generatedStorage.test.ts new file mode 100644 index 0000000000..de1732405a --- /dev/null +++ b/packages/agentic/storybook-desktop/src/driver/generatedStorage.test.ts @@ -0,0 +1,123 @@ +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; + +import type { NativeDriverArtifact } from '@fluentui-react-native/desktop-driver'; +import { createFixturePrivateStorage } from './fixtures/privateStorage'; +import { createFixtureStoredManifest } from './fixtures/storedManifest.cjs'; +import type { DesktopStorybookDriverManifest } from './driverManifest'; +import { createStorybookPrivateStorage, publishDriverManifest, readDriverManifest } from './generatedManifest'; + +const mockMacOSStorage = jest.fn(); +const mockWindowsStorage = jest.fn(); +const mockVerify = jest.fn(); +jest.mock('@fluentui-react-native/desktop-driver/authority', () => ({ + createMacOSPrivateStorage: (...args: unknown[]) => mockMacOSStorage(...args), + createWindowsPrivateStorage: (...args: unknown[]) => mockWindowsStorage(...args), +})); +jest.mock('@fluentui-react-native/desktop-driver/native', () => ({ + verifyNativeDriverArtifact: (...args: unknown[]) => mockVerify(...args), +})); + +const originalPlatform = Object.getOwnPropertyDescriptor(process, 'platform')!; +let root: string; +let privateParent: string; +let manifestPath: string; +let manifest: DesktopStorybookDriverManifest; + +beforeEach(() => { + root = fs.mkdtempSync(path.join(fs.realpathSync(os.tmpdir()), 'storybook-storage-')); + privateParent = path.join(root, 'os-known-folder'); + manifestPath = path.join(root, 'workspace', 'generated', 'manifest.json'); + const { credentials: _credentials, ...stored } = createFixtureStoredManifest(root, { + endpoint: 'windows', + entries: [], + platformManifestDigest: 'platform', + portablePlanDigest: 'portable', + schemaVersion: 1, + }); + manifest = { ...stored, bridgeNonce: 'bridge-only', application: { ...stored.application, leaseNonce: 'attach-only' } }; + mockMacOSStorage.mockReset().mockResolvedValue({}); + mockWindowsStorage.mockReset().mockImplementation(async ({ artifact, root: requestedRoot }) => { + const directory = requestedRoot ?? privateParent; + return { ...(await createFixturePrivateStorage(directory, artifact)), root: directory }; + }); + mockVerify.mockReset().mockImplementation(async (artifact: NativeDriverArtifact) => artifact); +}); +afterEach(() => { + Object.defineProperty(process, 'platform', originalPlatform); + fs.rmSync(root, { force: true, recursive: true }); +}); + +test.each(['darwin', 'win32', 'linux'] as const)('selects only the %s host storage boundary', async (platform) => { + Object.defineProperty(process, 'platform', { value: platform }); + if (platform === 'linux') { + await expect(createStorybookPrivateStorage(root, manifest.nativeDriver)).rejects.toThrow('portable tests must inject'); + expect(mockMacOSStorage).not.toHaveBeenCalled(); + expect(mockWindowsStorage).not.toHaveBeenCalled(); + } else { + await createStorybookPrivateStorage(root, manifest.nativeDriver); + if (platform === 'win32') { + expect(mockWindowsStorage).toHaveBeenCalledWith({ artifact: manifest.nativeDriver, root }); + expect(mockMacOSStorage).not.toHaveBeenCalled(); + } else { + expect(mockMacOSStorage).toHaveBeenCalledWith(root); + expect(mockWindowsStorage).not.toHaveBeenCalled(); + } + } +}); + +test('keeps Windows credentials out of the workspace in a helper-selected, project-specific namespace', async () => { + Object.defineProperty(process, 'platform', { value: 'win32' }); + const handoff = await publishDriverManifest(manifest, manifestPath); + const stored = JSON.parse(fs.readFileSync(manifestPath, 'utf8')); + const namespace = stored.credentials.root; + expect(path.dirname(namespace)).toBe(privateParent); + expect(path.basename(namespace)).toMatch(/^storybook-[0-9a-f]{64}$/); + expect(stored.application.leasePath).toBe(path.join(namespace, 'application-lease.windows.json')); + expect(fs.existsSync(path.join(path.dirname(manifestPath), '.private'))).toBe(false); + mockWindowsStorage.mockClear(); + mockVerify.mockClear(); + await expect(readDriverManifest(manifestPath, handoff)).resolves.toMatchObject({ + bridgeNonce: 'bridge-only', + application: { leaseNonce: 'attach-only', leasePath: stored.application.leasePath }, + }); + expect(mockWindowsStorage.mock.calls.map(([options]) => options.root)).toEqual([undefined, namespace]); + expect(mockVerify.mock.invocationCallOrder[0]).toBeLessThan(mockWindowsStorage.mock.invocationCallOrder[0]); + + const otherPath = path.join(root, 'other-workspace', 'generated', 'manifest.json'); + await publishDriverManifest(manifest, otherPath); + expect(JSON.parse(fs.readFileSync(otherPath, 'utf8')).credentials.root).not.toBe(namespace); +}); + +test('refuses a tampered Windows namespace before verifying or opening any helper', async () => { + Object.defineProperty(process, 'platform', { value: 'win32' }); + const handoff = await publishDriverManifest(manifest, manifestPath); + const stored = JSON.parse(fs.readFileSync(manifestPath, 'utf8')); + stored.credentials.root = path.join(root, 'editable-location'); + stored.application.leasePath = path.join(stored.credentials.root, 'application-lease.windows.json'); + fs.writeFileSync(manifestPath, JSON.stringify(stored)); + mockWindowsStorage.mockClear(); + mockVerify.mockClear(); + await expect(readDriverManifest(manifestPath, handoff)).rejects.toThrow('trusted parent handoff'); + expect(mockVerify).not.toHaveBeenCalled(); + expect(mockWindowsStorage).not.toHaveBeenCalled(); +}); + +test('requires the namespace selected by the current OS root instead of adopting the manifest root', async () => { + Object.defineProperty(process, 'platform', { value: 'win32' }); + const handoff = await publishDriverManifest(manifest, manifestPath); + privateParent = path.join(root, 'another-os-root'); + mockWindowsStorage.mockClear(); + await expect(readDriverManifest(manifestPath, handoff)).rejects.toThrow('generated instance namespace'); + expect(mockWindowsStorage.mock.calls.map(([options]) => options.root)).toEqual([undefined]); +}); + +test('reports the closed Windows refusal reason without exposing helper details', async () => { + Object.defineProperty(process, 'platform', { value: 'win32' }); + mockWindowsStorage.mockRejectedValue( + Object.defineProperty(new Error('Desktop Driver private storage is unsafe or inaccessible.'), 'reason', { value: 'ancestor' }), + ); + await expect(publishDriverManifest(manifest, manifestPath)).rejects.toThrow('reason: ancestor'); + expect(fs.existsSync(manifestPath)).toBe(false); +}); From ca27c1b0bbe740e5204c8523cb6148c7a737b496 Mon Sep 17 00:00:00 2001 From: Jason Morse Date: Thu, 12 Nov 2026 03:49:11 +0000 Subject: [PATCH 08/11] Record cross-platform storage CI fixes and qualification limits Record default-TMPDIR package results, the locked 178-task aggregate, and the unconfirmed Windows refusal and timeout diagnoses. Keep native Windows qualification explicitly pending. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../agentic/desktop-test/references/current-status.md | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/packages/agentic/desktop-test/references/current-status.md b/packages/agentic/desktop-test/references/current-status.md index 5d08c52436..da43264ed3 100644 --- a/packages/agentic/desktop-test/references/current-status.md +++ b/packages/agentic/desktop-test/references/current-status.md @@ -890,6 +890,14 @@ refusal, protected child calls, and outside-workspace Metro resolution. Evidence: `apps/storybook/artifacts/f6/ci-fix-{driver,integration,runtime}.log`. These simulated-platform results are not Windows ACL qualification. +**CI-fix repository validation:** source `17032203b` passed all 178 +`TF_BUILD=1 yarn lage buildci --concurrency 4` tasks after +`yarn clean-lage-cache`; both commands held the shared native lock and used +the default `TMPDIR`. Links passed all 90 tasks. Repository lint, instruction, +changeset, and whitespace checks passed. Evidence: +`apps/storybook/artifacts/f6/ci-fix-buildci.log` and `ci-fix-links.log`. +The Accessibility-blocked macOS consumer smoke was not repeated. + **Windows/Win32 qualification: pending, not sufficient yet.** Native execution is unavailable on this Mac, and `pwsh` is not installed, so PowerShell parser validation was not run. The first CI run confirms that Win32 Paper smoke From e760a36dec9c168ef9e3dfd875ad28e538d84837 Mon Sep 17 00:00:00 2001 From: Jason Morse Date: Thu, 12 Nov 2026 04:36:23 +0000 Subject: [PATCH 09/11] Keep private Storybook projections out of cross-volume Metro file maps Use a pinned-buffer transformer on the workspace stub for Windows and Win32 while preserving protected per-user storage and macOS resolution. Normalize Windows path identities and cover cross-drive, cache, delegation, and tamper cases. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .changeset/curvy-dragons-fry.md | 2 +- .../desktop-test/references/current-status.md | 54 ++++++++++-- .../storybook-desktop-runtime/AGENTS.md | 4 + .../config/metro.cjs | 31 ++++--- .../config/runtime-transformer.cjs | 60 +++++++++++++ .../storybook-desktop-runtime/package.json | 5 ++ .../references/runtime-contract.md | 17 +++- .../src/metro.test.ts | 88 ++++++++++++++++--- .../config/generated-contract.cjs | 12 +++ .../config/generated-contract.d.cts | 4 + .../references/contributing.md | 9 +- .../src/driver/generatedManifest.ts | 14 +-- .../src/driver/generatedStorage.test.ts | 10 +++ yarn.lock | 1 + 14 files changed, 272 insertions(+), 39 deletions(-) create mode 100644 packages/agentic/storybook-desktop-runtime/config/runtime-transformer.cjs diff --git a/.changeset/curvy-dragons-fry.md b/.changeset/curvy-dragons-fry.md index 2c45edb258..2fdb972cd0 100644 --- a/.changeset/curvy-dragons-fry.md +++ b/.changeset/curvy-dragons-fry.md @@ -5,4 +5,4 @@ Separate Storybook bridge and attachment credentials in owner-private storage, validate versioned generated manifests, and pin native helper provenance through the trusted parent handoff before child processes can spawn helpers. -Use helper-selected per-user namespaces on Windows, retain Metro resolution of private projections outside the workspace, and forward private-storage adapters into platform-neutral CLI contracts. +Use helper-selected per-user namespaces on Windows and forward private-storage adapters into platform-neutral CLI contracts. Resolve protected Windows projections through a digest-keyed Metro transformer on the constant workspace stub, avoiding cross-volume file-map paths and public secret copies. Normalize Windows namespace path identities while preserving macOS behavior. diff --git a/packages/agentic/desktop-test/references/current-status.md b/packages/agentic/desktop-test/references/current-status.md index da43264ed3..052815612f 100644 --- a/packages/agentic/desktop-test/references/current-status.md +++ b/packages/agentic/desktop-test/references/current-status.md @@ -872,15 +872,17 @@ namespace for the canonical generated directory. Reading rederives that namespace only after verifying the parent handoff and helper. No environment path, editable manifest root, relaxed ACL, or root repair chooses authority. Storybook now surfaces the bounded native refusal token. Metro retains its -workspace roots and also watches the pinned private runtime projection -outside the workspace. +workspace roots; this initial fix also watched the private runtime projection, +which the subsequent CI run exposed as incompatible with cross-volume Windows +workspaces. The separate Windows setup job failed four native build/handshake/UIA timeout cases, but its existing Windows private-storage native contracts passed. This branch does not change Windows helper build, resolution, handshake, C++, UIA, or fixture code; setup runs before Storybook publication. Runner flakiness is an inference, not a confirmed explanation. The next -same-branch CI run must establish the result; timeouts were not increased. +same-branch CI run passed setup, supporting that inference; no timeout or +native-helper behavior was changed. **CI-fix portable validation (default `TMPDIR`):** driver format/lint/build/test passed (1,222 tests; 66 skipped); Storybook integration passed (386; 4 skipped); @@ -898,11 +900,51 @@ changeset, and whitespace checks passed. Evidence: `apps/storybook/artifacts/f6/ci-fix-buildci.log` and `ci-fix-links.log`. The Accessibility-blocked macOS consumer smoke was not repeated. +**Second PR CI follow-up:** run `43150784347` on `ca27c1b0b` passed JS PR, +all macOS lanes, Windows/Win32 PR, and Windows native-helper setup. All three +Windows Fabric / Win32 Paper Storybook lanes opened the revised protected +per-user namespace, then failed before smoke during Metro bundling. The +workspace was on `D:` and private projection on `C:`; Metro's relative-path +file map recombined the absolute cross-volume result into `D:\C:\...`. +This confirms the new namespace works on the hosted runner, not that the +consumer flow is qualified. + +The bridge projection contains the bridge nonce, so it remains protected. +Windows/Win32 Metro now indexes only the constant workspace stub and supplies +the pinned private buffer through its supported custom-transformer hook, +delegating compilation/minification to the consumer's original worker. The +worker rechecks the digest, and its cache key binds that digest to avoid +stale nonce transforms. No cross-volume private watch folder or public +generated source copy is created. macOS private-path behavior is unchanged. +Windows namespace/path comparisons normalize drive letters, casing, and +separators without replacing the independent byte-digest trust checks. + +**Cross-volume portable evidence:** controlled fixtures cover a `C:` private +source with a `D:` workspace, case/drive aliases, a wrongly located stub, +unchanged watch roots, digest tampering, nonce cache invalidation, and +unrelated-module delegation. The actual consumer Metro worker/Babel/minifier +also compiled both Windows targets. A bounded full Metro file-map/worker-farm +fixture built minified Windows and Win32 bundles with the private source +explicitly excluded from the file map. These JavaScript checks are not native +Windows qualification. Evidence: +`apps/storybook/artifacts/f6/crossdrive-real-worker.log` and +`crossdrive-real-bundle-final.log`. + +**Cross-volume package validation (default `TMPDIR`):** format/lint/build/test +passed for the driver (1,222 tests; 66 skipped), Storybook integration +(387; 4 skipped), and runtime (37). The final transformer cache-key change +also passed the 11 controlled Metro cases. Knip now explicitly includes the +Metro config/worker entrypoints; repository lint, instruction integrity, +changesets, whitespace, and all 90 link tasks passed. Evidence: +`apps/storybook/artifacts/f6/crossdrive-{desktop-driver,storybook-desktop,storybook-desktop-runtime}.log`, +`crossdrive-final-format.log`, `crossdrive-repo-checks.log`, and +`crossdrive-repo-safeguards.log`. + **Windows/Win32 qualification: pending, not sufficient yet.** Native execution is unavailable on this Mac, and `pwsh` is not installed, so PowerShell parser -validation was not run. The first CI run confirms that Win32 Paper smoke -reaches the changed protected-storage path, but it does not qualify the -revised namespace or Windows Fabric flow. A passing same-branch run must demonstrate +validation was not run. CI confirms both Windows Fabric and Win32 Paper reach +the changed protected-storage path, but bundling has not yet passed on the +revised source. A passing same-branch run must demonstrate version-3 smoke control, trusted helper verification, protected-DACL lease publication/replacement/cleanup, private runtime resolution, and live bridge authentication. Portable negative fixtures do not qualify Windows ACL diff --git a/packages/agentic/storybook-desktop-runtime/AGENTS.md b/packages/agentic/storybook-desktop-runtime/AGENTS.md index 127b38eb42..0fd91b22f6 100644 --- a/packages/agentic/storybook-desktop-runtime/AGENTS.md +++ b/packages/agentic/storybook-desktop-runtime/AGENTS.md @@ -25,6 +25,10 @@ authenticated bridge, Metro, theme, and platform chrome. - Driver-backed Metro uses the parent's canonical generated-schema locator and pinned private bridge-only data module. Never copy attachment credentials into the runtime or trust provenance supplied only by the generated manifest. +- Windows Metro indexes only the workspace stub and reads the pinned private + bridge projection through its digest-keyed transformer. Never add a + cross-volume private-source watch folder or copy its nonce into public + generated source. ## Validation diff --git a/packages/agentic/storybook-desktop-runtime/config/metro.cjs b/packages/agentic/storybook-desktop-runtime/config/metro.cjs index 5829ee0ff8..b189d0d8a8 100644 --- a/packages/agentic/storybook-desktop-runtime/config/metro.cjs +++ b/packages/agentic/storybook-desktop-runtime/config/metro.cjs @@ -29,14 +29,15 @@ function createDesktopStorybookMetroConfig({ configPath }) { throw new TypeError('createDesktopStorybookMetroConfig requires an app-owned Storybook configPath.'); } - const runtimeModulePath = writeRuntimeInstanceModule(path.dirname(configPath)); + const projection = writeRuntimeInstanceModule(path.dirname(configPath)); + const runtimeModulePath = projection.path; const symlinkResolver = MetroSymlinksResolver({ resolver: 'oxc-resolver', }); const config = makeMetroConfig({ resolver: { resolveRequest: (context, moduleName, platform) => { - if (path.resolve(path.dirname(context.originModulePath), moduleName) === runtimeInstanceStub) { + if (path.relative(path.resolve(path.dirname(context.originModulePath), moduleName), runtimeInstanceStub) === '') { return { type: 'sourceFile', filePath: runtimeModulePath }; } // Storybook's path-based lite-mode mock does not recognize Yarn's virtual pnpm paths. @@ -57,15 +58,21 @@ function createDesktopStorybookMetroConfig({ configPath }) { unstable_allowRequireContext: true, }, }); - // Windows credentials live outside the workspace in a protected per-user namespace. Metro must watch the pinned - // projection's directory to hash/import that module, without losing the workspace folders chosen by makeMetroConfig. - config.watchFolders = [...new Set([...(config.watchFolders || []), path.dirname(runtimeModulePath)])]; + if (!projection.windows) { + config.watchFolders = [...new Set([...(config.watchFolders || []), path.dirname(runtimeModulePath)])]; + } const storybookConfig = withStorybook(config, { configPath, liteMode: true, }); - return storybookConfig; + if (!projection.windows) return storybookConfig; + // Keep the bridge nonce private, but never send a cross-volume source path through Metro's file map. + return require('./runtime-transformer.cjs').withPrivateRuntimeProjection(storybookConfig, { + digest: projection.digest, + modulePath: runtimeInstanceStub, + sourcePath: runtimeModulePath, + }); } function writeRuntimeInstanceModule(projectRoot) { @@ -75,13 +82,13 @@ function writeRuntimeInstanceModule(projectRoot) { if (!process.env.STORYBOOK_GENERATED_CONTRACT || !path.isAbsolute(process.env.STORYBOOK_GENERATED_CONTRACT)) { throw new Error('Desktop Storybook Metro requires the trusted parent generated-contract locator.'); } - const { parseDriverManifest, parseHandoff } = require(process.env.STORYBOOK_GENERATED_CONTRACT); + const { parseDriverManifest, parseHandoff, sameGeneratedPath } = require(process.env.STORYBOOK_GENERATED_CONTRACT); const contents = fs.readFileSync(process.env.STORYBOOK_DRIVER_MANIFEST, 'utf8'); const manifest = parseDriverManifest(JSON.parse(contents)); const handoff = parseHandoff(JSON.parse(process.env.STORYBOOK_DRIVER_HANDOFF || 'null')); if ( createHash('sha256').update(contents).digest('hex') !== handoff.manifestDigest || - handoff.runtimeModulePath !== path.join(manifest.credentials.root, manifest.credentials.runtimeModule) + !sameGeneratedPath(handoff.runtimeModulePath, path.join(manifest.credentials.root, manifest.credentials.runtimeModule)) ) { throw new Error('Desktop Storybook manifest does not match the trusted parent handoff.'); } @@ -91,7 +98,11 @@ function writeRuntimeInstanceModule(projectRoot) { ) { throw new Error('Desktop Storybook runtime module does not match the trusted parent handoff.'); } - return handoff.runtimeModulePath; + return { + digest: handoff.runtimeModuleDigest, + path: handoff.runtimeModulePath, + windows: manifest.endpoint === 'windows' || manifest.endpoint === 'win32', + }; } const generatedDirectory = path.join(projectRoot, 'storybook-desktop.generated'); const runtimeModulePath = path.join(generatedDirectory, 'runtime-instance.js'); @@ -108,7 +119,7 @@ function writeRuntimeInstanceModule(projectRoot) { fs.writeFileSync(runtimeModulePath, content); } - return runtimeModulePath; + return { path: runtimeModulePath, windows: false }; } function readPort(value, fallback) { diff --git a/packages/agentic/storybook-desktop-runtime/config/runtime-transformer.cjs b/packages/agentic/storybook-desktop-runtime/config/runtime-transformer.cjs new file mode 100644 index 0000000000..e8a403ce1f --- /dev/null +++ b/packages/agentic/storybook-desktop-runtime/config/runtime-transformer.cjs @@ -0,0 +1,60 @@ +const fs = require('node:fs'); +const path = require('node:path'); +const { createHash } = require('node:crypto'); +const { requireModuleFromMetro } = require('@rnx-kit/tools-react-native/metro'); + +function withPrivateRuntimeProjection(config, projection, paths = path) { + if (config.projectRoot && paths.isAbsolute(paths.relative(config.projectRoot, projection.modulePath))) { + throw new Error('Desktop Storybook runtime stub must be on the Metro project volume.'); + } + const resolveRequest = config.resolver.resolveRequest; + return { + ...config, + resolver: { + ...config.resolver, + resolveRequest: (...args) => { + const resolution = resolveRequest(...args); + if (resolution?.type === 'sourceFile' && paths.relative(resolution.filePath, projection.sourcePath) === '') { + return { type: 'sourceFile', filePath: projection.modulePath }; + } + return resolution; + }, + }, + transformerPath: __filename, + transformer: { + ...config.transformer, + storybookRuntimeProjection: { ...projection, transformerPath: config.transformerPath }, + }, + }; +} + +function getDelegate(config, projectRoot) { + const { storybookRuntimeProjection: projection, ...delegateConfig } = config; + const transformer = requireModuleFromMetro(projection.transformerPath, projectRoot); + return { delegateConfig, projection, transformer }; +} + +function getCacheKey(config, options) { + const { delegateConfig, projection, transformer } = getDelegate(config, options?.projectRoot); + return [ + transformer.getCacheKey?.(delegateConfig, options) || '', + createHash('sha256').update(fs.readFileSync(__filename)).digest('hex'), + projection.modulePath, + projection.digest, + ].join('$'); +} + +function transform(config, projectRoot, filename, data, options) { + const { delegateConfig, projection, transformer } = getDelegate(config, projectRoot); + if (path.relative(path.resolve(projectRoot, filename), projection.modulePath) === '') { + // Only the workspace stub enters Metro's file map. Read the independently pinned private data directly here: + // TreeFS cannot represent a per-user source on C: relative to a workspace on D:. + data = fs.readFileSync(projection.sourcePath); + if (createHash('sha256').update(data).digest('hex') !== projection.digest) { + throw new Error('Desktop Storybook runtime module does not match the trusted parent handoff.'); + } + } + return transformer.transform(delegateConfig, projectRoot, filename, data, options); +} + +module.exports = { getCacheKey, transform, withPrivateRuntimeProjection }; diff --git a/packages/agentic/storybook-desktop-runtime/package.json b/packages/agentic/storybook-desktop-runtime/package.json index 94c7c83b47..75fc260562 100644 --- a/packages/agentic/storybook-desktop-runtime/package.json +++ b/packages/agentic/storybook-desktop-runtime/package.json @@ -48,6 +48,7 @@ "@fluentui-react-native/native-core": "workspace:*", "@rnx-kit/metro-config": "catalog:", "@rnx-kit/metro-resolver-symlinks": "catalog:", + "@rnx-kit/tools-react-native": "catalog:", "@storybook/react-native": "^10.7.1", "@storybook/react-native-theming": "^10.7.1", "@storybook/react-native-ui-common": "^10.7.1", @@ -96,6 +97,10 @@ "furn": { "jestPlatform": "macos", "knip": { + "extraEntries": [ + "config/metro.cjs", + "config/runtime-transformer.cjs" + ], "ignoreDependencies": [ "@fluentui-react-native/native-core" ] diff --git a/packages/agentic/storybook-desktop-runtime/references/runtime-contract.md b/packages/agentic/storybook-desktop-runtime/references/runtime-contract.md index 92c93d880b..27970baf07 100644 --- a/packages/agentic/storybook-desktop-runtime/references/runtime-contract.md +++ b/packages/agentic/storybook-desktop-runtime/references/runtime-contract.md @@ -92,10 +92,19 @@ unknown generated fields and mismatched manifest/module hashes before using the owner's private bridge-only module. It never uses the generated helper path or receives the independent application-attachment nonce. The parent publishes credentials through OS private storage, not default-mode files. -On Windows the projection lives in the helper-selected per-user namespace -outside the workspace. Metro adds that pinned module's directory to its -watch folders without replacing the existing workspace roots; it does not -copy the projection or attachment credentials into public generated output. +On Windows the projection still contains the bridge nonce and remains in the +helper-selected protected per-user namespace. That location can be on `C:` +while the workspace is on `D:`; Metro's file map cannot represent this +cross-volume source. Only the package's constant workspace stub enters that +file map. A custom `transformerPath` delegates to the existing Metro worker, +substituting the independently pinned private data buffer for that stub. +The worker rechecks its digest before compilation, and its cache key includes +the projection digest so a new bridge nonce cannot reuse a stale transform. +Existing transforms, minification, and workspace watch roots are preserved. +No Windows private-source watch folder or public generated credential copy is +created. As before, the bridge nonce becomes application-bundle data, but the +attach credential is never supplied to Metro. macOS retains its existing +private-path resolution and watching behavior. The generated module's only statement is `export default `; the constant runtime loader imports it through Metro's resolver instead of embedding values in executable polyfill source. The old global instance remains a compatibility diff --git a/packages/agentic/storybook-desktop-runtime/src/metro.test.ts b/packages/agentic/storybook-desktop-runtime/src/metro.test.ts index 4b5a841fd3..2df61bd913 100644 --- a/packages/agentic/storybook-desktop-runtime/src/metro.test.ts +++ b/packages/agentic/storybook-desktop-runtime/src/metro.test.ts @@ -6,14 +6,24 @@ import path from 'node:path'; jest.mock('@rnx-kit/metro-config', () => ({ makeMetroConfig: (config: object) => ({ ...config, + projectRoot: require('node:path').resolve(__dirname), serializer: { getPolyfills: () => ['base-polyfill'] }, + transformerPath: 'fixture-transformer', watchFolders: ['existing-workspace'], }), })); jest.mock('@rnx-kit/metro-resolver-symlinks', () => () => jest.fn()); jest.mock('@storybook/react-native/withStorybook', () => ({ withStorybook: (config: unknown) => config })); +const mockTransform = jest.fn(); +jest.mock('@rnx-kit/tools-react-native/metro', () => ({ + requireModuleFromMetro: () => ({ + getCacheKey: () => 'fixture-transformer-key', + transform: (...args: unknown[]) => mockTransform(...args), + }), +})); const { createDesktopStorybookMetroConfig } = require('../config/metro.cjs'); +const { getCacheKey, transform, withPrivateRuntimeProjection } = require('../config/runtime-transformer.cjs'); const hash = (contents: string) => createHash('sha256').update(contents).digest('hex'); const environmentKeys = [ 'STORYBOOK_DRIVER_MANIFEST', @@ -30,6 +40,7 @@ describe('controlled Metro generation fixtures', () => { root = fs.mkdtempSync(path.join(os.tmpdir(), 'storybook-metro-contract-')); originalEnvironment = environmentKeys.map((key) => process.env[key]); for (const key of environmentKeys) delete process.env[key]; + mockTransform.mockReset().mockImplementation((_config, _root, _filename, data: Buffer) => data.toString('utf8')); }); afterEach(() => { environmentKeys.forEach((key, index) => { @@ -39,9 +50,13 @@ describe('controlled Metro generation fixtures', () => { fs.rmSync(root, { force: true, recursive: true }); }); - function controlledManifest(privateRoot = path.join(root, 'storybook-desktop.generated', '.private')) { + function controlledManifest( + privateRoot = path.join(root, 'storybook-desktop.generated', '.private'), + endpoint: 'macos' | 'windows' | 'win32' = 'macos', + bridgeNonce = 'bridge-only', + ) { const runtimeModulePath = path.join(privateRoot, 'runtime-fixture.js'); - const runtimeContents = 'export default {"bridgeNonce":"bridge-only"};\n'; + const runtimeContents = `export default ${JSON.stringify({ bridgeNonce })};\n`; const nativeDriver = { architecture: 'x64', artifactId: 'artifact', @@ -50,32 +65,32 @@ describe('controlled Metro generation fixtures', () => { buildId: 'build-id', compatibilityKey: 'compatibility', configuration: 'release', - endpoints: ['windows', 'win32'], + endpoints: [endpoint], executablePath: path.join(root, 'helper.exe'), features: ['probe'], origin: 'cache', - provider: 'windows', + provider: endpoint === 'macos' ? 'macos' : 'windows', schemaVersion: 1, signing: { mode: 'none' }, sourceDigest: 'source', wireProtocol: { major: 1, minor: 0 }, }; const manifest = { - application: { leasePath: path.join(privateRoot, 'application-lease.windows.json'), windowTitle: 'Fixture' }, + application: { leasePath: path.join(privateRoot, `application-lease.${endpoint}.json`), windowTitle: 'Fixture' }, appName: 'Fixture', credentials: { name: 'credentials-fixture.json', root: privateRoot, runtimeModule: 'runtime-fixture.js' }, displayName: 'Fixture', driverPort: 7010, - endpoint: 'windows', + endpoint, instanceId: 'fixture', metroPort: 8081, nativeDriver, platformManifestDigest: 'platform', portablePlanDigest: 'portable', - renderer: 'fabric', + renderer: endpoint === 'win32' ? 'paper' : 'fabric', schemaVersion: 3, storyManifest: { - endpoint: 'windows', + endpoint, entries: [], platformManifestDigest: 'platform', portablePlanDigest: 'portable', @@ -136,7 +151,7 @@ describe('controlled Metro generation fixtures', () => { expect(fs.existsSync(path.join(root, 'storybook-desktop.generated', 'runtime-instance.js'))).toBe(false); }); - test('watches a pinned projection outside the app workspace while preserving existing workspace roots', () => { + test('keeps macOS private projection resolution and existing workspace watch roots unchanged', () => { const fixture = controlledManifest(path.join(root, 'per-user-state', 'storybook-fixture')); const project = path.join(root, 'workspace', 'app'); const config = createDesktopStorybookMetroConfig({ configPath: path.join(project, 'src') }); @@ -145,12 +160,65 @@ describe('controlled Metro generation fixtures', () => { config.resolver.resolveRequest( { originModulePath: path.join(__dirname, 'createDesktopStorybookApp.tsx') }, '../config/runtime-instance.cjs', - 'windows', + 'macos', ), ).toEqual({ type: 'sourceFile', filePath: fixture.runtimeModulePath }); expect(fs.existsSync(path.join(project, 'storybook-desktop.generated'))).toBe(false); }); + test.each(['windows', 'win32'] as const)( + '%s hashes only the workspace stub and transforms pinned private data without copying it', + (endpoint) => { + const fixture = controlledManifest(path.join(root, 'per-user-state', endpoint), endpoint); + const config = createDesktopStorybookMetroConfig({ configPath: path.join(root, 'src') }); + const resolution = config.resolver.resolveRequest( + { originModulePath: path.join(__dirname, 'createDesktopStorybookApp.tsx') }, + '../config/runtime-instance.cjs', + endpoint, + ); + const stub = path.resolve(__dirname, '../config/runtime-instance.cjs'); + expect(resolution).toEqual({ type: 'sourceFile', filePath: stub }); + expect(config.watchFolders).toEqual(['existing-workspace']); + expect(fs.existsSync(path.join(root, 'storybook-desktop.generated', 'runtime-instance.js'))).toBe(false); + + const filename = path.relative(config.projectRoot, stub); + const options = { platform: endpoint }; + expect(transform(config.transformer, config.projectRoot, filename, fs.readFileSync(stub), options)).toBe(fixture.runtimeContents); + expect(mockTransform.mock.calls[0][0]).not.toHaveProperty('storybookRuntimeProjection'); + expect(mockTransform.mock.calls[0][4]).toBe(options); + const firstKey = getCacheKey(config.transformer, { projectRoot: config.projectRoot }); + controlledManifest(path.dirname(fixture.runtimeModulePath), endpoint, 'next-bridge'); + const next = createDesktopStorybookMetroConfig({ configPath: path.join(root, 'src') }); + expect(getCacheKey(next.transformer, { projectRoot: next.projectRoot })).not.toBe(firstKey); + + fs.writeFileSync(fixture.runtimeModulePath, 'throw new Error("tampered");\n'); + expect(() => transform(config.transformer, config.projectRoot, filename, Buffer.from('stub'), options)).toThrow('trusted parent'); + const untouched = Buffer.from('unrelated-module'); + expect(transform(config.transformer, config.projectRoot, 'unrelated.js', untouched, options)).toBe('unrelated-module'); + expect(mockTransform.mock.calls[1][3]).toBe(untouched); + }, + ); + + test('keeps a C: private source out of a D: file map, including drive-letter and path-case aliases', () => { + const sourcePath = 'C:\\Users\\runneradmin\\private\\runtime.js'; + const modulePath = 'D:\\repo\\packages\\runtime\\runtime-instance.cjs'; + const base = { + projectRoot: 'd:/REPO/apps/storybook', + resolver: { resolveRequest: () => ({ type: 'sourceFile', filePath: 'c:/USERS/runneradmin/PRIVATE/runtime.js' }) }, + transformer: {}, + transformerPath: 'fixture-transformer', + watchFolders: ['D:\\repo'], + }; + const config = withPrivateRuntimeProjection(base, { digest: 'pinned', modulePath, sourcePath }, path.win32); + const resolution = config.resolver.resolveRequest(); + expect(resolution.filePath).toBe(modulePath); + expect(path.win32.isAbsolute(path.win32.relative(base.projectRoot, resolution.filePath))).toBe(false); + expect(config.watchFolders).toBe(base.watchFolders); + expect(() => withPrivateRuntimeProjection(base, { digest: 'pinned', modulePath: sourcePath, sourcePath }, path.win32)).toThrow( + 'project volume', + ); + }); + test.each(['missing-handoff', 'missing-contract', 'unknown-field', 'manifest-tamper', 'runtime-tamper'])( 'fails closed on %s before generating a runtime module', (failure) => { diff --git a/packages/agentic/storybook-desktop/config/generated-contract.cjs b/packages/agentic/storybook-desktop/config/generated-contract.cjs index 67aa5ee13d..4867e0ac56 100644 --- a/packages/agentic/storybook-desktop/config/generated-contract.cjs +++ b/packages/agentic/storybook-desktop/config/generated-contract.cjs @@ -1,4 +1,5 @@ // Shared by the Node integration and Metro through the trusted parent handoff. Keep this contract independent of React. +const path = require('node:path'); const driverManifestVersion = 3; const credentialsVersion = 1; const handoffVersion = 1; @@ -173,11 +174,22 @@ function parseHandoff(value) { return parse(handoff, value, 'helper handoff'); } +function generatedPathIdentity(value, paths = path) { + const normalized = paths.normalize(value); + return paths.sep === '\\' ? normalized.toLowerCase() : normalized; +} + +function sameGeneratedPath(left, right, paths = path) { + return generatedPathIdentity(left, paths) === generatedPathIdentity(right, paths); +} + module.exports = { credentialsVersion, driverManifestVersion, + generatedPathIdentity, handoffVersion, parseCredentials, parseDriverManifest, parseHandoff, + sameGeneratedPath, }; diff --git a/packages/agentic/storybook-desktop/config/generated-contract.d.cts b/packages/agentic/storybook-desktop/config/generated-contract.d.cts index 5d890792f8..9a1009afed 100644 --- a/packages/agentic/storybook-desktop/config/generated-contract.d.cts +++ b/packages/agentic/storybook-desktop/config/generated-contract.d.cts @@ -1,6 +1,10 @@ +import type { PlatformPath } from 'node:path'; + export const credentialsVersion: 1; export const driverManifestVersion: 3; export const handoffVersion: 1; export function parseCredentials(value: unknown): unknown; export function parseDriverManifest(value: unknown): unknown; export function parseHandoff(value: unknown): unknown; +export function generatedPathIdentity(value: string, paths?: PlatformPath): string; +export function sameGeneratedPath(left: string, right: string, paths?: PlatformPath): boolean; diff --git a/packages/agentic/storybook-desktop/references/contributing.md b/packages/agentic/storybook-desktop/references/contributing.md index e2e1318f6b..0543677c64 100644 --- a/packages/agentic/storybook-desktop/references/contributing.md +++ b/packages/agentic/storybook-desktop/references/contributing.md @@ -65,8 +65,13 @@ Metro receives the canonical schema locator through the parent's against the handoff, and never reconstructs credentials from public JSON. The locator is trusted process configuration, not a manifest-controlled path. This keeps the integration CLI peer-free; the runtime remains app-owned. -Metro explicitly watches the pinned module directory while retaining its -workspace watch roots, so the per-user Windows projection remains resolvable. +Windows Metro indexes the constant workspace stub and reads the pinned private +projection through a digest-keyed transformer, rather than a cross-volume +watch folder. The bridge nonce is still private source data; it is not copied +into public generated output. macOS keeps its existing private-module path. +Windows namespace identities and path comparisons normalize drive letters, +separators, and casing; manifest and credential byte digests remain the +independent trust binding. The command factory must forward `createPrivateStorage` as well as native helper adapters. Portable CLI tests inject storage instead of accidentally depending on their host; production credential publication remains unsupported diff --git a/packages/agentic/storybook-desktop/src/driver/generatedManifest.ts b/packages/agentic/storybook-desktop/src/driver/generatedManifest.ts index 0169e0b9ed..8804ce6f98 100644 --- a/packages/agentic/storybook-desktop/src/driver/generatedManifest.ts +++ b/packages/agentic/storybook-desktop/src/driver/generatedManifest.ts @@ -9,10 +9,12 @@ import type { NativeDriverArtifact } from '@fluentui-react-native/desktop-driver import { validateDesktopCaseOptions, validateDesktopStoryTests } from '@fluentui-react-native/desktop-driver/authoring'; import { credentialsVersion, + generatedPathIdentity, handoffVersion, parseCredentials, parseDriverManifest, parseHandoff, + sameGeneratedPath, } from '../../config/generated-contract.cjs'; import type { DesktopStorybookDriverManifest } from './driverManifest.js'; @@ -63,7 +65,7 @@ async function privateStorageRoot(directory: string, artifact: NativeDriverArtif // Workspace ancestors can grant other users write/delete access. Let the verified helper choose its known-folder // root, not an environment variable, then create an independently protected namespace for this generated directory. const parent = await openWindowsPrivateStorage({ artifact }); - return path.join(parent.root, `storybook-${driverManifestDigest(directory)}`); + return path.join(parent.root, `storybook-${driverManifestDigest(generatedPathIdentity(directory))}`); } export function parseStoredDriverManifest(value: unknown): StoredDriverManifest { @@ -149,7 +151,7 @@ export async function publishDriverManifest( await storage.remove(runtimeModule, runtimeContents); throw error; } - if (previous?.credentials.root === root) { + if (previous && sameGeneratedPath(previous.credentials.root, root)) { for (const recordName of [previous.credentials.name, previous.credentials.runtimeModule]) { const previousContents = await storage.read(recordName); if (previousContents !== undefined) await storage.remove(recordName, previousContents); @@ -180,8 +182,8 @@ export async function readDriverManifest( const contents = fs.readFileSync(manifestPath, 'utf8'); const stored = parseStoredDriverManifest(JSON.parse(contents)); if ( - (!usesWindowsPrivateStorage(createStorage) && stored.credentials.root !== path.join(directory, '.private')) || - stored.application.leasePath !== path.join(stored.credentials.root, `application-lease.${stored.endpoint}.json`) + (!usesWindowsPrivateStorage(createStorage) && !sameGeneratedPath(stored.credentials.root, path.join(directory, '.private'))) || + !sameGeneratedPath(stored.application.leasePath, path.join(stored.credentials.root, `application-lease.${stored.endpoint}.json`)) ) { throw new Error('Desktop Storybook private state must use the generated instance namespace.'); } @@ -192,7 +194,7 @@ export async function readDriverManifest( if ( trusted.manifestDigest !== driverManifestDigest(contents) || JSON.stringify(trusted.nativeDriver) !== JSON.stringify(stored.nativeDriver) || - trusted.runtimeModulePath !== path.join(stored.credentials.root, stored.credentials.runtimeModule) + !sameGeneratedPath(trusted.runtimeModulePath, path.join(stored.credentials.root, stored.credentials.runtimeModule)) ) { throw new Error('Desktop Storybook manifest does not match the trusted parent handoff.'); } @@ -204,7 +206,7 @@ export async function readDriverManifest( // Resolving the Windows per-user namespace itself launches a helper. Do it only after the parent binding and // executable verification above; an editable manifest must never authorize even this one-shot helper. const root = await privateStorageRoot(directory, artifact, createStorage); - if (stored.credentials.root !== root) { + if (!sameGeneratedPath(stored.credentials.root, root)) { throw new Error('Desktop Storybook private state must use the generated instance namespace.'); } const storage = await createStorage(root, artifact); diff --git a/packages/agentic/storybook-desktop/src/driver/generatedStorage.test.ts b/packages/agentic/storybook-desktop/src/driver/generatedStorage.test.ts index de1732405a..6728f84f56 100644 --- a/packages/agentic/storybook-desktop/src/driver/generatedStorage.test.ts +++ b/packages/agentic/storybook-desktop/src/driver/generatedStorage.test.ts @@ -3,6 +3,7 @@ import os from 'node:os'; import path from 'node:path'; import type { NativeDriverArtifact } from '@fluentui-react-native/desktop-driver'; +import { generatedPathIdentity, sameGeneratedPath } from '../../config/generated-contract.cjs'; import { createFixturePrivateStorage } from './fixtures/privateStorage'; import { createFixtureStoredManifest } from './fixtures/storedManifest.cjs'; import type { DesktopStorybookDriverManifest } from './driverManifest'; @@ -121,3 +122,12 @@ test('reports the closed Windows refusal reason without exposing helper details' await expect(publishDriverManifest(manifest, manifestPath)).rejects.toThrow('reason: ancestor'); expect(fs.existsSync(manifestPath)).toBe(false); }); + +test('pins Windows project identity across drive-letter, separator, and casing aliases without accepting another volume', () => { + const generated = 'D:\\agent\\Project\\generated'; + const alias = 'd:/AGENT/project/generated'; + expect(sameGeneratedPath(generated, alias, path.win32)).toBe(true); + expect(generatedPathIdentity(generated, path.win32)).toBe(generatedPathIdentity(alias, path.win32)); + expect(sameGeneratedPath(generated, 'C:\\agent\\Project\\generated', path.win32)).toBe(false); + expect(sameGeneratedPath('/Project/generated', '/project/generated', path.posix)).toBe(false); +}); diff --git a/yarn.lock b/yarn.lock index 5cf79395c0..6be5d02e4a 100644 --- a/yarn.lock +++ b/yarn.lock @@ -4948,6 +4948,7 @@ __metadata: "@react-native/babel-preset": "npm:^0.81.0" "@rnx-kit/metro-config": "catalog:" "@rnx-kit/metro-resolver-symlinks": "catalog:" + "@rnx-kit/tools-react-native": "catalog:" "@storybook/react-native": "npm:^10.7.1" "@storybook/react-native-theming": "npm:^10.7.1" "@storybook/react-native-ui-common": "npm:^10.7.1" From 58ec7ab4fb7ce6e449d0e351ecb02352bf88f319 Mon Sep 17 00:00:00 2001 From: Jason Morse Date: Thu, 12 Nov 2026 04:39:35 +0000 Subject: [PATCH 10/11] Record cross-volume Metro qualification and pending Windows lanes Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- packages/agentic/desktop-test/references/current-status.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/packages/agentic/desktop-test/references/current-status.md b/packages/agentic/desktop-test/references/current-status.md index 052815612f..c372fc664c 100644 --- a/packages/agentic/desktop-test/references/current-status.md +++ b/packages/agentic/desktop-test/references/current-status.md @@ -940,6 +940,12 @@ changesets, whitespace, and all 90 link tasks passed. Evidence: `crossdrive-final-format.log`, `crossdrive-repo-checks.log`, and `crossdrive-repo-safeguards.log`. +**Cross-volume repository validation:** source `e760a36de` passed all 178 +`TF_BUILD=1 yarn lage buildci --concurrency 4` tasks after +`yarn clean-lage-cache`. Both commands held the shared native lock and used +the default `TMPDIR`; no native smoke or privacy-setting change was repeated. +Evidence: `apps/storybook/artifacts/f6/crossdrive-buildci.log`. + **Windows/Win32 qualification: pending, not sufficient yet.** Native execution is unavailable on this Mac, and `pwsh` is not installed, so PowerShell parser validation was not run. CI confirms both Windows Fabric and Win32 Paper reach From aadc2f3591d15f5d43496d7f069fa8d0d32d5384 Mon Sep 17 00:00:00 2001 From: Jason Morse Date: Thu, 12 Nov 2026 05:18:54 +0000 Subject: [PATCH 11/11] Record same-branch Windows Storybook trust qualification Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../desktop-test/references/current-status.md | 91 +++++++++++++++++-- 1 file changed, 81 insertions(+), 10 deletions(-) diff --git a/packages/agentic/desktop-test/references/current-status.md b/packages/agentic/desktop-test/references/current-status.md index c372fc664c..2b58da4e1a 100644 --- a/packages/agentic/desktop-test/references/current-status.md +++ b/packages/agentic/desktop-test/references/current-status.md @@ -68,7 +68,7 @@ did not retain a portable raw-report locator; do not imply otherwise. | --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | macOS | Live failed-cleanup and service-restart cases; Paper separately; supervisor death with Metro/channel/helper survivors; exact attached-app preservation. | | Windows / Win32 | Same-branch MCP restart/revocation/dispose/args tests; physical console Ctrl+C requalification of `serve --agent` after the idle-CLI fix; interactive input/capture rerun; naming launched (especially uncontained packaged) apps in the claim. | -| Storybook | Authenticated mutation ingress, context fencing/reconnect, consistent helper build policy. F6 now implements strict generated provenance and independent nonces; see the F6 evidence below for qualification limits. | +| Storybook | Authenticated mutation ingress, context fencing/reconnect, consistent helper build policy. F6 strict provenance and independent nonces are qualified by same-branch Windows Fabric and both Win32 Paper lanes in run 43156299266; see the F6 evidence below for scope and limits. | | Recovery | Durable uncertainty is wired in both paths; live restart qualification, ledger and exact-resource reconciliation still precede automatic reclaim. The workload claim records a Node.js-clock start time, so it needs a helper-described start time before claim inspection can prove a live owner or a reused PID. | | Concurrency | No physical-input suites in parallel on one interactive desktop. Separate machines may qualify independent endpoints. | | Reliability | Establish the required repeated-run window rather than interpreting aggregate past successes as a pass. | @@ -946,12 +946,83 @@ changesets, whitespace, and all 90 link tasks passed. Evidence: the default `TMPDIR`; no native smoke or privacy-setting change was repeated. Evidence: `apps/storybook/artifacts/f6/crossdrive-buildci.log`. -**Windows/Win32 qualification: pending, not sufficient yet.** Native execution -is unavailable on this Mac, and `pwsh` is not installed, so PowerShell parser -validation was not run. CI confirms both Windows Fabric and Win32 Paper reach -the changed protected-storage path, but bundling has not yet passed on the -revised source. A passing same-branch run must demonstrate -version-3 smoke control, trusted helper verification, protected-DACL lease -publication/replacement/cleanup, private runtime resolution, and live bridge -authentication. Portable negative fixtures do not qualify Windows ACL -behavior. Keep the PR draft until that coverage is observed. +**Windows/Win32 qualification: sufficient for F6's changed paths.** +[Run 43156299266](https://github.com/microsoft/fluentui-react-native/actions/runs/43156299266) +passed on source `58ec7ab4fb7ce6e449d0e351ecb02352bf88f319` on +2026-11-12. Full job logs and the uploaded terminal `run.json` reports agree: + +| Lane / job | Full story index rendered | Authored tests | Aggregate | +| ---------------------------------------------------------------------------------------------------------------------------------------- | ------------------------- | ------------------------------------- | ---------------------------------------------------- | +| Windows Fabric accessible / [130976919836](https://github.com/microsoft/fluentui-react-native/actions/runs/43156299266/job/130976919836) | 215/215 | 40/40 passed | 255 selected, executed, and passed | +| Win32 Paper accessible / [130976919943](https://github.com/microsoft/fluentui-react-native/actions/runs/43156299266/job/130976919943) | 188/188 | 45/45 passed | 233 selected, executed, and passed | +| Win32 Paper physical / [130976920038](https://github.com/microsoft/fluentui-react-native/actions/runs/43156299266/job/130976920038) | 188/188 | 100 passed; 1 quarantined unsupported | 289 selected; 288 executed and passed; 1 unsupported | + +All three reports have zero failed, skipped, incomplete, retried, or flaky +tests and zero groups not run. Each navigation result has a distinct story +ID and passed; the render totals match the complete runtime index, not an +early-stop subset. The physical lane's existing #4373 quarantine is not a +pass or an F6 failure. + +The five required paths are exercised in **each** lane. The successful +guarded execution establishes the mandatory checks below; these checks do +not emit separate success messages or upload secret records: + +1. **Version-3 control:** + `packages/agentic/storybook-desktop/config/storybook-control.cjs` uses the strict shared + generated-contract parser before driver traversal and authored tests. + The rendered-story and authored-test results above therefore cross the + v3 gate in all three lanes. +2. **Trusted helper verification:** each log records native Storybook/WebDriver + readiness before traversal. The channel child's + `packages/agentic/storybook-desktop/config/server.cjs` + requires the inherited parent handoff and awaits `readDriverManifest`, + which checks its independent byte/helper binding and calls + `verifyNativeDriverArtifact` before opening Windows private storage or + starting the native service. Readiness plus completed native traversal + demonstrates this guarded spawn path, not merely parent-side resolution. +3. **Protected-DACL lease lifecycle:** both PowerShell scripts require a + successful trusted Node publication and digest receipt before control, + and propagate lease-helper cleanup failures. Successful script completion + exercises publication, native consumption, and receipt-checked cleanup in + all lanes. Windows Fabric additionally stops/relaunches the app between + its stories/tests phases and replaces the lease using the prior receipt; + the Win32 lanes use one app incarnation. The Windows job also passed the + real NTFS `privateStorage.contract.test.ts` (log line 436), including + exclusive publication/removal and refusal of permissive root/record ACLs, + junctions, hard links, and replaced roots. This is native boundary + evidence, not portable mock coverage or an independent post-run ACL dump. +4. **Private runtime resolution:** all three logs finish writing the minified + Windows/Win32 bundle before native startup. On these hosted runners the + workspace is on `D:` and the protected per-user projection is on `C:`. + The Windows runtime transformer must read and hash-check that private + buffer before delegating the workspace stub to Metro's original worker; + the subsequent authenticated render confirms the resulting bundle works. +5. **Live bridge authentication:** successful native story selections require + `StorybookChannelOrchestrator.acceptHello` to match the nonce, instance, + endpoint, target, manifest digest, and connection epoch, followed by + correlated render-ready responses. The 215/188/188 successful selections + prove live authenticated runtime traffic, not just a listening server. + +**Evidence locators:** the Windows full log records bundle completion at +line 655, native readiness at 669-670, all stories at 709, authored tests at +1230, and terminal totals at 2295. Win32 accessible uses lines 502, +508-511, 1097, and 1118; Win32 physical uses 499, 505-508, 1809, and 1845. +The three artifacts are `Storybook_windows_fabric_43156299266_1` +(13916946307), `Storybook_win32_paper_accessible_43156299266_1` +(13917010025), and `Storybook_win32_paper_physical_43156299266_1` +(13916318019). Their main smoke reports under `apps/storybook/artifacts/desktop` +are respectively `414aa6f1-a539-4d67-9aa4-a92db05b58a4/run.json`, +`00cae5a0-ef44-45cf-aaa9-68485ecf2403/run.json`, and +`e5767c29-e4b1-4a9b-9685-8cdf8e0d3ee1/run.json`. Full logs, inventory, +and extracted reports are retained locally under ignored +`apps/storybook/artifacts/f6/ci-43156299266/`. + +**Limits:** collected channel stderr includes non-terminal +`bridge-unavailable` navigation diagnostics on Windows and an authenticated +epoch `lease-invalid` diagnostic on Win32 physical. Do not infer their +original timing from the buffered output, diagnostic-free operation, or +general bridge-recovery qualification from the terminal passes. The local +macOS Accessibility block above remains unchanged; no local smoke was +repeated. `pwsh` is unavailable locally, so its parser check remains not run; +the actual scripts executed in these CI lanes. Keep the PR draft until the +documentation follow-up's CI passes and the coordinator changes its status.