diff --git a/.github/workflows/studio.yml b/.github/workflows/studio.yml index c08dc88c..2d2086a4 100644 --- a/.github/workflows/studio.yml +++ b/.github/workflows/studio.yml @@ -219,7 +219,6 @@ jobs: run node tools/durable_chat_queue_browser.mjs run node tools/canonical_version_history_browser.mjs run node tools/rules_source_browser.mjs - run node tools/hosted_source_permission_browser.mjs run node tools/exact_representation_browser.mjs run node tools/covers_browser.mjs exit "$status" diff --git a/CONFORMANCE.md b/CONFORMANCE.md index a9ef6f65..307ac008 100644 --- a/CONFORMANCE.md +++ b/CONFORMANCE.md @@ -314,12 +314,6 @@ model does not sanction. | --- | --- | --- | | `FA-03` | `build` | The browser host refuses unsupported channels and invalid contracted responses with typed errors | -## hosted-source-permission - -| ID | Level | Statement | -| --- | --- | --- | -| `FA-83` | `build` | Stateful preview parsing and checking transmit source only under disclosed source-bound or turn-scoped revocable hosted permission | - ## in-tab-kernel-verdict | ID | Level | Statement | diff --git a/app/product.json b/app/product.json index 255445a8..ce5b8a0c 100644 --- a/app/product.json +++ b/app/product.json @@ -765,22 +765,20 @@ }, { "name": "Versions and preview", - "text": "Version history keeps content identity; a preview restores exact source, starts only as allowed and sends source only under permission.", + "text": "Version history keeps content identity; a preview restores exact source, starts only as allowed and sends no source anywhere.", "ids": [ "FA-39", "FA-52", "FA-53", "FA-54", "FA-55", - "FA-82", - "FA-83" + "FA-82" ], "calls": [ "VersionPreview::transitionPreview", "VersionPreviewProtocol::dispatchPreview", "FoundrySpecification::previewPermissionBoundary", - "FoundrySpecification::previewAutoStartBoundary", - "FoundrySpecification::hostedSourcePermissionBoundary" + "FoundrySpecification::previewAutoStartBoundary" ], "registry": [ "version-history", diff --git a/app/src/Features.lex.tex b/app/src/Features.lex.tex index 826beb28..da38cec4 100644 --- a/app/src/Features.lex.tex +++ b/app/src/Features.lex.tex @@ -1177,13 +1177,6 @@ body: "crates/conformance/tests/preview_auto_start.rs::preview_auto_start_fa_82" } -definition{ - name: testFA83, - parameters: [], - result: String, - body: "crates/conformance/tests/hosted_source_permission.rs::hosted_source_permission_fa_83" -} - definition{ name: acceptInteractionModelInteractionSilentWithoutConsent, parameters: [], @@ -1615,7 +1608,7 @@ name: featureVersionsAndPreview, parameters: [], result: Foundation.Arch::Feature, - body: (record Foundation.Arch::Feature {statement := "Versions and preview (FA-39, FA-52, FA-53, FA-54, FA-55, FA-82, FA-83): Version history keeps content identity; a preview restores exact source, starts only as allowed and sends source only under permission.", calls := (cons "VersionPreview::transitionPreview" (cons "VersionPreviewProtocol::dispatchPreview" (cons "FoundrySpecification::previewPermissionBoundary" (cons "FoundrySpecification::previewAutoStartBoundary" (cons "FoundrySpecification::hostedSourcePermissionBoundary" (cons "FoundrySpecification::versionHistoryBoundary" (cons "VersionPreview::boundary" (cons "FoundrySpecification::durableVersionPreviewBoundary" (cons "FoundrySpecification::messageRestorationBoundary" (nil String)))))))))), acceptance := (cons "Features::acceptVersionPreviewPreviewSelect" (cons "Features::acceptVersionPreviewPreviewStaleRevision" (cons "Features::acceptVersionPreviewProtocolPreviewWireSelect" (cons "Features::testFA39" (cons "Features::testFA52" (cons "Features::testFA53" (cons "Features::testFA54" (cons "Features::testFA55" (cons "Features::testFA82" (cons "Features::testFA83" (nil String)))))))))))}) + body: (record Foundation.Arch::Feature {statement := "Versions and preview (FA-39, FA-52, FA-53, FA-54, FA-55, FA-82): Version history keeps content identity; a preview restores exact source, starts only as allowed and sends no source anywhere.", calls := (cons "VersionPreview::transitionPreview" (cons "VersionPreviewProtocol::dispatchPreview" (cons "FoundrySpecification::previewPermissionBoundary" (cons "FoundrySpecification::previewAutoStartBoundary" (cons "FoundrySpecification::versionHistoryBoundary" (cons "VersionPreview::boundary" (cons "FoundrySpecification::durableVersionPreviewBoundary" (cons "FoundrySpecification::messageRestorationBoundary" (nil String))))))))), acceptance := (cons "Features::acceptVersionPreviewPreviewSelect" (cons "Features::acceptVersionPreviewPreviewStaleRevision" (cons "Features::acceptVersionPreviewProtocolPreviewWireSelect" (cons "Features::testFA39" (cons "Features::testFA52" (cons "Features::testFA53" (cons "Features::testFA54" (cons "Features::testFA55" (cons "Features::testFA82" (nil String))))))))))}) } definition{ diff --git a/app/src/FoundrySpecification.lex.tex b/app/src/FoundrySpecification.lex.tex index 6de85de3..f0f9551d 100644 --- a/app/src/FoundrySpecification.lex.tex +++ b/app/src/FoundrySpecification.lex.tex @@ -1288,30 +1288,5 @@ result: String, body: "The browser preview panel automatically starts only the selected application's initial idle run snapshot: matching positive safe app identity, idle phase, no operation, no start timestamp and no settlement. Missing or foreign identity and starting, ready, reloading, stopped or errored snapshots never authorize another automatic start. The imported app-run manager remains the run-state owner; the renderer uses its current snapshot and re-evaluates after hydration. Unchanged automatic eligibility does not retrigger the selection effect merely because the snapshot object changes. Responsive remounts, tab return and settings updates do not retry a declined preview or supersede an active run. Explicit existing start/restart controls remain available under the imported capabilities and still require ordinary preview authorization. Full document reload starts a fresh document-owned run session and may request permission again; this is not persisted denial or cross-window permission synchronization. Source model, permission grants and queue state are unchanged. A declined preview does not block Ask submission or cloud consent, and responsive layout must not open a fresh permission prompt after decline." } - -inductive{ - name: HostedSourcePermissionError, - type_parameters: [], - parameters: [], - constructors: [ - {name: invalidHostedSourcePermission, fields: []}, - {name: hostedSourcePermissionDenied, fields: []}, - {name: hostedSourcePermissionCancelled, fields: []}, - {name: hostedSourcePermissionExpired, fields: []}, - {name: hostedSourcePermissionOffline, fields: []}, - {name: hostedSourcePermissionUnavailable, fields: []}, - {name: hostedSourceChanged, fields: []}, - {name: hostedSourceNetworkFailed, fields: []}, - {name: hostedSourceMalformedResponse, fields: []}, - {name: hostedSourceServiceRefused, fields: []} - ] -} - -definition{ - name: hostedSourcePermissionBoundary, - parameters: [], - result: String, - body: "Stateful app parsing and checking require explicit browser approval before source leaves for https://mcp.uor.foundation/. A standalone operation discloses its immutable exact files. A streaming generation session discloses its application, unique turn, captured source identity, current exact files, and permission for subsequent generated module prefixes, repairs and supporting LexLean library modules in that same turn. This preserves incremental previews without treating inference or network-free frame permission as hosted-source consent. It does not permit another turn, application, destination, proof, publication or arbitrary network operation. Approval remains only in document memory, is unavailable offline, and expires within five minutes including active work. The host asserts current source and turn ownership before each request and after completion; only its own successful compare-and-swap commit may advance its expected local source. Denial, Escape, stop, generation cancellation and expiry are typed private refusals. A session remembers refusal without repeatedly prompting. A modal focuses denial and renders source as text; its active stop control explains that abort cannot recall transmitted data or stop remote work. Each parse/check operation further binds its exact file set and permits only one draft write plus matching draft checks or data reads. Requests omit cookies and credentials, reject redirects, use a bounded cancellation-aware deadline, and validate private fixed response failures. Malformed or refused service responses do not become checks or proofs. Replaced, forgotten or cancelled preview work cannot publish late frames. Preview attempts are identified by requested source and permission scope together: a refused attempt suppresses repeat prompts only in that scope, while a fresh scope may retry identical source. Reselecting a previously rendered module cancels and supersedes pending different-source work before reusing its frame, so stale content cannot acquire the selected module's trust. Incomplete replacement source also supersedes pending work without relabeling the last rendered frame. This is a hosted parsing/checking permission boundary, not proof verification, retention enforcement, same-origin caller authentication or overall release acceptance." -} \end{semanticmodule} \end{lexlean} diff --git a/crates/conformance/tests/hosted_source_permission.rs b/crates/conformance/tests/hosted_source_permission.rs deleted file mode 100644 index 16699ae4..00000000 --- a/crates/conformance/tests/hosted_source_permission.rs +++ /dev/null @@ -1,36 +0,0 @@ -//! Execute the hosted source permission boundary and every negative control. -use std::path::PathBuf; -use std::process::Command; - -#[test] -fn hosted_source_permission_fa_83() { - let root = PathBuf::from(env!("CARGO_MANIFEST_DIR")) - .ancestors() - .nth(2) - .expect("repository root") - .to_path_buf(); - let output = Command::new("node") - .args(["--test", "--test-reporter=tap"]) - .arg(root.join("studio/tools/hosted_source_permission.test.mjs")) - .output() - .expect("the locked SDK supplies Node"); - let report = String::from_utf8_lossy(&output.stdout); - assert!( - output.status.success(), - "{report}\n{}", - String::from_utf8_lossy(&output.stderr) - ); - for required in [ - "# tests 12", - "# pass 12", - "# fail 0", - "# cancelled 0", - "# skipped 0", - "# todo 0", - ] { - assert!( - report.lines().any(|line| line == required), - "incomplete oracle: {report}" - ); - } -} diff --git a/features/suites/hosted-source-permission.feature b/features/suites/hosted-source-permission.feature deleted file mode 100644 index 1890cf43..00000000 --- a/features/suites/hosted-source-permission.feature +++ /dev/null @@ -1,21 +0,0 @@ -Feature: Hosted source permission - @FA-83 @build - Scenario: Stateful streaming remains local until its hosted source disclosure is accepted - Given a captured application and generation turn without hosted permission - When runnable module prefixes or final checks are produced - Then no source is sent until the owner accepts the destination and this-turn source scope - And denial or cancellation sends no request and does not authorize a later turn - - @FA-83 @build - Scenario: Permission cannot authorize stale or unrelated source effects - Given an approved source or generation turn - When its owner changes or permission expires or is revoked - Then subsequent hosted requests are refused and late preview results are discarded - And redirects credentials malformed responses and undisclosed RPC effects are refused - - @FA-83 @build - Scenario: A fresh permission scope can retry the same source without accepting stale frames - Given a refused preview attempt and a new turn with identical module bytes - When the new turn explicitly approves its own hosted scope - Then parsing retries under the new scope and the current frame is rendered - And reselecting an existing frame cancels any different in-flight source before updating its trust diff --git a/model/ids.toml b/model/ids.toml index 638daeff..b6939872 100644 --- a/model/ids.toml +++ b/model/ids.toml @@ -820,12 +820,6 @@ level = "build" suite = "preview-auto-start" statement = "Automatic preview startup respects existing app state so remounts cannot repeat declined execution while explicit retry remains available" -[[id]] -id = "FA-83" -level = "build" -suite = "hosted-source-permission" -statement = "Stateful preview parsing and checking transmit source only under disclosed source-bound or turn-scoped revocable hosted permission" - [[id]] id = "FA-84" level = "build" diff --git a/studio/VERIFICATION.md b/studio/VERIFICATION.md index 4707ec2c..ec653b0f 100644 --- a/studio/VERIFICATION.md +++ b/studio/VERIFICATION.md @@ -21,9 +21,9 @@ Every claim carries its honesty level: `some-true` (from a source, not establish | Journey | a spec checker, model renderer or Foundation module in `shell/prism/` that is not prism-code 0.7.2's, byte for byte (`tools/prism_journey.mjs --check` in CI), so a spec means in the tab what it means to `npx prism-code` | build | armed 2026-11-10 by its first run: the four files were written from the package and the check passed; Forge's proof of the parking-fee spec through them returned attestation `4a4d1629…`, the one `prism_prove` returned for the same spec | | Engine | a copy of the interpreter, the presentation reader, the library model or the model's instructions under `shell/live/v2/` that differs from its source under `v2/` (`tools/v2_engine.mjs --check`), so a stateful app runs in the preview on the engine that is tested and held to compiled guests there | build | armed 2026-11-12: one comment line appended to `shell/live/v2/interp.mjs`; the check named the file and failed; restored, green | | App | a stateful app's module that is not told from a decision, not split at its whole declarations, drawn before it is runnable, or whose press from an out-of-date frame is acted on (`node --test tools/live_app.test.mjs`, 8 claims on a module an independent model wrote; a ninth asks the hosted service when `LIVE_APP_HOSTED=1`). A frame from here is a draft: nothing in this row says the module is checked or proved | build | armed 2026-11-12: `appLive.intent` made to act on any revision; the stale-press claim failed; restored, green. In the real Forge over the deployed site (`tools/overlay_serve.mjs`): the module streamed into the preview, typed and pressed, saved at the end of the turn, and run again after a reload | -| Approvals | an approval dialog opened over another's, so that the one beneath cannot be answered and expires (`node --test tools/approval_queue.test.mjs`, 5 claims: a question asked alone is shown in the same task; a second and a third are not shown until the one before is answered, whether approved or refused; one that cannot be shown does not hold the rest; each of `authorizeInference`, `authorizePreview` and `authorizeHostedSource` opens its dialog only through the queue; the chat counts lines for an app in the notation) | build | armed 2026-11-12: `oneAtATime` made to show every question at once; the ordering claim failed (`preview`, `request`, `source` all shown); restored, green. Found on the deployed site the same day: the preview's permission dialog covered the cloud request's Send button and the request expired twice. Not shown: the three real dialogs queued in a browser; their own browser gates run in CI, not here | +| Approvals | an approval dialog opened over another's, so that the one beneath cannot be answered and expires (`node --test tools/approval_queue.test.mjs`, 5 claims: a question asked alone is shown in the same task; a second and a third are not shown until the one before is answered, whether approved or refused; one that cannot be shown does not hold the rest; each of `authorizeInference` and `authorizePreview` opens its dialog only through the queue; the chat counts lines for an app in the notation) | build | armed 2026-11-12: `oneAtATime` made to show every question at once; the ordering claim failed (`preview`, `request`, `source` all shown); restored, green. Found on the deployed site the same day: the preview's permission dialog covered the cloud request's Send button and the request expired twice. Not shown: the three real dialogs queued in a browser; their own browser gates run in CI, not here | | Notation | app-notation lines that expand to another module than the one that was checked and proved (each fixture's module is held to its SHA-256), a module without a theorem for every promise, a label or a limit the lines state and the module does not hold, lines that do not read accepted, or a chat turn in the notation that is not its module to the preview, the store and the check (`node --test tools/live_notation.test.mjs`, 7 claims; an eighth, with `LIVE_APP_HOSTED=1`, has the hosted checker accept all seven modules and runs each: a row is added, an empty one refused, the seventeenth refused, a clear empties) | build | armed 2026-11-12: the row limit's ` button) { display: flex !important; justify-content: flex-end !important; gap: 8px !important; margin: 0 !important; } -/* A request that is open: one quiet pill, low and to the right, clear of the phone's tab bar. */ -aside[aria-label^="Active"] { - inset: auto 21px max(21px, env(safe-area-inset-bottom)) auto !important; padding: 5px !important; border-radius: 13px !important; - background: color-mix(in srgb, var(--popover) 88%, transparent) !important; color: var(--popover-foreground) !important; - -webkit-backdrop-filter: blur(28px) saturate(1.6); backdrop-filter: blur(28px) saturate(1.6); - border: 1px solid color-mix(in srgb, var(--popover-foreground) 12%, transparent) !important; - box-shadow: 0 13px 34px -13px color-mix(in srgb, var(--popover) 85%, transparent) !important; font: inherit !important; -} -aside[aria-label^="Active"] button { margin: 0 !important; border-color: transparent !important; min-height: 34px; gap: 8px; } -aside[aria-label^="Active"] button::before { content: ""; width: 8px; height: 8px; border-radius: 2px; background: var(--brand); } -@media (max-width: 767px) { aside[aria-label^="Active"] { inset: auto 21px calc(76px + env(safe-area-inset-bottom)) auto !important; } } -@media (pointer: coarse) { dialog:not([data-slot]) button, aside[aria-label^="Active"] button { min-height: 44px; } } +@media (pointer: coarse) { dialog:not([data-slot]) button { min-height: 44px; } } @media (prefers-reduced-motion: reduce) { dialog:not([data-slot])[open] { animation: none; } } /* Foundry's tools are on the Settings page, as its last card: a title, then one quiet control each, with its diff --git a/studio/shell/hosted-source-permission.mjs b/studio/shell/hosted-source-permission.mjs deleted file mode 100644 index 96684546..00000000 --- a/studio/shell/hosted-source-permission.mjs +++ /dev/null @@ -1,202 +0,0 @@ -import { oneAtATime } from "./approval-queue.mjs"; -// FoundrySpecification.hostedSourcePermissionBoundary. Permission is never persisted or inferred. -export const HOSTED_SOURCE_ENDPOINT = 'https://mcp.uor.foundation/'; -const messages = { - invalidHostedSourcePermission: 'Invalid hosted source permission', - hostedSourcePermissionDenied: 'Hosted source transfer declined; no new source was sent', - hostedSourcePermissionCancelled: 'Hosted source transfer stopped; submitted data cannot be recalled', - hostedSourcePermissionExpired: 'Hosted source permission expired', - hostedSourcePermissionOffline: 'Hosted source transfer is unavailable offline', - hostedSourcePermissionUnavailable: 'Hosted source permission could not be displayed', - hostedSourceChanged: 'The application source or turn changed; approve the current work again', - hostedSourceNetworkFailed: 'The hosted source request failed', - hostedSourceMalformedResponse: 'The hosted source service returned an invalid response', - hostedSourceServiceRefused: 'The hosted source service refused the request', -}; -export const hostedSourceFailure = code => Object.assign(new Error(messages[code] || messages.invalidHostedSourcePermission), { code: Object.hasOwn(messages, code) ? code : 'invalidHostedSourcePermission' }); -const fail = code => { throw hostedSourceFailure(code); }; -const onlineDefault = () => globalThis.navigator?.onLine !== false; -const utf8 = s => new TextEncoder().encode(s).length; -function filesOf(files) { - if (!Array.isArray(files) || !files.length || files.length > 32) fail('invalidHostedSourcePermission'); - let size = 0; - const copied = files.map(file => { - if (!file || Object.keys(file).sort().join() !== 'content,path' || typeof file.path !== 'string' || !/^src\/(?:[A-Za-z_]\w*\/)*[A-Za-z_]\w*\.lex\.tex$/.test(file.path) || typeof file.content !== 'string' || !file.content.length) fail('invalidHostedSourcePermission'); - size += utf8(file.content); - return Object.freeze({ path: file.path, content: file.content }); - }); - if (size > 2 * 1024 * 1024 || new Set(copied.map(f => f.path)).size !== copied.length) fail('invalidHostedSourcePermission'); - return Object.freeze(copied); -} -const signalValid = signal => signal === undefined || (signal && typeof signal.aborted === 'boolean' && typeof signal.addEventListener === 'function' && typeof signal.removeEventListener === 'function'); -export function describeHostedSource(input) { - if (!input || !['source', 'turn'].includes(input.scope) || !['parse', 'check'].includes(input.purpose)) fail('invalidHostedSourcePermission'); - const files = filesOf(input.files); - const disclosure = { scope: input.scope, purpose: input.purpose, endpoint: HOSTED_SOURCE_ENDPOINT, files, size: files.reduce((n, f) => n + utf8(f.content), 0) }; - if (input.scope === 'turn') { - if (!(Number.isSafeInteger(input.appId) && input.appId > 0) || !['turnId', 'source'].every(key => typeof input[key] === 'string' && input[key].length > 0 && input[key].length <= 256 && !/[\r\n]/.test(input[key]))) fail('invalidHostedSourcePermission'); - Object.assign(disclosure, { appId: input.appId, turnId: input.turnId, source: input.source }); - } - return Object.freeze(disclosure); -} -// Asked in its turn: a dialog opened over another approval's would cover its buttons (approval-queue.mjs). -export function authorizeHostedSource(input, options) { return oneAtATime(() => authorizeHostedSourceNow(input, options)); } -function authorizeHostedSourceNow(input, { document = globalThis.document, online = onlineDefault, now = Date.now, timeoutMs = 300000 } = {}) { - let disclosure; - try { - disclosure = describeHostedSource(input); - if (!signalValid(input.signal) || !Number.isInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 300000) fail('invalidHostedSourcePermission'); - if (input.signal?.aborted) fail('hostedSourcePermissionCancelled'); - if (!online()) fail('hostedSourcePermissionOffline'); - } catch (error) { return Promise.reject(error); } - return new Promise((resolve, reject) => { - const controller = new AbortController(), previous = document?.activeElement, expires = now() + timeoutMs; - let dialog, active, timer, approved = false, settled = false; - const close = () => { clearTimeout(timer); input.signal?.removeEventListener('abort', abort); dialog?.remove(); active?.remove(); previous?.focus?.(); }; - const stop = code => { controller.abort(); close(); if (!settled) { settled = true; reject(hostedSourceFailure(code)); } }; - const abort = () => stop('hostedSourcePermissionCancelled'); - try { - const el = (tag, text) => { const node = document.createElement(tag); if (text !== undefined) node.textContent = text; return node; }; - dialog = el('dialog'); dialog.setAttribute('aria-label', 'Review hosted source transfer'); - dialog.style.cssText = 'max-width:min(90vw,44rem);max-height:85vh;overflow:auto;padding:24px;border-radius:12px;color-scheme:light dark'; - dialog.append(el('h2', 'Send your app to be checked?'), el('p', 'Your app is checked, and its preview prepared, by a UOR service outside this browser.')); - dialog.append(el('p', 'Its LexLean source and the library it uses go to ' + disclosure.endpoint + '. The source may hold details from your project or chat, and the service may keep it. No AI key and no cookies are sent.')); - dialog.append(el('p', disclosure.scope === 'turn' ? `You are approving this one build of app ${disclosure.appId} for up to five minutes: the app as it is written, and any fix in the same build. Nothing else is covered: no other app, no other build, no proof and no publishing. Build ${disclosure.turnId}, starting from ${disclosure.source}.` : 'You are approving only the files below, once, for up to five minutes. It does not cover proof or publishing.')); - dialog.append(el('p', 'You can stop it, but what was sent cannot be taken back, and work there may continue.')); - const details = el('details'), pre = el('pre', disclosure.files.map(f => f.path + '\n' + f.content).join('\n\n')); - pre.style.cssText = 'white-space:pre-wrap;overflow-wrap:anywhere;max-height:18rem;overflow:auto'; - details.append(el('summary', `See exactly what is sent (${disclosure.size} bytes)`), pre); dialog.append(details); - const deny = el('button', "Don't send"), allow = el('button', disclosure.scope === 'turn' ? 'Allow this turn' : 'Send this source'); - deny.type = allow.type = 'button'; deny.autofocus = true; - deny.addEventListener('click', () => stop('hostedSourcePermissionDenied')); - dialog.addEventListener('cancel', event => { event.preventDefault(); stop('hostedSourcePermissionDenied'); }); - allow.addEventListener('click', () => { - if (settled) return; - if (input.signal?.aborted) return stop('hostedSourcePermissionCancelled'); - if (now() >= expires) return stop('hostedSourcePermissionExpired'); - if (!online()) return stop('hostedSourcePermissionOffline'); - try { - active = el('aside'); active.setAttribute('aria-label', 'Active hosted source transfer'); - active.style.cssText = 'position:fixed;bottom:1rem;right:1rem;z-index:2147483647;padding:12px;background:Canvas;color:CanvasText;border:1px solid;border-radius:8px'; - const stopButton = el('button', 'Stop hosted source transfer'); stopButton.type = 'button'; stopButton.addEventListener('click', abort); active.append(stopButton); document.body.append(active); - dialog.remove(); previous?.focus?.(); approved = true; settled = true; - resolve(Object.freeze({ disclosure, expires, signal: controller.signal, close })); - } catch { stop('hostedSourcePermissionUnavailable'); } - }); - dialog.append(deny, allow); document.body.append(dialog); - input.signal?.addEventListener('abort', abort, { once: true }); - if (input.signal?.aborted) return abort(); - timer = setTimeout(() => stop('hostedSourcePermissionExpired'), timeoutMs); - dialog.showModal(); deny.focus(); - } catch { if (!approved) stop('hostedSourcePermissionUnavailable'); } - }); -} -const sessions = new WeakSet(); -function sessionFor(context, { authorize = authorizeHostedSource, online = onlineDefault, now = Date.now, requestTimeoutMs = 30000 } = {}) { - if (!signalValid(context.signal) || !Number.isInteger(requestTimeoutMs) || requestTimeoutMs < 1 || requestTimeoutMs > 30000) fail('invalidHostedSourcePermission'); - const controller = new AbortController(); - let permission, approved, closed = false, expiryTimer; - const abort = () => controller.abort(); - context.signal?.addEventListener('abort', abort, { once: true }); - if (context.signal?.aborted) abort(); - const close = () => { closed = true; abort(); clearTimeout(expiryTimer); approved?.close(); context.signal?.removeEventListener('abort', abort); approved?.signal?.removeEventListener('abort', abort); }; - const assertActive = async () => { - if (approved && now() >= approved.expires) fail('hostedSourcePermissionExpired'); - if (closed || controller.signal.aborted) fail('hostedSourcePermissionCancelled'); - if (!online()) fail('hostedSourcePermissionOffline'); - if (context.assertCurrent) { - try { if (await context.assertCurrent() === false) throw Error(); } - catch { close(); fail('hostedSourceChanged'); } - } - if (closed || controller.signal.aborted) fail('hostedSourcePermissionCancelled'); - }; - const session = { - close, - async run(input, operation, fetchImpl = globalThis.fetch) { - const disclosure = describeHostedSource({ ...context, ...input, scope: context.scope }); - if (!signalValid(input.signal) || typeof operation !== 'function' || typeof fetchImpl !== 'function') fail('invalidHostedSourcePermission'); - if (input.signal?.aborted) fail('hostedSourcePermissionCancelled'); - await assertActive(); - if (!permission) { - permission = Promise.resolve().then(() => authorize({ ...disclosure, signal: controller.signal })).then(value => { - if (!value || JSON.stringify(value.disclosure) !== JSON.stringify(disclosure) || !signalValid(value.signal) || !value.signal || typeof value.close !== 'function' || !Number.isFinite(value.expires) || value.expires > now() + 300000) { value?.close?.(); fail('invalidHostedSourcePermission'); } - approved = value; - if (closed || controller.signal.aborted) { value.close(); fail('hostedSourcePermissionCancelled'); } - value.signal.addEventListener('abort', abort, { once: true }); - if (value.signal.aborted) abort(); - expiryTimer = setTimeout(() => { abort(); value.close(); }, Math.max(1, value.expires - now())); - return value; - }); - } - await permission; await assertActive(); - const local = new AbortController(), cancel = () => local.abort(); - controller.signal.addEventListener('abort', cancel, { once: true }); input.signal?.addEventListener('abort', cancel, { once: true }); - if (controller.signal.aborted || input.signal?.aborted) cancel(); - let draft, wrote = false, checked = false; - const readPaths = new Set(); - const request = async (url, init) => { - await assertActive(); if (local.signal.aborted) fail('hostedSourcePermissionCancelled'); - let payload; - try { payload = JSON.parse(init.body); } catch { fail('invalidHostedSourcePermission'); } - const { name, arguments: args } = payload.params || {}; - if (url !== HOSTED_SOURCE_ENDPOINT || init.method !== 'POST' || payload.jsonrpc !== '2.0' || payload.method !== 'tools/call' || Object.keys(payload).sort().join() !== 'id,jsonrpc,method,params' || !Number.isSafeInteger(payload.id) || payload.id < 1 || Object.keys(payload.params || {}).sort().join() !== 'arguments,name' || !args) fail('invalidHostedSourcePermission'); - if (name === 'lexlean_draft_write') { - if (wrote || args.profile !== 'prism-app' || Object.keys(args).sort().join() !== 'files,profile' || JSON.stringify(filesOf(args.files)) !== JSON.stringify(disclosure.files)) fail('invalidHostedSourcePermission'); - wrote = true; - } else if (name === 'lexlean_check') { - if (disclosure.purpose !== 'check' || checked || !draft || args.project !== draft || args.all !== true || Object.keys(args).sort().join() !== 'all,project') fail('invalidHostedSourcePermission'); - checked = true; - } else if (name === 'lexlean_draft_read') { - if (!draft || args.draft !== draft || args.view !== 'data' || !disclosure.files.some(f => f.path === args.path) || readPaths.has(args.path) || Object.keys(args).sort().join() !== 'draft,path,view') fail('invalidHostedSourcePermission'); - readPaths.add(args.path); - } else fail('invalidHostedSourcePermission'); - const transport = new AbortController(); let timer, rejectStop, reason; - const interrupted = new Promise((_, reject) => { rejectStop = reject; }); - const stop = code => { reason = hostedSourceFailure(code); transport.abort(); rejectStop(reason); }; - const cancelled = () => stop(approved && now() >= approved.expires ? 'hostedSourcePermissionExpired' : 'hostedSourcePermissionCancelled'); - local.signal.addEventListener('abort', cancelled, { once: true }); - if (local.signal.aborted) cancelled(); - timer = setTimeout(() => stop('hostedSourcePermissionExpired'), Math.min(requestTimeoutMs, Math.max(1, approved.expires - now()))); - try { - const work = async () => { - if (reason) throw reason; - const res = await fetchImpl(HOSTED_SOURCE_ENDPOINT, { method: 'POST', headers: { 'content-type': 'application/json', accept: 'application/json, text/event-stream' }, body: JSON.stringify(payload), redirect: 'error', credentials: 'omit', signal: transport.signal }); - if (reason) throw reason; - if (!res?.ok) fail('hostedSourceServiceRefused'); - let body; - try { body = await res.json(); } catch { fail('hostedSourceMalformedResponse'); } - if (reason) throw reason; - if (!body || typeof body !== 'object' || !body.result || body.error || body.result.isError) fail('hostedSourceServiceRefused'); - let data; - try { data = body.result.structuredContent ?? JSON.parse(body.result.content?.[0]?.text); } catch { fail('hostedSourceMalformedResponse'); } - if (!data || typeof data !== 'object' || Array.isArray(data)) fail('hostedSourceMalformedResponse'); - if (name === 'lexlean_draft_write') { - if (typeof data.draft !== 'string' || !data.draft || data.draft.length > 512) fail('hostedSourceMalformedResponse'); - draft = data.draft; - } else if (name === 'lexlean_check') { - if (typeof data.success !== 'boolean' || !Array.isArray(data.diagnostics) || data.diagnostics.length > 256 || data.diagnostics.some(d => !d || typeof d.message !== 'string')) fail('hostedSourceMalformedResponse'); - } else if (data.data?.spec !== 'lexlean/semantic-module/2' || !Array.isArray(data.data.declarations)) fail('hostedSourceMalformedResponse'); - await assertActive(); if (local.signal.aborted) fail('hostedSourcePermissionCancelled'); - return { ok: true, status: 200, json: async () => ({ result: { structuredContent: data } }) }; - }; - return await Promise.race([work(), interrupted]); - } catch (error) { if (reason) throw reason; if (messages[error?.code]) throw error; fail('hostedSourceNetworkFailed'); } - finally { clearTimeout(timer); local.signal.removeEventListener('abort', cancelled); } - }; - try { const result = await operation(request); await assertActive(); if (local.signal.aborted) fail('hostedSourcePermissionCancelled'); return result; } - finally { controller.signal.removeEventListener('abort', cancel); input.signal?.removeEventListener('abort', cancel); local.abort(); } - }, - }; - sessions.add(session); return Object.freeze(session); -} -export function createHostedSourceSession(context, boundary) { - describeHostedSource({ ...context, scope: 'turn', purpose: 'parse', files: [{ path: 'src/App.lex.tex', content: 'scope validation' }] }); - if (typeof context.assertCurrent !== 'function' || !context.signal) fail('invalidHostedSourcePermission'); - return sessionFor({ ...context, scope: 'turn' }, boundary); -} -export async function withHostedSourcePermission(input, operation, options = {}, fetchImpl = globalThis.fetch) { - if (options.session !== undefined && !sessions.has(options.session)) fail('invalidHostedSourcePermission'); - const session = options.session || sessionFor({ scope: 'source', signal: options.signal }, options); - try { return await session.run({ ...input, signal: options.signal }, operation, fetchImpl); } - finally { if (!options.session) session.close(); } -} diff --git a/studio/tools/approval_queue.test.mjs b/studio/tools/approval_queue.test.mjs index 39a884a6..f6835fb1 100644 --- a/studio/tools/approval_queue.test.mjs +++ b/studio/tools/approval_queue.test.mjs @@ -49,7 +49,7 @@ test("a question that cannot be shown rejects and does not hold the others", asy }); test("the three approvals of a build are each asked in their turn", () => { - for (const [file, name] of [["preview-permissions.mjs", "authorizePreview"], ["hosted-source-permission.mjs", "authorizeHostedSource"]]) { + for (const [file, name] of [["preview-permissions.mjs", "authorizePreview"]]) { const source = read("../shell/" + file); assert.ok(source.includes(`export function ${name}(input, options) { return oneAtATime(() => ${name}Now(input, options)); }`), file + " opens its dialog outside the queue"); assert.equal((source.match(/\.showModal\(\)/g) || []).length >= 1, true); diff --git a/studio/tools/backlog_workflows.test.mjs b/studio/tools/backlog_workflows.test.mjs index dd52cfd3..997b3953 100644 --- a/studio/tools/backlog_workflows.test.mjs +++ b/studio/tools/backlog_workflows.test.mjs @@ -71,7 +71,7 @@ test("Pages cache misses retain compiler renderer closure and acceptance orderin test("Studio collects independent browser failures without bypassing verified prerequisites", () => { const studio = workflow("studio.yml"); const guard = "if: ${{ !cancelled() && steps.shell_closure.conclusion == 'success' && steps.corpus.conclusion == 'success' }}"; - const cases = [["Check the declared host scope and real renderer error recovery", 9], ["Verify snapshot rollback in browser storage", 60]]; + const cases = [["Check the declared host scope and real renderer error recovery", 9], ["Verify snapshot rollback in browser storage", 59]]; const audit = source => { assert.match(source, /id: shell_closure\n/); assert.match(source, /id: corpus\n/); for (const [name, count] of cases) { diff --git a/studio/tools/build_source_browser.mjs b/studio/tools/build_source_browser.mjs index 8b65428c..9f2d0386 100644 --- a/studio/tools/build_source_browser.mjs +++ b/studio/tools/build_source_browser.mjs @@ -11,7 +11,7 @@ const sources = new Map([ ["/theme-library.mjs", fs.readFileSync(new URL("../shell/theme-library.mjs", import.meta.url))], ["/version-preview-codec.mjs", fs.readFileSync(new URL("../shell/version-preview-codec.mjs", import.meta.url))],["/blake3.mjs", fs.readFileSync(new URL("../../try/vendor/prism-code/src/blake3.mjs", import.meta.url))]]); for (const name of ["build-source", "project-lifecycle", "project-edit", "project-creation", "generation-patch", "snapshot-restore", "storage-request"]) sources.set(`/${name}.mjs`, fs.readFileSync(new URL(`../shell/${name}.mjs`, import.meta.url))); -for (const name of ["application-shape.mjs", "hosted-source-permission.mjs", "approval-queue.mjs", "live/app.mjs", "live/notation.mjs", "live/v2/interp.mjs", "live/v2/render.mjs", "canonical-build.mjs", "prism.js", "prism/spec.mjs", "prism/spec-file.mjs", "prism/render.mjs", "in-tab-verdict-codec.mjs", "prism/builder/route.mjs", "prism/builder/prompt.mjs", "prism/template.mjs", "prism/sha256.mjs", "live/lexlean.mjs", "live/obligations.mjs", "live/table.mjs", "prism-code/src/blake3.mjs"]) sources.set("/" + name, fs.readFileSync(new URL("../shell/" + name, import.meta.url))); +for (const name of ["application-shape.mjs", "approval-queue.mjs", "live/app.mjs", "live/notation.mjs", "live/v2/interp.mjs", "live/v2/render.mjs", "canonical-build.mjs", "prism.js", "prism/spec.mjs", "prism/spec-file.mjs", "prism/render.mjs", "in-tab-verdict-codec.mjs", "prism/builder/route.mjs", "prism/builder/prompt.mjs", "prism/template.mjs", "prism/sha256.mjs", "live/lexlean.mjs", "live/obligations.mjs", "live/table.mjs", "prism-code/src/blake3.mjs"]) sources.set("/" + name, fs.readFileSync(new URL("../shell/" + name, import.meta.url))); const server = http.createServer((req, res) => { const bytes = sources.get(req.url); if (!bytes && req.url !== "/") { res.writeHead(404, {"content-type":"text/plain"}); res.end("Fixture resource is not declared"); return; } diff --git a/studio/tools/hosted_source_permission.test.mjs b/studio/tools/hosted_source_permission.test.mjs deleted file mode 100644 index c65b57e7..00000000 --- a/studio/tools/hosted_source_permission.test.mjs +++ /dev/null @@ -1,119 +0,0 @@ -import {test} from 'node:test'; -import assert from 'node:assert/strict'; -import fs from 'node:fs'; -import {checkApp, splitDeclarations, wholePrefix} from '../shell/live/app.mjs'; -import {authorizeHostedSource, describeHostedSource, createHostedSourceSession, withHostedSourcePermission, hostedSourceFailure, HOSTED_SOURCE_ENDPOINT} from '../shell/hosted-source-permission.mjs'; -const read = path => fs.readFileSync(new URL(path, import.meta.url), 'utf8'); -const module = read('../../v2/loop/answers/guests-3.verified.lex.tex'); -const whole = JSON.parse(read('../../v2/loop/answers/guests-3.json')); -const files = [{path:'src/App.lex.tex',content:''}]; -const input = {scope:'source',purpose:'parse',files}; -const code = value => error => error.code === value; -const approval = async input => ({disclosure:describeHostedSource(input),expires:Date.now()+10000,signal:new AbortController().signal,close(){}}); -const options = {authorize:approval,online:()=>true}; -function dom() { - const nodes=[]; - class Element extends EventTarget {constructor(tag){super();this.tag=tag;this.style={};this.children=[];nodes.push(this);}append(...children){this.children.push(...children);}setAttribute(){}remove(){this.removed=true;}showModal(){this.open=true;}focus(){document.activeElement=this;}click(){this.dispatchEvent(new Event('click'));}} - const document={createElement:tag=>new Element(tag),body:new Element('body'),activeElement:{focus(){}}}; - return {document,nodes,button:label=>nodes.find(n=>n.tag==='button'&&n.textContent===label)}; -} -function service() { - const requests=[],drafts=new Map(); - const fetch=async(url,init)=>{ - requests.push({url,init});const request=JSON.parse(init.body),args=request.params.arguments;let payload; - if(request.params.name==='lexlean_draft_write'){const draft='prism-app/'+drafts.size;drafts.set(draft,args.files);payload={draft};} - else if(request.params.name==='lexlean_check')payload={success:true,diagnostics:[]}; - else {const source=drafts.get(args.draft).find(f=>f.path===args.path).content,names=new Set(splitDeclarations(source).declarations.map(d=>d.name));payload={data:{spec:whole.spec,declarations:whole.declarations.filter(d=>names.has(d.name))}};} - return {ok:true,json:async()=>({result:{structuredContent:payload}})}; - }; - return {fetch,requests}; -} -// A parse through the boundary itself: the preview reads its data form in the tab, so only these tests send one. -const dataForm=(source,fetchImpl,opts={})=>{const sent=[{path:'src/App.lex.tex',content:source}];return withHostedSourcePermission({purpose:'parse',files:sent},async f=>{const draft=(await (await f(HOSTED_SOURCE_ENDPOINT,rpc('lexlean_draft_write',{profile:'prism-app',files:sent}))).json()).result.structuredContent.draft;if(typeof draft!=='string'||!draft)throw hostedSourceFailure('hostedSourceMalformedResponse');return draft;},opts,fetchImpl);}; -// A check through the boundary, with the module and the library it imports: no shell code sends one any more. -const checkForm=(source,fetchImpl,opts={})=>{const sent=[{path:'src/App.lex.tex',content:source},{path:'src/Foundation/View/Browser/V1/Model.lex.tex',content:read('../shell/live/v2/Model.lex.tex')}];return withHostedSourcePermission({purpose:'check',files:sent},async f=>(await f(HOSTED_SOURCE_ENDPOINT,rpc('lexlean_draft_write',{profile:'prism-app',files:sent}))).json(),opts,fetchImpl);}; -const rpc=(name,args)=>({method:'POST',body:JSON.stringify({jsonrpc:'2.0',id:1,method:'tools/call',params:{name,arguments:args}})}); -function session(boundary={}) {const controller=new AbortController();let current=true;const scope=createHostedSourceSession({appId:7,turnId:'turn-one',source:'blake3:'+'a'.repeat(64),signal:controller.signal,assertCurrent:async()=>current},{...options,...boundary});return {scope,controller,change:()=>{current=false;}};} - -test('no default hosted source transmission occurs without permission', async () => { - let calls=0;await assert.rejects(dataForm('private source',async()=>{calls++;throw Error('network');}),code('hostedSourcePermissionUnavailable'));assert.equal(calls,0); - await assert.rejects(checkForm('private source',async()=>{calls++;throw Error('network');}),code('hostedSourcePermissionUnavailable'));assert.equal(calls,0); - const real=globalThis.fetch;globalThis.fetch=async()=>{calls++;throw Error('network');};try{await checkApp(module,{'Foundation.View.Browser.V1.Model':JSON.parse(read('../shell/live/v2/Model.json'))});}finally{globalThis.fetch=real;}assert.equal(calls,0,'the in-tab check sends nothing'); -}); -test('disclosure is immutable exact source with bounded paths and a fixed destination',()=>{ - const source=structuredClone(input),disclosure=describeHostedSource(source);source.files[0].content='changed';assert.equal(disclosure.files[0].content,files[0].content);assert.ok(Object.isFrozen(disclosure.files[0]));assert.equal(disclosure.endpoint,HOSTED_SOURCE_ENDPOINT); - for(const patch of [{scope:'unknown'},{purpose:'prove'},{files:[]},{files:[{path:'../secret',content:'x'}]},{files:[...files,...files]},{files:[{path:'src/App.lex.tex',content:'a'.repeat(2097153)}]}])assert.throws(()=>describeHostedSource({...input,...patch}),code('invalidHostedSourcePermission')); - assert.throws(()=>createHostedSourceSession({appId:7,turnId:'t',source:'s',signal:new AbortController().signal}),code('invalidHostedSourcePermission')); -}); -test('dialog denial escape timeout cancellation offline and broken UI are private refusals',async()=>{ - for(const action of ['deny','escape','timeout','abort']){ - const ui=dom(),controller=new AbortController(),result=authorizeHostedSource({...input,signal:controller.signal},{document:ui.document,online:()=>true,timeoutMs:action==='timeout'?5:1000}); - const expected=action==='timeout'?'hostedSourcePermissionExpired':action==='abort'?'hostedSourcePermissionCancelled':'hostedSourcePermissionDenied';const rejected=assert.rejects(result,code(expected)); - assert.equal(ui.document.activeElement,ui.button("Don't send")); - assert.ok(ui.nodes.find(n=>n.tag==='pre').textContent.includes(files[0].content)); - if(action==='deny')ui.button("Don't send").click();if(action==='escape')ui.nodes.find(n=>n.tag==='dialog').dispatchEvent(new Event('cancel',{cancelable:true}));if(action==='abort')controller.abort(); - await rejected;assert.ok(ui.nodes.find(n=>n.tag==='dialog').removed); - } - await assert.rejects(authorizeHostedSource(input,{online:()=>false}),code('hostedSourcePermissionOffline')); - await assert.rejects(authorizeHostedSource(input,{document:{createElement(){throw Error('private details');}},online:()=>true}),e=>e.code==='hostedSourcePermissionUnavailable'&&!e.message.includes('private')); -}); -test('approved browser scope links caller and stop cancellation and cleans its controls',async()=>{ - for(const action of ['caller','stop','complete']){ - const ui=dom(),controller=new AbortController(),result=authorizeHostedSource({...input,signal:controller.signal},{document:ui.document,online:()=>true}); - ui.button('Send this source').click();const permission=await result; - if(action==='caller')controller.abort();if(action==='stop')ui.button('Stop hosted source transfer').click();if(action==='complete')permission.close(); - assert.equal(permission.signal.aborted,action!=='complete');assert.ok(ui.nodes.find(n=>n.tag==='aside').removed); - } -}); -test('parser and checker require disclosed exact files and strip ambient credentials',async()=>{ - const transport=service();let disclosures=[];const opts={...options,authorize:async value=>{disclosures.push(describeHostedSource(value));return approval(value);}}; - await dataForm(wholePrefix(module).source,transport.fetch,opts); - await checkForm(module,transport.fetch,opts); - assert.equal(disclosures.length,2);assert.deepEqual(disclosures.map(d=>d.purpose),['parse','check']);assert.equal(disclosures[1].files.length,2); - for(const request of transport.requests){assert.equal(request.url,HOSTED_SOURCE_ENDPOINT);assert.equal(request.init.credentials,'omit');assert.equal(request.init.redirect,'error');assert.equal(request.init.headers.authorization,undefined);assert.ok(request.init.signal);} - assert.deepEqual(JSON.parse(transport.requests[0].init.body).params.arguments.files,disclosures[0].files); -}); -test('one turn approval covers later prefixes repairs and checks but never a different turn',async()=>{ - let approvals=0;const boundary={authorize:async value=>{approvals++;assert.equal(value.scope,'turn');assert.equal(value.appId,7);return approval(value);}},one=session(boundary),transport=service(); - try { - await dataForm('first prefix',transport.fetch,{session:one.scope});await dataForm('repaired module',transport.fetch,{session:one.scope}); - await checkForm(module,transport.fetch,{session:one.scope});assert.equal(approvals,1); - const two=session(boundary);try{await dataForm('another turn',transport.fetch,{session:two.scope});assert.equal(approvals,2);}finally{two.scope.close();} - }finally{one.scope.close();} -}); -test('a denied turn never repeats its prompt or transmits while a new session can ask',async()=>{ - let prompts=0,calls=0;const one=session({authorize:async()=>{prompts++;throw hostedSourceFailure('hostedSourcePermissionDenied');}}); - try{for(const source of ['one','two'])await assert.rejects(dataForm(source,async()=>calls++,{session:one.scope}),code('hostedSourcePermissionDenied'));assert.equal(prompts,1);assert.equal(calls,0);}finally{one.scope.close();} -}); -test('changed ownership revoked expired and offline sessions block further transfer',async()=>{ - for(const action of ['change','abort','close','expire','offline']){ - let time=1000,online=true;const transport=service(),one=session({now:()=>time,online:()=>online,authorize:async value=>({disclosure:describeHostedSource(value),expires:time+1000,signal:new AbortController().signal,close(){}})}); - try{await dataForm('first',transport.fetch,{session:one.scope});const before=transport.requests.length; - if(action==='change')one.change();if(action==='abort')one.controller.abort();if(action==='close')one.scope.close();if(action==='expire')time=2001;if(action==='offline')online=false; - const expected=action==='change'?'hostedSourceChanged':action==='expire'?'hostedSourcePermissionExpired':action==='offline'?'hostedSourcePermissionOffline':'hostedSourcePermissionCancelled'; - await assert.rejects(dataForm('second',transport.fetch,{session:one.scope}),code(expected));assert.equal(transport.requests.length,before); - }finally{one.scope.close();} - } -}); -test('transport rejects changed files endpoints extra fields and out of scope RPC effects',async()=>{ - let calls=0;const fetch=async()=>{calls++;assert.fail('invalid transfer');}; - const bad=[['https://evil.test/',rpc('lexlean_draft_write',{profile:'prism-app',files})],[HOSTED_SOURCE_ENDPOINT,rpc('lexlean_draft_write',{profile:'prism-app',files:[{...files[0],content:'other'}]})],[HOSTED_SOURCE_ENDPOINT,rpc('lexlean_verify',{project:'x'})],[HOSTED_SOURCE_ENDPOINT,rpc('lexlean_draft_read',{draft:'unknown',path:files[0].path,view:'data'})]]; - const extra=rpc('lexlean_draft_write',{profile:'prism-app',files});extra.body=extra.body.replace('"id":1','"id":1,"secret":"undisclosed"');bad.push([HOSTED_SOURCE_ENDPOINT,extra]); - for(const [url,init] of bad)await assert.rejects(withHostedSourcePermission({purpose:'parse',files},request=>request(url,init),options,fetch),code('invalidHostedSourcePermission'));assert.equal(calls,0); -}); -test('malformed refusals and failed transport expose only fixed typed errors',async()=>{ - const cases=[[()=>{throw Error('private bearer');},'hostedSourceNetworkFailed'],[()=>({ok:false}),'hostedSourceServiceRefused'],[()=>({ok:true,json:async()=>{throw Error('private body');}}),'hostedSourceMalformedResponse'],[()=>({ok:true,json:async()=>({result:{structuredContent:{draft:''}}})}),'hostedSourceMalformedResponse'],[()=>({ok:true,json:async()=>({result:{isError:true,structuredContent:{message:'private'}}})}),'hostedSourceServiceRefused']]; - for(const [fetch,expected] of cases)await assert.rejects(dataForm('source',fetch,options),e=>e.code===expected&&!/private|bearer/.test(e.message)); -}); -test('cancel and bounded deadline interrupt in flight requests even when fetch ignores abort',async()=>{ - for(const action of ['cancel','timeout']){ - const one=session({requestTimeoutMs:action==='timeout'?5:1000});let started;const seen=new Promise(resolve=>started=resolve); - const operation=dataForm('source',async()=>{started();return new Promise(()=>{});},{session:one.scope});const rejection=assert.rejects(operation,code(action==='timeout'?'hostedSourcePermissionExpired':'hostedSourcePermissionCancelled')); - await seen;if(action==='cancel')one.controller.abort();await rejection;one.scope.close(); - } -}); -test('a build turn and its check send no source: both are read, run and stated in the tab',()=>{ - const host=read('../shell/host.js'),app=read('../shell/live/app.mjs'); - assert.ok(!host.includes('createHostedSourceSession(')&&!app.includes('purpose: "parse"'));assert.ok(!app.includes('hosted-source-permission'));assert.ok(app.includes('createApp(semanticData(source), library)')); - assert.ok(read('../../app/src/FoundrySpecification.lex.tex').includes('name: hostedSourcePermissionBoundary,'));assert.ok(read('./shell_parse.mjs').includes('"hosted-source-permission.mjs": "mjs"')); -}); diff --git a/studio/tools/hosted_source_permission_browser.mjs b/studio/tools/hosted_source_permission_browser.mjs deleted file mode 100644 index 9c8a3913..00000000 --- a/studio/tools/hosted_source_permission_browser.mjs +++ /dev/null @@ -1,61 +0,0 @@ -// The shipped parser/check permission UI and transport, with all remote traffic intercepted. -import assert from 'node:assert/strict'; -import fs from 'node:fs'; -import path from 'node:path'; -import http from 'node:http'; -import {fileURLToPath} from 'node:url'; -import {chromium} from '../vendor/dyad/node_modules/playwright-core/index.mjs'; -const root=fileURLToPath(new URL('../shell/',import.meta.url)); -const server=http.createServer((req,res)=>{ - const pathname=new URL(req.url,'http://localhost').pathname; - if(pathname==='/'){res.setHeader('content-type','text/html');res.end('Hosted permission browser acceptance');return;} - const file=path.resolve(root,'.'+decodeURIComponent(pathname)); - if(!file.startsWith(root)||!fs.existsSync(file)||!fs.statSync(file).isFile()){res.writeHead(404);res.end();return;} - res.setHeader('content-type',file.endsWith('.json')?'application/json':'text/javascript');res.end(fs.readFileSync(file)); -}); -await new Promise(resolve=>server.listen(0,'127.0.0.1',resolve)); -const base=`http://127.0.0.1:${server.address().port}`; -const executablePath=process.env.CHROME_BIN||['/usr/bin/chromium','/usr/bin/google-chrome'].find(file=>fs.existsSync(file)); -let browser; -try{ - browser=await chromium.launch({executablePath,headless:true,args:['--no-sandbox']});const context=await browser.newContext(),page=await context.newPage(),sent=[],errors=[]; - page.on('pageerror',error=>errors.push(error.message));let hold=false,release,redirect=false,redirected=0; - await context.route('**/*',async route=>{ - const url=new URL(route.request().url()); - if(url.href==='https://mcp.uor.foundation/'){ - const request=JSON.parse(route.request().postData());sent.push({request,headers:route.request().headers()}); - if(redirect){await route.fulfill({status:302,headers:{location:'https://unapproved.invalid/leak'}});return;} - if(hold){await new Promise(resolve=>release=resolve);try{await route.abort();}catch{}return;} - const data=request.params.name==='lexlean_draft_write'?{draft:'prism-app/browser'}:{data:{spec:'lexlean/semantic-module/2',declarations:[]}}; - await route.fulfill({status:200,contentType:'application/json',headers:{'access-control-allow-origin':'*'},body:JSON.stringify({result:{structuredContent:data}})});return; - } - if(url.origin==='https://unapproved.invalid')redirected++; - if(url.origin===base)return route.continue();return route.abort(); - }); - await page.goto(base);await page.evaluate(async()=>{const permission=window.permission=await import('/hosted-source-permission.mjs'); - // A parse through the boundary: the shell's preview reads its data form in the tab, so only this suite sends one. - const call=(f,name,args)=>f(permission.HOSTED_SOURCE_ENDPOINT,{method:'POST',body:JSON.stringify({jsonrpc:'2.0',id:1,method:'tools/call',params:{name,arguments:args}})}).then(r=>r.json()).then(r=>r.result.structuredContent); - window.api={createHostedSourceSession:permission.createHostedSourceSession,dataForm:(source,fetchImpl,opts)=>{const files=[{path:'src/App.lex.tex',content:source}];return permission.withHostedSourcePermission({purpose:'parse',files},async f=>{const {draft}=await call(f,'lexlean_draft_write',{profile:'prism-app',files});return (await call(f,'lexlean_draft_read',{draft,path:'src/App.lex.tex',view:'data'})).data;},opts,fetchImpl);}};}); - const start=async({turn=false}={})=>page.evaluate(turn=>{ - window.result=null;window.controller=new AbortController();document.getElementById('prior').focus(); - if(turn)window.scope=window.api.createHostedSourceSession({appId:7,turnId:'browser-turn',source:'blake3:'+'a'.repeat(64),signal:controller.signal,assertCurrent:async()=>true}); - window.source=' private app source'; - void window.api.dataForm(window.source,fetch,{signal:controller.signal,...(turn?{session:scope}:{})}).then(value=>result={ok:true},error=>result={code:error.code}); - },turn); - const result=async()=>{await page.waitForFunction(()=>window.result!==null);return page.evaluate(()=>window.result);}; - const dialog=page.getByRole('dialog',{name:'Review hosted source transfer'}); - for(const action of ['escape','deny','abort']){ - await start();await dialog.waitFor();assert.equal(sent.length,0);assert.equal(await page.evaluate(()=>document.activeElement.textContent),"Don't send"); - if(action==='escape')await page.keyboard.press('Escape');if(action==='deny')await page.getByRole('button',{name:"Don't send",exact:true}).click();if(action==='abort')await page.evaluate(()=>controller.abort()); - assert.equal((await result()).code,action==='abort'?'hostedSourcePermissionCancelled':'hostedSourcePermissionDenied');assert.equal(await dialog.count(),0); - } - await start();await dialog.waitFor();assert.ok((await dialog.textContent()).includes('https://mcp.uor.foundation/'));assert.ok((await dialog.locator('pre').textContent()).includes('private app source'));assert.equal(await page.evaluate(()=>window.injected||false),false); - await page.getByRole('button',{name:'Send this source',exact:true}).click();assert.equal((await result()).ok,true);assert.equal(sent.length,2); - assert.equal(sent[0].request.params.arguments.files[0].content,await page.evaluate(()=>source));assert.equal(sent[0].headers.cookie,undefined);assert.equal(sent[0].headers.authorization,undefined);assert.equal(await page.getByRole('complementary',{name:'Active hosted source transfer'}).count(),0); - await start({turn:true});await dialog.waitFor();assert.ok((await dialog.textContent()).includes('any fix in the same build'));await page.getByRole('button',{name:'Allow this turn',exact:true}).click();assert.equal((await result()).ok,true); - await page.evaluate(async()=>{await api.dataForm('later generated prefix',fetch,{session:scope});scope.close();});assert.equal(sent.length,6);assert.equal(await dialog.count(),0); - hold=true;await start();await dialog.waitFor();await page.getByRole('button',{name:'Send this source',exact:true}).click();for(let i=0;!release&&i<100;i++)await new Promise(resolve=>setTimeout(resolve,10));assert.ok(release);await page.getByRole('button',{name:'Stop hosted source transfer',exact:true}).click();assert.equal((await result()).code,'hostedSourcePermissionCancelled');release();hold=false; - redirect=true;await start();await dialog.waitFor();await page.getByRole('button',{name:'Send this source',exact:true}).click();assert.equal((await result()).code,'hostedSourceNetworkFailed');assert.equal(redirected,0);redirect=false; - await context.setOffline(true);await start();assert.equal((await result()).code,'hostedSourcePermissionOffline');await context.setOffline(false); - assert.deepEqual(errors,[]);console.log('Hosted source browser acceptance passed: denial, Escape, cancellation, text-only disclosure, exact bytes, turn prefixes, stop, redirects, cookies and offline.'); -}finally{await browser?.close();await new Promise(resolve=>server.close(resolve));} diff --git a/studio/tools/shell_ui.test.mjs b/studio/tools/shell_ui.test.mjs index 48e874a9..52b9d0ea 100644 --- a/studio/tools/shell_ui.test.mjs +++ b/studio/tools/shell_ui.test.mjs @@ -13,7 +13,7 @@ const section = css.slice(css.indexOf("/* Foundry's own surfaces")); test("every dialog the shell opens is a native dialog, which the one rule styles", () => { assert.ok(section.includes("dialog:not([data-slot]) {"), "the dialog rule is gone"); - for (const file of ["preview-permissions.mjs", "hosted-source-permission.mjs", "portable-build-permission.mjs", "discovery-ui.mjs", "interaction-ui.mjs"]) { + for (const file of ["preview-permissions.mjs", "portable-build-permission.mjs", "discovery-ui.mjs", "interaction-ui.mjs"]) { const source = read("../shell/" + file); assert.match(source, /(element|el)\((document, ?)?['"]dialog['"]/, file + " no longer builds a native dialog: its surface is unstyled"); assert.equal(/data-slot/.test(source), false, file + " sets data-slot, which takes it out of the rule"); @@ -22,7 +22,7 @@ test("every dialog the shell opens is a native dialog, which the one rule styles test("the approvals are told apart from other dialogs by their label, and their approval is the last button", () => { assert.ok(section.includes('dialog:not([data-slot])[aria-label^="Review"] button:last-of-type')); - for (const [file, label, allow] of [["preview-permissions.mjs", "Review preview permissions", "Allow this preview"], ["hosted-source-permission.mjs", "Review hosted source transfer", "Allow this turn"]]) { + for (const [file, label, allow] of [["preview-permissions.mjs", "Review preview permissions", "Allow this preview"]]) { const source = read("../shell/" + file); assert.ok(source.includes(label), file + " lost its label"); const deny = source.search(/Don't (send|allow)/), ok = source.lastIndexOf(allow); @@ -32,8 +32,6 @@ test("the approvals are told apart from other dialogs by their label, and their }); test("open requests and the sidebar tools are covered, by the ids and labels the shell gives them", () => { - assert.ok(section.includes('aside[aria-label^="Active"]')); - for (const file of ["hosted-source-permission.mjs"]) assert.match(read("../shell/" + file), /setAttribute\(['"]aria-label['"], ?['"]Active /); assert.ok(section.includes("#foundry-shell-actions > button")); assert.ok(read("../shell/shell-action-dock.mjs").includes("dock.id='foundry-shell-actions'")); for (const id of ["foundry-preview-permissions", "foundry-interaction-applications", "foundry-application-discovery"]) assert.ok(section.includes("#" + id + "::before"), id + " has no mark"); @@ -128,29 +126,14 @@ test("studio/experience: centred popups, golden measures, tools on Settings, a q }); test("each approval explains why, then how, then what, in plain words, and still states what must be disclosed", () => { - const preview = read("../shell/preview-permissions.mjs"), hosted = read("../shell/hosted-source-permission.mjs"); + const preview = read("../shell/preview-permissions.mjs"); // why comes first in each - for (const [source, why, what] of [[preview, "The preview runs your app's code", "You are approving this one version"], [hosted, "by a UOR service outside this browser", "You are approving"]]) { + for (const [source, why, what] of [[preview, "The preview runs your app's code", "You are approving this one version"]]) { assert.ok(source.indexOf(why) > 0 && source.indexOf(what) > source.indexOf(why), why); } // the facts the approval boundaries require for (const fact of ["disclosure.source", "disclosure.endpoints", "IP address", "Preview permissions", "cannot take back"]) assert.ok(preview.includes(fact), fact); - for (const fact of ["disclosure.endpoint", "disclosure.appId", "disclosure.turnId", "disclosure.source", "five minutes", "no cookies", "no proof and no publishing", "cannot be taken back"]) assert.ok(hosted.includes(fact), fact); // no jargon left in the words a person reads - for (const source of [preview, hosted]) for (const word of ["UTF-8", "module prefixes", "Credential:", "bounded retries", "aborts", "executes generated code"]) assert.equal(source.includes(word), false, word); + for (const source of [preview]) for (const word of ["UTF-8", "module prefixes", "Credential:", "bounded retries", "aborts", "executes generated code"]) assert.equal(source.includes(word), false, word); }); -test("every phrase a browser gate reads from an approval is a phrase the approval still writes", () => { - const dialogs = ["hosted-source-permission.mjs", "preview-permissions.mjs"].map((s) => read("../shell/" + s)); - let found = 0; - for (const gate of ["hosted_source_permission_browser.mjs", "preview_permissions_browser.mjs", "sidebar_tool_access_browser.mjs"]) { - for (const m of read("./" + gate).matchAll(/assert\.ok\(\(await dialog\.textContent\(\)\)\.includes\((['"])((?:(?!\1).)+)\1\)/g)) { - const phrase = m[2]; - // Values a gate passes in itself (a key that must not appear, its own source, an address) are not wording. - if (/secret|private app source|^https?:/.test(phrase)) continue; - found++; - assert.ok(dialogs.some((source) => source.includes(phrase)), gate + " reads a phrase no approval writes: " + phrase); - } - } - assert.ok(found >= 1, "the gates' phrase checks were not found: " + found); -});